aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
-rw-r--r--.gitignore7
-rw-r--r--.gitreview1
-rw-r--r--.readthedocs.yaml20
-rw-r--r--BRMSGateway/config.properties2
-rw-r--r--BRMSGateway/dependency.json62
-rw-r--r--BRMSGateway/pom.xml13
-rw-r--r--BRMSGateway/src/main/java/org/onap/policy/brms/api/BrmsGateway.java43
-rw-r--r--BRMSGateway/src/main/java/org/onap/policy/brms/api/BrmsPush.java21
-rw-r--r--BRMSGateway/src/main/resources/logback.xml150
-rw-r--r--BRMSGateway/src/test/java/org/onap/policy/brms/BrmsPushTest.java26
-rw-r--r--BRMSGateway/src/test/java/org/onap/policy/brms/api/BrmsGatewayTest.java91
-rw-r--r--BRMSGateway/src/test/java/org/onap/policy/brms/api/BrmsHandlerTest.java15
-rw-r--r--BRMSGateway/src/test/java/org/onap/policy/brms/api/BrmsPushTest.java14
-rw-r--r--BRMSGateway/src/test/resources/config.properties2
-rw-r--r--LogParser/pom.xml6
-rw-r--r--LogParser/src/main/java/org/onap/xacml/parser/ParseLog.java11
-rw-r--r--LogParser/src/test/java/org/onap/xacml/parser/ParseLogTest.java6
-rw-r--r--ONAP-PAP-REST/pom.xml39
-rw-r--r--ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/ConsoleAndApiService.java138
-rw-r--r--ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/DataToNotifyPdp.java3
-rw-r--r--ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/DictionaryNames.java12
-rw-r--r--ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/Heartbeat.java38
-rw-r--r--ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/PAPRestConfig.java18
-rw-r--r--ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/UpdateOthersPAPS.java138
-rw-r--r--ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/UpdatePdpThread.java27
-rw-r--r--ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/XACMLPapServlet.java561
-rw-r--r--ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/adapters/SearchData.java27
-rw-r--r--ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/adapters/UpdateObjectData.java3
-rw-r--r--ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/ActionPolicy.java5
-rw-r--r--ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/ClosedLoopPolicy.java52
-rw-r--r--ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/ConfigPolicy.java37
-rw-r--r--ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/CreateBRMSRuleTemplate.java31
-rw-r--r--ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/CreateBrmsParamPolicy.java139
-rw-r--r--ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/CreateBrmsRawPolicy.java75
-rw-r--r--ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/CreateClosedLoopPerformanceMetrics.java82
-rw-r--r--ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/CreateNewMicroServiceModel.java44
-rw-r--r--ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/CreateNewOptimizationModel.java127
-rw-r--r--ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/DecisionPolicy.java148
-rw-r--r--ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/FirewallConfigPolicy.java360
-rw-r--r--ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/HandleIncomingNotifications.java178
-rw-r--r--ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/MicroServiceConfigPolicy.java211
-rw-r--r--ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/NotifyOtherPaps.java35
-rw-r--r--ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/OptimizationConfigPolicy.java210
-rw-r--r--ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/Policy.java39
-rw-r--r--ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/PolicyDbDao.java (renamed from ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/PolicyDBDao.java)440
-rw-r--r--ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/PolicyDbDaoTransaction.java (renamed from ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/PolicyDBDaoTransaction.java)56
-rw-r--r--ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/PolicyDbDaoTransactionInstance.java444
-rw-r--r--ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/SafePolicyBuilder.java43
-rw-r--r--ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/ActionPolicyDictionaryController.java78
-rw-r--r--ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/BRMSDictionaryController.java188
-rw-r--r--ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/ClosedLoopDictionaryController.java250
-rw-r--r--ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/DecisionPolicyDictionaryController.java89
-rw-r--r--ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/DescriptiveDictionaryController.java47
-rw-r--r--ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/DictionaryController.java74
-rw-r--r--ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/DictionaryImportController.java65
-rw-r--r--ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/FirewallDictionaryController.java510
-rw-r--r--ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/MicroServiceDictionaryController.java125
-rw-r--r--ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/OptimizationDictionaryController.java206
-rw-r--r--ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/PolicyScopeDictionaryController.java221
-rw-r--r--ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/PushPolicyController.java18
-rw-r--r--ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/SafePolicyController.java76
-rw-r--r--ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/package-info.java3
-rw-r--r--ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/daoimpl/CommonClassDaoImpl.java96
-rw-r--r--ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/elk/client/ElasticSearchPolicyUpdate.java250
-rw-r--r--ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/elk/client/ElkConnector.java12
-rw-r--r--ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/elk/client/ElkConnectorImpl.java132
-rw-r--r--ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/elk/client/Pair.java30
-rw-r--r--ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/elk/client/PolicyElasticData.java179
-rw-r--r--ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/elk/client/PolicyElasticSearchController.java389
-rw-r--r--ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/elk/client/PolicyLocator.java19
-rw-r--r--ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/handler/APIRequestHandler.java6
-rw-r--r--ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/handler/DeleteHandler.java14
-rw-r--r--ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/handler/DictionaryHandler.java19
-rw-r--r--ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/handler/DictionaryHandlerImpl.java7
-rw-r--r--ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/handler/PushPolicyHandler.java12
-rw-r--r--ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/handler/SavePolicyHandler.java75
-rw-r--r--ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/model/RemoveGroupPolicy.java10
-rw-r--r--ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/model/package-info.java3
-rw-r--r--ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/policycontroller/PolicyCreation.java443
-rw-r--r--ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/policycontroller/package-info.java9
-rw-r--r--ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/service/DictionaryService.java7
-rw-r--r--ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/service/ImportService.java24
-rw-r--r--ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/service/MetricService.java8
-rw-r--r--ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/util/AbstractPolicyCreation.java107
-rw-r--r--ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/util/DictionaryUtils.java21
-rw-r--r--ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/util/JPAUtils.java2
-rw-r--r--ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/util/JsonMessage.java14
-rw-r--r--ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/restAuth/AuthenticationService.java10
-rw-r--r--ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/restAuth/CheckPDP.java41
-rw-r--r--ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/restAuth/PAPAuthenticationFilter.java40
-rw-r--r--ONAP-PAP-REST/src/main/resources/META-INF/drop.ddl2
-rw-r--r--ONAP-PAP-REST/src/main/resources/META-INF/persistence.xml32
-rw-r--r--ONAP-PAP-REST/src/main/resources/logback.xml138
-rw-r--r--ONAP-PAP-REST/src/test/java/org/onap/policy/pap/ia/DbAuditCompareEntriesTest.java64
-rw-r--r--ONAP-PAP-REST/src/test/java/org/onap/policy/pap/test/UpdateOthersPAPSTest.java39
-rw-r--r--ONAP-PAP-REST/src/test/java/org/onap/policy/pap/test/XACMLPAPTest.java52
-rw-r--r--ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/ConsoleAndApiServiceTest.java38
-rw-r--r--ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/HeartbeatTest.java91
-rw-r--r--ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/PAPRestConfigTest.java13
-rw-r--r--ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/UpdatePdpThreadTest.java58
-rw-r--r--ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/WebConfigTest.java10
-rw-r--r--ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/XACMLPapServletTest.java75
-rw-r--r--ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/adapters/SearchDataTest.java6
-rw-r--r--ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/adapters/UpdateObjectDataTest.java5
-rw-r--r--ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/components/ActionPolicyTest.java21
-rw-r--r--ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/components/BRMSPolicyTest.java50
-rw-r--r--ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/components/ClosedLoopPolicyTest.java24
-rw-r--r--ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/components/CreateNewMicroServiceModelTest.java73
-rw-r--r--ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/components/CreateNewOptimizationTest.java37
-rw-r--r--ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/components/DecisionPolicyTest.java13
-rw-r--r--ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/components/FirewallConfigPolicyTest.java80
-rw-r--r--ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/components/HandleIncomingNotificationsTest.java20
-rw-r--r--ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/components/MicroServicePolicyTest.java88
-rw-r--r--ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/components/NotifyOtherPapsTest.java66
-rw-r--r--ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/components/OptimizationConfigPolicyTest.java81
-rw-r--r--ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/components/PolicyDBDaoTest.java107
-rw-r--r--ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/components/PolicyTest.java74
-rw-r--r--ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/controller/ActionPolicyDictionaryControllerTest.java87
-rw-r--r--ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/controller/BRMSDictionaryControllerTest.java111
-rw-r--r--ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/controller/ClosedLoopDictionaryControllerTest.java351
-rw-r--r--ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/controller/DecisionPolicyDictionaryControllerTest.java45
-rw-r--r--ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/controller/DescriptiveDictionaryControllerTest.java87
-rw-r--r--ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/controller/DictionaryControllerTest.java77
-rw-r--r--ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/controller/DictionaryImportControllerTest.java27
-rw-r--r--ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/controller/FirewallDictionaryControllerTest.java179
-rw-r--r--ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/controller/MicroServiceDictionaryControllerTest.java12
-rw-r--r--ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/controller/OptimizationDictionaryControllerTest.java101
-rw-r--r--ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/controller/PolicyScopeDictionaryControllerTest.java272
-rw-r--r--ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/controller/PushPolicyControllerTest.java44
-rw-r--r--ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/controller/SafePolicyControllerTest.java111
-rw-r--r--ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/elk/ElasticSearchPolicyUpdateTest.java18
-rw-r--r--ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/elk/ElkConnectorTest.java54
-rw-r--r--ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/elk/PairTest.java7
-rw-r--r--ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/elk/PolicyElasticDataTest.java12
-rw-r--r--ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/elk/PolicyElasticSearchControllerTest.java66
-rw-r--r--ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/elk/PolicyLocatorTest.java10
-rw-r--r--ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/elk/client/ElkConnectorImplTest.java (renamed from ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/elk/ElkConnectorImplTest.java)61
-rw-r--r--ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/handler/DeleteHandlerTest.java150
-rw-r--r--ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/handler/DictionaryHandlerTest.java3
-rw-r--r--ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/handler/PushPolicyHandlerTest.java5
-rw-r--r--ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/jpa/PolicyEntityTest.java1027
-rw-r--r--ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/model/RemoveGroupPolicyTest.java2
-rw-r--r--ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/policycontroller/PolicyCreationTest.java152
-rw-r--r--ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/service/ImportServiceTest.java62
-rw-r--r--ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/service/MetricServiceTest.java27
-rw-r--r--ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/util/JPAUtilsTest.java5
-rw-r--r--ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/util/JsonMessageTest.java7
-rw-r--r--ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/restAuth/AuthenticationServiceTest.java12
-rw-r--r--ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/restAuth/PAPAuthenticationFilterTest.java24
-rw-r--r--ONAP-PAP-REST/src/test/resources/dictionaryImport/PepOptions.csv (renamed from ONAP-PAP-REST/src/test/resources/dictionaryImport/PEPOptions.csv)0
-rw-r--r--ONAP-PAP-REST/src/test/resources/log4j.properties42
-rw-r--r--ONAP-PDP-REST/pom.xml9
-rw-r--r--ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/PapUrlResolver.java42
-rw-r--r--ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/XACMLPdpLoader.java1171
-rw-r--r--ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/XACMLPdpRegisterThread.java30
-rw-r--r--ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/XACMLPdpServlet.java80
-rw-r--r--ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/GetDictionaryService.java2
-rw-r--r--ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/NotificationService.java8
-rw-r--r--ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/PAPServices.java10
-rw-r--r--ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/PDPServices.java20
-rw-r--r--ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/notifications/ManualNotificationUpdateThread.java22
-rw-r--r--ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/notifications/NotificationController.java24
-rw-r--r--ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/notifications/NotificationServer.java369
-rw-r--r--ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/restauth/AuthenticationService.java4
-rw-r--r--ONAP-PDP-REST/src/main/resources/logback.xml142
-rw-r--r--ONAP-PDP-REST/src/test/java/org/onap/policy/pdp/rest/PapUrlResolverTest.java54
-rw-r--r--ONAP-PDP-REST/src/test/java/org/onap/policy/pdp/rest/XACMLPdpServletTest.java8
-rw-r--r--ONAP-PDP-REST/src/test/java/org/onap/policy/pdp/rest/api/test/GetDictionaryServiceTest.java2
-rw-r--r--ONAP-PDP-REST/src/test/java/org/onap/policy/pdp/rest/api/utils/test/PolicyApiUtilsTest.java1
-rw-r--r--ONAP-PDP-REST/src/test/java/org/onap/policy/pdp/rest/auth/test/AuthenticationServiceTest.java11
-rw-r--r--ONAP-PDP-REST/src/test/java/org/onap/policy/pdp/rest/notifications/test/NotificationTest.java2
-rw-r--r--ONAP-PDP-REST/src/test/resources/META-INF/drop.ddl2
-rw-r--r--ONAP-PDP-REST/src/test/resources/META-INF/persistence.xml32
-rw-r--r--ONAP-PDP-REST/src/test/resources/test.drl1113
-rw-r--r--ONAP-PDP-REST/xacml.pdp.properties12
-rw-r--r--ONAP-PDP/checkstyle-suppressions.xml33
-rw-r--r--ONAP-PDP/pom.xml7
-rw-r--r--ONAP-PDP/src/main/java/org/onap/policy/xacml/action/FindAction.java4
-rw-r--r--ONAP-PDP/src/test/java/org/onap/policy/xacml/action/FindActionTest.java9
-rw-r--r--ONAP-PDP/src/test/java/org/onap/policy/xacml/pdp/OnapPdpEngineFactoryTest.java9
-rw-r--r--ONAP-PDP/src/test/resources/logback-test.xml126
-rw-r--r--ONAP-REST/pom.xml25
-rw-r--r--ONAP-REST/src/main/java/org/onap/policy/rest/XacmlAdminAuthorization.java10
-rw-r--r--ONAP-REST/src/main/java/org/onap/policy/rest/XacmlRest.java (renamed from ONAP-REST/src/main/java/org/onap/policy/rest/XACMLRest.java)96
-rw-r--r--ONAP-REST/src/main/java/org/onap/policy/rest/XacmlRestProperties.java (renamed from ONAP-REST/src/main/java/org/onap/policy/rest/XACMLRestProperties.java)209
-rw-r--r--ONAP-REST/src/main/java/org/onap/policy/rest/adapter/PolicyRestAdapter.java53
-rw-r--r--ONAP-REST/src/main/java/org/onap/policy/rest/dao/CommonClassDao.java36
-rw-r--r--ONAP-REST/src/main/java/org/onap/policy/rest/dao/PolicyDbException.java (renamed from ONAP-REST/src/main/java/org/onap/policy/rest/dao/PolicyDBException.java)25
-rw-r--r--ONAP-REST/src/main/java/org/onap/policy/rest/daoimpl/PolicyValidationDaoImpl.java176
-rw-r--r--ONAP-REST/src/main/java/org/onap/policy/rest/jpa/ActionBodyEntity.java188
-rw-r--r--ONAP-REST/src/main/java/org/onap/policy/rest/jpa/ActionList.java49
-rw-r--r--ONAP-REST/src/main/java/org/onap/policy/rest/jpa/ActionPolicyDict.java137
-rw-r--r--ONAP-REST/src/main/java/org/onap/policy/rest/jpa/AddressGroup.java75
-rw-r--r--ONAP-REST/src/main/java/org/onap/policy/rest/jpa/Attribute.java255
-rw-r--r--ONAP-REST/src/main/java/org/onap/policy/rest/jpa/AttributeAssignment.java56
-rw-r--r--ONAP-REST/src/main/java/org/onap/policy/rest/jpa/BrmsController.java (renamed from ONAP-REST/src/main/java/org/onap/policy/rest/jpa/BRMSController.java)124
-rw-r--r--ONAP-REST/src/main/java/org/onap/policy/rest/jpa/BrmsDependency.java (renamed from ONAP-REST/src/main/java/org/onap/policy/rest/jpa/BRMSDependency.java)123
-rw-r--r--ONAP-REST/src/main/java/org/onap/policy/rest/jpa/BrmsParamTemplate.java (renamed from ONAP-REST/src/main/java/org/onap/policy/rest/jpa/BRMSParamTemplate.java)87
-rw-r--r--ONAP-REST/src/main/java/org/onap/policy/rest/jpa/Category.java171
-rw-r--r--ONAP-REST/src/main/java/org/onap/policy/rest/jpa/ClosedLoopD2Services.java100
-rw-r--r--ONAP-REST/src/main/java/org/onap/policy/rest/jpa/ClosedLoopSite.java100
-rw-r--r--ONAP-REST/src/main/java/org/onap/policy/rest/jpa/ClosedLoops.java75
-rw-r--r--ONAP-REST/src/main/java/org/onap/policy/rest/jpa/ConfigurationDataEntity.java214
-rw-r--r--ONAP-REST/src/main/java/org/onap/policy/rest/jpa/ConstraintType.java83
-rw-r--r--ONAP-REST/src/main/java/org/onap/policy/rest/jpa/ConstraintValue.java63
-rw-r--r--ONAP-REST/src/main/java/org/onap/policy/rest/jpa/DatabaseLockEntity.java28
-rw-r--r--ONAP-REST/src/main/java/org/onap/policy/rest/jpa/Datatype.java200
-rw-r--r--ONAP-REST/src/main/java/org/onap/policy/rest/jpa/DcaeUsers.java (renamed from ONAP-REST/src/main/java/org/onap/policy/rest/jpa/VMType.java)47
-rw-r--r--ONAP-REST/src/main/java/org/onap/policy/rest/jpa/DcaeUuid.java (renamed from ONAP-REST/src/main/java/org/onap/policy/rest/jpa/DCAEuuid.java)49
-rw-r--r--ONAP-REST/src/main/java/org/onap/policy/rest/jpa/DecisionSettings.java143
-rw-r--r--ONAP-REST/src/main/java/org/onap/policy/rest/jpa/DescriptiveScope.java102
-rw-r--r--ONAP-REST/src/main/java/org/onap/policy/rest/jpa/DictionaryData.java41
-rw-r--r--ONAP-REST/src/main/java/org/onap/policy/rest/jpa/FWTagPicker.java163
-rw-r--r--ONAP-REST/src/main/java/org/onap/policy/rest/jpa/FirewallDictionaryList.java63
-rw-r--r--ONAP-REST/src/main/java/org/onap/policy/rest/jpa/FunctionArgument.java102
-rw-r--r--ONAP-REST/src/main/java/org/onap/policy/rest/jpa/FunctionDefinition.java212
-rw-r--r--ONAP-REST/src/main/java/org/onap/policy/rest/jpa/FwTag.java (renamed from ONAP-REST/src/main/java/org/onap/policy/rest/jpa/FWTag.java)103
-rw-r--r--ONAP-REST/src/main/java/org/onap/policy/rest/jpa/FwTagPicker.java104
-rw-r--r--ONAP-REST/src/main/java/org/onap/policy/rest/jpa/GlobalRoleSettings.java58
-rw-r--r--ONAP-REST/src/main/java/org/onap/policy/rest/jpa/GroupEntity.java209
-rw-r--r--ONAP-REST/src/main/java/org/onap/policy/rest/jpa/GroupPolicyScopeList.java46
-rw-r--r--ONAP-REST/src/main/java/org/onap/policy/rest/jpa/GroupServiceList.java40
-rw-r--r--ONAP-REST/src/main/java/org/onap/policy/rest/jpa/MicroServiceAttribute.java55
-rw-r--r--ONAP-REST/src/main/java/org/onap/policy/rest/jpa/MicroServiceConfigName.java49
-rw-r--r--ONAP-REST/src/main/java/org/onap/policy/rest/jpa/MicroServiceLocation.java48
-rw-r--r--ONAP-REST/src/main/java/org/onap/policy/rest/jpa/MicroServiceModels.java134
-rw-r--r--ONAP-REST/src/main/java/org/onap/policy/rest/jpa/MicroserviceHeaderdeFaults.java95
-rw-r--r--ONAP-REST/src/main/java/org/onap/policy/rest/jpa/Obadvice.java148
-rw-r--r--ONAP-REST/src/main/java/org/onap/policy/rest/jpa/ObadviceExpression.java58
-rw-r--r--ONAP-REST/src/main/java/org/onap/policy/rest/jpa/OnapName.java99
-rw-r--r--ONAP-REST/src/main/java/org/onap/policy/rest/jpa/OptimizationModels.java140
-rw-r--r--ONAP-REST/src/main/java/org/onap/policy/rest/jpa/PIPConfigParam.java148
-rw-r--r--ONAP-REST/src/main/java/org/onap/policy/rest/jpa/PIPResolverParam.java148
-rw-r--r--ONAP-REST/src/main/java/org/onap/policy/rest/jpa/PdpEntity.java190
-rw-r--r--ONAP-REST/src/main/java/org/onap/policy/rest/jpa/PepOptions.java (renamed from ONAP-REST/src/main/java/org/onap/policy/rest/jpa/VNFType.java)113
-rw-r--r--ONAP-REST/src/main/java/org/onap/policy/rest/jpa/PipConfigParam.java135
-rw-r--r--ONAP-REST/src/main/java/org/onap/policy/rest/jpa/PipConfiguration.java (renamed from ONAP-REST/src/main/java/org/onap/policy/rest/jpa/PIPConfiguration.java)466
-rw-r--r--ONAP-REST/src/main/java/org/onap/policy/rest/jpa/PipResolver.java (renamed from ONAP-REST/src/main/java/org/onap/policy/rest/jpa/PIPResolver.java)286
-rw-r--r--ONAP-REST/src/main/java/org/onap/policy/rest/jpa/PipResolverParam.java132
-rw-r--r--ONAP-REST/src/main/java/org/onap/policy/rest/jpa/PipType.java (renamed from ONAP-REST/src/main/java/org/onap/policy/rest/jpa/PIPType.java)114
-rw-r--r--ONAP-REST/src/main/java/org/onap/policy/rest/jpa/PolicyAlgorithms.java84
-rw-r--r--ONAP-REST/src/main/java/org/onap/policy/rest/jpa/PolicyAuditlog.java48
-rw-r--r--ONAP-REST/src/main/java/org/onap/policy/rest/jpa/PolicyDBDaoEntity.java150
-rw-r--r--ONAP-REST/src/main/java/org/onap/policy/rest/jpa/PolicyDbDaoEntity.java107
-rw-r--r--ONAP-REST/src/main/java/org/onap/policy/rest/jpa/PolicyEditorScopes.java88
-rw-r--r--ONAP-REST/src/main/java/org/onap/policy/rest/jpa/PolicyEntity.java283
-rw-r--r--ONAP-REST/src/main/java/org/onap/policy/rest/jpa/PolicyGroupEntity.java37
-rw-r--r--ONAP-REST/src/main/java/org/onap/policy/rest/jpa/PolicyRoles.java64
-rw-r--r--ONAP-REST/src/main/java/org/onap/policy/rest/jpa/PolicyScopeClosedLoop.java48
-rw-r--r--ONAP-REST/src/main/java/org/onap/policy/rest/jpa/PolicyScopeResource.java47
-rw-r--r--ONAP-REST/src/main/java/org/onap/policy/rest/jpa/PolicyScopeService.java48
-rw-r--r--ONAP-REST/src/main/java/org/onap/policy/rest/jpa/PolicyScopeType.java47
-rw-r--r--ONAP-REST/src/main/java/org/onap/policy/rest/jpa/PolicyScore.java75
-rw-r--r--ONAP-REST/src/main/java/org/onap/policy/rest/jpa/PolicyVersion.java176
-rw-r--r--ONAP-REST/src/main/java/org/onap/policy/rest/jpa/PortList.java47
-rw-r--r--ONAP-REST/src/main/java/org/onap/policy/rest/jpa/PrefixList.java58
-rw-r--r--ONAP-REST/src/main/java/org/onap/policy/rest/jpa/ProtocolList.java50
-rw-r--r--ONAP-REST/src/main/java/org/onap/policy/rest/jpa/RainyDayTreatments.java87
-rw-r--r--ONAP-REST/src/main/java/org/onap/policy/rest/jpa/RemoteCatalogValues.java47
-rw-r--r--ONAP-REST/src/main/java/org/onap/policy/rest/jpa/RiskType.java97
-rw-r--r--ONAP-REST/src/main/java/org/onap/policy/rest/jpa/RuleAlgorithms.java76
-rw-r--r--ONAP-REST/src/main/java/org/onap/policy/rest/jpa/SafePolicyWarning.java58
-rw-r--r--ONAP-REST/src/main/java/org/onap/policy/rest/jpa/SecurityZone.java47
-rw-r--r--ONAP-REST/src/main/java/org/onap/policy/rest/jpa/ServiceList.java94
-rw-r--r--ONAP-REST/src/main/java/org/onap/policy/rest/jpa/SystemLogDb.java (renamed from ONAP-REST/src/main/java/org/onap/policy/rest/jpa/SystemLogDB.java)113
-rw-r--r--ONAP-REST/src/main/java/org/onap/policy/rest/jpa/TermList.java190
-rw-r--r--ONAP-REST/src/main/java/org/onap/policy/rest/jpa/UserInfo.java38
-rw-r--r--ONAP-REST/src/main/java/org/onap/policy/rest/jpa/VarbindDictionary.java104
-rw-r--r--ONAP-REST/src/main/java/org/onap/policy/rest/jpa/VmType.java (renamed from ONAP-REST/src/main/java/org/onap/policy/rest/jpa/DCAEUsers.java)50
-rw-r--r--ONAP-REST/src/main/java/org/onap/policy/rest/jpa/VnfType.java (renamed from ONAP-REST/src/main/java/org/onap/policy/rest/jpa/PEPOptions.java)121
-rw-r--r--ONAP-REST/src/main/java/org/onap/policy/rest/jpa/VsclAction.java (renamed from ONAP-REST/src/main/java/org/onap/policy/rest/jpa/VSCLAction.java)100
-rw-r--r--ONAP-REST/src/main/java/org/onap/policy/rest/jpa/WatchPolicyNotificationTable.java75
-rw-r--r--ONAP-REST/src/main/java/org/onap/policy/rest/jpa/Zone.java47
-rw-r--r--ONAP-REST/src/main/java/org/onap/policy/rest/util/LockdownListener.java12
-rw-r--r--ONAP-REST/src/main/java/org/onap/policy/rest/util/MsAttributeObject.java (renamed from ONAP-REST/src/main/java/org/onap/policy/rest/util/MSAttributeObject.java)88
-rw-r--r--ONAP-REST/src/main/java/org/onap/policy/rest/util/MsAttributeValue.java (renamed from ONAP-REST/src/main/java/org/onap/policy/rest/util/MSAttributeValue.java)43
-rw-r--r--ONAP-REST/src/main/java/org/onap/policy/rest/util/MsModelUtils.java (renamed from ONAP-REST/src/main/java/org/onap/policy/rest/util/MSModelUtils.java)897
-rw-r--r--ONAP-REST/src/main/java/org/onap/policy/rest/util/ParserException.java22
-rw-r--r--ONAP-REST/src/main/java/org/onap/policy/rest/util/PdpPolicyContainer.java (renamed from ONAP-REST/src/main/java/org/onap/policy/rest/util/PDPPolicyContainer.java)263
-rw-r--r--ONAP-REST/src/main/java/org/onap/policy/rest/util/PolicyContainer.java41
-rw-r--r--ONAP-REST/src/main/java/org/onap/policy/rest/util/PolicyItemSetChangeNotifier.java33
-rw-r--r--ONAP-REST/src/main/java/org/onap/policy/rest/util/PolicyValidation.java578
-rw-r--r--ONAP-REST/src/main/java/org/onap/policy/rest/util/PolicyValidationRequestWrapper.java691
-rw-r--r--ONAP-REST/src/test/java/org/onap/policy/rest/XACMLRestTest.java111
-rw-r--r--ONAP-REST/src/test/java/org/onap/policy/rest/XacmlAdminAuthorizationTest.java38
-rw-r--r--ONAP-REST/src/test/java/org/onap/policy/rest/XacmlRestTest.java303
-rw-r--r--ONAP-REST/src/test/java/org/onap/policy/rest/adapter/PolicyRestAdapterTest.java104
-rw-r--r--ONAP-REST/src/test/java/org/onap/policy/rest/dao/PolicyDbExceptionTest.java (renamed from ONAP-REST/src/test/java/org/onap/policy/rest/dao/PolicyDBExceptionTest.java)53
-rw-r--r--ONAP-REST/src/test/java/org/onap/policy/rest/daoimpl/PolicyValidationDaoImplTest.java912
-rw-r--r--ONAP-REST/src/test/java/org/onap/policy/rest/jpa/ActionBodyEntityTest.java70
-rw-r--r--ONAP-REST/src/test/java/org/onap/policy/rest/jpa/ActionDictionaryJpaTest.java (renamed from ONAP-REST/src/test/java/org/onap/policy/rest/jpa/ActionDictionaryJPATest.java)181
-rw-r--r--ONAP-REST/src/test/java/org/onap/policy/rest/jpa/BrmsDictionaryJpaTest.java (renamed from ONAP-REST/src/test/java/org/onap/policy/rest/jpa/BRMSDictionaryJPATest.java)59
-rw-r--r--ONAP-REST/src/test/java/org/onap/policy/rest/jpa/ClosedLoopPolicyDictionaryJpaTest.java (renamed from ONAP-REST/src/test/java/org/onap/policy/rest/jpa/ClosedLoopPolicyDictionaryJPATest.java)114
-rw-r--r--ONAP-REST/src/test/java/org/onap/policy/rest/jpa/CommonDictionaryJpaTest.java (renamed from ONAP-REST/src/test/java/org/onap/policy/rest/jpa/CommonDictionaryJPATest.java)117
-rw-r--r--ONAP-REST/src/test/java/org/onap/policy/rest/jpa/ConfigurationDataEntityTest.java83
-rw-r--r--ONAP-REST/src/test/java/org/onap/policy/rest/jpa/DecisionDictionaryJpaTest.java (renamed from ONAP-REST/src/test/java/org/onap/policy/rest/jpa/DecisionDictionaryJPATest.java)38
-rw-r--r--ONAP-REST/src/test/java/org/onap/policy/rest/jpa/DictionaryDataTest.java4
-rw-r--r--ONAP-REST/src/test/java/org/onap/policy/rest/jpa/DummyIdentifier.java46
-rw-r--r--ONAP-REST/src/test/java/org/onap/policy/rest/jpa/FwDictionaryJpaTest.java (renamed from ONAP-REST/src/test/java/org/onap/policy/rest/jpa/FWDictionaryJPATest.java)129
-rw-r--r--ONAP-REST/src/test/java/org/onap/policy/rest/jpa/GetterSetterToStringTest.java57
-rw-r--r--ONAP-REST/src/test/java/org/onap/policy/rest/jpa/MicroServiceDictionaryJpaTest.java (renamed from ONAP-REST/src/test/java/org/onap/policy/rest/jpa/MicroServiceDictionaryJPATest.java)125
-rw-r--r--ONAP-REST/src/test/java/org/onap/policy/rest/jpa/MicroserviceHeaderdeFaultsTest.java54
-rw-r--r--ONAP-REST/src/test/java/org/onap/policy/rest/jpa/OptimizationModelsJpaTest.java (renamed from ONAP-REST/src/test/java/org/onap/policy/rest/jpa/OptimizationModelsJPATest.java)26
-rw-r--r--ONAP-REST/src/test/java/org/onap/policy/rest/jpa/PIPConfigurationTest.java121
-rw-r--r--ONAP-REST/src/test/java/org/onap/policy/rest/jpa/PipConfigurationTest.java196
-rw-r--r--ONAP-REST/src/test/java/org/onap/policy/rest/jpa/PipJpaTest.java (renamed from ONAP-REST/src/test/java/org/onap/policy/rest/jpa/PIPJPATest.java)131
-rw-r--r--ONAP-REST/src/test/java/org/onap/policy/rest/jpa/PolicyAuditlogTest.java3
-rw-r--r--ONAP-REST/src/test/java/org/onap/policy/rest/jpa/PolicyEntityJPATest.java206
-rw-r--r--ONAP-REST/src/test/java/org/onap/policy/rest/jpa/PolicyEntityJpaTest.java528
-rw-r--r--ONAP-REST/src/test/java/org/onap/policy/rest/jpa/PolicyUtilsJPATest.java190
-rw-r--r--ONAP-REST/src/test/java/org/onap/policy/rest/jpa/PolicyUtilsJpaTest.java320
-rw-r--r--ONAP-REST/src/test/java/org/onap/policy/rest/util/DummyPolicyContainer.java77
-rw-r--r--ONAP-REST/src/test/java/org/onap/policy/rest/util/MsAttributeObjectTest.java (renamed from ONAP-REST/src/test/java/org/onap/policy/rest/util/MSAttributeObjectTest.java)13
-rw-r--r--ONAP-REST/src/test/java/org/onap/policy/rest/util/MsModelUtilsTest.java (renamed from ONAP-REST/src/test/java/org/onap/policy/rest/util/MSModelUtilsTest.java)47
-rw-r--r--ONAP-REST/src/test/java/org/onap/policy/rest/util/PDPPolicyContainerTest.java138
-rw-r--r--ONAP-REST/src/test/java/org/onap/policy/rest/util/ParserExceptionTest.java34
-rw-r--r--ONAP-REST/src/test/java/org/onap/policy/rest/util/PdpPolicyContainerTest.java267
-rw-r--r--ONAP-REST/src/test/java/org/onap/policy/rest/util/PolicyItemSetChangeNotifierTest.java69
-rw-r--r--ONAP-REST/src/test/java/org/onap/policy/rest/util/PolicyValidationRequestWrapperTest.java422
-rw-r--r--ONAP-REST/src/test/java/org/onap/policy/rest/util/PolicyValidationTest.java1234
-rw-r--r--ONAP-REST/src/test/resources/policies/DecisionPolicy.json1556
-rw-r--r--ONAP-REST/src/test/resources/policies/MicroServicePolicy.json38
-rw-r--r--ONAP-REST/src/test/resources/policies/MicroServicePolicyContent0.json23
-rw-r--r--ONAP-REST/src/test/resources/policies/MicroServicePolicyContent1.json27
-rw-r--r--ONAP-REST/src/test/resources/policies/PolicyJsonTrapFault.json9
-rw-r--r--ONAP-SDK-APP/pom.xml106
-rw-r--r--ONAP-SDK-APP/src/main/resources/logback.xml148
-rw-r--r--ONAP-SDK-APP/src/main/webapp/WEB-INF/defs/definitions.xml23
-rw-r--r--ONAP-SDK-APP/src/test/java/org/onap/portalapp/scheduler/RegisterTest.java5
-rw-r--r--ONAP-XACML/pom.xml25
-rw-r--r--ONAP-XACML/src/main/java/org/onap/policy/xacml/api/XACMLErrorConstants.java68
-rw-r--r--ONAP-XACML/src/main/java/org/onap/policy/xacml/api/pap/ONAPPapEngineFactory.java65
-rw-r--r--ONAP-XACML/src/main/java/org/onap/policy/xacml/api/pap/OnapPAPPolicy.java154
-rw-r--r--ONAP-XACML/src/main/java/org/onap/policy/xacml/api/pap/OnapPDP.java27
-rw-r--r--ONAP-XACML/src/main/java/org/onap/policy/xacml/api/pap/OnapPDPGroup.java20
-rw-r--r--ONAP-XACML/src/main/java/org/onap/policy/xacml/api/pap/PAPPolicyEngine.java3
-rw-r--r--ONAP-XACML/src/main/java/org/onap/policy/xacml/std/pap/StdEngine.java217
-rw-r--r--ONAP-XACML/src/main/java/org/onap/policy/xacml/std/pap/StdEngineFactory.java59
-rw-r--r--ONAP-XACML/src/main/java/org/onap/policy/xacml/std/pap/StdPAPPolicy.java85
-rw-r--r--ONAP-XACML/src/main/java/org/onap/policy/xacml/std/pap/StdPAPPolicyParams.java37
-rw-r--r--ONAP-XACML/src/main/java/org/onap/policy/xacml/std/pap/StdPDP.java406
-rw-r--r--ONAP-XACML/src/main/java/org/onap/policy/xacml/std/pap/StdPDPGroup.java1997
-rw-r--r--ONAP-XACML/src/main/java/org/onap/policy/xacml/std/pap/StdPDPGroupStatus.java708
-rw-r--r--ONAP-XACML/src/main/java/org/onap/policy/xacml/std/pap/StdPDPItemSetChangeNotifier.java126
-rw-r--r--ONAP-XACML/src/main/java/org/onap/policy/xacml/std/pap/StdPDPPIPConfig.java343
-rw-r--r--ONAP-XACML/src/main/java/org/onap/policy/xacml/std/pap/StdPDPPolicy.java146
-rw-r--r--ONAP-XACML/src/main/java/org/onap/policy/xacml/std/pap/StdPDPPolicyParams.java85
-rw-r--r--ONAP-XACML/src/main/java/org/onap/policy/xacml/std/pap/StdPDPStatus.java472
-rw-r--r--ONAP-XACML/src/main/java/org/onap/policy/xacml/std/pip/engines/OperationHistoryEngine.java460
-rw-r--r--ONAP-XACML/src/main/java/org/onap/policy/xacml/std/pip/engines/aaf/AAFEngine.java459
-rw-r--r--ONAP-XACML/src/main/java/org/onap/policy/xacml/util/MetricsUtil.java131
-rw-r--r--ONAP-XACML/src/main/java/org/onap/policy/xacml/util/XACMLPolicyScanner.java1222
-rw-r--r--ONAP-XACML/src/main/java/org/onap/policy/xacml/util/XACMLPolicyWriter.java191
-rw-r--r--ONAP-XACML/src/test/java/org/onap/policy/xacml/api/pap/ONAPPapEngineFactoryTest.java38
-rw-r--r--ONAP-XACML/src/test/java/org/onap/policy/xacml/test/api/XACMLErrorConstantsTest.java11
-rw-r--r--ONAP-XACML/src/test/java/org/onap/policy/xacml/test/std/pap/StdEngineFactoryTest.java115
-rw-r--r--ONAP-XACML/src/test/java/org/onap/policy/xacml/test/std/pap/StdEngineTest.java74
-rw-r--r--ONAP-XACML/src/test/java/org/onap/policy/xacml/test/std/pap/StdPAPPolicyTest.java980
-rw-r--r--ONAP-XACML/src/test/java/org/onap/policy/xacml/test/std/pap/StdPDPGroupStatusTest.java23
-rw-r--r--ONAP-XACML/src/test/java/org/onap/policy/xacml/test/std/pap/StdPDPGroupTest.java6
-rw-r--r--ONAP-XACML/src/test/java/org/onap/policy/xacml/test/std/pap/StdPDPPIPConfigTest.java16
-rw-r--r--ONAP-XACML/src/test/java/org/onap/policy/xacml/test/std/pap/StdPDPPolicyTest.java17
-rw-r--r--ONAP-XACML/src/test/java/org/onap/policy/xacml/test/std/pap/StdPDPStatusTest.java148
-rw-r--r--ONAP-XACML/src/test/java/org/onap/policy/xacml/test/std/pap/StdPDPTest.java19
-rw-r--r--ONAP-XACML/src/test/java/org/onap/policy/xacml/test/std/pip/engines/OperationHistoryEngineTest.java11
-rw-r--r--ONAP-XACML/src/test/java/org/onap/policy/xacml/test/util/AAFEngineTest.java18
-rw-r--r--ONAP-XACML/src/test/java/org/onap/policy/xacml/test/util/MetricsUtilTest.java4
-rw-r--r--ONAP-XACML/src/test/java/org/onap/policy/xacml/test/util/XACMLPolicyScannerTest.java180
-rw-r--r--ONAP-XACML/src/test/java/org/onap/policy/xacml/test/util/XACMLPolicyWriterTest.java22
-rw-r--r--ONAP-XACML/src/test/resources/logback-test.xml126
-rw-r--r--POLICY-SDK-APP/pom.xml112
-rw-r--r--POLICY-SDK-APP/src/main/java/org/onap/policy/admin/CheckPdpProperties.java (renamed from POLICY-SDK-APP/src/main/java/org/onap/policy/admin/CheckPDP.java)58
-rw-r--r--POLICY-SDK-APP/src/main/java/org/onap/policy/admin/PolicyAdapter.java49
-rw-r--r--POLICY-SDK-APP/src/main/java/org/onap/policy/admin/PolicyManagerServlet.java442
-rw-r--r--POLICY-SDK-APP/src/main/java/org/onap/policy/admin/PolicyNotificationMail.java145
-rw-r--r--POLICY-SDK-APP/src/main/java/org/onap/policy/admin/PolicyRestController.java158
-rw-r--r--POLICY-SDK-APP/src/main/java/org/onap/policy/admin/PolicyUserInfoController.java20
-rw-r--r--POLICY-SDK-APP/src/main/java/org/onap/policy/admin/RESTfulPAPEngine.java190
-rw-r--r--POLICY-SDK-APP/src/main/java/org/onap/policy/components/HumanPolicyComponent.java377
-rw-r--r--POLICY-SDK-APP/src/main/java/org/onap/policy/conf/HibernateSession.java67
-rw-r--r--POLICY-SDK-APP/src/main/java/org/onap/policy/controller/ActionPolicyController.java250
-rw-r--r--POLICY-SDK-APP/src/main/java/org/onap/policy/controller/AdminTabController.java71
-rw-r--r--POLICY-SDK-APP/src/main/java/org/onap/policy/controller/AutoPushController.java127
-rw-r--r--POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateBRMSParamController.java289
-rw-r--r--POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateBRMSRawController.java117
-rw-r--r--POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateClosedLoopFaultController.java255
-rw-r--r--POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateClosedLoopPMController.java151
-rw-r--r--POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateDcaeMicroServiceController.java711
-rw-r--r--POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateFirewallController.java1726
-rw-r--r--POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateOptimizationController.java383
-rw-r--r--POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreatePolicyController.java203
-rw-r--r--POLICY-SDK-APP/src/main/java/org/onap/policy/controller/DashboardController.java182
-rw-r--r--POLICY-SDK-APP/src/main/java/org/onap/policy/controller/DecisionPolicyController.java528
-rw-r--r--POLICY-SDK-APP/src/main/java/org/onap/policy/controller/ExportAndImportDecisionBlackListEntries.java44
-rw-r--r--POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PDPController.java732
-rw-r--r--POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PolicyController.java165
-rw-r--r--POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PolicyExportAndImportController.java167
-rw-r--r--POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PolicyNotificationController.java169
-rw-r--r--POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PolicyRolesController.java109
-rw-r--r--POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PolicyValidationController.java70
-rw-r--r--POLICY-SDK-APP/src/main/java/org/onap/policy/dao/SystemLogDbDao.java12
-rw-r--r--POLICY-SDK-APP/src/main/java/org/onap/policy/daoImp/CommonClassDaoImpl.java662
-rw-r--r--POLICY-SDK-APP/src/main/java/org/onap/policy/daoImp/SystemLogDbDaoImpl.java126
-rw-r--r--POLICY-SDK-APP/src/main/java/org/onap/policy/model/PDPGroupContainer.java80
-rw-r--r--POLICY-SDK-APP/src/main/java/org/onap/policy/model/Roles.java131
-rw-r--r--POLICY-SDK-APP/src/main/java/org/onap/policy/utils/UserUtils.java25
-rw-r--r--POLICY-SDK-APP/src/main/webapp/WEB-INF/conf/system.properties4
-rw-r--r--POLICY-SDK-APP/src/main/webapp/app/policyApp/CSS/bootstrap/dist/js/bootstrap-modalmanager.min.js341
-rw-r--r--POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/AutoPushController.js135
-rw-r--r--POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/AutoPushTabController/RemovePDPGroupPoliciesController.js4
-rw-r--r--POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/PolicyAddScopeRoleController.js6
-rw-r--r--POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dashboardCRUDController.js185
-rw-r--r--POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/BRMSControllerDictController.js4
-rw-r--r--POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/BRMSDependencyDictController.js4
-rw-r--r--POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/BRMSParamDictController.js5
-rw-r--r--POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/CLPepOptionsDictController.js4
-rw-r--r--POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/CLServiceDictController.js4
-rw-r--r--POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/CLSiteDictController.js4
-rw-r--r--POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/CLVarbindDictController.js4
-rw-r--r--POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/CLVnfTypeDictController.js4
-rw-r--r--POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/CLVsclActionDictController.js4
-rw-r--r--POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/DecisionRainyDayDictController.js14
-rw-r--r--POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/DecisionSettingsDictController.js4
-rw-r--r--POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/DescriptiveSearchDictController.js4
-rw-r--r--POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/EnforcerDictController.js22
-rw-r--r--POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/FWActionListDictController.js4
-rw-r--r--POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/FWAddressGroupDictController.js4
-rw-r--r--POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/FWParentListDictController.js4
-rw-r--r--POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/FWPortListDictController.js4
-rw-r--r--POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/FWPrefixListDictController.js4
-rw-r--r--POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/FWProtocolListDictController.js4
-rw-r--r--POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/FWSecurityZoneDictController.js72
-rw-r--r--POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/FWServiceGroupDictController.js4
-rw-r--r--POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/FWServiceListDictController.js4
-rw-r--r--POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/FWTagListDictController.js4
-rw-r--r--POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/FWTagPickerListDictController.js4
-rw-r--r--POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/FWTermListDictController.js28
-rw-r--r--POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/FWZoneDictController.js4
-rw-r--r--POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/MSConfigNameDictController.js4
-rw-r--r--POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/MSDcaeUUIDDictController.js4
-rw-r--r--POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/MSDictionaryController.js2
-rw-r--r--POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/MSHeaderDefaultValuesDictController.js195
-rw-r--r--POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/MSLocationDictController.js4
-rw-r--r--POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/ModelAttributeDictController.js4
-rw-r--r--POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/PSClosedLoopDictController.js4
-rw-r--r--POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/PSGroupPolicyScopeDictController.js156
-rw-r--r--POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/PSResourceDictController.js4
-rw-r--r--POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/PSServiceDictController.js4
-rw-r--r--POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/PSTypeDictController.js4
-rw-r--r--POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/RiskTypeDictController.js4
-rw-r--r--POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/SafePolicyWarningDictController.js4
-rw-r--r--POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/actionPolicyDictController.js4
-rw-r--r--POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/attributeDictController.js7
-rw-r--r--POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/onapNameEditorController.js4
-rw-r--r--POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryGridController/BRMSParamDictGridController.js6
-rw-r--r--POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryGridController/CLPepOptionsDictGridController.js6
-rw-r--r--POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryGridController/CLServiceDictGridController.js6
-rw-r--r--POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryGridController/CLSiteDictGridController.js6
-rw-r--r--POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryGridController/CLVarbindDictGridController.js4
-rw-r--r--POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryGridController/CLVnfTypeDictGridController.js6
-rw-r--r--POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryGridController/CLVsclActionDictGridController.js6
-rw-r--r--POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryGridController/MSHeaderDefaultValuesDictGridController.js27
-rw-r--r--POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryGridController/attributeDictGridController.js6
-rw-r--r--POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryGridController/onapNameDictGridController.js8
-rw-r--r--POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/policyAdminTabController.js84
-rw-r--r--POLICY-SDK-APP/src/main/webapp/app/policyApp/main/modalPopupController.js22
-rw-r--r--POLICY-SDK-APP/src/main/webapp/app/policyApp/main/policyEditor.html529
-rw-r--r--POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/PolicyTemplateController/ActionPolicyController.js15
-rw-r--r--POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/PolicyTemplateController/BRMSParamPolicyController.js233
-rw-r--r--POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/PolicyTemplateController/BRMSRawPolicyController.js218
-rw-r--r--POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/PolicyTemplateController/BaseConfigPolicyController.js6
-rw-r--r--POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/PolicyTemplateController/ClosedLoopFaultController.js1521
-rw-r--r--POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/PolicyTemplateController/ClosedLoopPMController.js6
-rw-r--r--POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/PolicyTemplateController/DCAEMicroServicePolicyController.js3126
-rw-r--r--POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/PolicyTemplateController/DecisionPolicyController.js848
-rw-r--r--POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/PolicyTemplateController/FirewallPolicyController.js270
-rw-r--r--POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/PolicyTemplateController/OptimizationPolicyController.js2370
-rw-r--r--POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/js/controllers/policyManager.js576
-rw-r--r--POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/js/controllers/policySearchManager.js330
-rw-r--r--POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/js/entities/item.js5
-rw-r--r--POLICY-SDK-APP/src/main/webapp/app/policyApp/service/modalService.js12
-rw-r--r--POLICY-SDK-APP/src/test/java/org/onap/policy/admin/CheckPDPTest.java95
-rw-r--r--POLICY-SDK-APP/src/test/java/org/onap/policy/admin/CheckPdpPropertiesTest.java82
-rw-r--r--POLICY-SDK-APP/src/test/java/org/onap/policy/admin/PolicyManagerServletTest.java686
-rw-r--r--POLICY-SDK-APP/src/test/java/org/onap/policy/admin/PolicyNotificationMailTest.java28
-rw-r--r--POLICY-SDK-APP/src/test/java/org/onap/policy/admin/PolicyRestControllerTest.java295
-rw-r--r--POLICY-SDK-APP/src/test/java/org/onap/policy/admin/PolicyUserInfoControllerTest.java22
-rw-r--r--POLICY-SDK-APP/src/test/java/org/onap/policy/admin/RESTfulPAPEngineTest.java204
-rw-r--r--POLICY-SDK-APP/src/test/java/org/onap/policy/components/HumanPolicyComponentTest.java839
-rw-r--r--POLICY-SDK-APP/src/test/java/org/onap/policy/conf/HibernateSessionTest.java7
-rw-r--r--POLICY-SDK-APP/src/test/java/org/onap/policy/controller/ActionPolicyControllerTest.java205
-rw-r--r--POLICY-SDK-APP/src/test/java/org/onap/policy/controller/AdminTabControllerTest.java44
-rw-r--r--POLICY-SDK-APP/src/test/java/org/onap/policy/controller/AutoPushControllerTest.java142
-rw-r--r--POLICY-SDK-APP/src/test/java/org/onap/policy/controller/CreateDcaeMicroServiceControllerTest.java34
-rw-r--r--POLICY-SDK-APP/src/test/java/org/onap/policy/controller/CreateOptimizationControllerTest.java109
-rw-r--r--POLICY-SDK-APP/src/test/java/org/onap/policy/controller/CreatePolicyControllerTest.java139
-rw-r--r--POLICY-SDK-APP/src/test/java/org/onap/policy/controller/DashboardControllerTest.java19
-rw-r--r--POLICY-SDK-APP/src/test/java/org/onap/policy/controller/ExportAndImportDecisionBlackListEntriesTest.java4
-rw-r--r--POLICY-SDK-APP/src/test/java/org/onap/policy/controller/PDPControllerTest.java34
-rw-r--r--POLICY-SDK-APP/src/test/java/org/onap/policy/controller/PolicyControllerTest.java16
-rw-r--r--POLICY-SDK-APP/src/test/java/org/onap/policy/controller/PolicyExportAndImportControllerTest.java25
-rw-r--r--POLICY-SDK-APP/src/test/java/org/onap/policy/controller/PolicyNotificationControllerTest.java23
-rw-r--r--POLICY-SDK-APP/src/test/java/org/onap/policy/controller/PolicyRolesControllerTest.java23
-rw-r--r--POLICY-SDK-APP/src/test/java/org/onap/policy/controller/PolicyValidationControllerTest.java11
-rw-r--r--POLICY-SDK-APP/src/test/java/org/onap/policy/daoImp/CommonClassDaoImplTest.java162
-rw-r--r--POLICY-SDK-APP/src/test/java/org/onap/policy/daoImp/SystemLogDbDaoImplTest.java77
-rw-r--r--POLICY-SDK-APP/src/test/java/org/onap/policy/model/PDPGroupContainerTest.java165
-rw-r--r--POLICY-SDK-APP/src/test/java/org/onap/policy/model/RolesTest.java38
-rw-r--r--POLICY-SDK-APP/src/test/resources/logback.xml124
-rw-r--r--POLICY-SDK-APP/src/test/resources/xacml.admin.properties8
-rw-r--r--PolicyEngineAPI/pom.xml48
-rw-r--r--PolicyEngineAPI/src/main/java/org/onap/policy/api/ImportParameters.java295
-rw-r--r--PolicyEngineAPI/src/main/resources/logback.xml148
-rw-r--r--PolicyEngineAPI/src/test/java/org/onap/policy/std/StdPolicyEngineTest.java9
-rw-r--r--PolicyEngineAPI/src/test/java/org/onap/policy/std/test/ManualClientEndUEBTest.java1
-rw-r--r--PolicyEngineAPI/src/test/java/org/onap/policy/std/test/NotificationStoreTest.java1
-rw-r--r--PolicyEngineAPI/src/test/java/org/onap/policy/test/PolicyConfigStatusTest.java6
-rw-r--r--PolicyEngineClient/pom.xml2
-rw-r--r--PolicyEngineClient/src/test/java/org/onap/policyengine/ActionPolicyClient.java156
-rw-r--r--PolicyEngineClient/src/test/java/org/onap/policyengine/BrmsParamPolicyClient.java77
-rw-r--r--PolicyEngineClient/src/test/java/org/onap/policyengine/BrmsRawPolicyClient.java51
-rw-r--r--PolicyEngineClient/src/test/java/org/onap/policyengine/ClosedLoopPolicyClient.java167
-rw-r--r--PolicyEngineClient/src/test/java/org/onap/policyengine/ClosedLoopPolicyPerformanceMetricClient.java169
-rw-r--r--PolicyEngineClient/src/test/java/org/onap/policyengine/ConfigBasePolicyClient.java108
-rw-r--r--PolicyEngineClient/src/test/java/org/onap/policyengine/ConfigFirewallPolicyClient.java143
-rw-r--r--PolicyEngineClient/src/test/java/org/onap/policyengine/DecisionPolicyClient.java167
-rw-r--r--PolicyEngineClient/src/test/java/org/onap/policyengine/DeletePolicyClient.java53
-rw-r--r--PolicyEngineClient/src/test/java/org/onap/policyengine/GeneralTestClient.java653
-rw-r--r--PolicyEngineClient/src/test/java/org/onap/policyengine/GetConfigSample.java31
-rw-r--r--PolicyEngineClient/src/test/java/org/onap/policyengine/Handler.java180
-rw-r--r--PolicyEngineClient/src/test/java/org/onap/policyengine/ImportBRMSTemplate.java41
-rw-r--r--PolicyEngineClient/src/test/java/org/onap/policyengine/ImportMicroServiceClient.java47
-rw-r--r--PolicyEngineClient/src/test/java/org/onap/policyengine/ListConfigPoliciesClient.java87
-rw-r--r--PolicyEngineClient/src/test/java/org/onap/policyengine/ListPolicyClient.java7
-rw-r--r--PolicyEngineClient/src/test/java/org/onap/policyengine/MainClient.java169
-rw-r--r--PolicyEngineClient/src/test/java/org/onap/policyengine/MicroServicesPolicyClient.java158
-rw-r--r--PolicyEngineClient/src/test/java/org/onap/policyengine/OptimizationPolicyJavaAPIClient.java162
-rw-r--r--PolicyEngineClient/src/test/java/org/onap/policyengine/PolicyEngineTestClient.java273
-rw-r--r--PolicyEngineClient/src/test/java/org/onap/policyengine/PushPoliciesToPDP.java54
-rw-r--r--PolicyEngineClient/src/test/java/org/onap/policyengine/RawDecisionPolicyClient.java12
-rw-r--r--PolicyEngineClient/src/test/resources/test.drl (renamed from ONAP-REST/src/main/java/org/onap/policy/rest/jpa/package-info.java)23
-rw-r--r--PolicyEngineClient/testResources/test.drl1121
-rw-r--r--PolicyEngineUtils/pom.xml24
-rw-r--r--PolicyEngineUtils/src/main/java/org/onap/policy/api/LoadedPolicy.java11
-rw-r--r--PolicyEngineUtils/src/main/java/org/onap/policy/api/NotificationHandler.java11
-rw-r--r--PolicyEngineUtils/src/main/java/org/onap/policy/api/NotificationType.java17
-rw-r--r--PolicyEngineUtils/src/main/java/org/onap/policy/api/PDPNotification.java8
-rw-r--r--PolicyEngineUtils/src/main/java/org/onap/policy/api/PEDependency.java68
-rw-r--r--PolicyEngineUtils/src/main/java/org/onap/policy/api/RemovedPolicy.java8
-rw-r--r--PolicyEngineUtils/src/main/java/org/onap/policy/api/UpdateType.java17
-rw-r--r--PolicyEngineUtils/src/main/java/org/onap/policy/jpa/BackUpMonitorEntity.java8
-rw-r--r--PolicyEngineUtils/src/main/java/org/onap/policy/std/NotificationStore.java173
-rw-r--r--PolicyEngineUtils/src/main/java/org/onap/policy/std/StdLoadedPolicy.java92
-rw-r--r--PolicyEngineUtils/src/main/java/org/onap/policy/std/StdPDPNotification.java7
-rw-r--r--PolicyEngineUtils/src/main/java/org/onap/policy/std/StdRemovedPolicy.java56
-rw-r--r--PolicyEngineUtils/src/main/java/org/onap/policy/utils/AAFEnvironment.java17
-rw-r--r--PolicyEngineUtils/src/main/java/org/onap/policy/utils/AAFPolicyClient.java45
-rw-r--r--PolicyEngineUtils/src/main/java/org/onap/policy/utils/AAFPolicyClientImpl.java69
-rw-r--r--PolicyEngineUtils/src/main/java/org/onap/policy/utils/AAFPolicyException.java54
-rw-r--r--PolicyEngineUtils/src/main/java/org/onap/policy/utils/BackUpHandler.java42
-rw-r--r--PolicyEngineUtils/src/main/java/org/onap/policy/utils/BackUpMonitor.java121
-rw-r--r--PolicyEngineUtils/src/main/java/org/onap/policy/utils/BackUpMonitorException.java27
-rw-r--r--PolicyEngineUtils/src/main/java/org/onap/policy/utils/BusConsumer.java186
-rw-r--r--PolicyEngineUtils/src/main/java/org/onap/policy/utils/BusPublisher.java215
-rw-r--r--PolicyEngineUtils/src/main/java/org/onap/policy/utils/PeCryptoUtils.java29
-rw-r--r--PolicyEngineUtils/src/main/java/org/onap/policy/utils/PolicyAccess.java19
-rw-r--r--PolicyEngineUtils/src/main/java/org/onap/policy/utils/PolicyUtils.java323
-rw-r--r--PolicyEngineUtils/src/main/java/org/onap/policy/utils/XMLErrorHandler.java8
-rw-r--r--PolicyEngineUtils/src/main/resources/META-INF/persistencePU.xml20
-rw-r--r--PolicyEngineUtils/src/test/java/org/onap/policy/utils/AAFEnvironmentTest.java39
-rw-r--r--PolicyEngineUtils/src/test/java/org/onap/policy/utils/BusTest.java (renamed from PolicyEngineUtils/src/test/java/org/onap/policy/utils/test/BusTest.java)49
-rw-r--r--PolicyEngineUtils/src/test/java/org/onap/policy/utils/PeCryptoUtilsTest.java9
-rw-r--r--PolicyEngineUtils/src/test/java/org/onap/policy/utils/test/AAFClientTest.java46
-rw-r--r--PolicyEngineUtils/src/test/java/org/onap/policy/utils/test/BackUpMonitorEntityTest.java52
-rw-r--r--PolicyEngineUtils/src/test/java/org/onap/policy/utils/test/BackUpMonitorExceptionTest.java61
-rw-r--r--PolicyEngineUtils/src/test/java/org/onap/policy/utils/test/BackUpMonitorTest.java4
-rw-r--r--PolicyEngineUtils/src/test/java/org/onap/policy/utils/test/DummyBackUpHandler.java26
-rw-r--r--PolicyEngineUtils/src/test/java/org/onap/policy/utils/test/NotificationStoreTest.java74
-rw-r--r--PolicyEngineUtils/src/test/java/org/onap/policy/utils/test/PEDependencyTest.java18
-rw-r--r--PolicyEngineUtils/src/test/java/org/onap/policy/utils/test/PolicyUtilsTest.java313
-rw-r--r--PolicyEngineUtils/src/test/resources/META-INF/persistencePUtest.xml79
-rw-r--r--TestSuite/Performance/pom.xml2
-rw-r--r--TestSuite/Stability/pom.xml2
-rw-r--r--TestSuite/pom.xml4
-rw-r--r--docker_build.sh126
-rw-r--r--docker_merge.sh114
-rw-r--r--docker_verify.sh98
-rw-r--r--docs/.gitignore3
-rw-r--r--docs/_static/css/ribbon.css63
-rwxr-xr-xdocs/_static/favicon.icobin0 -> 2102 bytes
-rw-r--r--docs/_static/logo_onap_2017.pngbin0 -> 12278 bytes
-rw-r--r--docs/conf.py15
-rw-r--r--docs/conf.yaml7
-rw-r--r--docs/index.rst5
-rw-r--r--docs/platform/architecture.rst15
-rw-r--r--docs/platform/cookbook.rst12
-rw-r--r--docs/platform/index.rst5
-rw-r--r--docs/platform/offeredapis.rst7
-rw-r--r--docs/release-notes.rst529
-rw-r--r--docs/requirements-docs.txt15
-rw-r--r--docs/tox.ini22
-rw-r--r--lombok.config2
-rwxr-xr-xpackages/base/pom.xml2
-rw-r--r--packages/base/src/files/etc/ssl/policy-keystorebin4407 -> 4431 bytes
-rwxr-xr-xpackages/base/src/files/install/mysql/data/161000_upgrade_script.sql2
-rw-r--r--packages/base/src/files/install/mysql/data/170701_downgrade_script.sql8
-rw-r--r--packages/base/src/files/install/mysql/data/170701_upgrade_script.sql16
-rw-r--r--packages/base/src/files/install/mysql/data/191000_upgrade_script.sql42
-rw-r--r--packages/base/src/files/install/servers/brmsgw/config.properties2
-rw-r--r--packages/base/src/files/install/servers/brmsgw/dependency.json8
-rw-r--r--packages/base/src/files/install/servers/onap/WEB-INF/classes/portal.properties2
-rw-r--r--packages/base/src/files/install/servers/pdp/bin/xacml.pdp.properties12
-rw-r--r--packages/docker/pom.xml232
-rw-r--r--packages/docker/src/main/docker/Dockerfile16
-rw-r--r--packages/docker/src/main/docker/do-start.sh7
-rw-r--r--packages/install/pom.xml2
-rw-r--r--packages/install/src/files/brmsgw.conf4
-rw-r--r--packages/pom.xml89
-rw-r--r--pom.xml135
-rw-r--r--releases/1.5.1.yaml4
-rw-r--r--releases/1.5.2.yaml4
-rw-r--r--releases/1.6.0.yaml4
-rw-r--r--releases/1.6.1-container.yaml8
-rw-r--r--releases/1.6.1.yaml4
-rw-r--r--releases/1.6.2-container.yaml8
-rw-r--r--releases/1.6.2.yaml4
-rw-r--r--releases/1.6.3-container.yaml8
-rw-r--r--releases/1.6.3.yaml5
-rw-r--r--version.properties4
629 files changed, 41487 insertions, 37858 deletions
diff --git a/.gitignore b/.gitignore
index 7df831f3b..dbc83afef 100644
--- a/.gitignore
+++ b/.gitignore
@@ -4,7 +4,12 @@
.classpath
.jupiter
.pydevproject
-.idea
+
+# IntelliJ files
+.idea/
+**/*.iml
+overlays/
+
target
.metadata/
ASTRAGateway/policyEngineLog.log
diff --git a/.gitreview b/.gitreview
index 9e38e62ac..e48a7ec91 100644
--- a/.gitreview
+++ b/.gitreview
@@ -2,3 +2,4 @@
host=gerrit.onap.org
port=29418
project=policy/engine.git
+defaultbranch=master
diff --git a/.readthedocs.yaml b/.readthedocs.yaml
new file mode 100644
index 000000000..3797dc8bb
--- /dev/null
+++ b/.readthedocs.yaml
@@ -0,0 +1,20 @@
+---
+# .readthedocs.yml
+# Read the Docs configuration file
+# See https://docs.readthedocs.io/en/stable/config-file/v2.html for details
+# Required
+version: 2
+
+formats:
+ - htmlzip
+
+build:
+ image: latest
+
+python:
+ version: 3.7
+ install:
+ - requirements: docs/requirements-docs.txt
+
+sphinx:
+ configuration: docs/conf.py
diff --git a/BRMSGateway/config.properties b/BRMSGateway/config.properties
index 592415405..d8f02ba3d 100644
--- a/BRMSGateway/config.properties
+++ b/BRMSGateway/config.properties
@@ -77,7 +77,7 @@ ping_interval=30000
#
#
#
-brms.dependency.version=1.4.1-SNAPSHOT
+brms.dependency.version=1.6.3-SNAPSHOT
ENVIRONMENT = DEVL
diff --git a/BRMSGateway/dependency.json b/BRMSGateway/dependency.json
index 6b0dd1041..bd119bdc2 100644
--- a/BRMSGateway/dependency.json
+++ b/BRMSGateway/dependency.json
@@ -3,120 +3,112 @@
"default": [{
"groupId": "org.onap.policy.drools-applications.controlloop.templates",
"artifactId": "template.demo",
- "version": "1.4.1-SNAPSHOT"
+ "version": "1.6.3-SNAPSHOT"
}, {
"groupId": "org.onap.policy.models.policy-models-interactions.model-impl",
"artifactId": "events",
- "version": "2.0.1-SNAPSHOT"
+ "version": "2.2.6-SNAPSHOT"
}, {
"groupId": "org.onap.policy.models.policy-models-interactions.model-impl",
"artifactId": "rest",
- "version": "2.0.1-SNAPSHOT"
+ "version": "2.2.6-SNAPSHOT"
}, {
"groupId": "org.onap.policy.models.policy-models-interactions.model-impl",
"artifactId": "appc",
- "version": "2.0.1-SNAPSHOT"
+ "version": "2.2.6-SNAPSHOT"
}, {
"groupId": "org.onap.policy.models.policy-models-interactions.model-impl",
"artifactId": "aai",
- "version": "2.0.1-SNAPSHOT"
+ "version": "2.2.6-SNAPSHOT"
}, {
"groupId": "org.onap.policy.models.policy-models-interactions.model-impl",
"artifactId": "so",
- "version": "2.0.1-SNAPSHOT"
+ "version": "2.2.6-SNAPSHOT"
}, {
"groupId": "org.onap.policy.models.policy-models-interactions.model-impl",
"artifactId": "sdnc",
- "version": "2.0.1-SNAPSHOT"
+ "version": "2.2.6-SNAPSHOT"
}, {
"groupId": "org.onap.policy.models.policy-models-interactions.model-impl",
"artifactId": "sdnr",
- "version": "2.0.1-SNAPSHOT"
- }, {
- "groupId": "org.onap.policy.models.policy-models-interactions.model-impl",
- "artifactId": "trafficgenerator",
- "version": "2.0.1-SNAPSHOT"
+ "version": "2.2.6-SNAPSHOT"
}],
"amsterdam": [{
"groupId": "org.onap.policy.models.policy-models-interactions.model-impl",
"artifactId": "events",
- "version": "2.0.1-SNAPSHOT"
+ "version": "2.2.6-SNAPSHOT"
}, {
"groupId": "org.onap.policy.models.policy-models-interactions.model-impl",
"artifactId": "appc",
- "version": "2.0.1-SNAPSHOT"
+ "version": "2.2.6-SNAPSHOT"
}, {
"groupId": "org.onap.policy.models.policy-models-interactions.model-impl",
"artifactId": "appclcm",
- "version": "2.0.1-SNAPSHOT"
+ "version": "2.2.6-SNAPSHOT"
}, {
"groupId": "org.onap.policy.models.policy-models-interactions.model-impl",
"artifactId": "vfc",
- "version": "2.0.1-SNAPSHOT"
+ "version": "2.2.6-SNAPSHOT"
}, {
"groupId": "org.onap.policy.models.policy-models-interactions.model-impl",
"artifactId": "so",
- "version": "2.0.1-SNAPSHOT"
+ "version": "2.2.6-SNAPSHOT"
}, {
"groupId": "org.onap.policy.models.policy-models-interactions.model-impl",
"artifactId": "sdnr",
- "version": "2.0.1-SNAPSHOT"
+ "version": "2.2.6-SNAPSHOT"
}, {
"groupId": "org.onap.policy.models.policy-models-interactions.model-impl",
"artifactId": "sdnc",
- "version": "2.0.1-SNAPSHOT"
+ "version": "2.2.6-SNAPSHOT"
}, {
"groupId": "org.onap.policy.models.policy-models-interactions.model-impl",
"artifactId": "aai",
- "version": "2.0.1-SNAPSHOT"
+ "version": "2.2.6-SNAPSHOT"
}, {
"groupId": "org.onap.policy.models.policy-models-interactions.model-impl",
"artifactId": "sdc",
- "version": "2.0.1-SNAPSHOT"
- }, {
- "groupId": "org.onap.policy.models.policy-models-interactions.model-impl",
- "artifactId": "trafficgenerator",
- "version": "2.0.1-SNAPSHOT"
+ "version": "2.2.6-SNAPSHOT"
}, {
"groupId": "org.onap.policy.drools-applications.controlloop.common",
"artifactId": "eventmanager",
- "version": "1.4.1-SNAPSHOT"
+ "version": "1.6.3-SNAPSHOT"
}, {
"groupId": "org.onap.policy.drools-applications.controlloop.common",
"artifactId": "guard",
- "version": "1.4.1-SNAPSHOT"
+ "version": "1.6.3-SNAPSHOT"
}, {
"groupId": "org.onap.policy.models.policy-models-interactions.model-actors",
"artifactId": "actorServiceProvider",
- "version": "2.0.1-SNAPSHOT"
+ "version": "2.2.6-SNAPSHOT"
}, {
"groupId": "org.onap.policy.models.policy-models-interactions.model-actors",
"artifactId": "actor.appc",
- "version": "2.0.1-SNAPSHOT"
+ "version": "2.2.6-SNAPSHOT"
}, {
"groupId": "org.onap.policy.models.policy-models-interactions.model-actors",
"artifactId": "actor.appclcm",
- "version": "2.0.1-SNAPSHOT"
+ "version": "2.2.6-SNAPSHOT"
}, {
"groupId": "org.onap.policy.models.policy-models-interactions.model-actors",
"artifactId": "actor.so",
- "version": "2.0.1-SNAPSHOT"
+ "version": "2.2.6-SNAPSHOT"
}, {
"groupId": "org.onap.policy.models.policy-models-interactions.model-actors",
"artifactId": "actor.sdnc",
- "version": "2.0.1-SNAPSHOT"
+ "version": "2.2.6-SNAPSHOT"
}, {
"groupId": "org.onap.policy.models.policy-models-interactions.model-actors",
"artifactId": "actor.sdnr",
- "version": "2.0.1-SNAPSHOT"
+ "version": "2.2.6-SNAPSHOT"
}, {
"groupId": "org.onap.policy.models.policy-models-interactions.model-actors",
"artifactId": "actor.vfc",
- "version": "2.0.1-SNAPSHOT"
+ "version": "2.2.6-SNAPSHOT"
}, {
"groupId": "org.onap.policy.models.policy-models-interactions",
"artifactId": "model-yaml",
- "version": "2.0.1-SNAPSHOT"
+ "version": "2.2.6-SNAPSHOT"
}, {
"groupId": "com.att.research.xacml",
"artifactId": "xacml-pdp",
diff --git a/BRMSGateway/pom.xml b/BRMSGateway/pom.xml
index b3fd734ec..dab57c5fa 100644
--- a/BRMSGateway/pom.xml
+++ b/BRMSGateway/pom.xml
@@ -2,7 +2,7 @@
============LICENSE_START=======================================================
ONAP Policy Engine
================================================================================
- Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ Copyright (C) 2017-2018, 2020 AT&T Intellectual Property. All rights reserved.
================================================================================
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
@@ -23,7 +23,7 @@
<parent>
<groupId>org.onap.policy.engine</groupId>
<artifactId>PolicyEngineSuite</artifactId>
- <version>1.4.1-SNAPSHOT</version>
+ <version>1.6.4-SNAPSHOT</version>
</parent>
<artifactId>BRMSGateway</artifactId>
<description>This application will take in BRMS rules and acts as interface between PR and PDP XACML</description>
@@ -91,6 +91,11 @@
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
</dependency>
+ <dependency>
+ <groupId>org.apache.commons</groupId>
+ <artifactId>commons-lang3</artifactId>
+ <version>3.9</version>
+ </dependency>
</dependencies>
<build>
<plugins>
@@ -109,7 +114,7 @@
<configLocation>onap-checkstyle/onap-java-style.xml</configLocation>
<!-- <sourceDirectory> is needed so that checkstyle
ignores the generated sources directory -->
- <sourceDirectory>${project.build.sourceDirectory}</sourceDirectory>
+ <sourceDirectories>${project.build.sourceDirectory}</sourceDirectories>
<includeResources>true</includeResources>
<includeTestSourceDirectory>true</includeTestSourceDirectory>
<includeTestResources>true</includeTestResources>
@@ -123,7 +128,7 @@
<dependency>
<groupId>org.onap.oparent</groupId>
<artifactId>checkstyle</artifactId>
- <version>0.1.1</version>
+ <version>${oparent.version}</version>
<scope>compile</scope>
</dependency>
</dependencies>
diff --git a/BRMSGateway/src/main/java/org/onap/policy/brms/api/BrmsGateway.java b/BRMSGateway/src/main/java/org/onap/policy/brms/api/BrmsGateway.java
index e743794ec..093bf4bae 100644
--- a/BRMSGateway/src/main/java/org/onap/policy/brms/api/BrmsGateway.java
+++ b/BRMSGateway/src/main/java/org/onap/policy/brms/api/BrmsGateway.java
@@ -2,14 +2,14 @@
* ============LICENSE_START=======================================================
* ONAP Policy Engine
* ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017, 2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -20,6 +20,7 @@
package org.onap.policy.brms.api;
+import java.util.concurrent.CountDownLatch;
import org.onap.policy.api.NotificationScheme;
import org.onap.policy.api.PolicyEngine;
import org.onap.policy.api.PolicyException;
@@ -31,7 +32,7 @@ import org.onap.policy.xacml.api.XACMLErrorConstants;
* BRMSGateway: This application acts as the Gateway interface between the PDP XACML and PDP Drools.
* The listens for BRMS based policies and pushes them to the specified Policy Repository, from
* where the PDP Drools reads the Rule Jar.
- *
+ *
* @version 0.1
*/
public class BrmsGateway {
@@ -41,6 +42,9 @@ public class BrmsGateway {
private static PolicyEngine policyEngine = null;
+ // may be overridden by junit tests
+ private static Factory factory = new Factory();
+
private BrmsGateway() {
// Default private constructor
}
@@ -68,7 +72,7 @@ public class BrmsGateway {
logger.info("Initializing BRMS Handler");
BrmsHandler brmsHandler = null;
try {
- brmsHandler = new BrmsHandler(configFile);
+ brmsHandler = factory.makeBrmsHandler(configFile);
} catch (final PolicyException e) {
String errorString = "Check your property file: " + e.getMessage();
logger.error(errorString);
@@ -85,21 +89,34 @@ public class BrmsGateway {
}
// Keep Running....
+ CountDownLatch latch = new CountDownLatch(1);
final Runnable runnable = () -> {
- while (true) {
- try {
- Thread.sleep(30000);
- } catch (final InterruptedException e) {
- logger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Thread Exception " + e.getMessage());
- Thread.currentThread().interrupt();
- }
+ try {
+ // wait until interrupted
+ latch.await();
+ } catch (final InterruptedException e) {
+ logger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Thread Exception " + e.getMessage());
+ Thread.currentThread().interrupt();
}
};
- final Thread thread = new Thread(runnable);
+ final Thread thread = factory.makeThread(runnable);
thread.start();
}
public static PolicyEngine getPolicyEngine() {
return policyEngine;
}
+
+ /**
+ * Factory to provide various data. May be overridden by junit tests.
+ */
+ public static class Factory {
+ public BrmsHandler makeBrmsHandler(String configFile) throws PolicyException {
+ return new BrmsHandler(configFile);
+ }
+
+ public Thread makeThread(Runnable runnable) {
+ return new Thread(runnable);
+ }
+ }
}
diff --git a/BRMSGateway/src/main/java/org/onap/policy/brms/api/BrmsPush.java b/BRMSGateway/src/main/java/org/onap/policy/brms/api/BrmsPush.java
index 97e225890..e321811a3 100644
--- a/BRMSGateway/src/main/java/org/onap/policy/brms/api/BrmsPush.java
+++ b/BRMSGateway/src/main/java/org/onap/policy/brms/api/BrmsPush.java
@@ -60,7 +60,7 @@ import javax.persistence.Persistence;
import javax.persistence.TypedQuery;
import javax.ws.rs.ProcessingException;
import org.apache.commons.io.FileUtils;
-import org.apache.commons.lang.StringEscapeUtils;
+import org.apache.commons.lang3.StringEscapeUtils;
import org.apache.maven.model.Dependency;
import org.apache.maven.model.DeploymentRepository;
import org.apache.maven.model.DistributionManagement;
@@ -117,7 +117,7 @@ public class BrmsPush {
private static final Logger LOGGER = FlexLogger.getLogger(BrmsPush.class.getName());
private static final String PROJECTSLOCATION = "RuleProjects";
private static final String[] GOALS = {"clean", "deploy"};
- private static final String DEFAULT_VERSION = "1.4.1-SNAPSHOT";
+ private static final String DEFAULT_VERSION = "1.6.3-SNAPSHOT";
private static final String DEPENDENCY_FILE = "dependency.json";
private static final String PROP_AES_KEY = "org.onap.policy.encryption.aes.key";
public static final String BRMSPERSISTENCE = "brmsEclipselink.persistencexml";
@@ -256,8 +256,8 @@ public class BrmsPush {
repUrlList = new ArrayList<>();
repUrlList.add(repUrl);
}
- repUserName = config.getProperty("repositoryUsername");
- repPassword = PeCryptoUtils.decrypt(config.getProperty("repositoryPassword"));
+ repUserName = getValue(config.getProperty("repositoryUsername"));
+ repPassword = PeCryptoUtils.decrypt(getValue(config.getProperty("repositoryPassword")));
if (repUserName == null || repPassword == null) {
LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE
+ "repostoryUserName and respositoryPassword properties are required.");
@@ -367,6 +367,13 @@ public class BrmsPush {
}
+ private String getValue(final String value) {
+ if (value != null && value.matches("[$][{].*[}]$")) {
+ return System.getenv(value.substring(2, value.length() - 1));
+ }
+ return value;
+ }
+
private static void setBackupMonitor(final BackUpMonitor instance) {
bm = instance;
}
@@ -1049,12 +1056,6 @@ public class BrmsPush {
msoDependency.setArtifactId("controlloop.common.model-impl.so");
msoDependency.setVersion(version);
dependencyList.add(msoDependency);
-
- final Dependency trafficgeneratorDependency = new Dependency();
- trafficgeneratorDependency.setGroupId(DROOLS_APPS_MODEL_GROUP);
- trafficgeneratorDependency.setArtifactId("controlloop.common.model-impl.trafficgenerator");
- trafficgeneratorDependency.setVersion(version);
- dependencyList.add(trafficgeneratorDependency);
return dependencyList;
}
diff --git a/BRMSGateway/src/main/resources/logback.xml b/BRMSGateway/src/main/resources/logback.xml
index b9e12a7b3..07a587212 100644
--- a/BRMSGateway/src/main/resources/logback.xml
+++ b/BRMSGateway/src/main/resources/logback.xml
@@ -2,14 +2,14 @@
============LICENSE_START=======================================================
ONAP Policy Engine
================================================================================
- Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
================================================================================
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
-
+
http://www.apache.org/licenses/LICENSE-2.0
-
+
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -22,73 +22,73 @@
<!--<jmxConfigurator /> -->
<!-- directory path for all other type logs -->
<property name="logDir" value="${POLICY_LOGS}" />
-
+
<!-- directory path for debugging type logs -->
<property name="debugDir" value="${POLICY_LOGS}" />
-
- <!-- specify the component name
+
+ <!-- specify the component name
<ONAP-component-name>::= "MSO" | "DCAE" | "ASDC " | "AAI" |"Policy" | "SDNC" | "AC" -->
<property name="componentName" value="policy"></property>
<property name="subComponentName" value="brmsgw"></property>
-
+
<!-- log file names -->
<property name="errorLogName" value="error" />
<property name="metricsLogName" value="metrics" />
<property name="auditLogName" value="audit" />
<property name="debugLogName" value="debug" />
-
-
+
+
<!-- modified time stamp format -->
-
- <!-- A U D I T
- <property name="defaultAuditPattern" value="%X{BeginTimestamp}|%X{EndTimestamp}|%X{RequestId}|%X{ServiceInstanceId}|%thread|%X{ServerName}|%X{ServiceName}|%X{PartnerName}|%X{StatusCode}|%X{ResponseCode}|%X{ResponseDescription}|%X{InstanceUUID}|%.-5level|%X{AlertSeverity}|%X{ServerIPAddress}|%X{ElapsedTime}|%X{ServerFQDN}|%X{RemoteHost}|%X{ClassName}||%X{ProcessKey}|%X{TargetVirtualEntity}|%X{CustomField1}|%X{CustomField2}|%X{CustomField3}|%X{CustomField4}|%msg%n" />
+
+ <!-- A U D I T
+ <property name="defaultAuditPattern" value="%X{BeginTimestamp}|%X{EndTimestamp}|%X{RequestId}|%X{ServiceInstanceId}|%thread|%X{ServerName}|%X{ServiceName}|%X{PartnerName}|%X{StatusCode}|%X{ResponseCode}|%X{ResponseDescription}|%X{InstanceUUID}|%.-5level|%X{Severity}|%X{ServerIPAddress}|%X{ElapsedTime}|%X{ServerFQDN}|%X{RemoteHost}|%X{ClassName}||%X{ProcessKey}|%X{TargetVirtualEntity}|%X{CustomField1}|%X{CustomField2}|%X{CustomField3}|%X{CustomField4}|%msg%n" />
<property name="defaultAuditPattern" value="%X{BeginTimestamp}|%X{EndTimestamp}|%X{requestId}|%X{serviceInstanceId}|%t|%X{serverName}|%X{serviceName}|%X{PartnerName}|%X{StatusCode}|%X{ResponseCode}|%X{ResponseDescription}|%X{instanceUuid}|%p|%X{severity}|%X{serverIpAddress}|%X{ElapsedTime}|%X{server}|%X{clientIpAddress}|%c||%X{ProcessKey}|%X{TargetVirtualEntity}|%X{CustomField1}|%X{CustomField2}|%X{CustomField3}|%X{CustomField4}|%msg%n" />
-->
<property name="defaultAuditPattern" value="%X{TransactionBeginTimestamp}|%X{TransactionEndTimestamp}|%X{requestId}|%X{serviceInstanceId}|%t|%X{serverName}|%X{serviceName}|%X{partnerName}|%X{statusCode}|%X{ResponseCode}|%X{ResponseDescription}|%X{instanceUuid}|%p|%X{severity}|%X{serverIpAddress}|%X{TransactionElapsedTime}|%X{server}|%X{clientIpAddress}|%c||%X{ProcessKey}|%X{CustomField1}|%X{CustomField2}|%X{CustomField3}|%X{CustomField4}|%msg%n" />
-
-
-
- <!-- M E T R I C
- <property name="defaultMetricPattern" value="%X{BeginTimestamp}|%X{EndTimestamp}|%X{RequestId}|%X{ServiceInstanceId}|%thread|%X{ServerName}|%X{ServiceName}|%X{PartnerName}|%X{TargetEntity}|%X{TargetServiceName}|%X{StatusCode}|%X{ResponseCode}|%X{ResponseDescription}|%X{InstanceUUID}|%.-5level|%X{AlertSeverity}|%X{ServerIPAddress}|%X{ElapsedTime}|%X{ServerFQDN}|%X{RemoteHost}|%X{ClassName}||%X{ProcessKey}|%X{TargetVirtualEntity}|%X{CustomField1}|%X{CustomField2}|%X{CustomField3}|%X{CustomField4}|%msg%n" />
+
+
+
+ <!-- M E T R I C
+ <property name="defaultMetricPattern" value="%X{BeginTimestamp}|%X{EndTimestamp}|%X{RequestId}|%X{ServiceInstanceId}|%thread|%X{ServerName}|%X{ServiceName}|%X{PartnerName}|%X{TargetEntity}|%X{TargetServiceName}|%X{StatusCode}|%X{ResponseCode}|%X{ResponseDescription}|%X{InstanceUUID}|%.-5level|%X{Severity}|%X{ServerIPAddress}|%X{ElapsedTime}|%X{ServerFQDN}|%X{RemoteHost}|%X{ClassName}||%X{ProcessKey}|%X{TargetVirtualEntity}|%X{CustomField1}|%X{CustomField2}|%X{CustomField3}|%X{CustomField4}|%msg%n" />
-->
<property name="defaultMetricPattern" value="%X{MetricBeginTimestamp}|%X{MetricEndTimestamp}|%X{requestId}|%X{serviceInstanceId}|%t|%X{serverName}|%X{serviceName}|%X{partnerName}|%X{targetEntity}|%X{targetServiceName}|%X{statusCode}|%X{ResponseCode}|%X{ResponseDescription}|%X{InstanceUUID}|%p|%X{severity}|%X{serverIpAddress}|%X{MetricElapsedTime}|%X{server}|%X{clientIpAddress}|%c||%X{ProcessKey}|%X{TargetVirtualEntity}|%X{CustomField1}|%X{CustomField2}|%X{CustomField3}|%X{CustomField4}|%msg%n" />
-
-
-
-
+
+
+
+
<!-- E R R O R
<property name="defaultErrorPattern" value="%d{yyyy-MM-dd'T'HH:mm:ss.SSS+00:00, UTC}|%X{RequestId}|%thread|%X{ServiceName}|%X{PartnerName}|%X{TargetEntity}|%X{TargetServiceName}|%X{ErrorCategory}|%X{ErrorCode}|%X{ErrorDesciption}|%msg%n" />
-->
<property name="defaultErrorPattern" value="%d{yyyy-MM-dd'T'HH:mm:ss.SSS+00:00, UTC}|%X{requestId}|%t|%X{serviceName}|%X{PartnerName}|%X{TargetEntity}|%X{TargetServiceName}|%X{ErrorCategory}|%X{ErrorCode}|%X{ErrorDesciption}|%msg%n" />
-
-
-
+
+
+
<!-- D E B U G
- <property name="debugLoggerPatternOld" value="%d{MM/dd-HH:mm:ss.SSS}|%X{RequestId}|%X{ServiceInstanceId}|%thread|%X{ServiceName}|%X{InstanceUUID}|%.-5level|%X{AlertSeverity}|%X{ServerIPAddress}|%X{ServerFQDN}|%X{RemoteHost}|%X{Timer}|[%caller{3}]|%msg%n" />
- <property name="debugLoggerPattern" value="%X{BeginTimestamp}|%X{EndTimestamp}|%X{RequestId}|%X{ServiceInstanceId}|%thread|%X{ServerName}|%X{ServiceName}|%X{PartnerName}|%X{StatusCode}|%X{ResponseCode}|%X{ResponseDescription}|%X{ServiceName}|%X{InstanceUUID}|%.-5level|%X{AlertSeverity}|%X{ServerIPAddress}|%X{ElapsedTime}|%X{ServerFQDN}|%X{RemoteHost}|%X{ClassName}||%X{ProcessKey}|%X{CustomField1}|%X{CustomField2}|%X{CustomField3}|%X{CustomField4}|%msg%n" /> -->
+ <property name="debugLoggerPatternOld" value="%d{MM/dd-HH:mm:ss.SSS}|%X{RequestId}|%X{ServiceInstanceId}|%thread|%X{ServiceName}|%X{InstanceUUID}|%.-5level|%X{Severity}|%X{ServerIPAddress}|%X{ServerFQDN}|%X{RemoteHost}|%X{Timer}|[%caller{3}]|%msg%n" />
+ <property name="debugLoggerPattern" value="%X{BeginTimestamp}|%X{EndTimestamp}|%X{RequestId}|%X{ServiceInstanceId}|%thread|%X{ServerName}|%X{ServiceName}|%X{PartnerName}|%X{StatusCode}|%X{ResponseCode}|%X{ResponseDescription}|%X{ServiceName}|%X{InstanceUUID}|%.-5level|%X{Severity}|%X{ServerIPAddress}|%X{ElapsedTime}|%X{ServerFQDN}|%X{RemoteHost}|%X{ClassName}||%X{ProcessKey}|%X{CustomField1}|%X{CustomField2}|%X{CustomField3}|%X{CustomField4}|%msg%n" /> -->
-->
- <property name="debugLoggerPattern" value="%d{yyyy-MM-dd'T'HH:mm:ss.SSS+00:00, UTC}|%X{RequestId}|%msg%n" />
-
-
-
- <!-- D E F A U L T
- <property name="defaultPatternOld" value="%d{MM/dd-HH:mm:ss.SSS}|%logger|%X{RequestId}|%X{ServiceInstanceId}|%thread|%X{ServiceName}|%X{InstanceUUID}|%.-5level|%X{AlertSeverity}|%X{ServerIPAddress}|%X{ServerFQDN}|%X{RemoteHost}|%X{ClassName}|%X{Timer}|%msg%n" />
- <property name="defaultPattern" value="%X{BeginTimestamp}|%X{EndTimestamp}|%X{RequestId}|%X{ServiceInstanceId}|%thread|%X{ServerName}|%X{ServiceName}|%X{PartnerName}|%X{TargetEntity}|%X{TargetServiceName}|%X{StatusCode}|%X{ResponseCode}|%X{ResponseDescription}|%X{InstanceUUID}|%.-5level|%X{AlertSeverity}|%X{ServerIPAddress}|%X{ElapsedTime}|%X{ServerFQDN}|%X{RemoteHost}|%X{ClassName}||%X{ProcessKey}|%X{TargetVirtualEntity}|%X{CustomField1}|%X{CustomField2}|%X{CustomField3}|%X{CustomField4}|%msg%n" />
+ <property name="debugLoggerPattern" value="%d{yyyy-MM-dd'T'HH:mm:ss.SSS+00:00, UTC}|%X{RequestId}|%msg%n" />
+
+
+
+ <!-- D E F A U L T
+ <property name="defaultPatternOld" value="%d{MM/dd-HH:mm:ss.SSS}|%logger|%X{RequestId}|%X{ServiceInstanceId}|%thread|%X{ServiceName}|%X{InstanceUUID}|%.-5level|%X{Severity}|%X{ServerIPAddress}|%X{ServerFQDN}|%X{RemoteHost}|%X{ClassName}|%X{Timer}|%msg%n" />
+ <property name="defaultPattern" value="%X{BeginTimestamp}|%X{EndTimestamp}|%X{RequestId}|%X{ServiceInstanceId}|%thread|%X{ServerName}|%X{ServiceName}|%X{PartnerName}|%X{TargetEntity}|%X{TargetServiceName}|%X{StatusCode}|%X{ResponseCode}|%X{ResponseDescription}|%X{InstanceUUID}|%.-5level|%X{Severity}|%X{ServerIPAddress}|%X{ElapsedTime}|%X{ServerFQDN}|%X{RemoteHost}|%X{ClassName}||%X{ProcessKey}|%X{TargetVirtualEntity}|%X{CustomField1}|%X{CustomField2}|%X{CustomField3}|%X{CustomField4}|%msg%n" />
-->
<property name="defaultPattern" value="%d{yyyy-MM-dd'T'HH:mm:ss.SSSXXX, UTC}|%X{requestId}|%X{serviceInstanceId}|%t|%X{serverName}|%X{serviceName}|%X{instanceUuid}|%p|%X{severity}|%X{serverIpAddress}|%X{server}|%X{clientIpAddress}|%c||%msg%n" />
-
-
-
+
+
+
<!-- P A T H
<property name="logDirectory" value="${catalina.base}/${logDir}/${componentName}/${subComponentName}" />
- <property name="debugLogDirectory" value="${catalina.base}/${debugDir}/${componentName}/${subComponentName}" />
- -->
+ <property name="debugLogDirectory" value="${catalina.base}/${debugDir}/${componentName}/${subComponentName}" />
+ -->
<property name="logDirectory" value="${logDir}/${componentName}/${subComponentName}" />
<property name="debugLogDirectory" value="${debugDir}/${componentName}/${subComponentName}" />
-
-
-
+
+
+
<!-- Example evaluator filter applied against console appender -->
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
@@ -100,28 +100,28 @@
<!-- EELF Appenders -->
<!-- ============================================================================ -->
- <!-- The EELFAppender is used to record events to the general application
+ <!-- The EELFAppender is used to record events to the general application
log -->
-
- <!-- EELF Audit Appender. This appender is used to record audit engine
- related logging events. The audit logger and appender are specializations
- of the EELF application root logger and appender. This can be used to segregate
- Policy engine events from other components, or it can be eliminated to record
+
+ <!-- EELF Audit Appender. This appender is used to record audit engine
+ related logging events. The audit logger and appender are specializations
+ of the EELF application root logger and appender. This can be used to segregate
+ Policy engine events from other components, or it can be eliminated to record
these events as part of the application root log. -->
-
+
<appender name="EELFAudit"
class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>${logDirectory}/${auditLogName}.log</file>
<rollingPolicy
class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
<fileNamePattern>${logDirectory}/${auditLogName}.%d{yyyy-MM-dd}.%i.log.zip</fileNamePattern>
-
- <!-- keep 30 days' worth of history capped at 3GB total size -->
+
+ <!-- keep 30 days' worth of history capped at 3GB total size -->
<maxFileSize>50MB</maxFileSize>
<maxHistory>30</maxHistory>
<totalSizeCap>10GB</totalSizeCap>
</rollingPolicy>
-
+
<encoder>
<pattern>${defaultAuditPattern}</pattern>
</encoder>
@@ -141,18 +141,18 @@
<rollingPolicy
class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
<fileNamePattern>${logDirectory}/${metricsLogName}.%d{yyyy-MM-dd}.%i.log.zip</fileNamePattern>
-
- <!-- keep 30 days' worth of history capped at 3GB total size -->
+
+ <!-- keep 30 days' worth of history capped at 3GB total size -->
<maxFileSize>50MB</maxFileSize>
<maxHistory>30</maxHistory>
<totalSizeCap>10GB</totalSizeCap>
</rollingPolicy>
-
+
<encoder>
<pattern>${defaultMetricPattern}</pattern>
</encoder>
</appender>
-
+
<appender name="asyncEELFMetrics" class="ch.qos.logback.classic.AsyncAppender">
<queueSize>256</queueSize>
<appender-ref ref="EELFMetrics"/>
@@ -160,15 +160,15 @@
-
+
<appender name="EELFError"
class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>${logDirectory}/${errorLogName}.log</file>
<rollingPolicy
class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
<fileNamePattern>${logDirectory}/${errorLogName}.%d{yyyy-MM-dd}.%i.log.zip</fileNamePattern>
-
- <!-- keep 30 days' worth of history capped at 3GB total size -->
+
+ <!-- keep 30 days' worth of history capped at 3GB total size -->
<maxFileSize>50MB</maxFileSize>
<maxHistory>30</maxHistory>
<totalSizeCap>10GB</totalSizeCap>
@@ -176,27 +176,27 @@
<filter class="ch.qos.logback.classic.filter.ThresholdFilter">
<level>ERROR</level>
</filter>
-
+
<encoder>
<pattern>${defaultErrorPattern}</pattern>
</encoder>
</appender>
-
+
<appender name="asyncEELFError" class="ch.qos.logback.classic.AsyncAppender">
<queueSize>256</queueSize>
<appender-ref ref="EELFError"/>
</appender>
-
+
<appender name="EELFDebug"
class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>${debugLogDirectory}/${debugLogName}.log</file>
<rollingPolicy
class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
<fileNamePattern>${debugLogDirectory}/${debugLogName}.%d{yyyy-MM-dd}.%i.log.zip</fileNamePattern>
-
- <!-- keep 30 days' worth of history capped at 3GB total size -->
+
+ <!-- keep 30 days' worth of history capped at 3GB total size -->
<maxFileSize>50MB</maxFileSize>
<maxHistory>30</maxHistory>
<totalSizeCap>10GB</totalSizeCap>
@@ -204,44 +204,44 @@
<filter class="ch.qos.logback.classic.filter.ThresholdFilter">
<level>DEBUG</level>
</filter>
-
+
<encoder>
<pattern>${debugLoggerPattern}</pattern>
</encoder>
</appender>
-
+
<appender name="asyncEELFDebug" class="ch.qos.logback.classic.AsyncAppender">
<queueSize>256</queueSize>
<appender-ref ref="EELFDebug" />
<includeCallerData>true</includeCallerData>
</appender>
-
-
+
+
<!-- ============================================================================ -->
<!-- EELF loggers -->
<!-- ============================================================================ -->
-
+
<logger name="com.att.eelf.audit" level="info" additivity="false">
<appender-ref ref="asyncEELFAudit" />
</logger>
-
+
<logger name="com.att.eelf.metrics" level="info" additivity="false">
<appender-ref ref="asyncEELFMetrics" />
</logger>
-
+
<logger name="com.att.eelf.error" level="error" additivity="false">
<appender-ref ref="asyncEELFError" />
</logger>
-
+
<logger name="com.att.eelf.debug" level="info" additivity="false">
<appender-ref ref="asyncEELFDebug" />
</logger>
-
-
-
+
+
+
<root level="INFO">
<appender-ref ref="asyncEELFDebug" />
<appender-ref ref="asyncEELFError" />
</root>
-</configuration> \ No newline at end of file
+</configuration>
diff --git a/BRMSGateway/src/test/java/org/onap/policy/brms/BrmsPushTest.java b/BRMSGateway/src/test/java/org/onap/policy/brms/BrmsPushTest.java
index de1a7d6eb..994e97368 100644
--- a/BRMSGateway/src/test/java/org/onap/policy/brms/BrmsPushTest.java
+++ b/BRMSGateway/src/test/java/org/onap/policy/brms/BrmsPushTest.java
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP Policy Engine
* ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017, 2020 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -81,7 +81,7 @@ public class BrmsPushTest {
}
@Test(expected = PolicyException.class)
- public void brmsHandlerFailTest2() throws PolicyException {
+ public void testBrmsHandlerFail2() throws PolicyException {
final PropertyChange prop = new PropertyChange();
prop.key = "defaultName";
prop.remove = true;
@@ -92,7 +92,7 @@ public class BrmsPushTest {
}
@Test(expected = PolicyException.class)
- public void brmsHandlerFailTest3() throws PolicyException {
+ public void testBrmsHandlerFail3() throws PolicyException {
PropertyChange prop = new PropertyChange();
prop.key = "repositoryID";
prop.remove = true;
@@ -107,7 +107,7 @@ public class BrmsPushTest {
}
@Test(expected = PolicyException.class)
- public void brmsHandlerFailTest4() throws PolicyException {
+ public void testBrmsHandlerFail4() throws PolicyException {
final PropertyChange prop = new PropertyChange();
prop.key = "repositoryURL";
prop.remove = true;
@@ -118,7 +118,7 @@ public class BrmsPushTest {
}
@Test(expected = PolicyException.class)
- public void brmsHandlerFailTest5() throws PolicyException {
+ public void testBrmsHandlerFail5() throws PolicyException {
final PropertyChange prop = new PropertyChange();
prop.key = "repositoryName";
prop.remove = true;
@@ -129,7 +129,7 @@ public class BrmsPushTest {
}
@Test(expected = PolicyException.class)
- public void brmsHandlerFailTest6() throws PolicyException {
+ public void testBrmsHandlerFail6() throws PolicyException {
PropertyChange prop = new PropertyChange();
prop.key = "repositoryURL";
prop.value = "http://nexus:8081/nexus/content/repositories/releases,"
@@ -146,7 +146,7 @@ public class BrmsPushTest {
}
@Test(expected = PolicyException.class)
- public void brmsHandlerFailTest7() throws PolicyException {
+ public void testBrmsHandlerFail7() throws PolicyException {
final PropertyChange prop = new PropertyChange();
prop.key = "repositoryPassword";
prop.remove = true;
@@ -157,7 +157,7 @@ public class BrmsPushTest {
}
@Test(expected = PolicyException.class)
- public void brmsHandlerFailTest8() throws PolicyException {
+ public void testBrmsHandlerFail8() throws PolicyException {
final PropertyChange prop = new PropertyChange();
prop.key = "policyKeyID";
prop.remove = true;
@@ -168,7 +168,7 @@ public class BrmsPushTest {
}
@Test(expected = PolicyException.class)
- public void brmsHandlerFailTest9() throws PolicyException {
+ public void testBrmsHandlerFail9() throws PolicyException {
PropertyChange prop = new PropertyChange();
prop.key = "sync";
prop.value = "true";
@@ -188,7 +188,7 @@ public class BrmsPushTest {
}
@Test(expected = PolicyException.class)
- public void brmsHandlerFailTest10() throws PolicyException {
+ public void testBrmsHandlerFail10() throws PolicyException {
final PropertyChange prop = new PropertyChange();
prop.key = "groupNames";
prop.value = "";
@@ -200,7 +200,7 @@ public class BrmsPushTest {
}
@Test(expected = PolicyException.class)
- public void brmsHandlerFailTest11() throws PolicyException {
+ public void testBrmsHandlerFail11() throws PolicyException {
final PropertyChange prop = new PropertyChange();
prop.key = "default.groupID";
prop.remove = true;
@@ -211,7 +211,7 @@ public class BrmsPushTest {
}
@Test(expected = PolicyException.class)
- public void brmsHandlerFailTest12() throws PolicyException {
+ public void testBrmsHandlerFail12() throws PolicyException {
final PropertyChange prop = new PropertyChange();
prop.key = "default.artifactID";
prop.remove = true;
@@ -222,7 +222,7 @@ public class BrmsPushTest {
}
@Test(expected = PolicyException.class)
- public void brmsHandlerFailTest13() throws PolicyException {
+ public void testBrmsHandlerFail13() throws PolicyException {
PropertyChange prop = new PropertyChange();
prop.key = "NOTIFICATION_TYPE";
prop.value = "dmaap";
diff --git a/BRMSGateway/src/test/java/org/onap/policy/brms/api/BrmsGatewayTest.java b/BRMSGateway/src/test/java/org/onap/policy/brms/api/BrmsGatewayTest.java
index fd8a7ed3b..f5a4fff8a 100644
--- a/BRMSGateway/src/test/java/org/onap/policy/brms/api/BrmsGatewayTest.java
+++ b/BRMSGateway/src/test/java/org/onap/policy/brms/api/BrmsGatewayTest.java
@@ -2,14 +2,14 @@
* ============LICENSE_START=======================================================
* ONAP Policy Engine
* ================================================================================
- * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2018-2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -20,37 +20,88 @@
package org.onap.policy.brms.api;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.fail;
-import static org.mockito.Matchers.any;
+import org.junit.After;
+import org.junit.AfterClass;
+import org.junit.Before;
+import org.junit.BeforeClass;
import org.junit.Test;
-import org.junit.runner.RunWith;
import org.mockito.Mockito;
-import org.powermock.api.mockito.PowerMockito;
-import org.powermock.core.classloader.annotations.PrepareForTest;
-import org.powermock.modules.junit4.PowerMockRunner;
+import org.onap.policy.api.PolicyException;
+import org.onap.policy.brms.api.BrmsGateway.Factory;
+import org.powermock.reflect.Whitebox;
-@RunWith(PowerMockRunner.class)
public class BrmsGatewayTest {
+ private static final String FACTORY_FIELD = "factory";
+
+ private static Factory saveFactory;
+
+ private Thread thread;
+
+ @BeforeClass
+ public static void setUpBeforeClass() {
+ saveFactory = Whitebox.getInternalState(BrmsGateway.class, FACTORY_FIELD);
+ }
+
+ @AfterClass
+ public static void tearDownAfterClass() {
+ Whitebox.setInternalState(BrmsGateway.class, FACTORY_FIELD, saveFactory);
+ }
+
+ /**
+ * Installs a factory.
+ */
+ @Before
+ public void setUp() {
+ thread = null;
+
+ Factory factory = new Factory() {
+ @Override
+ public BrmsHandler makeBrmsHandler(String configFile) throws PolicyException {
+ // Mock handler
+ return Mockito.mock(BrmsHandler.class);
+ }
+
+ @Override
+ public Thread makeThread(Runnable runnable) {
+ thread = super.makeThread(runnable);
+ return thread;
+ }
+
+ };
+
+ Whitebox.setInternalState(BrmsGateway.class, FACTORY_FIELD, factory);
+ }
+
+ /**
+ * Interrupts the thread, if there is one.
+ */
+ @After
+ public void tearDown() throws InterruptedException {
+ if (thread != null) {
+ thread.interrupt();
+ thread.join(5000L);
+ assertFalse(thread.isAlive());
+ }
+ }
+
+ @Test
+ public void testFactory() throws InterruptedException {
+ assertNotNull(saveFactory);
+ assertNotNull(saveFactory.makeThread(() -> { }));
+ }
+
@Test
public void testGet() {
assertNull(BrmsGateway.getPolicyEngine());
}
- @PrepareForTest({Thread.class, BrmsGateway.class})
@Test
public void testMain() throws Exception {
- // Mock Thread
- PowerMockito.spy(Thread.class);
- PowerMockito.doNothing().when(Thread.class);
- Thread.sleep(1000);
-
- // Mock handler
- final BrmsHandler handler = Mockito.mock(BrmsHandler.class);
- PowerMockito.whenNew(BrmsHandler.class).withArguments(any()).thenReturn(handler);
-
- // Run app
try {
final String[] args = new String[0];
BrmsGateway.main(args);
diff --git a/BRMSGateway/src/test/java/org/onap/policy/brms/api/BrmsHandlerTest.java b/BRMSGateway/src/test/java/org/onap/policy/brms/api/BrmsHandlerTest.java
index 1a6dc4719..079db2109 100644
--- a/BRMSGateway/src/test/java/org/onap/policy/brms/api/BrmsHandlerTest.java
+++ b/BRMSGateway/src/test/java/org/onap/policy/brms/api/BrmsHandlerTest.java
@@ -2,14 +2,14 @@
* ============LICENSE_START=======================================================
* ONAP Policy Engine
* ================================================================================
- * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2018, 2020 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -23,13 +23,12 @@ package org.onap.policy.brms.api;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.fail;
-import static org.mockito.Matchers.any;
+import static org.mockito.ArgumentMatchers.any;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;
-import javax.persistence.Query;
import javax.persistence.TypedQuery;
import org.junit.Test;
@@ -39,14 +38,16 @@ import org.onap.policy.api.NotificationType;
import org.onap.policy.std.StdPDPNotification;
import org.onap.policy.utils.BackUpMonitor;
import org.powermock.api.mockito.PowerMockito;
+import org.powermock.core.classloader.annotations.PowerMockIgnore;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
@RunWith(PowerMockRunner.class)
+@PowerMockIgnore({"com.sun.org.apache.xerces.*", "jdk.internal.reflect.*", "javax.xml.*", "org.xml.*", "org.w3c.*"})
+@PrepareForTest({Persistence.class, BackUpMonitor.class})
public class BrmsHandlerTest {
- @PrepareForTest({Persistence.class, BackUpMonitor.class})
@Test
- public void negativeTestNotifications() throws Exception {
+ public void testNegativeTestNotifications() throws Exception {
// Mock emf, persistence, and query
final EntityManagerFactory emf = Mockito.mock(EntityManagerFactory.class);
final EntityManager em = Mockito.mock(EntityManager.class);
diff --git a/BRMSGateway/src/test/java/org/onap/policy/brms/api/BrmsPushTest.java b/BRMSGateway/src/test/java/org/onap/policy/brms/api/BrmsPushTest.java
index 2c76a2eff..3adc55700 100644
--- a/BRMSGateway/src/test/java/org/onap/policy/brms/api/BrmsPushTest.java
+++ b/BRMSGateway/src/test/java/org/onap/policy/brms/api/BrmsPushTest.java
@@ -2,14 +2,14 @@
* ============LICENSE_START=======================================================
* ONAP Policy Engine
* ================================================================================
- * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2018-2020 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -23,7 +23,7 @@ package org.onap.policy.brms.api;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.fail;
-import static org.mockito.Matchers.any;
+import static org.mockito.ArgumentMatchers.any;
import java.util.HashMap;
import java.util.List;
@@ -46,15 +46,17 @@ import org.onap.policy.utils.BackUpHandler;
import org.onap.policy.utils.BackUpMonitor;
import org.onap.policy.utils.BackUpMonitorException;
import org.powermock.api.mockito.PowerMockito;
+import org.powermock.core.classloader.annotations.PowerMockIgnore;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
@RunWith(PowerMockRunner.class)
+@PowerMockIgnore({"com.sun.org.apache.xerces.*", "jdk.internal.reflect.*", "javax.xml.*", "org.xml.*", "org.w3c.*"})
+@PrepareForTest({Persistence.class, BackUpMonitor.class})
public class BrmsPushTest {
@Rule
public ExpectedException thrown = ExpectedException.none();
- @PrepareForTest({Persistence.class, BackUpMonitor.class})
@Test
public void testPush() throws BackUpMonitorException, PolicyException {
// Mock emf, persistence, and query
@@ -108,7 +110,7 @@ public class BrmsPushTest {
// Test misc methods
final String controllerName = "testController";
final List<Dependency> deps = push.defaultDependencies(controllerName);
- assertEquals(deps.size(), 7);
+ assertEquals(deps.size(), 6);
assertNotNull(BrmsPush.getBackUpMonitor());
assertEquals(push.urlListSize(), 1);
diff --git a/BRMSGateway/src/test/resources/config.properties b/BRMSGateway/src/test/resources/config.properties
index 48d9bc5a5..ce937dff0 100644
--- a/BRMSGateway/src/test/resources/config.properties
+++ b/BRMSGateway/src/test/resources/config.properties
@@ -81,6 +81,6 @@ ping_interval=30000
#
#
#
-brms.dependency.version=1.4.1-SNAPSHOT
+brms.dependency.version=1.6.3-SNAPSHOT
ENVIRONMENT = DEVL
diff --git a/LogParser/pom.xml b/LogParser/pom.xml
index 075372357..6430982c1 100644
--- a/LogParser/pom.xml
+++ b/LogParser/pom.xml
@@ -3,7 +3,7 @@
============LICENSE_START=======================================================
ONAP Policy Engine
================================================================================
- Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ Copyright (C) 2017-2018, 2020 AT&T Intellectual Property. All rights reserved.
================================================================================
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
@@ -24,7 +24,7 @@
<parent>
<groupId>org.onap.policy.engine</groupId>
<artifactId>PolicyEngineSuite</artifactId>
- <version>1.4.1-SNAPSHOT</version>
+ <version>1.6.4-SNAPSHOT</version>
</parent>
<artifactId>LogParser</artifactId>
<dependencies>
@@ -135,7 +135,7 @@
<configLocation>onap-checkstyle/onap-java-style.xml</configLocation>
<!-- <sourceDirectory> is needed so that checkstyle ignores the generated
sources directory -->
- <sourceDirectory>${project.build.sourceDirectory}</sourceDirectory>
+ <sourceDirectories>${project.build.sourceDirectory}</sourceDirectories>
<includeResources>true</includeResources>
<includeTestSourceDirectory>true</includeTestSourceDirectory>
<includeTestResources>true</includeTestResources>
diff --git a/LogParser/src/main/java/org/onap/xacml/parser/ParseLog.java b/LogParser/src/main/java/org/onap/xacml/parser/ParseLog.java
index f12522af6..77aafdf7a 100644
--- a/LogParser/src/main/java/org/onap/xacml/parser/ParseLog.java
+++ b/LogParser/src/main/java/org/onap/xacml/parser/ParseLog.java
@@ -884,11 +884,11 @@ public class ParseLog {
setLogFileProperties(splitString);
jdbcUrl = config.getProperty("JDBC_URL").replace("'", "");
- jdbcUser = config.getProperty("JDBC_USER");
+ jdbcUser = getValue(config.getProperty("JDBC_USER"));
jdbcDriver = config.getProperty("JDBC_DRIVER");
PeCryptoUtils.initAesKey(config.getProperty(PROP_AES_KEY));
- jdbcPassword = PeCryptoUtils.decrypt(config.getProperty("JDBC_PASSWORD"));
+ jdbcPassword = PeCryptoUtils.decrypt(getValue(config.getProperty("JDBC_PASSWORD")));
config.setProperty("javax.persistence.jdbc.password", jdbcPassword);
return config;
@@ -902,6 +902,13 @@ public class ParseLog {
return null;
}
+ private static String getValue(final String value) {
+ if (value != null && value.matches("[$][{].*[}]$")) {
+ return System.getenv(value.substring(2, value.length() - 1));
+ }
+ return value;
+ }
+
public static Connection getDbConnection() {
return dbConnection(jdbcDriver, jdbcUrl, jdbcUser, jdbcPassword);
}
diff --git a/LogParser/src/test/java/org/onap/xacml/parser/ParseLogTest.java b/LogParser/src/test/java/org/onap/xacml/parser/ParseLogTest.java
index 313750eeb..6609778a0 100644
--- a/LogParser/src/test/java/org/onap/xacml/parser/ParseLogTest.java
+++ b/LogParser/src/test/java/org/onap/xacml/parser/ParseLogTest.java
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* LogParser
* ================================================================================
- * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2018, 2020 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -47,11 +47,13 @@ import org.onap.policy.common.logging.flexlogger.FlexLogger;
import org.onap.policy.common.logging.flexlogger.Logger;
import org.onap.xacml.parser.LogEntryObject.LogType;
import org.powermock.api.mockito.PowerMockito;
+import org.powermock.core.classloader.annotations.PowerMockIgnore;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
-@PrepareForTest({ ParseLogTest.class, IntegrityMonitor.class })
@RunWith(PowerMockRunner.class)
+@PowerMockIgnore({"com.sun.org.apache.xerces.*", "jdk.internal.reflect.*", "javax.xml.*", "org.xml.*"})
+@PrepareForTest({ ParseLogTest.class, IntegrityMonitor.class })
public class ParseLogTest {
private static Logger logger = FlexLogger.getLogger(ParseLogTest.class);
diff --git a/ONAP-PAP-REST/pom.xml b/ONAP-PAP-REST/pom.xml
index 8cca55579..3a7d1b9e9 100644
--- a/ONAP-PAP-REST/pom.xml
+++ b/ONAP-PAP-REST/pom.xml
@@ -3,7 +3,7 @@
============LICENSE_START=======================================================
ONAP Policy Engine
================================================================================
- Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
+ Copyright (C) 2017-2020 AT&T Intellectual Property. All rights reserved.
Modifications Copyright (C) 2019 Nordix Foundation.
================================================================================
Licensed under the Apache License, Version 2.0 (the "License");
@@ -28,8 +28,11 @@
<parent>
<groupId>org.onap.policy.engine</groupId>
<artifactId>PolicyEngineSuite</artifactId>
- <version>1.4.1-SNAPSHOT</version>
+ <version>1.6.4-SNAPSHOT</version>
</parent>
+ <properties>
+ <hibernate.version>4.3.10.Final</hibernate.version>
+ </properties>
<build>
<plugins>
<plugin>
@@ -51,8 +54,7 @@
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
- <source>1.8</source>
- <target>1.8</target>
+ <release>${java.version}</release>
</configuration>
</plugin>
</plugins>
@@ -100,6 +102,10 @@
<groupId>org.json</groupId>
<artifactId>json</artifactId>
</exclusion>
+ <exclusion>
+ <groupId>xml-apis</groupId>
+ <artifactId>xml-apis</artifactId>
+ </exclusion>
</exclusions>
</dependency>
<dependency>
@@ -112,6 +118,21 @@
<artifactId>javax.servlet-api</artifactId>
</dependency>
<dependency>
+ <groupId>javax.xml.bind</groupId>
+ <artifactId>jaxb-api</artifactId>
+ <version>${version.javax.bind}</version>
+ </dependency>
+ <dependency>
+ <groupId>org.glassfish.jaxb</groupId>
+ <artifactId>jaxb-runtime</artifactId>
+ <version>2.3.2</version>
+ </dependency>
+ <dependency>
+ <groupId>javax.activation</groupId>
+ <artifactId>javax.activation-api</artifactId>
+ <version>1.2.0</version>
+ </dependency>
+ <dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.1.3</version>
@@ -223,6 +244,12 @@
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>${hibernate.version}</version>
+ <exclusions>
+ <exclusion>
+ <groupId>xml-apis</groupId>
+ <artifactId>xml-apis</artifactId>
+ </exclusion>
+ </exclusions>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
@@ -288,8 +315,4 @@
<version>8.5.9</version>
</dependency>
</dependencies>
- <properties>
- <hibernate.version>4.3.10.Final</hibernate.version>
- <projectversion>2.0.2</projectversion>
- </properties>
</project>
diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/ConsoleAndApiService.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/ConsoleAndApiService.java
index 52e4060b5..16340e5fe 100644
--- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/ConsoleAndApiService.java
+++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/ConsoleAndApiService.java
@@ -3,6 +3,7 @@
* ONAP-PAP-REST
* ================================================================================
* Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2019 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -22,6 +23,7 @@ package org.onap.policy.pap.xacml.rest;
import com.att.research.xacml.api.pap.PAPException;
import com.fasterxml.jackson.databind.ObjectMapper;
+
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
@@ -32,16 +34,18 @@ import java.util.HashSet;
import java.util.List;
import java.util.Scanner;
import java.util.Set;
+
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
-import org.onap.policy.common.logging.ONAPLoggingContext;
+
+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.common.logging.flexlogger.FlexLogger;
import org.onap.policy.common.logging.flexlogger.Logger;
-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.components.PolicyDbDao;
+import org.onap.policy.pap.xacml.rest.components.PolicyDbDaoTransaction;
import org.onap.policy.pap.xacml.rest.handler.PushPolicyHandler;
import org.onap.policy.xacml.api.XACMLErrorConstants;
import org.onap.policy.xacml.api.pap.OnapPDP;
@@ -53,6 +57,15 @@ import org.onap.policy.xacml.std.pap.StdPDPPolicy;
public class ConsoleAndApiService {
+ private static final String SPACE_UNIMPLEMENTED = " UNIMPLEMENTED";
+ private static final String XACMLPAPSERVLET_DO_AC_PUT_COMMIT_TRANS = "XACMLPapServlet doACPut commitTransaction";
+ private static final String UNIMPLEMENTED = "UNIMPLEMENTED";
+ private static final String APPLICATION_JSON = "application/json";
+ private static final String CONTENT_TYPE = "content-type";
+ private static final String TO_GROUP = ",to group=";
+ private static final String PDP_ID = "pdpId";
+ private static final String XACML_PAP_SERVLET_DO_AC_PUT = "XACMLPapServlet.doACPut";
+ private static final String UNKNOWN_GROUP_ID = "Unknown groupId '";
private static final Logger LOGGER = FlexLogger.getLogger(ConsoleAndApiService.class);
private static final Logger auditLogger = FlexLogger.getLogger("auditLogger");
private static final String ADD_GROUP_ERROR = "addGroupError";
@@ -79,8 +92,8 @@ public class ConsoleAndApiService {
* @throws IOException Signals that an I/O exception has occurred.
*/
public void doAcPost(HttpServletRequest request, HttpServletResponse response, String groupId,
- ONAPLoggingContext loggingContext, PAPPolicyEngine papEngine) throws IOException {
- PolicyDBDaoTransaction doAcPostTransaction = null;
+ OnapLoggingContext loggingContext, PAPPolicyEngine papEngine) throws IOException {
+ PolicyDbDaoTransaction doAcPostTransaction = null;
try {
String groupName = request.getParameter("groupName");
String groupDescription = request.getParameter("groupDescription");
@@ -98,9 +111,9 @@ public class ConsoleAndApiService {
} catch (UnsupportedEncodingException e) {
LOGGER.error(e);
}
- PolicyDBDaoTransaction newGroupTransaction = XACMLPapServlet.getPolicyDbDao().getNewTransaction();
+ PolicyDbDaoTransaction newGroupTransaction = XACMLPapServlet.getPolicyDbDao().getNewTransaction();
try {
- newGroupTransaction.createGroup(PolicyDBDao.createNewPDPGroupId(unescapedName), unescapedName,
+ newGroupTransaction.createGroup(PolicyDbDao.createNewPdpGroupId(unescapedName), unescapedName,
unescapedDescription, PAPSERVLETDOACPOST);
papEngine.newGroup(unescapedName, unescapedDescription);
loggingContext.metricStarted();
@@ -134,7 +147,7 @@ public class ConsoleAndApiService {
LOGGER.error(e);
}
if (group == null) {
- String message = "Unknown groupId '" + groupId + "'";
+ String message = UNKNOWN_GROUP_ID + groupId + "'";
// for fixing Header Manipulation of Fortify issue
if (!message.matches(REGEX)) {
response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
@@ -168,7 +181,7 @@ public class ConsoleAndApiService {
StdPDPGroup updatedGroup = null;
StdPDPPolicy policyForSafetyCheck = new StdPDPPolicy();
for (String policyId : policyIdList) {
- PolicyDBDaoTransaction addPolicyToGroupTransaction =
+ PolicyDbDaoTransaction addPolicyToGroupTransaction =
XACMLPapServlet.getPolicyDbDao().getNewTransaction();
try {
// Copying the policy to the file system and updating groups
@@ -224,13 +237,13 @@ public class ConsoleAndApiService {
*/
// Get new transaction to perform updateGroup()
- PolicyDBDaoTransaction acPutTransaction = XACMLPapServlet.getPolicyDbDao().getNewTransaction();
+ PolicyDbDaoTransaction acPutTransaction = XACMLPapServlet.getPolicyDbDao().getNewTransaction();
try {
// Assume that this is an update of an existing PDP
// Group
loggingContext.setServiceName("PolicyEngineAPI:PAP.updateGroup");
try {
- acPutTransaction.updateGroup(updatedGroup, "XACMLPapServlet.doACPut", userId);
+ acPutTransaction.updateGroup(updatedGroup, XACML_PAP_SERVLET_DO_AC_PUT, userId);
} catch (Exception e) {
PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, XACMLPAPSERVLET,
" Error occurred when notifying PAPs of a group change: " + e);
@@ -276,8 +289,6 @@ public class ConsoleAndApiService {
loggingContext.transactionEnded();
auditLogger.info(SUCCESS);
LOGGER.info(TRANSENDED);
-
- return;
} else if (request.getParameter("default") != null) {
// Args: group=<groupId> default=true <= make default
// change the current default group to be the one identified in
@@ -289,7 +300,7 @@ public class ConsoleAndApiService {
// It should never be the case that multiple groups are
// currently marked as the default, but protect against that
// anyway.
- PolicyDBDaoTransaction setDefaultGroupTransaction =
+ PolicyDbDaoTransaction setDefaultGroupTransaction =
XACMLPapServlet.getPolicyDbDao().getNewTransaction();
try {
setDefaultGroupTransaction.changeDefaultGroup(group, PAPSERVLETDOACPOST);
@@ -313,20 +324,19 @@ public class ConsoleAndApiService {
}
auditLogger.info(SUCCESS);
LOGGER.info(TRANSENDED);
- return;
- } else if (request.getParameter("pdpId") != null) {
+ } else if (request.getParameter(PDP_ID) != null) {
doAcPostTransaction = XACMLPapServlet.getPolicyDbDao().getNewTransaction();
// Args: group=<groupId> pdpId=<pdpId> <= move PDP to group
loggingContext.setServiceName("AC:PAP.movePDP");
- String pdpId = request.getParameter("pdpId");
+ String pdpId = request.getParameter(PDP_ID);
OnapPDP pdp = papEngine.getPDP(pdpId);
- OnapPDPGroup originalGroup = papEngine.getPDPGroup(pdp);
+ final OnapPDPGroup originalGroup = papEngine.getPDPGroup(pdp);
try {
doAcPostTransaction.movePdp(pdp, group, PAPSERVLETDOACPOST);
} 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="
+ " Error while moving pdp in the database: " + "pdp=" + pdp.getId() + TO_GROUP
+ group.getId());
throw new PAPException(e.getMessage());
}
@@ -348,14 +358,12 @@ public class ConsoleAndApiService {
loggingContext.transactionEnded();
auditLogger.info(SUCCESS);
PolicyLogger.audit(TRANSENDED);
- return;
}
} catch (PAPException e) {
PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, XACMLPAPSERVLET, " AC POST exception");
loggingContext.transactionEnded();
PolicyLogger.audit(TRANSACTIONFAILED);
setResponseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
- return;
}
}
@@ -370,10 +378,10 @@ public class ConsoleAndApiService {
* @throws IOException Signals that an I/O exception has occurred.
*/
public void doAcGet(HttpServletRequest request, HttpServletResponse response, String groupId,
- ONAPLoggingContext loggingContext, PAPPolicyEngine papEngine) throws IOException {
+ OnapLoggingContext loggingContext, PAPPolicyEngine papEngine) throws IOException {
try {
String parameterDefault = request.getParameter("default");
- String pdpId = request.getParameter("pdpId");
+ String pdpId = request.getParameter(PDP_ID);
String pdpGroup = request.getParameter("getPDPGroup");
if ("".equals(groupId)) {
// request IS from AC but does not identify a group by name
@@ -388,7 +396,7 @@ public class ConsoleAndApiService {
LOGGER.debug("GET Default group req from '" + request.getRequestURL() + "'");
}
response.setStatus(HttpServletResponse.SC_OK);
- response.setHeader("content-type", "application/json");
+ response.setHeader(CONTENT_TYPE, APPLICATION_JSON);
try {
response.getOutputStream().close();
} catch (IOException e) {
@@ -417,7 +425,7 @@ public class ConsoleAndApiService {
LOGGER.debug("GET pdp '" + pdpId + "' req from '" + request.getRequestURL() + "'");
}
response.setStatus(HttpServletResponse.SC_OK);
- response.setHeader("content-type", "application/json");
+ response.setHeader(CONTENT_TYPE, APPLICATION_JSON);
try {
response.getOutputStream().close();
} catch (IOException e) {
@@ -444,7 +452,7 @@ public class ConsoleAndApiService {
LOGGER.debug("GET PDP '" + pdpId + "' Group req from '" + request.getRequestURL() + "'");
}
response.setStatus(HttpServletResponse.SC_OK);
- response.setHeader("content-type", "application/json");
+ response.setHeader(CONTENT_TYPE, APPLICATION_JSON);
try {
response.getOutputStream().close();
} catch (IOException e) {
@@ -475,7 +483,7 @@ public class ConsoleAndApiService {
LOGGER.debug("GET All groups req");
}
response.setStatus(HttpServletResponse.SC_OK);
- response.setHeader("content-type", "application/json");
+ response.setHeader(CONTENT_TYPE, APPLICATION_JSON);
try {
response.getOutputStream().close();
} catch (IOException e) {
@@ -496,7 +504,7 @@ public class ConsoleAndApiService {
LOGGER.error(e);
}
if (group == null) {
- String message = "Unknown groupId '" + groupId + "'";
+ String message = UNKNOWN_GROUP_ID + groupId + "'";
// for fixing Header Manipulation of Fortify issue
if (!message.matches(REGEX)) {
response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
@@ -529,7 +537,7 @@ public class ConsoleAndApiService {
LOGGER.debug("GET group '" + group.getId() + "' req from '" + request.getRequestURL() + "'");
}
response.setStatus(HttpServletResponse.SC_OK);
- response.setHeader("content-type", "application/json");
+ response.setHeader(CONTENT_TYPE, APPLICATION_JSON);
try {
response.getOutputStream().close();
} catch (IOException e) {
@@ -551,13 +559,12 @@ public class ConsoleAndApiService {
PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " UNIMPLEMENTED ");
loggingContext.transactionEnded();
PolicyLogger.audit(TRANSACTIONFAILED);
- setResponseError(response, HttpServletResponse.SC_BAD_REQUEST, "UNIMPLEMENTED");
+ setResponseError(response, HttpServletResponse.SC_BAD_REQUEST, UNIMPLEMENTED);
} catch (PAPException e) {
PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, XACMLPAPSERVLET, " AC Get exception");
loggingContext.transactionEnded();
PolicyLogger.audit(TRANSACTIONFAILED);
setResponseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
- return;
}
}
@@ -572,8 +579,8 @@ public class ConsoleAndApiService {
* @throws IOException Signals that an I/O exception has occurred.
*/
public void doAcPut(HttpServletRequest request, HttpServletResponse response, String groupId,
- ONAPLoggingContext loggingContext, PAPPolicyEngine papEngine) throws IOException {
- PolicyDBDaoTransaction acPutTransaction = XACMLPapServlet.getPolicyDbDao().getNewTransaction();
+ OnapLoggingContext loggingContext, PAPPolicyEngine papEngine) throws IOException {
+ PolicyDbDaoTransaction acPutTransaction = XACMLPapServlet.getPolicyDbDao().getNewTransaction();
try {
String userId = request.getParameter("userId");
// for PUT operations the group may or may not need to exist before
@@ -584,7 +591,7 @@ public class ConsoleAndApiService {
// for remaining operations the group must exist before the
// operation can be done
if (group == null) {
- String message = "Unknown groupId '" + groupId + "'";
+ String message = UNKNOWN_GROUP_ID + groupId + "'";
PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " " + message);
loggingContext.transactionEnded();
PolicyLogger.audit(TRANSACTIONFAILED);
@@ -605,11 +612,10 @@ public class ConsoleAndApiService {
auditLogger.info(SUCCESS);
PolicyLogger.audit(TRANSENDED);
acPutTransaction.rollbackTransaction();
- return;
- } else if (request.getParameter("pdpId") != null) {
+ } else if (request.getParameter(PDP_ID) != null) {
// ARGS: group=<groupId> pdpId=<pdpId/URL> <= create a new PDP
// or Update an Existing one
- String pdpId = request.getParameter("pdpId");
+ String pdpId = request.getParameter(PDP_ID);
if (papEngine.getPDP(pdpId) == null) {
loggingContext.setServiceName("AC:PAP.createPDP");
} else {
@@ -658,18 +664,18 @@ public class ConsoleAndApiService {
// 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");
+ pdp.getDescription(), pdp.getJmxPort(), XACML_PAP_SERVLET_DO_AC_PUT);
papEngine.newPDP(pdp.getId(), group, pdp.getName(), pdp.getDescription(), pdp.getJmxPort());
} 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());
+ + TO_GROUP + group.getId());
throw new PAPException(e.getMessage());
}
} else {
// this is a request to update the pdp
try {
- acPutTransaction.updatePdp(pdp, "XACMLPapServlet.doACPut");
+ acPutTransaction.updatePdp(pdp, XACML_PAP_SERVLET_DO_AC_PUT);
papEngine.updatePDP(pdp);
} catch (Exception e) {
PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, XACMLPAPSERVLET,
@@ -688,15 +694,14 @@ public class ConsoleAndApiService {
loggingContext.metricStarted();
acPutTransaction.commitTransaction();
loggingContext.metricEnded();
- PolicyLogger.metrics("XACMLPapServlet doACPut commitTransaction");
+ PolicyLogger.metrics(XACMLPAPSERVLET_DO_AC_PUT_COMMIT_TRANS);
loggingContext.transactionEnded();
auditLogger.info(SUCCESS);
PolicyLogger.audit(TRANSENDED);
- return;
} else {
try {
PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, XACMLPAPSERVLET,
- " Error while adding pdp to group in the database: " + "pdp=null" + ",to group="
+ " Error while adding pdp to group in the database: " + "pdp=null" + TO_GROUP
+ group.getId());
throw new PAPException("PDP is null");
} catch (Exception e) {
@@ -708,12 +713,11 @@ public class ConsoleAndApiService {
// <= 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");
+ PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + UNIMPLEMENTED);
loggingContext.transactionEnded();
PolicyLogger.audit(TRANSACTIONFAILED);
- setResponseError(response, HttpServletResponse.SC_BAD_REQUEST, "UNIMPLEMENTED");
+ setResponseError(response, HttpServletResponse.SC_BAD_REQUEST, UNIMPLEMENTED);
acPutTransaction.rollbackTransaction();
- return;
} else {
// Assume that this is an update of an existing PDP Group
// ARGS: group=<groupId> <= Update an Existing Group
@@ -739,7 +743,7 @@ public class ConsoleAndApiService {
} catch (Exception e) {
LOGGER.error(e);
}
- if (objectFromJson == null || !(objectFromJson instanceof StdPDPGroup)
+ if (!(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);
@@ -760,7 +764,7 @@ public class ConsoleAndApiService {
if ("delete".equals(((StdPDPGroup) objectFromJson).getOperation())) {
acPutTransaction.updateGroup((StdPDPGroup) objectFromJson, "XACMLPapServlet.doDelete", userId);
} else {
- acPutTransaction.updateGroup((StdPDPGroup) objectFromJson, "XACMLPapServlet.doACPut", userId);
+ acPutTransaction.updateGroup((StdPDPGroup) objectFromJson, XACML_PAP_SERVLET_DO_AC_PUT, userId);
}
} catch (Exception e) {
PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW + " Error while updating group in the database: "
@@ -786,13 +790,12 @@ public class ConsoleAndApiService {
loggingContext.metricStarted();
acPutTransaction.commitTransaction();
loggingContext.metricEnded();
- PolicyLogger.metrics("XACMLPapServlet doACPut commitTransaction");
+ PolicyLogger.metrics(XACMLPAPSERVLET_DO_AC_PUT_COMMIT_TRANS);
// Group changed, which might include changing the policies
getPapInstance().groupChanged(group, loggingContext);
loggingContext.transactionEnded();
auditLogger.info(SUCCESS);
PolicyLogger.audit(TRANSENDED);
- return;
}
} catch (PAPException e) {
LOGGER.debug(e);
@@ -801,7 +804,6 @@ public class ConsoleAndApiService {
loggingContext.transactionEnded();
PolicyLogger.audit(TRANSACTIONFAILED);
setResponseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
- return;
}
}
@@ -816,19 +818,19 @@ public class ConsoleAndApiService {
* @throws IOException Signals that an I/O exception has occurred.
*/
public void doAcDelete(HttpServletRequest request, HttpServletResponse response, String groupId,
- ONAPLoggingContext loggingContext, PAPPolicyEngine papEngine) throws IOException {
- PolicyDBDaoTransaction removePdpOrGroupTransaction = XACMLPapServlet.getPolicyDbDao().getNewTransaction();
+ OnapLoggingContext loggingContext, PAPPolicyEngine papEngine) throws IOException {
+ PolicyDbDaoTransaction removePdpOrGroupTransaction = XACMLPapServlet.getPolicyDbDao().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 + "'";
+ String message = UNKNOWN_GROUP_ID + groupId + "'";
PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " " + message);
loggingContext.transactionEnded();
PolicyLogger.audit(TRANSACTIONFAILED);
- setResponseError(response, HttpServletResponse.SC_NOT_FOUND, "Unknown groupId '" + groupId + "'");
+ setResponseError(response, HttpServletResponse.SC_NOT_FOUND, UNKNOWN_GROUP_ID + groupId + "'");
removePdpOrGroupTransaction.rollbackTransaction();
return;
}
@@ -838,15 +840,14 @@ public class ConsoleAndApiService {
// group=<groupId> policy=<policyId> [delete=<true|false>] <=
// delete policy file from group
loggingContext.setServiceName("AC:PAP.deletePolicy");
- PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " UNIMPLEMENTED");
+ PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + SPACE_UNIMPLEMENTED);
loggingContext.transactionEnded();
PolicyLogger.audit(TRANSACTIONFAILED);
- setResponseError(response, HttpServletResponse.SC_BAD_REQUEST, "UNIMPLEMENTED");
+ setResponseError(response, HttpServletResponse.SC_BAD_REQUEST, UNIMPLEMENTED);
removePdpOrGroupTransaction.rollbackTransaction();
- return;
- } else if (request.getParameter("pdpId") != null) {
+ } else if (request.getParameter(PDP_ID) != null) {
// ARGS: group=<groupId> pdpId=<pdpId> <= delete PDP
- String pdpId = request.getParameter("pdpId");
+ String pdpId = request.getParameter(PDP_ID);
OnapPDP pdp = papEngine.getPDP(pdpId);
removePdpFromGroup(removePdpOrGroupTransaction, pdp, papEngine);
// adjust the status of the group, which may have changed when
@@ -859,21 +860,19 @@ public class ConsoleAndApiService {
loggingContext.metricStarted();
removePdpOrGroupTransaction.commitTransaction();
loggingContext.metricEnded();
- PolicyLogger.metrics("XACMLPapServlet doACPut commitTransaction");
+ PolicyLogger.metrics(XACMLPAPSERVLET_DO_AC_PUT_COMMIT_TRANS);
loggingContext.transactionEnded();
auditLogger.info(SUCCESS);
PolicyLogger.audit(TRANSENDED);
- return;
} else if (request.getParameter("pipId") != null) {
// group=<groupId> pipId=<pipEngineId> <= delete PIP config for
// given engine
loggingContext.setServiceName("AC:PAP.deletePIPConfig");
- PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " UNIMPLEMENTED");
+ PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + SPACE_UNIMPLEMENTED);
loggingContext.transactionEnded();
PolicyLogger.audit(TRANSACTIONFAILED);
- setResponseError(response, HttpServletResponse.SC_BAD_REQUEST, "UNIMPLEMENTED");
+ setResponseError(response, HttpServletResponse.SC_BAD_REQUEST, UNIMPLEMENTED);
removePdpOrGroupTransaction.rollbackTransaction();
- return;
} else {
// ARGS: group=<groupId> movePDPsToGroupId=<movePDPsToGroupId>
// <= delete a group and move all its PDPs to the given group
@@ -901,11 +900,10 @@ public class ConsoleAndApiService {
loggingContext.metricStarted();
removePdpOrGroupTransaction.commitTransaction();
loggingContext.metricEnded();
- PolicyLogger.metrics("XACMLPapServlet doACPut commitTransaction");
+ PolicyLogger.metrics(XACMLPAPSERVLET_DO_AC_PUT_COMMIT_TRANS);
loggingContext.transactionEnded();
auditLogger.info(SUCCESS);
PolicyLogger.audit(TRANSENDED);
- return;
}
} catch (PAPException e) {
removePdpOrGroupTransaction.rollbackTransaction();
@@ -913,11 +911,10 @@ public class ConsoleAndApiService {
loggingContext.transactionEnded();
PolicyLogger.audit(TRANSACTIONFAILED);
setResponseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
- return;
}
}
- private void deleteGroup(PolicyDBDaoTransaction removePdpOrGroupTransaction, OnapPDPGroup group,
+ private void deleteGroup(PolicyDbDaoTransaction removePdpOrGroupTransaction, OnapPDPGroup group,
OnapPDPGroup moveToGroup, PAPPolicyEngine papEngine) throws PAPException {
try {
removePdpOrGroupTransaction.deleteGroup(group, moveToGroup, "XACMLPapServlet.doACDelete");
@@ -929,7 +926,7 @@ public class ConsoleAndApiService {
}
}
- private void removePdpFromGroup(PolicyDBDaoTransaction removePdpOrGroupTransaction, OnapPDP pdp,
+ private void removePdpFromGroup(PolicyDbDaoTransaction removePdpOrGroupTransaction, OnapPDP pdp,
PAPPolicyEngine papEngine) throws PAPException {
try {
removePdpOrGroupTransaction.removePdpFromGroup(pdp.getId(), "XACMLPapServlet.doACDelete");
@@ -959,6 +956,5 @@ public class ConsoleAndApiService {
} catch (IOException e) {
LOGGER.error("Error setting Error response Header ", e);
}
- return;
}
}
diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/DataToNotifyPdp.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/DataToNotifyPdp.java
index 5615b13cf..f2a31db3c 100644
--- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/DataToNotifyPdp.java
+++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/DataToNotifyPdp.java
@@ -23,6 +23,7 @@ package org.onap.policy.pap.xacml.rest;
import com.att.research.xacml.api.pap.PAPException;
import com.att.research.xacml.util.XACMLProperties;
import com.google.common.base.Joiner;
+
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.file.Paths;
@@ -32,6 +33,7 @@ import java.util.Enumeration;
import java.util.List;
import java.util.Properties;
import java.util.TreeSet;
+
import org.onap.policy.common.logging.flexlogger.FlexLogger;
import org.onap.policy.common.logging.flexlogger.Logger;
import org.onap.policy.rest.dao.CommonClassDao;
@@ -60,7 +62,6 @@ public class DataToNotifyPdp {
// default constructor.
}
-
private static Properties readPipProperties() throws IOException {
if (pipProperties == null) {
try (FileInputStream inputStream = new FileInputStream(Paths.get("pip.properties").toString())) {
diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/DictionaryNames.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/DictionaryNames.java
index ce9cad408..0e1cc521a 100644
--- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/DictionaryNames.java
+++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/DictionaryNames.java
@@ -2,14 +2,14 @@
* ============LICENSE_START=======================================================
* ONAP-Logging
* ================================================================================
- * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2018-2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -18,11 +18,10 @@
* ============LICENSE_END=========================================================
*/
-
package org.onap.policy.pap.xacml.rest;
/**
- *
+ *
* MessageCodes contains all the valid Dictionary names
*
*/
@@ -37,7 +36,7 @@ public enum DictionaryNames {
VSCLAction,
ClosedLoopService,
ClosedLoopSite,
- PEPOptions,
+ PepOptions,
VarbindDictionary,
BRMSParamDictionary,
BRMSControllerDictionary,
@@ -54,4 +53,3 @@ public enum DictionaryNames {
TermList,
SearchCriteria
}
-
diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/Heartbeat.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/Heartbeat.java
index 2687799cc..920c3dd87 100644
--- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/Heartbeat.java
+++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/Heartbeat.java
@@ -23,6 +23,7 @@ package org.onap.policy.pap.xacml.rest;
import com.att.research.xacml.api.pap.PAPException;
import com.att.research.xacml.api.pap.PDPStatus;
import com.att.research.xacml.util.XACMLProperties;
+import com.google.common.annotations.VisibleForTesting;
import java.net.ConnectException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
@@ -37,12 +38,11 @@ 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.restAuth.CheckPDP;
-import org.onap.policy.rest.XACMLRestProperties;
+import org.onap.policy.rest.XacmlRestProperties;
import org.onap.policy.xacml.api.pap.OnapPDP;
import org.onap.policy.xacml.api.pap.OnapPDPGroup;
import org.onap.policy.xacml.api.pap.PAPPolicyEngine;
-
/**
* Heartbeat thread - periodically check on PDPs' status.
* Heartbeat with all known PDPs.
@@ -87,9 +87,9 @@ public class Heartbeat implements Runnable {
public Heartbeat(PAPPolicyEngine papEngine2) {
papEngine = papEngine2;
this.heartbeatInterval =
- Integer.parseInt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_HEARTBEAT_INTERVAL, "10000"));
+ Integer.parseInt(XACMLProperties.getProperty(XacmlRestProperties.PROP_PAP_HEARTBEAT_INTERVAL, "10000"));
this.heartbeatTimeout =
- Integer.parseInt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_HEARTBEAT_TIMEOUT, "10000"));
+ Integer.parseInt(XACMLProperties.getProperty(XacmlRestProperties.PROP_PAP_HEARTBEAT_TIMEOUT, "10000"));
}
@Override
@@ -126,7 +126,8 @@ public class Heartbeat implements Runnable {
}
}
- private void getPdpsFromGroup() {
+ @VisibleForTesting
+ protected void getPdpsFromGroup() {
try {
for (OnapPDPGroup g : papEngine.getOnapPDPGroups()) {
for (OnapPDP p : g.getOnapPdps()) {
@@ -135,11 +136,12 @@ public class Heartbeat implements Runnable {
}
} catch (PAPException e) {
PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, XACMLPAPSERVLET,
- "Heartbeat unable to read PDPs from PAPEngine");
+ "Heartbeat unable to read PDPs from PAPEngine");
}
}
- private void notifyEachPdp() {
+ @VisibleForTesting
+ protected void notifyEachPdp() {
HashMap<String, URL> idToUrlMap = new HashMap<>();
for (OnapPDP pdp : pdps) {
// Check for shutdown
@@ -162,14 +164,15 @@ public class Heartbeat implements Runnable {
}
} catch (MalformedURLException e) {
PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, XACMLPAPSERVLET,
- " PDP id '" + fullUrlString + "' is not a valid URL");
+ " PDP id '" + fullUrlString + "' is not a valid URL");
}
}
updatePdpStatus(pdp, openPdpConnection(pdpUrl, pdp));
}
}
- private String openPdpConnection(URL pdpUrl, OnapPDP pdp) {
+ @VisibleForTesting
+ protected String openPdpConnection(URL pdpUrl, OnapPDP pdp) {
// Do a GET with type HeartBeat
String newStatus = "";
HttpURLConnection connection = null;
@@ -188,7 +191,7 @@ public class Heartbeat implements Runnable {
// Do the connect
connection.connect();
if (connection.getResponseCode() == 204) {
- newStatus = connection.getHeaderField(XACMLRestProperties.PROP_PDP_HTTP_HEADER_HB);
+ newStatus = connection.getHeaderField(XacmlRestProperties.PROP_PDP_HTTP_HEADER_HB);
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Heartbeat '" + pdp.getId() + "' status='" + newStatus + "'");
}
@@ -196,25 +199,25 @@ public class Heartbeat implements Runnable {
// 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());
+ + connection.getResponseCode() + ": " + pdp.getId());
}
}
} catch (UnknownHostException e) {
newStatus = PDPStatus.Status.NO_SUCH_HOST.toString();
PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, XACMLPAPSERVLET,
- HEARTBEATSTRING + pdp.getId() + "' NO_SUCH_HOST");
+ HEARTBEATSTRING + pdp.getId() + "' NO_SUCH_HOST");
} catch (SocketTimeoutException e) {
newStatus = PDPStatus.Status.CANNOT_CONNECT.toString();
PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, XACMLPAPSERVLET,
- HEARTBEATSTRING + pdp.getId() + "' connection timeout");
+ HEARTBEATSTRING + pdp.getId() + "' connection timeout");
} catch (ConnectException e) {
newStatus = PDPStatus.Status.CANNOT_CONNECT.toString();
PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, XACMLPAPSERVLET,
- HEARTBEATSTRING + pdp.getId() + "' cannot connect");
+ HEARTBEATSTRING + pdp.getId() + "' cannot connect");
} catch (Exception e) {
newStatus = PDPStatus.Status.UNKNOWN.toString();
PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, XACMLPAPSERVLET,
- HEARTBEATSTRING + pdp.getId() + "' connect exception");
+ HEARTBEATSTRING + pdp.getId() + "' connect exception");
} finally {
// cleanup the connection
if (connection != null)
@@ -223,7 +226,8 @@ public class Heartbeat implements Runnable {
return newStatus;
}
- private void updatePdpStatus(OnapPDP pdp, String newStatus) {
+ @VisibleForTesting
+ protected void updatePdpStatus(OnapPDP pdp, String newStatus) {
if (!pdp.getStatus().getStatus().toString().equals(newStatus)) {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("previous status='" + pdp.getStatus().getStatus() + "' new Status='" + newStatus + "'");
@@ -232,7 +236,7 @@ public class Heartbeat implements Runnable {
getPAPInstance().setPDPSummaryStatus(pdp, newStatus);
} catch (PAPException e) {
PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, XACMLPAPSERVLET,
- "Unable to set state for PDP '" + pdp.getId());
+ "Unable to set state for PDP '" + pdp.getId());
}
}
}
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
index 9ccccff05..2ca87af28 100644
--- 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
@@ -24,13 +24,15 @@ package org.onap.policy.pap.xacml.rest;
import java.io.FileInputStream;
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.onap.policy.rest.XACMLRestProperties;
+import org.onap.policy.rest.XacmlRestProperties;
import org.onap.policy.utils.PeCryptoUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
@@ -45,9 +47,9 @@ import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter
@Configuration
@EnableWebMvc
@EnableTransactionManagement
-@ComponentScan(basePackages = { "org.onap.*", "com.*" })
+@ComponentScan(basePackages = {"org.onap.*", "com.*"})
public class PAPRestConfig extends WebMvcConfigurerAdapter {
- private static final Logger LOGGER = FlexLogger.getLogger(PAPRestConfig.class);
+ private static final Logger LOGGER = FlexLogger.getLogger(PAPRestConfig.class);
private static String dbDriver = null;
private static String dbUrl = null;
@@ -55,18 +57,18 @@ public class PAPRestConfig extends WebMvcConfigurerAdapter {
private static String dbPassword = null;
@PostConstruct
- public void init(){
+ public void init() {
Properties prop = new Properties();
- try(InputStream input = new FileInputStream("xacml.pap.properties")) {
+ try (InputStream 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"));
- PeCryptoUtils.initAesKey(prop.getProperty(XACMLRestProperties.PROP_AES_KEY));
+ PeCryptoUtils.initAesKey(prop.getProperty(XacmlRestProperties.PROP_AES_KEY));
setDbPassword(PeCryptoUtils.decrypt(prop.getProperty("javax.persistence.jdbc.password")));
- }catch(Exception e){
- LOGGER.error("Exception Occured while loading properties file"+e);
+ } catch (Exception e) {
+ LOGGER.error("Exception Occured while loading properties file" + e);
}
}
diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/UpdateOthersPAPS.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/UpdateOthersPAPS.java
index 22f919e4b..1b25c3b9f 100644
--- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/UpdateOthersPAPS.java
+++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/UpdateOthersPAPS.java
@@ -22,6 +22,7 @@ package org.onap.policy.pap.xacml.rest;
import com.att.research.xacml.util.XACMLProperties;
import com.fasterxml.jackson.databind.ObjectMapper;
+
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
@@ -33,19 +34,21 @@ import java.util.Base64;
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.adapters.UpdateObjectData;
import org.onap.policy.pap.xacml.rest.components.Policy;
import org.onap.policy.pap.xacml.rest.util.JsonMessage;
-import org.onap.policy.rest.XACMLRestProperties;
+import org.onap.policy.rest.XacmlRestProperties;
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.PolicyDBDaoEntity;
+import org.onap.policy.rest.jpa.PolicyDbDaoEntity;
import org.onap.policy.utils.PeCryptoUtils;
import org.onap.policy.xacml.api.XACMLErrorConstants;
import org.springframework.beans.factory.annotation.Autowired;
@@ -69,9 +72,10 @@ public class UpdateOthersPAPS {
private static CommonClassDao commonClassDao;
private static final String contentType = "application/json";
- private static String configType =".Config_";
- private static String actionType =".Action_";
- private static String error ="error";
+ private static String configType = ".Config_";
+ private static String actionType = ".Action_";
+ private static String error = "error";
+
public static CommonClassDao getCommonClassDao() {
return commonClassDao;
}
@@ -86,11 +90,11 @@ public class UpdateOthersPAPS {
}
public UpdateOthersPAPS() {
- //Empty Constructor
+ // Empty Constructor
}
- @RequestMapping(value="/notifyOtherPAPs", method= RequestMethod.POST)
- public void notifyOthersPAPsToUpdateConfigurations(HttpServletRequest request, HttpServletResponse response){
+ @RequestMapping(value = "/notifyOtherPAPs", method = RequestMethod.POST)
+ public void notifyOthersPAPsToUpdateConfigurations(HttpServletRequest request, HttpServletResponse response) {
Map<String, Object> model = new HashMap<>();
ObjectMapper mapper = new ObjectMapper();
UpdateObjectData body = new UpdateObjectData();
@@ -98,23 +102,23 @@ public class UpdateOthersPAPS {
body.setNewPolicyName(request.getParameter("newPolicyName"));
body.setOldPolicyName(request.getParameter("oldPolicyName"));
- String currentPap = XACMLRestProperties.getProperty("xacml.rest.pap.url");
- List<Object> getPAPUrls = commonClassDao.getData(PolicyDBDaoEntity.class);
- if(getPAPUrls != null && !getPAPUrls.isEmpty()){
- for(int i = 0; i < getPAPUrls.size(); i++){
- PolicyDBDaoEntity papId = (PolicyDBDaoEntity) getPAPUrls.get(i);
- String papUrl = papId.getPolicyDBDaoUrl();
- if(!papUrl.equals(currentPap)){
+ String currentPap = XacmlRestProperties.getProperty("xacml.rest.pap.url");
+ List<Object> getPAPUrls = commonClassDao.getData(PolicyDbDaoEntity.class);
+ if (getPAPUrls != null && !getPAPUrls.isEmpty()) {
+ for (int i = 0; i < getPAPUrls.size(); i++) {
+ PolicyDbDaoEntity papId = (PolicyDbDaoEntity) getPAPUrls.get(i);
+ String papUrl = papId.getPolicyDbDaoUrl();
+ if (!papUrl.equals(currentPap)) {
String userName = papId.getUsername();
String password = papId.getPassword();
Base64.Encoder encoder = Base64.getEncoder();
String txt;
try {
- PeCryptoUtils.initAesKey(XACMLProperties.getProperty(XACMLRestProperties.PROP_AES_KEY));
+ PeCryptoUtils.initAesKey(XACMLProperties.getProperty(XacmlRestProperties.PROP_AES_KEY));
txt = PeCryptoUtils.decrypt(password);
} catch (Exception e) {
policyLogger.debug(e);
- //if we can't decrypt, might as well try it anyway
+ // if we can't decrypt, might as well try it anyway
txt = password;
}
String encoding = encoder.encodeToString((userName + ":" + txt).getBytes(StandardCharsets.UTF_8));
@@ -126,33 +130,39 @@ public class UpdateOthersPAPS {
HttpEntity<?> requestEntity = new HttpEntity<>(body, headers);
HttpClientErrorException exception = null;
- try{
- restTemplate.exchange(papUrl + "onap/updateConfiguration", HttpMethod.POST, requestEntity, String.class);
- }catch(Exception e){
- policyLogger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error while connecting to " + papUrl, e);
+ try {
+ restTemplate.exchange(papUrl + "onap/updateConfiguration", HttpMethod.POST, 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())){
+ if ("409 Conflict".equals(e.getMessage())) {
policyLogger.error(e.getMessage());
response.addHeader(error, e.getMessage());
}
}
- if(exception != null && exception.getStatusCode()!=null){
+ if (exception != null && exception.getStatusCode() != null) {
String message;
- if(exception.getStatusCode().equals(HttpStatus.UNAUTHORIZED)){
- message = XACMLErrorConstants.ERROR_PERMISSIONS +":"+exception.getStatusCode()+":" + "ERROR_AUTH_GET_PERM" ;
+ if (exception.getStatusCode().equals(HttpStatus.UNAUTHORIZED)) {
+ message = XACMLErrorConstants.ERROR_PERMISSIONS + ":" + exception.getStatusCode() + ":"
+ + "ERROR_AUTH_GET_PERM";
policyLogger.error(message);
- }else if(exception.getStatusCode().equals(HttpStatus.BAD_REQUEST)){
- message = XACMLErrorConstants.ERROR_DATA_ISSUE + ":"+exception.getStatusCode()+":" + exception.getResponseBodyAsString();
+ } else if (exception.getStatusCode().equals(HttpStatus.BAD_REQUEST)) {
+ message = XACMLErrorConstants.ERROR_DATA_ISSUE + ":" + exception.getStatusCode() + ":"
+ + exception.getResponseBodyAsString();
policyLogger.error(message);
- }else if(exception.getStatusCode().equals(HttpStatus.NOT_FOUND)){
- message = XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error while connecting to " + papUrl + exception;
+ } else if (exception.getStatusCode().equals(HttpStatus.NOT_FOUND)) {
+ message = XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error while connecting to " + papUrl
+ + exception;
policyLogger.error(message);
- }else{
- message = XACMLErrorConstants.ERROR_PROCESS_FLOW + ":"+exception.getStatusCode()+":" + exception.getResponseBodyAsString();
+ } else {
+ message = XACMLErrorConstants.ERROR_PROCESS_FLOW + ":" + exception.getStatusCode() + ":"
+ + exception.getResponseBodyAsString();
policyLogger.error(message);
}
model.put(papUrl, message);
- }else{
+ } else {
model.put(papUrl, "Success");
}
}
@@ -163,78 +173,80 @@ public class UpdateOthersPAPS {
JSONObject j = new JSONObject(msg);
response.getWriter().write(j.toString());
} catch (Exception e) {
- policyLogger.error("Exception Occured"+e);
+ policyLogger.error("Exception Occured" + e);
}
}
}
- @RequestMapping(value="/updateConfiguration", method= RequestMethod.POST)
+ @RequestMapping(value = "/updateConfiguration", method = RequestMethod.POST)
@ResponseBody
- public void updateConfiguration(@RequestBody UpdateObjectData data, HttpServletResponse response){
+ public void updateConfiguration(@RequestBody UpdateObjectData data, HttpServletResponse response) {
String action = data.getAction();
String newPolicyName = data.getNewPolicyName();
String oldPolicyName = data.getOldPolicyName();
- try{
- if("rename".equals(action)){
- if(oldPolicyName.contains(configType) || oldPolicyName.contains(actionType)){
+ try {
+ if ("rename".equals(action)) {
+ if (oldPolicyName.contains(configType) || oldPolicyName.contains(actionType)) {
File file;
- if(oldPolicyName.contains(configType)){
+ if (oldPolicyName.contains(configType)) {
file = new File(Policy.getConfigHome() + File.separator + oldPolicyName);
- }else{
+ } else {
file = new File(Policy.getActionHome() + File.separator + oldPolicyName);
}
- if(file.exists()){
+ if (file.exists()) {
File renamefile;
- if(oldPolicyName.contains(configType)){
+ if (oldPolicyName.contains(configType)) {
renamefile = new File(Policy.getConfigHome() + File.separator + newPolicyName);
- }else{
+ } else {
renamefile = new File(Policy.getActionHome() + File.separator + newPolicyName);
}
- if(file.renameTo(renamefile)){
- policyLogger.info("Policy has been renamed Successfully"+newPolicyName);
+ if (file.renameTo(renamefile)) {
+ policyLogger.info("Policy has been renamed Successfully" + newPolicyName);
response.addHeader("rename", "Success");
- }else{
+ } else {
response.addHeader("rename", "Failure");
}
}
}
- }else if("delete".equals(action)){
- if(oldPolicyName.contains(configType)){
+ } else if ("delete".equals(action)) {
+ if (oldPolicyName.contains(configType)) {
Files.deleteIfExists(Paths.get(Policy.getConfigHome() + File.separator + oldPolicyName));
- }else if(oldPolicyName.contains("Action_")){
+ } else if (oldPolicyName.contains("Action_")) {
Files.deleteIfExists(Paths.get(Policy.getActionHome() + File.separator + oldPolicyName));
}
- }else if("clonePolicy".equals(action) || "exportPolicy".equals(action)){
- if(newPolicyName.contains(configType)){
- ConfigurationDataEntity configEntiy = (ConfigurationDataEntity) commonClassDao.getEntityItem(ConfigurationDataEntity.class, "configurationName", newPolicyName);
+ } else if ("clonePolicy".equals(action) || "exportPolicy".equals(action)) {
+ if (newPolicyName.contains(configType)) {
+ ConfigurationDataEntity configEntiy = (ConfigurationDataEntity) commonClassDao
+ .getEntityItem(ConfigurationDataEntity.class, "configurationName", newPolicyName);
saveConfigurationData(configEntiy, newPolicyName);
- }else if(newPolicyName.contains(actionType)){
- ActionBodyEntity actionEntiy = (ActionBodyEntity) commonClassDao.getEntityItem(ActionBodyEntity.class, "actionBodyName", newPolicyName);
+ } else if (newPolicyName.contains(actionType)) {
+ ActionBodyEntity actionEntiy = (ActionBodyEntity) commonClassDao
+ .getEntityItem(ActionBodyEntity.class, "actionBodyName", newPolicyName);
saveActionBodyData(actionEntiy, newPolicyName);
}
}
} catch (IOException e) {
- policyLogger.error("Exception Occured While updating Configuration"+e);
+ policyLogger.error("Exception Occured While updating Configuration" + e);
}
}
- private void saveConfigurationData(ConfigurationDataEntity configEntiy, String newPolicyName){
- try(FileWriter fw = new FileWriter(Policy.getConfigHome() + File.separator + newPolicyName)){
+ private void saveConfigurationData(ConfigurationDataEntity configEntiy, String newPolicyName) {
+ try (FileWriter fw = new FileWriter(Policy.getConfigHome() + File.separator + newPolicyName)) {
BufferedWriter bw = new BufferedWriter(fw);
bw.write(configEntiy.getConfigBody());
bw.close();
- }catch (IOException e) {
- policyLogger.error("Exception Occured While closing the File input stream"+e);
+ } catch (IOException e) {
+ policyLogger.error("Exception Occured While closing the File input stream" + e);
}
}
- private void saveActionBodyData(ActionBodyEntity actionEntiy , String newPolicyName){
- try(FileWriter fw = new FileWriter(Policy.getActionHome() + File.separator + newPolicyName)){
+ private void saveActionBodyData(ActionBodyEntity actionEntiy, String newPolicyName) {
+ try (FileWriter fw = new FileWriter(Policy.getActionHome() + File.separator + newPolicyName)) {
BufferedWriter bw = new BufferedWriter(fw);
bw.write(actionEntiy.getActionBody());
bw.close();
- }catch (IOException e) {
- policyLogger.error("Exception Occured While closing the File input stream"+e);
+ } catch (IOException e) {
+ policyLogger.error("Exception Occured While closing the File input stream" + e);
}
}
}
diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/UpdatePdpThread.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/UpdatePdpThread.java
index 11576d314..e32ae63b1 100644
--- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/UpdatePdpThread.java
+++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/UpdatePdpThread.java
@@ -22,13 +22,15 @@ package org.onap.policy.pap.xacml.rest;
import com.att.research.xacml.api.pap.PAPException;
import com.att.research.xacml.api.pap.PDPStatus;
+
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;
import java.util.Properties;
import java.util.UUID;
-import org.onap.policy.common.logging.ONAPLoggingContext;
+
+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.common.logging.flexlogger.FlexLogger;
@@ -39,17 +41,16 @@ import org.onap.policy.xacml.api.pap.OnapPDP;
public class UpdatePdpThread implements Runnable {
private static final Logger LOGGER = FlexLogger.getLogger(UpdatePdpThread.class);
- private ONAPLoggingContext baseLoggingContext = new XACMLPapServlet().getBaseLoggingContext();
+ private OnapLoggingContext baseLoggingContext = new XACMLPapServlet().getBaseLoggingContext();
private static final Logger auditLogger = FlexLogger.getLogger("auditLogger");
private static final String XACMLPAPSERVLET = "XACMLPapServlet";
private static final String MESSAGE = " message: ";
private OnapPDP pdp;
private String requestId;
- private ONAPLoggingContext loggingContext;
+ private OnapLoggingContext loggingContext;
private List<Properties> properties;
-
public UpdatePdpThread(OnapPDP pdp, List<Properties> properties) {
this.pdp = pdp;
this.properties = properties;
@@ -62,11 +63,11 @@ public class UpdatePdpThread implements Runnable {
* @param loggingContext the logging context
* @param properties the properties
*/
- public UpdatePdpThread(OnapPDP pdp, ONAPLoggingContext loggingContext, List<Properties> properties) {
+ public UpdatePdpThread(OnapPDP pdp, OnapLoggingContext loggingContext, List<Properties> properties) {
this.pdp = pdp;
if (loggingContext != null
- && (loggingContext.getRequestID() != null || "".equals(loggingContext.getRequestID()))) {
- this.requestId = loggingContext.getRequestID();
+ && (loggingContext.getRequestId() != null || "".equals(loggingContext.getRequestId()))) {
+ this.requestId = loggingContext.getRequestId();
}
this.loggingContext = loggingContext;
this.properties = properties;
@@ -79,7 +80,7 @@ public class UpdatePdpThread implements Runnable {
// get a new logging context for the thread
try {
if (this.loggingContext == null) {
- loggingContext = new ONAPLoggingContext(baseLoggingContext);
+ loggingContext = new OnapLoggingContext(baseLoggingContext);
}
} catch (Exception e) {
PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, XACMLPAPSERVLET,
@@ -95,14 +96,14 @@ public class UpdatePdpThread implements Runnable {
// post to loggingContext to be used later when calling PDP
if (requestId == null || "".equals(requestId)) {
UUID requestId = UUID.randomUUID();
- loggingContext.setRequestID(requestId.toString());
+ loggingContext.setRequestId(requestId.toString());
PolicyLogger
.info("requestID not provided in call to XACMLPapSrvlet (UpdatePDPThread) so we generated one: "
- + loggingContext.getRequestID());
+ + loggingContext.getRequestId());
} else {
- loggingContext.setRequestID(requestId);
+ loggingContext.setRequestId(requestId);
PolicyLogger.info("requestID was provided in call to XACMLPapSrvlet (UpdatePDPThread): "
- + loggingContext.getRequestID());
+ + loggingContext.getRequestId());
}
loggingContext.transactionStarted();
// the Id of the PDP is its URL
@@ -120,7 +121,7 @@ public class UpdatePdpThread implements Runnable {
connection.setRequestProperty("Authorization", "Basic " + encoding);
}
connection.setRequestProperty("Content-Type", "text/x-java-properties");
- connection.setRequestProperty("X-ECOMP-RequestID", loggingContext.getRequestID());
+ connection.setRequestProperty("X-ECOMP-RequestID", loggingContext.getRequestId());
connection.setInstanceFollowRedirects(true);
connection.setDoOutput(true);
if (!writePropertiesToStream(connection)) {
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
index b5951d823..60450efd7 100644
--- 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
@@ -2,7 +2,8 @@
* ============LICENSE_START=======================================================
* ONAP-PAP-REST
* ================================================================================
- * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2020 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2019 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -26,6 +27,7 @@ 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.annotations.VisibleForTesting;
import com.google.common.base.Splitter;
import java.io.File;
import java.io.FileInputStream;
@@ -59,22 +61,22 @@ import org.onap.policy.common.im.IntegrityMonitor;
import org.onap.policy.common.im.IntegrityMonitorException;
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.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.HandleIncomingNotifications;
-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.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.rest.dao.PolicyDBException;
+import org.onap.policy.rest.XacmlRest;
+import org.onap.policy.rest.XacmlRestProperties;
+import org.onap.policy.rest.dao.PolicyDbException;
import org.onap.policy.utils.PeCryptoUtils;
import org.onap.policy.utils.PolicyUtils;
import org.onap.policy.xacml.api.XACMLErrorConstants;
@@ -91,10 +93,14 @@ import org.onap.policy.xacml.std.pap.StdPDPStatus;
/**
* 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.")})
+@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);
@@ -116,8 +122,7 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList
* 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<String> adminConsoleURLStringList =
- new CopyOnWriteArrayList<>();
+ private static final CopyOnWriteArrayList<String> adminConsoleURLStringList = new CopyOnWriteArrayList<>();
private static String configHome;
private static String actionHome;
@@ -129,7 +134,7 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList
// The heartbeat thread.
private static Heartbeat heartbeat = null;
private static Thread heartbeatThread = null;
- private static PolicyDBDao policyDbDao;
+ private static PolicyDbDao policyDbDao;
/*
* papEngine - This is our engine workhorse that manages the PDP Groups and Nodes.
*/
@@ -158,7 +163,7 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList
* this servlet starts. Its configurable by the admin.
*/
private static transient Thread initiateThread = null;
- private transient ONAPLoggingContext baseLoggingContext = null;
+ private transient OnapLoggingContext baseLoggingContext = null;
private static final String GROUPID = "groupId";
/**
@@ -175,97 +180,89 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList
public void init(ServletConfig config) throws ServletException {
try {
// Logging
- baseLoggingContext = new ONAPLoggingContext();
+ 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", e);
+ LOGGER.warn(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Unable to get hostname for logging", e);
}
// Initialize
- XACMLRest.xacmlInit(config);
+ XacmlRest.xacmlInit(config);
// Load the properties
- XACMLRest.loadXacmlProperties(null, null);
+ XacmlRest.loadXacmlProperties(null, null);
/*
* Retrieve the property values
*/
setCommonProperties();
- String papSiteName = XACMLProperties.getProperty(XACMLRestProperties.PAP_SITE_NAME);
+ String papSiteName = XACMLProperties.getProperty(XacmlRestProperties.PAP_SITE_NAME);
if (papSiteName == null) {
PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, "XACMLPapServlet",
- " ERROR: Bad papSiteName property entry");
+ " ERROR: Bad papSiteName property entry");
throw new PAPException("papSiteName is null");
}
- String papNodeType = XACMLProperties.getProperty(XACMLRestProperties.PAP_NODE_TYPE);
+ String papNodeType = XACMLProperties.getProperty(XacmlRestProperties.PAP_NODE_TYPE);
if (papNodeType == null) {
PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, "XACMLPapServlet",
- " ERROR: Bad papNodeType property entry");
+ " ERROR: Bad papNodeType property entry");
throw new PAPException("papNodeType is null");
}
// Integer will throw an exception of anything is missing or
// unrecognized
- int papTransWait = Integer
- .parseInt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_TRANS_WAIT));
- int papTransTimeout = Integer.parseInt(
- XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_TRANS_TIMEOUT));
- int papAuditTimeout = Integer.parseInt(
- XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_AUDIT_TIMEOUT));
+ int papTransWait = Integer.parseInt(XACMLProperties.getProperty(XacmlRestProperties.PROP_PAP_TRANS_WAIT));
+ int papTransTimeout =
+ Integer.parseInt(XACMLProperties.getProperty(XacmlRestProperties.PROP_PAP_TRANS_TIMEOUT));
+ int papAuditTimeout =
+ Integer.parseInt(XACMLProperties.getProperty(XacmlRestProperties.PROP_PAP_AUDIT_TIMEOUT));
// Boolean will default to false if anything is missing or
// unrecognized
- boolean papAuditFlag = Boolean.parseBoolean(
- XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_RUN_AUDIT_FLAG));
- boolean papFileSystemAudit = Boolean.parseBoolean(
- XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_AUDIT_FLAG));
- String papDependencyGroups =
- XACMLProperties.getProperty(XACMLRestProperties.PAP_DEPENDENCY_GROUPS);
+ boolean papAuditFlag =
+ Boolean.parseBoolean(XACMLProperties.getProperty(XacmlRestProperties.PROP_PAP_RUN_AUDIT_FLAG));
+ boolean papFileSystemAudit =
+ Boolean.parseBoolean(XACMLProperties.getProperty(XacmlRestProperties.PROP_PAP_AUDIT_FLAG));
+ String papDependencyGroups = XACMLProperties.getProperty(XacmlRestProperties.PAP_DEPENDENCY_GROUPS);
if (papDependencyGroups == null) {
throw new PAPException("papDependencyGroups is null");
}
setPAPDependencyGroups(papDependencyGroups);
// Integer will throw an exception of anything is missing or
// unrecognized
- int fpMonitorInterval = Integer.parseInt(
- XACMLProperties.getProperty(IntegrityMonitorProperties.FP_MONITOR_INTERVAL));
- int failedCounterThreshold = Integer.parseInt(XACMLProperties
- .getProperty(IntegrityMonitorProperties.FAILED_COUNTER_THRESHOLD));
- int testTransInterval = Integer.parseInt(
- XACMLProperties.getProperty(IntegrityMonitorProperties.TEST_TRANS_INTERVAL));
- int 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 papTransWait = " + papTransWait + "\n papTransTimeout = "
- + papTransTimeout + "\n papAuditTimeout = " + papAuditTimeout
- + "\n papAuditFlag = " + papAuditFlag + "\n papFileSystemAudit = "
- + papFileSystemAudit + "\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**************************************");
+ int fpMonitorInterval =
+ Integer.parseInt(XACMLProperties.getProperty(IntegrityMonitorProperties.FP_MONITOR_INTERVAL));
+ int failedCounterThreshold =
+ Integer.parseInt(XACMLProperties.getProperty(IntegrityMonitorProperties.FAILED_COUNTER_THRESHOLD));
+ int testTransInterval =
+ Integer.parseInt(XACMLProperties.getProperty(IntegrityMonitorProperties.TEST_TRANS_INTERVAL));
+ int 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 papTransWait = " + papTransWait + "\n papTransTimeout = " + papTransTimeout
+ + "\n papAuditTimeout = " + papAuditTimeout + "\n papAuditFlag = " + papAuditFlag
+ + "\n papFileSystemAudit = " + papFileSystemAudit + "\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**************************************");
+ 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()");
+ " Error loading properties with: " + "XACMLProperties.getProperties()");
throw new ServletException(e.getMessage(), e.getCause());
}
// Create an IntegrityMonitor
if (properties.getProperty(PERSISTENCE_JDBC_PWD) != null) {
properties.setProperty(PERSISTENCE_JDBC_PWD,
- PeCryptoUtils.decrypt(properties.getProperty(PERSISTENCE_JDBC_PWD, "")));
+ PeCryptoUtils.decrypt(properties.getProperty(PERSISTENCE_JDBC_PWD, "")));
}
im = IntegrityMonitor.getInstance(papResourceName, properties);
// Create an IntegrityAudit
@@ -274,26 +271,25 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList
// 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
- setPapUrl(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_URL));
+ setPapUrl(XACMLProperties.getProperty(XacmlRestProperties.PROP_PAP_URL));
// Create the policyDBDao
setPolicyDbDao();
// Load our PAP engine, first create a factory
- ONAPPapEngineFactory factory = ONAPPapEngineFactory.newInstance(
- XACMLProperties.getProperty(XACMLProperties.PROP_PAP_PAPENGINEFACTORY));
+ ONAPPapEngineFactory factory = ONAPPapEngineFactory
+ .newInstance(XACMLProperties.getProperty(XACMLProperties.PROP_PAP_PAPENGINEFACTORY));
// The factory knows how to go about creating a PAP Engine
setPAPEngine(factory.newEngine());
if (((org.onap.policy.xacml.std.pap.StdEngine) papEngine).wasDefaultGroupJustAdded) {
createDefaultGroupOnInit();
}
policyDbDao.setPapEngine(XACMLPapServlet.papEngine);
- if (Boolean.parseBoolean(
- XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_RUN_AUDIT_FLAG))) {
+ if (Boolean.parseBoolean(XACMLProperties.getProperty(XacmlRestProperties.PROP_PAP_RUN_AUDIT_FLAG))) {
/*
* Auditing the local File System groups to be in sync with the Database
*/
// get an AuditTransaction to lock out all other transactions
- PolicyDBDaoTransaction auditTrans = policyDbDao.getNewAuditTransaction();
+ PolicyDbDaoTransaction auditTrans = policyDbDao.getNewAuditTransaction();
LOGGER.info("PapServlet: calling auditLocalFileSystem for PDP group audit");
LOGGER.info("PapServlet: old group is " + papEngine.getDefaultGroup().toString());
@@ -304,8 +300,7 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList
if (updatedGroup != null) {
papEngine.updateGroup(updatedGroup);
}
- LOGGER.info(
- "PapServlet: updated group is " + papEngine.getDefaultGroup().toString());
+ LOGGER.info("PapServlet: updated group is " + papEngine.getDefaultGroup().toString());
// sync up the config data from DB to file system
LOGGER.info("PapServlet: Sync config data from DB to file system");
@@ -318,41 +313,37 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList
// 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))) {
+ if (Boolean.parseBoolean(XACMLProperties.getProperty(XacmlRestProperties.PROP_PAP_INITIATE_PDP_CONFIG))) {
startInitiateThreadService(new Thread(this));
}
// After startup, the PAP does Heartbeat's to each of the PDPs
// periodically
startHeartBeatService(new Heartbeat(XACMLPapServlet.papEngine));
} 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);
+ 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);
+ " Failed to create engine - unexpected error");
+ throw new ServletException(
+ XACMLErrorConstants.ERROR_SYSTEM_ERROR + "PAP not initialized; unexpected error: " + e);
}
}
private void createDefaultGroupOnInit() {
- PolicyDBDaoTransaction addNewGroup = null;
+ PolicyDbDaoTransaction addNewGroup = null;
try {
addNewGroup = policyDbDao.getNewTransaction();
OnapPDPGroup group = papEngine.getDefaultGroup();
- addNewGroup.createGroup(group.getId(), group.getName(), group.getDescription(),
- "automaticallyAdded");
+ 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");
+ " Error creating new default group in the database");
if (addNewGroup != null) {
addNewGroup.rollbackTransaction();
}
@@ -364,8 +355,8 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList
initiateThread.start();
}
- private static void mapperWriteValue(ObjectMapper mapper, HttpServletResponse response,
- Object value) {
+ @VisibleForTesting
+ protected static void mapperWriteValue(ObjectMapper mapper, HttpServletResponse response, Object value) {
try {
mapper.writeValue(response.getOutputStream(), value);
} catch (Exception e) {
@@ -381,13 +372,13 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList
private static void setPolicyDbDao() throws ServletException {
try {
- policyDbDao = PolicyDBDao.getPolicyDBDaoInstance();
+ policyDbDao = PolicyDbDao.getPolicyDbDaoInstance();
} catch (Exception e) {
throw new ServletException("Unable to Create Policy DBDao Instance", e);
}
}
- public static PolicyDBDao getPolicyDbDao() {
+ public static PolicyDbDao getPolicyDbDao() {
return policyDbDao;
}
@@ -399,7 +390,8 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList
return papUrl;
}
- private static void setPAPEngine(PAPPolicyEngine newEngine) {
+ @VisibleForTesting
+ protected static void setPAPEngine(PAPPolicyEngine newEngine) {
XACMLPapServlet.papEngine = newEngine;
}
@@ -412,22 +404,19 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList
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());
+ 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");
+ " ERROR: " + msg + "Bad property entry");
throw e;
}
} catch (Exception e) {
- PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "XACMLPapServlet",
- " ERROR: Bad property entry");
+ PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "XACMLPapServlet", " ERROR: Bad property entry");
throw new PAPException(e);
}
}
@@ -435,39 +424,38 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList
private static void setCommonProperties() throws PAPException {
setConfigHome();
setActionHome();
- papDbDriver = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_DB_DRIVER);
+ papDbDriver = XACMLProperties.getProperty(XacmlRestProperties.PROP_PAP_DB_DRIVER);
if (papDbDriver == null) {
PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, "XACMLPapServlet",
- " ERROR: Bad papDbDriver property entry");
+ " ERROR: Bad papDbDriver property entry");
throw new PAPException("papDbDriver is null");
}
setPapDbDriver(papDbDriver);
- papDbUrl = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_DB_URL);
+ papDbUrl = XACMLProperties.getProperty(XacmlRestProperties.PROP_PAP_DB_URL);
if (papDbUrl == null) {
- PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, "XACMLPapServlet",
- " ERROR: Bad papDbUrl property entry");
+ 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);
+ papDbUser = XACMLProperties.getProperty(XacmlRestProperties.PROP_PAP_DB_USER);
if (papDbUser == null) {
PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, "XACMLPapServlet",
- " ERROR: Bad papDbUser property entry");
+ " ERROR: Bad papDbUser property entry");
throw new PAPException("papDbUser is null");
}
setPapDbUser(papDbUser);
- PeCryptoUtils.initAesKey(XACMLProperties.getProperty(XACMLRestProperties.PROP_AES_KEY));
- papDbPd = PeCryptoUtils.decrypt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_DB_PASSWORD));
+ PeCryptoUtils.initAesKey(XACMLProperties.getProperty(XacmlRestProperties.PROP_AES_KEY));
+ papDbPd = PeCryptoUtils.decrypt(XACMLProperties.getProperty(XacmlRestProperties.PROP_PAP_DB_PASSWORD));
if (papDbPd == null) {
PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, "XACMLPapServlet",
- " ERROR: Bad papDbPassword property entry");
+ " ERROR: Bad papDbPassword property entry");
throw new PAPException("papDbPassword is null");
}
setPapDbPassword(papDbPd);
- papResourceName = XACMLProperties.getProperty(XACMLRestProperties.PAP_RESOURCE_NAME);
+ papResourceName = XACMLProperties.getProperty(XacmlRestProperties.PAP_RESOURCE_NAME);
if (papResourceName == null) {
PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, "XACMLPapServlet",
- " ERROR: Bad papResourceName property entry");
+ " ERROR: Bad papResourceName property entry");
throw new PAPException("papResourceName is null");
}
environment = XACMLProperties.getProperty("ENVIRONMENT", "DEVL");
@@ -477,13 +465,12 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList
msPolicyName = XACMLProperties.getProperty("xacml.policy.msPolicyName");
setMsPolicyName(msPolicyName);
// PDPId File location
- XACMLPapServlet.pdpFile = XACMLProperties.getProperty(XACMLRestProperties.PROP_PDP_IDFILE);
+ 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. ");
+ 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. ");
}
}
@@ -517,8 +504,7 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList
XACMLPapServlet.heartbeatThread.join();
} catch (InterruptedException e) {
XACMLPapServlet.heartbeatThread.interrupt();
- PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet",
- " Error stopping heartbeat");
+ PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " Error stopping heartbeat");
}
}
if (initiateThread != null) {
@@ -527,10 +513,11 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList
initiateThread.join();
} catch (InterruptedException e) {
initiateThread.interrupt();
- PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet",
- " Error stopping thread");
+ PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " Error stopping thread");
}
}
+ // reset pap url
+ setPapUrl(null);
}
private ConsoleAndApiService getAcServiceInstance() {
@@ -545,21 +532,19 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
- throws ServletException, IOException {
- ONAPLoggingContext loggingContext =
- ONAPLoggingUtils.getLoggingContextForRequest(request, baseLoggingContext);
+ throws ServletException, IOException {
+ OnapLoggingContext loggingContext = OnapLoggingUtils.getLoggingContextForRequest(request, baseLoggingContext);
setLoggingContext(loggingContext, "doPost", "PAP.post");
- PolicyDBDaoTransaction pdpTransaction = null;
+ PolicyDbDaoTransaction pdpTransaction = null;
try {
loggingContext.metricStarted();
im.startTransaction();
loggingContext.metricEnded();
PolicyLogger.metrics("XACMLPapServlet doPost 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: "
- + PolicyUtils.CATCH_EXCEPTION;
+ String message =
+ "POST interface called for PAP " + papResourceName + " but it has an Administrative state of "
+ + im.getStateManager().getAdminState() + "\n Exception Message: " + PolicyUtils.CATCH_EXCEPTION;
LOGGER.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message, ae);
loggingContext.metricEnded();
PolicyLogger.metrics("XACMLPapServlet doPost im startTransaction");
@@ -567,12 +552,12 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList
PolicyLogger.audit("Transaction Failed - See Error.log");
setResponseError(response, 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.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message, se);
+ } catch (IntegrityMonitorException ime) {
+ String message =
+ "POST interface called for PAP " + papResourceName + " but it has an Administrative state of "
+ + im.getStateManager().getAdminState() + " and a Standby Status of "
+ + im.getStateManager().getStandbyStatus() + "\n Exception Message: " + ime.getMessage();
+ LOGGER.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message, ime);
loggingContext.metricEnded();
PolicyLogger.metrics("XACMLPapServlet doPost im startTransaction");
loggingContext.transactionEnded();
@@ -582,7 +567,7 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList
}
try {
loggingContext.metricStarted();
- XACMLRest.dumpRequest(request);
+ XacmlRest.dumpRequest(request);
loggingContext.metricEnded();
PolicyLogger.metrics("XACMLPapServlet doPost dumpRequest");
// since getParameter reads the content string, explicitly get the
@@ -608,8 +593,7 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList
}
}
loggingContext.metricStarted();
- getAcServiceInstance().doAcPost(request, response, groupId, loggingContext,
- papEngine);
+ getAcServiceInstance().doAcPost(request, response, groupId, loggingContext, papEngine);
loggingContext.metricEnded();
PolicyLogger.metrics("XACMLPapServlet doPost doACPost");
loggingContext.transactionEnded();
@@ -632,23 +616,18 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList
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 | PolicyDBException e) {
+ 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 | PolicyDbException e) {
pdpTransaction.rollbackTransaction();
String message = "Failed to create new PDP for id: " + id;
- PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet",
- " " + message);
+ PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " " + message);
loggingContext.transactionEnded();
PolicyLogger.audit("Transaction Failed - See Error.log");
- setResponseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
- e.getMessage());
+ setResponseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
im.endTransaction();
return;
}
@@ -666,8 +645,7 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList
PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW + " " + message);
loggingContext.transactionEnded();
PolicyLogger.audit("Transaction Failed - See Error.log");
- setResponseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
- message);
+ setResponseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
im.endTransaction();
return;
}
@@ -676,7 +654,7 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList
loggingContext.transactionEnded();
PolicyLogger.error(MessageCodes.ERROR_PERMISSIONS + " " + message);
setResponseError(response, HttpServletResponse.SC_UNAUTHORIZED,
- "PDP not Authorized to connect to this PAP. Please contact the PAP Admin for registration.");
+ "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;
@@ -688,7 +666,7 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList
PolicyLogger.metrics("XACMLPapServlet doPost commitTransaction");
} catch (Exception e) {
PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet",
- "Could not commit transaction to put pdp in the database");
+ "Could not commit transaction to put pdp in the database");
}
}
if (jmxport != null && !"".equals(jmxport)) {
@@ -706,12 +684,12 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList
LOGGER.error(e);
}
if (group == null) {
- PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW
- + " PDP not associated with any group, even the default");
+ PolicyLogger
+ .error(MessageCodes.ERROR_PROCESS_FLOW + " PDP not associated with any group, even the default");
loggingContext.transactionEnded();
PolicyLogger.audit("Transaction Failed - See Error.log");
setResponseError(response, HttpServletResponse.SC_UNAUTHORIZED,
- "PDP not associated with any group, even the default");
+ "PDP not associated with any group, even the default");
im.endTransaction();
return;
}
@@ -780,8 +758,7 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList
LOGGER.debug(XACMLErrorConstants.ERROR_PROCESS_FLOW + "POST exception: " + e, e);
loggingContext.transactionEnded();
PolicyLogger.audit("Transaction Failed - See Error.log");
- setResponseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
- e.getMessage());
+ setResponseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
im.endTransaction();
return;
}
@@ -806,12 +783,11 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
- throws ServletException, IOException {
- ONAPLoggingContext loggingContext =
- ONAPLoggingUtils.getLoggingContextForRequest(request, baseLoggingContext);
+ throws ServletException, IOException {
+ OnapLoggingContext loggingContext = OnapLoggingUtils.getLoggingContextForRequest(request, baseLoggingContext);
setLoggingContext(loggingContext, "doGet", "PAP.get");
loggingContext.metricStarted();
- XACMLRest.dumpRequest(request);
+ XacmlRest.dumpRequest(request);
loggingContext.metricEnded();
PolicyLogger.metrics("XACMLPapServlet doGet dumpRequest");
String pathInfo = request.getRequestURI();
@@ -831,23 +807,12 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList
im.startTransaction();
loggingContext.metricEnded();
PolicyLogger.metrics("XACMLPapServlet doGet 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, ae);
- PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message);
- loggingContext.transactionEnded();
- PolicyLogger.audit("Transaction Failed - See Error.log");
- setResponseError(response, 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, se);
+ } catch (IntegrityMonitorException ime) {
+ String message =
+ "GET interface called for PAP " + papResourceName + " but it has an Administrative state of "
+ + im.getStateManager().getAdminState() + " and a Standby Status of "
+ + im.getStateManager().getStandbyStatus() + "\n Exception Message: " + ime.getMessage();
+ LOGGER.info(message, ime);
PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message);
loggingContext.transactionEnded();
PolicyLogger.audit("Transaction Failed - See Error.log");
@@ -873,7 +838,7 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList
return;
} else {
String message =
- "PEP not Authorized for making this Request!! \n Contact Administrator for this Scope. ";
+ "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");
@@ -888,8 +853,7 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList
// this is from the Admin Console, so handle separately
try {
loggingContext.metricStarted();
- getAcServiceInstance().doAcGet(request, response, groupId, loggingContext,
- papEngine);
+ getAcServiceInstance().doAcGet(request, response, groupId, loggingContext, papEngine);
loggingContext.metricEnded();
PolicyLogger.metrics("XACMLPapServlet doGet doACGet");
} catch (IOException e) {
@@ -913,8 +877,7 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList
// Is it known?
if (pdp == null) {
// Check if request came from localhost
- if ("localhost".equals(request.getRemoteHost())
- || request.getRemoteHost().equals(request.getLocalAddr())) {
+ if ("localhost".equals(request.getRemoteHost()) || request.getRemoteHost().equals(request.getLocalAddr())) {
// Return status information - basically all the groups
loggingContext.setServiceName("PAP.getGroups");
Set<OnapPDPGroup> groups = null;
@@ -922,12 +885,10 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList
groups = papEngine.getOnapPDPGroups();
} catch (PAPException e) {
LOGGER.debug(e);
- PolicyLogger.error(MessageCodes.ERROR_UNKNOWN, e, "XACMLPapServlet",
- " GET exception");
+ PolicyLogger.error(MessageCodes.ERROR_UNKNOWN, e, "XACMLPapServlet", " GET exception");
loggingContext.transactionEnded();
PolicyLogger.audit("Transaction Failed - See Error.log");
- setResponseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
- e.getMessage());
+ setResponseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
im.endTransaction();
return;
}
@@ -940,8 +901,8 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList
im.endTransaction();
return;
}
- String message = "Unknown PDP: " + id + " from " + request.getRemoteHost() + " us: "
- + request.getLocalAddr();
+ 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");
@@ -988,15 +949,15 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList
return;
}
try {
- LOGGER.warn("PolicyDebugging: Policy Validity: " + policy.isValid() + "\n "
- + "Policy Name : " + policy.getName() + "\n Policy URI: "
- + policy.getLocation().toString());
+ LOGGER.warn("PolicyDebugging: Policy Validity: " + policy.isValid() + "\n " + "Policy Name : "
+ + policy.getName() + "\n Policy URI: " + policy.getLocation().toString());
} catch (PAPException | IOException e) {
LOGGER.error(e);
}
- try (InputStream is = new FileInputStream(
- ((StdPDPGroup) group).getDirectory().toString() + File.separator + policyId);
- OutputStream os = response.getOutputStream()) {
+ 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);
@@ -1021,9 +982,8 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList
*/
@Override
protected void doPut(HttpServletRequest request, HttpServletResponse response)
- throws ServletException, IOException {
- ONAPLoggingContext loggingContext =
- ONAPLoggingUtils.getLoggingContextForRequest(request, baseLoggingContext);
+ throws ServletException, IOException {
+ OnapLoggingContext loggingContext = OnapLoggingUtils.getLoggingContextForRequest(request, baseLoggingContext);
setLoggingContext(loggingContext, "doPut", "PAP.put");
try {
loggingContext.metricStarted();
@@ -1031,19 +991,10 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList
loggingContext.metricEnded();
PolicyLogger.metrics("XACMLPapServlet doPut im startTransaction");
} catch (IntegrityMonitorException e) {
- String message = "PUT interface called for PAP " + papResourceName;
- if (e instanceof AdministrativeStateException) {
- message += " but it has an Administrative state of "
- + im.getStateManager().getAdminState();
- } else if (e instanceof StandbyStatusException) {
- message += " but it has a Standby Status of "
- + im.getStateManager().getStandbyStatus();
- } else {
- message += " but an exception occurred";
-
- }
- message += "\n Exception Message: " + e.getMessage();
-
+ String message =
+ "PUT interface called for PAP " + papResourceName + " but it has an Administrative state of "
+ + im.getStateManager().getAdminState() + " and a Standby Status of "
+ + im.getStateManager().getStandbyStatus() + "\n Exception Message: " + e.getMessage();
LOGGER.info(message, e);
PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message);
loggingContext.transactionEnded();
@@ -1057,7 +1008,7 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList
String apiflag = request.getParameter("apiflag");
// For Debug purposes
if (!"api".equals(apiflag) && PolicyLogger.isDebugEnabled()) {
- XACMLRest.dumpRequest(request);
+ XacmlRest.dumpRequest(request);
PolicyLogger.metrics("XACMLPapServlet doPut dumpRequest");
}
loggingContext.metricEnded();
@@ -1078,11 +1029,9 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList
}
loggingContext.metricStarted();
LOGGER.info("XACMLPapServlet: Calling PolicyDBDao to handlIncomingHttpNotification");
- HandleIncomingNotifications handleIncomingNotifications =
- new HandleIncomingNotifications();
+ HandleIncomingNotifications handleIncomingNotifications = new HandleIncomingNotifications();
handleIncomingNotifications.handleIncomingHttpNotification(policyDBDaoRequestUrl,
- policyDBDaoRequestEntityId, policyDBDaoRequestEntityType,
- policyDBDaoRequestExtraData, this);
+ policyDBDaoRequestEntityId, policyDBDaoRequestEntityType, policyDBDaoRequestExtraData, this);
loggingContext.metricEnded();
PolicyLogger.metrics("XACMLPapServlet doPut handle incoming http notification");
response.setStatus(200);
@@ -1110,7 +1059,7 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList
return;
} else {
String message =
- "PEP not Authorized for making this Request!! \n Contact Administrator for this Scope. ";
+ "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");
@@ -1148,7 +1097,7 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList
if (apiflag != null) {
if (!authorizeRequest(request)) {
String message =
- "PEP not Authorized for making this Request!! \n Contact Administrator for this Scope. ";
+ "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");
@@ -1170,8 +1119,7 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList
// this is from the Admin Console, so handle separately
try {
loggingContext.metricEnded();
- getAcServiceInstance().doAcPut(request, response, groupId, loggingContext,
- papEngine);
+ getAcServiceInstance().doAcPut(request, response, groupId, loggingContext, papEngine);
loggingContext.metricEnded();
PolicyLogger.metrics("XACMLPapServlet goPut doACPut");
} catch (IOException e) {
@@ -1228,12 +1176,10 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList
}
// 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");
+ LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Request does not have groupId or apiflag");
loggingContext.transactionEnded();
PolicyLogger.audit("Transaction Failed - See Error.log");
- setResponseError(response, HttpServletResponse.SC_BAD_REQUEST,
- "Request does not have groupId or apiflag");
+ setResponseError(response, HttpServletResponse.SC_BAD_REQUEST, "Request does not have groupId or apiflag");
loggingContext.transactionEnded();
PolicyLogger.audit("Transaction Failed - See error.log");
im.endTransaction();
@@ -1244,32 +1190,20 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList
*/
@Override
protected void doDelete(HttpServletRequest request, HttpServletResponse response)
- throws ServletException, IOException {
- ONAPLoggingContext loggingContext =
- ONAPLoggingUtils.getLoggingContextForRequest(request, baseLoggingContext);
+ throws ServletException, IOException {
+ OnapLoggingContext loggingContext = OnapLoggingUtils.getLoggingContextForRequest(request, baseLoggingContext);
setLoggingContext(loggingContext, "doDelete", "PAP.delete");
try {
loggingContext.metricStarted();
im.startTransaction();
loggingContext.metricEnded();
PolicyLogger.metrics("XACMLPapServlet doDelete 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, ae);
- PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message);
- loggingContext.transactionEnded();
- PolicyLogger.audit("Transaction Failed - See Error.log");
- setResponseError(response, 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);
+ } catch (IntegrityMonitorException ime) {
+ String message =
+ "DELETE interface called for PAP " + papResourceName + " but it has an Administrative state of "
+ + im.getStateManager().getAdminState() + " and a Standby Status of "
+ + im.getStateManager().getStandbyStatus() + "\n Exception Message: " + ime.getMessage();
+ LOGGER.info(message, ime);
PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message);
loggingContext.transactionEnded();
PolicyLogger.audit("Transaction Failed - See Error.log");
@@ -1277,7 +1211,7 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList
return;
}
loggingContext.metricStarted();
- XACMLRest.dumpRequest(request);
+ XacmlRest.dumpRequest(request);
loggingContext.metricEnded();
PolicyLogger.metrics("XACMLPapServlet doDelete dumpRequest");
String groupId = request.getParameter(GROUPID);
@@ -1287,7 +1221,7 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList
if (apiflag != null) {
if (!authorizeRequest(request)) {
String message =
- "PEP not Authorized for making this Request!! \n Contact Administrator for this Scope. ";
+ "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");
@@ -1311,8 +1245,7 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList
// this is from the Admin Console, so handle separately
try {
loggingContext.metricStarted();
- getAcServiceInstance().doAcDelete(request, response, groupId, loggingContext,
- papEngine);
+ getAcServiceInstance().doAcDelete(request, response, groupId, loggingContext, papEngine);
loggingContext.metricEnded();
PolicyLogger.metrics("XACMLPapServlet doDelete doACDelete");
} catch (IOException e) {
@@ -1327,20 +1260,16 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList
PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " Request does not have groupId");
loggingContext.transactionEnded();
PolicyLogger.audit("Transaction Failed - See Error.log");
- setResponseError(response, HttpServletResponse.SC_BAD_REQUEST,
- "Request does not have groupId");
+ setResponseError(response, HttpServletResponse.SC_BAD_REQUEST, "Request does not have groupId");
im.endTransaction();
}
- private boolean isPDPCurrent(Properties policies, Properties pipconfig,
- Properties pdpProperties) {
+ private boolean isPDPCurrent(Properties policies, Properties pipconfig, Properties pdpProperties) {
String localRootPolicies = policies.getProperty(XACMLProperties.PROP_ROOTPOLICIES);
- String localReferencedPolicies =
- policies.getProperty(XACMLProperties.PROP_REFERENCEDPOLICIES);
+ 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);
+ 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
@@ -1350,9 +1279,8 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList
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)) {
+ && localReferencedPolicies.equals(pdpPolicies.getProperty(XACMLProperties.PROP_REFERENCEDPOLICIES))
+ && pdpPipConfig.equals(pipconfig)) {
// The PDP is current
return true;
}
@@ -1363,13 +1291,13 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList
// 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");
+ PolicyLogger.error(MessageCodes.ERROR_SCHEMA_INVALID, e, "XACMLPapServlet", " PDP Error");
}
return false;
}
- private void populatePolicyURL(StringBuffer urlPath, Properties policies) {
+ @VisibleForTesting
+ protected 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);
@@ -1385,7 +1313,7 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList
}
protected String getPDPID(HttpServletRequest request) {
- String pdpURL = request.getHeader(XACMLRestProperties.PROP_PDP_HTTP_HEADER_ID);
+ 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");
@@ -1395,11 +1323,11 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList
}
protected String getPDPJMX(HttpServletRequest request) {
- String pdpJMMX = request.getHeader(XACMLRestProperties.PROP_PDP_HTTP_HEADER_JMX_PORT);
+ 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");
+ + "PDP did not send custom header for JMX Port so the value of 0 is assigned");
return null;
}
return pdpJMMX;
@@ -1415,9 +1343,9 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList
* @throws ServletException
* @throws IOException
*/
- public void updateGroupsFromAPI(HttpServletRequest request, HttpServletResponse response,
- String groupId, ONAPLoggingContext loggingContext) throws IOException {
- PolicyDBDaoTransaction acPutTransaction = policyDbDao.getNewTransaction();
+ public void updateGroupsFromAPI(HttpServletRequest request, HttpServletResponse response, String groupId,
+ OnapLoggingContext loggingContext) throws IOException {
+ PolicyDbDaoTransaction acPutTransaction = policyDbDao.getNewTransaction();
PolicyLogger.audit("PolicyDBDaoTransaction started for updateGroupsFromAPI");
try {
String userId = request.getParameter("userId");
@@ -1443,7 +1371,7 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList
LOGGER.info("Removing old version of the policy");
for (PDPPolicy existingPolicy : group.getPolicies()) {
if (existingPolicy.getName().equals(policy.getName())
- && !existingPolicy.getId().equals(policy.getId())) {
+ && !existingPolicy.getId().equals(policy.getId())) {
group.removePolicy(existingPolicy);
LOGGER.info("Removing policy: " + existingPolicy);
break;
@@ -1456,7 +1384,7 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList
acPutTransaction.updateGroup(group, "XACMLPapServlet.doACPut", userId);
} catch (Exception e) {
PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet",
- " Error while updating group in the database: " + "group=" + group.getId());
+ " Error while updating group in the database: " + "group=" + group.getId());
throw new PAPException(e.getMessage());
}
@@ -1489,8 +1417,8 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList
loggingContext.transactionEnded();
LOGGER.info("Success");
- if (policy != null && ((policy.getId().contains("Config_MS_"))
- || (policy.getId().contains("BRMS_Param")))) {
+ if (policy != null
+ && ((policy.getId().contains("Config_MS_")) || (policy.getId().contains("BRMS_Param")))) {
PushPolicyHandler pushPolicyHandler = PushPolicyHandler.getInstance();
if (pushPolicyHandler.preSafetyCheck(policy, configHome)) {
LOGGER.debug("Precheck Successful.");
@@ -1501,14 +1429,12 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList
return;
} catch (PAPException e) {
acPutTransaction.rollbackTransaction();
- PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet",
- " API PUT exception");
+ 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.";
- setResponseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
- e.getMessage());
+ + "Exception in request to update group from API - See Error.log on on the PAP.";
+ setResponseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
response.addHeader("error", ADD_GROUP_ERROR);
response.addHeader("message", message);
@@ -1550,26 +1476,22 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList
try {
groups = papEngine.getOnapPDPGroups();
} catch (PAPException e) {
- PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet",
- " getPDPGroups failed");
- throw new IllegalAccessError(
- XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Unable to get Groups: " + e);
+ PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " getPDPGroups failed");
+ throw new IllegalAccessError(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Unable to get Groups: " + e);
}
for (OnapPDPGroup group : groups) {
groupChanged(group);
}
}
- public void changed(ONAPLoggingContext loggingContext) {
+ public void changed(OnapLoggingContext loggingContext) {
// all PDPs in all groups need to be updated/sync'd
Set<OnapPDPGroup> groups;
try {
groups = papEngine.getOnapPDPGroups();
} catch (PAPException e) {
- PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet",
- " getPDPGroups failed");
- throw new IllegalAccessError(
- XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Unable to get Groups: " + e);
+ PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " getPDPGroups failed");
+ throw new IllegalAccessError(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Unable to get Groups: " + e);
}
for (OnapPDPGroup group : groups) {
groupChanged(group, loggingContext);
@@ -1584,7 +1506,7 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList
}
}
- public void groupChanged(OnapPDPGroup group, ONAPLoggingContext loggingContext) {
+ public void groupChanged(OnapPDPGroup group, OnapLoggingContext loggingContext) {
// all PDPs within one group need to be updated/sync'd
for (OnapPDP pdp : group.getOnapPdps()) {
pdpChanged(pdp, loggingContext, getPdpDataByGroup(group));
@@ -1604,7 +1526,7 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList
}
}
- public void pdpChanged(OnapPDP pdp, ONAPLoggingContext loggingContext) {
+ public void pdpChanged(OnapPDP pdp, OnapLoggingContext loggingContext) {
// 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)
@@ -1623,8 +1545,7 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList
}
}
- private void pdpChanged(OnapPDP pdp, ONAPLoggingContext loggingContext,
- List<Properties> pdpDataByGroup) {
+ private void pdpChanged(OnapPDP pdp, OnapLoggingContext loggingContext, List<Properties> pdpDataByGroup) {
Thread t = new Thread(new UpdatePdpThread(pdp, loggingContext, pdpDataByGroup));
if (CheckPDP.validateID(pdp.getId())) {
t.start();
@@ -1641,8 +1562,7 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList
return dataToNotify.setPolicyConfigProperties(pdp, papEngine);
}
- private void testService(ONAPLoggingContext loggingContext, HttpServletResponse response)
- throws IOException {
+ private void testService(OnapLoggingContext loggingContext, HttpServletResponse response) throws IOException {
LOGGER.info("Test request received");
try {
im.evaluateSanity();
@@ -1653,8 +1573,7 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList
PolicyLogger.audit("Transaction Failed - See Error.log");
response.setStatus(HttpServletResponse.SC_OK);
return;
- } catch (ForwardProgressException | AdministrativeStateException
- | StandbyStatusException e) {
+ } catch (ForwardProgressException | AdministrativeStateException | StandbyStatusException e) {
String submsg;
if (e instanceof ForwardProgressException) {
submsg = " is not making forward progress.";
@@ -1664,8 +1583,8 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList
submsg = " Standby Status is NOT PROVIDING SERVICE.";
}
- String message = "GET:/pap/test called and PAP " + papResourceName + submsg
- + " Exception Message: " + e.getMessage();
+ String message =
+ "GET:/pap/test called and PAP " + papResourceName + submsg + " Exception Message: " + e.getMessage();
LOGGER.info(message, e);
PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message);
loggingContext.transactionEnded();
@@ -1679,8 +1598,8 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList
if (eMsg == null) {
eMsg = "No Exception Message";
}
- String message = "GET:/pap/test called and PAP " + papResourceName
- + " has had a subsystem failure." + " Exception Message: " + eMsg;
+ String message = "GET:/pap/test called and PAP " + papResourceName + " has had a subsystem failure."
+ + " Exception Message: " + eMsg;
LOGGER.info(message, e);
PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message);
loggingContext.transactionEnded();
@@ -1705,18 +1624,16 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList
}
}
- private void setLoggingContext(ONAPLoggingContext loggingContext, String methodType,
- String serviceName) {
+ private void setLoggingContext(OnapLoggingContext loggingContext, String methodType, String serviceName) {
loggingContext.transactionStarted();
loggingContext.setServiceName(serviceName);
- if (loggingContext.getRequestID() == null || "".equals(loggingContext.getRequestID())) {
+ if (loggingContext.getRequestId() == null || "".equals(loggingContext.getRequestId())) {
UUID requestID = UUID.randomUUID();
- loggingContext.setRequestID(requestID.toString());
- PolicyLogger.info("requestID not provided in call to XACMLPapServlet ('" + methodType
- + "') so we generated one");
+ loggingContext.setRequestId(requestID.toString());
+ PolicyLogger
+ .info("requestID not provided in call to XACMLPapServlet ('" + methodType + "') so we generated one");
} else {
- PolicyLogger.info(
- "requestID was provided in call to XACMLPapServlet ('" + methodType + "')");
+ PolicyLogger.info("requestID was provided in call to XACMLPapServlet ('" + methodType + "')");
}
}
@@ -1731,14 +1648,12 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList
private static void loadWebapps() throws PAPException {
if (actionHome == null || configHome == null) {
- Path webappsPath =
- Paths.get(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_WEBAPPS));
+ 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);
+ 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");
@@ -1747,17 +1662,15 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList
Files.createDirectories(webappsPathConfig);
} catch (IOException e) {
PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet",
- "Failed to create config directory: "
- + webappsPathConfig.toAbsolutePath().toString());
+ "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 action directory: "
- + webappsPathAction.toAbsolutePath().toString(), e);
+ LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Failed to create action directory: "
+ + webappsPathAction.toAbsolutePath().toString(), e);
}
}
actionHome = webappsPathAction.toString();
@@ -1809,7 +1722,7 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList
return papEngine;
}
- public static PolicyDBDaoTransaction getDbDaoTransaction() {
+ public static PolicyDbDaoTransaction getDbDaoTransaction() {
return policyDbDao.getNewTransaction();
}
@@ -1861,11 +1774,11 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList
XACMLPapServlet.msPolicyName = msPolicyName;
}
- public ONAPLoggingContext getBaseLoggingContext() {
+ public OnapLoggingContext getBaseLoggingContext() {
return baseLoggingContext;
}
- public void setBaseLoggingContext(ONAPLoggingContext baseLoggingContext) {
+ public void setBaseLoggingContext(OnapLoggingContext baseLoggingContext) {
this.baseLoggingContext = baseLoggingContext;
}
}
diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/adapters/SearchData.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/adapters/SearchData.java
index 45c46cb5b..be13c542a 100644
--- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/adapters/SearchData.java
+++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/adapters/SearchData.java
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP-PAP-REST
* ================================================================================
- * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2018-2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -17,6 +17,7 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.policy.pap.xacml.rest.adapters;
public class SearchData {
@@ -31,70 +32,92 @@ public class SearchData {
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;
}
-} \ No newline at end of file
+}
diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/adapters/UpdateObjectData.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/adapters/UpdateObjectData.java
index aa59868fe..ead403a02 100644
--- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/adapters/UpdateObjectData.java
+++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/adapters/UpdateObjectData.java
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP-PAP-REST
* ================================================================================
- * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2018-2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -17,6 +17,7 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.policy.pap.xacml.rest.adapters;
public class UpdateObjectData {
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
index 780ed86c7..c4076b2ad 100644
--- 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
@@ -21,6 +21,7 @@
package org.onap.policy.pap.xacml.rest.components;
import com.att.research.xacml.api.pap.PAPException;
+
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
@@ -32,6 +33,7 @@ import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
+
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;
@@ -47,6 +49,7 @@ 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.eelf.MessageCodes;
import org.onap.policy.common.logging.eelf.PolicyLogger;
import org.onap.policy.common.logging.flexlogger.FlexLogger;
@@ -82,7 +85,6 @@ public class ActionPolicy extends Policy {
List<String> dynamicFieldOneRuleAlgorithms = new LinkedList<>();
List<String> dynamicFieldTwoRuleAlgorithms = new LinkedList<>();
-
private CommonClassDao commonClassDao;
private static boolean isAttribute = false;
@@ -360,7 +362,6 @@ public class ActionPolicy extends Policy {
return obligations;
}
-
// if compound setting the inner apply here
protected ApplyType getInnerActionApply(String value1Label) {
ApplyType actionApply = new ApplyType();
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
index 8ca4dfa01..233add1ad 100644
--- 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
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP-PAP-REST
* ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017, 2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -20,6 +20,9 @@
package org.onap.policy.pap.xacml.rest.components;
+import com.att.research.xacml.api.pap.PAPException;
+import com.att.research.xacml.std.IdentifierImpl;
+
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
@@ -32,16 +35,6 @@ 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.api.pap.PAPException;
-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;
@@ -56,6 +49,13 @@ 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;
+
public class ClosedLoopPolicy extends Policy {
private static final Logger LOGGER = FlexLogger.getLogger(ClosedLoopPolicy.class);
@@ -68,7 +68,7 @@ public class ClosedLoopPolicy extends Policy {
this.policyAdapter = policyAdapter;
}
- //save configuration of the policy based on the policyname
+ // save configuration of the policy based on the policyname
private void saveConfigurations(String policyName, String jsonBody) {
if (policyName.endsWith(".xml")) {
@@ -76,7 +76,7 @@ public class ClosedLoopPolicy extends Policy {
}
try (PrintWriter out = new PrintWriter(CONFIG_HOME + File.separator + policyName + ".json")) {
String body = jsonBody;
- //Remove the trapMaxAge in Verification Signature
+ // Remove the trapMaxAge in Verification Signature
body = body.replace(",\"trapMaxAge\":null", "");
this.policyAdapter.setJsonBody(body);
out.println(body);
@@ -85,7 +85,7 @@ public class ClosedLoopPolicy extends Policy {
}
}
- //Utility to read json data from the existing file to a string
+ // 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));
@@ -93,7 +93,7 @@ public class ClosedLoopPolicy extends Policy {
}
- //create the configuration file based on the policy name on adding the extension as .json
+ // 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")) {
@@ -124,13 +124,13 @@ public class ClosedLoopPolicy extends Policy {
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
+ // 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 PAPException {
if (isPreparedToSave()) {
- //we have already done this
+ // we have already done this
return true;
}
@@ -176,17 +176,13 @@ public class ClosedLoopPolicy extends Policy {
// Match for Onap
allOf.getMatch().add(createMatch("ONAPName", policyAdapter.getOnapName()));
// Match for riskType
- allOf.getMatch().add(
- createDynamicMatch("RiskType", policyAdapter.getRiskType()));
+ allOf.getMatch().add(createDynamicMatch("RiskType", policyAdapter.getRiskType()));
// Match for riskLevel
- allOf.getMatch().add(
- createDynamicMatch("RiskLevel", String.valueOf(policyAdapter.getRiskLevel())));
+ allOf.getMatch().add(createDynamicMatch("RiskLevel", String.valueOf(policyAdapter.getRiskLevel())));
// Match for riskguard
- allOf.getMatch().add(
- createDynamicMatch("guard", policyAdapter.getGuard()));
+ allOf.getMatch().add(createDynamicMatch("guard", policyAdapter.getGuard()));
// Match for ttlDate
- allOf.getMatch().add(
- createDynamicMatch("TTLDate", policyAdapter.getTtlDate()));
+ allOf.getMatch().add(createDynamicMatch("TTLDate", policyAdapter.getTtlDate()));
AnyOfType anyOf = new AnyOfType();
anyOf.getAllOf().add(allOfOne);
@@ -340,7 +336,7 @@ public class ClosedLoopPolicy extends Policy {
advice.getAttributeAssignmentExpression().add(assignment5);
- //Risk Attributes
+ // Risk Attributes
AttributeAssignmentExpressionType assignment6 = new AttributeAssignmentExpressionType();
assignment6.setAttributeId("RiskType");
assignment6.setCategory(CATEGORY_RESOURCE);
@@ -389,7 +385,6 @@ public class ClosedLoopPolicy extends Policy {
advice.getAttributeAssignmentExpression().add(assignment9);
-
advices.getAdviceExpression().add(advice);
return advices;
}
@@ -399,5 +394,4 @@ public class ClosedLoopPolicy extends Policy {
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
index d6b09086a..1cab7166a 100644
--- 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
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP-PAP-REST
* ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017, 2019 AT&T Intellectual Property. All rights reserved.
* Modified Copyright (C) 2018 Samsung Electronics Co., Ltd.
* Modified Copyright (C) 2019 Bell Canada.
* ================================================================================
@@ -22,6 +22,9 @@
package org.onap.policy.pap.xacml.rest.components;
+import com.att.research.xacml.api.pap.PAPException;
+import com.att.research.xacml.std.IdentifierImpl;
+
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
@@ -33,17 +36,6 @@ 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 org.onap.policy.utils.PolicyUtils;
-
-import com.att.research.xacml.api.pap.PAPException;
-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;
@@ -58,6 +50,14 @@ 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.onap.policy.utils.PolicyUtils;
+
public class ConfigPolicy extends Policy {
/**
@@ -93,7 +93,6 @@ public class ConfigPolicy extends Policy {
}
}
-
// Here we are adding the extension for the configurations file based on the
// config type selection for saving.
private String getConfigFile(String filename) {
@@ -103,8 +102,7 @@ public class ConfigPolicy extends Policy {
if (id == null) {
return filename;
}
- switch (id.toUpperCase())
- {
+ switch (id.toUpperCase()) {
case JSON_CONFIG:
return filename + ".json";
case XML_CONFIG:
@@ -127,7 +125,6 @@ public class ConfigPolicy extends Policy {
return filename;
}
-
// Validations for Config form
/*
* FORM VALIDATION WILL BE DONE BY THE PAP-ADMIN before creating JSON object...
@@ -181,7 +178,7 @@ public class ConfigPolicy extends Policy {
}
if (!isPreparedToSave()) {
- //Prep and configure the policy for saving
+ // Prep and configure the policy for saving
prepareToSave();
}
@@ -192,8 +189,8 @@ public class ConfigPolicy extends Policy {
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
+ // 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 PAPException {
@@ -441,7 +438,7 @@ public class ConfigPolicy extends Policy {
}
}
- //Risk Attributes
+ // Risk Attributes
AttributeAssignmentExpressionType assignment8 = new AttributeAssignmentExpressionType();
assignment8.setAttributeId("RiskType");
assignment8.setCategory(CATEGORY_RESOURCE);
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
index 9809ad498..2151a1988 100644
--- 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
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP-PAP-REST
* ================================================================================
- * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -17,6 +17,7 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.policy.pap.xacml.rest.components;
import java.util.HashMap;
@@ -26,7 +27,7 @@ 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.BrmsParamTemplate;
import org.onap.policy.rest.jpa.UserInfo;
import org.onap.policy.utils.PolicyUtils;
import org.springframework.beans.factory.annotation.Autowired;
@@ -34,26 +35,28 @@ import org.springframework.stereotype.Service;
@Service
public class CreateBRMSRuleTemplate {
- private static final Logger LOGGER = FlexLogger.getLogger(CreateBRMSRuleTemplate.class);
+ private static final Logger LOGGER = FlexLogger.getLogger(CreateBRMSRuleTemplate.class);
private static CommonClassDao commonClassDao;
@Autowired
- public CreateBRMSRuleTemplate(CommonClassDao commonClassDao){
+ public CreateBRMSRuleTemplate(CommonClassDao commonClassDao) {
CreateBRMSRuleTemplate.commonClassDao = commonClassDao;
}
- public CreateBRMSRuleTemplate() {}
+ public CreateBRMSRuleTemplate() {
+ }
public Map<String, String> addRule(String rule, String ruleName, String description, String userID) {
- Map<String,String> responseMap = new HashMap<>();
- if(rule!=null && !PolicyUtils.brmsRawValidate(rule).contains("[ERR")){
- List<Object> duplicateData = commonClassDao.checkDuplicateEntry(ruleName, "ruleName", BRMSParamTemplate.class);
- if(duplicateData!=null && !duplicateData.isEmpty()){
+ Map<String, String> responseMap = new HashMap<>();
+ if (rule != null && !PolicyUtils.brmsRawValidate(rule).contains("[ERR")) {
+ List<Object> 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();
+ } else {
+ BrmsParamTemplate brmsParamTemplate = new BrmsParamTemplate();
brmsParamTemplate.setDescription(description);
brmsParamTemplate.setRuleName(ruleName);
brmsParamTemplate.setRule(rule);
@@ -63,7 +66,7 @@ public class CreateBRMSRuleTemplate {
LOGGER.info("Template created with " + ruleName + " by " + userID);
}
responseMap.put("success", "success");
- }else{
+ } else {
LOGGER.debug("Error during validating the rule for creating record for BRMS Param Template");
responseMap.put("error", "VALIDATION");
}
@@ -73,8 +76,8 @@ public class CreateBRMSRuleTemplate {
public static boolean validateRuleParams(String rule) {
CreateBrmsParamPolicy policy = new CreateBrmsParamPolicy();
Map<String, String> paramValues = policy.findType(rule);
- for(String key : paramValues.keySet()) {
- if(!PolicyUtils.SUCCESS.equals(PolicyUtils.policySpecialCharValidator(key))){
+ for (String key : paramValues.keySet()) {
+ if (!PolicyUtils.SUCCESS.equals(PolicyUtils.policySpecialCharValidator(key))) {
return false;
}
}
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
index 6a0c92650..ffb902bc4 100644
--- 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
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP-PAP-REST
* ================================================================================
- * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -20,6 +20,9 @@
package org.onap.policy.pap.xacml.rest.components;
+import com.att.research.xacml.api.pap.PAPException;
+import com.att.research.xacml.std.IdentifierImpl;
+import com.google.common.annotations.VisibleForTesting;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
@@ -38,22 +41,7 @@ import java.util.Map.Entry;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
-
import javax.script.SimpleBindings;
-
-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.api.pap.PAPException;
-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;
@@ -67,6 +55,15 @@ 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.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;
public class CreateBrmsParamPolicy extends Policy {
@@ -91,19 +88,18 @@ public class CreateBrmsParamPolicy extends Policy {
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.
+ // Finding all the keys in the Map data-structure.
Iterator<String> iterator = copyMap.keySet().iterator();
Pattern p;
Matcher m;
while (iterator.hasNext()) {
- //Converting the first character of the key into a lower case.
+ // 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.
+ 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.
+ // Replacing the value with the inputs provided by the user in the editor.
String finalInput = copyMap.get(input);
if (finalInput.contains("$")) {
finalInput = finalInput.replace("$", "\\$");
@@ -113,7 +109,6 @@ public class CreateBrmsParamPolicy extends Policy {
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));
@@ -133,11 +128,10 @@ public class CreateBrmsParamPolicy extends Policy {
out.close();
} catch (Exception e) {
PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "CreateBrmsParamPolicy",
- "Exception saving configuration file");
+ "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) {
@@ -151,6 +145,7 @@ public class CreateBrmsParamPolicy extends Policy {
}
// Validations for Config form
+ @Override
public boolean validateConfigForm() {
// Validating mandatory Fields.
@@ -187,12 +182,12 @@ public class CreateBrmsParamPolicy extends Policy {
private String getValueFromDictionary(String templateName) {
String ruleTemplate = null;
CommonClassDaoImpl dbConnection = new CommonClassDaoImpl();
- String queryString = "from BRMSParamTemplate where param_template_name= :templateName";
+ String queryString = "from BrmsParamTemplate where param_template_name= :templateName";
SimpleBindings params = new SimpleBindings();
params.put("templateName", templateName);
List<Object> result = dbConnection.getDataByQuery(queryString, params);
if (!result.isEmpty()) {
- BRMSParamTemplate template = (BRMSParamTemplate) result.get(0);
+ BrmsParamTemplate template = (BrmsParamTemplate) result.get(0);
ruleTemplate = template.getRule();
}
return ruleTemplate;
@@ -222,8 +217,7 @@ public class CreateBrmsParamPolicy extends Policy {
if (line.contains("*/")) {
try {
comment = false;
- line = line.split("\\/\\*")[0]
- + line.split("\\*\\/")[1].replace("*/", "");
+ line = line.split("\\/\\*")[0] + line.split("\\*\\/")[1].replace("*/", "");
} catch (Exception e) {
LOGGER.debug(e);
line = line.split("\\/\\*")[0];
@@ -255,8 +249,8 @@ public class CreateBrmsParamPolicy extends Policy {
break;
}
}
- String param = params.toString().replace("declare Params", "").replace("end", "")
- .replaceAll("\\s+", "");
+ String param =
+ params.toString().replace("declare Params", "").replace("end", "").replaceAll("\\s+", "");
String[] components = param.split(":");
String caption = "";
for (int i = 0; i < components.length; i++) {
@@ -274,7 +268,7 @@ public class CreateBrmsParamPolicy extends Policy {
LOGGER.debug(e);
nextComponent = components[i];
}
- //If the type is of type String then we add the UI Item and type to the map.
+ // 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);
@@ -287,7 +281,7 @@ public class CreateBrmsParamPolicy extends Policy {
}
} catch (Exception e) {
PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "CreateBrmsParamPolicy",
- "Exception parsing file in findType");
+ "Exception parsing file in findType");
}
}
return mapFieldType;
@@ -330,10 +324,8 @@ public class CreateBrmsParamPolicy extends Policy {
StringBuilder body = new StringBuilder();
try {
- body.append(
- "/* Autogenerated Code Please Don't change/remove this comment section. This is for the UI " +
- "purpose. \n\t " +
- "<$%BRMSParamTemplate=" + templateValue + "%$> \n");
+ body.append("/* Autogenerated Code Please Don't change/remove this comment section. This is for the UI "
+ + "purpose. \n\t " + "<$%BRMSParamTemplate=" + templateValue + "%$> \n");
body.append("<%$Values=");
for (Map.Entry<String, String> entry : ruleAndUIValue.entrySet()) {
String uiKey = entry.getKey();
@@ -344,8 +336,8 @@ public class CreateBrmsParamPolicy extends Policy {
body.append("$%> \n*/ \n");
body.append(valueFromDictionary + "\n");
} catch (Exception e) {
- PolicyLogger
- .error(MessageCodes.ERROR_PROCESS_FLOW, e, "CreateBrmsParamPolicy", "Exception saving policy");
+ PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "CreateBrmsParamPolicy",
+ "Exception saving policy");
}
saveConfigurations(policyName, body.toString());
@@ -366,12 +358,10 @@ public class CreateBrmsParamPolicy extends Policy {
String fileName = policyAdapter.getNewFileName();
String name = fileName.substring(fileName.lastIndexOf("\\") + 1);
if ((name == null) || (name.equals(""))) {
- name = fileName.substring(fileName.lastIndexOf("/") + 1
- );
+ name = fileName.substring(fileName.lastIndexOf("/") + 1);
}
allOfOne.getMatch().add(createMatch("PolicyName", name));
-
AllOfType allOf = new AllOfType();
// Match for ONAPName
@@ -415,12 +405,11 @@ public class CreateBrmsParamPolicy extends Policy {
accessURI = new URI(ACTION_ID);
} catch (URISyntaxException e) {
PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "CreateBrmsParamPolicy",
- "Exception creating ACCESS URI");
+ "Exception creating ACCESS URI");
}
accessAttributeDesignator.setCategory(CATEGORY_ACTION);
accessAttributeDesignator.setDataType(STRING_DATATYPE);
- accessAttributeDesignator.setAttributeId(new IdentifierImpl(
- accessURI).stringValue());
+ accessAttributeDesignator.setAttributeId(new IdentifierImpl(accessURI).stringValue());
accessMatch.setAttributeDesignator(accessAttributeDesignator);
accessMatch.setMatchId(FUNCTION_STRING_EQUAL_IGNORE);
@@ -438,7 +427,7 @@ public class CreateBrmsParamPolicy extends Policy {
configURI = new URI(RESOURCE_ID);
} catch (URISyntaxException e) {
PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "CreateBrmsParamPolicy",
- "Exception creating Config URI");
+ "Exception creating Config URI");
}
configAttributeDesignator.setCategory(CATEGORY_RESOURCE);
@@ -459,24 +448,21 @@ public class CreateBrmsParamPolicy extends Policy {
rule.setTarget(targetInRule);
rule.setAdviceExpressions(getAdviceExpressions(version, policyName));
- configPolicy
- .getCombinerParametersOrRuleCombinerParametersOrVariableDefinition()
- .add(rule);
+ configPolicy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition().add(rule);
policyAdapter.setPolicyData(configPolicy);
} else {
- PolicyLogger.error("Unsupported data object."
- + policyAdapter.getData().getClass().getCanonicalName());
+ 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) {
+ @VisibleForTesting
+ protected AdviceExpressionsType getAdviceExpressions(int version, String fileName) {
- //Policy Config ID Assignment
+ // Policy Config ID Assignment
AdviceExpressionsType advices = new AdviceExpressionsType();
AdviceExpressionType advice = new AdviceExpressionType();
advice.setAdviceId("BRMSPARAMID");
@@ -489,8 +475,7 @@ public class CreateBrmsParamPolicy extends Policy {
AttributeValueType configNameAttributeValue = new AttributeValueType();
configNameAttributeValue.setDataType(STRING_DATATYPE);
configNameAttributeValue.getContent().add("Configuration");
- assignment1.setExpression(new ObjectFactory()
- .createAttributeValue(configNameAttributeValue));
+ assignment1.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue));
advice.getAttributeAssignmentExpression().add(assignment1);
// For Config file Url if configurations are provided.
@@ -505,8 +490,7 @@ public class CreateBrmsParamPolicy extends Policy {
String content = CONFIG_URL + "/Config/" + getConfigFile(policyName);
attributeValue.getContent().add(content);
- assignment2.setExpression(new ObjectFactory()
- .createAttributeValue(attributeValue));
+ assignment2.setExpression(new ObjectFactory().createAttributeValue(attributeValue));
advice.getAttributeAssignmentExpression().add(assignment2);
// Policy Name Assignment
@@ -518,15 +502,12 @@ public class CreateBrmsParamPolicy extends Policy {
attributeValue3.setDataType(STRING_DATATYPE);
fileName = FilenameUtils.removeExtension(fileName);
fileName = fileName + ".xml";
- String name = fileName.substring(fileName.lastIndexOf("\\") + 1
- );
+ String name = fileName.substring(fileName.lastIndexOf("\\") + 1);
if ((name == null) || (name.equals(""))) {
- name = fileName.substring(fileName.lastIndexOf("/") + 1
- );
+ name = fileName.substring(fileName.lastIndexOf("/") + 1);
}
attributeValue3.getContent().add(name);
- assignment3.setExpression(new ObjectFactory()
- .createAttributeValue(attributeValue3));
+ assignment3.setExpression(new ObjectFactory().createAttributeValue(attributeValue3));
advice.getAttributeAssignmentExpression().add(assignment3);
// Version Number Assignment
@@ -537,8 +518,7 @@ public class CreateBrmsParamPolicy extends Policy {
AttributeValueType configNameAttributeValue4 = new AttributeValueType();
configNameAttributeValue4.setDataType(STRING_DATATYPE);
configNameAttributeValue4.getContent().add(Integer.toString(version));
- assignment4.setExpression(new ObjectFactory()
- .createAttributeValue(configNameAttributeValue4));
+ assignment4.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue4));
advice.getAttributeAssignmentExpression().add(assignment4);
// Onap Name Assignment
@@ -549,12 +529,10 @@ public class CreateBrmsParamPolicy extends Policy {
AttributeValueType configNameAttributeValue5 = new AttributeValueType();
configNameAttributeValue5.setDataType(STRING_DATATYPE);
configNameAttributeValue5.getContent().add(policyAdapter.getOnapName());
- assignment5.setExpression(new ObjectFactory()
- .createAttributeValue(configNameAttributeValue5));
+ assignment5.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue5));
advice.getAttributeAssignmentExpression().add(assignment5);
-
- //Config Name Assignment
+ // Config Name Assignment
AttributeAssignmentExpressionType assignment6 = new AttributeAssignmentExpressionType();
assignment6.setAttributeId("matching:" + CONFIGID);
assignment6.setCategory(CATEGORY_RESOURCE);
@@ -564,16 +542,15 @@ public class CreateBrmsParamPolicy extends Policy {
configNameAttributeValue6.getContent().add(policyAdapter.getConfigName());
assignment6.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue6));
advice.getAttributeAssignmentExpression().add(assignment6);
- // Adding Controller Information.
+ // Adding Controller Information.
if (policyAdapter.getBrmsController() != null) {
BRMSDictionaryController brmsDicitonaryController = new BRMSDictionaryController();
- advice.getAttributeAssignmentExpression().add(
- createResponseAttributes("controller:" + policyAdapter.getBrmsController(),
- brmsDicitonaryController.getControllerDataByID(policyAdapter.getBrmsController())
- .getController()));
+ advice.getAttributeAssignmentExpression()
+ .add(createResponseAttributes("controller:" + policyAdapter.getBrmsController(),
+ brmsDicitonaryController.getControllerDataByID(policyAdapter.getBrmsController()).getController()));
}
- // Adding Dependencies.
+ // Adding Dependencies.
if (policyAdapter.getBrmsDependency() != null) {
BRMSDictionaryController brmsDicitonaryController = new BRMSDictionaryController();
ArrayList<String> dependencies = new ArrayList<>();
@@ -582,18 +559,18 @@ public class CreateBrmsParamPolicy extends Policy {
dependencies.add(brmsDicitonaryController.getDependencyDataByID(dependencyName).getDependency());
key.append(dependencyName + ",");
}
- advice.getAttributeAssignmentExpression().add(
- createResponseAttributes("dependencies:" + key.toString(), dependencies.toString()));
+ advice.getAttributeAssignmentExpression()
+ .add(createResponseAttributes("dependencies:" + key.toString(), dependencies.toString()));
}
- // Dynamic Field Config Attributes.
+ // Dynamic Field Config Attributes.
Map<String, String> dynamicFieldConfigAttributes = policyAdapter.getDynamicFieldConfigAttributes();
for (Entry<String, String> map : dynamicFieldConfigAttributes.entrySet()) {
advice.getAttributeAssignmentExpression()
- .add(createResponseAttributes("key:" + map.getKey(), map.getValue()));
+ .add(createResponseAttributes("key:" + map.getKey(), map.getValue()));
}
- //Risk Attributes
+ // Risk Attributes
AttributeAssignmentExpressionType assignment8 = new AttributeAssignmentExpressionType();
assignment8.setAttributeId("RiskType");
assignment8.setCategory(CATEGORY_RESOURCE);
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
index efa28b2bb..bb46fd6a9 100644
--- 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
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP-PAP-REST
* ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017, 2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -20,6 +20,8 @@
package org.onap.policy.pap.xacml.rest.components;
+import com.att.research.xacml.api.pap.PAPException;
+import com.att.research.xacml.std.IdentifierImpl;
import java.io.File;
import java.io.IOException;
@@ -34,15 +36,6 @@ 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.api.pap.PAPException;
-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;
@@ -57,6 +50,11 @@ 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.pap.xacml.rest.controller.BRMSDictionaryController;
+import org.onap.policy.rest.adapter.PolicyRestAdapter;
public class CreateBrmsRawPolicy extends Policy {
@@ -76,8 +74,7 @@ public class CreateBrmsRawPolicy extends Policy {
protected void saveConfigurations(String policyName, String jsonBody) {
if (policyName.endsWith(".xml")) {
- policyName = policyName.substring(0,
- policyName.lastIndexOf(".xml"));
+ policyName = policyName.substring(0, policyName.lastIndexOf(".xml"));
}
try (PrintWriter out = new PrintWriter(CONFIG_HOME + File.separator + policyName + ".txt")) {
out.println(jsonBody);
@@ -195,7 +192,6 @@ public class CreateBrmsRawPolicy extends Policy {
}
allOfOne.getMatch().add(createMatch("PolicyName", name));
-
AllOfType allOf = new AllOfType();
// Match for ONAPName
@@ -243,8 +239,7 @@ public class CreateBrmsRawPolicy extends Policy {
}
accessAttributeDesignator.setCategory(CATEGORY_ACTION);
accessAttributeDesignator.setDataType(STRING_DATATYPE);
- accessAttributeDesignator.setAttributeId(new IdentifierImpl(
- accessURI).stringValue());
+ accessAttributeDesignator.setAttributeId(new IdentifierImpl(accessURI).stringValue());
accessMatch.setAttributeDesignator(accessAttributeDesignator);
accessMatch.setMatchId(FUNCTION_STRING_EQUAL_IGNORE);
@@ -267,8 +262,7 @@ public class CreateBrmsRawPolicy extends Policy {
configAttributeDesignator.setCategory(CATEGORY_RESOURCE);
configAttributeDesignator.setDataType(STRING_DATATYPE);
- configAttributeDesignator.setAttributeId(new IdentifierImpl(
- configURI).stringValue());
+ configAttributeDesignator.setAttributeId(new IdentifierImpl(configURI).stringValue());
configMatch.setAttributeDesignator(configAttributeDesignator);
configMatch.setMatchId(FUNCTION_STRING_EQUAL_IGNORE);
@@ -284,22 +278,18 @@ public class CreateBrmsRawPolicy extends Policy {
rule.setTarget(targetInRule);
rule.setAdviceExpressions(getAdviceExpressions(version, policyName));
- configPolicy
- .getCombinerParametersOrRuleCombinerParametersOrVariableDefinition()
- .add(rule);
+ configPolicy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition().add(rule);
policyAdapter.setPolicyData(configPolicy);
} else {
- PolicyLogger.error("Unsupported data object."
- + policyAdapter.getData().getClass().getCanonicalName());
+ 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) {
+ private AdviceExpressionsType getAdviceExpressions(int version, String fileName) {
// Policy Config ID Assignment
AdviceExpressionsType advices = new AdviceExpressionsType();
@@ -314,8 +304,7 @@ public class CreateBrmsRawPolicy extends Policy {
AttributeValueType configNameAttributeValue = new AttributeValueType();
configNameAttributeValue.setDataType(STRING_DATATYPE);
configNameAttributeValue.getContent().add("Configuration");
- assignment1.setExpression(new ObjectFactory()
- .createAttributeValue(configNameAttributeValue));
+ assignment1.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue));
advice.getAttributeAssignmentExpression().add(assignment1);
// For Config file Url if configurations are provided.
@@ -330,8 +319,7 @@ public class CreateBrmsRawPolicy extends Policy {
String content = CONFIG_URL + "/Config/" + getConfigFile(policyName);
AttributeValue.getContent().add(content);
- assignment2.setExpression(new ObjectFactory()
- .createAttributeValue(AttributeValue));
+ assignment2.setExpression(new ObjectFactory().createAttributeValue(AttributeValue));
advice.getAttributeAssignmentExpression().add(assignment2);
// Policy Name Assignment
@@ -350,8 +338,7 @@ public class CreateBrmsRawPolicy extends Policy {
}
System.out.println(name);
attributeValue3.getContent().add(name);
- assignment3.setExpression(new ObjectFactory()
- .createAttributeValue(attributeValue3));
+ assignment3.setExpression(new ObjectFactory().createAttributeValue(attributeValue3));
advice.getAttributeAssignmentExpression().add(assignment3);
// Version Number Assignment
@@ -362,8 +349,7 @@ public class CreateBrmsRawPolicy extends Policy {
AttributeValueType configNameAttributeValue4 = new AttributeValueType();
configNameAttributeValue4.setDataType(STRING_DATATYPE);
configNameAttributeValue4.getContent().add(Integer.toString(version));
- assignment4.setExpression(new ObjectFactory()
- .createAttributeValue(configNameAttributeValue4));
+ assignment4.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue4));
advice.getAttributeAssignmentExpression().add(assignment4);
// Onap Name Assignment
@@ -374,12 +360,10 @@ public class CreateBrmsRawPolicy extends Policy {
AttributeValueType configNameAttributeValue5 = new AttributeValueType();
configNameAttributeValue5.setDataType(STRING_DATATYPE);
configNameAttributeValue5.getContent().add(policyAdapter.getOnapName());
- assignment5.setExpression(new ObjectFactory()
- .createAttributeValue(configNameAttributeValue5));
+ assignment5.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue5));
advice.getAttributeAssignmentExpression().add(assignment5);
-
- //Config Name Assignment
+ // Config Name Assignment
AttributeAssignmentExpressionType assignment6 = new AttributeAssignmentExpressionType();
assignment6.setAttributeId("matching:" + CONFIGID);
assignment6.setCategory(CATEGORY_RESOURCE);
@@ -390,16 +374,15 @@ public class CreateBrmsRawPolicy extends Policy {
assignment6.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue6));
advice.getAttributeAssignmentExpression().add(assignment6);
- // Adding Controller Information.
+ // Adding Controller Information.
if (policyAdapter.getBrmsController() != null) {
BRMSDictionaryController brmsDicitonaryController = new BRMSDictionaryController();
- advice.getAttributeAssignmentExpression().add(
- createResponseAttributes("controller:" + policyAdapter.getBrmsController(),
- brmsDicitonaryController.getControllerDataByID(policyAdapter.getBrmsController())
- .getController()));
+ advice.getAttributeAssignmentExpression().add(createResponseAttributes(
+ "controller:" + policyAdapter.getBrmsController(),
+ brmsDicitonaryController.getControllerDataByID(policyAdapter.getBrmsController()).getController()));
}
- // Adding Dependencies.
+ // Adding Dependencies.
if (policyAdapter.getBrmsDependency() != null) {
BRMSDictionaryController brmsDicitonaryController = new BRMSDictionaryController();
ArrayList<String> dependencies = new ArrayList<>();
@@ -408,11 +391,11 @@ public class CreateBrmsRawPolicy extends Policy {
dependencies.add(brmsDicitonaryController.getDependencyDataByID(dependencyName).getDependency());
key.append(dependencyName).append(",");
}
- advice.getAttributeAssignmentExpression().add(
- createResponseAttributes("dependencies:" + key.toString(), dependencies.toString()));
+ advice.getAttributeAssignmentExpression()
+ .add(createResponseAttributes("dependencies:" + key.toString(), dependencies.toString()));
}
- // Dynamic Field Config Attributes.
+ // Dynamic Field Config Attributes.
Map<String, String> dynamicFieldConfigAttributes = policyAdapter.getDynamicFieldConfigAttributes();
for (Map.Entry<String, String> entry : dynamicFieldConfigAttributes.entrySet()) {
String keyField = entry.getKey();
@@ -420,7 +403,7 @@ public class CreateBrmsRawPolicy extends Policy {
.add(createResponseAttributes("key:" + keyField, entry.getValue()));
}
- //Risk Attributes
+ // Risk Attributes
AttributeAssignmentExpressionType assignment8 = new AttributeAssignmentExpressionType();
assignment8.setAttributeId("RiskType");
assignment8.setCategory(CATEGORY_RESOURCE);
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
index e74cc3359..a980e70d8 100644
--- 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
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP-PAP-REST
* ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017, 2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -20,6 +20,8 @@
package org.onap.policy.pap.xacml.rest.components;
+import com.att.research.xacml.api.pap.PAPException;
+import com.att.research.xacml.std.IdentifierImpl;
import java.io.File;
import java.io.PrintWriter;
@@ -30,16 +32,6 @@ 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.api.pap.PAPException;
-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;
@@ -54,40 +46,47 @@ 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;
+
public class CreateClosedLoopPerformanceMetrics extends Policy {
- private static final Logger LOGGER = FlexLogger.getLogger(CreateClosedLoopPerformanceMetrics.class);
+ private static final Logger LOGGER = FlexLogger.getLogger(CreateClosedLoopPerformanceMetrics.class);
public CreateClosedLoopPerformanceMetrics() {
super();
}
- public CreateClosedLoopPerformanceMetrics(PolicyRestAdapter policyAdapter){
+ public CreateClosedLoopPerformanceMetrics(PolicyRestAdapter policyAdapter) {
this.policyAdapter = policyAdapter;
}
- //save configuration of the policy based on the policyname
+ // save configuration of the policy based on the policyname
private void saveConfigurations(String policyName, final String jsonBody) {
- if(policyName.endsWith(".xml")){
- policyName = policyName.substring(0, policyName.lastIndexOf(".xml"));
- }
- try (PrintWriter out = new PrintWriter(CONFIG_HOME + File.separator + "."+ policyName +".json")){
+ if (policyName.endsWith(".xml")) {
+ policyName = policyName.substring(0, policyName.lastIndexOf(".xml"));
+ }
+ try (PrintWriter out = new PrintWriter(CONFIG_HOME + File.separator + "." + policyName + ".json")) {
out.println(jsonBody);
policyAdapter.setJsonBody(jsonBody);
policyAdapter.setConfigBodyData(jsonBody);
} catch (Exception e) {
- LOGGER.error("Exception Occured"+e);
+ LOGGER.error("Exception Occured" + e);
}
}
- //getting the policy name and setting to configuration on adding .json
+ // 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";
+ filename = filename + ".json";
return filename;
}
@@ -95,13 +94,13 @@ public class CreateClosedLoopPerformanceMetrics extends Policy {
public Map<String, String> savePolicies() throws PAPException {
Map<String, String> successMap = new HashMap<>();
- if(isPolicyExists()){
+ if (isPolicyExists()) {
successMap.put("EXISTS", "This Policy already exist on the PAP");
return successMap;
}
- if(!isPreparedToSave()){
- //Prep and configure the policy for saving
+ if (!isPreparedToSave()) {
+ // Prep and configure the policy for saving
prepareToSave();
}
@@ -109,18 +108,18 @@ public class CreateClosedLoopPerformanceMetrics extends Policy {
Path newPolicyPath = null;
newPolicyPath = Paths.get(policyAdapter.getNewFileName());
- successMap = createPolicy(newPolicyPath,getCorrectPolicyDataObject());
+ 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
+ // 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 PAPException{
+ public boolean prepareToSave() throws PAPException {
- if(isPreparedToSave()){
- //we have already done this
+ if (isPreparedToSave()) {
+ // we have already done this
return true;
}
@@ -148,7 +147,6 @@ public class CreateClosedLoopPerformanceMetrics extends Policy {
policyName = policyName + ".xml";
}
-
PolicyType configPolicy = (PolicyType) policyAdapter.getData();
configPolicy.setDescription(policyAdapter.getPolicyDescription());
@@ -167,17 +165,13 @@ public class CreateClosedLoopPerformanceMetrics extends Policy {
// 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()));
+ allOf.getMatch().add(createDynamicMatch("RiskType", policyAdapter.getRiskType()));
// Match for riskLevel
- allOf.getMatch().add(
- createDynamicMatch("RiskLevel", String.valueOf(policyAdapter.getRiskLevel())));
+ allOf.getMatch().add(createDynamicMatch("RiskLevel", String.valueOf(policyAdapter.getRiskLevel())));
// Match for riskguard
- allOf.getMatch().add(
- createDynamicMatch("guard", policyAdapter.getGuard()));
+ allOf.getMatch().add(createDynamicMatch("guard", policyAdapter.getGuard()));
// Match for ttlDate
- allOf.getMatch().add(
- createDynamicMatch("TTLDate", policyAdapter.getTtlDate()));
+ allOf.getMatch().add(createDynamicMatch("TTLDate", policyAdapter.getTtlDate()));
// Match for ServiceType
allOf.getMatch().add(createMatch("ServiceType", policyAdapter.getServiceType()));
@@ -210,7 +204,8 @@ public class CreateClosedLoopPerformanceMetrics extends Policy {
try {
accessURI = new URI(ACTION_ID);
} catch (URISyntaxException e) {
- PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "CreateClosedLoopPerformanceMetrics", "Exception creating ACCESS URI");
+ PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "CreateClosedLoopPerformanceMetrics",
+ "Exception creating ACCESS URI");
}
accessAttributeDesignator.setCategory(CATEGORY_ACTION);
accessAttributeDesignator.setDataType(STRING_DATATYPE);
@@ -229,7 +224,8 @@ public class CreateClosedLoopPerformanceMetrics extends Policy {
try {
configURI = new URI(RESOURCE_ID);
} catch (URISyntaxException e) {
- PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "CreateClosedLoopPerformanceMetrics", "Exception creating Config URI");
+ PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "CreateClosedLoopPerformanceMetrics",
+ "Exception creating Config URI");
}
configAttributeDesignator.setCategory(CATEGORY_RESOURCE);
configAttributeDesignator.setDataType(STRING_DATATYPE);
@@ -286,7 +282,7 @@ public class CreateClosedLoopPerformanceMetrics extends Policy {
AttributeValueType AttributeValue = new AttributeValueType();
AttributeValue.setDataType(URI_DATATYPE);
- String content = CONFIG_URL +"/Config/"+ getConfigFile(policyName);
+ String content = CONFIG_URL + "/Config/" + getConfigFile(policyName);
AttributeValue.getContent().add(content);
assignment2.setExpression(new ObjectFactory().createAttributeValue(AttributeValue));
@@ -344,7 +340,7 @@ public class CreateClosedLoopPerformanceMetrics extends Policy {
advice.getAttributeAssignmentExpression().add(assignment6);
- //Risk Attributes
+ // Risk Attributes
AttributeAssignmentExpressionType assignment7 = new AttributeAssignmentExpressionType();
assignment7.setAttributeId("RiskType");
assignment7.setCategory(CATEGORY_RESOURCE);
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
index 103928cbc..e18628dff 100644
--- 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
@@ -4,6 +4,7 @@
* ================================================================================
* Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
* Modified Copyright (C) 2018 Samsung Electronics Co., Ltd.
+ * Modifications Copyright (C) 2019 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -22,6 +23,7 @@
package org.onap.policy.pap.xacml.rest.components;
import com.google.gson.Gson;
+
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
@@ -36,6 +38,7 @@ 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;
@@ -46,17 +49,16 @@ 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;
+import org.onap.policy.rest.util.MsAttributeObject;
+import org.onap.policy.rest.util.MsModelUtils;
+import org.onap.policy.rest.util.MsModelUtils.ModelType;
public class CreateNewMicroServiceModel {
private static final Logger logger = FlexLogger.getLogger(CreateNewMicroServiceModel.class);
private MicroServiceModels newModel = null;
- private HashMap<String, MSAttributeObject> classMap = new HashMap<>();
-
+ private HashMap<String, MsAttributeObject> classMap = new HashMap<>();
- private MSModelUtils utils = new MSModelUtils(XACMLPapServlet.getMsOnapName(), XACMLPapServlet.getMsPolicyName());
+ private MsModelUtils utils = new MsModelUtils(XACMLPapServlet.getMsOnapName(), XACMLPapServlet.getMsPolicyName());
public CreateNewMicroServiceModel(String fileName, String serviceName, String string, String version) {
super();
@@ -82,7 +84,7 @@ public class CreateNewMicroServiceModel {
this.newModel.setUserCreatedBy(userInfo);
String cleanUpFile = null;
- Map<String, MSAttributeObject> tempMap = new HashMap<>();
+ Map<String, MsAttributeObject> tempMap = new HashMap<>();
// Need to delete the file
if (importFile.contains(".zip")) {
extractFolder(randomID + ".zip");
@@ -98,7 +100,7 @@ public class CreateNewMicroServiceModel {
cleanUpFile = "ExtractDir" + File.separator + randomID + ".yml";
} else {
- tempMap = utils.processEpackage("ExtractDir" + File.separator + randomID + ".xmi", MODEL_TYPE.XMI);
+ tempMap = utils.processEpackage("ExtractDir" + File.separator + randomID + ".xmi", ModelType.XMI);
classMap.putAll(tempMap);
cleanUpFile = "ExtractDir" + File.separator + randomID + ".xmi";
}
@@ -109,7 +111,7 @@ public class CreateNewMicroServiceModel {
}
private void processFiles(String modelName, List<File> fileList) {
- Map<String, MSAttributeObject> tempMap;
+ Map<String, MsAttributeObject> tempMap;
for (File file : fileList) {
if (file.isFile()) {
int indx = file.getName().lastIndexOf('.');
@@ -121,7 +123,7 @@ public class CreateNewMicroServiceModel {
} else {
- tempMap = utils.processEpackage(file.getAbsolutePath(), MODEL_TYPE.XMI);
+ tempMap = utils.processEpackage(file.getAbsolutePath(), ModelType.XMI);
classMap.putAll(tempMap);
}
}
@@ -145,10 +147,9 @@ public class CreateNewMicroServiceModel {
try {
-
utils.parseTosca(fileName);
- MSAttributeObject msAttributes = new MSAttributeObject();
+ MsAttributeObject msAttributes = new MsAttributeObject();
msAttributes.setClassName(modelName);
LinkedHashMap<String, String> returnAttributeList = new LinkedHashMap<>();
@@ -164,7 +165,7 @@ public class CreateNewMicroServiceModel {
returnReferenceList.put(modelName, utils.getReferenceAttributes());
msAttributes.setRefAttribute(returnReferenceList);
- if (!PolicyDBDao.isNullOrEmpty(utils.getListConstraints())) {
+ if (!PolicyDbDao.isNullOrEmpty(utils.getListConstraints())) {
LinkedHashMap<String, String> enumList = new LinkedHashMap<>();
String[] listArray = utils.getListConstraints().split("#");
for (String str : listArray) {
@@ -255,7 +256,7 @@ public class CreateNewMicroServiceModel {
public Map<String, String> addValuesToNewModel(String type) {
Map<String, String> successMap = new HashMap<>();
- MSAttributeObject mainClass = null;
+ MsAttributeObject mainClass = null;
List<String> dependency = null;
String subAttribute = null;
@@ -269,13 +270,12 @@ public class CreateNewMicroServiceModel {
}
mainClass = classMap.get(this.newModel.getModelName());
-
if (".yml".equalsIgnoreCase(type)) {
newModel.setDependency("[]");
if (mainClass.getSubClass() != null) {
String value = new Gson().toJson(mainClass.getSubClass());
- newModel.setSub_attributes(value);
+ newModel.setSubAttributes(value);
}
if (mainClass.getAttribute() != null) {
@@ -289,7 +289,7 @@ public class CreateNewMicroServiceModel {
String refAttributes = mainClass.getRefAttribute().toString().replace("{", "").replace("}", "");
int equalsIndex = refAttributes.indexOf("=");
String refAttributesAfterFirstEquals = refAttributes.substring(equalsIndex + 1);
- this.newModel.setRef_attributes(refAttributesAfterFirstEquals);
+ this.newModel.setRefAttributes(refAttributesAfterFirstEquals);
}
if (mainClass.getEnumType() != null) {
@@ -317,7 +317,7 @@ public class CreateNewMicroServiceModel {
dependency = utils.getFullDependencyList(dependency, classMap);
if (!dependency.isEmpty()) {
for (String element : dependency) {
- MSAttributeObject temp = new MSAttributeObject();
+ MsAttributeObject temp = new MsAttributeObject();
if (classMap.containsKey(element)) {
temp = classMap.get(element);
mainClass.addAllRefAttribute(temp.getRefAttribute());
@@ -328,14 +328,14 @@ public class CreateNewMicroServiceModel {
}
subAttribute = utils.createSubAttributes(dependency, classMap, this.newModel.getModelName());
- this.newModel.setSub_attributes(subAttribute);
+ this.newModel.setSubAttributes(subAttribute);
if (mainClass.getAttribute() != null && !mainClass.getAttribute().isEmpty()) {
this.newModel.setAttributes(mainClass.getAttribute().toString().replace("{", "").replace("}", ""));
}
if (mainClass.getRefAttribute() != null && !mainClass.getRefAttribute().isEmpty()) {
this.newModel
- .setRef_attributes(mainClass.getRefAttribute().toString().replace("{", "").replace("}", ""));
+ .setRefAttributes(mainClass.getRefAttribute().toString().replace("{", "").replace("}", ""));
}
if (mainClass.getEnumType() != null && !mainClass.getEnumType().isEmpty()) {
@@ -368,8 +368,8 @@ public class CreateNewMicroServiceModel {
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());
+ model.setRefAttributes(this.newModel.getRefAttributes());
+ model.setSubAttributes(this.newModel.getSubAttributes());
model.setDataOrderInfo(this.newModel.getDataOrderInfo());
model.setDecisionModel(this.newModel.isDecisionModel());
model.setRuleFormation(this.newModel.getRuleFormation());
diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/CreateNewOptimizationModel.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/CreateNewOptimizationModel.java
index 87c9f9108..8c63a2766 100644
--- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/CreateNewOptimizationModel.java
+++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/CreateNewOptimizationModel.java
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP-PAP-REST
* ================================================================================
- * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2018-2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -20,6 +20,8 @@
package org.onap.policy.pap.xacml.rest.components;
+import com.google.gson.Gson;
+
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
@@ -43,28 +45,26 @@ import org.onap.policy.pap.xacml.rest.XACMLPapServlet;
import org.onap.policy.pap.xacml.rest.daoimpl.CommonClassDaoImpl;
import org.onap.policy.rest.jpa.OptimizationModels;
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;
-
-import com.google.gson.Gson;
+import org.onap.policy.rest.util.MsAttributeObject;
+import org.onap.policy.rest.util.MsModelUtils;
+import org.onap.policy.rest.util.MsModelUtils.ModelType;
public class CreateNewOptimizationModel {
private static final Logger logger = FlexLogger.getLogger(CreateNewOptimizationModel.class);
private OptimizationModels newModel = null;
- private HashMap<String,MSAttributeObject > classMap = new HashMap<>();
+ private HashMap<String, MsAttributeObject> classMap = new HashMap<>();
private static final String EXTRACTDIR = "ExtractDir";
private static final String SUCCESS = "success";
-
- MSModelUtils utils = new MSModelUtils(XACMLPapServlet.getMsOnapName(), XACMLPapServlet.getMsPolicyName());
+ MsModelUtils utils = new MsModelUtils(XACMLPapServlet.getMsOnapName(), XACMLPapServlet.getMsPolicyName());
public CreateNewOptimizationModel() {
super();
}
- public CreateNewOptimizationModel(String importFile, String modelName, String description, String version, String randomID) {
+ public CreateNewOptimizationModel(String importFile, String modelName, String description, String version,
+ String randomID) {
this.newModel = new OptimizationModels();
this.newModel.setVersion(version);
@@ -75,15 +75,15 @@ public class CreateNewOptimizationModel {
this.newModel.setUserCreatedBy(userInfo);
String cleanUpFile = null;
- Map<String, MSAttributeObject> tempMap = new HashMap<>();
- //Need to delete the file
- if (importFile.contains(".zip")){
+ Map<String, MsAttributeObject> tempMap = new HashMap<>();
+ // Need to delete the file
+ if (importFile.contains(".zip")) {
extractFolder(randomID + ".zip");
File directory = new File(EXTRACTDIR + File.separator + randomID);
List<File> fileList = listModelFiles(directory.toString());
- //get all the files from a director
- for (File file : fileList){
- if (file.isFile()){
+ // get all the files from a director
+ for (File file : fileList) {
+ if (file.isFile()) {
processYmlModel(file.toString(), modelName);
}
}
@@ -96,32 +96,32 @@ public class CreateNewOptimizationModel {
} catch (IOException e) {
logger.error("Failed to unzip model file " + randomID, e);
}
- }else {
- if(importFile.contains(".yml")){
+ } else {
+ if (importFile.contains(".yml")) {
- processYmlModel(EXTRACTDIR + File.separator + randomID+".yml", modelName);
- cleanUpFile = EXTRACTDIR + File.separator + randomID+".yml";
+ processYmlModel(EXTRACTDIR + File.separator + randomID + ".yml", modelName);
+ cleanUpFile = EXTRACTDIR + File.separator + randomID + ".yml";
- }else{
- tempMap = utils.processEpackage(EXTRACTDIR + File.separator + randomID+".xmi", MODEL_TYPE.XMI);
+ } else {
+ tempMap = utils.processEpackage(EXTRACTDIR + File.separator + randomID + ".xmi", ModelType.XMI);
classMap.putAll(tempMap);
- cleanUpFile = EXTRACTDIR + File.separator + randomID+".xmi";
+ cleanUpFile = EXTRACTDIR + File.separator + randomID + ".xmi";
}
File deleteFile = new File(cleanUpFile);
deleteFile.delete();
}
}
- private void processYmlModel(String fileName, String modelName){
+ private void processYmlModel(String fileName, String modelName) {
try {
utils.parseTosca(fileName);
- MSAttributeObject msAttributes= new MSAttributeObject();
+ MsAttributeObject msAttributes = new MsAttributeObject();
msAttributes.setClassName(modelName);
- LinkedHashMap<String, String> returnAttributeList =new LinkedHashMap<>();
+ LinkedHashMap<String, String> returnAttributeList = new LinkedHashMap<>();
returnAttributeList.put(modelName, utils.getAttributeString());
msAttributes.setAttribute(returnAttributeList);
@@ -129,24 +129,24 @@ public class CreateNewOptimizationModel {
msAttributes.setMatchingSet(utils.getMatchableValues());
- LinkedHashMap<String, String> returnReferenceList =new LinkedHashMap<>();
+ LinkedHashMap<String, String> returnReferenceList = new LinkedHashMap<>();
returnReferenceList.put(modelName, utils.getReferenceAttributes());
msAttributes.setRefAttribute(returnReferenceList);
- if(!"".equals(utils.getListConstraints())){
- LinkedHashMap<String, String> enumList =new LinkedHashMap<>();
- String[] listArray=utils.getListConstraints().split("#");
- for(String str:listArray){
- String[] strArr= str.split("=");
- if(strArr.length>1){
+ if (!"".equals(utils.getListConstraints())) {
+ LinkedHashMap<String, String> enumList = new LinkedHashMap<>();
+ String[] listArray = utils.getListConstraints().split("#");
+ for (String str : listArray) {
+ String[] strArr = str.split("=");
+ if (strArr.length > 1) {
enumList.put(strArr[0], strArr[1]);
}
}
msAttributes.setEnumType(enumList);
}
- classMap=new LinkedHashMap<>();
+ classMap = new LinkedHashMap<>();
classMap.put(modelName, msAttributes);
} catch (Exception e) {
@@ -174,13 +174,13 @@ public class CreateNewOptimizationModel {
int buffer = 2048;
File file = new File(zipFile);
- try(ZipFile zip = new ZipFile(EXTRACTDIR + File.separator +file);){
- String newPath = zipFile.substring(0, zipFile.length() - 4);
+ try (ZipFile 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()){
+ while (zipFileEntries.hasMoreElements()) {
// grab a zip file entry
ZipEntry entry = (ZipEntry) zipFileEntries.nextElement();
String currentEntry = entry.getName();
@@ -189,13 +189,13 @@ public class CreateNewOptimizationModel {
destinationParent.mkdirs();
- if (!entry.isDirectory()){
+ if (!entry.isDirectory()) {
int currentByte;
byte[] data = new byte[buffer];
- try(FileOutputStream fos = new FileOutputStream(destFile);
+ try (FileOutputStream fos = new FileOutputStream(destFile);
BufferedInputStream is = new BufferedInputStream(zip.getInputStream(entry));
- BufferedOutputStream dest = new BufferedOutputStream(fos, buffer)) {
+ BufferedOutputStream dest = new BufferedOutputStream(fos, buffer)) {
while ((currentByte = is.read(data, 0, buffer)) != -1) {
dest.write(data, 0, currentByte);
@@ -204,7 +204,7 @@ public class CreateNewOptimizationModel {
}
}
- if (currentEntry.endsWith(".zip")){
+ if (currentEntry.endsWith(".zip")) {
extractFolder(destFile.getAbsolutePath());
}
}
@@ -216,40 +216,42 @@ public class CreateNewOptimizationModel {
public Map<String, String> addValuesToNewModel() {
Map<String, String> successMap = new HashMap<>();
- MSAttributeObject mainClass;
+ MsAttributeObject mainClass;
- 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");
+ 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());
newModel.setDependency("[]");
- if(mainClass.getSubClass() != null){
- String value = new Gson().toJson(mainClass.getSubClass());
- newModel.setSubattributes(value);
+ if (mainClass.getSubClass() != null) {
+ String value = new Gson().toJson(mainClass.getSubClass());
+ newModel.setSubattributes(value);
}
- if(mainClass.getAttribute() != null){
- String attributes= mainClass.getAttribute().toString().replace("{", "").replace("}", "");
- int equalsIndexForAttributes= attributes.indexOf('=');
- String atttributesAfterFirstEquals= attributes.substring(equalsIndexForAttributes+1);
+ if (mainClass.getAttribute() != null) {
+ String attributes = mainClass.getAttribute().toString().replace("{", "").replace("}", "");
+ int equalsIndexForAttributes = attributes.indexOf('=');
+ String atttributesAfterFirstEquals = attributes.substring(equalsIndexForAttributes + 1);
this.newModel.setAttributes(atttributesAfterFirstEquals);
}
- if(mainClass.getRefAttribute() != null){
- String refAttributes= mainClass.getRefAttribute().toString().replace("{", "").replace("}", "");
- int equalsIndex= refAttributes.indexOf('=');
- String refAttributesAfterFirstEquals= refAttributes.substring(equalsIndex+1);
+ if (mainClass.getRefAttribute() != null) {
+ String refAttributes = mainClass.getRefAttribute().toString().replace("{", "").replace("}", "");
+ int equalsIndex = refAttributes.indexOf('=');
+ String refAttributesAfterFirstEquals = refAttributes.substring(equalsIndex + 1);
this.newModel.setRefattributes(refAttributesAfterFirstEquals);
}
- if(mainClass.getEnumType() != null){
+ if (mainClass.getEnumType() != null) {
this.newModel.setEnumValues(mainClass.getEnumType().toString().replace("{", "").replace("}", ""));
}
- if(mainClass.getMatchingSet() != null){
+ if (mainClass.getMatchingSet() != null) {
this.newModel.setAnnotation(mainClass.getMatchingSet().toString().replace("{", "").replace("}", ""));
}
@@ -258,14 +260,15 @@ public class CreateNewOptimizationModel {
}
- public Map<String, String> saveImportService(){
+ public Map<String, String> saveImportService() {
String modelName = this.newModel.getModelName();
String importedBy = "API";
String version = this.newModel.getVersion();
Map<String, String> successMap = new HashMap<>();
CommonClassDaoImpl dbConnection = new CommonClassDaoImpl();
- List<Object> result = dbConnection.getDataById(OptimizationModels.class, "modelName:version", modelName+":"+version);
- if(result.isEmpty()){
+ List<Object> result =
+ dbConnection.getDataById(OptimizationModels.class, "modelName:version", modelName + ":" + version);
+ if (result.isEmpty()) {
OptimizationModels model = new OptimizationModels();
model.setModelName(modelName);
model.setVersion(version);
@@ -283,7 +286,7 @@ public class CreateNewOptimizationModel {
model.setUserCreatedBy(userInfo);
dbConnection.save(model);
successMap.put(SUCCESS, SUCCESS);
- }else{
+ } else {
successMap.put("DBError", "EXISTS");
logger.error("Import new service failed. Service already exists");
}
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
index 5e2bb58ff..ed1d551b4 100644
--- 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
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -23,6 +23,7 @@ package org.onap.policy.pap.xacml.rest.components;
import com.att.research.xacml.api.XACML3;
import com.att.research.xacml.api.pap.PAPException;
import com.att.research.xacml.std.IdentifierImpl;
+
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
@@ -40,6 +41,25 @@ import java.util.List;
import java.util.Map;
import java.util.UUID;
+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.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;
+import oasis.names.tc.xacml._3_0.core.schema.wd_17.VariableReferenceType;
+
import org.apache.commons.lang3.StringEscapeUtils;
import org.onap.policy.common.logging.eelf.MessageCodes;
import org.onap.policy.common.logging.eelf.PolicyLogger;
@@ -63,25 +83,6 @@ import org.onap.policy.xacml.std.pip.engines.aaf.AAFEngine;
import org.onap.policy.xacml.util.XACMLPolicyScanner;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
-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.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;
-import oasis.names.tc.xacml._3_0.core.schema.wd_17.VariableReferenceType;
-
@Component
public class DecisionPolicy extends Policy {
@@ -103,7 +104,6 @@ public class DecisionPolicy extends Policy {
private static final String POLICY_NAME = "PolicyName";
private static final String DESCRIPTION = "description";
-
List<String> dynamicLabelRuleAlgorithms = new LinkedList<>();
List<String> dynamicFieldComboRuleAlgorithms = new LinkedList<>();
List<String> dynamicFieldOneRuleAlgorithms = new LinkedList<>();
@@ -147,23 +147,22 @@ public class DecisionPolicy extends Policy {
successMap = createPolicy(newPolicyPath, getCorrectPolicyDataObject());
return successMap;
}
-
+
/**
* Scan the Raw Policy data and set to PolicyAdapter.
*/
private void readRawPolicyData() {
Object policy;
if ("API".equalsIgnoreCase(policyAdapter.getApiflag())) {
- policy = XACMLPolicyScanner.readPolicy(new ByteArrayInputStream(StringEscapeUtils
- .unescapeXml(policyAdapter.getRawXacmlPolicy()).getBytes(StandardCharsets.UTF_8)));
+ policy = XACMLPolicyScanner.readPolicy(new ByteArrayInputStream(
+ StringEscapeUtils.unescapeXml(policyAdapter.getRawXacmlPolicy()).getBytes(StandardCharsets.UTF_8)));
} else {
policy = XACMLPolicyScanner.readPolicy(
new ByteArrayInputStream(policyAdapter.getRawXacmlPolicy().getBytes(StandardCharsets.UTF_8)));
}
String policyRawDesc;
if (policy instanceof PolicySetType) {
- policyRawDesc =
- ((PolicySetType) policy).getDescription() + "@#RuleProvider@#Decision_Raw@#RuleProvider@#";
+ policyRawDesc = ((PolicySetType) policy).getDescription() + "@#RuleProvider@#Decision_Raw@#RuleProvider@#";
((PolicySetType) policy).setDescription(policyRawDesc);
} else {
policyRawDesc = ((PolicyType) policy).getDescription() + "@#RuleProvider@#Decision_Raw@#RuleProvider@#";
@@ -172,7 +171,7 @@ public class DecisionPolicy extends Policy {
policyAdapter.setPolicyData(policy);
policyAdapter.setData(policy);
setPreparedToSave(true);
-
+
}
// This is the method for preparing the policy for saving. We have broken it out
@@ -204,13 +203,13 @@ public class DecisionPolicy extends Policy {
}
policyName = policyAdapter.getNewFileName();
- if(policyAdapter.getRuleProvider().equals(GUARD_YAML) ||
- policyAdapter.getRuleProvider().equals(GUARD_BL_YAML) ||
- policyAdapter.getRuleProvider().equals(GUARD_MIN_MAX)){
-
+ if (policyAdapter.getRuleProvider().equals(GUARD_YAML) || policyAdapter.getRuleProvider().equals(GUARD_BL_YAML)
+ || policyAdapter.getRuleProvider().equals(GUARD_MIN_MAX)) {
+
Map<String, String> yamlParams = new HashMap<>();
- String blackListEntryType = policyAdapter.getBlackListEntryType() != null
- ? policyAdapter.getBlackListEntryType() : "Use Manual Entry";
+ String blackListEntryType =
+ policyAdapter.getBlackListEntryType() != null ? policyAdapter.getBlackListEntryType()
+ : "Use Manual Entry";
String description = policyAdapter.getPolicyDescription() != null ? policyAdapter.getPolicyDescription()
: "YAML Guard Policy";
yamlParams.put(DESCRIPTION, description + "@blEntry@" + blackListEntryType + "@blEntry@");
@@ -368,7 +367,7 @@ public class DecisionPolicy extends Policy {
case GUARD_MIN_MAX:
templateFile = new File(classLoader.getResource(XACML_GUARD_MIN_MAX_TEMPLATE).getFile());
xacmlTemplatePath = templateFile.toPath();
- cons = new Constraint(Integer.parseInt(yamlParams.get("min")),
+ cons = new Constraint(Integer.parseInt(yamlParams.get("min")),
Integer.parseInt(yamlParams.get("max")), activeTimeRange);
break;
default:
@@ -390,7 +389,7 @@ public class DecisionPolicy extends Policy {
cons = new Constraint(Integer.parseInt(yamlParams.get("limit")), timeWindow, activeTimeRange);
break;
}
-
+
builder = builder.addLimitConstraint(policy1.getId(), cons);
// Build the specification
Results results = builder.buildSpecification();
@@ -403,45 +402,37 @@ public class DecisionPolicy extends Policy {
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());
+ GuardPolicy guard = yamlGuardObject.getGuards().get(0);
+
+ yamlSpecs.put("actor", guard.getMatch_parameters().getActor());
+ yamlSpecs.put("recipe", guard.getMatch_parameters().getRecipe());
+ yamlSpecs.put("clname", guard.getMatch_parameters().getControlLoopName());
+
+ Constraint constraints = guard.getLimit_constraints().get(0);
+ if (constraints.getFreq_limit_per_target() != null) {
+ yamlSpecs.put("limit", constraints.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"));
+ if (constraints.getTime_window() != null) {
+ yamlSpecs.put("twValue", constraints.getTime_window().get("value"));
+ yamlSpecs.put("twUnits", constraints.getTime_window().get("units"));
}
-
- if (yamlGuardObject.getGuards().getFirst().getLimit_constraints().
- getFirst().getMaxVnfCount() != null) {
- yamlSpecs.put("max", yamlGuardObject.getGuards().getFirst().getLimit_constraints().getFirst()
- .getMaxVnfCount().toString());
+
+ if (constraints.getMaxVnfCount() != null) {
+ yamlSpecs.put("max", constraints.getMaxVnfCount().toString());
}
- if (yamlGuardObject.getGuards().getFirst().getLimit_constraints().
- getFirst().getMinVnfCount() != null) {
- yamlSpecs.put("min", yamlGuardObject.getGuards().getFirst().getLimit_constraints().getFirst()
- .getMinVnfCount().toString());
+ if (constraints.getMinVnfCount() != null) {
+ yamlSpecs.put("min", constraints.getMinVnfCount().toString());
}
- 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"));
+ yamlSpecs.put("guardActiveStart", constraints.getActive_time_range().get("start"));
+ yamlSpecs.put("guardActiveEnd", constraints.getActive_time_range().get("end"));
String xacmlPolicyContent = SafePolicyBuilder.generateXacmlGuard(xacmlTemplateContent, yamlSpecs,
- yamlGuardObject.getGuards().getFirst().getLimit_constraints().getFirst().getBlacklist(),
- yamlGuardObject.getGuards().getFirst().getMatch_parameters().getTargets());
-
+ constraints.getBlacklist(), guard.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(),
@@ -720,7 +711,8 @@ public class DecisionPolicy extends Policy {
if (!attributeId.startsWith("S_")) {
ApplyType innerDecisionApply = generateApplyTypeDataType(functionKey);
AttributeDesignatorType attributeDesignator = generateAttributeDesignatorDataType(functionKey);
- AttributeValueType decisionConditionAttributeValue = generateAttributeValueTypeDataType(functionKey);
+ AttributeValueType decisionConditionAttributeValue =
+ generateAttributeValueTypeDataType(functionKey);
if (attributeId != null) {
attributeDesignator.setCategory(CATEGORY_RESOURCE);
@@ -800,7 +792,6 @@ public class DecisionPolicy extends Policy {
dataTypeList.add(dataType);
}
-
private String getDataType(String key) {
DecisionSettings decisionSettings = findDecisionSettingsBySettingId(key);
@@ -833,8 +824,7 @@ public class DecisionPolicy extends Policy {
private AttributeDesignatorType generateAttributeDesignatorDataType(String functionKey) {
AttributeDesignatorType attributeDesignator = new AttributeDesignatorType();
- switch(functionKey.toLowerCase())
- {
+ switch (functionKey.toLowerCase()) {
case "integer":
attributeDesignator.setDataType(INTEGER_DATATYPE);
break;
@@ -846,8 +836,7 @@ public class DecisionPolicy extends Policy {
private ApplyType generateApplyTypeDataType(String functionKey) {
ApplyType applyType = new ApplyType();
- switch(functionKey.toLowerCase())
- {
+ switch (functionKey.toLowerCase()) {
case "integer":
applyType.setFunctionId(FUNTION_INTEGER_ONE_AND_ONLY);
break;
@@ -859,8 +848,7 @@ public class DecisionPolicy extends Policy {
private AttributeValueType generateAttributeValueTypeDataType(String functionKey) {
AttributeValueType applyType = new AttributeValueType();
- switch(functionKey.toLowerCase())
- {
+ switch (functionKey.toLowerCase()) {
case "integer":
applyType.setDataType(INTEGER_DATATYPE);
break;
@@ -871,8 +859,10 @@ public class DecisionPolicy extends Policy {
}
private void applyTwoTextFieldRuleAttribute(ApplyType decisionApply, String value1, String functionKey) {
- decisionApply.getExpression().add(new ObjectFactory().createApply(generateApplyTypeDataType(value1, functionKey)));
- decisionApply.getExpression().add(new ObjectFactory().createApply(generateApplyTypeDataType(value1, functionKey)));
+ decisionApply.getExpression()
+ .add(new ObjectFactory().createApply(generateApplyTypeDataType(value1, functionKey)));
+ decisionApply.getExpression()
+ .add(new ObjectFactory().createApply(generateApplyTypeDataType(value1, functionKey)));
}
private ApplyType generateApplyTypeDataType(String value1, String functionKey) {
@@ -881,10 +871,8 @@ public class DecisionPolicy extends Policy {
attributeDesignator.setCategory(CATEGORY_RESOURCE);
// Here set actual field values
- attributeDesignator
- .setAttributeId(value1.contains("resource:") ? value1.substring(9) : value1.substring(8));
- innerApply.getExpression()
- .add(new ObjectFactory().createAttributeDesignator(attributeDesignator));
+ attributeDesignator.setAttributeId(value1.contains("resource:") ? value1.substring(9) : value1.substring(8));
+ innerApply.getExpression().add(new ObjectFactory().createAttributeDesignator(attributeDesignator));
return innerApply;
}
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
index eca473f41..e153ea834 100644
--- 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
@@ -26,6 +26,7 @@ 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 java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
@@ -41,11 +42,27 @@ 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.script.SimpleBindings;
+
+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;
@@ -66,19 +83,6 @@ import org.onap.policy.rest.jpa.TermList;
import org.onap.policy.rest.jpa.UserInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
-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;
@Component
public class FirewallConfigPolicy extends Policy {
@@ -114,11 +118,11 @@ public class FirewallConfigPolicy extends Policy {
LOGGER.debug("Configuration is succesfully saved");
}
} catch (IOException e) {
- LOGGER.error("Save of configuration to file" +fileName+ "failed",e);
+ LOGGER.error("Save of configuration to file" + fileName + "failed", e);
}
}
- //Utility to read json data from the existing file to a string
+ // 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);
@@ -127,11 +131,11 @@ public class FirewallConfigPolicy extends Policy {
@Override
public Map<String, String> savePolicies() throws PAPException {
Map<String, String> successMap = new HashMap<>();
- if(isPolicyExists()){
+ if (isPolicyExists()) {
successMap.put("EXISTS", "This Policy already exist on the PAP");
return successMap;
}
- if(!isPreparedToSave()){
+ if (!isPreparedToSave()) {
prepareToSave();
}
@@ -139,9 +143,10 @@ public class FirewallConfigPolicy extends Policy {
Path newPolicyPath = null;
newPolicyPath = Paths.get(policyAdapter.getNewFileName());
Boolean dbIsUpdated = false;
- if (policyAdapter.getApiflag() != null && "admin".equalsIgnoreCase(policyAdapter.getApiflag())){
+ if (policyAdapter.getApiflag() != null && "admin".equalsIgnoreCase(policyAdapter.getApiflag())) {
if (policyAdapter.isEditPolicy()) {
- dbIsUpdated = updateFirewallDictionaryData(policyAdapter.getJsonBody(), policyAdapter.getPrevJsonBody());
+ dbIsUpdated =
+ updateFirewallDictionaryData(policyAdapter.getJsonBody(), policyAdapter.getPrevJsonBody());
} else {
try {
dbIsUpdated = insertFirewallDicionaryData(policyAdapter.getJsonBody());
@@ -153,14 +158,14 @@ public class FirewallConfigPolicy extends Policy {
dbIsUpdated = true;
}
- if(dbIsUpdated) {
- successMap = createPolicy(newPolicyPath,getCorrectPolicyDataObject());
+ if (dbIsUpdated) {
+ successMap = createPolicy(newPolicyPath, getCorrectPolicyDataObject());
} else {
PolicyLogger.error("Failed to Update the Database Dictionary Tables.");
- //remove the new json file
+ // remove the new json file
String jsonBody = policyAdapter.getPrevJsonBody();
- if (jsonBody!=null){
+ if (jsonBody != null) {
saveConfigurations(policyName, jsonBody);
} else {
saveConfigurations(policyName, "");
@@ -171,13 +176,13 @@ public class FirewallConfigPolicy extends Policy {
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
+ // 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 PAPException{
+ public boolean prepareToSave() throws PAPException {
- if(isPreparedToSave()){
- //we have already done this
+ if (isPreparedToSave()) {
+ // we have already done this
return true;
}
@@ -196,13 +201,13 @@ public class FirewallConfigPolicy extends Policy {
}
policyName = policyAdapter.getNewFileName();
- //String oldPolicyName = policyName.replace(".xml", "");
+ // String oldPolicyName = policyName.replace(".xml", "");
String scope = policyName.substring(0, policyName.indexOf('.'));
- String dbPolicyName = policyName.substring(policyName.indexOf('.')+1).replace(".xml", "");
+ 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){
+ 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";
}
@@ -277,7 +282,8 @@ public class FirewallConfigPolicy extends Policy {
try {
accessURI = new URI(ACTION_ID);
} catch (URISyntaxException e) {
- PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "FirewallConfigPolicy", "Exception creating ACCESS URI");
+ PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "FirewallConfigPolicy",
+ "Exception creating ACCESS URI");
}
accessAttributeDesignator.setCategory(CATEGORY_ACTION);
accessAttributeDesignator.setDataType(STRING_DATATYPE);
@@ -298,7 +304,8 @@ public class FirewallConfigPolicy extends Policy {
try {
configURI = new URI(RESOURCE_ID);
} catch (URISyntaxException e) {
- PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "FirewallConfigPolicy", "Exception creating Config URI");
+ PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "FirewallConfigPolicy",
+ "Exception creating Config URI");
}
configAttributeDesignator.setCategory(CATEGORY_RESOURCE);
@@ -332,7 +339,7 @@ public class FirewallConfigPolicy extends Policy {
// Data required for Advice part is setting here.
private AdviceExpressionsType getAdviceExpressions(int version, String fileName) {
- //Firewall Config ID Assignment
+ // Firewall Config ID Assignment
AdviceExpressionsType advices = new AdviceExpressionsType();
AdviceExpressionType advice = new AdviceExpressionType();
advice.setAdviceId("firewallConfigID");
@@ -349,7 +356,7 @@ public class FirewallConfigPolicy extends Policy {
advice.getAttributeAssignmentExpression().add(assignment1);
// For Config file Url if configurations are provided.
- //URL ID Assignment
+ // URL ID Assignment
AttributeAssignmentExpressionType assignment2 = new AttributeAssignmentExpressionType();
assignment2.setAttributeId("URLID");
assignment2.setCategory(CATEGORY_RESOURCE);
@@ -365,7 +372,7 @@ public class FirewallConfigPolicy extends Policy {
assignment2.setExpression(new ObjectFactory().createAttributeValue(AttributeValue));
advice.getAttributeAssignmentExpression().add(assignment2);
- //Policy Name Assignment
+ // Policy Name Assignment
AttributeAssignmentExpressionType assignment3 = new AttributeAssignmentExpressionType();
assignment3.setAttributeId("PolicyName");
assignment3.setCategory(CATEGORY_RESOURCE);
@@ -382,7 +389,7 @@ public class FirewallConfigPolicy extends Policy {
assignment3.setExpression(new ObjectFactory().createAttributeValue(attributeValue3));
advice.getAttributeAssignmentExpression().add(assignment3);
- //Version Number Assignment
+ // Version Number Assignment
AttributeAssignmentExpressionType assignment4 = new AttributeAssignmentExpressionType();
assignment4.setAttributeId("VersionNumber");
assignment4.setCategory(CATEGORY_RESOURCE);
@@ -393,7 +400,7 @@ public class FirewallConfigPolicy extends Policy {
assignment4.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue4));
advice.getAttributeAssignmentExpression().add(assignment4);
- //Onap Name Assignment
+ // Onap Name Assignment
AttributeAssignmentExpressionType assignment5 = new AttributeAssignmentExpressionType();
assignment5.setAttributeId("matching:" + ONAPID);
assignment5.setCategory(CATEGORY_RESOURCE);
@@ -403,7 +410,7 @@ public class FirewallConfigPolicy extends Policy {
assignment5.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue5));
advice.getAttributeAssignmentExpression().add(assignment5);
- //Config Name Assignment
+ // Config Name Assignment
AttributeAssignmentExpressionType assignment6 = new AttributeAssignmentExpressionType();
assignment6.setAttributeId("matching:" + CONFIGID);
assignment6.setCategory(CATEGORY_RESOURCE);
@@ -414,7 +421,7 @@ public class FirewallConfigPolicy extends Policy {
assignment6.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue6));
advice.getAttributeAssignmentExpression().add(assignment6);
- //Risk Attributes
+ // Risk Attributes
AttributeAssignmentExpressionType assignment7 = new AttributeAssignmentExpressionType();
assignment7.setAttributeId("RiskType");
assignment7.setCategory(CATEGORY_RESOURCE);
@@ -466,19 +473,18 @@ public class FirewallConfigPolicy extends Policy {
return advices;
}
-
- private Boolean insertFirewallDicionaryData (String jsonBody) throws SQLException {
+ private Boolean insertFirewallDicionaryData(String jsonBody) throws SQLException {
CommonClassDaoImpl dbConnection = new CommonClassDaoImpl();
JsonObject json = null;
if (jsonBody != null) {
- //Read jsonBody to JsonObject
+ // Read jsonBody to JsonObject
json = stringToJson(jsonBody);
JsonArray firewallRules = null;
JsonArray serviceGroup = null;
JsonArray addressGroup = null;
- //insert data into tables
+ // insert data into tables
try {
firewallRules = json.getJsonArray("firewallRuleList");
serviceGroup = json.getJsonArray("serviceGroups");
@@ -487,28 +493,28 @@ public class FirewallConfigPolicy extends Policy {
* Inserting firewallRuleList data into the Terms, SecurityZone, and Action tables
*/
if (firewallRules != null) {
- for(int i = 0;i<firewallRules.size();i++) {
+ for (int i = 0; i < firewallRules.size(); i++) {
/*
* Populate ArrayLists with values from the JSON
*/
- //create the JSON object from the JSON Array for each iteration through the for loop
+ // create the JSON object from the JSON Array for each iteration through the for loop
JsonObject ruleListobj = firewallRules.getJsonObject(i);
- //get values from JSON fields of firewallRulesList Array
+ // get values from JSON fields of firewallRulesList Array
String ruleName = ruleListobj.get("ruleName").toString();
String action = ruleListobj.get("action").toString();
String description = ruleListobj.get("description").toString();
List<Object> result = dbConnection.getDataById(TermList.class, "termName", ruleName);
- if(result != null && !result.isEmpty()){
+ if (result != null && !result.isEmpty()) {
TermList termEntry = (TermList) result.get(0);
dbConnection.delete(termEntry);
}
- //getting fromZone Array field from the firewallRulesList
+ // getting fromZone Array field from the firewallRulesList
JsonArray fromZoneArray = ruleListobj.getJsonArray("fromZones");
String fromZoneString = null;
- for (int fromZoneIndex = 0;fromZoneIndex<fromZoneArray.size(); fromZoneIndex++) {
+ for (int fromZoneIndex = 0; fromZoneIndex < fromZoneArray.size(); fromZoneIndex++) {
String value = fromZoneArray.get(fromZoneIndex).toString();
value = value.replace("\"", "");
if (fromZoneString != null) {
@@ -517,12 +523,12 @@ public class FirewallConfigPolicy extends Policy {
fromZoneString = value;
}
}
- String fromZoneInsert = "'"+fromZoneString+"'";
+ String fromZoneInsert = "'" + fromZoneString + "'";
- //getting toZone Array field from the firewallRulesList
+ // getting toZone Array field from the firewallRulesList
JsonArray toZoneArray = ruleListobj.getJsonArray("toZones");
String toZoneString = null;
- for (int toZoneIndex = 0; toZoneIndex<toZoneArray.size(); toZoneIndex++) {
+ for (int toZoneIndex = 0; toZoneIndex < toZoneArray.size(); toZoneIndex++) {
String value = toZoneArray.get(toZoneIndex).toString();
value = value.replace("\"", "");
if (toZoneString != null) {
@@ -531,19 +537,19 @@ public class FirewallConfigPolicy extends Policy {
toZoneString = value;
}
}
- String toZoneInsert = "'"+toZoneString+"'";
+ String toZoneInsert = "'" + toZoneString + "'";
- //getting sourceList Array fields from the firewallRulesList
+ // getting sourceList Array fields from the firewallRulesList
JsonArray srcListArray = ruleListobj.getJsonArray("sourceList");
String srcListString = null;
- for (int srcListIndex = 0; srcListIndex< srcListArray.size(); srcListIndex++) {
+ for (int srcListIndex = 0; srcListIndex < srcListArray.size(); srcListIndex++) {
JsonObject srcListObj = srcListArray.getJsonObject(srcListIndex);
String type = srcListObj.get("type").toString().replace("\"", "");
String value = null;
- if(type.equals("REFERENCE")||type.equals("GROUP")){
+ if (type.equals("REFERENCE") || type.equals("GROUP")) {
value = srcListObj.get("name").toString();
- } else if (type.equalsIgnoreCase("ANY")){
+ } else if (type.equalsIgnoreCase("ANY")) {
value = null;
} else {
value = srcListObj.get("value").toString();
@@ -552,19 +558,19 @@ public class FirewallConfigPolicy extends Policy {
srcListString = getLeftOrRight(srcListString, value);
}
- String srcListInsert = "'"+srcListString+"'";
+ String srcListInsert = "'" + srcListString + "'";
- //getting destinationList Array fields from the firewallRulesList
+ // getting destinationList Array fields from the firewallRulesList
JsonArray destListArray = ruleListobj.getJsonArray("destinationList");
String destListString = null;
- for (int destListIndex = 0; destListIndex <destListArray.size(); destListIndex++) {
+ for (int destListIndex = 0; destListIndex < destListArray.size(); destListIndex++) {
JsonObject destListObj = destListArray.getJsonObject(destListIndex);
String type = destListObj.get("type").toString().replace("\"", "");
String value = null;
- if(type.equals("REFERENCE")||type.equals("GROUP")){
+ if (type.equals("REFERENCE") || type.equals("GROUP")) {
value = destListObj.get("name").toString();
- } else if (type.equalsIgnoreCase("ANY")){
+ } else if (type.equalsIgnoreCase("ANY")) {
value = null;
} else {
value = destListObj.get("value").toString();
@@ -572,19 +578,20 @@ public class FirewallConfigPolicy extends Policy {
destListString = getLeftOrRight(destListString, value);
}
- String destListInsert = "'"+destListString+"'";
+ String destListInsert = "'" + destListString + "'";
- //getting destServices Array fields from the firewallRulesList
+ // getting destServices Array fields from the firewallRulesList
JsonArray destServicesArray = ruleListobj.getJsonArray("destServices");
String destPortListString = null;
- for (int destPortListIndex = 0; destPortListIndex < destServicesArray.size(); destPortListIndex++) {
+ for (int destPortListIndex = 0; destPortListIndex < destServicesArray
+ .size(); destPortListIndex++) {
JsonObject destServicesObj = destServicesArray.getJsonObject(destPortListIndex);
String type = destServicesObj.get("type").toString().replace("\"", "");
String value = null;
- if(type.equals("REFERENCE")||type.equals("GROUP")){
+ if (type.equals("REFERENCE") || type.equals("GROUP")) {
value = destServicesObj.get("name").toString();
- } else if (type.equalsIgnoreCase("ANY")){
+ } else if (type.equalsIgnoreCase("ANY")) {
value = null;
} else {
value = destServicesObj.get("value").toString();
@@ -592,7 +599,7 @@ public class FirewallConfigPolicy extends Policy {
destPortListString = getLeftOrRight(destPortListString, value);
}
- String destPortListInsert = "'"+destPortListString+"'";
+ String destPortListInsert = "'" + destPortListString + "'";
/*
* Create Queries to INSERT data into database tables and execute
@@ -603,16 +610,16 @@ public class FirewallConfigPolicy extends Policy {
TermList termEntry = new TermList();
termEntry.setTermName(ruleName);
- termEntry.setSrcIPList(srcListInsert);
- termEntry.setDestIPList(destListInsert);
+ termEntry.setSrcIpList(srcListInsert);
+ termEntry.setDestIpList(destListInsert);
termEntry.setProtocolList("null");
termEntry.setPortList("null");
termEntry.setSrcPortList("null");
termEntry.setDestPortList(destPortListInsert);
termEntry.setAction(action);
termEntry.setDescription(description);
- termEntry.setFromZones(fromZoneInsert);
- termEntry.setToZones(toZoneInsert);
+ termEntry.setFromZone(fromZoneInsert);
+ termEntry.setToZone(toZoneInsert);
termEntry.setUserCreatedBy(userInfo);
dbConnection.save(termEntry);
@@ -624,35 +631,35 @@ public class FirewallConfigPolicy extends Policy {
* Inserting serviceGroups data into the ServiceGroup, ServiceList, ProtocolList, and PortList tables
*/
if (serviceGroup != null) {
- for(int i = 0; i < serviceGroup.size() ; i++) {
+ for (int i = 0; i < serviceGroup.size(); i++) {
/*
* Populate ArrayLists with values from the JSON
*/
- //create the JSON object from the JSON Array for each iteration through the for loop
+ // create the JSON object from the JSON Array for each iteration through the for loop
JsonObject svcGroupListobj = serviceGroup.getJsonObject(i);
String serviceListName = svcGroupListobj.get("name").toString();
String description = null;
- if (svcGroupListobj.containsKey("description")){
+ if (svcGroupListobj.containsKey("description")) {
description = svcGroupListobj.get("description").toString();
}
- //getting members Array from the serviceGroup
+ // getting members Array from the serviceGroup
JsonArray membersArray = svcGroupListobj.getJsonArray("members");
- //String type = svcGroupListobj.get("type").toString();
+ // String type = svcGroupListobj.get("type").toString();
Boolean isServiceGroup = false;
- if (membersArray!=null){
+ 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
+ // Insert values into GROUPSERVICELIST table if name begins with Group
if (isServiceGroup) {
saveGroupServiceListTableToDb(dbConnection, serviceListName, membersArray);
- } else { //Insert JSON data serviceList table, protollist table, and portlist table
+ } else { // Insert JSON data serviceList table, protollist table, and portlist table
String type = svcGroupListobj.get("type").toString();
String transportProtocol = svcGroupListobj.get("transportProtocol").toString();
String ports = svcGroupListobj.get("ports").toString();
@@ -660,7 +667,8 @@ public class FirewallConfigPolicy extends Policy {
/*
* Create Queries to INSERT data into database table and execute
*/
- saveServiceListToDb(dbConnection, serviceListName, description, type, transportProtocol, ports);
+ saveServiceListToDb(dbConnection, serviceListName, description, type, transportProtocol,
+ ports);
saveProtocolListToDb(dbConnection, transportProtocol);
@@ -673,19 +681,19 @@ public class FirewallConfigPolicy extends Policy {
* Inserting addressGroup data into the ADDRESSGROUP table
*/
if (addressGroup != null) {
- for(int i = 0; i < addressGroup.size(); i++) {
+ for (int i = 0; i < addressGroup.size(); i++) {
/*
* Populate ArrayLists with values from the JSON
*/
- //create the JSON object from the JSON Array for each iteration through the for loop
+ // create the JSON object from the JSON Array for each iteration through the for loop
JsonObject addressGroupObj = addressGroup.getJsonObject(i);
- //create JSON array for members
+ // create JSON array for members
JsonArray membersArray = addressGroupObj.getJsonArray("members");
String addressGroupName = addressGroupObj.get("name").toString();
String description = null;
- if (addressGroupObj.containsKey("description")){
+ if (addressGroupObj.containsKey("description")) {
description = addressGroupObj.get("description").toString();
}
@@ -693,13 +701,11 @@ public class FirewallConfigPolicy extends Policy {
String type = null;
for (int membersIndex = 0; membersIndex < membersArray.size(); membersIndex++) {
JsonObject membersObj = membersArray.getJsonObject(membersIndex);
- //String value = membersObj.get("value").toString();
type = membersObj.get("type").toString().replace("\"", "");
- String value = null;
prefixIP = getName(prefixIP, membersObj, type);
}
- String prefixList = "'"+prefixIP+"'";
+ String prefixList = "'" + prefixIP + "'";
Boolean isAddressGroup = type.contains("REFERENCE");
@@ -711,8 +717,9 @@ public class FirewallConfigPolicy extends Policy {
}
}
removeDuplicateValuesFromLookup(dbConnection);
- }catch (Exception e) {
- PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "FirewallConfigPolicy", "Exception getting Json values");
+ } catch (Exception e) {
+ PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "FirewallConfigPolicy",
+ "Exception getting Json values");
return false;
}
return true;
@@ -731,33 +738,34 @@ public class FirewallConfigPolicy extends Policy {
+ "WHERE protocollist.id > p1.id AND protocollist.protocolname = p1.protocolname;";
dbConnection.updateQuery(protoDelete);
- //PortList Table
+ // 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
+ // 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
+ // 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);
}
- private void saveGroupServiceListTableToDb(CommonClassDaoImpl dbConnection, String serviceListName, JsonArray membersArray) {
+ private void saveGroupServiceListTableToDb(CommonClassDaoImpl dbConnection, String serviceListName,
+ JsonArray membersArray) {
String name = null;
- for (int membersIndex = 0; membersIndex< membersArray.size(); membersIndex++) {
+ for (int membersIndex = 0; membersIndex < membersArray.size(); membersIndex++) {
JsonObject membersObj = membersArray.getJsonObject(membersIndex);
String type = membersObj.get("type").toString().replace("\"", "");
name = getName(name, membersObj, type);
}
- String nameInsert = "'"+name+"'";
+ String nameInsert = "'" + name + "'";
GroupServiceList groupServiceEntry = new GroupServiceList();
groupServiceEntry.setGroupName(serviceListName);
groupServiceEntry.setServiceList(nameInsert);
@@ -766,9 +774,9 @@ public class FirewallConfigPolicy extends Policy {
private String getName(String name, JsonObject membersObj, String type) {
String value;
- if(type.equals("REFERENCE")||type.equals("GROUP")||type.equals("SERVICE")){
+ if (type.equals("REFERENCE") || type.equals("GROUP") || type.equals("SERVICE")) {
value = membersObj.get("name").toString();
- } else if (type.equalsIgnoreCase("ANY")){
+ } else if (type.equalsIgnoreCase("ANY")) {
value = null;
} else {
value = membersObj.get("value").toString();
@@ -791,7 +799,6 @@ public class FirewallConfigPolicy extends Policy {
return name;
}
-
private Boolean updateFirewallDictionaryData(String jsonBody, String prevJsonBody) {
CommonClassDaoImpl dbConnection = new CommonClassDaoImpl();
JsonObject oldJson = null;
@@ -802,7 +809,7 @@ public class FirewallConfigPolicy extends Policy {
oldJson = stringToJson(prevJsonBody);
newJson = stringToJson(jsonBody);
- //if no changes to the json then return true
+ // if no changes to the json then return true
if (oldJson != null && oldJson.equals(newJson)) {
return true;
}
@@ -815,12 +822,12 @@ public class FirewallConfigPolicy extends Policy {
serviceGroup = newJson.getJsonArray("serviceGroups");
addressGroup = newJson.getJsonArray("addressGroups");
- //insert data into tables
+ // insert data into tables
try {
JsonNode jsonDiff = createPatch(jsonBody, prevJsonBody);
- for (int i = 0; i<jsonDiff.size(); i++) {
- //String path = jsonDiff.get(i).asText();
+ for (int i = 0; i < jsonDiff.size(); i++) {
+ // String path = jsonDiff.get(i).asText();
String jsonpatch = jsonDiff.get(i).toString();
JsonObject patchObj = stringToJson(jsonpatch);
@@ -831,29 +838,29 @@ public class FirewallConfigPolicy extends Policy {
/*
* Inserting firewallRuleList data into the Terms, SecurityZone, and Action tables
*/
- for(int ri = 0; ri < firewallRules.size(); ri++) {
+ for (int ri = 0; ri < firewallRules.size(); ri++) {
/*
* Populate ArrayLists with values from the JSON
*/
- //create the JSON object from the JSON Array for each iteration through the for loop
+ // create the JSON object from the JSON Array for each iteration through the for loop
JsonObject ruleListobj = firewallRules.getJsonObject(ri);
- //get values from JSON fields of firewallRulesList Array
+ // get values from JSON fields of firewallRulesList Array
String ruleName = ruleListobj.get("ruleName").toString().replace('"', '\'');
String action = ruleListobj.get("action").toString().replace('"', '\'');
String description = ruleListobj.get("description").toString().replace('"', '\'');
List<Object> result = dbConnection.getDataById(TermList.class, "termName", ruleName);
- if(result != null && !result.isEmpty()){
+ if (result != null && !result.isEmpty()) {
TermList termEntry = (TermList) result.get(0);
dbConnection.delete(termEntry);
}
- //getting fromZone Array field from the firewallRulesList
+ // getting fromZone Array field from the firewallRulesList
JsonArray fromZoneArray = ruleListobj.getJsonArray("fromZones");
String fromZoneString = null;
- for (int fromZoneIndex = 0; fromZoneIndex<fromZoneArray.size() ; fromZoneIndex++) {
+ for (int fromZoneIndex = 0; fromZoneIndex < fromZoneArray.size(); fromZoneIndex++) {
String value = fromZoneArray.get(fromZoneIndex).toString();
value = value.replace("\"", "");
@@ -865,13 +872,12 @@ public class FirewallConfigPolicy extends Policy {
}
}
- String fromZoneInsert = "'"+fromZoneString+"'";
+ String fromZoneInsert = "'" + fromZoneString + "'";
- //getting toZone Array field from the firewallRulesList
+ // getting toZone Array field from the firewallRulesList
JsonArray toZoneArray = ruleListobj.getJsonArray("toZones");
String toZoneString = null;
-
for (int toZoneIndex = 0; toZoneIndex < toZoneArray.size(); toZoneIndex++) {
String value = toZoneArray.get(toZoneIndex).toString();
value = value.replace("\"", "");
@@ -884,18 +890,18 @@ public class FirewallConfigPolicy extends Policy {
}
}
- String toZoneInsert = "'"+toZoneString+"'";
- //getting sourceList Array fields from the firewallRulesList
+ String toZoneInsert = "'" + toZoneString + "'";
+ // getting sourceList Array fields from the firewallRulesList
JsonArray srcListArray = ruleListobj.getJsonArray("sourceList");
String srcListString = null;
- for (int srcListIndex = 0; srcListIndex<srcListArray.size(); srcListIndex++) {
+ for (int srcListIndex = 0; srcListIndex < srcListArray.size(); srcListIndex++) {
JsonObject srcListObj = srcListArray.getJsonObject(srcListIndex);
String type = srcListObj.get("type").toString().replace("\"", "");
String value = null;
- if(type.equals("REFERENCE")||type.equals("GROUP")){
+ if (type.equals("REFERENCE") || type.equals("GROUP")) {
value = srcListObj.get("name").toString();
- } else if (type.equalsIgnoreCase("ANY")){
+ } else if (type.equalsIgnoreCase("ANY")) {
value = null;
} else {
value = srcListObj.get("value").toString();
@@ -904,19 +910,19 @@ public class FirewallConfigPolicy extends Policy {
srcListString = getLeftOrRight(srcListString, value);
}
- String srcListInsert = "'"+srcListString+"'";
+ String srcListInsert = "'" + srcListString + "'";
- //getting destinationList Array fields from the firewallRulesList
+ // getting destinationList Array fields from the firewallRulesList
JsonArray destListArray = ruleListobj.getJsonArray("destinationList");
String destListString = null;
- for (int destListIndex = 0; destListIndex<destListArray.size(); destListIndex ++) {
+ for (int destListIndex = 0; destListIndex < destListArray.size(); destListIndex++) {
JsonObject destListObj = destListArray.getJsonObject(destListIndex);
String type = destListObj.get("type").toString().replace("\"", "");
String value = null;
- if(type.equals("REFERENCE")||type.equals("GROUP")){
+ if (type.equals("REFERENCE") || type.equals("GROUP")) {
value = destListObj.get("name").toString();
- } else if (type.equalsIgnoreCase("ANY")){
+ } else if (type.equalsIgnoreCase("ANY")) {
value = null;
} else {
value = destListObj.get("value").toString();
@@ -924,19 +930,20 @@ public class FirewallConfigPolicy extends Policy {
destListString = getLeftOrRight(destListString, value);
}
- String destListInsert = "'"+destListString+"'";
+ String destListInsert = "'" + destListString + "'";
- //getting destServices Array fields from the firewallRulesList
+ // getting destServices Array fields from the firewallRulesList
JsonArray destServicesArray = ruleListobj.getJsonArray("destServices");
String destPortListString = null;
- for (int destPortListIndex = 0; destPortListIndex < destServicesArray.size(); destPortListIndex++) {
+ for (int destPortListIndex = 0; destPortListIndex < destServicesArray
+ .size(); destPortListIndex++) {
JsonObject destServicesObj = destServicesArray.getJsonObject(destPortListIndex);
String type = destServicesObj.get("type").toString().replace("\"", "");
String value = null;
- if(type.equals("REFERENCE")||type.equals("GROUP")){
+ if (type.equals("REFERENCE") || type.equals("GROUP")) {
value = destServicesObj.get("name").toString();
- } else if (type.equalsIgnoreCase("ANY")){
+ } else if (type.equalsIgnoreCase("ANY")) {
value = null;
} else {
value = destServicesObj.get("value").toString();
@@ -944,7 +951,7 @@ public class FirewallConfigPolicy extends Policy {
destPortListString = getLeftOrRight(destPortListString, value);
}
- String destPortListInsert = "'"+destPortListString+"'";
+ String destPortListInsert = "'" + destPortListString + "'";
/*
* Create Queries to INSERT data into database tables and execute
@@ -955,21 +962,22 @@ public class FirewallConfigPolicy extends Policy {
TermList termEntry = new TermList();
termEntry.setTermName(ruleName);
- termEntry.setSrcIPList(srcListInsert);
- termEntry.setDestIPList(destListInsert);
+ termEntry.setSrcIpList(srcListInsert);
+ termEntry.setDestIpList(destListInsert);
termEntry.setProtocolList("null");
termEntry.setPortList("null");
termEntry.setSrcPortList("null");
termEntry.setDestPortList(destPortListInsert);
termEntry.setAction(action);
termEntry.setDescription(description);
- termEntry.setFromZones(fromZoneInsert);
- termEntry.setToZones(toZoneInsert);
+ termEntry.setFromZone(fromZoneInsert);
+ termEntry.setToZone(toZoneInsert);
termEntry.setUserCreatedBy(userInfo);
dbConnection.save(termEntry);
- List<Object> actionResult = dbConnection.getDataById(ActionList.class, "actionName", action);
- if(actionResult == null || actionResult.isEmpty()){
+ List<Object> actionResult =
+ dbConnection.getDataById(ActionList.class, "actionName", action);
+ if (actionResult == null || actionResult.isEmpty()) {
saveActionListToDb(dbConnection, action);
}
}
@@ -977,61 +985,66 @@ public class FirewallConfigPolicy extends Policy {
if (path.contains("serviceGroups")) {
/*
- * Inserting serviceGroups data into the ServiceGroup, ServiceList, ProtocolList, and PortList tables
+ * Inserting serviceGroups data into the ServiceGroup, ServiceList, ProtocolList, and PortList
+ * tables
*/
- for(int si = 0; si < serviceGroup.size(); si++) {
+ 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
+ // 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")){
+ if (svcGroupListobj.containsKey("description")) {
description = svcGroupListobj.get("description").toString().replace('"', '\'');
}
JsonArray membersArray = svcGroupListobj.getJsonArray("members");
Boolean isServiceGroup = false;
- if (membersArray!=null){
+ 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
+ // Insert values into GROUPSERVICELIST table if name begins with Group
if (isServiceGroup) {
- List<Object> result = dbConnection.getDataById(GroupServiceList.class, "name", groupName);
- if(result != null && !result.isEmpty()){
+ List<Object> result =
+ dbConnection.getDataById(GroupServiceList.class, "name", groupName);
+ if (result != null && !result.isEmpty()) {
GroupServiceList groupEntry = (GroupServiceList) result.get(0);
dbConnection.delete(groupEntry);
}
saveGroupServiceListTableToDb(dbConnection, groupName, membersArray);
- } else { //Insert JSON data serviceGroup table, protocollist table, and portlist table
+ } 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 transportProtocol =
+ svcGroupListobj.get("transportProtocol").toString().replace('"', '\'');
String ports = svcGroupListobj.get("ports").toString().replace('"', '\'');
List<Object> result = dbConnection.getDataById(ServiceList.class, "name", groupName);
- if(result != null && !result.isEmpty()){
+ if (result != null && !result.isEmpty()) {
ServiceList serviceEntry = (ServiceList) result.get(0);
dbConnection.delete(serviceEntry);
}
- saveServiceListToDb(dbConnection, groupName, description, type, transportProtocol, ports);
+ saveServiceListToDb(dbConnection, groupName, description, type, transportProtocol,
+ ports);
- List<Object> protocolResult = dbConnection.getDataById(ProtocolList.class, "protocolName", transportProtocol);
- if(protocolResult == null || protocolResult.isEmpty()){
+ List<Object> protocolResult =
+ dbConnection.getDataById(ProtocolList.class, "protocolName", transportProtocol);
+ if (protocolResult == null || protocolResult.isEmpty()) {
saveProtocolListToDb(dbConnection, transportProtocol);
}
List<Object> portResult = dbConnection.getDataById(PortList.class, "portName", ports);
- if(portResult == null || portResult.isEmpty()){
+ if (portResult == null || portResult.isEmpty()) {
savePortListToDb(dbConnection, ports);
}
}
@@ -1042,46 +1055,47 @@ public class FirewallConfigPolicy extends Policy {
/*
* Inserting addressGroup data into the ADDRESSGROUP table
*/
- for(int ai=0; ai < addressGroup.size() ; ai++) {
+ 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
+ // 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
+ // create JSON array for members
JsonArray membersArray = addressGroupObj.getJsonArray("members");
String addressGroupName = addressGroupObj.get("name").toString().replace('"', '\'');
String description = null;
- if (addressGroupObj.containsKey("description")){
+ if (addressGroupObj.containsKey("description")) {
description = addressGroupObj.get("description").toString().replace('"', '\'');
}
String prefixIP = null;
String type = null;
- for (int membersIndex=0; membersIndex < membersArray.size(); membersIndex++) {
+ for (int membersIndex = 0; membersIndex < membersArray.size(); membersIndex++) {
JsonObject membersObj = membersArray.getJsonObject(membersIndex);
type = membersObj.get("type").toString().replace("\"", "");
- String value = null;
prefixIP = getName(prefixIP, membersObj, type);
}
- String prefixList = "'"+prefixIP+"'";
+ String prefixList = "'" + prefixIP + "'";
Boolean isAddressGroup = type.contains("REFERENCE");
if (isAddressGroup) {
- List<Object> result = dbConnection.getDataById(AddressGroup.class, "name", addressGroupName);
- if(result != null && !result.isEmpty()){
+ List<Object> result =
+ dbConnection.getDataById(AddressGroup.class, "name", addressGroupName);
+ if (result != null && !result.isEmpty()) {
AddressGroup addressGroupEntry = (AddressGroup) result.get(0);
dbConnection.delete(addressGroupEntry);
}
saveAddressGroupToDb(dbConnection, addressGroupName, description, prefixList);
} else {
- List<Object> result = dbConnection.getDataById(PrefixList.class, "prefixListName", addressGroupName);
- if(result != null && !result.isEmpty()){
+ List<Object> result =
+ dbConnection.getDataById(PrefixList.class, "prefixListName", addressGroupName);
+ if (result != null && !result.isEmpty()) {
PrefixList prefixListEntry = (PrefixList) result.get(0);
dbConnection.delete(prefixListEntry);
}
@@ -1091,8 +1105,9 @@ public class FirewallConfigPolicy extends Policy {
}
}
removeDuplicateValuesFromLookup(dbConnection);
- }catch (Exception e) {
- PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "FirewallConfigPolicy", "Exception executing Firewall queries");
+ } catch (Exception e) {
+ PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "FirewallConfigPolicy",
+ "Exception executing Firewall queries");
return false;
}
return true;
@@ -1123,18 +1138,20 @@ public class FirewallConfigPolicy extends Policy {
dbConnection.save(protocolEntry);
}
- private void saveServiceListToDb(CommonClassDaoImpl dbConnection, String groupName, String description, String type, String transportProtocol, String ports) {
+ private void saveServiceListToDb(CommonClassDaoImpl dbConnection, String groupName, String description, String type,
+ String transportProtocol, String ports) {
ServiceList serviceListEntry = new ServiceList();
serviceListEntry.setServiceName(groupName);
serviceListEntry.setServiceDescription(description);
serviceListEntry.setServiceType(type);
- serviceListEntry.setServiceTransProtocol(transportProtocol);
+ serviceListEntry.setServiceTransportProtocol(transportProtocol);
serviceListEntry.setServiceAppProtocol("null");
serviceListEntry.setServicePorts(ports);
dbConnection.save(serviceListEntry);
}
- private void savePrefixListToDb(CommonClassDaoImpl dbConnection, String addressGroupName, String description, String prefixList) {
+ private void savePrefixListToDb(CommonClassDaoImpl dbConnection, String addressGroupName, String description,
+ String prefixList) {
PrefixList newPrefixList = new PrefixList();
newPrefixList.setPrefixListName(addressGroupName);
newPrefixList.setDescription(description);
@@ -1142,7 +1159,8 @@ public class FirewallConfigPolicy extends Policy {
dbConnection.save(newPrefixList);
}
- private void saveAddressGroupToDb(CommonClassDaoImpl dbConnection, String addressGroupName, String description, String prefixList) {
+ private void saveAddressGroupToDb(CommonClassDaoImpl dbConnection, String addressGroupName, String description,
+ String prefixList) {
AddressGroup newAddressGroup = new AddressGroup();
newAddressGroup.setGroupName(addressGroupName);
newAddressGroup.setDescription(description);
@@ -1151,7 +1169,7 @@ public class FirewallConfigPolicy extends Policy {
}
private JsonObject stringToJson(String jsonString) {
- //Read jsonBody to JsonObject
+ // Read jsonBody to JsonObject
StringReader in = new StringReader(jsonString);
JsonReader jsonReader = Json.createReader(in);
JsonObject json = jsonReader.readObject();
@@ -1167,7 +1185,7 @@ public class FirewallConfigPolicy extends Policy {
oldJason = JsonLoader.fromString(oldJson);
updatedJason = JsonLoader.fromString(json);
} catch (IOException e) {
- LOGGER.error("Exception Occured"+e);
+ LOGGER.error("Exception Occured" + e);
}
return JsonDiff.asJson(oldJason, updatedJason);
}
diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/HandleIncomingNotifications.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/HandleIncomingNotifications.java
index fc08b643e..72e6f488a 100644
--- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/HandleIncomingNotifications.java
+++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/HandleIncomingNotifications.java
@@ -3,6 +3,7 @@
* ONAP-PAP-REST
* ================================================================================
* Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2019 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -23,6 +24,7 @@ package org.onap.policy.pap.xacml.rest.components;
import com.att.research.xacml.api.pap.PAPException;
import com.att.research.xacml.api.pap.PDPPolicy;
import com.att.research.xacml.util.XACMLProperties;
+
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileWriter;
@@ -34,7 +36,9 @@ import java.nio.file.Paths;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
+
import javax.persistence.PersistenceException;
+
import org.apache.commons.io.FilenameUtils;
import org.hibernate.Query;
import org.hibernate.Session;
@@ -44,8 +48,8 @@ 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.dao.PolicyDBException;
+import org.onap.policy.rest.XacmlRestProperties;
+import org.onap.policy.rest.dao.PolicyDbException;
import org.onap.policy.rest.jpa.GroupEntity;
import org.onap.policy.rest.jpa.PdpEntity;
import org.onap.policy.rest.jpa.PolicyEntity;
@@ -70,7 +74,6 @@ public class HandleIncomingNotifications {
public static final String OTHER_CONFIG = "OTHER";
public static final String AUDIT_USER = "audit";
-
private static SessionFactory sessionfactory;
@Autowired
@@ -82,15 +85,24 @@ public class HandleIncomingNotifications {
// Default Constructor
}
+ /**
+ * Handle the incoming HTTP notification.
+ *
+ * @param url the URL
+ * @param entityId the entity id
+ * @param entityType the entity type
+ * @param extraData extra data
+ * @param xacmlPapServlet the servlet to use
+ */
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 = PolicyDBDao.getPolicyDBDaoInstance().getNewTransaction();
+ PolicyDbDaoTransaction transaction = PolicyDbDao.getPolicyDbDaoInstance().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));
+ .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;
@@ -101,6 +113,7 @@ public class HandleIncomingNotifications {
retries = 1;
}
int pauseBetweenRetries = 1000;
+
switch (entityType) {
case POLICY_NOTIFICATION:
@@ -110,7 +123,7 @@ public class HandleIncomingNotifications {
break;
} catch (Exception e) {
logger.debug(e);
- PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR,
+ PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR,
"Caught exception on handleIncomingPolicyChange(" + url + ", " + entityId + ", "
+ extraData + ")");
}
@@ -129,7 +142,7 @@ public class HandleIncomingNotifications {
break;
} catch (Exception e) {
logger.debug(e);
- PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR,
+ PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR,
"Caught exception on handleIncomingPdpChange(" + url + ", " + entityId + ", "
+ transaction + ")");
}
@@ -148,7 +161,7 @@ public class HandleIncomingNotifications {
break;
} catch (Exception e) {
logger.debug(e);
- PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR,
+ PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR,
"Caught exception on handleIncomingGroupChange(" + url + ", " + entityId + ", "
+ extraData + ", " + transaction + ", " + xacmlPapServlet + ")");
}
@@ -160,14 +173,25 @@ public class HandleIncomingNotifications {
}
}
break;
+
+ default:
}
// no changes should be being made in this function, we still need to
// close
transaction.rollbackTransaction();
}
- private void handleIncomingGroupChange(String groupId, String extraData, PolicyDBDaoTransaction transaction)
- throws PAPException, PolicyDBException {
+ /**
+ * Handle an incoming group change.
+ *
+ * @param groupId the group ID
+ * @param extraData extra data
+ * @param transaction the transaction
+ * @throws PAPException on PAP exceptions
+ * @throws PolicyDbException on Policy DB exceptions
+ */
+ private void handleIncomingGroupChange(String groupId, String extraData, PolicyDbDaoTransaction transaction)
+ throws PAPException, PolicyDbException {
GroupEntity groupRecord = null;
long groupIdLong = -1;
try {
@@ -178,7 +202,7 @@ public class HandleIncomingNotifications {
try {
groupRecord = transaction.getGroup(groupIdLong);
} catch (Exception e) {
- PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR,
+ PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR,
"Caught Exception trying to get pdp group record with transaction.getGroup(" + groupIdLong + ");");
throw new PAPException("Could not get local group " + groupIdLong);
}
@@ -189,7 +213,7 @@ public class HandleIncomingNotifications {
// does group folder exist
OnapPDPGroup localGroup = null;
try {
- localGroup = PolicyDBDao.getPolicyDBDaoInstance().getPapEngine().getGroup(groupRecord.getGroupId());
+ localGroup = PolicyDbDao.getPolicyDbDaoInstance().getPapEngine().getGroup(groupRecord.getGroupId());
} catch (Exception e) {
logger.warn("Caught PAPException trying to get local pdp group with papEngine.getGroup(" + groupId + ");",
e);
@@ -197,7 +221,7 @@ public class HandleIncomingNotifications {
if (localGroup == null && extraData != null) {
// here we can try to load an old group id from the extraData
try {
- localGroup = PolicyDBDao.getPolicyDBDaoInstance().getPapEngine().getGroup(extraData);
+ localGroup = PolicyDbDao.getPolicyDbDaoInstance().getPapEngine().getGroup(extraData);
} catch (Exception e) {
logger.warn(
"Caught PAPException trying to get local pdp group with papEngine.getGroup(" + extraData + ");",
@@ -208,17 +232,17 @@ public class HandleIncomingNotifications {
OnapPDPGroup newLocalGroup = null;
if (extraData != null) {
try {
- newLocalGroup = PolicyDBDao.getPolicyDBDaoInstance().getPapEngine().getGroup(extraData);
+ newLocalGroup = PolicyDbDao.getPolicyDbDaoInstance().getPapEngine().getGroup(extraData);
} catch (PAPException e) {
- PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR,
+ PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR,
"Caught PAPException trying to get new pdp group with papEngine.getGroup(" + extraData
+ ");");
}
}
try {
- PolicyDBDao.getPolicyDBDaoInstance().getPapEngine().removeGroup(localGroup, newLocalGroup);
+ PolicyDbDao.getPolicyDbDaoInstance().getPapEngine().removeGroup(localGroup, newLocalGroup);
} catch (NullPointerException | PAPException e) {
- PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR,
+ PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR,
"Caught PAPException trying to get remove pdp group with papEngine.removeGroup(" + localGroup
+ ", " + newLocalGroup + ");");
throw new PAPException("Could not remove group " + groupId);
@@ -226,18 +250,21 @@ public class HandleIncomingNotifications {
} else if (localGroup == null) {
// creating a new group
try {
- PolicyDBDao.getPolicyDBDaoInstance().getPapEngine().newGroup(groupRecord.getgroupName(),
+ PolicyDbDao.getPolicyDbDaoInstance().getPapEngine().newGroup(groupRecord.getGroupName(),
groupRecord.getDescription());
} catch (NullPointerException | PAPException e) {
- PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR,
- "Caught PAPException trying to create pdp group with papEngine.newGroup(groupRecord.getgroupName(), groupRecord.getDescription());");
+ PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR,
+ "Caught PAPException trying to create pdp group with "
+ + "papEngine.newGroup(groupRecord.getGroupName(), groupRecord.getDescription());");
throw new PAPException("Could not create group " + groupRecord);
}
try {
- localGroup = PolicyDBDao.getPolicyDBDaoInstance().getPapEngine().getGroup(groupRecord.getGroupId());
+ localGroup = PolicyDbDao.getPolicyDbDaoInstance().getPapEngine().getGroup(groupRecord.getGroupId());
} catch (PAPException e1) {
- PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e1, PolicyDBDao.POLICYDBDAO_VAR,
- "Caught PAPException trying to get pdp group we just created with papEngine.getGroup(groupRecord.getGroupId());\nAny PDPs or policies in the new group may not have been added");
+ PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e1, PolicyDbDao.POLICYDBDAO_VAR,
+ "Caught PAPException trying to get pdp group we just created with "
+ + "papEngine.getGroup(groupRecord.getGroupId());\nAny PDPs "
+ + "or policies in the new group may not have been added");
return;
}
// add possible pdps to group
@@ -245,11 +272,12 @@ public class HandleIncomingNotifications {
for (Object pdpO : pdpsInGroup) {
PdpEntity pdp = (PdpEntity) pdpO;
try {
- PolicyDBDao.getPolicyDBDaoInstance().getPapEngine().newPDP(pdp.getPdpId(), localGroup,
+ PolicyDbDao.getPolicyDbDaoInstance().getPapEngine().newPDP(pdp.getPdpId(), localGroup,
pdp.getPdpName(), pdp.getDescription(), pdp.getJmxPort());
} catch (NullPointerException | PAPException e) {
- PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR,
- "Caught PAPException trying to get create pdp with papEngine.newPDP(pdp.getPdpId(), localGroup, pdp.getPdpName(), pdp.getDescription(), pdp.getJmxPort());");
+ PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR,
+ "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);
}
}
@@ -269,36 +297,36 @@ public class HandleIncomingNotifications {
// set default if it should be
if (!localGroupClone.isDefaultGroup() && groupRecord.isDefaultGroup()) {
try {
- PolicyDBDao.getPolicyDBDaoInstance().getPapEngine().setDefaultGroup(localGroup);
+ PolicyDbDao.getPolicyDbDaoInstance().getPapEngine().setDefaultGroup(localGroup);
return;
} catch (PAPException e) {
- PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR,
+ PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR,
"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)) {
+ if (updateGroupPoliciesInFileSystem(localGroupClone, localGroup, groupRecord)) {
needToUpdate = true;
}
- if (!PolicyDBDao.stringEquals(localGroupClone.getId(), groupRecord.getGroupId())
- || !PolicyDBDao.stringEquals(localGroupClone.getName(), groupRecord.getgroupName())) {
+ if (!PolicyDbDao.stringEquals(localGroupClone.getId(), groupRecord.getGroupId())
+ || !PolicyDbDao.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());
+ localGroupClone.setName(groupRecord.getGroupName());
needToUpdate = true;
}
- if (!PolicyDBDao.stringEquals(localGroupClone.getDescription(), groupRecord.getDescription())) {
+ if (!PolicyDbDao.stringEquals(localGroupClone.getDescription(), groupRecord.getDescription())) {
localGroupClone.setDescription(groupRecord.getDescription());
needToUpdate = true;
}
if (needToUpdate) {
try {
- PolicyDBDao.getPolicyDBDaoInstance().getPapEngine().updateGroup(localGroupClone);
+ PolicyDbDao.getPolicyDbDaoInstance().getPapEngine().updateGroup(localGroupClone);
} catch (PAPException e) {
- PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR,
+ PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR,
"Caught PAPException trying to update group with papEngine.updateGroup(" + localGroupClone
+ ");");
throw new PAPException("Could not update group " + localGroupClone);
@@ -310,7 +338,7 @@ public class HandleIncomingNotifications {
// 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, PolicyDBException {
+ GroupEntity groupRecord) throws PAPException, PolicyDbException {
if (!(pdpGroup instanceof StdPDPGroup)) {
throw new PAPException("group is not a StdPDPGroup");
}
@@ -325,7 +353,7 @@ public class HandleIncomingNotifications {
}
for (PolicyEntity policy : groupRecord.getPolicies()) {
String pdpPolicyName =
- PolicyDBDao.getPolicyDBDaoInstance().getPdpPolicyName(policy.getPolicyName(), policy.getScope());
+ PolicyDbDao.getPolicyDbDaoInstance().getPdpPolicyName(policy.getPolicyName(), policy.getScope());
if (group.getPolicy(pdpPolicyName) == null) {
didUpdate = true;
if (currentPolicySet.containsKey(pdpPolicyName)) {
@@ -335,7 +363,7 @@ public class HandleIncomingNotifications {
"PolicyDBDao: Adding the new policy to the PDP group after notification: " + pdpPolicyName);
InputStream policyStream = new ByteArrayInputStream(policy.getPolicyData().getBytes());
group.copyPolicyToFile(pdpPolicyName, policyStream);
- ((StdPDPPolicy) (group.getPolicy(pdpPolicyName))).setName(PolicyDBDao.getPolicyDBDaoInstance()
+ ((StdPDPPolicy) (group.getPolicy(pdpPolicyName))).setName(PolicyDbDao.getPolicyDbDaoInstance()
.removeExtensionAndVersionFromPolicyName(pdpPolicyName));
try {
policyStream.close();
@@ -354,7 +382,7 @@ public class HandleIncomingNotifications {
return didUpdate;
}
- private void handleIncomingPdpChange(String pdpId, PolicyDBDaoTransaction transaction) throws PAPException {
+ private void handleIncomingPdpChange(String pdpId, PolicyDbDaoTransaction transaction) throws PAPException {
// get pdp
long pdpIdLong = -1;
try {
@@ -366,7 +394,7 @@ public class HandleIncomingNotifications {
try {
pdpRecord = transaction.getPdp(pdpIdLong);
} catch (Exception e) {
- PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR,
+ PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR,
"Caught Exception trying to get pdp record with transaction.getPdp(" + pdpIdLong + ");");
throw new PAPException("Could not get local pdp " + pdpIdLong);
}
@@ -375,15 +403,15 @@ public class HandleIncomingNotifications {
}
OnapPDP localPdp = null;
try {
- localPdp = PolicyDBDao.getPolicyDBDaoInstance().getPapEngine().getPDP(pdpRecord.getPdpId());
+ localPdp = PolicyDbDao.getPolicyDbDaoInstance().getPapEngine().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 {
- PolicyDBDao.getPolicyDBDaoInstance().getPapEngine().removePDP(localPdp);
+ PolicyDbDao.getPolicyDbDaoInstance().getPapEngine().removePDP(localPdp);
} catch (PAPException e) {
- PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR,
+ PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR,
"Caught PAPException trying to get remove pdp with papEngine.removePDP(" + localPdp + ");");
throw new PAPException("Could not remove pdp " + pdpId);
}
@@ -393,17 +421,18 @@ public class HandleIncomingNotifications {
OnapPDPGroup localGroup = null;
try {
localGroup =
- PolicyDBDao.getPolicyDBDaoInstance().getPapEngine().getGroup(pdpRecord.getGroup().getGroupId());
+ PolicyDbDao.getPolicyDbDaoInstance().getPapEngine().getGroup(pdpRecord.getGroup().getGroupId());
} catch (PAPException e1) {
- PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e1, PolicyDBDao.POLICYDBDAO_VAR,
- "Caught PAPException trying to get local group to add pdp to with papEngine.getGroup(pdpRecord.getGroup().getGroupId());");
+ PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e1, PolicyDbDao.POLICYDBDAO_VAR,
+ "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 {
- PolicyDBDao.getPolicyDBDaoInstance().getPapEngine().newPDP(pdpRecord.getPdpId(), localGroup,
+ PolicyDbDao.getPolicyDbDaoInstance().getPapEngine().newPDP(pdpRecord.getPdpId(), localGroup,
pdpRecord.getPdpName(), pdpRecord.getDescription(), pdpRecord.getJmxPort());
} catch (NullPointerException | PAPException e) {
- PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR,
+ PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR,
"Caught PAPException trying to create pdp with papEngine.newPDP(" + pdpRecord.getPdpId() + ", "
+ localGroup + ", " + pdpRecord.getPdpName() + ", " + pdpRecord.getDescription() + ", "
+ pdpRecord.getJmxPort() + ");");
@@ -411,41 +440,41 @@ public class HandleIncomingNotifications {
}
} else {
boolean needToUpdate = false;
- if (!PolicyDBDao.stringEquals(localPdp.getId(), pdpRecord.getPdpId())
- || !PolicyDBDao.stringEquals(localPdp.getName(), pdpRecord.getPdpName())) {
+ if (!PolicyDbDao.stringEquals(localPdp.getId(), pdpRecord.getPdpId())
+ || !PolicyDbDao.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 (!PolicyDBDao.stringEquals(localPdp.getDescription(), pdpRecord.getDescription())) {
+ if (!PolicyDbDao.stringEquals(localPdp.getDescription(), pdpRecord.getDescription())) {
localPdp.setDescription(pdpRecord.getDescription());
needToUpdate = true;
}
String localPdpGroupId = null;
try {
- localPdpGroupId = PolicyDBDao.getPolicyDBDaoInstance().getPapEngine().getPDPGroup(localPdp).getId();
+ localPdpGroupId = PolicyDbDao.getPolicyDbDaoInstance().getPapEngine().getPDPGroup(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);
+ logger.warn("Caught PAPException trying to get id of local group that pdp is in with "
+ + "localPdpGroupId = papEngine.getPDPGroup(localPdp).getId();", e);
}
- if (!PolicyDBDao.stringEquals(localPdpGroupId, pdpRecord.getGroup().getGroupId())) {
+ if (!PolicyDbDao.stringEquals(localPdpGroupId, pdpRecord.getGroup().getGroupId())) {
OnapPDPGroup newPdpGroup = null;
try {
- newPdpGroup = PolicyDBDao.getPolicyDBDaoInstance().getPapEngine()
+ newPdpGroup = PolicyDbDao.getPolicyDbDaoInstance().getPapEngine()
.getGroup(pdpRecord.getGroup().getGroupId());
} catch (PAPException e) {
// ok, now we have an issue. Time to stop things
- PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR,
- "Caught PAPException trying to get id of local group to move pdp to with papEngine.getGroup(pdpRecord.getGroup().getGroupId());");
+ PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR,
+ "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 {
- PolicyDBDao.getPolicyDBDaoInstance().getPapEngine().movePDP(localPdp, newPdpGroup);
+ PolicyDbDao.getPolicyDbDaoInstance().getPapEngine().movePDP(localPdp, newPdpGroup);
} catch (PAPException e) {
- PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR,
+ PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR,
"Caught PAPException trying to move pdp with papEngine.movePDP(localPdp, newPdpGroup);");
throw new PAPException("Could not move pdp " + localPdp);
}
@@ -456,9 +485,9 @@ public class HandleIncomingNotifications {
}
if (needToUpdate) {
try {
- PolicyDBDao.getPolicyDBDaoInstance().getPapEngine().updatePDP(localPdp);
+ PolicyDbDao.getPolicyDbDaoInstance().getPapEngine().updatePDP(localPdp);
} catch (PAPException e) {
- PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR,
+ PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR,
"Caught PAPException trying to update pdp with papEngine.updatePdp(" + localPdp + ");");
throw new PAPException("Could not update pdp " + localPdp);
}
@@ -490,22 +519,22 @@ public class HandleIncomingNotifications {
if (policy.getConfigurationData() != null) {
subFile =
- getPolicySubFile(policy.getConfigurationData().getConfigurationName(), PolicyDBDao.CONFIG);
+ getPolicySubFile(policy.getConfigurationData().getConfigurationName(), PolicyDbDao.CONFIG);
} else if (policy.getActionBodyEntity() != null) {
- subFile = getPolicySubFile(policy.getActionBodyEntity().getActionBodyName(), PolicyDBDao.ACTION);
+ subFile = getPolicySubFile(policy.getActionBodyEntity().getActionBodyName(), PolicyDbDao.ACTION);
}
if (subFile != null) {
Files.deleteIfExists(subFile);
}
if (policy.getConfigurationData() != null) {
- writePolicySubFile(policy, PolicyDBDao.CONFIG);
+ writePolicySubFile(policy, PolicyDbDao.CONFIG);
} else if (policy.getActionBodyEntity() != null) {
writePolicySubFile(policy, action);
}
}
} catch (IOException e1) {
- PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e1, PolicyDBDao.POLICYDBDAO_VAR,
+ PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e1, PolicyDbDao.POLICYDBDAO_VAR,
"Error occurred while performing [" + action + "] of Policy File: " + policyName);
} finally {
session.close();
@@ -518,8 +547,8 @@ public class HandleIncomingNotifications {
String type = null;
String subTypeName = null;
String subTypeBody = null;
- if (PolicyDBDao.CONFIG.equalsIgnoreCase(policyType)) {
- type = PolicyDBDao.CONFIG;
+ if (PolicyDbDao.CONFIG.equalsIgnoreCase(policyType)) {
+ type = PolicyDbDao.CONFIG;
subTypeName = FilenameUtils.removeExtension(policy.getConfigurationData().getConfigurationName());
subTypeBody = policy.getConfigurationData().getConfigBody();
@@ -539,12 +568,12 @@ public class HandleIncomingNotifications {
subTypeName = subTypeName + ".txt";
}
}
- } else if (PolicyDBDao.ACTION.equalsIgnoreCase(policyType)) {
- type = PolicyDBDao.ACTION;
+ } else if (PolicyDbDao.ACTION.equalsIgnoreCase(policyType)) {
+ type = PolicyDbDao.ACTION;
subTypeName = policy.getActionBodyEntity().getActionBodyName();
subTypeBody = policy.getActionBodyEntity().getActionBody();
}
- Path filePath = Paths.get(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_WEBAPPS).toString(), type);
+ Path filePath = Paths.get(XACMLProperties.getProperty(XacmlRestProperties.PROP_PAP_WEBAPPS), type);
if (subTypeBody == null) {
subTypeBody = "";
@@ -558,11 +587,10 @@ public class HandleIncomingNotifications {
try (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.POLICYDBDAO_VAR,
+ PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR,
"Exception occured while creating Configuration File for Policy : " + policy.getPolicyName());
}
return success;
@@ -571,7 +599,7 @@ public class HandleIncomingNotifications {
Path getPolicySubFile(String inputFileName, String subFileType) {
String filename = inputFileName;
logger.info("getPolicySubFile(" + filename + ", " + subFileType + ")");
- Path filePath = Paths.get(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_WEBAPPS), subFileType);
+ Path filePath = Paths.get(XACMLProperties.getProperty(XacmlRestProperties.PROP_PAP_WEBAPPS), subFileType);
File file = null;
filename = FilenameUtils.removeExtension(filename);
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
index 26c7ed834..5a7a2088f 100644
--- 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
@@ -2,14 +2,14 @@
* ============LICENSE_START=======================================================
* ONAP-PAP-REST
* ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017, 2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -20,6 +20,11 @@
package org.onap.policy.pap.xacml.rest.components;
+import com.att.research.xacml.api.pap.PAPException;
+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 java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
@@ -32,23 +37,6 @@ 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.api.pap.PAPException;
-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;
@@ -61,7 +49,16 @@ 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.TargetType;
+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;
public class MicroServiceConfigPolicy extends Policy {
@@ -70,7 +67,7 @@ public class MicroServiceConfigPolicy extends Policy {
private static Map<String, String> mapAttribute = new HashMap<>();
private static Map<String, String> mapMatch = new HashMap<>();
- private static synchronized Map<String, String> getMatchMap () {
+ private static synchronized Map<String, String> getMatchMap() {
return mapMatch;
}
@@ -82,34 +79,33 @@ public class MicroServiceConfigPolicy extends Policy {
super();
}
- public MicroServiceConfigPolicy(PolicyRestAdapter policyAdapter){
+ public MicroServiceConfigPolicy(PolicyRestAdapter policyAdapter) {
this.policyAdapter = policyAdapter;
}
- //save configuration of the policy based on the policyname
+ // save configuration of the policy based on the policyname
private void saveConfigurations(String policyName, String jsonBody) {
- if(policyName.endsWith(".xml")){
- policyName = policyName.replace(".xml", "");
- }
- try (PrintWriter out = new PrintWriter(CONFIG_HOME + File.separator + policyName +".json")){
+ if (policyName.endsWith(".xml")) {
+ policyName = policyName.replace(".xml", "");
+ }
+ try (PrintWriter out = new PrintWriter(CONFIG_HOME + File.separator + policyName + ".json")) {
out.println(jsonBody);
} catch (Exception e) {
- LOGGER.error("Exception Occured While writing Configuration data"+e);
+ LOGGER.error("Exception Occured While writing Configuration data" + e);
}
}
-
@Override
public Map<String, String> savePolicies() throws PAPException {
Map<String, String> successMap = new HashMap<>();
- if(isPolicyExists()){
+ if (isPolicyExists()) {
successMap.put("EXISTS", "This Policy already exist on the PAP");
return successMap;
}
- if(!isPreparedToSave()){
- //Prep and configure the policy for saving
+ if (!isPreparedToSave()) {
+ // Prep and configure the policy for saving
prepareToSave();
}
@@ -117,18 +113,18 @@ public class MicroServiceConfigPolicy extends Policy {
Path newPolicyPath = null;
newPolicyPath = Paths.get(policyAdapter.getNewFileName());
- successMap = createPolicy(newPolicyPath,getCorrectPolicyDataObject());
+ 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
+ // 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 PAPException{
+ public boolean prepareToSave() throws PAPException {
- if(isPreparedToSave()){
- //we have already done this
+ if (isPreparedToSave()) {
+ // we have already done this
return true;
}
@@ -156,7 +152,6 @@ public class MicroServiceConfigPolicy extends Policy {
policyName = policyName + ".xml";
}
-
PolicyType configPolicy = (PolicyType) policyAdapter.getData();
configPolicy.setDescription(policyAdapter.getPolicyDescription());
@@ -170,32 +165,33 @@ public class MicroServiceConfigPolicy extends Policy {
name = fileName.substring(fileName.lastIndexOf("/") + 1, fileName.length());
}
- //setup values for pulling out matching attributes
+ // setup values for pulling out matching attributes
ObjectMapper mapper = new ObjectMapper();
String matching = null;
Map<String, String> matchMap = null;
try {
JsonNode rootNode = mapper.readTree(policyAdapter.getJsonBody());
- if (policyAdapter.getTtlDate()==null){
+ if (policyAdapter.getTtlDate() == null) {
policyAdapter.setTtlDate("NA");
}
- if (policyAdapter.getServiceType().contains("-v")){
+ if (policyAdapter.getServiceType().contains("-v")) {
matching = getValueFromDictionary(policyAdapter.getServiceType());
} else {
- String jsonVersion = StringUtils.replaceEach(rootNode.get("version").toString(), new String[]{"\""}, new String[]{""});
+ String jsonVersion = StringUtils.replaceEach(rootNode.get("version").toString(),
+ new String[] {"\""}, new String[] {""});
matching = getValueFromDictionary(policyAdapter.getServiceType() + "-v" + jsonVersion);
}
- if (matching != null && !matching.isEmpty()){
+ if (matching != null && !matching.isEmpty()) {
matchMap = Splitter.on(",").withKeyValueSeparator("=").split(matching);
- setMatchMap(matchMap);
- if(policyAdapter.getJsonBody() != null){
- pullMatchValue(rootNode);
+ setMatchMap(matchMap);
+ if (policyAdapter.getJsonBody() != null) {
+ pullMatchValue(rootNode);
}
}
} catch (IOException e1) {
throw new PAPException(e1);
}
-
+
// Match for policyName
allOfOne.getMatch().add(createMatch("PolicyName", name));
@@ -203,7 +199,7 @@ public class MicroServiceConfigPolicy extends Policy {
// Adding the matches to AllOfType element Match for Onap
allOf.getMatch().add(createMatch("ONAPName", policyAdapter.getOnapName()));
- if (matchMap==null || matchMap.isEmpty()){
+ if (matchMap == null || matchMap.isEmpty()) {
// Match for ConfigName
allOf.getMatch().add(createMatch("ConfigName", policyAdapter.getConfigName()));
// Match for Service
@@ -212,29 +208,25 @@ public class MicroServiceConfigPolicy extends Policy {
allOf.getMatch().add(createDynamicMatch("uuid", policyAdapter.getUuid()));
// Match for location
allOf.getMatch().add(createDynamicMatch("location", policyAdapter.getLocation()));
- }else {
- for (Entry<String, String> matchValue : matchMap.entrySet()){
+ } else {
+ for (Entry<String, String> matchValue : matchMap.entrySet()) {
String value = matchValue.getValue();
String key = matchValue.getKey().trim();
- if (value.contains("matching-true")){
- if (mapAttribute.containsKey(key)){
+ 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()));
+ allOf.getMatch().add(createDynamicMatch("RiskType", policyAdapter.getRiskType()));
// Match for riskLevel
- allOf.getMatch().add(
- createDynamicMatch("RiskLevel", String.valueOf(policyAdapter.getRiskLevel())));
+ allOf.getMatch().add(createDynamicMatch("RiskLevel", String.valueOf(policyAdapter.getRiskLevel())));
// Match for riskguard
- allOf.getMatch().add(
- createDynamicMatch("guard", policyAdapter.getGuard()));
+ allOf.getMatch().add(createDynamicMatch("guard", policyAdapter.getGuard()));
// Match for ttlDate
- allOf.getMatch().add(
- createDynamicMatch("TTLDate", policyAdapter.getTtlDate()));
+ allOf.getMatch().add(createDynamicMatch("TTLDate", policyAdapter.getTtlDate()));
AnyOfType anyOf = new AnyOfType();
anyOf.getAllOf().add(allOfOne);
@@ -265,7 +257,8 @@ public class MicroServiceConfigPolicy extends Policy {
try {
accessURI = new URI(ACTION_ID);
} catch (URISyntaxException e) {
- PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "MicroServiceConfigPolicy", "Exception creating ACCESS URI");
+ PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "MicroServiceConfigPolicy",
+ "Exception creating ACCESS URI");
}
accessAttributeDesignator.setCategory(CATEGORY_ACTION);
accessAttributeDesignator.setDataType(STRING_DATATYPE);
@@ -284,7 +277,8 @@ public class MicroServiceConfigPolicy extends Policy {
try {
configURI = new URI(RESOURCE_ID);
} catch (URISyntaxException e) {
- PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "MicroServiceConfigPolicy", "Exception creating Config URI");
+ PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "MicroServiceConfigPolicy",
+ "Exception creating Config URI");
}
configAttributeDesignator.setCategory(CATEGORY_RESOURCE);
configAttributeDesignator.setDataType(STRING_DATATYPE);
@@ -317,36 +311,38 @@ public class MicroServiceConfigPolicy extends Policy {
private void pullMatchValue(JsonNode rootNode) {
Iterator<Map.Entry<String, JsonNode>> fieldsIterator = rootNode.fields();
String newValue = null;
- while (fieldsIterator.hasNext()) {
- Map.Entry<String, JsonNode> 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<Object> 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;
- }
-
+ while (fieldsIterator.hasNext()) {
+ Map.Entry<String, JsonNode> 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<Object> 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) {
+ protected AdviceExpressionsType getAdviceExpressions(int version, String fileName) {
AdviceExpressionsType advices = new AdviceExpressionsType();
AdviceExpressionType advice = new AdviceExpressionType();
advice.setAdviceId("MSID");
@@ -372,12 +368,12 @@ public class MicroServiceConfigPolicy extends Policy {
AttributeValueType AttributeValue = new AttributeValueType();
AttributeValue.setDataType(URI_DATATYPE);
String configName;
- if(policyName.endsWith(".xml")){
+ if (policyName.endsWith(".xml")) {
configName = policyName.replace(".xml", "");
- }else{
+ } else {
configName = policyName;
}
- String content = CONFIG_URL +"/Config/" + configName + ".json";
+ String content = CONFIG_URL + "/Config/" + configName + ".json";
AttributeValue.getContent().add(content);
assignment2.setExpression(new ObjectFactory().createAttributeValue(AttributeValue));
@@ -427,16 +423,16 @@ public class MicroServiceConfigPolicy extends Policy {
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);
Map<String, String> matchMap = getMatchMap();
- if (matchMap==null || matchMap.isEmpty()){
+ if (matchMap == null || matchMap.isEmpty()) {
AttributeAssignmentExpressionType assignment6 = new AttributeAssignmentExpressionType();
assignment6.setAttributeId("matching:" + CONFIGID);
assignment6.setCategory(CATEGORY_RESOURCE);
@@ -449,7 +445,6 @@ public class MicroServiceConfigPolicy extends Policy {
advice.getAttributeAssignmentExpression().add(assignment6);
-
AttributeAssignmentExpressionType assignment8 = new AttributeAssignmentExpressionType();
assignment8.setAttributeId("matching:uuid");
assignment8.setCategory(CATEGORY_RESOURCE);
@@ -474,28 +469,28 @@ public class MicroServiceConfigPolicy extends Policy {
advice.getAttributeAssignmentExpression().add(assignment9);
} else {
- for (Entry<String, String> matchValue : matchMap.entrySet()){
+ for (Entry<String, String> matchValue : matchMap.entrySet()) {
String value = matchValue.getValue();
String key = matchValue.getKey().trim();
- if (value.contains("matching-true")){
- if (mapAttribute.containsKey(key)){
+ 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);
@@ -508,7 +503,7 @@ public class MicroServiceConfigPolicy extends Policy {
advice.getAttributeAssignmentExpression().add(assignment10);
- //Risk Attributes
+ // Risk Attributes
AttributeAssignmentExpressionType assignment11 = new AttributeAssignmentExpressionType();
assignment11.setAttributeId("RiskType");
assignment11.setCategory(CATEGORY_RESOURCE);
diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/NotifyOtherPaps.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/NotifyOtherPaps.java
index 2e2a74015..e9db043bf 100644
--- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/NotifyOtherPaps.java
+++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/NotifyOtherPaps.java
@@ -3,6 +3,7 @@
* ONAP-PAP-REST
* ================================================================================
* Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2019 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -33,14 +34,14 @@ 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.rest.jpa.PolicyDBDaoEntity;
+import org.onap.policy.rest.XacmlRestProperties;
+import org.onap.policy.rest.jpa.PolicyDbDaoEntity;
import org.onap.policy.utils.PeCryptoUtils;
public class NotifyOtherPaps {
private static final Logger LOGGER = FlexLogger.getLogger(NotifyOtherPaps.class);
- private List<PolicyDBDaoEntity> failedPaps = null;
+ private List<PolicyDbDaoEntity> failedPaps = null;
public void notifyOthers(long entityId, String entityType) {
notifyOthers(entityId, entityType, null);
@@ -55,10 +56,10 @@ public class NotifyOtherPaps {
*/
public void notifyOthers(long entityId, String entityType, String newGroupId) {
LOGGER.debug("notifyOthers(long entityId, String entityType, long newGroupId) as notifyOthers(" + entityId + ","
- + entityType + "," + newGroupId + ") called");
+ + entityType + "," + newGroupId + ") called");
failedPaps = new ArrayList<>();
- List<?> otherServers = PolicyDBDao.getPolicyDBDaoInstance().getOtherServers();
+ List<?> otherServers = PolicyDbDao.getPolicyDbDaoInstance().getOtherServers();
// Notify other paps
startNotifyThreads(otherServers, entityId, entityType, newGroupId);
// Retry for failed paps
@@ -67,7 +68,7 @@ public class NotifyOtherPaps {
}
}
- private void startNotifyThreads(List<?> otherServers, long entityId, String entityType, String newGroupId) {
+ protected void startNotifyThreads(List<?> otherServers, long entityId, String entityType, String newGroupId) {
LinkedList<Thread> notifyThreads = new LinkedList<>();
// we're going to run notifications in parallel threads to speed things
// up
@@ -102,10 +103,9 @@ public class NotifyOtherPaps {
@Override
public void run() {
- PolicyDBDao dao = new PolicyDBDao();
- PolicyDBDaoEntity dbdEntity = (PolicyDBDaoEntity) obj;
- String otherPap = dbdEntity.getPolicyDBDaoUrl();
- String username = dbdEntity.getUsername();
+ PolicyDbDao dao = new PolicyDbDao();
+ PolicyDbDaoEntity dbdEntity = (PolicyDbDaoEntity) obj;
+ String otherPap = dbdEntity.getPolicyDbDaoUrl();
String txt;
try {
txt = PeCryptoUtils.decrypt(dbdEntity.getPassword());
@@ -116,7 +116,6 @@ public class NotifyOtherPaps {
}
HttpURLConnection connection = null;
- UUID requestId = UUID.randomUUID();
URL url;
String papUrl;
try {
@@ -143,11 +142,11 @@ public class NotifyOtherPaps {
return;
}
if (newGroupId == null) {
- url = new URL(otherPap + "?policydbdaourl=" + papUrl + "&entityid=" + entityId + "&entitytype="
- + entityType);
+ url = new URL(
+ otherPap + "?policydbdaourl=" + papUrl + "&entityid=" + entityId + "&entitytype=" + entityType);
} else {
url = new URL(otherPap + "?policydbdaourl=" + papUrl + "&entityid=" + entityId + "&entitytype="
- + entityType + "&extradata=" + newGroupId);
+ + entityType + "&extradata=" + newGroupId);
}
} catch (MalformedURLException e) {
LOGGER.warn("Caught MalformedURLException on: new URL()", e);
@@ -174,6 +173,10 @@ public class NotifyOtherPaps {
LOGGER.warn("Caught ProtocolException on connection.setRequestMethod(\"PUT\");", e);
return;
}
+
+ String username = dbdEntity.getUsername();
+ UUID requestId = UUID.randomUUID();
+
Base64.Encoder encoder = Base64.getEncoder();
String encoding = encoder.encodeToString((username + ":" + txt).getBytes(StandardCharsets.UTF_8));
connection.setRequestProperty("Authorization", "Basic " + encoding);
@@ -183,7 +186,7 @@ public class NotifyOtherPaps {
int readTimeout;
try {
readTimeout =
- Integer.parseInt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_NOTIFY_TIMEOUT));
+ 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.", e);
readTimeout = 10000;
@@ -212,7 +215,7 @@ public class NotifyOtherPaps {
LOGGER.info("PolicyDBDao: NotifyOtherThread received response 200 from pap server on notify");
} else {
LOGGER.warn("PolicyDBDao: NotifyOtherThread connection response code not 200, received: "
- + connection.getResponseCode());
+ + connection.getResponseCode());
failedPaps.add(dbdEntity);
}
} catch (Exception e) {
diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/OptimizationConfigPolicy.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/OptimizationConfigPolicy.java
index 2719a155b..097a33f8e 100644
--- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/OptimizationConfigPolicy.java
+++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/OptimizationConfigPolicy.java
@@ -2,14 +2,14 @@
* ============LICENSE_START=======================================================
* ONAP-PAP-REST
* ================================================================================
- * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2018-2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -20,6 +20,11 @@
package org.onap.policy.pap.xacml.rest.components;
+import com.att.research.xacml.api.pap.PAPException;
+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 java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
@@ -32,23 +37,6 @@ 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.OptimizationModels;
-
-import com.att.research.xacml.api.pap.PAPException;
-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;
@@ -61,7 +49,16 @@ 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.TargetType;
+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.OptimizationModels;
public class OptimizationConfigPolicy extends Policy {
@@ -70,7 +67,7 @@ public class OptimizationConfigPolicy extends Policy {
private static Map<String, String> mapAttribute = new HashMap<>();
private static Map<String, String> mapMatch = new HashMap<>();
- private static synchronized Map<String, String> getMatchMap () {
+ private static synchronized Map<String, String> getMatchMap() {
return mapMatch;
}
@@ -82,36 +79,35 @@ public class OptimizationConfigPolicy extends Policy {
super();
}
- public OptimizationConfigPolicy(PolicyRestAdapter policyAdapter){
+ public OptimizationConfigPolicy(PolicyRestAdapter policyAdapter) {
this.policyAdapter = policyAdapter;
}
- //save configuration of the policy based on the policyname
+ // save configuration of the policy based on the policyname
private void saveConfigurations(String policyName, String jsonBody) {
- if(policyName.endsWith(".xml")){
+ if (policyName.endsWith(".xml")) {
policyName = policyName.replace(".xml", "");
}
- try (PrintWriter out = new PrintWriter(CONFIG_HOME + File.separator + policyName +".json");){
+ try (PrintWriter out = new PrintWriter(CONFIG_HOME + File.separator + policyName + ".json");) {
out.println(jsonBody);
} catch (Exception e) {
- LOGGER.error("Exception Occured While writing Configuration data"+e);
+ LOGGER.error("Exception Occured While writing Configuration data" + e);
}
}
-
@Override
public Map<String, String> savePolicies() throws PAPException {
Map<String, String> successMap = new HashMap<>();
- if(isPolicyExists()){
+ if (isPolicyExists()) {
successMap.put("EXISTS", "This Policy already exist on the PAP");
return successMap;
}
- if(!isPreparedToSave()){
- //Prep and configure the policy for saving
+ if (!isPreparedToSave()) {
+ // Prep and configure the policy for saving
prepareToSave();
}
@@ -119,18 +115,18 @@ public class OptimizationConfigPolicy extends Policy {
Path newPolicyPath = null;
newPolicyPath = Paths.get(policyAdapter.getNewFileName());
- successMap = createPolicy(newPolicyPath,getCorrectPolicyDataObject());
+ 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
+ // 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 PAPException{
+ public boolean prepareToSave() throws PAPException {
- if(isPreparedToSave()){
- //we have already done this
+ if (isPreparedToSave()) {
+ // we have already done this
return true;
}
@@ -158,7 +154,6 @@ public class OptimizationConfigPolicy extends Policy {
policyName = policyName + ".xml";
}
-
PolicyType configPolicy = (PolicyType) policyAdapter.getData();
configPolicy.setDescription(policyAdapter.getPolicyDescription());
@@ -172,32 +167,33 @@ public class OptimizationConfigPolicy extends Policy {
name = fileName.substring(fileName.lastIndexOf('/') + 1, fileName.length());
}
- //setup values for pulling out matching attributes
+ // setup values for pulling out matching attributes
ObjectMapper mapper = new ObjectMapper();
String matching = null;
Map<String, String> matchMap = null;
try {
JsonNode rootNode = mapper.readTree(policyAdapter.getJsonBody());
- if (policyAdapter.getTtlDate()==null){
+ if (policyAdapter.getTtlDate() == null) {
policyAdapter.setTtlDate("NA");
}
- if (policyAdapter.getServiceType().contains("-v")){
+ if (policyAdapter.getServiceType().contains("-v")) {
matching = getValueFromDictionary(policyAdapter.getServiceType());
} else {
- String jsonVersion = StringUtils.replaceEach(rootNode.get("version").toString(), new String[]{"\""}, new String[]{""});
+ String jsonVersion = StringUtils.replaceEach(rootNode.get("version").toString(),
+ new String[] {"\""}, new String[] {""});
matching = getValueFromDictionary(policyAdapter.getServiceType() + "-v" + jsonVersion);
}
- if (matching != null && !matching.isEmpty()){
+ if (matching != null && !matching.isEmpty()) {
matchMap = Splitter.on(",").withKeyValueSeparator("=").split(matching);
setMatchMap(matchMap);
- if(policyAdapter.getJsonBody() != null){
- pullMatchValue(rootNode);
+ if (policyAdapter.getJsonBody() != null) {
+ pullMatchValue(rootNode);
}
}
} catch (IOException e1) {
throw new PAPException(e1);
}
-
+
// Match for policyName
allOfOne.getMatch().add(createMatch("PolicyName", name));
@@ -205,28 +201,24 @@ public class OptimizationConfigPolicy extends Policy {
// Adding the matches to AllOfType element Match for Onap
allOf.getMatch().add(createMatch("ONAPName", policyAdapter.getOnapName()));
- if (matchMap!=null && !matchMap.isEmpty()) {
- for (Entry<String, String> matchValue : matchMap.entrySet()){
+ if (matchMap != null && !matchMap.isEmpty()) {
+ for (Entry<String, String> matchValue : matchMap.entrySet()) {
String value = matchValue.getValue();
String key = matchValue.getKey().trim();
- if (value.contains("matching-true") && mapAttribute.containsKey(key)){
+ if (value.contains("matching-true") && mapAttribute.containsKey(key)) {
allOf.getMatch().add(createDynamicMatch(key, mapAttribute.get(key)));
}
}
}
// Match for riskType
- allOf.getMatch().add(
- createDynamicMatch("RiskType", policyAdapter.getRiskType()));
+ allOf.getMatch().add(createDynamicMatch("RiskType", policyAdapter.getRiskType()));
// Match for riskLevel
- allOf.getMatch().add(
- createDynamicMatch("RiskLevel", String.valueOf(policyAdapter.getRiskLevel())));
+ allOf.getMatch().add(createDynamicMatch("RiskLevel", String.valueOf(policyAdapter.getRiskLevel())));
// Match for riskguard
- allOf.getMatch().add(
- createDynamicMatch("guard", policyAdapter.getGuard()));
+ allOf.getMatch().add(createDynamicMatch("guard", policyAdapter.getGuard()));
// Match for ttlDate
- allOf.getMatch().add(
- createDynamicMatch("TTLDate", policyAdapter.getTtlDate()));
+ allOf.getMatch().add(createDynamicMatch("TTLDate", policyAdapter.getTtlDate()));
AnyOfType anyOf = new AnyOfType();
anyOf.getAllOf().add(allOfOne);
@@ -257,7 +249,8 @@ public class OptimizationConfigPolicy extends Policy {
try {
accessURI = new URI(ACTION_ID);
} catch (URISyntaxException e) {
- PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "OptimizationConfigPolicy", "Exception creating ACCESS URI");
+ PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "OptimizationConfigPolicy",
+ "Exception creating ACCESS URI");
}
accessAttributeDesignator.setCategory(CATEGORY_ACTION);
accessAttributeDesignator.setDataType(STRING_DATATYPE);
@@ -276,7 +269,8 @@ public class OptimizationConfigPolicy extends Policy {
try {
configURI = new URI(RESOURCE_ID);
} catch (URISyntaxException e) {
- PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "OptimizationConfigPolicy", "Exception creating Config URI");
+ PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "OptimizationConfigPolicy",
+ "Exception creating Config URI");
}
configAttributeDesignator.setCategory(CATEGORY_RESOURCE);
configAttributeDesignator.setDataType(STRING_DATATYPE);
@@ -309,36 +303,38 @@ public class OptimizationConfigPolicy extends Policy {
private void pullMatchValue(JsonNode rootNode) {
Iterator<Map.Entry<String, JsonNode>> fieldsIterator = rootNode.fields();
String newValue = null;
- while (fieldsIterator.hasNext()) {
- Map.Entry<String, JsonNode> 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<Object> result = dbConnection.getDataById(OptimizationModels.class, "modelName:version", modelName+":"+modelVersion);
- if(result != null && !result.isEmpty()){
- OptimizationModels model = (OptimizationModels) result.get(0);
- ruleTemplate = model.getAnnotation();
- }
- return ruleTemplate;
- }
-
+ while (fieldsIterator.hasNext()) {
+ Map.Entry<String, JsonNode> 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<Object> result =
+ dbConnection.getDataById(OptimizationModels.class, "modelName:version", modelName + ":" + modelVersion);
+ if (result != null && !result.isEmpty()) {
+ OptimizationModels model = (OptimizationModels) result.get(0);
+ ruleTemplate = model.getAnnotation();
+ }
+ return ruleTemplate;
+ }
+
// Data required for Advice part is setting here.
- private AdviceExpressionsType getAdviceExpressions(int version, String fileName) {
+ protected AdviceExpressionsType getAdviceExpressions(int version, String fileName) {
AdviceExpressionsType advices = new AdviceExpressionsType();
AdviceExpressionType advice = new AdviceExpressionType();
advice.setAdviceId("OptimizationID");
@@ -366,18 +362,18 @@ public class OptimizationConfigPolicy extends Policy {
AttributeValueType attributeValue = new AttributeValueType();
attributeValue.setDataType(URI_DATATYPE);
String configName;
- if(policyName.endsWith(".xml")){
+ if (policyName.endsWith(".xml")) {
configName = policyName.replace(".xml", "");
- }else{
+ } else {
configName = policyName;
}
- String content = CONFIG_URL +"/Config/" + configName + ".json";
+ String content = CONFIG_URL + "/Config/" + configName + ".json";
attributeValue.getContent().add(content);
assignment2.setExpression(new ObjectFactory().createAttributeValue(attributeValue));
advice.getAttributeAssignmentExpression().add(assignment2);
- //PolicyName Attribute Assignment
+ // PolicyName Attribute Assignment
AttributeAssignmentExpressionType assignment3 = new AttributeAssignmentExpressionType();
assignment3.setAttributeId("PolicyName");
assignment3.setCategory(CATEGORY_RESOURCE);
@@ -395,7 +391,7 @@ public class OptimizationConfigPolicy extends Policy {
assignment3.setExpression(new ObjectFactory().createAttributeValue(attributeValue3));
advice.getAttributeAssignmentExpression().add(assignment3);
- //VersionNumber Attribute Assignment
+ // VersionNumber Attribute Assignment
AttributeAssignmentExpressionType assignment4 = new AttributeAssignmentExpressionType();
assignment4.setAttributeId("VersionNumber");
assignment4.setCategory(CATEGORY_RESOURCE);
@@ -408,7 +404,7 @@ public class OptimizationConfigPolicy extends Policy {
advice.getAttributeAssignmentExpression().add(assignment4);
- //OnapName Attribute Assignment
+ // OnapName Attribute Assignment
AttributeAssignmentExpressionType assignment5 = new AttributeAssignmentExpressionType();
assignment5.setAttributeId("matching:" + ONAPID);
assignment5.setCategory(CATEGORY_RESOURCE);
@@ -421,41 +417,41 @@ public class OptimizationConfigPolicy extends Policy {
advice.getAttributeAssignmentExpression().add(assignment5);
- //ServiceType Attribute Assignment
+ // ServiceType Attribute Assignment
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);
// Add matching attribute assignments if exist
Map<String, String> matchMap = getMatchMap();
- if (matchMap!=null && !matchMap.isEmpty()) {
- for (Entry<String, String> matchValue : matchMap.entrySet()){
+ if (matchMap != null && !matchMap.isEmpty()) {
+ for (Entry<String, String> matchValue : matchMap.entrySet()) {
String value = matchValue.getValue();
String key = matchValue.getKey().trim();
- if (value.contains("matching-true") && mapAttribute.containsKey(key)){
+ if (value.contains("matching-true") && 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);
}
}
}
-
+
// Priority Attribute Assignment
AttributeAssignmentExpressionType assignment10 = new AttributeAssignmentExpressionType();
assignment10.setAttributeId("Priority");
@@ -469,7 +465,7 @@ public class OptimizationConfigPolicy extends Policy {
advice.getAttributeAssignmentExpression().add(assignment10);
- //RiskType Attribute Assignment
+ // RiskType Attribute Assignment
AttributeAssignmentExpressionType assignment11 = new AttributeAssignmentExpressionType();
assignment11.setAttributeId("RiskType");
assignment11.setCategory(CATEGORY_RESOURCE);
@@ -482,7 +478,7 @@ public class OptimizationConfigPolicy extends Policy {
advice.getAttributeAssignmentExpression().add(assignment11);
- //RiskLevel Attribute Assignment
+ // RiskLevel Attribute Assignment
AttributeAssignmentExpressionType assignment12 = new AttributeAssignmentExpressionType();
assignment12.setAttributeId("RiskLevel");
assignment12.setCategory(CATEGORY_RESOURCE);
@@ -495,7 +491,7 @@ public class OptimizationConfigPolicy extends Policy {
advice.getAttributeAssignmentExpression().add(assignment12);
- //Guard Attribute Assignment
+ // Guard Attribute Assignment
AttributeAssignmentExpressionType assignment13 = new AttributeAssignmentExpressionType();
assignment13.setAttributeId("guard");
assignment13.setCategory(CATEGORY_RESOURCE);
@@ -508,7 +504,7 @@ public class OptimizationConfigPolicy extends Policy {
advice.getAttributeAssignmentExpression().add(assignment13);
- //TTLDate Attribute Assignment
+ // TTLDate Attribute Assignment
AttributeAssignmentExpressionType assignment14 = new AttributeAssignmentExpressionType();
assignment14.setAttributeId("TTLDate");
assignment14.setCategory(CATEGORY_RESOURCE);
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
index 549d26b28..4873fc5ce 100644
--- 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
@@ -2,15 +2,15 @@
* ============LICENSE_START=======================================================
* ONAP-PAP-REST
* ================================================================================
- * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
* Modified Copyright (C) 2018 Samsung Electronics Co., Ltd.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -21,6 +21,12 @@
package org.onap.policy.pap.xacml.rest.components;
+import com.att.research.xacml.api.pap.PAPException;
+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 java.io.IOException;
import java.io.InputStream;
import java.net.URI;
@@ -30,24 +36,21 @@ import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;
+
+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.PolicySetType;
+import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType;
+
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.XACMLRestProperties;
+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.api.pap.PAPException;
-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.PolicySetType;
-import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType;
public abstract class Policy {
@@ -141,7 +144,7 @@ public abstract class Policy {
/**
* 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();
@@ -324,12 +327,12 @@ public abstract class Policy {
private static void loadWebapps() throws PAPException {
if (actionHome == null || configHome == null) {
- Path webappsPath = Paths.get(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_WEBAPPS));
+ 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);
+ PolicyLogger.error("Invalid Webapps Path Location property : " + XacmlRestProperties.PROP_PAP_WEBAPPS);
throw new PAPException(
- "Invalid Webapps Path Location property : " + XACMLRestProperties.PROP_PAP_WEBAPPS);
+ "Invalid Webapps Path Location property : " + XacmlRestProperties.PROP_PAP_WEBAPPS);
}
Path webappsPathConfig;
Path webappsPathAction;
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
index 9a39b6ed1..9af380b05 100644
--- 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
@@ -24,6 +24,7 @@ package org.onap.policy.pap.xacml.rest.components;
import com.att.research.xacml.api.pap.PAPException;
import com.att.research.xacml.api.pap.PDPPolicy;
import com.att.research.xacml.util.XACMLProperties;
+
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.net.URI;
@@ -36,7 +37,9 @@ import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
+
import javax.persistence.PersistenceException;
+
import org.apache.commons.io.FilenameUtils;
import org.hibernate.Criteria;
import org.hibernate.LockMode;
@@ -48,15 +51,15 @@ 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.XacmlRestProperties;
import org.onap.policy.rest.adapter.PolicyRestAdapter;
-import org.onap.policy.rest.dao.PolicyDBException;
+import org.onap.policy.rest.dao.PolicyDbException;
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.PolicyDbDaoEntity;
import org.onap.policy.rest.jpa.PolicyEntity;
import org.onap.policy.utils.PeCryptoUtils;
import org.onap.policy.xacml.api.XACMLErrorConstants;
@@ -68,9 +71,12 @@ import org.onap.policy.xacml.std.pap.StdPDPPolicy;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
+/**
+ * The Class PolicyDbDao.
+ */
@Component
-public class PolicyDBDao {
- private static final Logger logger = FlexLogger.getLogger(PolicyDBDao.class);
+public class PolicyDbDao {
+ private static final Logger logger = FlexLogger.getLogger(PolicyDbDao.class);
public static final String JSON_CONFIG = "JSON";
public static final String XML_CONFIG = "XML";
public static final String PROPERTIES_CONFIG = "PROPERTIES";
@@ -86,65 +92,82 @@ public class PolicyDBDao {
public static final String PDPENTITY_SELECT =
"SELECT p FROM PdpEntity p WHERE p.pdpId=:pdpId AND p.deleted=:deleted";
public static final String GROUP_NOT_FOUND = "The group could not be found with id ";
- public static final String FOUND_IN_DB_NOT_DEL =
- " were found in the database that are not deleted";
+ public static final String FOUND_IN_DB_NOT_DEL = " were found in the database that are not deleted";
public static final String MORE_THAN_ONE_PDP = "Somehow, more than one pdp with the same id ";
- public static final String DELETED_STATUS_FOUND =
- " and deleted status were found in the database";
+ public static final String DELETED_STATUS_FOUND = " and deleted status were found in the database";
public static final String DUPLICATE_GROUPID = "Somehow, more than one group with the same id ";
public static final String PDP_ID = "pdpId";
- public static final String QUERY_FAILED_FOR_GROUP =
- "Query failed trying to check for existing group";
+ public static final String QUERY_FAILED_FOR_GROUP = "Query failed trying to check for existing group";
public static final String QUERY_FAILED_GET_GROUP = "Query failed trying to get group ";
public static final String SCOPE = "scope";
public static final String POLICYDBDAO_VAR = "PolicyDBDao";
public static final String DUP_POLICYID = "Somehow, more than one policy with the id ";
public static final String FOUND_IN_DB = " were found in the database";
- private static PolicyDBDao currentInstance = null;
+
+ private static final String AUDIT_STR = "Audit";
+
+ private static PolicyDbDao currentInstance = null;
private static boolean isJunit = false;
private static SessionFactory sessionfactory;
private List<?> otherServers;
private PAPPolicyEngine papEngine;
-
/**
* 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.
+ * @throws IllegalStateException if a PolicyDBDao instance is null. Call createPolicyDBDaoInstance
+ * (EntityManagerFactory emf) to get this.
*/
- public static PolicyDBDao getPolicyDBDaoInstance() {
+ public static PolicyDbDao getPolicyDbDaoInstance() {
logger.debug("getPolicyDBDaoInstance() as getPolicyDBDaoInstance() called");
if (currentInstance != null) {
return currentInstance;
} else {
- currentInstance = new PolicyDBDao("init");
+ currentInstance = new PolicyDbDao("init");
}
return currentInstance;
}
+ /**
+ * Sets the pap engine.
+ *
+ * @param papEngine2 the new pap engine
+ */
public void setPapEngine(PAPPolicyEngine papEngine2) {
this.papEngine = papEngine2;
}
+ /**
+ * Instantiates a new policy db dao.
+ *
+ * @param sessionFactory the session factory
+ */
@Autowired
- public PolicyDBDao(SessionFactory sessionFactory) {
- PolicyDBDao.sessionfactory = sessionFactory;
+ public PolicyDbDao(SessionFactory sessionFactory) {
+ PolicyDbDao.sessionfactory = sessionFactory;
}
- public PolicyDBDao() {
+ /**
+ * Instantiates a new policy db dao.
+ */
+ public PolicyDbDao() {
// Default Constructor
}
- public PolicyDBDao(String init) {
+ /**
+ * Initialize the DAO.
+ *
+ * @param init initiation parameters
+ */
+ public PolicyDbDao(String init) {
// not needed in this release
if (!register()) {
- PolicyLogger.error(
- "This server's PolicyDBDao instance could not be registered and may not reveive updates");
+ PolicyLogger
+ .error("This server's PolicyDBDao instance could not be registered and may not reveive updates");
}
- otherServers = getRemotePolicyDBDaoList();
+ otherServers = getRemotePolicyDbDaoList();
if (logger.isDebugEnabled()) {
logger.debug("Number of remote PolicyDBDao instances: " + otherServers.size());
}
@@ -153,21 +176,26 @@ public class PolicyDBDao {
}
}
- // 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)
+ /**
+ * Start a synchronized transaction.
+ *
+ * <p>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)
+ *
+ * @param session the session
+ * @param waitTime the wait time
+ */
@SuppressWarnings("deprecation")
public void startTransactionSynced(Session session, int waitTime) {
- logger.debug("\n\nstartTransactionSynced(Hibernate Session,int waitTime) as "
- + "\n startTransactionSynced(" + session + "," + waitTime + ") called\n\n");
+ logger.debug("\n\nstartTransactionSynced(Hibernate Session,int waitTime) as " + "\n startTransactionSynced("
+ + session + "," + waitTime + ") called\n\n");
DatabaseLockEntity lock = null;
session.beginTransaction();
try {
if (logger.isDebugEnabled()) {
- logger.debug("\n\nstartTransactionSynced():" + "\n ATTEMPT to get the DB lock"
- + "\n\n");
+ logger.debug("\n\nstartTransactionSynced():" + "\n ATTEMPT to get the DB lock" + "\n\n");
}
- lock = (DatabaseLockEntity) session.get(DatabaseLockEntity.class, 1,
- LockMode.PESSIMISTIC_WRITE);
+ lock = (DatabaseLockEntity) session.get(DatabaseLockEntity.class, 1, LockMode.PESSIMISTIC_WRITE);
if (logger.isDebugEnabled()) {
logger.debug("\n\nstartTransactionSynced():" + "\n GOT the DB lock" + "\n\n");
}
@@ -182,17 +210,17 @@ public class PolicyDBDao {
}
/**
- * Gets the list of other registered PolicyDBDaos from the database
+ * Gets the list of other registered PolicyDBDaos from the database.
*
- * @return List (type PolicyDBDaoEntity) of other PolicyDBDaos
+ * @return List (type PolicyDbDaoEntity) of other PolicyDBDaos
*/
- private List<?> getRemotePolicyDBDaoList() {
+ private List<?> getRemotePolicyDbDaoList() {
logger.debug("getRemotePolicyDBDaoList() as getRemotePolicyDBDaoList() called");
- List<?> policyDBDaoEntityList = new LinkedList<>();
+ List<?> policyDbDaoEntityList = new LinkedList<>();
Session session = sessionfactory.openSession();
try {
- Criteria cr = session.createCriteria(PolicyDBDaoEntity.class);
- policyDBDaoEntityList = cr.list();
+ Criteria cr = session.createCriteria(PolicyDbDaoEntity.class);
+ policyDbDaoEntityList = cr.list();
} catch (Exception e) {
PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, POLICYDBDAO_VAR,
"Exception querying for other registered PolicyDBDaos");
@@ -201,32 +229,37 @@ public class PolicyDBDao {
try {
session.close();
} catch (Exception e) {
- logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW
- + "Error While Closing Connection/Statement" + e);
+ logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement" + e);
}
}
- return policyDBDaoEntityList;
+ return policyDbDaoEntityList;
}
- public PolicyDBDaoTransaction getNewTransaction() {
+ /**
+ * Gets the new transaction.
+ *
+ * @return the new transaction
+ */
+ public PolicyDbDaoTransaction getNewTransaction() {
logger.debug("getNewTransaction() as getNewTransaction() called");
return new PolicyDbDaoTransactionInstance("init");
}
- /*
- * 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.
+ /**
+ * Get a new audit transaction.
+ *
+ * <p>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.
+ *
+ * @return the new audit transaction
*/
- public PolicyDBDaoTransaction getNewAuditTransaction() {
+ 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));
+ 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));
+ int auditTimeoutMs = Integer.parseInt(XACMLProperties.getProperty(XacmlRestProperties.PROP_PAP_AUDIT_TIMEOUT));
return new PolicyDbDaoTransactionInstance(auditTimeoutMs, auditWaitMs);
}
@@ -235,10 +268,10 @@ public class PolicyDBDao {
*
* @param one A String or null to compare
* @param two A String or null to compare
+ * @return true, if successful
*/
public static boolean stringEquals(String one, String two) {
- logger.debug("stringEquals(String one, String two) as stringEquals(" + one + ", " + two
- + ") called");
+ logger.debug("stringEquals(String one, String two) as stringEquals(" + one + ", " + two + ") called");
if (one == null && two == null) {
return true;
}
@@ -249,20 +282,25 @@ public class PolicyDBDao {
}
/**
- * Returns the url of this local pap server, removing the username and password, if they are
- * present
+ * 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
*/
public String[] getPapUrlUserPass() {
logger.debug("getPapUrl() as getPapUrl() called");
- String url = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_URL);
+ String url = XACMLProperties.getProperty(XacmlRestProperties.PROP_PAP_URL);
if (url == null) {
return null;
}
return splitPapUrlUserPass(url);
}
+ /**
+ * Split the user and password of a PAP URL.
+ *
+ * @param url the URL
+ * @return the user and password
+ */
public String[] splitPapUrlUserPass(String url) {
String[] urlUserPass = new String[3];
String[] commaSplit = url.split(",");
@@ -272,15 +310,14 @@ public class PolicyDBDao {
urlUserPass[2] = commaSplit[2];
}
if (urlUserPass[1] == null || "".equals(urlUserPass[1])) {
- String usernamePropertyValue =
- XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_USERID);
+ String usernamePropertyValue = XACMLProperties.getProperty(XacmlRestProperties.PROP_PAP_USERID);
if (usernamePropertyValue != null) {
urlUserPass[1] = usernamePropertyValue;
}
}
if (urlUserPass[2] == null || "".equals(urlUserPass[2])) {
String passwordPropertyValue =
- PeCryptoUtils.decrypt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_PASS));
+ PeCryptoUtils.decrypt(XACMLProperties.getProperty(XacmlRestProperties.PROP_PAP_PASS));
if (passwordPropertyValue != null) {
urlUserPass[2] = passwordPropertyValue;
}
@@ -291,7 +328,7 @@ public class PolicyDBDao {
}
/**
- * Register the PolicyDBDao instance in the PolicyDBDaoEntity table
+ * Register the PolicyDBDao instance in the PolicyDbDaoEntity table.
*
* @return Boolean, were we able to register?
*/
@@ -332,26 +369,25 @@ public class PolicyDBDao {
}
}
}
- logger.debug(
- "\nPolicyDBDao.register. Database locking and concurrency control is initialized\n");
- PolicyDBDaoEntity foundPolicyDBDaoEntity = null;
- Criteria cr = session.createCriteria(PolicyDBDaoEntity.class);
- cr.add(Restrictions.eq("policyDBDaoUrl", url[0]));
+ logger.debug("\nPolicyDBDao.register. Database locking and concurrency control is initialized\n");
+ PolicyDbDaoEntity foundPolicyDbDaoEntity = null;
+ Criteria cr = session.createCriteria(PolicyDbDaoEntity.class);
+ cr.add(Restrictions.eq("policyDbDaoUrl", url[0]));
List<?> data = cr.list();
if (!data.isEmpty()) {
- foundPolicyDBDaoEntity = (PolicyDBDaoEntity) data.get(0);
+ foundPolicyDbDaoEntity = (PolicyDbDaoEntity) data.get(0);
}
// encrypt the password
String txt = PeCryptoUtils.encrypt(url[2]);
- if (foundPolicyDBDaoEntity == null) {
- PolicyDBDaoEntity newPolicyDBDaoEntity = new PolicyDBDaoEntity();
- newPolicyDBDaoEntity.setPolicyDBDaoUrl(url[0]);
- newPolicyDBDaoEntity.setDescription("PAP server at " + url[0]);
- newPolicyDBDaoEntity.setUsername(url[1]);
- newPolicyDBDaoEntity.setPassword(txt);
+ if (foundPolicyDbDaoEntity == null) {
+ PolicyDbDaoEntity newPolicyDbDaoEntity = new PolicyDbDaoEntity();
+ newPolicyDbDaoEntity.setPolicyDbDaoUrl(url[0]);
+ newPolicyDbDaoEntity.setDescription("PAP server at " + url[0]);
+ newPolicyDbDaoEntity.setUsername(url[1]);
+ newPolicyDbDaoEntity.setPassword(txt);
try {
- session.persist(newPolicyDBDaoEntity);
+ session.persist(newPolicyDbDaoEntity);
session.getTransaction().commit();
} catch (Exception e) {
logger.debug(e);
@@ -365,13 +401,13 @@ public class PolicyDBDao {
}
} else {
// just want to update in order to change modified date
- if (url[1] != null && !stringEquals(url[1], foundPolicyDBDaoEntity.getUsername())) {
- foundPolicyDBDaoEntity.setUsername(url[1]);
+ if (url[1] != null && !stringEquals(url[1], foundPolicyDbDaoEntity.getUsername())) {
+ foundPolicyDbDaoEntity.setUsername(url[1]);
}
- if (txt != null && !stringEquals(txt, foundPolicyDBDaoEntity.getPassword())) {
- foundPolicyDBDaoEntity.setPassword(txt);
+ if (txt != null && !stringEquals(txt, foundPolicyDbDaoEntity.getPassword())) {
+ foundPolicyDbDaoEntity.setPassword(txt);
}
- foundPolicyDBDaoEntity.preUpdate();
+ foundPolicyDbDaoEntity.preUpdate();
try {
session.getTransaction().commit();
} catch (Exception e) {
@@ -390,12 +426,20 @@ public class PolicyDBDao {
return true;
}
- /*
- * This method is called during all pushPolicy transactions and makes sure the file system group
- * is in sync with the database groupentity
+ /**
+ * Synchronize group policies in the fuile system.
+ *
+ * <p>This method is called during all pushPolicy transactions and makes sure the file system group is in sync with
+ * the database group entity
+ *
+ * @param pdpGroup the pdp group
+ * @param groupentity the groupentity
+ * @return the std PDP group
+ * @throws PAPException the PAP exception
+ * @throws PolicyDbException the policy db exception
*/
- public StdPDPGroup synchronizeGroupPoliciesInFileSystem(StdPDPGroup pdpGroup,
- GroupEntity groupentity) throws PAPException, PolicyDBException {
+ public StdPDPGroup synchronizeGroupPoliciesInFileSystem(StdPDPGroup pdpGroup, GroupEntity groupentity)
+ throws PAPException, PolicyDbException {
HashMap<String, PDPPolicy> currentPolicyMap = new HashMap<>();
HashSet<String> newPolicyIdSet = new HashSet<>();
@@ -415,23 +459,19 @@ public class PolicyDBDao {
// convert PolicyEntity object to PDPPolicy
String name = pdpPolicyId.replace(".xml", "");
name = name.substring(0, name.lastIndexOf('.'));
- InputStream policyStream =
- new ByteArrayInputStream(policy.getPolicyData().getBytes());
+ InputStream policyStream = new ByteArrayInputStream(policy.getPolicyData().getBytes());
pdpGroup.copyPolicyToFile(pdpPolicyId, name, policyStream);
- URI location =
- Paths.get(pdpGroup.getDirectory().toAbsolutePath().toString(), pdpPolicyId)
- .toUri();
+ URI location = Paths.get(pdpGroup.getDirectory().toAbsolutePath().toString(), pdpPolicyId).toUri();
StdPDPPolicy newPolicy = null;
try {
newPolicy = new StdPDPPolicy(pdpPolicyId, true,
removeExtensionAndVersionFromPolicyName(pdpPolicyId), location);
newPolicySet.add(newPolicy);
- logger.info("Adding new policy to PDPGroup - " + newPolicy.getId()
- + ", Location - " + location);
+ logger.info("Adding new policy to PDPGroup - " + newPolicy.getId() + ", Location - " + location);
} catch (Exception e) {
logger.debug(e);
- PolicyLogger.error(
- "PolicyDBDao: Exception occurred while creating the StdPDPPolicy newPolicy object "
+ PolicyLogger
+ .error("PolicyDBDao: Exception occurred while creating the StdPDPPolicy newPolicy object "
+ e.getMessage());
}
}
@@ -444,39 +484,44 @@ public class PolicyDBDao {
} catch (Exception e) {
logger.debug(e);
PolicyLogger.error(
- "PolicyDBDao: Exception occurred while attempting to delete the old version of the policy file from the group. "
- + e.getMessage());
+ "PolicyDBDao: Exception occurred while attempting to delete the old version of the policy"
+ + " file from the group. " + e.getMessage());
}
}
}
- logger.info(
- "PolicyDBDao: Adding new policy set to group to keep filesystem and DB in sync");
+ logger.info("PolicyDBDao: Adding new policy set to group to keep filesystem and DB in sync");
pdpGroup.setPolicies(newPolicySet);
return pdpGroup;
}
- public String removeExtensionAndVersionFromPolicyName(String originalPolicyName)
- throws PolicyDBException {
+ /**
+ * Removes the extension and version from policy name.
+ *
+ * @param originalPolicyName the original policy name
+ * @return the string
+ * @throws PolicyDbException the policy db exception
+ */
+ public String removeExtensionAndVersionFromPolicyName(String originalPolicyName) throws PolicyDbException {
return getPolicyNameAndVersionFromPolicyFileName(originalPolicyName)[0];
}
/**
- * Splits apart the policy name and version from a policy file path
+ * Splits apart the policy name and version from a policy file path.
*
- * @param originalPolicyName: a policy file name ex: Config_policy.2.xml
+ * @param originalPolicyName the original policy name
* @return An array [0]: The policy name, [1]: the policy version, as a string
+ * @throws PolicyDbException the policy db exception
*/
- public String[] getPolicyNameAndVersionFromPolicyFileName(String originalPolicyName)
- throws PolicyDBException {
+ public String[] getPolicyNameAndVersionFromPolicyFileName(String originalPolicyName) throws PolicyDbException {
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 PolicyDBException();
+ throw new PolicyDbException();
}
} catch (Exception e) {
nameAndVersion[0] = originalPolicyName;
@@ -485,7 +530,7 @@ public class PolicyDBDao {
try {
nameAndVersion[1] = policyName.substring(policyName.lastIndexOf('.') + 1);
if (isNullOrEmpty(nameAndVersion[1])) {
- throw new PolicyDBException();
+ throw new PolicyDbException();
}
} catch (Exception e) {
nameAndVersion[1] = "1";
@@ -494,6 +539,13 @@ public class PolicyDBDao {
return nameAndVersion;
}
+ /**
+ * Get the PDP policy by name.
+ *
+ * @param name The name to get
+ * @param scope The scope to use
+ * @return the policy.
+ */
public String getPdpPolicyName(String name, String scope) {
String finalName = "";
finalName += scope;
@@ -507,18 +559,28 @@ public class PolicyDBDao {
return fileName.substring(0, fileName.lastIndexOf('.'));
}
+ /**
+ * Audit local database.
+ *
+ * @param papEngine2 the pap engine 2
+ */
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_VAR,
- "auditLocalDatabase() error");
+ PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, POLICYDBDAO_VAR, "auditLocalDatabase() error");
logger.error("Exception Occured" + e);
}
}
+ /**
+ * Audit local file system.
+ *
+ * @param group the group
+ * @return the std PDP group
+ */
public StdPDPGroup auditLocalFileSystem(StdPDPGroup group) {
logger.info("Starting Local File System group audit");
@@ -534,17 +596,15 @@ public class PolicyDBDao {
if (groupQueryList != null && !groupQueryList.isEmpty()) {
GroupEntity dbgroup = (GroupEntity) groupQueryList.get(0);
updatedGroup = synchronizeGroupPoliciesInFileSystem(group, dbgroup);
- logger.info(
- "Group was updated during file system audit: " + updatedGroup.toString());
+ logger.info("Group was updated during file system audit: " + updatedGroup.toString());
}
- } catch (PAPException | PolicyDBException e) {
+ } catch (PAPException | PolicyDbException e) {
logger.error(e);
} catch (Exception e) {
logger.error(e);
PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, POLICYDBDAO_VAR,
"Caught Exception trying to check if group exists groupQuery.getResultList()");
- throw new PersistenceException(
- "Query failed trying to check if group " + group.getId() + " exists");
+ throw new PersistenceException("Query failed trying to check if group " + group.getId() + " exists");
}
session.getTransaction().commit();
@@ -553,9 +613,8 @@ public class PolicyDBDao {
return updatedGroup;
}
- /*
- * This method is called at startup to recreate config data from DB to the file system.
- *
+ /**
+ * Synchronize config data in file system.
*/
public void synchronizeConfigDataInFileSystem() {
@@ -571,8 +630,7 @@ public class PolicyDBDao {
final Criteria configDataQuery = session.createCriteria(cl.getName());
@SuppressWarnings("unchecked")
final List<T> configDataResult = configDataQuery.list();
- Path webappsPath = Paths
- .get(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_WEBAPPS), type);
+ Path webappsPath = Paths.get(XACMLProperties.getProperty(XacmlRestProperties.PROP_PAP_WEBAPPS), type);
for (final T configData : configDataResult) {
String configName = null;
@@ -588,8 +646,7 @@ public class PolicyDBDao {
} else {
configName = ((ActionBodyEntity) configData).getActionBodyName();
configBody = (((ActionBodyEntity) configData).getActionBody() != null)
- ? ((ActionBodyEntity) configData).getActionBody()
- .getBytes(StandardCharsets.UTF_8)
+ ? ((ActionBodyEntity) configData).getActionBody().getBytes(StandardCharsets.UTF_8)
: "".getBytes();
}
Path filePath = Paths.get(webappsPath.toString(), configName);
@@ -609,6 +666,9 @@ public class PolicyDBDao {
session.close();
}
+ /**
+ * Delete all group tables.
+ */
public void deleteAllGroupTables() {
logger.debug("PolicyDBDao.deleteAllGroupTables() called");
Session session = sessionfactory.openSession();
@@ -624,13 +684,17 @@ public class PolicyDBDao {
session.close();
}
+ /**
+ * Audit groups.
+ *
+ * @param papEngine2 the pap engine 2
+ */
@SuppressWarnings("unchecked")
public void auditGroups(PAPPolicyEngine papEngine2) {
logger.debug("PolicyDBDao.auditGroups() called");
Session session = sessionfactory.openSession();
session.getTransaction().begin();
- final String AUDIT_STR = "Audit";
try {
Set<OnapPDPGroup> groups = papEngine2.getOnapPDPGroups();
@@ -642,7 +706,7 @@ public class PolicyDBDao {
groupEntity.setDescription(grp.getDescription());
groupEntity.setDefaultGroup(grp.isDefaultGroup());
groupEntity.setCreatedBy(AUDIT_STR);
- groupEntity.setGroupId(createNewPDPGroupId(grp.getId()));
+ groupEntity.setGroupId(createNewPdpGroupId(grp.getId()));
groupEntity.setModifiedBy(AUDIT_STR);
session.persist(groupEntity);
Set<OnapPDP> pdps = grp.getOnapPdps();
@@ -662,15 +726,13 @@ public class PolicyDBDao {
for (PDPPolicy policy : policies) {
try {
- String[] stringArray =
- getNameScopeAndVersionFromPdpPolicy(policy.getId());
+ String[] stringArray = getNameScopeAndVersionFromPdpPolicy(policy.getId());
if (stringArray == null) {
throw new IllegalArgumentException(
"Invalid input - policyID must contain name, scope and version");
}
List<PolicyEntity> policyEntityList;
- Query getPolicyEntitiesQuery =
- session.getNamedQuery("PolicyEntity.findByNameAndScope");
+ Query getPolicyEntitiesQuery = session.getNamedQuery("PolicyEntity.findByNameAndScope");
getPolicyEntitiesQuery.setParameter("name", stringArray[0]);
getPolicyEntitiesQuery.setParameter(SCOPE, stringArray[1]);
@@ -694,8 +756,7 @@ public class PolicyDBDao {
}
} catch (Exception e) {
session.getTransaction().rollback();
- PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, POLICYDBDAO_VAR,
- "Exception auditGroups outer catch");
+ PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, POLICYDBDAO_VAR, "Exception auditGroups outer catch");
session.close();
return;
}
@@ -705,6 +766,13 @@ public class PolicyDBDao {
}
+ /**
+ * Gets the config file.
+ *
+ * @param filename the filename
+ * @param policy the policy
+ * @return the config file
+ */
public String getConfigFile(String filename, PolicyRestAdapter policy) {
if (policy == null) {
return getConfigFile(filename, (String) null);
@@ -714,12 +782,18 @@ public class PolicyDBDao {
// copied from ConfigPolicy.java and modified
// Here we are adding the extension for the configurations file based on the
+ /**
+ * Gets the config file.
+ *
+ * @param inputFilename the input filename
+ * @param configType the config type
+ * @return the config file
+ */
// config type selection for saving.
public String getConfigFile(String inputFilename, String configType) {
String filename = inputFilename;
- logger.debug(
- "getConfigFile(String filename, String scope, String configType) as getConfigFile("
- + filename + ", " + configType + ") called");
+ logger.debug("getConfigFile(String filename, String scope, String configType) as getConfigFile(" + filename
+ + ", " + configType + ") called");
filename = FilenameUtils.removeExtension(filename);
String id = configType;
@@ -740,6 +814,12 @@ public class PolicyDBDao {
return filename;
}
+ /**
+ * Gets the name scope and version from pdp policy.
+ *
+ * @param fileName the file name
+ * @return the name scope and version from pdp policy
+ */
public String[] getNameScopeAndVersionFromPdpPolicy(String fileName) {
String[] splitByDots = fileName.split("\\.");
if (splitByDots.length < 3) {
@@ -763,7 +843,13 @@ public class PolicyDBDao {
return returnArray;
}
- public static String createNewPDPGroupId(String name) {
+ /**
+ * Creates the new PDP group id.
+ *
+ * @param name the name
+ * @return the string
+ */
+ public static String createNewPdpGroupId(String name) {
String id = name;
// replace "bad" characters with sequences that will be ok for file
// names and properties keys.
@@ -786,7 +872,7 @@ public class PolicyDBDao {
}
/**
- * Checks if any of the given strings are empty or null
+ * 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
@@ -800,47 +886,107 @@ public class PolicyDBDao {
return false;
}
+ /**
+ * Gets the other servers.
+ *
+ * @return the other servers
+ */
public List<?> getOtherServers() {
return otherServers;
}
+ /**
+ * Sets the other servers.
+ *
+ * @param otherServers the new other servers
+ */
public void setOtherServers(List<?> otherServers) {
this.otherServers = otherServers;
}
+ /**
+ * Gets the pap engine.
+ *
+ * @return the pap engine
+ */
public PAPPolicyEngine getPapEngine() {
return papEngine;
}
-
+ /**
+ * Checks if is junit.
+ *
+ * @return true, if is junit
+ */
public static boolean isJunit() {
return isJunit;
}
+ /**
+ * Sets the junit.
+ *
+ * @param isJunit the new junit
+ */
public static void setJunit(boolean isJunit) {
- PolicyDBDao.isJunit = isJunit;
+ PolicyDbDao.isJunit = isJunit;
}
- public static PolicyDBDaoTestClass getPolicyDBDaoTestClass() {
- return new PolicyDBDao().new PolicyDBDaoTestClass();
+ /**
+ * Gets the policy DB dao test class.
+ *
+ * @return the policy DB dao test class
+ */
+ public static PolicyDbDaoTestClass getPolicyDbDaoTestClass() {
+ return new PolicyDbDao().new PolicyDbDaoTestClass();
}
- final class PolicyDBDaoTestClass {
+ /**
+ * The Class PolicyDBDaoTestClass.
+ */
+ final class PolicyDbDaoTestClass {
+
+ /**
+ * Gets the config file.
+ *
+ * @param filename the filename
+ * @param scope the scope
+ * @param policy the policy
+ * @return the config file
+ */
String getConfigFile(String filename, String scope, PolicyRestAdapter policy) {
- return scope + "." + PolicyDBDao.this.getConfigFile(filename, policy);
- }
-
- String[] getPolicyNameAndVersionFromPolicyFileName(String originalPolicyName)
- throws PolicyDBException {
- return PolicyDBDao.this.getPolicyNameAndVersionFromPolicyFileName(originalPolicyName);
- }
-
+ return scope + "." + PolicyDbDao.this.getConfigFile(filename, policy);
+ }
+
+ /**
+ * Gets the policy name and version from policy file name.
+ *
+ * @param originalPolicyName the original policy name
+ * @return the policy name and version from policy file name
+ * @throws PolicyDbException the policy db exception
+ */
+ String[] getPolicyNameAndVersionFromPolicyFileName(String originalPolicyName) throws PolicyDbException {
+ return PolicyDbDao.this.getPolicyNameAndVersionFromPolicyFileName(originalPolicyName);
+ }
+
+ /**
+ * Gets the name scope and version from pdp policy.
+ *
+ * @param fileName the file name
+ * @return the name scope and version from pdp policy
+ */
String[] getNameScopeAndVersionFromPdpPolicy(String fileName) {
- return PolicyDBDao.this.getNameScopeAndVersionFromPdpPolicy(fileName);
+ return PolicyDbDao.this.getNameScopeAndVersionFromPdpPolicy(fileName);
}
+ /**
+ * Gets the pdp policy name.
+ *
+ * @param name the name
+ * @param scope the scope
+ * @return the pdp policy name
+ */
String getPdpPolicyName(String name, String scope) {
- return PolicyDBDao.this.getPdpPolicyName(name, scope);
+ return PolicyDbDao.this.getPdpPolicyName(name, scope);
}
}
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
index dbb2fa830..70ca36ac7 100644
--- 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
@@ -3,6 +3,7 @@
* ONAP-PAP-REST
* ================================================================================
* Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2019 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -21,16 +22,19 @@
package org.onap.policy.pap.xacml.rest.components;
import com.att.research.xacml.api.pap.PAPException;
+
import java.util.List;
+
import javax.persistence.PersistenceException;
-import org.onap.policy.rest.dao.PolicyDBException;
+
+import org.onap.policy.rest.dao.PolicyDbException;
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 org.onap.policy.xacml.std.pap.StdPDPGroup;
-public interface PolicyDBDaoTransaction {
+public interface PolicyDbDaoTransaction {
/**
* Commits (makes permanent) the current transaction. Also, notifies other PolicyDBDao instances on other PAP
@@ -42,7 +46,7 @@ public interface PolicyDBDaoTransaction {
public void commitTransaction();
/**
- * Create or update a policy
+ * 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
@@ -50,10 +54,10 @@ public interface PolicyDBDaoTransaction {
* @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 PolicyDBException;
+ public void createPolicy(Policy policy, String username) throws PolicyDbException;
/**
- * Check if the PolicyDBDaoTransaction is currently open
+ * 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.
*/
@@ -70,9 +74,8 @@ public interface PolicyDBDaoTransaction {
*/
public void close();
-
/**
- * Create a new PDP group in the database
+ * 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
@@ -83,23 +86,22 @@ public interface PolicyDBDaoTransaction {
* @throws PersistenceException If a database error occurs
*/
public void createGroup(String groupID, String groupName, String groupDescription, String username)
- throws PolicyDBException;
+ throws PolicyDbException;
/**
- * Updates a group in the database with a new name of description
+ * 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
* @param userId needed to store user information in policyAuditlog table during transaction.
* @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 requestType, String userId) throws PolicyDBException;
+ public void updateGroup(OnapPDPGroup group, String requestType, String userId) throws PolicyDbException;
/**
- * Updates a PDP in the database with new information
+ * Updates a PDP in the database with new information.
*
* @param pdp The PDP to update
* @param username Username of the user performing the operation
@@ -107,7 +109,7 @@ public interface PolicyDBDaoTransaction {
* @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 PolicyDBException;
+ public void updatePdp(OnapPDP pdp, String username) throws PolicyDbException;
/**
* Change the default group in the database to the group provided.
@@ -118,7 +120,7 @@ public interface PolicyDBDaoTransaction {
* @throws IllegalStateException If a transaction is already open
* @throws PersistenceException If a database error occurs
*/
- public void changeDefaultGroup(OnapPDPGroup group, String username) throws PolicyDBException;
+ public void changeDefaultGroup(OnapPDPGroup group, String username) throws PolicyDbException;
/**
* Moves a PDP to a new group.
@@ -130,41 +132,37 @@ public interface PolicyDBDaoTransaction {
* @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 PolicyDBException;
+ public void movePdp(OnapPDP pdp, OnapPDPGroup group, String username) throws PolicyDbException;
/**
- * Add a new PDP to an existing group
+ * 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 pdpJmxPort PDP JMX port
* @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 PolicyDBException;
+ String username) throws PolicyDbException;
/**
- * Add an existing policy to an existing group
+ * 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
- * @return
- * @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 PolicyDBException
+ * @return the PDP groups
+ * @throws PolicyDbException on DB exceptions
*/
public StdPDPGroup addPolicyToGroup(String group, String policyID, String requestType, String username)
- throws PolicyDBException;
-
+ throws PolicyDbException;
/**
- * Delete an existing PDP groupPolicyDBException
+ * Delete an existing PDP groupPolicyDBException.
*
* @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
@@ -174,7 +172,7 @@ public interface PolicyDBDaoTransaction {
* @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 PolicyDBException;
+ public void deleteGroup(OnapPDPGroup group, OnapPDPGroup moveToGroup, String username) throws PolicyDbException;
/**
* Removes an existing PDP from its group and deletes it.
@@ -184,7 +182,7 @@ public interface PolicyDBDaoTransaction {
* @throws IllegalStateException If a transaction is already open
* @throws PersistenceException If a database error occurs
*/
- public void removePdpFromGroup(String pdpID, String username) throws PolicyDBException;
+ public void removePdpFromGroup(String pdpID, String username) throws PolicyDbException;
public GroupEntity getGroup(long groupKey);
diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/PolicyDbDaoTransactionInstance.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/PolicyDbDaoTransactionInstance.java
index f63649ddc..e694f7e0b 100644
--- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/PolicyDbDaoTransactionInstance.java
+++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/PolicyDbDaoTransactionInstance.java
@@ -2,7 +2,8 @@
* ============LICENSE_START=======================================================
* ONAP-PAP-REST
* ================================================================================
- * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2019-2020 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2019 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -23,6 +24,7 @@ package org.onap.policy.pap.xacml.rest.components;
import com.att.research.xacml.api.pap.PAPException;
import com.att.research.xacml.api.pap.PDPPolicy;
import com.att.research.xacml.util.XACMLProperties;
+
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
@@ -36,14 +38,17 @@ import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
+
import javax.persistence.PersistenceException;
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 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.io.FilenameUtils;
import org.apache.commons.io.IOUtils;
import org.hibernate.Query;
@@ -53,9 +58,9 @@ 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.XacmlRestProperties;
import org.onap.policy.rest.adapter.PolicyRestAdapter;
-import org.onap.policy.rest.dao.PolicyDBException;
+import org.onap.policy.rest.dao.PolicyDbException;
import org.onap.policy.rest.jpa.ActionBodyEntity;
import org.onap.policy.rest.jpa.ConfigurationDataEntity;
import org.onap.policy.rest.jpa.GroupEntity;
@@ -71,12 +76,16 @@ import org.springframework.stereotype.Component;
import org.w3c.dom.Document;
import org.xml.sax.InputSource;
-
@Component
-public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction {
-
+public class PolicyDbDaoTransactionInstance implements PolicyDbDaoTransaction {
private static final Logger logger = FlexLogger.getLogger(PolicyDbDaoTransactionInstance.class);
+ // Recurring constants
+ private static final String BRACKET_CALLED = ") called";
+ private static final String EXISTS = " exists";
+ private static final String GROUP = "group";
+ private static final String CAUGHT_EXCEPTION_ON_NOTIFY_OTHERS = "Caught Exception on notifyOthers(";
+
private final Object emLock = new Object();
long policyId;
long groupId;
@@ -86,8 +95,7 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction {
private Thread transactionTimer;
private static final String POLICY_NOTIFICATION = "policy";
private static final String PDP_NOTIFICATION = "pdp";
- private static final String GROUP_NOTIFICATION = "group";
-
+ private static final String GROUP_NOTIFICATION = GROUP;
private static final String DECISIONMS_MODEL = "MicroService_Model";
private static boolean isJunit = false;
@@ -100,8 +108,8 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction {
*/
public PolicyDbDaoTransactionInstance(String test) {
// call the constructor with arguments
- this(Integer.parseInt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_TRANS_TIMEOUT)),
- Integer.parseInt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_TRANS_WAIT)));
+ this(Integer.parseInt(XACMLProperties.getProperty(XacmlRestProperties.PROP_PAP_TRANS_TIMEOUT)),
+ Integer.parseInt(XACMLProperties.getProperty(XacmlRestProperties.PROP_PAP_TRANS_WAIT)));
}
public PolicyDbDaoTransactionInstance() {
@@ -115,7 +123,6 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction {
private static SessionFactory sessionfactory;
-
/**
* Instantiates a new policy DB dao transaction instance.
*
@@ -134,7 +141,7 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction {
synchronized (emLock) {
session = sessionfactory.openSession();
try {
- PolicyDBDao.getPolicyDBDaoInstance().startTransactionSynced(session, transactionWaitTime);
+ PolicyDbDao.getPolicyDbDaoInstance().startTransactionSynced(session, transactionWaitTime);
} catch (Exception e) {
logger.error("Could not lock transaction within " + transactionWaitTime + " milliseconds" + e);
throw new PersistenceException(
@@ -221,7 +228,7 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction {
try {
session.getTransaction().commit();
} catch (RollbackException e) {
- PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR,
+ PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR,
"Caught RollbackException on em.getTransaction().commit()");
throw new PersistenceException("The commit failed. Message:\n" + e.getMessage());
}
@@ -232,16 +239,16 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction {
try {
otherPaps.notifyOthers(policyId, POLICY_NOTIFICATION, newGroupId);
} catch (Exception e) {
- PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR,
- "Caught Exception on notifyOthers(" + policyId + "," + POLICY_NOTIFICATION + ","
+ PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR,
+ CAUGHT_EXCEPTION_ON_NOTIFY_OTHERS + policyId + "," + POLICY_NOTIFICATION + ","
+ newGroupId + ")");
}
} else {
try {
otherPaps.notifyOthers(policyId, POLICY_NOTIFICATION);
} catch (Exception e) {
- PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR,
- "Caught Exception on notifyOthers(" + policyId + "," + POLICY_NOTIFICATION + ")");
+ PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR,
+ CAUGHT_EXCEPTION_ON_NOTIFY_OTHERS + policyId + "," + POLICY_NOTIFICATION + ")");
}
}
}
@@ -251,16 +258,16 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction {
try {
otherPaps.notifyOthers(groupId, GROUP_NOTIFICATION, newGroupId);
} catch (Exception e) {
- PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR,
- "Caught Exception on notifyOthers(" + groupId + "," + GROUP_NOTIFICATION + ","
+ PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR,
+ CAUGHT_EXCEPTION_ON_NOTIFY_OTHERS + groupId + "," + GROUP_NOTIFICATION + ","
+ newGroupId + ")");
}
} else {
try {
otherPaps.notifyOthers(groupId, GROUP_NOTIFICATION);
} catch (Exception e) {
- PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR,
- "Caught Exception on notifyOthers(" + groupId + "," + GROUP_NOTIFICATION + ")");
+ PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR,
+ CAUGHT_EXCEPTION_ON_NOTIFY_OTHERS + groupId + "," + GROUP_NOTIFICATION + ")");
}
}
}
@@ -269,8 +276,8 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction {
try {
otherPaps.notifyOthers(pdpId, PDP_NOTIFICATION);
} catch (Exception e) {
- PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR,
- "Caught Exception on notifyOthers(" + pdpId + "," + PDP_NOTIFICATION + ")");
+ PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR,
+ CAUGHT_EXCEPTION_ON_NOTIFY_OTHERS + pdpId + "," + PDP_NOTIFICATION + ")");
}
}
}
@@ -287,13 +294,13 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction {
try {
session.getTransaction().rollback();
} catch (Exception e) {
- PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR,
+ PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR,
"Could not rollback transaction");
}
try {
session.close();
} catch (Exception e) {
- PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR,
+ PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR,
"Could not close Hibernate Session.");
}
@@ -317,7 +324,7 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction {
+ " String policyName, String policyDataString) as createPolicy(" + policy + ", " + username + ", "
+ policyScope + ", " + policyName + ", " + policyDataString + ") called");
synchronized (emLock) {
- PolicyDBDao policyDbDao = new PolicyDBDao();
+ PolicyDbDao policyDbDao = new PolicyDbDao();
checkBeforeOperationRun();
String configName = policyName;
if (policyName.contains("Config_")) {
@@ -332,7 +339,7 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction {
policyName = policyName.split(":")[1];
Query createPolicyQuery = session
.createQuery("SELECT p FROM PolicyEntity p WHERE p.scope=:scope AND p.policyName=:policyName");
- createPolicyQuery.setParameter(PolicyDBDao.SCOPE, policyScope);
+ createPolicyQuery.setParameter(PolicyDbDao.SCOPE, policyScope);
createPolicyQuery.setParameter("policyName", policyName);
List<?> createPolicyQueryList = createPolicyQuery.list();
PolicyEntity newPolicyEntity;
@@ -351,7 +358,7 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction {
}
ActionBodyEntity newActionBodyEntity = null;
- if (policy.getPolicyType().equals(PolicyDBDao.ACTION)) {
+ if (policy.getPolicyType().equals(PolicyDbDao.ACTION)) {
boolean abupdate = false;
if (newPolicyEntity.getActionBodyEntity() == null) {
newActionBodyEntity = new ActionBodyEntity();
@@ -410,7 +417,7 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction {
}
ConfigurationDataEntity newConfigurationDataEntity;
- if (PolicyDBDao.CONFIG.equals(policy.getPolicyType())
+ if (PolicyDbDao.CONFIG.equals(policy.getPolicyType())
|| DECISIONMS_MODEL.equals(policy.getRuleProvider())) {
boolean configUpdate;
if (newPolicyEntity.getConfigurationData() == null) {
@@ -423,7 +430,7 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction {
}
if (newConfigurationDataEntity != null) {
- if (!PolicyDBDao.stringEquals(newConfigurationDataEntity.getConfigurationName(),
+ if (!PolicyDbDao.stringEquals(newConfigurationDataEntity.getConfigurationName(),
policyDbDao.getConfigFile(configName, policy))) {
newConfigurationDataEntity.setConfigurationName(policyDbDao.getConfigFile(configName, policy));
}
@@ -478,22 +485,22 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction {
}
policyId = newPolicyEntity.getPolicyId();
- if (!PolicyDBDao.stringEquals(newPolicyEntity.getPolicyName(), policyName)) {
+ if (!PolicyDbDao.stringEquals(newPolicyEntity.getPolicyName(), policyName)) {
newPolicyEntity.setPolicyName(policyName);
}
- if (!PolicyDBDao.stringEquals(newPolicyEntity.getCreatedBy(), username)) {
+ if (!PolicyDbDao.stringEquals(newPolicyEntity.getCreatedBy(), username)) {
newPolicyEntity.setCreatedBy(username);
}
- if (!PolicyDBDao.stringEquals(newPolicyEntity.getDescription(), policy.getPolicyDescription())) {
+ if (!PolicyDbDao.stringEquals(newPolicyEntity.getDescription(), policy.getPolicyDescription())) {
newPolicyEntity.setDescription(policy.getPolicyDescription());
}
- if (!PolicyDBDao.stringEquals(newPolicyEntity.getModifiedBy(), username)) {
+ if (!PolicyDbDao.stringEquals(newPolicyEntity.getModifiedBy(), username)) {
newPolicyEntity.setModifiedBy(username);
}
- if (!PolicyDBDao.stringEquals(newPolicyEntity.getPolicyData(), policyDataString)) {
+ if (!PolicyDbDao.stringEquals(newPolicyEntity.getPolicyData(), policyDataString)) {
newPolicyEntity.setPolicyData(policyDataString);
}
- if (!PolicyDBDao.stringEquals(newPolicyEntity.getScope(), policyScope)) {
+ if (!PolicyDbDao.stringEquals(newPolicyEntity.getScope(), policyScope)) {
newPolicyEntity.setScope(policyScope);
}
if (newPolicyEntity.isDeleted()) {
@@ -518,7 +525,7 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction {
InputStream policyXmlStream = null;
try {
logger.debug("createPolicy(PolicyRestAdapter policy, String username) as createPolicy(" + policy + ","
- + username + ") called");
+ + username + BRACKET_CALLED);
String policyScope = policy.policyAdapter.getDomainDir().replace(File.separator, ".");
// Does not need to be XACMLPolicyWriterWithPapNotify since it is
// already in the PAP
@@ -535,22 +542,26 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction {
policyDataString = IOUtils.toString(policyXmlStream);
} catch (IOException e) {
policyDataString = "could not read";
- PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR,
+ PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR,
"Caught IOException on IOUtils.toString(" + policyXmlStream + ")");
throw new IllegalArgumentException("Cannot parse the policy xml from the PolicyRestAdapter.");
}
IOUtils.closeQuietly(policyXmlStream);
- if (PolicyDBDao.isJunit()) {
+ if (PolicyDbDao.isJunit()) {
+ if (policyDataString != null) {
+ logger.warn("isJUnit will overwrite policyDataString");
+ }
// Using parentPath object to set policy data.
policyDataString = policy.policyAdapter.getParentPath();
}
String configPath = "";
- if (PolicyDBDao.CONFIG.equalsIgnoreCase(policy.policyAdapter.getPolicyType())) {
+ if (PolicyDbDao.CONFIG.equalsIgnoreCase(policy.policyAdapter.getPolicyType())) {
configPath = evaluateXPath(
- "/Policy/Rule/AdviceExpressions/AdviceExpression[contains(@AdviceId,'ID')]/AttributeAssignmentExpression[@AttributeId='URLID']/AttributeValue/text()",
+ "/Policy/Rule/AdviceExpressions/AdviceExpression[contains(@AdviceId,'ID')]/"
+ + "AttributeAssignmentExpression[@AttributeId='URLID']/AttributeValue/text()",
policyDataString);
- } else if (PolicyDBDao.ACTION.equalsIgnoreCase(policy.policyAdapter.getPolicyType())) {
+ } else if (PolicyDbDao.ACTION.equalsIgnoreCase(policy.policyAdapter.getPolicyType())) {
configPath = evaluateXPath(
"/Policy/Rule/ObligationExpressions/ObligationExpression[contains(@ObligationId, "
+ policy.policyAdapter.getActionAttribute()
@@ -558,16 +569,17 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction {
policyDataString);
} else if (DECISIONMS_MODEL.equalsIgnoreCase(policy.policyAdapter.getRuleProvider())) {
configPath = evaluateXPath(
- "/Policy/Rule/AdviceExpressions/AdviceExpression[contains(@AdviceId,'MicroService')]/AttributeAssignmentExpression[@AttributeId='URLID']/AttributeValue/text()",
+ "/Policy/Rule/AdviceExpressions/AdviceExpression[contains(@AdviceId,'MicroService')]/"
+ + "AttributeAssignmentExpression[@AttributeId='URLID']/AttributeValue/text()",
policyDataString);
}
String prefix = null;
- if (PolicyDBDao.CONFIG.equalsIgnoreCase(policy.policyAdapter.getPolicyType())
+ if (PolicyDbDao.CONFIG.equalsIgnoreCase(policy.policyAdapter.getPolicyType())
|| DECISIONMS_MODEL.equalsIgnoreCase(policy.policyAdapter.getRuleProvider())) {
prefix = configPath.substring(configPath.indexOf(policyScope + ".") + policyScope.concat(".").length(),
configPath.lastIndexOf(policy.policyAdapter.getPolicyName()));
- if (PolicyDBDao.isNullOrEmpty(policy.policyAdapter.getConfigBodyData())) {
+ if (PolicyDbDao.isNullOrEmpty(policy.policyAdapter.getConfigBodyData())) {
String configData = "";
try {
String newConfigPath = configPath;
@@ -582,7 +594,7 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction {
}
policy.policyAdapter.setConfigBodyData(configData);
}
- } else if (PolicyDBDao.ACTION.equalsIgnoreCase(policy.policyAdapter.getPolicyType())) {
+ } else if (PolicyDbDao.ACTION.equalsIgnoreCase(policy.policyAdapter.getPolicyType())) {
prefix = "Action_";
} else if ("Decision".equalsIgnoreCase(policy.policyAdapter.getPolicyType())) {
prefix = "Decision_";
@@ -599,20 +611,20 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction {
// get the config file extension
String ext = "";
if (configPath != null && !"".equalsIgnoreCase(configPath)) {
- ext = configPath.substring(configPath.lastIndexOf('.'), configPath.length());;
+ ext = configPath.substring(configPath.lastIndexOf('.'), configPath.length());
}
if (ext.contains("txt")) {
- policy.policyAdapter.setConfigType(PolicyDBDao.OTHER_CONFIG);
+ policy.policyAdapter.setConfigType(PolicyDbDao.OTHER_CONFIG);
} else if (ext.contains("json")) {
- policy.policyAdapter.setConfigType(PolicyDBDao.JSON_CONFIG);
+ policy.policyAdapter.setConfigType(PolicyDbDao.JSON_CONFIG);
} else if (ext.contains("xml")) {
- policy.policyAdapter.setConfigType(PolicyDBDao.XML_CONFIG);
+ policy.policyAdapter.setConfigType(PolicyDbDao.XML_CONFIG);
} else if (ext.contains("properties")) {
- policy.policyAdapter.setConfigType(PolicyDBDao.PROPERTIES_CONFIG);
+ policy.policyAdapter.setConfigType(PolicyDbDao.PROPERTIES_CONFIG);
} else {
- if (policy.policyAdapter.getPolicyType().equalsIgnoreCase(PolicyDBDao.ACTION)) {
- policy.policyAdapter.setConfigType(PolicyDBDao.JSON_CONFIG);
+ if (policy.policyAdapter.getPolicyType().equalsIgnoreCase(PolicyDbDao.ACTION)) {
+ policy.policyAdapter.setConfigType(PolicyDbDao.JSON_CONFIG);
}
}
}
@@ -629,7 +641,6 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction {
}
}
-
public PolicyEntity getPolicy(int policyId) {
return getPolicy(policyId, null, null);
}
@@ -640,42 +651,42 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction {
private PolicyEntity getPolicy(int policyIdVar, String policyName, String scope) {
logger.debug("getPolicy(int policyId, String policyName) as " + " getPolicy(" + policyIdVar + "," + policyName
- + ") called");
- if (policyIdVar < 0 && PolicyDBDao.isNullOrEmpty(policyName, scope)) {
+ + BRACKET_CALLED);
+ if (policyIdVar < 0 && PolicyDbDao.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;
+ String locPolicyId;
Query policyQuery;
- if (!PolicyDBDao.isNullOrEmpty(policyName, scope)) {
- policyId = policyName;
+ if (!PolicyDbDao.isNullOrEmpty(policyName, scope)) {
+ locPolicyId = policyName;
policyQuery =
session.createQuery("SELECT p FROM PolicyEntity p WHERE p.policyName=:name AND p.scope=:scope");
- policyQuery.setParameter("name", policyId);
+ policyQuery.setParameter("name", locPolicyId);
policyQuery.setParameter("scope", scope);
} else {
- policyId = String.valueOf(policyIdVar);
+ locPolicyId = String.valueOf(policyIdVar);
policyQuery = session.getNamedQuery("PolicyEntity.FindById");
- policyQuery.setParameter("id", policyId);
+ policyQuery.setParameter("id", locPolicyId);
}
List<?> policyQueryList;
try {
policyQueryList = policyQuery.list();
} catch (Exception e) {
- PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR,
+ PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR,
"Caught Exception trying to get policy with policyQuery.getResultList()");
- throw new PersistenceException("Query failed trying to get policy " + policyId);
+ throw new PersistenceException("Query failed trying to get policy " + locPolicyId);
}
if (policyQueryList.isEmpty()) {
- PolicyLogger.error("Policy does not exist with id " + policyId);
- throw new PersistenceException("Group policy is being added to does not exist with id " + policyId);
+ PolicyLogger.error("Policy does not exist with id " + locPolicyId);
+ throw new PersistenceException("Group policy is being added to does not exist with id " + locPolicyId);
} else if (policyQueryList.size() > 1) {
- PolicyLogger.error(PolicyDBDao.DUP_POLICYID + policyId + PolicyDBDao.FOUND_IN_DB);
- throw new PersistenceException(PolicyDBDao.DUP_POLICYID + policyId + PolicyDBDao.FOUND_IN_DB);
+ PolicyLogger.error(PolicyDbDao.DUP_POLICYID + locPolicyId + PolicyDbDao.FOUND_IN_DB);
+ throw new PersistenceException(PolicyDbDao.DUP_POLICYID + locPolicyId + PolicyDbDao.FOUND_IN_DB);
}
return (PolicyEntity) policyQueryList.get(0);
}
@@ -683,7 +694,7 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction {
@Override
public GroupEntity getGroup(long groupKey) {
- logger.debug("getGroup(int groupKey) as getGroup(" + groupKey + ") called");
+ logger.debug("getGroup(int groupKey) as getGroup(" + groupKey + BRACKET_CALLED);
if (groupKey < 0) {
throw new IllegalArgumentException("groupKey must be at least 0");
}
@@ -696,18 +707,18 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction {
try {
groupQueryList = groupQuery.list();
} catch (Exception e) {
- PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR,
+ PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR,
"Caught Exception trying to get group with groupQuery.getResultList()");
- throw new PersistenceException(PolicyDBDao.QUERY_FAILED_GET_GROUP + groupKey);
+ throw new PersistenceException(PolicyDbDao.QUERY_FAILED_GET_GROUP + groupKey);
}
if (groupQueryList.isEmpty()) {
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 + PolicyDBDao.FOUND_IN_DB);
+ .error("Somehow, more than one group with the groupKey " + groupKey + PolicyDbDao.FOUND_IN_DB);
throw new PersistenceException(
- "Somehow, more than one group with the groupKey " + groupKey + PolicyDBDao.FOUND_IN_DB);
+ "Somehow, more than one group with the groupKey " + groupKey + PolicyDbDao.FOUND_IN_DB);
}
return (GroupEntity) groupQueryList.get(0);
}
@@ -715,29 +726,29 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction {
@Override
public GroupEntity getGroup(String groupId) {
- logger.debug("getGroup(String groupId) as getGroup(" + groupId + ") called");
- if (PolicyDBDao.isNullOrEmpty(groupId)) {
+ logger.debug("getGroup(String groupId) as getGroup(" + groupId + BRACKET_CALLED);
+ if (PolicyDbDao.isNullOrEmpty(groupId)) {
throw new IllegalArgumentException("groupId must not be null or empty");
}
synchronized (emLock) {
checkBeforeOperationRun(true);
// check if group exists
Query groupQuery = session.createQuery("SELECT g FROM GroupEntity g WHERE g.groupId=:groupId");
- groupQuery.setParameter(PolicyDBDao.GROUP_ID, groupId);
+ groupQuery.setParameter(PolicyDbDao.GROUP_ID, groupId);
List<?> groupQueryList;
try {
groupQueryList = groupQuery.list();
} catch (Exception e) {
- PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR,
+ PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR,
"Caught Exception trying to get group with groupQuery.getResultList()");
- throw new PersistenceException(PolicyDBDao.QUERY_FAILED_GET_GROUP + groupId);
+ throw new PersistenceException(PolicyDbDao.QUERY_FAILED_GET_GROUP + groupId);
}
if (groupQueryList.isEmpty()) {
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(PolicyDBDao.DUPLICATE_GROUPID + groupId + PolicyDBDao.FOUND_IN_DB);
- throw new PersistenceException(PolicyDBDao.DUPLICATE_GROUPID + groupId + PolicyDBDao.FOUND_IN_DB);
+ PolicyLogger.error(PolicyDbDao.DUPLICATE_GROUPID + groupId + PolicyDbDao.FOUND_IN_DB);
+ throw new PersistenceException(PolicyDbDao.DUPLICATE_GROUPID + groupId + PolicyDbDao.FOUND_IN_DB);
}
return (GroupEntity) groupQueryList.get(0);
}
@@ -745,21 +756,21 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction {
@Override
public List<?> getPdpsInGroup(long groupKey) {
- logger.debug("getPdpsInGroup(int groupKey) as getPdpsInGroup(" + groupKey + ") called");
+ logger.debug("getPdpsInGroup(int groupKey) as getPdpsInGroup(" + groupKey + BRACKET_CALLED);
if (groupKey < 0) {
throw new IllegalArgumentException("groupId must not be < 0");
}
synchronized (emLock) {
checkBeforeOperationRun(true);
Query pdpsQuery = session.createQuery("SELECT p FROM PdpEntity p WHERE p.groupEntity=:group");
- pdpsQuery.setParameter("group", getGroup(groupKey));
+ pdpsQuery.setParameter(GROUP, getGroup(groupKey));
return pdpsQuery.list();
}
}
@Override
public PdpEntity getPdp(long pdpKey) {
- logger.debug("getPdp(int pdpKey) as getPdp(" + pdpKey + ") called");
+ logger.debug("getPdp(int pdpKey) as getPdp(" + pdpKey + BRACKET_CALLED);
if (pdpKey < 0) {
throw new IllegalArgumentException("pdpKey must be at least 0");
}
@@ -772,7 +783,7 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction {
try {
pdpQueryList = pdpQuery.list();
} catch (Exception e) {
- PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR,
+ PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR,
"Caught Exception trying to get pdp with pdpQuery.getResultList()");
throw new PersistenceException("Query failed trying to get pdp " + pdpKey);
}
@@ -780,9 +791,9 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction {
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 + PolicyDBDao.FOUND_IN_DB);
+ PolicyLogger.error("Somehow, more than one pdp with the pdpKey " + pdpKey + PolicyDbDao.FOUND_IN_DB);
throw new PersistenceException(
- "Somehow, more than one pdp with the pdpKey " + pdpKey + PolicyDBDao.FOUND_IN_DB);
+ "Somehow, more than one pdp with the pdpKey " + pdpKey + PolicyDbDao.FOUND_IN_DB);
}
return (PdpEntity) pdpQueryList.get(0);
}
@@ -798,7 +809,7 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction {
private String processConfigPath(String inputConfigPath) {
String configPath = inputConfigPath;
- String webappsPath = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_WEBAPPS);
+ 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");
@@ -835,7 +846,6 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction {
return configDataString;
}
-
@Override
public void close() {
synchronized (emLock) {
@@ -855,8 +865,8 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction {
public void createGroup(String groupId, String groupName, String inputGroupDescription, String username) {
String groupDescription = inputGroupDescription;
logger.debug("deletePolicy(String policyToDeletes) as createGroup(" + groupId + ", " + groupName + ", "
- + groupDescription + ") called");
- if (PolicyDBDao.isNullOrEmpty(groupId, groupName, username)) {
+ + groupDescription + BRACKET_CALLED);
+ if (PolicyDbDao.isNullOrEmpty(groupId, groupName, username)) {
throw new IllegalArgumentException("groupId, groupName, and username must not be null or empty");
}
if (groupDescription == null) {
@@ -865,16 +875,16 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction {
synchronized (emLock) {
checkBeforeOperationRun();
- Query checkGroupQuery = session.createQuery(PolicyDBDao.GROUPENTITY_SELECT);
- checkGroupQuery.setParameter(PolicyDBDao.GROUP_ID, groupId);
- checkGroupQuery.setParameter(PolicyDBDao.DELETED, false);
+ Query checkGroupQuery = session.createQuery(PolicyDbDao.GROUPENTITY_SELECT);
+ checkGroupQuery.setParameter(PolicyDbDao.GROUP_ID, groupId);
+ checkGroupQuery.setParameter(PolicyDbDao.DELETED, false);
List<?> checkGroupQueryList;
try {
checkGroupQueryList = checkGroupQuery.list();
} catch (Exception e) {
- PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR,
+ PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR,
"Caught Exception on checkGroupQuery.getResultList()");
- throw new PersistenceException(PolicyDBDao.QUERY_FAILED_FOR_GROUP);
+ throw new PersistenceException(PolicyDbDao.QUERY_FAILED_FOR_GROUP);
}
if (!checkGroupQueryList.isEmpty()) {
PolicyLogger.error("The group being added already exists with id " + groupId);
@@ -898,50 +908,50 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction {
@Override
public void updateGroup(OnapPDPGroup group, String requestType, String username) {
logger.info("PolicyDBDao: updateGroup(PDPGroup group) as updateGroup(" + group + "," + requestType + ","
- + username + ") called");
+ + username + BRACKET_CALLED);
if (group == null) {
throw new IllegalArgumentException("PDPGroup group must not be null");
}
- if (PolicyDBDao.isNullOrEmpty(group.getId(), requestType)) {
+ if (PolicyDbDao.isNullOrEmpty(group.getId(), requestType)) {
throw new IllegalArgumentException("group.getId() and username must not be null or empty");
}
synchronized (emLock) {
- PolicyDBDao policyDbDaoVar = new PolicyDBDao();
+ PolicyDbDao policyDbDaoVar = new PolicyDbDao();
checkBeforeOperationRun();
- Query getGroupQuery = session.createQuery(PolicyDBDao.GROUPENTITY_SELECT);
- getGroupQuery.setParameter(PolicyDBDao.GROUP_ID, group.getId());
- getGroupQuery.setParameter(PolicyDBDao.DELETED, false);
+ Query getGroupQuery = session.createQuery(PolicyDbDao.GROUPENTITY_SELECT);
+ getGroupQuery.setParameter(PolicyDbDao.GROUP_ID, group.getId());
+ getGroupQuery.setParameter(PolicyDbDao.DELETED, false);
List<?> getGroupQueryList;
try {
getGroupQueryList = getGroupQuery.list();
} catch (Exception e) {
- PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR,
+ PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR,
"Caught Exception on getGroupQuery.getResultList()");
- throw new PersistenceException(PolicyDBDao.QUERY_FAILED_GET_GROUP + group.getId() + " for editing");
+ throw new PersistenceException(PolicyDbDao.QUERY_FAILED_GET_GROUP + group.getId() + " for editing");
}
if (getGroupQueryList.isEmpty()) {
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(PolicyDBDao.DUPLICATE_GROUPID + group.getId() + PolicyDBDao.DELETED_STATUS_FOUND);
+ PolicyLogger.error(PolicyDbDao.DUPLICATE_GROUPID + group.getId() + PolicyDbDao.DELETED_STATUS_FOUND);
throw new PersistenceException(
- PolicyDBDao.DUPLICATE_GROUPID + group.getId() + PolicyDBDao.DELETED_STATUS_FOUND);
+ PolicyDbDao.DUPLICATE_GROUPID + group.getId() + PolicyDbDao.DELETED_STATUS_FOUND);
}
GroupEntity groupToUpdateInDb = (GroupEntity) getGroupQueryList.get(0);
- if (!PolicyDBDao.stringEquals(groupToUpdateInDb.getModifiedBy(), requestType)) {
+ if (!PolicyDbDao.stringEquals(groupToUpdateInDb.getModifiedBy(), requestType)) {
groupToUpdateInDb.setModifiedBy(requestType);
}
if (group.getDescription() != null
- && !PolicyDBDao.stringEquals(group.getDescription(), groupToUpdateInDb.getDescription())) {
+ && !PolicyDbDao.stringEquals(group.getDescription(), groupToUpdateInDb.getDescription())) {
groupToUpdateInDb.setDescription(group.getDescription());
}
// let's find out what policies have been deleted
StdPDPGroup oldGroup = null;
try {
- oldGroup = (StdPDPGroup) PolicyDBDao.getPolicyDBDaoInstance().getPapEngine().getGroup(group.getId());
+ oldGroup = (StdPDPGroup) PolicyDbDao.getPolicyDbDaoInstance().getPapEngine().getGroup(group.getId());
} catch (PAPException e1) {
- PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e1, PolicyDBDao.POLICYDBDAO_VAR,
+ PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e1, PolicyDbDao.POLICYDBDAO_VAR,
"We cannot get the group from the papEngine to delete policies");
}
if (oldGroup == null) {
@@ -992,7 +1002,7 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction {
}
}
} catch (Exception e) {
- PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR,
+ PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR,
"Could not get policy to remove: " + pol.getId());
throw new PersistenceException("Could not get policy to remove: " + pol.getId());
}
@@ -1001,19 +1011,19 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction {
}
if (group.getName() != null
- && !PolicyDBDao.stringEquals(group.getName(), groupToUpdateInDb.getgroupName())) {
+ && !PolicyDbDao.stringEquals(group.getName(), groupToUpdateInDb.getGroupName())) {
// we need to check if the new id exists in the database
- String newGrpId = PolicyDBDao.createNewPDPGroupId(group.getName());
- Query checkGroupQuery = session.createQuery(PolicyDBDao.GROUPENTITY_SELECT);
- checkGroupQuery.setParameter(PolicyDBDao.GROUP_ID, newGrpId);
- checkGroupQuery.setParameter(PolicyDBDao.DELETED, false);
+ String newGrpId = PolicyDbDao.createNewPdpGroupId(group.getName());
+ Query checkGroupQuery = session.createQuery(PolicyDbDao.GROUPENTITY_SELECT);
+ checkGroupQuery.setParameter(PolicyDbDao.GROUP_ID, newGrpId);
+ checkGroupQuery.setParameter(PolicyDbDao.DELETED, false);
List<?> checkGroupQueryList;
try {
checkGroupQueryList = checkGroupQuery.list();
} catch (Exception e) {
- PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR,
+ PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR,
"Caught Exception on checkGroupQuery.getResultList()");
- throw new PersistenceException(PolicyDBDao.QUERY_FAILED_FOR_GROUP);
+ throw new PersistenceException(PolicyDbDao.QUERY_FAILED_FOR_GROUP);
}
if (!checkGroupQueryList.isEmpty()) {
PolicyLogger.error("The new group name already exists, group id " + newGrpId);
@@ -1034,35 +1044,35 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction {
logger.debug("addPdpToGroup(String pdpID, String groupID, String pdpName, "
+ "String pdpDescription, int pdpJmxPort, String username) as addPdpToGroup(" + pdpId + ", "
+ groupIdVar + ", " + pdpName + ", " + pdpDescription + ", " + pdpJmxPort + ", " + username
- + ") called");
- if (PolicyDBDao.isNullOrEmpty(pdpId, groupIdVar, pdpName, username)) {
+ + BRACKET_CALLED);
+ if (PolicyDbDao.isNullOrEmpty(pdpId, groupIdVar, pdpName, username)) {
throw new IllegalArgumentException("pdpID, groupID, pdpName, and username must not be null or empty");
}
synchronized (emLock) {
checkBeforeOperationRun();
- Query checkGroupQuery = session.createQuery(PolicyDBDao.GROUPENTITY_SELECT);
- checkGroupQuery.setParameter(PolicyDBDao.GROUP_ID, groupIdVar);
- checkGroupQuery.setParameter(PolicyDBDao.DELETED, false);
+ Query checkGroupQuery = session.createQuery(PolicyDbDao.GROUPENTITY_SELECT);
+ checkGroupQuery.setParameter(PolicyDbDao.GROUP_ID, groupIdVar);
+ checkGroupQuery.setParameter(PolicyDbDao.DELETED, false);
List<?> checkGroupQueryList;
try {
checkGroupQueryList = checkGroupQuery.list();
} catch (Exception e) {
- PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR,
+ PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR,
"Caught Exception trying to check for existing group on checkGroupQuery.getResultList()");
- throw new PersistenceException(PolicyDBDao.QUERY_FAILED_FOR_GROUP);
+ throw new PersistenceException(PolicyDbDao.QUERY_FAILED_FOR_GROUP);
}
if (checkGroupQueryList.size() != 1) {
PolicyLogger.error("The group does not exist");
throw new PersistenceException("The group does not exist");
}
- Query checkDuplicateQuery = session.createQuery(PolicyDBDao.PDPENTITY_SELECT);
- checkDuplicateQuery.setParameter(PolicyDBDao.PDP_ID, pdpId);
- checkDuplicateQuery.setParameter(PolicyDBDao.DELETED, false);
+ Query checkDuplicateQuery = session.createQuery(PolicyDbDao.PDPENTITY_SELECT);
+ checkDuplicateQuery.setParameter(PolicyDbDao.PDP_ID, pdpId);
+ checkDuplicateQuery.setParameter(PolicyDbDao.DELETED, false);
List<?> checkDuplicateList;
try {
checkDuplicateList = checkDuplicateQuery.list();
} catch (Exception e) {
- PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR,
+ PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR,
"Caught Exception trying to check for duplicate PDP " + pdpId
+ " on checkDuplicateQuery.getResultList()");
throw new PersistenceException("Query failed trying to check for duplicate PDP " + pdpId);
@@ -1094,24 +1104,24 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction {
@Override
public void updatePdp(OnapPDP pdp, String username) {
- logger.debug("updatePdp(PDP pdp, String username) as updatePdp(" + pdp + "," + username + ") called");
+ logger.debug("updatePdp(PDP pdp, String username) as updatePdp(" + pdp + "," + username + BRACKET_CALLED);
if (pdp == null) {
throw new IllegalArgumentException("PDP pdp must not be null");
}
- if (PolicyDBDao.isNullOrEmpty(pdp.getId(), username)) {
+ if (PolicyDbDao.isNullOrEmpty(pdp.getId(), username)) {
throw new IllegalArgumentException("pdp.getId() and username must not be null or empty");
}
synchronized (emLock) {
checkBeforeOperationRun();
- Query getPdpQuery = session.createQuery(PolicyDBDao.PDPENTITY_SELECT);
- getPdpQuery.setParameter(PolicyDBDao.PDP_ID, pdp.getId());
- getPdpQuery.setParameter(PolicyDBDao.DELETED, false);
+ Query getPdpQuery = session.createQuery(PolicyDbDao.PDPENTITY_SELECT);
+ getPdpQuery.setParameter(PolicyDbDao.PDP_ID, pdp.getId());
+ getPdpQuery.setParameter(PolicyDbDao.DELETED, false);
List<?> getPdpQueryList;
try {
getPdpQueryList = getPdpQuery.list();
} catch (Exception e) {
- PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR,
+ PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR,
"Caught Exception on getPdpQuery.getResultList()");
throw new PersistenceException("Query failed trying to get PDP " + pdp.getId());
}
@@ -1119,19 +1129,19 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction {
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(PolicyDBDao.MORE_THAN_ONE_PDP + pdp.getId() + PolicyDBDao.DELETED_STATUS_FOUND);
+ PolicyLogger.error(PolicyDbDao.MORE_THAN_ONE_PDP + pdp.getId() + PolicyDbDao.DELETED_STATUS_FOUND);
throw new PersistenceException(
- PolicyDBDao.MORE_THAN_ONE_PDP + pdp.getId() + PolicyDBDao.DELETED_STATUS_FOUND);
+ PolicyDbDao.MORE_THAN_ONE_PDP + pdp.getId() + PolicyDbDao.DELETED_STATUS_FOUND);
}
PdpEntity pdpToUpdate = (PdpEntity) getPdpQueryList.get(0);
- if (!PolicyDBDao.stringEquals(pdpToUpdate.getModifiedBy(), username)) {
+ if (!PolicyDbDao.stringEquals(pdpToUpdate.getModifiedBy(), username)) {
pdpToUpdate.setModifiedBy(username);
}
if (pdp.getDescription() != null
- && !PolicyDBDao.stringEquals(pdp.getDescription(), pdpToUpdate.getDescription())) {
+ && !PolicyDbDao.stringEquals(pdp.getDescription(), pdpToUpdate.getDescription())) {
pdpToUpdate.setDescription(pdp.getDescription());
}
- if (pdp.getName() != null && !PolicyDBDao.stringEquals(pdp.getName(), pdpToUpdate.getPdpName())) {
+ if (pdp.getName() != null && !PolicyDbDao.stringEquals(pdp.getName(), pdpToUpdate.getPdpName())) {
pdpToUpdate.setPdpName(pdp.getName());
}
if (pdp.getJmxPort() != null && !pdp.getJmxPort().equals(pdpToUpdate.getJmxPort())) {
@@ -1146,25 +1156,25 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction {
@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");
+ + username + BRACKET_CALLED);
if (pdp == null || group == null) {
throw new IllegalArgumentException("PDP pdp and PDPGroup group must not be null");
}
- if (PolicyDBDao.isNullOrEmpty(username, pdp.getId(), group.getId())) {
+ if (PolicyDbDao.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 = session.createQuery(PolicyDBDao.PDPENTITY_SELECT);
- getPdpQuery.setParameter(PolicyDBDao.PDP_ID, pdp.getId());
- getPdpQuery.setParameter(PolicyDBDao.DELETED, false);
+ Query getPdpQuery = session.createQuery(PolicyDbDao.PDPENTITY_SELECT);
+ getPdpQuery.setParameter(PolicyDbDao.PDP_ID, pdp.getId());
+ getPdpQuery.setParameter(PolicyDbDao.DELETED, false);
List<?> getPdpQueryList;
try {
getPdpQueryList = getPdpQuery.list();
} catch (Exception e) {
- PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR,
+ PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR,
"Caught Exception on getPdpQuery.getResultList()");
throw new PersistenceException("Query failed trying to get pdp to move with id " + pdp.getId());
}
@@ -1172,20 +1182,20 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction {
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(PolicyDBDao.MORE_THAN_ONE_PDP + pdp.getId() + PolicyDBDao.DELETED_STATUS_FOUND);
+ PolicyLogger.error(PolicyDbDao.MORE_THAN_ONE_PDP + pdp.getId() + PolicyDbDao.DELETED_STATUS_FOUND);
throw new PersistenceException(
- PolicyDBDao.MORE_THAN_ONE_PDP + pdp.getId() + PolicyDBDao.DELETED_STATUS_FOUND);
+ PolicyDbDao.MORE_THAN_ONE_PDP + pdp.getId() + PolicyDbDao.DELETED_STATUS_FOUND);
}
// check if new group exists
- Query checkGroupQuery = session.createQuery(PolicyDBDao.GROUPENTITY_SELECT);
- checkGroupQuery.setParameter(PolicyDBDao.GROUP_ID, group.getId());
- checkGroupQuery.setParameter(PolicyDBDao.DELETED, false);
+ Query checkGroupQuery = session.createQuery(PolicyDbDao.GROUPENTITY_SELECT);
+ checkGroupQuery.setParameter(PolicyDbDao.GROUP_ID, group.getId());
+ checkGroupQuery.setParameter(PolicyDbDao.DELETED, false);
List<?> checkGroupQueryList;
try {
checkGroupQueryList = checkGroupQuery.list();
} catch (Exception e) {
- PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR,
+ PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR,
"Caught Exception trying to get group on checkGroupQuery.getResultList()");
throw new PersistenceException("Query failed trying to get new group " + group.getId());
}
@@ -1196,7 +1206,7 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction {
GroupEntity groupToMoveInto = (GroupEntity) checkGroupQueryList.get(0);
PdpEntity pdpToUpdate = (PdpEntity) getPdpQueryList.get(0);
pdpToUpdate.setGroup(groupToMoveInto);
- if (!PolicyDBDao.stringEquals(pdpToUpdate.getModifiedBy(), username)) {
+ if (!PolicyDbDao.stringEquals(pdpToUpdate.getModifiedBy(), username)) {
pdpToUpdate.setModifiedBy(username);
}
@@ -1208,38 +1218,38 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction {
@Override
public void changeDefaultGroup(OnapPDPGroup group, String username) {
logger.debug("changeDefaultGroup(PDPGroup group, String username) as changeDefaultGroup(" + group + ","
- + username + ") called");
+ + username + BRACKET_CALLED);
if (group == null) {
throw new IllegalArgumentException("PDPGroup group must not be null");
}
- if (PolicyDBDao.isNullOrEmpty(group.getId(), username)) {
+ if (PolicyDbDao.isNullOrEmpty(group.getId(), username)) {
throw new IllegalArgumentException("group.getId() and username must not be null or empty");
}
synchronized (emLock) {
checkBeforeOperationRun();
- Query getGroupQuery = session.createQuery(PolicyDBDao.GROUPENTITY_SELECT);
- getGroupQuery.setParameter(PolicyDBDao.GROUP_ID, group.getId());
- getGroupQuery.setParameter(PolicyDBDao.DELETED, false);
+ Query getGroupQuery = session.createQuery(PolicyDbDao.GROUPENTITY_SELECT);
+ getGroupQuery.setParameter(PolicyDbDao.GROUP_ID, group.getId());
+ getGroupQuery.setParameter(PolicyDbDao.DELETED, false);
List<?> getGroupQueryList;
try {
getGroupQueryList = getGroupQuery.list();
} catch (Exception e) {
- PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR,
+ PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR,
"Caught Exception on getGroupQuery.getResultList()");
- throw new PersistenceException(PolicyDBDao.QUERY_FAILED_GET_GROUP + group.getId());
+ throw new PersistenceException(PolicyDbDao.QUERY_FAILED_GET_GROUP + group.getId());
}
if (getGroupQueryList.isEmpty()) {
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(PolicyDBDao.DUPLICATE_GROUPID + group.getId() + PolicyDBDao.DELETED_STATUS_FOUND);
+ PolicyLogger.error(PolicyDbDao.DUPLICATE_GROUPID + group.getId() + PolicyDbDao.DELETED_STATUS_FOUND);
throw new PersistenceException(
- PolicyDBDao.DUPLICATE_GROUPID + group.getId() + PolicyDBDao.DELETED_STATUS_FOUND);
+ PolicyDbDao.DUPLICATE_GROUPID + group.getId() + PolicyDbDao.DELETED_STATUS_FOUND);
}
GroupEntity newDefaultGroup = (GroupEntity) getGroupQueryList.get(0);
newDefaultGroup.setDefaultGroup(true);
- if (!PolicyDBDao.stringEquals(newDefaultGroup.getModifiedBy(), username)) {
+ if (!PolicyDbDao.stringEquals(newDefaultGroup.getModifiedBy(), username)) {
newDefaultGroup.setModifiedBy(username);
}
@@ -1249,12 +1259,12 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction {
+ "WHERE g.deleted=:deleted AND g.groupKey<>:groupKey");
// not going to set modified by for all groups
setAllGroupsNotDefault.setParameter("defaultGroup", false);
- setAllGroupsNotDefault.setParameter(PolicyDBDao.DELETED, false);
+ setAllGroupsNotDefault.setParameter(PolicyDbDao.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.POLICYDBDAO_VAR,
+ PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR,
"Caught Exception on setAllGroupsNotDefault.executeUpdate()");
throw new PersistenceException("Could not set all other groups default to false");
}
@@ -1263,51 +1273,51 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction {
}
@Override
- public void deleteGroup(OnapPDPGroup group, OnapPDPGroup moveToGroup, String username) throws PolicyDBException {
+ public void deleteGroup(OnapPDPGroup group, OnapPDPGroup moveToGroup, String username) throws PolicyDbException {
logger.debug("deleteGroup(PDPGroup group, PDPGroup moveToGroup, String username) as deleteGroup(" + group + ", "
- + moveToGroup + "," + username + ") called");
+ + moveToGroup + "," + username + BRACKET_CALLED);
if (group == null) {
throw new IllegalArgumentException("PDPGroup group cannot be null");
}
- if (PolicyDBDao.isNullOrEmpty(username, group.getId())) {
+ if (PolicyDbDao.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 PolicyDBException("You cannot delete the default group.");
+ throw new PolicyDbException("You cannot delete the default group.");
}
synchronized (emLock) {
checkBeforeOperationRun();
- Query deleteGroupQuery = session.createQuery(PolicyDBDao.GROUPENTITY_SELECT);
- deleteGroupQuery.setParameter(PolicyDBDao.GROUP_ID, group.getId());
- deleteGroupQuery.setParameter(PolicyDBDao.DELETED, false);
+ Query deleteGroupQuery = session.createQuery(PolicyDbDao.GROUPENTITY_SELECT);
+ deleteGroupQuery.setParameter(PolicyDbDao.GROUP_ID, group.getId());
+ deleteGroupQuery.setParameter(PolicyDbDao.DELETED, false);
List<?> deleteGroupQueryList;
try {
deleteGroupQueryList = deleteGroupQuery.list();
} catch (Exception e) {
- PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR,
+ PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR,
"Caught Exception trying to check if group exists deleteGroupQuery.getResultList()");
throw new PersistenceException("Query failed trying to check if group exists");
}
if (deleteGroupQueryList.isEmpty()) {
- logger.warn(PolicyDBDao.GROUP_NOT_FOUND + group.getId());
+ logger.warn(PolicyDbDao.GROUP_NOT_FOUND + group.getId());
return;
} else if (deleteGroupQueryList.size() > 1) {
- PolicyLogger.error(PolicyDBDao.DUPLICATE_GROUPID + group.getId() + PolicyDBDao.FOUND_IN_DB_NOT_DEL);
+ PolicyLogger.error(PolicyDbDao.DUPLICATE_GROUPID + group.getId() + PolicyDbDao.FOUND_IN_DB_NOT_DEL);
throw new PersistenceException(
- PolicyDBDao.DUPLICATE_GROUPID + group.getId() + PolicyDBDao.FOUND_IN_DB_NOT_DEL);
+ PolicyDbDao.DUPLICATE_GROUPID + group.getId() + PolicyDbDao.FOUND_IN_DB_NOT_DEL);
}
Query pdpsInGroupQuery =
session.createQuery("SELECT p FROM PdpEntity p WHERE p.groupEntity=:group and p.deleted=:deleted");
- pdpsInGroupQuery.setParameter("group", (deleteGroupQueryList.get(0)));
- pdpsInGroupQuery.setParameter(PolicyDBDao.DELETED, false);
+ pdpsInGroupQuery.setParameter(GROUP, (deleteGroupQueryList.get(0)));
+ pdpsInGroupQuery.setParameter(PolicyDbDao.DELETED, false);
List<?> pdpsInGroupList;
try {
pdpsInGroupList = pdpsInGroupQuery.list();
} catch (Exception e) {
- PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR,
+ PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR,
"Caught Exception trying to get PDPs in group on pdpsInGroupQuery.getResultList()");
throw new PersistenceException("Query failed trying to get PDPs in group");
}
@@ -1315,37 +1325,37 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction {
if (moveToGroup != null) {
Query checkMoveToGroupQuery = session
.createQuery("SELECT o FROM GroupEntity o WHERE o.groupId=:groupId AND o.deleted=:deleted");
- checkMoveToGroupQuery.setParameter(PolicyDBDao.GROUP_ID, moveToGroup.getId());
- checkMoveToGroupQuery.setParameter(PolicyDBDao.DELETED, false);
+ checkMoveToGroupQuery.setParameter(PolicyDbDao.GROUP_ID, moveToGroup.getId());
+ checkMoveToGroupQuery.setParameter(PolicyDbDao.DELETED, false);
List<?> checkMoveToGroupList;
try {
checkMoveToGroupList = checkMoveToGroupQuery.list();
} catch (Exception e) {
- PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR,
+ PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR,
"Caught Exception trying to check if group exists checkMoveToGroupQuery.getResultList");
throw new PersistenceException("Query failed trying to check if group exists");
}
if (checkMoveToGroupList.isEmpty()) {
- PolicyLogger.error(PolicyDBDao.GROUP_NOT_FOUND + moveToGroup.getId());
- throw new PersistenceException(PolicyDBDao.GROUP_NOT_FOUND + moveToGroup.getId());
+ PolicyLogger.error(PolicyDbDao.GROUP_NOT_FOUND + moveToGroup.getId());
+ throw new PersistenceException(PolicyDbDao.GROUP_NOT_FOUND + moveToGroup.getId());
} else if (checkMoveToGroupList.size() > 1) {
PolicyLogger.error(
- PolicyDBDao.DUPLICATE_GROUPID + moveToGroup.getId() + PolicyDBDao.FOUND_IN_DB_NOT_DEL);
+ PolicyDbDao.DUPLICATE_GROUPID + moveToGroup.getId() + PolicyDbDao.FOUND_IN_DB_NOT_DEL);
throw new PersistenceException(
- PolicyDBDao.DUPLICATE_GROUPID + moveToGroup.getId() + PolicyDBDao.FOUND_IN_DB_NOT_DEL);
+ PolicyDbDao.DUPLICATE_GROUPID + moveToGroup.getId() + PolicyDbDao.FOUND_IN_DB_NOT_DEL);
} else {
GroupEntity newGroup = (GroupEntity) checkMoveToGroupList.get(0);
for (Object pdpObject : pdpsInGroupList) {
PdpEntity pdp = (PdpEntity) pdpObject;
pdp.setGroup(newGroup);
- if (!PolicyDBDao.stringEquals(pdp.getModifiedBy(), username)) {
+ if (!PolicyDbDao.stringEquals(pdp.getModifiedBy(), username)) {
pdp.setModifiedBy(username);
}
try {
session.flush();
this.newGroupId = newGroup.getGroupId();
} catch (PersistenceException e) {
- PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR,
+ PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR,
"Caught PersistenceException trying to set pdp group to null on em.flush()");
throw new PersistenceException("Query failed trying to set pdp group to ");
}
@@ -1354,14 +1364,14 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction {
} else {
PolicyLogger.error("Group " + group.getId()
+ " is trying to be delted with PDPs. No group was provided to move them to");
- throw new PolicyDBException("Group has PDPs. Must provide a group for them to move to");
+ throw new PolicyDbException("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 (!PolicyDBDao.stringEquals(groupToDelete.getModifiedBy(), username)) {
+ if (!PolicyDbDao.stringEquals(groupToDelete.getModifiedBy(), username)) {
groupToDelete.setModifiedBy(username);
}
session.flush();
@@ -1371,40 +1381,40 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction {
@Override
public StdPDPGroup addPolicyToGroup(String groupIdVar, String policyIdVar, String requestType, String username)
- throws PolicyDBException {
+ throws PolicyDbException {
logger.info(
"PolicyDBDao: addPolicyToGroup(String groupID, String policyID, String username) as addPolicyToGroup("
- + groupIdVar + ", " + policyIdVar + "," + requestType + "," + username + ") called");
- if (PolicyDBDao.isNullOrEmpty(groupIdVar, policyIdVar, requestType)) {
+ + groupIdVar + ", " + policyIdVar + "," + requestType + "," + username + BRACKET_CALLED);
+ if (PolicyDbDao.isNullOrEmpty(groupIdVar, policyIdVar, requestType)) {
throw new IllegalArgumentException("groupID, policyID, and username must not be null or empty");
}
synchronized (emLock) {
checkBeforeOperationRun();
// check if group exists
- Query groupQuery = session.createQuery(PolicyDBDao.GROUPENTITY_SELECT);
- groupQuery.setParameter(PolicyDBDao.GROUP_ID, groupIdVar);
- groupQuery.setParameter(PolicyDBDao.DELETED, false);
+ Query groupQuery = session.createQuery(PolicyDbDao.GROUPENTITY_SELECT);
+ groupQuery.setParameter(PolicyDbDao.GROUP_ID, groupIdVar);
+ groupQuery.setParameter(PolicyDbDao.DELETED, false);
List<?> groupQueryList;
try {
groupQueryList = groupQuery.list();
} catch (Exception e) {
- PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR,
+ PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR,
"Caught Exception trying to check if group exists groupQuery.getResultList()");
- throw new PersistenceException("Query failed trying to check if group " + groupIdVar + " exists");
+ throw new PersistenceException("Query failed trying to check if group " + groupIdVar + EXISTS);
}
if (groupQueryList.isEmpty()) {
PolicyLogger.error("Group policy is being added to does not exist with id " + groupIdVar);
throw new PersistenceException("Group policy is being added to does not exist with id " + groupIdVar);
} else if (groupQueryList.size() > 1) {
- PolicyLogger.error(PolicyDBDao.DUPLICATE_GROUPID + groupIdVar + PolicyDBDao.FOUND_IN_DB_NOT_DEL);
+ PolicyLogger.error(PolicyDbDao.DUPLICATE_GROUPID + groupIdVar + PolicyDbDao.FOUND_IN_DB_NOT_DEL);
throw new PersistenceException(
- PolicyDBDao.DUPLICATE_GROUPID + groupIdVar + PolicyDBDao.FOUND_IN_DB_NOT_DEL);
+ PolicyDbDao.DUPLICATE_GROUPID + groupIdVar + PolicyDbDao.FOUND_IN_DB_NOT_DEL);
}
// 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)
- PolicyDBDao policyDbDao = new PolicyDBDao();
+ PolicyDbDao policyDbDao = new PolicyDbDao();
String[] policyNameScopeAndVersion = policyDbDao.getNameScopeAndVersionFromPdpPolicy(policyIdVar);
if (policyNameScopeAndVersion == null) {
throw new IllegalArgumentException("Invalid input - policyID must contain name, scope and version");
@@ -1412,17 +1422,17 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction {
Query policyQuery = session.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(PolicyDBDao.SCOPE, policyNameScopeAndVersion[1]);
- policyQuery.setParameter(PolicyDBDao.DELETED, false);
+ policyQuery.setParameter(PolicyDbDao.SCOPE, policyNameScopeAndVersion[1]);
+ policyQuery.setParameter(PolicyDbDao.DELETED, false);
List<?> policyQueryList;
try {
policyQueryList = policyQuery.list();
} catch (Exception e) {
logger.debug(e);
- PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR,
+ PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR,
"Caught Exception trying to check if policy exists policyQuery.getResultList()");
throw new PersistenceException(
- "Query failed trying to check if policy " + policyNameScopeAndVersion[0] + " exists");
+ "Query failed trying to check if policy " + policyNameScopeAndVersion[0] + EXISTS);
}
if (policyQueryList.isEmpty()) {
PolicyLogger.error("Policy being added to the group does not exist with policy id "
@@ -1431,9 +1441,9 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction {
+ policyNameScopeAndVersion[0]);
} else if (policyQueryList.size() > 1) {
PolicyLogger.error(
- PolicyDBDao.DUP_POLICYID + policyNameScopeAndVersion[0] + PolicyDBDao.FOUND_IN_DB_NOT_DEL);
+ PolicyDbDao.DUP_POLICYID + policyNameScopeAndVersion[0] + PolicyDbDao.FOUND_IN_DB_NOT_DEL);
throw new PersistenceException(
- PolicyDBDao.DUPLICATE_GROUPID + policyNameScopeAndVersion[0] + PolicyDBDao.FOUND_IN_DB_NOT_DEL);
+ PolicyDbDao.DUPLICATE_GROUPID + policyNameScopeAndVersion[0] + PolicyDbDao.FOUND_IN_DB_NOT_DEL);
}
logger.info("PolicyDBDao: Getting group and policy from database");
GroupEntity group = (GroupEntity) groupQueryList.get(0);
@@ -1464,7 +1474,7 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction {
// filesytem group is in sync with the db group
try {
StdPDPGroup pdpGroup =
- (StdPDPGroup) PolicyDBDao.getPolicyDBDaoInstance().getPapEngine().getGroup(group.getGroupId());
+ (StdPDPGroup) PolicyDbDao.getPolicyDbDaoInstance().getPapEngine().getGroup(group.getGroupId());
return policyDbDao.synchronizeGroupPoliciesInFileSystem(pdpGroup, group);
} catch (PAPException e) {
logger.debug(e);
@@ -1479,27 +1489,27 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction {
@Override
public void removePdpFromGroup(String pdpId, String username) {
logger.debug("removePdpFromGroup(String pdpID, String username) as removePdpFromGroup(" + pdpId + "," + username
- + ") called");
- if (PolicyDBDao.isNullOrEmpty(pdpId, username)) {
+ + BRACKET_CALLED);
+ if (PolicyDbDao.isNullOrEmpty(pdpId, username)) {
throw new IllegalArgumentException("pdpID and username must not be null or empty");
}
synchronized (emLock) {
checkBeforeOperationRun();
- Query pdpQuery = session.createQuery(PolicyDBDao.PDPENTITY_SELECT);
- pdpQuery.setParameter(PolicyDBDao.PDP_ID, pdpId);
- pdpQuery.setParameter(PolicyDBDao.DELETED, false);
+ Query pdpQuery = session.createQuery(PolicyDbDao.PDPENTITY_SELECT);
+ pdpQuery.setParameter(PolicyDbDao.PDP_ID, pdpId);
+ pdpQuery.setParameter(PolicyDbDao.DELETED, false);
List<?> pdpList;
try {
pdpList = pdpQuery.list();
} catch (Exception e) {
- PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR,
+ PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR,
"Caught Exception trying to check if pdp exists pdpQuery.getResultList()");
- throw new PersistenceException("Query failed trying to check if pdp " + pdpId + " exists");
+ 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 + PolicyDBDao.FOUND_IN_DB_NOT_DEL);
+ PolicyLogger.error("Somehow, more than one pdp with the id " + pdpId + PolicyDbDao.FOUND_IN_DB_NOT_DEL);
throw new PersistenceException(
- "Somehow, more than one pdp with the id " + pdpId + PolicyDBDao.FOUND_IN_DB_NOT_DEL);
+ "Somehow, more than one pdp with the id " + pdpId + PolicyDbDao.FOUND_IN_DB_NOT_DEL);
} else if (pdpList.isEmpty()) {
PolicyLogger.error("Pdp being removed does not exist with id " + pdpId);
return;
@@ -1509,7 +1519,7 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction {
pdp.setGroup(null);
}
- if (!PolicyDBDao.stringEquals(pdp.getModifiedBy(), username)) {
+ if (!PolicyDbDao.stringEquals(pdp.getModifiedBy(), username)) {
pdp.setModifiedBy(username);
}
pdp.setDeleted(true);
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
index 7a0f708d8..6ef7a8f18 100644
--- 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
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP-PAP-REST
* ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017, 2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -17,6 +17,7 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.policy.pap.xacml.rest.components;
import java.util.List;
@@ -31,8 +32,8 @@ import org.yaml.snakeyaml.constructor.Constructor;
public class SafePolicyBuilder {
- private SafePolicyBuilder(){
- //Private Constructor.
+ private SafePolicyBuilder() {
+ // Private Constructor.
}
public static ControlLoopGuard loadYamlGuard(String specification) {
@@ -45,40 +46,42 @@ public class SafePolicyBuilder {
return (ControlLoopGuard) obj;
}
- public static String generateXacmlGuard(String xacmlFileContent,Map<String, String> generateMap, List<String> blacklist, List<String> targets) {
- //Setup default values and Targets.
- StringBuilder targetRegex= new StringBuilder(".*|");
- if(targets!=null && !targets.isEmpty()){
+ public static String generateXacmlGuard(String xacmlFileContent, Map<String, String> generateMap,
+ List<String> blacklist, List<String> targets) {
+ // Setup default values and Targets.
+ StringBuilder targetRegex = new StringBuilder(".*|");
+ if (targets != null && !targets.isEmpty()) {
targetRegex = new StringBuilder();
- for(String t : targets){
+ for (String t : targets) {
targetRegex.append(t + "|");
}
}
- if(generateMap.get("clname")==null|| generateMap.get("clname").isEmpty()){
- generateMap.put("clname",".*");
+ if (generateMap.get("clname") == null || generateMap.get("clname").isEmpty()) {
+ generateMap.put("clname", ".*");
}
- generateMap.put("targets", targetRegex.toString().substring(0, targetRegex.length()-1));
+ generateMap.put("targets", targetRegex.toString().substring(0, targetRegex.length() - 1));
// Replace values.
- for(Map.Entry<String,String> map: generateMap.entrySet()){
- Pattern p = Pattern.compile("\\$\\{" +map.getKey() +"\\}");
+ for (Map.Entry<String, String> map : generateMap.entrySet()) {
+ Pattern p = Pattern.compile("\\$\\{" + map.getKey() + "\\}");
Matcher m = p.matcher(xacmlFileContent);
String finalInput = map.getValue();
- if(finalInput.contains("$")){
+ if (finalInput.contains("$")) {
finalInput = finalInput.replace("$", "\\$");
}
- xacmlFileContent=m.replaceAll(finalInput);
+ xacmlFileContent = m.replaceAll(finalInput);
}
- if(blacklist!=null && !blacklist.isEmpty()){
+ if (blacklist != null && !blacklist.isEmpty()) {
StringBuilder rule = new StringBuilder();
- for(String blackListName : blacklist){
- if(blackListName.contains("$")){
+ for (String blackListName : blacklist) {
+ if (blackListName.contains("$")) {
blackListName = blackListName.replace("$", "\\$");
}
- rule.append("<AttributeValue DataType=\"http://www.w3.org/2001/XMLSchema#string\">"+blackListName+"</AttributeValue>");
+ rule.append("<AttributeValue DataType=\"http://www.w3.org/2001/XMLSchema#string\">" + blackListName
+ + "</AttributeValue>");
}
Pattern p = Pattern.compile("\\$\\{blackListElement\\}");
Matcher m = p.matcher(xacmlFileContent);
- xacmlFileContent=m.replaceAll(rule.toString());
+ 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/controller/ActionPolicyDictionaryController.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/ActionPolicyDictionaryController.java
index 8e620408b..f576bffe8 100644
--- 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
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP-PAP-REST
* ================================================================================
- * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -20,6 +20,10 @@
package org.onap.policy.pap.xacml.rest.controller;
+import com.fasterxml.jackson.databind.DeserializationFeature;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+
import java.io.IOException;
import java.util.Date;
import java.util.List;
@@ -38,10 +42,6 @@ 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 ActionPolicyDictionaryController {
@@ -51,36 +51,43 @@ public class ActionPolicyDictionaryController {
private static String actionDatas = "actionPolicyDictionaryDatas";
@Autowired
- public ActionPolicyDictionaryController(CommonClassDao commonClassDao){
+ public ActionPolicyDictionaryController(CommonClassDao commonClassDao) {
ActionPolicyDictionaryController.commonClassDao = commonClassDao;
}
- public void setCommonClassDao(CommonClassDao commonClassDao){
+ public void setCommonClassDao(CommonClassDao commonClassDao) {
ActionPolicyDictionaryController.commonClassDao = commonClassDao;
}
- public ActionPolicyDictionaryController(){
+ public ActionPolicyDictionaryController() {
super();
}
- private DictionaryUtils getDictionaryUtilsInstance(){
+ private DictionaryUtils getDictionaryUtilsInstance() {
return DictionaryUtils.getDictionaryUtils();
}
- @RequestMapping(value={"/get_ActionPolicyDictDataByName"}, method={RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE)
- public void getActionEntitybyName(HttpServletResponse response){
+ @RequestMapping(
+ value = {"/get_ActionPolicyDictDataByName"},
+ method = {RequestMethod.GET},
+ produces = MediaType.APPLICATION_JSON_VALUE)
+ public void getActionEntitybyName(HttpServletResponse response) {
DictionaryUtils utils = getDictionaryUtilsInstance();
utils.getDataByEntity(response, actionDatas, attributeName, ActionPolicyDict.class);
}
- @RequestMapping(value={"/get_ActionPolicyDictData"}, method={RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE)
- public void getActionPolicyDictionaryEntityData(HttpServletResponse response){
+ @RequestMapping(
+ value = {"/get_ActionPolicyDictData"},
+ method = {RequestMethod.GET},
+ produces = MediaType.APPLICATION_JSON_VALUE)
+ public void getActionPolicyDictionaryEntityData(HttpServletResponse response) {
DictionaryUtils utils = getDictionaryUtilsInstance();
utils.getData(response, actionDatas, ActionPolicyDict.class);
}
- @RequestMapping(value={"/action_dictionary/save_ActionDict"}, method={RequestMethod.POST})
- public ModelAndView saveActionPolicyDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{
+ @RequestMapping(value = {"/action_dictionary/save_ActionDict"}, method = {RequestMethod.POST})
+ public ModelAndView saveActionPolicyDictionary(HttpServletRequest request, HttpServletResponse response)
+ throws IOException {
DictionaryUtils utils = getDictionaryUtilsInstance();
try {
boolean fromAPI = utils.isRequestFromAPI(request);
@@ -90,63 +97,68 @@ public class ActionPolicyDictionaryController {
ActionPolicyDict actionPolicyDict = null;
ActionAdapter adapter = null;
String userId = null;
- if(fromAPI){
+ if (fromAPI) {
actionPolicyDict = mapper.readValue(root.get("dictionaryFields").toString(), ActionPolicyDict.class);
adapter = mapper.readValue(root.get("dictionaryFields").toString(), ActionAdapter.class);
userId = "API";
- }else{
- actionPolicyDict = mapper.readValue(root.get("actionPolicyDictionaryData").toString(), ActionPolicyDict.class);
+ } else {
+ actionPolicyDict =
+ mapper.readValue(root.get("actionPolicyDictionaryData").toString(), ActionPolicyDict.class);
adapter = mapper.readValue(root.get("actionPolicyDictionaryData").toString(), ActionAdapter.class);
userId = root.get("userid").textValue();
}
UserInfo userInfo = utils.getUserInfo(userId);
- List<Object> duplicateData = commonClassDao.checkDuplicateEntry(actionPolicyDict.getAttributeName(), attributeName, ActionPolicyDict.class);
+ List<Object> duplicateData = commonClassDao.checkDuplicateEntry(actionPolicyDict.getAttributeName(),
+ attributeName, ActionPolicyDict.class);
boolean duplicateflag = false;
- if(!duplicateData.isEmpty()){
+ if (!duplicateData.isEmpty()) {
ActionPolicyDict data = (ActionPolicyDict) duplicateData.get(0);
- if(request.getParameter(operation) != null && "update".equals(request.getParameter(operation))){
+ if (request.getParameter(operation) != null && "update".equals(request.getParameter(operation))) {
actionPolicyDict.setId(data.getId());
- }else if((request.getParameter(operation) != null && !"update".equals(request.getParameter(operation))) ||
- (request.getParameter(operation) == null && (data.getId() != actionPolicyDict.getId()))){
+ } else if ((request.getParameter(operation) != null
+ && !"update".equals(request.getParameter(operation)))
+ || (request.getParameter(operation) == null && (data.getId() != actionPolicyDict.getId()))) {
duplicateflag = true;
}
}
actionPolicyDict.setHeader(utils.appendKeyValue(adapter.getHeaders(), ":", "="));
String responseString = null;
- if(!duplicateflag){
+ if (!duplicateflag) {
actionPolicyDict.setUserModifiedBy(userInfo);
- if(actionPolicyDict.getId() == 0){
+ if (actionPolicyDict.getId() == 0) {
actionPolicyDict.setUserCreatedBy(userInfo);
commonClassDao.save(actionPolicyDict);
- }else{
+ } else {
actionPolicyDict.setModifiedDate(new Date());
commonClassDao.update(actionPolicyDict);
}
responseString = mapper.writeValueAsString(commonClassDao.getData(ActionPolicyDict.class));
- }else{
+ } else {
responseString = "Duplicate";
}
- if(fromAPI){
+ if (fromAPI) {
return utils.getResultForApi(responseString);
- }else{
+ } else {
utils.setResponseData(response, actionDatas, responseString);
}
- }catch(Exception e){
+ } catch (Exception e) {
utils.setErrorResponseData(response, e);
}
return null;
}
- @RequestMapping(value={"/action_dictionary/remove_actionPolicyDict"}, method={RequestMethod.POST})
- public void removeActionPolicyDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException {
+ @RequestMapping(value = {"/action_dictionary/remove_actionPolicyDict"}, method = {RequestMethod.POST})
+ public void removeActionPolicyDictionary(HttpServletRequest request, HttpServletResponse response)
+ throws IOException {
DictionaryUtils utils = getDictionaryUtilsInstance();
utils.removeData(request, response, actionDatas, ActionPolicyDict.class);
}
}
-class ActionAdapter{
+
+class ActionAdapter {
private List<Object> headers;
public List<Object> getHeaders() {
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
index d6ebed2b8..d9cde35bb 100644
--- 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
@@ -23,13 +23,16 @@ package org.onap.policy.pap.xacml.rest.controller;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
+
import java.io.IOException;
import java.io.StringWriter;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.List;
+
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
+
import org.apache.commons.io.IOUtils;
import org.onap.policy.api.PEDependency;
import org.onap.policy.common.logging.flexlogger.FlexLogger;
@@ -37,9 +40,9 @@ import org.onap.policy.common.logging.flexlogger.Logger;
import org.onap.policy.pap.xacml.rest.components.CreateBRMSRuleTemplate;
import org.onap.policy.pap.xacml.rest.util.DictionaryUtils;
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.BrmsController;
+import org.onap.policy.rest.jpa.BrmsDependency;
+import org.onap.policy.rest.jpa.BrmsParamTemplate;
import org.onap.policy.rest.jpa.OnapName;
import org.onap.policy.rest.jpa.UserInfo;
import org.onap.policy.utils.PolicyUtils;
@@ -51,7 +54,6 @@ import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
-
@Controller
public class BRMSDictionaryController {
@@ -91,32 +93,35 @@ public class BRMSDictionaryController {
return DictionaryUtils.getDictionaryUtils();
}
- @RequestMapping(value = {"/get_BRMSParamDataByName"}, method = {RequestMethod.GET},
+ @RequestMapping(
+ value = {"/get_BRMSParamDataByName"},
+ method = {RequestMethod.GET},
produces = MediaType.APPLICATION_JSON_VALUE)
public void getBRMSParamDictionaryByNameEntityData(HttpServletResponse response) {
DictionaryUtils utils = getDictionaryUtilsInstance();
- utils.getDataByEntity(response, brmsParamDatas, ruleName, BRMSParamTemplate.class);
+ utils.getDataByEntity(response, brmsParamDatas, ruleName, BrmsParamTemplate.class);
}
- @RequestMapping(value = {"/get_BRMSParamData"}, method = {RequestMethod.GET},
+ @RequestMapping(
+ value = {"/get_BRMSParamData"},
+ method = {RequestMethod.GET},
produces = MediaType.APPLICATION_JSON_VALUE)
public void getBRMSParamDictionaryEntityData(HttpServletResponse response) {
DictionaryUtils utils = getDictionaryUtilsInstance();
- utils.getData(response, brmsParamDatas, BRMSParamTemplate.class);
+ utils.getData(response, brmsParamDatas, BrmsParamTemplate.class);
}
@RequestMapping(value = {"/brms_dictionary/set_BRMSParamData"}, method = {RequestMethod.POST})
public static void setRuleData(HttpServletRequest request) throws IOException {
StringWriter writer = new StringWriter();
IOUtils.copy(request.getInputStream(), writer, StandardCharsets.UTF_8);
- String cleanStreamBoundary =
- writer.toString().replaceFirst("------(.*)(?s).*octet-stream", "");
+ String cleanStreamBoundary = writer.toString().replaceFirst("------(.*)(?s).*octet-stream", "");
rule = cleanStreamBoundary.substring(0, cleanStreamBoundary.lastIndexOf("end") + 4);
}
@RequestMapping(value = {"/brms_dictionary/save_BRMSParam"}, method = {RequestMethod.POST})
- public ModelAndView saveBRMSParamDictionary(HttpServletRequest request,
- HttpServletResponse response) throws IOException {
+ public ModelAndView saveBRMSParamDictionary(HttpServletRequest request, HttpServletResponse response)
+ throws IOException {
DictionaryUtils utils = getDictionaryUtilsInstance();
try {
boolean fromAPI = utils.isRequestFromAPI(request);
@@ -124,26 +129,25 @@ public class BRMSDictionaryController {
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
JsonNode root = mapper.readTree(request.getReader());
- BRMSParamTemplate bRMSParamTemplateData;
+ BrmsParamTemplate bRMSParamTemplateData;
String userId = null;
if (fromAPI) {
- bRMSParamTemplateData = mapper.readValue(root.get(dictionaryFields).toString(),
- BRMSParamTemplate.class);
+ bRMSParamTemplateData =
+ mapper.readValue(root.get(dictionaryFields).toString(), BrmsParamTemplate.class);
userId = "API";
} else {
- bRMSParamTemplateData = mapper.readValue(
- root.get("brmsParamDictionaryData").toString(), BRMSParamTemplate.class);
+ bRMSParamTemplateData =
+ mapper.readValue(root.get("brmsParamDictionaryData").toString(), BrmsParamTemplate.class);
userId = root.get(userid).textValue();
}
UserInfo userInfo = utils.getUserInfo(userId);
- List<Object> duplicateData = commonClassDao.checkDuplicateEntry(
- bRMSParamTemplateData.getRuleName(), ruleName, BRMSParamTemplate.class);
+ List<Object> duplicateData = commonClassDao.checkDuplicateEntry(bRMSParamTemplateData.getRuleName(),
+ ruleName, BrmsParamTemplate.class);
boolean duplicateflag = false;
if (!duplicateData.isEmpty()) {
- BRMSParamTemplate data = (BRMSParamTemplate) duplicateData.get(0);
- if (request.getParameter(operation) != null
- && "update".equals(request.getParameter(operation))) {
+ BrmsParamTemplate data = (BrmsParamTemplate) duplicateData.get(0);
+ if (request.getParameter(operation) != null && "update".equals(request.getParameter(operation))) {
bRMSParamTemplateData.setId(data.getId());
} else if ((request.getParameter(operation) != null
&& !"update".equals(request.getParameter(operation)))
@@ -164,8 +168,7 @@ public class BRMSDictionaryController {
} else {
commonClassDao.update(bRMSParamTemplateData);
}
- responseString = mapper
- .writeValueAsString(commonClassDao.getData(BRMSParamTemplate.class));
+ responseString = mapper.writeValueAsString(commonClassDao.getData(BrmsParamTemplate.class));
} else {
responseString = duplicateResponseString;
}
@@ -192,30 +195,32 @@ public class BRMSDictionaryController {
}
@RequestMapping(value = {"/brms_dictionary/remove_brmsParam"}, method = {RequestMethod.POST})
- public void removeBRMSParamDictionary(HttpServletRequest request, HttpServletResponse response)
- throws IOException {
+ public void removeBRMSParamDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException {
DictionaryUtils utils = getDictionaryUtilsInstance();
- utils.removeData(request, response, brmsParamDatas, BRMSParamTemplate.class);
+ utils.removeData(request, response, brmsParamDatas, BrmsParamTemplate.class);
}
- @RequestMapping(value = {"/get_BRMSDependencyDataByName"}, method = {RequestMethod.GET},
+ @RequestMapping(
+ value = {"/get_BRMSDependencyDataByName"},
+ method = {RequestMethod.GET},
produces = MediaType.APPLICATION_JSON_VALUE)
public void getBRMSDependencyDictionaryByNameEntityData(HttpServletResponse response) {
DictionaryUtils utils = getDictionaryUtilsInstance();
- utils.getDataByEntity(response, brmsDependencyDatas, dependencyName, BRMSDependency.class);
+ utils.getDataByEntity(response, brmsDependencyDatas, dependencyName, BrmsDependency.class);
}
- @RequestMapping(value = {"/get_BRMSDependencyData"}, method = {RequestMethod.GET},
+ @RequestMapping(
+ value = {"/get_BRMSDependencyData"},
+ method = {RequestMethod.GET},
produces = MediaType.APPLICATION_JSON_VALUE)
public void getBRMSDependencyDictionaryEntityData(HttpServletResponse response) {
DictionaryUtils utils = getDictionaryUtilsInstance();
- utils.getData(response, brmsDependencyDatas, BRMSDependency.class);
+ utils.getData(response, brmsDependencyDatas, BrmsDependency.class);
}
- @RequestMapping(value = {"/brms_dictionary/save_BRMSDependencyData"},
- method = {RequestMethod.POST})
- public ModelAndView saveBRMSDependencyDictionary(HttpServletRequest request,
- HttpServletResponse response) throws IOException {
+ @RequestMapping(value = {"/brms_dictionary/save_BRMSDependencyData"}, method = {RequestMethod.POST})
+ public ModelAndView saveBRMSDependencyDictionary(HttpServletRequest request, HttpServletResponse response)
+ throws IOException {
DictionaryUtils utils = getDictionaryUtilsInstance();
try {
LOGGER.debug("DictionaryController: saveBRMSDependencyDictionary() is called");
@@ -224,46 +229,41 @@ public class BRMSDictionaryController {
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
JsonNode root = mapper.readTree(request.getReader());
- BRMSDependency brmsDependency;
+ BrmsDependency brmsDependency;
String userId = null;
if (fromAPI) {
- brmsDependency = mapper.readValue(root.get(dictionaryFields).toString(),
- BRMSDependency.class);
+ brmsDependency = mapper.readValue(root.get(dictionaryFields).toString(), BrmsDependency.class);
userId = "API";
} else {
- brmsDependency = mapper.readValue(
- root.get("brmsDependencyDictionaryData").toString(), BRMSDependency.class);
+ brmsDependency =
+ mapper.readValue(root.get("brmsDependencyDictionaryData").toString(), BrmsDependency.class);
userId = root.get(userid).textValue();
}
UserInfo userInfo = utils.getUserInfo(userId);
- List<Object> duplicateData = commonClassDao.checkDuplicateEntry(
- brmsDependency.getDependencyName(), dependencyName, BRMSDependency.class);
+ List<Object> duplicateData = commonClassDao.checkDuplicateEntry(brmsDependency.getDependencyName(),
+ dependencyName, BrmsDependency.class);
boolean duplicateflag = false;
if (!duplicateData.isEmpty()) {
- BRMSDependency data = (BRMSDependency) duplicateData.get(0);
- if (request.getParameter(operation) != null
- && "update".equals(request.getParameter(operation))) {
+ BrmsDependency data = (BrmsDependency) duplicateData.get(0);
+ if (request.getParameter(operation) != null && "update".equals(request.getParameter(operation))) {
brmsDependency.setId(data.getId());
} else if ((request.getParameter(operation) != null
&& !"update".equals(request.getParameter(operation)))
- || (request.getParameter(operation) == null
- && (data.getId() != brmsDependency.getId()))) {
+ || (request.getParameter(operation) == null && (data.getId() != brmsDependency.getId()))) {
duplicateflag = true;
}
}
LOGGER.audit("the userId from the onap portal is: " + userId);
String responseString = null;
- if (brmsDependency.getDependency() != null
- && !("").equals(brmsDependency.getDependency().trim())) {
+ if (brmsDependency.getDependency() != null && !("").equals(brmsDependency.getDependency().trim())) {
PEDependency dependency = null;
try {
- dependency = PolicyUtils.jsonStringToObject(brmsDependency.getDependency(),
- PEDependency.class);
+ 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(), e);
+ + "wrong data given for BRMS PEDependency Dictionary : " + brmsDependency.getDependency(),
+ e);
}
if (dependency == null) {
responseString = errorMessage;
@@ -277,8 +277,7 @@ public class BRMSDictionaryController {
brmsDependency.setModifiedDate(new Date());
commonClassDao.update(brmsDependency);
}
- responseString = mapper
- .writeValueAsString(commonClassDao.getData(BRMSDependency.class));
+ responseString = mapper.writeValueAsString(commonClassDao.getData(BrmsDependency.class));
} else {
responseString = duplicateResponseString;
}
@@ -302,33 +301,34 @@ public class BRMSDictionaryController {
return null;
}
- @RequestMapping(value = {"/brms_dictionary/remove_brmsDependency"},
- method = {RequestMethod.POST})
- public void removeBRMSDependencyDictionary(HttpServletRequest request,
- HttpServletResponse response) throws IOException {
+ @RequestMapping(value = {"/brms_dictionary/remove_brmsDependency"}, method = {RequestMethod.POST})
+ public void removeBRMSDependencyDictionary(HttpServletRequest request, HttpServletResponse response)
+ throws IOException {
DictionaryUtils utils = getDictionaryUtilsInstance();
- utils.removeData(request, response, brmsDependencyDatas, BRMSDependency.class);
+ utils.removeData(request, response, brmsDependencyDatas, BrmsDependency.class);
}
-
- @RequestMapping(value = {"/get_BRMSControllerDataByName"}, method = {RequestMethod.GET},
+ @RequestMapping(
+ value = {"/get_BRMSControllerDataByName"},
+ method = {RequestMethod.GET},
produces = MediaType.APPLICATION_JSON_VALUE)
public void getBRMSControllerDictionaryByNameEntityData(HttpServletResponse response) {
DictionaryUtils utils = getDictionaryUtilsInstance();
- utils.getDataByEntity(response, brmsControllerDatas, controllerName, BRMSController.class);
+ utils.getDataByEntity(response, brmsControllerDatas, controllerName, BrmsController.class);
}
- @RequestMapping(value = {"/get_BRMSControllerData"}, method = {RequestMethod.GET},
+ @RequestMapping(
+ value = {"/get_BRMSControllerData"},
+ method = {RequestMethod.GET},
produces = MediaType.APPLICATION_JSON_VALUE)
public void getBRMSControllerDictionaryEntityData(HttpServletResponse response) {
DictionaryUtils utils = getDictionaryUtilsInstance();
- utils.getData(response, brmsControllerDatas, BRMSController.class);
+ utils.getData(response, brmsControllerDatas, BrmsController.class);
}
- @RequestMapping(value = {"/brms_dictionary/save_BRMSControllerData"},
- method = {RequestMethod.POST})
- public ModelAndView saveBRMSControllerDictionary(HttpServletRequest request,
- HttpServletResponse response) throws IOException {
+ @RequestMapping(value = {"/brms_dictionary/save_BRMSControllerData"}, method = {RequestMethod.POST})
+ public ModelAndView saveBRMSControllerDictionary(HttpServletRequest request, HttpServletResponse response)
+ throws IOException {
DictionaryUtils utils = getDictionaryUtilsInstance();
try {
LOGGER.debug("DictionaryController: saveBRMSControllerDictionary() is called");
@@ -336,45 +336,39 @@ public class BRMSDictionaryController {
ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
JsonNode root = mapper.readTree(request.getReader());
- BRMSController brmsController;
+ BrmsController brmsController;
String userId = null;
if (fromAPI) {
- brmsController = mapper.readValue(root.get(dictionaryFields).toString(),
- BRMSController.class);
+ brmsController = mapper.readValue(root.get(dictionaryFields).toString(), BrmsController.class);
userId = "API";
} else {
- brmsController = mapper.readValue(
- root.get("brmsControllerDictionaryData").toString(), BRMSController.class);
+ brmsController =
+ mapper.readValue(root.get("brmsControllerDictionaryData").toString(), BrmsController.class);
userId = root.get(userid).textValue();
}
UserInfo userInfo = utils.getUserInfo(userId);
- List<Object> duplicateData = commonClassDao.checkDuplicateEntry(
- brmsController.getControllerName(), controllerName, BRMSController.class);
+ List<Object> duplicateData = commonClassDao.checkDuplicateEntry(brmsController.getControllerName(),
+ controllerName, BrmsController.class);
boolean duplicateflag = false;
if (!duplicateData.isEmpty()) {
- BRMSController data = (BRMSController) duplicateData.get(0);
- if (request.getParameter(operation) != null
- && "update".equals(request.getParameter(operation))) {
+ BrmsController data = (BrmsController) duplicateData.get(0);
+ if (request.getParameter(operation) != null && "update".equals(request.getParameter(operation))) {
brmsController.setId(data.getId());
} else if ((request.getParameter(operation) != null
&& !"update".equals(request.getParameter(operation)))
- || (request.getParameter(operation) == null
- && (data.getId() != brmsController.getId()))) {
+ || (request.getParameter(operation) == null && (data.getId() != brmsController.getId()))) {
duplicateflag = true;
}
}
String responseString = null;
- if (brmsController.getController() != null
- && !("").equals(brmsController.getController().trim())) {
+ if (brmsController.getController() != null && !("").equals(brmsController.getController().trim())) {
PEDependency dependency = null;
try {
- dependency = PolicyUtils.jsonStringToObject(brmsController.getController(),
- PEDependency.class);
+ 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(), e);
+ + "wrong data given for BRMS Controller Dictionary : " + brmsController.getController(), e);
}
if (dependency == null) {
responseString = errorMessage;
@@ -388,8 +382,7 @@ public class BRMSDictionaryController {
brmsController.setModifiedDate(new Date());
commonClassDao.update(brmsController);
}
- responseString =
- mapper.writeValueAsString(commonClassDao.getData(OnapName.class));
+ responseString = mapper.writeValueAsString(commonClassDao.getData(OnapName.class));
} else {
responseString = duplicateResponseString;
}
@@ -412,21 +405,20 @@ public class BRMSDictionaryController {
return null;
}
- @RequestMapping(value = {"/brms_dictionary/remove_brmsController"},
- method = {RequestMethod.POST})
- public void removeBRMSControllerDictionary(HttpServletRequest request,
- HttpServletResponse response) throws IOException {
+ @RequestMapping(value = {"/brms_dictionary/remove_brmsController"}, method = {RequestMethod.POST})
+ public void removeBRMSControllerDictionary(HttpServletRequest request, HttpServletResponse response)
+ throws IOException {
DictionaryUtils utils = getDictionaryUtilsInstance();
- utils.removeData(request, response, brmsControllerDatas, BRMSController.class);
+ utils.removeData(request, response, brmsControllerDatas, BrmsController.class);
}
- public BRMSDependency getDependencyDataByID(String dependencyName) {
- return (BRMSDependency) commonClassDao.getEntityItem(BRMSDependency.class,
+ public BrmsDependency getDependencyDataByID(String dependencyName) {
+ return (BrmsDependency) commonClassDao.getEntityItem(BrmsDependency.class,
BRMSDictionaryController.dependencyName, dependencyName);
}
- public BRMSController getControllerDataByID(String controllerName) {
- return (BRMSController) commonClassDao.getEntityItem(BRMSController.class,
+ public BrmsController getControllerDataByID(String controllerName) {
+ return (BrmsController) commonClassDao.getEntityItem(BrmsController.class,
BRMSDictionaryController.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
index 2aec0cc0d..9ea956aa7 100644
--- 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
@@ -23,11 +23,14 @@ package org.onap.policy.pap.xacml.rest.controller;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
+
import java.io.IOException;
import java.util.Date;
import java.util.List;
+
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
+
import org.onap.policy.pap.xacml.rest.adapters.GridData;
import org.onap.policy.pap.xacml.rest.daoimpl.CommonClassDaoImpl;
import org.onap.policy.pap.xacml.rest.util.DictionaryUtils;
@@ -35,10 +38,10 @@ 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.OnapName;
-import org.onap.policy.rest.jpa.PEPOptions;
+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.VnfType;
+import org.onap.policy.rest.jpa.VsclAction;
import org.onap.policy.rest.jpa.VarbindDictionary;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
@@ -51,9 +54,9 @@ import org.springframework.web.servlet.ModelAndView;
public class ClosedLoopDictionaryController {
private static CommonClassDao commonClassDao;
- private static String vsclaction = "vsclaction";
+ private static String vsclaction = "action";
private static String operation = "operation";
- private static String vnftype = "vnftype";
+ private static String vnftype = "type";
private static String pepName = "pepName";
private static String varbindName = "varbindName";
private static String serviceName = "serviceName";
@@ -89,85 +92,108 @@ public class ClosedLoopDictionaryController {
return DictionaryUtils.getDictionaryUtils();
}
- @RequestMapping(value = {"/get_VSCLActionDataByName"}, method = {RequestMethod.GET},
+ @RequestMapping(
+ value = {"/get_VSCLActionDataByName"},
+ method = {RequestMethod.GET},
produces = MediaType.APPLICATION_JSON_VALUE)
public void getVSCLActionDictionaryByNameEntityData(HttpServletResponse response) {
DictionaryUtils utils = getDictionaryUtilsInstance();
- utils.getDataByEntity(response, vsclActionDatas, vsclaction, VSCLAction.class);
+ utils.getDataByEntity(response, vsclActionDatas, vsclaction, VsclAction.class);
}
-
- @RequestMapping(value = {"/get_VSCLActionData"}, method = {RequestMethod.GET},
+ @RequestMapping(
+ value = {"/get_VSCLActionData"},
+ method = {RequestMethod.GET},
produces = MediaType.APPLICATION_JSON_VALUE)
public void getVSCLActionDictionaryEntityData(HttpServletResponse response) {
DictionaryUtils utils = getDictionaryUtilsInstance();
- utils.getData(response, vsclActionDatas, VSCLAction.class);
+ utils.getData(response, vsclActionDatas, VsclAction.class);
}
- @RequestMapping(value = {"/get_VNFTypeDataByName"}, method = {RequestMethod.GET},
+ @RequestMapping(
+ value = {"/get_VNFTypeDataByName"},
+ method = {RequestMethod.GET},
produces = MediaType.APPLICATION_JSON_VALUE)
public void getVNFTypeDictionaryByNameEntityData(HttpServletResponse response) {
DictionaryUtils utils = getDictionaryUtilsInstance();
- utils.getDataByEntity(response, vnfTypeDatas, vnftype, VNFType.class);
+ utils.getDataByEntity(response, vnfTypeDatas, vnftype, VnfType.class);
}
- @RequestMapping(value = {"/get_VNFTypeData"}, method = {RequestMethod.GET},
+ @RequestMapping(
+ value = {"/get_VNFTypeData"},
+ method = {RequestMethod.GET},
produces = MediaType.APPLICATION_JSON_VALUE)
public void getVNFTypeDictionaryEntityData(HttpServletResponse response) {
DictionaryUtils utils = getDictionaryUtilsInstance();
- utils.getData(response, vnfTypeDatas, VNFType.class);
+ utils.getData(response, vnfTypeDatas, VnfType.class);
}
- @RequestMapping(value = {"/get_PEPOptionsDataByName"}, method = {RequestMethod.GET},
+ @RequestMapping(
+ value = {"/get_PEPOptionsDataByName"},
+ method = {RequestMethod.GET},
produces = MediaType.APPLICATION_JSON_VALUE)
public void getPEPOptionsDictionaryByNameEntityData(HttpServletResponse response) {
DictionaryUtils utils = getDictionaryUtilsInstance();
- utils.getDataByEntity(response, pepOptionDatas, pepName, PEPOptions.class);
+ utils.getDataByEntity(response, pepOptionDatas, pepName, PepOptions.class);
}
- @RequestMapping(value = {"/get_PEPOptionsData"}, method = {RequestMethod.GET},
+ @RequestMapping(
+ value = {"/get_PEPOptionsData"},
+ method = {RequestMethod.GET},
produces = MediaType.APPLICATION_JSON_VALUE)
public void getPEPOptionsDictionaryEntityData(HttpServletResponse response) {
DictionaryUtils utils = getDictionaryUtilsInstance();
- utils.getData(response, pepOptionDatas, PEPOptions.class);
+ utils.getData(response, pepOptionDatas, PepOptions.class);
}
- @RequestMapping(value = {"/get_VarbindDictionaryDataByName"}, method = {RequestMethod.GET},
+ @RequestMapping(
+ value = {"/get_VarbindDictionaryDataByName"},
+ method = {RequestMethod.GET},
produces = MediaType.APPLICATION_JSON_VALUE)
public void getVarbindDictionaryByNameEntityData(HttpServletResponse response) {
DictionaryUtils utils = getDictionaryUtilsInstance();
utils.getDataByEntity(response, varbindDatas, varbindName, VarbindDictionary.class);
}
- @RequestMapping(value = {"/get_VarbindDictionaryData"}, method = {RequestMethod.GET},
+ @RequestMapping(
+ value = {"/get_VarbindDictionaryData"},
+ method = {RequestMethod.GET},
produces = MediaType.APPLICATION_JSON_VALUE)
public void getVarbindDictionaryEntityData(HttpServletResponse response) {
DictionaryUtils utils = getDictionaryUtilsInstance();
utils.getData(response, varbindDatas, VarbindDictionary.class);
}
- @RequestMapping(value = {"/get_ClosedLoopServicesDataByName"}, method = {RequestMethod.GET},
+ @RequestMapping(
+ value = {"/get_ClosedLoopServicesDataByName"},
+ method = {RequestMethod.GET},
produces = MediaType.APPLICATION_JSON_VALUE)
public void getClosedLoopServiceDictionaryByNameEntityData(HttpServletResponse response) {
DictionaryUtils utils = getDictionaryUtilsInstance();
utils.getDataByEntity(response, closedLoopDatas, serviceName, ClosedLoopD2Services.class);
}
- @RequestMapping(value = {"/get_ClosedLoopServicesData"}, method = {RequestMethod.GET},
+ @RequestMapping(
+ value = {"/get_ClosedLoopServicesData"},
+ method = {RequestMethod.GET},
produces = MediaType.APPLICATION_JSON_VALUE)
public void getClosedLoopServiceDictionaryEntityData(HttpServletResponse response) {
DictionaryUtils utils = getDictionaryUtilsInstance();
utils.getData(response, closedLoopDatas, ClosedLoopD2Services.class);
}
- @RequestMapping(value = {"/get_ClosedLoopSiteDataByName"}, method = {RequestMethod.GET},
+ @RequestMapping(
+ value = {"/get_ClosedLoopSiteDataByName"},
+ method = {RequestMethod.GET},
produces = MediaType.APPLICATION_JSON_VALUE)
public void getClosedLoopSiteDictionaryByNameEntityData(HttpServletResponse response) {
DictionaryUtils utils = getDictionaryUtilsInstance();
utils.getDataByEntity(response, closedLoopSiteDatas, siteName, ClosedLoopSite.class);
}
- @RequestMapping(value = {"/get_ClosedLoopSiteData"}, method = {RequestMethod.GET},
+ @RequestMapping(
+ value = {"/get_ClosedLoopSiteData"},
+ method = {RequestMethod.GET},
produces = MediaType.APPLICATION_JSON_VALUE)
public void getClosedLoopSiteDictionaryEntityData(HttpServletResponse response) {
DictionaryUtils utils = getDictionaryUtilsInstance();
@@ -175,39 +201,34 @@ public class ClosedLoopDictionaryController {
}
@RequestMapping(value = {"/cl_dictionary/save_vsclAction"}, method = {RequestMethod.POST})
- public ModelAndView saveVSCLAction(HttpServletRequest request, HttpServletResponse response)
- throws IOException {
+ public ModelAndView saveVSCLAction(HttpServletRequest request, HttpServletResponse response) throws IOException {
DictionaryUtils utils = getDictionaryUtilsInstance();
try {
boolean fromAPI = utils.isRequestFromAPI(request);
ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
JsonNode root = mapper.readTree(request.getReader());
- VSCLAction vSCLAction;
+ VsclAction vSCLAction;
String userId = null;
if (fromAPI) {
- vSCLAction =
- mapper.readValue(root.get(dictionaryFields).toString(), VSCLAction.class);
+ vSCLAction = mapper.readValue(root.get(dictionaryFields).toString(), VsclAction.class);
userId = "API";
} else {
- vSCLAction = mapper.readValue(root.get("vsclActionDictionaryData").toString(),
- VSCLAction.class);
+ vSCLAction = mapper.readValue(root.get("vsclActionDictionaryData").toString(), VsclAction.class);
userId = root.get(userid).textValue();
}
UserInfo userInfo = utils.getUserInfo(userId);
- List<Object> duplicateData = commonClassDao
- .checkDuplicateEntry(vSCLAction.getVsclaction(), vsclaction, VSCLAction.class);
+ List<Object> duplicateData =
+ commonClassDao.checkDuplicateEntry(vSCLAction.getAction(), vsclaction, VsclAction.class);
boolean duplicateflag = false;
if (!duplicateData.isEmpty()) {
- VSCLAction data = (VSCLAction) duplicateData.get(0);
- if (request.getParameter(operation) != null
- && "update".equals(request.getParameter(operation))) {
+ VsclAction data = (VsclAction) duplicateData.get(0);
+ if (request.getParameter(operation) != null && "update".equals(request.getParameter(operation))) {
vSCLAction.setId(data.getId());
} else if ((request.getParameter(operation) != null
&& !"update".equals(request.getParameter(operation)))
- || (request.getParameter(operation) == null
- && (data.getId() != vSCLAction.getId()))) {
+ || (request.getParameter(operation) == null && (data.getId() != vSCLAction.getId()))) {
duplicateflag = true;
}
}
@@ -221,8 +242,7 @@ public class ClosedLoopDictionaryController {
vSCLAction.setModifiedDate(new Date());
commonClassDao.update(vSCLAction);
}
- responseString =
- mapper.writeValueAsString(commonClassDao.getData(VSCLAction.class));
+ responseString = mapper.writeValueAsString(commonClassDao.getData(VsclAction.class));
} else {
responseString = duplicateResponseString;
}
@@ -239,45 +259,40 @@ public class ClosedLoopDictionaryController {
}
@RequestMapping(value = {"/cl_dictionary/remove_VsclAction"}, method = {RequestMethod.POST})
- public void removeVSCLAction(HttpServletRequest request, HttpServletResponse response)
- throws IOException {
+ public void removeVSCLAction(HttpServletRequest request, HttpServletResponse response) throws IOException {
DictionaryUtils utils = getDictionaryUtilsInstance();
utils.removeData(request, response, vsclActionDatas, OnapName.class);
}
@RequestMapping(value = {"/cl_dictionary/save_vnfType"}, method = {RequestMethod.POST})
- public ModelAndView saveVnfType(HttpServletRequest request, HttpServletResponse response)
- throws IOException {
+ public ModelAndView saveVnfType(HttpServletRequest request, HttpServletResponse response) throws IOException {
DictionaryUtils utils = getDictionaryUtilsInstance();
try {
boolean fromAPI = utils.isRequestFromAPI(request);
ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
JsonNode root = mapper.readTree(request.getReader());
- VNFType vNFType;
+ VnfType vNFType;
String userId = null;
if (fromAPI) {
- vNFType = mapper.readValue(root.get(dictionaryFields).toString(), VNFType.class);
+ vNFType = mapper.readValue(root.get(dictionaryFields).toString(), VnfType.class);
userId = "API";
} else {
- vNFType = mapper.readValue(root.get("vnfTypeDictionaryData").toString(),
- VNFType.class);
+ vNFType = mapper.readValue(root.get("vnfTypeDictionaryData").toString(), VnfType.class);
userId = root.get(userid).textValue();
}
UserInfo userInfo = utils.getUserInfo(userId);
- List<Object> duplicateData = commonClassDao.checkDuplicateEntry(vNFType.getVnftype(),
- vnftype, VNFType.class);
+ List<Object> duplicateData =
+ commonClassDao.checkDuplicateEntry(vNFType.getType(), vnftype, VnfType.class);
boolean duplicateflag = false;
if (!duplicateData.isEmpty()) {
- VNFType data = (VNFType) duplicateData.get(0);
- if (request.getParameter(operation) != null
- && "update".equals(request.getParameter(operation))) {
+ VnfType data = (VnfType) duplicateData.get(0);
+ if (request.getParameter(operation) != null && "update".equals(request.getParameter(operation))) {
vNFType.setId(data.getId());
} else if ((request.getParameter(operation) != null
&& !"update".equals(request.getParameter(operation)))
- || (request.getParameter(operation) == null
- && (data.getId() != vNFType.getId()))) {
+ || (request.getParameter(operation) == null && (data.getId() != vNFType.getId()))) {
duplicateflag = true;
}
}
@@ -291,7 +306,7 @@ public class ClosedLoopDictionaryController {
vNFType.setModifiedDate(new Date());
commonClassDao.update(vNFType);
}
- responseString = mapper.writeValueAsString(commonClassDao.getData(VNFType.class));
+ responseString = mapper.writeValueAsString(commonClassDao.getData(VnfType.class));
} else {
responseString = duplicateResponseString;
}
@@ -308,34 +323,29 @@ public class ClosedLoopDictionaryController {
}
@RequestMapping(value = {"/cl_dictionary/remove_vnfType"}, method = {RequestMethod.POST})
- public void removeVnfType(HttpServletRequest request, HttpServletResponse response)
- throws IOException {
+ public void removeVnfType(HttpServletRequest request, HttpServletResponse response) throws IOException {
DictionaryUtils utils = getDictionaryUtilsInstance();
- utils.removeData(request, response, vnfTypeDatas, VNFType.class);
+ utils.removeData(request, response, vnfTypeDatas, VnfType.class);
}
@RequestMapping(value = {"/cl_dictionary/save_pepOptions"}, method = {RequestMethod.POST})
- public ModelAndView savePEPOptions(HttpServletRequest request, HttpServletResponse response)
- throws IOException {
+ public ModelAndView savePEPOptions(HttpServletRequest request, HttpServletResponse response) throws IOException {
DictionaryUtils utils = getDictionaryUtilsInstance();
try {
boolean fromAPI = utils.isRequestFromAPI(request);
ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
JsonNode root = mapper.readTree(request.getReader());
- PEPOptions pEPOptions;
+ PepOptions pEPOptions;
GridData gridData;
String userId = null;
if (fromAPI) {
- pEPOptions =
- mapper.readValue(root.get(dictionaryFields).toString(), PEPOptions.class);
+ pEPOptions = mapper.readValue(root.get(dictionaryFields).toString(), PepOptions.class);
gridData = mapper.readValue(root.get(dictionaryFields).toString(), GridData.class);
userId = "API";
} else {
- pEPOptions = mapper.readValue(root.get("pepOptionsDictionaryData").toString(),
- PEPOptions.class);
- gridData = mapper.readValue(root.get("pepOptionsDictionaryData").toString(),
- GridData.class);
+ pEPOptions = mapper.readValue(root.get("pepOptionsDictionaryData").toString(), PepOptions.class);
+ gridData = mapper.readValue(root.get("pepOptionsDictionaryData").toString(), GridData.class);
userId = root.get(userid).textValue();
}
UserInfo userInfo = utils.getUserInfo(userId);
@@ -344,18 +354,16 @@ public class ClosedLoopDictionaryController {
pEPOptions.setActions(utils.appendKeyValue(gridData.getAttributes(), ":#@", "=#@"));
}
- List<Object> duplicateData = commonClassDao.checkDuplicateEntry(pEPOptions.getPepName(),
- pepName, PEPOptions.class);
+ List<Object> duplicateData =
+ commonClassDao.checkDuplicateEntry(pEPOptions.getPepName(), pepName, PepOptions.class);
boolean duplicateflag = false;
if (!duplicateData.isEmpty()) {
- PEPOptions data = (PEPOptions) duplicateData.get(0);
- if (request.getParameter(operation) != null
- && "update".equals(request.getParameter(operation))) {
+ PepOptions data = (PepOptions) duplicateData.get(0);
+ if (request.getParameter(operation) != null && "update".equals(request.getParameter(operation))) {
pEPOptions.setId(data.getId());
} else if ((request.getParameter(operation) != null
&& !"update".equals(request.getParameter(operation)))
- || (request.getParameter(operation) == null
- && (data.getId() != pEPOptions.getId()))) {
+ || (request.getParameter(operation) == null && (data.getId() != pEPOptions.getId()))) {
duplicateflag = true;
}
}
@@ -369,8 +377,7 @@ public class ClosedLoopDictionaryController {
pEPOptions.setModifiedDate(new Date());
commonClassDao.update(pEPOptions);
}
- responseString =
- mapper.writeValueAsString(commonClassDao.getData(PEPOptions.class));
+ responseString = mapper.writeValueAsString(commonClassDao.getData(PepOptions.class));
} else {
responseString = duplicateResponseString;
}
@@ -387,15 +394,13 @@ public class ClosedLoopDictionaryController {
}
@RequestMapping(value = {"/cl_dictionary/remove_pepOptions"}, method = {RequestMethod.POST})
- public void removePEPOptions(HttpServletRequest request, HttpServletResponse response)
- throws IOException {
+ public void removePEPOptions(HttpServletRequest request, HttpServletResponse response) throws IOException {
DictionaryUtils utils = getDictionaryUtilsInstance();
- utils.removeData(request, response, pepOptionDatas, VNFType.class);
+ utils.removeData(request, response, pepOptionDatas, VnfType.class);
}
@RequestMapping(value = {"/cl_dictionary/save_service"}, method = {RequestMethod.POST})
- public ModelAndView saveServiceType(HttpServletRequest request, HttpServletResponse response)
- throws IOException {
+ public ModelAndView saveServiceType(HttpServletRequest request, HttpServletResponse response) throws IOException {
DictionaryUtils utils = getDictionaryUtilsInstance();
try {
boolean fromAPI = utils.isRequestFromAPI(request);
@@ -405,29 +410,25 @@ public class ClosedLoopDictionaryController {
ClosedLoopD2Services serviceData;
String userId = null;
if (fromAPI) {
- serviceData = mapper.readValue(root.get(dictionaryFields).toString(),
- ClosedLoopD2Services.class);
+ serviceData = mapper.readValue(root.get(dictionaryFields).toString(), ClosedLoopD2Services.class);
userId = "API";
} else {
- serviceData =
- mapper.readValue(root.get("closedLoopServiceDictionaryData").toString(),
- ClosedLoopD2Services.class);
+ serviceData = mapper.readValue(root.get("closedLoopServiceDictionaryData").toString(),
+ ClosedLoopD2Services.class);
userId = root.get(userid).textValue();
}
UserInfo userInfo = utils.getUserInfo(userId);
- List<Object> duplicateData = commonClassDao.checkDuplicateEntry(
- serviceData.getServiceName(), serviceName, ClosedLoopD2Services.class);
+ List<Object> duplicateData = commonClassDao.checkDuplicateEntry(serviceData.getServiceName(), serviceName,
+ ClosedLoopD2Services.class);
boolean duplicateflag = false;
if (!duplicateData.isEmpty()) {
ClosedLoopD2Services data = (ClosedLoopD2Services) duplicateData.get(0);
- if (request.getParameter(operation) != null
- && "update".equals(request.getParameter(operation))) {
+ if (request.getParameter(operation) != null && "update".equals(request.getParameter(operation))) {
serviceData.setId(data.getId());
} else if ((request.getParameter(operation) != null
&& !"update".equals(request.getParameter(operation)))
- || (request.getParameter(operation) == null
- && (data.getId() != serviceData.getId()))) {
+ || (request.getParameter(operation) == null && (data.getId() != serviceData.getId()))) {
duplicateflag = true;
}
}
@@ -441,8 +442,7 @@ public class ClosedLoopDictionaryController {
serviceData.setModifiedDate(new Date());
commonClassDao.update(serviceData);
}
- responseString = mapper
- .writeValueAsString(commonClassDao.getData(ClosedLoopD2Services.class));
+ responseString = mapper.writeValueAsString(commonClassDao.getData(ClosedLoopD2Services.class));
} else {
responseString = duplicateResponseString;
}
@@ -458,15 +458,13 @@ public class ClosedLoopDictionaryController {
}
@RequestMapping(value = {"/cl_dictionary/remove_Service"}, method = {RequestMethod.POST})
- public void removeServiceType(HttpServletRequest request, HttpServletResponse response)
- throws IOException {
+ public void removeServiceType(HttpServletRequest request, HttpServletResponse response) throws IOException {
DictionaryUtils utils = getDictionaryUtilsInstance();
- utils.removeData(request, response, closedLoopDatas, VNFType.class);
+ utils.removeData(request, response, closedLoopDatas, VnfType.class);
}
@RequestMapping(value = {"/cl_dictionary/save_siteName"}, method = {RequestMethod.POST})
- public ModelAndView saveSiteType(HttpServletRequest request, HttpServletResponse response)
- throws IOException {
+ public ModelAndView saveSiteType(HttpServletRequest request, HttpServletResponse response) throws IOException {
DictionaryUtils utils = getDictionaryUtilsInstance();
try {
boolean fromAPI = utils.isRequestFromAPI(request);
@@ -476,28 +474,24 @@ public class ClosedLoopDictionaryController {
ClosedLoopSite siteData;
String userId = null;
if (fromAPI) {
- siteData = mapper.readValue(root.get(dictionaryFields).toString(),
- ClosedLoopSite.class);
+ siteData = mapper.readValue(root.get(dictionaryFields).toString(), ClosedLoopSite.class);
userId = "API";
} else {
- siteData = mapper.readValue(root.get("closedLoopSiteDictionaryData").toString(),
- ClosedLoopSite.class);
+ siteData = mapper.readValue(root.get("closedLoopSiteDictionaryData").toString(), ClosedLoopSite.class);
userId = root.get(userid).textValue();
}
UserInfo userInfo = utils.getUserInfo(userId);
- List<Object> duplicateData = commonClassDao.checkDuplicateEntry(siteData.getSiteName(),
- siteName, ClosedLoopSite.class);
+ List<Object> duplicateData =
+ commonClassDao.checkDuplicateEntry(siteData.getSiteName(), siteName, ClosedLoopSite.class);
boolean duplicateflag = false;
if (!duplicateData.isEmpty()) {
ClosedLoopSite data = (ClosedLoopSite) duplicateData.get(0);
- if (request.getParameter(operation) != null
- && "update".equals(request.getParameter(operation))) {
+ if (request.getParameter(operation) != null && "update".equals(request.getParameter(operation))) {
siteData.setId(data.getId());
} else if ((request.getParameter(operation) != null
&& !"update".equals(request.getParameter(operation)))
- || (request.getParameter(operation) == null
- && (data.getId() != siteData.getId()))) {
+ || (request.getParameter(operation) == null && (data.getId() != siteData.getId()))) {
duplicateflag = true;
}
}
@@ -511,8 +505,7 @@ public class ClosedLoopDictionaryController {
siteData.setModifiedDate(new Date());
commonClassDao.update(siteData);
}
- responseString =
- mapper.writeValueAsString(commonClassDao.getData(ClosedLoopSite.class));
+ responseString = mapper.writeValueAsString(commonClassDao.getData(ClosedLoopSite.class));
} else {
responseString = duplicateResponseString;
}
@@ -528,15 +521,13 @@ public class ClosedLoopDictionaryController {
}
@RequestMapping(value = {"/cl_dictionary/remove_site"}, method = {RequestMethod.POST})
- public void removeSiteType(HttpServletRequest request, HttpServletResponse response)
- throws IOException {
+ public void removeSiteType(HttpServletRequest request, HttpServletResponse response) throws IOException {
DictionaryUtils utils = getDictionaryUtilsInstance();
- utils.removeData(request, response, closedLoopSiteDatas, VNFType.class);
+ utils.removeData(request, response, closedLoopSiteDatas, VnfType.class);
}
@RequestMapping(value = {"/cl_dictionary/save_varbind"}, method = {RequestMethod.POST})
- public ModelAndView saveVarbind(HttpServletRequest request, HttpServletResponse response)
- throws IOException {
+ public ModelAndView saveVarbind(HttpServletRequest request, HttpServletResponse response) throws IOException {
DictionaryUtils utils = getDictionaryUtilsInstance();
try {
boolean fromAPI = utils.isRequestFromAPI(request);
@@ -546,28 +537,25 @@ public class ClosedLoopDictionaryController {
VarbindDictionary varbindDictionary;
String userId = null;
if (fromAPI) {
- varbindDictionary = mapper.readValue(root.get(dictionaryFields).toString(),
- VarbindDictionary.class);
+ varbindDictionary = mapper.readValue(root.get(dictionaryFields).toString(), VarbindDictionary.class);
userId = "API";
} else {
- varbindDictionary = mapper.readValue(root.get("varbindDictionaryData").toString(),
- VarbindDictionary.class);
+ varbindDictionary =
+ mapper.readValue(root.get("varbindDictionaryData").toString(), VarbindDictionary.class);
userId = root.get(userid).textValue();
}
UserInfo userInfo = utils.getUserInfo(userId);
- List<Object> duplicateData = commonClassDao.checkDuplicateEntry(
- varbindDictionary.getVarbindName(), varbindName, VarbindDictionary.class);
+ List<Object> duplicateData = commonClassDao.checkDuplicateEntry(varbindDictionary.getVarbindName(),
+ varbindName, VarbindDictionary.class);
boolean duplicateflag = false;
if (!duplicateData.isEmpty()) {
VarbindDictionary data = (VarbindDictionary) duplicateData.get(0);
- if (request.getParameter(operation) != null
- && "update".equals(request.getParameter(operation))) {
+ if (request.getParameter(operation) != null && "update".equals(request.getParameter(operation))) {
varbindDictionary.setId(data.getId());
} else if ((request.getParameter(operation) != null
&& !"update".equals(request.getParameter(operation)))
- || (request.getParameter(operation) == null
- && (data.getId() != varbindDictionary.getId()))) {
+ || (request.getParameter(operation) == null && (data.getId() != varbindDictionary.getId()))) {
duplicateflag = true;
}
}
@@ -582,8 +570,7 @@ public class ClosedLoopDictionaryController {
varbindDictionary.setModifiedDate(new Date());
commonClassDao.update(varbindDictionary);
}
- responseString =
- mapper.writeValueAsString(commonClassDao.getData(VarbindDictionary.class));
+ responseString = mapper.writeValueAsString(commonClassDao.getData(VarbindDictionary.class));
} else {
responseString = duplicateResponseString;
}
@@ -599,9 +586,8 @@ public class ClosedLoopDictionaryController {
}
@RequestMapping(value = {"/cl_dictionary/remove_varbindDict"}, method = {RequestMethod.POST})
- public void removeVarbind(HttpServletRequest request, HttpServletResponse response)
- throws IOException {
+ public void removeVarbind(HttpServletRequest request, HttpServletResponse response) throws IOException {
DictionaryUtils utils = getDictionaryUtilsInstance();
- utils.removeData(request, response, varbindDatas, VNFType.class);
+ utils.removeData(request, response, varbindDatas, VnfType.class);
}
}
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
index c89d21e91..4b6492baa 100644
--- 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
@@ -23,12 +23,15 @@ package org.onap.policy.pap.xacml.rest.controller;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
+
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
+
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
+
import org.onap.policy.pap.xacml.rest.util.DictionaryUtils;
import org.onap.policy.rest.dao.CommonClassDao;
import org.onap.policy.rest.jpa.DecisionSettings;
@@ -66,16 +69,18 @@ public class DecisionPolicyDictionaryController {
return DictionaryUtils.getDictionaryUtils();
}
- @RequestMapping(value = {"/get_SettingsDictionaryDataByName"}, method = {RequestMethod.GET},
+ @RequestMapping(
+ value = {"/get_SettingsDictionaryDataByName"},
+ method = {RequestMethod.GET},
produces = MediaType.APPLICATION_JSON_VALUE)
- public void getSettingsDictionaryByNameEntityData(HttpServletRequest request,
- HttpServletResponse response) {
+ public void getSettingsDictionaryByNameEntityData(HttpServletRequest request, HttpServletResponse response) {
DictionaryUtils utils = getDictionaryUtilsInstance();
utils.getDataByEntity(response, settingDatas, xacmlId, DecisionSettings.class);
}
-
- @RequestMapping(value = {"/get_SettingsDictionaryData"}, method = {RequestMethod.GET},
+ @RequestMapping(
+ value = {"/get_SettingsDictionaryData"},
+ method = {RequestMethod.GET},
produces = MediaType.APPLICATION_JSON_VALUE)
public void getSettingsDictionaryEntityData(HttpServletResponse response) {
DictionaryUtils utils = getDictionaryUtilsInstance();
@@ -83,8 +88,8 @@ public class DecisionPolicyDictionaryController {
}
@RequestMapping(value = {"/decision_dictionary/save_Settings"}, method = {RequestMethod.POST})
- public ModelAndView saveSettingsDictionary(HttpServletRequest request,
- HttpServletResponse response) throws IOException {
+ public ModelAndView saveSettingsDictionary(HttpServletRequest request, HttpServletResponse response)
+ throws IOException {
DictionaryUtils utils = getDictionaryUtilsInstance();
try {
boolean fromAPI = utils.isRequestFromAPI(request);
@@ -95,27 +100,24 @@ public class DecisionPolicyDictionaryController {
String userId = null;
if (fromAPI) {
- decisionSettings = mapper.readValue(root.get(dictionaryFields).toString(),
- DecisionSettings.class);
+ decisionSettings = mapper.readValue(root.get(dictionaryFields).toString(), DecisionSettings.class);
userId = "API";
} else {
- decisionSettings = mapper.readValue(root.get("settingsDictionaryData").toString(),
- DecisionSettings.class);
+ decisionSettings =
+ mapper.readValue(root.get("settingsDictionaryData").toString(), DecisionSettings.class);
userId = root.get("userid").textValue();
}
UserInfo userInfo = utils.getUserInfo(userId);
- List<Object> duplicateData = commonClassDao.checkDuplicateEntry(
- decisionSettings.getXacmlId(), xacmlId, DecisionSettings.class);
+ List<Object> duplicateData =
+ commonClassDao.checkDuplicateEntry(decisionSettings.getXacmlId(), xacmlId, DecisionSettings.class);
boolean duplicateflag = false;
if (!duplicateData.isEmpty()) {
DecisionSettings data = (DecisionSettings) duplicateData.get(0);
- if (request.getParameter(operation) != null
- && "update".equals(request.getParameter(operation))) {
+ if (request.getParameter(operation) != null && "update".equals(request.getParameter(operation))) {
decisionSettings.setId(data.getId());
} else if ((request.getParameter(operation) != null
&& !"update".equals(request.getParameter(operation)))
- || (request.getParameter(operation) == null
- && (data.getId() != decisionSettings.getId()))) {
+ || (request.getParameter(operation) == null && (data.getId() != decisionSettings.getId()))) {
duplicateflag = true;
}
}
@@ -133,8 +135,7 @@ public class DecisionPolicyDictionaryController {
decisionSettings.setModifiedDate(new Date());
commonClassDao.update(decisionSettings);
}
- responseString =
- mapper.writeValueAsString(commonClassDao.getData(DecisionSettings.class));
+ responseString = mapper.writeValueAsString(commonClassDao.getData(DecisionSettings.class));
} else {
responseString = duplicateResponseString;
}
@@ -150,21 +151,23 @@ public class DecisionPolicyDictionaryController {
}
@RequestMapping(value = {"/settings_dictionary/remove_settings"}, method = {RequestMethod.POST})
- public void removeSettingsDictionary(HttpServletRequest request, HttpServletResponse response)
- throws IOException {
+ public void removeSettingsDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException {
DictionaryUtils utils = getDictionaryUtilsInstance();
utils.removeData(request, response, settingDatas, DecisionSettings.class);
}
- @RequestMapping(value = {"/get_RainyDayDictionaryDataByName"}, method = {RequestMethod.GET},
+ @RequestMapping(
+ value = {"/get_RainyDayDictionaryDataByName"},
+ method = {RequestMethod.GET},
produces = MediaType.APPLICATION_JSON_VALUE)
- public void getRainyDayDictionaryByNameEntityData(HttpServletRequest request,
- HttpServletResponse response) {
+ public void getRainyDayDictionaryByNameEntityData(HttpServletRequest request, HttpServletResponse response) {
DictionaryUtils utils = getDictionaryUtilsInstance();
utils.getDataByEntity(response, rainDayDatas, bbID, RainyDayTreatments.class);
}
- @RequestMapping(value = {"/get_RainyDayDictionaryData"}, method = {RequestMethod.GET},
+ @RequestMapping(
+ value = {"/get_RainyDayDictionaryData"},
+ method = {RequestMethod.GET},
produces = MediaType.APPLICATION_JSON_VALUE)
public void getRainyDayDictionaryEntityData(HttpServletResponse response) {
DictionaryUtils utils = getDictionaryUtilsInstance();
@@ -172,8 +175,8 @@ public class DecisionPolicyDictionaryController {
}
@RequestMapping(value = {"/decision_dictionary/save_RainyDay"}, method = {RequestMethod.POST})
- public ModelAndView saveRainyDayDictionary(HttpServletRequest request,
- HttpServletResponse response) throws IOException {
+ public ModelAndView saveRainyDayDictionary(HttpServletRequest request, HttpServletResponse response)
+ throws IOException {
DictionaryUtils utils = getDictionaryUtilsInstance();
try {
boolean fromAPI = utils.isRequestFromAPI(request);
@@ -183,32 +186,26 @@ public class DecisionPolicyDictionaryController {
RainyDayTreatments decisionRainyDay;
TreatmentValues treatmentsData = null;
if (fromAPI) {
- decisionRainyDay = mapper.readValue(root.get(dictionaryFields).toString(),
- RainyDayTreatments.class);
- treatmentsData = mapper.readValue(root.get(dictionaryFields).toString(),
- TreatmentValues.class);
+ decisionRainyDay = mapper.readValue(root.get(dictionaryFields).toString(), RainyDayTreatments.class);
+ treatmentsData = mapper.readValue(root.get(dictionaryFields).toString(), TreatmentValues.class);
} else {
- decisionRainyDay = mapper.readValue(root.get("rainyDayDictionaryData").toString(),
- RainyDayTreatments.class);
- treatmentsData = mapper.readValue(root.get("rainyDayDictionaryData").toString(),
- TreatmentValues.class);
+ decisionRainyDay =
+ mapper.readValue(root.get("rainyDayDictionaryData").toString(), RainyDayTreatments.class);
+ treatmentsData = mapper.readValue(root.get("rainyDayDictionaryData").toString(), TreatmentValues.class);
}
- decisionRainyDay.setTreatments(
- utils.appendKey(treatmentsData.getUserDataTypeValues(), "treatment", ","));
+ decisionRainyDay.setTreatments(utils.appendKey(treatmentsData.getUserDataTypeValues(), "treatment", ","));
List<Object> duplicateData = commonClassDao.checkDuplicateEntry(
- decisionRainyDay.getBbid() + ":" + decisionRainyDay.getWorkstep(),
- "bbid:workstep", RainyDayTreatments.class);
+ decisionRainyDay.getBbid() + ":" + decisionRainyDay.getWorkstep(), "bbid:workstep",
+ RainyDayTreatments.class);
boolean duplicateflag = false;
if (!duplicateData.isEmpty()) {
RainyDayTreatments data = (RainyDayTreatments) duplicateData.get(0);
- if (request.getParameter(operation) != null
- && "update".equals(request.getParameter(operation))) {
+ if (request.getParameter(operation) != null && "update".equals(request.getParameter(operation))) {
decisionRainyDay.setId(data.getId());
} else if ((request.getParameter(operation) != null
&& !"update".equals(request.getParameter(operation)))
- || (request.getParameter(operation) == null
- && (data.getId() != decisionRainyDay.getId()))) {
+ || (request.getParameter(operation) == null && (data.getId() != decisionRainyDay.getId()))) {
duplicateflag = true;
}
}
@@ -219,8 +216,7 @@ public class DecisionPolicyDictionaryController {
} else {
commonClassDao.update(decisionRainyDay);
}
- responseString =
- mapper.writeValueAsString(commonClassDao.getData(RainyDayTreatments.class));
+ responseString = mapper.writeValueAsString(commonClassDao.getData(RainyDayTreatments.class));
} else {
responseString = duplicateResponseString;
}
@@ -236,8 +232,7 @@ public class DecisionPolicyDictionaryController {
}
@RequestMapping(value = {"/decision_dictionary/remove_rainyDay"}, method = {RequestMethod.POST})
- public void removeRainyDayDictionary(HttpServletRequest request, HttpServletResponse response)
- throws IOException {
+ public void removeRainyDayDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException {
DictionaryUtils utils = getDictionaryUtilsInstance();
utils.removeData(request, response, rainDayDatas, RainyDayTreatments.class);
}
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
index 51c8a1d91..1645b0af9 100644
--- 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
@@ -23,11 +23,14 @@ package org.onap.policy.pap.xacml.rest.controller;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
+
import java.io.IOException;
import java.util.Date;
import java.util.List;
+
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
+
import org.onap.policy.pap.xacml.rest.adapters.GridData;
import org.onap.policy.pap.xacml.rest.util.DictionaryUtils;
import org.onap.policy.rest.dao.CommonClassDao;
@@ -65,24 +68,27 @@ public class DescriptiveDictionaryController {
return DictionaryUtils.getDictionaryUtils();
}
- @RequestMapping(value = {"/get_DescriptiveScopeByName"}, method = {RequestMethod.GET},
+ @RequestMapping(
+ value = {"/get_DescriptiveScopeByName"},
+ method = {RequestMethod.GET},
produces = MediaType.APPLICATION_JSON_VALUE)
public void getDescriptiveDictionaryByNameEntityData(HttpServletResponse response) {
DictionaryUtils utils = getDictionaryUtilsInstance();
utils.getDataByEntity(response, descriptiveDatas, dScopeName, DescriptiveScope.class);
}
- @RequestMapping(value = {"/get_DescriptiveScope"}, method = {RequestMethod.GET},
+ @RequestMapping(
+ value = {"/get_DescriptiveScope"},
+ method = {RequestMethod.GET},
produces = MediaType.APPLICATION_JSON_VALUE)
public void getDescriptiveDictionaryEntityData(HttpServletResponse response) {
DictionaryUtils utils = getDictionaryUtilsInstance();
utils.getData(response, descriptiveDatas, DescriptiveScope.class);
}
- @RequestMapping(value = {"/descriptive_dictionary/save_descriptive"},
- method = {RequestMethod.POST})
- public ModelAndView saveDescriptiveDictionary(HttpServletRequest request,
- HttpServletResponse response) throws IOException {
+ @RequestMapping(value = {"/descriptive_dictionary/save_descriptive"}, method = {RequestMethod.POST})
+ public ModelAndView saveDescriptiveDictionary(HttpServletRequest request, HttpServletResponse response)
+ throws IOException {
DictionaryUtils utils = getDictionaryUtilsInstance();
try {
boolean fromAPI = utils.isRequestFromAPI(request);
@@ -93,32 +99,27 @@ public class DescriptiveDictionaryController {
GridData data;
String userId = null;
if (fromAPI) {
- descriptiveScope = mapper.readValue(root.get("dictionaryFields").toString(),
- DescriptiveScope.class);
+ descriptiveScope = mapper.readValue(root.get("dictionaryFields").toString(), DescriptiveScope.class);
data = mapper.readValue(root.get("dictionaryFields").toString(), GridData.class);
userId = "API";
} else {
descriptiveScope =
- mapper.readValue(root.get("descriptiveScopeDictionaryData").toString(),
- DescriptiveScope.class);
- data = mapper.readValue(root.get("descriptiveScopeDictionaryData").toString(),
- GridData.class);
+ mapper.readValue(root.get("descriptiveScopeDictionaryData").toString(), DescriptiveScope.class);
+ data = mapper.readValue(root.get("descriptiveScopeDictionaryData").toString(), GridData.class);
userId = root.get("userid").textValue();
}
descriptiveScope.setSearch(utils.appendKeyValue(data.getAttributes(), "AND", ":"));
UserInfo userInfo = utils.getUserInfo(userId);
- List<Object> duplicateData = commonClassDao.checkDuplicateEntry(
- descriptiveScope.getScopeName(), dScopeName, DescriptiveScope.class);
+ List<Object> duplicateData = commonClassDao.checkDuplicateEntry(descriptiveScope.getScopeName(), dScopeName,
+ DescriptiveScope.class);
boolean duplicateflag = false;
if (!duplicateData.isEmpty()) {
DescriptiveScope data1 = (DescriptiveScope) duplicateData.get(0);
- if (request.getParameter(operation) != null
- && "update".equals(request.getParameter(operation))) {
+ if (request.getParameter(operation) != null && "update".equals(request.getParameter(operation))) {
descriptiveScope.setId(data1.getId());
} else if ((request.getParameter(operation) != null
&& !"update".equals(request.getParameter(operation)))
- || (request.getParameter(operation) == null
- && (data1.getId() != descriptiveScope.getId()))) {
+ || (request.getParameter(operation) == null && (data1.getId() != descriptiveScope.getId()))) {
duplicateflag = true;
}
}
@@ -132,8 +133,7 @@ public class DescriptiveDictionaryController {
descriptiveScope.setModifiedDate(new Date());
commonClassDao.update(descriptiveScope);
}
- responseString =
- mapper.writeValueAsString(commonClassDao.getData(DescriptiveScope.class));
+ responseString = mapper.writeValueAsString(commonClassDao.getData(DescriptiveScope.class));
} else {
responseString = "Duplicate";
}
@@ -148,10 +148,9 @@ public class DescriptiveDictionaryController {
return null;
}
- @RequestMapping(value = {"/descriptive_dictionary/remove_descriptiveScope"},
- method = {RequestMethod.POST})
- public void removeDescriptiveDictionary(HttpServletRequest request,
- HttpServletResponse response) throws IOException {
+ @RequestMapping(value = {"/descriptive_dictionary/remove_descriptiveScope"}, method = {RequestMethod.POST})
+ public void removeDescriptiveDictionary(HttpServletRequest request, HttpServletResponse response)
+ throws IOException {
DictionaryUtils utils = getDictionaryUtilsInstance();
utils.removeData(request, response, descriptiveDatas, DescriptiveScope.class);
}
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
index 94275e7c1..2c0278ed5 100644
--- 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
@@ -23,11 +23,14 @@ package org.onap.policy.pap.xacml.rest.controller;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
+
import java.io.IOException;
import java.util.Date;
import java.util.List;
+
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
+
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.onap.policy.pap.xacml.rest.util.DictionaryUtils;
@@ -52,7 +55,7 @@ public class DictionaryController {
private static String operation = "operation";
private static String dictionaryFields = "dictionaryFields";
private static String duplicateResponseString = "Duplicate";
- private static String onapName = "onapName";
+ private static String onapName = "name";
private static String attributeDatas = "attributeDictionaryDatas";
private static String onapNameDatas = "onapNameDictionaryDatas";
@@ -69,7 +72,9 @@ public class DictionaryController {
return DictionaryUtils.getDictionaryUtils();
}
- @RequestMapping(value = {"/get_AttributeDatabyAttributeName"}, method = {RequestMethod.GET},
+ @RequestMapping(
+ value = {"/get_AttributeDatabyAttributeName"},
+ method = {RequestMethod.GET},
produces = MediaType.APPLICATION_JSON_VALUE)
public void getAttributeDictionaryEntityDatabyAttributeName(HttpServletResponse response) {
DictionaryUtils utils = getDictionaryUtilsInstance();
@@ -77,7 +82,9 @@ public class DictionaryController {
}
// Attribute Dictionary
- @RequestMapping(value = "/get_AttributeData", method = RequestMethod.GET,
+ @RequestMapping(
+ value = "/get_AttributeData",
+ method = RequestMethod.GET,
produces = MediaType.APPLICATION_JSON_VALUE)
public void getAttributeDictionaryEntityData(HttpServletResponse response) {
DictionaryUtils utils = getDictionaryUtilsInstance();
@@ -85,8 +92,8 @@ public class DictionaryController {
}
@RequestMapping(value = {"/attribute_dictionary/save_attribute"}, method = {RequestMethod.POST})
- public ModelAndView saveAttributeDictionary(HttpServletRequest request,
- HttpServletResponse response) throws IOException {
+ public ModelAndView saveAttributeDictionary(HttpServletRequest request, HttpServletResponse response)
+ throws IOException {
DictionaryUtils utils = getDictionaryUtilsInstance();
try {
boolean fromAPI = utils.isRequestFromAPI(request);
@@ -97,38 +104,33 @@ public class DictionaryController {
AttributeValues attributeValueData = null;
String userId = null;
if (fromAPI) {
- attributeData =
- mapper.readValue(root.get(dictionaryFields).toString(), Attribute.class);
- attributeValueData = mapper.readValue(root.get(dictionaryFields).toString(),
- AttributeValues.class);
+ attributeData = mapper.readValue(root.get(dictionaryFields).toString(), Attribute.class);
+ attributeValueData = mapper.readValue(root.get(dictionaryFields).toString(), AttributeValues.class);
userId = "API";
} else {
- attributeData = mapper.readValue(root.get("attributeDictionaryData").toString(),
- Attribute.class);
- attributeValueData = mapper.readValue(
- root.get("attributeDictionaryData").toString(), AttributeValues.class);
+ attributeData = mapper.readValue(root.get("attributeDictionaryData").toString(), Attribute.class);
+ attributeValueData =
+ mapper.readValue(root.get("attributeDictionaryData").toString(), AttributeValues.class);
userId = root.get("userid").textValue();
}
UserInfo userInfo = utils.getUserInfo(userId);
- List<Object> duplicateData = commonClassDao
- .checkDuplicateEntry(attributeData.getXacmlId(), xacmlId, Attribute.class);
+ List<Object> duplicateData =
+ commonClassDao.checkDuplicateEntry(attributeData.getXacmlId(), xacmlId, Attribute.class);
boolean duplicateflag = false;
if (!duplicateData.isEmpty()) {
Attribute data = (Attribute) duplicateData.get(0);
- if (request.getParameter(operation) != null
- && "update".equals(request.getParameter(operation))) {
+ if (request.getParameter(operation) != null && "update".equals(request.getParameter(operation))) {
attributeData.setId(data.getId());
} else if ((request.getParameter(operation) != null
&& !"update".equals(request.getParameter(operation)))
- || (request.getParameter(operation) == null
- && (data.getId() != attributeData.getId()))) {
+ || (request.getParameter(operation) == null && (data.getId() != attributeData.getId()))) {
duplicateflag = true;
}
}
if (attributeValueData.getUserDataTypeValues() != null
&& !attributeValueData.getUserDataTypeValues().isEmpty()) {
- attributeData.setAttributeValue(utils.appendKey(
- attributeValueData.getUserDataTypeValues(), "attributeValues", ","));
+ attributeData.setAttributeValue(
+ utils.appendKey(attributeValueData.getUserDataTypeValues(), "attributeValues", ","));
}
if (attributeData.getDatatypeBean().getShortName() != null) {
@@ -162,16 +164,16 @@ public class DictionaryController {
return null;
}
- @RequestMapping(value = {"/attribute_dictionary/remove_attribute"},
- method = {RequestMethod.POST})
- public void removeAttributeDictionary(HttpServletRequest request, HttpServletResponse response)
- throws IOException {
+ @RequestMapping(value = {"/attribute_dictionary/remove_attribute"}, method = {RequestMethod.POST})
+ public void removeAttributeDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException {
DictionaryUtils utils = getDictionaryUtilsInstance();
utils.removeData(request, response, attributeDatas, Attribute.class);
}
// OnapName Dictionary
- @RequestMapping(value = {"/get_OnapNameDataByName"}, method = {RequestMethod.GET},
+ @RequestMapping(
+ value = {"/get_OnapNameDataByName"},
+ method = {RequestMethod.GET},
produces = MediaType.APPLICATION_JSON_VALUE)
public void getOnapNameDictionaryByNameEntityData(HttpServletResponse response) {
LOGGER.info("get_OnapNameDataByName is called");
@@ -179,7 +181,9 @@ public class DictionaryController {
utils.getDataByEntity(response, onapNameDatas, onapName, OnapName.class);
}
- @RequestMapping(value = {"/get_OnapNameData"}, method = {RequestMethod.GET},
+ @RequestMapping(
+ value = {"/get_OnapNameData"},
+ method = {RequestMethod.GET},
produces = MediaType.APPLICATION_JSON_VALUE)
public void getOnapNameDictionaryEntityData(HttpServletResponse response) {
DictionaryUtils utils = getDictionaryUtilsInstance();
@@ -201,24 +205,21 @@ public class DictionaryController {
onapData = mapper.readValue(root.get(dictionaryFields).toString(), OnapName.class);
userId = "API";
} else {
- onapData = mapper.readValue(root.get("onapNameDictionaryData").toString(),
- OnapName.class);
+ onapData = mapper.readValue(root.get("onapNameDictionaryData").toString(), OnapName.class);
userId = root.get("userid").textValue();
}
UserInfo userInfo = utils.getUserInfo(userId);
- List<Object> duplicateData = commonClassDao.checkDuplicateEntry(onapData.getOnapName(),
- onapName, OnapName.class);
+ List<Object> duplicateData =
+ commonClassDao.checkDuplicateEntry(onapData.getName(), onapName, OnapName.class);
boolean duplicateflag = false;
if (!duplicateData.isEmpty()) {
OnapName data = (OnapName) duplicateData.get(0);
- if (request.getParameter(operation) != null
- && "update".equals(request.getParameter(operation))) {
+ if (request.getParameter(operation) != null && "update".equals(request.getParameter(operation))) {
onapData.setId(data.getId());
} else if ((request.getParameter(operation) != null
&& !"update".equals(request.getParameter(operation)))
- || (request.getParameter(operation) == null
- && (data.getId() != onapData.getId()))) {
+ || (request.getParameter(operation) == null && (data.getId() != onapData.getId()))) {
duplicateflag = true;
}
}
@@ -248,8 +249,7 @@ public class DictionaryController {
}
@RequestMapping(value = {"/onap_dictionary/remove_onap"}, method = {RequestMethod.POST})
- public void removeOnapDictionary(HttpServletRequest request, HttpServletResponse response)
- throws IOException {
+ public void removeOnapDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException {
DictionaryUtils utils = getDictionaryUtilsInstance();
utils.removeData(request, response, onapNameDatas, OnapName.class);
}
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
index b42731d61..029582213 100644
--- 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
@@ -21,16 +21,20 @@
package org.onap.policy.pap.xacml.rest.controller;
import au.com.bytecode.opencsv.CSVReader;
+
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
+
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
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.common.logging.flexlogger.FlexLogger;
import org.onap.policy.common.logging.flexlogger.Logger;
@@ -40,9 +44,9 @@ 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.BRMSController;
-import org.onap.policy.rest.jpa.BRMSDependency;
-import org.onap.policy.rest.jpa.BRMSParamTemplate;
+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.Category;
import org.onap.policy.rest.jpa.ClosedLoopD2Services;
import org.onap.policy.rest.jpa.ClosedLoopSite;
@@ -52,15 +56,15 @@ import org.onap.policy.rest.jpa.DescriptiveScope;
import org.onap.policy.rest.jpa.GroupServiceList;
import org.onap.policy.rest.jpa.MicroServiceModels;
import org.onap.policy.rest.jpa.OnapName;
-import org.onap.policy.rest.jpa.PEPOptions;
+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.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;
@@ -68,7 +72,6 @@ import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
-
@Controller
public class DictionaryImportController {
private static final Logger LOGGER = FlexLogger.getLogger(DictionaryImportController.class);
@@ -92,8 +95,7 @@ public class DictionaryImportController {
}
@RequestMapping(value = {"/dictionary/import_dictionary"}, method = {RequestMethod.POST})
- public void importDictionaryData(HttpServletRequest request, HttpServletResponse response)
- throws IOException {
+ public void importDictionaryData(HttpServletRequest request, HttpServletResponse response) throws IOException {
ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
String userId = request.getParameter("userId");
@@ -211,7 +213,7 @@ public class DictionaryImportController {
for (int j = 0; j < rows.length; j++) {
if ("onap_name".equalsIgnoreCase(dictSheet.get(0)[j])
|| "Onap Name".equalsIgnoreCase(dictSheet.get(0)[j])) {
- attribute.setOnapName(rows[j]);
+ attribute.setName(rows[j]);
}
if (DESCRIPTION.equalsIgnoreCase(dictSheet.get(0)[j])) {
attribute.setDescription(rows[j]);
@@ -250,10 +252,10 @@ public class DictionaryImportController {
attribute.setEnumValues(rows[j]);
}
if ("Ref Attributes".equalsIgnoreCase(dictSheet.get(0)[j])) {
- attribute.setRef_attributes(rows[j]);
+ attribute.setRefAttributes(rows[j]);
}
if ("Sub Attributes".equalsIgnoreCase(dictSheet.get(0)[j])) {
- attribute.setSub_attributes(rows[j]);
+ attribute.setSubAttributes(rows[j]);
}
if ("annotations".equalsIgnoreCase(dictSheet.get(0)[j])) {
attribute.setAnnotation(rows[j]);
@@ -273,8 +275,7 @@ public class DictionaryImportController {
String[] rows = dictSheet.get(i);
for (int j = 0; j < rows.length; j++) {
if ("modelName".equalsIgnoreCase(dictSheet.get(0)[j])
- || "Optimization Service Model"
- .equalsIgnoreCase(dictSheet.get(0)[j])) {
+ || "Optimization Service Model".equalsIgnoreCase(dictSheet.get(0)[j])) {
attribute.setModelName(rows[j]);
}
if ("version".equalsIgnoreCase(dictSheet.get(0)[j])
@@ -294,10 +295,10 @@ public class DictionaryImportController {
attribute.setEnumValues(rows[j]);
}
if ("Ref Attributes".equalsIgnoreCase(dictSheet.get(0)[j])) {
- attribute.setRef_attributes(rows[j]);
+ attribute.setRefAttributes(rows[j]);
}
if ("Sub Attributes".equalsIgnoreCase(dictSheet.get(0)[j])) {
- attribute.setSub_attributes(rows[j]);
+ attribute.setSubAttributes(rows[j]);
}
if ("annotations".equalsIgnoreCase(dictSheet.get(0)[j])) {
attribute.setAnnotation(rows[j]);
@@ -310,7 +311,7 @@ public class DictionaryImportController {
if (dictionaryName.startsWith("VNFType")) {
for (int i = 1; i < dictSheet.size(); i++) {
- VNFType attribute = new VNFType();
+ VnfType attribute = new VnfType();
UserInfo userinfo = new UserInfo();
userinfo.setUserLoginId(userId);
attribute.setUserCreatedBy(userinfo);
@@ -319,7 +320,7 @@ public class DictionaryImportController {
for (int j = 0; j < rows.length; j++) {
if ("vnf_type".equalsIgnoreCase(dictSheet.get(0)[j])
|| "VNF Type".equalsIgnoreCase(dictSheet.get(0)[j])) {
- attribute.setVnftype(rows[j]);
+ attribute.setType(rows[j]);
}
if (DESCRIPTION.equalsIgnoreCase(dictSheet.get(0)[j])) {
attribute.setDescription(rows[j]);
@@ -330,7 +331,7 @@ public class DictionaryImportController {
}
if (dictionaryName.startsWith("VSCLAction")) {
for (int i = 1; i < dictSheet.size(); i++) {
- VSCLAction attribute = new VSCLAction();
+ VsclAction attribute = new VsclAction();
UserInfo userinfo = new UserInfo();
userinfo.setUserLoginId(userId);
attribute.setUserCreatedBy(userinfo);
@@ -339,7 +340,7 @@ public class DictionaryImportController {
for (int j = 0; j < rows.length; j++) {
if ("vscl_action".equalsIgnoreCase(dictSheet.get(0)[j])
|| "VSCL Action".equalsIgnoreCase(dictSheet.get(0)[j])) {
- attribute.setVsclaction(rows[j]);
+ attribute.setAction(rows[j]);
}
if (DESCRIPTION.equalsIgnoreCase(dictSheet.get(0)[j])) {
attribute.setDescription(rows[j]);
@@ -388,9 +389,9 @@ public class DictionaryImportController {
commonClassDao.save(attribute);
}
}
- if (dictionaryName.startsWith("PEPOptions")) {
+ if (dictionaryName.startsWith("PepOptions")) {
for (int i = 1; i < dictSheet.size(); i++) {
- PEPOptions attribute = new PEPOptions();
+ PepOptions attribute = new PepOptions();
UserInfo userinfo = new UserInfo();
userinfo.setUserLoginId(userId);
attribute.setUserCreatedBy(userinfo);
@@ -430,7 +431,7 @@ public class DictionaryImportController {
}
if ("varbind_oid".equalsIgnoreCase(dictSheet.get(0)[j])
|| "Varbind OID".equalsIgnoreCase(dictSheet.get(0)[j])) {
- attribute.setVarbindOID(rows[j]);
+ attribute.setVarbindOid(rows[j]);
}
}
commonClassDao.save(attribute);
@@ -438,7 +439,7 @@ public class DictionaryImportController {
}
if (dictionaryName.startsWith("BRMSParamDictionary")) {
for (int i = 1; i < dictSheet.size(); i++) {
- BRMSParamTemplate attribute = new BRMSParamTemplate();
+ BrmsParamTemplate attribute = new BrmsParamTemplate();
UserInfo userinfo = new UserInfo();
userinfo.setUserLoginId(userId);
attribute.setUserCreatedBy(userinfo);
@@ -460,7 +461,7 @@ public class DictionaryImportController {
}
if (dictionaryName.startsWith("BRMSControllerDictionary")) {
for (int i = 1; i < dictSheet.size(); i++) {
- BRMSController attribute = new BRMSController();
+ BrmsController attribute = new BrmsController();
UserInfo userinfo = new UserInfo();
userinfo.setUserLoginId(userId);
attribute.setUserCreatedBy(userinfo);
@@ -482,7 +483,7 @@ public class DictionaryImportController {
}
if (dictionaryName.startsWith("BRMSDependencyDictionary")) {
for (int i = 1; i < dictSheet.size(); i++) {
- BRMSDependency attribute = new BRMSDependency();
+ BrmsDependency attribute = new BrmsDependency();
UserInfo userinfo = new UserInfo();
userinfo.setUserLoginId(userId);
attribute.setUserCreatedBy(userinfo);
@@ -614,7 +615,7 @@ public class DictionaryImportController {
}
if ("serviceTrasProtocol".equalsIgnoreCase(dictSheet.get(0)[j])
|| "Transport Protocol".equalsIgnoreCase(dictSheet.get(0)[j])) {
- attribute.setServiceTransProtocol(rows[j]);
+ attribute.setServiceTransportProtocol(rows[j]);
}
if ("serviceAppProtocol".equalsIgnoreCase(dictSheet.get(0)[j])
|| "APP Protocol".equalsIgnoreCase(dictSheet.get(0)[j])) {
@@ -716,19 +717,19 @@ public class DictionaryImportController {
}
if ("fromZone".equalsIgnoreCase(dictSheet.get(0)[j])
|| "From Zone".equalsIgnoreCase(dictSheet.get(0)[j])) {
- attribute.setFromZones(rows[j]);
+ attribute.setFromZone(rows[j]);
}
if ("toZone".equalsIgnoreCase(dictSheet.get(0)[j])
|| "To Zone".equalsIgnoreCase(dictSheet.get(0)[j])) {
- attribute.setToZones(rows[j]);
+ attribute.setToZone(rows[j]);
}
if ("srcIPList".equalsIgnoreCase(dictSheet.get(0)[j])
|| "Source-IP-List".equalsIgnoreCase(dictSheet.get(0)[j])) {
- attribute.setSrcIPList(rows[j]);
+ attribute.setSrcIpList(rows[j]);
}
if ("destIPList".equalsIgnoreCase(dictSheet.get(0)[j])
|| "Destination-IP-List".equalsIgnoreCase(dictSheet.get(0)[j])) {
- attribute.setDestIPList(rows[j]);
+ attribute.setDestIpList(rows[j]);
}
if ("srcPortList".equalsIgnoreCase(dictSheet.get(0)[j])
|| "Source-Port-List".equalsIgnoreCase(dictSheet.get(0)[j])) {
@@ -800,7 +801,7 @@ public class DictionaryImportController {
case VSCLAction:
case ClosedLoopService:
case ClosedLoopSite:
- case PEPOptions:
+ case PepOptions:
case VarbindDictionary:
case BRMSParamDictionary:
case BRMSControllerDictionary:
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
index 7cf12043c..3c3cbac30 100644
--- 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
@@ -23,13 +23,16 @@ package org.onap.policy.pap.xacml.rest.controller;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
+
import java.io.IOException;
import java.io.PrintWriter;
import java.net.UnknownHostException;
import java.util.Date;
import java.util.List;
+
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;
@@ -39,8 +42,8 @@ import org.onap.policy.pap.xacml.rest.util.DictionaryUtils;
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.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.PortList;
@@ -58,7 +61,6 @@ import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
-
@Controller
public class FirewallDictionaryController {
@@ -95,7 +97,6 @@ public class FirewallDictionaryController {
private static String fwTagPickerDatas = "fwTagPickerDictionaryDatas";
private static String fwTagDatas = "fwTagDictionaryDatas";
-
@Autowired
public FirewallDictionaryController(CommonClassDao commonClassDao) {
FirewallDictionaryController.commonClassDao = commonClassDao;
@@ -113,14 +114,18 @@ public class FirewallDictionaryController {
return DictionaryUtils.getDictionaryUtils();
}
- @RequestMapping(value = {"/get_PrefixListDataByName"}, method = {RequestMethod.GET},
+ @RequestMapping(
+ value = {"/get_PrefixListDataByName"},
+ method = {RequestMethod.GET},
produces = MediaType.APPLICATION_JSON_VALUE)
public void getPrefixListDictionaryEntityDataByName(HttpServletResponse response) {
DictionaryUtils utils = getDictionaryUtilsInstance();
utils.getDataByEntity(response, pfListDatas, prefixListName, PrefixList.class);
}
- @RequestMapping(value = {"/get_PrefixListData"}, method = {RequestMethod.GET},
+ @RequestMapping(
+ value = {"/get_PrefixListData"},
+ method = {RequestMethod.GET},
produces = MediaType.APPLICATION_JSON_VALUE)
public void getPrefixListDictionaryEntityData(HttpServletResponse response) {
DictionaryUtils utils = getDictionaryUtilsInstance();
@@ -128,8 +133,8 @@ public class FirewallDictionaryController {
}
@RequestMapping(value = {"/fw_dictionary/save_prefixList"}, method = {RequestMethod.POST})
- public ModelAndView savePrefixListDictionary(HttpServletRequest request,
- HttpServletResponse response) throws IOException {
+ public ModelAndView savePrefixListDictionary(HttpServletRequest request, HttpServletResponse response)
+ throws IOException {
DictionaryUtils utils = getDictionaryUtilsInstance();
try {
boolean fromAPI = utils.isRequestFromAPI(request);
@@ -138,25 +143,21 @@ public class FirewallDictionaryController {
JsonNode root = mapper.readTree(request.getReader());
PrefixList prefixList;
if (fromAPI) {
- prefixList =
- mapper.readValue(root.get(dictionaryFields).toString(), PrefixList.class);
+ prefixList = mapper.readValue(root.get(dictionaryFields).toString(), PrefixList.class);
} else {
- prefixList = mapper.readValue(root.get("prefixListDictionaryData").toString(),
- PrefixList.class);
+ prefixList = mapper.readValue(root.get("prefixListDictionaryData").toString(), PrefixList.class);
}
- List<Object> duplicateData = commonClassDao.checkDuplicateEntry(
- prefixList.getPrefixListName(), prefixListName, PrefixList.class);
+ List<Object> duplicateData = commonClassDao.checkDuplicateEntry(prefixList.getPrefixListName(),
+ prefixListName, PrefixList.class);
boolean duplicateflag = false;
if (!duplicateData.isEmpty()) {
PrefixList data = (PrefixList) duplicateData.get(0);
- if (request.getParameter(operation) != null
- && "update".equals(request.getParameter(operation))) {
+ if (request.getParameter(operation) != null && "update".equals(request.getParameter(operation))) {
prefixList.setId(data.getId());
} else if ((request.getParameter(operation) != null
&& !"update".equals(request.getParameter(operation)))
- || (request.getParameter(operation) == null
- && (data.getId() != prefixList.getId()))) {
+ || (request.getParameter(operation) == null && (data.getId() != prefixList.getId()))) {
duplicateflag = true;
}
}
@@ -167,8 +168,7 @@ public class FirewallDictionaryController {
} else {
commonClassDao.update(prefixList);
}
- responseString =
- mapper.writeValueAsString(commonClassDao.getData(PrefixList.class));
+ responseString = mapper.writeValueAsString(commonClassDao.getData(PrefixList.class));
} else {
responseString = duplicateResponseString;
}
@@ -191,15 +191,14 @@ public class FirewallDictionaryController {
}
@RequestMapping(value = {"/fw_dictionary/validate_prefixList"}, method = {RequestMethod.POST})
- public void validatePrefixListDictionary(HttpServletRequest request,
- HttpServletResponse response) throws IOException {
+ public void validatePrefixListDictionary(HttpServletRequest request, HttpServletResponse response)
+ throws IOException {
DictionaryUtils utils = getDictionaryUtilsInstance();
try {
ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
JsonNode root = mapper.readTree(request.getReader());
- PrefixList prefixList = mapper
- .readValue(root.get("prefixListDictionaryData").toString(), PrefixList.class);
+ PrefixList prefixList = mapper.readValue(root.get("prefixListDictionaryData").toString(), PrefixList.class);
String responseValidation = successMessage;
try {
CIDR.newCIDR(prefixList.getPrefixListValue());
@@ -219,7 +218,9 @@ public class FirewallDictionaryController {
}
}
- @RequestMapping(value = {"/get_PortListData"}, method = {RequestMethod.GET},
+ @RequestMapping(
+ value = {"/get_PortListData"},
+ method = {RequestMethod.GET},
produces = MediaType.APPLICATION_JSON_VALUE)
public void getPortListDictionaryEntityData(HttpServletResponse response) {
DictionaryUtils utils = getDictionaryUtilsInstance();
@@ -227,8 +228,8 @@ public class FirewallDictionaryController {
}
@RequestMapping(value = {"/fw_dictionary/save_portName"}, method = {RequestMethod.POST})
- public ModelAndView savePortListDictionary(HttpServletRequest request,
- HttpServletResponse response) throws IOException {
+ public ModelAndView savePortListDictionary(HttpServletRequest request, HttpServletResponse response)
+ throws IOException {
DictionaryUtils utils = getDictionaryUtilsInstance();
try {
boolean fromAPI = utils.isRequestFromAPI(request);
@@ -239,21 +240,18 @@ public class FirewallDictionaryController {
if (fromAPI) {
portList = mapper.readValue(root.get(dictionaryFields).toString(), PortList.class);
} else {
- portList = mapper.readValue(root.get("portListDictionaryData").toString(),
- PortList.class);
+ portList = mapper.readValue(root.get("portListDictionaryData").toString(), PortList.class);
}
- List<Object> duplicateData = commonClassDao.checkDuplicateEntry(portList.getPortName(),
- "portName", PortList.class);
+ List<Object> duplicateData =
+ commonClassDao.checkDuplicateEntry(portList.getPortName(), "portName", PortList.class);
boolean duplicateflag = false;
if (!duplicateData.isEmpty()) {
PortList data = (PortList) duplicateData.get(0);
- if (request.getParameter(operation) != null
- && "update".equals(request.getParameter(operation))) {
+ if (request.getParameter(operation) != null && "update".equals(request.getParameter(operation))) {
portList.setId(data.getId());
} else if ((request.getParameter(operation) != null
&& !"update".equals(request.getParameter(operation)))
- || (request.getParameter(operation) == null
- && (data.getId() != portList.getId()))) {
+ || (request.getParameter(operation) == null && (data.getId() != portList.getId()))) {
duplicateflag = true;
}
}
@@ -280,20 +278,23 @@ public class FirewallDictionaryController {
}
@RequestMapping(value = {"/fw_dictionary/remove_PortList"}, method = {RequestMethod.POST})
- public void removePortListDictionary(HttpServletRequest request, HttpServletResponse response)
- throws IOException {
+ public void removePortListDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException {
DictionaryUtils utils = getDictionaryUtilsInstance();
utils.removeData(request, response, portListDatas, PortList.class);
}
- @RequestMapping(value = {"/get_ProtocolListData"}, method = {RequestMethod.GET},
+ @RequestMapping(
+ value = {"/get_ProtocolListData"},
+ method = {RequestMethod.GET},
produces = MediaType.APPLICATION_JSON_VALUE)
public void getProtocolListDictionaryEntityData(HttpServletResponse response) {
DictionaryUtils utils = getDictionaryUtilsInstance();
utils.getData(response, protocolListDatas, ProtocolList.class);
}
- @RequestMapping(value = {"/get_ProtocolListDataByName"}, method = {RequestMethod.GET},
+ @RequestMapping(
+ value = {"/get_ProtocolListDataByName"},
+ method = {RequestMethod.GET},
produces = MediaType.APPLICATION_JSON_VALUE)
public void getProtocolListDictionaryEntityDataByName(HttpServletResponse response) {
DictionaryUtils utils = getDictionaryUtilsInstance();
@@ -301,8 +302,8 @@ public class FirewallDictionaryController {
}
@RequestMapping(value = {"/fw_dictionary/save_protocolList"}, method = {RequestMethod.POST})
- public ModelAndView saveProtocolListDictionary(HttpServletRequest request,
- HttpServletResponse response) throws IOException {
+ public ModelAndView saveProtocolListDictionary(HttpServletRequest request, HttpServletResponse response)
+ throws IOException {
DictionaryUtils utils = getDictionaryUtilsInstance();
try {
boolean fromAPI = utils.isRequestFromAPI(request);
@@ -311,24 +312,20 @@ public class FirewallDictionaryController {
JsonNode root = mapper.readTree(request.getReader());
ProtocolList protocolList;
if (fromAPI) {
- protocolList =
- mapper.readValue(root.get(dictionaryFields).toString(), ProtocolList.class);
+ protocolList = mapper.readValue(root.get(dictionaryFields).toString(), ProtocolList.class);
} else {
- protocolList = mapper.readValue(root.get("protocolListDictionaryData").toString(),
- ProtocolList.class);
+ protocolList = mapper.readValue(root.get("protocolListDictionaryData").toString(), ProtocolList.class);
}
- List<Object> duplicateData = commonClassDao.checkDuplicateEntry(
- protocolList.getProtocolName(), protocolName, ProtocolList.class);
+ List<Object> duplicateData = commonClassDao.checkDuplicateEntry(protocolList.getProtocolName(),
+ protocolName, ProtocolList.class);
boolean duplicateflag = false;
if (!duplicateData.isEmpty()) {
ProtocolList data = (ProtocolList) duplicateData.get(0);
- if (request.getParameter(operation) != null
- && "update".equals(request.getParameter(operation))) {
+ if (request.getParameter(operation) != null && "update".equals(request.getParameter(operation))) {
protocolList.setId(data.getId());
} else if ((request.getParameter(operation) != null
&& !"update".equals(request.getParameter(operation)))
- || (request.getParameter(operation) == null
- && (data.getId() != protocolList.getId()))) {
+ || (request.getParameter(operation) == null && (data.getId() != protocolList.getId()))) {
duplicateflag = true;
}
}
@@ -339,8 +336,7 @@ public class FirewallDictionaryController {
} else {
commonClassDao.update(protocolList);
}
- responseString =
- mapper.writeValueAsString(commonClassDao.getData(ProtocolList.class));
+ responseString = mapper.writeValueAsString(commonClassDao.getData(ProtocolList.class));
} else {
responseString = duplicateResponseString;
}
@@ -356,20 +352,24 @@ public class FirewallDictionaryController {
}
@RequestMapping(value = {"/fw_dictionary/remove_protocol"}, method = {RequestMethod.POST})
- public void removeProtocolListDictionary(HttpServletRequest request,
- HttpServletResponse response) throws IOException {
+ public void removeProtocolListDictionary(HttpServletRequest request, HttpServletResponse response)
+ throws IOException {
DictionaryUtils utils = getDictionaryUtilsInstance();
utils.removeData(request, response, protocolListDatas, ProtocolList.class);
}
- @RequestMapping(value = {"/get_AddressGroupDictionaryDataByName"}, method = {RequestMethod.GET},
+ @RequestMapping(
+ value = {"/get_AddressGroupDictionaryDataByName"},
+ method = {RequestMethod.GET},
produces = MediaType.APPLICATION_JSON_VALUE)
public void getAddressGroupDictionaryEntityDataByName(HttpServletResponse response) {
DictionaryUtils utils = getDictionaryUtilsInstance();
utils.getDataByEntity(response, addressGroupDatas, "name", AddressGroup.class);
}
- @RequestMapping(value = {"/get_AddressGroupData"}, method = {RequestMethod.GET},
+ @RequestMapping(
+ value = {"/get_AddressGroupData"},
+ method = {RequestMethod.GET},
produces = MediaType.APPLICATION_JSON_VALUE)
public void getAddressGroupDictionaryEntityData(HttpServletResponse response) {
DictionaryUtils utils = getDictionaryUtilsInstance();
@@ -377,8 +377,8 @@ public class FirewallDictionaryController {
}
@RequestMapping(value = {"/fw_dictionary/save_addressGroup"}, method = {RequestMethod.POST})
- public ModelAndView saveAddressGroupDictionary(HttpServletRequest request,
- HttpServletResponse response) throws IOException {
+ public ModelAndView saveAddressGroupDictionary(HttpServletRequest request, HttpServletResponse response)
+ throws IOException {
DictionaryUtils utils = getDictionaryUtilsInstance();
try {
boolean fromAPI = utils.isRequestFromAPI(request);
@@ -388,32 +388,27 @@ public class FirewallDictionaryController {
AddressGroup addressGroup;
GridData gridData;
if (fromAPI) {
- addressGroup =
- mapper.readValue(root.get(dictionaryFields).toString(), AddressGroup.class);
+ addressGroup = mapper.readValue(root.get(dictionaryFields).toString(), AddressGroup.class);
gridData = mapper.readValue(root.get(dictionaryFields).toString(), GridData.class);
} else {
- addressGroup = mapper.readValue(root.get("addressGroupDictionaryData").toString(),
- AddressGroup.class);
- gridData = mapper.readValue(root.get("addressGroupDictionaryData").toString(),
- GridData.class);
+ addressGroup = mapper.readValue(root.get("addressGroupDictionaryData").toString(), AddressGroup.class);
+ gridData = mapper.readValue(root.get("addressGroupDictionaryData").toString(), GridData.class);
}
if (!addressGroup.getGroupName().startsWith(groupNameStart)) {
String groupName = groupNameStart + addressGroup.getGroupName();
addressGroup.setGroupName(groupName);
}
addressGroup.setServiceList(utils.appendKey(gridData.getAttributes(), option, ","));
- List<Object> duplicateData = commonClassDao
- .checkDuplicateEntry(addressGroup.getGroupName(), "name", AddressGroup.class);
+ List<Object> duplicateData =
+ commonClassDao.checkDuplicateEntry(addressGroup.getGroupName(), "name", AddressGroup.class);
boolean duplicateflag = false;
if (!duplicateData.isEmpty()) {
AddressGroup data = (AddressGroup) duplicateData.get(0);
- if (request.getParameter(operation) != null
- && "update".equals(request.getParameter(operation))) {
+ if (request.getParameter(operation) != null && "update".equals(request.getParameter(operation))) {
addressGroup.setId(data.getId());
} else if ((request.getParameter(operation) != null
&& !"update".equals(request.getParameter(operation)))
- || (request.getParameter(operation) == null
- && (data.getId() != addressGroup.getId()))) {
+ || (request.getParameter(operation) == null && (data.getId() != addressGroup.getId()))) {
duplicateflag = true;
}
}
@@ -424,8 +419,7 @@ public class FirewallDictionaryController {
} else {
commonClassDao.update(addressGroup);
}
- responseString =
- mapper.writeValueAsString(commonClassDao.getData(AddressGroup.class));
+ responseString = mapper.writeValueAsString(commonClassDao.getData(AddressGroup.class));
} else {
responseString = duplicateResponseString;
}
@@ -441,20 +435,24 @@ public class FirewallDictionaryController {
}
@RequestMapping(value = {"/fw_dictionary/remove_AddressGroup"}, method = {RequestMethod.POST})
- public void removeAddressGroupDictionary(HttpServletRequest request,
- HttpServletResponse response) throws IOException {
+ public void removeAddressGroupDictionary(HttpServletRequest request, HttpServletResponse response)
+ throws IOException {
DictionaryUtils utils = getDictionaryUtilsInstance();
utils.removeData(request, response, addressGroupDatas, AddressGroup.class);
}
- @RequestMapping(value = {"/get_ActionListDictionaryDataByName"}, method = {RequestMethod.GET},
+ @RequestMapping(
+ value = {"/get_ActionListDictionaryDataByName"},
+ method = {RequestMethod.GET},
produces = MediaType.APPLICATION_JSON_VALUE)
public void getActionListDictionaryEntityDataByName(HttpServletResponse response) {
DictionaryUtils utils = getDictionaryUtilsInstance();
utils.getDataByEntity(response, actionListDatas, "actionName", ActionList.class);
}
- @RequestMapping(value = {"/get_ActionListData"}, method = {RequestMethod.GET},
+ @RequestMapping(
+ value = {"/get_ActionListData"},
+ method = {RequestMethod.GET},
produces = MediaType.APPLICATION_JSON_VALUE)
public void getActionListDictionaryEntityData(HttpServletResponse response) {
DictionaryUtils utils = getDictionaryUtilsInstance();
@@ -462,8 +460,8 @@ public class FirewallDictionaryController {
}
@RequestMapping(value = {"/fw_dictionary/save_ActionList"}, method = {RequestMethod.POST})
- public ModelAndView saveActionListDictionary(HttpServletRequest request,
- HttpServletResponse response) throws IOException {
+ public ModelAndView saveActionListDictionary(HttpServletRequest request, HttpServletResponse response)
+ throws IOException {
DictionaryUtils utils = getDictionaryUtilsInstance();
try {
boolean fromAPI = utils.isRequestFromAPI(request);
@@ -472,24 +470,20 @@ public class FirewallDictionaryController {
JsonNode root = mapper.readTree(request.getReader());
ActionList actionList;
if (fromAPI) {
- actionList =
- mapper.readValue(root.get(dictionaryFields).toString(), ActionList.class);
+ actionList = mapper.readValue(root.get(dictionaryFields).toString(), ActionList.class);
} else {
- actionList = mapper.readValue(root.get("actionListDictionaryData").toString(),
- ActionList.class);
+ actionList = mapper.readValue(root.get("actionListDictionaryData").toString(), ActionList.class);
}
- List<Object> duplicateData = commonClassDao.checkDuplicateEntry(
- actionList.getActionName(), "actionName", ActionList.class);
+ List<Object> duplicateData =
+ commonClassDao.checkDuplicateEntry(actionList.getActionName(), "actionName", ActionList.class);
boolean duplicateflag = false;
if (!duplicateData.isEmpty()) {
ActionList data = (ActionList) duplicateData.get(0);
- if (request.getParameter(operation) != null
- && "update".equals(request.getParameter(operation))) {
+ if (request.getParameter(operation) != null && "update".equals(request.getParameter(operation))) {
actionList.setId(data.getId());
} else if ((request.getParameter(operation) != null
&& !"update".equals(request.getParameter(operation)))
- || (request.getParameter(operation) == null
- && (data.getId() != actionList.getId()))) {
+ || (request.getParameter(operation) == null && (data.getId() != actionList.getId()))) {
duplicateflag = true;
}
}
@@ -500,8 +494,7 @@ public class FirewallDictionaryController {
} else {
commonClassDao.update(actionList);
}
- responseString =
- mapper.writeValueAsString(commonClassDao.getData(ActionList.class));
+ responseString = mapper.writeValueAsString(commonClassDao.getData(ActionList.class));
} else {
responseString = duplicateResponseString;
}
@@ -523,14 +516,18 @@ public class FirewallDictionaryController {
utils.removeData(request, response, actionListDatas, ActionList.class);
}
- @RequestMapping(value = {"/get_ServiceGroupData"}, method = {RequestMethod.GET},
+ @RequestMapping(
+ value = {"/get_ServiceGroupData"},
+ method = {RequestMethod.GET},
produces = MediaType.APPLICATION_JSON_VALUE)
public void getServiceGroupDictionaryEntityData(HttpServletResponse response) {
DictionaryUtils utils = getDictionaryUtilsInstance();
utils.getData(response, serviceGroupDatas, GroupServiceList.class);
}
- @RequestMapping(value = {"/get_ServiceGroupDictionaryDataByName"}, method = {RequestMethod.GET},
+ @RequestMapping(
+ value = {"/get_ServiceGroupDictionaryDataByName"},
+ method = {RequestMethod.GET},
produces = MediaType.APPLICATION_JSON_VALUE)
public void getServiceGroupDictionaryEntityDataByName(HttpServletResponse response) {
DictionaryUtils utils = getDictionaryUtilsInstance();
@@ -538,8 +535,8 @@ public class FirewallDictionaryController {
}
@RequestMapping(value = {"/fw_dictionary/save_serviceGroup"}, method = {RequestMethod.POST})
- public ModelAndView saveServiceGroupDictionary(HttpServletRequest request,
- HttpServletResponse response) throws IOException {
+ public ModelAndView saveServiceGroupDictionary(HttpServletRequest request, HttpServletResponse response)
+ throws IOException {
DictionaryUtils utils = getDictionaryUtilsInstance();
try {
boolean fromAPI = utils.isRequestFromAPI(request);
@@ -549,32 +546,28 @@ public class FirewallDictionaryController {
GroupServiceList groupServiceList;
GridData gridData;
if (fromAPI) {
- groupServiceList = mapper.readValue(root.get(dictionaryFields).toString(),
- GroupServiceList.class);
+ groupServiceList = mapper.readValue(root.get(dictionaryFields).toString(), GroupServiceList.class);
gridData = mapper.readValue(root.get(dictionaryFields).toString(), GridData.class);
} else {
- groupServiceList = mapper.readValue(
- root.get("serviceGroupDictionaryData").toString(), GroupServiceList.class);
- gridData = mapper.readValue(root.get("serviceGroupDictionaryData").toString(),
- GridData.class);
+ groupServiceList =
+ mapper.readValue(root.get("serviceGroupDictionaryData").toString(), GroupServiceList.class);
+ gridData = mapper.readValue(root.get("serviceGroupDictionaryData").toString(), GridData.class);
}
if (!groupServiceList.getGroupName().startsWith(groupNameStart)) {
String groupName = groupNameStart + groupServiceList.getGroupName();
groupServiceList.setGroupName(groupName);
}
groupServiceList.setServiceList(utils.appendKey(gridData.getAttributes(), option, ","));
- List<Object> duplicateData = commonClassDao.checkDuplicateEntry(
- groupServiceList.getGroupName(), "name", GroupServiceList.class);
+ List<Object> duplicateData =
+ commonClassDao.checkDuplicateEntry(groupServiceList.getGroupName(), "name", GroupServiceList.class);
boolean duplicateflag = false;
if (!duplicateData.isEmpty()) {
GroupServiceList data = (GroupServiceList) duplicateData.get(0);
- if (request.getParameter(operation) != null
- && "update".equals(request.getParameter(operation))) {
+ if (request.getParameter(operation) != null && "update".equals(request.getParameter(operation))) {
groupServiceList.setId(data.getId());
} else if ((request.getParameter(operation) != null
&& !"update".equals(request.getParameter(operation)))
- || (request.getParameter(operation) == null
- && (data.getId() != groupServiceList.getId()))) {
+ || (request.getParameter(operation) == null && (data.getId() != groupServiceList.getId()))) {
duplicateflag = true;
}
}
@@ -585,8 +578,7 @@ public class FirewallDictionaryController {
} else {
commonClassDao.update(groupServiceList);
}
- responseString =
- mapper.writeValueAsString(commonClassDao.getData(GroupServiceList.class));
+ responseString = mapper.writeValueAsString(commonClassDao.getData(GroupServiceList.class));
} else {
responseString = duplicateResponseString;
}
@@ -602,20 +594,24 @@ public class FirewallDictionaryController {
}
@RequestMapping(value = {"/fw_dictionary/remove_serviceGroup"}, method = {RequestMethod.POST})
- public void removeServiceGroupDictionary(HttpServletRequest request,
- HttpServletResponse response) throws IOException {
+ public void removeServiceGroupDictionary(HttpServletRequest request, HttpServletResponse response)
+ throws IOException {
DictionaryUtils utils = getDictionaryUtilsInstance();
utils.removeData(request, response, serviceGroupDatas, GroupServiceList.class);
}
- @RequestMapping(value = {"/get_SecurityZoneDataByName"}, method = {RequestMethod.GET},
+ @RequestMapping(
+ value = {"/get_SecurityZoneDataByName"},
+ method = {RequestMethod.GET},
produces = MediaType.APPLICATION_JSON_VALUE)
public void getSecurityZoneDictionaryEntityDataByName(HttpServletResponse response) {
DictionaryUtils utils = getDictionaryUtilsInstance();
utils.getDataByEntity(response, securityZoneDatas, zoneName, SecurityZone.class);
}
- @RequestMapping(value = {"/get_SecurityZoneData"}, method = {RequestMethod.GET},
+ @RequestMapping(
+ value = {"/get_SecurityZoneData"},
+ method = {RequestMethod.GET},
produces = MediaType.APPLICATION_JSON_VALUE)
public void getSecurityZoneDictionaryEntityData(HttpServletResponse response) {
DictionaryUtils utils = getDictionaryUtilsInstance();
@@ -623,8 +619,8 @@ public class FirewallDictionaryController {
}
@RequestMapping(value = {"/fw_dictionary/save_securityZone"}, method = {RequestMethod.POST})
- public ModelAndView saveSecurityZoneDictionary(HttpServletRequest request,
- HttpServletResponse response) throws IOException {
+ public ModelAndView saveSecurityZoneDictionary(HttpServletRequest request, HttpServletResponse response)
+ throws IOException {
DictionaryUtils utils = getDictionaryUtilsInstance();
try {
boolean fromAPI = utils.isRequestFromAPI(request);
@@ -633,24 +629,20 @@ public class FirewallDictionaryController {
JsonNode root = mapper.readTree(request.getReader());
SecurityZone securityZone;
if (fromAPI) {
- securityZone =
- mapper.readValue(root.get(dictionaryFields).toString(), SecurityZone.class);
+ securityZone = mapper.readValue(root.get(dictionaryFields).toString(), SecurityZone.class);
} else {
- securityZone = mapper.readValue(root.get("securityZoneDictionaryData").toString(),
- SecurityZone.class);
+ securityZone = mapper.readValue(root.get("securityZoneDictionaryData").toString(), SecurityZone.class);
}
- List<Object> duplicateData = commonClassDao
- .checkDuplicateEntry(securityZone.getZoneName(), zoneName, SecurityZone.class);
+ List<Object> duplicateData =
+ commonClassDao.checkDuplicateEntry(securityZone.getZoneName(), zoneName, SecurityZone.class);
boolean duplicateflag = false;
if (!duplicateData.isEmpty()) {
SecurityZone data = (SecurityZone) duplicateData.get(0);
- if (request.getParameter(operation) != null
- && "update".equals(request.getParameter(operation))) {
+ if (request.getParameter(operation) != null && "update".equals(request.getParameter(operation))) {
securityZone.setId(data.getId());
} else if ((request.getParameter(operation) != null
&& !"update".equals(request.getParameter(operation)))
- || (request.getParameter(operation) == null
- && (data.getId() != securityZone.getId()))) {
+ || (request.getParameter(operation) == null && (data.getId() != securityZone.getId()))) {
duplicateflag = true;
}
}
@@ -661,8 +653,7 @@ public class FirewallDictionaryController {
} else {
commonClassDao.update(securityZone);
}
- responseString =
- mapper.writeValueAsString(commonClassDao.getData(SecurityZone.class));
+ responseString = mapper.writeValueAsString(commonClassDao.getData(SecurityZone.class));
} else {
responseString = duplicateResponseString;
}
@@ -678,21 +669,24 @@ public class FirewallDictionaryController {
}
@RequestMapping(value = {"/fw_dictionary/remove_securityZone"}, method = {RequestMethod.POST})
- public void removeSecurityZoneDictionary(HttpServletRequest request,
- HttpServletResponse response) throws IOException {
+ public void removeSecurityZoneDictionary(HttpServletRequest request, HttpServletResponse response)
+ throws IOException {
DictionaryUtils utils = getDictionaryUtilsInstance();
utils.removeData(request, response, securityZoneDatas, SecurityZone.class);
}
-
- @RequestMapping(value = {"/get_ServiceListData"}, method = {RequestMethod.GET},
+ @RequestMapping(
+ value = {"/get_ServiceListData"},
+ method = {RequestMethod.GET},
produces = MediaType.APPLICATION_JSON_VALUE)
public void getServiceListDictionaryEntityData(HttpServletResponse response) {
DictionaryUtils utils = getDictionaryUtilsInstance();
utils.getData(response, serviceListDatas, ServiceList.class);
}
- @RequestMapping(value = {"/get_ServiceListDictionaryDataByName"}, method = {RequestMethod.GET},
+ @RequestMapping(
+ value = {"/get_ServiceListDictionaryDataByName"},
+ method = {RequestMethod.GET},
produces = MediaType.APPLICATION_JSON_VALUE)
public void getServiceListDictionaryEntityDataByName(HttpServletResponse response) {
DictionaryUtils utils = getDictionaryUtilsInstance();
@@ -700,8 +694,8 @@ public class FirewallDictionaryController {
}
@RequestMapping(value = {"/fw_dictionary/save_serviceList"}, method = {RequestMethod.POST})
- public ModelAndView saveServiceListDictionary(HttpServletRequest request,
- HttpServletResponse response) throws IOException {
+ public ModelAndView saveServiceListDictionary(HttpServletRequest request, HttpServletResponse response)
+ throws IOException {
DictionaryUtils utils = getDictionaryUtilsInstance();
try {
boolean fromAPI = utils.isRequestFromAPI(request);
@@ -711,33 +705,27 @@ public class FirewallDictionaryController {
ServiceList serviceList;
GridData serviceListGridData;
if (fromAPI) {
- serviceList =
- mapper.readValue(root.get(dictionaryFields).toString(), ServiceList.class);
- serviceListGridData =
- mapper.readValue(root.get(dictionaryFields).toString(), GridData.class);
+ serviceList = mapper.readValue(root.get(dictionaryFields).toString(), ServiceList.class);
+ serviceListGridData = mapper.readValue(root.get(dictionaryFields).toString(), GridData.class);
} else {
- serviceList = mapper.readValue(root.get("serviceListDictionaryData").toString(),
- ServiceList.class);
- serviceListGridData = mapper.readValue(
- root.get("serviceListDictionaryData").toString(), GridData.class);
+ serviceList = mapper.readValue(root.get("serviceListDictionaryData").toString(), ServiceList.class);
+ serviceListGridData =
+ mapper.readValue(root.get("serviceListDictionaryData").toString(), GridData.class);
}
- serviceList.setServiceTransProtocol(
- utils.appendKey(serviceListGridData.getTransportProtocols(), option, ","));
- serviceList.setServiceAppProtocol(
- utils.appendKey(serviceListGridData.getAppProtocols(), option, ","));
+ serviceList
+ .setServiceTransportProtocol(utils.appendKey(serviceListGridData.getTransportProtocols(), option, ","));
+ serviceList.setServiceAppProtocol(utils.appendKey(serviceListGridData.getAppProtocols(), option, ","));
serviceList.setServiceType("SERVICE");
- List<Object> duplicateData = commonClassDao.checkDuplicateEntry(
- serviceList.getServiceName(), serviceName, ServiceList.class);
+ List<Object> duplicateData =
+ commonClassDao.checkDuplicateEntry(serviceList.getServiceName(), serviceName, ServiceList.class);
boolean duplicateflag = false;
if (!duplicateData.isEmpty()) {
ServiceList data = (ServiceList) duplicateData.get(0);
- if (request.getParameter(operation) != null
- && "update".equals(request.getParameter(operation))) {
+ if (request.getParameter(operation) != null && "update".equals(request.getParameter(operation))) {
serviceList.setId(data.getId());
} else if ((request.getParameter(operation) != null
&& !"update".equals(request.getParameter(operation)))
- || (request.getParameter(operation) == null
- && (data.getId() != serviceList.getId()))) {
+ || (request.getParameter(operation) == null && (data.getId() != serviceList.getId()))) {
duplicateflag = true;
}
}
@@ -748,8 +736,7 @@ public class FirewallDictionaryController {
} else {
commonClassDao.update(serviceList);
}
- responseString =
- mapper.writeValueAsString(commonClassDao.getData(ServiceList.class));
+ responseString = mapper.writeValueAsString(commonClassDao.getData(ServiceList.class));
} else {
responseString = duplicateResponseString;
}
@@ -765,20 +752,24 @@ public class FirewallDictionaryController {
}
@RequestMapping(value = {"/fw_dictionary/remove_serviceList"}, method = {RequestMethod.POST})
- public void removeServiceListDictionary(HttpServletRequest request,
- HttpServletResponse response) throws IOException {
+ public void removeServiceListDictionary(HttpServletRequest request, HttpServletResponse response)
+ throws IOException {
DictionaryUtils utils = getDictionaryUtilsInstance();
utils.removeData(request, response, serviceListDatas, ServiceList.class);
}
- @RequestMapping(value = {"/get_ZoneData"}, method = {RequestMethod.GET},
+ @RequestMapping(
+ value = {"/get_ZoneData"},
+ method = {RequestMethod.GET},
produces = MediaType.APPLICATION_JSON_VALUE)
public void getZoneDictionaryEntityData(HttpServletResponse response) {
DictionaryUtils utils = getDictionaryUtilsInstance();
utils.getData(response, zoneDatas, Zone.class);
}
- @RequestMapping(value = {"/get_ZoneDictionaryDataByName"}, method = {RequestMethod.GET},
+ @RequestMapping(
+ value = {"/get_ZoneDictionaryDataByName"},
+ method = {RequestMethod.GET},
produces = MediaType.APPLICATION_JSON_VALUE)
public void getZoneDictionaryEntityDataByName(HttpServletResponse response) {
DictionaryUtils utils = getDictionaryUtilsInstance();
@@ -800,18 +791,15 @@ public class FirewallDictionaryController {
} else {
zone = mapper.readValue(root.get("zoneDictionaryData").toString(), Zone.class);
}
- List<Object> duplicateData =
- commonClassDao.checkDuplicateEntry(zone.getZoneName(), zoneName, Zone.class);
+ List<Object> duplicateData = commonClassDao.checkDuplicateEntry(zone.getZoneName(), zoneName, Zone.class);
boolean duplicateflag = false;
if (!duplicateData.isEmpty()) {
Zone data = (Zone) duplicateData.get(0);
- if (request.getParameter(operation) != null
- && "update".equals(request.getParameter(operation))) {
+ if (request.getParameter(operation) != null && "update".equals(request.getParameter(operation))) {
zone.setId(data.getId());
} else if ((request.getParameter(operation) != null
&& !"update".equals(request.getParameter(operation)))
- || (request.getParameter(operation) == null
- && (data.getId() != zone.getId()))) {
+ || (request.getParameter(operation) == null && (data.getId() != zone.getId()))) {
duplicateflag = true;
}
}
@@ -838,20 +826,23 @@ public class FirewallDictionaryController {
}
@RequestMapping(value = {"/fw_dictionary/remove_zone"}, method = {RequestMethod.POST})
- public void removeZoneDictionary(HttpServletRequest request, HttpServletResponse response)
- throws IOException {
+ public void removeZoneDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException {
DictionaryUtils utils = getDictionaryUtilsInstance();
utils.removeData(request, response, zoneDatas, Zone.class);
}
- @RequestMapping(value = {"/get_TermListDataByName"}, method = {RequestMethod.GET},
+ @RequestMapping(
+ value = {"/get_TermListDataByName"},
+ method = {RequestMethod.GET},
produces = MediaType.APPLICATION_JSON_VALUE)
public void getTermListDictionaryEntityDataByName(HttpServletResponse response) {
DictionaryUtils utils = getDictionaryUtilsInstance();
utils.getDataByEntity(response, termListDictDatas, termName, TermList.class);
}
- @RequestMapping(value = {"/get_TermListData"}, method = {RequestMethod.GET},
+ @RequestMapping(
+ value = {"/get_TermListData"},
+ method = {RequestMethod.GET},
produces = MediaType.APPLICATION_JSON_VALUE)
public void getTermListDictionaryEntityData(HttpServletResponse response) {
DictionaryUtils utils = getDictionaryUtilsInstance();
@@ -859,8 +850,8 @@ public class FirewallDictionaryController {
}
@RequestMapping(value = {"/fw_dictionary/save_termList"}, method = {RequestMethod.POST})
- public ModelAndView saveTermListDictionary(HttpServletRequest request,
- HttpServletResponse response) throws IOException {
+ public ModelAndView saveTermListDictionary(HttpServletRequest request, HttpServletResponse response)
+ throws IOException {
DictionaryUtils utils = getDictionaryUtilsInstance();
try {
boolean fromAPI = utils.isRequestFromAPI(request);
@@ -872,41 +863,33 @@ public class FirewallDictionaryController {
String userId = null;
if (fromAPI) {
termList = mapper.readValue(root.get(dictionaryFields).toString(), TermList.class);
- termListDatas =
- mapper.readValue(root.get(dictionaryFields).toString(), TermListData.class);
+ termListDatas = mapper.readValue(root.get(dictionaryFields).toString(), TermListData.class);
userId = "API";
} else {
- termList = mapper.readValue(root.get("termListDictionaryData").toString(),
- TermList.class);
- termListDatas = mapper.readValue(root.get("termListDictionaryData").toString(),
- TermListData.class);
+ termList = mapper.readValue(root.get("termListDictionaryData").toString(), TermList.class);
+ termListDatas = mapper.readValue(root.get("termListDictionaryData").toString(), TermListData.class);
userId = root.get(userid).textValue();
}
- termList.setFromZones(utils.appendKey(termListDatas.getFromZoneDatas(), option, ","));
- termList.setToZones(utils.appendKey(termListDatas.getToZoneDatas(), option, ","));
- termList.setSrcIPList(utils.appendKey(termListDatas.getSourceListDatas(), option, ","));
- termList.setDestIPList(
- utils.appendKey(termListDatas.getDestinationListDatas(), option, ","));
- termList.setSrcPortList(
- utils.appendKey(termListDatas.getSourceServiceDatas(), option, ","));
- termList.setDestPortList(
- utils.appendKey(termListDatas.getDestinationServiceDatas(), option, ","));
+ termList.setFromZone(utils.appendKey(termListDatas.getFromZoneDatas(), option, ","));
+ termList.setToZone(utils.appendKey(termListDatas.getToZoneDatas(), option, ","));
+ termList.setSrcIpList(utils.appendKey(termListDatas.getSourceListDatas(), option, ","));
+ termList.setDestIpList(utils.appendKey(termListDatas.getDestinationListDatas(), option, ","));
+ termList.setSrcPortList(utils.appendKey(termListDatas.getSourceServiceDatas(), option, ","));
+ termList.setDestPortList(utils.appendKey(termListDatas.getDestinationServiceDatas(), option, ","));
termList.setAction(utils.appendKey(termListDatas.getActionListDatas(), option, ","));
UserInfo userInfo = utils.getUserInfo(userId);
- List<Object> duplicateData = commonClassDao.checkDuplicateEntry(termList.getTermName(),
- termName, TermList.class);
+ List<Object> duplicateData =
+ commonClassDao.checkDuplicateEntry(termList.getTermName(), termName, TermList.class);
boolean duplicateflag = false;
if (!duplicateData.isEmpty()) {
TermList data = (TermList) duplicateData.get(0);
- if (request.getParameter(operation) != null
- && "update".equals(request.getParameter(operation))) {
+ if (request.getParameter(operation) != null && "update".equals(request.getParameter(operation))) {
termList.setId(data.getId());
} else if ((request.getParameter(operation) != null
&& !"update".equals(request.getParameter(operation)))
- || (request.getParameter(operation) == null
- && (data.getId() != termList.getId()))) {
+ || (request.getParameter(operation) == null && (data.getId() != termList.getId()))) {
duplicateflag = true;
}
}
@@ -936,22 +919,24 @@ public class FirewallDictionaryController {
}
@RequestMapping(value = {"/fw_dictionary/remove_termList"}, method = {RequestMethod.POST})
- public void removeTermListDictionary(HttpServletRequest request, HttpServletResponse response)
- throws IOException {
+ public void removeTermListDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException {
DictionaryUtils utils = getDictionaryUtilsInstance();
utils.removeData(request, response, termListDictDatas, TermList.class);
}
// ParentList Dictionary Data
- @RequestMapping(value = {"/get_FWDictionaryListDataByName"}, method = {RequestMethod.GET},
+ @RequestMapping(
+ value = {"/get_FWDictionaryListDataByName"},
+ method = {RequestMethod.GET},
produces = MediaType.APPLICATION_JSON_VALUE)
public void getFWDictListDictionaryEntityDataByName(HttpServletResponse response) {
DictionaryUtils utils = getDictionaryUtilsInstance();
- utils.getDataByEntity(response, fwDictListDatas, "parentItemName",
- FirewallDictionaryList.class);
+ utils.getDataByEntity(response, fwDictListDatas, "parentItemName", FirewallDictionaryList.class);
}
- @RequestMapping(value = {"/get_FWDictionaryListData"}, method = {RequestMethod.GET},
+ @RequestMapping(
+ value = {"/get_FWDictionaryListData"},
+ method = {RequestMethod.GET},
produces = MediaType.APPLICATION_JSON_VALUE)
public void getFWDictionaryListEntityData(HttpServletResponse response) {
DictionaryUtils utils = getDictionaryUtilsInstance();
@@ -959,8 +944,8 @@ public class FirewallDictionaryController {
}
@RequestMapping(value = {"/fw_dictionary/save_FWDictionaryList"}, method = {RequestMethod.POST})
- public ModelAndView saveFWDictionaryList(HttpServletRequest request,
- HttpServletResponse response) throws IOException {
+ public ModelAndView saveFWDictionaryList(HttpServletRequest request, HttpServletResponse response)
+ throws IOException {
DictionaryUtils utils = getDictionaryUtilsInstance();
try {
boolean fromAPI = utils.isRequestFromAPI(request);
@@ -970,31 +955,27 @@ public class FirewallDictionaryController {
FirewallDictionaryList fwDictList;
GridData gridData;
if (fromAPI) {
- fwDictList = mapper.readValue(root.get(dictionaryFields).toString(),
- FirewallDictionaryList.class);
+ fwDictList = mapper.readValue(root.get(dictionaryFields).toString(), FirewallDictionaryList.class);
gridData = mapper.readValue(root.get(dictionaryFields).toString(), GridData.class);
} else {
- fwDictList = mapper.readValue(root.get("fwDictListDictionaryData").toString(),
- FirewallDictionaryList.class);
- gridData = mapper.readValue(root.get("fwDictListDictionaryData").toString(),
- GridData.class);
+ fwDictList =
+ mapper.readValue(root.get("fwDictListDictionaryData").toString(), FirewallDictionaryList.class);
+ gridData = mapper.readValue(root.get("fwDictListDictionaryData").toString(), GridData.class);
}
fwDictList.setServiceList(utils.appendKey(gridData.getAttributes(), option, ","));
fwDictList.setAddressList(utils.appendKey(gridData.getAlAttributes(), option, ","));
- List<Object> duplicateData = commonClassDao.checkDuplicateEntry(
- fwDictList.getParentItemName(), "parentItemName", FirewallDictionaryList.class);
+ List<Object> duplicateData = commonClassDao.checkDuplicateEntry(fwDictList.getParentItemName(),
+ "parentItemName", FirewallDictionaryList.class);
boolean duplicateflag = false;
if (!duplicateData.isEmpty()) {
FirewallDictionaryList data = (FirewallDictionaryList) duplicateData.get(0);
- if (request.getParameter(operation) != null
- && "update".equals(request.getParameter(operation))) {
+ if (request.getParameter(operation) != null && "update".equals(request.getParameter(operation))) {
fwDictList.setId(data.getId());
} else if ((request.getParameter(operation) != null
&& !"update".equals(request.getParameter(operation)))
- || (request.getParameter(operation) == null
- && (data.getId() != fwDictList.getId()))) {
+ || (request.getParameter(operation) == null && (data.getId() != fwDictList.getId()))) {
duplicateflag = true;
}
}
@@ -1005,8 +986,7 @@ public class FirewallDictionaryController {
} else {
commonClassDao.update(fwDictList);
}
- responseString = mapper
- .writeValueAsString(commonClassDao.getData(FirewallDictionaryList.class));
+ responseString = mapper.writeValueAsString(commonClassDao.getData(FirewallDictionaryList.class));
} else {
responseString = duplicateResponseString;
}
@@ -1021,69 +1001,65 @@ public class FirewallDictionaryController {
return null;
}
- @RequestMapping(value = {"/fw_dictionary/remove_FWDictionaryList"},
- method = {RequestMethod.POST})
- public void removeFWDictionaryList(HttpServletRequest request, HttpServletResponse response)
- throws IOException {
+ @RequestMapping(value = {"/fw_dictionary/remove_FWDictionaryList"}, method = {RequestMethod.POST})
+ public void removeFWDictionaryList(HttpServletRequest request, HttpServletResponse response) throws IOException {
DictionaryUtils utils = getDictionaryUtilsInstance();
utils.removeData(request, response, fwDictListDatas, FirewallDictionaryList.class);
}
-
- @RequestMapping(value = {"/get_TagPickerNameByName"}, method = {RequestMethod.GET},
+ @RequestMapping(
+ value = {"/get_TagPickerNameByName"},
+ method = {RequestMethod.GET},
produces = MediaType.APPLICATION_JSON_VALUE)
public void getTagPickerNameEntityDataByName(HttpServletResponse response) {
DictionaryUtils utils = getDictionaryUtilsInstance();
- utils.getDataByEntity(response, fwTagPickerDatas, tagPickerName, FWTagPicker.class);
+ utils.getDataByEntity(response, fwTagPickerDatas, tagPickerName, FwTagPicker.class);
}
- @RequestMapping(value = {"/get_TagPickerListData"}, method = {RequestMethod.GET},
+ @RequestMapping(
+ value = {"/get_TagPickerListData"},
+ method = {RequestMethod.GET},
produces = MediaType.APPLICATION_JSON_VALUE)
public void getTagPickerDictionaryEntityData(HttpServletResponse response) {
DictionaryUtils utils = getDictionaryUtilsInstance();
- utils.getData(response, fwTagPickerDatas, FWTagPicker.class);
+ utils.getData(response, fwTagPickerDatas, FwTagPicker.class);
}
@RequestMapping(value = {"/fw_dictionary/save_fwTagPicker"}, method = {RequestMethod.POST})
- public ModelAndView saveFirewallTagPickerDictionary(HttpServletRequest request,
- HttpServletResponse response) throws IOException {
+ public ModelAndView saveFirewallTagPickerDictionary(HttpServletRequest request, HttpServletResponse response)
+ throws IOException {
DictionaryUtils utils = getDictionaryUtilsInstance();
try {
boolean fromAPI = utils.isRequestFromAPI(request);
ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
JsonNode root = mapper.readTree(request.getReader());
- FWTagPicker fwTagPicker;
+ FwTagPicker fwTagPicker;
TagGridValues data;
String userId = "";
if (fromAPI) {
- fwTagPicker =
- mapper.readValue(root.get(dictionaryFields).toString(), FWTagPicker.class);
+ fwTagPicker = mapper.readValue(root.get(dictionaryFields).toString(), FwTagPicker.class);
data = mapper.readValue(root.get(dictionaryFields).toString(), TagGridValues.class);
userId = "API";
} else {
- fwTagPicker = mapper.readValue(root.get("fwTagPickerDictionaryData").toString(),
- FWTagPicker.class);
- data = mapper.readValue(root.get("fwTagPickerDictionaryData").toString(),
- TagGridValues.class);
+ fwTagPicker = mapper.readValue(root.get("fwTagPickerDictionaryData").toString(), FwTagPicker.class);
+ data = mapper.readValue(root.get("fwTagPickerDictionaryData").toString(), TagGridValues.class);
userId = root.get(userid).textValue();
}
fwTagPicker.setTagValues(utils.appendKeyValue(data.getTags(), "#", ":"));
UserInfo userInfo = utils.getUserInfo(userId);
- List<Object> duplicateData = commonClassDao.checkDuplicateEntry(
- fwTagPicker.getTagPickerName(), tagPickerName, FWTagPicker.class);
+ List<Object> duplicateData = commonClassDao.checkDuplicateEntry(fwTagPicker.getTagPickerName(),
+ tagPickerName, FwTagPicker.class);
boolean duplicateflag = false;
if (!duplicateData.isEmpty()) {
- FWTagPicker data1 = (FWTagPicker) duplicateData.get(0);
- if (request.getParameter(operation) != null
- && "update".equals(request.getParameter(operation))) {
+ FwTagPicker data1 = (FwTagPicker) duplicateData.get(0);
+ if (request.getParameter(operation) != null && "update".equals(request.getParameter(operation))) {
fwTagPicker.setId(data1.getId());
} else if ((request.getParameter(operation) != null
&& !"update".equals(request.getParameter(operation)))
- || (request.getParameter(operation) == null
- && (data1.getId() != fwTagPicker.getId()))) {
+ || (request.getParameter(operation) == null && (data1.getId() != fwTagPicker.getId()))) {
duplicateflag = true;
}
}
@@ -1097,8 +1073,7 @@ public class FirewallDictionaryController {
fwTagPicker.setModifiedDate(new Date());
commonClassDao.update(fwTagPicker);
}
- responseString =
- mapper.writeValueAsString(commonClassDao.getData(FWTagPicker.class));
+ responseString = mapper.writeValueAsString(commonClassDao.getData(FwTagPicker.class));
} else {
responseString = duplicateResponseString;
}
@@ -1114,65 +1089,64 @@ public class FirewallDictionaryController {
}
@RequestMapping(value = {"/fw_dictionary/remove_tagPicker"}, method = {RequestMethod.POST})
- public void removeFirewallTagPickerDictionary(HttpServletRequest request,
- HttpServletResponse response) throws IOException {
+ public void removeFirewallTagPickerDictionary(HttpServletRequest request, HttpServletResponse response)
+ throws IOException {
DictionaryUtils utils = getDictionaryUtilsInstance();
- utils.removeData(request, response, fwTagPickerDatas, FWTagPicker.class);
+ utils.removeData(request, response, fwTagPickerDatas, FwTagPicker.class);
}
- @RequestMapping(value = {"/get_TagListData"}, method = {RequestMethod.GET},
+ @RequestMapping(
+ value = {"/get_TagListData"},
+ method = {RequestMethod.GET},
produces = MediaType.APPLICATION_JSON_VALUE)
public void getTagDictionaryEntityData(HttpServletResponse response) {
DictionaryUtils utils = getDictionaryUtilsInstance();
- utils.getData(response, fwTagDatas, FWTag.class);
+ utils.getData(response, fwTagDatas, FwTag.class);
}
- @RequestMapping(value = {"/get_TagNameByName"}, method = {RequestMethod.GET},
+ @RequestMapping(
+ value = {"/get_TagNameByName"},
+ method = {RequestMethod.GET},
produces = MediaType.APPLICATION_JSON_VALUE)
public void getTagNameEntityDataByName(HttpServletResponse response) {
DictionaryUtils utils = getDictionaryUtilsInstance();
- utils.getDataByEntity(response, fwTagDatas, "fwTagName", FWTag.class);
+ utils.getDataByEntity(response, fwTagDatas, "fwTagName", FwTag.class);
}
-
@RequestMapping(value = {"/fw_dictionary/save_fwTag"}, method = {RequestMethod.POST})
- public ModelAndView saveFirewallTagDictionary(HttpServletRequest request,
- HttpServletResponse response) throws IOException {
+ public ModelAndView saveFirewallTagDictionary(HttpServletRequest request, HttpServletResponse response)
+ throws IOException {
DictionaryUtils utils = getDictionaryUtilsInstance();
try {
boolean fromAPI = utils.isRequestFromAPI(request);
ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
JsonNode root = mapper.readTree(request.getReader());
- FWTag fwTag;
+ FwTag fwTag;
TagGridValues tagGridValues;
String userId = "";
if (fromAPI) {
- fwTag = mapper.readValue(root.get(dictionaryFields).toString(), FWTag.class);
- tagGridValues = mapper.readValue(root.get(dictionaryFields).toString(),
- TagGridValues.class);
+ fwTag = mapper.readValue(root.get(dictionaryFields).toString(), FwTag.class);
+ tagGridValues = mapper.readValue(root.get(dictionaryFields).toString(), TagGridValues.class);
userId = "API";
} else {
- fwTag = mapper.readValue(root.get("fwTagDictionaryData").toString(), FWTag.class);
- tagGridValues = mapper.readValue(root.get("fwTagDictionaryData").toString(),
- TagGridValues.class);
+ fwTag = mapper.readValue(root.get("fwTagDictionaryData").toString(), FwTag.class);
+ tagGridValues = mapper.readValue(root.get("fwTagDictionaryData").toString(), TagGridValues.class);
userId = root.get(userid).textValue();
}
fwTag.setTagValues(utils.appendKey(tagGridValues.getTags(), "tags", ","));
UserInfo userInfo = utils.getUserInfo(userId);
- List<Object> duplicateData = commonClassDao.checkDuplicateEntry(fwTag.getFwTagName(),
- "fwTagName", FWTag.class);
+ List<Object> duplicateData =
+ commonClassDao.checkDuplicateEntry(fwTag.getFwTagName(), "fwTagName", FwTag.class);
boolean duplicateflag = false;
if (!duplicateData.isEmpty()) {
- FWTag data = (FWTag) duplicateData.get(0);
- if (request.getParameter(operation) != null
- && "update".equals(request.getParameter(operation))) {
+ FwTag data = (FwTag) duplicateData.get(0);
+ if (request.getParameter(operation) != null && "update".equals(request.getParameter(operation))) {
fwTag.setId(data.getId());
} else if ((request.getParameter(operation) != null
&& !"update".equals(request.getParameter(operation)))
- || (request.getParameter(operation) == null
- && (data.getId() != fwTag.getId()))) {
+ || (request.getParameter(operation) == null && (data.getId() != fwTag.getId()))) {
duplicateflag = true;
}
}
@@ -1186,7 +1160,7 @@ public class FirewallDictionaryController {
fwTag.setModifiedDate(new Date());
commonClassDao.update(fwTag);
}
- responseString = mapper.writeValueAsString(commonClassDao.getData(FWTag.class));
+ responseString = mapper.writeValueAsString(commonClassDao.getData(FwTag.class));
} else {
responseString = duplicateResponseString;
}
@@ -1202,10 +1176,10 @@ public class FirewallDictionaryController {
}
@RequestMapping(value = {"/fw_dictionary/remove_tagList"}, method = {RequestMethod.POST})
- public void removeFirewallTagDictionary(HttpServletRequest request,
- HttpServletResponse response) throws IOException {
+ public void removeFirewallTagDictionary(HttpServletRequest request, HttpServletResponse response)
+ throws IOException {
DictionaryUtils utils = getDictionaryUtilsInstance();
- utils.removeData(request, response, fwTagDatas, FWTag.class);
+ utils.removeData(request, response, fwTagDatas, FwTag.class);
}
}
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
index ee274d2a7..566ac1447 100644
--- 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
@@ -24,6 +24,7 @@ import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.Gson;
+
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
@@ -32,8 +33,10 @@ 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.apache.commons.lang.StringUtils;
import org.json.JSONObject;
import org.onap.policy.common.logging.flexlogger.FlexLogger;
@@ -42,7 +45,7 @@ import org.onap.policy.pap.xacml.rest.XACMLPapServlet;
import org.onap.policy.pap.xacml.rest.util.DictionaryUtils;
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.DcaeUuid;
import org.onap.policy.rest.jpa.DictionaryData;
import org.onap.policy.rest.jpa.MicroServiceAttribute;
import org.onap.policy.rest.jpa.MicroServiceConfigName;
@@ -51,8 +54,8 @@ import org.onap.policy.rest.jpa.MicroServiceModels;
import org.onap.policy.rest.jpa.MicroserviceHeaderdeFaults;
import org.onap.policy.rest.jpa.PrefixList;
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.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;
@@ -72,11 +75,9 @@ public class MicroServiceDictionaryController {
private static String getDictionary = "getDictionary";
private static String errorMsg = "error";
private static String dictionaryDBQuery = "dictionaryDBQuery";
- private LinkedHashMap<String, MSAttributeObject> classMap;
+ private LinkedHashMap<String, MsAttributeObject> classMap;
private List<String> modelList = new ArrayList<>();
- private static String apiflag = "apiflag";
private static String dictionaryFields = "dictionaryFields";
- private static String update = "update";
private static String duplicateResponseString = "Duplicate";
private static String microServiceModelsDictionaryDatas = "microServiceModelsDictionaryDatas";
private static String modelName = "modelName";
@@ -108,22 +109,26 @@ public class MicroServiceDictionaryController {
MicroServiceDictionaryController.commonClassDao = commonClassDao;
}
- MSModelUtils utils = new MSModelUtils(XACMLPapServlet.getMsOnapName(), XACMLPapServlet.getMsPolicyName());
+ MsModelUtils utils = new MsModelUtils(XACMLPapServlet.getMsOnapName(), XACMLPapServlet.getMsPolicyName());
private MicroServiceModels newModel;
- @RequestMapping(value = {"/get_DCAEUUIDDataByName"}, method = {RequestMethod.GET},
+ @RequestMapping(
+ value = {"/get_DCAEUUIDDataByName"},
+ method = {RequestMethod.GET},
produces = MediaType.APPLICATION_JSON_VALUE)
public void getDCAEUUIDDictionaryByNameEntityData(HttpServletResponse response) {
DictionaryUtils utils = getDictionaryUtilsInstance();
- utils.getDataByEntity(response, dcaeUUIDDatas, "name", DCAEuuid.class);
+ utils.getDataByEntity(response, dcaeUUIDDatas, "name", DcaeUuid.class);
}
- @RequestMapping(value = {"/get_DCAEUUIDData"}, method = {RequestMethod.GET},
+ @RequestMapping(
+ value = {"/get_DCAEUUIDData"},
+ method = {RequestMethod.GET},
produces = MediaType.APPLICATION_JSON_VALUE)
public void getDCAEUUIDDictionaryEntityData(HttpServletResponse response) {
DictionaryUtils utils = getDictionaryUtilsInstance();
- utils.getData(response, dcaeUUIDDatas, DCAEuuid.class);
+ utils.getData(response, dcaeUUIDDatas, DcaeUuid.class);
}
@RequestMapping(value = {"/ms_dictionary/save_dcaeUUID"}, method = {RequestMethod.POST})
@@ -135,17 +140,17 @@ public class MicroServiceDictionaryController {
ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
JsonNode root = mapper.readTree(request.getReader());
- DCAEuuid dCAEuuid;
+ DcaeUuid dCAEuuid;
if (fromAPI) {
- dCAEuuid = mapper.readValue(root.get(dictionaryFields).toString(), DCAEuuid.class);
+ dCAEuuid = mapper.readValue(root.get(dictionaryFields).toString(), DcaeUuid.class);
} else {
- dCAEuuid = mapper.readValue(root.get("dcaeUUIDDictionaryData").toString(), DCAEuuid.class);
+ dCAEuuid = mapper.readValue(root.get("dcaeUUIDDictionaryData").toString(), DcaeUuid.class);
}
- List<Object> duplicateData = commonClassDao.checkDuplicateEntry(dCAEuuid.getName(), "name", DCAEuuid.class);
+ List<Object> duplicateData = commonClassDao.checkDuplicateEntry(dCAEuuid.getName(), "name", DcaeUuid.class);
boolean duplicateflag = false;
if (duplicateData != null && !duplicateData.isEmpty()) {
- DCAEuuid data = (DCAEuuid) duplicateData.get(0);
+ DcaeUuid data = (DcaeUuid) duplicateData.get(0);
if (request.getParameter(operation) != null && "update".equals(request.getParameter(operation))) {
dCAEuuid.setId(data.getId());
} else if ((request.getParameter(operation) != null
@@ -161,7 +166,7 @@ public class MicroServiceDictionaryController {
} else {
commonClassDao.update(dCAEuuid);
}
- responseString = mapper.writeValueAsString(commonClassDao.getData(DCAEuuid.class));
+ responseString = mapper.writeValueAsString(commonClassDao.getData(DcaeUuid.class));
} else {
responseString = duplicateResponseString;
}
@@ -179,24 +184,30 @@ public class MicroServiceDictionaryController {
@RequestMapping(value = {"/ms_dictionary/remove_dcaeuuid"}, method = {RequestMethod.POST})
public void removeDCAEUUIDDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException {
DictionaryUtils utils = getDictionaryUtilsInstance();
- utils.removeData(request, response, dcaeUUIDDatas, DCAEuuid.class);
+ utils.removeData(request, response, dcaeUUIDDatas, DcaeUuid.class);
}
- @RequestMapping(value = {"/get_MicroServiceConfigNameDataByName"}, method = {RequestMethod.GET},
+ @RequestMapping(
+ value = {"/get_MicroServiceConfigNameDataByName"},
+ method = {RequestMethod.GET},
produces = MediaType.APPLICATION_JSON_VALUE)
public void getMicroServiceConfigNameByNameDictionaryEntityData(HttpServletResponse response) {
DictionaryUtils utils = getDictionaryUtilsInstance();
utils.getDataByEntity(response, microServiceConfigNameDatas, "name", MicroServiceConfigName.class);
}
- @RequestMapping(value = {"/get_MicroServiceConfigNameData"}, method = {RequestMethod.GET},
+ @RequestMapping(
+ value = {"/get_MicroServiceConfigNameData"},
+ method = {RequestMethod.GET},
produces = MediaType.APPLICATION_JSON_VALUE)
public void getMicroServiceConfigNameDictionaryEntityData(HttpServletResponse response) {
DictionaryUtils utils = getDictionaryUtilsInstance();
utils.getData(response, microServiceConfigNameDatas, MicroServiceConfigName.class);
}
- @RequestMapping(value = {"/get_MicroServiceDictData"}, method = {RequestMethod.GET},
+ @RequestMapping(
+ value = {"/get_MicroServiceDictData"},
+ method = {RequestMethod.GET},
produces = MediaType.APPLICATION_JSON_VALUE)
public void getMicroServiceDictNameDictionaryEntityData(HttpServletResponse response) {
DictionaryUtils utils = getDictionaryUtilsInstance();
@@ -330,14 +341,18 @@ public class MicroServiceDictionaryController {
utils.removeData(request, response, microServiceConfigNameDatas, MicroServiceConfigName.class);
}
- @RequestMapping(value = {"/get_MicroServiceLocationDataByName"}, method = {RequestMethod.GET},
+ @RequestMapping(
+ value = {"/get_MicroServiceLocationDataByName"},
+ method = {RequestMethod.GET},
produces = MediaType.APPLICATION_JSON_VALUE)
public void getMicroServiceLocationByNameDictionaryEntityData(HttpServletResponse response) {
DictionaryUtils utils = getDictionaryUtilsInstance();
utils.getDataByEntity(response, microServiceLocationDatas, "name", MicroServiceLocation.class);
}
- @RequestMapping(value = {"/get_MicroServiceLocationData"}, method = {RequestMethod.GET},
+ @RequestMapping(
+ value = {"/get_MicroServiceLocationData"},
+ method = {RequestMethod.GET},
produces = MediaType.APPLICATION_JSON_VALUE)
public void getMicroServiceLocationDictionaryEntityData(HttpServletResponse response) {
DictionaryUtils utils = getDictionaryUtilsInstance();
@@ -405,14 +420,18 @@ public class MicroServiceDictionaryController {
utils.removeData(request, response, microServiceLocationDatas, MicroServiceLocation.class);
}
- @RequestMapping(value = {"/get_MicroServiceAttributeDataByName"}, method = {RequestMethod.GET},
+ @RequestMapping(
+ value = {"/get_MicroServiceAttributeDataByName"},
+ method = {RequestMethod.GET},
produces = MediaType.APPLICATION_JSON_VALUE)
public void getMicroServiceAttributeByNameDictionaryEntityData(HttpServletResponse response) {
DictionaryUtils utils = getDictionaryUtilsInstance();
utils.getDataByEntity(response, microServiceAttributeDatas, "name", MicroServiceAttribute.class);
}
- @RequestMapping(value = {"/get_MicroServiceAttributeData"}, method = {RequestMethod.GET},
+ @RequestMapping(
+ value = {"/get_MicroServiceAttributeData"},
+ method = {RequestMethod.GET},
produces = MediaType.APPLICATION_JSON_VALUE)
public void getMicroServiceAttributeDictionaryEntityData(HttpServletResponse response) {
DictionaryUtils utils = getDictionaryUtilsInstance();
@@ -483,15 +502,18 @@ public class MicroServiceDictionaryController {
utils.removeData(request, response, microServiceAttributeDatas, MicroServiceAttribute.class);
}
-
- @RequestMapping(value = {"/get_MicroServiceModelsDataByName"}, method = {RequestMethod.GET},
+ @RequestMapping(
+ value = {"/get_MicroServiceModelsDataByName"},
+ method = {RequestMethod.GET},
produces = MediaType.APPLICATION_JSON_VALUE)
public void getMicroServiceModelsDictionaryByNameEntityData(HttpServletResponse response) {
DictionaryUtils utils = getDictionaryUtilsInstance();
utils.getDataByEntity(response, microServiceModelsDictionaryDatas, modelName, MicroServiceModels.class);
}
- @RequestMapping(value = {"/get_MicroServiceModelsDataByVersion"}, method = {RequestMethod.GET},
+ @RequestMapping(
+ value = {"/get_MicroServiceModelsDataByVersion"},
+ method = {RequestMethod.GET},
produces = MediaType.APPLICATION_JSON_VALUE)
public void getMicroServiceModelsDictionaryByVersionEntityData(HttpServletRequest request,
HttpServletResponse response) {
@@ -517,14 +539,18 @@ public class MicroServiceDictionaryController {
}
}
- @RequestMapping(value = {"/get_MicroServiceModelsData"}, method = {RequestMethod.GET},
+ @RequestMapping(
+ value = {"/get_MicroServiceModelsData"},
+ method = {RequestMethod.GET},
produces = MediaType.APPLICATION_JSON_VALUE)
public void getMicroServiceModelsDictionaryEntityData(HttpServletResponse response) {
DictionaryUtils utils = getDictionaryUtilsInstance();
utils.getData(response, microServiceModelsDictionaryDatas, MicroServiceModels.class);
}
- @RequestMapping(value = {"/get_MicroServiceModelsDataServiceVersion"}, method = {RequestMethod.GET},
+ @RequestMapping(
+ value = {"/get_MicroServiceModelsDataServiceVersion"},
+ method = {RequestMethod.GET},
produces = MediaType.APPLICATION_JSON_VALUE)
public void getMicroServiceModelsDictionaryEntityDataServiceVersion(HttpServletResponse response) {
try {
@@ -552,7 +578,9 @@ public class MicroServiceDictionaryController {
}
}
- @RequestMapping(value = {"/get_MicroServiceModelsDataByClass"}, method = {RequestMethod.GET},
+ @RequestMapping(
+ value = {"/get_MicroServiceModelsDataByClass"},
+ method = {RequestMethod.GET},
produces = MediaType.APPLICATION_JSON_VALUE)
public void getMicroServiceModelsDictionaryClassEntityData(HttpServletResponse response) {
try {
@@ -622,15 +650,15 @@ public class MicroServiceDictionaryController {
Set<String> keys = jsonObject.keySet();
for (String key : keys) {
String value = jsonObject.get(key).toString();
- MSAttributeObject msAttributeObject = mapper1.readValue(value, MSAttributeObject.class);
+ MsAttributeObject msAttributeObject = mapper1.readValue(value, MsAttributeObject.class);
classMap.put(key, msAttributeObject);
}
userId = root.get("userid").textValue();
- MSAttributeObject mainClass = classMap.get(this.newModel.getModelName());
+ MsAttributeObject mainClass = classMap.get(this.newModel.getModelName());
this.newModel.setDependency("[]");
String value = new Gson().toJson(mainClass.getSubClass());
- this.newModel.setSub_attributes(value);
+ this.newModel.setSubAttributes(value);
String attributes = mainClass.getAttribute().toString().replace("{", "").replace("}", "");
int equalsIndexForAttributes = attributes.indexOf('=');
String atttributesAfterFirstEquals = attributes.substring(equalsIndexForAttributes + 1);
@@ -638,7 +666,7 @@ public class MicroServiceDictionaryController {
String refAttributes = mainClass.getRefAttribute().toString().replace("{", "").replace("}", "");
int equalsIndex = refAttributes.indexOf("=");
String refAttributesAfterFirstEquals = refAttributes.substring(equalsIndex + 1);
- this.newModel.setRef_attributes(refAttributesAfterFirstEquals);
+ this.newModel.setRefAttributes(refAttributesAfterFirstEquals);
this.newModel.setEnumValues(mainClass.getEnumType().toString().replace("{", "").replace("}", ""));
this.newModel
.setAnnotation(mainClass.getMatchingSet().toString().replace("{", "").replace("}", ""));
@@ -675,7 +703,7 @@ public class MicroServiceDictionaryController {
Set<String> keys = jsonObject.keySet();
for (String key : keys) {
String value = jsonObject.get(key).toString();
- MSAttributeObject msAttributeObject = mapper1.readValue(value, MSAttributeObject.class);
+ MsAttributeObject msAttributeObject = mapper1.readValue(value, MsAttributeObject.class);
classMap.put(key, msAttributeObject);
}
}
@@ -685,10 +713,10 @@ public class MicroServiceDictionaryController {
}
}
microServiceModels.setAttributes(this.newModel.getAttributes());
- microServiceModels.setRef_attributes(this.newModel.getRef_attributes());
+ microServiceModels.setRefAttributes(this.newModel.getRefAttributes());
microServiceModels.setDependency(this.newModel.getDependency());
microServiceModels.setModelName(this.newModel.getModelName());
- microServiceModels.setSub_attributes(this.newModel.getSub_attributes());
+ microServiceModels.setSubAttributes(this.newModel.getSubAttributes());
microServiceModels.setVersion(this.newModel.getVersion());
microServiceModels.setEnumValues(this.newModel.getEnumValues());
microServiceModels.setAnnotation(this.newModel.getAnnotation());
@@ -741,11 +769,11 @@ public class MicroServiceDictionaryController {
utils.removeData(request, response, microServiceModelsDictionaryDatas, MicroServiceModels.class);
}
- private void addValuesToNewModel(HashMap<String, MSAttributeObject> classMap) {
+ private void addValuesToNewModel(HashMap<String, MsAttributeObject> classMap) {
// Loop through the classmap and pull out the required info for the new file.
String subAttribute = null;
- MSAttributeObject mainClass = classMap.get(this.newModel.getModelName());
+ MsAttributeObject mainClass = classMap.get(this.newModel.getModelName());
if (mainClass != null) {
String dependTemp = StringUtils.replaceEach(mainClass.getDependency(), new String[] {"[", "]", " "},
@@ -753,7 +781,7 @@ public class MicroServiceDictionaryController {
ArrayList<String> dependency = new ArrayList<>(Arrays.asList(dependTemp.split(",")));
dependency = getFullDependencyList(dependency);
for (String element : dependency) {
- MSAttributeObject temp = classMap.get(element);
+ MsAttributeObject temp = classMap.get(element);
if (temp != null) {
mainClass.addAllRefAttribute(temp.getRefAttribute());
mainClass.addAllAttribute(temp.getAttribute());
@@ -770,9 +798,9 @@ public class MicroServiceDictionaryController {
}
if (mainClass != null) {
this.newModel.setDependency(mainClass.getDependency());
- this.newModel.setSub_attributes(subAttribute);
+ this.newModel.setSubAttributes(subAttribute);
this.newModel.setAttributes(mainClass.getAttribute().toString().replace("{", "").replace("}", ""));
- this.newModel.setRef_attributes(mainClass.getRefAttribute().toString().replace("{", "").replace("}", ""));
+ this.newModel.setRefAttributes(mainClass.getRefAttribute().toString().replace("{", "").replace("}", ""));
this.newModel.setEnumValues(mainClass.getEnumType().toString().replace("{", "").replace("}", ""));
this.newModel.setAnnotation(mainClass.getMatchingSet().toString().replace("{", "").replace("}", ""));
}
@@ -784,7 +812,7 @@ public class MicroServiceDictionaryController {
returnList.addAll(dependency);
for (String element : dependency) {
if (classMap.containsKey(element)) {
- MSAttributeObject value = classMap.get(element);
+ MsAttributeObject value = classMap.get(element);
String rawValue =
StringUtils.replaceEach(value.getDependency(), new String[] {"[", "]"}, new String[] {"", ""});
workingList = new ArrayList<>(Arrays.asList(rawValue.split(",")));
@@ -800,21 +828,24 @@ public class MicroServiceDictionaryController {
return returnList;
}
- @RequestMapping(value = {"/get_MicroServiceHeaderDefaultsDataByName"}, method = {RequestMethod.GET},
+ @RequestMapping(
+ value = {"/get_MicroServiceHeaderDefaultsDataByName"},
+ method = {RequestMethod.GET},
produces = MediaType.APPLICATION_JSON_VALUE)
public void getMicroServiceHeaderDefaultsEntityDataByName(HttpServletResponse response) {
DictionaryUtils utils = getDictionaryUtilsInstance();
utils.getDataByEntity(response, microServiceHeaderDefaultDatas, "modelName", MicroserviceHeaderdeFaults.class);
}
- @RequestMapping(value = {"/get_MicroServiceHeaderDefaultsData"}, method = {RequestMethod.GET},
+ @RequestMapping(
+ value = {"/get_MicroServiceHeaderDefaultsData"},
+ method = {RequestMethod.GET},
produces = MediaType.APPLICATION_JSON_VALUE)
public void getMicroServiceHeaderDefaultsEntityData(HttpServletResponse response) {
DictionaryUtils utils = getDictionaryUtilsInstance();
utils.getData(response, microServiceHeaderDefaultDatas, MicroserviceHeaderdeFaults.class);
}
-
@RequestMapping(value = {"/ms_dictionary/save_headerDefaults"}, method = {RequestMethod.POST})
public ModelAndView saveMicroServiceHeaderDefaultValues(HttpServletRequest request, HttpServletResponse response)
throws IOException {
diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/OptimizationDictionaryController.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/OptimizationDictionaryController.java
index 3d1dba905..a24ee0275 100644
--- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/OptimizationDictionaryController.java
+++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/OptimizationDictionaryController.java
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP-PAP-REST
* ================================================================================
- * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2018-2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -17,8 +17,14 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.policy.pap.xacml.rest.controller;
+import com.fasterxml.jackson.databind.DeserializationFeature;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.google.gson.Gson;
+
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
@@ -37,8 +43,8 @@ import org.onap.policy.pap.xacml.rest.util.DictionaryUtils;
import org.onap.policy.rest.dao.CommonClassDao;
import org.onap.policy.rest.jpa.OptimizationModels;
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.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;
@@ -46,18 +52,13 @@ 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.Gson;
-
@Controller
public class OptimizationDictionaryController {
private static CommonClassDao commonClassDao;
private static String operation = "operation";
- private LinkedHashMap<String,MSAttributeObject > classMap;
- private static String dictionaryFields ="dictionaryFields";
+ private LinkedHashMap<String, MsAttributeObject> classMap;
+ private static String dictionaryFields = "dictionaryFields";
private static String duplicateResponseString = "Duplicate";
private static String optimizationModelsDictionaryDatas = "optimizationModelsDictionaryDatas";
private static String modelName = "modelName";
@@ -67,41 +68,48 @@ public class OptimizationDictionaryController {
private static String classMapData = "classMap";
private static final String UPDATE = "update";
-
- public OptimizationDictionaryController(){
+ public OptimizationDictionaryController() {
super();
- }
+ }
- private DictionaryUtils getDictionaryUtilsInstance(){
+ private DictionaryUtils getDictionaryUtilsInstance() {
return DictionaryUtils.getDictionaryUtils();
}
-
+
@Autowired
- public OptimizationDictionaryController(CommonClassDao commonClassDao){
+ public OptimizationDictionaryController(CommonClassDao commonClassDao) {
setCommonClassDao(commonClassDao);
}
+
public static void setCommonClassDao(CommonClassDao commonClassDao) {
OptimizationDictionaryController.commonClassDao = commonClassDao;
}
- MSModelUtils utils = new MSModelUtils(XACMLPapServlet.getMsOnapName(), XACMLPapServlet.getMsPolicyName());
+ MsModelUtils utils = new MsModelUtils(XACMLPapServlet.getMsOnapName(), XACMLPapServlet.getMsPolicyName());
private OptimizationModels newModel;
- @RequestMapping(value={"/get_OptimizationModelsData"}, method={RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE)
- public void getOptimizationModelsDictionaryEntityData(HttpServletResponse response){
+ @RequestMapping(
+ value = {"/get_OptimizationModelsData"},
+ method = {RequestMethod.GET},
+ produces = MediaType.APPLICATION_JSON_VALUE)
+ public void getOptimizationModelsDictionaryEntityData(HttpServletResponse response) {
DictionaryUtils dUtils = getDictionaryUtilsInstance();
dUtils.getData(response, optimizationModelsDictionaryDatas, OptimizationModels.class);
}
- @RequestMapping(value={"/get_OptimizationModelsDataByName"}, method={RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE)
- public void getOptimizationModelsDictionaryByNameEntityData(HttpServletResponse response){
+ @RequestMapping(
+ value = {"/get_OptimizationModelsDataByName"},
+ method = {RequestMethod.GET},
+ produces = MediaType.APPLICATION_JSON_VALUE)
+ public void getOptimizationModelsDictionaryByNameEntityData(HttpServletResponse response) {
DictionaryUtils dUtils = getDictionaryUtilsInstance();
dUtils.getDataByEntity(response, optimizationModelsDictionaryDatas, modelName, OptimizationModels.class);
}
- @RequestMapping(value={"/oof_dictionary/save_model"}, method={RequestMethod.POST})
- public ModelAndView saveOptimizationModelsDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{
+ @RequestMapping(value = {"/oof_dictionary/save_model"}, method = {RequestMethod.POST})
+ public ModelAndView saveOptimizationModelsDictionary(HttpServletRequest request, HttpServletResponse response)
+ throws IOException {
DictionaryUtils dUtils = getDictionaryUtilsInstance();
try {
this.newModel = new OptimizationModels();
@@ -113,24 +121,27 @@ public class OptimizationDictionaryController {
String userId = null;
String dataOrderInfo = null;
- if(root.has("dataOrderInfo")){
+ if (root.has("dataOrderInfo")) {
dataOrderInfo = root.get("dataOrderInfo").toString();
}
- if(root.has("modelType")){
+ if (root.has("modelType")) {
JsonNode dataType = root.get("modelType");
- String modelType= dataType.toString();
- if(modelType.contains("yml")){
- if (root.has(optimizationModelsDictionaryData)){
- if (root.get(optimizationModelsDictionaryData).has(description)){
- optimizationModels.setDescription(root.get(optimizationModelsDictionaryData).get(description).asText().replace("\"", ""));
+ String modelType = dataType.toString();
+ if (modelType.contains("yml")) {
+ if (root.has(optimizationModelsDictionaryData)) {
+ if (root.get(optimizationModelsDictionaryData).has(description)) {
+ optimizationModels.setDescription(root.get(optimizationModelsDictionaryData)
+ .get(description).asText().replace("\"", ""));
}
- if (root.get(optimizationModelsDictionaryData).has(modelName)){
- optimizationModels.setModelName(root.get(optimizationModelsDictionaryData).get(modelName).asText().replace("\"", ""));
+ if (root.get(optimizationModelsDictionaryData).has(modelName)) {
+ optimizationModels.setModelName(root.get(optimizationModelsDictionaryData).get(modelName)
+ .asText().replace("\"", ""));
this.newModel.setModelName(optimizationModels.getModelName());
}
- if (root.get(optimizationModelsDictionaryData).has(version)){
- optimizationModels.setVersion(root.get(optimizationModelsDictionaryData).get(version).asText().replace("\"", ""));
+ if (root.get(optimizationModelsDictionaryData).has(version)) {
+ optimizationModels.setVersion(
+ root.get(optimizationModelsDictionaryData).get(version).asText().replace("\"", ""));
this.newModel.setVersion(optimizationModels.getVersion());
}
}
@@ -138,63 +149,70 @@ public class OptimizationDictionaryController {
classMap = new LinkedHashMap<>();
JsonNode data = root.get(classMapData);
ObjectMapper mapper1 = new ObjectMapper();
- String data1 = data.toString().substring(1, data.toString().length()-1);
+ String data1 = data.toString().substring(1, data.toString().length() - 1);
data1 = data1.replace("\\", "");
- data1=data1.replace("\"{","{");
- data1=data1.replace("}\"","}");
+ data1 = data1.replace("\"{", "{");
+ data1 = data1.replace("}\"", "}");
JSONObject jsonObject = new JSONObject(data1);
Set<String> keys = jsonObject.keySet();
- for(String key : keys){
+ for (String key : keys) {
String value = jsonObject.get(key).toString();
- MSAttributeObject msAttributeObject = mapper1.readValue(value, MSAttributeObject.class);
+ MsAttributeObject msAttributeObject = mapper1.readValue(value, MsAttributeObject.class);
classMap.put(key, msAttributeObject);
}
userId = root.get("userid").textValue();
- MSAttributeObject mainClass = classMap.get(this.newModel.getModelName());
+ MsAttributeObject mainClass = classMap.get(this.newModel.getModelName());
this.newModel.setDependency("[]");
String value = new Gson().toJson(mainClass.getSubClass());
this.newModel.setSubattributes(value);
- String attributes= mainClass.getAttribute().toString().replace("{", "").replace("}", "");
- int equalsIndexForAttributes= attributes.indexOf('=');
- String atttributesAfterFirstEquals= attributes.substring(equalsIndexForAttributes+1, attributes.length()-1);
+ String attributes = mainClass.getAttribute().toString().replace("{", "").replace("}", "");
+ int equalsIndexForAttributes = attributes.indexOf('=');
+ String atttributesAfterFirstEquals =
+ attributes.substring(equalsIndexForAttributes + 1, attributes.length() - 1);
this.newModel.setAttributes(atttributesAfterFirstEquals);
- String refAttributes= mainClass.getRefAttribute().toString().replace("{", "").replace("}", "");
- int equalsIndex= refAttributes.indexOf('=');
- String refAttributesAfterFirstEquals= refAttributes.substring(equalsIndex+1, refAttributes.length()-1);
+ String refAttributes = mainClass.getRefAttribute().toString().replace("{", "").replace("}", "");
+ int equalsIndex = refAttributes.indexOf('=');
+ String refAttributesAfterFirstEquals =
+ refAttributes.substring(equalsIndex + 1, refAttributes.length() - 1);
this.newModel.setRefattributes(refAttributesAfterFirstEquals);
this.newModel.setEnumValues(mainClass.getEnumType().toString().replace("{", "").replace("}", ""));
- this.newModel.setAnnotation(mainClass.getMatchingSet().toString().replace("{", "").replace("}", ""));
+ this.newModel
+ .setAnnotation(mainClass.getMatchingSet().toString().replace("{", "").replace("}", ""));
- }else{
+ } else {
if (fromAPI) {
- optimizationModels = mapper.readValue(root.get(dictionaryFields).toString(), OptimizationModels.class);
+ optimizationModels =
+ mapper.readValue(root.get(dictionaryFields).toString(), OptimizationModels.class);
userId = "API";
} else {
- if (root.has(optimizationModelsDictionaryData)){
- if (root.get(optimizationModelsDictionaryData).has(description)){
- optimizationModels.setDescription(root.get(optimizationModelsDictionaryData).get(description).asText().replace("\"", ""));
+ if (root.has(optimizationModelsDictionaryData)) {
+ if (root.get(optimizationModelsDictionaryData).has(description)) {
+ optimizationModels.setDescription(root.get(optimizationModelsDictionaryData)
+ .get(description).asText().replace("\"", ""));
}
- if (root.get(optimizationModelsDictionaryData).has(modelName)){
- optimizationModels.setModelName(root.get(optimizationModelsDictionaryData).get(modelName).asText().replace("\"", ""));
+ if (root.get(optimizationModelsDictionaryData).has(modelName)) {
+ optimizationModels.setModelName(root.get(optimizationModelsDictionaryData)
+ .get(modelName).asText().replace("\"", ""));
this.newModel.setModelName(optimizationModels.getModelName());
}
- if (root.get(optimizationModelsDictionaryData).has(version)){
- optimizationModels.setVersion(root.get(optimizationModelsDictionaryData).get(version).asText().replace("\"", ""));
+ if (root.get(optimizationModelsDictionaryData).has(version)) {
+ optimizationModels.setVersion(root.get(optimizationModelsDictionaryData).get(version)
+ .asText().replace("\"", ""));
this.newModel.setVersion(optimizationModels.getVersion());
}
}
- if(root.has(classMapData)){
+ if (root.has(classMapData)) {
classMap = new LinkedHashMap<>();
JsonNode data = root.get(classMapData);
ObjectMapper mapper1 = new ObjectMapper();
- String data1 = data.toString().substring(1, data.toString().length()-1);
+ String data1 = data.toString().substring(1, data.toString().length() - 1);
data1 = data1.replace("\\", "");
JSONObject jsonObject = new JSONObject(data1);
Set<String> keys = jsonObject.keySet();
- for(String key : keys){
+ for (String key : keys) {
String value = jsonObject.get(key).toString();
- MSAttributeObject msAttributeObject = mapper1.readValue(value, MSAttributeObject.class);
+ MsAttributeObject msAttributeObject = mapper1.readValue(value, MsAttributeObject.class);
classMap.put(key, msAttributeObject);
}
}
@@ -212,80 +230,83 @@ public class OptimizationDictionaryController {
optimizationModels.setEnumValues(this.newModel.getEnumValues());
optimizationModels.setAnnotation(this.newModel.getAnnotation());
- if(dataOrderInfo != null){
+ if (dataOrderInfo != null) {
optimizationModels.setDataOrderInfo(dataOrderInfo);
}
String checkName = optimizationModels.getModelName() + ":" + optimizationModels.getVersion();
- List<Object> duplicateData = commonClassDao.checkDuplicateEntry(checkName, "modelName:version", OptimizationModels.class);
+ List<Object> duplicateData =
+ commonClassDao.checkDuplicateEntry(checkName, "modelName:version", OptimizationModels.class);
boolean duplicateflag = false;
- if(duplicateData!=null && !duplicateData.isEmpty()){
+ if (duplicateData != null && !duplicateData.isEmpty()) {
OptimizationModels data = (OptimizationModels) duplicateData.get(0);
- if(request.getParameter(operation) != null && UPDATE.equals(request.getParameter(operation))){
+ if (request.getParameter(operation) != null && UPDATE.equals(request.getParameter(operation))) {
optimizationModels.setId(data.getId());
- }else if((request.getParameter(operation) != null && !UPDATE.equals(request.getParameter(operation))) ||
- (request.getParameter(operation) == null && (data.getId() != optimizationModels.getId()))){
+ } else if ((request.getParameter(operation) != null && !UPDATE.equals(request.getParameter(operation)))
+ || (request.getParameter(operation) == null && (data.getId() != optimizationModels.getId()))) {
duplicateflag = true;
}
}
UserInfo userInfo = dUtils.getUserInfo(userId);
String responseString = null;
- if(!duplicateflag){
+ if (!duplicateflag) {
optimizationModels.setUserCreatedBy(userInfo);
- if(optimizationModels.getId() == 0){
+ if (optimizationModels.getId() == 0) {
commonClassDao.save(optimizationModels);
- }else{
+ } else {
commonClassDao.update(optimizationModels);
}
responseString = mapper.writeValueAsString(commonClassDao.getData(OptimizationModels.class));
- }else{
+ } else {
responseString = duplicateResponseString;
}
- if(fromAPI){
+ if (fromAPI) {
return dUtils.getResultForApi(responseString);
- }else{
+ } else {
dUtils.setResponseData(response, optimizationModelsDictionaryDatas, responseString);
}
- }catch (Exception e){
+ } catch (Exception e) {
dUtils.setErrorResponseData(response, e);
}
return null;
}
- @RequestMapping(value={"/oof_dictionary/remove_model"}, method={RequestMethod.POST})
- public void removeOptimizationModelsDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException {
+ @RequestMapping(value = {"/oof_dictionary/remove_model"}, method = {RequestMethod.POST})
+ public void removeOptimizationModelsDictionary(HttpServletRequest request, HttpServletResponse response)
+ throws IOException {
DictionaryUtils dUtils = getDictionaryUtilsInstance();
dUtils.removeData(request, response, optimizationModelsDictionaryDatas, OptimizationModels.class);
}
- private void addValuesToNewModel(HashMap<String,MSAttributeObject > classMap) {
- //Loop through the classmap and pull out the required info for the new file.
+ private void addValuesToNewModel(HashMap<String, MsAttributeObject> classMap) {
+ // Loop through the classmap and pull out the required info for the new file.
String subAttribute = null;
- MSAttributeObject mainClass = classMap.get(this.newModel.getModelName());
+ MsAttributeObject mainClass = classMap.get(this.newModel.getModelName());
- if (mainClass !=null){
- String dependTemp = StringUtils.replaceEach(mainClass.getDependency(), new String[]{"[", "]", " "}, new String[]{"", "", ""});
+ if (mainClass != null) {
+ String dependTemp = StringUtils.replaceEach(mainClass.getDependency(), new String[] {"[", "]", " "},
+ new String[] {"", "", ""});
ArrayList<String> dependency = new ArrayList<>(Arrays.asList(dependTemp.split(",")));
dependency = getFullDependencyList(dependency);
- for (String element : dependency){
- MSAttributeObject temp = classMap.get(element);
- if (temp!=null){
+ for (String element : dependency) {
+ 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{
+ } else {
subAttribute = "{}";
this.newModel.setDependency("");
}
- if (mainClass != null && mainClass.getDependency()==null){
+ if (mainClass != null && mainClass.getDependency() == null) {
mainClass.setDependency("");
}
- if(mainClass != null){
+ if (mainClass != null) {
this.newModel.setDependency(mainClass.getDependency());
this.newModel.setSubattributes(subAttribute);
this.newModel.setAttributes(mainClass.getAttribute().toString().replace("{", "").replace("}", ""));
@@ -299,13 +320,14 @@ public class OptimizationDictionaryController {
ArrayList<String> returnList = new ArrayList<>();
ArrayList<String> workingList;
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[]{"", ""});
+ 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()){
+ for (String depend : workingList) {
+ if (!returnList.contains(depend) && !depend.isEmpty()) {
returnList.add(depend.trim());
}
}
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
index c0e7729db..a230ebe38 100644
--- 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
@@ -23,11 +23,14 @@ package org.onap.policy.pap.xacml.rest.controller;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
+
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
+
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
+
import org.apache.commons.lang.StringUtils;
import org.onap.policy.common.logging.flexlogger.FlexLogger;
import org.onap.policy.common.logging.flexlogger.Logger;
@@ -49,8 +52,7 @@ import org.springframework.web.servlet.ModelAndView;
@Controller
public class PolicyScopeDictionaryController {
- private static final Logger LOGGER =
- FlexLogger.getLogger(PolicyScopeDictionaryController.class);
+ private static final Logger LOGGER = FlexLogger.getLogger(PolicyScopeDictionaryController.class);
private static CommonClassDao commonClassDao;
private static String operation = "operation";
@@ -81,24 +83,27 @@ public class PolicyScopeDictionaryController {
PolicyScopeDictionaryController.commonClassDao = commonClassDao;
}
- @RequestMapping(value = {"/get_GroupPolicyScopeDataByName"}, method = {RequestMethod.GET},
+ @RequestMapping(
+ value = {"/get_GroupPolicyScopeDataByName"},
+ method = {RequestMethod.GET},
produces = MediaType.APPLICATION_JSON_VALUE)
public void getGroupPolicyScopeEntityDataByName(HttpServletResponse response) {
DictionaryUtils utils = getDictionaryUtilsInstance();
utils.getDataByEntity(response, groupPolicyScopeDatas, "name", GroupPolicyScopeList.class);
}
- @RequestMapping(value = {"/get_GroupPolicyScopeData"}, method = {RequestMethod.GET},
+ @RequestMapping(
+ value = {"/get_GroupPolicyScopeData"},
+ method = {RequestMethod.GET},
produces = MediaType.APPLICATION_JSON_VALUE)
public void getGroupPolicyScopeEntityData(HttpServletResponse response) {
DictionaryUtils utils = getDictionaryUtilsInstance();
utils.getData(response, groupPolicyScopeDatas, GroupPolicyScopeList.class);
}
- @RequestMapping(value = {"/ps_dictionary/save_psGroupPolicyScope"},
- method = {RequestMethod.POST})
- public ModelAndView savePSGroupScopeDictionary(HttpServletRequest request,
- HttpServletResponse response) throws IOException {
+ @RequestMapping(value = {"/ps_dictionary/save_psGroupPolicyScope"}, method = {RequestMethod.POST})
+ public ModelAndView savePSGroupScopeDictionary(HttpServletRequest request, HttpServletResponse response)
+ throws IOException {
DictionaryUtils utils = getDictionaryUtilsInstance();
try {
boolean fromAPI = utils.isRequestFromAPI(request);
@@ -109,40 +114,33 @@ public class PolicyScopeDictionaryController {
GroupPolicyScope groupData = null;
boolean duplicateGroupFlag = false;
if (fromAPI) {
- gpdata = mapper.readValue(root.get(dictionaryFields).toString(),
- GroupPolicyScopeList.class);
+ gpdata = mapper.readValue(root.get(dictionaryFields).toString(), GroupPolicyScopeList.class);
try {
- groupData = mapper.readValue(root.get(groupPolicyScopeListData1).toString(),
- GroupPolicyScope.class);
+ groupData =
+ 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("\"", ""));
+ 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("\"", ""));
LOGGER.error(e);
}
} else {
- gpdata = mapper.readValue(root.get("groupPolicyScopeListData").toString(),
- GroupPolicyScopeList.class);
+ gpdata = mapper.readValue(root.get("groupPolicyScopeListData").toString(), GroupPolicyScopeList.class);
try {
- groupData = mapper.readValue(root.get(groupPolicyScopeListData1).toString(),
- GroupPolicyScope.class);
+ groupData =
+ mapper.readValue(root.get(groupPolicyScopeListData1).toString(), GroupPolicyScope.class);
} catch (Exception e) {
LOGGER.error(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("\"", ""));
+ 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)) {
@@ -158,15 +156,15 @@ public class PolicyScopeDictionaryController {
valueList.add("service=" + serviceValue);
valueList.add("type=" + typeValue);
valueList.add("closedLoopControlName=" + closedLoopValue);
- String list = StringUtils.replaceEach(valueList.toString(),
- new String[] {"[", "]", " "}, new String[] {"", "", ""});
+ String list = StringUtils.replaceEach(valueList.toString(), new String[] {"[", "]", " "},
+ new String[] {"", "", ""});
gpdata.setGroupList(list);
- List<Object> duplicateData = commonClassDao.checkDuplicateEntry(gpdata.getGroupName(),
- "name", GroupPolicyScopeList.class);
+ List<Object> duplicateData =
+ commonClassDao.checkDuplicateEntry(gpdata.getGroupName(), "name", GroupPolicyScopeList.class);
if (duplicateData.isEmpty()) {
- duplicateData = commonClassDao.checkDuplicateEntry(gpdata.getGroupList(),
- "groupList", GroupPolicyScopeList.class);
+ duplicateData = commonClassDao.checkDuplicateEntry(gpdata.getGroupList(), "groupList",
+ GroupPolicyScopeList.class);
if (duplicateData.isEmpty()) {
duplicateGroupFlag = true;
}
@@ -174,13 +172,11 @@ public class PolicyScopeDictionaryController {
boolean duplicateflag = false;
if (!duplicateData.isEmpty()) {
GroupPolicyScopeList data = (GroupPolicyScopeList) duplicateData.get(0);
- if (request.getParameter(operation) != null
- && "update".equals(request.getParameter(operation))) {
+ if (request.getParameter(operation) != null && "update".equals(request.getParameter(operation))) {
gpdata.setId(data.getId());
} else if ((request.getParameter(operation) != null
&& !"update".equals(request.getParameter(operation)))
- || (request.getParameter(operation) == null
- && (data.getId() != gpdata.getId()))) {
+ || (request.getParameter(operation) == null && (data.getId() != gpdata.getId()))) {
duplicateflag = true;
}
}
@@ -191,8 +187,7 @@ public class PolicyScopeDictionaryController {
} else {
commonClassDao.update(gpdata);
}
- responseString = mapper
- .writeValueAsString(commonClassDao.getData(GroupPolicyScopeList.class));
+ responseString = mapper.writeValueAsString(commonClassDao.getData(GroupPolicyScopeList.class));
} else if (duplicateGroupFlag) {
responseString = "DuplicateGroup";
} else {
@@ -209,22 +204,25 @@ public class PolicyScopeDictionaryController {
return null;
}
- @RequestMapping(value = {"/ps_dictionary/remove_GroupPolicyScope"},
- method = {RequestMethod.POST})
- public void removePSGroupScopeDictionary(HttpServletRequest request,
- HttpServletResponse response) throws IOException {
+ @RequestMapping(value = {"/ps_dictionary/remove_GroupPolicyScope"}, method = {RequestMethod.POST})
+ public void removePSGroupScopeDictionary(HttpServletRequest request, HttpServletResponse response)
+ throws IOException {
DictionaryUtils utils = getDictionaryUtilsInstance();
utils.removeData(request, response, groupPolicyScopeDatas, GroupPolicyScopeList.class);
}
- @RequestMapping(value = {"/get_PSClosedLoopDataByName"}, method = {RequestMethod.GET},
+ @RequestMapping(
+ value = {"/get_PSClosedLoopDataByName"},
+ method = {RequestMethod.GET},
produces = MediaType.APPLICATION_JSON_VALUE)
public void getPSClosedLoopEntityDataByName(HttpServletResponse response) {
DictionaryUtils utils = getDictionaryUtilsInstance();
utils.getDataByEntity(response, psCLDatas, "name", OnapName.class);
}
- @RequestMapping(value = {"/get_PSClosedLoopData"}, method = {RequestMethod.GET},
+ @RequestMapping(
+ value = {"/get_PSClosedLoopData"},
+ method = {RequestMethod.GET},
produces = MediaType.APPLICATION_JSON_VALUE)
public void getPSClosedLoopEntityData(HttpServletResponse response) {
DictionaryUtils utils = getDictionaryUtilsInstance();
@@ -232,8 +230,8 @@ public class PolicyScopeDictionaryController {
}
@RequestMapping(value = {"/ps_dictionary/save_psClosedLoop"}, method = {RequestMethod.POST})
- public ModelAndView savePSClosedLoopDictionary(HttpServletRequest request,
- HttpServletResponse response) throws IOException {
+ public ModelAndView savePSClosedLoopDictionary(HttpServletRequest request, HttpServletResponse response)
+ throws IOException {
DictionaryUtils utils = getDictionaryUtilsInstance();
try {
boolean fromAPI = utils.isRequestFromAPI(request);
@@ -242,25 +240,22 @@ public class PolicyScopeDictionaryController {
JsonNode root = mapper.readTree(request.getReader());
PolicyScopeClosedLoop onapData;
if (fromAPI) {
- onapData = mapper.readValue(root.get(dictionaryFields).toString(),
- PolicyScopeClosedLoop.class);
+ onapData = mapper.readValue(root.get(dictionaryFields).toString(), PolicyScopeClosedLoop.class);
} else {
onapData = mapper.readValue(root.get("psClosedLoopDictionaryData").toString(),
PolicyScopeClosedLoop.class);
}
- List<Object> duplicateData = commonClassDao.checkDuplicateEntry(onapData.getName(),
- "name", PolicyScopeClosedLoop.class);
+ List<Object> duplicateData =
+ commonClassDao.checkDuplicateEntry(onapData.getName(), "name", PolicyScopeClosedLoop.class);
boolean duplicateflag = false;
if (!duplicateData.isEmpty()) {
PolicyScopeClosedLoop data = (PolicyScopeClosedLoop) duplicateData.get(0);
- if (request.getParameter(operation) != null
- && "update".equals(request.getParameter(operation))) {
+ if (request.getParameter(operation) != null && "update".equals(request.getParameter(operation))) {
onapData.setId(data.getId());
} else if ((request.getParameter(operation) != null
&& !"update".equals(request.getParameter(operation)))
- || (request.getParameter(operation) == null
- && (data.getId() != onapData.getId()))) {
+ || (request.getParameter(operation) == null && (data.getId() != onapData.getId()))) {
duplicateflag = true;
}
}
@@ -271,8 +266,7 @@ public class PolicyScopeDictionaryController {
} else {
commonClassDao.update(onapData);
}
- responseString = mapper
- .writeValueAsString(commonClassDao.getData(PolicyScopeClosedLoop.class));
+ responseString = mapper.writeValueAsString(commonClassDao.getData(PolicyScopeClosedLoop.class));
} else {
responseString = duplicateResponseString;
}
@@ -288,20 +282,24 @@ public class PolicyScopeDictionaryController {
}
@RequestMapping(value = {"/ps_dictionary/remove_PSClosedLoop"}, method = {RequestMethod.POST})
- public void removePSClosedLoopDictionary(HttpServletRequest request,
- HttpServletResponse response) throws IOException {
+ public void removePSClosedLoopDictionary(HttpServletRequest request, HttpServletResponse response)
+ throws IOException {
DictionaryUtils utils = getDictionaryUtilsInstance();
utils.removeData(request, response, psCLDatas, PolicyScopeClosedLoop.class);
}
- @RequestMapping(value = {"/get_PSServiceDataByName"}, method = {RequestMethod.GET},
+ @RequestMapping(
+ value = {"/get_PSServiceDataByName"},
+ method = {RequestMethod.GET},
produces = MediaType.APPLICATION_JSON_VALUE)
public void getPSServiceEntityDataByName(HttpServletResponse response) {
DictionaryUtils utils = getDictionaryUtilsInstance();
utils.getDataByEntity(response, psServiceDatas, "name", PolicyScopeService.class);
}
- @RequestMapping(value = {"/get_PSServiceData"}, method = {RequestMethod.GET},
+ @RequestMapping(
+ value = {"/get_PSServiceData"},
+ method = {RequestMethod.GET},
produces = MediaType.APPLICATION_JSON_VALUE)
public void getPSServiceEntityData(HttpServletResponse response) {
DictionaryUtils utils = getDictionaryUtilsInstance();
@@ -309,8 +307,8 @@ public class PolicyScopeDictionaryController {
}
@RequestMapping(value = {"/ps_dictionary/save_psService"}, method = {RequestMethod.POST})
- public ModelAndView savePSServiceDictionary(HttpServletRequest request,
- HttpServletResponse response) throws IOException {
+ public ModelAndView savePSServiceDictionary(HttpServletRequest request, HttpServletResponse response)
+ throws IOException {
DictionaryUtils utils = getDictionaryUtilsInstance();
try {
boolean fromAPI = utils.isRequestFromAPI(request);
@@ -319,25 +317,21 @@ public class PolicyScopeDictionaryController {
JsonNode root = mapper.readTree(request.getReader());
PolicyScopeService onapData;
if (fromAPI) {
- onapData = mapper.readValue(root.get(dictionaryFields).toString(),
- PolicyScopeService.class);
+ onapData = mapper.readValue(root.get(dictionaryFields).toString(), PolicyScopeService.class);
} else {
- onapData = mapper.readValue(root.get("psServiceDictionaryData").toString(),
- PolicyScopeService.class);
+ onapData = mapper.readValue(root.get("psServiceDictionaryData").toString(), PolicyScopeService.class);
}
- List<Object> duplicateData = commonClassDao.checkDuplicateEntry(onapData.getName(),
- "name", PolicyScopeService.class);
+ List<Object> duplicateData =
+ commonClassDao.checkDuplicateEntry(onapData.getName(), "name", PolicyScopeService.class);
boolean duplicateflag = false;
if (!duplicateData.isEmpty()) {
PolicyScopeService data = (PolicyScopeService) duplicateData.get(0);
- if (request.getParameter(operation) != null
- && "update".equals(request.getParameter(operation))) {
+ if (request.getParameter(operation) != null && "update".equals(request.getParameter(operation))) {
onapData.setId(data.getId());
} else if ((request.getParameter(operation) != null
&& !"update".equals(request.getParameter(operation)))
- || (request.getParameter(operation) == null
- && (data.getId() != onapData.getId()))) {
+ || (request.getParameter(operation) == null && (data.getId() != onapData.getId()))) {
duplicateflag = true;
}
}
@@ -348,8 +342,7 @@ public class PolicyScopeDictionaryController {
} else {
commonClassDao.update(onapData);
}
- responseString =
- mapper.writeValueAsString(commonClassDao.getData(PolicyScopeService.class));
+ responseString = mapper.writeValueAsString(commonClassDao.getData(PolicyScopeService.class));
} else {
responseString = duplicateResponseString;
}
@@ -365,20 +358,23 @@ public class PolicyScopeDictionaryController {
}
@RequestMapping(value = {"/ps_dictionary/remove_PSService"}, method = {RequestMethod.POST})
- public void removePSServiceDictionary(HttpServletRequest request, HttpServletResponse response)
- throws IOException {
+ public void removePSServiceDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException {
DictionaryUtils utils = getDictionaryUtilsInstance();
utils.removeData(request, response, psServiceDatas, PolicyScopeService.class);
}
- @RequestMapping(value = {"/get_PSTypeDataByName"}, method = {RequestMethod.GET},
+ @RequestMapping(
+ value = {"/get_PSTypeDataByName"},
+ method = {RequestMethod.GET},
produces = MediaType.APPLICATION_JSON_VALUE)
public void getPSTypeEntityDataByName(HttpServletResponse response) {
DictionaryUtils utils = getDictionaryUtilsInstance();
utils.getDataByEntity(response, psTypeDatas, "name", PolicyScopeType.class);
}
- @RequestMapping(value = {"/get_PSTypeData"}, method = {RequestMethod.GET},
+ @RequestMapping(
+ value = {"/get_PSTypeData"},
+ method = {RequestMethod.GET},
produces = MediaType.APPLICATION_JSON_VALUE)
public void getPSTypeEntityData(HttpServletResponse response) {
DictionaryUtils utils = getDictionaryUtilsInstance();
@@ -386,8 +382,8 @@ public class PolicyScopeDictionaryController {
}
@RequestMapping(value = {"/ps_dictionary/save_psType"}, method = {RequestMethod.POST})
- public ModelAndView savePSTypeDictionary(HttpServletRequest request,
- HttpServletResponse response) throws IOException {
+ public ModelAndView savePSTypeDictionary(HttpServletRequest request, HttpServletResponse response)
+ throws IOException {
DictionaryUtils utils = getDictionaryUtilsInstance();
try {
boolean fromAPI = utils.isRequestFromAPI(request);
@@ -396,25 +392,21 @@ public class PolicyScopeDictionaryController {
JsonNode root = mapper.readTree(request.getReader());
PolicyScopeType onapData;
if (fromAPI) {
- onapData = mapper.readValue(root.get(dictionaryFields).toString(),
- PolicyScopeType.class);
+ onapData = mapper.readValue(root.get(dictionaryFields).toString(), PolicyScopeType.class);
} else {
- onapData = mapper.readValue(root.get("psTypeDictionaryData").toString(),
- PolicyScopeType.class);
+ onapData = mapper.readValue(root.get("psTypeDictionaryData").toString(), PolicyScopeType.class);
}
- List<Object> duplicateData = commonClassDao.checkDuplicateEntry(onapData.getName(),
- "name", PolicyScopeType.class);
+ List<Object> duplicateData =
+ commonClassDao.checkDuplicateEntry(onapData.getName(), "name", PolicyScopeType.class);
boolean duplicateflag = false;
if (!duplicateData.isEmpty()) {
PolicyScopeType data = (PolicyScopeType) duplicateData.get(0);
- if (request.getParameter(operation) != null
- && "update".equals(request.getParameter(operation))) {
+ if (request.getParameter(operation) != null && "update".equals(request.getParameter(operation))) {
onapData.setId(data.getId());
} else if ((request.getParameter(operation) != null
&& !"update".equals(request.getParameter(operation)))
- || (request.getParameter(operation) == null
- && (data.getId() != onapData.getId()))) {
+ || (request.getParameter(operation) == null && (data.getId() != onapData.getId()))) {
duplicateflag = true;
}
}
@@ -425,8 +417,7 @@ public class PolicyScopeDictionaryController {
} else {
commonClassDao.update(onapData);
}
- responseString =
- mapper.writeValueAsString(commonClassDao.getData(PolicyScopeType.class));
+ responseString = mapper.writeValueAsString(commonClassDao.getData(PolicyScopeType.class));
} else {
responseString = duplicateResponseString;
}
@@ -442,20 +433,23 @@ public class PolicyScopeDictionaryController {
}
@RequestMapping(value = {"/ps_dictionary/remove_PSType"}, method = {RequestMethod.POST})
- public void removePSTypeDictionary(HttpServletRequest request, HttpServletResponse response)
- throws IOException {
+ public void removePSTypeDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException {
DictionaryUtils utils = getDictionaryUtilsInstance();
utils.removeData(request, response, psTypeDatas, PolicyScopeType.class);
}
- @RequestMapping(value = {"/get_PSResourceDataByName"}, method = {RequestMethod.GET},
+ @RequestMapping(
+ value = {"/get_PSResourceDataByName"},
+ method = {RequestMethod.GET},
produces = MediaType.APPLICATION_JSON_VALUE)
public void getPSResourceEntityDataByName(HttpServletResponse response) {
DictionaryUtils utils = getDictionaryUtilsInstance();
utils.getDataByEntity(response, psResourceDatas, "name", PolicyScopeResource.class);
}
- @RequestMapping(value = {"/get_PSResourceData"}, method = {RequestMethod.GET},
+ @RequestMapping(
+ value = {"/get_PSResourceData"},
+ method = {RequestMethod.GET},
produces = MediaType.APPLICATION_JSON_VALUE)
public void getPSResourceEntityData(HttpServletResponse response) {
DictionaryUtils utils = getDictionaryUtilsInstance();
@@ -463,8 +457,8 @@ public class PolicyScopeDictionaryController {
}
@RequestMapping(value = {"/ps_dictionary/save_psResource"}, method = {RequestMethod.POST})
- public ModelAndView savePSResourceDictionary(HttpServletRequest request,
- HttpServletResponse response) throws IOException {
+ public ModelAndView savePSResourceDictionary(HttpServletRequest request, HttpServletResponse response)
+ throws IOException {
DictionaryUtils utils = getDictionaryUtilsInstance();
try {
boolean fromAPI = utils.isRequestFromAPI(request);
@@ -473,25 +467,21 @@ public class PolicyScopeDictionaryController {
JsonNode root = mapper.readTree(request.getReader());
PolicyScopeResource onapData;
if (fromAPI) {
- onapData = mapper.readValue(root.get(dictionaryFields).toString(),
- PolicyScopeResource.class);
+ onapData = mapper.readValue(root.get(dictionaryFields).toString(), PolicyScopeResource.class);
} else {
- onapData = mapper.readValue(root.get("psResourceDictionaryData").toString(),
- PolicyScopeResource.class);
+ onapData = mapper.readValue(root.get("psResourceDictionaryData").toString(), PolicyScopeResource.class);
}
- List<Object> duplicateData = commonClassDao.checkDuplicateEntry(onapData.getName(),
- "name", PolicyScopeResource.class);
+ List<Object> duplicateData =
+ commonClassDao.checkDuplicateEntry(onapData.getName(), "name", PolicyScopeResource.class);
boolean duplicateflag = false;
if (!duplicateData.isEmpty()) {
PolicyScopeResource data = (PolicyScopeResource) duplicateData.get(0);
- if (request.getParameter(operation) != null
- && "update".equals(request.getParameter(operation))) {
+ if (request.getParameter(operation) != null && "update".equals(request.getParameter(operation))) {
onapData.setId(data.getId());
} else if ((request.getParameter(operation) != null
&& !"update".equals(request.getParameter(operation)))
- || (request.getParameter(operation) == null
- && (data.getId() != onapData.getId()))) {
+ || (request.getParameter(operation) == null && (data.getId() != onapData.getId()))) {
duplicateflag = true;
}
}
@@ -502,8 +492,7 @@ public class PolicyScopeDictionaryController {
} else {
commonClassDao.update(onapData);
}
- responseString = mapper
- .writeValueAsString(commonClassDao.getData(PolicyScopeResource.class));
+ responseString = mapper.writeValueAsString(commonClassDao.getData(PolicyScopeResource.class));
} else {
responseString = duplicateResponseString;
}
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
index 17fce7142..b7b63a9e0 100644
--- 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
@@ -24,6 +24,7 @@ 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;
+
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
@@ -32,9 +33,11 @@ import java.io.ObjectOutputStream;
import java.net.URI;
import java.util.List;
import java.util.UUID;
+
import javax.script.SimpleBindings;
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;
@@ -93,8 +96,8 @@ public class PushPolicyController {
LOGGER.info("No request ID provided, sending generated ID: " + requestID);
}
LOGGER.info("Push policy Request to get the selectedPolicy : " + root.asText());
- String policyVersionName = policyScope.replace(".", File.separator) + File.separator
- + filePrefix + policyName;
+ String policyVersionName =
+ policyScope.replace(".", File.separator) + File.separator + filePrefix + policyName;
List<?> policyVersionObject =
commonClassDao.getDataById(PolicyVersion.class, policyNames, policyVersionName);
if (policyVersionObject != null) {
@@ -120,10 +123,10 @@ public class PushPolicyController {
}
private void addPolicyToGroup(String policyScope, String policyID, String policyName, String pdpGroup,
- HttpServletResponse response) {
+ HttpServletResponse response) {
StdPDPGroup selectedPDPGroup = null;
StdPDPPolicy selectedPolicy = null;
- //Get the selected PDP Group to push the policy
+ // Get the selected PDP Group to push the policy
try {
selectedPDPGroup = (StdPDPGroup) XACMLPapServlet.getPAPEngine().getGroup(pdpGroup);
} catch (PAPException e1) {
@@ -147,16 +150,15 @@ public class PushPolicyController {
params.put("scope", policyScope);
params.put(policyNames, policyName.substring(policyScope.length() + 1));
List<?> createPolicyQueryList = commonClassDao.getDataByQuery(createPolicyQuery, params);
- LOGGER.info("addPolicyToGroup:Total execution time to retrieve " + policyNames
- + " from PolicyEntity");
+ LOGGER.info("addPolicyToGroup:Total execution time to retrieve " + policyNames + " from PolicyEntity");
PolicyEntity policyEntity = null;
if (!createPolicyQueryList.isEmpty()) {
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");
+ .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(errorMsg, "unknownPolicy");
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
index 6e794d966..577870c70 100644
--- 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
@@ -23,11 +23,14 @@ package org.onap.policy.pap.xacml.rest.controller;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
+
import java.io.IOException;
import java.util.Date;
import java.util.List;
+
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
+
import org.onap.policy.pap.xacml.rest.util.DictionaryUtils;
import org.onap.policy.rest.dao.CommonClassDao;
import org.onap.policy.rest.jpa.RiskType;
@@ -66,14 +69,18 @@ public class SafePolicyController {
return DictionaryUtils.getDictionaryUtils();
}
- @RequestMapping(value = {"/get_RiskTypeDataByName"}, method = {RequestMethod.GET},
+ @RequestMapping(
+ value = {"/get_RiskTypeDataByName"},
+ method = {RequestMethod.GET},
produces = MediaType.APPLICATION_JSON_VALUE)
public void getRiskTypeDictionaryByNameEntityData(HttpServletResponse response) {
DictionaryUtils utils = getDictionaryUtilsInstance();
utils.getDataByEntity(response, riskTypeDatas, "name", RiskType.class);
}
- @RequestMapping(value = {"/get_RiskTypeData"}, method = {RequestMethod.GET},
+ @RequestMapping(
+ value = {"/get_RiskTypeData"},
+ method = {RequestMethod.GET},
produces = MediaType.APPLICATION_JSON_VALUE)
public void getRiskTypeDictionaryEntityData(HttpServletResponse response) {
DictionaryUtils utils = getDictionaryUtilsInstance();
@@ -81,8 +88,8 @@ public class SafePolicyController {
}
@RequestMapping(value = {"/sp_dictionary/save_riskType"}, method = {RequestMethod.POST})
- public ModelAndView saveRiskTypeDictionary(HttpServletRequest request,
- HttpServletResponse response) throws IOException {
+ public ModelAndView saveRiskTypeDictionary(HttpServletRequest request, HttpServletResponse response)
+ throws IOException {
DictionaryUtils utils = getDictionaryUtilsInstance();
try {
boolean fromAPI = utils.isRequestFromAPI(request);
@@ -92,27 +99,23 @@ public class SafePolicyController {
RiskType riskTypeData;
String userId = null;
if (fromAPI) {
- riskTypeData =
- mapper.readValue(root.get("dictionaryFields").toString(), RiskType.class);
+ riskTypeData = mapper.readValue(root.get("dictionaryFields").toString(), RiskType.class);
userId = "API";
} else {
- riskTypeData = mapper.readValue(root.get("riskTypeDictionaryData").toString(),
- RiskType.class);
+ riskTypeData = mapper.readValue(root.get("riskTypeDictionaryData").toString(), RiskType.class);
userId = root.get("userid").textValue();
}
UserInfo userInfo = utils.getUserInfo(userId);
- List<Object> duplicateData = commonClassDao
- .checkDuplicateEntry(riskTypeData.getRiskName(), "name", RiskType.class);
+ List<Object> duplicateData =
+ commonClassDao.checkDuplicateEntry(riskTypeData.getName(), "name", RiskType.class);
boolean duplicateflag = false;
if (!duplicateData.isEmpty()) {
RiskType data = (RiskType) duplicateData.get(0);
- if (request.getParameter(operation) != null
- && "update".equals(request.getParameter(operation))) {
+ if (request.getParameter(operation) != null && "update".equals(request.getParameter(operation))) {
riskTypeData.setId(data.getId());
} else if ((request.getParameter(operation) != null
&& !"update".equals(request.getParameter(operation)))
- || (request.getParameter(operation) == null
- && (data.getId() != riskTypeData.getId()))) {
+ || (request.getParameter(operation) == null && (data.getId() != riskTypeData.getId()))) {
duplicateflag = true;
}
}
@@ -142,30 +145,32 @@ public class SafePolicyController {
}
@RequestMapping(value = {"/sp_dictionary/remove_riskType"}, method = {RequestMethod.POST})
- public void removeRiskTypeDictionary(HttpServletRequest request, HttpServletResponse response)
- throws IOException {
+ public void removeRiskTypeDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException {
DictionaryUtils utils = getDictionaryUtilsInstance();
utils.removeData(request, response, riskTypeDatas, RiskType.class);
}
- @RequestMapping(value = {"/get_SafePolicyWarningDataByName"}, method = {RequestMethod.GET},
+ @RequestMapping(
+ value = {"/get_SafePolicyWarningDataByName"},
+ method = {RequestMethod.GET},
produces = MediaType.APPLICATION_JSON_VALUE)
public void getSafePolicyWarningEntityDataByName(HttpServletResponse response) {
DictionaryUtils utils = getDictionaryUtilsInstance();
utils.getDataByEntity(response, safePolicyWarningDatas, "name", SafePolicyWarning.class);
}
- @RequestMapping(value = {"/get_SafePolicyWarningData"}, method = {RequestMethod.GET},
+ @RequestMapping(
+ value = {"/get_SafePolicyWarningData"},
+ method = {RequestMethod.GET},
produces = MediaType.APPLICATION_JSON_VALUE)
public void getSafePolicyWarningeEntityData(HttpServletResponse response) {
DictionaryUtils utils = getDictionaryUtilsInstance();
utils.getData(response, safePolicyWarningDatas, SafePolicyWarning.class);
}
- @RequestMapping(value = {"/sp_dictionary/save_safePolicyWarning"},
- method = {RequestMethod.POST})
- public ModelAndView saveSafePolicyWarningDictionary(HttpServletRequest request,
- HttpServletResponse response) throws IOException {
+ @RequestMapping(value = {"/sp_dictionary/save_safePolicyWarning"}, method = {RequestMethod.POST})
+ public ModelAndView saveSafePolicyWarningDictionary(HttpServletRequest request, HttpServletResponse response)
+ throws IOException {
DictionaryUtils utils = getDictionaryUtilsInstance();
try {
boolean fromAPI = utils.isRequestFromAPI(request);
@@ -174,25 +179,22 @@ public class SafePolicyController {
JsonNode root = mapper.readTree(request.getReader());
SafePolicyWarning safePolicyWarning;
if (fromAPI) {
- safePolicyWarning = mapper.readValue(root.get("dictionaryFields").toString(),
- SafePolicyWarning.class);
+ safePolicyWarning = mapper.readValue(root.get("dictionaryFields").toString(), SafePolicyWarning.class);
} else {
- safePolicyWarning = mapper.readValue(root.get("safePolicyWarningData").toString(),
- SafePolicyWarning.class);
+ safePolicyWarning =
+ mapper.readValue(root.get("safePolicyWarningData").toString(), SafePolicyWarning.class);
}
- List<Object> duplicateData = commonClassDao.checkDuplicateEntry(
- safePolicyWarning.getName(), "name", SafePolicyWarning.class);
+ List<Object> duplicateData =
+ commonClassDao.checkDuplicateEntry(safePolicyWarning.getName(), "name", SafePolicyWarning.class);
boolean duplicateflag = false;
if (!duplicateData.isEmpty()) {
SafePolicyWarning data = (SafePolicyWarning) duplicateData.get(0);
- if (request.getParameter(operation) != null
- && "update".equals(request.getParameter(operation))) {
+ if (request.getParameter(operation) != null && "update".equals(request.getParameter(operation))) {
safePolicyWarning.setId(data.getId());
} else if ((request.getParameter(operation) != null
&& !"update".equals(request.getParameter(operation)))
- || (request.getParameter(operation) == null
- && (data.getId() != safePolicyWarning.getId()))) {
+ || (request.getParameter(operation) == null && (data.getId() != safePolicyWarning.getId()))) {
duplicateflag = true;
}
}
@@ -203,8 +205,7 @@ public class SafePolicyController {
} else {
commonClassDao.update(safePolicyWarning);
}
- responseString =
- mapper.writeValueAsString(commonClassDao.getData(SafePolicyWarning.class));
+ responseString = mapper.writeValueAsString(commonClassDao.getData(SafePolicyWarning.class));
} else {
responseString = duplicateResponseString;
}
@@ -219,10 +220,9 @@ public class SafePolicyController {
return null;
}
- @RequestMapping(value = {"/sp_dictionary/remove_SafePolicyWarning"},
- method = {RequestMethod.POST})
- public void removeSafePolicyWarningDictionary(HttpServletRequest request,
- HttpServletResponse response) throws IOException {
+ @RequestMapping(value = {"/sp_dictionary/remove_SafePolicyWarning"}, method = {RequestMethod.POST})
+ public void removeSafePolicyWarningDictionary(HttpServletRequest request, HttpServletResponse response)
+ throws IOException {
DictionaryUtils utils = getDictionaryUtilsInstance();
utils.removeData(request, response, safePolicyWarningDatas, SafePolicyWarning.class);
}
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
index bb42fb6aa..7e940a2a1 100644
--- 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
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP-PAP-REST
* ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017, 2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -18,5 +18,4 @@
* ============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
index 2688d7d3c..ee5c22f1c 100644
--- 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
@@ -22,7 +22,9 @@ package org.onap.policy.pap.xacml.rest.daoimpl;
import java.util.List;
import java.util.Map;
+
import javax.script.SimpleBindings;
+
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.Criteria;
@@ -51,10 +53,8 @@ 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;
@@ -78,14 +78,12 @@ public class CommonClassDaoImpl implements CommonClassDao {
try {
session.close();
} catch (Exception e) {
- LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW
- + "Error While Closing Connection/Statement" + e);
+ LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement" + e);
}
}
return data;
}
-
@SuppressWarnings({"rawtypes", "unchecked"})
@Override
public List<Object> getDataById(Class className, String columnName, String key) {
@@ -109,8 +107,7 @@ public class CommonClassDaoImpl implements CommonClassDao {
try {
session.close();
} catch (Exception e1) {
- LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW
- + "Error While Closing Connection/Statement" + e1);
+ LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement" + e1);
}
}
return data;
@@ -131,8 +128,7 @@ public class CommonClassDaoImpl implements CommonClassDao {
try {
session.close();
} catch (Exception e) {
- LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW
- + "Error While Closing Connection/Statement" + e);
+ LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement" + e);
}
}
return data;
@@ -146,14 +142,12 @@ public class CommonClassDaoImpl implements CommonClassDao {
session.persist(entity);
tx.commit();
} catch (Exception e) {
- LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW
- + "Error While Saving data to Table" + 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);
+ LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement" + e1);
}
}
@@ -167,20 +161,17 @@ public class CommonClassDaoImpl implements CommonClassDao {
session.delete(entity);
tx.commit();
} catch (Exception e) {
- LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW
- + "Error While Deleting data from Table" + 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);
+ LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement" + e1);
}
}
}
-
@Override
public void update(Object entity) {
Session session = sessionFactory.openSession();
@@ -189,20 +180,17 @@ public class CommonClassDaoImpl implements CommonClassDao {
session.update(entity);
tx.commit();
} catch (Exception e) {
- LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW
- + "Error While Updating data to Table" + 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);
+ LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement" + e1);
}
}
}
-
@SuppressWarnings({"unchecked", "rawtypes"})
@Override
public List<Object> checkDuplicateEntry(String value, String columnName, Class className) {
@@ -231,20 +219,18 @@ public class CommonClassDaoImpl implements CommonClassDao {
data = cr.list();
tx.commit();
} catch (Exception e) {
- LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW
- + "Error While Querying for Duplicate Entries for Table" + e + className);
+ 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);
+ LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement" + e1);
}
}
return data;
}
-
@SuppressWarnings("unchecked")
@Override
public List<Object> getDataByQuery(String query, SimpleBindings params) {
@@ -263,21 +249,18 @@ public class CommonClassDaoImpl implements CommonClassDao {
data = hbquery.list();
tx.commit();
} catch (Exception e) {
- LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW
- + "Error While Querying Database Table" + e);
+ LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Querying Database Table" + e);
throw e;
} finally {
try {
session.close();
} catch (HibernateException e1) {
- LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW
- + "Error While Closing Connection/Statement", 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();
@@ -287,19 +270,16 @@ public class CommonClassDaoImpl implements CommonClassDao {
hbquery.executeUpdate();
tx.commit();
} catch (Exception e) {
- LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW
- + "Error While Updating Database Table" + 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);
+ LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement" + e1);
}
}
}
-
@SuppressWarnings("rawtypes")
@Override
public Object getEntityItem(Class className, String columnName, String key) {
@@ -320,20 +300,17 @@ public class CommonClassDaoImpl implements CommonClassDao {
data = cr.list().get(0);
tx.commit();
} catch (Exception e) {
- LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW
- + "Error While Querying Database Table" + 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);
+ LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement" + e1);
}
}
return data;
}
-
@SuppressWarnings("unchecked")
@Override
public List<PolicyRoles> getUserRoles() {
@@ -355,20 +332,17 @@ public class CommonClassDaoImpl implements CommonClassDao {
rolesData = cr.add(disjunction).list();
tx.commit();
} catch (Exception e) {
- LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW
- + "Error While Querying PolicyRoles Table" + 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);
+ LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement" + e1);
}
}
return rolesData;
}
-
@SuppressWarnings("unchecked")
@Override
public void updateClAlarms(String clName, String alarms) {
@@ -384,14 +358,12 @@ public class CommonClassDaoImpl implements CommonClassDao {
session.update(closedloop);
tx.commit();
} catch (Exception e) {
- LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW
- + "Error While Updating ClosedLoops Table" + 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) {
@@ -407,14 +379,12 @@ public class CommonClassDaoImpl implements CommonClassDao {
session.update(closedloop);
tx.commit();
} catch (Exception e) {
- LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW
- + "Error While Updating ClosedLoops Table" + e);
+ LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Updating ClosedLoops Table" + e);
} finally {
session.close();
}
}
-
@SuppressWarnings("unchecked")
@Override
public void deleteAll() {
@@ -438,8 +408,8 @@ public class CommonClassDaoImpl implements CommonClassDao {
tx.commit();
} catch (Exception e) {
- LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW
- + "Error while deleting ClosedLoops from the table" + e);
+ LOGGER.error(
+ XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error while deleting ClosedLoops from the table" + e);
} finally {
session.close();
}
@@ -447,8 +417,7 @@ public class CommonClassDaoImpl implements CommonClassDao {
@SuppressWarnings({"unchecked"})
@Override
- public List<Object> checkExistingGroupListforUpdate(String groupListValue,
- String groupNameValue) {
+ public List<Object> checkExistingGroupListforUpdate(String groupListValue, String groupNameValue) {
Session session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();
List<Object> data = null;
@@ -461,23 +430,20 @@ public class CommonClassDaoImpl implements CommonClassDao {
tx.commit();
} catch (Exception e) {
LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW
- + "Error While Querying for Duplicate Entries for GroupPolicyScopeList Table"
- + e);
+ + "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);
+ LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement" + e1);
}
}
return data;
}
-
@Override
- public List<Object> getMultipleDataOnAddingConjunction(
- @SuppressWarnings("rawtypes") Class className, String columnName, List<String> data) {
+ public List<Object> getMultipleDataOnAddingConjunction(@SuppressWarnings("rawtypes") Class className,
+ String columnName, List<String> data) {
return null;
}
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
index f04be861b..cfae68091 100644
--- 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
@@ -21,6 +21,7 @@
package org.onap.policy.pap.xacml.rest.elk.client;
import com.google.gson.Gson;
+
import io.searchbox.client.JestClientFactory;
import io.searchbox.client.config.HttpClientConfig;
import io.searchbox.client.http.JestHttpClient;
@@ -28,6 +29,7 @@ import io.searchbox.core.Bulk;
import io.searchbox.core.Bulk.Builder;
import io.searchbox.core.BulkResult;
import io.searchbox.core.Index;
+
import java.io.ByteArrayInputStream;
import java.io.FileInputStream;
import java.io.InputStream;
@@ -43,6 +45,7 @@ import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;
+
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;
@@ -50,13 +53,12 @@ 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;
+
import org.onap.policy.common.logging.flexlogger.FlexLogger;
import org.onap.policy.common.logging.flexlogger.Logger;
import org.onap.policy.utils.PeCryptoUtils;
import org.onap.policy.xacml.util.XACMLPolicyScanner;
-
-
/**
* This code will deals with parsing the XACML content on reading from
* database(PolicyEntity, ConfigurationDataEntity and ActionBodyEntity tables)
@@ -126,54 +128,53 @@ public class ElasticSearchPolicyUpdate {
String policyEntityQuery = "Select * from PolicyEntity";
result = stmt.executeQuery(policyEntityQuery);
- while(result.next()){
+ 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+"\",");
+ if (policyName != null) {
+ policyDataString.append("\"policyName\":\"" + scope + "." + policyName + "\",");
}
String description = result.getString("description");
- if(description != null){
- policyDataString.append("\"policyDescription\":\""+description+"\",");
+ if (description != null) {
+ policyDataString.append("\"policyDescription\":\"" + description + "\",");
}
Object policyData = result.getString("policydata");
- if(scope != null){
- policyDataString.append("\"scope\":\""+scope+"\",");
+ 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_")){
+ if (policyWithScopeName.contains(".Config_")) {
policyDataString.append("\"policyType\":\"Config\",");
- if(policyWithScopeName.contains(".Config_Fault_")){
+ if (policyWithScopeName.contains(".Config_Fault_")) {
_type = "closedloop";
policyDataString.append("\"configPolicyType\":\"ClosedLoop_Fault\",");
- }else if(policyWithScopeName.contains(".Config_PM_")){
+ } else if (policyWithScopeName.contains(".Config_PM_")) {
_type = "closedloop";
policyDataString.append("\"configPolicyType\":\"ClosedLoop_PM\",");
- }else{
+ } else {
_type = "config";
policyDataString.append("\"configPolicyType\":\"Base\",");
}
- }else if(policyWithScopeName.contains(".Action_")){
+ } else if (policyWithScopeName.contains(".Action_")) {
_type = "action";
policyDataString.append("\"policyType\":\"Action\",");
- }else if(policyWithScopeName.contains(".Decision_")){
+ } else if (policyWithScopeName.contains(".Decision_")) {
_type = "decision";
policyDataString.append("\"policyType\":\"Decision\",");
}
- if(!"decision".equals(_type)){
- if(configurationdataid != null){
+ if (!"decision".equals(_type)) {
+ if (configurationdataid != null) {
updateConfigData(conn, configurationdataid, policyDataString);
}
- if(actionbodyid != null){
+ if (actionbodyid != null) {
updateActionData(conn, actionbodyid, policyDataString);
}
}
@@ -181,72 +182,72 @@ public class ElasticSearchPolicyUpdate {
String _id = policyWithScopeName;
String dataString = constructPolicyData(policyData, policyDataString);
- dataString = dataString.substring(0, dataString.length()-1);
+ dataString = dataString.substring(0, dataString.length() - 1);
dataString = dataString.trim().replace(System.getProperty("line.separator"), "") + "}";
dataString = dataString.replace("null", "\"\"");
dataString = dataString.replaceAll("\n", "");
- try{
+ try {
Gson gson = new Gson();
gson.fromJson(dataString, Object.class);
- }catch(Exception e){
+ } catch (Exception e) {
LOGGER.error(e);
continue;
}
- if("config".equals(_type)){
+ if ("config".equals(_type)) {
listIndex.add(new Index.Builder(dataString).index("policy").type("config").id(_id).build());
- }else if("closedloop".equals(_type)){
+ } else if ("closedloop".equals(_type)) {
listIndex.add(new Index.Builder(dataString).index("policy").type("closedloop").id(_id).build());
- }else if("action".equals(_type)){
+ } else if ("action".equals(_type)) {
listIndex.add(new Index.Builder(dataString).index("policy").type("action").id(_id).build());
- }else if("decision".equals(_type)){
+ } 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++){
+ for (int i = 0; i < listIndex.size(); i++) {
bulk.addAction(listIndex.get(i));
}
BulkResult searchResult = client.execute(bulk.build());
- if(searchResult.isSucceeded()){
+ if (searchResult.isSucceeded()) {
LOGGER.debug("Success");
- }else{
+ } else {
LOGGER.error("Failure");
}
} catch (Exception e) {
- LOGGER.error("Exception Occured while performing database Operation for Elastic Search Policy Upgrade"+e);
- }finally{
- if(result != null){
- try {
- result.close();
- } catch (Exception e) {
- LOGGER.error("Exception Occured while closing the resultset"+e);
- }
+ LOGGER.error("Exception Occured while performing database Operation for Elastic Search Policy Upgrade" + e);
+ } finally {
+ if (result != null) {
+ try {
+ result.close();
+ } catch (Exception e) {
+ LOGGER.error("Exception Occured while closing the resultset" + e);
}
- if(stmt != null){
- try {
- stmt.close();
- } catch (Exception e) {
- LOGGER.error("Exception Occured while closing the statement"+e);
- }
+ }
+ if (stmt != null) {
+ try {
+ stmt.close();
+ } catch (Exception e) {
+ LOGGER.error("Exception Occured while closing the statement" + e);
}
- if(conn != null){
+ }
+ if (conn != null) {
try {
conn.close();
} catch (Exception e) {
- LOGGER.error("Exception Occured while closing the connection"+e);
+ LOGGER.error("Exception Occured while closing the connection" + e);
}
}
}
}
- public static String constructPolicyData(Object policyContent, StringBuilder policyDataString){
+ public static String constructPolicyData(Object policyContent, StringBuilder policyDataString) {
InputStream stream = new ByteArrayInputStream(policyContent.toString().getBytes(StandardCharsets.UTF_8));
Object policyData = XACMLPolicyScanner.readPolicy(stream);
- if(policyData instanceof PolicyType){
+ if (policyData instanceof PolicyType) {
PolicyType policy = (PolicyType) policyData;
TargetType target = policy.getTarget();
if (target != null) {
@@ -278,19 +279,19 @@ public class ElasticSearchPolicyUpdate {
String attributeId = designator.getAttributeId();
// First match in the target is OnapName, so set that value.
if ("ONAPName".equals(attributeId)) {
- policyDataString.append("\"onapName\":\""+value+"\",");
+ policyDataString.append("\"onapName\":\"" + value + "\",");
}
- if ("RiskType".equals(attributeId)){
- policyDataString.append("\"riskType\":\""+value+"\",");
+ if ("RiskType".equals(attributeId)) {
+ policyDataString.append("\"riskType\":\"" + value + "\",");
}
- if ("RiskLevel".equals(attributeId)){
- policyDataString.append("\"riskLevel\":\""+value+"\",");
+ if ("RiskLevel".equals(attributeId)) {
+ policyDataString.append("\"riskLevel\":\"" + value + "\",");
}
- if ("guard".equals(attributeId)){
- policyDataString.append("\"guard\":\""+value+"\",");
+ if ("guard".equals(attributeId)) {
+ policyDataString.append("\"guard\":\"" + value + "\",");
}
- if ("ConfigName".equals(attributeId)){
- policyDataString.append("\"configName\":\""+value+"\",");
+ if ("ConfigName".equals(attributeId)) {
+ policyDataString.append("\"configName\":\"" + value + "\",");
}
}
}
@@ -303,79 +304,82 @@ public class ElasticSearchPolicyUpdate {
return policyDataString.toString();
}
- private static void updateConfigData(Connection conn, String configurationdataid, StringBuilder policyDataString) throws Exception {
-
- PreparedStatement pstmt = null;
- ResultSet configResult = null;
- try {
- String configEntityQuery = "Select * from ConfigurationDataEntity where configurationDataId = ?";
- pstmt = null;
- pstmt = conn.prepareStatement(configEntityQuery);
- pstmt.setString(1, configurationdataid);
- configResult = pstmt.executeQuery();
- while(configResult.next()){
- String configBody = configResult.getString("configbody");
- String configType = configResult.getString("configtype");
- if(configBody!=null){
- configBody = configBody.replace("null", "\"\"");
- configBody= configBody.replace("\"", "\\\"");
- policyDataString.append("\"jsonBodyData\":\""+configBody+"\",\"configType\":\""+configType+"\",");
- }
+ private static void updateConfigData(Connection conn, String configurationdataid, StringBuilder policyDataString)
+ throws Exception {
+
+ PreparedStatement pstmt = null;
+ ResultSet configResult = null;
+ try {
+ String configEntityQuery = "Select * from ConfigurationDataEntity where configurationDataId = ?";
+ pstmt = null;
+ pstmt = conn.prepareStatement(configEntityQuery);
+ pstmt.setString(1, configurationdataid);
+ configResult = pstmt.executeQuery();
+ while (configResult.next()) {
+ String configBody = configResult.getString("configbody");
+ String configType = configResult.getString("configtype");
+ if (configBody != null) {
+ configBody = configBody.replace("null", "\"\"");
+ configBody = configBody.replace("\"", "\\\"");
+ policyDataString
+ .append("\"jsonBodyData\":\"" + configBody + "\",\"configType\":\"" + configType + "\",");
}
- } catch(Exception e) {
- LOGGER.error("Exception Occured while updating configData"+e);
- throw(e);
- } finally {
- if(configResult != null){
- try {
- configResult.close();
- } catch (Exception e) {
- LOGGER.error("Exception Occured while closing the ResultSet"+e);
- }
+ }
+ } catch (Exception e) {
+ LOGGER.error("Exception Occured while updating configData" + e);
+ throw (e);
+ } finally {
+ if (configResult != null) {
+ try {
+ configResult.close();
+ } catch (Exception e) {
+ LOGGER.error("Exception Occured while closing the ResultSet" + e);
}
- if(pstmt != null){
- try {
- pstmt.close();
- } catch (Exception e) {
- LOGGER.error("Exception Occured while closing the PreparedStatement"+e);
- }
+ }
+ if (pstmt != null) {
+ try {
+ pstmt.close();
+ } catch (Exception e) {
+ LOGGER.error("Exception Occured while closing the PreparedStatement" + e);
}
- }
+ }
+ }
}
- private static void updateActionData(Connection conn, String actionbodyid, StringBuilder policyDataString) throws Exception {
-
- PreparedStatement pstmt = null;
- ResultSet actionResult = null;
- try {
- String actionEntityQuery = "Select * from ActionBodyEntity where actionBodyId = ?";
- pstmt = conn.prepareStatement(actionEntityQuery);
- pstmt.setString(1, actionbodyid);
- actionResult = pstmt.executeQuery();
- while(actionResult.next()){
- String actionBody = actionResult.getString("actionbody");
- actionBody = actionBody.replace("null", "\"\"");
- actionBody = actionBody.replace("\"", "\\\"");
- policyDataString.append("\"jsonBodyData\":\""+actionBody+"\",");
- }
- } catch(Exception e) {
- LOGGER.error("Exception Occured while updating actionData"+e);
- throw(e);
- } finally {
- if(actionResult != null){
- try {
- actionResult.close();
- } catch (Exception e) {
- LOGGER.error("Exception Occured while closing the ResultSet"+e);
- }
+ private static void updateActionData(Connection conn, String actionbodyid, StringBuilder policyDataString)
+ throws Exception {
+
+ PreparedStatement pstmt = null;
+ ResultSet actionResult = null;
+ try {
+ String actionEntityQuery = "Select * from ActionBodyEntity where actionBodyId = ?";
+ pstmt = conn.prepareStatement(actionEntityQuery);
+ pstmt.setString(1, actionbodyid);
+ actionResult = pstmt.executeQuery();
+ while (actionResult.next()) {
+ String actionBody = actionResult.getString("actionbody");
+ actionBody = actionBody.replace("null", "\"\"");
+ actionBody = actionBody.replace("\"", "\\\"");
+ policyDataString.append("\"jsonBodyData\":\"" + actionBody + "\",");
+ }
+ } catch (Exception e) {
+ LOGGER.error("Exception Occured while updating actionData" + e);
+ throw (e);
+ } finally {
+ if (actionResult != null) {
+ try {
+ actionResult.close();
+ } catch (Exception e) {
+ LOGGER.error("Exception Occured while closing the ResultSet" + e);
}
- if(pstmt != null){
- try {
- pstmt.close();
- } catch (Exception e) {
- LOGGER.error("Exception Occured while closing the PreparedStatement"+e);
- }
+ }
+ if (pstmt != null) {
+ try {
+ pstmt.close();
+ } catch (Exception e) {
+ LOGGER.error("Exception Occured while closing the PreparedStatement" + e);
}
- }
+ }
+ }
}
}
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
index d64b71763..d3f7f4dea 100644
--- 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
@@ -20,9 +20,10 @@
package org.onap.policy.pap.xacml.rest.elk.client;
-
import io.searchbox.client.JestResult;
+
import java.util.Map;
+
import org.onap.policy.rest.adapter.PolicyRestAdapter;
public interface ElkConnector {
@@ -44,8 +45,7 @@ public interface ElkConnector {
public boolean delete(PolicyRestAdapter policyData) throws IllegalStateException;
- public JestResult search(PolicyIndexType type, String text)
- throws IllegalStateException, IllegalArgumentException;
+ public JestResult search(PolicyIndexType type, String text) throws IllegalStateException, IllegalArgumentException;
public JestResult search(PolicyIndexType type, String text, Map<String, String> searchKeyValue)
throws IllegalStateException, IllegalArgumentException;
@@ -54,8 +54,7 @@ public interface ElkConnector {
public ElkConnector singleton = new ElkConnectorImpl();
- public static PolicyIndexType toPolicyIndexType(String policyName)
- throws IllegalArgumentException {
+ public static PolicyIndexType toPolicyIndexType(String policyName) throws IllegalArgumentException {
if (policyName == null)
throw new IllegalArgumentException("Unsupported NULL policy name conversion");
@@ -76,8 +75,7 @@ public interface ElkConnector {
} else if (policyName.startsWith("Config")) {
return PolicyIndexType.config;
} else {
- throw new IllegalArgumentException(
- "Unsupported policy name conversion to index: " + policyName);
+ 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
index 6bbe033a3..4d84526a5 100644
--- 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
@@ -32,9 +32,11 @@ import io.searchbox.core.Search.Builder;
import io.searchbox.indices.IndicesExists;
import io.searchbox.indices.type.TypeExist;
import io.searchbox.params.Parameters;
+
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;
@@ -56,8 +58,7 @@ public class ElkConnectorImpl implements ElkConnector {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("ENTER: -");
}
- HttpClientConfig jestClientConfig =
- new HttpClientConfig.Builder(ELK_URL).multiThreaded(true).build();
+ HttpClientConfig jestClientConfig = new HttpClientConfig.Builder(ELK_URL).multiThreaded(true).build();
jestFactory.setHttpClientConfig(jestClientConfig);
jestClient = jestFactory.getObject();
}
@@ -68,8 +69,7 @@ public class ElkConnectorImpl implements ElkConnector {
}
try {
- Action<JestResult> typeQuery =
- new TypeExist.Builder(ELK_INDEX_POLICY).addType(type.toString()).build();
+ Action<JestResult> typeQuery = new TypeExist.Builder(ELK_INDEX_POLICY).addType(type.toString()).build();
JestResult result = jestClient.execute(typeQuery);
if (LOGGER.isInfoEnabled()) {
@@ -80,9 +80,7 @@ public class ElkConnectorImpl implements ElkConnector {
}
return result.isSucceeded();
} catch (IOException e) {
- LOGGER.warn(
- "Error checking type existance of " + type.toString() + ": " + e.getMessage(),
- e);
+ LOGGER.warn("Error checking type existance of " + type.toString() + ": " + e.getMessage(), e);
throw e;
}
}
@@ -100,9 +98,7 @@ public class ElkConnectorImpl implements ElkConnector {
}
return result.isSucceeded();
} catch (IOException e) {
- LOGGER.warn(
- "Error checking index existance of " + ELK_INDEX_POLICY + ": " + e.getMessage(),
- e);
+ LOGGER.warn("Error checking index existance of " + ELK_INDEX_POLICY + ": " + e.getMessage(), e);
throw e;
}
}
@@ -112,8 +108,7 @@ public class ElkConnectorImpl implements ElkConnector {
}
@Override
- public JestResult search(PolicyIndexType type, String text)
- throws IllegalStateException, IllegalArgumentException {
+ public JestResult search(PolicyIndexType type, String text) throws IllegalStateException, IllegalArgumentException {
if (LOGGER.isTraceEnabled()) {
LOGGER.trace("ENTER: " + text);
}
@@ -129,9 +124,8 @@ public class ElkConnectorImpl implements ElkConnector {
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);
+ 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()) {
@@ -148,24 +142,21 @@ public class ElkConnectorImpl implements ElkConnector {
try {
result = jestClient.execute(search);
} catch (IOException ioe) {
- LOGGER.warn(
- XACMLErrorConstants.ERROR_SYSTEM_ERROR + ":" + search + ": " + ioe.getMessage(),
- 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());
+ 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());
+ LOGGER.warn(XACMLErrorConstants.ERROR_PROCESS_FLOW + ":" + result.getResponseCode() + ": "
+ + search.getURI() + ":" + result.getPathToResult() + ":" + result.getJsonString() + ":"
+ + result.getErrorMessage());
}
String errorMessage = result.getErrorMessage();
@@ -173,24 +164,19 @@ public class ElkConnectorImpl implements ElkConnector {
String xMessage;
if (errorMessage.contains("TokenMgrError")) {
int indexError = errorMessage.lastIndexOf("TokenMgrError");
- xMessage = "Invalid Search Expression. Details: "
- + errorMessage.substring(indexError);
+ 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);
+ 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);
+ 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);
+ 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);
+ xMessage = "Invalid Search Expression. Details: " + errorMessage.substring(indexError);
} else {
xMessage = result.getErrorMessage();
}
@@ -201,7 +187,6 @@ public class ElkConnectorImpl implements ElkConnector {
return result;
}
-
@Override
public JestResult search(PolicyIndexType type, String text, Map<String, String> filter_s)
throws IllegalStateException, IllegalArgumentException {
@@ -218,8 +203,8 @@ public class ElkConnectorImpl implements ElkConnector {
}
String matches_s = "";
- matches_s = "{\n" + " \"size\" : " + ElkConnectorImpl.QUERY_MAXRECORDS + ",\n"
- + " \"query\": {\n" + " \"bool\" : {\n" + " \"must\" : [";
+ matches_s = "{\n" + " \"size\" : " + ElkConnectorImpl.QUERY_MAXRECORDS + ",\n" + " \"query\": {\n"
+ + " \"bool\" : {\n" + " \"must\" : [";
String match_params = "";
boolean first = true;
@@ -230,8 +215,7 @@ public class ElkConnectorImpl implements ElkConnector {
match_params = "\"match\" : {\"" + key + "\" : \"" + value + "\" }},";
first = false;
} else {
- match_params =
- match_params + "{\"match\" : { \"" + key + "\" : \"" + value + "\" } },";
+ match_params = match_params + "{\"match\" : { \"" + key + "\" : \"" + value + "\" } },";
}
}
if (match_params.endsWith(",")) {
@@ -271,24 +255,21 @@ public class ElkConnectorImpl implements ElkConnector {
try {
result = jestClient.execute(search);
} catch (IOException ioe) {
- LOGGER.warn(
- XACMLErrorConstants.ERROR_SYSTEM_ERROR + ":" + search + ": " + ioe.getMessage(),
- 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());
+ 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());
+ LOGGER.warn(XACMLErrorConstants.ERROR_PROCESS_FLOW + ":" + result.getResponseCode() + ": "
+ + search.getURI() + ":" + result.getPathToResult() + ":" + result.getJsonString() + ":"
+ + result.getErrorMessage());
}
String errorMessage = result.getErrorMessage();
@@ -296,24 +277,19 @@ public class ElkConnectorImpl implements ElkConnector {
String xMessage = errorMessage;
if (errorMessage.contains("TokenMgrError")) {
int indexError = errorMessage.lastIndexOf("TokenMgrError");
- xMessage = "Invalid Search Expression. Details: "
- + errorMessage.substring(indexError);
+ 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);
+ 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);
+ 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);
+ 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);
+ xMessage = "Invalid Search Expression. Details: " + errorMessage.substring(indexError);
} else {
xMessage = result.getErrorMessage();
}
@@ -347,22 +323,20 @@ public class ElkConnectorImpl implements ElkConnector {
}
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();
+ 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("ElkConnector: OK: PUT operation of " + "->" + ": " + "success="
- + result.isSucceeded() + "[" + result.getResponseCode() + ":"
- + result.getPathToResult() + "]" + System.lineSeparator()
+ LOGGER.info("ElkConnector: OK: PUT operation of " + "->" + ": " + "success=" + result.isSucceeded()
+ + "[" + result.getResponseCode() + ":" + result.getPathToResult() + "]" + System.lineSeparator()
+ result.getJsonString());
} else {
if (LOGGER.isWarnEnabled())
- LOGGER.warn("ElkConnector: FAILURE: PUT operation of " + "->" + ": " + "success="
- + result.isSucceeded() + "[" + result.getResponseCode() + ":"
- + result.getPathToResult() + "]" + System.lineSeparator()
+ LOGGER.warn("ElkConnector: FAILURE: PUT operation of " + "->" + ": " + "success=" + result.isSucceeded()
+ + "[" + result.getResponseCode() + ":" + result.getPathToResult() + "]" + System.lineSeparator()
+ result.getJsonString());
}
@@ -387,31 +361,29 @@ public class ElkConnectorImpl implements ElkConnector {
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");
+ 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();
+ 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);
+ 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());
+ 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());
+ LOGGER.warn("FAILURE: DELETE operation of " + indexType + ":" + policyData.getNewFileName() + ": "
+ + "success=" + result.isSucceeded() + "[" + result.getResponseCode() + ":"
+ + result.getPathToResult() + "]" + System.lineSeparator() + result.getJsonString());
}
return result.isSucceeded();
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
index 2b0c94bf3..cd3fc4f0c 100644
--- 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
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP-PAP-REST
* ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017, 2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -17,17 +17,31 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.policy.pap.xacml.rest.elk.client;
-public class Pair<L,R> {
+public class Pair<L, R> {
private L left;
private R right;
- public Pair(L l, R r){
+
+ 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;
}
- 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
index 988640ca6..70964c487 100644
--- 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
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP-PAP-REST
* ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017, 2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -17,6 +17,7 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.policy.pap.xacml.rest.elk.client;
import java.util.ArrayList;
@@ -46,14 +47,14 @@ public class PolicyElasticData {
private Map<?, ?> description;
private Map<?, ?> attributeFields;
- //Safe Policy
+ // Safe Policy
private String policyScope;
private String providerComboBox;
private String riskType;
private String riskLevel;
private String guard;
private String ttlDate;
- private Map<String,String> matching;
+ private Map<String, String> matching;
private List<Object> triggerSignatures;
private List<Object> symptomSignatures;
@@ -62,39 +63,39 @@ public class PolicyElasticData {
public String gocServerScope;
private String supressionType;
- //MicroSerice
+ // MicroSerice
private String serviceType;
private String uuid;
private String location;
private String priority;
private String msLocation;
- //BRMS Policies
+ // BRMS Policies
private String ruleName;
- private Map<String,String> brmsParamBody;
+ private Map<String, String> brmsParamBody;
private String brmsController;
private List<String> brmsDependency;
- private LinkedHashMap<?, ?> ruleData;
- private LinkedHashMap<?,?> ruleListData;
- private Map<String,String> drlRuleAndUIParams;
+ private LinkedHashMap<?, ?> ruleData;
+ private LinkedHashMap<?, ?> ruleListData;
+ private Map<String, String> drlRuleAndUIParams;
- //ClosedLoop
+ // ClosedLoop
private String clearTimeOut;
private String trapMaxAge;
private String verificationclearTimeOut;
- public Map<String , String> dynamicLayoutMap;
+ public Map<String, String> dynamicLayoutMap;
- //FireWall
+ // FireWall
private String fwPolicyType;
private List<Object> fwattributes;
private String parentForChild;
private String securityZone;
- //Action & Decision
+ // Action & Decision
private String ruleCombiningAlgId;
- private Map<String,String> dynamicFieldConfigAttributes;
- private Map<String,String> dynamicSettingsMap;
- private Map<String,String> dropDownMap;
+ private Map<String, String> dynamicFieldConfigAttributes;
+ private Map<String, String> dynamicSettingsMap;
+ private Map<String, String> dropDownMap;
private String actionPerformer;
private String actionAttribute;
private List<String> dynamicRuleAlgorithmLabels;
@@ -117,15 +118,15 @@ public class PolicyElasticData {
this.policyType = policyData.getPolicyType();
this.configPolicyType = policyData.getConfigPolicyType();
this.configBodyData = policyData.getConfigBodyData();
- this.policyName = policyData.getNewFileName();
- this.policyDescription = policyData.getPolicyDescription();
+ 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")){
+ if (configPolicyType.startsWith("ClosedLoop")) {
this.jsonBodyData = jsonBody;
- }else{
+ } else {
this.jsonBodyData = policyData.getJsonBodyData();
}
@@ -134,12 +135,12 @@ public class PolicyElasticData {
this.description = policyData.getDescription();
this.attributeFields = policyData.getAttributeFields();
- //Safe Policy
+ // Safe Policy
this.policyScope = policyData.getPolicyScope();
this.providerComboBox = policyData.getProviderComboBox();
this.riskType = policyData.getRiskType();
this.riskLevel = policyData.getRiskLevel();
- this.guard = policyData.getGuard();
+ this.guard = policyData.getGuard();
this.ttlDate = policyData.getTtlDate();
this.matching = policyData.getMatching();
@@ -150,14 +151,14 @@ public class PolicyElasticData {
this.gocServerScope = policyData.getGocServerScope();
this.supressionType = policyData.getSupressionType();
- //MicroSerice
+ // MicroSerice
this.serviceType = policyData.getServiceType();
this.uuid = policyData.getUuid();
this.location = policyData.getLocation();
this.priority = policyData.getPriority();
this.msLocation = policyData.getMsLocation();
- //BRMS Policies
+ // BRMS Policies
this.ruleName = policyData.getRuleName();
this.brmsParamBody = policyData.getBrmsParamBody();
this.brmsController = policyData.getBrmsController();
@@ -166,19 +167,19 @@ public class PolicyElasticData {
this.ruleListData = policyData.getRuleListData();
this.drlRuleAndUIParams = policyData.getDrlRuleAndUIParams();
- //ClosedLoop
+ // ClosedLoop
this.clearTimeOut = policyData.getClearTimeOut();
this.trapMaxAge = policyData.getTrapMaxAge();
this.verificationclearTimeOut = policyData.getVerificationclearTimeOut();
this.dynamicLayoutMap = policyData.getDynamicLayoutMap();
- //FireWall
+ // FireWall
this.fwPolicyType = policyData.getFwPolicyType();
this.fwattributes = policyData.getFwattributes();
this.parentForChild = policyData.getParentForChild();
this.securityZone = policyData.getSecurityZone();
- //Action & Decision
+ // Action & Decision
this.ruleCombiningAlgId = policyData.getRuleCombiningAlgId();
this.dynamicFieldConfigAttributes = policyData.getDynamicFieldConfigAttributes();
this.dynamicSettingsMap = policyData.getDynamicSettingsMap();
@@ -204,21 +205,27 @@ public class PolicyElasticData {
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;
}
@@ -226,42 +233,55 @@ public class PolicyElasticData {
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 Map<?, ?> getServiceTypePolicyName() {
return serviceTypePolicyName;
}
@@ -293,318 +313,423 @@ public class PolicyElasticData {
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<String, String> getMatching() {
return matching;
}
+
public void setMatching(Map<String, String> matching) {
this.matching = matching;
}
+
public List<Object> getTriggerSignatures() {
return triggerSignatures;
}
+
public void setTriggerSignatures(ArrayList<Object> triggerSignatures) {
this.triggerSignatures = triggerSignatures;
}
+
public List<Object> getSymptomSignatures() {
return symptomSignatures;
}
+
public void setSymptomSignatures(ArrayList<Object> 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<String, String> getBrmsParamBody() {
return brmsParamBody;
}
+
public void setBrmsParamBody(Map<String, String> brmsParamBody) {
this.brmsParamBody = brmsParamBody;
}
+
public String getBrmsController() {
return brmsController;
}
+
public void setBrmsController(String brmsController) {
this.brmsController = brmsController;
}
+
public List<String> getBrmsDependency() {
return brmsDependency;
}
+
public void setBrmsDependency(List<String> brmsDependency) {
this.brmsDependency = brmsDependency;
}
+
public Map<?, ?> getRuleData() {
return ruleData;
}
+
public void setRuleData(LinkedHashMap<?, ?> ruleData) {
this.ruleData = ruleData;
}
+
public Map<?, ?> getRuleListData() {
return ruleListData;
}
+
public void setRuleListData(LinkedHashMap<?, ?> ruleListData) {
this.ruleListData = ruleListData;
}
+
public Map<String, String> getDrlRuleAndUIParams() {
return drlRuleAndUIParams;
}
+
public void setDrlRuleAndUIParams(Map<String, String> 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<String, String> getDynamicLayoutMap() {
return dynamicLayoutMap;
}
+
public void setDynamicLayoutMap(Map<String, String> dynamicLayoutMap) {
this.dynamicLayoutMap = dynamicLayoutMap;
}
+
public String getFwPolicyType() {
return fwPolicyType;
}
+
public void setFwPolicyType(String fwPolicyType) {
this.fwPolicyType = fwPolicyType;
}
+
public List<Object> getFwattributes() {
return fwattributes;
}
+
public void setFwattributes(ArrayList<Object> 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<String, String> getDynamicFieldConfigAttributes() {
return dynamicFieldConfigAttributes;
}
+
public void setDynamicFieldConfigAttributes(Map<String, String> dynamicFieldConfigAttributes) {
this.dynamicFieldConfigAttributes = dynamicFieldConfigAttributes;
}
+
public Map<String, String> getDynamicSettingsMap() {
return dynamicSettingsMap;
}
+
public void setDynamicSettingsMap(Map<String, String> dynamicSettingsMap) {
this.dynamicSettingsMap = dynamicSettingsMap;
}
+
public Map<String, String> getDropDownMap() {
return dropDownMap;
}
+
public void setDropDownMap(Map<String, String> 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<String> getDynamicRuleAlgorithmLabels() {
return dynamicRuleAlgorithmLabels;
}
+
public void setDynamicRuleAlgorithmLabels(List<String> dynamicRuleAlgorithmLabels) {
this.dynamicRuleAlgorithmLabels = dynamicRuleAlgorithmLabels;
}
+
public List<String> getDynamicRuleAlgorithmCombo() {
return dynamicRuleAlgorithmCombo;
}
+
public void setDynamicRuleAlgorithmCombo(List<String> dynamicRuleAlgorithmCombo) {
this.dynamicRuleAlgorithmCombo = dynamicRuleAlgorithmCombo;
}
+
public List<String> getDynamicRuleAlgorithmField1() {
return dynamicRuleAlgorithmField1;
}
+
public void setDynamicRuleAlgorithmField1(List<String> dynamicRuleAlgorithmField1) {
this.dynamicRuleAlgorithmField1 = dynamicRuleAlgorithmField1;
}
+
public List<String> getDynamicRuleAlgorithmField2() {
return dynamicRuleAlgorithmField2;
}
+
public void setDynamicRuleAlgorithmField2(List<String> dynamicRuleAlgorithmField2) {
this.dynamicRuleAlgorithmField2 = dynamicRuleAlgorithmField2;
}
+
public List<Object> getDynamicVariableList() {
return dynamicVariableList;
}
+
public void setDynamicVariableList(List<Object> dynamicVariableList) {
this.dynamicVariableList = dynamicVariableList;
}
+
public List<String> getDataTypeList() {
return dataTypeList;
}
+
public void setDataTypeList(List<String> 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;
}
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
index 50965bd2b..48dc46c1b 100644
--- 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
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP-PAP-REST
* ================================================================================
- * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -17,8 +17,15 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.policy.pap.xacml.rest.elk.client;
+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;
import java.io.IOException;
import java.io.PrintWriter;
@@ -41,22 +48,22 @@ 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.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.DcaeUuid;
import org.onap.policy.rest.jpa.DecisionSettings;
import org.onap.policy.rest.jpa.DescriptiveScope;
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.OnapName;
-import org.onap.policy.rest.jpa.PEPOptions;
+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.VnfType;
+import org.onap.policy.rest.jpa.VsclAction;
import org.onap.policy.rest.jpa.VarbindDictionary;
import org.onap.policy.utils.PolicyUtils;
import org.onap.policy.xacml.api.XACMLErrorConstants;
@@ -66,24 +73,14 @@ 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{
+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
+ enum Mode {
+ attribute, onapName, actionPolicy, brmsParam, pepOptions, clSite, clService, clVarbind, clVnf, clVSCL, decision, fwTerm, msDCAEUUID, msConfigName, msLocation, msModels, psGroupPolicy, safeRisk, safePolicyWarning
}
protected static final HashMap<String, String> name2jsonPath = new HashMap<String, String>() {
@@ -108,7 +105,7 @@ public class PolicyElasticSearchController{
}
public ElkConnector.PolicyIndexType toPolicyIndexType(String type) throws IllegalArgumentException {
- if (type == null || type.isEmpty()){
+ if (type == null || type.isEmpty()) {
return PolicyIndexType.all;
}
return PolicyIndexType.valueOf(type);
@@ -154,11 +151,10 @@ public class PolicyElasticSearchController{
return success;
}
-
- @RequestMapping(value="/searchPolicy", method= RequestMethod.POST)
+ @RequestMapping(value = "/searchPolicy", method = RequestMethod.POST)
public void searchPolicy(HttpServletRequest request, HttpServletResponse response) {
- try{
- String message="";
+ try {
+ String message = "";
boolean result = false;
boolean policyResult = false;
boolean validationCheck = true;
@@ -168,16 +164,16 @@ public class PolicyElasticSearchController{
PolicyElasticSearchController controller = new PolicyElasticSearchController();
Map<String, String> searchKeyValue = new HashMap<>();
List<String> policyList = new ArrayList<>();
- if(request.getParameter("policyName") != null){
+ if (request.getParameter("policyName") != null) {
String policyName = request.getParameter("policyName");
policyData.setNewFileName(policyName);
- if("delete".equalsIgnoreCase(request.getParameter(action))){
+ if ("delete".equalsIgnoreCase(request.getParameter(action))) {
result = controller.deleteElk(policyData);
- }else{
+ } else {
result = controller.updateElk(policyData);
}
}
- if("search".equalsIgnoreCase(request.getParameter(action))){
+ if ("search".equalsIgnoreCase(request.getParameter(action))) {
try {
JsonNode root = mapper.readTree(request.getReader());
SearchData searchData = mapper.readValue(root.get("searchdata").toString(), SearchData.class);
@@ -186,111 +182,117 @@ public class PolicyElasticSearchController{
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){
+ 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())){
- if(!PolicyUtils.policySpecialCharValidator(entry[1]).contains(success)){
- message = "The Descriptive Scope Dictionary value contains space and it is invalid for Search : "+entry[1];
+ if (searchData.getPolicyType() != null
+ && "closedLoop".equals(searchData.getPolicyType())) {
+ if (!PolicyUtils.policySpecialCharValidator(entry[1]).contains(success)) {
+ message =
+ "The Descriptive Scope Dictionary value contains space and it is invalid for Search : "
+ + entry[1];
validationCheck = false;
}
- searchKeyValue.put(jsonBodyData, "*" +entry[1] +"*");
- }else{
+ searchKeyValue.put(jsonBodyData, "*" + entry[1] + "*");
+ } else {
searchText = entry[1];
}
}
}
}
- if(!PolicyUtils.policySpecialCharValidator(searchText).contains(success)){
- message = "The Search value contains space and it is invalid for Search : "+searchText;
+ if (!PolicyUtils.policySpecialCharValidator(searchText).contains(success)) {
+ message = "The Search value contains space and it is invalid for Search : " + searchText;
validationCheck = false;
}
- if(searchData.getClosedLooppolicyType() != null){
+ if (searchData.getClosedLooppolicyType() != null) {
String closedLoopType;
- if("Config_Fault".equalsIgnoreCase(searchData.getClosedLooppolicyType())){
- closedLoopType = "ClosedLoop_Fault";
- }else{
- closedLoopType = "ClosedLoop_PM";
+ if ("Config_Fault".equalsIgnoreCase(searchData.getClosedLooppolicyType())) {
+ closedLoopType = "ClosedLoop_Fault";
+ } else {
+ closedLoopType = "ClosedLoop_PM";
}
searchKeyValue.put("configPolicyType", closedLoopType);
}
- if(searchData.getOnapName() != null){
+ if (searchData.getOnapName() != null) {
searchKeyValue.put("onapName", searchData.getOnapName());
}
- if(searchData.getD2Service() != null){
+ if (searchData.getD2Service() != null) {
String d2Service = searchData.getD2Service().trim();
- if("Hosted Voice (Trinity)".equalsIgnoreCase(d2Service)){
+ if ("Hosted Voice (Trinity)".equalsIgnoreCase(d2Service)) {
d2Service = "trinity";
- }else if("vUSP".equalsIgnoreCase(d2Service)){
+ } else if ("vUSP".equalsIgnoreCase(d2Service)) {
d2Service = "vUSP";
- }else if("MCR".equalsIgnoreCase(d2Service)){
+ } else if ("MCR".equalsIgnoreCase(d2Service)) {
d2Service = "mcr";
- }else if("Gamma".equalsIgnoreCase(d2Service)){
+ } else if ("Gamma".equalsIgnoreCase(d2Service)) {
d2Service = "gamma";
- }else if("vDNS".equalsIgnoreCase(d2Service)){
+ } else if ("vDNS".equalsIgnoreCase(d2Service)) {
d2Service = "vDNS";
}
- searchKeyValue.put("jsonBodyData."+d2Service+"", "true");
+ searchKeyValue.put("jsonBodyData." + d2Service + "", "true");
}
- if(searchData.getVnfType() != null){
- searchKeyValue.put(jsonBodyData, "*"+searchData.getVnfType()+"*");
+ if (searchData.getVnfType() != null) {
+ searchKeyValue.put(jsonBodyData, "*" + searchData.getVnfType() + "*");
}
- if(searchData.getPolicyStatus() != null){
- searchKeyValue.put(jsonBodyData, "*"+searchData.getPolicyStatus()+"*");
+ if (searchData.getPolicyStatus() != null) {
+ searchKeyValue.put(jsonBodyData, "*" + searchData.getPolicyStatus() + "*");
}
- if(searchData.getVproAction() != null){
- searchKeyValue.put(jsonBodyData, "*"+searchData.getVproAction()+"*");
+ if (searchData.getVproAction() != null) {
+ searchKeyValue.put(jsonBodyData, "*" + searchData.getVproAction() + "*");
}
- if(searchData.getServiceType() != null){
+ if (searchData.getServiceType() != null) {
searchKeyValue.put("serviceType", searchData.getServiceType());
}
- if(searchData.getBindTextSearch() != null){
+ if (searchData.getBindTextSearch() != null) {
searchKeyValue.put(searchData.getBindTextSearch(), searchText);
searchText = null;
}
PolicyIndexType type = null;
- if(policyType != null){
- if(action.equalsIgnoreCase(policyType)){
+ if (policyType != null) {
+ if (action.equalsIgnoreCase(policyType)) {
type = ElkConnector.PolicyIndexType.action;
- }else if(decision.equalsIgnoreCase(policyType)){
+ } else if (decision.equalsIgnoreCase(policyType)) {
type = ElkConnector.PolicyIndexType.decision;
- }else if(config.equalsIgnoreCase(policyType)){
+ } else if (config.equalsIgnoreCase(policyType)) {
type = ElkConnector.PolicyIndexType.config;
- }else if("closedloop".equalsIgnoreCase(policyType)){
+ } else if ("closedloop".equalsIgnoreCase(policyType)) {
type = ElkConnector.PolicyIndexType.closedloop;
- }else{
+ } else {
type = ElkConnector.PolicyIndexType.all;
}
- }else{
+ } else {
type = ElkConnector.PolicyIndexType.all;
}
- if(validationCheck){
+ if (validationCheck) {
JestResult policyResultList = controller.search(type, searchText, searchKeyValue);
- if(policyResultList.isSucceeded()){
+ 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++){
+ 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");
+ } else {
+ LOGGER.error(
+ "Exception Occured While Searching for Data in Elastic Search Server, Check the Logs");
}
}
- }catch(Exception e){
+ } catch (Exception e) {
LOGGER.error("Exception Occured While Searching for Data in Elastic Search Server" + e);
}
}
- if(validationCheck){
- if(result){
+ if (validationCheck) {
+ if (result) {
message = "Elastic Server Transaction is success";
- }else{
+ } else {
message = "Elastic Server Transaction is failed, please check the logs";
}
}
@@ -298,22 +300,25 @@ public class PolicyElasticSearchController{
JSONObject j = new JSONObject(msg);
response.setStatus(HttpServletResponse.SC_OK);
response.addHeader(success, success);
- if(policyResult){
+ if (policyResult) {
JSONObject k = new JSONObject("{policyresult: " + policyList + "}");
response.getWriter().write(k.toString());
- }else{
+ } else {
response.getWriter().write(j.toString());
}
- }catch(Exception e){
+ } 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(),e);
+ LOGGER.error("Exception Occured While Performing Elastic Transaction" + e.getMessage(), e);
}
}
- @RequestMapping(value={"/searchDictionary"}, method={org.springframework.web.bind.annotation.RequestMethod.POST})
- public ModelAndView searchDictionary(HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException, IOException {
- try{
+ @RequestMapping(
+ value = {"/searchDictionary"},
+ method = {org.springframework.web.bind.annotation.RequestMethod.POST})
+ public ModelAndView searchDictionary(HttpServletRequest request, HttpServletResponse response)
+ throws UnsupportedEncodingException, IOException {
+ try {
PolicyIndexType config = PolicyIndexType.config;
PolicyIndexType closedloop = PolicyIndexType.closedloop;
PolicyIndexType action = PolicyIndexType.action;
@@ -327,105 +332,114 @@ public class PolicyElasticSearchController{
Mode mode = Mode.valueOf(dictionaryType);
String value;
List<String> policyList = new ArrayList<>();
- switch (mode){
- case attribute :
- Attribute attributedata = mapper.readValue(root.get("data").toString(), Attribute.class);
- value = attributedata.getXacmlId();
- policyList = searchElkDatabase(all, pholder,value);
- break;
- case onapName :
- OnapName onapName = mapper.readValue(root.get("data").toString(), OnapName.class);
- value = onapName.getOnapName();
- policyList = searchElkDatabase(all, "onapName",value);
- break;
- case actionPolicy :
- ActionPolicyDict actionPolicyDict = mapper.readValue(root.get("data").toString(), ActionPolicyDict.class);
- value = actionPolicyDict.getAttributeName();
- policyList = searchElkDatabase(action, "actionAttributeValue",value);
- break;
- case brmsParam :
- BRMSParamTemplate bRMSParamTemplate = mapper.readValue(root.get("data").toString(), BRMSParamTemplate.class);
- value = bRMSParamTemplate.getRuleName();
- policyList = searchElkDatabase(config, "ruleName",value);
- break;
- case 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 = mapper.readValue(root.get("data").toString(), ClosedLoopSite.class);
- value = closedLoopSite.getSiteName();
- policyList = searchElkDatabase(closedloop,"siteNames",value);
- break;
- case clService :
- ClosedLoopD2Services closedLoopD2Services = mapper.readValue(root.get("data").toString(), ClosedLoopD2Services.class);
- value = closedLoopD2Services.getServiceName();
- policyList = searchElkDatabase(closedloop, pholder,value);
- break;
- case clVarbind :
- VarbindDictionary varbindDictionary = mapper.readValue(root.get("data").toString(), VarbindDictionary.class);
- value = varbindDictionary.getVarbindName();
- policyList = searchElkDatabase(closedloop, jsonBodyData,"*"+value+"*");
- break;
- case clVnf :
- VNFType vNFType = mapper.readValue(root.get("data").toString(), VNFType.class);
- value = vNFType.getVnftype();
- policyList = searchElkDatabase(closedloop, jsonBodyData,"*"+value+"*");
- break;
- case clVSCL :
- VSCLAction vsclAction = mapper.readValue(root.get("data").toString(), VSCLAction.class);
- value = vsclAction.getVsclaction();
- policyList = searchElkDatabase(closedloop, jsonBodyData,"*"+value+"*");
- break;
- case decision :
- DecisionSettings decisionSettings = mapper.readValue(root.get("data").toString(), DecisionSettings.class);
- value = decisionSettings.getXacmlId();
- policyList = searchElkDatabase(decision,pholder,value);
- break;
- case fwTerm :
- TermList term = mapper.readValue(root.get("data").toString(), TermList.class);
- value = term.getTermName();
- policyList = searchElkDatabase(config, pholder,value);
- break;
- case msDCAEUUID :
- DCAEuuid dcaeUUID = mapper.readValue(root.get("data").toString(), DCAEuuid.class);
- value = dcaeUUID.getName();
- policyList = searchElkDatabase(config, "uuid",value);
- break;
- case msLocation :
- MicroServiceLocation mslocation = mapper.readValue(root.get("data").toString(), MicroServiceLocation.class);
- value = mslocation.getName();
- policyList = searchElkDatabase(config, "location",value);
- break;
- case msModels :
- MicroServiceModels msModels = mapper.readValue(root.get("data").toString(), MicroServiceModels.class);
- value = msModels.getModelName();
- policyList = searchElkDatabase(config, "serviceType",value);
- break;
- case psGroupPolicy :
- GroupPolicyScopeList groupPoilicy = mapper.readValue(root.get("data").toString(), GroupPolicyScopeList.class);
- value = groupPoilicy.getGroupName();
- policyList = searchElkDatabase(config, pholder,value);
- break;
- case safeRisk :
- RiskType riskType= mapper.readValue(root.get("data").toString(), RiskType.class);
- value = riskType.getRiskName();
- policyList = searchElkDatabase(config, "riskType",value);
- break;
- case safePolicyWarning :
- SafePolicyWarning safePolicy = mapper.readValue(root.get("data").toString(), SafePolicyWarning.class);
- value = safePolicy.getName();
- policyList = searchElkDatabase(config, pholder,value);
- break;
- default:
+ switch (mode) {
+ case attribute:
+ Attribute attributedata = mapper.readValue(root.get("data").toString(), Attribute.class);
+ value = attributedata.getXacmlId();
+ policyList = searchElkDatabase(all, pholder, value);
+ break;
+ case onapName:
+ OnapName onapName = mapper.readValue(root.get("data").toString(), OnapName.class);
+ value = onapName.getName();
+ policyList = searchElkDatabase(all, "onapName", value);
+ break;
+ case actionPolicy:
+ ActionPolicyDict actionPolicyDict =
+ mapper.readValue(root.get("data").toString(), ActionPolicyDict.class);
+ value = actionPolicyDict.getAttributeName();
+ policyList = searchElkDatabase(action, "actionAttributeValue", value);
+ break;
+ case brmsParam:
+ BrmsParamTemplate bRMSParamTemplate =
+ mapper.readValue(root.get("data").toString(), BrmsParamTemplate.class);
+ value = bRMSParamTemplate.getRuleName();
+ policyList = searchElkDatabase(config, "ruleName", value);
+ break;
+ case 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 = mapper.readValue(root.get("data").toString(), ClosedLoopSite.class);
+ value = closedLoopSite.getSiteName();
+ policyList = searchElkDatabase(closedloop, "siteNames", value);
+ break;
+ case clService:
+ ClosedLoopD2Services closedLoopD2Services =
+ mapper.readValue(root.get("data").toString(), ClosedLoopD2Services.class);
+ value = closedLoopD2Services.getServiceName();
+ policyList = searchElkDatabase(closedloop, pholder, value);
+ break;
+ case clVarbind:
+ VarbindDictionary varbindDictionary =
+ mapper.readValue(root.get("data").toString(), VarbindDictionary.class);
+ value = varbindDictionary.getVarbindName();
+ policyList = searchElkDatabase(closedloop, jsonBodyData, "*" + value + "*");
+ break;
+ case clVnf:
+ VnfType vNFType = mapper.readValue(root.get("data").toString(), VnfType.class);
+ value = vNFType.getType();
+ policyList = searchElkDatabase(closedloop, jsonBodyData, "*" + value + "*");
+ break;
+ case clVSCL:
+ VsclAction vsclAction = mapper.readValue(root.get("data").toString(), VsclAction.class);
+ value = vsclAction.getAction();
+ policyList = searchElkDatabase(closedloop, jsonBodyData, "*" + value + "*");
+ break;
+ case decision:
+ DecisionSettings decisionSettings =
+ mapper.readValue(root.get("data").toString(), DecisionSettings.class);
+ value = decisionSettings.getXacmlId();
+ policyList = searchElkDatabase(decision, pholder, value);
+ break;
+ case fwTerm:
+ TermList term = mapper.readValue(root.get("data").toString(), TermList.class);
+ value = term.getTermName();
+ policyList = searchElkDatabase(config, pholder, value);
+ break;
+ case msDCAEUUID:
+ DcaeUuid dcaeUUID = mapper.readValue(root.get("data").toString(), DcaeUuid.class);
+ value = dcaeUUID.getName();
+ policyList = searchElkDatabase(config, "uuid", value);
+ break;
+ case msLocation:
+ MicroServiceLocation mslocation =
+ mapper.readValue(root.get("data").toString(), MicroServiceLocation.class);
+ value = mslocation.getName();
+ policyList = searchElkDatabase(config, "location", value);
+ break;
+ case msModels:
+ MicroServiceModels msModels =
+ mapper.readValue(root.get("data").toString(), MicroServiceModels.class);
+ value = msModels.getModelName();
+ policyList = searchElkDatabase(config, "serviceType", value);
+ break;
+ case psGroupPolicy:
+ GroupPolicyScopeList groupPoilicy =
+ mapper.readValue(root.get("data").toString(), GroupPolicyScopeList.class);
+ value = groupPoilicy.getGroupName();
+ policyList = searchElkDatabase(config, pholder, value);
+ break;
+ case safeRisk:
+ RiskType riskType = mapper.readValue(root.get("data").toString(), RiskType.class);
+ value = riskType.getName();
+ policyList = searchElkDatabase(config, "riskType", value);
+ break;
+ case safePolicyWarning:
+ SafePolicyWarning safePolicy =
+ 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){
+ } catch (Exception e) {
response.setCharacterEncoding("UTF-8");
request.setCharacterEncoding("UTF-8");
PrintWriter out = response.getWriter();
@@ -435,30 +449,31 @@ public class PolicyElasticSearchController{
return null;
}
- //Search the Elk database
- public List<String> searchElkDatabase(PolicyIndexType type, String key, String value){
+ // Search the Elk database
+ public List<String> searchElkDatabase(PolicyIndexType type, String key, String value) {
PolicyElasticSearchController controller = new PolicyElasticSearchController();
Map<String, String> searchKeyValue = new HashMap<>();
- if(!pholder.equals(key)){
+ if (!pholder.equals(key)) {
searchKeyValue.put(key, value);
}
List<String> 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++){
+ 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{
+ } 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<String, String> searchKeyValue) {
- return ElkConnector.singleton.search(type, text, searchKeyValue);
+ return ElkConnector.singleton.search(type, text, searchKeyValue);
}
-} \ No newline at end of file
+}
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
index 9338cdbbd..95930ede8 100644
--- 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
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP-PAP-REST
* ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017, 2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -17,6 +17,7 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.policy.pap.xacml.rest.elk.client;
public class PolicyLocator {
@@ -27,11 +28,10 @@ public class PolicyLocator {
public final String policyId;
public final String version;
- public PolicyLocator(String policyType, String policyName,
- String owner, String scope, String policyId,
- String version) {
+ public PolicyLocator(String policyType, String policyName, String owner, String scope, String policyId,
+ String version) {
this.policyType = policyType;
- this.policyName= policyName;
+ this.policyName = policyName;
this.owner = owner;
this.scope = scope;
this.policyId = policyId;
@@ -39,13 +39,8 @@ public class PolicyLocator {
}
public String toString() {
- return "[" +
- this.owner + "|" +
- this.scope + "|" +
- this.policyType + "|" +
- this.policyName + "|" +
- this.policyId + "|" +
- "v" + this.version + "|" + "]";
+ 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
index 5bea62dff..4baa13fda 100644
--- 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
@@ -21,9 +21,11 @@
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.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;
@@ -97,7 +99,7 @@ public class APIRequestHandler {
* @param apiflag the apiflag
* @throws IOException Signals that an I/O exception has occurred.
*/
- public void doDelete(HttpServletRequest request, HttpServletResponse response, ONAPLoggingContext loggingContext,
+ public void doDelete(HttpServletRequest request, HttpServletResponse response, OnapLoggingContext loggingContext,
String apiflag) throws IOException {
DeleteHandler deleteHandler = DeleteHandler.getInstance();
if ("deletePapApi".equalsIgnoreCase(apiflag)) {
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
index 92e43c62f..b300f6dd1 100644
--- 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
@@ -3,6 +3,7 @@
* ONAP-PAP-REST
* ================================================================================
* Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2019 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -23,21 +24,24 @@ package org.onap.policy.pap.xacml.rest.handler;
import com.att.research.xacml.api.pap.PAPException;
import com.att.research.xacml.api.pap.PDPPolicy;
import com.att.research.xacml.util.XACMLProperties;
+
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
+
import javax.script.SimpleBindings;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
+
import org.apache.commons.lang3.StringUtils;
-import org.onap.policy.common.logging.ONAPLoggingContext;
+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.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.PolicyDBDaoTransaction;
+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;
@@ -352,7 +356,7 @@ public class DeleteHandler {
* @throws IOException Signals that an I/O exception has occurred.
*/
public void doApiDeleteFromPdp(HttpServletRequest request, HttpServletResponse response,
- ONAPLoggingContext loggingContext) throws IOException {
+ OnapLoggingContext loggingContext) throws IOException {
String groupId = request.getParameter("groupId");
@@ -449,8 +453,8 @@ public class DeleteHandler {
}
}
- private String deletePolicyFromPdpGroup(OnapPDPGroup group, ONAPLoggingContext loggingContext, String userId) {
- PolicyDBDaoTransaction acPutTransaction = XACMLPapServlet.getDbDaoTransaction();
+ private String deletePolicyFromPdpGroup(OnapPDPGroup group, OnapLoggingContext loggingContext, String userId) {
+ PolicyDbDaoTransaction acPutTransaction = XACMLPapServlet.getDbDaoTransaction();
String response = null;
loggingContext.setServiceName("API:PAP.DeleteHandler");
OnapPDPGroup existingGroup = 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
index 89ce18835..e9edde66c 100644
--- 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
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP-PAP-REST
* ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017, 2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -17,16 +17,17 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.policy.pap.xacml.rest.handler;
+import com.att.research.xacml.util.XACMLProperties;
+
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 com.att.research.xacml.util.XACMLProperties;
-
public interface DictionaryHandler {
public static final Logger logger = FlexLogger.getLogger(DictionaryHandler.class);
String DICTIONARY_DEFAULT_CLASS = DictionaryHandlerImpl.class.getName();
@@ -34,13 +35,14 @@ public interface DictionaryHandler {
/*
* Get Instance
*/
- public static DictionaryHandler getInstance(){
+ public static DictionaryHandler getInstance() {
try {
- Class<?> dictionaryHandler = Class.forName(XACMLProperties.getProperty("dictionary.impl.className", DICTIONARY_DEFAULT_CLASS));
+ Class<?> dictionaryHandler =
+ Class.forName(XACMLProperties.getProperty("dictionary.impl.className", DICTIONARY_DEFAULT_CLASS));
DictionaryHandler instance = (DictionaryHandler) dictionaryHandler.newInstance();
return instance;
} catch (Exception e) {
- logger.error(e.getMessage(),e);
+ logger.error(e.getMessage(), e);
}
return null;
}
@@ -49,6 +51,7 @@ public interface DictionaryHandler {
* Get Equivalent for Dictionary Services.
*/
public void doDictionaryAPIGet(HttpServletRequest request, HttpServletResponse response);
+
/*
* Put Equivalent for Dictionary Services.
*/
@@ -59,7 +62,9 @@ public interface DictionaryHandler {
*
* getflag=true indicates Get Request.
* getflag=false indicates Put Request.
+ *
* @return
*/
- public String extendedOptions(String dictionaryType, HttpServletRequest request, HttpServletResponse response, boolean getflag);
+ 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
index 5fc737887..f16c2031c 100644
--- 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
@@ -22,6 +22,7 @@ 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;
@@ -55,7 +56,7 @@ public class DictionaryHandlerImpl implements DictionaryHandler {
case "VNFType":
dictionary.getVnfType(response);
break;
- case "PEPOptions":
+ case "PepOptions":
dictionary.getPEPOptions(response);
break;
case "Varbind":
@@ -205,7 +206,7 @@ public class DictionaryHandlerImpl implements DictionaryHandler {
case "VNFType":
result = dictionary.saveVnfType(request, response);
break;
- case "PEPOptions":
+ case "PepOptions":
result = dictionary.savePEPOptions(request, response);
break;
case "Varbind":
@@ -313,7 +314,7 @@ public class DictionaryHandlerImpl implements DictionaryHandler {
response.addHeader("error", message);
return;
}
- if(("Success").equalsIgnoreCase(result)) {
+ if (("Success").equalsIgnoreCase(result)) {
response.setStatus(HttpServletResponse.SC_OK);
response.addHeader("successMapKey", "success");
if (operation.equalsIgnoreCase("update")) {
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
index ed1c57369..81da91107 100644
--- 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
@@ -21,12 +21,15 @@
package org.onap.policy.pap.xacml.rest.handler;
import com.att.research.xacml.util.XACMLProperties;
+
import java.io.File;
import java.net.URI;
import java.util.List;
+
import javax.script.SimpleBindings;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
+
import org.onap.policy.common.logging.eelf.PolicyLogger;
import org.onap.policy.common.logging.flexlogger.FlexLogger;
import org.onap.policy.common.logging.flexlogger.Logger;
@@ -104,21 +107,22 @@ public class PushPolicyHandler {
}
}
- public boolean preSafetyCheck(StdPDPPolicy policy, String configHome){
+ public boolean preSafetyCheck(StdPDPPolicy policy, String configHome) {
return true;
}
- public boolean preSafetyCheck(OnapPDPGroup policy, String configHome){
+ 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()));
+ Class<?> pushPolicyHandler = Class.forName(
+ XACMLProperties.getProperty("pushPolicy.impl.className", PushPolicyHandler.class.getName()));
PushPolicyHandler instance = (PushPolicyHandler) pushPolicyHandler.newInstance();
return instance;
} catch (Exception e) {
- logger.error(e.getMessage(),e);
+ logger.error(e.getMessage(), e);
}
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
index 90f8b5a70..8a7c60490 100644
--- 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
@@ -21,12 +21,15 @@
package org.onap.policy.pap.xacml.rest.handler;
import com.att.research.xacml.util.XACMLProperties;
+
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.common.logging.flexlogger.FlexLogger;
import org.onap.policy.common.logging.flexlogger.Logger;
@@ -45,11 +48,11 @@ public class SavePolicyHandler {
String policyType = request.getParameter("policyType");
String apiflag = request.getParameter("apiflag");
PolicyCreation creation = new PolicyCreation();
- if ( policyType != null ) {
+ if (policyType != null) {
PolicyRestAdapter policyAdapter = new PolicyRestAdapter();
- if("update".equalsIgnoreCase(operation)){
+ if ("update".equalsIgnoreCase(operation)) {
policyAdapter.setEditPolicy(true);
- }else{
+ } else {
policyAdapter.setEditPolicy(false);
}
@@ -58,10 +61,10 @@ public class SavePolicyHandler {
// 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() : "";
+ json = scanner.hasNext() ? scanner.next() : "";
scanner.close();
- if(policyAdapter.isEditPolicy()){
+ if (policyAdapter.isEditPolicy()) {
PolicyLogger.info("SavePolicyHandler: JSON request from API to update a policy: " + json);
} else {
PolicyLogger.info("SavePolicyHandler: JSON request from API to create a policy: " + json);
@@ -69,67 +72,68 @@ public class SavePolicyHandler {
// 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)
+ // Set policyAdapter values including parentPath (Common to all policy types)
try {
PolicyLogger.info("SavePolicyHandler: Setting parameter values to PolicyAdapter");
policyAdapter = setDataToPolicyAdapter(policy, policyType, apiflag);
- if(!extendedPolicyOptions(policyAdapter, response)){
+ if (!extendedPolicyOptions(policyAdapter, response)) {
creation.savePolicy(policyAdapter, response);
}
if ("update".equalsIgnoreCase(operation)) {
- response.addHeader("operation", "update");
+ response.addHeader("operation", "update");
} else {
response.addHeader("operation", "create");
}
} catch (Exception e1) {
- logger.error("Could not set data to policy adapter "+e1.getMessage(),e1);
+ logger.error("Could not set data to policy adapter " + e1.getMessage(), e1);
}
}
}
- private PolicyRestAdapter setDataToPolicyAdapter(StdPAPPolicy policy, String policyType, String apiflag) throws ParserConfigurationException, ServletException, SAXException, IOException{
+ 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
+ // Common among policy types
policyAdapter.setPolicyName(policy.getPolicyName());
policyAdapter.setPolicyDescription(policy.getPolicyDescription());
- policyAdapter.setOnapName(policy.getOnapName()); //Config Base and Decision Policies
+ 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());
- //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
+ // 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.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.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
+ // 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
+ // Decision Policy Specific
policyAdapter.setDynamicSettingsMap(policy.getDynamicSettingsMap());
policyAdapter.setRuleProvider(policy.getProviderComboBox());
policyAdapter.setDomainDir(policyAdapter.getPolicyScope());
@@ -139,24 +143,25 @@ public class SavePolicyHandler {
return policyAdapter;
}
- public boolean extendedPolicyOptions(PolicyRestAdapter policyAdapter, HttpServletResponse response){
+ public boolean extendedPolicyOptions(PolicyRestAdapter policyAdapter, HttpServletResponse response) {
return false;
}
- public void addErrorHeader(String key, String value){
- if(ErrorHeaders==null){
- ErrorHeaders= new HashMap<>();
+ 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()));
+ Class<?> savePolicyHandler = Class.forName(
+ XACMLProperties.getProperty("savePolicy.impl.className", SavePolicyHandler.class.getName()));
SavePolicyHandler instance = (SavePolicyHandler) savePolicyHandler.newInstance();
return instance;
} catch (Exception e) {
- logger.error(e.getMessage(),e);
+ logger.error(e.getMessage(), e);
}
return null;
}
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
index 42c815aa8..908353ba3 100644
--- 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
@@ -21,17 +21,19 @@
package org.onap.policy.pap.xacml.rest.model;
import com.att.research.xacml.api.pap.PDPPolicy;
+
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
-import org.onap.policy.rest.util.PDPPolicyContainer;
+
+import org.onap.policy.rest.util.PdpPolicyContainer;
import org.onap.policy.xacml.api.pap.OnapPDPGroup;
import org.onap.policy.xacml.std.pap.StdPDPGroup;
public class RemoveGroupPolicy {
// Container from where we are fetching the policies
- private static PDPPolicyContainer policyContainer;
+ private static PdpPolicyContainer policyContainer;
private StdPDPGroup updatedObject;
private final StdPDPGroup group;
@@ -55,7 +57,7 @@ public class RemoveGroupPolicy {
if (this.group == null) {
return;
}
- setRemoveGroupPolicy(new PDPPolicyContainer(group));
+ setRemoveGroupPolicy(new PdpPolicyContainer(group));
}
/**
@@ -69,7 +71,7 @@ public class RemoveGroupPolicy {
this.isSaved = true;
}
- private static void setRemoveGroupPolicy(PDPPolicyContainer pdpPolicyContainer) {
+ private static void setRemoveGroupPolicy(PdpPolicyContainer pdpPolicyContainer) {
RemoveGroupPolicy.policyContainer = pdpPolicyContainer;
}
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
index 51d988887..f5ade96ac 100644
--- 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
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP-PAP-REST
* ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017, 2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -17,4 +17,5 @@
* 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
index d8a77269c..f2f2e8dbc 100644
--- 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
@@ -2,7 +2,8 @@
* ============LICENSE_START=======================================================
* ONAP-PAP-REST
* ================================================================================
- * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2020 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2019 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -21,6 +22,7 @@
package org.onap.policy.pap.xacml.rest.policycontroller;
import com.fasterxml.jackson.databind.ObjectMapper;
+
import java.io.File;
import java.util.Date;
import java.util.HashMap;
@@ -28,8 +30,10 @@ 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;
@@ -45,14 +49,14 @@ 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.OptimizationConfigPolicy;
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.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.BrmsParamTemplate;
import org.onap.policy.rest.jpa.PolicyEditorScopes;
import org.onap.policy.rest.jpa.PolicyVersion;
import org.onap.policy.rest.jpa.UserInfo;
@@ -68,37 +72,68 @@ import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
-
+/**
+ * The Class PolicyCreation.
+ */
@RestController
@RequestMapping("/")
-public class PolicyCreation extends AbstractPolicyCreation{
+public class PolicyCreation extends AbstractPolicyCreation {
+ private static final Logger LOGGER = FlexLogger.getLogger(PolicyCreation.class);
- private static final Logger LOGGER = FlexLogger.getLogger(PolicyCreation.class);
+ // Recurring constants
+ private static final String INVALID_ATTRIBUTE = "invalidAttribute";
+ private static final String SUCCESS = "success";
+ private static final String ERROR = "error";
+ private static final String POLICY_NAME = "policyName";
private String ruleID = "";
- private PolicyDBDao policyDBDao;
- String CLName = null;
+ private String clName = null;
private static CommonClassDao commonClassDao;
+ /**
+ * Gets the common class dao.
+ *
+ * @return the common class dao
+ */
public static CommonClassDao getCommonClassDao() {
return commonClassDao;
}
+ /**
+ * Sets the common class dao.
+ *
+ * @param commonClassDao the new common class dao
+ */
public static void setCommonClassDao(CommonClassDao commonClassDao) {
PolicyCreation.commonClassDao = commonClassDao;
}
+ /**
+ * Instantiates a new policy creation.
+ *
+ * @param commonClassDao the common class dao
+ */
@Autowired
- public PolicyCreation(CommonClassDao commonClassDao){
+ public PolicyCreation(CommonClassDao commonClassDao) {
PolicyCreation.commonClassDao = commonClassDao;
}
- public PolicyCreation(){}
-
- @RequestMapping(value="/policycreation/save_policy", method = RequestMethod.POST)
+ /**
+ * Instantiates a new policy creation.
+ */
+ public PolicyCreation() {}
+
+ /**
+ * Save policy.
+ *
+ * @param policyData the policy data
+ * @param response the response
+ * @return the response entity
+ */
+ @RequestMapping(value = "/policycreation/save_policy", method = RequestMethod.POST)
@ResponseBody
- public ResponseEntity<String> savePolicy(@RequestBody PolicyRestAdapter policyData, HttpServletResponse response){
+ public ResponseEntity<String> savePolicy(@RequestBody PolicyRestAdapter policyData, HttpServletResponse response) {
String body = null;
HttpStatus status = HttpStatus.BAD_REQUEST;
Map<String, String> successMap = new HashMap<>();
@@ -110,11 +145,11 @@ public class PolicyCreation extends AbstractPolicyCreation{
String policyConfigType = null;
String userId = policyData.getUserId();
- if (policyData.getTtlDate()==null){
+ if (policyData.getTtlDate() == null) {
policyData.setTtlDate("NA");
- }else{
- String dateTTL = policyData.getTtlDate();
- String newDate = convertDate(dateTTL);
+ } else {
+ String dateTtl = policyData.getTtlDate();
+ String newDate = convertDate(dateTtl);
policyData.setTtlDate(newDate);
}
@@ -125,19 +160,19 @@ public class PolicyCreation extends AbstractPolicyCreation{
policyConfigType = policyData.getConfigPolicyType();
if ("Firewall Config".equalsIgnoreCase(policyConfigType)) {
filePrefix = "Config_FW_";
- }else if ("ClosedLoop_Fault".equalsIgnoreCase(policyConfigType)) {
+ } else if ("ClosedLoop_Fault".equalsIgnoreCase(policyConfigType)) {
filePrefix = "Config_Fault_";
- }else if ("ClosedLoop_PM".equalsIgnoreCase(policyConfigType)) {
+ } else if ("ClosedLoop_PM".equalsIgnoreCase(policyConfigType)) {
filePrefix = "Config_PM_";
- }else if ("Micro Service".equalsIgnoreCase(policyConfigType)) {
+ } else if ("Micro Service".equalsIgnoreCase(policyConfigType)) {
filePrefix = "Config_MS_";
- }else if ("Optimization".equalsIgnoreCase(policyConfigType)) {
+ } else if ("Optimization".equalsIgnoreCase(policyConfigType)) {
filePrefix = "Config_OOF_";
- }else if ("BRMS_Raw".equalsIgnoreCase(policyConfigType)) {
+ } else if ("BRMS_Raw".equalsIgnoreCase(policyConfigType)) {
filePrefix = "Config_BRMS_Raw_";
- }else if ("BRMS_Param".equalsIgnoreCase(policyConfigType)) {
+ } else if ("BRMS_Param".equalsIgnoreCase(policyConfigType)) {
filePrefix = "Config_BRMS_Param_";
- }else {
+ } else {
filePrefix = "Config_";
}
} else if ("Action".equalsIgnoreCase(policyType)) {
@@ -151,8 +186,9 @@ public class PolicyCreation extends AbstractPolicyCreation{
String createdBy;
String modifiedBy;
String scopeCheck = policyData.getDomainDir().replace(".", File.separator);
- PolicyEditorScopes policyEditorScope = (PolicyEditorScopes) commonClassDao.getEntityItem(PolicyEditorScopes.class, "scopeName", scopeCheck);
- if(policyEditorScope == null){
+ PolicyEditorScopes policyEditorScope = (PolicyEditorScopes) commonClassDao
+ .getEntityItem(PolicyEditorScopes.class, "scopeName", scopeCheck);
+ if (policyEditorScope == null) {
UserInfo userInfo = new UserInfo();
userInfo.setUserName("API");
userInfo.setUserLoginId("API");
@@ -162,21 +198,22 @@ public class PolicyCreation extends AbstractPolicyCreation{
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();
+ // 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){
+ if (policyVersion == null) {
highestVersion = 0;
- }else{
+ } else {
highestVersion = policyVersion.getHigherVersion();
}
- if(highestVersion != 0 && policyVersion != null){
- if(policyData.isEditPolicy()){
- version = highestVersion +1;
- if(userId ==null){
+ if (highestVersion != 0 && policyVersion != null) {
+ if (policyData.isEditPolicy()) {
+ version = highestVersion + 1;
+ if (userId == null) {
modifiedBy = "API";
- }else{
+ } else {
modifiedBy = userId;
}
policyData.setUserId("API");
@@ -186,30 +223,31 @@ public class PolicyCreation extends AbstractPolicyCreation{
policyVersionDao.setHigherVersion(version);
policyVersionDao.setModifiedBy(modifiedBy);
policyVersionDao.setModifiedDate(new Date());
- }else{
+ } else {
body = "policyExists";
status = HttpStatus.CONFLICT;
response.setStatus(HttpServletResponse.SC_CONFLICT);
- response.addHeader("error", "policyExists");
- response.addHeader("policyName", policyData.getPolicyName());
+ response.addHeader(ERROR, "policyExists");
+ response.addHeader(POLICY_NAME, policyData.getPolicyName());
return new ResponseEntity<>(body, status);
}
- }else{
+ } else {
// if policy does not exist and the request is updatePolicy return error
- if(policyData.isEditPolicy()){
+ if (policyData.isEditPolicy()) {
body = "policyNotAvailableForEdit";
status = HttpStatus.NOT_FOUND;
response.setStatus(HttpServletResponse.SC_NOT_FOUND);
- response.addHeader("error", body);
- response.addHeader("message", policyData.getPolicyName() + " does not exist on the PAP and cannot be updated.");
+ response.addHeader(ERROR, body);
+ response.addHeader("message",
+ policyData.getPolicyName() + " does not exist on the PAP and cannot be updated.");
return new ResponseEntity<>(body, status);
}
version = 1;
- if(userId == null){
+ if (userId == null) {
createdBy = "API";
modifiedBy = "API";
policyData.setUserId("API");
- }else{
+ } else {
createdBy = userId;
modifiedBy = userId;
policyData.setUserId("API");
@@ -225,15 +263,16 @@ public class PolicyCreation extends AbstractPolicyCreation{
policyData.setPolicyID(newPolicyID());
policyData.setRuleID(ruleID);
- String policyFileName = dbCheckPolicyName.replace(File.separator, ".")+ "." + version + ".xml";
+ String policyFileName = dbCheckPolicyName.replace(File.separator, ".") + "." + version + ".xml";
policyData.setNewFileName(policyFileName);
- policyData.setPolicyDescription(policyData.getPolicyDescription()+ "@CreatedBy:" +createdBy + "@CreatedBy:" + "@ModifiedBy:" +modifiedBy + "@ModifiedBy:");
+ 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 && !policyData.getAttributes().isEmpty()){
- for(Object attribute : policyData.getAttributes()){
- if(attribute instanceof LinkedHashMap<?, ?>){
+ if (policyData.getApiflag() == null) {
+ // set the Rule Combining Algorithm Id to be sent to PAP-REST via JSON
+ if (policyData.getAttributes() != null && !policyData.getAttributes().isEmpty()) {
+ 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);
@@ -250,97 +289,105 @@ public class PolicyCreation extends AbstractPolicyCreation{
if ("Config".equalsIgnoreCase(policyType)) {
if ("Firewall Config".equalsIgnoreCase(policyConfigType)) {
newPolicy = new FirewallConfigPolicy(policyData);
- }else if ("BRMS_Raw".equalsIgnoreCase(policyConfigType)) {
+ } else if ("BRMS_Raw".equalsIgnoreCase(policyConfigType)) {
policyData.setOnapName("DROOLS");
policyData.setConfigName("BRMS_RAW_RULE");
newPolicy = new CreateBrmsRawPolicy(policyData);
- }else if ("BRMS_Param".equalsIgnoreCase(policyConfigType)) {
+ } else if ("BRMS_Param".equalsIgnoreCase(policyConfigType)) {
policyData.setOnapName("DROOLS");
policyData.setConfigName("BRMS_PARAM_RULE");
- Map<String, String> drlRuleAndUIParams = new HashMap<>();
- if(policyData.getApiflag() == null){
+ Map<String, String> drlRuleAndUiParams = new HashMap<>();
+ if (policyData.getApiflag() == null) {
// If there is any dynamic field create the matches here
- String key="templateName";
- String value= 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());
+ String key = "templateName";
+ String value = 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.";
+ 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(ERROR, message);
response.addHeader("modelName", modelName);
- return new ResponseEntity<String>(body, status);
+ return new ResponseEntity<>(body, status);
}
}
newPolicy = new CreateBrmsParamPolicy(policyData);
- }else if ("Base".equalsIgnoreCase(policyConfigType)) {
- newPolicy = new ConfigPolicy(policyData);
- }else if ("ClosedLoop_Fault".equalsIgnoreCase(policyConfigType)) {
+ } else if ("Base".equalsIgnoreCase(policyConfigType)) {
+ newPolicy = new ConfigPolicy(policyData);
+ } else if ("ClosedLoop_Fault".equalsIgnoreCase(policyConfigType)) {
newPolicy = new ClosedLoopPolicy(policyData);
- }else if ("ClosedLoop_PM".equalsIgnoreCase(policyConfigType)) {
- if(policyData.getApiflag() == null){
- policyData.setServiceType(policyData.getServiceTypePolicyName().get("serviceTypePolicyName").toString());
+ } else if ("ClosedLoop_PM".equalsIgnoreCase(policyConfigType)) {
+ 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.replaceFirst("\\{",
+ "\\{\"serviceTypePolicyName\": \"serviceTypeFieldValue\",");
jsonBody = jsonBody.replace("serviceTypeFieldValue", policyData.getServiceType());
policyData.setJsonBody(jsonBody);
}
newPolicy = new CreateClosedLoopPerformanceMetrics(policyData);
- }else if ("Micro Service".equalsIgnoreCase(policyConfigType)) {
+ } else if ("Micro Service".equalsIgnoreCase(policyConfigType)) {
newPolicy = new MicroServiceConfigPolicy(policyData);
- }else if ("Optimization".equalsIgnoreCase(policyConfigType)) {
+ } else if ("Optimization".equalsIgnoreCase(policyConfigType)) {
newPolicy = new OptimizationConfigPolicy(policyData);
}
- }else if("Action".equalsIgnoreCase(policyType)) {
- if(policyData.getApiflag() == null){
+ } else if ("Action".equalsIgnoreCase(policyType)) {
+ if (policyData.getApiflag() == null) {
List<String> dynamicRuleAlgorithmLabels = new LinkedList<>();
List<String> dynamicRuleAlgorithmCombo = new LinkedList<>();
List<String> dynamicRuleAlgorithmField1 = new LinkedList<>();
List<String> dynamicRuleAlgorithmField2 = new LinkedList<>();
-
- if(!policyData.getRuleAlgorithmschoices().isEmpty()){
- for(Object attribute : policyData.getRuleAlgorithmschoices()){
- if(attribute instanceof LinkedHashMap<?, ?>){
+ if (!policyData.getRuleAlgorithmschoices().isEmpty()) {
+ 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);
+ String key =
+ ((LinkedHashMap<?, ?>) attribute).get("dynamicRuleAlgorithmField1").toString();
dynamicRuleAlgorithmField1.add(key);
+ String rule =
+ ((LinkedHashMap<?, ?>) attribute).get("dynamicRuleAlgorithmCombo").toString();
dynamicRuleAlgorithmCombo.add(rule);
+ String value =
+ ((LinkedHashMap<?, ?>) attribute).get("dynamicRuleAlgorithmField2").toString();
dynamicRuleAlgorithmField2.add(value);
}
}
}
String actionDictValue = policyData.getActionAttributeValue();
- ActionPolicyDict jsonData = ((ActionPolicyDict) commonClassDao.getEntityItem(ActionPolicyDict.class, "attributeName", actionDictValue));
- if(jsonData!=null){
- String actionBodyString = jsonData.getBody();
+ ActionPolicyDict jsonData = ((ActionPolicyDict) commonClassDao.getEntityItem(ActionPolicyDict.class,
+ "attributeName", actionDictValue));
+ if (jsonData != null) {
String actionDictHeader = jsonData.getHeader();
- String actionDictType = jsonData.getType();
- String actionDictUrl = jsonData.getUrl();
- String actionDictMethod = jsonData.getMethod();
policyData.setActionDictHeader(actionDictHeader);
+ String actionDictType = jsonData.getType();
policyData.setActionDictType(actionDictType);
+ String actionDictUrl = jsonData.getUrl();
policyData.setActionDictUrl(actionDictUrl);
+ String actionDictMethod = jsonData.getMethod();
policyData.setActionDictMethod(actionDictMethod);
+ String actionBodyString = jsonData.getBody();
if (actionBodyString != null) {
policyData.setActionBody(actionBodyString);
}
@@ -350,11 +397,12 @@ public class PolicyCreation extends AbstractPolicyCreation{
policyData.setDynamicRuleAlgorithmCombo(dynamicRuleAlgorithmCombo);
policyData.setDynamicRuleAlgorithmField1(dynamicRuleAlgorithmField1);
policyData.setDynamicRuleAlgorithmField2(dynamicRuleAlgorithmField2);
- }else{
+ } else {
// API request.
String comboDictValue = policyData.getActionAttribute();
- ActionPolicyDict jsonData = ((ActionPolicyDict) commonClassDao.getEntityItem(ActionPolicyDict.class, "attributeName", comboDictValue));
- if(jsonData!=null){
+ ActionPolicyDict jsonData = ((ActionPolicyDict) commonClassDao.getEntityItem(ActionPolicyDict.class,
+ "attributeName", comboDictValue));
+ if (jsonData != null) {
policyData.setActionBody(jsonData.getBody());
policyData.setActionDictHeader(jsonData.getHeader());
policyData.setActionDictType(jsonData.getType());
@@ -364,37 +412,37 @@ public class PolicyCreation extends AbstractPolicyCreation{
}
newPolicy = new ActionPolicy(policyData, commonClassDao);
} else if ("Decision".equalsIgnoreCase(policyType)) {
- if(policyData.getApiflag() == null){
- Map<String, String> settingsMap = new HashMap<>();
+ if (policyData.getApiflag() == null) {
Map<String, String> treatmentMap = new HashMap<>();
- List<String> dynamicRuleAlgorithmLabels = new LinkedList<>();
- List<String> dynamicRuleAlgorithmCombo = new LinkedList<>();
- List<String> dynamicRuleAlgorithmField1 = new LinkedList<>();
- List<String> dynamicRuleAlgorithmField2 = new LinkedList<>();
- List<Object> dynamicVariableList = new LinkedList<>();
- List<String> dataTypeList = new LinkedList<>();
- List<String> errorCodeList = new LinkedList<>();
- List<String> treatmentList = new LinkedList<>();
-
- if(!policyData.getSettings().isEmpty()){
- for(Object settingsData : policyData.getSettings()){
- if(settingsData instanceof LinkedHashMap<?, ?>){
+ Map<String, String> settingsMap = new HashMap<>();
+ if (!policyData.getSettings().isEmpty()) {
+ 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<?, ?>){
+
+ List<String> dynamicRuleAlgorithmLabels = new LinkedList<>();
+ List<String> dynamicRuleAlgorithmField1 = new LinkedList<>();
+ List<String> dynamicRuleAlgorithmCombo = new LinkedList<>();
+ List<String> dynamicRuleAlgorithmField2 = new LinkedList<>();
+ if (policyData.getRuleAlgorithmschoices() != null
+ && !policyData.getRuleAlgorithmschoices().isEmpty()) {
+ 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);
+ String key =
+ ((LinkedHashMap<?, ?>) attribute).get("dynamicRuleAlgorithmField1").toString();
dynamicRuleAlgorithmField1.add(key);
+ String rule =
+ ((LinkedHashMap<?, ?>) attribute).get("dynamicRuleAlgorithmCombo").toString();
dynamicRuleAlgorithmCombo.add(rule);
+ String value =
+ ((LinkedHashMap<?, ?>) attribute).get("dynamicRuleAlgorithmField2").toString();
dynamicRuleAlgorithmField2.add(value);
}
}
@@ -455,6 +503,11 @@ public class PolicyCreation extends AbstractPolicyCreation{
}
}
+ List<Object> dynamicVariableList = new LinkedList<>();
+ List<String> dataTypeList = new LinkedList<>();
+ List<String> errorCodeList = new LinkedList<>();
+ List<String> treatmentList = new LinkedList<>();
+
policyData.setDynamicRuleAlgorithmLabels(dynamicRuleAlgorithmLabels);
policyData.setDynamicRuleAlgorithmCombo(dynamicRuleAlgorithmCombo);
policyData.setDynamicRuleAlgorithmField1(dynamicRuleAlgorithmField1);
@@ -470,125 +523,143 @@ public class PolicyCreation extends AbstractPolicyCreation{
newPolicy = new DecisionPolicy(policyData);
}
- if(newPolicy != null){
+ if (newPolicy != null) {
newPolicy.prepareToSave();
- }else{
- body = "error";
+ } else {
+ body = ERROR;
status = HttpStatus.INTERNAL_SERVER_ERROR;
response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
- response.addHeader("error", "error");
+ response.addHeader(ERROR, ERROR);
return new ResponseEntity<>(body, status);
}
- PolicyDBDaoTransaction policyDBDaoTransaction = null;
- try{
- policyDBDao = PolicyDBDao.getPolicyDBDaoInstance();
- policyDBDaoTransaction = policyDBDao.getNewTransaction();
- policyDBDaoTransaction.createPolicy(newPolicy, policyData.getUserId());
+ PolicyDbDaoTransaction policyDbDaoTransaction = null;
+ try {
+ PolicyDbDao policyDbDao = PolicyDbDao.getPolicyDbDaoInstance();
+ policyDbDaoTransaction = policyDbDao.getNewTransaction();
+ policyDbDaoTransaction.createPolicy(newPolicy, policyData.getUserId());
successMap = newPolicy.savePolicies();
- if(successMap.containsKey("success")){
- policyDBDaoTransaction.commitTransaction();
- if(policyData.isEditPolicy()){
+ if (successMap.containsKey(SUCCESS)) {
+ policyDbDaoTransaction.commitTransaction();
+ if (policyData.isEditPolicy()) {
commonClassDao.update(policyVersionDao);
- }else{
+ } else {
commonClassDao.save(policyVersionDao);
}
- try{
- PolicyElasticSearchController search= new PolicyElasticSearchController();
+ try {
+ PolicyElasticSearchController search = new PolicyElasticSearchController();
search.updateElk(policyData);
- }catch(Exception e){
- LOGGER.error("Error Occured while saving policy to Elastic Database"+e);
+ } catch (Exception e) {
+ LOGGER.error("Error Occured while saving policy to Elastic Database" + e);
}
- body = "success";
+ body = SUCCESS;
status = HttpStatus.OK;
response.setStatus(HttpServletResponse.SC_OK);
- response.addHeader("successMapKey", "success");
- response.addHeader("policyName", policyData.getNewFileName());
+ response.addHeader("successMapKey", SUCCESS);
+ response.addHeader(POLICY_NAME, policyData.getNewFileName());
- //get message from the SafetyCheckerResults if present
+ // get message from the SafetyCheckerResults if present
String safetyCheckerResponse = policyData.getClWarning();
- String existingCLName = policyData.getExistingCLName();
+ String existingClName = policyData.getExistingCLName();
- //if safetyCheckerResponse is not null add a header to send back with response
- if(safetyCheckerResponse!=null) {
+ // 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);
+ 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";
+ } else if (successMap.containsKey(INVALID_ATTRIBUTE)) {
+ LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Could not fine "
+ + policyData.getActionAttribute() + " in the ActionPolicyDict table.");
+ body = INVALID_ATTRIBUTE;
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();
+ response.addHeader(INVALID_ATTRIBUTE, policyData.getActionAttribute());
+
+ String message = XACMLErrorConstants.ERROR_DATA_ISSUE + "Invalid Action Attribute";
+ response.addHeader(ERROR, message);
+ response.addHeader(POLICY_NAME, 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.";
+ response.addHeader(ERROR, message);
+ response.addHeader(POLICY_NAME, 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";
+ response.addHeader(ERROR, message);
+ response.addHeader(POLICY_NAME, policyData.getPolicyName());
+ } else {
+ policyDbDaoTransaction.rollbackTransaction();
+ body = ERROR;
status = HttpStatus.INTERNAL_SERVER_ERROR;
response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
- response.addHeader("error", "error");
+ response.addHeader(ERROR, ERROR);
}
- }catch(Exception e){
- LOGGER.error("Exception Occured : ",e);
- if(policyDBDaoTransaction != null){
- policyDBDaoTransaction.rollbackTransaction();
+ } catch (Exception e) {
+ LOGGER.error("Exception Occured : ", e);
+ if (policyDbDaoTransaction != null) {
+ policyDbDaoTransaction.rollbackTransaction();
}
}
- }
- catch (Exception e){
- LOGGER.error("Exception Occured : "+e.getMessage(),e);
- body = "error";
- response.addHeader("error", e.getMessage());
+ } catch (Exception e) {
+ LOGGER.error("Exception Occured : " + e.getMessage(), e);
+ body = ERROR;
+ //
+ // Because we are catching any old exception instead of a dedicated exception,
+ // its possible the e.getMessage() returns a null value. You cannot add a header
+ // to the response with a null value, it will throw an exception. This is something
+ // this is undesirable.
+ //
+ response.addHeader(ERROR, (e.getMessage() == null ? "missing exception message" : e.getMessage()));
response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
}
return new ResponseEntity<>(body, status);
}
+ /**
+ * Message not readable exception handler.
+ *
+ * @param req the req
+ * @param exception the exception
+ * @return the response entity
+ */
@ExceptionHandler({ HttpMessageNotReadableException.class })
- public ResponseEntity<String> messageNotReadableExceptionHandler(HttpServletRequest req, HttpMessageNotReadableException exception) {
+ public ResponseEntity<String> 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());
+ 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;
- }
+ /**
+ * Gets the policy version data.
+ *
+ * @param dbCheckPolicyName the db check policy name
+ * @return the policy version data
+ */
+ public PolicyVersion getPolicyVersionData(String dbCheckPolicyName) {
+ PolicyVersion entityItem =
+ (PolicyVersion) commonClassDao.getEntityItem(PolicyVersion.class, POLICY_NAME, dbCheckPolicyName);
+ if (entityItem != null && 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
index bb5307573..6c0891513 100644
--- 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
@@ -2,14 +2,14 @@
* ============LICENSE_START=======================================================
* ONAP-PAP-REST
* ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017, 2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -17,4 +17,5 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-package org.onap.policy.pap.xacml.rest.policycontroller; \ No newline at end of file
+
+package org.onap.policy.pap.xacml.rest.policycontroller;
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
index 2dea96517..45e82cc54 100644
--- 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
@@ -21,8 +21,10 @@
package org.onap.policy.pap.xacml.rest.service;
import java.io.IOException;
+
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
+
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;
@@ -37,7 +39,6 @@ import org.onap.policy.pap.xacml.rest.controller.SafePolicyController;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.ModelAndView;
-
// TODO: Auto-generated Javadoc
/**
* The Class DictionaryService.
@@ -387,8 +388,6 @@ public class DictionaryService {
return result.getViewName();
}
-
-
/**
* Save micro service location dictionary.
*
@@ -608,7 +607,6 @@ public class DictionaryService {
return result.getViewName();
}
-
/**
* Gets the onap dictionary.
*
@@ -854,7 +852,6 @@ public class DictionaryService {
dictionary.getTermListDictionaryEntityData(response);
}
-
/**
* Gets the micro service location dictionary.
*
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
index 01fbff7ce..050bcc561 100644
--- 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
@@ -30,6 +30,7 @@ import java.io.Writer;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
+import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.onap.policy.common.logging.eelf.PolicyLogger;
@@ -72,7 +73,8 @@ public class ImportService {
StringBuilder builder = new StringBuilder();
int ch;
try {
- while ((ch = request.getInputStream().read()) != -1) {
+ ServletInputStream stream = request.getInputStream();
+ while ((ch = stream.read()) != -1) {
builder.append((char) ch);
}
} catch (IOException e) {
@@ -84,8 +86,7 @@ public class ImportService {
response.addHeader(service, serviceName);
}
CreateBRMSRuleTemplate brmsRuleTemplate = new CreateBRMSRuleTemplate();
- successMap =
- brmsRuleTemplate.addRule(builder.toString(), serviceName, description, "API");
+ successMap = brmsRuleTemplate.addRule(builder.toString(), serviceName, description, "API");
} else if (("MICROSERVICE").equals(importServiceCreation)) {
CreateNewMicroServiceModel newMS = null;
String randomID = UUID.randomUUID().toString();
@@ -114,8 +115,7 @@ public class ImportService {
}
PolicyLogger.info("Request from API to import new Service");
try (Writer writer = new BufferedWriter(new OutputStreamWriter(
- new FileOutputStream(extractDir + File.separator + randomID + type),
- "utf-8"))) {
+ new FileOutputStream(extractDir + File.separator + randomID + type), "utf-8"))) {
writer.write(xmi);
} catch (IOException e) {
logger.error(e);
@@ -125,7 +125,7 @@ public class ImportService {
} else {
InputStream inputStream = null;
try (FileOutputStream outputStream =
- new FileOutputStream(extractDir + File.separator + randomID + ".zip")) {
+ new FileOutputStream(extractDir + File.separator + randomID + ".zip")) {
inputStream = request.getInputStream();
byte[] buffer = new byte[4096];
int bytesRead = -1;
@@ -141,14 +141,12 @@ public class ImportService {
inputStream.close();
}
} catch (IOException e) {
- PolicyLogger.error(
- "Exception Occured while closing the input/output stream" + e);
+ PolicyLogger.error("Exception Occured while closing the input/output stream" + e);
}
}
}
- newMS = new CreateNewMicroServiceModel(fileName, serviceName, "API", version,
- randomID);
+ newMS = new CreateNewMicroServiceModel(fileName, serviceName, "API", version, randomID);
successMap = newMS.addValuesToNewModel(type);
@@ -180,8 +178,7 @@ public class ImportService {
}
PolicyLogger.info("Request from API to import new Optimization Service Model");
try (Writer writer = new BufferedWriter(new OutputStreamWriter(
- new FileOutputStream(extractDir + File.separator + randomID + type),
- "utf-8"))) {
+ new FileOutputStream(extractDir + File.separator + randomID + type), "utf-8"))) {
writer.write(yml);
} catch (IOException e) {
logger.error(e);
@@ -189,8 +186,7 @@ public class ImportService {
return;
}
- newOOF = new CreateNewOptimizationModel(fileName, serviceName, "API Import Service",
- version, randomID);
+ newOOF = new CreateNewOptimizationModel(fileName, serviceName, "API Import Service", version, randomID);
successMap = newOOF.addValuesToNewModel();
if (successMap.containsKey(successMessage)) {
successMap.clear();
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
index 0a539dcbb..36dd5fdee 100644
--- 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
@@ -21,6 +21,7 @@
package org.onap.policy.pap.xacml.rest.service;
import com.att.research.xacml.api.pap.PDPPolicy;
+import com.google.common.annotations.VisibleForTesting;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
@@ -48,8 +49,9 @@ public class MetricService {
}
+ @VisibleForTesting
@Autowired
- private MetricService(CommonClassDao commonClassDao) {
+ protected MetricService(CommonClassDao commonClassDao) {
MetricService.commonClassDao = commonClassDao;
}
@@ -76,7 +78,7 @@ public class MetricService {
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.");
+ "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");
@@ -84,7 +86,7 @@ public class MetricService {
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.";
+ "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(errorMsg, 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
index f411e7d98..db68fb29f 100644
--- 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
@@ -2,14 +2,14 @@
* ============LICENSE_START=======================================================
* ONAP-PAP-REST
* ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017, 2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -17,82 +17,83 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.policy.pap.xacml.rest.util;
+import com.att.research.xacml.util.XACMLProperties;
+import com.google.common.base.Joiner;
import java.util.UUID;
-import org.onap.policy.rest.XACMLRestProperties;
+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");
+ return XACMLProperties.getProperty(XacmlRestProperties.PROP_ADMIN_DOMAIN, "urn");
}
public String newPolicyID() {
- return Joiner.on(':').skipNulls().join((getDomain().startsWith("urn") ? null: "urn"),
+ return Joiner.on(':').skipNulls().join((getDomain().startsWith("urn") ? null : "urn"),
getDomain().replaceAll("[/\\\\.]", ":"), "xacml", "policy", "id", UUID.randomUUID());
}
public String convertDate(String dateTTL) {
String formateDate = null;
- if(dateTTL.contains("/")){
+ if (dateTTL.contains("/")) {
formateDate = dateTTL.replace("/", "-");
- }else {
+ } else {
formateDate = dateTTL;
}
return formateDate;
}
-
-
- public void updatePolicyCreationToDatabase(){
+ 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<Object> 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);
- }
- }*/
+ /*
+ * 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<Object> 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/DictionaryUtils.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/util/DictionaryUtils.java
index e88efa931..ec27e0304 100644
--- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/util/DictionaryUtils.java
+++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/util/DictionaryUtils.java
@@ -23,14 +23,17 @@ package org.onap.policy.pap.xacml.rest.util;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
+
import java.io.IOException;
import java.io.PrintWriter;
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;
@@ -80,8 +83,7 @@ public class DictionaryUtils {
}
public boolean isRequestFromAPI(HttpServletRequest request) {
- return request.getParameter(apiflag) != null
- && "api".equalsIgnoreCase(request.getParameter(apiflag));
+ return request.getParameter(apiflag) != null && "api".equalsIgnoreCase(request.getParameter(apiflag));
}
public String appendKey(List<Object> objects, String key1, String appendValue) {
@@ -134,8 +136,7 @@ public class DictionaryUtils {
}
public Category getCategory() {
- return (Category) commonClassDao.getDataById(Category.class, "shortName", "resource")
- .get(0);
+ return (Category) commonClassDao.getDataById(Category.class, "shortName", "resource").get(0);
}
public ModelAndView getResultForApi(String inResponseString) {
@@ -148,8 +149,7 @@ public class DictionaryUtils {
return result;
}
- public void setResponseData(HttpServletResponse response, String key, String responseString)
- throws IOException {
+ public void setResponseData(HttpServletResponse response, String key, String responseString) throws IOException {
response.setCharacterEncoding(utf8);
response.setContentType(applicationJsonContentType);
@@ -166,13 +166,11 @@ public class DictionaryUtils {
}
@SuppressWarnings("rawtypes")
- public void getDataByEntity(HttpServletResponse response, String key, String value,
- Class className) {
+ public void getDataByEntity(HttpServletResponse response, String key, String value, Class className) {
try {
Map<String, Object> model = new HashMap<>();
ObjectMapper mapper = new ObjectMapper();
- model.put(key,
- mapper.writeValueAsString(commonClassDao.getDataByColumn(className, value)));
+ model.put(key, mapper.writeValueAsString(commonClassDao.getDataByColumn(className, value)));
JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
JSONObject j = new JSONObject(msg);
response.getWriter().write(j.toString());
@@ -206,8 +204,7 @@ public class DictionaryUtils {
ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
JsonNode root = mapper.readTree(request.getReader());
- commonClassDao
- .delete(mapper.readValue(root.get("data").toString(), className));
+ commonClassDao.delete(mapper.readValue(root.get("data").toString(), className));
String responseString = mapper.writeValueAsString(commonClassDao.getData(className));
setResponseData(response, key, responseString);
} catch (Exception e) {
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
index cb9abb9db..efb8287f0 100644
--- 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
@@ -21,6 +21,7 @@
package org.onap.policy.pap.xacml.rest.util;
import java.util.List;
+
import org.onap.policy.common.logging.flexlogger.FlexLogger;
import org.onap.policy.common.logging.flexlogger.Logger;
import org.onap.policy.rest.XacmlAdminAuthorization;
@@ -41,7 +42,6 @@ public class JPAUtils {
JPAUtils.commonClassDao = commonClassDao;
}
-
/**
* Get an instance of a JPAUtils. It creates one if it does not exist. Only one instance is allowed
* to be created per server.
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
index 6ea0c79ee..cafeb0c92 100644
--- 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
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP-PAP-REST
* ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017, 2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -25,17 +25,19 @@ 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) {
+
+ public JsonMessage(String data, String data2) {
super();
this.data = data;
this.data2 = data2;
}
- public JsonMessage(String data,String data2,String data3) {
+ public JsonMessage(String data, String data2, String data3) {
super();
this.data = data;
this.data2 = data2;
@@ -49,19 +51,21 @@ public class JsonMessage {
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/restAuth/AuthenticationService.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/restAuth/AuthenticationService.java
index 10cc81549..4e938acff 100644
--- 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
@@ -21,16 +21,18 @@
package org.onap.policy.pap.xacml.restAuth;
import com.att.research.xacml.util.XACMLProperties;
+
import java.nio.charset.StandardCharsets;
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 org.onap.policy.rest.XacmlRestProperties;
import org.onap.policy.utils.PeCryptoUtils;
public class AuthenticationService {
- private String papId = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_USERID);
+ private String papId = XACMLProperties.getProperty(XacmlRestProperties.PROP_PAP_USERID);
private String papPass = null;
/**
@@ -49,9 +51,9 @@ public class AuthenticationService {
String usernameAndPassword = null;
try {
- String secretKey = XACMLProperties.getProperty(XACMLRestProperties.PROP_AES_KEY);
+ String secretKey = XACMLProperties.getProperty(XacmlRestProperties.PROP_AES_KEY);
PeCryptoUtils.initAesKey(secretKey);
- papPass = PeCryptoUtils.decrypt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_PASS));
+ papPass = PeCryptoUtils.decrypt(XACMLProperties.getProperty(XacmlRestProperties.PROP_PAP_PASS));
} catch (Exception e) {
PolicyLogger.error(e);
}
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
index 181dd0910..ab1576715 100644
--- 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
@@ -21,6 +21,7 @@
package org.onap.policy.pap.xacml.restAuth;
import com.att.research.xacml.api.pap.PAPException;
+
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
@@ -37,6 +38,7 @@ import java.util.HashMap;
import java.util.List;
import java.util.Objects;
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;
@@ -73,19 +75,20 @@ public class CheckPDP {
String pdpFile = XACMLPapServlet.getPDPFile();
if (pdpFile == null) {
PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + "PDP File name is undefined");
- throw new PAPException(XACMLErrorConstants.ERROR_SYSTEM_ERROR +"PDP File name not Valid : " + pdpFile);
+ throw new PAPException(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 PAPException(XACMLErrorConstants.ERROR_SYSTEM_ERROR +"File doesn't exist in the specified Path : "+ pdpPath.toString());
+ throw new PAPException(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 PAPException(XACMLErrorConstants.ERROR_SYSTEM_ERROR +"Not a .properties file");
+ throw new PAPException(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Not a .properties file");
}
}
// Check if File is updated recently
@@ -98,7 +101,7 @@ public class CheckPDP {
}
}
- @SuppressWarnings({ "rawtypes", "unchecked" })
+ @SuppressWarnings({"rawtypes", "unchecked"})
private static void readProps() throws PAPException {
InputStream in;
pdpProp = new Properties();
@@ -137,45 +140,47 @@ public class CheckPDP {
}
if (pdpMap == null || pdpMap.isEmpty()) {
logger.debug(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Cannot Proceed without PDP_URLs");
- throw new PAPException(XACMLErrorConstants.ERROR_SYSTEM_ERROR +"Cannot Proceed without PDP_URLs");
+ throw new PAPException(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Cannot Proceed without PDP_URLs");
}
}
- private static void readPDPParam(String pdpVal) throws PAPException{
- if(pdpVal.contains(",")){
+ private static void readPDPParam(String pdpVal) throws PAPException {
+ if (pdpVal.contains(",")) {
List<String> pdpValues = new ArrayList<>(Arrays.asList(pdpVal.split("\\s*,\\s*")));
- if(pdpValues.size()==3){
+ if (pdpValues.size() == 3) {
// 1:2 will be UserID:Password
String userID = pdpValues.get(1);
String pass = PeCryptoUtils.decrypt(pdpValues.get(2));
Base64.Encoder encoder = Base64.getEncoder();
// 0 - PDPURL
- pdpMap.put(pdpValues.get(0), encoder.encodeToString((userID+":"+pass).getBytes(StandardCharsets.UTF_8)));
- }else{
+ 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 PAPException(XACMLErrorConstants.ERROR_PERMISSIONS + "No enough Credentials to send Request. " + pdpValues);
+ throw new PAPException(
+ XACMLErrorConstants.ERROR_PERMISSIONS + "No enough Credentials to send Request. " + pdpValues);
}
- }else{
+ } else {
PolicyLogger.error(MessageCodes.ERROR_PERMISSIONS + "No Credentials to send Request: " + pdpVal);
- throw new PAPException(XACMLErrorConstants.ERROR_PERMISSIONS +"No enough Credentials to send Request.");
+ throw new PAPException(XACMLErrorConstants.ERROR_PERMISSIONS + "No enough Credentials to send Request.");
}
}
- public static String getEncoding(String pdpID){
+ 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{
+ if (pdpMap != null && (!pdpMap.isEmpty())) {
+ try {
encoding = pdpMap.get(pdpID);
- } catch(Exception e){
+ } catch (Exception e) {
PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "CheckPDP", "Exception encoding");
}
return encoding;
- }else{
+ } 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
index 94cd9c798..323b89a01 100644
--- 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
@@ -2,14 +2,14 @@
* ============LICENSE_START=======================================================
* ONAP-PAP-REST
* ================================================================================
- * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -41,13 +41,12 @@ import org.apache.commons.logging.LogFactory;
@WebFilter("/*")
public class PAPAuthenticationFilter implements Filter {
- private static final Log logger = LogFactory.getLog(PAPAuthenticationFilter.class);
+ 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 {
-
+ public void doFilter(ServletRequest request, ServletResponse response, FilterChain filter)
+ throws IOException, ServletException {
if (request instanceof HttpServletRequest) {
HttpServletRequest httpServletRequest = (HttpServletRequest) request;
@@ -57,7 +56,7 @@ public class PAPAuthenticationFilter implements Filter {
logger.info("Request URI: " + url);
- //getting authentication credentials
+ // getting authentication credentials
authCredentials = httpServletRequest.getHeader(AUTHENTICATION_HEADER);
// Check Authentication credentials
@@ -65,17 +64,17 @@ public class PAPAuthenticationFilter implements Filter {
boolean authenticationStatus = authenticationService.authenticate(authCredentials);
if (authenticationStatus) {
- //indicates the request comes from Traditional Admin Console or PolicyEngineAPI
- if ("/pap/".equals(url)){
+ // indicates the request comes from Traditional Admin Console or PolicyEngineAPI
+ if ("/pap/".equals(url)) {
logger.info("Request comes from Traditional Admin Console or PolicyEngineAPI");
- //forward request to the XACMLPAPServlet if authenticated
+ // forward request to the XACMLPAPServlet if authenticated
request.getRequestDispatcher("/pap/pap/").forward(request, response);
- }else if (url.startsWith("/pap/onap/") && response instanceof HttpServletResponse){
- //indicates the request comes from the ONAP Portal onap-sdk-app
- HttpServletResponse alteredResponse = ((HttpServletResponse)response);
+ } else if (url.startsWith("/pap/onap/") && response instanceof HttpServletResponse) {
+ // indicates the request comes from the ONAP Portal onap-sdk-app
+ 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
+ // Spring dispatcher servlet is at the end of the filter chain at /pap/onap/ path
filter.doFilter(request, response);
}
} else {
@@ -88,22 +87,23 @@ public class PAPAuthenticationFilter implements Filter {
}
}
- //method to add CorsHeaders for onap portal rest call
+ // 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");
+ 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() {
- //Empty
+ // Empty
}
@Override
public void init(FilterConfig arg0) throws ServletException {
- //Empty
+ // Empty
}
}
diff --git a/ONAP-PAP-REST/src/main/resources/META-INF/drop.ddl b/ONAP-PAP-REST/src/main/resources/META-INF/drop.ddl
index 062169345..d28a00dde 100644
--- a/ONAP-PAP-REST/src/main/resources/META-INF/drop.ddl
+++ b/ONAP-PAP-REST/src/main/resources/META-INF/drop.ddl
@@ -20,7 +20,7 @@
DROP TABLE IF EXISTS ConfigurationDataEntity
DROP TABLE IF EXISTS PolicyEntity
-DROP TABLE IF EXISTS PolicyDBDaoEntity
+DROP TABLE IF EXISTS PolicyDbDaoEntity
DROP TABLE IF EXISTS ActionBodyEntity
DROP SEQUENCE IF EXISTS seqPolicy
DROP SEQUENCE IF EXISTS seqConfig
diff --git a/ONAP-PAP-REST/src/main/resources/META-INF/persistence.xml b/ONAP-PAP-REST/src/main/resources/META-INF/persistence.xml
index 7be95014d..fcfe9d271 100644
--- a/ONAP-PAP-REST/src/main/resources/META-INF/persistence.xml
+++ b/ONAP-PAP-REST/src/main/resources/META-INF/persistence.xml
@@ -22,7 +22,7 @@
<persistence-unit name="XACML-PAP-REST">
<class>org.onap.policy.rest.jpa.PolicyEntity</class>
<class>org.onap.policy.rest.jpa.ConfigurationDataEntity</class>
- <class>org.onap.policy.rest.jpa.PolicyDBDaoEntity</class>
+ <class>org.onap.policy.rest.jpa.PolicyDbDaoEntity</class>
<class>org.onap.policy.rest.jpa.GroupEntity</class>
<class>org.onap.policy.rest.jpa.PdpEntity</class>
<class>org.onap.policy.rest.jpa.ActionBodyEntity</class>
@@ -40,7 +40,7 @@
<class>org.onap.policy.rest.jpa.ActionPolicyDict</class>
<class>org.onap.policy.rest.jpa.DecisionSettings</class>
<class>org.onap.policy.rest.jpa.MicroServiceModels</class>
- <class>org.onap.policy.rest.jpa.BRMSParamTemplate</class>
+ <class>org.onap.policy.rest.jpa.BrmsParamTemplate</class>
<class>org.onap.policy.rest.jpa.PolicyEditorScopes</class>
<!-- unique to PolicyEngineUtils - will be audited from PAP -->
<class>org.onap.policy.jpa.BackUpMonitorEntity</class>
@@ -109,7 +109,7 @@
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<class>org.onap.policy.rest.jpa.PolicyEntity</class>
<class>org.onap.policy.rest.jpa.ConfigurationDataEntity</class>
- <class>org.onap.policy.rest.jpa.PolicyDBDaoEntity</class>
+ <class>org.onap.policy.rest.jpa.PolicyDbDaoEntity</class>
<class>org.onap.policy.rest.jpa.GroupEntity</class>
<class>org.onap.policy.rest.jpa.PdpEntity</class>
<class>org.onap.policy.rest.jpa.ActionBodyEntity</class>
@@ -131,11 +131,11 @@
<class>org.onap.policy.rest.jpa.ActionList</class>
<class>org.onap.policy.rest.jpa.AddressGroup</class>
<class>org.onap.policy.rest.jpa.AttributeAssignment</class>
- <class>org.onap.policy.rest.jpa.BRMSParamTemplate</class>
+ <class>org.onap.policy.rest.jpa.BrmsParamTemplate</class>
<class>org.onap.policy.rest.jpa.ClosedLoopD2Services</class>
<class>org.onap.policy.rest.jpa.ClosedLoopSite</class>
- <class>org.onap.policy.rest.jpa.DCAEUsers</class>
- <class>org.onap.policy.rest.jpa.DCAEuuid</class>
+ <class>org.onap.policy.rest.jpa.DcaeUsers</class>
+ <class>org.onap.policy.rest.jpa.Dcaeuuid</class>
<class>org.onap.policy.rest.jpa.DescriptiveScope</class>
<class>org.onap.policy.rest.jpa.OnapName</class>
<class>org.onap.policy.rest.jpa.EnforcingType</class>
@@ -146,12 +146,12 @@
<class>org.onap.policy.rest.jpa.MicroServiceLocation</class>
<class>org.onap.policy.rest.jpa.Obadvice</class>
<class>org.onap.policy.rest.jpa.ObadviceExpression</class>
- <class>org.onap.policy.rest.jpa.PEPOptions</class>
- <class>org.onap.policy.rest.jpa.PIPConfigParam</class>
- <class>org.onap.policy.rest.jpa.PIPConfiguration</class>
- <class>org.onap.policy.rest.jpa.PIPResolver</class>
- <class>org.onap.policy.rest.jpa.PIPResolverParam</class>
- <class>org.onap.policy.rest.jpa.PIPType</class>
+ <class>org.onap.policy.rest.jpa.PepOptions</class>
+ <class>org.onap.policy.rest.jpa.PipConfigParam</class>
+ <class>org.onap.policy.rest.jpa.PipConfiguration</class>
+ <class>org.onap.policy.rest.jpa.PipResolver</class>
+ <class>org.onap.policy.rest.jpa.PipResolverParam</class>
+ <class>org.onap.policy.rest.jpa.PipType</class>
<class>org.onap.policy.rest.jpa.PolicyAlgorithms</class>
<class>org.onap.policy.rest.jpa.PolicyManagement</class>
<class>org.onap.policy.rest.jpa.PolicyScopeService</class>
@@ -166,12 +166,12 @@
<class>org.onap.policy.rest.jpa.RuleAlgorithms</class>
<class>org.onap.policy.rest.jpa.SecurityZone</class>
<class>org.onap.policy.rest.jpa.ServiceList</class>
- <class>org.onap.policy.rest.jpa.SystemLogDB</class>
+ <class>org.onap.policy.rest.jpa.SystemLogDb</class>
<class>org.onap.policy.rest.jpa.TermList</class>
<class>org.onap.policy.rest.jpa.VarbindDictionary</class>
- <class>org.onap.policy.rest.jpa.VMType</class>
- <class>org.onap.policy.rest.jpa.VNFType</class>
- <class>org.onap.policy.rest.jpa.VSCLAction</class>
+ <class>org.onap.policy.rest.jpa.VmType</class>
+ <class>org.onap.policy.rest.jpa.VnfType</class>
+ <class>org.onap.policy.rest.jpa.VsclAction</class>
<class>org.onap.policy.rest.jpa.Zone</class>
<!-- unique to PolicyEngineUtils -->
<class>org.onap.policy.jpa.BackUpMonitorEntity</class>
diff --git a/ONAP-PAP-REST/src/main/resources/logback.xml b/ONAP-PAP-REST/src/main/resources/logback.xml
index d7b118178..2cf21e105 100644
--- a/ONAP-PAP-REST/src/main/resources/logback.xml
+++ b/ONAP-PAP-REST/src/main/resources/logback.xml
@@ -2,14 +2,14 @@
============LICENSE_START=======================================================
ONAP-PAP-REST
================================================================================
- Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
================================================================================
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
-
+
http://www.apache.org/licenses/LICENSE-2.0
-
+
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -22,74 +22,74 @@
<!--<jmxConfigurator /> -->
<!-- directory path for all other type logs -->
<property name="logDir" value="${POLICY_LOGS}" />
-
+
<!-- directory path for debugging type logs -->
<property name="debugDir" value="${POLICY_LOGS}" />
-
- <!-- specify the component name
+
+ <!-- specify the component name
<ONAP-component-name>::= "MSO" | "DCAE" | "ASDC " | "AAI" |"Policy" | "SDNC" | "AC" -->
<property name="componentName" value="policy"></property>
<property name="subComponentName" value="pap"></property>
-
+
<!-- log file names -->
<property name="errorLogName" value="error" />
<property name="metricsLogName" value="metrics" />
<property name="auditLogName" value="audit" />
<property name="debugLogName" value="debug" />
-
-
+
+
<!-- modified time stamp format -->
-
- <!-- A U D I T
- <property name="defaultAuditPattern" value="%X{BeginTimestamp}|%X{EndTimestamp}|%X{RequestId}|%X{ServiceInstanceId}|%thread|%X{ServerName}|%X{ServiceName}|%X{PartnerName}|%X{StatusCode}|%X{ResponseCode}|%X{ResponseDescription}|%X{InstanceUUID}|%.-5level|%X{AlertSeverity}|%X{ServerIPAddress}|%X{ElapsedTime}|%X{ServerFQDN}|%X{RemoteHost}|%X{ClassName}||%X{ProcessKey}|%X{TargetVirtualEntity}|%X{CustomField1}|%X{CustomField2}|%X{CustomField3}|%X{CustomField4}|%msg%n" />
+
+ <!-- A U D I T
+ <property name="defaultAuditPattern" value="%X{BeginTimestamp}|%X{EndTimestamp}|%X{RequestId}|%X{ServiceInstanceId}|%thread|%X{ServerName}|%X{ServiceName}|%X{PartnerName}|%X{StatusCode}|%X{ResponseCode}|%X{ResponseDescription}|%X{InstanceUUID}|%.-5level|%X{Severity}|%X{ServerIPAddress}|%X{ElapsedTime}|%X{ServerFQDN}|%X{RemoteHost}|%X{ClassName}||%X{ProcessKey}|%X{TargetVirtualEntity}|%X{CustomField1}|%X{CustomField2}|%X{CustomField3}|%X{CustomField4}|%msg%n" />
<property name="defaultAuditPattern" value="%X{BeginTimestamp}|%X{EndTimestamp}|%X{requestId}|%X{serviceInstanceId}|%t|%X{serverName}|%X{serviceName}|%X{PartnerName}|%X{StatusCode}|%X{ResponseCode}|%X{ResponseDescription}|%X{instanceUuid}|%p|%X{severity}|%X{serverIpAddress}|%X{ElapsedTime}|%X{server}|%X{clientIpAddress}|%c||%X{ProcessKey}|%X{TargetVirtualEntity}|%X{CustomField1}|%X{CustomField2}|%X{CustomField3}|%X{CustomField4}|%msg%n" />
-->
<property name="defaultAuditPattern" value="%X{TransactionBeginTimestamp}|%X{TransactionEndTimestamp}|%X{requestId}|%X{serviceInstanceId}|%t|%X{serverName}|%X{serviceName}|%X{partnerName}|%X{statusCode}|%X{ResponseCode}|%X{ResponseDescription}|%X{instanceUuid}|%p|%X{severity}|%X{serverIpAddress}|%X{TransactionElapsedTime}|%X{server}|%X{clientIpAddress}|%c||%X{ProcessKey}|%X{CustomField1}|%X{CustomField2}|%X{CustomField3}|%X{CustomField4}|%msg%n" />
-
-
-
- <!-- M E T R I C
- <property name="defaultMetricPattern" value="%X{BeginTimestamp}|%X{EndTimestamp}|%X{RequestId}|%X{ServiceInstanceId}|%thread|%X{ServerName}|%X{ServiceName}|%X{PartnerName}|%X{TargetEntity}|%X{TargetServiceName}|%X{StatusCode}|%X{ResponseCode}|%X{ResponseDescription}|%X{InstanceUUID}|%.-5level|%X{AlertSeverity}|%X{ServerIPAddress}|%X{ElapsedTime}|%X{ServerFQDN}|%X{RemoteHost}|%X{ClassName}||%X{ProcessKey}|%X{TargetVirtualEntity}|%X{CustomField1}|%X{CustomField2}|%X{CustomField3}|%X{CustomField4}|%msg%n" />
+
+
+
+ <!-- M E T R I C
+ <property name="defaultMetricPattern" value="%X{BeginTimestamp}|%X{EndTimestamp}|%X{RequestId}|%X{ServiceInstanceId}|%thread|%X{ServerName}|%X{ServiceName}|%X{PartnerName}|%X{TargetEntity}|%X{TargetServiceName}|%X{StatusCode}|%X{ResponseCode}|%X{ResponseDescription}|%X{InstanceUUID}|%.-5level|%X{Severity}|%X{ServerIPAddress}|%X{ElapsedTime}|%X{ServerFQDN}|%X{RemoteHost}|%X{ClassName}||%X{ProcessKey}|%X{TargetVirtualEntity}|%X{CustomField1}|%X{CustomField2}|%X{CustomField3}|%X{CustomField4}|%msg%n" />
-->
<property name="defaultMetricPattern" value="%X{MetricBeginTimestamp}|%X{MetricEndTimestamp}|%X{requestId}|%X{serviceInstanceId}|%t|%X{serverName}|%X{serviceName}|%X{partnerName}|%X{targetEntity}|%X{targetServiceName}|%X{statusCode}|%X{ResponseCode}|%X{ResponseDescription}|%X{InstanceUUID}|%p|%X{severity}|%X{serverIpAddress}|%X{MetricElapsedTime}|%X{server}|%X{clientIpAddress}|%c||%X{ProcessKey}|%X{TargetVirtualEntity}|%X{CustomField1}|%X{CustomField2}|%X{CustomField3}|%X{CustomField4}|%msg%n" />
-
-
-
-
+
+
+
+
<!-- E R R O R
<property name="defaultErrorPattern" value="%d{yyyy-MM-dd'T'HH:mm:ss.SSS+00:00, UTC}|%X{RequestId}|%thread|%X{ServiceName}|%X{PartnerName}|%X{TargetEntity}|%X{TargetServiceName}|%X{ErrorCategory}|%X{ErrorCode}|%X{ErrorDesciption}|%msg%n" />
-->
<property name="defaultErrorPattern" value="%d{yyyy-MM-dd'T'HH:mm:ss.SSS+00:00, UTC}|%X{requestId}|%t|%X{serviceName}|%X{PartnerName}|%X{TargetEntity}|%X{TargetServiceName}|%X{ErrorCategory}|%X{ErrorCode}|%X{ErrorDesciption}|%msg%n" />
-
-
-
+
+
+
<!-- D E B U G
- <property name="debugLoggerPatternOld" value="%d{MM/dd-HH:mm:ss.SSS}|%X{RequestId}|%X{ServiceInstanceId}|%thread|%X{ServiceName}|%X{InstanceUUID}|%.-5level|%X{AlertSeverity}|%X{ServerIPAddress}|%X{ServerFQDN}|%X{RemoteHost}|%X{Timer}|[%caller{3}]|%msg%n" />
- <property name="debugLoggerPattern" value="%X{BeginTimestamp}|%X{EndTimestamp}|%X{RequestId}|%X{ServiceInstanceId}|%thread|%X{ServerName}|%X{ServiceName}|%X{PartnerName}|%X{StatusCode}|%X{ResponseCode}|%X{ResponseDescription}|%X{ServiceName}|%X{InstanceUUID}|%.-5level|%X{AlertSeverity}|%X{ServerIPAddress}|%X{ElapsedTime}|%X{ServerFQDN}|%X{RemoteHost}|%X{ClassName}||%X{ProcessKey}|%X{CustomField1}|%X{CustomField2}|%X{CustomField3}|%X{CustomField4}|%msg%n" /> -->
+ <property name="debugLoggerPatternOld" value="%d{MM/dd-HH:mm:ss.SSS}|%X{RequestId}|%X{ServiceInstanceId}|%thread|%X{ServiceName}|%X{InstanceUUID}|%.-5level|%X{Severity}|%X{ServerIPAddress}|%X{ServerFQDN}|%X{RemoteHost}|%X{Timer}|[%caller{3}]|%msg%n" />
+ <property name="debugLoggerPattern" value="%X{BeginTimestamp}|%X{EndTimestamp}|%X{RequestId}|%X{ServiceInstanceId}|%thread|%X{ServerName}|%X{ServiceName}|%X{PartnerName}|%X{StatusCode}|%X{ResponseCode}|%X{ResponseDescription}|%X{ServiceName}|%X{InstanceUUID}|%.-5level|%X{Severity}|%X{ServerIPAddress}|%X{ElapsedTime}|%X{ServerFQDN}|%X{RemoteHost}|%X{ClassName}||%X{ProcessKey}|%X{CustomField1}|%X{CustomField2}|%X{CustomField3}|%X{CustomField4}|%msg%n" /> -->
-->
- <property name="debugLoggerPattern" value="%d{yyyy-MM-dd'T'HH:mm:ss.SSS+00:00, UTC}|%X{RequestId}|%msg%n" />
-
-
-
- <!-- D E F A U L T
- <property name="defaultPatternOld" value="%d{MM/dd-HH:mm:ss.SSS}|%logger|%X{RequestId}|%X{ServiceInstanceId}|%thread|%X{ServiceName}|%X{InstanceUUID}|%.-5level|%X{AlertSeverity}|%X{ServerIPAddress}|%X{ServerFQDN}|%X{RemoteHost}|%X{ClassName}|%X{Timer}|%msg%n" />
- <property name="defaultPattern" value="%X{BeginTimestamp}|%X{EndTimestamp}|%X{RequestId}|%X{ServiceInstanceId}|%thread|%X{ServerName}|%X{ServiceName}|%X{PartnerName}|%X{TargetEntity}|%X{TargetServiceName}|%X{StatusCode}|%X{ResponseCode}|%X{ResponseDescription}|%X{InstanceUUID}|%.-5level|%X{AlertSeverity}|%X{ServerIPAddress}|%X{ElapsedTime}|%X{ServerFQDN}|%X{RemoteHost}|%X{ClassName}||%X{ProcessKey}|%X{TargetVirtualEntity}|%X{CustomField1}|%X{CustomField2}|%X{CustomField3}|%X{CustomField4}|%msg%n" />
+ <property name="debugLoggerPattern" value="%d{yyyy-MM-dd'T'HH:mm:ss.SSS+00:00, UTC}|%X{RequestId}|%msg%n" />
+
+
+
+ <!-- D E F A U L T
+ <property name="defaultPatternOld" value="%d{MM/dd-HH:mm:ss.SSS}|%logger|%X{RequestId}|%X{ServiceInstanceId}|%thread|%X{ServiceName}|%X{InstanceUUID}|%.-5level|%X{Severity}|%X{ServerIPAddress}|%X{ServerFQDN}|%X{RemoteHost}|%X{ClassName}|%X{Timer}|%msg%n" />
+ <property name="defaultPattern" value="%X{BeginTimestamp}|%X{EndTimestamp}|%X{RequestId}|%X{ServiceInstanceId}|%thread|%X{ServerName}|%X{ServiceName}|%X{PartnerName}|%X{TargetEntity}|%X{TargetServiceName}|%X{StatusCode}|%X{ResponseCode}|%X{ResponseDescription}|%X{InstanceUUID}|%.-5level|%X{Severity}|%X{ServerIPAddress}|%X{ElapsedTime}|%X{ServerFQDN}|%X{RemoteHost}|%X{ClassName}||%X{ProcessKey}|%X{TargetVirtualEntity}|%X{CustomField1}|%X{CustomField2}|%X{CustomField3}|%X{CustomField4}|%msg%n" />
-->
<property name="defaultPattern" value="%d{yyyy-MM-dd'T'HH:mm:ss.SSSXXX, UTC}|%X{requestId}|%X{serviceInstanceId}|%t|%X{serverName}|%X{serviceName}|%X{instanceUuid}|%p|%X{severity}|%X{serverIpAddress}|%X{server}|%X{clientIpAddress}|%c||%msg%n" />
-
-
-
+
+
+
<!-- P A T H
<property name="logDirectory" value="${logDir}/${componentName}/${subComponentName}" />
<property name="debugLogDirectory" value="${debugDir}/${componentName}/${subComponentName}" />
- -->
+ -->
<property name="logDirectory" value="${logDir}/${componentName}/${subComponentName}" />
<property name="debugLogDirectory" value="${debugDir}/${componentName}/${subComponentName}" />
-
-
-
+
+
+
<!-- Example evaluator filter applied against console appender -->
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
@@ -101,23 +101,23 @@
<!-- EELF Appenders -->
<!-- ============================================================================ -->
- <!-- The EELFAppender is used to record events to the general application
+ <!-- The EELFAppender is used to record events to the general application
log -->
-
- <!-- EELF Audit Appender. This appender is used to record audit engine
- related logging events. The audit logger and appender are specializations
- of the EELF application root logger and appender. This can be used to segregate
- Policy engine events from other components, or it can be eliminated to record
+
+ <!-- EELF Audit Appender. This appender is used to record audit engine
+ related logging events. The audit logger and appender are specializations
+ of the EELF application root logger and appender. This can be used to segregate
+ Policy engine events from other components, or it can be eliminated to record
these events as part of the application root log. -->
-
+
<appender name="EELFAudit"
class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>${logDirectory}/${auditLogName}.log</file>
<rollingPolicy
class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
<fileNamePattern>${logDirectory}/${auditLogName}.%d{yyyy-MM-dd}.%i.log.zip</fileNamePattern>
-
- <!-- keep 30 days' worth of history capped at 3GB total size -->
+
+ <!-- keep 30 days' worth of history capped at 3GB total size -->
<maxFileSize>50MB</maxFileSize>
<maxHistory>30</maxHistory>
<totalSizeCap>10GB</totalSizeCap>
@@ -141,8 +141,8 @@
<rollingPolicy
class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
<fileNamePattern>${logDirectory}/${metricsLogName}.%d{yyyy-MM-dd}.%i.log.zip</fileNamePattern>
-
- <!-- keep 30 days' worth of history capped at 3GB total size -->
+
+ <!-- keep 30 days' worth of history capped at 3GB total size -->
<maxFileSize>50MB</maxFileSize>
<maxHistory>30</maxHistory>
<totalSizeCap>10GB</totalSizeCap>
@@ -151,7 +151,7 @@
<pattern>${defaultMetricPattern}</pattern>
</encoder>
</appender>
-
+
<appender name="asyncEELFMetrics" class="ch.qos.logback.classic.AsyncAppender">
<queueSize>256</queueSize>
<appender-ref ref="EELFMetrics"/>
@@ -159,15 +159,15 @@
-
+
<appender name="EELFError"
class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>${logDirectory}/${errorLogName}.log</file>
<rollingPolicy
class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
<fileNamePattern>${logDirectory}/${errorLogName}.%d{yyyy-MM-dd}.%i.log.zip</fileNamePattern>
-
- <!-- keep 30 days' worth of history capped at 3GB total size -->
+
+ <!-- keep 30 days' worth of history capped at 3GB total size -->
<maxFileSize>50MB</maxFileSize>
<maxHistory>30</maxHistory>
<totalSizeCap>10GB</totalSizeCap>
@@ -179,22 +179,22 @@
<pattern>${defaultErrorPattern}</pattern>
</encoder>
</appender>
-
+
<appender name="asyncEELFError" class="ch.qos.logback.classic.AsyncAppender">
<queueSize>256</queueSize>
<appender-ref ref="EELFError"/>
</appender>
-
+
<appender name="EELFDebug"
class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>${debugLogDirectory}/${debugLogName}.log</file>
<rollingPolicy
class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
<fileNamePattern>${debugLogDirectory}/${debugLogName}.%d{yyyy-MM-dd}.%i.log.zip</fileNamePattern>
-
- <!-- keep 30 days' worth of history capped at 3GB total size -->
+
+ <!-- keep 30 days' worth of history capped at 3GB total size -->
<maxFileSize>50MB</maxFileSize>
<maxHistory>30</maxHistory>
<totalSizeCap>10GB</totalSizeCap>
@@ -206,36 +206,36 @@
<pattern>${debugLoggerPattern}</pattern>
</encoder>
</appender>
-
+
<appender name="asyncEELFDebug" class="ch.qos.logback.classic.AsyncAppender">
<queueSize>256</queueSize>
<appender-ref ref="EELFDebug" />
<includeCallerData>true</includeCallerData>
</appender>
-
-
+
+
<!-- ============================================================================ -->
<!-- EELF loggers -->
<!-- ============================================================================ -->
-
+
<logger name="com.att.eelf.audit" level="info" additivity="false">
<appender-ref ref="asyncEELFAudit" />
</logger>
-
+
<logger name="com.att.eelf.metrics" level="info" additivity="false">
<appender-ref ref="asyncEELFMetrics" />
</logger>
-
+
<logger name="com.att.eelf.error" level="error" additivity="false">
<appender-ref ref="asyncEELFError" />
</logger>
-
+
<logger name="com.att.eelf.debug" level="info" additivity="false">
<appender-ref ref="asyncEELFDebug" />
</logger>
-
-
-
+
+
+
<root level="INFO">
<appender-ref ref="asyncEELFDebug" />
<appender-ref ref="asyncEELFError" />
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
index 9fded580c..b6b674dc7 100644
--- 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
@@ -86,7 +86,7 @@ public class DbAuditCompareEntriesTest {
persistenceUnit = "testPapPU";
resourceName = "siteA.pap1";
- //Clean the iaTest DB table for IntegrityAuditEntity entries
+ // Clean the iaTest DB table for IntegrityAuditEntity entries
cleanDb(persistenceUnit, properties);
logger.info("setUp: Exiting");
@@ -95,11 +95,11 @@ public class DbAuditCompareEntriesTest {
@After
public void tearDown() throws Exception {
logger.info("tearDown: Entering");
- //nothing to do
+ // nothing to do
logger.info("tearDown: Exiting");
}
- public void cleanDb(String persistenceUnit, Properties properties){
+ public void cleanDb(String persistenceUnit, Properties properties) {
logger.debug("cleanDb: enter");
EntityManagerFactory emf = Persistence.createEntityManagerFactory(persistenceUnit, properties);
@@ -119,7 +119,6 @@ public class DbAuditCompareEntriesTest {
logger.debug("cleanDb: exit");
}
-
/*
* Tests that a comparison between hashsets is successful if
* the entries match
@@ -128,20 +127,18 @@ public class DbAuditCompareEntriesTest {
public void runAllTests() throws Exception {
logger.info("runAllTests: Entering");
-
testIntegrityAuditEntity();
testBackupMonitorEntity();
testStateManagementEntity();
testForwardProgressEntity();
testResourceRegistrationEntity();
- //clean up the IntegrityAuditEntity table
+ // clean up the IntegrityAuditEntity table
cleanDb(persistenceUnit, properties);
logger.info("runAllTests: Exit");
}
-
public void testIntegrityAuditEntity() throws Exception {
logger.info("testIntegrityAuditEntity: Entering");
@@ -149,10 +146,10 @@ public class DbAuditCompareEntriesTest {
DbAudit dbAudit = new DbAudit(dbDAO);
String className = null;
- //There is only one entry IntegrityAuditEntity, but we will check anyway
+ // There is only one entry IntegrityAuditEntity, but we will check anyway
Set<String> classNameSet = dbDAO.getPersistenceClassNames();
- for(String c : classNameSet){
- if (c.equals("org.onap.policy.common.ia.jpa.IntegrityAuditEntity")){
+ for (String c : classNameSet) {
+ if (c.equals("org.onap.policy.common.ia.jpa.IntegrityAuditEntity")) {
className = c;
}
}
@@ -231,7 +228,6 @@ public class DbAuditCompareEntriesTest {
// Two entries with the same field values
-
entry1.setFlag("flag1");
entry1.setResourceNodeName("node1");
entry1.setResourceName("resourceName");
@@ -248,17 +244,14 @@ public class DbAuditCompareEntriesTest {
Set<Object> 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
@@ -272,8 +265,7 @@ public class DbAuditCompareEntriesTest {
result = dbAudit.compareEntries(myEntries, theirEntries);
-
- //Assert that there was one mismatch
+ // Assert that there was one mismatch
assertEquals(1, result.size());
logger.info("testBackupMonitorEntity: Exit");
@@ -308,17 +300,14 @@ public class DbAuditCompareEntriesTest {
Set<Object> 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
@@ -332,8 +321,7 @@ public class DbAuditCompareEntriesTest {
result = dbAudit.compareEntries(myEntries, theirEntries);
-
- //Assert that there was one mismatch
+ // Assert that there was one mismatch
assertEquals(1, result.size());
logger.info("testStateManagementEntity: Exit");
@@ -365,15 +353,14 @@ public class DbAuditCompareEntriesTest {
Set<Object> 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
@@ -387,8 +374,7 @@ public class DbAuditCompareEntriesTest {
result = dbAudit.compareEntries(myEntries, theirEntries);
-
- //Assert that there was one mismatch
+ // Assert that there was one mismatch
assertEquals(1, result.size());
logger.info("testForwardProgressEntity: Exit");
@@ -422,15 +408,14 @@ public class DbAuditCompareEntriesTest {
Set<Object> 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
@@ -444,10 +429,9 @@ public class DbAuditCompareEntriesTest {
result = dbAudit.compareEntries(myEntries, theirEntries);
-
- //Assert that there was one mismatch
+ // 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/test/UpdateOthersPAPSTest.java b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/test/UpdateOthersPAPSTest.java
index 5a8e20b26..fcec4a652 100644
--- a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/test/UpdateOthersPAPSTest.java
+++ b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/test/UpdateOthersPAPSTest.java
@@ -2,14 +2,14 @@
* ============LICENSE_START=======================================================
* ONAP-PAP-REST
* ================================================================================
- * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2018-2020 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -17,12 +17,14 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.policy.pap.test;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
+import static org.mockito.ArgumentMatchers.anyString;
import java.io.File;
import java.util.ArrayList;
@@ -34,7 +36,6 @@ import org.json.JSONObject;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
-import org.mockito.Matchers;
import org.mockito.Mockito;
import org.onap.policy.common.logging.flexlogger.FlexLogger;
import org.onap.policy.common.logging.flexlogger.Logger;
@@ -42,13 +43,16 @@ import org.onap.policy.pap.xacml.rest.UpdateOthersPAPS;
import org.onap.policy.pap.xacml.rest.adapters.UpdateObjectData;
import org.onap.policy.pap.xacml.rest.components.Policy;
import org.onap.policy.rest.dao.CommonClassDao;
-import org.onap.policy.rest.jpa.PolicyDBDaoEntity;
+import org.onap.policy.rest.jpa.PolicyDbDaoEntity;
import org.powermock.api.mockito.PowerMockito;
+import org.powermock.core.classloader.annotations.PowerMockIgnore;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import org.springframework.mock.web.MockHttpServletResponse;
@RunWith(PowerMockRunner.class)
+@PowerMockIgnore({"com.sun.org.apache.xalan.*", "com.sun.org.apache.xerces.*", "jdk.internal.reflect.*", "javax.xml.*", "org.xml.*", "org.w3c.*"})
+@PrepareForTest(UpdateOthersPAPS.class)
public class UpdateOthersPAPSTest {
private static Logger logger = FlexLogger.getLogger(UpdateOthersPAPSTest.class);
@@ -60,28 +64,28 @@ public class UpdateOthersPAPSTest {
public void setUp() throws Exception {
logger.info("setUp: Entering");
commonClassDao = mock(CommonClassDao.class);
-
- request = mock(HttpServletRequest.class);
- response = new MockHttpServletResponse();
+
+ request = mock(HttpServletRequest.class);
+ response = new MockHttpServletResponse();
List<Object> data = new ArrayList<>();
- PolicyDBDaoEntity entity = new PolicyDBDaoEntity();
- entity.setPolicyDBDaoUrl("http://localhost:8070/pap");
+ PolicyDbDaoEntity entity = new PolicyDbDaoEntity();
+ entity.setPolicyDbDaoUrl("http://localhost:8070/pap");
entity.setUsername("test");
entity.setPassword("test");
- PolicyDBDaoEntity entity1 = new PolicyDBDaoEntity();
- entity1.setPolicyDBDaoUrl("http://localhost:8071/pap");
+ PolicyDbDaoEntity entity1 = new PolicyDbDaoEntity();
+ entity1.setPolicyDbDaoUrl("http://localhost:8071/pap");
entity1.setUsername("test");
entity1.setPassword("test");
data.add(entity);
data.add(entity1);
- System.setProperty("xacml.rest.pap.url","http://localhost:8070/pap");
- when(commonClassDao.getData(PolicyDBDaoEntity.class)).thenReturn(data);
+ System.setProperty("xacml.rest.pap.url", "http://localhost:8070/pap");
+ when(commonClassDao.getData(PolicyDbDaoEntity.class)).thenReturn(data);
}
@Test
- public void testNotifyOthersPAPsToUpdateConfigurations(){
+ public void testNotifyOthersPAPsToUpdateConfigurations() {
UpdateOthersPAPS updateOtherPaps = new UpdateOthersPAPS();
UpdateOthersPAPS.setCommonClassDao(commonClassDao);
when(request.getParameter("action")).thenReturn("rename");
@@ -98,7 +102,7 @@ public class UpdateOthersPAPSTest {
@PrepareForTest({Policy.class})
@Test
- public void testUpdateConfiguration() throws Exception{
+ public void testUpdateConfiguration() throws Exception {
UpdateOthersPAPS updateOtherPaps = new UpdateOthersPAPS();
UpdateObjectData data = new UpdateObjectData();
PowerMockito.mockStatic(Policy.class);
@@ -109,7 +113,8 @@ public class UpdateOthersPAPSTest {
when(Policy.getActionHome()).thenReturn("test");
File mockedFile = Mockito.mock(File.class);
Mockito.when(mockedFile.exists()).thenReturn(true);
- PowerMockito.whenNew(File.class).withParameterTypes(String.class).withArguments(Matchers.anyString()).thenReturn(mockedFile);
+ PowerMockito.whenNew(File.class).withParameterTypes(String.class).withArguments(anyString())
+ .thenReturn(mockedFile);
updateOtherPaps.updateConfiguration(data, response);
assertTrue(response.getStatus() == 200);
}
diff --git a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/test/XACMLPAPTest.java b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/test/XACMLPAPTest.java
index 6ebc74a91..f9faa2928 100644
--- a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/test/XACMLPAPTest.java
+++ b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/test/XACMLPAPTest.java
@@ -24,7 +24,9 @@ package org.onap.policy.pap.test;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.mockito.Mockito.when;
+
import com.mockrunner.mock.web.MockServletInputStream;
+
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
@@ -36,11 +38,13 @@ import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
+
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
+
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.tomcat.dbcp.dbcp2.BasicDataSource;
@@ -67,7 +71,7 @@ import org.onap.policy.pap.xacml.rest.policycontroller.PolicyCreation;
import org.onap.policy.pap.xacml.rest.util.DictionaryUtils;
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.BrmsParamTemplate;
import org.onap.policy.rest.jpa.Category;
import org.onap.policy.rest.jpa.FunctionDefinition;
import org.onap.policy.rest.jpa.PolicyEditorScopes;
@@ -79,7 +83,6 @@ import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.mock.web.MockServletConfig;
import org.springframework.orm.hibernate4.LocalSessionFactoryBuilder;
-
public class XACMLPAPTest {
private static final Log logger = LogFactory.getLog(XACMLPAPTest.class);
@@ -93,10 +96,6 @@ public class XACMLPAPTest {
private static SessionFactory sessionFactory;
private static CommonClassDao commonClassDao;
- private static final String DEFAULT_DB_DRIVER = "org.h2.Driver";
- private static final String DEFAULT_DB_USER = "sa";
- private static final String DEFAULT_DB_PWD = "";
-
@BeforeClass
public static void beforeClassSetup() throws ServletException {
sessionFactory = PolicyDBDaoTest.setupH2DbDaoImpl("xacmlpaptest");
@@ -127,6 +126,7 @@ public class XACMLPAPTest {
public void testInit() {
httpServletRequest = Mockito.mock(HttpServletRequest.class);
httpServletResponse = Mockito.mock(MockHttpServletResponse.class);
+ logger.info(httpServletResponse);
Mockito.when(httpServletRequest.getHeaderNames()).thenReturn(Collections.enumeration(headers));
Mockito.when(httpServletRequest.getAttributeNames()).thenReturn(Collections.enumeration(headers));
CommonClassDaoImpl.setSessionfactory(sessionFactory);
@@ -163,7 +163,8 @@ public class XACMLPAPTest {
MockServletInputStream mockInput =
new MockServletInputStream(PolicyUtils.objectToJsonString(newPAPPolicy).getBytes());
Mockito.when(httpServletRequest.getInputStream()).thenReturn(mockInput);
-
+ logger.info(httpServletRequest);
+ logger.info(httpServletResponse);
pap.service(httpServletRequest, httpServletResponse);
Mockito.verify(httpServletResponse).addHeader("operation", "create");
}
@@ -192,6 +193,8 @@ public class XACMLPAPTest {
Mockito.when(httpServletRequest.getInputStream()).thenReturn(mockInput);
setPolicyCreation();
+ logger.info(httpServletRequest);
+ logger.info(httpServletResponse);
pap.service(httpServletRequest, httpServletResponse);
Mockito.verify(httpServletResponse).addHeader("operation", "create");
}
@@ -215,6 +218,8 @@ public class XACMLPAPTest {
Mockito.when(httpServletRequest.getInputStream()).thenReturn(mockInput);
setPolicyCreation();
+ logger.info(httpServletRequest);
+ logger.info(httpServletResponse);
pap.service(httpServletRequest, httpServletResponse);
Mockito.verify(httpServletResponse).addHeader("operation", "create");
}
@@ -238,6 +243,8 @@ public class XACMLPAPTest {
Mockito.when(httpServletRequest.getInputStream()).thenReturn(mockInput);
setPolicyCreation();
+ logger.info(httpServletRequest);
+ logger.info(httpServletResponse);
pap.service(httpServletRequest, httpServletResponse);
Mockito.verify(httpServletResponse).addHeader("operation", "create");
}
@@ -257,6 +264,8 @@ public class XACMLPAPTest {
new MockServletInputStream(PolicyUtils.objectToJsonString(newPAPPolicy).getBytes());
Mockito.when(httpServletRequest.getInputStream()).thenReturn(mockInput);
+ logger.info(httpServletRequest);
+ logger.info(httpServletResponse);
pap.service(httpServletRequest, httpServletResponse);
Mockito.verify(httpServletResponse).addHeader("operation", "create");
}
@@ -287,6 +296,8 @@ public class XACMLPAPTest {
new MockServletInputStream(PolicyUtils.objectToJsonString(newPAPPolicy).getBytes());
Mockito.when(httpServletRequest.getInputStream()).thenReturn(mockInput);
+ logger.info(httpServletRequest);
+ logger.info(httpServletResponse);
pap.service(httpServletRequest, httpServletResponse);
Mockito.verify(httpServletResponse).addHeader("operation", "create");
}
@@ -318,11 +329,12 @@ public class XACMLPAPTest {
new MockServletInputStream(PolicyUtils.objectToJsonString(newPAPPolicy).getBytes());
Mockito.when(httpServletRequest.getInputStream()).thenReturn(mockInput);
+ logger.info(httpServletRequest);
+ logger.info(httpServletResponse);
pap.service(httpServletRequest, httpServletResponse);
Mockito.verify(httpServletResponse).addHeader("operation", "create");
}
-
@Test
public void testDecisonBLGuardPolicy() throws IOException, ServletException, SQLException {
httpServletRequest = Mockito.mock(HttpServletRequest.class);
@@ -346,6 +358,8 @@ public class XACMLPAPTest {
new MockServletInputStream(PolicyUtils.objectToJsonString(newPAPPolicy).getBytes());
Mockito.when(httpServletRequest.getInputStream()).thenReturn(mockInput);
+ logger.info(httpServletRequest);
+ logger.info(httpServletResponse);
pap.service(httpServletRequest, httpServletResponse);
Mockito.verify(httpServletResponse).addHeader("operation", "create");
}
@@ -369,6 +383,8 @@ public class XACMLPAPTest {
new MockServletInputStream(PolicyUtils.objectToJsonString(newPAPPolicy).getBytes());
Mockito.when(httpServletRequest.getInputStream()).thenReturn(mockInput);
+ logger.info(httpServletRequest);
+ logger.info(httpServletResponse);
pap.service(httpServletRequest, httpServletResponse);
Mockito.verify(httpServletResponse).addHeader("operation", "create");
}
@@ -425,11 +441,12 @@ public class XACMLPAPTest {
new MockServletInputStream(PolicyUtils.objectToJsonString(newPapPolicy).getBytes());
Mockito.when(httpServletRequest.getInputStream()).thenReturn(mockInput);
+ logger.info(httpServletRequest);
+ logger.info(httpServletResponse);
pap.service(httpServletRequest, httpServletResponse);
Mockito.verify(httpServletResponse).addHeader("operation", "create");
}
-
private void setPolicyCreation() {
CommonClassDao commonClassDao = Mockito.mock(CommonClassDao.class);
PolicyCreation.setCommonClassDao(commonClassDao);
@@ -442,7 +459,7 @@ public class XACMLPAPTest {
editorScope.setUserModifiedBy(userInfo);
Mockito.when(commonClassDao.getEntityItem(PolicyEditorScopes.class, "scopeName", "test"))
.thenReturn(editorScope);
- BRMSParamTemplate template = new BRMSParamTemplate();
+ BrmsParamTemplate template = new BrmsParamTemplate();
template.setRuleName("testPolicy");
template.setUserCreatedBy(userInfo);
String rule = "package com.sample;\n" + "import com.sample.DroolsTest.Message;\n" + "declare Params\n"
@@ -454,7 +471,7 @@ public class XACMLPAPTest {
+ "Params($param.samPoll > 50)\n" + "then\n" + "System.out.println(\"Firing rule 1\");\n"
+ "System.out.println($param);\n" + "end\n";
template.setRule(rule);
- Mockito.when(commonClassDao.getEntityItem(BRMSParamTemplate.class, "ruleName", "testPolicy"))
+ Mockito.when(commonClassDao.getEntityItem(BrmsParamTemplate.class, "ruleName", "testPolicy"))
.thenReturn(template);
}
@@ -471,7 +488,7 @@ public class XACMLPAPTest {
// Verify
Mockito.verify(httpServletResponse).setStatus(HttpServletResponse.SC_OK);
//
- // Check VNFType
+ // Check VnfType
//
httpServletRequest = Mockito.mock(HttpServletRequest.class);
httpServletResponse = Mockito.mock(MockHttpServletResponse.class);
@@ -482,14 +499,14 @@ public class XACMLPAPTest {
// Verify
Mockito.verify(httpServletResponse).setStatus(HttpServletResponse.SC_OK);
//
- // Check PEPOptions
+ // Check PepOptions
//
httpServletRequest = Mockito.mock(HttpServletRequest.class);
httpServletResponse = Mockito.mock(MockHttpServletResponse.class);
json = "{\"dictionaryFields\":{\"pepName\":\"testRestAPI\",\"description\":\"testing create\","
+ "\"attributes\":[{\"option\":\"test1\",\"number\":\"test\"},{\"option\":\"test2\","
+ "\"number\":\"test\"}]}}";
- dictionaryTestSetup(false, "PEPOptions", json);
+ dictionaryTestSetup(false, "PepOptions", json);
// send Request to PAP
pap.service(httpServletRequest, httpServletResponse);
// Verify
@@ -678,7 +695,6 @@ public class XACMLPAPTest {
// Verify
Mockito.verify(httpServletResponse).setStatus(HttpServletResponse.SC_OK);
-
httpServletRequest = Mockito.mock(HttpServletRequest.class);
httpServletResponse = Mockito.mock(MockHttpServletResponse.class);
json = "{\"dictionaryFields\":{\"attributeName\":\"TestMMrestAPI1\",\"type\":\"REST\",\"url\":\"testsomeurl"
@@ -870,7 +886,7 @@ public class XACMLPAPTest {
@Test
public void getDictionary() throws ServletException, IOException {
String[] dictionarys = new String[] {"Attribute", "OnapName", "Action", "BRMSParamTemplate", "VSCLAction",
- "VNFType", "PEPOptions", "Varbind", "Service", "Site", "Settings", "RainyDayTreatments",
+ "VNFType", "PepOptions", "Varbind", "Service", "Site", "Settings", "RainyDayTreatments",
"DescriptiveScope", "ActionList", "ProtocolList", "Zone", "SecurityZone", "PrefixList", "AddressGroup",
"ServiceGroup", "ServiceList", "TermList", "MicroServiceLocation", "MicroServiceConfigName", "DCAEUUID",
"MicroServiceModels", "PolicyScopeService", "PolicyScopeResource", "PolicyScopeType",
@@ -897,14 +913,14 @@ public class XACMLPAPTest {
try {
Mockito.when(httpServletResponse.getOutputStream()).thenReturn(mockOutput);
} catch (IOException e) {
- fail();
+ fail(e.getMessage());
}
try {
pap.service(httpServletRequest, httpServletResponse);
assertTrue(true);
} catch (Exception e) {
- fail();
+ fail(e.getMessage());
}
}
diff --git a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/ConsoleAndApiServiceTest.java b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/ConsoleAndApiServiceTest.java
index 0cd70f9b5..36e67a718 100644
--- a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/ConsoleAndApiServiceTest.java
+++ b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/ConsoleAndApiServiceTest.java
@@ -2,7 +2,8 @@
* ============LICENSE_START=======================================================
* ONAP-PAP-REST
* ================================================================================
- * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2019-2020 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2019 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -26,6 +27,7 @@ import static org.mockito.Mockito.when;
import com.att.research.xacml.util.XACMLProperties;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectWriter;
+
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
@@ -34,28 +36,32 @@ import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
+
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
+
import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType;
import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType;
+
import org.apache.commons.io.IOUtils;
import org.hibernate.SessionFactory;
+import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.mockito.Mockito;
-import org.onap.policy.common.logging.ONAPLoggingContext;
+import org.onap.policy.common.logging.OnapLoggingContext;
import org.onap.policy.pap.xacml.rest.components.ConfigPolicy;
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.PolicyDbDao;
import org.onap.policy.pap.xacml.rest.components.PolicyDBDaoTest;
-import org.onap.policy.pap.xacml.rest.components.PolicyDBDaoTransaction;
+import org.onap.policy.pap.xacml.rest.components.PolicyDbDaoTransaction;
import org.onap.policy.pap.xacml.rest.daoimpl.CommonClassDaoImpl;
import org.onap.policy.pap.xacml.rest.policycontroller.PolicyCreation;
import org.onap.policy.rest.adapter.PolicyRestAdapter;
-import org.onap.policy.rest.dao.PolicyDBException;
+import org.onap.policy.rest.dao.PolicyDbException;
import org.onap.policy.xacml.std.pap.StdEngine;
import org.onap.policy.xacml.std.pap.StdPDP;
import org.springframework.mock.web.DelegatingServletInputStream;
@@ -83,8 +89,8 @@ public class ConsoleAndApiServiceTest {
private static final String USER_ID = "userId";
private static final String APIFLAG = "apiflag";
private static final String ENVIRONMENT_HEADER = "Environment";
- private static final ONAPLoggingContext logContext = Mockito.mock(ONAPLoggingContext.class);
- private static PolicyDBDao dbd;
+ private static final OnapLoggingContext logContext = Mockito.mock(OnapLoggingContext.class);
+ private static PolicyDbDao dbd;
private static StdEngine stdEngine = null;
private static SessionFactory sessionFactory = null;
private static List<String> headers = new ArrayList<>();
@@ -105,9 +111,9 @@ public class ConsoleAndApiServiceTest {
public static void setUpBeforeClass() throws Exception {
System.setProperty(XACMLProperties.XACML_PROPERTIES_NAME, "src/test/resources/xacml.pap.properties");
sessionFactory = PolicyDBDaoTest.setupH2DbDaoImpl("testConsoleApi");
- PolicyDBDao.setJunit(true);
- dbd = PolicyDBDao.getPolicyDBDaoInstance();
- PolicyDBDao.setJunit(true);
+ PolicyDbDao.setJunit(true);
+ dbd = PolicyDbDao.getPolicyDbDaoInstance();
+ PolicyDbDao.setJunit(true);
consoleAndApi = new ConsoleAndApiService();
servletConfig = Mockito.mock(MockServletConfig.class);
@@ -119,6 +125,10 @@ public class ConsoleAndApiServiceTest {
pap.init(servletConfig);
}
+ @AfterClass
+ public static void after() {
+ pap.destroy();
+ }
/**
* Sets the up.
@@ -228,7 +238,6 @@ public class ConsoleAndApiServiceTest {
consoleAndApi.doAcPost(httpServletRequest, httpServletResponse, TESTGRP5, logContext, stdEngine);
assertTrue(HttpServletResponse.SC_NO_CONTENT == httpServletResponse.getStatus());
-
Mockito.when(httpServletRequest.getParameter(GROUP_DESCRIPTION)).thenReturn(null);
Mockito.when(httpServletRequest.getParameter(PDP_ID)).thenReturn("http://localhost:4344/pdp/");
Mockito.when(httpServletRequest.getMethod()).thenReturn(PUT);
@@ -240,7 +249,6 @@ public class ConsoleAndApiServiceTest {
consoleAndApi.doAcPut(httpServletRequest, httpServletResponse, TESTGRP5, logContext, stdEngine);
assertTrue(HttpServletResponse.SC_NO_CONTENT == httpServletResponse.getStatus());
-
httpServletRequest = Mockito.mock(HttpServletRequest.class);
httpServletResponse = new MockHttpServletResponse();
Mockito.when(httpServletRequest.getHeader(ENVIRONMENT_HEADER)).thenReturn(DEVL);
@@ -252,7 +260,6 @@ public class ConsoleAndApiServiceTest {
consoleAndApi.doAcPost(httpServletRequest, httpServletResponse, TESTGRP4, logContext, stdEngine);
assertTrue(HttpServletResponse.SC_NO_CONTENT == httpServletResponse.getStatus());
-
httpServletRequest = Mockito.mock(HttpServletRequest.class);
httpServletResponse = new MockHttpServletResponse();
Mockito.when(httpServletRequest.getHeader(ENVIRONMENT_HEADER)).thenReturn(DEVL);
@@ -264,7 +271,6 @@ public class ConsoleAndApiServiceTest {
consoleAndApi.doAcDelete(httpServletRequest, httpServletResponse, TESTGRP4, logContext, stdEngine);
assertTrue(HttpServletResponse.SC_NO_CONTENT == httpServletResponse.getStatus());
-
}
@Test
@@ -293,7 +299,7 @@ public class ConsoleAndApiServiceTest {
assertTrue(HttpServletResponse.SC_OK == httpServletResponse.getStatus());
}
- private static void populatePolicyInDb() throws IOException, PolicyDBException {
+ private static void populatePolicyInDb() throws IOException, PolicyDbException {
CommonClassDaoImpl.setSessionfactory(sessionFactory);
PolicyCreation.setCommonClassDao(new CommonClassDaoImpl());
Policy policyObject = new ConfigPolicy();
@@ -318,7 +324,7 @@ public class ConsoleAndApiServiceTest {
policyObject.policyAdapter.setParentPath(IOUtils.toString(
ConsoleAndApiServiceTest.class.getClassLoader().getResourceAsStream("Config_SampleTest1206.1.xml")));
- PolicyDBDaoTransaction transaction = dbd.getNewTransaction();
+ PolicyDbDaoTransaction transaction = dbd.getNewTransaction();
transaction.createPolicy(policyObject, API);
transaction.commitTransaction();
}
diff --git a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/HeartbeatTest.java b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/HeartbeatTest.java
new file mode 100644
index 000000000..33b7f8be6
--- /dev/null
+++ b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/HeartbeatTest.java
@@ -0,0 +1,91 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP-PAP-REST
+ * ================================================================================
+ * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 static org.assertj.core.api.Assertions.assertThatCode;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+
+import com.att.research.xacml.api.pap.PAPException;
+import java.io.IOException;
+import java.net.MalformedURLException;
+import java.net.URL;
+import java.util.HashSet;
+import java.util.Set;
+import org.junit.Test;
+import org.mockito.Mockito;
+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.StdPDP;
+import org.onap.policy.xacml.std.pap.StdPDPGroup;
+
+public class HeartbeatTest {
+ @Test
+ public void testHeartbeat() throws IOException, PAPException {
+ Heartbeat hb = new Heartbeat(null);
+
+ assertThatThrownBy(hb::run).isInstanceOf(NullPointerException.class);
+ assertTrue(hb.isHeartBeatRunning());
+ hb.terminate();
+ assertFalse(hb.isHeartBeatRunning());
+ }
+
+ @Test
+ public void testGetPdps() throws PAPException, IOException {
+ Set<OnapPDPGroup> pdpGroups = new HashSet<OnapPDPGroup>();
+ StdPDPGroup pdpGroup = new StdPDPGroup();
+ OnapPDP pdp = new StdPDP();
+ pdpGroup.addPDP(pdp);
+ pdpGroups.add(pdpGroup);
+ PAPPolicyEngine pap = Mockito.mock(PAPPolicyEngine.class);
+ Mockito.when(pap.getOnapPDPGroups()).thenReturn(pdpGroups);
+ Heartbeat hb = new Heartbeat(pap);
+ hb.getPdpsFromGroup();
+ assertFalse(hb.isHeartBeatRunning());
+
+ assertThatCode(hb::notifyEachPdp).doesNotThrowAnyException();
+ assertThatThrownBy(hb::run).isInstanceOf(Exception.class);
+ assertThatThrownBy(hb::notifyEachPdp).isInstanceOf(Exception.class);
+ }
+
+ @Test
+ public void testOpen() throws MalformedURLException {
+ Heartbeat hb = new Heartbeat(null);
+ OnapPDP pdp = new StdPDP();
+
+ assertThatCode(() -> {
+ URL url = new URL("http://onap.org");
+ hb.openPdpConnection(url, pdp);
+ }).doesNotThrowAnyException();
+
+ assertThatCode(() -> {
+ URL url = new URL("http://1.2.3.4");
+ hb.openPdpConnection(url, pdp);
+ }).doesNotThrowAnyException();
+
+ assertThatCode(() -> {
+ URL url = new URL("http://fakesite.fakenews");
+ hb.openPdpConnection(url, pdp);
+ }).doesNotThrowAnyException();
+ }
+}
diff --git a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/PAPRestConfigTest.java b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/PAPRestConfigTest.java
index dfadf8e81..2815328a8 100644
--- a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/PAPRestConfigTest.java
+++ b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/PAPRestConfigTest.java
@@ -2,14 +2,14 @@
* ============LICENSE_START=======================================================
* ONAP-PAP-REST
* ================================================================================
- * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2018-2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -21,6 +21,7 @@
package org.onap.policy.pap.xacml.rest;
import static org.junit.Assert.assertEquals;
+
import org.apache.tomcat.dbcp.dbcp2.BasicDataSource;
import org.hibernate.SessionFactory;
import org.junit.Test;
@@ -45,7 +46,9 @@ public class PAPRestConfigTest {
@Test
public void testInit() {
String driver = "org.mariadb.jdbc.Driver";
- String url = "jdbc:mariadb://localhost:3306/onap_sdk?connectTimeout=30000&socketTimeout=60000&log=true&sessionVariables=max_statement_time=30";
+ String url =
+ "jdbc:mariadb://localhost:3306/onap_sdk?connectTimeout=30000&socketTimeout=60000&log="
+ + "true&sessionVariables=max_statement_time=30";
String user = "policy_user";
String password = "policy_user";
@@ -58,7 +61,7 @@ public class PAPRestConfigTest {
assertEquals(PAPRestConfig.getDbPassword(), password);
// Test hibernate
- BasicDataSource source = (BasicDataSource)config.getDataSource();
+ BasicDataSource source = (BasicDataSource) config.getDataSource();
assertEquals(source.getDriverClassName(), driver);
assertEquals(source.getUrl(), url);
assertEquals(source.getUsername(), user);
diff --git a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/UpdatePdpThreadTest.java b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/UpdatePdpThreadTest.java
new file mode 100644
index 000000000..9034f393b
--- /dev/null
+++ b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/UpdatePdpThreadTest.java
@@ -0,0 +1,58 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP-PAP-REST
+ * ================================================================================
+ * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 static org.assertj.core.api.Assertions.assertThatCode;
+import static org.junit.Assert.assertNotNull;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Properties;
+import org.junit.Test;
+import org.onap.policy.common.logging.OnapLoggingContext;
+import org.onap.policy.xacml.api.pap.OnapPDP;
+import org.onap.policy.xacml.std.pap.StdPDP;
+
+public class UpdatePdpThreadTest {
+ @Test
+ public void testConstructor1() {
+ UpdatePdpThread thread = new UpdatePdpThread(null, null);
+ assertNotNull(thread);
+ }
+
+ @Test
+ public void testConstructor2() {
+ OnapLoggingContext loggingContext = new OnapLoggingContext();
+ loggingContext.setRequestId("id");
+ UpdatePdpThread thread = new UpdatePdpThread(null, loggingContext, null);
+ assertNotNull(thread);
+ }
+
+ @Test
+ public void testRun() {
+ OnapPDP pdp = new StdPDP("http://id", 0);
+ OnapLoggingContext loggingContext = new OnapLoggingContext();
+ loggingContext.setRequestId("id");
+ List<Properties> properties = new ArrayList<Properties>();
+ UpdatePdpThread thread = new UpdatePdpThread(pdp, loggingContext, properties);
+ assertThatCode(thread::run).doesNotThrowAnyException();
+ }
+}
diff --git a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/WebConfigTest.java b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/WebConfigTest.java
index 32d7dedd3..22f657249 100644
--- a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/WebConfigTest.java
+++ b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/WebConfigTest.java
@@ -2,14 +2,14 @@
* ============LICENSE_START=======================================================
* ONAP-PAP-REST
* ================================================================================
- * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2018-2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -21,13 +21,15 @@
package org.onap.policy.pap.xacml.rest;
import static org.junit.Assert.fail;
+
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
+
import org.junit.Test;
import org.mockito.Mockito;
public class WebConfigTest {
- @Test(expected=NullPointerException.class)
+ @Test(expected = NullPointerException.class)
public void testNegativeStartup() throws ServletException {
WebConfig init = new WebConfig();
ServletContext container = Mockito.mock(ServletContext.class);
diff --git a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/XACMLPapServletTest.java b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/XACMLPapServletTest.java
index 36d40278b..420e380b6 100644
--- a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/XACMLPapServletTest.java
+++ b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/XACMLPapServletTest.java
@@ -2,14 +2,14 @@
* ============LICENSE_START=======================================================
* ONAP-PAP-REST
* ================================================================================
- * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2018-2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -20,31 +20,46 @@
package org.onap.policy.pap.xacml.rest;
+import static org.assertj.core.api.Assertions.assertThatCode;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertNull;
+
+import com.att.research.xacml.api.pap.PAPException;
+import com.att.research.xacml.util.XACMLProperties;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.mockrunner.mock.web.MockHttpServletRequest;
+import com.mockrunner.mock.web.MockHttpServletResponse;
+import java.io.IOException;
+import java.util.Properties;
+import javax.servlet.ServletException;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import org.junit.After;
+import org.junit.Before;
import org.junit.Test;
-import org.onap.policy.pap.xacml.rest.XACMLPapServlet;
public class XACMLPapServletTest {
+ String systemKey = "xacml.properties";
+ String oldProperty = System.getProperty(systemKey);
+
+ @Before
+ public void setup() {
+ // Set the system property temporarily
+ System.setProperty(systemKey, "xacml.pap.properties");
+ }
+
@Test
public void testSetAndGet() {
- String systemKey = "xacml.properties";
String testVal = "testVal";
XACMLPapServlet servlet = new XACMLPapServlet();
- // Set the system property temporarily
- String oldProperty = System.getProperty(systemKey);
- System.setProperty(systemKey, "xacml.pap.properties");
-
+ assertNotNull(servlet);
assertNotNull(XACMLPapServlet.getConfigHome());
assertNotNull(XACMLPapServlet.getActionHome());
assertEquals(XACMLPapServlet.getPersistenceUnit(), "XACML-PAP-REST");
- //assertNull(XACMLPapServlet.getEmf());
- //assertNull(XACMLPapServlet.getPDPFile());
- //assertNull(XACMLPapServlet.getPAPEngine());
- //assertNull(servlet.getIa());
-
XACMLPapServlet.setPapDbDriver(testVal);
assertEquals(XACMLPapServlet.getPapDbDriver(), testVal);
XACMLPapServlet.setPapDbUrl(testVal);
@@ -57,12 +72,38 @@ public class XACMLPapServletTest {
assertEquals(XACMLPapServlet.getMsOnapName(), testVal);
XACMLPapServlet.setMsPolicyName(testVal);
assertEquals(XACMLPapServlet.getMsPolicyName(), testVal);
+ }
+
+ @Test
+ public void testMethods() throws ServletException, IOException, PAPException {
+ XACMLPapServlet servlet = new XACMLPapServlet();
+
+ ObjectMapper mapper = new ObjectMapper();
+ HttpServletResponse response = new MockHttpServletResponse();
+ assertThatCode(() -> XACMLPapServlet.mapperWriteValue(mapper, response, "hello")).doesNotThrowAnyException();
+ assertThatCode(() -> XACMLPapServlet.mapperWriteValue(null, null, null)).doesNotThrowAnyException();
+ assertNull(XACMLPapServlet.getPapUrl());
+ HttpServletRequest request = new MockHttpServletRequest();
+ assertThatThrownBy(() -> servlet.doDelete(request, response)).isInstanceOf(NullPointerException.class);
+
+ StringBuffer urlPath = new StringBuffer("http://foo");
+ Properties policies = new Properties();
+ servlet.populatePolicyURL(urlPath, policies);
+ assertNull(policies.getProperty("foo.url"));
+
+ policies.setProperty(XACMLProperties.PROP_ROOTPOLICIES, "foo");
+ policies.setProperty(XACMLProperties.PROP_REFERENCEDPOLICIES, "bar");
+ servlet.populatePolicyURL(urlPath, policies);
+ assertEquals("http://foo?id=foo", policies.getProperty("foo.url"));
+ }
+
+ @After
+ public void after() {
// Restore the original system property
if (oldProperty != null) {
- System.setProperty(systemKey, oldProperty);
- }
- else {
+ System.setProperty(systemKey, oldProperty);
+ } else {
System.clearProperty(systemKey);
}
}
diff --git a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/adapters/SearchDataTest.java b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/adapters/SearchDataTest.java
index 841ba28fc..1b1564cf9 100644
--- a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/adapters/SearchDataTest.java
+++ b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/adapters/SearchDataTest.java
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP-PAP-REST
* ================================================================================
- * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2018-2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -17,6 +17,7 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.policy.pap.xacml.rest.adapters;
import static org.junit.Assert.*;
@@ -25,9 +26,8 @@ import org.junit.Test;
public class SearchDataTest {
-
@Test
- public void testSearchData(){
+ public void testSearchData() {
String data = "Test";
SearchData searchData = new SearchData();
searchData.setQuery(data);
diff --git a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/adapters/UpdateObjectDataTest.java b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/adapters/UpdateObjectDataTest.java
index 094994e41..00649c5e2 100644
--- a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/adapters/UpdateObjectDataTest.java
+++ b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/adapters/UpdateObjectDataTest.java
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP Policy Engine
* ================================================================================
- * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2018-2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -17,6 +17,7 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.policy.pap.xacml.rest.adapters;
import static org.junit.Assert.assertTrue;
@@ -26,7 +27,7 @@ import org.junit.Test;
public class UpdateObjectDataTest {
@Test
- public void testClosedLoopFaultTrapDatas(){
+ public void testClosedLoopFaultTrapDatas() {
UpdateObjectData updateObject = new UpdateObjectData();
updateObject.setAction("Rename");
assertTrue("Rename".equals(updateObject.getAction()));
diff --git a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/components/ActionPolicyTest.java b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/components/ActionPolicyTest.java
index b80eaed89..6f4e09775 100644
--- a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/components/ActionPolicyTest.java
+++ b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/components/ActionPolicyTest.java
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP-PAP-REST
* ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017, 2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Modifications Copyright (C) 2019 Samsung
* ================================================================================
@@ -19,15 +19,20 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.policy.pap.xacml.rest.components;
import static org.junit.Assert.*;
import static org.mockito.Mockito.when;
+
+import com.att.research.xacml.util.XACMLProperties;
+
import java.util.HashMap;
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;
@@ -35,8 +40,6 @@ 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 com.att.research.xacml.util.XACMLProperties;
-
public class ActionPolicyTest {
@@ -55,8 +58,7 @@ public class ActionPolicyTest {
@Before
public void setUp() throws Exception {
logger.info("setUp: Entering");
- System.setProperty(XACMLProperties.XACML_PROPERTIES_NAME,
- "src/test/resources/xacml.pap.properties");
+ System.setProperty(XACMLProperties.XACML_PROPERTIES_NAME, "src/test/resources/xacml.pap.properties");
dynamicRuleAlgorithmLabels.add("test");
dynamicRuleAlgorithmField1.add("testField1");
@@ -65,8 +67,7 @@ public class ActionPolicyTest {
policyAdapter.setPolicyName("Test.Action_junitTest");
policyAdapter.setPolicyDescription("test");
- policyAdapter.setRuleCombiningAlgId(
- "urn:oasis:names:tc:xacml:3.0:rule-combining-algorithm:permit-overrides");
+ policyAdapter.setRuleCombiningAlgId("urn:oasis:names:tc:xacml:3.0:rule-combining-algorithm:permit-overrides");
policyAdapter.setPolicyType("Action");
policyAdapter.setEditPolicy(false);
policyAdapter.setDomainDir("Test");
@@ -95,12 +96,6 @@ public class ActionPolicyTest {
}
/**
- * @throws java.lang.Exception
- */
- @After
- public void tearDown() throws Exception {}
-
- /**
* Test method for
* {@link org.openecomp.policy.pap.xacml.rest.components.ActionPolicy#savePolicies()}.
*/
diff --git a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/components/BRMSPolicyTest.java b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/components/BRMSPolicyTest.java
index 39586ba1b..5c1d3dd76 100644
--- a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/components/BRMSPolicyTest.java
+++ b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/components/BRMSPolicyTest.java
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP-PAP-REST
* ================================================================================
- * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2018-2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Modifications Copyright (C) 2019 Samsung
* ================================================================================
@@ -19,15 +19,25 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.policy.pap.xacml.rest.components;
+import static org.assertj.core.api.Assertions.assertThatCode;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertTrue;
+
+import com.att.research.xacml.api.pap.PAPException;
import java.io.IOException;
+import java.nio.charset.Charset;
+import java.util.HashMap;
+import java.util.Map;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.mockito.Mockito;
+import org.onap.policy.rest.adapter.PolicyRestAdapter;
import org.onap.policy.rest.dao.CommonClassDao;
public class BRMSPolicyTest {
@@ -65,4 +75,42 @@ public class BRMSPolicyTest {
String userID = "testID";
assertEquals(1, template.addRule(rule, ruleName, description, userID).size());
}
+
+ @Test
+ public void testCreateBrmsParamPolicyAdapter() throws PAPException {
+ Map<String, String> brmsParamBody = new HashMap<String, String>();
+ brmsParamBody.put("key", "value");
+
+ PolicyRestAdapter adapter = new PolicyRestAdapter();
+ adapter.setHighestVersion(1);
+ adapter.setPolicyType("Config");
+ adapter.setBrmsParamBody(brmsParamBody);
+ adapter.setNewFileName("policyName.1.xml");
+ Map<String, String> dynamicFieldConfigAttributes = new HashMap<String, String>();
+ dynamicFieldConfigAttributes.put("key", "value");
+ adapter.setDynamicFieldConfigAttributes(dynamicFieldConfigAttributes);
+ CreateBrmsParamPolicy policy = new CreateBrmsParamPolicy(adapter);
+ String ruleContents = "contents";
+
+ assertThatCode(() -> policy.saveConfigurations("name.xml", "rules")).doesNotThrowAnyException();
+ try {
+ policy.prepareToSave();
+ policy.savePolicies();
+ } catch (Exception ex) {
+ // Ignore
+ }
+
+ assertThatThrownBy(() -> policy.expandConfigBody(ruleContents, brmsParamBody))
+ .isInstanceOf(NullPointerException.class);
+ assertTrue(policy.validateConfigForm());
+ policy.getAdviceExpressions(1, "name.1.xml");
+ assertNotNull(policy.getCorrectPolicyDataObject());
+ }
+
+ @Test
+ public void testRead() {
+ Charset encoding = Charset.defaultCharset();
+ assertThatCode(() -> CreateBrmsParamPolicy.readFile("xacml.pap.properties", encoding))
+ .doesNotThrowAnyException();
+ }
}
diff --git a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/components/ClosedLoopPolicyTest.java b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/components/ClosedLoopPolicyTest.java
index 542d45e3e..75fa23605 100644
--- a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/components/ClosedLoopPolicyTest.java
+++ b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/components/ClosedLoopPolicyTest.java
@@ -2,14 +2,14 @@
* ============LICENSE_START=======================================================
* ONAP-PAP-REST
* ================================================================================
- * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2018-2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -17,19 +17,23 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.policy.pap.xacml.rest.components;
-import org.junit.Rule;
-import org.junit.Test;
-import org.junit.rules.ExpectedException;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.fail;
-import java.io.IOException;
-import org.onap.policy.rest.adapter.PolicyRestAdapter;
+
import com.att.research.xacml.api.pap.PAPException;
+
+import java.io.IOException;
import java.nio.charset.StandardCharsets;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.rules.ExpectedException;
+import org.onap.policy.rest.adapter.PolicyRestAdapter;
+
public class ClosedLoopPolicyTest {
@Rule
public ExpectedException thrown = ExpectedException.none();
@@ -51,7 +55,7 @@ public class ClosedLoopPolicyTest {
@Test
public void testReadFile() throws IOException {
thrown.expect(IOException.class);
- String read = ClosedLoopPolicy.readFile("/foo", StandardCharsets.UTF_8);
+ ClosedLoopPolicy.readFile("/foo", StandardCharsets.UTF_8);
fail("Expecting an exception.");
}
@@ -65,4 +69,4 @@ public class ClosedLoopPolicyTest {
policy.prepareToSave();
assertEquals(policy.isPreparedToSave(), true);
}
-} \ No newline at end of file
+}
diff --git a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/components/CreateNewMicroServiceModelTest.java b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/components/CreateNewMicroServiceModelTest.java
new file mode 100644
index 000000000..1e82bbd06
--- /dev/null
+++ b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/components/CreateNewMicroServiceModelTest.java
@@ -0,0 +1,73 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP-PAP-REST
+ * ================================================================================
+ * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.mockito.Matchers.any;
+import static org.mockito.Matchers.anyString;
+import static org.mockito.Mockito.when;
+
+import java.io.File;
+import java.util.Collections;
+
+import org.junit.Test;
+import org.mockito.Mockito;
+import org.onap.policy.pap.xacml.rest.daoimpl.CommonClassDaoImpl;
+
+public class CreateNewMicroServiceModelTest {
+ @Test
+ public void testEmptyModel() {
+ CreateNewMicroServiceModel model =
+ new CreateNewMicroServiceModel("file.yml", "model", "desc", "1.0", "id");
+ assertNotNull(model);
+ assertEquals(1, model.addValuesToNewModel(".yml").size());
+ }
+
+ @Test
+ public void testCreateConstructor1() {
+ CreateNewMicroServiceModel model = new CreateNewMicroServiceModel(null, null, null, null);
+ assertNotNull(model);
+ }
+
+ @Test
+ public void testCreateModel() throws Exception {
+ // Mock file retrieval
+ File testFile = new File("testFile");
+ File[] testList = new File[1];
+ testList[0] = testFile;
+ File impl = Mockito.mock(File.class);
+ when(impl.listFiles()).thenReturn(testList);
+ when(impl.isFile()).thenReturn(true);
+
+ // Mock internal dictionary retrieval
+ CommonClassDaoImpl daoImpl = Mockito.mock(CommonClassDaoImpl.class);
+ when(daoImpl.getDataById(any(), anyString(), anyString()))
+ .thenReturn(Collections.emptyList());
+
+ // Test create methods
+ String testFileName = "testFile.yml";
+ String testVal = "testVal";
+ CreateNewMicroServiceModel model =
+ new CreateNewMicroServiceModel(testFileName, testVal, testVal, testVal, testVal);
+ assertEquals(1, model.addValuesToNewModel(".yml").size());
+ }
+}
diff --git a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/components/CreateNewOptimizationTest.java b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/components/CreateNewOptimizationTest.java
new file mode 100644
index 000000000..e6b9f47ca
--- /dev/null
+++ b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/components/CreateNewOptimizationTest.java
@@ -0,0 +1,37 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP-PAP-REST
+ * ================================================================================
+ * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+
+import org.junit.Test;
+
+public class CreateNewOptimizationTest {
+ @Test
+ public void testEmptyModel() {
+ CreateNewOptimizationModel model = new CreateNewOptimizationModel();
+ assertNotNull(model);
+ model = new CreateNewOptimizationModel("file.yml", "model", "desc", "1.0", "id");
+ assertNotNull(model);
+ assertEquals(1, model.addValuesToNewModel().size());
+ }
+}
diff --git a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/components/DecisionPolicyTest.java b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/components/DecisionPolicyTest.java
index ec9229c71..900d1227f 100644
--- a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/components/DecisionPolicyTest.java
+++ b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/components/DecisionPolicyTest.java
@@ -23,12 +23,15 @@ package org.onap.policy.pap.xacml.rest.components;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.when;
+
import com.att.research.xacml.util.XACMLProperties;
+
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.UUID;
+
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mockito;
@@ -61,7 +64,7 @@ public class DecisionPolicyTest {
@Before
public void setUp() throws Exception {
logger.info("setUp: Entering");
- System.setProperty(XACMLProperties.XACML_PROPERTIES_NAME,"src/test/resources/xacml.pap.properties");
+ System.setProperty(XACMLProperties.XACML_PROPERTIES_NAME, "src/test/resources/xacml.pap.properties");
policyAdapter.setPolicyName("Test.Decision_junitTest.1.xml");
policyAdapter.setPolicyDescription("testing");
@@ -71,10 +74,10 @@ public class DecisionPolicyTest {
policyAdapter.setDomainDir("Test");
policyAdapter.setNewFileName("/src/test/resources/Test/client.properties");
policyAdapter.setHighestVersion(1);
- policyAdapter.setPolicyID("urn:xacml:policy:id:"+UUID.randomUUID());
+ policyAdapter.setPolicyID("urn:xacml:policy:id:" + UUID.randomUUID());
policyAdapter.setOnapName("MSO");
- //rainy day attributes
+ // rainy day attributes
attributeMap.put("ServiceType", "S");
attributeMap.put("VNFType", "V");
attributeMap.put("BB_ID", "testBB");
@@ -119,7 +122,7 @@ public class DecisionPolicyTest {
e.printStackTrace();
}
- assertEquals(successMap.get("success"),"success");
+ assertEquals(successMap.get("success"), "success");
}
/**
@@ -135,7 +138,7 @@ public class DecisionPolicyTest {
try {
response = component.prepareToSave();
} catch (Exception e) {
- logger.error("Exception Occured"+e);
+ logger.error("Exception Occured" + e);
}
assertTrue(response);
}
diff --git a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/components/FirewallConfigPolicyTest.java b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/components/FirewallConfigPolicyTest.java
index 7f3ebb3b4..4ddc8d057 100644
--- a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/components/FirewallConfigPolicyTest.java
+++ b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/components/FirewallConfigPolicyTest.java
@@ -2,14 +2,14 @@
* ============LICENSE_START=======================================================
* ONAP-PAP-REST
* ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017, 2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -17,15 +17,17 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.policy.pap.xacml.rest.components;
import static org.junit.Assert.*;
import static org.mockito.Mockito.when;
+import com.att.research.xacml.util.XACMLProperties;
+
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
-
import java.util.Map;
import java.util.UUID;
@@ -38,9 +40,6 @@ import org.onap.policy.common.logging.flexlogger.Logger;
import org.onap.policy.pap.test.XACMLPAPTest;
import org.onap.policy.rest.adapter.PolicyRestAdapter;
-import com.att.research.xacml.util.XACMLProperties;
-
-
public class FirewallConfigPolicyTest {
private static Logger logger = FlexLogger.getLogger(FirewallConfigPolicyTest.class);
@@ -56,7 +55,7 @@ public class FirewallConfigPolicyTest {
@Before
public void setUp() throws Exception {
logger.info("setup: enter");
- System.setProperty(XACMLProperties.XACML_PROPERTIES_NAME,"src/test/resources/xacml.pap.properties");
+ System.setProperty(XACMLProperties.XACML_PROPERTIES_NAME, "src/test/resources/xacml.pap.properties");
policyAdapter.setPolicyName("FWjunitTest");
policyAdapter.setPolicyDescription("test");
@@ -68,7 +67,7 @@ public class FirewallConfigPolicyTest {
policyAdapter.setNewFileName("Test.Config_FW_junitTest.1.xml");
policyAdapter.setHighestVersion(1);
policyAdapter.setVersion(String.valueOf(1));
- policyAdapter.setPolicyID("urn:xacml:policy:id:"+UUID.randomUUID());
+ policyAdapter.setPolicyID("urn:xacml:policy:id:" + UUID.randomUUID());
policyAdapter.setRuleID("");
policyAdapter.setConfigName("testname");
policyAdapter.setGuard("True");
@@ -106,7 +105,7 @@ public class FirewallConfigPolicyTest {
when(mockFWConfig.savePolicies()).thenReturn(successMap);
successMap = mockFWConfig.savePolicies();
} catch (Exception e) {
- logger.error("Exception Occured"+e);
+ logger.error("Exception Occured" + e);
}
}
@@ -122,29 +121,74 @@ public class FirewallConfigPolicyTest {
when(mockFWConfig.prepareToSave()).thenReturn(true);
response = mockFWConfig.prepareToSave();
} catch (Exception e) {
- logger.error("Exception Occured"+e);
+ logger.error("Exception Occured" + e);
}
assertTrue(response);
}
@Test
- public void testUpdateJson() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException{
+ public void testUpdateJson() throws NoSuchMethodException, SecurityException, IllegalAccessException,
+ IllegalArgumentException, InvocationTargetException {
FirewallConfigPolicy firewallConfigPolicy = new FirewallConfigPolicy();
- Method method = firewallConfigPolicy.getClass().getDeclaredMethod("updateFirewallDictionaryData", String.class , String.class);
+ Method method = firewallConfigPolicy.getClass().getDeclaredMethod("updateFirewallDictionaryData", String.class,
+ String.class);
method.setAccessible(true);
- String jsonBody= "{\"serviceTypeId\":\"/v0/firewall/pan\",\"configName\":\"TestFwPolicyConfig\",\"deploymentOption\":{\"deployNow\":false},\"securityZoneId\":\"cloudsite:dev1a\",\"serviceGroups\":[{\"name\":\"SSH\",\"description\":\"Sshservice entry in servicelist\",\"type\":\"SERVICE\",\"transportProtocol\":\"tcp\",\"appProtocol\":null,\"ports\":\"22\"}],\"addressGroups\":[{\"name\":\"test\",\"description\":\"Destination\",\"members\":[{\"type\":\"SUBNET\",\"value\":\"127.0.0.1/12\"}]},{\"name\":\"TestServers\",\"description\":\"SourceTestServers for firsttesting\",\"members\":[{\"type\":\"SUBNET\",\"value\":\"127.0.0.1/23\"}]}],\"firewallRuleList\":[{\"position\":\"1\",\"ruleName\":\"FWRuleTestServerToTest\",\"fromZones\":[\"UntrustedZoneTestName\"],\"toZones\":[\"TrustedZoneTestName\"],\"negateSource\":false,\"negateDestination\":false,\"sourceList\":[{\"type\":\"REFERENCE\",\"name\":\"TestServers\"}],\"destinationList\":[{\"type\":\"REFERENCE\",\"name\":\"Test\"}],\"sourceServices\":[],\"destServices\":[{\"type\":\"REFERENCE\",\"name\":\"SSH\"}],\"action\":\"accept\",\"description\":\"FWrule for Test source to Test destination\",\"enabled\":true,\"log\":true}]}";
- String prevJsonBody = "{\"serviceTypeId\":\"/v0/firewall/pan\",\"configName\":\"TestFwPolicy1Config\",\"deploymentOption\":{\"deployNow\":false},\"securityZoneId\":\"cloudsite:dev\",\"vendorServiceId\":\"test\",\"vendorSpecificData\":{\"idMap\":[{\"Id\":\"cloudsite:dev1a\",\"vendorId\":\"deviceGroup:dev\"}]},\"serviceGroups\":[{\"name\":\"SSH\",\"description\":\"Ssh service entry in service list\",\"type\":\"SERVICE\",\"transportProtocol\":\"tcp\",\"appProtocol\":null,\"ports\":\"22\"}],\"addressGroups\":[{\"name\":\"Test\",\"description\":\"Destination Test\",\"members\":[{\"type\":\"SUBNET\",\"value\":\"127.0.0.1/12\"}]},{\"name\":\"TestServers\",\"description\":\"Source TestServers for first testing\",\"members\":[{\"type\":\"SUBNET\",\"value\":\"127.0.0.1/23\"}]}],\"firewallRuleList\":[{\"position\":\"1\",\"ruleName\":\"FWRuleTestServerTot\",\"fromZones\":[\"UntrustedZoneTestName\"],\"toZones\":[\"TrustedZoneTName\"],\"negateSource\":false,\"negateDestination\":false,\"sourceList\":[{\"type\":\"REFERENCE\",\"name\":\"TServers\"}],\"destinationList\":[{\"type\":\"REFERENCE\",\"name\":\"Test\"}],\"sourceServices\":[],\"destServices\":[{\"type\":\"REFERENCE\",\"name\":\"SSH\"}],\"action\":\"accept\",\"description\":\"FW rule for HOHO source to CiscoVCE destination\",\"enabled\":true,\"log\":true}]}";
+ String jsonBody =
+ "{\"serviceTypeId\":\"/v0/firewall/pan\",\"configName\":\"TestFwPolicyConfig\",\"deploymentOption\":"
+ + "{\"deployNow\":false},\"securityZoneId\":\"cloudsite:dev1a\",\"serviceGroups\":[{\"name\":"
+ + "\"SSH\",\"description\":\"Sshservice entry in servicelist\",\"type\":\"SERVICE\","
+ + "\"transportProtocol\":\"tcp\",\"appProtocol\":null,\"ports\":\"22\"}],\"addressGroups\":"
+ + "[{\"name\":\"test\",\"description\":\"Destination\",\"members\":[{\"type\":\"SUBNET\",\"value\":"
+ + "\"127.0.0.1/12\"}]},{\"name\":\"TestServers\",\"description\":"
+ + "\"SourceTestServers for firsttesting\",\"members\":[{\"type\":\"SUBNET\",\"value\":"
+ + "\"127.0.0.1/23\"}]}],\"firewallRuleList\":[{\"position\":\"1\",\"ruleName\":"
+ + "\"FWRuleTestServerToTest\",\"fromZones\":[\"UntrustedZoneTestName\"],\"toZones\":"
+ + "[\"TrustedZoneTestName\"],\"negateSource\":false,\"negateDestination\":false,\"sourceList\":"
+ + "[{\"type\":\"REFERENCE\",\"name\":\"TestServers\"}],\"destinationList\":[{\"type\":"
+ + "\"REFERENCE\",\"name\":\"Test\"}],\"sourceServices\":[],\"destServices\":[{\"type\":"
+ + "\"REFERENCE\",\"name\":\"SSH\"}],\"action\":\"accept\",\"description\":"
+ + "\"FWrule for Test source to Test destination\",\"enabled\":true,\"log\":true}]}";
+ String prevJsonBody =
+ "{\"serviceTypeId\":\"/v0/firewall/pan\",\"configName\":\"TestFwPolicy1Config\","
+ + "\"deploymentOption\":{\"deployNow\":false},\"securityZoneId\":\"cloudsite:dev\","
+ + "\"vendorServiceId\":\"test\",\"vendorSpecificData\":{\"idMap\":[{\"Id\":\"cloudsite:dev1a\","
+ + "\"vendorId\":\"deviceGroup:dev\"}]},\"serviceGroups\":[{\"name\":\"SSH\",\"description\":"
+ + "\"Ssh service entry in service list\",\"type\":\"SERVICE\",\"transportProtocol\":\"tcp\","
+ + "\"appProtocol\":null,\"ports\":\"22\"}],\"addressGroups\":[{\"name\":\"Test\",\"description\":"
+ + "\"Destination Test\",\"members\":[{\"type\":\"SUBNET\",\"value\":\"127.0.0.1/12\"}]},{\"name\":"
+ + "\"TestServers\",\"description\":\"Source TestServers for first testing\",\"members\":[{\"type\":"
+ + "\"SUBNET\",\"value\":\"127.0.0.1/23\"}]}],\"firewallRuleList\":[{\"position\":\"1\",\"ruleName\":"
+ + "\"FWRuleTestServerTot\",\"fromZones\":[\"UntrustedZoneTestName\"],\"toZones\":"
+ + "[\"TrustedZoneTName\"],\"negateSource\":false,\"negateDestination\":false,\"sourceList\":"
+ + "[{\"type\":\"REFERENCE\",\"name\":\"TServers\"}],\"destinationList\":[{\"type\":\"REFERENCE\","
+ + "\"name\":\"Test\"}],\"sourceServices\":[],\"destServices\":[{\"type\":\"REFERENCE\",\"name\":"
+ + "\"SSH\"}],\"action\":\"accept\",\"description\":\"FW rule for HOHO source to CiscoVCE destination\","
+ + "\"enabled\":true,\"log\":true}]}";
assertTrue((Boolean) method.invoke(firewallConfigPolicy, jsonBody, prevJsonBody));
}
@Test
- public void testInsertJson() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException{
+ public void testInsertJson() throws NoSuchMethodException, SecurityException, IllegalAccessException,
+ IllegalArgumentException, InvocationTargetException {
FirewallConfigPolicy firewallConfigPolicy = new FirewallConfigPolicy();
Method method = firewallConfigPolicy.getClass().getDeclaredMethod("insertFirewallDicionaryData", String.class);
method.setAccessible(true);
- String jsonBody= "{\"serviceTypeId\":\"/v0/firewall/pan\",\"configName\":\"TestFwPolicyConfig\",\"deploymentOption\":{\"deployNow\":false},\"securityZoneId\":\"cloudsite:dev1a\",\"serviceGroups\":[{\"name\":\"SSH\",\"description\":\"Sshservice entry in servicelist\",\"type\":\"SERVICE\",\"transportProtocol\":\"tcp\",\"appProtocol\":null,\"ports\":\"22\"}],\"addressGroups\":[{\"name\":\"test\",\"description\":\"Destination\",\"members\":[{\"type\":\"SUBNET\",\"value\":\"127.0.0.1/12\"}]},{\"name\":\"TestServers\",\"description\":\"SourceTestServers for firsttesting\",\"members\":[{\"type\":\"SUBNET\",\"value\":\"127.0.0.1/23\"}]}],\"firewallRuleList\":[{\"position\":\"1\",\"ruleName\":\"FWRuleTestServerToTest\",\"fromZones\":[\"UntrustedZoneTestName\"],\"toZones\":[\"TrustedZoneTestName\"],\"negateSource\":false,\"negateDestination\":false,\"sourceList\":[{\"type\":\"REFERENCE\",\"name\":\"TestServers\"}],\"destinationList\":[{\"type\":\"REFERENCE\",\"name\":\"Test\"}],\"sourceServices\":[],\"destServices\":[{\"type\":\"REFERENCE\",\"name\":\"SSH\"}],\"action\":\"accept\",\"description\":\"FWrule for Test source to Test destination\",\"enabled\":true,\"log\":true}]}";
+ String jsonBody =
+ "{\"serviceTypeId\":\"/v0/firewall/pan\",\"configName\":\"TestFwPolicyConfig\",\"deploymentOption\":"
+ + "{\"deployNow\":false},\"securityZoneId\":\"cloudsite:dev1a\",\"serviceGroups\":[{\"name\":\"SSH\","
+ + "\"description\":\"Sshservice entry in servicelist\",\"type\":\"SERVICE\",\"transportProtocol\":"
+ + "\"tcp\",\"appProtocol\":null,\"ports\":\"22\"}],\"addressGroups\":[{\"name\":\"test\","
+ + "\"description\":\"Destination\",\"members\":[{\"type\":\"SUBNET\",\"value\":\"127.0.0.1/12\"}]},"
+ + "{\"name\":\"TestServers\",\"description\":\"SourceTestServers for firsttesting\",\"members\":"
+ + "[{\"type\":\"SUBNET\",\"value\":\"127.0.0.1/23\"}]}],\"firewallRuleList\":[{\"position\":\"1\","
+ + "\"ruleName\":\"FWRuleTestServerToTest\",\"fromZones\":[\"UntrustedZoneTestName\"],\"toZones\":"
+ + "[\"TrustedZoneTestName\"],\"negateSource\":false,\"negateDestination\":false,\"sourceList\":"
+ + "[{\"type\":\"REFERENCE\",\"name\":\"TestServers\"}],\"destinationList\":[{\"type\":\"REFERENCE\","
+ + "\"name\":\"Test\"}],\"sourceServices\":[],\"destServices\":[{\"type\":\"REFERENCE\",\"name\":"
+ + "\"SSH\"}],\"action\":\"accept\",\"description\":\"FWrule for Test source to Test destination\","
+ + "\"enabled\":true,\"log\":true}]}";
assertTrue((Boolean) method.invoke(firewallConfigPolicy, jsonBody));
}
-} \ No newline at end of file
+}
diff --git a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/components/HandleIncomingNotificationsTest.java b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/components/HandleIncomingNotificationsTest.java
index 436ff7fc8..86a7af11f 100644
--- a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/components/HandleIncomingNotificationsTest.java
+++ b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/components/HandleIncomingNotificationsTest.java
@@ -3,6 +3,7 @@
* ONAP-PAP-REST
* ================================================================================
* Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2019 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -22,10 +23,13 @@ package org.onap.policy.pap.xacml.rest.components;
import com.att.research.xacml.api.pap.PAPException;
import com.att.research.xacml.util.XACMLProperties;
+
import java.io.File;
import java.io.IOException;
+
import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType;
import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType;
+
import org.apache.commons.io.IOUtils;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
@@ -35,7 +39,7 @@ import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.onap.policy.rest.adapter.PolicyRestAdapter;
-import org.onap.policy.rest.dao.PolicyDBException;
+import org.onap.policy.rest.dao.PolicyDbException;
import org.onap.policy.rest.jpa.GroupEntity;
import org.onap.policy.rest.jpa.PdpEntity;
import org.onap.policy.xacml.std.pap.StdEngine;
@@ -46,7 +50,7 @@ public class HandleIncomingNotificationsTest {
private static final String PDP = "pdp";
private static final String GROUP = "group";
private static final String ONE = "1";
- private static PolicyDBDao dbd;
+ private static PolicyDbDao dbd;
private static StdEngine stdEngine = null;
private static SessionFactory sessionFactory = null;
private static HandleIncomingNotifications handleIncomingNotifications;
@@ -64,9 +68,9 @@ public class HandleIncomingNotificationsTest {
System.setProperty(XACMLProperties.XACML_PROPERTIES_NAME, "src/test/resources/xacml.pap.properties");
sessionFactory = PolicyDBDaoTest.setupH2DbDaoImpl("testHandleIncoming");
handleIncomingNotifications = new HandleIncomingNotifications(sessionFactory);
- PolicyDBDao.setJunit(true);
- dbd = PolicyDBDao.getPolicyDBDaoInstance();
- PolicyDBDao.setJunit(true);
+ PolicyDbDao.setJunit(true);
+ dbd = PolicyDbDao.getPolicyDbDaoInstance();
+ PolicyDbDao.setJunit(true);
populateDb();
}
@@ -93,7 +97,7 @@ public class HandleIncomingNotificationsTest {
handleIncomingNotifications.handleIncomingHttpNotification(null, TWO, PDP, null, null);
}
- private static void populateDb() throws PolicyDBException, IOException {
+ private static void populateDb() throws PolicyDbException, IOException {
groupEntity = new GroupEntity();
groupEntity.setCreatedBy(API);
groupEntity.setDefaultGroup(false);
@@ -130,7 +134,7 @@ public class HandleIncomingNotificationsTest {
session.close();
}
- private static void populatePolicyInDb() throws PolicyDBException, IOException {
+ private static void populatePolicyInDb() throws PolicyDbException, IOException {
Policy policyObject = new ConfigPolicy();
policyObject.policyAdapter = new PolicyRestAdapter();
policyObject.policyAdapter.setConfigName("testpolicyhandle");
@@ -154,7 +158,7 @@ public class HandleIncomingNotificationsTest {
policyObject.policyAdapter
.setParentPath(IOUtils.toString(classLoader.getResourceAsStream("Config_SampleTest1206.1.xml")));
- PolicyDBDaoTransaction transaction = dbd.getNewTransaction();
+ PolicyDbDaoTransaction transaction = dbd.getNewTransaction();
transaction.createPolicy(policyObject, "testuser1");
transaction.commitTransaction();
diff --git a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/components/MicroServicePolicyTest.java b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/components/MicroServicePolicyTest.java
index f698bc0c0..35c99f770 100644
--- a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/components/MicroServicePolicyTest.java
+++ b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/components/MicroServicePolicyTest.java
@@ -2,14 +2,14 @@
* ============LICENSE_START=======================================================
* ONAP-PAP-REST
* ================================================================================
- * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2018-2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -17,29 +17,22 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.policy.pap.xacml.rest.components;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
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 static org.mockito.Matchers.anyString;
-import static org.mockito.Mockito.when;
-import static org.mockito.Matchers.any;
+
+import com.att.research.xacml.api.pap.PAPException;
+import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionsType;
+import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
-import org.junit.runner.RunWith;
-import org.mockito.Mockito;
-import org.onap.policy.pap.xacml.rest.daoimpl.CommonClassDaoImpl;
import org.onap.policy.rest.adapter.PolicyRestAdapter;
-import org.powermock.api.mockito.PowerMockito;
-import org.powermock.core.classloader.annotations.PrepareForTest;
-import org.powermock.modules.junit4.PowerMockRunner;
-import java.io.File;
-import java.util.Collections;
-@RunWith(PowerMockRunner.class)
public class MicroServicePolicyTest {
@Rule
public ExpectedException thrown = ExpectedException.none();
@@ -59,53 +52,38 @@ public class MicroServicePolicyTest {
assertNull(policy.getCorrectPolicyDataObject());
}
- @PrepareForTest({MicroServiceConfigPolicy.class})
- @Test
- public void testPrepareToSave() throws Exception {
- // Need to mock internal dictionary retrieval
- CommonClassDaoImpl impl = Mockito.mock(CommonClassDaoImpl.class);
- PowerMockito.whenNew(CommonClassDaoImpl.class).withNoArguments().thenReturn(impl);
- when(impl.getDataById(any(), anyString(), anyString())).thenReturn(null);
-
+ @Test(expected = NullPointerException.class)
+ public void testSave() throws PAPException {
PolicyRestAdapter policyAdapter = new PolicyRestAdapter();
- MicroServiceConfigPolicy policy = new MicroServiceConfigPolicy(policyAdapter);
+ PolicyType policyType = new PolicyType();
+ policyAdapter.setPolicyID("id");
policyAdapter.setHighestVersion(1);
policyAdapter.setPolicyType("Config");
- policyAdapter.setNewFileName("foo.xml");
- policyAdapter.setJsonBody("{ \"version\": \"1.0\"}");
- policyAdapter.setServiceType("foo");
- policy.prepareToSave();
- assertEquals(policy.isPreparedToSave(), true);
- }
+ policyAdapter.setNewFileName("newfile");
+ policyAdapter.setData(policyType);
+ policyAdapter.setJsonBody("{\"key\":\"value\"}");
+ policyAdapter.setServiceType("svcType");
+ MicroServiceConfigPolicy policy = new MicroServiceConfigPolicy(policyAdapter);
- @Test
- public void testCreateConstructor1() {
- CreateNewMicroServiceModel model = new CreateNewMicroServiceModel(null, null, null, null);
- assertNotNull(model);
+ policy.savePolicies();
}
- @PrepareForTest({CreateNewMicroServiceModel.class})
@Test
- public void testCreateModel() throws Exception {
- // Mock file retrieval
- File testFile = new File("testFile");
- File[] testList = new File[1];
- testList[0] = testFile;
- File impl = Mockito.mock(File.class);
- PowerMockito.whenNew(File.class).withAnyArguments().thenReturn(impl);
- when(impl.listFiles()).thenReturn(testList);
- when(impl.isFile()).thenReturn(true);
+ public void testAdvice() {
+ PolicyType policyType = new PolicyType();
+ PolicyRestAdapter policyAdapter = new PolicyRestAdapter();
+ policyAdapter.setPolicyID("id");
+ policyAdapter.setHighestVersion(1);
+ policyAdapter.setPolicyType("Config");
+ policyAdapter.setNewFileName("newfile");
+ policyAdapter.setData(policyType);
+ policyAdapter.setJsonBody("{\"key\":\"value\"}");
+ policyAdapter.setServiceType("svcType");
- // Mock internal dictionary retrieval
- CommonClassDaoImpl daoImpl = Mockito.mock(CommonClassDaoImpl.class);
- PowerMockito.whenNew(CommonClassDaoImpl.class).withNoArguments().thenReturn(daoImpl);
- when(daoImpl.getDataById(any(), anyString(), anyString())).thenReturn(Collections.emptyList());
+ MicroServiceConfigPolicy policy = new MicroServiceConfigPolicy(policyAdapter);
+ assertThatThrownBy(() -> policy.savePolicies()).isInstanceOf(NullPointerException.class);
- // Test create methods
- String testFileName = "testFile.zip";
- String testVal = "testVal";
- CreateNewMicroServiceModel model = new CreateNewMicroServiceModel(testFileName, testVal, testVal, testVal, testVal);
- model.addValuesToNewModel(".xmi");
- model.saveImportService();
+ AdviceExpressionsType expType = policy.getAdviceExpressions(1, "filename");
+ assertEquals(1, expType.getAdviceExpression().size());
}
}
diff --git a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/components/NotifyOtherPapsTest.java b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/components/NotifyOtherPapsTest.java
new file mode 100644
index 000000000..7156ec788
--- /dev/null
+++ b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/components/NotifyOtherPapsTest.java
@@ -0,0 +1,66 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP-PAP-REST
+ * ================================================================================
+ * Copyright (C) 2018-2019 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 static org.assertj.core.api.Assertions.assertThatCode;
+
+import com.att.research.xacml.util.XACMLProperties;
+import java.util.ArrayList;
+import java.util.List;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+import org.onap.policy.rest.jpa.PolicyDbDaoEntity;
+
+public class NotifyOtherPapsTest {
+ private static final String systemKey = XACMLProperties.XACML_PROPERTIES_NAME;
+ private static final String oldProperty = System.getProperty(systemKey);
+
+ @Before
+ public void setup() {
+ // Set the system property temporarily
+ System.setProperty(systemKey, "xacml.pap.properties");
+ }
+
+ @Test
+ public void negTestNotify() {
+ NotifyOtherPaps notify = new NotifyOtherPaps();
+ List<PolicyDbDaoEntity> otherServers = new ArrayList<PolicyDbDaoEntity>();
+ PolicyDbDaoEntity dbdaoEntity = new PolicyDbDaoEntity();
+ dbdaoEntity.setPolicyDbDaoUrl("http://test");
+ otherServers.add(dbdaoEntity);
+ long entityId = 0;
+ String entityType = "entityType";
+ String newGroupId = "newGroupId";
+ assertThatCode(() -> notify.startNotifyThreads(otherServers, entityId, entityType, newGroupId))
+ .doesNotThrowAnyException();
+ }
+
+ @After
+ public void cleanup() {
+ // Restore the original system property
+ if (oldProperty != null) {
+ System.setProperty(systemKey, oldProperty);
+ } else {
+ System.clearProperty(systemKey);
+ }
+ }
+}
diff --git a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/components/OptimizationConfigPolicyTest.java b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/components/OptimizationConfigPolicyTest.java
index 25e94c1a2..8437fb0f7 100644
--- a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/components/OptimizationConfigPolicyTest.java
+++ b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/components/OptimizationConfigPolicyTest.java
@@ -2,14 +2,14 @@
* ============LICENSE_START=======================================================
* ONAP-PAP-REST
* ================================================================================
- * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2018-2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -17,29 +17,22 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.policy.pap.xacml.rest.components;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
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 static org.mockito.Matchers.anyString;
-import static org.mockito.Mockito.when;
-import static org.mockito.Matchers.any;
+
+import com.att.research.xacml.api.pap.PAPException;
+import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionsType;
+import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
-import org.junit.runner.RunWith;
-import org.mockito.Mockito;
-import org.onap.policy.pap.xacml.rest.daoimpl.CommonClassDaoImpl;
import org.onap.policy.rest.adapter.PolicyRestAdapter;
-import org.powermock.api.mockito.PowerMockito;
-import org.powermock.core.classloader.annotations.PrepareForTest;
-import org.powermock.modules.junit4.PowerMockRunner;
-import java.io.File;
-import java.util.Collections;
-@RunWith(PowerMockRunner.class)
public class OptimizationConfigPolicyTest {
@Rule
public ExpectedException thrown = ExpectedException.none();
@@ -59,47 +52,37 @@ public class OptimizationConfigPolicyTest {
assertNull(policy.getCorrectPolicyDataObject());
}
- @PrepareForTest({OptimizationConfigPolicy.class})
@Test
- public void testPrepareToSave() throws Exception {
- // Need to mock internal dictionary retrieval
- CommonClassDaoImpl impl = Mockito.mock(CommonClassDaoImpl.class);
- PowerMockito.whenNew(CommonClassDaoImpl.class).withNoArguments().thenReturn(impl);
- when(impl.getDataById(any(), anyString(), anyString())).thenReturn(null);
-
+ public void testSave() throws PAPException {
+ PolicyType policyType = new PolicyType();
PolicyRestAdapter policyAdapter = new PolicyRestAdapter();
- OptimizationConfigPolicy policy = new OptimizationConfigPolicy(policyAdapter);
+ policyAdapter.setPolicyID("id");
policyAdapter.setHighestVersion(1);
policyAdapter.setPolicyType("Config");
- policyAdapter.setNewFileName("foo.xml");
- policyAdapter.setJsonBody("{ \"version\": \"1.0\"}");
- policyAdapter.setServiceType("foo");
- policy.prepareToSave();
- assertEquals(true, policy.isPreparedToSave());
+ policyAdapter.setNewFileName("newfile");
+ policyAdapter.setData(policyType);
+ policyAdapter.setJsonBody("{\"key\":\"value\"}");
+ policyAdapter.setServiceType("svcType");
+ OptimizationConfigPolicy policy = new OptimizationConfigPolicy(policyAdapter);
+ assertThatThrownBy(() -> policy.savePolicies()).isInstanceOf(Exception.class);
}
- @PrepareForTest({CreateNewOptimizationModel.class})
@Test
- public void testCreateModel() throws Exception {
- // Mock file retrieval
- File testFile = new File("testFile");
- File[] testList = new File[1];
- testList[0] = testFile;
- File impl = Mockito.mock(File.class);
- PowerMockito.whenNew(File.class).withAnyArguments().thenReturn(impl);
- when(impl.listFiles()).thenReturn(testList);
- when(impl.isFile()).thenReturn(true);
+ public void testAdvice() {
+ PolicyType policyType = new PolicyType();
+ PolicyRestAdapter policyAdapter = new PolicyRestAdapter();
+ policyAdapter.setPolicyID("id");
+ policyAdapter.setHighestVersion(1);
+ policyAdapter.setPolicyType("Config");
+ policyAdapter.setNewFileName("newfile");
+ policyAdapter.setData(policyType);
+ policyAdapter.setJsonBody("{\"key\":\"value\"}");
+ policyAdapter.setServiceType("svcType");
- // Mock internal dictionary retrieval
- CommonClassDaoImpl daoImpl = Mockito.mock(CommonClassDaoImpl.class);
- PowerMockito.whenNew(CommonClassDaoImpl.class).withNoArguments().thenReturn(daoImpl);
- when(daoImpl.getDataById(any(), anyString(), anyString())).thenReturn(Collections.emptyList());
+ OptimizationConfigPolicy policy = new OptimizationConfigPolicy(policyAdapter);
+ assertThatThrownBy(() -> policy.savePolicies()).isInstanceOf(Exception.class);
- // Test create methods
- String testFileName = "testFile.zip";
- String testVal = "testVal";
- CreateNewOptimizationModel model = new CreateNewOptimizationModel(testFileName, testVal, testVal, testVal, testVal);
- model.addValuesToNewModel();
- model.saveImportService();
+ AdviceExpressionsType expType = policy.getAdviceExpressions(1, "filename");
+ assertEquals(1, expType.getAdviceExpression().size());
}
}
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
index aa1e56988..99cc47c23 100644
--- 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
@@ -3,6 +3,7 @@
* ONAP-PAP-REST
* ================================================================================
* Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2019 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -21,8 +22,10 @@
package org.onap.policy.pap.xacml.rest.components;
import static org.junit.Assert.fail;
+
import com.att.research.xacml.api.pap.PAPException;
import com.att.research.xacml.util.XACMLProperties;
+
import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
@@ -30,9 +33,12 @@ import java.nio.file.Paths;
import java.util.Date;
import java.util.List;
import java.util.Properties;
+import javax.persistence.Persistence;
import javax.persistence.PersistenceException;
+
import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType;
import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType;
+
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.tomcat.dbcp.dbcp2.BasicDataSource;
@@ -47,12 +53,12 @@ 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.DataToNotifyPdp;
-import org.onap.policy.pap.xacml.rest.components.PolicyDBDao.PolicyDBDaoTestClass;
+import org.onap.policy.pap.xacml.rest.components.PolicyDbDao.PolicyDbDaoTestClass;
import org.onap.policy.pap.xacml.rest.daoimpl.CommonClassDaoImpl;
import org.onap.policy.pap.xacml.rest.policycontroller.PolicyCreation;
-import org.onap.policy.rest.XACMLRestProperties;
+import org.onap.policy.rest.XacmlRestProperties;
import org.onap.policy.rest.adapter.PolicyRestAdapter;
-import org.onap.policy.rest.dao.PolicyDBException;
+import org.onap.policy.rest.dao.PolicyDbException;
import org.onap.policy.rest.jpa.DatabaseLockEntity;
import org.onap.policy.rest.jpa.GroupEntity;
import org.onap.policy.rest.jpa.PdpEntity;
@@ -66,9 +72,9 @@ import org.springframework.orm.hibernate4.LocalSessionFactoryBuilder;
public class PolicyDBDaoTest {
private static Logger logger = FlexLogger.getLogger(PolicyDBDaoTest.class);
- static PolicyDBDaoTestClass d;
- static PolicyDBDao dbd;
- static PolicyDBDao dbd2;
+ static PolicyDbDaoTestClass d;
+ static PolicyDbDao dbd;
+ static PolicyDbDao dbd2;
private static Path repository;
static StdEngine stdEngine = null;
static SessionFactory sessionFactory = null;
@@ -78,14 +84,14 @@ public class PolicyDBDaoTest {
System.setProperty(XACMLProperties.XACML_PROPERTIES_NAME, "src/test/resources/xacml.pap.properties");
try {
sessionFactory = setupH2DbDaoImpl("testdbdao");
- dbd = PolicyDBDao.getPolicyDBDaoInstance();
- dbd2 = PolicyDBDao.getPolicyDBDaoInstance();
+ dbd = PolicyDbDao.getPolicyDbDaoInstance();
+ dbd2 = PolicyDbDao.getPolicyDbDaoInstance();
} catch (Exception e) {
Assert.fail();
}
- d = PolicyDBDao.getPolicyDBDaoTestClass();
- PolicyDBDao.setJunit(true);
+ d = PolicyDbDao.getPolicyDbDaoTestClass();
+ PolicyDbDao.setJunit(true);
repository = Paths.get("src/test/resources/pdps");
stdEngine = new StdEngine(repository);
dbd.setPapEngine(stdEngine);
@@ -101,6 +107,8 @@ public class PolicyDBDaoTest {
}
public static SessionFactory setupH2DbDaoImpl(String dbName) {
+ setUpAuditDb();
+
System.setProperty(XACMLProperties.XACML_PROPERTIES_NAME, "src/test/resources/xacml.pap.properties");
BasicDataSource dataSource = new BasicDataSource();
dataSource.setDriverClassName("org.h2.Driver");
@@ -118,7 +126,7 @@ public class PolicyDBDaoTest {
sessionBuilder.addProperties(properties);
SessionFactory sessionFac = sessionBuilder.buildSessionFactory();
- new PolicyDBDao(sessionFac);
+ new PolicyDbDao(sessionFac);
PolicyDbDaoTransactionInstance.setJunit(true);
new PolicyDbDaoTransactionInstance(sessionFac);
CommonClassDaoImpl.setSessionfactory(sessionFac);
@@ -151,6 +159,16 @@ public class PolicyDBDaoTest {
return sessionFac;
}
+ private static void setUpAuditDb() {
+ 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, "");
+
+ // create the DB and then close it
+ Persistence.createEntityManagerFactory("testPapPU", properties).close();
+ }
@Test
public void testGetConfigFile() {
@@ -164,7 +182,7 @@ public class PolicyDBDaoTest {
}
@Test
- public void getPolicyNameAndVersionFromPolicyFileNameTest() throws PolicyDBException {
+ public void getPolicyNameAndVersionFromPolicyFileNameTest() throws PolicyDbException {
String policyName = "com.Decision_testname.1.xml";
String[] expectedNameAndVersion = new String[2];
expectedNameAndVersion[0] = "com.Decision_testname";
@@ -233,7 +251,7 @@ public class PolicyDBDaoTest {
fail();
}
- PolicyDBDaoTransaction transaction = dbd.getNewTransaction();
+ PolicyDbDaoTransaction transaction = dbd.getNewTransaction();
try {
transaction.createPolicy(policyObject, "testuser1");
transaction.commitTransaction();
@@ -275,10 +293,10 @@ public class PolicyDBDaoTest {
@Test
public void groupTransactions() {
- PolicyDBDaoTransaction group = dbd.getNewTransaction();
+ PolicyDbDaoTransaction group = dbd.getNewTransaction();
String groupName = "test group 1";
try {
- group.createGroup(PolicyDBDao.createNewPDPGroupId(groupName), groupName, "this is a test group",
+ group.createGroup(PolicyDbDao.createNewPdpGroupId(groupName), groupName, "this is a test group",
"testuser");
group.commitTransaction();
} catch (Exception e) {
@@ -290,18 +308,18 @@ public class PolicyDBDaoTest {
session.getTransaction().begin();
Query getGroup =
session.createQuery("SELECT g FROM GroupEntity g WHERE g.groupId=:groupId AND g.deleted=:deleted");
- getGroup.setParameter("groupId", PolicyDBDao.createNewPDPGroupId(groupName));
+ getGroup.setParameter("groupId", PolicyDbDao.createNewPdpGroupId(groupName));
getGroup.setParameter("deleted", false);
List<?> groups = getGroup.list();
GroupEntity groupEntity = (GroupEntity) groups.get(0);
- Assert.assertEquals(groupName, groupEntity.getgroupName());
+ Assert.assertEquals(groupName, groupEntity.getGroupName());
Assert.assertEquals("this is a test group", groupEntity.getDescription());
session.getTransaction().commit();
session.close();
group = dbd.getNewTransaction();
try {
- OnapPDPGroup groupToDelete = new StdPDPGroup(PolicyDBDao.createNewPDPGroupId(groupName), Paths.get("/"));
+ OnapPDPGroup groupToDelete = new StdPDPGroup(PolicyDbDao.createNewPdpGroupId(groupName), Paths.get("/"));
group.deleteGroup(groupToDelete, null, "testuser");
group.commitTransaction();
} catch (Exception e) {
@@ -313,7 +331,7 @@ public class PolicyDBDaoTest {
session2.getTransaction().begin();
Query getGroup2 =
session2.createQuery("SELECT g FROM GroupEntity g WHERE g.groupId=:groupId AND g.deleted=:deleted");
- getGroup2.setParameter("groupId", PolicyDBDao.createNewPDPGroupId(groupName));
+ getGroup2.setParameter("groupId", PolicyDbDao.createNewPdpGroupId(groupName));
getGroup2.setParameter("deleted", false);
List<?> groups2 = getGroup2.list();
groups2 = getGroup2.list();
@@ -324,11 +342,10 @@ public class PolicyDBDaoTest {
session2.getTransaction().commit();
session2.close();
-
// add a pdp to a group
group = dbd.getNewTransaction();
try {
- group.createGroup(PolicyDBDao.createNewPDPGroupId(groupName), groupName, "test group", "testuser");
+ group.createGroup(PolicyDbDao.createNewPdpGroupId(groupName), groupName, "test group", "testuser");
group.commitTransaction();
} catch (Exception e) {
group.rollbackTransaction();
@@ -338,7 +355,7 @@ public class PolicyDBDaoTest {
group = dbd.getNewTransaction();
try {
- group.addPdpToGroup("http://localhost:4344/pdp/", PolicyDBDao.createNewPDPGroupId(groupName), "primary",
+ group.addPdpToGroup("http://localhost:4344/pdp/", PolicyDbDao.createNewPdpGroupId(groupName), "primary",
"the main pdp", 3232, "testuser");
group.commitTransaction();
} catch (Exception e) {
@@ -358,12 +375,11 @@ public class PolicyDBDaoTest {
Assert.fail();
}
PdpEntity pdp = (PdpEntity) pdps.get(0);
- Assert.assertEquals(groupName, pdp.getGroup().getgroupName());
+ Assert.assertEquals(groupName, pdp.getGroup().getGroupName());
Assert.assertEquals(pdp.getPdpName(), "primary");
session3.getTransaction().commit();
session3.close();
-
group = dbd.getNewTransaction();
try {
group.removePdpFromGroup("http://localhost:4344/pdp/", "testuser");
@@ -391,7 +407,7 @@ public class PolicyDBDaoTest {
// add some pdps to groups
group = dbd.getNewTransaction();
try {
- group.createGroup(PolicyDBDao.createNewPDPGroupId("testgroup1"), "testgroup1", "test group", "testuser");
+ group.createGroup(PolicyDbDao.createNewPdpGroupId("testgroup1"), "testgroup1", "test group", "testuser");
group.commitTransaction();
} catch (Exception e) {
group.rollbackTransaction();
@@ -400,7 +416,7 @@ public class PolicyDBDaoTest {
}
group = dbd.getNewTransaction();
try {
- group.createGroup(PolicyDBDao.createNewPDPGroupId("testgroup2"), "testgroup2", "test group", "testuser");
+ group.createGroup(PolicyDbDao.createNewPdpGroupId("testgroup2"), "testgroup2", "test group", "testuser");
group.commitTransaction();
} catch (Exception e) {
group.rollbackTransaction();
@@ -410,7 +426,7 @@ public class PolicyDBDaoTest {
group = dbd.getNewTransaction();
try {
- group.addPdpToGroup("http://localhost:4344/pdp/", PolicyDBDao.createNewPDPGroupId("testgroup1"), "primary",
+ group.addPdpToGroup("http://localhost:4344/pdp/", PolicyDbDao.createNewPdpGroupId("testgroup1"), "primary",
"the main pdp", 3232, "testuser");
group.commitTransaction();
} catch (Exception e) {
@@ -420,7 +436,7 @@ public class PolicyDBDaoTest {
}
group = dbd.getNewTransaction();
try {
- group.addPdpToGroup("http://localhost:4345/pdp/", PolicyDBDao.createNewPDPGroupId("testgroup1"),
+ group.addPdpToGroup("http://localhost:4345/pdp/", PolicyDbDao.createNewPdpGroupId("testgroup1"),
"secondary", "the second pdp", 3233, "testuser");
group.commitTransaction();
} catch (Exception e) {
@@ -435,17 +451,16 @@ public class PolicyDBDaoTest {
getPdp3.setParameter("deleted", false);
List<?> pdps3 = getPdp3.list();
for (Object obj : pdps3) {
- Assert.assertEquals("testgroup1", ((PdpEntity) obj).getGroup().getgroupName());
+ Assert.assertEquals("testgroup1", ((PdpEntity) obj).getGroup().getGroupName());
}
session5.getTransaction().commit();
session5.close();
-
group = dbd.getNewTransaction();
try {
- OnapPDPGroup groupToDelete = new StdPDPGroup(PolicyDBDao.createNewPDPGroupId("testgroup1"), Paths.get("/"));
- OnapPDPGroup groupToMoveTo = new StdPDPGroup(PolicyDBDao.createNewPDPGroupId("testgroup2"), Paths.get("/"));
+ 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) {
@@ -475,21 +490,20 @@ public class PolicyDBDaoTest {
getPdp4.setParameter("deleted", false);
List<?> pdps4 = getPdp4.list();
for (Object obj : pdps4) {
- Assert.assertEquals("testgroup2", ((PdpEntity) obj).getGroup().getgroupName());
+ Assert.assertEquals("testgroup2", ((PdpEntity) obj).getGroup().getGroupName());
}
session7.getTransaction().commit();
session7.close();
-
group = dbd.getNewTransaction();
try {
- OnapPDPGroup groupToDelete = new StdPDPGroup(PolicyDBDao.createNewPDPGroupId("testgroup2"), Paths.get("/"));
+ OnapPDPGroup groupToDelete = new StdPDPGroup(PolicyDbDao.createNewPdpGroupId("testgroup2"), Paths.get("/"));
OnapPDPGroup groupToMoveTo = null;
group.deleteGroup(groupToDelete, groupToMoveTo, "testuser");
group.commitTransaction();
Assert.fail();
- } catch (PolicyDBException pe) {
+ } catch (PolicyDbException pe) {
// good, can't delete group with pdps
group.rollbackTransaction();
} catch (Exception e) {
@@ -550,12 +564,12 @@ public class PolicyDBDaoTest {
+ "******************************\n\n");
}
- PolicyDBDaoTransaction t = dbd.getNewTransaction();
+ 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;
+ 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
@@ -573,13 +587,12 @@ public class PolicyDBDaoTest {
}
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();
+ PolicyDbDaoTransaction a = dbd.getNewTransaction();
if (logger.isDebugEnabled()) {
Date date = new java.util.Date();
logger.debug(
@@ -591,7 +604,7 @@ public class PolicyDBDaoTest {
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;
+ 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
@@ -606,7 +619,7 @@ public class PolicyDBDaoTest {
logger.debug("\n\nPolicyDBDaoTest.threadingStabilityTest() " + "\n b = dbd.getNewTransaction() "
+ "\n TimeStamp = " + date.getTime() + "\n\n");
}
- PolicyDBDaoTransaction b = dbd.getNewTransaction();
+ PolicyDbDaoTransaction b = dbd.getNewTransaction();
if (logger.isDebugEnabled()) {
Date date = new java.util.Date();
logger.debug(
@@ -623,14 +636,12 @@ public class PolicyDBDaoTest {
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");
+ 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");
+ System.setProperty(XacmlRestProperties.PROP_PAP_TRANS_TIMEOUT, "5000");
// get a transacton
- PolicyDBDaoTransaction t1 = dbd.getNewTransaction();
+ PolicyDbDaoTransaction t1 = dbd.getNewTransaction();
if (logger.isDebugEnabled()) {
Date date = new java.util.Date();
logger.debug(
@@ -643,7 +654,7 @@ public class PolicyDBDaoTest {
// 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();
+ 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
diff --git a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/components/PolicyTest.java b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/components/PolicyTest.java
new file mode 100644
index 000000000..8d8663e17
--- /dev/null
+++ b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/components/PolicyTest.java
@@ -0,0 +1,74 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP-PAP-REST
+ * ================================================================================
+ * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertNull;
+
+import com.att.research.xacml.util.XACMLProperties;
+
+import java.nio.file.Path;
+import java.nio.file.Paths;
+
+import org.junit.Test;
+import org.mockito.Mockito;
+import org.onap.policy.rest.adapter.PolicyRestAdapter;
+
+import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType;
+
+public class PolicyTest {
+ @Test
+ public void testPolicy() {
+ // Setup test data
+ System.setProperty(XACMLProperties.XACML_PROPERTIES_NAME, "xacml.pap.properties");
+ PolicyRestAdapter adapter = Mockito.mock(PolicyRestAdapter.class);
+ Policy policy = new ConfigPolicy(adapter);
+ Path path = Paths.get("src/test/resources");
+
+ // Test set and get
+ policy.setFinalPolicyPath(path);
+ assertEquals(path, policy.getFinalPolicyPath());
+
+ // Test misc methods
+ assertNotNull(policy.createMatch("testKey", "testVal"));
+ assertNotNull(policy.createDynamicMatch("testKey", "testVal"));
+ assertNotNull(policy.getNextFilename(path, "Config", "SampleTest1206", 1));
+ assertNull(policy.getNextLoopFilename(path, "Config", "ClosedLoop_PM", "foo", 1));
+ assertNull(policy.getNextLoopFilename(path, "Config", "ClosedLoop_Fault", "foo", 1));
+ assertNull(policy.getNextLoopFilename(path, "Config", "Micro Service", "foo", 1));
+ assertNull(policy.getNextLoopFilename(path, "Config", "Optimization", "foo", 1));
+
+ // Test create
+ Object policyData = null;
+ assertEquals(0, policy.createPolicy(null, policyData).size());
+ policyData = new PolicyType();
+ assertEquals(1, policy.createPolicy(null, policyData).size());
+
+ // Test remaining set and get
+ assertNotNull(Policy.getConfigHome());
+ assertEquals(true, policy.validateConfigForm());
+ policy.setPreparedToSave(true);
+ assertEquals(true, policy.isPreparedToSave());
+ policy.setPolicyExists(true);
+ assertEquals(true, policy.isPolicyExists());
+ }
+}
diff --git a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/controller/ActionPolicyDictionaryControllerTest.java b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/controller/ActionPolicyDictionaryControllerTest.java
index efb13b5a0..eccf13ba7 100644
--- a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/controller/ActionPolicyDictionaryControllerTest.java
+++ b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/controller/ActionPolicyDictionaryControllerTest.java
@@ -2,14 +2,14 @@
* ============LICENSE_START=======================================================
* ONAP-PAP-REST
* ================================================================================
- * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2018-2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -17,6 +17,7 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.policy.pap.xacml.rest.controller;
import static org.junit.Assert.assertTrue;
@@ -57,8 +58,8 @@ public class ActionPolicyDictionaryControllerTest {
public void setUp() throws Exception {
logger.info("setUp: Entering");
commonClassDao = Mockito.mock(CommonClassDao.class);
- List<String> data = new ArrayList<>();
- List<Object> objectData = new ArrayList<>();
+ List<String> data = new ArrayList<>();
+ List<Object> objectData = new ArrayList<>();
data.add("Test");
UserInfo userInfo = new UserInfo();
@@ -71,9 +72,9 @@ public class ActionPolicyDictionaryControllerTest {
actionData.setBody("Test");
assertTrue("Test".equals(actionData.getBody()));
actionData.setCreatedDate(new Date());
- assertTrue(actionData.getCreatedDate()!= null);
+ assertTrue(actionData.getCreatedDate() != null);
actionData.setModifiedDate(new Date());
- assertTrue(actionData.getModifiedDate()!= null);
+ assertTrue(actionData.getModifiedDate() != null);
actionData.setHeader("Test");
assertTrue("Test".equals(actionData.getHeader()));
actionData.setMethod("POST");
@@ -83,9 +84,9 @@ public class ActionPolicyDictionaryControllerTest {
actionData.setUrl("http://test.com");
assertTrue("http://test.com".equals(actionData.getUrl()));
actionData.setUserCreatedBy(userInfo);
- assertTrue(actionData.getUserCreatedBy()!= null);
+ assertTrue(actionData.getUserCreatedBy() != null);
actionData.setUserModifiedBy(userInfo);
- assertTrue(actionData.getUserModifiedBy()!= null);
+ assertTrue(actionData.getUserModifiedBy() != null);
objectData.add(actionData);
when(commonClassDao.getDataByColumn(ActionPolicyDict.class, "attributeName")).thenReturn(data);
@@ -95,7 +96,7 @@ public class ActionPolicyDictionaryControllerTest {
controller = new ActionPolicyDictionaryController();
controller.setCommonClassDao(commonClassDao);
request = Mockito.mock(HttpServletRequest.class);
- response = new MockHttpServletResponse();
+ response = new MockHttpServletResponse();
new DictionaryUtils(commonClassDao);
DictionaryUtils.setDictionaryUtils(new DictionaryUtils());
mock(DictionaryUtils.class);
@@ -103,60 +104,78 @@ public class ActionPolicyDictionaryControllerTest {
}
@Test
- public void testGetActionEntitybyName(){
+ public void testGetActionEntitybyName() {
controller.getActionEntitybyName(response);
try {
- assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("actionPolicyDictionaryDatas"));
+ assertTrue(response.getContentAsString() != null
+ && response.getContentAsString().contains("actionPolicyDictionaryDatas"));
} catch (Exception e) {
fail();
- logger.error(e.getMessage(),e);
+ logger.error(e.getMessage(), e);
}
}
@Test
- public void testGetActionPolicyDictionaryEntityData(){
+ public void testGetActionPolicyDictionaryEntityData() {
controller.getActionPolicyDictionaryEntityData(response);
try {
- assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("actionPolicyDictionaryDatas"));
+ assertTrue(response.getContentAsString() != null
+ && response.getContentAsString().contains("actionPolicyDictionaryDatas"));
} catch (Exception e) {
fail();
- logger.error(e.getMessage(),e);
+ logger.error(e.getMessage(), e);
}
}
@Test
- public void testSaveActionPolicyDictionary(){
- jsonString = "{\"actionPolicyDictionaryData\":{\"attributeName\":\"Test\",\"body\":\"{}\",\"description\":\"test\",\"headers\":[{\"$$hashKey\":\"object:548\",\"id\":\"choice1\",\"number\":\"12\",\"option\":\"test\"}],\"method\":\"GET\",\"type\":\"REST\",\"url\":\"http://test.com\"},\"userid\":\"demo\"}";
- try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){
+ public void testSaveActionPolicyDictionary() {
+ jsonString =
+ "{\"actionPolicyDictionaryData\":{\"attributeName\":\"Test\",\"body\":\"{}\",\"description\":"
+ + "\"test\",\"headers\":[{\"$$hashKey\":\"object:548\",\"id\":\"choice1\",\"number\":\"12\","
+ + "\"option\":\"test\"}],\"method\":\"GET\",\"type\":\"REST\",\"url\":\"http://test.com\"},"
+ + "\"userid\":\"demo\"}";
+ try (BufferedReader br = new BufferedReader(new StringReader(jsonString))) {
when(request.getReader()).thenReturn(br);
controller.saveActionPolicyDictionary(request, response);
- assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("actionPolicyDictionaryData"));
- }catch(Exception e){
- logger.error("Exception"+ e);
+ assertTrue(response.getContentAsString() != null
+ && response.getContentAsString().contains("actionPolicyDictionaryData"));
+ } catch (Exception e) {
+ logger.error("Exception" + e);
}
}
@Test
- public void testUpdateActionPolicyDictionary(){
- jsonString = "{\"actionPolicyDictionaryData\":{\"id\":1,\"attributeName\":\"Test\",\"body\":\"{}\",\"description\":\"test\",\"headers\":[{\"$$hashKey\":\"object:548\",\"id\":\"choice1\",\"number\":\"12\",\"option\":\"test\"}],\"method\":\"GET\",\"type\":\"REST\",\"url\":\"http://test.com\"},\"userid\":\"demo\"}";
- try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){
+ public void testUpdateActionPolicyDictionary() {
+ jsonString =
+ "{\"actionPolicyDictionaryData\":{\"id\":1,\"attributeName\":\"Test\",\"body\":\"{}\",\"description\":"
+ + "\"test\",\"headers\":[{\"$$hashKey\":\"object:548\",\"id\":\"choice1\",\"number\":"
+ + "\"12\",\"option\":\"test\"}],\"method\":\"GET\",\"type\":\"REST\",\"url\":\"http://test.com\"},"
+ + "\"userid\":\"demo\"}";
+ try (BufferedReader br = new BufferedReader(new StringReader(jsonString))) {
when(request.getReader()).thenReturn(br);
controller.saveActionPolicyDictionary(request, response);
- assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("actionPolicyDictionaryData"));
- }catch(Exception e){
- logger.error("Exception"+ e);
+ assertTrue(response.getContentAsString() != null
+ && response.getContentAsString().contains("actionPolicyDictionaryData"));
+ } catch (Exception e) {
+ logger.error("Exception" + e);
}
}
@Test
- public void testRemoveActionPolicyDictionary(){
- jsonString = "{\"data\":{\"$$hashKey\":\"uiGrid-003S\",\"attributeName\":\"Test\",\"body\":\"{}\",\"createdDate\":1518195117000,\"description\":\"test\",\"header\":\"test=12\",\"id\":1,\"method\":\"GET\",\"modifiedDate\":1518195489000,\"type\":\"REST\",\"url\":\"http://test.com\",\"userCreatedBy\":{\"userLoginId\":\"demo\",\"userName\":\"Demo\"},\"userModifiedBy\":{\"userLoginId\":\"demo\",\"userName\":\"Demo\"}}}";
- try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){
+ public void testRemoveActionPolicyDictionary() {
+ jsonString =
+ "{\"data\":{\"$$hashKey\":\"uiGrid-003S\",\"attributeName\":\"Test\",\"body\":\"{}\",\"createdDate\":"
+ + "1518195117000,\"description\":\"test\",\"header\":\"test=12\",\"id\":1,\"method\":\"GET\","
+ + "\"modifiedDate\":1518195489000,\"type\":\"REST\",\"url\":\"http://test.com\",\"userCreatedBy\":"
+ + "{\"userLoginId\":\"demo\",\"userName\":\"Demo\"},\"userModifiedBy\":{\"userLoginId\":\"demo\","
+ + "\"userName\":\"Demo\"}}}";
+ try (BufferedReader br = new BufferedReader(new StringReader(jsonString))) {
when(request.getReader()).thenReturn(br);
controller.removeActionPolicyDictionary(request, response);
- assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("actionPolicyDictionaryDatas"));
- }catch(Exception e){
- logger.error("Exception"+ e);
+ assertTrue(response.getContentAsString() != null
+ && response.getContentAsString().contains("actionPolicyDictionaryDatas"));
+ } catch (Exception e) {
+ logger.error("Exception" + e);
}
}
}
diff --git a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/controller/BRMSDictionaryControllerTest.java b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/controller/BRMSDictionaryControllerTest.java
index d34e505ba..7d260907b 100644
--- a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/controller/BRMSDictionaryControllerTest.java
+++ b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/controller/BRMSDictionaryControllerTest.java
@@ -2,14 +2,14 @@
* ============LICENSE_START=======================================================
* ONAP-PAP-REST
* ================================================================================
- * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2018-2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -17,6 +17,7 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.policy.pap.xacml.rest.controller;
import static org.junit.Assert.assertTrue;
@@ -40,7 +41,7 @@ import org.onap.policy.common.logging.flexlogger.FlexLogger;
import org.onap.policy.common.logging.flexlogger.Logger;
import org.onap.policy.pap.xacml.rest.util.DictionaryUtils;
import org.onap.policy.rest.dao.CommonClassDao;
-import org.onap.policy.rest.jpa.BRMSParamTemplate;
+import org.onap.policy.rest.jpa.BrmsParamTemplate;
import org.onap.policy.rest.jpa.UserInfo;
import org.springframework.mock.web.MockHttpServletResponse;
@@ -61,14 +62,14 @@ public class BRMSDictionaryControllerTest {
userInfo.setUserLoginId("testUserId");
userInfo.setUserName("John");
when(commonClassDao.getEntityItem(UserInfo.class, "userLoginId", "testing")).thenReturn(userInfo);
- List<String> brms = new ArrayList<String>();
+ List<String> brms = new ArrayList<String>();
brms.add("BRMS-Model");
- when(commonClassDao.getDataByColumn(BRMSParamTemplate.class, "name")).thenReturn(brms);
- doNothing().when(commonClassDao).delete(new BRMSParamTemplate());
- doNothing().when(commonClassDao).save(new BRMSParamTemplate());
+ when(commonClassDao.getDataByColumn(BrmsParamTemplate.class, "name")).thenReturn(brms);
+ doNothing().when(commonClassDao).delete(new BrmsParamTemplate());
+ doNothing().when(commonClassDao).save(new BrmsParamTemplate());
controller = new BRMSDictionaryController();
request = Mockito.mock(HttpServletRequest.class);
- response = new MockHttpServletResponse();
+ response = new MockHttpServletResponse();
new DictionaryUtils(commonClassDao);
DictionaryUtils.setDictionaryUtils(new DictionaryUtils());
mock(DictionaryUtils.class);
@@ -76,12 +77,13 @@ public class BRMSDictionaryControllerTest {
}
@Test
- public void testGetBRMSParamDictionaryByNameEntityData(){
+ public void testGetBRMSParamDictionaryByNameEntityData() {
logger.info("testGetBRMSParamDictionaryByNameEntityData: Entering");
BRMSDictionaryController.setCommonClassDao(commonClassDao);
controller.getBRMSParamDictionaryByNameEntityData(response);
try {
- assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("brmsParamDictionaryDatas"));
+ assertTrue(response.getContentAsString() != null
+ && response.getContentAsString().contains("brmsParamDictionaryDatas"));
logger.info("response.getContentAsString(): " + response.getContentAsString());
} catch (UnsupportedEncodingException e) {
fail("Exception: " + e);
@@ -94,7 +96,8 @@ public class BRMSDictionaryControllerTest {
logger.info("testGetBRMSParamDictionaryEntityData: Entering");
controller.getBRMSParamDictionaryEntityData(response);
try {
- assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("brmsParamDictionaryDatas"));
+ assertTrue(response.getContentAsString() != null
+ && response.getContentAsString().contains("brmsParamDictionaryDatas"));
logger.info("response.getContentAsString(): " + response.getContentAsString());
} catch (UnsupportedEncodingException e) {
fail("Exception: " + e);
@@ -105,14 +108,16 @@ public class BRMSDictionaryControllerTest {
@Test
public void testSaveBRMSParamDictionary() {
logger.info("testSaveBRMSParamDictionary: Entering");
- jsonString = "{\"brmsParamDictionaryData\": {\"ruleName\": \"test\",\"rule\": \"test\"},\"userid\": \"testName\"}";
- try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){
+ jsonString =
+ "{\"brmsParamDictionaryData\": {\"ruleName\": \"test\",\"rule\": \"test\"},\"userid\": \"testName\"}";
+ try (BufferedReader br = new BufferedReader(new StringReader(jsonString))) {
when(request.getReader()).thenReturn(br);
controller.saveBRMSParamDictionary(request, response);
- assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("brmsParamDictionaryData"));
+ assertTrue(response.getContentAsString() != null
+ && response.getContentAsString().contains("brmsParamDictionaryData"));
logger.info("response.getContentAsString(): " + response.getContentAsString());
- }catch(Exception e){
- logger.error("Exception"+ e);
+ } catch (Exception e) {
+ logger.error("Exception" + e);
}
logger.info("testSaveBRMSParamDictionary: exit");
}
@@ -121,11 +126,12 @@ public class BRMSDictionaryControllerTest {
public void testRemoveBRMSParamDictionary() {
logger.info("testRemoveBRMSParamDictionary: Entering");
jsonString = "{\"data\": {\"ruleName\": \"test\",\"rule\": \"test\"}}";
- try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){
+ try (BufferedReader br = new BufferedReader(new StringReader(jsonString))) {
when(request.getReader()).thenReturn(br);
controller.removeBRMSParamDictionary(request, response);
logger.info("response.getContentAsString(): " + response.getContentAsString());
- assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("brmsParamDictionaryDatas"));
+ assertTrue(response.getContentAsString() != null
+ && response.getContentAsString().contains("brmsParamDictionaryDatas"));
} catch (Exception e) {
fail("Exception: " + e);
}
@@ -133,12 +139,13 @@ public class BRMSDictionaryControllerTest {
}
@Test
- public void testGetBRMSDependencyDictionaryByNameEntityData(){
+ public void testGetBRMSDependencyDictionaryByNameEntityData() {
logger.info("testGetBRMSDependencyDictionaryByNameEntityData: Entering");
BRMSDictionaryController.setCommonClassDao(commonClassDao);
controller.getBRMSDependencyDictionaryByNameEntityData(response);
try {
- assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("brmsDependencyDictionaryDatas"));
+ assertTrue(response.getContentAsString() != null
+ && response.getContentAsString().contains("brmsDependencyDictionaryDatas"));
logger.info("response.getContentAsString(): " + response.getContentAsString());
} catch (UnsupportedEncodingException e) {
fail("Exception: " + e);
@@ -147,12 +154,13 @@ public class BRMSDictionaryControllerTest {
}
@Test
- public void testGetBRMSDependencyDictionaryEntityData(){
+ public void testGetBRMSDependencyDictionaryEntityData() {
logger.info("testGetBRMSDependencyDictionaryEntityData: Entering");
BRMSDictionaryController.setCommonClassDao(commonClassDao);
controller.getBRMSDependencyDictionaryEntityData(response);
try {
- assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("brmsDependencyDictionaryDatas"));
+ assertTrue(response.getContentAsString() != null
+ && response.getContentAsString().contains("brmsDependencyDictionaryDatas"));
logger.info("response.getContentAsString(): " + response.getContentAsString());
} catch (UnsupportedEncodingException e) {
fail("Exception: " + e);
@@ -164,13 +172,16 @@ public class BRMSDictionaryControllerTest {
@Test
public void testSaveBRMSDependencyDictionary() {
logger.info("testSaveBRMSDependencyDictionary: Entering");
- jsonString = "{\"brmsDependencyDictionaryData\": {\"ruleName\": \"test\",\"rule\": \"test\"},\"userid\": \"testName\"}";
- try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){
- when(request.getReader()).thenReturn(br);
- controller.saveBRMSDependencyDictionary(request, response);
- logger.info("response.getContentAsString(): " + response.getContentAsString());
- assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("brmsDependencyDictionaryData"));
- } catch (Exception e) {
+ jsonString =
+ "{\"brmsDependencyDictionaryData\": "
+ + "{\"ruleName\": \"test\",\"rule\": \"test\"},\"userid\": \"testName\"}";
+ try (BufferedReader br = new BufferedReader(new StringReader(jsonString))) {
+ when(request.getReader()).thenReturn(br);
+ controller.saveBRMSDependencyDictionary(request, response);
+ logger.info("response.getContentAsString(): " + response.getContentAsString());
+ assertTrue(response.getContentAsString() != null
+ && response.getContentAsString().contains("brmsDependencyDictionaryData"));
+ } catch (Exception e) {
fail("Exception: " + e);
}
logger.info("testSaveBRMSDependencyDictionary: exit");
@@ -179,14 +190,15 @@ public class BRMSDictionaryControllerTest {
@Test
public void testRemoveBRMSDependencyDictionary() {
logger.info("testRemoveBRMSDependencyDictionary: Entering");
- MockHttpServletResponse response = new MockHttpServletResponse();
+ MockHttpServletResponse response = new MockHttpServletResponse();
request = mock(HttpServletRequest.class);
jsonString = "{\"data\": {\"ruleName\": \"test\",\"rule\": \"test\"}}";
- try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){
+ try (BufferedReader br = new BufferedReader(new StringReader(jsonString))) {
when(request.getReader()).thenReturn(br);
controller.removeBRMSDependencyDictionary(request, response);
logger.info("response.getContentAsString(): " + response.getContentAsString());
- assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("brmsDependencyDictionaryDatas"));
+ assertTrue(response.getContentAsString() != null
+ && response.getContentAsString().contains("brmsDependencyDictionaryDatas"));
} catch (Exception e) {
fail("Exception: " + e);
}
@@ -194,13 +206,14 @@ public class BRMSDictionaryControllerTest {
}
@Test
- public void testGetBRMSControllerDictionaryByNameEntityData(){
+ public void testGetBRMSControllerDictionaryByNameEntityData() {
logger.info("testGetBRMSControllerDictionaryByNameEntityData: Entering");
- MockHttpServletResponse response = new MockHttpServletResponse();
+ MockHttpServletResponse response = new MockHttpServletResponse();
BRMSDictionaryController.setCommonClassDao(commonClassDao);
controller.getBRMSControllerDictionaryByNameEntityData(response);
try {
- assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("brmsControllerDictionaryDatas"));
+ assertTrue(response.getContentAsString() != null
+ && response.getContentAsString().contains("brmsControllerDictionaryDatas"));
logger.info("response.getContentAsString(): " + response.getContentAsString());
} catch (UnsupportedEncodingException e) {
fail("Exception: " + e);
@@ -209,13 +222,14 @@ public class BRMSDictionaryControllerTest {
}
@Test
- public void testGetBRMSControllerDictionaryEntityData(){
+ public void testGetBRMSControllerDictionaryEntityData() {
logger.info("testGetBRMSControllerDictionaryEntityData: Entering");
- MockHttpServletResponse response = new MockHttpServletResponse();
+ MockHttpServletResponse response = new MockHttpServletResponse();
BRMSDictionaryController.setCommonClassDao(commonClassDao);
controller.getBRMSControllerDictionaryEntityData(response);
try {
- assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("brmsControllerDictionaryDatas"));
+ assertTrue(response.getContentAsString() != null
+ && response.getContentAsString().contains("brmsControllerDictionaryDatas"));
logger.info("response.getContentAsString(): " + response.getContentAsString());
} catch (UnsupportedEncodingException e) {
fail("Exception: " + e);
@@ -227,14 +241,17 @@ public class BRMSDictionaryControllerTest {
public void testSaveBRMSControllerDictionary() {
logger.info("testSaveBRMSControllerDictionary: Entering");
- MockHttpServletResponse response = new MockHttpServletResponse();
+ MockHttpServletResponse response = new MockHttpServletResponse();
request = mock(HttpServletRequest.class);
- jsonString = "{\"brmsControllerDictionaryData\": {\"ruleName\": \"test\",\"rule\": \"test\"},\"userid\": \"testName\"}";
- try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){
+ jsonString =
+ "{\"brmsControllerDictionaryData\": "
+ + "{\"ruleName\": \"test\",\"rule\": \"test\"},\"userid\": \"testName\"}";
+ try (BufferedReader br = new BufferedReader(new StringReader(jsonString))) {
when(request.getReader()).thenReturn(br);
controller.saveBRMSControllerDictionary(request, response);
logger.info("response.getContentAsString(): " + response.getContentAsString());
- assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("brmsControllerDictionaryData"));
+ assertTrue(response.getContentAsString() != null
+ && response.getContentAsString().contains("brmsControllerDictionaryData"));
} catch (Exception e) {
fail("Exception: " + e);
}
@@ -244,14 +261,15 @@ public class BRMSDictionaryControllerTest {
@Test
public void testRemoveBRMSControllerDictionary() {
logger.info("testRemoveBRMSControllerDictionary: Entering");
- MockHttpServletResponse response = new MockHttpServletResponse();
+ MockHttpServletResponse response = new MockHttpServletResponse();
request = mock(HttpServletRequest.class);
jsonString = "{\"data\": {\"ruleName\": \"test\",\"rule\": \"test\"}}";
- try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){
+ try (BufferedReader br = new BufferedReader(new StringReader(jsonString))) {
when(request.getReader()).thenReturn(br);
controller.removeBRMSControllerDictionary(request, response);
logger.info("response.getContentAsString(): " + response.getContentAsString());
- assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("brmsControllerDictionaryDatas"));
+ assertTrue(response.getContentAsString() != null
+ && response.getContentAsString().contains("brmsControllerDictionaryDatas"));
} catch (Exception e) {
fail("Exception: " + e);
@@ -259,4 +277,3 @@ public class BRMSDictionaryControllerTest {
logger.info("testRemoveBRMSControllerDictionary: exit");
}
}
-
diff --git a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/controller/ClosedLoopDictionaryControllerTest.java b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/controller/ClosedLoopDictionaryControllerTest.java
index f530b4c62..8f0d52b21 100644
--- a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/controller/ClosedLoopDictionaryControllerTest.java
+++ b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/controller/ClosedLoopDictionaryControllerTest.java
@@ -2,14 +2,14 @@
* ============LICENSE_START=======================================================
* ONAP-PAP-REST
* ================================================================================
- * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2018-2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -17,6 +17,7 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.policy.pap.xacml.rest.controller;
import static org.junit.Assert.assertTrue;
@@ -41,10 +42,10 @@ import org.onap.policy.pap.xacml.rest.util.DictionaryUtils;
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.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.VnfType;
+import org.onap.policy.rest.jpa.VsclAction;
import org.onap.policy.rest.jpa.VarbindDictionary;
import org.springframework.mock.web.MockHttpServletResponse;
@@ -57,7 +58,7 @@ public class ClosedLoopDictionaryControllerTest {
private ClosedLoopDictionaryController controller = null;
private MockHttpServletResponse response = null;
private UserInfo userInfo;
- private List<String> data;
+ private List<String> data;
@Before
public void setUp() throws Exception {
@@ -71,14 +72,14 @@ public class ClosedLoopDictionaryControllerTest {
userInfo.setUserLoginId("Test");
userInfo.setUserName("Test");
- doNothing().when(commonClassDao).delete(new VSCLAction());
- doNothing().when(commonClassDao).save(new VSCLAction());
+ doNothing().when(commonClassDao).delete(new VsclAction());
+ doNothing().when(commonClassDao).save(new VsclAction());
controller = new ClosedLoopDictionaryController();
controller.setCommonClassDao(commonClassDao);
request = Mockito.mock(HttpServletRequest.class);
- response = new MockHttpServletResponse();
+ response = new MockHttpServletResponse();
new DictionaryUtils(commonClassDao);
DictionaryUtils.setDictionaryUtils(new DictionaryUtils());
mock(DictionaryUtils.class);
@@ -86,362 +87,404 @@ public class ClosedLoopDictionaryControllerTest {
}
@Test
- public void testGetVSCLActionDictionaryByNameEntityData(){
- when(commonClassDao.getDataByColumn(VSCLAction.class, "vsclaction")).thenReturn(data);
+ public void testGetVSCLActionDictionaryByNameEntityData() {
+ when(commonClassDao.getDataByColumn(VsclAction.class, "vsclaction")).thenReturn(data);
controller.getVSCLActionDictionaryByNameEntityData(response);
try {
- assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("vsclActionDictionaryDatas"));
+ assertTrue(response.getContentAsString() != null
+ && response.getContentAsString().contains("vsclActionDictionaryDatas"));
} catch (Exception e) {
fail();
- logger.error(e.getMessage(),e);
+ logger.error(e.getMessage(), e);
}
}
@Test
- public void testGetVSCLActionDictionaryEntityData(){
- when(commonClassDao.getData(VSCLAction.class)).thenReturn(new ArrayList<>());
+ public void testGetVSCLActionDictionaryEntityData() {
+ when(commonClassDao.getData(VsclAction.class)).thenReturn(new ArrayList<>());
controller.getVSCLActionDictionaryEntityData(response);
try {
- assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("vsclActionDictionaryDatas"));
+ assertTrue(response.getContentAsString() != null
+ && response.getContentAsString().contains("vsclActionDictionaryDatas"));
} catch (Exception e) {
fail();
- logger.error(e.getMessage(),e);
+ logger.error(e.getMessage(), e);
}
}
@Test
- public void testGetVNFTypeDictionaryByNameEntityData(){
- when(commonClassDao.getDataByColumn(VNFType.class, "vnftype")).thenReturn(data);
+ public void testGetVNFTypeDictionaryByNameEntityData() {
+ when(commonClassDao.getDataByColumn(VnfType.class, "vnftype")).thenReturn(data);
controller.getVNFTypeDictionaryByNameEntityData(response);
try {
- assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("vnfTypeDictionaryDatas"));
+ assertTrue(response.getContentAsString() != null
+ && response.getContentAsString().contains("vnfTypeDictionaryDatas"));
} catch (Exception e) {
fail();
- logger.error(e.getMessage(),e);
+ logger.error(e.getMessage(), e);
}
}
@Test
- public void testGetVNFTypeDictionaryEntityData(){
- when(commonClassDao.getData(VNFType.class)).thenReturn(new ArrayList<>());
+ public void testGetVNFTypeDictionaryEntityData() {
+ when(commonClassDao.getData(VnfType.class)).thenReturn(new ArrayList<>());
controller.getVNFTypeDictionaryEntityData(response);
try {
- assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("vnfTypeDictionaryDatas"));
+ assertTrue(response.getContentAsString() != null
+ && response.getContentAsString().contains("vnfTypeDictionaryDatas"));
} catch (Exception e) {
fail();
- logger.error(e.getMessage(),e);
+ logger.error(e.getMessage(), e);
}
}
@Test
- public void testGetPEPOptionsDictionaryByNameEntityData(){
- when(commonClassDao.getDataByColumn(PEPOptions.class, "pepName")).thenReturn(data);
+ public void testGetPEPOptionsDictionaryByNameEntityData() {
+ when(commonClassDao.getDataByColumn(PepOptions.class, "pepName")).thenReturn(data);
controller.getPEPOptionsDictionaryByNameEntityData(response);
try {
- assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("pepOptionsDictionaryDatas"));
+ assertTrue(response.getContentAsString() != null
+ && response.getContentAsString().contains("pepOptionsDictionaryDatas"));
} catch (Exception e) {
fail();
- logger.error(e.getMessage(),e);
+ logger.error(e.getMessage(), e);
}
}
@Test
- public void testGetPEPOptionsDictionaryEntityData(){
- when(commonClassDao.getData(PEPOptions.class)).thenReturn(new ArrayList<>());
+ public void testGetPEPOptionsDictionaryEntityData() {
+ when(commonClassDao.getData(PepOptions.class)).thenReturn(new ArrayList<>());
controller.getPEPOptionsDictionaryEntityData(response);
try {
- assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("pepOptionsDictionaryDatas"));
+ assertTrue(response.getContentAsString() != null
+ && response.getContentAsString().contains("pepOptionsDictionaryDatas"));
} catch (Exception e) {
fail();
- logger.error(e.getMessage(),e);
+ logger.error(e.getMessage(), e);
}
}
@Test
- public void testGetVarbindDictionaryByNameEntityData(){
+ public void testGetVarbindDictionaryByNameEntityData() {
when(commonClassDao.getDataByColumn(VarbindDictionary.class, "varbindName")).thenReturn(data);
controller.getVarbindDictionaryByNameEntityData(response);
try {
- assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("varbindDictionaryDatas"));
+ assertTrue(response.getContentAsString() != null
+ && response.getContentAsString().contains("varbindDictionaryDatas"));
} catch (Exception e) {
fail();
- logger.error(e.getMessage(),e);
+ logger.error(e.getMessage(), e);
}
}
@Test
- public void testGetVarbindDictionaryEntityData(){
+ public void testGetVarbindDictionaryEntityData() {
when(commonClassDao.getData(VarbindDictionary.class)).thenReturn(new ArrayList<>());
controller.getVarbindDictionaryEntityData(response);
try {
- assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("varbindDictionaryDatas"));
+ assertTrue(response.getContentAsString() != null
+ && response.getContentAsString().contains("varbindDictionaryDatas"));
} catch (Exception e) {
fail();
- logger.error(e.getMessage(),e);
+ logger.error(e.getMessage(), e);
}
}
@Test
- public void testGetClosedLoopServiceDictionaryByNameEntityData(){
+ public void testGetClosedLoopServiceDictionaryByNameEntityData() {
when(commonClassDao.getDataByColumn(ClosedLoopD2Services.class, "serviceName")).thenReturn(data);
controller.getClosedLoopServiceDictionaryByNameEntityData(response);
try {
- assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("closedLoopServiceDictionaryDatas"));
+ assertTrue(response.getContentAsString() != null
+ && response.getContentAsString().contains("closedLoopServiceDictionaryDatas"));
} catch (Exception e) {
fail();
- logger.error(e.getMessage(),e);
+ logger.error(e.getMessage(), e);
}
}
@Test
- public void testGetClosedLoopServiceDictionaryEntityData(){
+ public void testGetClosedLoopServiceDictionaryEntityData() {
when(commonClassDao.getData(ClosedLoopD2Services.class)).thenReturn(new ArrayList<>());
controller.getClosedLoopServiceDictionaryEntityData(response);
try {
- assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("closedLoopServiceDictionaryDatas"));
+ assertTrue(response.getContentAsString() != null
+ && response.getContentAsString().contains("closedLoopServiceDictionaryDatas"));
} catch (Exception e) {
fail();
- logger.error(e.getMessage(),e);
+ logger.error(e.getMessage(), e);
}
}
@Test
- public void testGetClosedLoopSiteDictionaryByNameEntityData(){
+ public void testGetClosedLoopSiteDictionaryByNameEntityData() {
when(commonClassDao.getDataByColumn(ClosedLoopSite.class, "siteName")).thenReturn(data);
controller.getClosedLoopSiteDictionaryByNameEntityData(response);
try {
- assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("closedLoopSiteDictionaryDatas"));
+ assertTrue(response.getContentAsString() != null
+ && response.getContentAsString().contains("closedLoopSiteDictionaryDatas"));
} catch (Exception e) {
fail();
- logger.error(e.getMessage(),e);
+ logger.error(e.getMessage(), e);
}
}
@Test
- public void testGetClosedLoopSiteDictionaryEntityData(){
+ public void testGetClosedLoopSiteDictionaryEntityData() {
when(commonClassDao.getData(ClosedLoopSite.class)).thenReturn(new ArrayList<>());
controller.getClosedLoopSiteDictionaryEntityData(response);
try {
- assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("closedLoopSiteDictionaryDatas"));
+ assertTrue(response.getContentAsString() != null
+ && response.getContentAsString().contains("closedLoopSiteDictionaryDatas"));
} catch (Exception e) {
fail();
- logger.error(e.getMessage(),e);
+ logger.error(e.getMessage(), e);
}
}
@Test
- public void testSaveVSCLAction(){
- jsonString = "{\"userid\":\"demo\",\"vsclActionDictionaryData\":{\"description\":\"test\",\"vsclaction\":\"Test\"}}";
- try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){
+ public void testSaveVSCLAction() {
+ jsonString =
+ "{\"userid\":\"demo\",\"vsclActionDictionaryData\":{\"description\":\"test\",\"vsclaction\":\"Test\"}}";
+ try (BufferedReader br = new BufferedReader(new StringReader(jsonString))) {
when(request.getReader()).thenReturn(br);
controller.saveVSCLAction(request, response);
- assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("vsclActionDictionaryDatas"));
- }catch(Exception e){
- logger.error("Exception"+ e);
+ assertTrue(response.getContentAsString() != null
+ && response.getContentAsString().contains("vsclActionDictionaryDatas"));
+ } catch (Exception e) {
+ logger.error("Exception" + e);
}
}
@Test
- public void testUpdateVSCLAction(){
- jsonString = "{\"userid\":\"demo\",\"vsclActionDictionaryData\":{\"id\":1,\"description\":\"test\",\"vsclaction\":\"Test\"}}";
- try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){
+ public void testUpdateVSCLAction() {
+ jsonString =
+ "{\"userid\":\"demo\",\"vsclActionDictionaryData\":{\"id\":1,\"description\":\"test\",\"vsclaction\":\"Test\"}}";
+ try (BufferedReader br = new BufferedReader(new StringReader(jsonString))) {
when(request.getReader()).thenReturn(br);
controller.saveVSCLAction(request, response);
- assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("vsclActionDictionaryDatas"));
- }catch(Exception e){
- logger.error("Exception"+ e);
+ assertTrue(response.getContentAsString() != null
+ && response.getContentAsString().contains("vsclActionDictionaryDatas"));
+ } catch (Exception e) {
+ logger.error("Exception" + e);
}
}
@Test
- public void testRemoveVSCLAction(){
+ public void testRemoveVSCLAction() {
jsonString = "{\"userid\":\"demo\",\"data\":{\"id\":1,\"description\":\"test\",\"vsclaction\":\"Test\"}}";
- try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){
+ try (BufferedReader br = new BufferedReader(new StringReader(jsonString))) {
when(request.getReader()).thenReturn(br);
controller.removeVSCLAction(request, response);
- assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("vsclActionDictionaryDatas"));
- }catch(Exception e){
- logger.error("Exception"+ e);
+ assertTrue(response.getContentAsString() != null
+ && response.getContentAsString().contains("vsclActionDictionaryDatas"));
+ } catch (Exception e) {
+ logger.error("Exception" + e);
}
}
@Test
- public void testSaveVnfType(){
+ public void testSaveVnfType() {
jsonString = "{\"userid\":\"demo\",\"vnfTypeDictionaryData\":{\"description\":\"test\",\"vnftype\":\"Test\"}}";
- try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){
+ try (BufferedReader br = new BufferedReader(new StringReader(jsonString))) {
when(request.getReader()).thenReturn(br);
controller.saveVnfType(request, response);
- assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("vnfTypeDictionaryData"));
- }catch(Exception e){
- logger.error("Exception"+ e);
+ assertTrue(response.getContentAsString() != null
+ && response.getContentAsString().contains("vnfTypeDictionaryData"));
+ } catch (Exception e) {
+ logger.error("Exception" + e);
}
}
@Test
- public void testUpdateVnfType(){
- jsonString = "{\"userid\":\"demo\",\"vnfTypeDictionaryData\":{\"id\":1,\"description\":\"test\",\"vnftype\":\"Test\"}}";
- try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){
+ public void testUpdateVnfType() {
+ jsonString =
+ "{\"userid\":\"demo\",\"vnfTypeDictionaryData\":{\"id\":1,\"description\":\"test\",\"vnftype\":\"Test\"}}";
+ try (BufferedReader br = new BufferedReader(new StringReader(jsonString))) {
when(request.getReader()).thenReturn(br);
controller.saveVnfType(request, response);
- assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("vnfTypeDictionaryData"));
- }catch(Exception e){
- logger.error("Exception"+ e);
+ assertTrue(response.getContentAsString() != null
+ && response.getContentAsString().contains("vnfTypeDictionaryData"));
+ } catch (Exception e) {
+ logger.error("Exception" + e);
}
}
@Test
- public void testRemoveVnfType(){
+ public void testRemoveVnfType() {
jsonString = "{\"userid\":\"demo\",\"data\":{\"id\":1,\"description\":\"test\",\"vnftype\":\"Test\"}}";
- try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){
+ try (BufferedReader br = new BufferedReader(new StringReader(jsonString))) {
when(request.getReader()).thenReturn(br);
controller.removeVnfType(request, response);
- assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("vnfTypeDictionaryData"));
- }catch(Exception e){
- logger.error("Exception"+ e);
+ assertTrue(response.getContentAsString() != null
+ && response.getContentAsString().contains("vnfTypeDictionaryData"));
+ } catch (Exception e) {
+ logger.error("Exception" + e);
}
}
@Test
- public void testSavePEPOptions(){
- jsonString = "{\"pepOptionsDictionaryData\":{\"attributes\":[{\"$$hashKey\":\"object:257\",\"id\":\"choice1\",\"number\":\"12\",\"option\":\"test\"}],\"description\":\"test\",\"pepName\":\"Test\"},\"userid\":\"demo\"}";
- try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){
+ public void testSavePEPOptions() {
+ jsonString =
+ "{\"pepOptionsDictionaryData\":{\"attributes\":[{\"$$hashKey\":\"object:257\",\"id\":\"choice1\",\"number\":\"12\",\"option\":\"test\"}],\"description\":\"test\",\"pepName\":\"Test\"},\"userid\":\"demo\"}";
+ try (BufferedReader br = new BufferedReader(new StringReader(jsonString))) {
when(request.getReader()).thenReturn(br);
controller.savePEPOptions(request, response);
- assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("pepOptionsDictionaryDatas"));
- }catch(Exception e){
- logger.error("Exception"+ e);
+ assertTrue(response.getContentAsString() != null
+ && response.getContentAsString().contains("pepOptionsDictionaryDatas"));
+ } catch (Exception e) {
+ logger.error("Exception" + e);
}
}
@Test
- public void testUpdatePEPOptions(){
- jsonString = "{\"pepOptionsDictionaryData\":{\"attributes\":[{\"$$hashKey\":\"object:257\",\"id\":\"choice1\",\"number\":\"12\",\"option\":\"test\"}],\"description\":\"test\",\"pepName\":\"Test\",\"id\":1},\"userid\":\"demo\"}";
- try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){
+ public void testUpdatePEPOptions() {
+ jsonString =
+ "{\"pepOptionsDictionaryData\":{\"attributes\":[{\"$$hashKey\":\"object:257\",\"id\":\"choice1\",\"number\":\"12\",\"option\":\"test\"}],\"description\":\"test\",\"pepName\":\"Test\",\"id\":1},\"userid\":\"demo\"}";
+ try (BufferedReader br = new BufferedReader(new StringReader(jsonString))) {
when(request.getReader()).thenReturn(br);
controller.savePEPOptions(request, response);
- assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("pepOptionsDictionaryDatas"));
- }catch(Exception e){
- logger.error("Exception"+ e);
+ assertTrue(response.getContentAsString() != null
+ && response.getContentAsString().contains("pepOptionsDictionaryDatas"));
+ } catch (Exception e) {
+ logger.error("Exception" + e);
}
}
@Test
- public void testRemovePEPOptions(){
- jsonString = "{\"data\":{\"attributes\":[{\"$$hashKey\":\"object:257\",\"id\":\"choice1\",\"number\":\"12\",\"option\":\"test\"}],\"description\":\"test\",\"pepName\":\"Test\"},\"userid\":\"demo\"}";
- try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){
+ public void testRemovePEPOptions() {
+ jsonString =
+ "{\"data\":{\"attributes\":[{\"$$hashKey\":\"object:257\",\"id\":\"choice1\",\"number\":\"12\",\"option\":\"test\"}],\"description\":\"test\",\"pepName\":\"Test\"},\"userid\":\"demo\"}";
+ try (BufferedReader br = new BufferedReader(new StringReader(jsonString))) {
when(request.getReader()).thenReturn(br);
controller.removePEPOptions(request, response);
- assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("pepOptionsDictionaryDatas"));
- }catch(Exception e){
- logger.error("Exception"+ e);
+ assertTrue(response.getContentAsString() != null
+ && response.getContentAsString().contains("pepOptionsDictionaryDatas"));
+ } catch (Exception e) {
+ logger.error("Exception" + e);
}
}
@Test
- public void testSaveServiceType(){
- jsonString = "{\"userid\":\"demo\",\"closedLoopServiceDictionaryData\":{\"description\":\"test\",\"serviceName\":\"Test\",\"id\":1}}";
- try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){
+ public void testSaveServiceType() {
+ jsonString =
+ "{\"userid\":\"demo\",\"closedLoopServiceDictionaryData\":{\"description\":\"test\",\"serviceName\":\"Test\",\"id\":1}}";
+ try (BufferedReader br = new BufferedReader(new StringReader(jsonString))) {
when(request.getReader()).thenReturn(br);
controller.saveServiceType(request, response);
- assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("closedLoopServiceDictionaryData"));
- }catch(Exception e){
- logger.error("Exception"+ e);
+ assertTrue(response.getContentAsString() != null
+ && response.getContentAsString().contains("closedLoopServiceDictionaryData"));
+ } catch (Exception e) {
+ logger.error("Exception" + e);
}
}
@Test
- public void testUpdateServiceType(){
- jsonString = "{\"userid\":\"demo\",\"closedLoopServiceDictionaryData\":{\"id\":1,\"description\":\"test\",\"serviceName\":\"Test\"}}";
- try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){
+ public void testUpdateServiceType() {
+ jsonString =
+ "{\"userid\":\"demo\",\"closedLoopServiceDictionaryData\":{\"id\":1,\"description\":\"test\",\"serviceName\":\"Test\"}}";
+ try (BufferedReader br = new BufferedReader(new StringReader(jsonString))) {
when(request.getReader()).thenReturn(br);
controller.saveServiceType(request, response);
- assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("closedLoopServiceDictionaryData"));
- }catch(Exception e){
- logger.error("Exception"+ e);
+ assertTrue(response.getContentAsString() != null
+ && response.getContentAsString().contains("closedLoopServiceDictionaryData"));
+ } catch (Exception e) {
+ logger.error("Exception" + e);
}
}
@Test
- public void testRemoveServiceType(){
+ public void testRemoveServiceType() {
jsonString = "{\"userid\":\"demo\",\"data\":{\"id\":1,\"description\":\"test\",\"serviceName\":\"Test\"}}";
- try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){
+ try (BufferedReader br = new BufferedReader(new StringReader(jsonString))) {
when(request.getReader()).thenReturn(br);
controller.removeServiceType(request, response);
- assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("closedLoopServiceDictionaryData"));
- }catch(Exception e){
- logger.error("Exception"+ e);
+ assertTrue(response.getContentAsString() != null
+ && response.getContentAsString().contains("closedLoopServiceDictionaryData"));
+ } catch (Exception e) {
+ logger.error("Exception" + e);
}
}
@Test
- public void testSaveSiteType(){
- jsonString = "{\"userid\":\"demo\",\"closedLoopSiteDictionaryData\":{\"description\":\"test\",\"siteName\":\"Test\"}}";
- try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){
+ public void testSaveSiteType() {
+ jsonString =
+ "{\"userid\":\"demo\",\"closedLoopSiteDictionaryData\":{\"description\":\"test\",\"siteName\":\"Test\"}}";
+ try (BufferedReader br = new BufferedReader(new StringReader(jsonString))) {
when(request.getReader()).thenReturn(br);
controller.saveSiteType(request, response);
- assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("closedLoopSiteDictionaryDatas"));
- }catch(Exception e){
- logger.error("Exception"+ e);
+ assertTrue(response.getContentAsString() != null
+ && response.getContentAsString().contains("closedLoopSiteDictionaryDatas"));
+ } catch (Exception e) {
+ logger.error("Exception" + e);
}
}
@Test
- public void testUpdateSiteType(){
- jsonString = "{\"userid\":\"demo\",\"closedLoopSiteDictionaryData\":{\"id\":1,\"description\":\"test\",\"siteName\":\"Test\"}}";
- try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){
+ public void testUpdateSiteType() {
+ jsonString =
+ "{\"userid\":\"demo\",\"closedLoopSiteDictionaryData\":{\"id\":1,\"description\":\"test\",\"siteName\":\"Test\"}}";
+ try (BufferedReader br = new BufferedReader(new StringReader(jsonString))) {
when(request.getReader()).thenReturn(br);
controller.saveSiteType(request, response);
- assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("closedLoopSiteDictionaryDatas"));
- }catch(Exception e){
- logger.error("Exception"+ e);
+ assertTrue(response.getContentAsString() != null
+ && response.getContentAsString().contains("closedLoopSiteDictionaryDatas"));
+ } catch (Exception e) {
+ logger.error("Exception" + e);
}
}
@Test
- public void testRemoveSiteType(){
+ public void testRemoveSiteType() {
jsonString = "{\"userid\":\"demo\",\"data\":{\"id\":1,\"description\":\"test\",\"siteName\":\"Test\"}}";
- try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){
+ try (BufferedReader br = new BufferedReader(new StringReader(jsonString))) {
when(request.getReader()).thenReturn(br);
controller.removeSiteType(request, response);
- assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("closedLoopSiteDictionaryDatas"));
- }catch(Exception e){
- logger.error("Exception"+ e);
+ assertTrue(response.getContentAsString() != null
+ && response.getContentAsString().contains("closedLoopSiteDictionaryDatas"));
+ } catch (Exception e) {
+ logger.error("Exception" + e);
}
}
@Test
- public void testSaveVarbind(){
- jsonString = "{\"userid\":\"demo\",\"varbindDictionaryData\":{\"description\":\"test\",\"varbindName\":\"Test\"}}";
- try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){
+ public void testSaveVarbind() {
+ jsonString =
+ "{\"userid\":\"demo\",\"varbindDictionaryData\":{\"description\":\"test\",\"varbindName\":\"Test\"}}";
+ try (BufferedReader br = new BufferedReader(new StringReader(jsonString))) {
when(request.getReader()).thenReturn(br);
controller.saveVarbind(request, response);
- assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("varbindDictionaryDatas"));
- }catch(Exception e){
- logger.error("Exception"+ e);
+ assertTrue(response.getContentAsString() != null
+ && response.getContentAsString().contains("varbindDictionaryDatas"));
+ } catch (Exception e) {
+ logger.error("Exception" + e);
}
}
@Test
- public void testUpdateVarbind(){
- jsonString = "{\"userid\":\"demo\",\"varbindDictionaryData\":{\"id\":1,\"description\":\"test\",\"varbindName\":\"Test\"}}";
- try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){
+ public void testUpdateVarbind() {
+ jsonString =
+ "{\"userid\":\"demo\",\"varbindDictionaryData\":{\"id\":1,\"description\":\"test\",\"varbindName\":\"Test\"}}";
+ try (BufferedReader br = new BufferedReader(new StringReader(jsonString))) {
when(request.getReader()).thenReturn(br);
controller.saveVarbind(request, response);
- assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("varbindDictionaryDatas"));
- }catch(Exception e){
- logger.error("Exception"+ e);
+ assertTrue(response.getContentAsString() != null
+ && response.getContentAsString().contains("varbindDictionaryDatas"));
+ } catch (Exception e) {
+ logger.error("Exception" + e);
}
}
@Test
- public void testRemoveVarbind(){
+ public void testRemoveVarbind() {
jsonString = "{\"userid\":\"demo\",\"data\":{\"id\":1,\"description\":\"test\",\"varbindName\":\"Test\"}}";
- try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){
+ try (BufferedReader br = new BufferedReader(new StringReader(jsonString))) {
when(request.getReader()).thenReturn(br);
controller.removeVarbind(request, response);
- assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("varbindDictionaryDatas"));
- }catch(Exception e){
- logger.error("Exception"+ e);
+ assertTrue(response.getContentAsString() != null
+ && response.getContentAsString().contains("varbindDictionaryDatas"));
+ } catch (Exception e) {
+ logger.error("Exception" + e);
}
}
}
diff --git a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/controller/DecisionPolicyDictionaryControllerTest.java b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/controller/DecisionPolicyDictionaryControllerTest.java
index 1334f96a0..30d6d52bc 100644
--- a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/controller/DecisionPolicyDictionaryControllerTest.java
+++ b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/controller/DecisionPolicyDictionaryControllerTest.java
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP-PAP-REST
* ================================================================================
- * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Modifications Copyright (C) 2019 Samsung
* ================================================================================
@@ -19,16 +19,19 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.policy.pap.xacml.rest.controller;
import static org.junit.Assert.*;
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 javax.servlet.http.HttpServletRequest;
-import org.junit.After;
+
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mockito;
@@ -39,8 +42,7 @@ import org.onap.policy.rest.dao.CommonClassDao;
import org.springframework.mock.web.MockHttpServletResponse;
public class DecisionPolicyDictionaryControllerTest {
- private static Logger logger =
- FlexLogger.getLogger(DecisionPolicyDictionaryControllerTest.class);
+ private static Logger logger = FlexLogger.getLogger(DecisionPolicyDictionaryControllerTest.class);
private static CommonClassDao commonClassDao;
private String jsonString = null;
private HttpServletRequest request = null;
@@ -52,19 +54,18 @@ public class DecisionPolicyDictionaryControllerTest {
commonClassDao = Mockito.mock(CommonClassDao.class);
HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
- 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\"}}";
+ 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\"}}";
BufferedReader br = new BufferedReader(new StringReader(jsonString));
@@ -78,9 +79,6 @@ public class DecisionPolicyDictionaryControllerTest {
logger.info("setUp: exit");
}
- @After
- public void tearDown() throws Exception {}
-
@Test
public void testGetSettingsDictionaryByNameEntityData() {
logger.info("testGetSettingsDictionaryByNameEntityData: Entering");
@@ -235,10 +233,9 @@ public class DecisionPolicyDictionaryControllerTest {
try {
// mock the getReader() call
- jsonString =
- "{\"rainyDayDictionaryData\":{\"bbid\":\"BB2\",\"workstep\":\"1\",\"userDataTypeValues\""
- + ":[{\"$$hashKey\":\"object:233\",\"treatment\":\"test1\"},{\"$$hashKey\":\"object:239\","
- + "\"treatment\":\"test2\"}]},\"userid\":\"mm117s\"}";
+ jsonString = "{\"rainyDayDictionaryData\":{\"bbid\":\"BB2\",\"workstep\":\"1\",\"userDataTypeValues\""
+ + ":[{\"$$hashKey\":\"object:233\",\"treatment\":\"test1\"},{\"$$hashKey\":\"object:239\","
+ + "\"treatment\":\"test2\"}]},\"userid\":\"mm117s\"}";
BufferedReader br = new BufferedReader(new StringReader(jsonString));
when(request.getReader()).thenReturn(br);
diff --git a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/controller/DescriptiveDictionaryControllerTest.java b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/controller/DescriptiveDictionaryControllerTest.java
index 0950b1cfd..f12299334 100644
--- a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/controller/DescriptiveDictionaryControllerTest.java
+++ b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/controller/DescriptiveDictionaryControllerTest.java
@@ -2,14 +2,14 @@
* ============LICENSE_START=======================================================
* ONAP-PAP-REST
* ================================================================================
- * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2018-2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -17,6 +17,7 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.policy.pap.xacml.rest.controller;
import static org.junit.Assert.assertTrue;
@@ -53,7 +54,7 @@ public class DescriptiveDictionaryControllerTest {
private DescriptiveDictionaryController controller = null;
private MockHttpServletResponse response = null;
private UserInfo userInfo;
- private List<String> data;
+ private List<String> data;
@Before
public void setUp() throws Exception {
@@ -74,15 +75,15 @@ public class DescriptiveDictionaryControllerTest {
controller.setCommonClassDao(commonClassDao);
request = Mockito.mock(HttpServletRequest.class);
- response = new MockHttpServletResponse();
+ response = new MockHttpServletResponse();
new DictionaryUtils(commonClassDao);
DictionaryUtils.setDictionaryUtils(new DictionaryUtils());
mock(DictionaryUtils.class);
logger.info("setUp: exit");
}
- public List<Object> testDescriptiveScope(){
- List<Object> objectData = new ArrayList<>();
+ public List<Object> testDescriptiveScope() {
+ List<Object> objectData = new ArrayList<>();
DescriptiveScope data = new DescriptiveScope();
data.setId(1);
@@ -94,75 +95,89 @@ public class DescriptiveDictionaryControllerTest {
data.setSearch("Test");
assertTrue("Test".equals(data.getSearch()));
data.setCreatedDate(new Date());
- assertTrue(data.getCreatedDate()!= null);
+ assertTrue(data.getCreatedDate() != null);
data.setModifiedDate(new Date());
- assertTrue(data.getModifiedDate()!= null);
+ assertTrue(data.getModifiedDate() != null);
data.setUserCreatedBy(userInfo);
- assertTrue(data.getUserCreatedBy()!= null);
+ assertTrue(data.getUserCreatedBy() != null);
data.setUserModifiedBy(userInfo);
- assertTrue(data.getUserModifiedBy()!= null);
+ assertTrue(data.getUserModifiedBy() != null);
objectData.add(data);
return objectData;
}
@Test
- public void testGetDescriptiveDictionaryByNameEntityData(){
+ public void testGetDescriptiveDictionaryByNameEntityData() {
when(commonClassDao.getDataByColumn(DescriptiveScope.class, "descriptiveScopeName")).thenReturn(data);
controller.getDescriptiveDictionaryByNameEntityData(response);
try {
- assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("descriptiveScopeDictionaryDatas"));
+ assertTrue(response.getContentAsString() != null
+ && response.getContentAsString().contains("descriptiveScopeDictionaryDatas"));
} catch (Exception e) {
fail();
- logger.error(e.getMessage(),e);
+ logger.error(e.getMessage(), e);
}
}
@Test
- public void testGetDescriptiveDictionaryEntityData(){
+ public void testGetDescriptiveDictionaryEntityData() {
when(commonClassDao.getData(DescriptiveScope.class)).thenReturn(testDescriptiveScope());
controller.getDescriptiveDictionaryEntityData(response);
try {
- assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("descriptiveScopeDictionaryDatas"));
+ assertTrue(response.getContentAsString() != null
+ && response.getContentAsString().contains("descriptiveScopeDictionaryDatas"));
} catch (Exception e) {
fail();
- logger.error(e.getMessage(),e);
+ logger.error(e.getMessage(), e);
}
}
@Test
- public void testSaveDescriptiveDictionary(){
- jsonString = "{\"descriptiveScopeDictionaryData\":{\"attributes\":[{\"$$hashKey\":\"object:257\",\"id\":\"choice1\",\"number\":\"12\",\"option\":\"test\"}],\"description\":\"test\",\"descriptiveScopeName\":\"Test\",\"search\":\"Test\"},\"userid\":\"demo\"}";
- try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){
+ public void testSaveDescriptiveDictionary() {
+ jsonString =
+ "{\"descriptiveScopeDictionaryData\":{\"attributes\":[{\"$$hashKey\":\"object:257\",\"id\":"
+ + "\"choice1\",\"number\":\"12\",\"option\":\"test\"}],\"description\":\"test\","
+ + "\"descriptiveScopeName\":\"Test\",\"search\":\"Test\"},\"userid\":\"demo\"}";
+ try (BufferedReader br = new BufferedReader(new StringReader(jsonString))) {
when(request.getReader()).thenReturn(br);
controller.saveDescriptiveDictionary(request, response);
- assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("descriptiveScopeDictionaryDatas"));
- }catch(Exception e){
- logger.error("Exception"+ e);
+ assertTrue(response.getContentAsString() != null
+ && response.getContentAsString().contains("descriptiveScopeDictionaryDatas"));
+ } catch (Exception e) {
+ logger.error("Exception" + e);
}
}
@Test
- public void testUpdateDescriptiveDictionary(){
- jsonString = "{\"descriptiveScopeDictionaryData\":{\"attributes\":[{\"$$hashKey\":\"object:257\",\"id\":\"choice1\",\"number\":\"12\",\"option\":\"test\"}],\"description\":\"test\",\"descriptiveScopeName\":\"Test\",\"id\":1,\"search\":\"Test\"},\"userid\":\"demo\"}";
- try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){
+ public void testUpdateDescriptiveDictionary() {
+ jsonString =
+ "{\"descriptiveScopeDictionaryData\":{\"attributes\":[{\"$$hashKey\":\"object:257\",\"id\":"
+ + "\"choice1\",\"number\":\"12\",\"option\":\"test\"}],\"description\":\"test\","
+ + "\"descriptiveScopeName\":\"Test\",\"id\":1,\"search\":\"Test\"},\"userid\":\"demo\"}";
+ try (BufferedReader br = new BufferedReader(new StringReader(jsonString))) {
when(request.getReader()).thenReturn(br);
controller.saveDescriptiveDictionary(request, response);
- assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("descriptiveScopeDictionaryDatas"));
- }catch(Exception e){
- logger.error("Exception"+ e);
+ assertTrue(response.getContentAsString() != null
+ && response.getContentAsString().contains("descriptiveScopeDictionaryDatas"));
+ } catch (Exception e) {
+ logger.error("Exception" + e);
}
}
@Test
- public void testRemoveDescriptiveDictionary(){
- jsonString = "{\"data\":{\"attributes\":[{\"$$hashKey\":\"object:257\",\"id\":\"choice1\",\"number\":\"12\",\"option\":\"test\"}],\"description\":\"test\",\"descriptiveScopeName\":\"Test\",\"id\":1,\"search\":\"Test\"},\"userid\":\"demo\"}";
- try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){
+ public void testRemoveDescriptiveDictionary() {
+ jsonString =
+ "{\"data\":{\"attributes\":[{\"$$hashKey\":\"object:257\",\"id\":\"choice1\",\"number\":\"12\","
+ + "\"option\":\"test\"}],\"description\":\"test\",\"descriptiveScopeName\":\"Test\",\"id\":1,"
+ + "\"search\":\"Test\"},\"userid\":\"demo\"}";
+ try (BufferedReader br = new BufferedReader(new StringReader(jsonString))) {
when(request.getReader()).thenReturn(br);
controller.removeDescriptiveDictionary(request, response);
- assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("descriptiveScopeDictionaryDatas"));
- }catch(Exception e){
- logger.error("Exception"+ e);
+ assertTrue(response.getContentAsString() != null
+ && response.getContentAsString().contains("descriptiveScopeDictionaryDatas"));
+ } catch (Exception e) {
+ logger.error("Exception" + e);
}
}
-} \ No newline at end of file
+}
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
index 89be75f52..52b79b88f 100644
--- 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
@@ -2,14 +2,14 @@
* ============LICENSE_START=======================================================
* ONAP-PAP-REST
* ================================================================================
- * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -18,7 +18,6 @@
* ============LICENSE_END=========================================================
*/
-
package org.onap.policy.pap.xacml.rest.controller;
import static org.junit.Assert.assertTrue;
@@ -70,12 +69,12 @@ public class DictionaryControllerTest {
commonClassDao = Mockito.mock(CommonClassDao.class);
MicroServiceModels testData = new MicroServiceModels();
- testData.setVersion("1707.4.1.2-Junit");
+ testData.setVersion("1707.4.1.2-Junit");
- //--- mock the getDataByColumn() call
- List<String> microList = new ArrayList<String>();
+ // --- mock the getDataByColumn() call
+ List<String> microList = new ArrayList<String>();
microList.add("123");
- List<Object> listId = new ArrayList<Object>();
+ List<Object> listId = new ArrayList<Object>();
when(commonClassDao.getDataByColumn(Attribute.class, "xacmlId")).thenReturn(microList);
List<Object> object = new ArrayList<>();
object.add(new Category());
@@ -83,9 +82,9 @@ public class DictionaryControllerTest {
PolicyEditorScopes editorScope = new PolicyEditorScopes();
doNothing().when(commonClassDao).save(editorScope);
doNothing().when(commonClassDao).update(editorScope);
-
+
when(commonClassDao.getData(Attribute.class)).thenReturn(listId);
-
+
request = mock(HttpServletRequest.class);
controller = new DictionaryController(commonClassDao);
new DictionaryUtils(commonClassDao);
@@ -98,12 +97,13 @@ public class DictionaryControllerTest {
public void testGetAttributeDictionaryEntityDatabyAttributeName() {
logger.info("testGetAttributeDictionaryEntityDatabyAttributeName: Entering");
- MockHttpServletResponse response = new MockHttpServletResponse();
+ MockHttpServletResponse response = new MockHttpServletResponse();
controller.getAttributeDictionaryEntityDatabyAttributeName(response);
try {
- assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("attributeDictionaryDatas"));
+ assertTrue(response.getContentAsString() != null
+ && response.getContentAsString().contains("attributeDictionaryDatas"));
logger.info("response.getContentAsString(): " + response.getContentAsString());
} catch (UnsupportedEncodingException e) {
fail("Exception: " + e);
@@ -116,12 +116,13 @@ public class DictionaryControllerTest {
public void testGetAttributeDictionaryEntityData() {
logger.info("testGetAttributeDictionaryEntityData: Entering");
- MockHttpServletResponse response = new MockHttpServletResponse();
+ MockHttpServletResponse response = new MockHttpServletResponse();
controller.getAttributeDictionaryEntityData(response);
try {
- assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("attributeDictionaryDatas"));
+ assertTrue(response.getContentAsString() != null
+ && response.getContentAsString().contains("attributeDictionaryDatas"));
logger.info("response.getContentAsString(): " + response.getContentAsString());
} catch (UnsupportedEncodingException e) {
fail("Exception: " + e);
@@ -134,16 +135,22 @@ public class DictionaryControllerTest {
public void testSaveAttributeDictionary() {
logger.info("testSaveAttributeDictionary: Entering");
- MockHttpServletResponse response = new MockHttpServletResponse();
+ MockHttpServletResponse response = new MockHttpServletResponse();
request = mock(HttpServletRequest.class);
-
+
try {
- jsonString = "{\"attributeDictionaryData\":{\"datatypeBean\":{\"shortName\":\"string\"},\"description\":\"Qwerty\",\"priority\":\"High\",\"userDataTypeValues\":[{\"$$hashKey\":\"object:641\",\"attributeValues\":\"test\",\"id\":\"choice1\"},{\"$$hashKey\":\"object:646\",\"attributeValues\":\"test\",\"id\":\"choice2\"}],\"xacmlId\":\"Qwerty\"},\"userid\":\"demo\"}";
+ jsonString =
+ "{\"attributeDictionaryData\":{\"datatypeBean\":{\"shortName\":\"string\"},\"description\":"
+ + "\"Qwerty\",\"priority\":\"High\",\"userDataTypeValues\":[{\"$$hashKey\":"
+ + "\"object:641\",\"attributeValues\":\"test\",\"id\":\"choice1\"},{\"$$hashKey\":"
+ + "\"object:646\",\"attributeValues\":\"test\",\"id\":\"choice2\"}],\"xacmlId\":"
+ + "\"Qwerty\"},\"userid\":\"demo\"}";
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"));
+ assertTrue(response.getContentAsString() != null
+ && response.getContentAsString().contains("attributeDictionaryDatas"));
} catch (Exception e) {
fail("Exception: " + e);
@@ -156,16 +163,17 @@ public class DictionaryControllerTest {
public void testRemoveAttributeDictionary() {
logger.info("testRemoveAttributeDictionary: Entering");
- MockHttpServletResponse response = new MockHttpServletResponse();
+ MockHttpServletResponse response = new MockHttpServletResponse();
request = mock(HttpServletRequest.class);
try {
jsonString = "{\"userid\":\"demo\",\"data\":{\"id\":1,\"description\":\"test\",\"xacmlId\":\"Test\"}}";
- BufferedReader br = new BufferedReader(new StringReader(jsonString));
+ 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"));
+ assertTrue(response.getContentAsString() != null
+ && response.getContentAsString().contains("attributeDictionaryDatas"));
} catch (Exception e) {
fail("Exception: " + e);
@@ -178,12 +186,13 @@ public class DictionaryControllerTest {
public void testGetOnapNameDictionaryByNameEntityData() {
logger.info("testGetOnapNameDictionaryByNameEntityData: Entering");
- MockHttpServletResponse response = new MockHttpServletResponse();
+ MockHttpServletResponse response = new MockHttpServletResponse();
controller.getOnapNameDictionaryByNameEntityData(response);
try {
- assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("onapNameDictionaryDatas"));
+ assertTrue(response.getContentAsString() != null
+ && response.getContentAsString().contains("onapNameDictionaryDatas"));
logger.info("response.getContentAsString(): " + response.getContentAsString());
} catch (UnsupportedEncodingException e) {
fail("Exception: " + e);
@@ -196,12 +205,13 @@ public class DictionaryControllerTest {
public void testGetOnapNameDictionaryEntityData() {
logger.info("testGetOnapNameDictionaryEntityData: Entering");
- MockHttpServletResponse response = new MockHttpServletResponse();
+ MockHttpServletResponse response = new MockHttpServletResponse();
controller.getOnapNameDictionaryEntityData(response);
try {
- assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("onapNameDictionaryDatas"));
+ assertTrue(response.getContentAsString() != null
+ && response.getContentAsString().contains("onapNameDictionaryDatas"));
logger.info("response.getContentAsString(): " + response.getContentAsString());
} catch (UnsupportedEncodingException e) {
fail("Exception: " + e);
@@ -215,16 +225,18 @@ public class DictionaryControllerTest {
logger.info("testSaveOnapDictionary: Entering");
- MockHttpServletResponse response = new MockHttpServletResponse();
+ MockHttpServletResponse response = new MockHttpServletResponse();
request = mock(HttpServletRequest.class);
-
+
try {
- jsonString = "{\"userid\":\"demo\",\"onapNameDictionaryData\":{\"description\":\"test\",\"onapName\":\"Test\"}}";
+ jsonString =
+ "{\"userid\":\"demo\",\"onapNameDictionaryData\":{\"description\":\"test\",\"onapName\":\"Test\"}}";
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"));
+ assertTrue(response.getContentAsString() != null
+ && response.getContentAsString().contains("onapNameDictionaryDatas"));
} catch (Exception e) {
fail("Exception: " + e);
@@ -237,16 +249,17 @@ public class DictionaryControllerTest {
public void testRemoveOnapDictionary() {
logger.info("testRemoveOnapDictionary: Entering");
- MockHttpServletResponse response = new MockHttpServletResponse();
+ MockHttpServletResponse response = new MockHttpServletResponse();
request = mock(HttpServletRequest.class);
try {
jsonString = "{\"userid\":\"demo\",\"data\":{\"id\":1,\"description\":\"test\",\"onapName\":\"Test\"}}";
- BufferedReader br = new BufferedReader(new StringReader(jsonString));
+ 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"));
+ assertTrue(response.getContentAsString() != null
+ && response.getContentAsString().contains("onapNameDictionaryDatas"));
} catch (Exception e) {
fail("Exception: " + e);
diff --git a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/controller/DictionaryImportControllerTest.java b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/controller/DictionaryImportControllerTest.java
index 7ab1b170e..ee4dff803 100644
--- a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/controller/DictionaryImportControllerTest.java
+++ b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/controller/DictionaryImportControllerTest.java
@@ -2,14 +2,14 @@
* ============LICENSE_START=======================================================
* ONAP-PAP-REST
* ================================================================================
- * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2018-2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -17,6 +17,7 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.policy.pap.xacml.rest.controller;
import static org.junit.Assert.assertTrue;
@@ -42,7 +43,7 @@ import org.onap.policy.common.logging.flexlogger.Logger;
import org.onap.policy.rest.dao.CommonClassDao;
import org.springframework.mock.web.MockHttpServletResponse;
-public class DictionaryImportControllerTest extends Mockito{
+public class DictionaryImportControllerTest extends Mockito {
private static Logger logger = FlexLogger.getLogger(DictionaryImportController.class);
@@ -59,20 +60,20 @@ public class DictionaryImportControllerTest extends Mockito{
controller = new DictionaryImportController();
new DictionaryImportController(commonClassDao);
request = Mockito.mock(HttpServletRequest.class);
- response = new MockHttpServletResponse();
+ response = new MockHttpServletResponse();
}
@Test
- public void testIsValidDictionaryName(){
+ public void testIsValidDictionaryName() {
DictionaryImportController cotroller = new DictionaryImportController();
- //test invalid name
+ // test invalid name
assertTrue(!cotroller.isValidDictionaryName("wrong-name"));
- //test valid name
+ // test valid name
assertTrue(cotroller.isValidDictionaryName("ActionList"));
}
@Test
- public void testImportDictionaryData() throws ServletException, IOException{
+ public void testImportDictionaryData() throws ServletException, IOException {
List<String> fileNames = new ArrayList<>();
fileNames.add("Attribute.csv");
fileNames.add("ActionPolicyDictionary.csv");
@@ -95,13 +96,13 @@ public class DictionaryImportControllerTest extends Mockito{
fileNames.add("SearchCriteria.csv");
fileNames.add("VNFType.csv");
fileNames.add("VSCLAction.csv");
- fileNames.add("PEPOptions.csv");
+ fileNames.add("PepOptions.csv");
fileNames.add("Settings.csv");
fileNames.add("Zone.csv");
fileNames.add("ActionList.csv");
- for(int i =0; i < fileNames.size(); i++){
- File file = new File("src/test/resources/dictionaryImport/"+fileNames.get(i));
- try(FileInputStream targetStream = new FileInputStream(file)){
+ for (int i = 0; i < fileNames.size(); i++) {
+ File file = new File("src/test/resources/dictionaryImport/" + fileNames.get(i));
+ try (FileInputStream targetStream = new FileInputStream(file)) {
PushPolicyControllerTest pushController = new PushPolicyControllerTest();
when(request.getInputStream()).thenReturn(pushController.getInputStream(getBytes(targetStream)));
when(request.getParameter("userId")).thenReturn("demo");
diff --git a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/controller/FirewallDictionaryControllerTest.java b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/controller/FirewallDictionaryControllerTest.java
index 45d8466b6..3359a7aed 100644
--- a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/controller/FirewallDictionaryControllerTest.java
+++ b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/controller/FirewallDictionaryControllerTest.java
@@ -2,14 +2,14 @@
* ============LICENSE_START=======================================================
* ONAP-PAP-REST
* ================================================================================
- * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2018-2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -17,6 +17,7 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.policy.pap.xacml.rest.controller;
import static org.junit.Assert.assertTrue;
@@ -46,8 +47,8 @@ import org.onap.policy.rest.adapter.Term;
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.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.PortList;
@@ -117,7 +118,8 @@ public class FirewallDictionaryControllerTest {
@Test
public void testGetProtocolListDictionaryEntityDataByName() {
- test_WithGetDataByColumn(ProtocolList.class, "protocolListDictionaryDatas", "protocolName",
+ test_WithGetDataByColumn(ProtocolList.class,
+ "protocolListDictionaryDatas", "protocolName",
() -> controller.getProtocolListDictionaryEntityDataByName(response));
}
@@ -195,7 +197,8 @@ public class FirewallDictionaryControllerTest {
@Test
public void testGetZoneDictionaryEntityData() {
- test_WithGetData(Zone.class, "zoneDictionaryDatas", () -> controller.getZoneDictionaryEntityData(response));
+ test_WithGetData(Zone.class, "zoneDictionaryDatas", () ->
+ controller.getZoneDictionaryEntityData(response));
}
@Test
@@ -212,7 +215,8 @@ public class FirewallDictionaryControllerTest {
@Test
public void testGetFWDictListDictionaryEntityDataByName() {
- test_WithGetDataByColumn(FirewallDictionaryList.class, "fwDictListDictionaryDatas", "parentItemName",
+ test_WithGetDataByColumn(FirewallDictionaryList.class,
+ "fwDictListDictionaryDatas", "parentItemName",
() -> controller.getFWDictListDictionaryEntityDataByName(response));
}
@@ -224,37 +228,41 @@ public class FirewallDictionaryControllerTest {
@Test
public void testGetTagPickerNameEntityDataByName() {
- test_WithGetDataByColumn(FWTagPicker.class, "fwTagPickerDictionaryDatas", "tagPickerName",
+ test_WithGetDataByColumn(FwTagPicker.class, "fwTagPickerDictionaryDatas", "tagPickerName",
() -> controller.getTagPickerNameEntityDataByName(response));
}
@Test
public void testGetTagPickerDictionaryEntityData() {
- test_WithGetData(FWTagPicker.class, "fwTagPickerDictionaryDatas",
+ test_WithGetData(FwTagPicker.class, "fwTagPickerDictionaryDatas",
() -> controller.getTagPickerDictionaryEntityData(response));
}
@Test
public void testGetTagNameEntityDataByName() {
- test_WithGetDataByColumn(FWTag.class, "fwTagDictionaryDatas", "fwTagName",
+ test_WithGetDataByColumn(FwTag.class, "fwTagDictionaryDatas", "fwTagName",
() -> controller.getTagNameEntityDataByName(response));
}
@Test
public void testGetTagDictionaryEntityData() {
- test_WithGetData(FWTag.class, "fwTagDictionaryDatas", () -> controller.getTagDictionaryEntityData(response));
+ test_WithGetData(FwTag.class, "fwTagDictionaryDatas", () -> controller.getTagDictionaryEntityData(response));
}
@Test
public void testSavePrefixListDictionary() {
- jsonString = "{\"userid\":\"demo\",\"prefixListDictionaryData\":{\"description\":\"test\",\"prefixListName\":\"Test\"}}";
+ jsonString =
+ "{\"userid\":\"demo\",\"prefixListDictionaryData\":"
+ + "{\"description\":\"test\",\"prefixListName\":\"Test\"}}";
testSave(PrefixList.class, "prefixListDictionaryDatas", "prefixListName",
() -> controller.savePrefixListDictionary(request, response));
}
@Test
public void testUpdatePrefixListDictionary() {
- jsonString = "{\"userid\":\"demo\",\"prefixListDictionaryData\":{\"id\":1,\"description\":\"test\",\"prefixListName\":\"Test\"}}";
+ jsonString =
+ "{\"userid\":\"demo\",\"prefixListDictionaryData\":{\"id\":1,\"description\":"
+ + "\"test\",\"prefixListName\":\"Test\"}}";
testUpdate(PrefixList.class, "prefixListDictionaryDatas", "prefixListName",
() -> controller.savePrefixListDictionary(request, response));
}
@@ -268,20 +276,25 @@ public class FirewallDictionaryControllerTest {
@Test
public void testValidatePrefixListDictionary() {
- jsonString = "{\"userid\":\"demo\",\"prefixListDictionaryData\":{\"id\":1,\"description\":\"test\",\"prefixListName\":\"Test\",\"prefixListValue\":\"10.10.10\"}}";
+ jsonString =
+ "{\"userid\":\"demo\",\"prefixListDictionaryData\":{\"id\":1,\"description\":"
+ + "\"test\",\"prefixListName\":\"Test\",\"prefixListValue\":\"10.10.10\"}}";
testValidate(PrefixList.class, "result", () -> controller.validatePrefixListDictionary(request, response));
}
@Test
public void testSavePortListDictionary() {
- jsonString = "{\"userid\":\"demo\",\"portListDictionaryData\":{\"description\":\"test\",\"portName\":\"Test\"}}";
+ jsonString =
+ "{\"userid\":\"demo\",\"portListDictionaryData\":{\"description\":\"test\",\"portName\":\"Test\"}}";
testSave(PortList.class, "portListDictionaryDatas", "portName",
() -> controller.savePortListDictionary(request, response));
}
@Test
public void testUpdatePortListDictionary() {
- jsonString = "{\"userid\":\"demo\",\"portListDictionaryData\":{\"id\":1,\"description\":\"test\",\"portName\":\"Test\"}}";
+ jsonString =
+ "{\"userid\":\"demo\",\"portListDictionaryData\":{\"id\":1,\"description\":"
+ + "\"test\",\"portName\":\"Test\"}}";
testUpdate(PortList.class, "portListDictionaryDatas", "portName",
() -> controller.savePortListDictionary(request, response));
}
@@ -295,14 +308,18 @@ public class FirewallDictionaryControllerTest {
@Test
public void testSaveProtocolListDictionary() {
- jsonString = "{\"userid\":\"demo\",\"protocolListDictionaryData\":{\"description\":\"test\",\"protocolName\":\"Test\"}}";
+ jsonString =
+ "{\"userid\":\"demo\",\"protocolListDictionaryData\":{\"description\":\"test\",\"protocolName\":"
+ + "\"Test\"}}";
testSave(ProtocolList.class, "protocolListDictionaryDatas", "protocolName",
() -> controller.saveProtocolListDictionary(request, response));
}
@Test
public void testUpdateProtocolListDictionary() {
- jsonString = "{\"userid\":\"demo\",\"protocolListDictionaryData\":{\"id\":1,\"description\":\"test\",\"protocolName\":\"Test\"}}";
+ jsonString =
+ "{\"userid\":\"demo\",\"protocolListDictionaryData\":{\"id\":1,\"description\":"
+ + "\"test\",\"protocolName\":\"Test\"}}";
testUpdate(ProtocolList.class, "protocolListDictionaryDatas", "protocolName",
() -> controller.saveProtocolListDictionary(request, response));
}
@@ -316,14 +333,20 @@ public class FirewallDictionaryControllerTest {
@Test
public void testSaveAddressGroupDictionary() {
- jsonString = "{\"addressGroupDictionaryData\":{\"attributes\":[{\"$$hashKey\":\"object:409\",\"id\":\"choice1\",\"option\":\"Test\"}],\"description\":\"test\",\"groupName\":\"Test\"},\"userid\":\"demo\"}";
+ jsonString =
+ "{\"addressGroupDictionaryData\":{\"attributes\":[{\"$$hashKey\":\"object:409\",\"id\":"
+ + "\"choice1\",\"option\":\"Test\"}],\"description\":\"test\",\"groupName\":"
+ + "\"Test\"},\"userid\":\"demo\"}";
testSave(AddressGroup.class, "addressGroupDictionaryDatas", "name", "Group_Test",
() -> controller.saveAddressGroupDictionary(request, response));
}
@Test
public void testUpdateAddressGroupDictionary() {
- jsonString = "{\"addressGroupDictionaryData\":{\"id\":1, \"attributes\":[{\"$$hashKey\":\"object:409\",\"id\":\"choice1\",\"option\":\"Test\"}],\"description\":\"test\",\"groupName\":\"Test\"},\"userid\":\"demo\"}";
+ jsonString =
+ "{\"addressGroupDictionaryData\":{\"id\":1, \"attributes\":[{\"$$hashKey\":\"object:409\",\"id\":"
+ + "\"choice1\",\"option\":\"Test\"}],\"description\":\"test\",\"groupName\":\"Test\"},\"userid\":"
+ + "\"demo\"}";
testUpdate(AddressGroup.class, "addressGroupDictionaryDatas", "name", "Group_Test",
() -> controller.saveAddressGroupDictionary(request, response));
}
@@ -337,14 +360,18 @@ public class FirewallDictionaryControllerTest {
@Test
public void testSaveActionListDictionary() {
- jsonString = "{\"userid\":\"demo\",\"actionListDictionaryData\":{\"description\":\"test\",\"actionName\":\"Test\"}}";
+ jsonString =
+ "{\"userid\":\"demo\",\"actionListDictionaryData\":{\"description\":\"test\",\"actionName\":"
+ + "\"Test\"}}";
testSave(ActionList.class, "actionListDictionaryDatas", "actionName",
() -> controller.saveActionListDictionary(request, response));
}
@Test
public void testUpdateActionListDictionary() {
- jsonString = "{\"userid\":\"demo\",\"actionListDictionaryData\":{\"id\":1,\"description\":\"test\",\"actionName\":\"Test\"}}";
+ jsonString =
+ "{\"userid\":\"demo\",\"actionListDictionaryData\":{\"id\":1,\"description\":\"test\",\"actionName\":"
+ + "\"Test\"}}";
testUpdate(ActionList.class, "actionListDictionaryDatas", "actionName",
() -> controller.saveActionListDictionary(request, response));
}
@@ -358,14 +385,18 @@ public class FirewallDictionaryControllerTest {
@Test
public void testSaveServiceGroupDictionary() {
- jsonString = "{\"serviceGroupDictionaryData\":{\"attributes\":[{\"$$hashKey\":\"object:657\",\"id\":\"choice1\",\"option\":\"Test\"}],\"groupName\":\"Test\"},\"userid\":\"demo\"}";
+ jsonString =
+ "{\"serviceGroupDictionaryData\":{\"attributes\":[{\"$$hashKey\":\"object:657\",\"id\":"
+ + "\"choice1\",\"option\":\"Test\"}],\"groupName\":\"Test\"},\"userid\":\"demo\"}";
testSave(GroupServiceList.class, "serviceGroupDictionaryDatas", "name", "Group_Test",
() -> controller.saveServiceGroupDictionary(request, response));
}
@Test
public void testUpdateServiceGroupDictionary() {
- jsonString = "{\"serviceGroupDictionaryData\":{\"id\":1, \"attributes\":[{\"$$hashKey\":\"object:657\",\"id\":\"choice1\",\"option\":\"Test\"}],\"groupName\":\"Test\"},\"userid\":\"demo\"}";
+ jsonString =
+ "{\"serviceGroupDictionaryData\":{\"id\":1, \"attributes\":[{\"$$hashKey\":\"object:657\",\"id\":"
+ + "\"choice1\",\"option\":\"Test\"}],\"groupName\":\"Test\"},\"userid\":\"demo\"}";
testUpdate(GroupServiceList.class, "serviceGroupDictionaryDatas", "name", "Group_Test",
() -> controller.saveServiceGroupDictionary(request, response));
}
@@ -379,14 +410,18 @@ public class FirewallDictionaryControllerTest {
@Test
public void testSaveSecurityZoneDictionary() {
- jsonString = "{\"userid\":\"demo\",\"securityZoneDictionaryData\":{\"description\":\"test\",\"zoneName\":\"Test\"}}";
+ jsonString =
+ "{\"userid\":\"demo\",\"securityZoneDictionaryData\":{\"description\":\"test\",\"zoneName\":"
+ + "\"Test\"}}";
testSave(SecurityZone.class, "securityZoneDictionaryDatas", "zoneName",
() -> controller.saveSecurityZoneDictionary(request, response));
}
@Test
public void testUpdateSecurityZoneDictionary() {
- jsonString = "{\"userid\":\"demo\",\"securityZoneDictionaryData\":{\"id\":1,\"description\":\"test\",\"zoneName\":\"Test\"}}";
+ jsonString =
+ "{\"userid\":\"demo\",\"securityZoneDictionaryData\":{\"id\":1,\"description\":\"test\",\"zoneName\":"
+ + "\"Test\"}}";
testUpdate(SecurityZone.class, "securityZoneDictionaryDatas", "zoneName",
() -> controller.saveSecurityZoneDictionary(request, response));
}
@@ -400,21 +435,33 @@ public class FirewallDictionaryControllerTest {
@Test
public void testSaveServiceListDictionary() {
- jsonString = "{\"serviceListDictionaryData\":{\"appProtocols\":[{\"$$hashKey\":\"object:560\",\"id\":\"choice1\",\"option\":\"Test\"}],\"serviceDescription\":\"test\",\"serviceName\":\"Test\",\"servicePorts\":\"1010\",\"transportProtocols\":[{\"$$hashKey\":\"object:555\",\"id\":\"choice1\",\"option\":\"Test\"}]},\"userid\":\"demo\"}";
+ jsonString =
+ "{\"serviceListDictionaryData\":{\"appProtocols\":[{\"$$hashKey\":\"object:560\",\"id\":"
+ + "\"choice1\",\"option\":\"Test\"}],\"serviceDescription\":\"test\",\"serviceName\":"
+ + "\"Test\",\"servicePorts\":\"1010\",\"transportProtocols\":[{\"$$hashKey\":\"object:555\",\"id\":"
+ + "\"choice1\",\"option\":\"Test\"}]},\"userid\":\"demo\"}";
testSave(ServiceList.class, "serviceListDictionaryDatas", "serviceName",
() -> controller.saveServiceListDictionary(request, response));
}
@Test
public void testUpdateServiceListDictionary() {
- jsonString = "{\"serviceListDictionaryData\":{\"appProtocols\":[{\"$$hashKey\":\"object:560\",\"id\":\"choice1\",\"option\":\"Test\"}],\"serviceDescription\":\"test\",\"id\":1,\"serviceName\":\"Test\",\"servicePorts\":\"1010\",\"transportProtocols\":[{\"$$hashKey\":\"object:555\",\"id\":\"choice1\",\"option\":\"Test\"}]},\"userid\":\"demo\"}";
+ jsonString =
+ "{\"serviceListDictionaryData\":{\"appProtocols\":[{\"$$hashKey\":\"object:560\",\"id\":"
+ + "\"choice1\",\"option\":\"Test\"}],\"serviceDescription\":\"test\",\"id\":1,\"serviceName\":"
+ + "\"Test\",\"servicePorts\":\"1010\",\"transportProtocols\":[{\"$$hashKey\":\"object:555\",\"id\":"
+ + "\"choice1\",\"option\":\"Test\"}]},\"userid\":\"demo\"}";
testUpdate(ServiceList.class, "serviceListDictionaryDatas", "serviceName",
() -> controller.saveServiceListDictionary(request, response));
}
@Test
public void testRemoveServiceListDictionary() {
- jsonString = "{\"data\":{\"appProtocols\":[{\"$$hashKey\":\"object:560\",\"id\":\"choice1\",\"option\":\"Test\"}],\"serviceDescription\":\"test\",\"id\":1,\"serviceName\":\"Test\",\"servicePorts\":\"1010\",\"transportProtocols\":[{\"$$hashKey\":\"object:555\",\"id\":\"choice1\",\"option\":\"Test\"}]},\"userid\":\"demo\"}";
+ jsonString =
+ "{\"data\":{\"appProtocols\":[{\"$$hashKey\":\"object:560\",\"id\":\"choice1\",\"option\":"
+ + "\"Test\"}],\"serviceDescription\":\"test\",\"id\":1,\"serviceName\":\"Test\",\"servicePorts\":"
+ + "\"1010\",\"transportProtocols\":[{\"$$hashKey\":\"object:555\",\"id\":\"choice1\",\"option\":"
+ + "\"Test\"}]},\"userid\":\"demo\"}";
testRemove(ServiceList.class, "serviceListDictionaryDatas",
() -> controller.removeServiceListDictionary(request, response));
}
@@ -422,12 +469,14 @@ public class FirewallDictionaryControllerTest {
@Test
public void testSaveZoneDictionary() {
jsonString = "{\"userid\":\"demo\",\"zoneDictionaryData\":{\"zoneValue\":\"test\",\"zoneName\":\"Test\"}}";
- testSave(Zone.class, "zoneDictionaryDatas", "zoneName", () -> controller.saveZoneDictionary(request, response));
+ testSave(Zone.class, "zoneDictionaryDatas", "zoneName", ()
+ -> controller.saveZoneDictionary(request, response));
}
@Test
public void testUpdateZoneDictionary() {
- jsonString = "{\"userid\":\"demo\",\"zoneDictionaryData\":{\"id\":1,\"zoneValue\":\"test\",\"zoneName\":\"Test\"}}";
+ jsonString =
+ "{\"userid\":\"demo\",\"zoneDictionaryData\":{\"id\":1,\"zoneValue\":\"test\",\"zoneName\":\"Test\"}}";
testUpdate(Zone.class, "zoneDictionaryDatas", "zoneName",
() -> controller.saveZoneDictionary(request, response));
}
@@ -440,14 +489,34 @@ public class FirewallDictionaryControllerTest {
@Test
public void testSaveTermListDictionary() {
- jsonString = "{\"termListDictionaryData\":{\"actionListDatas\":[{\"$$hashKey\":\"object:1220\",\"id\":\"choice1\",\"option\":\"Group_Test\"}],\"destinationListDatas\":[{\"$$hashKey\":\"object:1220\",\"id\":\"choice1\",\"option\":\"Group_Test\"}],\"destinationServiceDatas\":[{\"$$hashKey\":\"object:1230\",\"id\":\"choice1\",\"option\":\"Group_Test\"}],\"fromZoneDatas\":[{\"$$hashKey\":\"object:1245\",\"id\":\"choice1\",\"option\":\"Test\"}],\"sourceListDatas\":[{\"$$hashKey\":\"object:1215\",\"id\":\"choice1\",\"option\":\"Group_Test\"}],\"sourceServiceDatas\":[{\"$$hashKey\":\"object:1225\",\"id\":\"choice1\",\"option\":\"Group_Test\"}],\"termDescription\":\"test\",\"termName\":\"Test\",\"toZoneDatas\":[{\"$$hashKey\":\"object:1240\",\"id\":\"choice1\",\"option\":\"Test\"}]},\"userid\":\"demo\"}";
+ jsonString =
+ "{\"termListDictionaryData\":{\"actionListDatas\":[{\"$$hashKey\":\"object:1220\",\"id\":"
+ + "\"choice1\",\"option\":\"Group_Test\"}],\"destinationListDatas\":[{\"$$hashKey\":"
+ + "\"object:1220\",\"id\":\"choice1\",\"option\":\"Group_Test\"}],\"destinationServiceDatas\":"
+ + "[{\"$$hashKey\":\"object:1230\",\"id\":\"choice1\",\"option\":\"Group_Test\"}],\"fromZoneDatas\":"
+ + "[{\"$$hashKey\":\"object:1245\",\"id\":\"choice1\",\"option\":\"Test\"}],\"sourceListDatas\":"
+ + "[{\"$$hashKey\":\"object:1215\",\"id\":\"choice1\",\"option\":"
+ + "\"Group_Test\"}],\"sourceServiceDatas\":[{\"$$hashKey\":\"object:1225\",\"id\":"
+ + "\"choice1\",\"option\":\"Group_Test\"}],\"termDescription\":\"test\",\"termName\":"
+ + "\"Test\",\"toZoneDatas\":[{\"$$hashKey\":\"object:1240\",\"id\":\"choice1\",\"option\":"
+ + "\"Test\"}]},\"userid\":\"demo\"}";
testSave(TermList.class, "termListDictionaryDatas", "termName",
() -> controller.saveTermListDictionary(request, response));
}
@Test
public void testUpdateTermListDictionary() {
- jsonString = "{\"termListDictionaryData\":{\"id\":1,\"actionListDatas\":[{\"$$hashKey\":\"object:1220\",\"id\":\"choice1\",\"option\":\"Group_Test\"}],\"destinationListDatas\":[{\"$$hashKey\":\"object:1220\",\"id\":\"choice1\",\"option\":\"Group_Test\"}],\"destinationServiceDatas\":[{\"$$hashKey\":\"object:1230\",\"id\":\"choice1\",\"option\":\"Group_Test\"}],\"fromZoneDatas\":[{\"$$hashKey\":\"object:1245\",\"id\":\"choice1\",\"option\":\"Test\"}],\"sourceListDatas\":[{\"$$hashKey\":\"object:1215\",\"id\":\"choice1\",\"option\":\"Group_Test\"}],\"sourceServiceDatas\":[{\"$$hashKey\":\"object:1225\",\"id\":\"choice1\",\"option\":\"Group_Test\"}],\"termDescription\":\"test\",\"termName\":\"Test\",\"toZoneDatas\":[{\"$$hashKey\":\"object:1240\",\"id\":\"choice1\",\"option\":\"Test\"}]},\"userid\":\"demo\"}";
+ jsonString =
+ "{\"termListDictionaryData\":{\"id\":1,\"actionListDatas\":[{\"$$hashKey\":\"object:1220\",\"id\":"
+ + "\"choice1\",\"option\":\"Group_Test\"}],\"destinationListDatas\":[{\"$$hashKey\":"
+ + "\"object:1220\",\"id\":\"choice1\",\"option\":\"Group_Test\"}],\"destinationServiceDatas\":"
+ + "[{\"$$hashKey\":\"object:1230\",\"id\":\"choice1\",\"option\":\"Group_Test\"}],\"fromZoneDatas\":"
+ + "[{\"$$hashKey\":\"object:1245\",\"id\":\"choice1\",\"option\":\"Test\"}],\"sourceListDatas\":"
+ + "[{\"$$hashKey\":\"object:1215\",\"id\":\"choice1\",\"option\":"
+ + "\"Group_Test\"}],\"sourceServiceDatas\":[{\"$$hashKey\":\"object:1225\",\"id\":"
+ + "\"choice1\",\"option\":\"Group_Test\"}],\"termDescription\":\"test\",\"termName\":"
+ + "\"Test\",\"toZoneDatas\":[{\"$$hashKey\":\"object:1240\",\"id\":\"choice1\",\"option\":"
+ + "\"Test\"}]},\"userid\":\"demo\"}";
testUpdate(TermList.class, "termListDictionaryDatas", "termName",
() -> controller.saveTermListDictionary(request, response));
}
@@ -461,14 +530,22 @@ public class FirewallDictionaryControllerTest {
@Test
public void testSaveFWDictionaryList() {
- jsonString = "{\"fwDictListDictionaryData\":{\"alAttributes\":[{\"$$hashKey\":\"object:1379\",\"id\":\"choice1\",\"option\":\"Group_Test\"}],\"attributes\":[{\"$$hashKey\":\"object:1374\",\"id\":\"choice1\",\"option\":\"Test\"}],\"description\":\"test\",\"parentItemName\":\"Test\"},\"userid\":\"demo\"}";
+ jsonString =
+ "{\"fwDictListDictionaryData\":{\"alAttributes\":[{\"$$hashKey\":\"object:1379\",\"id\":"
+ + "\"choice1\",\"option\":\"Group_Test\"}],\"attributes\":[{\"$$hashKey\":\"object:1374\",\"id\":"
+ + "\"choice1\",\"option\":\"Test\"}],\"description\":\"test\",\"parentItemName\":\"Test\"},\"userid\":"
+ + "\"demo\"}";
testSave(FirewallDictionaryList.class, "fwDictListDictionaryDatas", "parentItemName",
() -> controller.saveFWDictionaryList(request, response));
}
@Test
public void testUpdateFWDictionaryList() {
- jsonString = "{\"fwDictListDictionaryData\":{\"id\":1,\"alAttributes\":[{\"$$hashKey\":\"object:1379\",\"id\":\"choice1\",\"option\":\"Group_Test\"}],\"attributes\":[{\"$$hashKey\":\"object:1374\",\"id\":\"choice1\",\"option\":\"Test\"}],\"description\":\"test\",\"parentItemName\":\"Test\"},\"userid\":\"demo\"}";
+ jsonString =
+ "{\"fwDictListDictionaryData\":{\"id\":1,\"alAttributes\":[{\"$$hashKey\":\"object:1379\",\"id\":"
+ + "\"choice1\",\"option\":\"Group_Test\"}],\"attributes\":[{\"$$hashKey\":\"object:1374\",\"id\":"
+ + "\"choice1\",\"option\":\"Test\"}],\"description\":\"test\",\"parentItemName\":\"Test\"},\"userid\":"
+ + "\"demo\"}";
testUpdate(FirewallDictionaryList.class, "fwDictListDictionaryDatas", "parentItemName",
() -> controller.saveFWDictionaryList(request, response));
}
@@ -482,43 +559,53 @@ public class FirewallDictionaryControllerTest {
@Test
public void testSaveFirewallTagPickerDictionary() {
- jsonString = "{\"fwTagPickerDictionaryData\":{\"description\":\"test\",\"networkRole\":\"test\",\"tagPickerName\":\"Test\",\"tags\":[{\"$$hashKey\":\"object:1855\",\"id\":\"choice1\",\"number\":\"test\",\"option\":\"Test\"}]},\"userid\":\"demo\"}";
- testSave(FWTagPicker.class, "fwTagPickerDictionaryDatas", "tagPickerName",
+ jsonString =
+ "{\"fwTagPickerDictionaryData\":{\"description\":\"test\",\"networkRole\":\"test\",\"tagPickerName\":"
+ + "\"Test\",\"tags\":[{\"$$hashKey\":\"object:1855\",\"id\":\"choice1\",\"number\":\"test\",\"option\":"
+ + "\"Test\"}]},\"userid\":\"demo\"}";
+ testSave(FwTagPicker.class, "fwTagPickerDictionaryDatas", "tagPickerName",
() -> controller.saveFirewallTagPickerDictionary(request, response));
}
@Test
public void testUpdateFirewallTagPickerDictionary() {
- jsonString = "{\"fwTagPickerDictionaryData\":{\"id\":1,\"description\":\"test\",\"networkRole\":\"test\",\"tagPickerName\":\"Test\",\"tags\":[{\"$$hashKey\":\"object:1855\",\"id\":\"choice1\",\"number\":\"test\",\"option\":\"Test\"}]},\"userid\":\"demo\"}";
- testUpdate(FWTagPicker.class, "fwTagPickerDictionaryDatas", "tagPickerName",
+ jsonString =
+ "{\"fwTagPickerDictionaryData\":{\"id\":1,\"description\":\"test\",\"networkRole\":"
+ + "\"test\",\"tagPickerName\":\"Test\",\"tags\":[{\"$$hashKey\":\"object:1855\",\"id\":"
+ + "\"choice1\",\"number\":\"test\",\"option\":\"Test\"}]},\"userid\":\"demo\"}";
+ testUpdate(FwTagPicker.class, "fwTagPickerDictionaryDatas", "tagPickerName",
() -> controller.saveFirewallTagPickerDictionary(request, response));
}
@Test
public void testRemoveFirewallTagPickerDictionary() {
jsonString = "{\"userid\":\"demo\",\"data\":{\"id\":1,\"description\":\"test\",\"tagPickerName\":\"Test\"}}";
- testRemove(FWTagPicker.class, "fwTagPickerDictionaryDatas",
+ testRemove(FwTagPicker.class, "fwTagPickerDictionaryDatas",
() -> controller.removeFirewallTagPickerDictionary(request, response));
}
@Test
public void testSaveFirewallTagDictionary() {
- jsonString = "{\"fwTagDictionaryData\":{\"description\":\"test\",\"fwTagName\":\"Test\",\"tags\":[{\"$$hashKey\":\"object:1690\",\"id\":\"choice1\",\"tags\":\"test\"}]},\"userid\":\"demo\"}";
- testSave(FWTag.class, "fwTagDictionaryDatas", "fwTagName",
+ jsonString =
+ "{\"fwTagDictionaryData\":{\"description\":\"test\",\"fwTagName\":\"Test\",\"tags\":[{\"$$hashKey\":"
+ + "\"object:1690\",\"id\":\"choice1\",\"tags\":\"test\"}]},\"userid\":\"demo\"}";
+ testSave(FwTag.class, "fwTagDictionaryDatas", "fwTagName",
() -> controller.saveFirewallTagDictionary(request, response));
}
@Test
public void testUpdateFirewallTagDictionary() {
- jsonString = "{\"fwTagDictionaryData\":{\"id\":1,\"description\":\"test\",\"fwTagName\":\"Test\",\"tags\":[{\"$$hashKey\":\"object:1690\",\"id\":\"choice1\",\"tags\":\"test\"}]},\"userid\":\"demo\"}";
- testUpdate(FWTag.class, "fwTagDictionaryDatas", "fwTagName",
+ jsonString =
+ "{\"fwTagDictionaryData\":{\"id\":1,\"description\":\"test\",\"fwTagName\":\"Test\",\"tags\":"
+ + "[{\"$$hashKey\":\"object:1690\",\"id\":\"choice1\",\"tags\":\"test\"}]},\"userid\":\"demo\"}";
+ testUpdate(FwTag.class, "fwTagDictionaryDatas", "fwTagName",
() -> controller.saveFirewallTagDictionary(request, response));
}
@Test
public void testRemoveFirewallTagDictionary() {
jsonString = "{\"userid\":\"demo\",\"data\":{\"id\":1,\"description\":\"test\",\"fwTagName\":\"Test\"}}";
- testRemove(FWTag.class, "fwTagDictionaryDatas",
+ testRemove(FwTag.class, "fwTagDictionaryDatas",
() -> controller.removeFirewallTagDictionary(request, response));
}
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
index e561a65b2..115e30249 100644
--- 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
@@ -20,7 +20,6 @@
* ============LICENSE_END=========================================================
*/
-
package org.onap.policy.pap.xacml.rest.controller;
import static org.junit.Assert.assertTrue;
@@ -28,12 +27,15 @@ 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.Before;
import org.junit.Test;
import org.mockito.Mockito;
@@ -41,7 +43,7 @@ import org.onap.policy.common.logging.flexlogger.FlexLogger;
import org.onap.policy.common.logging.flexlogger.Logger;
import org.onap.policy.pap.xacml.rest.util.DictionaryUtils;
import org.onap.policy.rest.dao.CommonClassDao;
-import org.onap.policy.rest.jpa.DCAEuuid;
+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;
@@ -75,7 +77,7 @@ public class MicroServiceDictionaryControllerTest {
List<String> listIds = new ArrayList<String>();
listIds.add("Jack");
- when(commonClassDao.getDataByColumn(DCAEuuid.class, "name")).thenReturn(listIds);
+ when(commonClassDao.getDataByColumn(DcaeUuid.class, "name")).thenReturn(listIds);
List<String> microList = new ArrayList<String>();
microList.add("MC-Model");
@@ -83,7 +85,7 @@ public class MicroServiceDictionaryControllerTest {
List<Object> listId = new ArrayList<Object>();
listId.add("smith");
- when(commonClassDao.getData(DCAEuuid.class)).thenReturn(listId);
+ when(commonClassDao.getData(DcaeUuid.class)).thenReturn(listId);
MicroServiceModels microServiceModels = new MicroServiceModels();
doNothing().when(commonClassDao).delete(microServiceModels);
@@ -141,7 +143,6 @@ public class MicroServiceDictionaryControllerTest {
logger.info("testSaveMicroServiceHeaderDefaultValues: exit");
}
-
@Test
public void testGetMicroServiceHeaderDefaultsEntityDataByName() {
logger.info("testGetMicroServiceHeaderDefaultsEntityDataByName: Entering");
@@ -215,7 +216,6 @@ public class MicroServiceDictionaryControllerTest {
logger.info("testRemoveMicroServiceHeaderDefaults: exit");
}
-
@Test
public void testGetDCAEUUIDDictionaryByNameEntityData() {
diff --git a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/controller/OptimizationDictionaryControllerTest.java b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/controller/OptimizationDictionaryControllerTest.java
index 5e0b7ce28..f109dbdda 100644
--- a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/controller/OptimizationDictionaryControllerTest.java
+++ b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/controller/OptimizationDictionaryControllerTest.java
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP-PAP-REST
* ================================================================================
- * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2018-2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Modifications Copyright (C) 2019 Samsung
* ================================================================================
@@ -19,19 +19,23 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.policy.pap.xacml.rest.controller;
+import static org.assertj.core.api.Assertions.assertThatCode;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+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 com.mockrunner.mock.web.MockHttpServletRequest;
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 javax.ws.rs.core.Response;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mockito;
@@ -39,14 +43,10 @@ import org.onap.policy.common.logging.flexlogger.FlexLogger;
import org.onap.policy.common.logging.flexlogger.Logger;
import org.onap.policy.pap.xacml.rest.util.DictionaryUtils;
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.OptimizationModels;
import org.onap.policy.rest.jpa.UserInfo;
import org.springframework.mock.web.MockHttpServletResponse;
-
public class OptimizationDictionaryControllerTest {
private static Logger logger = FlexLogger.getLogger(OptimizationDictionaryControllerTest.class);
@@ -63,8 +63,7 @@ public class OptimizationDictionaryControllerTest {
UserInfo userInfo = new UserInfo();
userInfo.setUserLoginId("testUserId");
userInfo.setUserName("John");
- when(commonClassDao.getEntityItem(UserInfo.class, "userLoginId", "testing"))
- .thenReturn(userInfo);
+ when(commonClassDao.getEntityItem(UserInfo.class, "userLoginId", "testing")).thenReturn(userInfo);
OptimizationModels optimziationModels = new OptimizationModels();
@@ -76,19 +75,17 @@ public class OptimizationDictionaryControllerTest {
HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
- jsonString =
- "{\"optimizationModelsDictionaryData\": {\"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\"}}";
+ jsonString = "{\"optimizationModelsDictionaryData\": {\"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\"}}";
br = new BufferedReader(new StringReader(jsonString));
// --- mock the getReader() call
@@ -115,7 +112,7 @@ public class OptimizationDictionaryControllerTest {
controller.getOptimizationModelsDictionaryEntityData(response);
logger.info("response.getContentAsString(): " + response.getContentAsString());
assertTrue(response.getContentAsString() != null
- && response.getContentAsString().contains("optimizationModelsDictionaryDatas"));
+ && response.getContentAsString().contains("optimizationModelsDictionaryDatas"));
} catch (Exception e) {
fail("Exception: " + e);
@@ -137,7 +134,7 @@ public class OptimizationDictionaryControllerTest {
controller.saveOptimizationModelsDictionary(request, response);
logger.info("response.getContentAsString(): " + response.getContentAsString());
assertTrue(response.getContentAsString() != null
- && response.getContentAsString().contains("optimizationModelsDictionaryDatas"));
+ && response.getContentAsString().contains("optimizationModelsDictionaryDatas"));
} catch (Exception e) {
fail("Exception: " + e);
@@ -156,28 +153,58 @@ public class OptimizationDictionaryControllerTest {
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\"}}";
+ "{\"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.removeOptimizationModelsDictionary(request, response);
logger.info("response.getContentAsString(): " + response.getContentAsString());
assertTrue(response.getContentAsString() != null
- && response.getContentAsString().contains("optimizationModelsDictionaryDatas"));
+ && response.getContentAsString().contains("optimizationModelsDictionaryDatas"));
} catch (Exception e) {
fail("Exception: " + e);
}
logger.info("testRemoveOptimizationModelsDictionary: exit");
}
+
+ @Test
+ public void testGet() {
+ OptimizationDictionaryController controller = new OptimizationDictionaryController(commonClassDao);
+ MockHttpServletResponse response = new MockHttpServletResponse();
+ controller.getOptimizationModelsDictionaryByNameEntityData(response);
+ assertEquals(Response.Status.OK.getStatusCode(), response.getStatus());
+ }
+
+ @Test
+ public void testSave() {
+ OptimizationDictionaryController controller = new OptimizationDictionaryController(commonClassDao);
+ MockHttpServletRequest req = new MockHttpServletRequest();
+ MockHttpServletResponse response = new MockHttpServletResponse();
+ req.setBodyContent("{\n\"modelType\": \"type.yml\", \"dataOrderInfo\": \"info\", \"userid\": \"id\", "
+ + "\"optimizationModelsDictionaryData\": {\"description\": \"desc\", \"modelName\": \"name\", \"version\": \"1.0\"}, "
+ + "\"classMap\": \"{\\\"dep\\\":\\\"{\\\"dependency\\\":\\\"depval\\\"}\\\"}\" }\n");
+ assertThatThrownBy(() -> controller.saveOptimizationModelsDictionary(req, response))
+ .isInstanceOf(NullPointerException.class);
+
+ req.setBodyContent("{\n\"modelType\": \"type.xml\", \"dataOrderInfo\": \"info\", \"userid\": \"id\", "
+ + "\"optimizationModelsDictionaryData\": {\"description\": \"desc\", \"modelName\": \"name\", \"version\": \"1.0\"}, "
+ + "\"classMap\": \"{\\\"dep\\\": {\\\"dependency\\\":\\\"depval\\\"} }\" }\n");
+ assertThatCode(() -> controller.saveOptimizationModelsDictionary(req, response)).doesNotThrowAnyException();
+
+ req.setupAddParameter("apiflag", "api");
+ assertThatThrownBy(() -> controller.saveOptimizationModelsDictionary(req, response))
+ .isInstanceOf(NullPointerException.class);
+ }
+
}
diff --git a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/controller/PolicyScopeDictionaryControllerTest.java b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/controller/PolicyScopeDictionaryControllerTest.java
index 9bf2ae590..f8273493b 100644
--- a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/controller/PolicyScopeDictionaryControllerTest.java
+++ b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/controller/PolicyScopeDictionaryControllerTest.java
@@ -2,14 +2,14 @@
* ============LICENSE_START=======================================================
* ONAP-PAP-REST
* ================================================================================
- * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2018-2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -17,6 +17,7 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.policy.pap.xacml.rest.controller;
import static org.junit.Assert.assertTrue;
@@ -55,7 +56,7 @@ public class PolicyScopeDictionaryControllerTest {
private PolicyScopeDictionaryController controller = null;
private MockHttpServletResponse response = null;
private UserInfo userInfo;
- private List<String> data;
+ private List<String> data;
@Before
public void setUp() throws Exception {
@@ -76,7 +77,7 @@ public class PolicyScopeDictionaryControllerTest {
controller.setCommonClassDao(commonClassDao);
request = Mockito.mock(HttpServletRequest.class);
- response = new MockHttpServletResponse();
+ response = new MockHttpServletResponse();
new DictionaryUtils(commonClassDao);
DictionaryUtils.setDictionaryUtils(new DictionaryUtils());
mock(DictionaryUtils.class);
@@ -84,302 +85,339 @@ public class PolicyScopeDictionaryControllerTest {
}
@Test
- public void testGetGroupPolicyScopeEntityDataByName(){
+ public void testGetGroupPolicyScopeEntityDataByName() {
when(commonClassDao.getDataByColumn(GroupPolicyScopeList.class, "name")).thenReturn(data);
controller.getGroupPolicyScopeEntityDataByName(response);
try {
- assertTrue(response.getContentAsString() != null && response.getContentAsString().contains("groupPolicyScopeListDatas"));
+ assertTrue(response.getContentAsString() != null
+ && response.getContentAsString().contains("groupPolicyScopeListDatas"));
} catch (Exception e) {
fail();
- logger.error(e.getMessage(),e);
+ logger.error(e.getMessage(), e);
}
}
@Test
- public void testGetGroupPolicyScopeEntityData(){
+ public void testGetGroupPolicyScopeEntityData() {
when(commonClassDao.getData(GroupPolicyScopeList.class)).thenReturn(new ArrayList<>());
controller.getGroupPolicyScopeEntityData(response);
try {
- assertTrue(response.getContentAsString() != null && response.getContentAsString().contains("groupPolicyScopeListDatas"));
+ assertTrue(response.getContentAsString() != null
+ && response.getContentAsString().contains("groupPolicyScopeListDatas"));
} catch (Exception e) {
fail();
- logger.error(e.getMessage(),e);
+ logger.error(e.getMessage(), e);
}
}
@Test
- public void testGetPSClosedLoopEntityDataByName(){
+ public void testGetPSClosedLoopEntityDataByName() {
when(commonClassDao.getDataByColumn(PolicyScopeClosedLoop.class, "name")).thenReturn(data);
controller.getPSClosedLoopEntityDataByName(response);
try {
- assertTrue(response.getContentAsString() != null && response.getContentAsString().contains("psClosedLoopDictionaryDatas"));
+ assertTrue(response.getContentAsString() != null
+ && response.getContentAsString().contains("psClosedLoopDictionaryDatas"));
} catch (Exception e) {
fail();
- logger.error(e.getMessage(),e);
+ logger.error(e.getMessage(), e);
}
}
@Test
- public void testGetPSClosedLoopEntityData(){
+ public void testGetPSClosedLoopEntityData() {
when(commonClassDao.getData(PolicyScopeClosedLoop.class)).thenReturn(new ArrayList<>());
controller.getPSClosedLoopEntityData(response);
try {
- assertTrue(response.getContentAsString() != null && response.getContentAsString().contains("psClosedLoopDictionaryDatas"));
+ assertTrue(response.getContentAsString() != null
+ && response.getContentAsString().contains("psClosedLoopDictionaryDatas"));
} catch (Exception e) {
fail();
- logger.error(e.getMessage(),e);
+ logger.error(e.getMessage(), e);
}
}
@Test
- public void testGetPSServiceEntityDataByName(){
+ public void testGetPSServiceEntityDataByName() {
when(commonClassDao.getDataByColumn(PolicyScopeService.class, "name")).thenReturn(data);
controller.getPSServiceEntityDataByName(response);
try {
- assertTrue(response.getContentAsString() != null && response.getContentAsString().contains("psServiceDictionaryDatas"));
+ assertTrue(response.getContentAsString() != null
+ && response.getContentAsString().contains("psServiceDictionaryDatas"));
} catch (Exception e) {
fail();
- logger.error(e.getMessage(),e);
+ logger.error(e.getMessage(), e);
}
}
@Test
- public void testGetPSServiceEntityData(){
+ public void testGetPSServiceEntityData() {
when(commonClassDao.getData(PolicyScopeService.class)).thenReturn(new ArrayList<>());
controller.getPSServiceEntityData(response);
try {
- assertTrue(response.getContentAsString() != null && response.getContentAsString().contains("psServiceDictionaryDatas"));
+ assertTrue(response.getContentAsString() != null
+ && response.getContentAsString().contains("psServiceDictionaryDatas"));
} catch (Exception e) {
fail();
- logger.error(e.getMessage(),e);
+ logger.error(e.getMessage(), e);
}
}
@Test
- public void testGetPSTypeEntityDataByName(){
+ public void testGetPSTypeEntityDataByName() {
when(commonClassDao.getDataByColumn(PolicyScopeType.class, "name")).thenReturn(data);
controller.getPSTypeEntityDataByName(response);
try {
- assertTrue(response.getContentAsString() != null && response.getContentAsString().contains("psTypeDictionaryDatas"));
+ assertTrue(response.getContentAsString() != null
+ && response.getContentAsString().contains("psTypeDictionaryDatas"));
} catch (Exception e) {
fail();
- logger.error(e.getMessage(),e);
+ logger.error(e.getMessage(), e);
}
}
@Test
- public void testGetPSTypeEntityData(){
+ public void testGetPSTypeEntityData() {
when(commonClassDao.getData(PolicyScopeType.class)).thenReturn(new ArrayList<>());
controller.getPSTypeEntityData(response);
try {
- assertTrue(response.getContentAsString() != null && response.getContentAsString().contains("psTypeDictionaryDatas"));
+ assertTrue(response.getContentAsString() != null
+ && response.getContentAsString().contains("psTypeDictionaryDatas"));
} catch (Exception e) {
fail();
- logger.error(e.getMessage(),e);
+ logger.error(e.getMessage(), e);
}
}
@Test
- public void testGetPSResourceEntityDataByName(){
+ public void testGetPSResourceEntityDataByName() {
when(commonClassDao.getDataByColumn(PolicyScopeResource.class, "name")).thenReturn(data);
controller.getPSResourceEntityDataByName(response);
try {
- assertTrue(response.getContentAsString() != null && response.getContentAsString().contains("psResourceDictionaryDatas"));
+ assertTrue(response.getContentAsString() != null
+ && response.getContentAsString().contains("psResourceDictionaryDatas"));
} catch (Exception e) {
fail();
- logger.error(e.getMessage(),e);
+ logger.error(e.getMessage(), e);
}
}
@Test
- public void testGetPSResourceEntityData(){
+ public void testGetPSResourceEntityData() {
when(commonClassDao.getData(PolicyScopeResource.class)).thenReturn(new ArrayList<>());
controller.getPSResourceEntityData(response);
try {
- assertTrue(response.getContentAsString() != null && response.getContentAsString().contains("psResourceDictionaryDatas"));
+ assertTrue(response.getContentAsString() != null
+ && response.getContentAsString().contains("psResourceDictionaryDatas"));
} catch (Exception e) {
fail();
- logger.error(e.getMessage(),e);
+ logger.error(e.getMessage(), e);
}
}
@Test
- public void testSavePSGroupScopeDictionary(){
- jsonString = "{\"groupPolicyScopeListData\":{\"description\":\"test\",\"groupName\":\"Test\"},\"groupPolicyScopeListData1\":{\"closedloop\":\"SampleClosedLoop\",\"resource\":\"SampleResource\",\"service\":\"SampleService\",\"type\":\"SampleType\"},\"userid\":\"demo\"}";
- try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){
+ public void testSavePSGroupScopeDictionary() {
+ jsonString =
+ "{\"groupPolicyScopeListData\":{\"description\":\"test\",\"groupName\":\"Test\"},\"groupPolicyScopeListData1\":{\"closedloop\":\"SampleClosedLoop\",\"resource\":\"SampleResource\",\"service\":\"SampleService\",\"type\":\"SampleType\"},\"userid\":\"demo\"}";
+ try (BufferedReader br = new BufferedReader(new StringReader(jsonString))) {
when(request.getReader()).thenReturn(br);
controller.savePSGroupScopeDictionary(request, response);
- assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("groupPolicyScopeListDatas"));
- }catch(Exception e){
- logger.error("Exception"+ e);
+ assertTrue(response.getContentAsString() != null
+ && response.getContentAsString().contains("groupPolicyScopeListDatas"));
+ } catch (Exception e) {
+ logger.error("Exception" + e);
}
}
@Test
- public void testUpdatePSGroupScopeDictionary(){
- jsonString = "{\"groupPolicyScopeListData\":{\"id\":1,\"description\":\"test\",\"groupName\":\"Test\"},\"groupPolicyScopeListData1\":{\"closedloop\":\"SampleClosedLoop\",\"resource\":\"SampleResource\",\"service\":\"SampleService\",\"type\":\"SampleType\"},\"userid\":\"demo\"}";
- try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){
+ public void testUpdatePSGroupScopeDictionary() {
+ jsonString =
+ "{\"groupPolicyScopeListData\":{\"id\":1,\"description\":\"test\",\"groupName\":"
+ + "\"Test\"},\"groupPolicyScopeListData1\":{\"closedloop\":\"SampleClosedLoop\",\"resource\":"
+ + "\"SampleResource\",\"service\":\"SampleService\",\"type\":\"SampleType\"},\"userid\":\"demo\"}";
+ try (BufferedReader br = new BufferedReader(new StringReader(jsonString))) {
when(request.getReader()).thenReturn(br);
controller.savePSGroupScopeDictionary(request, response);
- assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("groupPolicyScopeListDatas"));
- }catch(Exception e){
- logger.error("Exception"+ e);
+ assertTrue(response.getContentAsString() != null
+ && response.getContentAsString().contains("groupPolicyScopeListDatas"));
+ } catch (Exception e) {
+ logger.error("Exception" + e);
}
}
@Test
- public void testRemovePSGroupScopeDictionary(){
+ public void testRemovePSGroupScopeDictionary() {
jsonString = "{\"userid\":\"demo\",\"data\":{\"id\":1,\"description\":\"test\",\"name\":\"Test\"}}";
- try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){
+ try (BufferedReader br = new BufferedReader(new StringReader(jsonString))) {
when(request.getReader()).thenReturn(br);
controller.removePSGroupScopeDictionary(request, response);
- assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("groupPolicyScopeListDatas"));
- }catch(Exception e){
- logger.error("Exception"+ e);
+ assertTrue(response.getContentAsString() != null
+ && response.getContentAsString().contains("groupPolicyScopeListDatas"));
+ } catch (Exception e) {
+ logger.error("Exception" + e);
}
}
@Test
- public void testSavePSClosedLoopDictionary(){
- jsonString = "{\"userid\":\"demo\",\"psClosedLoopDictionaryData\":{\"id\":1,\"description\":\"test\",\"name\":\"Test\"}}";
- try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){
+ public void testSavePSClosedLoopDictionary() {
+ jsonString =
+ "{\"userid\":\"demo\",\"psClosedLoopDictionaryData\":{\"id\":1,\"description\":\"test\",\"name\":"
+ + "\"Test\"}}";
+ try (BufferedReader br = new BufferedReader(new StringReader(jsonString))) {
when(request.getReader()).thenReturn(br);
controller.savePSClosedLoopDictionary(request, response);
- assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("psClosedLoopDictionaryDatas"));
- }catch(Exception e){
- logger.error("Exception"+ e);
+ assertTrue(response.getContentAsString() != null
+ && response.getContentAsString().contains("psClosedLoopDictionaryDatas"));
+ } catch (Exception e) {
+ logger.error("Exception" + e);
}
}
@Test
- public void testUpdatePSClosedLoopDictionary(){
- jsonString = "{\"userid\":\"demo\",\"psClosedLoopDictionaryData\":{\"description\":\"test\",\"name\":\"Test\"}}";
- try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){
+ public void testUpdatePSClosedLoopDictionary() {
+ jsonString =
+ "{\"userid\":\"demo\",\"psClosedLoopDictionaryData\":{\"description\":\"test\",\"name\":\"Test\"}}";
+ try (BufferedReader br = new BufferedReader(new StringReader(jsonString))) {
when(request.getReader()).thenReturn(br);
controller.savePSClosedLoopDictionary(request, response);
- assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("psClosedLoopDictionaryDatas"));
- }catch(Exception e){
- logger.error("Exception"+ e);
+ assertTrue(response.getContentAsString() != null
+ && response.getContentAsString().contains("psClosedLoopDictionaryDatas"));
+ } catch (Exception e) {
+ logger.error("Exception" + e);
}
}
@Test
- public void testRemovePSClosedLoopDictionary(){
+ public void testRemovePSClosedLoopDictionary() {
jsonString = "{\"userid\":\"demo\",\"data\":{\"id\":1,\"description\":\"test\",\"name\":\"Test\"}}";
- try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){
+ try (BufferedReader br = new BufferedReader(new StringReader(jsonString))) {
when(request.getReader()).thenReturn(br);
controller.removePSClosedLoopDictionary(request, response);
- assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("psClosedLoopDictionaryDatas"));
- }catch(Exception e){
- logger.error("Exception"+ e);
+ assertTrue(response.getContentAsString() != null
+ && response.getContentAsString().contains("psClosedLoopDictionaryDatas"));
+ } catch (Exception e) {
+ logger.error("Exception" + e);
}
}
@Test
- public void testSavePSServiceDictionary(){
- jsonString = "{\"userid\":\"demo\",\"psServiceDictionaryData\":{\"id\":1,\"description\":\"test\",\"name\":\"Test\"}}";
- try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){
+ public void testSavePSServiceDictionary() {
+ jsonString =
+ "{\"userid\":\"demo\",\"psServiceDictionaryData\":{\"id\":1,\"description\":\"test\",\"name\":"
+ + "\"Test\"}}";
+ try (BufferedReader br = new BufferedReader(new StringReader(jsonString))) {
when(request.getReader()).thenReturn(br);
controller.savePSServiceDictionary(request, response);
- assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("psServiceDictionaryDatas"));
- }catch(Exception e){
- logger.error("Exception"+ e);
+ assertTrue(response.getContentAsString() != null
+ && response.getContentAsString().contains("psServiceDictionaryDatas"));
+ } catch (Exception e) {
+ logger.error("Exception" + e);
}
}
@Test
- public void testUpdatePSServiceDictionary(){
+ public void testUpdatePSServiceDictionary() {
jsonString = "{\"userid\":\"demo\",\"psServiceDictionaryData\":{\"description\":\"test\",\"name\":\"Test\"}}";
- try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){
+ try (BufferedReader br = new BufferedReader(new StringReader(jsonString))) {
when(request.getReader()).thenReturn(br);
controller.savePSServiceDictionary(request, response);
- assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("psServiceDictionaryDatas"));
- }catch(Exception e){
- logger.error("Exception"+ e);
+ assertTrue(response.getContentAsString() != null
+ && response.getContentAsString().contains("psServiceDictionaryDatas"));
+ } catch (Exception e) {
+ logger.error("Exception" + e);
}
}
@Test
- public void testRemovePSServiceDictionary(){
+ public void testRemovePSServiceDictionary() {
jsonString = "{\"userid\":\"demo\",\"data\":{\"id\":1,\"description\":\"test\",\"name\":\"Test\"}}";
- try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){
+ try (BufferedReader br = new BufferedReader(new StringReader(jsonString))) {
when(request.getReader()).thenReturn(br);
controller.removePSServiceDictionary(request, response);
- assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("psServiceDictionaryDatas"));
- }catch(Exception e){
- logger.error("Exception"+ e);
+ assertTrue(response.getContentAsString() != null
+ && response.getContentAsString().contains("psServiceDictionaryDatas"));
+ } catch (Exception e) {
+ logger.error("Exception" + e);
}
}
@Test
- public void testSavePSTypeDictionary(){
+ public void testSavePSTypeDictionary() {
jsonString = "{\"userid\":\"demo\",\"psTypeDictionaryData\":{\"description\":\"test\",\"name\":\"Test\"}}";
- try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){
+ try (BufferedReader br = new BufferedReader(new StringReader(jsonString))) {
when(request.getReader()).thenReturn(br);
controller.savePSTypeDictionary(request, response);
- assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("psTypeDictionaryDatas"));
- }catch(Exception e){
- logger.error("Exception"+ e);
+ assertTrue(response.getContentAsString() != null
+ && response.getContentAsString().contains("psTypeDictionaryDatas"));
+ } catch (Exception e) {
+ logger.error("Exception" + e);
}
}
@Test
- public void testUpdatePSTypeDictionary(){
- jsonString = "{\"userid\":\"demo\",\"psTypeDictionaryData\":{\"id\":1,\"description\":\"test\",\"name\":\"Test\"}}";
- try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){
+ public void testUpdatePSTypeDictionary() {
+ jsonString =
+ "{\"userid\":\"demo\",\"psTypeDictionaryData\":{\"id\":1,\"description\":\"test\",\"name\":\"Test\"}}";
+ try (BufferedReader br = new BufferedReader(new StringReader(jsonString))) {
when(request.getReader()).thenReturn(br);
controller.savePSTypeDictionary(request, response);
- assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("psTypeDictionaryDatas"));
- }catch(Exception e){
- logger.error("Exception"+ e);
+ assertTrue(response.getContentAsString() != null
+ && response.getContentAsString().contains("psTypeDictionaryDatas"));
+ } catch (Exception e) {
+ logger.error("Exception" + e);
}
}
@Test
- public void testRemovePSTypeDictionary(){
+ public void testRemovePSTypeDictionary() {
jsonString = "{\"userid\":\"demo\",\"data\":{\"id\":1,\"description\":\"test\",\"name\":\"Test\"}}";
- try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){
+ try (BufferedReader br = new BufferedReader(new StringReader(jsonString))) {
when(request.getReader()).thenReturn(br);
controller.removePSTypeDictionary(request, response);
- assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("psTypeDictionaryDatas"));
- }catch(Exception e){
- logger.error("Exception"+ e);
+ assertTrue(response.getContentAsString() != null
+ && response.getContentAsString().contains("psTypeDictionaryDatas"));
+ } catch (Exception e) {
+ logger.error("Exception" + e);
}
}
@Test
- public void testSavePSResourceDictionary(){
+ public void testSavePSResourceDictionary() {
jsonString = "{\"userid\":\"demo\",\"psResourceDictionaryData\":{\"description\":\"test\",\"name\":\"Test\"}}";
- try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){
+ try (BufferedReader br = new BufferedReader(new StringReader(jsonString))) {
when(request.getReader()).thenReturn(br);
controller.savePSResourceDictionary(request, response);
- assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("psResourceDictionaryDatas"));
- }catch(Exception e){
- logger.error("Exception"+ e);
+ assertTrue(response.getContentAsString() != null
+ && response.getContentAsString().contains("psResourceDictionaryDatas"));
+ } catch (Exception e) {
+ logger.error("Exception" + e);
}
}
@Test
- public void testUpdatePSResourceDictionary(){
- jsonString = "{\"userid\":\"demo\",\"psResourceDictionaryData\":{\"id\":1,\"description\":\"test\",\"name\":\"Test\"}}";
- try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){
+ public void testUpdatePSResourceDictionary() {
+ jsonString =
+ "{\"userid\":\"demo\",\"psResourceDictionaryData\":{\"id\":1,\"description\":\"test\",\"name\":"
+ + "\"Test\"}}";
+ try (BufferedReader br = new BufferedReader(new StringReader(jsonString))) {
when(request.getReader()).thenReturn(br);
controller.savePSResourceDictionary(request, response);
- assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("psResourceDictionaryDatas"));
- }catch(Exception e){
- logger.error("Exception"+ e);
+ assertTrue(response.getContentAsString() != null
+ && response.getContentAsString().contains("psResourceDictionaryDatas"));
+ } catch (Exception e) {
+ logger.error("Exception" + e);
}
}
@Test
- public void testRemovePSResourceDictionary(){
+ public void testRemovePSResourceDictionary() {
jsonString = "{\"userid\":\"demo\",\"data\":{\"id\":1,\"description\":\"test\",\"name\":\"Test\"}}";
- try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){
+ try (BufferedReader br = new BufferedReader(new StringReader(jsonString))) {
when(request.getReader()).thenReturn(br);
controller.removePSResourceDictionary(request, response);
- assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("psResourceDictionaryDatas"));
- }catch(Exception e){
- logger.error("Exception"+ e);
+ assertTrue(response.getContentAsString() != null
+ && response.getContentAsString().contains("psResourceDictionaryDatas"));
+ } catch (Exception e) {
+ logger.error("Exception" + e);
}
}
}
diff --git a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/controller/PushPolicyControllerTest.java b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/controller/PushPolicyControllerTest.java
index 007d02120..f9711b9ed 100644
--- a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/controller/PushPolicyControllerTest.java
+++ b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/controller/PushPolicyControllerTest.java
@@ -22,7 +22,9 @@ package org.onap.policy.pap.xacml.rest.controller;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.when;
+
import com.att.research.xacml.api.pap.PAPException;
+
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.File;
@@ -32,12 +34,14 @@ import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
+
import javax.servlet.ReadListener;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
+
import org.hibernate.SessionFactory;
import org.junit.After;
import org.junit.Before;
@@ -52,7 +56,6 @@ import org.onap.policy.rest.dao.CommonClassDao;
import org.onap.policy.rest.jpa.PolicyVersion;
import org.springframework.mock.web.MockServletConfig;
-
public class PushPolicyControllerTest {
private static Logger logger = FlexLogger.getLogger(PushPolicyControllerTest.class);
@@ -68,7 +71,7 @@ public class PushPolicyControllerTest {
@BeforeClass
public static void beforeClassSetup() throws ServletException {
- sessionFactory = PolicyDBDaoTest.setupH2DbDaoImpl("pushcontrollertest");
+ sessionFactory = PolicyDBDaoTest.setupH2DbDaoImpl("pushcontrollertest");
}
@Before
@@ -82,7 +85,8 @@ public class PushPolicyControllerTest {
servletConfig = Mockito.mock(MockServletConfig.class);
System.setProperty("com.sun.management.jmxremote.port", "9993");
Mockito.when(servletConfig.getInitParameterNames()).thenReturn(Collections.enumeration(headers));
- Mockito.when(servletConfig.getInitParameter("XACML_PROPERTIES_NAME")).thenReturn("src/test/resources/xacml.pap.properties");
+ Mockito.when(servletConfig.getInitParameter("XACML_PROPERTIES_NAME"))
+ .thenReturn("src/test/resources/xacml.pap.properties");
commonClassDao = Mockito.mock(CommonClassDao.class);
controller = new PushPolicyController();
@@ -91,35 +95,39 @@ public class PushPolicyControllerTest {
}
@Test
- public void testPushPolicy() throws ServletException, PAPException{
+ public void testPushPolicy() throws ServletException, PAPException {
PolicyVersion versionData = new PolicyVersion();
- versionData.setPolicyName("com"+File.separator+"Config_Test");
+ versionData.setPolicyName("com" + File.separator + "Config_Test");
versionData.setActiveVersion(1);
versionData.setHigherVersion(1);
List<Object> data = new ArrayList<>();
data.add(versionData);
- when(commonClassDao.getDataById(PolicyVersion.class, "policyName", "com"+File.separator+"Config_Test")).thenReturn(data);
+ when(commonClassDao.getDataById(PolicyVersion.class, "policyName", "com" + File.separator + "Config_Test"))
+ .thenReturn(data);
pap = new XACMLPapServlet();
pap.init(servletConfig);
callPushPolicy();
- when(commonClassDao.getDataById(PolicyVersion.class, "policyName", "com"+File.separator+"Config_Test")).thenReturn(null);
+ when(commonClassDao.getDataById(PolicyVersion.class, "policyName", "com" + File.separator + "Config_Test"))
+ .thenReturn(null);
callPushPolicy();
}
- public void callPushPolicy(){
- jsonString = "{\"policyScope\":\"com\",\"filePrefix\":\"Config_\",\"policyName\":\"Test\",\"pdpGroup\":\"default\"}";
- try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){
+ public void callPushPolicy() {
+ jsonString =
+ "{\"policyScope\":\"com\",\"filePrefix\":\"Config_\",\"policyName\":\"Test\",\"pdpGroup\":\"default\"}";
+ try (BufferedReader br = new BufferedReader(new StringReader(jsonString))) {
char[] charBuffer = new char[8 * 1024];
StringBuilder builder = new StringBuilder();
int numCharsRead;
while ((numCharsRead = br.read(charBuffer, 0, charBuffer.length)) != -1) {
builder.append(charBuffer, 0, numCharsRead);
}
- when(request.getInputStream()).thenReturn(getInputStream(builder.toString().getBytes(StandardCharsets.UTF_8)));
+ when(request.getInputStream())
+ .thenReturn(getInputStream(builder.toString().getBytes(StandardCharsets.UTF_8)));
controller.pushPolicy(request, response);
assertTrue(response != null);
- }catch(Exception e){
- logger.error("Exception"+ e);
+ } catch (Exception e) {
+ logger.error("Exception" + e);
}
}
@@ -148,9 +156,9 @@ public class PushPolicyControllerTest {
return servletInputStream;
}
- @After
- public void destroy(){
- if(pap!=null)
- pap.destroy();
- }
+ @After
+ public void destroy() {
+ if (pap != null)
+ pap.destroy();
+ }
}
diff --git a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/controller/SafePolicyControllerTest.java b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/controller/SafePolicyControllerTest.java
index ae1840ebb..8292704b8 100644
--- a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/controller/SafePolicyControllerTest.java
+++ b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/controller/SafePolicyControllerTest.java
@@ -2,14 +2,14 @@
* ============LICENSE_START=======================================================
* ONAP-PAP-REST
* ================================================================================
- * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2018-2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -17,6 +17,7 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.policy.pap.xacml.rest.controller;
import static org.junit.Assert.assertTrue;
@@ -53,7 +54,7 @@ public class SafePolicyControllerTest {
private SafePolicyController controller = null;
private MockHttpServletResponse response = null;
private UserInfo userInfo;
- private List<String> data;
+ private List<String> data;
@Before
public void setUp() throws Exception {
@@ -76,127 +77,139 @@ public class SafePolicyControllerTest {
DictionaryUtils.setDictionaryUtils(new DictionaryUtils());
mock(DictionaryUtils.class);
request = Mockito.mock(HttpServletRequest.class);
- response = new MockHttpServletResponse();
+ response = new MockHttpServletResponse();
logger.info("setUp: exit");
}
@Test
- public void testGetRiskTypeDictionaryByNameEntityData(){
+ public void testGetRiskTypeDictionaryByNameEntityData() {
when(commonClassDao.getDataByColumn(RiskType.class, "name")).thenReturn(data);
controller.getRiskTypeDictionaryByNameEntityData(response);
try {
- assertTrue(response.getContentAsString() != null && response.getContentAsString().contains("riskTypeDictionaryDatas"));
+ assertTrue(response.getContentAsString() != null
+ && response.getContentAsString().contains("riskTypeDictionaryDatas"));
} catch (Exception e) {
fail();
- logger.error(e.getMessage(),e);
+ logger.error(e.getMessage(), e);
}
}
@Test
- public void testGetRiskTypeDictionaryEntityData(){
+ public void testGetRiskTypeDictionaryEntityData() {
when(commonClassDao.getData(RiskType.class)).thenReturn(new ArrayList<>());
controller.getRiskTypeDictionaryEntityData(response);
try {
- assertTrue(response.getContentAsString() != null && response.getContentAsString().contains("riskTypeDictionaryDatas"));
+ assertTrue(response.getContentAsString() != null
+ && response.getContentAsString().contains("riskTypeDictionaryDatas"));
} catch (Exception e) {
fail();
- logger.error(e.getMessage(),e);
+ logger.error(e.getMessage(), e);
}
}
@Test
- public void testGetSafePolicyWarningEntityDataByName(){
+ public void testGetSafePolicyWarningEntityDataByName() {
when(commonClassDao.getDataByColumn(SafePolicyWarning.class, "name")).thenReturn(data);
controller.getSafePolicyWarningEntityDataByName(response);
try {
- assertTrue(response.getContentAsString() != null && response.getContentAsString().contains("safePolicyWarningDatas"));
+ assertTrue(response.getContentAsString() != null
+ && response.getContentAsString().contains("safePolicyWarningDatas"));
} catch (Exception e) {
fail();
- logger.error(e.getMessage(),e);
+ logger.error(e.getMessage(), e);
}
}
@Test
- public void testGetSafePolicyWarningeEntityData(){
+ public void testGetSafePolicyWarningeEntityData() {
when(commonClassDao.getData(SafePolicyWarning.class)).thenReturn(new ArrayList<>());
controller.getSafePolicyWarningeEntityData(response);
try {
- assertTrue(response.getContentAsString() != null && response.getContentAsString().contains("safePolicyWarningDatas"));
+ assertTrue(response.getContentAsString() != null
+ && response.getContentAsString().contains("safePolicyWarningDatas"));
} catch (Exception e) {
fail();
- logger.error(e.getMessage(),e);
+ logger.error(e.getMessage(), e);
}
}
@Test
- public void testSaveRiskTypeDictionary(){
- jsonString = "{\"userid\":\"demo\",\"riskTypeDictionaryData\":{\"id\":1,\"description\":\"test\",\"name\":\"Test\"}}";
- try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){
+ public void testSaveRiskTypeDictionary() {
+ jsonString =
+ "{\"userid\":\"demo\",\"riskTypeDictionaryData\":{\"id\":1,\"description\":\"test\",\"name\":\"Test\"}}";
+ try (BufferedReader br = new BufferedReader(new StringReader(jsonString))) {
when(request.getReader()).thenReturn(br);
controller.saveRiskTypeDictionary(request, response);
- assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("riskTypeDictionaryDatas"));
- }catch(Exception e){
- logger.error("Exception"+ e);
+ assertTrue(response.getContentAsString() != null
+ && response.getContentAsString().contains("riskTypeDictionaryDatas"));
+ } catch (Exception e) {
+ logger.error("Exception" + e);
}
}
@Test
- public void testUpdateRiskTypeDictionary(){
+ public void testUpdateRiskTypeDictionary() {
jsonString = "{\"userid\":\"demo\",\"riskTypeDictionaryData\":{\"description\":\"test\",\"name\":\"Test\"}}";
- try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){
+ try (BufferedReader br = new BufferedReader(new StringReader(jsonString))) {
when(request.getReader()).thenReturn(br);
controller.saveRiskTypeDictionary(request, response);
- assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("riskTypeDictionaryDatas"));
- }catch(Exception e){
- logger.error("Exception"+ e);
+ assertTrue(response.getContentAsString() != null
+ && response.getContentAsString().contains("riskTypeDictionaryDatas"));
+ } catch (Exception e) {
+ logger.error("Exception" + e);
}
}
@Test
- public void testRemoveRiskTypeDictionary(){
+ public void testRemoveRiskTypeDictionary() {
jsonString = "{\"userid\":\"demo\",\"data\":{\"id\":1,\"description\":\"test\",\"name\":\"Test\"}}";
- try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){
+ try (BufferedReader br = new BufferedReader(new StringReader(jsonString))) {
when(request.getReader()).thenReturn(br);
controller.removeRiskTypeDictionary(request, response);
- assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("riskTypeDictionaryDatas"));
- }catch(Exception e){
- logger.error("Exception"+ e);
+ assertTrue(response.getContentAsString() != null
+ && response.getContentAsString().contains("riskTypeDictionaryDatas"));
+ } catch (Exception e) {
+ logger.error("Exception" + e);
}
}
@Test
- public void testSaveSafePolicyWarningDictionary(){
- jsonString = "{\"userid\":\"demo\",\"safePolicyWarningData\":{\"id\":1,\"description\":\"test\",\"name\":\"Test\"}}";
- try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){
+ public void testSaveSafePolicyWarningDictionary() {
+ jsonString =
+ "{\"userid\":\"demo\",\"safePolicyWarningData\":{\"id\":1,\"description\":\"test\",\"name\":\"Test\"}}";
+ try (BufferedReader br = new BufferedReader(new StringReader(jsonString))) {
when(request.getReader()).thenReturn(br);
controller.saveSafePolicyWarningDictionary(request, response);
- assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("safePolicyWarningDatas"));
- }catch(Exception e){
- logger.error("Exception"+ e);
+ assertTrue(response.getContentAsString() != null
+ && response.getContentAsString().contains("safePolicyWarningDatas"));
+ } catch (Exception e) {
+ logger.error("Exception" + e);
}
}
@Test
- public void testUpdateSafePolicyWarningDictionary(){
+ public void testUpdateSafePolicyWarningDictionary() {
jsonString = "{\"userid\":\"demo\",\"safePolicyWarningData\":{\"description\":\"test\",\"name\":\"Test\"}}";
- try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){
+ try (BufferedReader br = new BufferedReader(new StringReader(jsonString))) {
when(request.getReader()).thenReturn(br);
controller.saveSafePolicyWarningDictionary(request, response);
- assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("safePolicyWarningDatas"));
- }catch(Exception e){
- logger.error("Exception"+ e);
+ assertTrue(response.getContentAsString() != null
+ && response.getContentAsString().contains("safePolicyWarningDatas"));
+ } catch (Exception e) {
+ logger.error("Exception" + e);
}
}
@Test
- public void testRemoveSafePolicyWarningDictionary(){
+ public void testRemoveSafePolicyWarningDictionary() {
jsonString = "{\"userid\":\"demo\",\"data\":{\"id\":1,\"description\":\"test\",\"name\":\"Test\"}}";
- try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){
+ try (BufferedReader br = new BufferedReader(new StringReader(jsonString))) {
when(request.getReader()).thenReturn(br);
controller.removeSafePolicyWarningDictionary(request, response);
- assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("safePolicyWarningDatas"));
- }catch(Exception e){
- logger.error("Exception"+ e);
+ assertTrue(response.getContentAsString() != null
+ && response.getContentAsString().contains("safePolicyWarningDatas"));
+ } catch (Exception e) {
+ logger.error("Exception" + e);
}
}
}
diff --git a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/elk/ElasticSearchPolicyUpdateTest.java b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/elk/ElasticSearchPolicyUpdateTest.java
index da9c4e8f5..2b95be068 100644
--- a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/elk/ElasticSearchPolicyUpdateTest.java
+++ b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/elk/ElasticSearchPolicyUpdateTest.java
@@ -2,14 +2,14 @@
* ============LICENSE_START=======================================================
* ONAP-PAP-REST
* ================================================================================
- * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2018-2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -17,6 +17,7 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.policy.pap.xacml.rest.elk;
import static org.junit.Assert.assertTrue;
@@ -46,21 +47,21 @@ public class ElasticSearchPolicyUpdateTest {
private XACMLPAPTest papTest;
@Before
- public void setUp() throws IOException, ServletException, SQLException{
+ public void setUp() throws IOException, ServletException, SQLException {
// Set the system property temporarily
System.setProperty("PROPERTY_FILE", "src/test/resources/policyelk.properties");
try {
ClassLoader classLoader = getClass().getClassLoader();
policyContent = IOUtils.toString(classLoader.getResourceAsStream("Config_SampleTest1206.1.xml"));
} catch (Exception e1) {
- logger.error("Exception Occured"+e1);
+ logger.error("Exception Occured" + e1);
}
papTest = new XACMLPAPTest();
papTest.setDBDao();
}
@Test
- public void testElasticSearchMainFunction() throws SQLException{
+ public void testElasticSearchMainFunction() throws SQLException {
ConfigurationDataEntity configurationEntity = new ConfigurationDataEntity();
configurationEntity.setConfigBody("Sample Test");
configurationEntity.setConfigType("OTHER");
@@ -68,8 +69,7 @@ public class ElasticSearchPolicyUpdateTest {
configurationEntity.setDescription("test");
configurationEntity.setModifiedBy("Test");
configurationEntity.setModifiedDate(new Date());
-
-
+
PolicyEntity entity = new PolicyEntity();
entity.setPolicyName("Config_SampleTest.1.xml");
entity.setPolicyData(policyContent.toString());
@@ -91,7 +91,7 @@ public class ElasticSearchPolicyUpdateTest {
}
@After
- public void reset(){
+ public void reset() {
System.clearProperty("PROPERTY_FILE");
}
}
diff --git a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/elk/ElkConnectorTest.java b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/elk/ElkConnectorTest.java
new file mode 100644
index 000000000..145873981
--- /dev/null
+++ b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/elk/ElkConnectorTest.java
@@ -0,0 +1,54 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP-PAP-REST
+ * ================================================================================
+ * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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;
+
+import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+
+import org.junit.Test;
+import org.onap.policy.pap.xacml.rest.elk.client.ElkConnector;
+import org.onap.policy.pap.xacml.rest.elk.client.ElkConnector.PolicyBodyType;
+import org.onap.policy.pap.xacml.rest.elk.client.ElkConnector.PolicyIndexType;
+import org.onap.policy.pap.xacml.rest.elk.client.ElkConnector.PolicyType;
+
+public class ElkConnectorTest {
+ @Test
+ public void testConnector() {
+ PolicyType type = PolicyType.Config;
+ PolicyBodyType body = PolicyBodyType.json;
+ assertNotNull(type);
+ assertNotNull(body);
+
+ assertEquals(PolicyIndexType.closedloop, ElkConnector.toPolicyIndexType("Config_Fault"));
+ assertEquals(PolicyIndexType.closedloop, ElkConnector.toPolicyIndexType("Config_PM"));
+ assertEquals(PolicyIndexType.config, ElkConnector.toPolicyIndexType("Config_FW"));
+ assertEquals(PolicyIndexType.config, ElkConnector.toPolicyIndexType("Config_MS"));
+ assertEquals(PolicyIndexType.config, ElkConnector.toPolicyIndexType("Config_OOF"));
+ assertEquals(PolicyIndexType.action, ElkConnector.toPolicyIndexType("Action"));
+ assertEquals(PolicyIndexType.decision, ElkConnector.toPolicyIndexType("Decision"));
+ assertEquals(PolicyIndexType.config, ElkConnector.toPolicyIndexType("Config"));
+
+ assertThatIllegalArgumentException().isThrownBy(() -> ElkConnector.toPolicyIndexType(null));
+
+ assertThatIllegalArgumentException().isThrownBy(() -> ElkConnector.toPolicyIndexType("Foo"));
+ }
+}
diff --git a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/elk/PairTest.java b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/elk/PairTest.java
index 0b8c86c1e..7d6b90831 100644
--- a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/elk/PairTest.java
+++ b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/elk/PairTest.java
@@ -2,14 +2,14 @@
* ============LICENSE_START=======================================================
* ONAP-PAP-REST
* ================================================================================
- * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2018-2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -21,6 +21,7 @@
package org.onap.policy.pap.xacml.rest.elk;
import static org.junit.Assert.assertEquals;
+
import org.junit.Test;
import org.onap.policy.pap.xacml.rest.elk.client.Pair;
diff --git a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/elk/PolicyElasticDataTest.java b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/elk/PolicyElasticDataTest.java
index 76c0ce788..401e419bb 100644
--- a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/elk/PolicyElasticDataTest.java
+++ b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/elk/PolicyElasticDataTest.java
@@ -2,14 +2,14 @@
* ============LICENSE_START=======================================================
* ONAP-PAP-REST
* ================================================================================
- * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2018-2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -21,9 +21,11 @@
package org.onap.policy.pap.xacml.rest.elk;
import static org.junit.Assert.assertEquals;
+
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
+
import org.junit.Test;
import org.onap.policy.pap.xacml.rest.elk.client.PolicyElasticData;
import org.onap.policy.rest.adapter.PolicyRestAdapter;
@@ -103,7 +105,7 @@ public class PolicyElasticDataTest {
data.setSupressionType(testVal);
assertEquals(data.getSupressionType(), testVal);
data.setServiceType(testVal);
- assertEquals(data.getServiceType(),testVal);
+ assertEquals(data.getServiceType(), testVal);
data.setUuid(testVal);
assertEquals(data.getUuid(), testVal);
data.setLocation(testVal);
@@ -111,7 +113,7 @@ public class PolicyElasticDataTest {
data.setPriority(testVal);
assertEquals(data.getPriority(), testVal);
data.setMsLocation(testVal);
- assertEquals(data.getMsLocation(),testVal);
+ assertEquals(data.getMsLocation(), testVal);
data.setRuleName(testVal);
assertEquals(data.getRuleName(), testVal);
data.setBrmsParamBody(testMap);
diff --git a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/elk/PolicyElasticSearchControllerTest.java b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/elk/PolicyElasticSearchControllerTest.java
index bdbe1441d..38102afb0 100644
--- a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/elk/PolicyElasticSearchControllerTest.java
+++ b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/elk/PolicyElasticSearchControllerTest.java
@@ -2,14 +2,14 @@
* ============LICENSE_START=======================================================
* ONAP-PAP-REST
* ================================================================================
- * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2018-2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -17,39 +17,48 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.policy.pap.xacml.rest.elk;
+import static org.assertj.core.api.Assertions.assertThatCode;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
import static org.mockito.Mockito.when;
import java.io.BufferedReader;
+import java.io.IOException;
import java.io.StringReader;
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.junit.Before;
import org.junit.Test;
import org.mockito.Mockito;
+import org.onap.policy.pap.xacml.rest.elk.client.ElkConnector.PolicyIndexType;
import org.onap.policy.pap.xacml.rest.elk.client.PolicyElasticSearchController;
+import org.onap.policy.rest.adapter.PolicyRestAdapter;
+import org.onap.policy.rest.dao.CommonClassDao;
+import org.springframework.mock.web.MockHttpServletResponse;
public class PolicyElasticSearchControllerTest {
- private PolicyElasticSearchController conroller;
+ private PolicyElasticSearchController controller;
private HttpServletRequest request = null;
private HttpServletResponse response = null;
@Before
- public void setup(){
- conroller = new PolicyElasticSearchController();
+ public void setup() {
+ controller = new PolicyElasticSearchController();
request = Mockito.mock(HttpServletRequest.class);
- response = Mockito.mock(HttpServletResponse.class);
+ response = new MockHttpServletResponse();
}
@Test
- public void testSearchDictionary(){
+ public void testSearchDictionary() throws IOException {
List<String> jsonString = new ArrayList<>();
jsonString.add("{\"type\":\"attribute\",\"data\":{\"xacmlId\":\"Test\"}}");
jsonString.add("{\"type\":\"onapName\",\"data\":{\"onapName\":\"Test\"}}");
@@ -69,13 +78,36 @@ public class PolicyElasticSearchControllerTest {
jsonString.add("{\"type\":\"psGroupPolicy\",\"data\":{\"name\":\"Test\"}}");
jsonString.add("{\"type\":\"safeRisk\",\"data\":{\"name\":\"Test\"}}");
jsonString.add("{\"type\":\"safePolicyWarning\",\"data\":{\"name\":\"Test\"}}");
- for(int i = 0; i < jsonString.size(); i++){
- try(BufferedReader br = new BufferedReader(new StringReader(jsonString.get(i)))) {
- when(request.getReader()).thenReturn(br);
- conroller.searchDictionary(request, response);
- } catch (Exception e) {
- assertEquals(NullPointerException.class, e.getClass());
- }
+ for (int i = 0; i < jsonString.size(); i++) {
+ BufferedReader br = new BufferedReader(new StringReader(jsonString.get(i)));
+ when(request.getReader()).thenReturn(br);
+ assertThatCode(() -> controller.searchDictionary(request, response)).doesNotThrowAnyException();
}
}
+
+ @Test
+ public void testController() throws IOException {
+ CommonClassDao dao = Mockito.mock(CommonClassDao.class);
+ PolicyElasticSearchController controller = new PolicyElasticSearchController(dao);
+ assertEquals(PolicyIndexType.all, controller.toPolicyIndexType(null));
+ assertEquals(PolicyIndexType.config, controller.toPolicyIndexType("config"));
+
+ Map<String, String> searchKeys = new HashMap<String, String>();
+ searchKeys.put("key", "value");
+ assertThatThrownBy(() -> controller.search(PolicyIndexType.config, "text", searchKeys))
+ .isInstanceOf(Exception.class);
+
+ when(request.getParameter("policyName")).thenReturn("policyName");
+ when(request.getParameter("action")).thenReturn("search");
+ when(request.getReader())
+ .thenReturn(new BufferedReader(new StringReader("{\"searchdata\": { \"query\": \"value space\", "
+ + "\"policyType\": \"all\", " + "\"closedLooppolicyType\": \"type\", " + "\"onapName\": \"pef\", "
+ + "\"vnfType\": \"vnf\", " + "\"policyStatus\": \"active\", " + "\"vproAction\": \"reboot\", "
+ + "\"serviceType\": \"type\", " + "\"bindTextSearch\": \"pef\", " + "\"d2Service\": \"vDNS\"} }")));
+ controller.searchPolicy(request, response);
+ assertEquals(HttpServletResponse.SC_OK, response.getStatus());
+
+ PolicyRestAdapter policyData = new PolicyRestAdapter();
+ assertFalse(controller.deleteElk(policyData));
+ }
}
diff --git a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/elk/PolicyLocatorTest.java b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/elk/PolicyLocatorTest.java
index 7df295382..bffdf3d79 100644
--- a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/elk/PolicyLocatorTest.java
+++ b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/elk/PolicyLocatorTest.java
@@ -2,14 +2,14 @@
* ============LICENSE_START=======================================================
* ONAP-PAP-REST
* ================================================================================
- * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2018-2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -21,6 +21,7 @@
package org.onap.policy.pap.xacml.rest.elk;
import static org.junit.Assert.assertEquals;
+
import org.junit.Test;
import org.onap.policy.pap.xacml.rest.elk.client.PolicyLocator;
@@ -35,8 +36,7 @@ public class PolicyLocatorTest {
String version = "1.0";
String testString = "[owner|scope|type|name|id|v1.0|]";
- PolicyLocator locator = new PolicyLocator(policyType, policyName, owner,
- scope, policyId, version);
+ PolicyLocator locator = new PolicyLocator(policyType, policyName, owner, scope, policyId, version);
String locatorString = locator.toString();
assertEquals(locatorString, testString);
}
diff --git a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/elk/ElkConnectorImplTest.java b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/elk/client/ElkConnectorImplTest.java
index 2f3d580f7..8eb003ca8 100644
--- a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/elk/ElkConnectorImplTest.java
+++ b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/elk/client/ElkConnectorImplTest.java
@@ -2,14 +2,14 @@
* ============LICENSE_START=======================================================
* ONAP-PAP-REST
* ================================================================================
- * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -18,23 +18,24 @@
* ============LICENSE_END=========================================================
*/
-package org.onap.policy.pap.xacml.rest.elk;
+package org.onap.policy.pap.xacml.rest.elk.client;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
-import io.searchbox.client.JestResult;
+import io.searchbox.client.JestResult;
import java.io.IOException;
import java.lang.reflect.Method;
-
+import java.util.HashMap;
+import java.util.Map;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.onap.policy.pap.xacml.rest.elk.client.ElkConnector.PolicyIndexType;
-import org.onap.policy.pap.xacml.rest.elk.client.ElkConnectorImpl;
import org.onap.policy.rest.adapter.PolicyRestAdapter;
public class ElkConnectorImplTest {
@@ -56,41 +57,41 @@ public class ElkConnectorImplTest {
}
@Test
- public void searchTest(){
- JestResult r1=null, r2=null, r3=null, r4=null;
+ public void searchTest() {
+ JestResult r1 = null, r2 = null, r3 = null, r4 = null;
// Should always work if the above test passes and ELK server is up
- try{
+ try {
r1 = new ElkConnectorImpl().search(PolicyIndexType.decision, "abc123");
} catch (Exception e) {
// ELK server is down. Don't continue the test
- if(e instanceof IllegalStateException){
+ if (e instanceof IllegalStateException) {
return;
}
fail();
}
// Should always work
- try{
+ try {
r2 = new ElkConnectorImpl().search(PolicyIndexType.decision, "The_quick_brown_fox_jumps_over_the_lazy_dog");
} catch (Exception e) {
fail();
}
// Should throw exception
- try{
+ try {
r3 = new ElkConnectorImpl().search(PolicyIndexType.decision, "abc123{}");
} catch (Exception e) {
- if(! (e instanceof IllegalArgumentException)){
+ if (!(e instanceof IllegalArgumentException)) {
fail();
}
}
// Should throw exception
- try{
+ try {
r4 = new ElkConnectorImpl().search(PolicyIndexType.decision, "The quick brown fox jumps over the lazy dog");
} catch (Exception e) {
- if(! (e instanceof IllegalArgumentException)){
+ if (!(e instanceof IllegalArgumentException)) {
fail();
}
}
@@ -114,7 +115,6 @@ public class ElkConnectorImplTest {
fail("Expected exception to be thrown");
}
-
@Test
public void testPut() throws IOException {
thrown.expect(NullPointerException.class);
@@ -143,4 +143,31 @@ public class ElkConnectorImplTest {
impl.search(PolicyIndexType.config, "search", null);
fail("Expected exception to be thrown");
}
+
+ @Test
+ public void testImplNegCases() throws IOException {
+ ElkConnectorImpl impl = new ElkConnectorImpl();
+ Map<String, String> filter = new HashMap<String, String>();
+ assertThatThrownBy(() -> impl.isType(PolicyIndexType.config)).isInstanceOf(IOException.class);
+ assertThatThrownBy(() -> impl.isIndex()).isInstanceOf(IOException.class);
+ assertThatThrownBy(() -> impl.search(null, null)).isInstanceOf(IllegalArgumentException.class);
+ assertThatThrownBy(() -> impl.search(null, "")).isInstanceOf(IllegalArgumentException.class);
+ assertThatThrownBy(() -> impl.search(null, ";;;")).isInstanceOf(IllegalArgumentException.class);
+ assertThatThrownBy(() -> impl.search(null, "foo")).isInstanceOf(IllegalStateException.class);
+ assertThatThrownBy(() -> impl.search(PolicyIndexType.all, "foo")).isInstanceOf(IllegalStateException.class);
+
+ assertThatThrownBy(() -> impl.search(null, null, null)).isInstanceOf(IllegalArgumentException.class);
+ assertThatThrownBy(() -> impl.search(null, null, filter)).isInstanceOf(IllegalArgumentException.class);
+ filter.put("key", "value");
+ assertThatThrownBy(() -> impl.search(null, ";;;", filter)).isInstanceOf(IllegalArgumentException.class);
+ assertThatThrownBy(() -> impl.search(null, "foo", filter)).isInstanceOf(IllegalStateException.class);
+ assertThatThrownBy(() -> impl.search(PolicyIndexType.config, "foo", filter))
+ .isInstanceOf(IllegalStateException.class);
+
+ PolicyRestAdapter adapter = new PolicyRestAdapter();
+ adapter.setNewFileName("scope.Decision_newFile");
+ adapter.setConfigPolicyType("Config");
+ assertThatThrownBy(() -> impl.put(adapter)).isInstanceOf(IOException.class);
+ assertThatThrownBy(() -> impl.delete(adapter)).isInstanceOf(IllegalStateException.class);
+ }
}
diff --git a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/handler/DeleteHandlerTest.java b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/handler/DeleteHandlerTest.java
index 73540033f..885230da4 100644
--- a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/handler/DeleteHandlerTest.java
+++ b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/handler/DeleteHandlerTest.java
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP-PAP-REST
* ================================================================================
- * Copyright (C) 2018-2019 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2018-2020 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -23,11 +23,15 @@ package org.onap.policy.pap.xacml.rest.handler;
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 static org.mockito.Matchers.any;
+import static org.junit.Assert.assertTrue;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.when;
+
import com.mockrunner.mock.web.MockHttpServletRequest;
import com.mockrunner.mock.web.MockHttpServletResponse;
+import java.io.IOException;
+import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.hibernate.Session;
@@ -37,18 +41,23 @@ import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
-import org.onap.policy.common.logging.ONAPLoggingContext;
+import org.onap.policy.common.logging.OnapLoggingContext;
import org.onap.policy.pap.xacml.rest.XACMLPapServlet;
import org.onap.policy.pap.xacml.rest.daoimpl.CommonClassDaoImpl;
import org.onap.policy.pap.xacml.rest.elk.client.PolicyElasticSearchController;
+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.pap.PAPPolicyEngine;
import org.onap.policy.xacml.std.pap.StdEngine;
import org.powermock.api.mockito.PowerMockito;
+import org.powermock.core.classloader.annotations.PowerMockIgnore;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
@RunWith(PowerMockRunner.class)
+@PowerMockIgnore({"com.sun.org.apache.xerces.*", "jdk.internal.reflect.*", "javax.xml.*", "org.xml.*", "org.w3c.*"})
+@PrepareForTest(DeleteHandler.class)
public class DeleteHandlerTest {
@Before
public void setUp() {
@@ -93,31 +102,114 @@ public class DeleteHandlerTest {
PolicyElasticSearchController controller = Mockito.mock(PolicyElasticSearchController.class);
PowerMockito.whenNew(PolicyElasticSearchController.class).withNoArguments().thenReturn(controller);
- // Test deletion from PAP
- MockHttpServletResponse response = new MockHttpServletResponse();
- try {
- handler.doApiDeleteFromPap(request, response);
- } catch (Exception ex) {
- fail("Not expecting an exception: " + ex);
- }
+ // Test deletion from PAP
+ MockHttpServletResponse response = new MockHttpServletResponse();
+ handler.doApiDeleteFromPap(request, response);
// Test deletion from PDP
- ONAPLoggingContext loggingContext = Mockito.mock(ONAPLoggingContext.class);
- try {
- handler.doApiDeleteFromPdp(request, response, loggingContext);
- }
- catch (Exception ex) {
- fail("Not expecting an exception: " + ex);
- }
-
- // Test delete entity
- PolicyEntity policyEntity = new PolicyEntity();
- policyEntity.setPolicyName("testVal");
- String result = DeleteHandler.deletePolicyEntityData(policyEntity);
- assertEquals(result, "success");
-
- // Test check entity
- List<?> peResult = Collections.emptyList();
- assertEquals(DeleteHandler.checkPolicyGroupEntity(peResult), false);
- }
+ OnapLoggingContext loggingContext = Mockito.mock(OnapLoggingContext.class);
+ handler.doApiDeleteFromPdp(request, response, loggingContext);
+
+ // Test delete entity
+ PolicyEntity policyEntity = new PolicyEntity();
+ policyEntity.setPolicyName("testVal");
+ String result = DeleteHandler.deletePolicyEntityData(policyEntity);
+ assertEquals(result, "success");
+
+ // Test check entity
+ List<?> peResult = Collections.emptyList();
+ assertEquals(DeleteHandler.checkPolicyGroupEntity(peResult), false);
+ }
+
+ @Test
+ public void testDoDeletePap() throws IOException {
+ CommonClassDao dao = Mockito.mock(CommonClassDao.class);
+ DeleteHandler handler = new DeleteHandler(dao);
+
+ // Request #1
+ MockHttpServletRequest request = new MockHttpServletRequest();
+ request.setBodyContent(
+ "{\n\"PAPPolicyType\": \"StdPAPPolicy\", \"policyName\": \"foo.Config_name.1.xml\", \"deleteCondition\": \"All Versions\"\n}\n");
+ MockHttpServletResponse response = new MockHttpServletResponse();
+ handler.doApiDeleteFromPap(request, response);
+ assertTrue(response.containsHeader("error"));
+
+ // Request #2
+ request.setBodyContent(
+ "{\n\"PAPPolicyType\": \"StdPAPPolicy\", \"policyName\": \"foo.Action_name.1.xml\", \"deleteCondition\": \"All Versions\"\n}\n");
+ handler.doApiDeleteFromPap(request, response);
+ assertTrue(response.containsHeader("error"));
+
+ // Request #3
+ request.setBodyContent(
+ "{\n\"PAPPolicyType\": \"StdPAPPolicy\", \"policyName\": \"foo.Decision_name.1.xml\", \"deleteCondition\": \"All Versions\"\n}\n");
+ handler.doApiDeleteFromPap(request, response);
+ assertTrue(response.containsHeader("error"));
+
+ // Request #4
+ request.setBodyContent(
+ "{\n\"PAPPolicyType\": \"StdPAPPolicy\", \"policyName\": \"foo.Bar_name.1.xml\", \"deleteCondition\": \"All Versions\"\n}\n");
+ handler.doApiDeleteFromPap(request, response);
+ assertTrue(response.containsHeader("error"));
+
+ // Request #5
+ request.setBodyContent(
+ "{\n\"PAPPolicyType\": \"StdPAPPolicy\", \"policyName\": \"foo.Config_name.1.xml\", \"deleteCondition\": \"Current Version\"\n}\n");
+ handler.doApiDeleteFromPap(request, response);
+ assertTrue(response.containsHeader("error"));
+
+ // Request #6
+ request.setBodyContent(
+ "{\n\"PAPPolicyType\": \"StdPAPPolicy\", \"policyName\": \"foo.Action_name.1.xml\", \"deleteCondition\": \"Current Version\"\n}\n");
+ handler.doApiDeleteFromPap(request, response);
+ assertTrue(response.containsHeader("error"));
+
+ // Request #7
+ request.setBodyContent(
+ "{\n\"PAPPolicyType\": \"StdPAPPolicy\", \"policyName\": \"foo.Decision_name.1.xml\", \"deleteCondition\": \"Current Version\"\n}\n");
+ handler.doApiDeleteFromPap(request, response);
+ assertTrue(response.containsHeader("error"));
+
+ // Mock dao
+ List<PolicyVersion> pePVs = new ArrayList<PolicyVersion>();
+ PolicyVersion pv = new PolicyVersion();
+ pePVs.add(pv);
+ List<Object> peObjs = new ArrayList<Object>(pePVs);
+ List<PolicyEntity> peEnts = new ArrayList<PolicyEntity>();
+ PolicyEntity peEnt = new PolicyEntity();
+ peEnts.add(peEnt);
+ List<Object> peEntObjs = new ArrayList<Object>(peEnts);
+ Mockito.when(dao.getDataByQuery(eq("Select p from PolicyVersion p where p.policyName=:pname"), any()))
+ .thenReturn(peObjs);
+ Mockito.when(
+ dao.getDataByQuery(eq("SELECT p FROM PolicyEntity p WHERE p.policyName=:pName and p.scope=:pScope"), any()))
+ .thenReturn(peEntObjs);
+
+ // Request #8
+ request.setBodyContent(
+ "{\n\"PAPPolicyType\": \"StdPAPPolicy\", \"policyName\": \"foo.Decision_name.1.xml\", \"deleteCondition\": \"Current Version\"\n}\n");
+ handler.doApiDeleteFromPap(request, response);
+ assertTrue(response.containsHeader("error"));
+
+ // Request #9
+ request.setBodyContent(
+ "{\n\"PAPPolicyType\": \"StdPAPPolicy\", \"policyName\": \"foo.Decision_name.1.xml\", \"deleteCondition\": \"Current Version\"\n, \"deleteCondition\": \"All Versions\"}\n");
+ handler.doApiDeleteFromPap(request, response);
+ assertTrue(response.containsHeader("error"));
+ }
+
+ @Test(expected = NullPointerException.class)
+ public void testDoDeletePdp() throws IOException {
+ CommonClassDao dao = Mockito.mock(CommonClassDao.class);
+ DeleteHandler handler = new DeleteHandler(dao);
+ OnapLoggingContext loggingContext = new OnapLoggingContext();
+
+ // Mock request
+ MockHttpServletRequest request = new MockHttpServletRequest();
+ request.setBodyContent(
+ "{\n\"PAPPolicyType\": \"StdPAPPolicy\", \"policyName\": \"foo.Config_name.1.xml\", \"deleteCondition\": \"All Versions\"\n}\n");
+ MockHttpServletResponse response = new MockHttpServletResponse();
+
+ handler.doApiDeleteFromPdp(request, response, loggingContext);
+ }
}
diff --git a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/handler/DictionaryHandlerTest.java b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/handler/DictionaryHandlerTest.java
index ca6860ae8..8c35c17ef 100644
--- a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/handler/DictionaryHandlerTest.java
+++ b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/handler/DictionaryHandlerTest.java
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP-PAP-REST
* ================================================================================
- * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2018-2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Modifications Copyright (C) 2019 Samsung
* ================================================================================
@@ -23,6 +23,7 @@
package org.onap.policy.pap.xacml.rest.handler;
import static org.junit.Assert.assertNull;
+
import org.junit.Test;
public class DictionaryHandlerTest {
diff --git a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/handler/PushPolicyHandlerTest.java b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/handler/PushPolicyHandlerTest.java
index 3daed2455..ae6235f0e 100644
--- a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/handler/PushPolicyHandlerTest.java
+++ b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/handler/PushPolicyHandlerTest.java
@@ -25,13 +25,17 @@ import static org.junit.Assert.assertNotNull;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.doReturn;
+
import com.mockrunner.mock.web.MockHttpServletResponse;
+
import java.io.File;
import java.util.ArrayList;
import java.util.List;
+
import javax.script.SimpleBindings;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
+
import org.junit.Test;
import org.mockito.Mockito;
import org.onap.policy.rest.dao.CommonClassDao;
@@ -40,7 +44,6 @@ import org.onap.policy.xacml.api.pap.OnapPDPGroup;
import org.onap.policy.xacml.std.pap.StdPDPGroup;
import org.onap.policy.xacml.std.pap.StdPDPPolicy;
-
public class PushPolicyHandlerTest {
@Test
public void testGetsAndChecks() {
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
index e7de8d0c4..d7fbda259 100644
--- 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
@@ -2,14 +2,14 @@
* ============LICENSE_START=======================================================
* ONAP-PAP-REST
* ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017, 2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -22,14 +22,9 @@ 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 java.util.Date;
+import java.util.List;
+import java.util.Properties;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
@@ -37,560 +32,526 @@ 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.junit.*;
+import org.onap.policy.common.logging.flexlogger.FlexLogger;
import org.onap.policy.common.logging.flexlogger.Logger;
-
-import java.util.Properties;
+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;
public class PolicyEntityTest {
private static Logger logger = FlexLogger.getLogger(PolicyEntityTest.class);
@Test
- public void testAllOps(){
+ 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, "");
+ 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();
+ // 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
+ // Create a policy object
PolicyEntity p1 = new PolicyEntity();
-
- //persist the policy
+
+ // 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");
-
+ 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 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
+
+ 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
+
+ // Set policyData
p1.setPolicyData("<policy>PolicyData</policy>");
-
- //We will NOT set the ConfigurationDataEntity or ActionBodyEntity object just to test that it is optional
-
- //set createdBy
+
+ // 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
+
+ // createdDate will be set when it is persisted
+
+ // set scope
p1.setScope("mckiou.kevin");
-
- //set description
+
+ // set description
p1.setDescription("PolicyEntity Description");
-
- //set modifiedBy
+
+ // set modifiedBy
p1.setModifiedBy("kevin");
-
- //modifiedDate will be set when it is persisted
-
- //Flush to the DB
+
+ // modifiedDate will be set when it is persisted
+
+ // Flush to the DB
em.flush();
-
- //Now lets get some attribute values
-
+
+ // 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");
-
+ configDataStr1 = (configData1 != null ? "configurationDataId = " + configData1.getConfigurationDataId()
+ : "configurationData is null");
+
actionBody1 = p1.getActionBodyEntity();
- actionBodyStr1 = (actionBody1!=null ? "actionBodyId = " + actionBody1.getActionBodyId() : "actionBody is null");
-
+ 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
+
+ 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.setModifiedBy("kevin");
+
c1.setDeleted(true);
-
- //persist the action Body
-
+
+ // 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());
-
-
-
+ + "\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
+ + "\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
-
+
+ // 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
+
+ // Just test that we are retrieving the right object
@SuppressWarnings("rawtypes")
List psList = queryscope.getResultList();
PolicyEntity px = null;
- if(!psList.isEmpty()){
- //ignores multiple results
+ if (!psList.isEmpty()) {
+ // ignores multiple results
px = (PolicyEntity) psList.get(0);
- }else{
+ } 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.
+
+ // 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()){
+ if (!resultList.isEmpty()) {
// ignores multiple results
p2 = (PolicyEntity) resultList.get(0);
- }else{
+ } 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
+
+ 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
+
+ // Get the database version of the Configuration Data
resultList = query2.getResultList();
ConfigurationDataEntity c2 = null;
- if(!resultList.isEmpty()){
+ if (!resultList.isEmpty()) {
// ignores multiple results
c2 = (ConfigurationDataEntity) resultList.get(0);
- }else{
+ } 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
+
+ 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
+
+ // 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
+
+ // Get the database version of the Action Body
resultList = querya2.getResultList();
ActionBodyEntity a2 = null;
- if(!resultList.isEmpty()){
+ if (!resultList.isEmpty()) {
// ignores multiple results
a2 = (ActionBodyEntity) resultList.get(0);
- }else{
+ } 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
+
+ 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
+
+ // 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()){
+ if (!resultList.isEmpty()) {
// ignores multiple results
p2 = (PolicyEntity) resultList.get(0);
- }else{
+ } 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
+
+ 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()){
+ if (!resultList.isEmpty()) {
// ignores multiple results
c2 = (ConfigurationDataEntity) resultList.get(0);
- }else{
+ } 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
+
+ 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()){
+ if (!resultList.isEmpty()) {
// ignores multiple results
a2 = (ActionBodyEntity) resultList.get(0);
- }else{
+ } 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
-
+
+ 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
+
+ // 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
+
+ // 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()){
+ if (resultList.isEmpty()) {
logger.debug("\n\n********PolicyEntityTest: orphanRemoval=true******"
+ "\n Success!! No ConfigurationDataEntity DB entry found");
-
- }else{
+
+ } 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
+
+ // 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()){
+ if (resultList.isEmpty()) {
logger.debug("\n\n********PolicyEntityTest: orphanRemoval=true******"
+ "\n Success!! No ActionBodyEntity DB entry found");
-
- }else{
+
+ } else {
a2 = (ActionBodyEntity) resultList.get(0);
- fail("\nPolicyEntityTest: ActionBodyEntity DB entry found - and none should exist"
- + "\nactionBodyId = " + a2.getActionBodyId());
+ 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.
+
+ // 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
+
+ // retrieve the policy object
resultList = query.getResultList();
p2 = null;
- if(!resultList.isEmpty()){
+ if (!resultList.isEmpty()) {
// ignores multiple results
p2 = (PolicyEntity) resultList.get(0);
- }else{
+ } 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
+
+ // 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()){
+ if (!resultList.isEmpty()) {
// ignores multiple results
c2 = (ConfigurationDataEntity) resultList.get(0);
- }else{
+ } 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
+
+ // 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{
+ 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 "
+ } catch (Exception e) {
+ logger.debug("\n\n***********PolicyEntityTest: et.commit Failed********" + "\nTRANSACTION ROLLBACK "
+ "\n with exception: " + e);
}
@@ -598,206 +559,184 @@ public class PolicyEntityTest {
EntityTransaction et2 = em.getTransaction();
et2.begin();
-
- //Let's test if the PolicyEntity uniqueConstraint for policyName and scopeId hold
+
+ // 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
+ // 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
+ + "\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
+ + "\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);
+ + "\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{
+ try {
et2.commit();
logger.debug("\n\n***********PolicyEntityTest: et2.commit Succeeded********");
- }catch(Exception e){
- logger.debug("\n\n***********PolicyEntityTest: et2.commit Failed********"
- + "\nTRANSACTION ROLLBACK "
+ } catch (Exception e) {
+ logger.debug("\n\n***********PolicyEntityTest: et2.commit Failed********" + "\nTRANSACTION ROLLBACK "
+ "\n with exception: " + e);
}
-
- //****************Test the PolicyDBDaoEntity************************
-
- //Create a transaction
+
+ // ****************Test the PolicyDbDaoEntity************************
+
+ // Create a transaction
EntityTransaction et3 = em.getTransaction();
et3.begin();
-
- //create one
- PolicyDBDaoEntity pe1 = new PolicyDBDaoEntity();
+
+ // 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
+
+ pe1.setPolicyDbDaoUrl("http://123.45.2.456:2345");
+
+ // push it to the DB
em.flush();
-
- //create another
- PolicyDBDaoEntity pe2 = new PolicyDBDaoEntity();
+
+ // 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
+
+ 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;
+ // Now let's retrieve them from the DB using the named query
+
+ resultList = em.createNamedQuery("PolicyDbDaoEntity.findAll").getResultList();
- if(!resultList.isEmpty()){
- if (resultList.size() != 2){
- fail("\nPolicyEntityTest: Number of PolicyDBDaoEntity entries = " + resultList.size() + " instead of 2");
+ 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")){
+ 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")){
+ } 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);
+ // 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");
+
+ } 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);
+
+ // 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");
+
+ // 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");
+ 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");
+ 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();
+
+ // 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{
+
+ // 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 "
+ } catch (Exception e) {
+ logger.debug("\n\n***********PolicyEntityTest: et3.commit Failed********" + "\nTRANSACTION ROLLBACK "
+ "\n with exception: " + e);
}
-
-
- //Tidy up
+
+ // Tidy up
em.close();
}
-
+
}
diff --git a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/model/RemoveGroupPolicyTest.java b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/model/RemoveGroupPolicyTest.java
index cd6bf021d..81f9fae9d 100644
--- a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/model/RemoveGroupPolicyTest.java
+++ b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/model/RemoveGroupPolicyTest.java
@@ -21,7 +21,9 @@
package org.onap.policy.pap.xacml.rest.model;
import static org.junit.Assert.assertEquals;
+
import com.att.research.xacml.api.pap.PDPPolicy;
+
import org.junit.Test;
import org.onap.policy.xacml.std.pap.StdPDPGroup;
import org.onap.policy.xacml.std.pap.StdPDPPolicy;
diff --git a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/policycontroller/PolicyCreationTest.java b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/policycontroller/PolicyCreationTest.java
new file mode 100644
index 000000000..953fff35c
--- /dev/null
+++ b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/policycontroller/PolicyCreationTest.java
@@ -0,0 +1,152 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP-PAP-REST
+ * ================================================================================
+ * Copyright (C) 2019-2020 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 static org.assertj.core.api.Assertions.assertThat;
+import static org.junit.Assert.assertEquals;
+import static org.mockito.ArgumentMatchers.anyString;
+import static org.mockito.ArgumentMatchers.eq;
+import java.util.ArrayList;
+import java.util.LinkedHashMap;
+import java.util.LinkedList;
+import java.util.List;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import org.hibernate.Criteria;
+import org.hibernate.Session;
+import org.hibernate.SessionFactory;
+import org.junit.Test;
+import org.mockito.Mockito;
+import org.onap.policy.pap.xacml.rest.components.PolicyDbDao;
+import org.onap.policy.pap.xacml.rest.components.PolicyDbDaoTransaction;
+import org.onap.policy.rest.adapter.PolicyRestAdapter;
+import org.onap.policy.rest.dao.CommonClassDao;
+import org.onap.policy.rest.jpa.PolicyDbDaoEntity;
+import org.onap.policy.rest.jpa.PolicyVersion;
+import org.powermock.reflect.Whitebox;
+import org.springframework.http.HttpStatus;
+import org.springframework.http.ResponseEntity;
+import org.springframework.http.converter.HttpMessageNotReadableException;
+import org.springframework.mock.web.MockHttpServletResponse;
+import com.mockrunner.mock.web.MockHttpServletRequest;
+
+public class PolicyCreationTest {
+ @Test
+ public void testCreation() {
+ CommonClassDao dao = Mockito.mock(CommonClassDao.class);
+ PolicyVersion version = new PolicyVersion();
+ version.setPolicyName("policyname");
+ Mockito.when(dao.getEntityItem(eq(PolicyVersion.class), eq("policyName"), anyString())).thenReturn(version);
+ PolicyCreation.setCommonClassDao(dao);
+ assertEquals(dao, PolicyCreation.getCommonClassDao());
+ PolicyCreation creation = new PolicyCreation(dao);
+ assertEquals(dao, PolicyCreation.getCommonClassDao());
+
+ HttpServletRequest req = new MockHttpServletRequest();
+ Exception cause = new Exception("oops");
+ HttpMessageNotReadableException exception = new HttpMessageNotReadableException("oops", cause);
+ assertEquals(HttpStatus.BAD_REQUEST,
+ creation.messageNotReadableExceptionHandler(req, exception).getStatusCode());
+
+ HttpServletResponse response = new MockHttpServletResponse();
+ PolicyRestAdapter policyData = new PolicyRestAdapter();
+ policyData.setPolicyType("Config");
+ policyData.setConfigPolicyType("ClosedLoop_Fault");
+ policyData.setDomainDir("domain");
+ policyData.setPolicyName("policyname");
+ ResponseEntity<String> responseEntity = creation.savePolicy(policyData, response);
+ assertThat(responseEntity).isNotNull();
+
+ version.setHigherVersion(1);
+ responseEntity = creation.savePolicy(policyData, response);
+ assertThat(responseEntity).isNotNull();
+
+ policyData.setEditPolicy(true);
+ responseEntity = creation.savePolicy(policyData, response);
+ assertThat(responseEntity).isNotNull();
+
+ policyData.setEditPolicy(false);
+ version.setHigherVersion(0);
+ responseEntity = creation.savePolicy(policyData, response);
+ assertThat(responseEntity).isNotNull();
+
+ policyData.setEditPolicy(true);
+ responseEntity = creation.savePolicy(policyData, response);
+ assertThat(responseEntity).isNotNull();
+
+ version.setHigherVersion(1);
+ policyData.setConfigPolicyType("Firewall Config");
+ responseEntity = creation.savePolicy(policyData, response);
+ assertThat(responseEntity).isNotNull();
+
+ policyData.setConfigPolicyType("BRMS_Raw");
+ responseEntity = creation.savePolicy(policyData, response);
+ assertThat(responseEntity).isNotNull();
+
+ policyData.setConfigPolicyType("BRMS_Param");
+ responseEntity = creation.savePolicy(policyData, response);
+ assertThat(responseEntity).isNotNull();
+
+ policyData.setConfigPolicyType("Base");
+ Mockito.when(policyData.getRuleData()).thenReturn(new LinkedHashMap<>());
+
+ SessionFactory mockSessionFactory = Mockito.mock(SessionFactory.class);
+ Session mockSession = Mockito.mock(Session.class);
+ Criteria mockCriteria = Mockito.mock(Criteria.class);
+ List<?> policyDbDaoEntityList = new LinkedList<>();
+
+ Mockito.when(mockSessionFactory.openSession()).thenReturn(mockSession);
+ Mockito.when(mockSession.createCriteria(PolicyDbDaoEntity.class)).thenReturn(mockCriteria);
+ Mockito.when(mockCriteria.list()).thenReturn(policyDbDaoEntityList);
+ Whitebox.setInternalState(PolicyDbDao.class, "sessionfactory", mockSessionFactory);
+
+ PolicyDbDao mockPolicyDbDao = Mockito.mock(PolicyDbDao.class);
+ PolicyDbDaoTransaction mockTransaction = Mockito.mock(PolicyDbDaoTransaction.class);
+ Mockito.when(mockPolicyDbDao.getNewTransaction()).thenReturn(mockTransaction);
+
+ responseEntity = creation.savePolicy(policyData, response);
+ assertThat(responseEntity).isNotNull();
+
+ policyData.setConfigPolicyType("ClosedLoop_PM");
+ responseEntity = creation.savePolicy(policyData, response);
+ assertThat(responseEntity).isNotNull();
+
+ policyData.setConfigPolicyType("Micro Service");
+ responseEntity = creation.savePolicy(policyData, response);
+ assertThat(responseEntity).isNotNull();
+
+ policyData.setConfigPolicyType("Optimization");
+ responseEntity = creation.savePolicy(policyData, response);
+ assertThat(responseEntity).isNotNull();
+
+ policyData.setPolicyType("Action");
+ List<Object> choices = new ArrayList<>();
+ policyData.setRuleAlgorithmschoices(choices);
+ responseEntity = creation.savePolicy(policyData, response);
+ assertThat(responseEntity).isNotNull();
+
+ policyData.setPolicyType("Decision");
+ List<Object> settings = new ArrayList<>();
+ policyData.setSettings(settings);
+ responseEntity = creation.savePolicy(policyData, response);
+ assertThat(responseEntity).isNotNull();
+ }
+}
diff --git a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/service/ImportServiceTest.java b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/service/ImportServiceTest.java
index ba400dfc0..cee67dd51 100644
--- a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/service/ImportServiceTest.java
+++ b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/service/ImportServiceTest.java
@@ -2,14 +2,14 @@
* ============LICENSE_START=======================================================
* ONAP-PAP-REST
* ================================================================================
- * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2018-2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -20,12 +20,18 @@
package org.onap.policy.pap.xacml.rest.service;
+import static org.assertj.core.api.Assertions.assertThatCode;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.junit.Assert.assertEquals;
+import com.mockrunner.mock.web.MockHttpServletRequest;
+import com.mockrunner.mock.web.MockHttpServletResponse;
+import java.io.File;
+import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
+import org.apache.commons.io.FileUtils;
+import org.junit.AfterClass;
import org.junit.Test;
-import com.mockrunner.mock.web.MockHttpServletRequest;
-import com.mockrunner.mock.web.MockHttpServletResponse;
public class ImportServiceTest {
@Test
@@ -34,6 +40,50 @@ public class ImportServiceTest {
HttpServletRequest request = new MockHttpServletRequest();
HttpServletResponse response = new MockHttpServletResponse();
service.doImportMicroServicePut(request, response);
- assertEquals(response.getHeader("error"), "missing");
+ assertEquals("missing", response.getHeader("error"));
+ }
+
+ @Test
+ public void testImportBRMS() {
+ ImportService service = new ImportService();
+ MockHttpServletRequest request = new MockHttpServletRequest();
+ request.setupAddParameter("serviceName", "serviceName");
+ request.setupAddParameter("importService", "BRMSPARAM");
+ request.setBodyContent("foo");
+ HttpServletResponse response = new MockHttpServletResponse();
+ assertThatCode(() -> service.doImportMicroServicePut(request, response)).doesNotThrowAnyException();
+ }
+
+ @Test
+ public void testImportMS() {
+ ImportService service = new ImportService();
+ MockHttpServletRequest request = new MockHttpServletRequest();
+ request.setupAddParameter("serviceName", "serviceName");
+ request.setupAddParameter("importService", "MICROSERVICE");
+ request.setupAddParameter("fileName", "fileName");
+ request.setBodyContent("foo");
+ HttpServletResponse response = new MockHttpServletResponse();
+ assertThatThrownBy(() -> service.doImportMicroServicePut(request, response)).isInstanceOf(Exception.class);
+ }
+
+ @Test
+ public void testImportOpt() {
+ ImportService service = new ImportService();
+ MockHttpServletRequest request = new MockHttpServletRequest();
+ request.setupAddParameter("serviceName", "serviceName");
+ request.setupAddParameter("importService", "OPTIMIZATION");
+ request.setupAddParameter("fileName", "fileName");
+ request.setBodyContent("foo");
+ HttpServletResponse response = new MockHttpServletResponse();
+ assertThatThrownBy(() -> service.doImportMicroServicePut(request, response)).isInstanceOf(Exception.class);
+ }
+
+ @AfterClass
+ public static void tearDown(){
+ try {
+ FileUtils.deleteDirectory(new File("ExtractDir"));
+ } catch (IOException e) {
+ e.printStackTrace();
+ }
}
}
diff --git a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/service/MetricServiceTest.java b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/service/MetricServiceTest.java
index c90e59bf6..8136c8329 100644
--- a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/service/MetricServiceTest.java
+++ b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/service/MetricServiceTest.java
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP-PAP-REST
* ================================================================================
- * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2018-2020 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -21,17 +21,27 @@
package org.onap.policy.pap.xacml.rest.service;
import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
import static org.mockito.Mockito.when;
+
import com.mockrunner.mock.web.MockHttpServletResponse;
+import java.util.ArrayList;
+import java.util.List;
import javax.servlet.http.HttpServletResponse;
import org.junit.Test;
import org.junit.runner.RunWith;
+import org.mockito.Mockito;
import org.onap.policy.pap.xacml.rest.XACMLPapServlet;
+import org.onap.policy.rest.dao.CommonClassDao;
+import org.onap.policy.rest.jpa.PolicyVersion;
import org.powermock.api.mockito.PowerMockito;
+import org.powermock.core.classloader.annotations.PowerMockIgnore;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
@RunWith(PowerMockRunner.class)
+@PowerMockIgnore({"com.sun.org.apache.xerces.*", "jdk.internal.reflect.*", "javax.xml.*", "org.xml.*", "org.w3c.*"})
+@PrepareForTest(CommonClassDao.class)
public class MetricServiceTest {
@PrepareForTest({XACMLPapServlet.class})
@Test
@@ -42,6 +52,19 @@ public class MetricServiceTest {
MockHttpServletResponse response = new MockHttpServletResponse();
MetricService.doGetPolicyMetrics(response);
- assertEquals(response.getStatusCode(), HttpServletResponse.SC_BAD_REQUEST);
+ assertEquals(HttpServletResponse.SC_BAD_REQUEST, response.getStatusCode());
+ }
+
+ @Test
+ public void testService() {
+ CommonClassDao dao = Mockito.mock(CommonClassDao.class);
+ List<Object> value = new ArrayList<Object>();
+ when(dao.getData(PolicyVersion.class)).thenReturn(value);
+ MetricService service = new MetricService(dao);
+ assertNotNull(service);
+
+ MockHttpServletResponse response = new MockHttpServletResponse();
+ MetricService.doGetPolicyMetrics(response);
+ assertEquals(HttpServletResponse.SC_BAD_REQUEST, response.getStatusCode());
}
}
diff --git a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/util/JPAUtilsTest.java b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/util/JPAUtilsTest.java
index ad8f86c59..6c83dcd1c 100644
--- a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/util/JPAUtilsTest.java
+++ b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/util/JPAUtilsTest.java
@@ -22,8 +22,9 @@
package org.onap.policy.pap.xacml.rest.util;
-import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
import static org.junit.Assert.fail;
+
import org.junit.BeforeClass;
import org.junit.Test;
import org.onap.policy.pap.xacml.rest.components.PolicyDBDaoTest;
@@ -41,7 +42,7 @@ public class JPAUtilsTest {
// Test lockdown
JPAUtils utils = JPAUtils.getJPAUtilsInstance();
- assertEquals(utils.dbLockdownIgnoreErrors(), false);
+ assertFalse(utils.dbLockdownIgnoreErrors());
utils.dbLockdown();
fail("Expecting an exception");
}
diff --git a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/util/JsonMessageTest.java b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/util/JsonMessageTest.java
index e3a575456..fd96451f3 100644
--- a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/util/JsonMessageTest.java
+++ b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/util/JsonMessageTest.java
@@ -2,16 +2,16 @@
* ============LICENSE_START=======================================================
* ONAP-PAP-REST
* ================================================================================
- * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2018-2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Modifications Copyright (C) 2019 Samsung
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -23,6 +23,7 @@
package org.onap.policy.pap.xacml.rest.util;
import static org.junit.Assert.assertEquals;
+
import org.junit.Test;
public class JsonMessageTest {
diff --git a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/restAuth/AuthenticationServiceTest.java b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/restAuth/AuthenticationServiceTest.java
index cbe9ff250..f84f41e5f 100644
--- a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/restAuth/AuthenticationServiceTest.java
+++ b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/restAuth/AuthenticationServiceTest.java
@@ -2,14 +2,14 @@
* ============LICENSE_START=======================================================
* ONAP-PAP-REST
* ================================================================================
- * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2018-2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -17,11 +17,14 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.policy.pap.xacml.restAuth;
import static org.junit.Assert.assertEquals;
+
import java.io.UnsupportedEncodingException;
import java.util.Base64;
+
import org.junit.Test;
import org.onap.policy.pap.xacml.restAuth.AuthenticationService;
@@ -44,8 +47,7 @@ public class AuthenticationServiceTest {
// Restore the original system property
if (oldProperty != null) {
System.setProperty(systemKey, oldProperty);
- }
- else {
+ } else {
System.clearProperty(systemKey);
}
}
diff --git a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/restAuth/PAPAuthenticationFilterTest.java b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/restAuth/PAPAuthenticationFilterTest.java
index f1554e84c..c358a85ad 100644
--- a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/restAuth/PAPAuthenticationFilterTest.java
+++ b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/restAuth/PAPAuthenticationFilterTest.java
@@ -2,14 +2,14 @@
* ============LICENSE_START=======================================================
* ONAP-PDP-REST
* ================================================================================
- * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2018-2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -17,11 +17,15 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.policy.pap.xacml.restAuth;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
+import com.mockrunner.mock.web.MockHttpServletRequest;
+import com.mockrunner.mock.web.MockHttpServletResponse;
+
import java.io.IOException;
import javax.servlet.FilterChain;
@@ -34,9 +38,6 @@ import org.junit.Before;
import org.junit.Test;
import org.mockito.Mockito;
-import com.mockrunner.mock.web.MockHttpServletRequest;
-import com.mockrunner.mock.web.MockHttpServletResponse;
-
public class PAPAuthenticationFilterTest {
private HttpServletRequest request = null;
@@ -47,7 +48,7 @@ public class PAPAuthenticationFilterTest {
private PAPAuthenticationFilter papFilter;
@Before
- public void setUp(){
+ public void setUp() {
// Set the system property temporarily
oldProperty = System.getProperty(systemKey);
System.setProperty(systemKey, "xacml.pap.properties");
@@ -74,8 +75,7 @@ public class PAPAuthenticationFilterTest {
try {
filter.destroy();
filter.init(null);
- }
- catch (Exception ex) {
+ } catch (Exception ex) {
fail("Not expecting any exceptions.");
}
}
@@ -89,7 +89,7 @@ public class PAPAuthenticationFilterTest {
callDoFilter();
}
- public void callDoFilter(){
+ public void callDoFilter() {
try {
papFilter.doFilter(request, response, filter);
} catch (Exception e) {
@@ -98,7 +98,7 @@ public class PAPAuthenticationFilterTest {
}
@Test
- public void testOnPassingInvalidParamters(){
+ public void testOnPassingInvalidParamters() {
Mockito.when(request.getRequestURI()).thenReturn("/pap/");
Mockito.when(request.getHeader("Authorization")).thenReturn("Basic dGVzdHBhcDphbHBoYTE789==");
try {
@@ -110,7 +110,7 @@ public class PAPAuthenticationFilterTest {
}
@After
- public void reset(){
+ public void reset() {
// Restore the original system property
if (oldProperty != null) {
System.setProperty(systemKey, oldProperty);
diff --git a/ONAP-PAP-REST/src/test/resources/dictionaryImport/PEPOptions.csv b/ONAP-PAP-REST/src/test/resources/dictionaryImport/PepOptions.csv
index 61adca140..61adca140 100644
--- a/ONAP-PAP-REST/src/test/resources/dictionaryImport/PEPOptions.csv
+++ b/ONAP-PAP-REST/src/test/resources/dictionaryImport/PepOptions.csv
diff --git a/ONAP-PAP-REST/src/test/resources/log4j.properties b/ONAP-PAP-REST/src/test/resources/log4j.properties
new file mode 100644
index 000000000..e498777bb
--- /dev/null
+++ b/ONAP-PAP-REST/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-REST/pom.xml b/ONAP-PDP-REST/pom.xml
index ef76cc036..15b6702b7 100644
--- a/ONAP-PDP-REST/pom.xml
+++ b/ONAP-PDP-REST/pom.xml
@@ -23,7 +23,7 @@
<parent>
<groupId>org.onap.policy.engine</groupId>
<artifactId>PolicyEngineSuite</artifactId>
- <version>1.4.1-SNAPSHOT</version>
+ <version>1.6.4-SNAPSHOT</version>
</parent>
<artifactId>ONAP-PDP-REST</artifactId>
<description>ONAP PDP REST</description>
@@ -48,6 +48,12 @@
<groupId>org.onap.policy.engine</groupId>
<artifactId>ONAP-PDP</artifactId>
<version>${project.version}</version>
+ <exclusions>
+ <exclusion>
+ <groupId>xml-apis</groupId>
+ <artifactId>xml-apis</artifactId>
+ </exclusion>
+ </exclusions>
</dependency>
<dependency>
<groupId>commons-logging</groupId>
@@ -87,7 +93,6 @@
<dependency>
<groupId>org.awaitility</groupId>
<artifactId>awaitility</artifactId>
- <version>3.0.0</version>
<scope>test</scope>
</dependency>
<dependency>
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
index 0fab3db61..237ed9334 100644
--- 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
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -31,7 +31,7 @@ import java.util.Objects;
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.rest.XacmlRestProperties;
import org.onap.policy.utils.PeCryptoUtils;
public class PapUrlResolver {
@@ -96,12 +96,12 @@ public class PapUrlResolver {
String papUrlFailedList = failedList;
String papUrlSuccessList = succeededList;
if (papUrlLists == null) {
- papUrlLists = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_URLS);
+ papUrlLists = XACMLProperties.getProperty(XacmlRestProperties.PROP_PAP_URLS);
if (papUrlLists == null) {
- papUrlLists = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_URL);
+ papUrlLists = XACMLProperties.getProperty(XacmlRestProperties.PROP_PAP_URL);
}
- papUrlFailedList = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_FAILED_URLS);
- papUrlSuccessList = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_SUCCEEDED_URLS);
+ papUrlFailedList = XACMLProperties.getProperty(XacmlRestProperties.PROP_PAP_FAILED_URLS);
+ papUrlSuccessList = XACMLProperties.getProperty(XacmlRestProperties.PROP_PAP_SUCCEEDED_URLS);
}
String[] urls = papUrlLists.split(",");
@@ -116,12 +116,12 @@ public class PapUrlResolver {
String userId = null;
String pass = null;
- userId = XACMLProperties.getProperty(urls[i] + "." + XACMLRestProperties.PROP_PAP_USERID);
+ userId = XACMLProperties.getProperty(urls[i] + "." + XacmlRestProperties.PROP_PAP_USERID);
pass = XACMLProperties.getProperty(urls[i] + "."
- + PeCryptoUtils.decrypt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_PASS)));
+ + PeCryptoUtils.decrypt(XACMLProperties.getProperty(XacmlRestProperties.PROP_PAP_PASS)));
if (userId == null || pass == null) {
- userId = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_USERID);
- pass = PeCryptoUtils.decrypt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_PASS));
+ userId = XACMLProperties.getProperty(XacmlRestProperties.PROP_PAP_USERID);
+ pass = PeCryptoUtils.decrypt(XACMLProperties.getProperty(XacmlRestProperties.PROP_PAP_PASS));
}
if (userId == null || pass == null) {
userId = "";
@@ -216,9 +216,9 @@ public class PapUrlResolver {
failedPropertyString = failedPropertyString.substring(1);
succeededPropertyString = succeededPropertyString.substring(1);
urlPropertyString = urlPropertyString.substring(1);
- prop.setProperty(XACMLRestProperties.PROP_PAP_FAILED_URLS, failedPropertyString);
- prop.setProperty(XACMLRestProperties.PROP_PAP_URLS, urlPropertyString);
- prop.setProperty(XACMLRestProperties.PROP_PAP_SUCCEEDED_URLS, succeededPropertyString);
+ prop.setProperty(XacmlRestProperties.PROP_PAP_FAILED_URLS, failedPropertyString);
+ prop.setProperty(XacmlRestProperties.PROP_PAP_URLS, urlPropertyString);
+ prop.setProperty(XacmlRestProperties.PROP_PAP_SUCCEEDED_URLS, succeededPropertyString);
return prop;
}
@@ -229,12 +229,12 @@ public class PapUrlResolver {
}
Properties prop = getProperties();
- LOGGER.debug("Failed PAP Url List: " + prop.getProperty(XACMLRestProperties.PROP_PAP_FAILED_URLS));
- LOGGER.debug("Succeeded PAP Url List: " + prop.getProperty(XACMLRestProperties.PROP_PAP_SUCCEEDED_URLS));
- XACMLProperties.setProperty(XACMLRestProperties.PROP_PAP_FAILED_URLS,
- prop.getProperty(XACMLRestProperties.PROP_PAP_FAILED_URLS));
- XACMLProperties.setProperty(XACMLRestProperties.PROP_PAP_SUCCEEDED_URLS,
- prop.getProperty(XACMLRestProperties.PROP_PAP_SUCCEEDED_URLS));
+ LOGGER.debug("Failed PAP Url List: " + prop.getProperty(XacmlRestProperties.PROP_PAP_FAILED_URLS));
+ LOGGER.debug("Succeeded PAP Url List: " + prop.getProperty(XacmlRestProperties.PROP_PAP_SUCCEEDED_URLS));
+ XACMLProperties.setProperty(XacmlRestProperties.PROP_PAP_FAILED_URLS,
+ prop.getProperty(XacmlRestProperties.PROP_PAP_FAILED_URLS));
+ XACMLProperties.setProperty(XacmlRestProperties.PROP_PAP_SUCCEEDED_URLS,
+ prop.getProperty(XacmlRestProperties.PROP_PAP_SUCCEEDED_URLS));
}
// iterates to the next available PAP url, according to the priority order
@@ -333,7 +333,7 @@ public class PapUrlResolver {
// property)
private Date setHandler(Object time) {
if (time instanceof String) {
- if ("-1".equals((String) time)) {
+ if ("-1".equals(time)) {
return null;
}
try {
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
index 102d43f0c..9fd655194 100644
--- 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
@@ -3,13 +3,14 @@
* ONAP-PDP-REST
* ================================================================================
* Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2019 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -20,6 +21,22 @@
package org.onap.policy.pdp.rest;
+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 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;
+
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
@@ -39,602 +56,608 @@ 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.pdp.rest.notifications.NotificationController;
+import org.onap.policy.rest.XacmlRest;
+import org.onap.policy.rest.XacmlRestProperties;
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.
- *
- *
- *
+ * 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();
+ private static final Logger LOGGER = FlexLogger.getLogger(XACMLPdpLoader.class);
+
+ // Repeated string constants.
+ private static final String DOES_NOT_EXIST = " does NOT exist.";
+ private static final String CORRUPTED_POLICY_FILE_DELETING = "Corrupted policy file, deleting: ";
+ private static final String DOT_FILE = ".file";
+
+ 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 "<PolicyId>.file" properties for files existing
+ // local
+ //
+ LOGGER.info("XACMLPdpLoader: cache the policies.");
+ XACMLPdpLoader.cachePolicies(policyProperties);
+ //
+ // Validate the policies
+ //
+ LOGGER.info("XACMLPdpLoader: validating 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);
+ }
+ return engine;
+ }
+ private static HashMap<String, PolicyDef> policyContainer = null;
- 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);
- }
- }
+ /**
+ * Thread for sending notifications.
+ */
+ public static synchronized void sendNotification() {
+ Thread notify = new Thread() {
+ @Override
+ public void run() {
+ try {
+ Thread.sleep(notifyDelay);
+ NotificationController.sendNotification();
+ } catch (Exception e) {
+ LOGGER.error(XACMLErrorConstants.ERROR_UNKNOWN + e);
+ }
+ }
+ };
+ notify.start();
+ }
- //
- // Get our policy cache up-to-date
- //
- // Side effects of this include:
- // - downloading of policies from remote locations, and
- // - creating new "<PolicyId>.file" properties for files existing
- // local
- //
- LOGGER.info("XACMLPdpLoader: cache the policies.");
- XACMLPdpLoader.cachePolicies(policyProperties);
- //
- // Validate the policies
- //
- LOGGER.info("XACMLPdpLoader: validating 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);
- }
- return engine;
- }
+ /**
+ * Method to validate policies.
+ *
+ * @param properties The properties of the policies
+ * @param status the PDP status
+ * @throws PAPException on validation errors
+ */
+ public static synchronized void validatePolicies(Properties properties, StdPDPStatus status) throws PAPException {
+ Set<String> rootPolicies = XACMLProperties.getRootPolicyIDs(properties);
+ policyContainer = new HashMap<>();
- private static HashMap<String, PolicyDef> policyContainer = null;
-
- public static synchronized 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<String> rootPolicies = XACMLProperties.getRootPolicyIDs(properties);
- Set<String> refPolicies = XACMLProperties
- .getReferencedPolicyIDs(properties);
- policyContainer = new HashMap<String, PolicyDef>();
+ LOGGER.info("XACMLPdpLoader: load rootPolicies");
+ for (String id : rootPolicies) {
+ loadPolicy(properties, status, id, true);
+ }
+ // remember which policies were root policies
+ status.addAllLoadedRootPolicies(status.getLoadedPolicies());
+ LOGGER.info("XACMLPdpLoader: load referencedPolicies");
+ Set<String> refPolicies = XACMLProperties.getReferencedPolicyIDs(properties);
+ 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().isEmpty()) {
+ 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();
+ }
- LOGGER.info("XACMLPdpLoader: load rootPolicies");
- for (String id : rootPolicies) {
- loadPolicy(properties, status, id, true);
- }
- // remember which policies were root policies
- status.addAllLoadedRootPolicies(status.getLoadedPolicies());
- LOGGER.info("XACMLPdpLoader: load referencedPolicies");
- 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();
- }
+ /**
+ * Load a policy.
+ *
+ * @param properties the policy properties
+ * @param status the PDP status
+ * @param id the policy ID
+ * @param isRoot indicates if operation being done as root
+ * @throws PAPException on loading errors
+ */
+ 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 + DOT_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 + DOT_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();
+ 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;
+ }
+ String encoding =
+ encoder.encodeToString((papID + ":" + papPass).getBytes(StandardCharsets.UTF_8));
+ 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 + DOT_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));
-
- 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);
- }
- }
- }
- }
+ } 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);
- }
- }
+ /**
+ * Validate PIP configuration.
+ *
+ * @param properties the properties to validate
+ * @param status the PDP status
+ * @throws PAPException on validation exceptions
+ */
+ 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 "&lt;PolicyID&gt;.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 "&lt;PolicyID&gt;.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<String> policies = Splitter.on(',').trimResults()
- .omitEmptyStrings().split(list);
- for (String policy : policies) {
- boolean policyExists = false;
+ /**
+ * 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 "&lt;PolicyID&gt;.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 "&lt;PolicyID&gt;.url" property and try to GET the policy from that location (and set the
+ * ".file" property)
+ *
+ * <p>If the ".file" property is created, then true is returned to tell the caller that the props object changed.
+ *
+ * @param props the properties to cache
+ * @return true/false if anything was changed in the props object
+ * @throws PAPException on cacheing exceptions
+ */
+ 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<String> 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.");
- }
- }
+ // 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 = Paths.get(propLocation).toFile().exists();
+ if (!policyExists) {
+ 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 {
+ // 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) {
+ //
+ // 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 = outFile.toFile().exists();
+ 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)
+ // 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 (MalformedURLException e) {
- papUrls.failed();
- LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Policy '" + policy
- + "' had bad URL in new configuration, URL='" + propLocation + "'");
- } catch (Exception e) {
- papUrls.failed();
- 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;
- }
+ //
+ // 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 (MalformedURLException e) {
+ papUrls.failed();
+ LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Policy '" + policy
+ + "' had bad URL in new configuration, URL='" + propLocation + "'");
+ } catch (Exception e) {
+ papUrls.failed();
+ 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;
- }
+ /**
+ * Get the PDP policy cache.
+ *
+ * @return the PDP policy cache
+ * @throws PAPException on cache get errors
+ */
+ public static synchronized Path getPDPPolicyCache() throws PAPException {
+ Path config = getPDPConfig();
+ Path policyProperties = Paths.get(config.toAbsolutePath().toString(), "xacml.policy.properties");
+ if (!policyProperties.toFile().exists()) {
+ 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;
- }
+ /**
+ * Get the PIP configuration.
+ *
+ * @return the PIP configuration
+ * @throws PAPException on get exceptions
+ */
+ public static synchronized Path getPIPConfig() throws PAPException {
+ Path config = getPDPConfig();
+ Path pipConfigProperties = Paths.get(config.toAbsolutePath().toString(), "xacml.pip.properties");
+ if (!pipConfigProperties.toFile().exists()) {
+ 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;
- }
+ /**
+ * Get the PDP configuration.
+ *
+ * @return the PDP configuration
+ * @throws PAPException on get exceptions
+ */
+ public static synchronized Path getPDPConfig() throws PAPException {
+ Path config = Paths.get(XACMLProperties.getProperty(XacmlRestProperties.PROP_PDP_CONFIG));
+ if (!config.toFile().exists()) {
+ 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
index b33c4bd16..56d82bd3f 100644
--- 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
@@ -2,15 +2,15 @@
* ============LICENSE_START=======================================================
* ONAP-PDP-REST
* ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017, 2019 AT&T Intellectual Property. All rights reserved.
* Modified Copyright (C) 2018 Samsung Electronics Co., Ltd.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -37,25 +37,25 @@ 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.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.OnapLoggingContext;
import org.onap.policy.common.logging.eelf.PolicyLogger;
-import org.onap.policy.common.logging.flexlogger.*;
+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;
+ private OnapLoggingContext baseLoggingContext = null;
public volatile boolean isRunning = false;
- public XACMLPdpRegisterThread(ONAPLoggingContext baseLoggingContext) {
+ public XACMLPdpRegisterThread(OnapLoggingContext baseLoggingContext) {
this.baseLoggingContext = baseLoggingContext;
}
@@ -78,7 +78,7 @@ public class XACMLPdpRegisterThread implements Runnable {
this.isRunning = true;
}
// get a new logging context for the thread
- ONAPLoggingContext loggingContext = new ONAPLoggingContext(baseLoggingContext);
+ OnapLoggingContext loggingContext = new OnapLoggingContext(baseLoggingContext);
loggingContext.setServiceName("PDP:PAP.register");
//are we registered with at least one
boolean registered = false;
@@ -86,7 +86,7 @@ public class XACMLPdpRegisterThread implements Runnable {
/*
int seconds;
try {
- seconds = Integer.parseInt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PDP_REGISTER_SLEEP));
+ seconds = Integer.parseInt(XACMLProperties.getProperty(XacmlRestProperties.PROP_PDP_REGISTER_SLEEP));
} catch (NumberFormatException e) {
LOGGER.error( XACMLErrorConstants.ERROR_SYSTEM_ERROR +"REGISTER_SLEEP: ", e);
seconds = 5;
@@ -96,7 +96,7 @@ public class XACMLPdpRegisterThread implements Runnable {
}
int retries;
try {
- retries = Integer.parseInt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PDP_REGISTER_RETRIES));
+ retries = Integer.parseInt(XACMLProperties.getProperty(XacmlRestProperties.PROP_PDP_REGISTER_RETRIES));
} catch (NumberFormatException e) {
LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR +" REGISTER_SLEEP: ", e);
retries = -1;
@@ -124,13 +124,13 @@ public class XACMLPdpRegisterThread implements Runnable {
// each time through the inner loop (which handles redirects) is a
// continuation of the same transaction.
UUID requestID = UUID.randomUUID();
- loggingContext.setRequestID(requestID.toString());
+ 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 papUrlList = XACMLProperties.getProperty(XacmlRestProperties.PROP_PAP_URL);
//String[] papUrls = papUrlList.split(",");
//PapUrlResolver.setPapUrls(papUrls);
URL url = new URL(papUrls.getUrl());
@@ -149,8 +149,8 @@ public class XACMLPdpRegisterThread implements Runnable {
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(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);
//
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
index c86e21c09..cae73ce29 100644
--- 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
@@ -20,17 +20,6 @@
package org.onap.policy.pdp.rest;
-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;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
@@ -64,17 +53,28 @@ import org.onap.policy.common.im.IntegrityMonitor;
import org.onap.policy.common.im.IntegrityMonitorException;
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.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.rest.XacmlRest;
+import org.onap.policy.rest.XacmlRestProperties;
import org.onap.policy.utils.PeCryptoUtils;
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
@@ -177,7 +177,7 @@ public class XACMLPdpServlet extends HttpServlet implements Runnable {
//
private static transient Thread configThread = null;
private static volatile boolean configThreadTerminate = false;
- private transient ONAPLoggingContext baseLoggingContext = null;
+ private transient OnapLoggingContext baseLoggingContext = null;
private transient IntegrityMonitor im;
public IntegrityMonitor getIm() {
@@ -205,7 +205,7 @@ public class XACMLPdpServlet extends HttpServlet implements Runnable {
//
// Initialize
//
- XACMLRest.xacmlInit(config);
+ XacmlRest.xacmlInit(config);
// Load the Notification Delay.
setNotificationDelay();
// Load Queue size. Not sure if we really need to have the queue bounded, we should look further into this
@@ -226,7 +226,7 @@ public class XACMLPdpServlet extends HttpServlet implements Runnable {
//
// Logging stuff....
//
- baseLoggingContext = new ONAPLoggingContext();
+ baseLoggingContext = new OnapLoggingContext();
// fixed data that will be the same in all logging output goes here
try {
String hostname = InetAddress.getLocalHost().getCanonicalHostName();
@@ -243,7 +243,7 @@ public class XACMLPdpServlet extends HttpServlet implements Runnable {
"Error loading properties with: XACMLProperties.getProperties()");
throw new ServletException(e.getMessage(), e.getCause());
}
- if (properties.getProperty(XACMLRestProperties.PDP_RESOURCE_NAME) == null) {
+ if (properties.getProperty(XacmlRestProperties.PDP_RESOURCE_NAME) == null) {
XACMLProperties.reloadProperties();
try {
properties = XACMLProperties.getProperties();
@@ -269,7 +269,7 @@ public class XACMLPdpServlet extends HttpServlet implements Runnable {
properties.getProperty("createUpdatePolicy.impl.className", CREATE_UPDATE_POLICY_SERVICE);
setCreateUpdatePolicyConstructor(createUpdateResourceName);
- PeCryptoUtils.initAesKey(properties.getProperty(XACMLRestProperties.PROP_AES_KEY));
+ PeCryptoUtils.initAesKey(properties.getProperty(XacmlRestProperties.PROP_AES_KEY));
// Create an IntegrityMonitor
try {
@@ -281,7 +281,7 @@ public class XACMLPdpServlet extends HttpServlet implements Runnable {
PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "Failed to create IntegrityMonitor" + e);
throw new ServletException(e);
}
-
+
try {
System.setProperty("msToscaModel.home", properties.getProperty("msToscaModel.home"));
} catch (Exception e) {
@@ -291,12 +291,12 @@ public class XACMLPdpServlet extends HttpServlet implements Runnable {
startThreads(baseLoggingContext, new Thread(this));
}
- private static void startThreads(ONAPLoggingContext baseLoggingContext, Thread thread) {
+ private static void startThreads(OnapLoggingContext baseLoggingContext, Thread thread) {
environment = XACMLProperties.getProperty("ENVIRONMENT", "DEVL");
//
// Kick off our thread to register with the PAP servlet.
//
- if (Boolean.parseBoolean(XACMLProperties.getProperty(XACMLRestProperties.PROP_PDP_REGISTER))) {
+ if (Boolean.parseBoolean(XACMLProperties.getProperty(XacmlRestProperties.PROP_PDP_REGISTER))) {
XACMLPdpServlet.registerRunnable = new XACMLPdpRegisterThread(baseLoggingContext);
XACMLPdpServlet.registerThread = new Thread(XACMLPdpServlet.registerRunnable);
XACMLPdpServlet.registerThread.start();
@@ -321,9 +321,9 @@ public class XACMLPdpServlet extends HttpServlet implements Runnable {
}
private static void setPDPResourceName(Properties properties) throws ServletException {
- pdpResourceName = properties.getProperty(XACMLRestProperties.PDP_RESOURCE_NAME);
+ pdpResourceName = properties.getProperty(XacmlRestProperties.PDP_RESOURCE_NAME);
if (pdpResourceName == null) {
- PolicyLogger.error(MessageCodes.MISS_PROPERTY_ERROR, XACMLRestProperties.PDP_RESOURCE_NAME, "xacml.pdp");
+ PolicyLogger.error(MessageCodes.MISS_PROPERTY_ERROR, XacmlRestProperties.PDP_RESOURCE_NAME, "xacml.pdp");
throw new ServletException("pdpResourceName is null");
}
}
@@ -335,7 +335,7 @@ public class XACMLPdpServlet extends HttpServlet implements Runnable {
private static void setNotificationDelay() {
try {
XACMLPdpServlet.notificationDelay =
- Integer.parseInt(XACMLProperties.getProperty(XACMLRestProperties.PROP_NOTIFICATION_DELAY));
+ Integer.parseInt(XACMLProperties.getProperty(XacmlRestProperties.PROP_NOTIFICATION_DELAY));
} catch (NumberFormatException e) {
logger.error("Error in notification delay format, Taking the default value.", e);
}
@@ -426,11 +426,11 @@ public class XACMLPdpServlet extends HttpServlet implements Runnable {
@Override
protected void doPut(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
- ONAPLoggingContext loggingContext = ONAPLoggingUtils.getLoggingContextForRequest(request, baseLoggingContext);
+ OnapLoggingContext loggingContext = OnapLoggingUtils.getLoggingContextForRequest(request, baseLoggingContext);
loggingContext.transactionStarted();
- if ((loggingContext.getRequestID() == null) || "".equals(loggingContext.getRequestID())) {
+ if ((loggingContext.getRequestId() == null) || "".equals(loggingContext.getRequestId())) {
UUID requestID = UUID.randomUUID();
- loggingContext.setRequestID(requestID.toString());
+ 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)");
@@ -445,7 +445,7 @@ public class XACMLPdpServlet extends HttpServlet implements Runnable {
// Dump our request out
//
if (logger.isDebugEnabled()) {
- XACMLRest.dumpRequest(request);
+ XacmlRest.dumpRequest(request);
}
try {
@@ -509,7 +509,7 @@ public class XACMLPdpServlet extends HttpServlet implements Runnable {
}
protected void doPutConfig(String config, HttpServletRequest request, HttpServletResponse response,
- ONAPLoggingContext loggingContext) throws IOException {
+ OnapLoggingContext loggingContext) throws IOException {
try {
// prevent multiple configuration changes from stacking up
logger.info("XACMLPdpServlet: checking remainingCapacity of Queue.");
@@ -642,11 +642,11 @@ public class XACMLPdpServlet extends HttpServlet implements Runnable {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
- ONAPLoggingContext loggingContext = ONAPLoggingUtils.getLoggingContextForRequest(request, baseLoggingContext);
+ OnapLoggingContext loggingContext = OnapLoggingUtils.getLoggingContextForRequest(request, baseLoggingContext);
loggingContext.transactionStarted();
- if ((loggingContext.getRequestID() == null) || (loggingContext.getRequestID() == "")) {
+ if ((loggingContext.getRequestId() == null) || (loggingContext.getRequestId() == "")) {
UUID requestID = UUID.randomUUID();
- loggingContext.setRequestID(requestID.toString());
+ 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)");
@@ -658,7 +658,7 @@ public class XACMLPdpServlet extends HttpServlet implements Runnable {
loggingContext.metricEnded();
PolicyLogger.metrics("Metric example posted here - 2 of 2");
- XACMLRest.dumpRequest(request);
+ XacmlRest.dumpRequest(request);
String pathInfo = request.getRequestURI();
if (pathInfo != null && "/pdp/test".equals(pathInfo)) {
@@ -805,7 +805,7 @@ public class XACMLPdpServlet extends HttpServlet implements Runnable {
}
if (returnHB) {
synchronized (pdpStatusLock) {
- response.addHeader(XACMLRestProperties.PROP_PDP_HTTP_HEADER_HB, status.getStatus().toString());
+ response.addHeader(XacmlRestProperties.PROP_PDP_HTTP_HEADER_HB, status.getStatus().toString());
}
}
loggingContext.transactionEnded();
@@ -825,12 +825,12 @@ public class XACMLPdpServlet extends HttpServlet implements Runnable {
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
- ONAPLoggingContext loggingContext = ONAPLoggingUtils.getLoggingContextForRequest(request, baseLoggingContext);
+ OnapLoggingContext loggingContext = OnapLoggingUtils.getLoggingContextForRequest(request, baseLoggingContext);
loggingContext.transactionStarted();
loggingContext.setServiceName("PDP.decide");
- if ((loggingContext.getRequestID() == null) || ("".equals(loggingContext.getRequestID()))) {
+ if ((loggingContext.getRequestId() == null) || ("".equals(loggingContext.getRequestId()))) {
UUID requestID = UUID.randomUUID();
- loggingContext.setRequestID(requestID.toString());
+ 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)");
@@ -876,7 +876,7 @@ public class XACMLPdpServlet extends HttpServlet implements Runnable {
return;
}
- XACMLRest.dumpRequest(request);
+ XacmlRest.dumpRequest(request);
//
// Set our no-cache header
//
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
index 44cc76478..1f0700f81 100644
--- 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
@@ -158,7 +158,7 @@ public class GetDictionaryService {
case "VNFType":
jsonString = jsonString.replace("vnfTypeDictionaryDatas", "DictionaryDatas");
break;
- case "PEPOptions":
+ case "PepOptions":
jsonString = jsonString.replace("pepOptionsDictionaryDatas", "DictionaryDatas");
break;
case "Varbind":
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
index d61b7c006..1d9e3e13f 100644
--- 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
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -39,7 +39,7 @@ 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.rest.XacmlRestProperties;
import org.onap.policy.utils.BusPublisher;
import org.onap.policy.xacml.api.XACMLErrorConstants;
import org.springframework.http.HttpStatus;
@@ -99,7 +99,7 @@ public class NotificationService {
private static void init() {
if (dmaapServers == null || aafLogin == null || aafPassword == null) {
- dmaapServers = XACMLProperties.getProperty(XACMLRestProperties.PROP_NOTIFICATION_SERVERS);
+ dmaapServers = XACMLProperties.getProperty(XacmlRestProperties.PROP_NOTIFICATION_SERVERS);
aafLogin = XACMLProperties.getProperty("DMAAP_AAF_LOGIN");
aafPassword = XACMLProperties.getProperty("DMAAP_AAF_PASSWORD");
interval =
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
index 822599f13..516d873d4 100644
--- 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
@@ -41,7 +41,7 @@ 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.restauth.AuthenticationService;
-import org.onap.policy.rest.XACMLRestProperties;
+import org.onap.policy.rest.XacmlRestProperties;
import org.onap.policy.utils.PeCryptoUtils;
import org.onap.policy.xacml.api.XACMLErrorConstants;
import org.onap.policy.xacml.std.pap.StdPDPPolicy;
@@ -67,9 +67,9 @@ public class PAPServices {
environment = AuthenticationService.getEnvironment();
if (paps == null) {
synchronized (papResourceLock) {
- String urlList = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_URLS);
+ String urlList = XACMLProperties.getProperty(XacmlRestProperties.PROP_PAP_URLS);
if (urlList == null) {
- urlList = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_URL);
+ urlList = XACMLProperties.getProperty(XacmlRestProperties.PROP_PAP_URL);
}
paps = Arrays.asList(urlList.split(","));
}
@@ -78,8 +78,8 @@ public class PAPServices {
private String getPAPEncoding() {
if (encoding == null) {
- String userID = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_USERID);
- String pass = PeCryptoUtils.decrypt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_PASS));
+ String userID = XACMLProperties.getProperty(XacmlRestProperties.PROP_PAP_USERID);
+ String pass = PeCryptoUtils.decrypt(XACMLProperties.getProperty(XacmlRestProperties.PROP_PAP_PASS));
Base64.Encoder encoder = Base64.getEncoder();
encoding = encoder.encodeToString((userID + ":" + pass).getBytes(StandardCharsets.UTF_8));
}
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
index e61bbd3aa..9a5fc5ef2 100644
--- 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
@@ -8,9 +8,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -70,7 +70,7 @@ 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.rest.XacmlRestProperties;
import org.onap.policy.std.Matches;
import org.onap.policy.xacml.api.XACMLErrorConstants;
import org.w3c.dom.Document;
@@ -207,7 +207,7 @@ public class PDPServices {
if (uri == 1) {
configUrl = attribute.getAttributeValue().getValue().toString();
pdpConfigLocation = configUrl.replace("$URL",
- XACMLProperties.getProperty(XACMLRestProperties.PROP_PDP_WEBAPPS));
+ XACMLProperties.getProperty(XacmlRestProperties.PROP_PDP_WEBAPPS));
} else {
if (!("PDP".equalsIgnoreCase(attribute.getIssuer()))) {
throw new PolicyException(XACMLErrorConstants.ERROR_DATA_ISSUE
@@ -350,7 +350,7 @@ public class PDPServices {
/**
* Process Decision Result.
- *
+ *
* @param result input from Response.
* @return pdpResposne based on result.
*/
@@ -388,7 +388,7 @@ public class PDPServices {
/**
* Check for Decision for decision based calls.
- *
+ *
* @param pdpResponseInput pdpResponse.
* @param result result.
* @return pdpResponse.
@@ -420,7 +420,7 @@ public class PDPServices {
/**
* Check if there is a configuration.
- *
+ *
* @param advice advice.
* @param configRetrieved boolean.
* @param pdpResponse pdpResposneInput.
@@ -431,7 +431,7 @@ public class PDPServices {
if (attribute.getDataTypeId().stringValue().endsWith("anyURI")) {
String configUrl = attribute.getAttributeValue().getValue().toString();
String pdpConfigLocation =
- configUrl.replace("$URL", XACMLProperties.getProperty(XACMLRestProperties.PROP_PDP_WEBAPPS));
+ configUrl.replace("$URL", XACMLProperties.getProperty(XacmlRestProperties.PROP_PDP_WEBAPPS));
// If there is a configuration.
try {
LOGGER.debug("processDecisionResult: Configuration Call to : " + configUrl);
@@ -615,7 +615,7 @@ public class PDPServices {
/**
* Returns the requestFormat.
- *
+ *
* @return the requestFormat.
*/
public String getRequestFormat() {
@@ -624,7 +624,7 @@ public class PDPServices {
/**
* Set the Request Format.
- *
+ *
* @param requestMode to set requestFormat.
*/
public void setRequestFormat(String requestMode) {
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
index 9027e27a5..9c75e1e38 100644
--- 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
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -31,7 +31,7 @@ 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.rest.XacmlRestProperties;
import org.onap.policy.utils.BusConsumer;
import org.onap.policy.utils.BusPublisher;
import org.onap.policy.xacml.api.XACMLErrorConstants;
@@ -67,9 +67,9 @@ public class ManualNotificationUpdateThread implements Runnable {
}
/**
- *
+ *
* This is our thread that runs on startup if the system is configured to UEB to accept manual update requests
- *
+ *
*/
@Override
public void run() {
@@ -85,7 +85,7 @@ public class ManualNotificationUpdateThread implements Runnable {
if ("ueb".equals(propNotificationType)) {
try {
setCluster();
- String url = XACMLProperties.getProperty(XACMLRestProperties.PROP_PDP_ID);
+ String url = XACMLProperties.getProperty(XacmlRestProperties.PROP_PDP_ID);
aURL = new URL(url);
topic = aURL.getHost() + aURL.getPort();
} catch (NumberFormatException e) {
@@ -129,8 +129,8 @@ public class ManualNotificationUpdateThread implements Runnable {
} else if ("dmaap".equals(propNotificationType)) {
String dmaapServers = null;
try {
- dmaapServers = XACMLProperties.getProperty(XACMLRestProperties.PROP_NOTIFICATION_SERVERS);
- topic = XACMLProperties.getProperty(XACMLRestProperties.PROP_NOTIFICATION_TOPIC);
+ dmaapServers = XACMLProperties.getProperty(XacmlRestProperties.PROP_NOTIFICATION_SERVERS);
+ topic = XACMLProperties.getProperty(XacmlRestProperties.PROP_NOTIFICATION_TOPIC);
setAAFCreds();
} catch (Exception e) {
LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Unable to get DMaaP servers list:", e);
@@ -145,7 +145,7 @@ public class ManualNotificationUpdateThread implements Runnable {
dmaapServers = dmaapServers.trim();
topic = topic.trim();
- String consumerTopic = XACMLProperties.getProperty(XACMLRestProperties.PROP_NOTIFICATION_TOPIC).trim();
+ String consumerTopic = XACMLProperties.getProperty(XacmlRestProperties.PROP_NOTIFICATION_TOPIC).trim();
sendMessage(consumerTopic, "Starting-Topic");
dmaapList = new ArrayList<>();
for (String u : dmaapServers.split(",")) {
@@ -189,14 +189,14 @@ public class ManualNotificationUpdateThread implements Runnable {
}
private static void setCluster() {
- clusterList = XACMLProperties.getProperty(XACMLRestProperties.PROP_NOTIFICATION_SERVERS);
+ clusterList = XACMLProperties.getProperty(XacmlRestProperties.PROP_NOTIFICATION_SERVERS);
if (clusterList != null) {
clusterList = clusterList.trim();
}
}
private static void setPropNotification() {
- propNotificationType = XACMLProperties.getProperty(XACMLRestProperties.PROP_NOTIFICATION_TYPE);
+ propNotificationType = XACMLProperties.getProperty(XacmlRestProperties.PROP_NOTIFICATION_TYPE);
}
private void sendMessage(String topic, String message) {
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
index c62872fbd..974ca5c01 100644
--- 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
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -44,7 +44,7 @@ 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.rest.XacmlRestProperties;
import org.onap.policy.xacml.api.XACMLErrorConstants;
import com.att.research.xacml.api.pap.PDPPolicy;
@@ -61,7 +61,7 @@ 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
*
*/
@@ -81,7 +81,7 @@ public class NotificationController {
private static Boolean notificationFlag = false;
public void check(PDPStatus newStatus, Map<String, PolicyDef> policyContainer) {
-
+
LOGGER.info("NotificationController: checking for updated and removed policies.");
boolean isUpdated = false;
boolean isRemoved = false;
@@ -101,7 +101,7 @@ public class NotificationController {
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.
LOGGER.info("NotificationController: check for updated or new policies");
for (PDPPolicy newPolicy : newStatus.getLoadedPolicies()) {
@@ -191,8 +191,8 @@ public class NotificationController {
}
private static void setPropNotification() {
- propNotificationType = XACMLProperties.getProperty(XACMLRestProperties.PROP_NOTIFICATION_TYPE);
- pdpURL = XACMLProperties.getProperty(XACMLRestProperties.PROP_PDP_ID);
+ propNotificationType = XACMLProperties.getProperty(XacmlRestProperties.PROP_NOTIFICATION_TYPE);
+ pdpURL = XACMLProperties.getProperty(XacmlRestProperties.PROP_PDP_ID);
}
public static void sendNotification() {
@@ -382,7 +382,7 @@ public class NotificationController {
private void removeFile(PDPPolicy oldPolicy) {
try {
- Path removedPolicyFile = Paths.get(XACMLProperties.getProperty(XACMLRestProperties.PROP_PDP_CONFIG)
+ Path removedPolicyFile = Paths.get(XACMLProperties.getProperty(XacmlRestProperties.PROP_PDP_CONFIG)
+ File.separator + oldPolicy.getId());
Files.deleteIfExists(removedPolicyFile);
boolean delete = false;
@@ -390,11 +390,11 @@ public class NotificationController {
if (oldPolicy.getName().contains(".Config_")) {
delete = true;
dir = new File(
- XACMLProperties.getProperty(XACMLRestProperties.PROP_PDP_WEBAPPS) + File.separator + "Config");
+ XACMLProperties.getProperty(XacmlRestProperties.PROP_PDP_WEBAPPS) + File.separator + "Config");
} else if (oldPolicy.getName().contains(".Action_")) {
delete = true;
dir = new File(
- XACMLProperties.getProperty(XACMLRestProperties.PROP_PDP_WEBAPPS) + File.separator + "Action");
+ XACMLProperties.getProperty(XacmlRestProperties.PROP_PDP_WEBAPPS) + File.separator + "Action");
}
if (delete) {
FileFilter fileFilter = new WildcardFileFilter(
@@ -412,7 +412,7 @@ public class NotificationController {
private void callPap(String urlString, String type) {
Path configLocation = Paths
- .get(XACMLProperties.getProperty(XACMLRestProperties.PROP_PDP_WEBAPPS) + File.separator + type);
+ .get(XACMLProperties.getProperty(XacmlRestProperties.PROP_PDP_WEBAPPS) + File.separator + type);
if (Files.notExists(configLocation)) {
try {
Files.createDirectories(configLocation);
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
index 4c2d1ef57..5c1162a7d 100644
--- 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
@@ -3,13 +3,14 @@
* ONAP-PDP-REST
* ================================================================================
* Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2019 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -20,6 +21,10 @@
package org.onap.policy.pdp.rest.notifications;
+import com.att.nsa.cambria.client.CambriaBatchingPublisher;
+import com.att.nsa.cambria.client.CambriaClientBuilders;
+import com.att.research.xacml.util.XACMLProperties;
+
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
@@ -44,184 +49,204 @@ 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.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.
- *
+ * 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<Session> queue = new ConcurrentLinkedQueue<>();
- private static String update = 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 PolicyEngineException, IOException, InterruptedException {
-
- LOGGER.debug("Notification set to " + propNotificationType);
- if (propNotificationType.equals("ueb")){
-
- String topic = null;
- try {
- URL 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 ");
- }
- String 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 PolicyEngineException(XACMLErrorConstants.ERROR_DATA_ISSUE + "UEB properties are missing from the property file ");
- }
-
- hosts = hosts.trim();
- topic = topic.trim();
- apiKey = apiKey.trim();
- apiSecret = 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 PolicyEngineException(XACMLErrorConstants.ERROR_DATA_ISSUE + "DMaaP properties are missing from the property file ");
- }
-
- dmaapServers= dmaapServers.trim();
- topic= topic.trim();
- aafLogin= aafLogin.trim();
- aafPassword= aafPassword.trim();
-
- List<String> 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 {
- LOGGER.info("\n Sending Notification: " + notification + " for client session id: " + session.getId() + "\n "
- + "PDPUrl is " + pdpURL);
- LOGGER.info("NotificationServer: sending text message");
- 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;
- }
-
+ private static final Logger LOGGER = FlexLogger.getLogger(NotificationServer.class);
+ private static Queue<Session> queue = new ConcurrentLinkedQueue<>();
+ private static String update = 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);
+ }
+
+ /**
+ * Error callback method.
+ * @param session The session on which the error occurs
+ * @param throwable exception thrown on the error callback
+ */
+ @OnError
+ public void error(Session session, Throwable throwable) {
+ queue.remove(session);
+ LOGGER.info(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Session Error for : " + session.getId() + " Error: "
+ + throwable.getMessage());
+ }
+
+ /**
+ * Message callback method.
+ * @param message the message on the callback
+ * @param session The session on which the error occurs
+ */
+ @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");
+ }
+ }
+ }
+
+ /**
+ * Send a notification.
+ * @param notification The notification type
+ * @param propNotificationType Notification type properties
+ * @param pdpUrl URL of the PDP
+ * @throws PolicyEngineException on errors from the policy engine
+ * @throws IOException exceptions on IO errors
+ * @throws InterruptedException interrupts
+ */
+ public static void sendNotification(String notification, String propNotificationType, String pdpUrl)
+ throws PolicyEngineException, IOException, InterruptedException {
+
+ LOGGER.debug("Notification set to " + propNotificationType);
+ if (propNotificationType.equals("ueb")) {
+
+ String topic = null;
+ try {
+ URL notificationUrl = new URL(pdpUrl);
+ topic = notificationUrl.getHost() + notificationUrl.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 ");
+ }
+ String 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 PolicyEngineException(XACMLErrorConstants.ERROR_DATA_ISSUE
+ + "UEB properties are missing from the property file ");
+ }
+
+ hosts = hosts.trim();
+ topic = topic.trim();
+ apiKey = apiKey.trim();
+ apiSecret = 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 PolicyEngineException(XACMLErrorConstants.ERROR_DATA_ISSUE
+ + "DMaaP properties are missing from the property file ");
+ }
+
+ dmaapServers = dmaapServers.trim();
+ topic = topic.trim();
+ aafLogin = aafLogin.trim();
+ aafPassword = aafPassword.trim();
+
+ List<String> 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 {
+ LOGGER.info("\n Sending Notification: " + notification + " for client session id: " + session.getId()
+ + "\n " + "PDPUrl is " + pdpUrl);
+ LOGGER.info("NotificationServer: sending text message");
+ 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/restauth/AuthenticationService.java b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/restauth/AuthenticationService.java
index 87a46aa23..54a5151c4 100644
--- 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
@@ -42,7 +42,7 @@ 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.rest.XacmlRestProperties;
import org.onap.policy.utils.AAFPolicyClient;
import org.onap.policy.utils.AAFPolicyException;
import org.onap.policy.utils.PeCryptoUtils;
@@ -66,7 +66,7 @@ public class AuthenticationService {
*/
private static void setProperty() {
environment = XACMLProperties.getProperty("ENVIRONMENT", "DEVL");
- String clientFile = XACMLProperties.getProperty(XACMLRestProperties.PROP_PEP_IDFILE);
+ String clientFile = XACMLProperties.getProperty(XacmlRestProperties.PROP_PEP_IDFILE);
if (clientFile != null) {
clientPath = Paths.get(clientFile);
}
diff --git a/ONAP-PDP-REST/src/main/resources/logback.xml b/ONAP-PDP-REST/src/main/resources/logback.xml
index 23f870d37..ef1e38dac 100644
--- a/ONAP-PDP-REST/src/main/resources/logback.xml
+++ b/ONAP-PDP-REST/src/main/resources/logback.xml
@@ -2,14 +2,14 @@
============LICENSE_START=======================================================
ONAP-PDP-REST
================================================================================
- Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
================================================================================
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
-
+
http://www.apache.org/licenses/LICENSE-2.0
-
+
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -22,73 +22,73 @@
<!--<jmxConfigurator /> -->
<!-- directory path for all other type logs -->
<property name="logDir" value="${POLICY_LOGS}" />
-
+
<!-- directory path for debugging type logs -->
<property name="debugDir" value="${POLICY_LOGS}" />
-
- <!-- specify the component name
+
+ <!-- specify the component name
<ONAP-component-name>::= "MSO" | "DCAE" | "ASDC " | "AAI" |"Policy" | "SDNC" | "AC" -->
<property name="componentName" value="policy"></property>
<property name="subComponentName" value="pdpx"></property>
-
+
<!-- log file names -->
<property name="errorLogName" value="error" />
<property name="metricsLogName" value="metrics" />
<property name="auditLogName" value="audit" />
<property name="debugLogName" value="debug" />
-
-
+
+
<!-- modified time stamp format -->
-
- <!-- A U D I T
- <property name="defaultAuditPattern" value="%X{BeginTimestamp}|%X{EndTimestamp}|%X{RequestId}|%X{ServiceInstanceId}|%thread|%X{ServerName}|%X{ServiceName}|%X{PartnerName}|%X{StatusCode}|%X{ResponseCode}|%X{ResponseDescription}|%X{InstanceUUID}|%.-5level|%X{AlertSeverity}|%X{ServerIPAddress}|%X{ElapsedTime}|%X{ServerFQDN}|%X{RemoteHost}|%X{ClassName}||%X{ProcessKey}|%X{TargetVirtualEntity}|%X{CustomField1}|%X{CustomField2}|%X{CustomField3}|%X{CustomField4}|%msg%n" />
+
+ <!-- A U D I T
+ <property name="defaultAuditPattern" value="%X{BeginTimestamp}|%X{EndTimestamp}|%X{RequestId}|%X{ServiceInstanceId}|%thread|%X{ServerName}|%X{ServiceName}|%X{PartnerName}|%X{StatusCode}|%X{ResponseCode}|%X{ResponseDescription}|%X{InstanceUUID}|%.-5level|%X{Severity}|%X{ServerIPAddress}|%X{ElapsedTime}|%X{ServerFQDN}|%X{RemoteHost}|%X{ClassName}||%X{ProcessKey}|%X{TargetVirtualEntity}|%X{CustomField1}|%X{CustomField2}|%X{CustomField3}|%X{CustomField4}|%msg%n" />
<property name="defaultAuditPattern" value="%X{BeginTimestamp}|%X{EndTimestamp}|%X{requestId}|%X{serviceInstanceId}|%t|%X{serverName}|%X{serviceName}|%X{PartnerName}|%X{StatusCode}|%X{ResponseCode}|%X{ResponseDescription}|%X{instanceUuid}|%p|%X{severity}|%X{serverIpAddress}|%X{ElapsedTime}|%X{server}|%X{clientIpAddress}|%c||%X{ProcessKey}|%X{TargetVirtualEntity}|%X{CustomField1}|%X{CustomField2}|%X{CustomField3}|%X{CustomField4}|%msg%n" />
-->
<property name="defaultAuditPattern" value="%X{TransactionBeginTimestamp}|%X{TransactionEndTimestamp}|%X{requestId}|%X{serviceInstanceId}|%t|%X{serverName}|%X{serviceName}|%X{partnerName}|%X{statusCode}|%X{ResponseCode}|%X{ResponseDescription}|%X{instanceUuid}|%p|%X{severity}|%X{serverIpAddress}|%X{TransactionElapsedTime}|%X{server}|%X{clientIpAddress}|%c||%X{ProcessKey}|%X{CustomField1}|%X{CustomField2}|%X{CustomField3}|%X{CustomField4}|%msg%n" />
-
-
-
- <!-- M E T R I C
- <property name="defaultMetricPattern" value="%X{BeginTimestamp}|%X{EndTimestamp}|%X{RequestId}|%X{ServiceInstanceId}|%thread|%X{ServerName}|%X{ServiceName}|%X{PartnerName}|%X{TargetEntity}|%X{TargetServiceName}|%X{StatusCode}|%X{ResponseCode}|%X{ResponseDescription}|%X{InstanceUUID}|%.-5level|%X{AlertSeverity}|%X{ServerIPAddress}|%X{ElapsedTime}|%X{ServerFQDN}|%X{RemoteHost}|%X{ClassName}||%X{ProcessKey}|%X{TargetVirtualEntity}|%X{CustomField1}|%X{CustomField2}|%X{CustomField3}|%X{CustomField4}|%msg%n" />
+
+
+
+ <!-- M E T R I C
+ <property name="defaultMetricPattern" value="%X{BeginTimestamp}|%X{EndTimestamp}|%X{RequestId}|%X{ServiceInstanceId}|%thread|%X{ServerName}|%X{ServiceName}|%X{PartnerName}|%X{TargetEntity}|%X{TargetServiceName}|%X{StatusCode}|%X{ResponseCode}|%X{ResponseDescription}|%X{InstanceUUID}|%.-5level|%X{Severity}|%X{ServerIPAddress}|%X{ElapsedTime}|%X{ServerFQDN}|%X{RemoteHost}|%X{ClassName}||%X{ProcessKey}|%X{TargetVirtualEntity}|%X{CustomField1}|%X{CustomField2}|%X{CustomField3}|%X{CustomField4}|%msg%n" />
-->
<property name="defaultMetricPattern" value="%X{MetricBeginTimestamp}|%X{MetricEndTimestamp}|%X{requestId}|%X{serviceInstanceId}|%t|%X{serverName}|%X{serviceName}|%X{partnerName}|%X{targetEntity}|%X{targetServiceName}|%X{statusCode}|%X{ResponseCode}|%X{ResponseDescription}|%X{InstanceUUID}|%p|%X{severity}|%X{serverIpAddress}|%X{MetricElapsedTime}|%X{server}|%X{clientIpAddress}|%c||%X{ProcessKey}|%X{TargetVirtualEntity}|%X{CustomField1}|%X{CustomField2}|%X{CustomField3}|%X{CustomField4}|%msg%n" />
-
-
-
+
+
+
<!-- E R R O R
<property name="defaultErrorPattern" value="%d{yyyy-MM-dd'T'HH:mm:ss.SSS+00:00, UTC}|%X{RequestId}|%thread|%X{ServiceName}|%X{PartnerName}|%X{TargetEntity}|%X{TargetServiceName}|%X{ErrorCategory}|%X{ErrorCode}|%X{ErrorDesciption}|%msg%n" />
-->
<property name="defaultErrorPattern" value="%d{yyyy-MM-dd'T'HH:mm:ss.SSS+00:00, UTC}|%X{requestId}|%t|%X{serviceName}|%X{PartnerName}|%X{TargetEntity}|%X{TargetServiceName}|%X{ErrorCategory}|%X{ErrorCode}|%X{ErrorDesciption}|%msg%n" />
-
-
-
+
+
+
<!-- D E B U G
- <property name="debugLoggerPatternOld" value="%d{MM/dd-HH:mm:ss.SSS}|%X{RequestId}|%X{ServiceInstanceId}|%thread|%X{ServiceName}|%X{InstanceUUID}|%.-5level|%X{AlertSeverity}|%X{ServerIPAddress}|%X{ServerFQDN}|%X{RemoteHost}|%X{Timer}|[%caller{3}]|%msg%n" />
- <property name="debugLoggerPattern" value="%X{BeginTimestamp}|%X{EndTimestamp}|%X{RequestId}|%X{ServiceInstanceId}|%thread|%X{ServerName}|%X{ServiceName}|%X{PartnerName}|%X{StatusCode}|%X{ResponseCode}|%X{ResponseDescription}|%X{ServiceName}|%X{InstanceUUID}|%.-5level|%X{AlertSeverity}|%X{ServerIPAddress}|%X{ElapsedTime}|%X{ServerFQDN}|%X{RemoteHost}|%X{ClassName}||%X{ProcessKey}|%X{CustomField1}|%X{CustomField2}|%X{CustomField3}|%X{CustomField4}|%msg%n" /> -->
+ <property name="debugLoggerPatternOld" value="%d{MM/dd-HH:mm:ss.SSS}|%X{RequestId}|%X{ServiceInstanceId}|%thread|%X{ServiceName}|%X{InstanceUUID}|%.-5level|%X{Severity}|%X{ServerIPAddress}|%X{ServerFQDN}|%X{RemoteHost}|%X{Timer}|[%caller{3}]|%msg%n" />
+ <property name="debugLoggerPattern" value="%X{BeginTimestamp}|%X{EndTimestamp}|%X{RequestId}|%X{ServiceInstanceId}|%thread|%X{ServerName}|%X{ServiceName}|%X{PartnerName}|%X{StatusCode}|%X{ResponseCode}|%X{ResponseDescription}|%X{ServiceName}|%X{InstanceUUID}|%.-5level|%X{Severity}|%X{ServerIPAddress}|%X{ElapsedTime}|%X{ServerFQDN}|%X{RemoteHost}|%X{ClassName}||%X{ProcessKey}|%X{CustomField1}|%X{CustomField2}|%X{CustomField3}|%X{CustomField4}|%msg%n" /> -->
-->
- <property name="debugLoggerPattern" value="%d{yyyy-MM-dd'T'HH:mm:ss.SSS+00:00, UTC}|%X{RequestId}|%msg%n" />
-
-
-
- <!-- D E F A U L T
- <property name="defaultPatternOld" value="%d{MM/dd-HH:mm:ss.SSS}|%logger|%X{RequestId}|%X{ServiceInstanceId}|%thread|%X{ServiceName}|%X{InstanceUUID}|%.-5level|%X{AlertSeverity}|%X{ServerIPAddress}|%X{ServerFQDN}|%X{RemoteHost}|%X{ClassName}|%X{Timer}|%msg%n" />
- <property name="defaultPattern" value="%X{BeginTimestamp}|%X{EndTimestamp}|%X{RequestId}|%X{ServiceInstanceId}|%thread|%X{ServerName}|%X{ServiceName}|%X{PartnerName}|%X{TargetEntity}|%X{TargetServiceName}|%X{StatusCode}|%X{ResponseCode}|%X{ResponseDescription}|%X{InstanceUUID}|%.-5level|%X{AlertSeverity}|%X{ServerIPAddress}|%X{ElapsedTime}|%X{ServerFQDN}|%X{RemoteHost}|%X{ClassName}||%X{ProcessKey}|%X{TargetVirtualEntity}|%X{CustomField1}|%X{CustomField2}|%X{CustomField3}|%X{CustomField4}|%msg%n" />
+ <property name="debugLoggerPattern" value="%d{yyyy-MM-dd'T'HH:mm:ss.SSS+00:00, UTC}|%X{RequestId}|%msg%n" />
+
+
+
+ <!-- D E F A U L T
+ <property name="defaultPatternOld" value="%d{MM/dd-HH:mm:ss.SSS}|%logger|%X{RequestId}|%X{ServiceInstanceId}|%thread|%X{ServiceName}|%X{InstanceUUID}|%.-5level|%X{Severity}|%X{ServerIPAddress}|%X{ServerFQDN}|%X{RemoteHost}|%X{ClassName}|%X{Timer}|%msg%n" />
+ <property name="defaultPattern" value="%X{BeginTimestamp}|%X{EndTimestamp}|%X{RequestId}|%X{ServiceInstanceId}|%thread|%X{ServerName}|%X{ServiceName}|%X{PartnerName}|%X{TargetEntity}|%X{TargetServiceName}|%X{StatusCode}|%X{ResponseCode}|%X{ResponseDescription}|%X{InstanceUUID}|%.-5level|%X{Severity}|%X{ServerIPAddress}|%X{ElapsedTime}|%X{ServerFQDN}|%X{RemoteHost}|%X{ClassName}||%X{ProcessKey}|%X{TargetVirtualEntity}|%X{CustomField1}|%X{CustomField2}|%X{CustomField3}|%X{CustomField4}|%msg%n" />
-->
<property name="defaultPattern" value="%d{yyyy-MM-dd'T'HH:mm:ss.SSSXXX, UTC}|%X{requestId}|%X{serviceInstanceId}|%t|%X{serverName}|%X{serviceName}|%X{instanceUuid}|%p|%X{severity}|%X{serverIpAddress}|%X{server}|%X{clientIpAddress}|%c||%msg%n" />
-
-
-
+
+
+
<!-- P A T H
<property name="logDirectory" value="${logDir}/${componentName}/${subComponentName}" />
<property name="debugLogDirectory" value="${debugDir}/${componentName}/${subComponentName}" />
- -->
+ -->
<property name="logDirectory" value="${logDir}/${componentName}/${subComponentName}" />
<property name="debugLogDirectory" value="${debugDir}/${componentName}/${subComponentName}" />
-
-
-
+
+
+
<!-- Example evaluator filter applied against console appender -->
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
@@ -100,28 +100,28 @@
<!-- EELF Appenders -->
<!-- ============================================================================ -->
- <!-- The EELFAppender is used to record events to the general application
+ <!-- The EELFAppender is used to record events to the general application
log -->
-
- <!-- EELF Audit Appender. This appender is used to record audit engine
- related logging events. The audit logger and appender are specializations
- of the EELF application root logger and appender. This can be used to segregate
- Policy engine events from other components, or it can be eliminated to record
+
+ <!-- EELF Audit Appender. This appender is used to record audit engine
+ related logging events. The audit logger and appender are specializations
+ of the EELF application root logger and appender. This can be used to segregate
+ Policy engine events from other components, or it can be eliminated to record
these events as part of the application root log. -->
-
+
<appender name="EELFAudit"
class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>${logDirectory}/${auditLogName}.log</file>
<rollingPolicy
class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
<fileNamePattern>${logDirectory}/${auditLogName}.%d{yyyy-MM-dd}.%i.log.zip</fileNamePattern>
-
- <!-- keep 30 days' worth of history capped at 3GB total size -->
+
+ <!-- keep 30 days' worth of history capped at 3GB total size -->
<maxFileSize>50MB</maxFileSize>
<maxHistory>30</maxHistory>
<totalSizeCap>10GB</totalSizeCap>
</rollingPolicy>
-
+
<encoder>
<pattern>${defaultAuditPattern}</pattern>
</encoder>
@@ -141,18 +141,18 @@
<rollingPolicy
class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
<fileNamePattern>${logDirectory}/${metricsLogName}.%d{yyyy-MM-dd}.%i.log.zip</fileNamePattern>
-
- <!-- keep 30 days' worth of history capped at 3GB total size -->
+
+ <!-- keep 30 days' worth of history capped at 3GB total size -->
<maxFileSize>50MB</maxFileSize>
<maxHistory>30</maxHistory>
<totalSizeCap>10GB</totalSizeCap>
</rollingPolicy>
-
+
<encoder>
<pattern>${defaultMetricPattern}</pattern>
</encoder>
</appender>
-
+
<appender name="asyncEELFMetrics" class="ch.qos.logback.classic.AsyncAppender">
<queueSize>256</queueSize>
<appender-ref ref="EELFMetrics"/>
@@ -160,15 +160,15 @@
-
+
<appender name="EELFError"
class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>${logDirectory}/${errorLogName}.log</file>
<rollingPolicy
class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
<fileNamePattern>${logDirectory}/${errorLogName}.%d{yyyy-MM-dd}.%i.log.zip</fileNamePattern>
-
- <!-- keep 30 days' worth of history capped at 3GB total size -->
+
+ <!-- keep 30 days' worth of history capped at 3GB total size -->
<maxFileSize>50MB</maxFileSize>
<maxHistory>30</maxHistory>
<totalSizeCap>10GB</totalSizeCap>
@@ -180,22 +180,22 @@
<pattern>${defaultErrorPattern}</pattern>
</encoder>
</appender>
-
+
<appender name="asyncEELFError" class="ch.qos.logback.classic.AsyncAppender">
<queueSize>256</queueSize>
<appender-ref ref="EELFError"/>
</appender>
-
+
<appender name="EELFDebug"
class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>${debugLogDirectory}/${debugLogName}.log</file>
<rollingPolicy
class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
<fileNamePattern>${debugLogDirectory}/${debugLogName}.%d{yyyy-MM-dd}.%i.log.zip</fileNamePattern>
-
- <!-- keep 30 days' worth of history capped at 3GB total size -->
+
+ <!-- keep 30 days' worth of history capped at 3GB total size -->
<maxFileSize>50MB</maxFileSize>
<maxHistory>30</maxHistory>
<totalSizeCap>10GB</totalSizeCap>
@@ -203,41 +203,41 @@
<filter class="ch.qos.logback.classic.filter.ThresholdFilter">
<level>DEBUG</level>
</filter>
-
+
<encoder>
<pattern>${debugLoggerPattern}</pattern>
</encoder>
</appender>
-
+
<appender name="asyncEELFDebug" class="ch.qos.logback.classic.AsyncAppender">
<queueSize>256</queueSize>
<appender-ref ref="EELFDebug" />
<includeCallerData>true</includeCallerData>
</appender>
-
-
+
+
<!-- ============================================================================ -->
<!-- EELF loggers -->
<!-- ============================================================================ -->
-
+
<logger name="com.att.eelf.audit" level="info" additivity="false">
<appender-ref ref="asyncEELFAudit" />
</logger>
-
+
<logger name="com.att.eelf.metrics" level="info" additivity="false">
<appender-ref ref="asyncEELFMetrics" />
</logger>
-
+
<logger name="com.att.eelf.error" level="error" additivity="false">
<appender-ref ref="asyncEELFError" />
</logger>
-
+
<logger name="com.att.eelf.debug" level="info" additivity="false">
<appender-ref ref="asyncEELFDebug" />
</logger>
-
-
-
+
+
+
<root level="INFO">
<appender-ref ref="asyncEELFDebug" />
<appender-ref ref="asyncEELFError" />
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
index cf3ddb3b2..841fad641 100644
--- 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
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP-PDP-REST
* ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017, 2020 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Modifications Copyright (C) 2019 Samsung
* ================================================================================
@@ -28,7 +28,7 @@ import java.util.Date;
import java.util.Properties;
import org.junit.Assert;
import org.junit.Test;
-import org.onap.policy.rest.XACMLRestProperties;
+import org.onap.policy.rest.XacmlRestProperties;
public class PapUrlResolverTest {
@@ -41,7 +41,7 @@ public class PapUrlResolverTest {
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),
+ Assert.assertEquals(rs.getProperties().getProperty(XacmlRestProperties.PROP_PAP_URLS),
urls);
rs.failed();
@@ -51,14 +51,17 @@ public class PapUrlResolverTest {
Assert.assertFalse(rs.hasMoreUrls());
Properties prop = rs.getProperties();
Assert.assertEquals(df.format(new Date()) + ",-1,-1,-1",
- prop.getProperty(XACMLRestProperties.PROP_PAP_FAILED_URLS));
+ prop.getProperty(XacmlRestProperties.PROP_PAP_FAILED_URLS));
Assert.assertEquals("-1," + df.format(new Date()) + ",-1,-1",
- prop.getProperty(XACMLRestProperties.PROP_PAP_SUCCEEDED_URLS));
+ prop.getProperty(XacmlRestProperties.PROP_PAP_SUCCEEDED_URLS));
- failed = prop.getProperty(XACMLRestProperties.PROP_PAP_FAILED_URLS);
- succeeded = 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://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());
@@ -66,18 +69,15 @@ public class PapUrlResolverTest {
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));
+ prop.getProperty(XacmlRestProperties.PROP_PAP_FAILED_URLS));
- failed = prop.getProperty(XACMLRestProperties.PROP_PAP_FAILED_URLS);
- succeeded = 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://one.localhost.com", rs.getUrl());
@@ -85,8 +85,8 @@ public class PapUrlResolverTest {
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);
+ 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());
@@ -94,8 +94,8 @@ public class PapUrlResolverTest {
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);
+ 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());
@@ -104,7 +104,7 @@ public class PapUrlResolverTest {
Assert.assertFalse(rs.hasMoreUrls());
prop = rs.getProperties();
- succeeded = prop.getProperty(XACMLRestProperties.PROP_PAP_SUCCEEDED_URLS);
+ succeeded = prop.getProperty(XacmlRestProperties.PROP_PAP_SUCCEEDED_URLS);
}
@SuppressWarnings("unused")
@@ -128,13 +128,13 @@ public class PapUrlResolverTest {
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());
+ Assert.assertEquals("http://one.localhost.com", rs.getUrl());
rs.getNext();
Assert.assertTrue(rs.hasMoreUrls());
- Assert.assertEquals("http://three.localhost.com", rs.getUrl());
+ Assert.assertEquals("http://two.localhost.com", rs.getUrl());
rs.getNext();
Assert.assertTrue(rs.hasMoreUrls());
- Assert.assertEquals("http://one.localhost.com", rs.getUrl());
+ Assert.assertEquals("http://three.localhost.com", rs.getUrl());
rs.getNext();
Assert.assertTrue(rs.hasMoreUrls());
Assert.assertEquals("http://four.localhost.com", rs.getUrl());
@@ -186,13 +186,13 @@ public class PapUrlResolverTest {
succeeded = "-1,-1,-1,-1";
rs = PapUrlResolver.getInstance(urls, failed, succeeded);
Assert.assertTrue(rs.hasMoreUrls());
- Assert.assertEquals("http://two.localhost.com", rs.getUrl());
+ Assert.assertEquals("http://one.localhost.com", rs.getUrl());
rs.getNext();
Assert.assertTrue(rs.hasMoreUrls());
- Assert.assertEquals("http://three.localhost.com", rs.getUrl());
+ Assert.assertEquals("http://two.localhost.com", rs.getUrl());
rs.getNext();
Assert.assertTrue(rs.hasMoreUrls());
- Assert.assertEquals("http://one.localhost.com", rs.getUrl());
+ Assert.assertEquals("http://three.localhost.com", rs.getUrl());
rs.getNext();
Assert.assertTrue(rs.hasMoreUrls());
Assert.assertEquals("http://four.localhost.com", rs.getUrl());
@@ -204,6 +204,9 @@ public class PapUrlResolverTest {
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());
@@ -212,9 +215,6 @@ public class PapUrlResolverTest {
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";
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
index 14c231aed..eb6910ca7 100644
--- 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
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP-PDP-REST
* ================================================================================
- * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2020 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Modifications Copyright (C) 2019 Samsung
* ================================================================================
@@ -41,12 +41,13 @@ import org.mockito.Mockito;
import org.onap.policy.common.ia.IntegrityAuditProperties;
import org.onap.policy.common.im.IntegrityMonitor;
import org.onap.policy.common.im.IntegrityMonitorException;
-import org.onap.policy.common.logging.ONAPLoggingContext;
+import org.onap.policy.common.logging.OnapLoggingContext;
import org.onap.policy.common.logging.flexlogger.FlexLogger;
import org.onap.policy.common.logging.flexlogger.Logger;
import org.onap.policy.xacml.std.pap.StdPDPPolicy;
import org.onap.policy.xacml.std.pap.StdPDPStatus;
import org.powermock.api.mockito.PowerMockito;
+import org.powermock.core.classloader.annotations.PowerMockIgnore;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import org.springframework.mock.web.MockHttpServletResponse;
@@ -56,6 +57,7 @@ import com.mockrunner.mock.web.MockServletInputStream;
import junit.framework.TestCase;
@RunWith(PowerMockRunner.class)
+@PowerMockIgnore({"com.sun.org.apache.xerces.*", "javax.xml.*", "org.xml.*", "javax.management.*", "org.w3c.dom.*"})
@PrepareForTest({IntegrityMonitor.class})
public class XACMLPdpServletTest extends TestCase {
private static Logger LOGGER = FlexLogger.getLogger(XACMLPdpServletTest.class);
@@ -223,7 +225,7 @@ public class XACMLPdpServletTest extends TestCase {
public void testXACMLPdpRegisterThread() {
LOGGER.info("XACMLPdpServletTest - testXACMLPdpRegisterThread");
try {
- ONAPLoggingContext baseLoggingContext = new ONAPLoggingContext();
+ OnapLoggingContext baseLoggingContext = new OnapLoggingContext();
baseLoggingContext.setServer("localhost");
XACMLPdpRegisterThread regThread = new XACMLPdpRegisterThread(baseLoggingContext);
regThread.run();
diff --git a/ONAP-PDP-REST/src/test/java/org/onap/policy/pdp/rest/api/test/GetDictionaryServiceTest.java b/ONAP-PDP-REST/src/test/java/org/onap/policy/pdp/rest/api/test/GetDictionaryServiceTest.java
index 4544b6b1c..1904b4bf0 100644
--- a/ONAP-PDP-REST/src/test/java/org/onap/policy/pdp/rest/api/test/GetDictionaryServiceTest.java
+++ b/ONAP-PDP-REST/src/test/java/org/onap/policy/pdp/rest/api/test/GetDictionaryServiceTest.java
@@ -76,7 +76,7 @@ public class GetDictionaryServiceTest {
result = (String) formatDictionary.invoke(gds, input);
assertNotNull(result);
//
- dp.setDictionary("PEPOptions");
+ dp.setDictionary("PepOptions");
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/api/utils/test/PolicyApiUtilsTest.java b/ONAP-PDP-REST/src/test/java/org/onap/policy/pdp/rest/api/utils/test/PolicyApiUtilsTest.java
index d1da554d9..d09059978 100644
--- a/ONAP-PDP-REST/src/test/java/org/onap/policy/pdp/rest/api/utils/test/PolicyApiUtilsTest.java
+++ b/ONAP-PDP-REST/src/test/java/org/onap/policy/pdp/rest/api/utils/test/PolicyApiUtilsTest.java
@@ -28,7 +28,6 @@ import static org.junit.Assert.assertTrue;
import javax.json.Json;
import javax.json.JsonArray;
import javax.json.JsonObject;
-import org.json.JSONObject;
import org.junit.Test;
import org.onap.policy.pdp.rest.api.utils.PolicyApiUtils;
diff --git a/ONAP-PDP-REST/src/test/java/org/onap/policy/pdp/rest/auth/test/AuthenticationServiceTest.java b/ONAP-PDP-REST/src/test/java/org/onap/policy/pdp/rest/auth/test/AuthenticationServiceTest.java
index 0795526fc..4f03221b7 100644
--- a/ONAP-PDP-REST/src/test/java/org/onap/policy/pdp/rest/auth/test/AuthenticationServiceTest.java
+++ b/ONAP-PDP-REST/src/test/java/org/onap/policy/pdp/rest/auth/test/AuthenticationServiceTest.java
@@ -24,11 +24,15 @@ package org.onap.policy.pdp.rest.auth.test;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.mock;
+
+import com.att.research.xacml.util.XACMLProperties;
+
import java.io.UnsupportedEncodingException;
import java.util.Base64;
import javax.servlet.ServletRequest;
import org.junit.Test;
import org.onap.policy.pdp.rest.restauth.AuthenticationService;
+import org.onap.policy.rest.XacmlRestProperties;
public class AuthenticationServiceTest {
private final String testCred = "python:test";
@@ -40,10 +44,13 @@ public class AuthenticationServiceTest {
String systemKey = "xacml.properties";
// Set the system property temporarily
- String oldProperty = System.getProperty(systemKey);
+ final String oldProperty = System.getProperty(systemKey);
System.setProperty(systemKey, "xacml.pdp.properties");
- ServletRequest request = mock(ServletRequest.class);
+ XACMLProperties.setProperty("enable_aaf", "false");
+ XACMLProperties.setProperty(XacmlRestProperties.PROP_PEP_IDFILE, "client.properties");
+ ServletRequest request = mock(ServletRequest.class);
+ AuthenticationService.getEnvironment();
assertTrue(AuthenticationService.checkPermissions(null, basicCred, "getConfig", "DEVL", request));
// Restore the original system property
diff --git a/ONAP-PDP-REST/src/test/java/org/onap/policy/pdp/rest/notifications/test/NotificationTest.java b/ONAP-PDP-REST/src/test/java/org/onap/policy/pdp/rest/notifications/test/NotificationTest.java
index 261226527..190f93aa7 100644
--- a/ONAP-PDP-REST/src/test/java/org/onap/policy/pdp/rest/notifications/test/NotificationTest.java
+++ b/ONAP-PDP-REST/src/test/java/org/onap/policy/pdp/rest/notifications/test/NotificationTest.java
@@ -23,8 +23,6 @@ package org.onap.policy.pdp.rest.notifications.test;
import static org.junit.Assert.assertEquals;
import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Collections;
import java.util.List;
import org.junit.Test;
import org.onap.policy.api.NotificationType;
diff --git a/ONAP-PDP-REST/src/test/resources/META-INF/drop.ddl b/ONAP-PDP-REST/src/test/resources/META-INF/drop.ddl
index 062169345..d28a00dde 100644
--- a/ONAP-PDP-REST/src/test/resources/META-INF/drop.ddl
+++ b/ONAP-PDP-REST/src/test/resources/META-INF/drop.ddl
@@ -20,7 +20,7 @@
DROP TABLE IF EXISTS ConfigurationDataEntity
DROP TABLE IF EXISTS PolicyEntity
-DROP TABLE IF EXISTS PolicyDBDaoEntity
+DROP TABLE IF EXISTS PolicyDbDaoEntity
DROP TABLE IF EXISTS ActionBodyEntity
DROP SEQUENCE IF EXISTS seqPolicy
DROP SEQUENCE IF EXISTS seqConfig
diff --git a/ONAP-PDP-REST/src/test/resources/META-INF/persistence.xml b/ONAP-PDP-REST/src/test/resources/META-INF/persistence.xml
index b44841c9d..01ea8dc2e 100644
--- a/ONAP-PDP-REST/src/test/resources/META-INF/persistence.xml
+++ b/ONAP-PDP-REST/src/test/resources/META-INF/persistence.xml
@@ -22,7 +22,7 @@
<persistence-unit name="XACML-PAP-REST">
<class>org.onap.policy.rest.jpa.PolicyEntity</class>
<class>org.onap.policy.rest.jpa.ConfigurationDataEntity</class>
- <class>org.onap.policy.rest.jpa.PolicyDBDaoEntity</class>
+ <class>org.onap.policy.rest.jpa.PolicyDbDaoEntity</class>
<class>org.onap.policy.rest.jpa.GroupEntity</class>
<class>org.onap.policy.rest.jpa.PdpEntity</class>
<class>org.onap.policy.rest.jpa.ActionBodyEntity</class>
@@ -40,7 +40,7 @@
<class>org.onap.policy.rest.jpa.ActionPolicyDict</class>
<class>org.onap.policy.rest.jpa.DecisionSettings</class>
<class>org.onap.policy.rest.jpa.MicroServiceModels</class>
- <class>org.onap.policy.rest.jpa.BRMSParamTemplate</class>
+ <class>org.onap.policy.rest.jpa.BrmsParamTemplate</class>
<class>org.onap.policy.rest.jpa.PolicyEditorScopes</class>
<!-- unique to PolicyEngineUtils - will be audited from PAP -->
<class>org.onap.policy.jpa.BackUpMonitorEntity</class>
@@ -109,7 +109,7 @@
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<class>org.onap.policy.rest.jpa.PolicyEntity</class>
<class>org.onap.policy.rest.jpa.ConfigurationDataEntity</class>
- <class>org.onap.policy.rest.jpa.PolicyDBDaoEntity</class>
+ <class>org.onap.policy.rest.jpa.PolicyDbDaoEntity</class>
<class>org.onap.policy.rest.jpa.GroupEntity</class>
<class>org.onap.policy.rest.jpa.PdpEntity</class>
<class>org.onap.policy.rest.jpa.ActionBodyEntity</class>
@@ -131,11 +131,11 @@
<class>org.onap.policy.rest.jpa.ActionList</class>
<class>org.onap.policy.rest.jpa.AddressGroup</class>
<class>org.onap.policy.rest.jpa.AttributeAssignment</class>
- <class>org.onap.policy.rest.jpa.BRMSParamTemplate</class>
+ <class>org.onap.policy.rest.jpa.BrmsParamTemplate</class>
<class>org.onap.policy.rest.jpa.ClosedLoopD2Services</class>
<class>org.onap.policy.rest.jpa.ClosedLoopSite</class>
- <class>org.onap.policy.rest.jpa.DCAEUsers</class>
- <class>org.onap.policy.rest.jpa.DCAEuuid</class>
+ <class>org.onap.policy.rest.jpa.DcaeUsers</class>
+ <class>org.onap.policy.rest.jpa.Dcaeuuid</class>
<class>org.onap.policy.rest.jpa.DescriptiveScope</class>
<class>org.onap.policy.rest.jpa.OnapName</class>
<class>org.onap.policy.rest.jpa.EnforcingType</class>
@@ -146,12 +146,12 @@
<class>org.onap.policy.rest.jpa.MicroServiceLocation</class>
<class>org.onap.policy.rest.jpa.Obadvice</class>
<class>org.onap.policy.rest.jpa.ObadviceExpression</class>
- <class>org.onap.policy.rest.jpa.PEPOptions</class>
- <class>org.onap.policy.rest.jpa.PIPConfigParam</class>
- <class>org.onap.policy.rest.jpa.PIPConfiguration</class>
- <class>org.onap.policy.rest.jpa.PIPResolver</class>
- <class>org.onap.policy.rest.jpa.PIPResolverParam</class>
- <class>org.onap.policy.rest.jpa.PIPType</class>
+ <class>org.onap.policy.rest.jpa.PepOptions</class>
+ <class>org.onap.policy.rest.jpa.PipConfigParam</class>
+ <class>org.onap.policy.rest.jpa.PipConfiguration</class>
+ <class>org.onap.policy.rest.jpa.PipResolver</class>
+ <class>org.onap.policy.rest.jpa.PipResolverParam</class>
+ <class>org.onap.policy.rest.jpa.PipType</class>
<class>org.onap.policy.rest.jpa.PolicyAlgorithms</class>
<class>org.onap.policy.rest.jpa.PolicyManagement</class>
<class>org.onap.policy.rest.jpa.PolicyScopeService</class>
@@ -166,12 +166,12 @@
<class>org.onap.policy.rest.jpa.RuleAlgorithms</class>
<class>org.onap.policy.rest.jpa.SecurityZone</class>
<class>org.onap.policy.rest.jpa.ServiceList</class>
- <class>org.onap.policy.rest.jpa.SystemLogDB</class>
+ <class>org.onap.policy.rest.jpa.SystemLogDb</class>
<class>org.onap.policy.rest.jpa.TermList</class>
<class>org.onap.policy.rest.jpa.VarbindDictionary</class>
- <class>org.onap.policy.rest.jpa.VMType</class>
- <class>org.onap.policy.rest.jpa.VNFType</class>
- <class>org.onap.policy.rest.jpa.VSCLAction</class>
+ <class>org.onap.policy.rest.jpa.VmType</class>
+ <class>org.onap.policy.rest.jpa.VnfType</class>
+ <class>org.onap.policy.rest.jpa.VsclAction</class>
<class>org.onap.policy.rest.jpa.Zone</class>
<!-- unique to PolicyEngineUtils -->
<class>org.onap.policy.jpa.BackUpMonitorEntity</class>
diff --git a/ONAP-PDP-REST/src/test/resources/test.drl b/ONAP-PDP-REST/src/test/resources/test.drl
index 7accc63ae..bb709575d 100644
--- a/ONAP-PDP-REST/src/test/resources/test.drl
+++ b/ONAP-PDP-REST/src/test/resources/test.drl
@@ -1,15 +1,14 @@
/*-
* ============LICENSE_START=======================================================
- * archetype-closed-loop-demo-rules
- * ================================================================================
* Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2019 Bell Canada.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -20,1102 +19,16 @@
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<String, Object>();
- //
- // 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);
- }
+rule "INIT"
+when
+then
+ insert("This is a test");
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<AAINQF199InventoryResponseItem> 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<String, Object>();
- //
- // 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;
- }
+rule "PRINT_MSG"
+when
+ $o : Object();
+then
+ System.out.println("MSG: " + $o);
+ retract($o);
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
index fc826b3e1..64cfa0626 100644
--- a/ONAP-PDP-REST/xacml.pdp.properties
+++ b/ONAP-PDP-REST/xacml.pdp.properties
@@ -172,7 +172,7 @@ xacml.rest.pep.idfile=client.properties
enable_aaf=false
policy.aaf.namespace=org.onap.policy
policy.aaf.root.permission=org.onap.policy.pdpx
-cm_url=https://aaf-onap-test.osaaf.org:8095/AAF_NS.cm:2.1
+cm_url=https://aaf-onap-test.osaaf.org:8095/onap.org.osaaf.aaf.cm:2.1
cadi_latitude=38.000
cadi.longitude=72.000
cadi_alias=policy@policy.onap.org
@@ -185,12 +185,12 @@ cadi_keystore_password=Pol1cy_0nap
cadi_truststore=../packages/base/src/files/etc/ssl/policy-truststore
cadi_truststore_password=Pol1cy_0nap
aaf_env=DEV
-aaf_url=https://aaf-onap-test.osaaf.org:8095/AAF_NS.service:2.1
+aaf_url=https://aaf-onap-test.osaaf.org:8095/onap.org.osaaf.aaf.service:2.1
aaf_fqdn=aaf-onap-test.osaaf.org
-aaf_oauth2_introspect_url=https://aaf-onap-test.osaaf.org:8095/AAF_NS.introspect:2.1/introspect
-aaf_oauth2_token_url=https://aaf-onap-test.osaaf.org:8095/AAF_NS.token:2.1/token
-fs_url=https://aaf-onap-test.osaaf.org:8095/AAF_NS.fs.2.1
-gui_url=https://aaf-onap-test.osaaf.org:8095/AAF_NS.gui.2.1
+aaf_oauth2_introspect_url=https://aaf-onap-test.osaaf.org:8095/onap.org.osaaf.aaf.introspect:2.1/introspect
+aaf_oauth2_token_url=https://aaf-onap-test.osaaf.org:8095/onap.org.osaaf.aaf.token:2.1/token
+fs_url=https://aaf-onap-test.osaaf.org:8095/onap.org.osaaf.aaf.fs.2.1
+gui_url=https://aaf-onap-test.osaaf.org:8095/onap.org.osaaf.aaf.gui.2.1
#TOSCA MS model yaml file directory which can be changed based on systems.
#msToscaModel.home=C://home//msyamlFiles//
diff --git a/ONAP-PDP/checkstyle-suppressions.xml b/ONAP-PDP/checkstyle-suppressions.xml
new file mode 100644
index 000000000..ee01ae5ae
--- /dev/null
+++ b/ONAP-PDP/checkstyle-suppressions.xml
@@ -0,0 +1,33 @@
+<?xml version="1.0"?>
+<!--
+ ============LICENSE_START=======================================================
+ Copyright (C) 2020 AT&T Technologies. All rights reserved.
+ ================================================================================
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+
+ SPDX-License-Identifier: Apache-2.0
+ ============LICENSE_END=========================================================
+
+
+ **** NOTE ****
+ This file is needed to suppress checkstyle for properties files.
+ **************
+-->
+
+<!DOCTYPE suppressions PUBLIC
+ "-//Puppy Crawl//DTD Suppressions 1.0//EN"
+ "http://www.puppycrawl.com/dtds/suppressions_1_0.dtd">
+
+<suppressions>
+ <suppress files="\.properties" checks="[a-zA-Z0-9]*"/>
+</suppressions>
diff --git a/ONAP-PDP/pom.xml b/ONAP-PDP/pom.xml
index eacdbdac6..18f77c570 100644
--- a/ONAP-PDP/pom.xml
+++ b/ONAP-PDP/pom.xml
@@ -3,7 +3,7 @@
============LICENSE_START=======================================================
ONAP Policy Engine
================================================================================
- Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ Copyright (C) 2017-2018, 2020 AT&T Intellectual Property. All rights reserved.
================================================================================
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
@@ -27,7 +27,7 @@
<parent>
<groupId>org.onap.policy.engine</groupId>
<artifactId>PolicyEngineSuite</artifactId>
- <version>1.4.1-SNAPSHOT</version>
+ <version>1.6.4-SNAPSHOT</version>
</parent>
<dependencies>
<dependency>
@@ -99,12 +99,13 @@
<configLocation>onap-checkstyle/onap-java-style.xml</configLocation>
<!-- <sourceDirectory> is needed so that checkstyle ignores the generated
sources directory -->
- <sourceDirectory>${project.build.sourceDirectory}</sourceDirectory>
+ <sourceDirectories>${project.build.sourceDirectory}</sourceDirectories>
<includeResources>true</includeResources>
<includeTestSourceDirectory>true</includeTestSourceDirectory>
<includeTestResources>true</includeTestResources>
<excludes>
</excludes>
+ <suppressionsLocation>/checkstyle-suppressions.xml</suppressionsLocation>
<consoleOutput>true</consoleOutput>
<failOnViolation>true</failOnViolation>
<violationSeverity>warning</violationSeverity>
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
index c256626e6..f4a196adf 100644
--- 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
@@ -60,7 +60,7 @@ 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 org.onap.policy.rest.XacmlRestProperties;
@SuppressWarnings("deprecation")
public class FindAction {
@@ -159,7 +159,7 @@ public class FindAction {
attribute.getAttributeValue().getValue().toString());
afterRemoveAssignments.add(attribute);
} else if (attribute.getAttributeId().stringValue().equalsIgnoreCase("body")) {
- String papPath = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_URL);
+ String papPath = XACMLProperties.getProperty(XacmlRestProperties.PROP_PAP_URL);
papPath = papPath.replace("/pap", "");
matchValues.put("body",
attribute.getAttributeValue().getValue().toString().replace("$URL", papPath));
diff --git a/ONAP-PDP/src/test/java/org/onap/policy/xacml/action/FindActionTest.java b/ONAP-PDP/src/test/java/org/onap/policy/xacml/action/FindActionTest.java
index 5403f8ff1..f8729d696 100644
--- a/ONAP-PDP/src/test/java/org/onap/policy/xacml/action/FindActionTest.java
+++ b/ONAP-PDP/src/test/java/org/onap/policy/xacml/action/FindActionTest.java
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP-PDP
* ================================================================================
- * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -46,6 +46,7 @@ import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.onap.policy.common.endpoints.http.server.HttpServletServer;
+import org.onap.policy.common.endpoints.http.server.HttpServletServerFactoryInstance;
import org.onap.policy.common.utils.network.NetworkUtil;
import org.onap.policy.xacml.custom.OnapFunctionDefinitionFactory;
@@ -68,8 +69,8 @@ public class FindActionTest {
@BeforeClass
public static void setUpServer() {
try {
- final HttpServletServer testServer =
- HttpServletServer.factory.build("dmaapSim", "localhost", MOCK_SERVER_PORT, "/", false, true);
+ final HttpServletServer testServer = HttpServletServerFactoryInstance.getServerFactory().build("dmaapSim",
+ "localhost", MOCK_SERVER_PORT, "/", false, true);
testServer.addServletClass("/*", DummyRest.class.getName());
testServer.waitedStart(2000);
if (!NetworkUtil.isTcpPortOpen("localhost", testServer.getPort(), 5, 10000L)) {
@@ -83,7 +84,7 @@ public class FindActionTest {
@AfterClass
public static void tearDownSimulator() {
- HttpServletServer.factory.destroy();
+ HttpServletServerFactoryInstance.getServerFactory().destroy();
}
/**
diff --git a/ONAP-PDP/src/test/java/org/onap/policy/xacml/pdp/OnapPdpEngineFactoryTest.java b/ONAP-PDP/src/test/java/org/onap/policy/xacml/pdp/OnapPdpEngineFactoryTest.java
index d3ee544a5..9447a951a 100644
--- a/ONAP-PDP/src/test/java/org/onap/policy/xacml/pdp/OnapPdpEngineFactoryTest.java
+++ b/ONAP-PDP/src/test/java/org/onap/policy/xacml/pdp/OnapPdpEngineFactoryTest.java
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP-PDP
* ================================================================================
- * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2018, 2020 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -33,10 +33,13 @@ import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.powermock.api.mockito.PowerMockito;
+import org.powermock.core.classloader.annotations.PowerMockIgnore;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
@RunWith(PowerMockRunner.class)
+@PowerMockIgnore({"com.sun.org.apache.xerces.*", "jdk.internal.reflect.*", "javax.xml.*", "org.xml.*"})
+@PrepareForTest(OnapPdpEngineFactory.class)
public class OnapPdpEngineFactoryTest {
@Test
public final void testNewEngine() {
@@ -61,7 +64,7 @@ public class OnapPdpEngineFactoryTest {
@PrepareForTest({ EvaluationContextFactory.class, FactoryFinder.class })
@Test(expected = FactoryException.class)
- public void negTestEngine() throws FactoryException {
+ public void testNegTestEngine() throws FactoryException {
// Setup test data
PowerMockito.mockStatic(FactoryFinder.class);
PowerMockito.when(FactoryFinder.find(Mockito.any(), Mockito.any(), Mockito.any())).thenReturn(null);
@@ -74,7 +77,7 @@ public class OnapPdpEngineFactoryTest {
@PrepareForTest({ EvaluationContextFactory.class, FactoryFinder.class })
@Test(expected = FactoryException.class)
- public void negTestEngine2() throws FactoryException {
+ public void testNegTestEngine2() throws FactoryException {
// Setup test data
PowerMockito.mockStatic(FactoryFinder.class);
PowerMockito.when(FactoryFinder.find(Mockito.any(), Mockito.any(), Mockito.any())).thenReturn(null);
diff --git a/ONAP-PDP/src/test/resources/logback-test.xml b/ONAP-PDP/src/test/resources/logback-test.xml
index 93f0a10b8..6fa8c855f 100644
--- a/ONAP-PDP/src/test/resources/logback-test.xml
+++ b/ONAP-PDP/src/test/resources/logback-test.xml
@@ -2,14 +2,14 @@
============LICENSE_START=======================================================
ONAP-PDP
================================================================================
- Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
================================================================================
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
-
+
http://www.apache.org/licenses/LICENSE-2.0
-
+
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -22,73 +22,73 @@
<!--<jmxConfigurator /> -->
<!-- directory path for all other type logs -->
<property name="logDir" value="logs" />
-
+
<!-- directory path for debugging type logs -->
<property name="debugDir" value="logs" />
-
- <!-- specify the component name
+
+ <!-- specify the component name
<ONAP-component-name>::= "MSO" | "DCAE" | "ASDC " | "AAI" |"Policy" | "SDNC" | "AC" -->
<property name="componentName" value="Policy"></property>
<property name="subComponentName" value="ONAP-PDP"></property>
-
+
<!-- log file names -->
<property name="errorLogName" value="error" />
<property name="metricsLogName" value="metrics" />
<property name="auditLogName" value="audit" />
<property name="debugLogName" value="debug" />
-
-
+
+
<!-- modified time stamp format -->
-
- <!-- A U D I T
- <property name="defaultAuditPattern" value="%X{BeginTimestamp}|%X{EndTimestamp}|%X{RequestId}|%X{ServiceInstanceId}|%thread|%X{ServerName}|%X{ServiceName}|%X{PartnerName}|%X{StatusCode}|%X{ResponseCode}|%X{ResponseDescription}|%X{InstanceUUID}|%.-5level|%X{AlertSeverity}|%X{ServerIPAddress}|%X{ElapsedTime}|%X{ServerFQDN}|%X{RemoteHost}|%X{ClassName}||%X{ProcessKey}|%X{TargetVirtualEntity}|%X{CustomField1}|%X{CustomField2}|%X{CustomField3}|%X{CustomField4}|%msg%n" />
+
+ <!-- A U D I T
+ <property name="defaultAuditPattern" value="%X{BeginTimestamp}|%X{EndTimestamp}|%X{RequestId}|%X{ServiceInstanceId}|%thread|%X{ServerName}|%X{ServiceName}|%X{PartnerName}|%X{StatusCode}|%X{ResponseCode}|%X{ResponseDescription}|%X{InstanceUUID}|%.-5level|%X{Severity}|%X{ServerIPAddress}|%X{ElapsedTime}|%X{ServerFQDN}|%X{RemoteHost}|%X{ClassName}||%X{ProcessKey}|%X{TargetVirtualEntity}|%X{CustomField1}|%X{CustomField2}|%X{CustomField3}|%X{CustomField4}|%msg%n" />
<property name="defaultAuditPattern" value="%X{BeginTimestamp}|%X{EndTimestamp}|%X{requestId}|%X{serviceInstanceId}|%t|%X{serverName}|%X{serviceName}|%X{PartnerName}|%X{StatusCode}|%X{ResponseCode}|%X{ResponseDescription}|%X{instanceUuid}|%p|%X{severity}|%X{serverIpAddress}|%X{ElapsedTime}|%X{server}|%X{clientIpAddress}|%c||%X{ProcessKey}|%X{TargetVirtualEntity}|%X{CustomField1}|%X{CustomField2}|%X{CustomField3}|%X{CustomField4}|%msg%n" />
-->
<property name="defaultAuditPattern" value="%X{TransactionBeginTimestamp}|%X{TransactionEndTimestamp}|%X{requestId}|%X{serviceInstanceId}|%t|%X{serverName}|%X{serviceName}|%X{partnerName}|%X{statusCode}|%X{ResponseCode}|%X{ResponseDescription}|%X{instanceUuid}|%p|%X{severity}|%X{serverIpAddress}|%X{TransactionElapsedTime}|%X{server}|%X{clientIpAddress}|%c||%X{ProcessKey}|%X{CustomField1}|%X{CustomField2}|%X{CustomField3}|%X{CustomField4}|%msg%n" />
-
-
-
- <!-- M E T R I C
- <property name="defaultMetricPattern" value="%X{BeginTimestamp}|%X{EndTimestamp}|%X{RequestId}|%X{ServiceInstanceId}|%thread|%X{ServerName}|%X{ServiceName}|%X{PartnerName}|%X{TargetEntity}|%X{TargetServiceName}|%X{StatusCode}|%X{ResponseCode}|%X{ResponseDescription}|%X{InstanceUUID}|%.-5level|%X{AlertSeverity}|%X{ServerIPAddress}|%X{ElapsedTime}|%X{ServerFQDN}|%X{RemoteHost}|%X{ClassName}||%X{ProcessKey}|%X{TargetVirtualEntity}|%X{CustomField1}|%X{CustomField2}|%X{CustomField3}|%X{CustomField4}|%msg%n" />
+
+
+
+ <!-- M E T R I C
+ <property name="defaultMetricPattern" value="%X{BeginTimestamp}|%X{EndTimestamp}|%X{RequestId}|%X{ServiceInstanceId}|%thread|%X{ServerName}|%X{ServiceName}|%X{PartnerName}|%X{TargetEntity}|%X{TargetServiceName}|%X{StatusCode}|%X{ResponseCode}|%X{ResponseDescription}|%X{InstanceUUID}|%.-5level|%X{Severity}|%X{ServerIPAddress}|%X{ElapsedTime}|%X{ServerFQDN}|%X{RemoteHost}|%X{ClassName}||%X{ProcessKey}|%X{TargetVirtualEntity}|%X{CustomField1}|%X{CustomField2}|%X{CustomField3}|%X{CustomField4}|%msg%n" />
-->
<property name="defaultMetricPattern" value="%X{MetricBeginTimestamp}|%X{MetricEndTimestamp}|%X{requestId}|%X{serviceInstanceId}|%t|%X{serverName}|%X{serviceName}|%X{partnerName}|%X{targetEntity}|%X{targetServiceName}|%X{statusCode}|%X{ResponseCode}|%X{ResponseDescription}|%X{InstanceUUID}|%p|%X{severity}|%X{serverIpAddress}|%X{MetricElapsedTime}|%X{server}|%X{clientIpAddress}|%c||%X{ProcessKey}|%X{TargetVirtualEntity}|%X{CustomField1}|%X{CustomField2}|%X{CustomField3}|%X{CustomField4}|%msg%n" />
-
-
-
-
+
+
+
+
<!-- E R R O R
<property name="defaultErrorPattern" value="%d{yyyy-MM-dd'T'HH:mm:ss.SSS+00:00, UTC}|%X{RequestId}|%thread|%X{ServiceName}|%X{PartnerName}|%X{TargetEntity}|%X{TargetServiceName}|%X{ErrorCategory}|%X{ErrorCode}|%X{ErrorDesciption}|%msg%n" />
-->
<property name="defaultErrorPattern" value="%d{yyyy-MM-dd'T'HH:mm:ss.SSS+00:00, UTC}|%X{requestId}|%t|%X{serviceName}|%X{PartnerName}|%X{TargetEntity}|%X{TargetServiceName}|%X{ErrorCategory}|%X{ErrorCode}|%X{ErrorDesciption}|%msg%n" />
-
-
-
+
+
+
<!-- D E B U G
- <property name="debugLoggerPatternOld" value="%d{MM/dd-HH:mm:ss.SSS}|%X{RequestId}|%X{ServiceInstanceId}|%thread|%X{ServiceName}|%X{InstanceUUID}|%.-5level|%X{AlertSeverity}|%X{ServerIPAddress}|%X{ServerFQDN}|%X{RemoteHost}|%X{Timer}|[%caller{3}]|%msg%n" />
- <property name="debugLoggerPattern" value="%X{BeginTimestamp}|%X{EndTimestamp}|%X{RequestId}|%X{ServiceInstanceId}|%thread|%X{ServerName}|%X{ServiceName}|%X{PartnerName}|%X{StatusCode}|%X{ResponseCode}|%X{ResponseDescription}|%X{ServiceName}|%X{InstanceUUID}|%.-5level|%X{AlertSeverity}|%X{ServerIPAddress}|%X{ElapsedTime}|%X{ServerFQDN}|%X{RemoteHost}|%X{ClassName}||%X{ProcessKey}|%X{CustomField1}|%X{CustomField2}|%X{CustomField3}|%X{CustomField4}|%msg%n" /> -->
+ <property name="debugLoggerPatternOld" value="%d{MM/dd-HH:mm:ss.SSS}|%X{RequestId}|%X{ServiceInstanceId}|%thread|%X{ServiceName}|%X{InstanceUUID}|%.-5level|%X{Severity}|%X{ServerIPAddress}|%X{ServerFQDN}|%X{RemoteHost}|%X{Timer}|[%caller{3}]|%msg%n" />
+ <property name="debugLoggerPattern" value="%X{BeginTimestamp}|%X{EndTimestamp}|%X{RequestId}|%X{ServiceInstanceId}|%thread|%X{ServerName}|%X{ServiceName}|%X{PartnerName}|%X{StatusCode}|%X{ResponseCode}|%X{ResponseDescription}|%X{ServiceName}|%X{InstanceUUID}|%.-5level|%X{Severity}|%X{ServerIPAddress}|%X{ElapsedTime}|%X{ServerFQDN}|%X{RemoteHost}|%X{ClassName}||%X{ProcessKey}|%X{CustomField1}|%X{CustomField2}|%X{CustomField3}|%X{CustomField4}|%msg%n" /> -->
-->
- <property name="debugLoggerPattern" value="%d{yyyy-MM-dd'T'HH:mm:ss.SSS+00:00, UTC}|%X{RequestId}|%msg%n" />
-
-
-
- <!-- D E F A U L T
- <property name="defaultPatternOld" value="%d{MM/dd-HH:mm:ss.SSS}|%logger|%X{RequestId}|%X{ServiceInstanceId}|%thread|%X{ServiceName}|%X{InstanceUUID}|%.-5level|%X{AlertSeverity}|%X{ServerIPAddress}|%X{ServerFQDN}|%X{RemoteHost}|%X{ClassName}|%X{Timer}|%msg%n" />
- <property name="defaultPattern" value="%X{BeginTimestamp}|%X{EndTimestamp}|%X{RequestId}|%X{ServiceInstanceId}|%thread|%X{ServerName}|%X{ServiceName}|%X{PartnerName}|%X{TargetEntity}|%X{TargetServiceName}|%X{StatusCode}|%X{ResponseCode}|%X{ResponseDescription}|%X{InstanceUUID}|%.-5level|%X{AlertSeverity}|%X{ServerIPAddress}|%X{ElapsedTime}|%X{ServerFQDN}|%X{RemoteHost}|%X{ClassName}||%X{ProcessKey}|%X{TargetVirtualEntity}|%X{CustomField1}|%X{CustomField2}|%X{CustomField3}|%X{CustomField4}|%msg%n" />
+ <property name="debugLoggerPattern" value="%d{yyyy-MM-dd'T'HH:mm:ss.SSS+00:00, UTC}|%X{RequestId}|%msg%n" />
+
+
+
+ <!-- D E F A U L T
+ <property name="defaultPatternOld" value="%d{MM/dd-HH:mm:ss.SSS}|%logger|%X{RequestId}|%X{ServiceInstanceId}|%thread|%X{ServiceName}|%X{InstanceUUID}|%.-5level|%X{Severity}|%X{ServerIPAddress}|%X{ServerFQDN}|%X{RemoteHost}|%X{ClassName}|%X{Timer}|%msg%n" />
+ <property name="defaultPattern" value="%X{BeginTimestamp}|%X{EndTimestamp}|%X{RequestId}|%X{ServiceInstanceId}|%thread|%X{ServerName}|%X{ServiceName}|%X{PartnerName}|%X{TargetEntity}|%X{TargetServiceName}|%X{StatusCode}|%X{ResponseCode}|%X{ResponseDescription}|%X{InstanceUUID}|%.-5level|%X{Severity}|%X{ServerIPAddress}|%X{ElapsedTime}|%X{ServerFQDN}|%X{RemoteHost}|%X{ClassName}||%X{ProcessKey}|%X{TargetVirtualEntity}|%X{CustomField1}|%X{CustomField2}|%X{CustomField3}|%X{CustomField4}|%msg%n" />
-->
<property name="defaultPattern" value="%d{yyyy-MM-dd'T'HH:mm:ss.SSSXXX, UTC}|%X{requestId}|%X{serviceInstanceId}|%t|%X{serverName}|%X{serviceName}|%X{instanceUuid}|%p|%X{severity}|%X{serverIpAddress}|%X{server}|%X{clientIpAddress}|%c||%msg%n" />
-
-
-
+
+
+
<!-- P A T H
<property name="logDirectory" value="${catalina.base}/${logDir}/${componentName}/${subComponentName}" />
- <property name="debugLogDirectory" value="${catalina.base}/${debugDir}/${componentName}/${subComponentName}" />
- -->
+ <property name="debugLogDirectory" value="${catalina.base}/${debugDir}/${componentName}/${subComponentName}" />
+ -->
<property name="logDirectory" value="${logDir}/${componentName}/${subComponentName}" />
<property name="debugLogDirectory" value="${debugDir}/${componentName}/${subComponentName}" />
-
-
-
+
+
+
<!-- Example evaluator filter applied against console appender -->
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
@@ -100,15 +100,15 @@
<!-- EELF Appenders -->
<!-- ============================================================================ -->
- <!-- The EELFAppender is used to record events to the general application
+ <!-- The EELFAppender is used to record events to the general application
log -->
-
- <!-- EELF Audit Appender. This appender is used to record audit engine
- related logging events. The audit logger and appender are specializations
- of the EELF application root logger and appender. This can be used to segregate
- Policy engine events from other components, or it can be eliminated to record
+
+ <!-- EELF Audit Appender. This appender is used to record audit engine
+ related logging events. The audit logger and appender are specializations
+ of the EELF application root logger and appender. This can be used to segregate
+ Policy engine events from other components, or it can be eliminated to record
these events as part of the application root log. -->
-
+
<appender name="EELFAudit"
class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>${logDirectory}/${auditLogName}.log</file>
@@ -151,12 +151,12 @@
<maxFileSize>5MB</maxFileSize>
</triggeringPolicy>
<encoder>
- <!-- <pattern>"%d{HH:mm:ss.SSS} [%thread] %-5level %logger{1024} -
+ <!-- <pattern>"%d{HH:mm:ss.SSS} [%thread] %-5level %logger{1024} -
%msg%n"</pattern> -->
<pattern>${defaultMetricPattern}</pattern>
</encoder>
</appender>
-
+
<appender name="asyncEELFMetrics" class="ch.qos.logback.classic.AsyncAppender">
<queueSize>256</queueSize>
<appender-ref ref="EELFMetrics"/>
@@ -164,7 +164,7 @@
-
+
<appender name="EELFError"
class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>${logDirectory}/${errorLogName}.log</file>
@@ -186,14 +186,14 @@
<pattern>${defaultErrorPattern}</pattern>
</encoder>
</appender>
-
+
<appender name="asyncEELFError" class="ch.qos.logback.classic.AsyncAppender">
<queueSize>256</queueSize>
<appender-ref ref="EELFError"/>
</appender>
-
+
<appender name="EELFDebug"
class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>${debugLogDirectory}/${debugLogName}.log</file>
@@ -215,36 +215,36 @@
<pattern>${debugLoggerPattern}</pattern>
</encoder>
</appender>
-
+
<appender name="asyncEELFDebug" class="ch.qos.logback.classic.AsyncAppender">
<queueSize>256</queueSize>
<appender-ref ref="EELFDebug" />
<includeCallerData>true</includeCallerData>
</appender>
-
-
+
+
<!-- ============================================================================ -->
<!-- EELF loggers -->
<!-- ============================================================================ -->
-
+
<logger name="com.att.eelf.audit" level="info" additivity="false">
<appender-ref ref="asyncEELFAudit" />
</logger>
-
+
<logger name="com.att.eelf.metrics" level="info" additivity="false">
<appender-ref ref="asyncEELFMetrics" />
</logger>
-
+
<logger name="com.att.eelf.error" level="error" additivity="false">
<appender-ref ref="asyncEELFError" />
</logger>
-
+
<logger name="com.att.eelf.debug" level="info" additivity="false">
<appender-ref ref="asyncEELFDebug" />
</logger>
-
-
-
+
+
+
<root level="INFO">
<appender-ref ref="asyncEELFDebug" />
<appender-ref ref="asyncEELFError" />
diff --git a/ONAP-REST/pom.xml b/ONAP-REST/pom.xml
index 46ae78eb2..bfd298ce8 100644
--- a/ONAP-REST/pom.xml
+++ b/ONAP-REST/pom.xml
@@ -3,7 +3,7 @@
============LICENSE_START=======================================================
ONAP Policy Engine
================================================================================
- Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ Copyright (C) 2017-2018, 2020 AT&T Intellectual Property. All rights reserved.
================================================================================
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
@@ -20,12 +20,13 @@
-->
<!-- Apache Maven 2 POM generated by Apache Ivy http://ant.apache.org/ivy/
Apache Ivy version: 2.0.0-beta1 20071206070608 -->
-<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.onap.policy.engine</groupId>
<artifactId>PolicyEngineSuite</artifactId>
- <version>1.4.1-SNAPSHOT</version>
+ <version>1.6.4-SNAPSHOT</version>
</parent>
<artifactId>ONAP-REST</artifactId>
<description>ONAP REST</description>
@@ -39,7 +40,6 @@
<dependency>
<groupId>org.yaml</groupId>
<artifactId>snakeyaml</artifactId>
- <version>1.16</version>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
@@ -79,6 +79,11 @@
<artifactId>javax.servlet-api</artifactId>
</dependency>
<dependency>
+ <groupId>org.apache.commons</groupId>
+ <artifactId>commons-lang3</artifactId>
+ <version>3.9</version>
+ </dependency>
+ <dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.1.3</version>
@@ -158,6 +163,12 @@
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>${hibernate.version}</version>
+ <exclusions>
+ <exclusion>
+ <groupId>xml-apis</groupId>
+ <artifactId>xml-apis</artifactId>
+ </exclusion>
+ </exclusions>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
@@ -169,5 +180,11 @@
<artifactId>tomcat-dbcp</artifactId>
<version>8.5.9</version>
</dependency>
+ <dependency>
+ <groupId>org.onap.policy.common</groupId>
+ <artifactId>utils-test</artifactId>
+ <version>${version.policy.common}</version>
+ <scope>test</scope>
+ </dependency>
</dependencies>
</project>
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
index 184d1ff60..10b3cbfb4 100644
--- a/ONAP-REST/src/main/java/org/onap/policy/rest/XacmlAdminAuthorization.java
+++ b/ONAP-REST/src/main/java/org/onap/policy/rest/XacmlAdminAuthorization.java
@@ -3,13 +3,14 @@
* ONAP-REST
* ================================================================================
* Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2019 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -32,9 +33,10 @@ public class XacmlAdminAuthorization {
String userRole;
- Role(String a) {
- this.userRole = a;
+ Role(String userRole) {
+ this.userRole = userRole;
}
+
@Override
public String toString() {
return this.userRole;
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
index 7cced5667..011fb8868 100644
--- a/ONAP-REST/src/main/java/org/onap/policy/rest/XACMLRest.java
+++ b/ONAP-REST/src/main/java/org/onap/policy/rest/XacmlRest.java
@@ -4,13 +4,14 @@
* ================================================================================
* Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
* Modified Copyright (C) 2018 Samsung Electronics Co., Ltd.
+ * Modifications Copyright (C) 2019 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -21,6 +22,8 @@
package org.onap.policy.rest;
+import com.att.research.xacml.util.XACMLProperties;
+
import java.io.IOException;
import java.util.Enumeration;
import java.util.Map;
@@ -35,37 +38,31 @@ 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.
- *
+ * 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);
+public class XacmlRest {
+ private static final Log logger = LogFactory.getLog(XacmlRest.class);
private static Properties restProperties = new Properties();
- private XACMLRest(){
+ private XacmlRest() {
// Empty constructor
}
+
/**
- * 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:
+ * 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.
*
+ * <p>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.
+ * <p>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
*/
@@ -100,7 +97,7 @@ public class XACMLRest {
Enumeration<String> params = config.getInitParameterNames();
while (params.hasMoreElements()) {
String param = params.nextElement();
- if (! "XACML_PROPERTIES_NAME".equals(param)) {
+ if (!"XACML_PROPERTIES_NAME".equals(param)) {
String value = config.getInitParameter(param);
PolicyLogger.info(param + "=" + config.getInitParameter(param));
restProperties.setProperty(param, value);
@@ -109,15 +106,14 @@ public class XACMLRest {
}
/**
- * 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.
+ * 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.
+ * <p>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
+ * @param policyProperties - Policy configuration properties
*/
public static void loadXacmlProperties(Properties policyProperties, Properties pipProperties) {
try {
@@ -128,7 +124,7 @@ public class XACMLRest {
//
// Now load our init properties
//
- XACMLProperties.getProperties().putAll(XACMLRest.restProperties);
+ XACMLProperties.getProperties().putAll(XacmlRest.restProperties);
//
// Load our policy properties
//
@@ -142,7 +138,8 @@ public class XACMLRest {
XACMLProperties.getProperties().putAll(pipProperties);
}
} catch (IOException e) {
- PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "Failed to put init properties into Xacml properties");
+ PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e,
+ "Failed to put init properties into Xacml properties");
}
//
// Dump them
@@ -166,12 +163,26 @@ public class XACMLRest {
return;
}
- // special-case for receiving heartbeat - don't need to repeatedly output all of the information in multiple lines
- if ("GET".equals(request.getMethod()) && "hb".equals(request.getParameter("type")) ) {
+ // special-case for receiving heartbeat - don't need to repeatedly output all of the information in multiple
+ // lines
+ if ("GET".equals(request.getMethod()) && "hb".equals(request.getParameter("type"))) {
PolicyLogger.debug("GET type=hb : heartbeat received");
return;
}
- logger.debug(request.getMethod() + ":" + request.getRemoteAddr() + " " + request.getRemoteHost() + " " + request.getRemotePort());
+
+ dumpRequestHeadersAttributesContextPath(request);
+
+ dumpRequestBody(request);
+ }
+
+ /**
+ * Dump the headers, attributes, and context path of the request.
+ *
+ * @param request the request to dump
+ */
+ private static void dumpRequestHeadersAttributesContextPath(HttpServletRequest request) {
+ logger.debug(request.getMethod() + ":" + request.getRemoteAddr() + " " + request.getRemoteHost() + " "
+ + request.getRemotePort());
logger.debug(request.getLocalAddr() + " " + request.getLocalName() + " " + request.getLocalPort());
Enumeration<String> en = request.getHeaderNames();
logger.debug("Headers:");
@@ -190,9 +201,20 @@ public class XACMLRest {
logger.debug(element + ":" + request.getAttribute(element));
}
logger.debug("ContextPath: " + request.getContextPath());
+ }
+
+
+ /**
+ * Dump the body of the request.
+ *
+ * @param request the request to act on
+ */
+ private static void dumpRequestBody(HttpServletRequest request) {
if ("PUT".equals(request.getMethod()) || "POST".equals(request.getMethod())) {
- // 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).
+ // 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.
@@ -204,7 +226,7 @@ public class XACMLRest {
logger.debug("Content available: " + request.getInputStream().available());
}
} catch (Exception e) {
- logger.debug("Content: inputStream exception: " + e.getMessage() + "; (May not be relevant)" +e);
+ logger.debug("Content: inputStream exception: " + e.getMessage() + "; (May not be relevant)" + e);
}
} else {
logger.debug("Parameters:");
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
index f7f887cef..f75f80c7c 100644
--- a/ONAP-REST/src/main/java/org/onap/policy/rest/XACMLRestProperties.java
+++ b/ONAP-REST/src/main/java/org/onap/policy/rest/XacmlRestProperties.java
@@ -3,6 +3,7 @@
* ONAP-REST
* ================================================================================
* Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2019 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -23,52 +24,48 @@ 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.
+ * These are XACML Properties that are relevant to the RESTful API interface for the PDP, PAP and AC interfaces.
*
*
*/
-public class XACMLRestProperties extends XACMLProperties {
+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.
+ * 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/
+ * <p>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.
+ * 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
+ * <p>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
+ // 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.
+ * 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.
+ * 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.
+ * 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.
+ * 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
+ * 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";
/**
@@ -76,55 +73,48 @@ public class XACMLRestProperties extends XACMLProperties {
*/
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
+ * 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.
+ * 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.
+ * 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";
/**
- * Upon startup, have the PAP servlet send latest configuration information
- * to all the PDP nodes it knows about.
+ * 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.
+ * 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.
+ * 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
+ * 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.
+ * 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.
+ * Local path to where the GIT repository exists.
*
* Eg. /opt/app/xacml/repository
*/
@@ -166,8 +156,8 @@ public class XACMLRestProperties extends XACMLProperties {
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.
+ * 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";
@@ -181,12 +171,12 @@ public class XACMLRestProperties extends XACMLProperties {
*/
public static final String PROP_PAP_NOTIFY_TIMEOUT = "xacml.rest.pap.notify.timeoutms";
/*
- * Value for Enable/Disable of AutoPush Flag.
+ * 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.
+ * Properties file for the AutoPush Functionality.
*/
public static final String PROP_PAP_PUSH_FILE = "xacml.rest.pap.autopush.file";
@@ -197,14 +187,12 @@ public class XACMLRestProperties extends XACMLProperties {
*/
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.
+ * 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.
+ * This is the domain you can setup for your organization, it should be a URI.
*
* Eg. com:sample:foo
*/
@@ -212,38 +200,33 @@ public class XACMLRestProperties extends XACMLProperties {
/**
* 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.
+ * <p>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");
+ * <p>((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
+ * <p>Eg. hs1234
*
- * @see #PROP_ADMIN_USER_NAME for more information.
+ * <p>@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.
+ * 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";
/**
@@ -251,8 +234,7 @@ public class XACMLRestProperties extends XACMLProperties {
*/
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.
+ * 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";
/**
@@ -305,7 +287,7 @@ public class XACMLRestProperties extends XACMLProperties {
/*
* webapps Location of the PAP-REST server
*/
- public static final String PROP_PAP_WEBAPPS= "xacml.rest.config.webapps";
+ public static final String PROP_PAP_WEBAPPS = "xacml.rest.config.webapps";
/*
* Value for Notification Option
*/
@@ -317,27 +299,27 @@ public class XACMLRestProperties extends XACMLProperties {
/*
* Value for Notification Delay
*/
- public static final String PROP_NOTIFICATION_DELAY= "NOTIFICATION_DELAY";
+ public static final String PROP_NOTIFICATION_DELAY = "NOTIFICATION_DELAY";
/*
* Value for Notification Topic
*/
- public static final String PROP_NOTIFICATION_TOPIC= "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";
+ 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";
+ 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";
+ public static final String TEMPLATE_VERSION_FAULT = "xacml.rest.closedLoopFault";
/*
* Closedloop PM Policy Template Version
*/
- public static final String TemplateVersion_PM= "xacml.rest.closedLoopPM";
+ public static final String TEMPLATE_VERSION_PM = "xacml.rest.closedLoopPM";
/*
* Value for model properties file
*/
@@ -345,89 +327,88 @@ public class XACMLRestProperties extends XACMLProperties {
/*
* MicroService Policy Template Version
*/
- public static final String TemplateVersion_MS= "xacml.rest.microServices";
+ public static final String TEMPLATE_VERSION_MS = "xacml.rest.microServices";
/*
* Optimization Policy Template Version
*/
- public static final String TemplateVersion_OOF= "xacml.rest.optimization";
+ public static final String TEMPLATE_VERSION_OOF = "xacml.rest.optimization";
/*
* Firewall Policy Template Version
*/
- public static final String TemplateVersion_FW= "xacml.rest.firewallPolicy";
+ public static final String TEMPLATE_VERSION_FW = "xacml.rest.firewallPolicy";
/*
- * Size of SelectList for Users in MS
+ * Size of SelectList for Users in MS
*
- */
- public static final String PROP_USER_SELECTLIST_WINDOW_SIZE= "xacml.user.column.count";
+ */
+ 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";
+ 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";
+ public static final String PROP_TEST_ENVIRONMENT_LOGINID = "xacml.testEnvironment.loginId";
/*
- * Size of of the page length for sqlcontainer
+ * Size of of the page length for sqlcontainer
*
- */
- public static final String PROP_SQLCONTAINER_PAGE_LENGTH= "xacml.sqlcontainer.page.length";
+ */
+ public static final String PROP_SQLCONTAINER_PAGE_LENGTH = "xacml.sqlcontainer.page.length";
/*
- * add values used to connect to restful api
+ * add values used to connect to restful api
*
- */
- public static final String PROP_RESTFUL_INTERFACE= "xacm.restful.interface.file";
+ */
+ public static final String PROP_RESTFUL_INTERFACE = "xacm.restful.interface.file";
/*
- * add pattern to identify what values are designed as required
+ * add pattern to identify what values are designed as required
*
- */
- public static final String PROP_XCORE_REQUIRED_PATTERN= "xacm.xcor.required.pattern";
+ */
+ public static final String PROP_XCORE_REQUIRED_PATTERN = "xacm.xcor.required.pattern";
/*
- * Time before a cache value is evicted
+ * Time before a cache value is evicted
*
- */
- public static final String PROP_CACHE_LIVE_TIME= "xacm.cache.live.time";
+ */
+ public static final String PROP_CACHE_LIVE_TIME = "xacm.cache.live.time";
/*
- * Highest value allowed in priority
+ * Highest value allowed in priority
*
- */
- public static final String PROP_PRIORITY_COUNT= "xacml.max.priority.count";
+ */
+ public static final String PROP_PRIORITY_COUNT = "xacml.max.priority.count";
/*
- * The name of the PAP. Must be unique across the system
+ * The name of the PAP. Must be unique across the system
*/
- public static final String PAP_RESOURCE_NAME="xacml.rest.pap.resource.name";
+ 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";
+ 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";
+ 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.
+ * 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";
+ 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
+ * 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
+ * The name of the Admin. Must be unique across the system
*/
- public static final String ADMIN_RESOURCE_NAME="xacml.rest.admin.resource.name";
+ public static final String ADMIN_RESOURCE_NAME = "xacml.rest.admin.resource.name";
/*
- * The name of the PDP. Must be unique across the system
+ * The name of the PDP. Must be unique across the system
*/
- public static final String PDP_RESOURCE_NAME="xacml.rest.pdp.resource.name";
+ 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";
+ public static final String PROP_AUTOMATIC_POLICYPUSH = "xacml.automatic.push";
/*
* Add Limit for Onap Portal Dashboard tab data
*/
@@ -444,7 +425,7 @@ public class XACMLRestProperties extends XACMLProperties {
/*
* The number of Risk Levels allowed
*/
- public static final String ADMIN_RISK_LEVEL_COUNT="xacml.risk.level.count";
+ public static final String ADMIN_RISK_LEVEL_COUNT = "xacml.risk.level.count";
/*
* The maxium Level displayed on the UI for Micro Services
*/
@@ -453,7 +434,7 @@ public class XACMLRestProperties extends XACMLProperties {
/*
* Value for Incoming Notification tries
*
- * */
+ */
public static final String PROP_PAP_INCOMINGNOTIFICATION_TRIES = "xacml.rest.pap.incomingnotification.tries";
/*
@@ -463,7 +444,7 @@ public class XACMLRestProperties extends XACMLProperties {
// Static class, hide constructor
- private XACMLRestProperties() {
+ private XacmlRestProperties() {
super();
}
}
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
index 0a3f46c78..e7879a855 100644
--- 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
@@ -23,7 +23,9 @@ package org.onap.policy.rest.adapter;
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 {
@@ -1154,4 +1156,55 @@ public class PolicyRestAdapter {
public void setUiJsonBody(String uiJsonBody) {
this.uiJsonBody = uiJsonBody;
}
+
+ public boolean setupUsingAttribute(String attributeId, String value) {
+ switch (attributeId) {
+ case "ONAPName":
+ this.setOnapName(value);
+ OnapName tempOnapName = new OnapName();
+ tempOnapName.setName(value);
+ this.setOnapNameField(tempOnapName);
+ return true;
+ case "RiskType":
+ this.setRiskType(value);
+ return true;
+ case "RiskLevel":
+ this.setRiskLevel(value);
+ return true;
+ case "guard":
+ this.setGuard(value);
+ return true;
+ case "ConfigName":
+ this.setConfigName(value);
+ return true;
+ case "uuid":
+ this.setUuid(value);
+ return true;
+ case "location":
+ this.setLocation(value);
+ return true;
+ case "TTLDate":
+ if (!value.contains("NA")) {
+ this.setTtlDate(PolicyRestAdapter.convertDate(value));
+ return true;
+ }
+ return false;
+ default:
+ return false;
+ }
+ }
+
+ /**
+ * Function to convert date.
+ *
+ * @param dateTimeToLive input date value.
+ * @return
+ */
+ private static String convertDate(String dateTimeToLive) {
+ String formatDate = null;
+ if (dateTimeToLive.contains("-")) {
+ formatDate = dateTimeToLive.replace("-", "/");
+ }
+ return formatDate;
+ }
}
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
index 0056a2bf5..6bc9a646e 100644
--- 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
@@ -3,6 +3,7 @@
* ONAP-REST
* ================================================================================
* Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2019 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -22,37 +23,46 @@ package org.onap.policy.rest.dao;
import java.util.List;
-import org.onap.policy.rest.jpa.PolicyRoles;
import javax.script.SimpleBindings;
+import org.onap.policy.rest.jpa.PolicyRoles;
+
public interface CommonClassDao {
- //Common methods
+ // Common methods
List<Object> getData(@SuppressWarnings("rawtypes") Class className);
+
List<Object> getDataById(@SuppressWarnings("rawtypes") Class className, String columnName, String key);
+
List<String> getDataByColumn(@SuppressWarnings("rawtypes") Class className, String columnName);
- List<Object> checkDuplicateEntry(String value, String columnName, @SuppressWarnings("rawtypes") Class className);
+
+ List<Object> checkDuplicateEntry(String value, String columnName, @SuppressWarnings("rawtypes") Class className);
+
Object getEntityItem(@SuppressWarnings("rawtypes") Class className, String columnName, String key);
- List<Object> getDataByQuery(String query, SimpleBindings params);
- List<Object> getMultipleDataOnAddingConjunction(@SuppressWarnings("rawtypes") Class className, String columnName, List<String> data);
+
+ List<Object> getDataByQuery(String query, SimpleBindings params);
+
+ List<Object> getMultipleDataOnAddingConjunction(@SuppressWarnings("rawtypes") Class className, String columnName,
+ List<String> data);
+
void save(Object entity);
+
void delete(Object entity);
+
void update(Object entity);
+
void updateQuery(String query);
- //Group Policy Scope
+ // Group Policy Scope
List<Object> checkExistingGroupListforUpdate(String groupListValue, String groupNameValue);
-
- //Roles
+ // Roles
List<PolicyRoles> getUserRoles();
-
- //ClosedLoops
+ // ClosedLoops
void updateClAlarms(String clName, String alarms);
- void updateClYaml(String clName, String yaml);
- void deleteAll();
-
+ void updateClYaml(String clName, String yaml);
+ void deleteAll();
}
diff --git a/ONAP-REST/src/main/java/org/onap/policy/rest/dao/PolicyDBException.java b/ONAP-REST/src/main/java/org/onap/policy/rest/dao/PolicyDbException.java
index df6bf12b2..4a982ccc0 100644
--- a/ONAP-REST/src/main/java/org/onap/policy/rest/dao/PolicyDBException.java
+++ b/ONAP-REST/src/main/java/org/onap/policy/rest/dao/PolicyDbException.java
@@ -3,6 +3,7 @@
* ONAP-REST
* ================================================================================
* Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2019 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -21,30 +22,30 @@
package org.onap.policy.rest.dao;
/**
- * PolicyDBException extends <code>Exception</code> to implement exceptions thrown by Policy Database transactions.
- *
+ * PolicyDBException extends <code>Exception</code> to implement exceptions thrown by Policy Database transactions.
+ *
* @version 0.1
*/
-public class PolicyDBException extends Exception {
+public class PolicyDbException extends Exception {
private static final long serialVersionUID = -6162444281003852781L;
- public PolicyDBException() {
+ public PolicyDbException() {
// Empty constructor
}
-
- public PolicyDBException(String message) {
+
+ public PolicyDbException(String message) {
super(message);
}
-
- public PolicyDBException(Throwable cause){
+
+ public PolicyDbException(Throwable cause) {
super(cause);
}
-
- public PolicyDBException(String message, Throwable cause) {
+
+ public PolicyDbException(String message, Throwable cause) {
super(message, cause);
}
-
- public PolicyDBException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
+
+ public PolicyDbException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
}
}
diff --git a/ONAP-REST/src/main/java/org/onap/policy/rest/daoimpl/PolicyValidationDaoImpl.java b/ONAP-REST/src/main/java/org/onap/policy/rest/daoimpl/PolicyValidationDaoImpl.java
index 66401ccb3..f64b9ce19 100644
--- a/ONAP-REST/src/main/java/org/onap/policy/rest/daoimpl/PolicyValidationDaoImpl.java
+++ b/ONAP-REST/src/main/java/org/onap/policy/rest/daoimpl/PolicyValidationDaoImpl.java
@@ -3,13 +3,14 @@
* ONAP Policy Engine
* ================================================================================
* Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2019 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -17,6 +18,7 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.policy.rest.daoimpl;
import java.util.ArrayList;
@@ -45,28 +47,28 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
-public class PolicyValidationDaoImpl implements CommonClassDao{
+public class PolicyValidationDaoImpl implements CommonClassDao {
private static final Logger LOGGER = FlexLogger.getLogger(PolicyValidationDaoImpl.class);
private static final String DB_CONNECTION_CLOSING_ERROR = "Error While Closing Connection/Statement";
private static final String DBTABLE_QUERY_ERROR = "Error While Querying Table";
private static SessionFactory sessionfactory;
-
- public static SessionFactory getSessionfactory() {
- return sessionfactory;
+
+ @Autowired
+ private PolicyValidationDaoImpl(SessionFactory sessionfactory) {
+ PolicyValidationDaoImpl.sessionfactory = sessionfactory;
}
- public static void setSessionfactory(SessionFactory sessionfactory) {
- PolicyValidationDaoImpl.sessionfactory = sessionfactory;
+ public PolicyValidationDaoImpl() {
+ // Default Constructor
}
- @Autowired
- private PolicyValidationDaoImpl(SessionFactory sessionfactory){
- PolicyValidationDaoImpl.sessionfactory = sessionfactory;
+ public static SessionFactory getSessionfactory() {
+ return sessionfactory;
}
-
- public PolicyValidationDaoImpl(){
- //Default Constructor
+
+ public static void setSessionfactory(SessionFactory sessionfactory) {
+ PolicyValidationDaoImpl.sessionfactory = sessionfactory;
}
@SuppressWarnings({ "unchecked", "rawtypes" })
@@ -74,16 +76,16 @@ public class PolicyValidationDaoImpl implements CommonClassDao{
public List<Object> getData(Class className) {
Session session = sessionfactory.openSession();
List<Object> data = null;
- try{
+ try {
Criteria cr = session.createCriteria(className);
data = cr.list();
- }catch(Exception e){
+ } catch (Exception e) {
LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + DBTABLE_QUERY_ERROR + e);
- }finally{
- try{
+ } finally {
+ try {
session.close();
- }catch(Exception e){
- LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + DB_CONNECTION_CLOSING_ERROR+e);
+ } catch (Exception e) {
+ LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + DB_CONNECTION_CLOSING_ERROR + e);
}
}
return data;
@@ -97,22 +99,22 @@ public class PolicyValidationDaoImpl implements CommonClassDao{
List<Object> data = null;
try {
Criteria cr = session.createCriteria(className);
- if(columnName.contains(":") && key.contains(":")){
+ if (columnName.contains(":") && key.contains(":")) {
String[] columns = columnName.split(":");
String[] keys = key.split(":");
- for(int i=0; i < columns.length; i++){
+ for (int i = 0; i < columns.length; i++) {
cr.add(Restrictions.eq(columns[i], keys[i]));
}
- }else{
+ } else {
cr.add(Restrictions.eq(columnName, key));
}
data = cr.list();
} catch (Exception e) {
LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + DBTABLE_QUERY_ERROR + e);
- }finally{
- try{
+ } finally {
+ try {
session.close();
- }catch(Exception e1){
+ } catch (Exception e1) {
LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + DB_CONNECTION_CLOSING_ERROR + e1);
}
}
@@ -126,12 +128,12 @@ public class PolicyValidationDaoImpl implements CommonClassDao{
try {
session.persist(entity);
tx.commit();
- }catch(Exception e){
- LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Saving data to Table"+e);
- }finally{
- try{
+ } catch (Exception e) {
+ LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Saving data to Table" + e);
+ } finally {
+ try {
session.close();
- }catch(Exception e1){
+ } catch (Exception e1) {
LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + DB_CONNECTION_CLOSING_ERROR + e1);
}
}
@@ -145,12 +147,12 @@ public class PolicyValidationDaoImpl implements CommonClassDao{
try {
session.delete(entity);
tx.commit();
- }catch(Exception e){
- LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Deleting data from Table"+e);
- }finally{
- try{
+ } catch (Exception e) {
+ LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Deleting data from Table" + e);
+ } finally {
+ try {
session.close();
- }catch(Exception e1){
+ } catch (Exception e1) {
LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + DB_CONNECTION_CLOSING_ERROR + e1);
}
}
@@ -165,12 +167,12 @@ public class PolicyValidationDaoImpl implements CommonClassDao{
try {
session.update(entity);
tx.commit();
- }catch(Exception e){
- LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Updating data to Table"+e);
- }finally{
- try{
+ } catch (Exception e) {
+ LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Updating data to Table" + e);
+ } finally {
+ try {
session.close();
- }catch(Exception e1){
+ } catch (Exception e1) {
LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + DB_CONNECTION_CLOSING_ERROR + e1);
}
}
@@ -185,30 +187,31 @@ public class PolicyValidationDaoImpl implements CommonClassDao{
Transaction tx = session.beginTransaction();
List<Object> data = null;
String[] columnNames = null;
- if(columnName != null && columnName.contains(":")){
+ if (columnName != null && columnName.contains(":")) {
columnNames = columnName.split(":");
}
String[] values = null;
- if(value != null && value.contains(":")){
+ 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]));
+ 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));
+ } 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{
+ LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Querying for Duplicate Entries for Table"
+ + e + className);
+ } finally {
+ try {
session.close();
- }catch(Exception e1){
+ } catch (Exception e1) {
LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + DB_CONNECTION_CLOSING_ERROR + e1);
}
}
@@ -223,13 +226,13 @@ public class PolicyValidationDaoImpl implements CommonClassDao{
Transaction tx = session.beginTransaction();
List<PolicyRoles> rolesData = null;
try {
- Criteria cr = session.createCriteria(PolicyRoles.class);
- Disjunction disjunction = Restrictions.disjunction();
- Conjunction conjunction1 = Restrictions.conjunction();
+ final Criteria cr = session.createCriteria(PolicyRoles.class);
+ final Disjunction disjunction = Restrictions.disjunction();
+ Conjunction conjunction1 = Restrictions.conjunction();
conjunction1.add(Restrictions.eq("role", "admin"));
- Conjunction conjunction2 = Restrictions.conjunction();
+ Conjunction conjunction2 = Restrictions.conjunction();
conjunction2.add(Restrictions.eq("role", "editor"));
- Conjunction conjunction3 = Restrictions.conjunction();
+ Conjunction conjunction3 = Restrictions.conjunction();
conjunction3.add(Restrictions.eq("role", "guest"));
disjunction.add(conjunction1);
disjunction.add(conjunction2);
@@ -237,11 +240,11 @@ public class PolicyValidationDaoImpl implements CommonClassDao{
rolesData = cr.add(disjunction).list();
tx.commit();
} catch (Exception e) {
- LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Querying PolicyRoles Table"+e);
- }finally{
- try{
+ LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Querying PolicyRoles Table" + e);
+ } finally {
+ try {
session.close();
- }catch(Exception e1){
+ } catch (Exception e1) {
LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + DB_CONNECTION_CLOSING_ERROR + e1);
}
}
@@ -270,10 +273,9 @@ public class PolicyValidationDaoImpl implements CommonClassDao{
try {
Query hbquery = session.createQuery(query);
for (Map.Entry<String, Object> paramPair : params.entrySet()) {
- if(paramPair.getValue() instanceof java.lang.Long){
+ if (paramPair.getValue() instanceof java.lang.Long) {
hbquery.setLong(paramPair.getKey(), (long) paramPair.getValue());
- }
- else{
+ } else {
hbquery.setParameter(paramPair.getKey(), paramPair.getValue());
}
}
@@ -282,10 +284,10 @@ public class PolicyValidationDaoImpl implements CommonClassDao{
} catch (Exception e) {
LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + DBTABLE_QUERY_ERROR + e);
throw e;
- }finally{
- try{
+ } finally {
+ try {
session.close();
- }catch(HibernateException e1){
+ } catch (HibernateException e1) {
LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + DB_CONNECTION_CLOSING_ERROR + e1);
}
}
@@ -301,23 +303,23 @@ public class PolicyValidationDaoImpl implements CommonClassDao{
Object data = null;
try {
Criteria cr = session.createCriteria(className);
- if(columnName.contains(":") && key.contains(":")){
+ if (columnName.contains(":") && key.contains(":")) {
String[] columns = columnName.split(":");
String[] keys = key.split(":");
- for(int i=0; i < columns.length; i++){
+ for (int i = 0; i < columns.length; i++) {
cr.add(Restrictions.eq(columns[i], keys[i]));
}
- }else{
+ } else {
cr.add(Restrictions.eq(columnName, key));
}
data = cr.list().get(0);
tx.commit();
} catch (Exception e) {
LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + DBTABLE_QUERY_ERROR + e);
- }finally{
- try{
+ } finally {
+ try {
session.close();
- }catch(Exception e1){
+ } catch (Exception e1) {
LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + DB_CONNECTION_CLOSING_ERROR + e1);
}
}
@@ -346,11 +348,11 @@ public class PolicyValidationDaoImpl implements CommonClassDao{
hbquery.executeUpdate();
tx.commit();
} catch (Exception e) {
- LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Updating Database Table"+e);
- }finally{
- try{
+ LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Updating Database Table" + e);
+ } finally {
+ try {
session.close();
- }catch(Exception e1){
+ } catch (Exception e1) {
LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + DB_CONNECTION_CLOSING_ERROR + e1);
}
}
@@ -363,16 +365,16 @@ public class PolicyValidationDaoImpl implements CommonClassDao{
public List<String> getDataByColumn(Class className, String columnName) {
Session session = sessionfactory.openSession();
List<String> data = null;
- try{
+ try {
Criteria cr = session.createCriteria(className);
cr.setProjection(Projections.property(columnName));
data = cr.list();
- }catch(Exception e){
+ } catch (Exception e) {
LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + DBTABLE_QUERY_ERROR + e);
- }finally{
- try{
+ } finally {
+ try {
session.close();
- }catch(Exception e){
+ } catch (Exception e) {
LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + DB_CONNECTION_CLOSING_ERROR + e);
}
}
@@ -391,24 +393,24 @@ public class PolicyValidationDaoImpl implements CommonClassDao{
Disjunction disjunction = Restrictions.disjunction();
List<Conjunction> conjunctionList = new ArrayList<>();
String[] columNames = columnName.split(":");
- for(int i =0; i < data.size(); i++){
+ 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++){
+ 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 + DBTABLE_QUERY_ERROR + className + e);
- }finally{
- try{
+ } finally {
+ try {
session.close();
- }catch(Exception e1){
+ } catch (Exception e1) {
LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + DB_CONNECTION_CLOSING_ERROR + e1);
}
}
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
index 16f6e7347..c0c009fb9 100644
--- 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
@@ -3,13 +3,14 @@
* ONAP-REST
* ================================================================================
* Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2019 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -17,12 +18,13 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.policy.rest.jpa;
-/*
- */
+
+import com.fasterxml.jackson.annotation.JsonBackReference;
+
import java.io.Serializable;
import java.util.Date;
-import java.util.Objects;
import javax.persistence.Column;
import javax.persistence.Entity;
@@ -38,190 +40,80 @@ import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.persistence.Version;
+
+import lombok.Getter;
+import lombok.NoArgsConstructor;
+import lombok.Setter;
+
/*
* The Entity class to persist a policy object Action Body
*/
-
-
-import com.fasterxml.jackson.annotation.JsonBackReference;
-
+// @formatter:off
@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")
-})
+@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")
+ }
+)
+@Getter
+@Setter
+@NoArgsConstructor
+// @foramtter:on
public class ActionBodyEntity implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
- @Column(name="actionBodyId")
+ @Column(name = "actionBodyId")
@JsonBackReference
private long actionBodyId;
- @Column(name="actionBodyName", nullable=false, length=255)
+ @Column(name = "actionBodyName", nullable = false, length = 255)
private String actionBodyName = "";
@Version
- @Column(name="version")
+ @Column(name = "version")
private int version;
@Lob
- @Column(name="actionBody", nullable=false, columnDefinition="TEXT")
+ @Column(name = "actionBody", nullable = false, columnDefinition = "TEXT")
private String actionBody = "NoBody";
- @Column(name="created_by", nullable=false, length=255)
+ @Column(name = "created_by", nullable = false, length = 255)
private String createdBy = "guest";
@Temporal(TemporalType.TIMESTAMP)
- @Column(name="created_date", updatable=false)
+ @Column(name = "created_date", updatable = false)
private Date createdDate;
- @Column(name="modified_by", nullable=false, length=255)
+ @Column(name = "modified_by", nullable = false, length = 255)
private String modifiedBy = "guest";
@Temporal(TemporalType.TIMESTAMP)
- @Column(name="modified_date", nullable=false)
+ @Column(name = "modified_date", nullable = false)
private Date modifiedDate;
- @Column(name="deleted", nullable=false)
+ @Column(name = "deleted", nullable = false)
private boolean deleted = false;
- public ActionBodyEntity() {
- //An empty constructor
- }
-
+ /**
+ * Called before an instance is persisted.
+ */
@PrePersist
- public void prePersist() {
+ public void prePersist() {
Date date = new Date();
this.createdDate = date;
this.modifiedDate = date;
}
+ /**
+ * Called before an instance is updated.
+ */
@PreUpdate
public void preUpdate() {
this.modifiedDate = new Date();
}
- /**
- * @return the configurationDataId
- */
- public long getActionBodyId() {
- return actionBodyId;
- }
- /**
- * @param name the configuration body name 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 body 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;
- }
-
- @Override
- public int hashCode() {
- return Objects.hash(actionBodyId, actionBodyName, version, actionBody,
- createdBy, createdDate, modifiedBy, modifiedDate, deleted);
- }
-
- @Override
- public boolean equals(Object obj) {
- if(obj == null){
- return false;
- }
- if(obj == this){
- return true;
- }
- if(!(obj instanceof ActionBodyEntity)){
- return false;
- }
-
- return actionBodyId == ((ActionBodyEntity) obj).actionBodyId &&
- actionBodyName.equals(((ActionBodyEntity) obj).actionBodyName) &&
- version == ((ActionBodyEntity) obj).version &&
- actionBody.equals(((ActionBodyEntity) obj).actionBody) &&
- createdBy.equals(((ActionBodyEntity) obj).createdBy) &&
- createdDate.equals(((ActionBodyEntity) obj).createdDate) &&
- modifiedBy.equals(((ActionBodyEntity) obj).modifiedBy) &&
- modifiedDate.equals(((ActionBodyEntity) obj).modifiedDate) &&
- deleted == ((ActionBodyEntity) obj).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
index d3e870bff..e72c4022d 100644
--- 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
@@ -3,13 +3,14 @@
* ONAP-REST
* ================================================================================
* Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2019 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -19,8 +20,7 @@
*/
package org.onap.policy.rest.jpa;
-/*
- */
+
import java.io.Serializable;
import javax.persistence.Column;
@@ -32,47 +32,26 @@ import javax.persistence.NamedQuery;
import javax.persistence.OrderBy;
import javax.persistence.Table;
+import lombok.Getter;
+import lombok.Setter;
+
@Entity
-@Table(name="actionlist")
-@NamedQuery(name="ActionList.findAll", query="SELECT e FROM ActionList e ")
+@Table(name = "actionlist")
+@NamedQuery(name = "ActionList.findAll", query = "SELECT e FROM ActionList e ")
+@Getter
+@Setter
public class ActionList implements Serializable {
private static final long serialVersionUID = 1L;
-
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
- @Column(name="id")
+ @Column(name = "id")
private int id;
- @Column(name="actionname", nullable=false)
+ @Column(name = "actionname", nullable = false)
@OrderBy("asc")
private String actionName;
- @Column(name="description")
+ @Column(name = "description")
private String description;
-
- 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
index e9a29446d..7847585c3 100644
--- 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
@@ -3,13 +3,14 @@
* ONAP-REST
* ================================================================================
* Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2019 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -18,9 +19,8 @@
* ============LICENSE_END=========================================================
*/
-/*
- */
package org.onap.policy.rest.jpa;
+
import java.io.Serializable;
import java.util.Date;
@@ -40,150 +40,85 @@ import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
+import lombok.Getter;
+import lombok.Setter;
+// @formatter:off
@Entity
-@Table(name="ActionPolicyDict")
-@NamedQueries({
- @NamedQuery(name="ActionPolicyDict.findAll", query="SELECT e FROM ActionPolicyDict e")
-})
+@Table(name = "ActionPolicyDict")
+@NamedQueries(
+ {
+ @NamedQuery(name = "ActionPolicyDict.findAll", query = "SELECT e FROM ActionPolicyDict e")
+ }
+)
+@Getter
+@Setter
+//@formatter:on
public class ActionPolicyDict implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
- @Column(name="id")
+ @Column(name = "id")
private int id;
- @Column(name="ATTRIBUTE_NAME", nullable=false)
+ @Column(name = "ATTRIBUTE_NAME", nullable = false)
@OrderBy("asc")
private String attributeName;
- @Column(name="Type", nullable=false)
+ @Column(name = "Type", nullable = false)
@OrderBy("asc")
private String type;
- @Column(name="URL", nullable=false)
+ @Column(name = "URL", nullable = false)
@OrderBy("asc")
private String url;
- @Column(name="Method", nullable=false)
+ @Column(name = "Method", nullable = false)
@OrderBy("asc")
private String method;
- @Column(name="Headers", nullable=true)
+ @Column(name = "Headers", nullable = true)
@OrderBy("asc")
private String header;
- @Column(name="Body", nullable=true)
+ @Column(name = "Body", nullable = true)
@OrderBy("asc")
private String body;
@Temporal(TemporalType.TIMESTAMP)
- @Column(name="created_date", updatable=false)
+ @Column(name = "created_date", updatable = false)
private Date createdDate;
- @Column(name="description", nullable=true, length=2048)
+ @Column(name = "description", nullable = true, length = 2048)
private String description;
@Temporal(TemporalType.TIMESTAMP)
- @Column(name="modified_date", nullable=false)
+ @Column(name = "modified_date", nullable = false)
private Date modifiedDate;
@ManyToOne(optional = false)
- @JoinColumn(name="created_by")
+ @JoinColumn(name = "created_by")
private UserInfo userCreatedBy;
@ManyToOne(optional = false)
- @JoinColumn(name="modified_by")
+ @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;
- }
-
+ /**
+ * Called before an instance is persisted.
+ */
@PrePersist
- public void prePersist() {
+ public void prePersist() {
Date date = new Date();
this.createdDate = date;
this.modifiedDate = date;
}
+
+ /**
+ * Called before an instance is updated.
+ */
@PreUpdate
public void preUpdate() {
this.modifiedDate = new 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 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
index c71969a8b..3d2c69aa0 100644
--- 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
@@ -3,13 +3,14 @@
* ONAP-REST
* ================================================================================
* Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2019 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -19,8 +20,7 @@
*/
package org.onap.policy.rest.jpa;
-/*
- */
+
import java.io.Serializable;
import javax.persistence.Column;
@@ -32,59 +32,62 @@ import javax.persistence.NamedQuery;
import javax.persistence.OrderBy;
import javax.persistence.Table;
+import lombok.Getter;
+import lombok.Setter;
+import lombok.ToString;
+
+/**
+ * The Class AddressGroup is a JPA class for address groups.
+ */
@Entity
-@Table(name="AddressGroup")
-@NamedQuery(name="AddressGroup.findAll", query="SELECT e FROM AddressGroup e ")
+@Table(name = "AddressGroup")
+@NamedQuery(name = "AddressGroup.findAll", query = "SELECT e FROM AddressGroup e ")
+
+@Getter
+@Setter
+@ToString
public class AddressGroup implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
- @Column(name="id")
+ @Column(name = "id")
private int id;
- @Column(name="name", nullable=false)
+ @Column(name = "name", nullable = false)
@OrderBy("asc")
private String name;
- @Column(name="prefixlist")
+ @Column(name = "prefixlist")
private String prefixList;
-
- @Column(name="description")
+ @Column(name = "description")
private String description;
- public int getId() {
- return this.id;
- }
-
- public void setId(int id) {
- this.id = id;
- }
+ /**
+ * Get the group name.
+ *
+ * @return the group name
+ */
public String getGroupName() {
- return this.name;
+ return name;
}
- public void setGroupName(String serviceName) {
- this.name = serviceName;
-
- }
-
- public String getPrefixList() {
- return this.prefixList;
+ /**
+ * Set the group name.
+ *
+ * @param groupName the group name
+ */
+ public void setGroupName(final String groupName) {
+ this.name = groupName;
}
+ /**
+ * Sets the service list.
+ *
+ * @param prefixList the new service list
+ */
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
index 3389d391e..4b8059e9c 100644
--- 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
@@ -3,13 +3,14 @@
* ONAP-REST
* ================================================================================
* Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2019 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -20,6 +21,8 @@
package org.onap.policy.rest.jpa;
+import com.fasterxml.jackson.annotation.JsonIgnore;
+
import java.io.Serializable;
import java.util.Date;
import java.util.HashSet;
@@ -43,77 +46,81 @@ import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.persistence.Transient;
-import com.fasterxml.jackson.annotation.JsonIgnore;
+import lombok.Getter;
+import lombok.NoArgsConstructor;
+import lombok.Setter;
/**
* 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")
+@Table(name = "Attribute")
+@NamedQuery(name = "Attribute.findAll", query = "SELECT a FROM Attribute a order by a.priority asc, a.xacmlId asc")
+
+@Getter
+@Setter
+@NoArgsConstructor
public class Attribute implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
- @Column(name="id")
+ @Column(name = "id")
private int id;
- //bi-directional many-to-one association to Category
+ // bi-directional many-to-one association to Category
@ManyToOne
- @JoinColumn(name="constraint_type", nullable=true)
+ @JoinColumn(name = "constraint_type", nullable = true)
@JsonIgnore
private ConstraintType constraintType;
@Temporal(TemporalType.TIMESTAMP)
- @Column(name="created_date", updatable=false)
+ @Column(name = "created_date", updatable = false)
private Date createdDate;
- @Column(name="description", nullable=true, length=2048)
+ @Column(name = "description", nullable = true, length = 2048)
private String description;
@Temporal(TemporalType.TIMESTAMP)
- @Column(name="modified_date", nullable=false)
+ @Column(name = "modified_date", nullable = false)
private Date modifiedDate;
- @Column(name="PRIORITY", nullable=true)
+ @Column(name = "PRIORITY", nullable = true)
@OrderBy("asc")
private String priority;
- @Column(name="ATTRIBUTE_VALUE", nullable=true)
+ @Column(name = "ATTRIBUTE_VALUE", nullable = true)
@OrderBy("asc")
private String attributeValue;
- @Column(name="xacml_id", unique = true, nullable=false)
+ @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)
+ // bi-directional many-to-one association to ConstraintValue
+ @OneToMany(mappedBy = "attribute", orphanRemoval = true, cascade = CascadeType.REMOVE)
@JsonIgnore
private Set<ConstraintValue> constraintValues = new HashSet<>();
- //bi-directional many-to-one association to Category
+ // bi-directional many-to-one association to Category
@ManyToOne
- @JoinColumn(name="category")
+ @JoinColumn(name = "category")
@JsonIgnore
private Category categoryBean;
- //bi-directional many-to-one association to Datatype
+ // bi-directional many-to-one association to Datatype
@ManyToOne
- @JoinColumn(name="datatype")
+ @JoinColumn(name = "datatype")
private Datatype datatypeBean;
- @Column(name="is_designator", nullable=false)
+ @Column(name = "is_designator", nullable = false)
@JsonIgnore
private char isDesignator = '1';
- @Column(name="selector_path", nullable=true, length=2048)
+ @Column(name = "selector_path", nullable = true, length = 2048)
private String selectorPath;
-
-
@Transient
private String issuer = null;
@@ -121,38 +128,27 @@ public class Attribute implements Serializable {
private boolean mustBePresent = false;
@ManyToOne(optional = false)
- @JoinColumn(name="created_by")
+ @JoinColumn(name = "created_by")
private UserInfo userCreatedBy;
@ManyToOne(optional = false)
- @JoinColumn(name="modified_by")
+ @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() {
- //An empty constructor
- }
-
+ /**
+ * Constructor with domain.
+ *
+ * @param domain the domain to use to construct the object
+ */
public Attribute(String domain) {
this.xacmlId = domain;
}
+ /**
+ * Copy constructor.
+ *
+ * @param copy the copy to copy from
+ */
public Attribute(Attribute copy) {
this(copy.getXacmlId() + ":(0)");
this.constraintType = copy.getConstraintType();
@@ -166,78 +162,45 @@ public class Attribute implements Serializable {
}
}
+ /**
+ * Called before an instance is persisted.
+ */
@PrePersist
- public void prePersist() {
+ public void prePersist() {
Date date = new Date();
this.createdDate = date;
this.modifiedDate = date;
}
+ /**
+ * Called before an instance is updated.
+ */
@PreUpdate
public void preUpdate() {
this.modifiedDate = new Date();
}
- 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;
- }
-
-
- public void setXacmlId(String xacmlId) {
- this.xacmlId = xacmlId;
- }
-
- public Set<ConstraintValue> getConstraintValues() {
- return this.constraintValues;
- }
-
+ /**
+ * Sets the constraint values.
+ *
+ * @param constraintValues the new constraint values
+ */
public void setConstraintValues(Set<ConstraintValue> constraintValues) {
+ if (this.constraintValues == null) {
+ this.constraintValues = new HashSet<>();
+ }
for (ConstraintValue value : this.constraintValues) {
value.setAttribute(this);
}
this.constraintValues = constraintValues;
}
+ /**
+ * Adds the constraint value.
+ *
+ * @param constraintValue the constraint value
+ * @return the constraint value
+ */
public ConstraintValue addConstraintValue(ConstraintValue constraintValue) {
if (this.constraintValues == null) {
this.constraintValues = new HashSet<>();
@@ -248,6 +211,12 @@ public class Attribute implements Serializable {
return constraintValue;
}
+ /**
+ * Removes the constraint value.
+ *
+ * @param constraintValue the constraint value
+ * @return the constraint value
+ */
public ConstraintValue removeConstraintValue(ConstraintValue constraintValue) {
this.constraintValues.remove(constraintValue);
constraintValue.setAttribute(null);
@@ -255,6 +224,9 @@ public class Attribute implements Serializable {
return constraintValue;
}
+ /**
+ * Removes the all constraint values.
+ */
public void removeAllConstraintValues() {
if (this.constraintValues == null) {
return;
@@ -265,63 +237,61 @@ public class Attribute implements Serializable {
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;
- }
-
+ /**
+ * Gets the issuer.
+ *
+ * @return the issuer
+ */
@Transient
public String getIssuer() {
return issuer;
}
+ /**
+ * Sets the issuer.
+ *
+ * @param issuer the new issuer
+ */
@Transient
public void setIssuer(String issuer) {
this.issuer = issuer;
}
+ /**
+ * Checks if is must be present.
+ *
+ * @return true, if is must be present
+ */
@Transient
public boolean isMustBePresent() {
return mustBePresent;
}
+ /**
+ * Sets the must be present.
+ *
+ * @param mustBePresent the new must be present
+ */
@Transient
public void setMustBePresent(boolean mustBePresent) {
this.mustBePresent = mustBePresent;
}
+ /**
+ * Checks if is designator.
+ *
+ * @return true, if is designator
+ */
@Transient
public boolean isDesignator() {
return this.isDesignator == '1';
}
+ /**
+ * Sets the checks if is designator.
+ *
+ * @param is the new checks if is designator
+ */
@Transient
public void setIsDesignator(boolean is) {
if (is) {
@@ -330,21 +300,4 @@ public class Attribute implements Serializable {
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
index d05b2d4af..8a40f4cf3 100644
--- 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
@@ -3,13 +3,14 @@
* ONAP-REST
* ================================================================================
* Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2019 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -17,6 +18,7 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.policy.rest.jpa;
import java.io.Serializable;
@@ -30,14 +32,20 @@ import javax.persistence.ManyToOne;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
+import lombok.Getter;
+import lombok.NoArgsConstructor;
+import lombok.Setter;
/**
* The persistent class for the ObadviceExpressions database table.
- *
+ *
*/
@Entity
-@Table(name="AttributeAssignment")
-@NamedQuery(name="AttributeAssignment.findAll", query="SELECT a FROM AttributeAssignment a")
+@Table(name = "AttributeAssignment")
+@NamedQuery(name = "AttributeAssignment.findAll", query = "SELECT a FROM AttributeAssignment a")
+@Getter
+@Setter
+@NoArgsConstructor
public class AttributeAssignment implements Serializable {
private static final long serialVersionUID = 1L;
@@ -50,45 +58,17 @@ public class AttributeAssignment implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
- @Column(name="id")
+ @Column(name = "id")
private int id;
- @Column(name="attribute_id")
+ @Column(name = "attribute_id")
private int attributeId;
- //bi-directional many-to-one association to Obadvice
- @Column(name="expression", nullable=false)
+ // bi-directional many-to-one association to Obadvice
+ @Column(name = "expression", nullable = false)
private String expression;
- //bi-directional many-to-one association to Obadvice
+ // bi-directional many-to-one association to Obadvice
@ManyToOne
private Obadvice obadvice;
-
- public AttributeAssignment() {
- //An empty constructor
- }
-
- 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
index af2b11a20..7eaf075fb 100644
--- 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
@@ -3,13 +3,14 @@
* ONAP-REST
* ================================================================================
* Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2019 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -38,117 +39,66 @@ import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
+import lombok.Getter;
+import lombok.Setter;
+
+/**
+ * The Class BRMSController.
+ */
@Entity
-@Table(name="BRMSController")
-@NamedQuery(name="BRMSController.findAll", query="SELECT b from BRMSController b ")
-public class BRMSController implements Serializable{
+@Table(name = "BrmsController")
+@NamedQuery(name = "BrmsController.findAll", query = "SELECT b from BrmsController b ")
+@Getter
+@Setter
+public class BrmsController implements Serializable {
private static final long serialVersionUID = -8666947569754164177L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
- @Column(name="id")
+ @Column(name = "id")
private int id;
-
- @Column(name="controller_name", nullable=false, length=1024, unique=true)
+
+ @Column(name = "controller_name", nullable = false, length = 1024, unique = true)
@OrderBy("asc")
private String controllerName;
-
- @Column(name="description", nullable=true, length=1024)
+
+ @Column(name = "description", nullable = true, length = 1024)
private String description;
-
+
@Temporal(TemporalType.TIMESTAMP)
- @Column(name="created_date", updatable=false)
+ @Column(name = "created_date", updatable = false)
private Date createdDate;
-
+
@ManyToOne(optional = false)
- @JoinColumn(name="created_by")
+ @JoinColumn(name = "created_by")
private UserInfo userCreatedBy;
-
+
@Temporal(TemporalType.TIMESTAMP)
- @Column(name="modified_date", nullable=false)
+ @Column(name = "modified_date", nullable = false)
private Date modifiedDate;
-
+
@ManyToOne(optional = false)
- @JoinColumn(name="modified_by")
+ @JoinColumn(name = "modified_by")
private UserInfo userModifiedBy;
-
- @Column(name="controller", nullable=false)
+
+ @Column(name = "controller", nullable = false)
private String controller;
-
+
+ /**
+ * Called before persisting an instance.
+ */
@PrePersist
public void prePersist() {
Date date = new Date();
this.createdDate = date;
this.modifiedDate = date;
}
-
+
+ /**
+ * Pre update.
+ */
@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
index d06ec5d92..1b6c89f89 100644
--- 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
@@ -3,13 +3,14 @@
* ONAP-REST
* ================================================================================
* Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2019 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -38,116 +39,66 @@ import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
+import lombok.Getter;
+import lombok.Setter;
+
+/**
+ * The Class BrmsDependency.
+ */
@Entity
-@Table(name="BRMSDependency")
-@NamedQuery(name="BRMSDependency.findAll", query="SELECT b from BRMSDependency b ")
-public class BRMSDependency implements Serializable{
+@Table(name = "BrmsDependency")
+@NamedQuery(name = "BrmsDependency.findAll", query = "SELECT b from BrmsDependency b ")
+@Getter
+@Setter
+public class BrmsDependency implements Serializable {
private static final long serialVersionUID = -7005622785653160761L;
-
+
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
- @Column(name="id")
+ @Column(name = "id")
private int id;
-
- @Column(name="dependency_name", nullable=false, length=1024, unique=true)
+
+ @Column(name = "dependency_name", nullable = false, length = 1024, unique = true)
@OrderBy("asc")
private String dependencyName;
- @Column(name="description", nullable=true, length=1024)
+ @Column(name = "description", nullable = true, length = 1024)
private String description;
-
+
@Temporal(TemporalType.TIMESTAMP)
- @Column(name="created_date", updatable=false)
+ @Column(name = "created_date", updatable = false)
private Date createdDate;
-
+
@ManyToOne(optional = false)
- @JoinColumn(name="created_by")
+ @JoinColumn(name = "created_by")
private UserInfo userCreatedBy;
-
+
@Temporal(TemporalType.TIMESTAMP)
- @Column(name="modified_date", nullable=false)
+ @Column(name = "modified_date", nullable = false)
private Date modifiedDate;
-
+
@ManyToOne(optional = false)
- @JoinColumn(name="modified_by")
+ @JoinColumn(name = "modified_by")
private UserInfo userModifiedBy;
-
- @Column(name="dependency", nullable=false)
+
+ @Column(name = "dependency", nullable = false)
private String dependency;
-
+
+ /**
+ * Pre persist.
+ */
@PrePersist
public void prePersist() {
Date date = new Date();
this.createdDate = date;
this.modifiedDate = date;
}
-
+
+ /**
+ * Pre update.
+ */
@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
index 7e47c0fb3..e3531fedd 100644
--- 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
@@ -3,13 +3,14 @@
* ONAP-REST
* ================================================================================
* Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2019 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -38,98 +39,48 @@ import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
-import org.onap.policy.rest.jpa.UserInfo;
+import lombok.Getter;
+import lombok.Setter;
-/*
- * JPA for the BRMS Param Template.
- *
- * @version: 0.1
+/**
+ * JPA for the BRMS Param Template.
*/
-
@Entity
-@Table(name="BRMSParamTemplate")
-@NamedQuery(name="BRMSParamTemplate.findAll", query="SELECT b FROM BRMSParamTemplate b ")
-public class BRMSParamTemplate implements Serializable{
+@Table(name = "BrmsParamTemplate")
+@NamedQuery(name = "BrmsParamTemplate.findAll", query = "SELECT b FROM BrmsParamTemplate b ")
+@Getter
+@Setter
+public class BrmsParamTemplate implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
- @Column(name="id")
+ @Column(name = "id")
private int id;
- @Column(name="param_template_name", nullable=false, unique=true)
+ @Column(name = "param_template_name", nullable = false, unique = true)
@OrderBy("asc")
private String ruleName;
@Lob
- @Column(name="rule",nullable=false)
+ @Column(name = "rule", nullable = false)
private String rule;
- @Column(name="description", nullable=true, length=2048)
+ @Column(name = "description", nullable = true, length = 2048)
private String description;
@Temporal(TemporalType.TIMESTAMP)
- @Column(name="created_date", updatable=false)
+ @Column(name = "created_date", updatable = false)
private Date createdDate;
-
@ManyToOne(optional = false)
- @JoinColumn(name="created_by")
+ @JoinColumn(name = "created_by")
private UserInfo userCreatedBy;
- public UserInfo getUserCreatedBy() {
- return userCreatedBy;
- }
-
- public void setUserCreatedBy(UserInfo userCreatedBy) {
- this.userCreatedBy = userCreatedBy;
- }
-
@PrePersist
- public void 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
index f3874a480..d417b37db 100644
--- 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
@@ -4,13 +4,14 @@
* ================================================================================
* Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
* Modified Copyright (C) 2018 Samsung Electronics Co., Ltd.
+ * Modifications Copyright (C) 2019 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -21,6 +22,11 @@
package org.onap.policy.rest.jpa;
+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 java.io.Serializable;
import java.util.HashSet;
import java.util.Set;
@@ -35,19 +41,20 @@ 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 lombok.Getter;
+import lombok.Setter;
+import lombok.ToString;
/**
* The persistent class for the Categories database table.
- *
+ *
*/
@Entity
-@Table(name="Category")
-@NamedQuery(name="Category.findAll", query="SELECT c FROM Category c")
+@Table(name = "Category")
+@NamedQuery(name = "Category.findAll", query = "SELECT c FROM Category c")
+@Getter
+@Setter
+@ToString
public class Category implements Serializable {
private static final long serialVersionUID = 1L;
@@ -56,26 +63,29 @@ public class Category implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
- @Column(name="id")
+ @Column(name = "id")
private int id;
- @Column(name="grouping", nullable=false, length=64)
+ @Column(name = "grouping", nullable = false, length = 64)
private String grouping;
- @Column(name="is_standard", nullable=false)
+ @Column(name = "is_standard", nullable = false)
private char isStandard;
- @Column(name="xacml_id", nullable=false, unique=true, length=255)
+ @Column(name = "xacml_id", nullable = false, unique = true, length = 255)
private String xacmlId;
- @Column(name="short_name", nullable=false, length=64)
+ @Column(name = "short_name", nullable = false, length = 64)
private String shortName;
- //bi-directional many-to-one association to Attribute
- @OneToMany(mappedBy="categoryBean")
+ // bi-directional many-to-one association to Attribute
+ @OneToMany(mappedBy = "categoryBean")
@JsonBackReference
private Set<Attribute> attributes = new HashSet<>();
+ /**
+ * Instantiates a new category.
+ */
public Category() {
this.xacmlId = XACML3.ID_SUBJECT_CATEGORY_ACCESS_SUBJECT.stringValue();
this.grouping = "subject";
@@ -83,6 +93,13 @@ public class Category implements Serializable {
this.shortName = "subject";
}
+ /**
+ * Instantiates a new category.
+ *
+ * @param cat the cat
+ * @param grouping the grouping
+ * @param isStandard the is standard
+ */
public Category(Identifier cat, String grouping, char isStandard) {
if (cat != null) {
this.xacmlId = cat.stringValue();
@@ -95,66 +112,41 @@ public class Category implements Serializable {
}
}
+ /**
+ * Instantiates a new category.
+ *
+ * @param cat the cat
+ * @param grouping the grouping
+ */
public Category(Identifier cat, String grouping) {
this(cat, grouping, Category.STANDARD);
}
+ /**
+ * Instantiates a new category.
+ *
+ * @param cat the cat
+ * @param standard the standard
+ */
public Category(Identifier cat, char standard) {
this(cat, null, standard);
}
+ /**
+ * Instantiates a new category.
+ *
+ * @param cat the cat
+ */
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<Attribute> getAttributes() {
- return this.attributes;
- }
-
- public void setAttributes(Set<Attribute> attributes) {
- this.attributes = attributes;
- }
-
+ /**
+ * Adds the attribute.
+ *
+ * @param attribute the attribute
+ * @return the attribute
+ */
public Attribute addAttribute(Attribute attribute) {
getAttributes().add(attribute);
attribute.setCategoryBean(this);
@@ -162,6 +154,12 @@ public class Category implements Serializable {
return attribute;
}
+ /**
+ * Removes the attribute.
+ *
+ * @param attribute the attribute
+ * @return the attribute
+ */
public Attribute removeAttribute(Attribute attribute) {
getAttributes().remove(attribute);
attribute.setCategoryBean(null);
@@ -169,30 +167,41 @@ public class Category implements Serializable {
return attribute;
}
+ /**
+ * Checks if is standard.
+ *
+ * @return true, if is standard
+ */
@Transient
public boolean isStandard() {
return this.isStandard == Category.STANDARD;
}
+ /**
+ * Checks if is custom.
+ *
+ * @return true, if is custom
+ */
@Transient
public boolean isCustom() {
return this.isStandard == Category.CUSTOM;
}
+ /**
+ * Extract grouping.
+ *
+ * @param xacmlId the xacml id
+ * @return the string
+ */
@Transient
- public static String extractGrouping(String xacmlId) {
+ public static String extractGrouping(String xacmlId) {
if (xacmlId == null) {
return null;
}
String[] parts = xacmlId.split("[:]");
- if (xacmlId.matches(".*:attribute\\-category:.*")) {
- if (parts.length > 0) {
- return parts[parts.length - 1];
- }
- } else if (xacmlId.matches(".*:[a-zA-Z]+[\\-]category:.*")) {
- if (parts.length <= 0) {
- return null;
- }
+ if (xacmlId.matches(".*:attribute\\-category:.*")) {
+ return parts[parts.length - 1];
+ } else if (xacmlId.matches(".*:[a-zA-Z]+[\\-]category:.*")) {
for (String part : parts) {
int index = part.indexOf("-category");
if (index > 0) {
@@ -203,17 +212,13 @@ public class Category implements Serializable {
return null;
}
+ /**
+ * Gets the identifer.
+ *
+ * @return the identifer
+ */
@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
index cd2ea591d..41a2b2a56 100644
--- 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
@@ -3,6 +3,7 @@
* ONAP-REST
* ================================================================================
* Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2019 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -19,11 +20,10 @@
*/
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;
@@ -39,112 +39,70 @@ import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
+import lombok.Getter;
+import lombok.Setter;
+/**
+ * The Class ClosedLoopD2Services.
+ */
@Entity
@Table(name = "ClosedLoopD2Services")
-@NamedQuery(name="ClosedLoopD2Services.findAll", query="SELECT c FROM ClosedLoopD2Services c ")
-public class ClosedLoopD2Services implements Serializable{
+@NamedQuery(name = "ClosedLoopD2Services.findAll", query = "SELECT c FROM ClosedLoopD2Services c ")
+@Getter
+@Setter
+public class ClosedLoopD2Services implements Serializable {
private static final long serialVersionUID = 1L;
@Id
- @Column(name ="id")
+ @Column(name = "id")
@GeneratedValue(strategy = GenerationType.AUTO)
private int id;
- @Column(name="service_Name", nullable=false, unique=true)
+ @Column(name = "service_Name", nullable = false, unique = true)
@OrderBy("asc")
private String serviceName;
- @Column(name="description", nullable=true, length=2048)
+ @Column(name = "description", nullable = true, length = 2048)
private String description;
@Temporal(TemporalType.TIMESTAMP)
- @Column(name="created_date", updatable=false)
+ @Column(name = "created_date", updatable = false)
private Date createdDate;
@Temporal(TemporalType.TIMESTAMP)
- @Column(name="modified_date", nullable=false)
+ @Column(name = "modified_date", nullable = false)
private Date modifiedDate;
@ManyToOne(optional = false)
- @JoinColumn(name="created_by")
+ @JoinColumn(name = "created_by")
private UserInfo userCreatedBy;
@ManyToOne(optional = false)
- @JoinColumn(name="modified_by")
+ @JoinColumn(name = "modified_by")
private UserInfo userModifiedBy;
+ /**
+ * Instantiates a new closed loop D 2 services.
+ */
public ClosedLoopD2Services() {
this.setModifiedDate(new Date());
}
-
- 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;
- }
-
+ /**
+ * Pre persist.
+ */
@PrePersist
- public void prePersist() {
+ public void prePersist() {
Date date = new Date();
this.createdDate = date;
this.modifiedDate = date;
}
+ /**
+ * Pre update.
+ */
@PreUpdate
public void preUpdate() {
this.modifiedDate = new Date();
}
-
- 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
index 52b5a2a4a..fb220d7c0 100644
--- 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
@@ -3,6 +3,7 @@
* ONAP-REST
* ================================================================================
* Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2019 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -20,11 +21,9 @@
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;
@@ -40,113 +39,70 @@ import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
+import lombok.Getter;
+import lombok.Setter;
+/**
+ * The Class ClosedLoopSite.
+ */
@Entity
@Table(name = "ClosedLoopSite")
-@NamedQuery(name="ClosedLoopSite.findAll", query="SELECT c FROM ClosedLoopSite c ")
-public class ClosedLoopSite implements Serializable{
+@NamedQuery(name = "ClosedLoopSite.findAll", query = "SELECT c FROM ClosedLoopSite c ")
+@Getter
+@Setter
+public class ClosedLoopSite implements Serializable {
private static final long serialVersionUID = 1L;
-
@Id
- @Column(name ="id")
+ @Column(name = "id")
@GeneratedValue(strategy = GenerationType.AUTO)
private int id;
- @Column(name="site_Name", nullable=false, unique=true)
+ @Column(name = "site_Name", nullable = false, unique = true)
@OrderBy("asc")
private String siteName;
- @Column(name="description", nullable=true, length=2048)
+ @Column(name = "description", nullable = true, length = 2048)
private String description;
@Temporal(TemporalType.TIMESTAMP)
- @Column(name="created_date", updatable=false)
+ @Column(name = "created_date", updatable = false)
private Date createdDate;
@Temporal(TemporalType.TIMESTAMP)
- @Column(name="modified_date", nullable=false)
+ @Column(name = "modified_date", nullable = false)
private Date modifiedDate;
@ManyToOne(optional = false)
- @JoinColumn(name="created_by")
+ @JoinColumn(name = "created_by")
private UserInfo userCreatedBy;
@ManyToOne(optional = false)
- @JoinColumn(name="modified_by")
+ @JoinColumn(name = "modified_by")
private UserInfo userModifiedBy;
+ /**
+ * Instantiates a new closed loop site.
+ */
public ClosedLoopSite() {
this.setModifiedDate(new Date());
}
-
- 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;
- }
-
+ /**
+ * Pre persist.
+ */
@PrePersist
- public void prePersist() {
+ public void prePersist() {
Date date = new Date();
this.createdDate = date;
this.modifiedDate = date;
}
+ /**
+ * Pre update.
+ */
@PreUpdate
public void preUpdate() {
this.modifiedDate = new Date();
}
-
- 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
index 721a2c5f4..3b1be82cf 100644
--- 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
@@ -3,13 +3,14 @@
* ONAP-REST
* ================================================================================
* Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2019 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -32,68 +33,38 @@ import javax.persistence.NamedQuery;
import javax.persistence.OrderBy;
import javax.persistence.Table;
+import lombok.Getter;
+import lombok.NoArgsConstructor;
+import lombok.Setter;
+
+// @formatter:off
@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")
-})
+@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")
+ }
+)
+@Getter
+@Setter
+@NoArgsConstructor
+//@formatter:on
public class ClosedLoops implements Serializable {
-
- /**
- *
- */
private static final long serialVersionUID = -7796845092457926842L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
- @Column(name="id")
+ @Column(name = "id")
private int id;
- @Column(name="closedLoopControlName", nullable=false, length=255)
+ @Column(name = "closedLoopControlName", nullable = false, length = 255)
@OrderBy("asc")
private String closedLoopControlName;
- @Column(name="alarmConditions", nullable=true, length=255)
+ @Column(name = "alarmConditions", nullable = true, length = 255)
private String alarmConditions;
- @Column(name="yaml", nullable=true, length=1028)
+ @Column(name = "yaml", nullable = true, length = 1028)
private String yaml;
-
- public ClosedLoops() {
- //An empty constructor
- }
-
- 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
index 7bb73f36a..f5ae1817b 100644
--- 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
@@ -3,13 +3,14 @@
* ONAP-REST
* ================================================================================
* Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2019 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -19,11 +20,13 @@
*/
package org.onap.policy.rest.jpa;
+
+import com.fasterxml.jackson.annotation.JsonBackReference;
+
/*
*/
import java.io.Serializable;
import java.util.Date;
-import java.util.Objects;
import javax.persistence.Column;
import javax.persistence.Entity;
@@ -43,216 +46,87 @@ import javax.persistence.Version;
* The Entity class to persist a policy object configuration data
*/
+import lombok.Getter;
+import lombok.NoArgsConstructor;
+import lombok.Setter;
+import lombok.ToString;
-import com.fasterxml.jackson.annotation.JsonBackReference;
-
+/**
+ * The Class ConfigurationDataEntity.
+ */
+// @formatter:off
@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")
-})
+@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")
+ }
+)
+@Getter
+@Setter
+@ToString
+@NoArgsConstructor
+//@formatter:on
public class ConfigurationDataEntity implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
- @Column(name="configurationDataId")
+ @Column(name = "configurationDataId")
@JsonBackReference
private long configurationDataId;
- @Column(name="configurationName", nullable=false, length=255)
+ @Column(name = "configurationName", nullable = false, length = 255)
private String configurationName = "";
@Version
- @Column(name="version")
+ @Column(name = "version")
private int version;
- @Column(name="configType", nullable=false, length=255)
+ @Column(name = "configType", nullable = false, length = 255)
private String configType = "NoType";
@Lob
- @Column(name="configBody", nullable=false, columnDefinition="TEXT")
+ @Column(name = "configBody", nullable = false, columnDefinition = "TEXT")
private String configBody = "NoBody";
- @Column(name="created_by", nullable=false, length=255)
+ @Column(name = "created_by", nullable = false, length = 255)
private String createdBy = "guest";
@Temporal(TemporalType.TIMESTAMP)
- @Column(name="created_date", updatable=false)
+ @Column(name = "created_date", updatable = false)
private Date createdDate;
- @Column(name="description", nullable=false, length=2048)
+ @Column(name = "description", nullable = false, length = 2048)
private String description = "NoDescription";
- @Column(name="modified_by", nullable=false, length=255)
+ @Column(name = "modified_by", nullable = false, length = 255)
private String modifiedBy = "guest";
@Temporal(TemporalType.TIMESTAMP)
- @Column(name="modified_date", nullable=false)
+ @Column(name = "modified_date", nullable = false)
private Date modifiedDate;
- @Column(name="deleted", nullable=false)
+ @Column(name = "deleted", nullable = false)
private boolean deleted = false;
- public ConfigurationDataEntity() {
- //An empty constructor
- }
-
+ /**
+ * Pre persist.
+ */
@PrePersist
- public void prePersist() {
+ public void prePersist() {
Date date = new Date();
this.createdDate = date;
this.modifiedDate = date;
}
+ /**
+ * Pre update.
+ */
@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;
- }
-
- @Override
- public int hashCode() {
- return Objects.hash(configurationDataId, configurationName, version, configType,
- configBody, createdBy, createdDate, description, modifiedBy, modifiedDate, deleted);
- }
-
- @Override
- public boolean equals(Object obj) {
- if(obj == null){
- return false;
- }
- if(obj == this){
- return true;
- }
- if(!(obj instanceof ConfigurationDataEntity)){
- return false;
- }
-
- return configurationDataId == ((ConfigurationDataEntity) obj).configurationDataId &&
- configurationName.equals(((ConfigurationDataEntity) obj).configurationName) &&
- version == ((ConfigurationDataEntity) obj).version &&
- configType.equals(((ConfigurationDataEntity) obj).configType) &&
- configBody.equals(((ConfigurationDataEntity) obj).configBody) &&
- createdBy.equals(((ConfigurationDataEntity) obj).createdBy) &&
- createdDate.equals(((ConfigurationDataEntity) obj).createdDate) &&
- description.equals(((ConfigurationDataEntity) obj).description) &&
- modifiedBy.equals(((ConfigurationDataEntity) obj).modifiedBy) &&
- modifiedDate.equals(((ConfigurationDataEntity) obj).modifiedDate) &&
- deleted == ((ConfigurationDataEntity) obj).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
index 606403318..10394ae6f 100644
--- 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
@@ -3,13 +3,14 @@
* ONAP-REST
* ================================================================================
* Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2019 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -35,9 +36,16 @@ import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.Table;
+import lombok.Getter;
+import lombok.NoArgsConstructor;
+import lombok.Setter;
+
@Entity
-@Table(name="ConstraintType")
-@NamedQuery(name="ConstraintType.findAll", query="SELECT a FROM ConstraintType a")
+@Table(name = "ConstraintType")
+@NamedQuery(name = "ConstraintType.findAll", query = "SELECT a FROM ConstraintType a")
+@Getter
+@Setter
+@NoArgsConstructor
public class ConstraintType implements Serializable {
private static final long serialVersionUID = 1L;
@@ -46,35 +54,37 @@ public class ConstraintType implements Serializable {
public static final String REGEXP_TYPE = "Regular Expression";
protected static final Map<String, String> 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.");
+ 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"};
+
+ private static final String[] RANGE_TYPES =
+ { "minExclusive", "minInclusive", "maxExclusive", "maxInclusive" };
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
- @Column(name="id")
+ @Column(name = "id")
private int id;
- @Column(name="constraint_type", nullable=false, length=64)
- private String constraintType;
+ @Column(name = "constraint_type", nullable = false, length = 64)
+ private String theConstraintType;
- @Column(name="description", nullable=false, length=255)
+ @Column(name = "description", nullable = false, length = 255)
private String description;
- //bi-directional many-to-one association to Attribute
- @OneToMany(mappedBy="constraintType")
+ // bi-directional many-to-one association to Attribute
+ @OneToMany(mappedBy = "constraintType")
private Set<Attribute> attributes = new HashSet<>();
- public ConstraintType() {
- //An empty constructor
- }
-
public ConstraintType(String constraintType) {
this();
- this.constraintType = constraintType;
+ this.theConstraintType = constraintType;
}
public ConstraintType(String constraintType, String description) {
@@ -82,40 +92,15 @@ public class ConstraintType implements Serializable {
this.description = description;
}
- public int getId() {
- return id;
- }
-
- public void setId(int id) {
- this.id = id;
+ public static String[] getRangeTypes() {
+ return RANGE_TYPES;
}
public String getConstraintType() {
- return constraintType;
+ return theConstraintType;
}
- public void setConstraintType(String constraintType) {
- this.constraintType = constraintType;
+ public void setConstraintType(final String theConstraintType) {
+ this.theConstraintType = theConstraintType;
}
-
- public String getDescription() {
- return description;
- }
-
- public void setDescription(String description) {
- this.description = description;
- }
-
- public Set<Attribute> getAttributes() {
- return attributes;
- }
-
- public void setAttributes(Set<Attribute> 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
index 4c3bf6609..d4043962f 100644
--- 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
@@ -3,13 +3,14 @@
* ONAP-REST
* ================================================================================
* Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2019 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -32,37 +33,39 @@ import javax.persistence.ManyToOne;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
+import lombok.Getter;
+import lombok.NoArgsConstructor;
+import lombok.Setter;
/**
* The persistent class for the ConstraintValues database table.
- *
+ *
*/
@Entity
-@Table(name="ConstraintValues")
-@NamedQuery(name="ConstraintValue.findAll", query="SELECT c FROM ConstraintValue c")
+@Table(name = "ConstraintValues")
+@NamedQuery(name = "ConstraintValue.findAll", query = "SELECT c FROM ConstraintValue c")
+@Getter
+@Setter
+@NoArgsConstructor
public class ConstraintValue implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
- @Column(name="id")
+ @Column(name = "id")
private int id;
- @Column(name="property")
+ @Column(name = "property")
private String property;
- @Column(name="value")
+ @Column(name = "value")
private String value;
- //bi-directional many-to-one association to Attribute
+ // bi-directional many-to-one association to Attribute
@ManyToOne
- @JoinColumn(name="attribute_id")
+ @JoinColumn(name = "attribute_id")
private Attribute attribute;
- public ConstraintValue() {
- //An empty constructor
- }
-
public ConstraintValue(String property, String value) {
this.property = property;
this.value = value;
@@ -73,38 +76,6 @@ public class ConstraintValue implements Serializable {
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;
- }
-
@Override
public ConstraintValue clone() {
ConstraintValue constraint = new ConstraintValue();
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
index b82ec4882..0ea3b71c4 100644
--- 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
@@ -3,13 +3,14 @@
* ONAP-REST
* ================================================================================
* Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2019 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -27,21 +28,18 @@ import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
+import lombok.Getter;
+import lombok.NoArgsConstructor;
+import lombok.Setter;
+
@Entity
-@Table(name="DatabaseLockEntity")
+@Table(name = "DatabaseLockEntity")
+@Getter
+@Setter
+@NoArgsConstructor
public class DatabaseLockEntity implements Serializable {
private static final long serialVersionUID = 1L;
@Id
- @Column(name="lock_key")
- private int lock_key = 1;
- public DatabaseLockEntity(){
- //An empty constructor
- }
- public int getKey(){
- return lock_key;
- }
- public void setKey(int key){
- this.lock_key = key;
- }
-
+ @Column(name = "lock_key")
+ private int key = 1;
}
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
index 4ab577976..9bb2340c7 100644
--- 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
@@ -3,13 +3,14 @@
* ONAP-REST
* ================================================================================
* Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2019 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -20,6 +21,12 @@
package org.onap.policy.rest.jpa;
+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;
+
import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;
@@ -34,20 +41,20 @@ 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;
-
+import lombok.Getter;
+import lombok.Setter;
+import lombok.ToString;
/**
* The persistent class for the Datatype database table.
- *
+ *
*/
@Entity
-@Table(name="Datatype")
-@NamedQuery(name="Datatype.findAll", query="SELECT d FROM Datatype d")
+@Table(name = "Datatype")
+@NamedQuery(name = "Datatype.findAll", query = "SELECT d FROM Datatype d")
+@Getter
+@Setter
+@ToString
public class Datatype implements Serializable {
private static final long serialVersionUID = 1L;
@@ -56,39 +63,47 @@ public class Datatype implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
- @Column(name="id")
+ @Column(name = "id")
private int id;
- @Column(name="is_standard", nullable=false)
+ @Column(name = "is_standard", nullable = false)
private char isStandard;
- @Column(name="xacml_id", nullable=false, unique=true, length=255)
+ @Column(name = "xacml_id", nullable = false, unique = true, length = 255)
private String xacmlId;
- @Column(name="short_name", nullable=false, length=64)
+ @Column(name = "short_name", nullable = false, length = 64)
private String shortName;
- //bi-directional many-to-one association to Attribute
- @OneToMany(mappedBy="datatypeBean")
+ // bi-directional many-to-one association to Attribute
+ @OneToMany(mappedBy = "datatypeBean")
@JsonBackReference
private Set<Attribute> attributes = new HashSet<>();
- //bi-directional many-to-one association to Attribute
- @OneToMany(mappedBy="datatypeBean")
+ // bi-directional many-to-one association to Attribute
+ @OneToMany(mappedBy = "datatypeBean")
@JsonIgnore
private Set<FunctionDefinition> functions = new HashSet<>();
- //bi-directional many-to-one association to Attribute
- @OneToMany(mappedBy="datatypeBean")
+ // bi-directional many-to-one association to Attribute
+ @OneToMany(mappedBy = "datatypeBean")
@JsonIgnore
private Set<FunctionArgument> arguments = new HashSet<>();
+ /**
+ * Instantiates a new datatype.
+ */
public Datatype() {
this.xacmlId = XACML3.ID_DATATYPE_STRING.stringValue();
this.isStandard = Datatype.STANDARD;
}
-
+ /**
+ * Instantiates a new datatype.
+ *
+ * @param id the id
+ * @param dt the dt
+ */
public Datatype(int id, Datatype dt) {
this.id = id;
this.isStandard = dt.isStandard;
@@ -100,6 +115,12 @@ public class Datatype implements Serializable {
this.attributes = new HashSet<>();
}
+ /**
+ * Instantiates a new datatype.
+ *
+ * @param identifier the identifier
+ * @param standard the standard
+ */
public Datatype(Identifier identifier, char standard) {
if (identifier != null) {
this.xacmlId = identifier.stringValue();
@@ -108,50 +129,21 @@ public class Datatype implements Serializable {
this.isStandard = standard;
}
+ /**
+ * Instantiates a new datatype.
+ *
+ * @param identifier the identifier
+ */
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<Attribute> getAttributes() {
- return this.attributes;
- }
-
- public void setAttributes(Set<Attribute> attributes) {
- this.attributes = attributes;
- }
-
+ /**
+ * Adds the attribute.
+ *
+ * @param attribute the attribute
+ * @return the attribute
+ */
public Attribute addAttribute(Attribute attribute) {
getAttributes().add(attribute);
attribute.setDatatypeBean(this);
@@ -159,6 +151,12 @@ public class Datatype implements Serializable {
return attribute;
}
+ /**
+ * Removes the attribute.
+ *
+ * @param attribute the attribute
+ * @return the attribute
+ */
public Attribute removeAttribute(Attribute attribute) {
getAttributes().remove(attribute);
attribute.setDatatypeBean(null);
@@ -166,21 +164,12 @@ public class Datatype implements Serializable {
return attribute;
}
- public Set<FunctionDefinition> getFunctions() {
- return this.functions;
- }
-
- public void setFunctions(Set<FunctionDefinition> functions) {
- this.functions = functions;
- }
-
- public FunctionDefinition addFunction(FunctionDefinition function) {
- getFunctions().add(function);
- function.setDatatypeBean(this);
-
- return function;
- }
-
+ /**
+ * Removes the attribute.
+ *
+ * @param function the function
+ * @return the function definition
+ */
public FunctionDefinition removeAttribute(FunctionDefinition function) {
getFunctions().remove(function);
function.setDatatypeBean(null);
@@ -188,14 +177,25 @@ public class Datatype implements Serializable {
return function;
}
- public Set<FunctionArgument> getArguments() {
- return this.arguments;
- }
+ /**
+ * Adds the function.
+ *
+ * @param function the function
+ * @return the function definition
+ */
+ public FunctionDefinition addFunction(FunctionDefinition function) {
+ getFunctions().add(function);
+ function.setDatatypeBean(this);
- public void setArguments(Set<FunctionArgument> argument) {
- this.arguments = argument;
+ return function;
}
+ /**
+ * Adds the argument.
+ *
+ * @param argument the argument
+ * @return the function argument
+ */
public FunctionArgument addArgument(FunctionArgument argument) {
getArguments().add(argument);
argument.setDatatypeBean(this);
@@ -203,6 +203,12 @@ public class Datatype implements Serializable {
return argument;
}
+ /**
+ * Removes the argument.
+ *
+ * @param argument the argument
+ * @return the function argument
+ */
public FunctionArgument removeArgument(FunctionArgument argument) {
getArguments().remove(argument);
argument.setDatatypeBean(null);
@@ -210,33 +216,43 @@ public class Datatype implements Serializable {
return argument;
}
+ /**
+ * Gets the identifer.
+ *
+ * @return the identifer
+ */
@Transient
public Identifier getIdentifer() {
return new IdentifierImpl(this.xacmlId);
}
+ /**
+ * Gets the identifer by short name.
+ *
+ * @return the identifer by short name
+ */
@Transient
public Identifier getIdentiferByShortName() {
return new IdentifierImpl(this.shortName);
}
+ /**
+ * Checks if is standard.
+ *
+ * @return true, if is standard
+ */
@Transient
public boolean isStandard() {
return this.isStandard == Datatype.STANDARD;
}
+ /**
+ * Checks if is custom.
+ *
+ * @return true, if is custom
+ */
@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 + "]";
- }
-
}
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/DcaeUsers.java
index 463e51709..3313d0310 100644
--- a/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/VMType.java
+++ b/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/DcaeUsers.java
@@ -3,13 +3,14 @@
* ONAP-REST
* ================================================================================
* Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2019 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -19,8 +20,7 @@
*/
package org.onap.policy.rest.jpa;
-/*
- */
+
import java.io.Serializable;
import javax.persistence.Column;
@@ -32,47 +32,34 @@ import javax.persistence.NamedQuery;
import javax.persistence.OrderBy;
import javax.persistence.Table;
+import lombok.Getter;
+import lombok.Setter;
@Entity
-@Table(name="VMType")
-@NamedQuery(name="VMType.findAll", query="SELECT e FROM VMType e ")
-public class VMType implements Serializable {
+@Table(name = "DcaeUsers")
+@NamedQuery(name = "DcaeUsers.findAll", query = "SELECT e FROM DcaeUsers e ")
+@Getter
+@Setter
+public class DcaeUsers implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
- @Column(name="id")
+ @Column(name = "id")
private int id;
- @Column(name="name", nullable=false)
+ @Column(name = "name", nullable = false)
@OrderBy("asc")
private String name;
- @Column(name="description")
+ @Column(name = "description ")
private String description;
- public String getDescription() {
- return description;
+ public String getDescriptionValue() {
+ return this.description;
}
- public void setDescription(String description) {
+ public void setDescriptionValue(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/DCAEuuid.java b/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/DcaeUuid.java
index 5194093d1..990f396eb 100644
--- 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
@@ -3,13 +3,14 @@
* ONAP-REST
* ================================================================================
* Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2019 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -19,8 +20,7 @@
*/
package org.onap.policy.rest.jpa;
-/*
- */
+
import java.io.Serializable;
import javax.persistence.Column;
@@ -32,47 +32,26 @@ import javax.persistence.NamedQuery;
import javax.persistence.OrderBy;
import javax.persistence.Table;
+import lombok.Getter;
+import lombok.Setter;
@Entity
-@Table(name="DCAEuuid")
-@NamedQuery(name="DCAEuuid.findAll", query="SELECT e FROM DCAEuuid e ")
-public class DCAEuuid implements Serializable {
+@Table(name = "DcaeUuid")
+@NamedQuery(name = "DcaeUuid.findAll", query = "SELECT e FROM DcaeUuid e ")
+@Getter
+@Setter
+public class DcaeUuid implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
- @Column(name="id")
+ @Column(name = "id")
private int id;
- @Column(name="name", nullable=false)
+ @Column(name = "name", nullable = false)
@OrderBy("asc")
private String name;
- @Column(name="description")
+ @Column(name = "description")
private String description;
-
- 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/DecisionSettings.java b/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/DecisionSettings.java
index e469c0b4f..bfa217674 100644
--- 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
@@ -3,13 +3,14 @@
* ONAP-REST
* ================================================================================
* Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2019 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -39,40 +40,52 @@ import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.persistence.Transient;
+import lombok.Getter;
+import lombok.Setter;
+/**
+ * The Class DecisionSettings.
+ */
+// @formatter:off
@Entity
-@Table(name="DecisionSettings")
-@NamedQuery(name="DecisionSettings.findAll", query="SELECT a FROM DecisionSettings a order by a.priority asc, a.xacmlId asc")
+@Table(name = "DecisionSettings")
+@NamedQuery(
+ name = "DecisionSettings.findAll",
+ query = "SELECT a FROM DecisionSettings a order by a.priority asc, a.xacmlId asc"
+)
+@Getter
+@Setter
+//@formatter:on
public class DecisionSettings implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
- @Column(name="id")
+ @Column(name = "id")
private int id;
@Temporal(TemporalType.TIMESTAMP)
- @Column(name="created_date", updatable=false)
+ @Column(name = "created_date", updatable = false)
private Date createdDate;
- @Column(name="description", nullable=true, length=2048)
+ @Column(name = "description", nullable = true, length = 2048)
private String description;
@Temporal(TemporalType.TIMESTAMP)
- @Column(name="modified_date", nullable=false)
+ @Column(name = "modified_date", nullable = false)
private Date modifiedDate;
- @Column(name="PRIORITY", nullable=true)
+ @Column(name = "PRIORITY", nullable = true)
@OrderBy("asc")
private String priority;
- @Column(name="xacml_id", unique = true, nullable=false)
+ @Column(name = "xacml_id", unique = true, nullable = false)
@OrderBy("asc")
private String xacmlId = "urn";
- //bi-directional many-to-one association to Datatype
+ // bi-directional many-to-one association to Datatype
@ManyToOne
- @JoinColumn(name="datatype")
+ @JoinColumn(name = "datatype")
private Datatype datatypeBean;
@Transient
@@ -82,116 +95,28 @@ public class DecisionSettings implements Serializable {
private boolean mustBePresent = false;
@ManyToOne(optional = false)
- @JoinColumn(name="created_by")
+ @JoinColumn(name = "created_by")
private UserInfo userCreatedBy;
@ManyToOne(optional = false)
- @JoinColumn(name="modified_by")
+ @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;
- }
-
+ /**
+ * Pre persist.
+ */
@PrePersist
- public void prePersist() {
+ public void prePersist() {
Date date = new Date();
this.createdDate = date;
this.modifiedDate = date;
}
+ /**
+ * Pre update.
+ */
@PreUpdate
public void preUpdate() {
this.modifiedDate = new 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 Date getModifiedDate() {
- return this.modifiedDate;
- }
-
- public void setModifiedDate(Date modifiedDate) {
- this.modifiedDate = modifiedDate;
- }
-
- public String getXacmlId() {
- return 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
index aab9126e2..4360131a4 100644
--- 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
@@ -3,13 +3,14 @@
* ONAP-REST
* ================================================================================
* Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2019 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -38,10 +39,17 @@ import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
+import lombok.Getter;
+import lombok.Setter;
+/**
+ * The Class DescriptiveScope.
+ */
@Entity
@Table(name = "DescriptiveScope")
-@NamedQuery(name = "DescriptiveScope.findAll", query= "Select p from DescriptiveScope p")
+@NamedQuery(name = "DescriptiveScope.findAll", query = "Select p from DescriptiveScope p")
+@Getter
+@Setter
public class DescriptiveScope implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@@ -49,106 +57,66 @@ public class DescriptiveScope implements Serializable {
@Column(name = "Id")
private int id;
- @Column(name="scopename", nullable=false)
+ @Column(name = "scopename", nullable = false)
@OrderBy("asc")
private String descriptiveScopeName;
- @Column(name="description", nullable=true, length=2048)
+ @Column(name = "description", nullable = true, length = 2048)
private String description;
- @Column(name="search", nullable=true)
+ @Column(name = "search", nullable = true)
@OrderBy("asc")
private String search;
@Temporal(TemporalType.TIMESTAMP)
- @Column(name="created_date", updatable=false)
+ @Column(name = "created_date", updatable = false)
private Date createdDate;
@Temporal(TemporalType.TIMESTAMP)
- @Column(name="modified_date", nullable=false)
+ @Column(name = "modified_date", nullable = false)
private Date modifiedDate;
@ManyToOne(optional = false)
- @JoinColumn(name="created_by")
+ @JoinColumn(name = "created_by")
private UserInfo userCreatedBy;
@ManyToOne(optional = false)
- @JoinColumn(name="modified_by")
+ @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;
- }
-
+ /**
+ * Pre persist.
+ */
@PrePersist
- public void prePersist() {
+ public void prePersist() {
Date date = new Date();
this.createdDate = date;
this.modifiedDate = date;
}
+ /**
+ * Pre update.
+ */
@PreUpdate
public void preUpdate() {
this.modifiedDate = new Date();
}
- public int getId() {
- return this.id;
- }
- public void setId(int id) {
- this.id = id;
- }
-
+ /**
+ * Gets the scope name.
+ *
+ * @return the scope name
+ */
public String getScopeName() {
return descriptiveScopeName;
}
+ /**
+ * Sets the scope name.
+ *
+ * @param descriptiveScopeName the new scope name
+ */
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/DictionaryData.java b/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/DictionaryData.java
index 85a5091e8..a3db91b75 100644
--- a/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/DictionaryData.java
+++ b/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/DictionaryData.java
@@ -3,6 +3,7 @@
* ONAP-REST
* ================================================================================
* Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2019 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -28,12 +29,15 @@ import javax.persistence.Id;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
+import lombok.Getter;
+import lombok.Setter;
+
@Entity
@Table(name = "DictionaryData")
@NamedQuery(name = "DictionaryData.findAll", query = "SELECT v FROM DictionaryData v ")
+@Getter
+@Setter
public class DictionaryData {
- private static final long serialVersionUID = 1L;
-
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "id")
@@ -47,37 +51,4 @@ public class DictionaryData {
@Column(name = "dictionaryDataByName", nullable = false, length = 1024)
private String dictionaryDataByName;
-
- public String getDictionaryUrl() {
- return dictionaryUrl;
- }
-
- public void setDictionaryUrl(String dictionaryUrl) {
- this.dictionaryUrl = dictionaryUrl;
- }
-
- public String getDictionaryDataByName() {
- return dictionaryDataByName;
- }
-
- public void setDictionaryDataByName(String dictionaryDataByName) {
- this.dictionaryDataByName = dictionaryDataByName;
- }
-
- public String getDictionaryName() {
- return dictionaryName;
- }
-
- public void setDictionaryName(String dictionaryName) {
- this.dictionaryName = dictionaryName;
- }
-
- 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/FWTagPicker.java b/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/FWTagPicker.java
deleted file mode 100644
index 0910d60d7..000000000
--- a/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/FWTagPicker.java
+++ /dev/null
@@ -1,163 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * ONAP-REST
- * ================================================================================
- * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 = "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;
-
- @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 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
index 6ef5f60e0..8581cdf51 100644
--- 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
@@ -3,13 +3,14 @@
* ONAP-REST
* ================================================================================
* Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2019 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -31,68 +32,32 @@ import javax.persistence.NamedQuery;
import javax.persistence.OrderBy;
import javax.persistence.Table;
+import lombok.Getter;
+import lombok.Setter;
@Entity
-@Table(name="parentdictionaryitems")
-@NamedQuery(name="FirewallDictionaryList.findAll", query="SELECT e FROM FirewallDictionaryList e")
+@Table(name = "parentdictionaryitems")
+@NamedQuery(name = "FirewallDictionaryList.findAll", query = "SELECT e FROM FirewallDictionaryList e")
+@Getter
+@Setter
public class FirewallDictionaryList implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
- @Column(name="id")
+ @Column(name = "id")
private int id;
- @Column(name="parentItemName", nullable=false)
+ @Column(name = "parentItemName", nullable = false)
@OrderBy("asc")
private String parentItemName;
- @Column(name="description")
+ @Column(name = "description")
private String description;
- @Column(name="addressList")
+ @Column(name = "addressList")
private String addressList;
- @Column(name="serviceList")
+ @Column(name = "serviceList")
private String serviceList;
-
- 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;
- }
}
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
index a0d14e66b..f978cf089 100644
--- 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
@@ -3,13 +3,14 @@
* ONAP-REST
* ================================================================================
* Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2019 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -22,44 +23,62 @@ package org.onap.policy.rest.jpa;
import java.io.Serializable;
-import javax.persistence.*;
-
+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;
+import javax.persistence.Transient;
+
+import lombok.Getter;
+import lombok.NoArgsConstructor;
+import lombok.Setter;
+import lombok.ToString;
/**
* The persistent class for the FunctionArguments database table.
- *
+ *
*/
@Entity
-@Table(name="FunctionArguments")
-@NamedQuery(name="FunctionArgument.findAll", query="SELECT f FROM FunctionArgument f")
+@Table(name = "FunctionArguments")
+@NamedQuery(name = "FunctionArgument.findAll", query = "SELECT f FROM FunctionArgument f")
+@Getter
+@Setter
+@ToString
+@NoArgsConstructor
public class FunctionArgument implements Serializable {
private static final long serialVersionUID = 1L;
@Id
- @GeneratedValue(strategy=GenerationType.AUTO)
- @Column(name="id")
+ @GeneratedValue(strategy = GenerationType.AUTO)
+ @Column(name = "id")
private int id;
- @Column(name="is_bag", nullable=false)
+ @Column(name = "is_bag", nullable = false)
private int isBag;
- //bi-directional many-to-one association to FunctionDefinition
+ // bi-directional many-to-one association to FunctionDefinition
@ManyToOne
- @JoinColumn(name="function_id")
+ @JoinColumn(name = "function_id")
private FunctionDefinition functionDefinition;
- @Column(name="arg_index", nullable=false)
+ @Column(name = "arg_index", nullable = false)
private int argIndex;
- //bi-directional many-to-one association to Datatype
+ // bi-directional many-to-one association to Datatype
@ManyToOne
- @JoinColumn(name="datatype_id")
+ @JoinColumn(name = "datatype_id")
private Datatype datatypeBean;
- public FunctionArgument() {
- //An empty constructor
- }
-
+ /**
+ * Copy constructor.
+ *
+ * @param argument the object to copy from
+ */
public FunctionArgument(final FunctionArgument argument) {
this.argIndex = argument.argIndex;
this.datatypeBean = argument.datatypeBean;
@@ -67,57 +86,12 @@ public class FunctionArgument implements Serializable {
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
index 80c9beb2c..9201eec32 100644
--- 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
@@ -3,13 +3,14 @@
* ONAP-REST
* ================================================================================
* Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2019 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -21,165 +22,93 @@
package org.onap.policy.rest.jpa;
import java.io.Serializable;
-
-import javax.persistence.*;
-
import java.util.List;
+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.OneToMany;
+import javax.persistence.Table;
+import javax.persistence.Transient;
+
+import lombok.Getter;
+import lombok.NoArgsConstructor;
+import lombok.Setter;
+import lombok.ToString;
/**
* The persistent class for the FunctionDefinition database table.
- *
+ *
*/
+// @formatter:off
@Entity
-@Table(name="FunctionDefinition")
-@NamedQueries({
- @NamedQuery(name="FunctionDefinition.findAll", query="SELECT f FROM FunctionDefinition f")
-})
+@Table(name = "FunctionDefinition")
+@NamedQueries(
+ {
+ @NamedQuery(name = "FunctionDefinition.findAll", query = "SELECT f FROM FunctionDefinition f")
+ }
+)
+@Getter
+@Setter
+@ToString
+@NoArgsConstructor
+// @formatter:on
public class FunctionDefinition implements Serializable {
private static final long serialVersionUID = 1L;
@Id
- @GeneratedValue(strategy=GenerationType.AUTO)
- @Column(name="id")
+ @GeneratedValue(strategy = GenerationType.AUTO)
+ @Column(name = "id")
private int id;
- @Column(name="short_name", nullable=false, length=64)
+ @Column(name = "short_name", nullable = false, length = 64)
private String shortname;
- @Column(name="xacml_id", nullable=false, length=255)
+ @Column(name = "xacml_id", nullable = false, length = 255)
private String xacmlid;
- //bi-directional many-to-one association to Datatype
+ // bi-directional many-to-one association to Datatype
@ManyToOne
- @JoinColumn(name="return_datatype", nullable=true)
+ @JoinColumn(name = "return_datatype", nullable = true)
private Datatype datatypeBean;
- @Column(name="is_bag_return", nullable=false)
+ @Column(name = "is_bag_return", nullable = false)
private Integer isBagReturn;
- @Column(name="is_higher_order", nullable=false)
+ @Column(name = "is_higher_order", nullable = false)
private Integer isHigherOrder;
- @Column(name="arg_lb", nullable=false)
+ @Column(name = "arg_lb", nullable = false)
private Integer argLb;
- @Column(name="arg_ub", nullable=false)
+ @Column(name = "arg_ub", nullable = false)
private Integer argUb;
- @Column(name="ho_arg_lb", nullable=true)
- private Integer higherOrderArg_LB;
+ @Column(name = "ho_arg_lb", nullable = true)
+ private Integer higherOrderArgLb;
- @Column(name="ho_arg_ub", nullable=true)
- private Integer higherOrderArg_UB;
+ @Column(name = "ho_arg_ub", nullable = true)
+ private Integer higherOrderArgUb;
- @Column(name="ho_primitive", nullable=true)
+ @Column(name = "ho_primitive", nullable = true)
private Character higherOrderIsPrimitive;
- //bi-directional many-to-one association to FunctionArgument
- @OneToMany(mappedBy="functionDefinition")
+ // bi-directional many-to-one association to FunctionArgument
+ @OneToMany(mappedBy = "functionDefinition")
private List<FunctionArgument> functionArguments;
- public FunctionDefinition() {
- //An empty constructor
- }
-
- 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<FunctionArgument> getFunctionArguments() {
- return this.functionArguments;
- }
-
- public void setFunctionArguments(List<FunctionArgument> functionArguments) {
- this.functionArguments = functionArguments;
- }
-
+ /**
+ * Adds the function argument.
+ *
+ * @param functionArgument the function argument
+ * @return the function argument
+ */
public FunctionArgument addFunctionArgument(FunctionArgument functionArgument) {
getFunctionArguments().add(functionArgument);
functionArgument.setFunctionDefinition(this);
@@ -187,6 +116,12 @@ public class FunctionDefinition implements Serializable {
return functionArgument;
}
+ /**
+ * Removes the function argument.
+ *
+ * @param functionArgument the function argument
+ * @return the function argument
+ */
public FunctionArgument removeFunctionArgument(FunctionArgument functionArgument) {
getFunctionArguments().remove(functionArgument);
functionArgument.setFunctionDefinition(null);
@@ -194,24 +129,21 @@ public class FunctionDefinition implements Serializable {
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 + "]";
- }
-
+ /**
+ * Checks if is bag return.
+ *
+ * @return true, if is bag return
+ */
@Transient
public boolean isBagReturn() {
return this.isBagReturn == 1;
}
+ /**
+ * Checks if is higher order.
+ *
+ * @return true, if is higher order
+ */
@Transient
public boolean isHigherOrder() {
return this.isHigherOrder == 1;
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
index 75710d5b6..d19615d6c 100644
--- 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
@@ -3,13 +3,14 @@
* ONAP-REST
* ================================================================================
* Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2019 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -38,117 +39,63 @@ import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
+import lombok.Getter;
+import lombok.Setter;
+
@Entity
-@Table(name = "FWTag")
-@NamedQuery(name = "FWTag.findAll", query= "Select p from FWTag p")
-public class FWTag implements Serializable {
+@Table(name = "FwTag")
+@NamedQuery(name = "FwTag.findAll", query = "Select p from FwTag p")
+@Getter
+@Setter
+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)
+ @Column(name = "tagName", nullable = false)
@OrderBy("asc")
private String fwTagName;
- @Column(name="description", nullable=true, length=2048)
+ @Column(name = "description", nullable = true, length = 2048)
private String description;
- @Column(name="tagValues", nullable=true)
+ @Column(name = "tagValues", nullable = true)
@OrderBy("asc")
private String tagValues;
@Temporal(TemporalType.TIMESTAMP)
- @Column(name="created_date", updatable=false)
+ @Column(name = "created_date", updatable = false)
private Date createdDate;
@Temporal(TemporalType.TIMESTAMP)
- @Column(name="modified_date", nullable=false)
+ @Column(name = "modified_date", nullable = false)
private Date modifiedDate;
@ManyToOne(optional = false)
- @JoinColumn(name="created_by")
+ @JoinColumn(name = "created_by")
private UserInfo userCreatedBy;
@ManyToOne(optional = false)
- @JoinColumn(name="modified_by")
+ @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;
- }
-
+ /**
+ * Called before an instance is persisted.
+ */
@PrePersist
- public void prePersist() {
+ public void prePersist() {
Date date = new Date();
this.createdDate = date;
this.modifiedDate = date;
}
+ /**
+ * Called before an instance is updated.
+ */
@PreUpdate
public void preUpdate() {
this.modifiedDate = new Date();
}
-
- 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..aa01433ff
--- /dev/null
+++ b/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/FwTagPicker.java
@@ -0,0 +1,104 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP-REST
+ * ================================================================================
+ * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2019 Nordix Foundation.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 lombok.Getter;
+import lombok.Setter;
+
+@Entity
+@Table(name = "FWTagPicker")
+@NamedQuery(name = "FwTagPicker.findAll", query = "Select p from FwTagPicker p")
+@Getter
+@Setter
+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;
+
+ /**
+ * Called before an instance is persisted.
+ */
+ @PrePersist
+ public void prePersist() {
+ Date date = new Date();
+ this.createdDate = date;
+ this.modifiedDate = date;
+ }
+
+ /**
+ * Called before an instance is updated.
+ */
+ @PreUpdate
+ public void preUpdate() {
+ this.modifiedDate = new Date();
+ }
+}
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
index 1b871d183..b89547927 100644
--- 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
@@ -3,13 +3,14 @@
* ONAP-REST
* ================================================================================
* Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2019 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -28,22 +29,25 @@ import javax.persistence.Id;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
+import lombok.Getter;
+import lombok.Setter;
/**
- * Entity implementation class for Entity: Administration
- *
+ * 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 {
+@Table(name = "GlobalRoleSettings")
+@NamedQuery(name = "GlobalRoleSettings.findAll", query = "SELECT g FROM GlobalRoleSettings g")
+@Getter
+@Setter
+public class GlobalRoleSettings implements Serializable {
private static final long serialVersionUID = 1L;
@Id
- @Column(name="role", length=45)
+ @Column(name = "role", length = 45)
private String role;
- @Column(name="lockdown")
+ @Column(name = "lockdown")
private boolean lockdown;
public GlobalRoleSettings() {
@@ -54,40 +58,4 @@ public class GlobalRoleSettings implements Serializable {
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
index 9b0ea0d7f..71e0bc4a2 100644
--- 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
@@ -3,6 +3,7 @@
* ONAP-REST
* ================================================================================
* Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2019 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -17,13 +18,18 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.policy.rest.jpa;
+
import com.fasterxml.jackson.annotation.JsonManagedReference;
+
/*
*/
import java.io.Serializable;
+import java.util.ArrayList;
import java.util.Date;
import java.util.List;
+
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
@@ -43,216 +49,125 @@ import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.persistence.Version;
-/*
- * The Entity class to persist a policy object and its configuration data
- */
+import lombok.Getter;
+import lombok.Setter;
/**
- *
+ * The Entity class to persist a policy object and its configuration data.
*/
+// @formatter:off
@Entity
-//Add a non-unique index and a constraint that says the combo of policyName and scopeId must be unique
-@Table(name="GroupEntity")
+// 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")
+ }
+)
-@NamedQueries({
- @NamedQuery(name="GroupEntity.findAll", query="SELECT e FROM GroupEntity e "),
- @NamedQuery(name="GroupEntity.deleteAll", query="DELETE FROM GroupEntity WHERE 1=1")
-})
+@Getter
+@Setter
+//@formatter:on
public class GroupEntity implements Serializable {
private static final long serialVersionUID = 1L;
@Id
- @Column (name="groupKey", nullable=false)
+ @Column(name = "groupKey", nullable = false)
@GeneratedValue(strategy = GenerationType.AUTO)
private long groupKey;
- @Column (name="groupId", nullable=false)
+ @Column(name = "groupId", nullable = false)
private String groupId;
- @Column(name="groupName", nullable=false, unique=false, length=255)
+ @Column(name = "groupName", nullable = false, unique = false, length = 255)
private String groupName;
@Version
- @Column(name="version")
+ @Column(name = "version")
private int version;
@ManyToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
- @JoinTable(name="PolicyGroupEntity",joinColumns={@JoinColumn(name="groupKey")}, inverseJoinColumns={@JoinColumn(name="policyId")})
+ @JoinTable(name = "PolicyGroupEntity", joinColumns =
+ { @JoinColumn(name = "groupKey") }, inverseJoinColumns =
+ { @JoinColumn(name = "policyId") })
@JsonManagedReference
private List<PolicyEntity> policies;
- @Column(name="created_by", nullable=false, length=255)
+ @Column(name = "created_by", nullable = false, length = 255)
private String createdBy = "guest";
@Temporal(TemporalType.TIMESTAMP)
- @Column(name="created_date", updatable=false)
+ @Column(name = "created_date", updatable = false)
private Date createdDate;
- @Column(name="description", nullable=false, length=2048)
+ @Column(name = "description", nullable = false, length = 2048)
private String description = "NoDescription";
- @Column(name="modified_by", nullable=false, length=255)
+ @Column(name = "modified_by", nullable = false, length = 255)
private String modifiedBy = "guest";
@Temporal(TemporalType.TIMESTAMP)
- @Column(name="modified_date", nullable=false)
+ @Column(name = "modified_date", nullable = false)
private Date modifiedDate;
- @Column(name="defaultGroup", nullable=false)
+ @Column(name = "defaultGroup", nullable = false)
private boolean defaultGroup = false;
- @Column(name="deleted", nullable=false)
+ @Column(name = "deleted", nullable = false)
private boolean deleted = false;
+ /**
+ * Instantiates a new group entity.
+ */
public GroupEntity() {
super();
}
+ /**
+ * Called before an instance is persisted.
+ */
@PrePersist
- public void prePersist() {
+ public void prePersist() {
Date date = new Date();
this.createdDate = date;
this.modifiedDate = date;
}
+ /**
+ * Called before an instance is updated.
+ */
@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<PolicyEntity> getPolicies() {
- return policies;
- }
-
- /**
- * @param configurationDataEntity the configurationDataEntity to set
+ * Adds the policy to group.
+ *
+ * @param policy the policy
*/
public void addPolicyToGroup(PolicyEntity policy) {
- if(!this.policies.contains(policy)){
- this.policies.add(policy);
+ if (policies == null) {
+ policies = new ArrayList<>();
}
- }
- 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;
+ if (!this.policies.contains(policy)) {
+ this.policies.add(policy);
+ }
}
/**
- * @return the deleted
+ * Removes the policy from group.
+ *
+ * @param policy the policy
*/
- public boolean isDeleted() {
- return deleted;
- }
+ public void removePolicyFromGroup(PolicyEntity policy) {
+ this.policies.remove(policy);
- /**
- * @param deleted the deleted to set
- */
- public void setDeleted(boolean deleted) {
- this.deleted = deleted;
+ if (policies.isEmpty()) {
+ policies = null;
+ }
}
-
-
}
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
index 8b10083d8..71eb19ec5 100644
--- 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
@@ -3,13 +3,14 @@
* ONAP-REST
* ================================================================================
* Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2019 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -19,8 +20,7 @@
*/
package org.onap.policy.rest.jpa;
-/*
- */
+
import java.io.Serializable;
import javax.persistence.Column;
@@ -32,35 +32,32 @@ import javax.persistence.NamedQuery;
import javax.persistence.OrderBy;
import javax.persistence.Table;
+import lombok.Getter;
+import lombok.Setter;
@Entity
-@Table(name="GroupPolicyScopeList")
-@NamedQuery(name="GroupPolicyScopeList.findAll", query="SELECT e FROM GroupPolicyScopeList e ")
+@Table(name = "GroupPolicyScopeList")
+@NamedQuery(name = "GroupPolicyScopeList.findAll", query = "SELECT e FROM GroupPolicyScopeList e ")
+@Getter
+@Setter
public class GroupPolicyScopeList implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
- @Column(name="id")
+ @Column(name = "id")
private int id;
- @Column(name="name", nullable=false)
+ @Column(name = "name", nullable = false)
@OrderBy("asc")
private String name;
- @Column(name="groupList")
+ @Column(name = "groupList")
private String groupList;
- @Column(name="description")
+ @Column(name = "description")
private String description;
- public int getId() {
- return this.id;
- }
-
- public void setId(int id) {
- this.id = id;
- }
public String getGroupName() {
return this.name;
}
@@ -69,19 +66,4 @@ public class GroupPolicyScopeList implements Serializable {
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
index 63f673f59..6d1120307 100644
--- 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
@@ -3,13 +3,14 @@
* ONAP-REST
* ================================================================================
* Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2019 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -19,8 +20,7 @@
*/
package org.onap.policy.rest.jpa;
-/*
- */
+
import java.io.Serializable;
import javax.persistence.Column;
@@ -32,48 +32,34 @@ import javax.persistence.NamedQuery;
import javax.persistence.OrderBy;
import javax.persistence.Table;
+import lombok.Getter;
+import lombok.Setter;
@Entity
-@Table(name="GroupServiceList")
-@NamedQuery(name="GroupServiceList.findAll", query="SELECT e FROM GroupServiceList e ")
+@Table(name = "GroupServiceList")
+@NamedQuery(name = "GroupServiceList.findAll", query = "SELECT e FROM GroupServiceList e ")
+@Getter
+@Setter
public class GroupServiceList implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
- @Column(name="id")
+ @Column(name = "id")
private int id;
- @Column(name="name", nullable=false)
+ @Column(name = "name", nullable = false)
@OrderBy("asc")
private String name;
- @Column(name="serviceList ")
+ @Column(name = "serviceList ")
private String serviceList;
- 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
index 574212097..8ae81b9c0 100644
--- 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
@@ -3,13 +3,14 @@
* ONAP-REST
* ================================================================================
* Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2019 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -31,54 +32,30 @@ import javax.persistence.NamedQuery;
import javax.persistence.OrderBy;
import javax.persistence.Table;
+import lombok.Getter;
+import lombok.Setter;
+
@Entity
-@Table(name="MicroServiceAttribute")
-@NamedQuery(name="MicroServiceAttribute.findAll", query="SELECT e FROM MicroServiceAttribute e ")
+@Table(name = "MicroServiceAttribute")
+@NamedQuery(name = "MicroServiceAttribute.findAll", query = "SELECT e FROM MicroServiceAttribute e ")
+@Getter
+@Setter
+
public class MicroServiceAttribute implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
- @Column(name="id")
+ @Column(name = "id")
private int id;
- @Column(name="name", nullable=false)
+ @Column(name = "name", nullable = false)
@OrderBy("asc")
private String name;
- @Column(name="value")
- private String value ;
+ @Column(name = "value")
+ private String value;
- @Column(name="modelName")
+ @Column(name = "modelName")
private String modelName;
-
- 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
index 9719abbed..ab80c582b 100644
--- 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
@@ -3,13 +3,14 @@
* ONAP-REST
* ================================================================================
* Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2019 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -19,8 +20,7 @@
*/
package org.onap.policy.rest.jpa;
-/*
- */
+
import java.io.Serializable;
import javax.persistence.Column;
@@ -32,46 +32,27 @@ import javax.persistence.NamedQuery;
import javax.persistence.OrderBy;
import javax.persistence.Table;
+import lombok.Getter;
+import lombok.Setter;
@Entity
-@Table(name="MicroServiceConfigName")
-@NamedQuery(name="MicroServiceConfigName.findAll", query="SELECT e FROM MicroServiceConfigName e ")
+@Table(name = "MicroServiceConfigName")
+@NamedQuery(name = "MicroServiceConfigName.findAll", query = "SELECT e FROM MicroServiceConfigName e ")
+@Getter
+@Setter
+
public class MicroServiceConfigName implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
- @Column(name="id")
+ @Column(name = "id")
private int id;
- @Column(name="name", nullable=false)
+ @Column(name = "name", nullable = false)
@OrderBy("asc")
private String name;
- @Column(name="description ")
- private String 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;
-
- }
- public String getDescriptionValue() {
- return this.description ;
- }
-
- public void setDescriptionValue(String description ) {
- this.description = description ;
- }
-
+ @Column(name = "description ")
+ private String 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
index 669b191e7..84962d551 100644
--- 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
@@ -3,13 +3,14 @@
* ONAP-REST
* ================================================================================
* Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2019 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -19,8 +20,7 @@
*/
package org.onap.policy.rest.jpa;
-/*
- */
+
import java.io.Serializable;
import javax.persistence.Column;
@@ -32,46 +32,26 @@ import javax.persistence.NamedQuery;
import javax.persistence.OrderBy;
import javax.persistence.Table;
+import lombok.Getter;
+import lombok.Setter;
@Entity
-@Table(name="MicroServiceLocation")
-@NamedQuery(name="MicroServiceLocation.findAll", query="SELECT e FROM MicroServiceLocation e ")
+@Table(name = "MicroServiceLocation")
+@NamedQuery(name = "MicroServiceLocation.findAll", query = "SELECT e FROM MicroServiceLocation e ")
+@Getter
+@Setter
public class MicroServiceLocation implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
- @Column(name="id")
+ @Column(name = "id")
private int id;
- @Column(name="name", nullable=false)
+ @Column(name = "name", nullable = false)
@OrderBy("asc")
private String name;
- @Column(name="description ")
- private String 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;
-
- }
- public String getDescriptionValue() {
- return this.description ;
- }
-
- public void setDescriptionValue(String description ) {
- this.description = description ;
- }
-
+ @Column(name = "description ")
+ private String 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
index 1c6d811e1..ccedd6b8b 100644
--- 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
@@ -3,6 +3,7 @@
* ONAP-REST
* ================================================================================
* Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2019 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -21,6 +22,7 @@
package org.onap.policy.rest.jpa;
import java.io.Serializable;
+
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
@@ -38,12 +40,23 @@ import javax.persistence.Table;
* @version: 0.1
*/
+import lombok.Getter;
+import lombok.Setter;
+// @formatter:off
@Entity
@Table(name = "MicroServiceModels")
-@NamedQueries({@NamedQuery(name = "MicroServiceModels.findAll", query = "SELECT b FROM MicroServiceModels b "),
- @NamedQuery(name = "MicroServiceModels.findAllDecision",
- query = "SELECT b FROM MicroServiceModels b WHERE b.decisionModel=1")})
+@NamedQueries(
+ {
+ @NamedQuery(name = "MicroServiceModels.findAll", query = "SELECT b FROM MicroServiceModels b "),
+ @NamedQuery(
+ name = "MicroServiceModels.findAllDecision",
+ query = "SELECT b FROM MicroServiceModels b WHERE b.decisionModel=1")
+ }
+)
+@Getter
+@Setter
+// @formatter:on
public class MicroServiceModels implements Serializable {
private static final long serialVersionUID = 1L;
@@ -66,10 +79,10 @@ public class MicroServiceModels implements Serializable {
private String attributes;
@Column(name = "ref_attributes", nullable = false, length = 255)
- private String ref_attributes;
+ private String refAttributes;
@Column(name = "sub_attributes", nullable = false, length = 2000)
- private String sub_attributes;
+ private String subAttributes;
@Column(name = "dataOrderInfo", nullable = true, length = 2000)
private String dataOrderInfo;
@@ -89,120 +102,11 @@ public class MicroServiceModels implements Serializable {
@Column(name = "ruleFormation", nullable = true)
private String ruleFormation;
- public String getRuleFormation() {
- return ruleFormation;
- }
-
- public void setRuleFormation(String ruleFormation) {
- this.ruleFormation = ruleFormation;
- }
-
- public String getSub_attributes() {
- return sub_attributes;
- }
-
- public void setSub_attributes(String sub_attributes) {
- this.sub_attributes = sub_attributes;
- }
-
- public String getDataOrderInfo() {
- return dataOrderInfo;
- }
-
- public void setDataOrderInfo(String dataOrderInfo) {
- this.dataOrderInfo = dataOrderInfo;
- }
-
- 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 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;
- }
-
- public Boolean isDecisionModel() {
+ public boolean isDecisionModel() {
return decisionModel;
}
-
- public void setDecisionModel(boolean decisionModel) {
- this.decisionModel = decisionModel;
- }
}
-
diff --git a/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/MicroserviceHeaderdeFaults.java b/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/MicroserviceHeaderdeFaults.java
index 905555120..c7708abb3 100644
--- a/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/MicroserviceHeaderdeFaults.java
+++ b/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/MicroserviceHeaderdeFaults.java
@@ -2,14 +2,15 @@
* ============LICENSE_START=======================================================
* ONAP-REST
* ================================================================================
- * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2018-2019 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2019 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -33,91 +34,55 @@ import javax.persistence.PrePersist;
import javax.persistence.PreUpdate;
import javax.persistence.Table;
+import lombok.Getter;
+import lombok.Setter;
+
@Entity
-@Table(name="MicroserviceHeaderdeFaults")
-@NamedQuery(name="MicroserviceHeaderdeFaults.findAll", query="SELECT e FROM MicroserviceHeaderdeFaults e ")
+@Table(name = "MicroserviceHeaderdeFaults")
+@NamedQuery(name = "MicroserviceHeaderdeFaults.findAll", query = "SELECT e FROM MicroserviceHeaderdeFaults e ")
+@Getter
+@Setter
public class MicroserviceHeaderdeFaults implements Serializable {
private static final long serialVersionUID = 1L;
- private static String domain;
-
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
- @Column(name="id")
+ @Column(name = "id")
private int id;
- @Column(name="onapName")
+ @Column(name = "onapName")
private String onapName;
- @Column(name="guard")
- private String guard ;
+ @Column(name = "guard")
+ private String guard;
- @Column(name="priority")
+ @Column(name = "priority")
private String priority;
- @Column(name="riskType")
- private String riskType ;
+ @Column(name = "riskType")
+ private String riskType;
- @Column(name="riskLevel")
+ @Column(name = "riskLevel")
private String riskLevel;
- @Column(name="modelName", nullable=false)
+ @Column(name = "modelName", nullable = false)
@OrderBy("asc")
private String modelName;
+ /**
+ * Called before persisting the object.
+ */
@PrePersist
- public void prePersist() {
-
+ public void prePersist() {
+ // Required for testing
}
+
+ /**
+ * Called before updating the object.
+ */
@PreUpdate
public void preUpdate() {
+ // Required for testing
}
-
-
- public int getId() {
- return this.id;
- }
-
- public void setId(int id) {
- this.id = id;
- }
-
- public String getModelName() {
- return modelName;
- }
- public void setModelName(String modelName) {
- this.modelName = modelName;
- }
- public String getOnapName() {
- return onapName;
- }
- public void setOnapName(String onapName) {
- this.onapName = onapName;
- }
- public String getGuard() {
- return guard;
- }
- public void setGuard(String guard) {
- this.guard = guard;
- }
- public String getPriority() {
- return priority;
- }
- public void setPriority(String priority) {
- this.priority = priority;
- }
- 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;
- }
-
} \ No newline at end of file
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
index 1c6b75d25..0734203e4 100644
--- 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
@@ -3,13 +3,14 @@
* ONAP-REST
* ================================================================================
* Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2019 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -20,6 +21,8 @@
package org.onap.policy.rest.jpa;
+import com.att.research.xacml.api.Identifier;
+
import java.io.Serializable;
import java.util.Date;
import java.util.HashSet;
@@ -40,15 +43,17 @@ import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.persistence.Transient;
-import com.att.research.xacml.api.Identifier;
+import lombok.Getter;
+import lombok.Setter;
/**
* The persistent class for the Obadvice database table.
- *
*/
@Entity
-@Table(name="Obadvice")
-@NamedQuery(name="Obadvice.findAll", query="SELECT o FROM Obadvice o")
+@Table(name = "Obadvice")
+@NamedQuery(name = "Obadvice.findAll", query = "SELECT o FROM Obadvice o")
+@Getter
+@Setter
public class Obadvice implements Serializable {
private static final long serialVersionUID = 1L;
@@ -58,44 +63,53 @@ public class Obadvice implements Serializable {
public static final String EFFECT_DENY = "Deny";
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
- @Column(name="id")
+ @Column(name = "id")
private int id;
- @Column(name="type", nullable=false)
+ @Column(name = "type", nullable = false)
private String type;
- @Column(name="xacml_id", nullable=false, length=255)
+ @Column(name = "xacml_id", nullable = false, length = 255)
private String xacmlId;
- @Column(name="fulfill_on", nullable=true, length=32)
+ @Column(name = "fulfill_on", nullable = true, length = 32)
private String fulfillOn;
- @Column(name="description", nullable=true, length=2048)
+ @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)
+ // bi-directional one-to-many association to Attribute Assignment
+ @OneToMany(mappedBy = "obadvice", orphanRemoval = true, cascade = CascadeType.REMOVE)
private Set<ObadviceExpression> obadviceExpressions = new HashSet<>(2);
- @Column(name="created_by", nullable=false, length=255)
+ @Column(name = "created_by", nullable = false, length = 255)
private String createdBy;
@Temporal(TemporalType.TIMESTAMP)
- @Column(name="created_date", nullable=false, updatable=false)
+ @Column(name = "created_date", nullable = false, updatable = false)
private Date createdDate;
- @Column(name="modified_by", nullable=false, length=255)
+ @Column(name = "modified_by", nullable = false, length = 255)
private String modifiedBy;
@Temporal(TemporalType.TIMESTAMP)
- @Column(name="modified_date", nullable=false)
+ @Column(name = "modified_date", nullable = false)
private Date modifiedDate;
+ /**
+ * Instantiates a new obadvice.
+ */
public Obadvice() {
this.type = Obadvice.OBLIGATION;
this.fulfillOn = Obadvice.EFFECT_PERMIT;
}
+ /**
+ * Instantiates a new obadvice.
+ *
+ * @param domain the domain
+ * @param userid the userid
+ */
public Obadvice(String domain, String userid) {
this.xacmlId = domain;
this.type = Obadvice.OBLIGATION;
@@ -104,86 +118,40 @@ public class Obadvice implements Serializable {
this.modifiedBy = userid;
}
+ /**
+ * Instantiates a new obadvice.
+ *
+ * @param id the id
+ * @param userid the userid
+ */
public Obadvice(Identifier id, String userid) {
this(id.stringValue(), userid);
}
+ /**
+ * Pre persist.
+ */
@PrePersist
- public void prePersist() {
+ public void prePersist() {
Date date = new Date();
this.createdDate = date;
this.modifiedDate = date;
}
+ /**
+ * Pre update.
+ */
@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<ObadviceExpression> getObadviceExpressions() {
- return this.obadviceExpressions;
- }
-
- public void setObadviceExpressions(Set<ObadviceExpression> obadviceExpressions) {
- this.obadviceExpressions = obadviceExpressions;
- }
-
+ /**
+ * Adds the obadvice expression.
+ *
+ * @param obadviceExpression the obadvice expression
+ * @return the obadvice expression
+ */
public ObadviceExpression addObadviceExpression(ObadviceExpression obadviceExpression) {
this.obadviceExpressions.add(obadviceExpression);
obadviceExpression.setObadvice(this);
@@ -191,6 +159,12 @@ public class Obadvice implements Serializable {
return obadviceExpression;
}
+ /**
+ * Removes the obadvice expression.
+ *
+ * @param obadviceExpression the obadvice expression
+ * @return the obadvice expression
+ */
public ObadviceExpression removeObadviceExpression(ObadviceExpression obadviceExpression) {
this.obadviceExpressions.remove(obadviceExpression);
obadviceExpression.setObadvice(null);
@@ -198,6 +172,9 @@ public class Obadvice implements Serializable {
return obadviceExpression;
}
+ /**
+ * Removes the all expressions.
+ */
public void removeAllExpressions() {
if (this.obadviceExpressions == null) {
return;
@@ -208,6 +185,11 @@ public class Obadvice implements Serializable {
this.obadviceExpressions.clear();
}
+ /**
+ * Clone.
+ *
+ * @return the obadvice
+ */
@Transient
@Override
public Obadvice clone() {
@@ -219,7 +201,7 @@ public class Obadvice implements Serializable {
obadvice.description = this.description;
obadvice.createdBy = this.createdBy;
obadvice.modifiedBy = this.modifiedBy;
- for (ObadviceExpression exp: this.obadviceExpressions) {
+ for (ObadviceExpression exp : this.obadviceExpressions) {
obadvice.addObadviceExpression(exp.clone());
}
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
index 9d82b7325..db437095c 100644
--- 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
@@ -3,13 +3,14 @@
* ONAP-REST
* ================================================================================
* Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2019 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -33,14 +34,17 @@ import javax.persistence.NamedQuery;
import javax.persistence.OneToOne;
import javax.persistence.Table;
+import lombok.Getter;
+import lombok.Setter;
/**
* The persistent class for the ObadviceExpressions database table.
- *
*/
@Entity
-@Table(name="ObadviceExpressions")
-@NamedQuery(name="ObadviceExpression.findAll", query="SELECT o FROM ObadviceExpression o")
+@Table(name = "ObadviceExpressions")
+@NamedQuery(name = "ObadviceExpression.findAll", query = "SELECT o FROM ObadviceExpression o")
+@Getter
+@Setter
public class ObadviceExpression implements Serializable {
private static final long serialVersionUID = 1L;
@@ -53,58 +57,26 @@ public class ObadviceExpression implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
- @Column(name="id")
+ @Column(name = "id")
private int id;
- //unidirectional one-to-one association to Attribute
+ // unidirectional one-to-one association to Attribute
@OneToOne
- @JoinColumn(name="attribute_id")
+ @JoinColumn(name = "attribute_id")
private Attribute attribute;
- @Column(name="type", nullable=false)
+ @Column(name = "type", nullable = false)
private String type;
- //bi-directional many-to-one association to Obadvice
+ // bi-directional many-to-one association to Obadvice
@ManyToOne
- @JoinColumn(name="obadvice_id")
+ @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;
- }
-
@Override
public ObadviceExpression clone() {
ObadviceExpression expression = new ObadviceExpression();
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
index 0b39129a8..e128241ec 100644
--- 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
@@ -3,13 +3,14 @@
* ONAP-REST
* ================================================================================
* Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2019 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -19,8 +20,7 @@
*/
package org.onap.policy.rest.jpa;
-/*
- */
+
import java.io.Serializable;
import java.util.Date;
@@ -39,106 +39,63 @@ import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
+import lombok.Getter;
+import lombok.Setter;
+/**
+ * The Class OnapName.
+ */
@Entity
-@Table(name="OnapName")
-@NamedQuery(name="OnapName.findAll", query="SELECT e FROM OnapName e ")
+@Table(name = "OnapName")
+@NamedQuery(name = "OnapName.findAll", query = "SELECT e FROM OnapName e ")
+@Getter
+@Setter
public class OnapName implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
- @Column(name="id")
+ @Column(name = "id")
private int id;
- @Column(name="onap_Name", nullable=false, unique=true)
+ @Column(name = "onap_Name", nullable = false, unique = true)
@OrderBy("asc")
- private String onapName;
+ private String name;
@Temporal(TemporalType.TIMESTAMP)
- @Column(name="created_date", updatable=false)
+ @Column(name = "created_date", updatable = false)
private Date createdDate;
- @Column(name="description", nullable=true, length=2048)
+ @Column(name = "description", nullable = true, length = 2048)
private String description;
@Temporal(TemporalType.TIMESTAMP)
- @Column(name="modified_date", nullable=false)
+ @Column(name = "modified_date", nullable = false)
private Date modifiedDate;
@ManyToOne(optional = false)
- @JoinColumn(name="created_by")
+ @JoinColumn(name = "created_by")
private UserInfo userCreatedBy;
@ManyToOne(optional = false)
- @JoinColumn(name="modified_by")
+ @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;
- }
-
+ /**
+ * Pre persist.
+ */
@PrePersist
- public void prePersist() {
+ public void prePersist() {
Date date = new Date();
this.createdDate = date;
this.modifiedDate = date;
}
+ /**
+ * Pre update.
+ */
@PreUpdate
public void preUpdate() {
this.modifiedDate = new Date();
}
- 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/OptimizationModels.java b/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/OptimizationModels.java
index 60b360029..457ca7382 100644
--- a/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/OptimizationModels.java
+++ b/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/OptimizationModels.java
@@ -3,13 +3,14 @@
* ONAP-REST
* ================================================================================
* Copyright (C) 2018 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2019 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -17,6 +18,7 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.policy.rest.jpa;
import java.io.Serializable;
@@ -32,151 +34,59 @@ import javax.persistence.NamedQuery;
import javax.persistence.OrderBy;
import javax.persistence.Table;
/*
- * JPA for the OOF Models.
- *
+ * JPA for the OOF Models.
+ *
* @version: 0.1
*/
+import lombok.Getter;
+import lombok.Setter;
@Entity
-@Table(name="OptimizationModels")
-@NamedQuery(name="OptimizationModels.findAll", query="SELECT b FROM OptimizationModels b ")
-public class OptimizationModels implements Serializable{
+@Table(name = "OptimizationModels")
+@NamedQuery(name = "OptimizationModels.findAll", query = "SELECT b FROM OptimizationModels b ")
+@Getter
+@Setter
+public class OptimizationModels implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
- @Column(name="id")
+ @Column(name = "id")
private int id;
- @Column(name="modelName", nullable=false, unique=true)
+ @Column(name = "modelName", nullable = false, unique = true)
@OrderBy("asc")
private String modelName;
- @Column(name="description", nullable=true, length=2048)
+ @Column(name = "description", nullable = true, length = 2048)
private String description;
- @Column(name="dependency", nullable=true, length=2048)
+ @Column(name = "dependency", nullable = true, length = 2048)
private String dependency;
- @Column(name="attributes", nullable=false, length=255)
+ @Column(name = "attributes", nullable = false, length = 255)
private String attributes;
- @Column(name="ref_attributes", nullable=false, length=255)
+ @Column(name = "ref_attributes", nullable = false, length = 255)
private String refattributes;
- @Column (name="sub_attributes", nullable=false, length=2000)
+ @Column(name = "sub_attributes", nullable = false, length = 2000)
private String subattributes;
- @Column (name="dataOrderInfo", nullable=true, length=2000)
+ @Column(name = "dataOrderInfo", nullable = true, length = 2000)
private String dataOrderInfo;
- @Column (name="version", nullable=false, length=2000)
+ @Column(name = "version", nullable = false, length = 2000)
private String version;
- @Column (name="enumValues", nullable=false, length=2000)
+ @Column(name = "enumValues", nullable = false, length = 2000)
private String enumValues;
- @Column (name="annotation", nullable=false, length=2000)
+ @Column(name = "annotation", nullable = false, length = 2000)
private String annotation;
- public String getSubattributes() {
- return subattributes;
- }
-
- public void setSubattributes(String subattributes) {
- this.subattributes = subattributes;
- }
-
- public String getDataOrderInfo() {
- return dataOrderInfo;
- }
-
- public void setDataOrderInfo(String dataOrderInfo) {
- this.dataOrderInfo = dataOrderInfo;
- }
-
- public String getVersion() {
- return version;
- }
-
- public void setVersion(String version) {
- this.version = version;
- }
-
@ManyToOne
- @JoinColumn(name="imported_by")
+ @JoinColumn(name = "imported_by")
private UserInfo userCreatedBy;
-
- public UserInfo getUserCreatedBy() {
- return userCreatedBy;
- }
-
- public void setUserCreatedBy(UserInfo userCreatedBy) {
- this.userCreatedBy = userCreatedBy;
- }
-
- public String getAttributes() {
- return attributes;
- }
-
- public void setAttributes(String attributes) {
- this.attributes = attributes;
- }
-
- public String getRefattributes() {
- return refattributes;
- }
-
- public void setRefattributes(String refattributes) {
- this.refattributes = refattributes;
- }
-
- 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/PIPConfigParam.java b/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/PIPConfigParam.java
deleted file mode 100644
index 0f32de6d3..000000000
--- a/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/PIPConfigParam.java
+++ /dev/null
@@ -1,148 +0,0 @@
-/*-
- * ============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() {
- //An empty constructor
- }
-
- 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/PIPResolverParam.java b/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/PIPResolverParam.java
deleted file mode 100644
index 7356eebf8..000000000
--- a/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/PIPResolverParam.java
+++ /dev/null
@@ -1,148 +0,0 @@
-/*-
- * ============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() {
- // Empty constructor
- }
-
- 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/PdpEntity.java b/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/PdpEntity.java
index 92c0c9dbe..69ad3f572 100644
--- 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
@@ -3,13 +3,14 @@
* ONAP-REST
* ================================================================================
* Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2019 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -19,8 +20,7 @@
*/
package org.onap.policy.rest.jpa;
-/*
- */
+
import java.io.Serializable;
import java.util.Date;
@@ -39,108 +39,95 @@ import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
-/*
- * The Entity class to persist a policy object and its configuration data
- */
+import lombok.Getter;
+import lombok.Setter;
/**
- *
+ * The Entity class to persist a policy object and its configuration data.
*/
+// @formatter:off
@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")
-})
-
+// 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")
+ }
+)
+@Getter
+@Setter
+// @formatter:on
public class PdpEntity implements Serializable {
private static final long serialVersionUID = 1L;
@Id
- //@GeneratedValue(strategy = GenerationType.SEQUENCE, generator="seqPdp")
+ // @GeneratedValue(strategy = GenerationType.SEQUENCE, generator="seqPdp")
@GeneratedValue(strategy = GenerationType.AUTO)
- @Column (name="pdpKey")
+ @Column(name = "pdpKey")
private long pdpKey;
- @Column (name="pdpId", nullable=false, unique=false, length=255)
+ @Column(name = "pdpId", nullable = false, unique = false, length = 255)
private String pdpId;
- @Column(name="pdpName", nullable=false, unique=false, length=255)
+ @Column(name = "pdpName", nullable = false, unique = false, length = 255)
private String pdpName;
- @Column(name="jmxPort", nullable=false, unique=false)
+ @Column(name = "jmxPort", nullable = false, unique = false)
private int jmxPort;
-
- @ManyToOne(optional=false)
- @JoinColumn(name="groupKey", referencedColumnName="groupKey")
+ @ManyToOne(optional = false)
+ @JoinColumn(name = "groupKey", referencedColumnName = "groupKey")
private GroupEntity groupEntity;
- @Column(name="created_by", nullable=false, length=255)
+ @Column(name = "created_by", nullable = false, length = 255)
private String createdBy = "guest";
@Temporal(TemporalType.TIMESTAMP)
- @Column(name="created_date", updatable=false)
+ @Column(name = "created_date", updatable = false)
private Date createdDate;
- @Column(name="description", nullable=false, length=2048)
+ @Column(name = "description", nullable = false, length = 2048)
private String description = "NoDescription";
- @Column(name="modified_by", nullable=false, length=255)
+ @Column(name = "modified_by", nullable = false, length = 255)
private String modifiedBy = "guest";
@Temporal(TemporalType.TIMESTAMP)
- @Column(name="modified_date", nullable=false)
+ @Column(name = "modified_date", nullable = false)
private Date modifiedDate;
- @Column(name="deleted", nullable=false)
+ @Column(name = "deleted", nullable = false)
private boolean deleted = false;
+ /**
+ * Instantiates a new pdp entity.
+ */
public PdpEntity() {
super();
}
+ /**
+ * Pre persist.
+ */
@PrePersist
- public void prePersist() {
+ public void prePersist() {
Date date = new Date();
this.createdDate = date;
this.modifiedDate = date;
}
+ /**
+ * Pre update.
+ */
@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;
- }
-
-
-
/**
+ * Gets the group.
+ *
* @return the configurationDataEntity
*/
public GroupEntity getGroup() {
@@ -148,94 +135,11 @@ public class PdpEntity implements Serializable {
}
/**
- * @param configurationDataEntity the configurationDataEntity to set
+ * Sets the group.
+ *
+ * @param group the new group
*/
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/VNFType.java b/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/PepOptions.java
index 3d7c7f67b..3a5f791de 100644
--- a/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/VNFType.java
+++ b/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/PepOptions.java
@@ -3,6 +3,7 @@
* ONAP-REST
* ================================================================================
* Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2019 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -20,8 +21,12 @@
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;
@@ -37,111 +42,73 @@ import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
+import lombok.Getter;
+import lombok.Setter;
-
+/**
+ * The Class PepOptions.
+ */
@Entity
-@Table(name="VNFType")
-@NamedQuery(name="VNFType.findAll", query="SELECT v FROM VNFType v ")
-public class VNFType implements Serializable {
+@Table(name = "PepOptions")
+@NamedQuery(name = "PepOptions.findAll", query = "Select p from PepOptions p")
+@Getter
+@Setter
+public class PepOptions implements Serializable {
private static final long serialVersionUID = 1L;
-
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
- @Column(name="id")
+ @Column(name = "Id")
private int id;
- @Column(name="vnf_type", nullable=false, unique=true)
+ @Column(name = "PEP_NAME", nullable = false)
@OrderBy("asc")
- private String vnftype;
+ 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)
+ @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)
+ @Column(name = "modified_date", nullable = false)
private Date modifiedDate;
@ManyToOne(optional = false)
- @JoinColumn(name="created_by")
+ @JoinColumn(name = "created_by")
private UserInfo userCreatedBy;
@ManyToOne(optional = false)
- @JoinColumn(name="modified_by")
+ @JoinColumn(name = "modified_by")
private UserInfo userModifiedBy;
- public VNFType() {
+ /**
+ * Instantiates a new PEP options.
+ */
+ public PepOptions() {
this.modifiedDate = new Date();
}
- 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 String getVnftype() {
- return vnftype;
- }
-
- public void setVnftype(String vnftype) {
- this.vnftype = vnftype;
- }
-
+ /**
+ * Pre persist.
+ */
@PrePersist
- public void prePersist() {
+ public void prePersist() {
Date date = new Date();
this.createdDate = date;
this.modifiedDate = date;
}
+ /**
+ * Pre update.
+ */
@PreUpdate
public void preUpdate() {
this.modifiedDate = new 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 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..06f6bef61
--- /dev/null
+++ b/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/PipConfigParam.java
@@ -0,0 +1,135 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP-REST
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2019 Nordix Foundation.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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;
+import javax.persistence.Transient;
+
+import lombok.Getter;
+import lombok.NoArgsConstructor;
+import lombok.Setter;
+import lombok.ToString;
+
+/**
+ * The persistent class for the PipConfigParams database table.
+ *
+ */
+@Entity
+@Table(name = "PipConfigParams")
+@NamedQuery(name = "PipConfigParam.findAll", query = "SELECT p FROM PipConfigParam p")
+@Getter
+@Setter
+@ToString
+/**
+ * Instantiates a new PIP config param.
+ */
+@NoArgsConstructor
+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;
+
+ /**
+ * Instantiates a new PIP config param.
+ *
+ * @param param the param
+ */
+ public PipConfigParam(String param) {
+ this.paramName = param;
+ }
+
+ /**
+ * Instantiates a new PIP config param.
+ *
+ * @param param the param
+ * @param value the value
+ */
+ public PipConfigParam(String param, String value) {
+ this(param);
+ this.paramValue = value;
+ }
+
+ /**
+ * Instantiates a new PIP config param.
+ *
+ * @param param the param
+ */
+ public PipConfigParam(PipConfigParam param) {
+ this(param.getParamName(), param.getParamValue());
+ this.paramDefault = param.getParamDefault();
+ this.required = param.required;
+ }
+
+ /**
+ * Checks if is required.
+ *
+ * @return true, if is required
+ */
+ @Transient
+ public boolean isRequired() {
+ return this.required == '1';
+ }
+
+ /**
+ * Sets the required flag.
+ *
+ * @param required the new required flag
+ */
+ @Transient
+ public void setRequiredFlag(boolean required) {
+ if (required) {
+ this.setRequired('1');
+ } else {
+ this.setRequired('0');
+ }
+ }
+}
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
index d34c4bd0b..99bd613e8 100644
--- 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
@@ -3,13 +3,14 @@
* ONAP-REST
* ================================================================================
* Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2019 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -20,6 +21,12 @@
package org.onap.policy.rest.jpa;
+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;
+
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
@@ -49,85 +56,89 @@ import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.persistence.Transient;
+import lombok.Getter;
+import lombok.NoArgsConstructor;
+import lombok.Setter;
+import lombok.ToString;
+
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.
- *
+ * 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 {
+@Table(name = "PipConfiguration")
+@NamedQuery(name = "PipConfiguration.findAll", query = "SELECT p FROM PipConfiguration p")
+@Getter
+@Setter
+@NoArgsConstructor
+@ToString
+public class PipConfiguration implements Serializable {
private static final long serialVersionUID = 1L;
- private static final Log logger = LogFactory.getLog(PIPConfiguration.class);
+ private static final Log logger = LogFactory.getLog(PipConfiguration.class);
@Id
- @GeneratedValue(strategy=GenerationType.AUTO)
- @Column(name="id")
+ @GeneratedValue(strategy = GenerationType.AUTO)
+ @Column(name = "id")
private int id;
- @Column(name="DESCRIPTION", nullable=true, length=2048)
+ @Column(name = "DESCRIPTION", nullable = true, length = 2048)
private String description;
- @Column(name="NAME", nullable=false, length=255)
+ @Column(name = "NAME", nullable = false, length = 255)
private String name;
- @Column(name="CLASSNAME", nullable=false, length=2048)
+ @Column(name = "CLASSNAME", nullable = false, length = 2048)
private String classname;
- @Column(name="ISSUER", nullable=true, length=1024)
+ @Column(name = "ISSUER", nullable = true, length = 1024)
private String issuer;
- @Column(name="READ_ONLY", nullable=false)
+ @Column(name = "READ_ONLY", nullable = false)
private char readOnly = '0';
- @Column(name="REQUIRES_RESOLVER", nullable=false)
+ @Column(name = "REQUIRES_RESOLVER", nullable = false)
private char requiresResolvers;
- @Column(name="CREATED_BY", nullable=false, length=255)
+ @Column(name = "CREATED_BY", nullable = false, length = 255)
private String createdBy = "guest";
@Temporal(TemporalType.TIMESTAMP)
- @Column(name="CREATED_DATE", nullable=false, updatable=false)
+ @Column(name = "CREATED_DATE", nullable = false, updatable = false)
private Date createdDate;
- @Column(name="MODIFIED_BY", nullable=false, length=255)
+ @Column(name = "MODIFIED_BY", nullable = false, length = 255)
private String modifiedBy = "guest";
@Temporal(TemporalType.TIMESTAMP)
- @Column(name="MODIFIED_DATE", nullable=false)
+ @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<PIPConfigParam> pipconfigParams = new HashSet<>();
+ // bi-directional many-to-one association to PipConfigParam
+ @OneToMany(mappedBy = "pipconfiguration", orphanRemoval = true, cascade = CascadeType.REMOVE)
+ private Set<PipConfigParam> pipconfigParams = new HashSet<>();
- //bi-directional many-to-one association to PIPType
+ // 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<PIPResolver> pipresolvers = new HashSet<>();
-
- public PIPConfiguration() {
- //An empty constructor
- }
-
- public PIPConfiguration(PIPConfiguration config, String user) {
+ @JoinColumn(name = "TYPE")
+ private PipType piptype;
+
+ // bi-directional many-to-one association to PipResolver
+ @OneToMany(mappedBy = "pipconfiguration", orphanRemoval = true, cascade = CascadeType.REMOVE)
+ private Set<PipResolver> pipresolvers = new HashSet<>();
+
+ /**
+ * Instantiates a new PIP configuration.
+ *
+ * @param config the config
+ * @param user the user
+ */
+ public PipConfiguration(PipConfiguration config, String user) {
this.description = config.description;
this.name = config.name;
this.classname = config.classname;
@@ -135,108 +146,77 @@ public class PIPConfiguration implements Serializable {
this.requiresResolvers = config.requiresResolvers;
this.readOnly = config.readOnly;
this.piptype = config.piptype;
- for (PIPConfigParam param : config.pipconfigParams) {
- this.addPipconfigParam(new PIPConfigParam(param));
+ for (PipConfigParam param : config.pipconfigParams) {
+ this.addPipconfigParam(new PipConfigParam(param));
}
- for (PIPResolver resolver : config.pipresolvers) {
- this.addPipresolver(new PIPResolver(resolver));
+ for (PipResolver resolver : config.pipresolvers) {
+ this.addPipresolver(new PipResolver(resolver));
}
}
- public PIPConfiguration(String id, Properties properties) throws PIPException {
+ /**
+ * Instantiates a new PIP configuration.
+ *
+ * @param id the id
+ * @param properties the properties
+ * @throws PIPException the PIP exception
+ */
+ public PipConfiguration(String id, Properties properties) throws PIPException {
this.readProperties(id, properties);
}
- public PIPConfiguration(String id, Properties properties, String user) throws PIPException {
+ /**
+ * Instantiates a new PIP configuration.
+ *
+ * @param id the id
+ * @param properties the properties
+ * @param user the user
+ * @throws PIPException the PIP exception
+ */
+ public PipConfiguration(String id, Properties properties, String user) throws PIPException {
this.createdBy = user;
this.modifiedBy = user;
this.readProperties(id, properties);
}
+ /**
+ * Pre persist.
+ */
@PrePersist
- public void prePersist() {
+ public void prePersist() {
Date date = new Date();
this.createdDate = date;
this.modifiedDate = date;
}
+ /**
+ * Pre update.
+ */
@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<PIPConfigParam> getPipconfigParams() {
- return this.pipconfigParams;
- }
-
- public void setPipconfigParams(Set<PIPConfigParam> pipconfigParams) {
- this.pipconfigParams = pipconfigParams;
- }
-
- public PIPConfigParam addPipconfigParam(PIPConfigParam pipconfigParam) {
+ /**
+ * Adds the pipconfig param.
+ *
+ * @param pipconfigParam the pipconfig param
+ * @return the PIP config param
+ */
+ public PipConfigParam addPipconfigParam(PipConfigParam pipconfigParam) {
getPipconfigParams().add(pipconfigParam);
pipconfigParam.setPipconfiguration(this);
return pipconfigParam;
}
- public PIPConfigParam removePipconfigParam(PIPConfigParam pipconfigParam) {
+ /**
+ * Removes the pipconfig param.
+ *
+ * @param pipconfigParam the pipconfig param
+ * @return the PIP config param
+ */
+ public PipConfigParam removePipconfigParam(PipConfigParam pipconfigParam) {
if (pipconfigParam == null) {
return pipconfigParam;
}
@@ -246,6 +226,9 @@ public class PIPConfiguration implements Serializable {
return pipconfigParam;
}
+ /**
+ * Clear config params.
+ */
@Transient
public void clearConfigParams() {
while (!this.pipconfigParams.isEmpty()) {
@@ -253,75 +236,49 @@ public class PIPConfiguration implements Serializable {
}
}
- public PIPType getPiptype() {
- return this.piptype;
- }
-
- public void setPiptype(PIPType piptype) {
- this.piptype = piptype;
- }
-
- public Set<PIPResolver> getPipresolvers() {
- return this.pipresolvers;
- }
-
- public void setPipresolvers(Set<PIPResolver> pipresolvers) {
- this.pipresolvers = pipresolvers;
- }
-
- public PIPResolver addPipresolver(PIPResolver pipresolver) {
+ /**
+ * Adds the pipresolver.
+ *
+ * @param pipresolver the pipresolver
+ * @return the PIP resolver
+ */
+ public PipResolver addPipresolver(PipResolver pipresolver) {
getPipresolvers().add(pipresolver);
pipresolver.setPipconfiguration(this);
return pipresolver;
}
- public PIPResolver removePipresolver(PIPResolver pipresolver) {
+ /**
+ * Removes the pipresolver.
+ *
+ * @param pipresolver the pipresolver
+ * @return the PIP resolver
+ */
+ 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;
- }
-
+ /**
+ * Checks if is read only.
+ *
+ * @return true, if is read only
+ */
@Transient
public boolean isReadOnly() {
return this.readOnly == '1';
}
+ /**
+ * Sets the read only flag.
+ *
+ * @param readOnly the new read only flag
+ */
@Transient
- public void setReadOnly(boolean readOnly) {
+ public void setReadOnlyFlag(boolean readOnly) {
if (readOnly) {
this.readOnly = '1';
} else {
@@ -329,13 +286,23 @@ public class PIPConfiguration implements Serializable {
}
}
+ /**
+ * Requires resolvers.
+ *
+ * @return true, if successful
+ */
@Transient
public boolean requiresResolvers() {
return this.requiresResolvers == '1';
}
+ /**
+ * Sets the requires resolvers flag.
+ *
+ * @param requires the new requires resolvers flag
+ */
@Transient
- public void setRequiresResolvers(boolean requires) {
+ public void setRequiresResolversFlag(boolean requires) {
if (requires) {
this.requiresResolvers = '1';
} else {
@@ -343,32 +310,45 @@ public class PIPConfiguration implements Serializable {
}
}
+ /**
+ * Import PIP configurations.
+ *
+ * @param properties the properties
+ * @return the collection
+ */
@Transient
- public static Collection<PIPConfiguration> importPIPConfigurations(Properties properties) {
- Collection<PIPConfiguration> configurations = new ArrayList<>();
+ public static Collection<PipConfiguration> importPipConfigurations(Properties properties) {
+ Collection<PipConfiguration> 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;
+ PipConfiguration configuration;
try {
String user = "super-admin";
- configuration = new PIPConfiguration(id, properties, user);
+ 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");
+ PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "PipConfiguration", "Import failed");
}
}
return configurations;
}
+ /**
+ * Read properties.
+ *
+ * @param id the id
+ * @param properties the properties
+ * @throws PIPException the PIP exception
+ */
@Transient
- protected void readProperties(String id, Properties properties) throws PIPException {
+ protected void readProperties(String id, Properties properties) throws PIPException {
//
// Save the id if we don't have one already
//
@@ -378,7 +358,7 @@ public class PIPConfiguration implements Serializable {
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");
+ PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "PipConfiguration", "Convert id to integer failed");
}
}
//
@@ -391,47 +371,8 @@ public class PIPConfiguration implements Serializable {
//
// Go through each property
//
- for (Object nme : properties.keySet()) {
- if (!nme.toString().startsWith(id)) {
- continue;
- }
- if (nme.equals(id + ".classname")) {
- //
- // We already saved this
- //
- } else if (nme.equals(id + "." + StdConfigurableEngine.PROP_NAME)) {
- this.name = properties.getProperty(nme.toString());
- } else if (nme.equals(id + "." + StdConfigurableEngine.PROP_DESCRIPTION)) {
- this.description = properties.getProperty(nme.toString());
- } else if (nme.equals(id + "." + StdConfigurableEngine.PROP_ISSUER)) {
- this.issuer = properties.getProperty(nme.toString());
- } else if (nme.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<PIPResolver> resolvers = PIPResolver.importResolvers(id + ".resolver",
- properties.getProperty(nme.toString()),
- properties,"super-admin"
- );
- for (PIPResolver resolver : resolvers) {
- this.addPipresolver(resolver);
- }
- } else if (nme.toString().startsWith(id + ".resolver")) {
- //
- // Ignore, the PIPResolver will parse these values
- //
- } else {
- //
- // Config Parameter
- //
- this.addPipconfigParam(new PIPConfigParam(nme.toString().substring(id.length() + 1),
- properties.getProperty(nme.toString())));
- }
+ for (Object propertyKey : properties.keySet()) {
+ readProperty(id, properties, propertyKey);
}
//
// Make sure we have a name at least
@@ -441,7 +382,61 @@ public class PIPConfiguration implements Serializable {
}
}
+ /**
+ * Read a property into the PIP configuration.
+ *
+ * @param id the ID of the property
+ * @param properties the properties object to read from
+ * @param key the key of the property being checked
+ * @throws PIPException on exceptions thrown on reading the property
+ */
+ private void readProperty(String id, Properties properties, Object key) throws PIPException {
+ if (!key.toString().startsWith(id)) {
+ return;
+ }
+ if (key.equals(id + ".classname")) {
+ //
+ // We already saved this
+ //
+ } else if (key.equals(id + "." + StdConfigurableEngine.PROP_NAME)) {
+ this.name = properties.getProperty(key.toString());
+ } else if (key.equals(id + "." + StdConfigurableEngine.PROP_DESCRIPTION)) {
+ this.description = properties.getProperty(key.toString());
+ } else if (key.equals(id + "." + StdConfigurableEngine.PROP_ISSUER)) {
+ this.issuer = properties.getProperty(key.toString());
+ } else if (key.equals(id + ".resolvers")) {
+ //
+ // It has resolvers, make sure this is set to true if
+ // it has been already.
+ //
+ this.setRequiresResolversFlag(true);
+ //
+ // Parse the resolvers
+ //
+ Collection<PipResolver> resolvers = PipResolver.importResolvers(id + ".resolver",
+ properties.getProperty(key.toString()), properties, "super-admin");
+ for (PipResolver resolver : resolvers) {
+ this.addPipresolver(resolver);
+ }
+ } else if (key.toString().startsWith(id + ".resolver")) {
+ //
+ // Ignore, the PipResolver will parse these values
+ //
+ } else {
+ //
+ // Config Parameter
+ //
+ this.addPipconfigParam(new PipConfigParam(key.toString().substring(id.length() + 1),
+ properties.getProperty(key.toString())));
+ }
+ }
+ /**
+ * Gets the configuration.
+ *
+ * @param name the name
+ * @return the configuration
+ */
@Transient
public Map<String, String> getConfiguration(String name) {
String prefix;
@@ -463,14 +458,14 @@ public class PIPConfiguration implements Serializable {
map.put(prefix + "issuer", this.issuer);
}
- for (PIPConfigParam param : this.pipconfigParams) {
+ for (PipConfigParam param : this.pipconfigParams) {
map.put(prefix + param.getParamName(), param.getParamValue());
}
List<String> ids = new ArrayList<>();
- Iterator<PIPResolver> iter = this.pipresolvers.iterator();
+ Iterator<PipResolver> iter = this.pipresolvers.iterator();
while (iter.hasNext()) {
- PIPResolver resolver = iter.next();
+ PipResolver resolver = iter.next();
String idd = Integer.toString(resolver.getId());
Map<String, String> resolverMap = resolver.getConfiguration(prefix + "resolver." + idd);
map.putAll(resolverMap);
@@ -482,8 +477,14 @@ public class PIPConfiguration implements Serializable {
return map;
}
+ /**
+ * Generate properties.
+ *
+ * @param name the name
+ * @return the properties
+ */
@Transient
- public Properties generateProperties(String name) {
+ public Properties generateProperties(String name) {
String prefix;
if (name == null) {
prefix = Integer.toString(this.id);
@@ -492,10 +493,14 @@ public class PIPConfiguration implements Serializable {
prefix = name;
} else {
prefix = name + ".";
+ /**
+ * Instantiates a new PIP configuration.
+ */
+
}
}
Properties props = new Properties();
- props.setProperty("xacml.pip.engines", name);
+ props.setProperty("xacml.pip.engines", prefix);
props.setProperty(prefix + "classname", this.classname);
props.setProperty(prefix + "name", this.name);
if (this.description != null) {
@@ -505,14 +510,14 @@ public class PIPConfiguration implements Serializable {
props.setProperty(prefix + "issuer", this.issuer);
}
- for (PIPConfigParam param : this.pipconfigParams) {
+ for (PipConfigParam param : this.pipconfigParams) {
props.setProperty(prefix + param.getParamName(), param.getParamValue());
}
List<String> ids = new ArrayList<>();
- Iterator<PIPResolver> iter = this.pipresolvers.iterator();
+ Iterator<PipResolver> iter = this.pipresolvers.iterator();
while (iter.hasNext()) {
- PIPResolver resolver = iter.next();
+ PipResolver resolver = iter.next();
String idd = Integer.toString(resolver.getId());
resolver.generateProperties(props, prefix + "resolver." + idd);
ids.add(idd);
@@ -522,17 +527,4 @@ public class PIPConfiguration implements Serializable {
}
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
index a8b02580d..74e24b3db 100644
--- 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
@@ -3,13 +3,14 @@
* ONAP-REST
* ================================================================================
* Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2019 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -20,6 +21,10 @@
package org.onap.policy.rest.jpa;
+import com.att.research.xacml.api.pip.PIPException;
+import com.att.research.xacml.std.pip.engines.StdConfigurableEngine;
+import com.google.common.base.Splitter;
+
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
@@ -47,202 +52,135 @@ 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;
-
+import lombok.Getter;
+import lombok.NoArgsConstructor;
+import lombok.Setter;
/**
- * The persistent class for the PIPResolver database table.
- *
+ * 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 {
+@Table(name = "PipResolver")
+@NamedQuery(name = "PipResolver.findAll", query = "SELECT p FROM PipResolver p")
+@Getter
+@Setter
+@NoArgsConstructor
+public class PipResolver implements Serializable {
private static final long serialVersionUID = 1L;
@Id
- @GeneratedValue(strategy=GenerationType.AUTO)
- @Column(name="id")
+ @GeneratedValue(strategy = GenerationType.AUTO)
+ @Column(name = "id")
private int id;
- @Column(name="DESCRIPTION", nullable=true, length=2048)
+ @Column(name = "DESCRIPTION", nullable = true, length = 2048)
private String description;
- @Column(name="NAME", nullable=false, length=255)
+ @Column(name = "NAME", nullable = false, length = 255)
private String name;
- @Column(name="ISSUER", nullable=true, length=1024)
+ @Column(name = "ISSUER", nullable = true, length = 1024)
private String issuer;
- @Column(name="CLASSNAME", nullable=false, length=2048)
+ @Column(name = "CLASSNAME", nullable = false, length = 2048)
private String classname;
- @Column(name="READ_ONLY", nullable=false)
+ @Column(name = "READ_ONLY", nullable = false)
private char readOnly = '0';
- @Column(name="CREATED_BY", nullable=false, length=255)
+ @Column(name = "CREATED_BY", nullable = false, length = 255)
private String createdBy = "guest";
@Temporal(TemporalType.TIMESTAMP)
- @Column(name="CREATED_DATE", nullable=false, updatable=false)
+ @Column(name = "CREATED_DATE", nullable = false, updatable = false)
private Date createdDate;
- @Column(name="MODIFIED_BY", nullable=false, length=255)
+ @Column(name = "MODIFIED_BY", nullable = false, length = 255)
private String modifiedBy = "guest";
@Temporal(TemporalType.TIMESTAMP)
- @Column(name="MODIFIED_DATE", nullable=false)
+ @Column(name = "MODIFIED_DATE", nullable = false)
private Date modifiedDate;
- //bi-directional many-to-one association to PIPConfiguration
+ // 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<PIPResolverParam> pipresolverParams = new HashSet<>();
-
- public PIPResolver() {
- //An empty constructor
- }
-
- public PIPResolver(String prefix, Properties properties, String user) throws PIPException {
+ @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<PipResolverParam> pipresolverParams = new HashSet<>();
+
+ /**
+ * Instantiates a new PIP resolver.
+ *
+ * @param prefix the prefix
+ * @param properties the properties
+ * @param user the user
+ * @throws PIPException the PIP exception
+ */
+ 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) {
+ /**
+ * Instantiates a new PIP resolver.
+ *
+ * @param resolver the resolver
+ */
+ 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));
+ for (PipResolverParam param : resolver.pipresolverParams) {
+ this.addPipresolverParam(new PipResolverParam(param));
}
}
+ /**
+ * Pre persist.
+ */
@PrePersist
- public void prePersist() {
+ public void prePersist() {
Date date = new Date();
this.createdDate = date;
this.modifiedDate = date;
}
+ /**
+ * Pre update.
+ */
@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<PIPResolverParam> getPipresolverParams() {
- return this.pipresolverParams;
- }
-
- public void setPipresolverParams(Set<PIPResolverParam> pipresolverParams) {
- this.pipresolverParams = pipresolverParams;
- }
-
- public PIPResolverParam addPipresolverParam(PIPResolverParam pipresolverParam) {
+ /**
+ * Adds the pipresolver param.
+ *
+ * @param pipresolverParam the pipresolver param
+ * @return the PIP resolver param
+ */
+ public PipResolverParam addPipresolverParam(PipResolverParam pipresolverParam) {
getPipresolverParams().add(pipresolverParam);
pipresolverParam.setPipresolver(this);
return pipresolverParam;
}
- public PIPResolverParam removePipresolverParam(PIPResolverParam pipresolverParam) {
+ /**
+ * Removes the pipresolver param.
+ *
+ * @param pipresolverParam the pipresolver param
+ * @return the PIP resolver param
+ */
+ public PipResolverParam removePipresolverParam(PipResolverParam pipresolverParam) {
if (pipresolverParam == null) {
return pipresolverParam;
}
@@ -252,6 +190,9 @@ public class PIPResolver implements Serializable {
return pipresolverParam;
}
+ /**
+ * Clear params.
+ */
@Transient
public void clearParams() {
while (!this.pipresolverParams.isEmpty()) {
@@ -259,11 +200,21 @@ public class PIPResolver implements Serializable {
}
}
+ /**
+ * Checks if is read only.
+ *
+ * @return true, if is read only
+ */
@Transient
public boolean isReadOnly() {
return this.readOnly == '1';
}
+ /**
+ * Sets the read only.
+ *
+ * @param readOnly the new read only
+ */
@Transient
public void setReadOnly(boolean readOnly) {
if (readOnly) {
@@ -273,15 +224,33 @@ public class PIPResolver implements Serializable {
}
}
+ /**
+ * Import resolvers.
+ *
+ * @param prefix the prefix
+ * @param list the list
+ * @param properties the properties
+ * @param user the user
+ * @return the collection
+ * @throws PIPException the PIP exception
+ */
@Transient
- public static Collection<PIPResolver> importResolvers(String prefix, String list, Properties properties, String user) throws PIPException {
- Collection<PIPResolver> resolvers = new ArrayList<>();
+ public static Collection<PipResolver> importResolvers(String prefix, String list, Properties properties,
+ String user) throws PIPException {
+ Collection<PipResolver> resolvers = new ArrayList<>();
for (String id : Splitter.on(',').trimResults().omitEmptyStrings().split(list)) {
- resolvers.add(new PIPResolver(prefix + "." + id, properties, user));
+ resolvers.add(new PipResolver(prefix + "." + id, properties, user));
}
return resolvers;
}
+ /**
+ * Read properties.
+ *
+ * @param prefix the prefix
+ * @param properties the properties
+ * @throws PIPException the PIP exception
+ */
@Transient
protected void readProperties(String prefix, Properties properties) throws PIPException {
//
@@ -309,12 +278,18 @@ public class PIPResolver implements Serializable {
} else if (nme.equals(prefix + "." + StdConfigurableEngine.PROP_ISSUER)) {
this.issuer = properties.getProperty(nme.toString());
} else {
- this.addPipresolverParam(new PIPResolverParam(nme.toString().substring(prefix.length() + 1),
- properties.getProperty(nme.toString())));
+ this.addPipresolverParam(new PipResolverParam(nme.toString().substring(prefix.length() + 1),
+ properties.getProperty(nme.toString())));
}
}
}
+ /**
+ * Gets the configuration.
+ *
+ * @param prefix the prefix
+ * @return the configuration
+ */
@Transient
public Map<String, String> getConfiguration(String prefix) {
String pref = prefix;
@@ -330,14 +305,20 @@ public class PIPResolver implements Serializable {
if (this.issuer != null && this.issuer.isEmpty()) {
map.put(pref + "issuer", this.issuer);
}
- for (PIPResolverParam param : this.pipresolverParams) {
+ for (PipResolverParam param : this.pipresolverParams) {
map.put(pref + param.getParamName(), param.getParamValue());
}
return map;
}
+ /**
+ * Generate properties.
+ *
+ * @param props the props
+ * @param prefix the prefix
+ */
@Transient
- public void generateProperties(Properties props, String prefix) {
+ public void generateProperties(Properties props, String prefix) {
String pref = prefix;
if (!prefix.endsWith(".")) {
pref = prefix + ".";
@@ -350,19 +331,22 @@ public class PIPResolver implements Serializable {
if (this.issuer != null && this.issuer.isEmpty()) {
props.setProperty(pref + "issuer", this.issuer);
}
- for (PIPResolverParam param : this.pipresolverParams) {
+ for (PipResolverParam param : this.pipresolverParams) {
props.setProperty(pref + param.getParamName(), param.getParamValue());
}
}
+ /**
+ * To string.
+ *
+ * @return the string
+ */
@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 + "]";
+ 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..3dd096862
--- /dev/null
+++ b/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/PipResolverParam.java
@@ -0,0 +1,132 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP-REST
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2019 Nordix Foundation.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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;
+import javax.persistence.Transient;
+
+import lombok.Getter;
+import lombok.NoArgsConstructor;
+import lombok.Setter;
+import lombok.ToString;
+
+/**
+ * The persistent class for the PipResolverParam database table.
+ *
+ */
+@Entity
+@Table(name = "PipResolverParams")
+@NamedQuery(name = "PipResolverParam.findAll", query = "SELECT p FROM PipResolverParam p")
+@Getter
+@Setter
+@NoArgsConstructor
+@ToString
+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;
+
+ /**
+ * Instantiates a new PIP resolver param.
+ *
+ * @param name the name
+ */
+ public PipResolverParam(String name) {
+ this.paramName = name;
+ }
+
+ /**
+ * Instantiates a new PIP resolver param.
+ *
+ * @param name the name
+ * @param value the value
+ */
+ public PipResolverParam(String name, String value) {
+ this(name);
+ this.paramValue = value;
+ }
+
+ /**
+ * Instantiates a new PIP resolver param.
+ *
+ * @param param the param
+ */
+ public PipResolverParam(PipResolverParam param) {
+ this(param.getParamName(), param.getParamValue());
+ this.paramDefault = param.getParamDefault();
+ this.required = param.required;
+ }
+
+ /**
+ * Checks if is required.
+ *
+ * @return true, if is required
+ */
+ @Transient
+ public boolean isRequired() {
+ return this.required == '1';
+ }
+
+ /**
+ * Sets the required.
+ *
+ * @param required the new required
+ */
+ @Transient
+ public void setRequired(boolean required) {
+ if (required) {
+ this.required = '1';
+ } else {
+ this.required = '0';
+ }
+ }
+}
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
index aa8c45ef2..0179d0d33 100644
--- 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
@@ -3,13 +3,14 @@
* ONAP-REST
* ================================================================================
* Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2019 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -33,15 +34,21 @@ import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Transient;
+import lombok.Getter;
+import lombok.NoArgsConstructor;
+import lombok.Setter;
/**
- * The persistent class for the PIPType database table.
- *
+ * 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 {
+@Table(name = "PipType")
+@NamedQuery(name = "PipType.findAll", query = "SELECT p FROM PipType p")
+@Getter
+@Setter
+@NoArgsConstructor
+public class PipType implements Serializable {
private static final long serialVersionUID = 1L;
public static final String TYPE_SQL = "SQL";
@@ -51,81 +58,90 @@ public class PIPType implements Serializable {
public static final String TYPE_CUSTOM = "Custom";
@Id
- @GeneratedValue(strategy=GenerationType.AUTO)
- @Column(name="id")
+ @GeneratedValue(strategy = GenerationType.AUTO)
+ @Column(name = "id")
private int id;
- @Column(name="type", nullable=false, length=45)
+ @Column(name = "type", nullable = false, length = 45)
private String type;
- //bi-directional many-to-one association to PIPConfiguration
- @OneToMany(mappedBy="piptype")
- private Set<PIPConfiguration> pipconfigurations;
-
- public PIPType() {
- // Empty constructor
- }
-
- 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<PIPConfiguration> getPipconfigurations() {
- return this.pipconfigurations;
- }
-
- public void setPipconfigurations(Set<PIPConfiguration> pipconfigurations) {
- this.pipconfigurations = pipconfigurations;
- }
-
- public PIPConfiguration addPipconfiguration(PIPConfiguration pipconfiguration) {
+ // bi-directional many-to-one association to PipConfiguration
+ @OneToMany(mappedBy = "piptype")
+ private Set<PipConfiguration> pipconfigurations;
+
+ /**
+ * Adds the pipconfiguration.
+ *
+ * @param pipconfiguration the pipconfiguration
+ * @return the PIP configuration
+ */
+ public PipConfiguration addPipconfiguration(PipConfiguration pipconfiguration) {
getPipconfigurations().add(pipconfiguration);
pipconfiguration.setPiptype(this);
return pipconfiguration;
}
- public PIPConfiguration removePipconfiguration(PIPConfiguration pipconfiguration) {
+ /**
+ * Removes the pipconfiguration.
+ *
+ * @param pipconfiguration the pipconfiguration
+ * @return the PIP configuration
+ */
+ public PipConfiguration removePipconfiguration(PipConfiguration pipconfiguration) {
getPipconfigurations().remove(pipconfiguration);
pipconfiguration.setPiptype(null);
return pipconfiguration;
}
+ /**
+ * Checks if is sql.
+ *
+ * @return true, if is sql
+ */
@Transient
- public boolean isSQL() {
+ public boolean isSql() {
return this.type.equals(TYPE_SQL);
}
+ /**
+ * Checks if is ldap.
+ *
+ * @return true, if is ldap
+ */
@Transient
- public boolean isLDAP() {
+ public boolean isLdap() {
return this.type.equals(TYPE_LDAP);
}
+ /**
+ * Checks if is csv.
+ *
+ * @return true, if is csv
+ */
@Transient
- public boolean isCSV() {
+ public boolean isCsv() {
return this.type.equals(TYPE_CSV);
}
+ /**
+ * Checks if is hyper CSV.
+ *
+ * @return true, if is hyper CSV
+ */
@Transient
- public boolean isHyperCSV() {
+ public boolean isHyperCsv() {
return this.type.equals(TYPE_HYPERCSV);
}
+ /**
+ * Checks if is custom.
+ *
+ * @return true, if is custom
+ */
@Transient
- public boolean isCustom() {
+ public boolean isCustom() {
return this.type.equals(TYPE_CUSTOM);
}
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
index ba1097500..0f23f55da 100644
--- 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
@@ -3,13 +3,14 @@
* ONAP-REST
* ================================================================================
* Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2019 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -20,6 +21,8 @@
package org.onap.policy.rest.jpa;
+import com.att.research.xacml.api.Identifier;
+
import java.io.Serializable;
import javax.persistence.Column;
@@ -31,11 +34,17 @@ import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.persistence.Transient;
-import com.att.research.xacml.api.Identifier;
+import lombok.Getter;
+import lombok.Setter;
+/**
+ * The Class PolicyAlgorithms.
+ */
@Entity
-@Table(name="PolicyAlgorithms")
-@NamedQuery(name="PolicyAlgorithms.findAll", query="SELECT d FROM PolicyAlgorithms d")
+@Table(name = "PolicyAlgorithms")
+@NamedQuery(name = "PolicyAlgorithms.findAll", query = "SELECT d FROM PolicyAlgorithms d")
+@Getter
+@Setter
public class PolicyAlgorithms implements Serializable {
private static final long serialVersionUID = 1L;
@@ -44,18 +53,24 @@ public class PolicyAlgorithms implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
- @Column(name="id")
+ @Column(name = "id")
private int id;
- @Column(name="is_standard", nullable=false)
+ @Column(name = "is_standard", nullable = false)
private char isStandard;
- @Column(name="xacml_id", nullable=false, unique=true, length=255)
+ @Column(name = "xacml_id", nullable = false, unique = true, length = 255)
private String xacmlId;
- @Column(name="short_name", nullable=false, length=64)
+ @Column(name = "short_name", nullable = false, length = 64)
private String shortName;
+ /**
+ * Instantiates a new policy algorithms.
+ *
+ * @param identifier the identifier
+ * @param standard the standard
+ */
public PolicyAlgorithms(Identifier identifier, char standard) {
this.isStandard = standard;
if (identifier != null) {
@@ -63,54 +78,39 @@ public class PolicyAlgorithms implements Serializable {
}
}
+ /**
+ * Instantiates a new policy algorithms.
+ *
+ * @param identifier the identifier
+ */
public PolicyAlgorithms(Identifier identifier) {
this(identifier, PolicyAlgorithms.STANDARD);
}
+ /**
+ * Instantiates a new policy algorithms.
+ */
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;
- }
-
+ /**
+ * Checks if is standard.
+ *
+ * @return true, if is standard
+ */
@Transient
public boolean isStandard() {
return this.isStandard == PolicyAlgorithms.STANDARD;
}
+ /**
+ * Checks if is custom.
+ *
+ * @return true, if is custom
+ */
@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/PolicyAuditlog.java b/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/PolicyAuditlog.java
index bfd7769b4..75924e867 100644
--- a/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/PolicyAuditlog.java
+++ b/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/PolicyAuditlog.java
@@ -3,6 +3,7 @@
* ONAP-PAP-REST
* ================================================================================
* Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2019 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -21,6 +22,7 @@
package org.onap.policy.rest.jpa;
import java.util.Date;
+
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
@@ -29,11 +31,15 @@ import javax.persistence.Id;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
+import lombok.Getter;
+import lombok.Setter;
+
@Entity
@Table(name = "policyAuditlog")
@NamedQuery(name = "policyAuditlog.findAll", query = "SELECT v FROM PolicyAuditlog v ")
+@Getter
+@Setter
public class PolicyAuditlog {
- private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "id", nullable = false, unique = true)
@@ -50,44 +56,4 @@ public class PolicyAuditlog {
@Column(name = "dateAndTime", nullable = false)
private Date dateAndTime;
-
- public int getId() {
- return id;
- }
-
- public void setId(int id) {
- this.id = id;
- }
-
- public String getUserName() {
- return userName;
- }
-
- public void setUserName(String userName) {
- this.userName = userName;
- }
-
- public String getPolicyName() {
- return policyName;
- }
-
- public void setPolicyName(String policyName) {
- this.policyName = policyName;
- }
-
- public String getActions() {
- return actions;
- }
-
- public void setActions(String actions) {
- this.actions = actions;
- }
-
- public Date getDateAndTime() {
- return dateAndTime;
- }
-
- public void setDateAndTime(Date dateAndTime) {
- this.dateAndTime = dateAndTime;
- }
}
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
deleted file mode 100644
index 7a0c2fe2f..000000000
--- a/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/PolicyDBDaoEntity.java
+++ /dev/null
@@ -1,150 +0,0 @@
-/*-
- * ============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/PolicyDbDaoEntity.java b/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/PolicyDbDaoEntity.java
new file mode 100644
index 000000000..fbad21763
--- /dev/null
+++ b/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/PolicyDbDaoEntity.java
@@ -0,0 +1,107 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP-REST
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2019 Nordix Foundation.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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;
+
+import lombok.Getter;
+import lombok.Setter;
+
+/**
+ * The Entity class to persist a PolicyDbDaoEntity object for registration of PolicyDBDao.
+ */
+// @formatter:off
+@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")
+ }
+)
+@Getter
+@Setter
+//@formatter:on
+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;
+
+ /**
+ * Instantiates a new policy DB dao entity.
+ */
+ public PolicyDbDaoEntity() {
+ super();
+ }
+
+ /**
+ * Pre persist.
+ */
+ @PrePersist
+ public void prePersist() {
+ Date date = new Date();
+ this.createdDate = date;
+ this.modifiedDate = date;
+ }
+
+ /**
+ * Pre update.
+ */
+ @PreUpdate
+ public void preUpdate() {
+ this.modifiedDate = new Date();
+ }
+}
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
index 62fd0266e..7642a1417 100644
--- 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
@@ -3,6 +3,7 @@
* ONAP-REST
* ================================================================================
* Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2019 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -22,6 +23,7 @@ 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;
@@ -37,99 +39,67 @@ import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
+import lombok.Getter;
+import lombok.Setter;
+
+/**
+ * The Class PolicyEditorScopes.
+ */
@Entity
-@Table(name="PolicyEditorScopes")
-@NamedQuery(name="PolicyEditorScopes.findAll", query="SELECT p FROM PolicyEditorScopes p ")
-public class PolicyEditorScopes implements Serializable{
+@Table(name = "PolicyEditorScopes")
+@NamedQuery(name = "PolicyEditorScopes.findAll", query = "SELECT p FROM PolicyEditorScopes p ")
+@Getter
+@Setter
+public class PolicyEditorScopes implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
- @Column(name="id")
+ @Column(name = "id")
private int id;
- @Column(name="scopeName", nullable=false, unique=true)
+ @Column(name = "scopeName", nullable = false, unique = true)
@OrderBy("asc")
private String scopeName;
@Temporal(TemporalType.TIMESTAMP)
- @Column(name="created_date", updatable=false)
+ @Column(name = "created_date", updatable = false)
private Date createdDate;
@Temporal(TemporalType.TIMESTAMP)
- @Column(name="modified_date", nullable=false)
+ @Column(name = "modified_date", nullable = false)
private Date modifiedDate;
@ManyToOne(optional = false)
- @JoinColumn(name="created_by")
+ @JoinColumn(name = "created_by")
private UserInfo userCreatedBy;
@ManyToOne(optional = false)
- @JoinColumn(name="modified_by")
+ @JoinColumn(name = "modified_by")
private UserInfo userModifiedBy;
+ /**
+ * Instantiates a new policy editor scopes.
+ */
public PolicyEditorScopes() {
this.modifiedDate = new Date();
}
+ /**
+ * Pre persist.
+ */
@PrePersist
- public void prePersist() {
+ public void prePersist() {
Date date = new Date();
this.createdDate = date;
this.modifiedDate = date;
}
+ /**
+ * Pre update.
+ */
@PreUpdate
public void preUpdate() {
this.modifiedDate = new Date();
}
-
- 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
index 40ddb4308..8fa80e635 100644
--- 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
@@ -3,13 +3,14 @@
* ONAP-REST
* ================================================================================
* Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2019 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -24,9 +25,10 @@ package org.onap.policy.rest.jpa;
*/
import com.fasterxml.jackson.annotation.JsonBackReference;
import com.fasterxml.jackson.annotation.JsonManagedReference;
+
import java.io.Serializable;
import java.util.Date;
-import java.util.Objects;
+
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
@@ -44,23 +46,45 @@ import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.persistence.Version;
+import lombok.EqualsAndHashCode;
+import lombok.Getter;
+import lombok.Setter;
-/*
- * The Entity class to persist a policy object and its configuration data
+/**
+ * The Entity class to persist a policy object and its configuration data.
*/
-
+// @formatter:off
@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")
-})
+@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"
+ )
+ }
+)
+@Getter
+@Setter
+@EqualsAndHashCode
+// @formatter:on
public class PolicyEntity implements Serializable {
private static final long serialVersionUID = 1L;
@@ -145,43 +169,8 @@ public class PolicyEntity implements Serializable {
}
/**
- * Returns Policy Id.
- * @return the policyId
- */
- public long getPolicyId() {
- return policyId;
- }
-
- /**
- * Returns policy name.
- * @return the policy name
- */
- public String getPolicyName() {
- return policyName;
- }
-
- public void setPolicyName(String policyName) {
- this.policyName = policyName;
- }
-
- /**
- * Returns policy data.
- * @return the policyData
- */
- public String getPolicyData() {
- return policyData;
- }
-
- /**
- * Set policy data.
- * @param policyData the policyData to set
- */
- public void setPolicyData(String policyData) {
- this.policyData = policyData;
- }
-
- /**
* Returns configurationDataEntity.
+ *
* @return the configurationDataEntity
*/
public ConfigurationDataEntity getConfigurationData() {
@@ -190,200 +179,10 @@ public class PolicyEntity implements Serializable {
/**
* Set configurationDataEntity.
+ *
* @param configurationDataEntity the configurationDataEntity to set
*/
public void setConfigurationData(ConfigurationDataEntity configurationDataEntity) {
this.configurationDataEntity = configurationDataEntity;
}
-
- /**
- * Returns actionBodyEntity.
- * @return the actionBodyEntity
- */
- public ActionBodyEntity getActionBodyEntity() {
- return actionBodyEntity;
- }
-
- /**
- * Set actionBodyEntity.
- * @param actionBodyEntity the actionBodyEntity to set
- */
- public void setActionBodyEntity(ActionBodyEntity actionBodyEntity) {
- this.actionBodyEntity = actionBodyEntity;
- }
-
- /**
- * Returns scope.
- * @return the scope
- */
- public String getScope() {
- return scope;
- }
-
- /**
- * Set scope.
- * @param scope the scope to set
- */
- public void setScope(String scope) {
- this.scope = scope;
- }
-
- /**
- * Returns createdBy.
- * @return the createdBy
- */
- public String getCreatedBy() {
- return createdBy;
- }
-
- /**
- * Set createdBy.
- * @param createdBy the createdBy to set
- */
- public void setCreatedBy(String createdBy) {
- this.createdBy = createdBy;
- }
-
- /**
- * Returns description.
- * @return the description
- */
- public String getDescription() {
- return description;
- }
-
- /**
- * Set description.
- * @param description the description to set
- */
- public void setDescription(String description) {
- this.description = description;
- }
-
- /**
- * Returns modifiedBy.
- * @return the modifiedBy
- */
- public String getModifiedBy() {
- return modifiedBy;
- }
-
- /**
- * Set modifiedBy.
- * @param modifiedBy the modifiedBy to set
- */
- public void setModifiedBy(String modifiedBy) {
- this.modifiedBy = modifiedBy;
- }
-
- /**
- * Returns version.
- * @return version
- */
- public int getVersion() {
- return version;
- }
-
- /**
- * Returns createdDate.
- * @return the createdDate
- */
- public Date getCreatedDate() {
- return createdDate;
- }
-
- /**
- * Returns modifiedDate.
- * @return the modifiedDate
- */
- public Date getModifiedDate() {
- return modifiedDate;
- }
-
- /**
- * Return deleted.
- * @return the deleted
- */
- public boolean isDeleted() {
- return deleted;
- }
-
- /**
- * Set deleted.
- * @param deleted the deleted to set
- */
- public void setDeleted(boolean deleted) {
- this.deleted = deleted;
- }
-
- /**
- * Return the reason code.
- * @return deleted reason code
- */
- public String getDeleteReasonCode() {
- return deleteReasonCode;
- }
-
- /**
- * Set the reason of deletion.
- * @param deleteReasonCode String object
- */
- public void setDeleteReasonCode(String deleteReasonCode) {
- this.deleteReasonCode = deleteReasonCode;
- }
-
- /**
- * Return deleted By.
- * @return deletedBy
- */
- public String getDeletedBy() {
- return deletedBy;
- }
-
- /**
- * Set deleted By.
- * @param deletedBy String object
- */
- public void setDeletedBy(String deletedBy) {
- this.deletedBy = deletedBy;
- }
-
- @Override
- public int hashCode() {
- return Objects.hash(policyId, policyName, scope, version, policyVersion, policyData, configurationDataEntity,
- actionBodyEntity, createdBy, createdDate, description, modifiedBy, modifiedDate, deleted);
- }
-
- @Override
- public boolean equals(Object obj) {
- if (obj == null) {
- return false;
- }
- if (obj == this) {
- return true;
- }
- if (!(obj instanceof PolicyEntity)) {
- return false;
- }
-
- PolicyEntity p = (PolicyEntity) obj;
-
- return policyId == p.policyId
- && policyName.equals(p.policyName)
- && scope.equals(p.scope)
- && version == p.version
- && policyVersion == p.policyVersion
- && policyData.equals(p.policyData)
- && ((configurationDataEntity == null && p.configurationDataEntity == null)
- || (configurationDataEntity != null
- && configurationDataEntity
- .equals(p.configurationDataEntity)))
- && ((actionBodyEntity == null && p.actionBodyEntity == null) || (actionBodyEntity != null
- && actionBodyEntity
- .equals(p.actionBodyEntity))) && createdBy.equals(p.createdBy)
- && createdDate.equals(p.createdDate) && description.equals(p.description)
- && modifiedBy.equals(p.modifiedBy) && modifiedDate.equals(p.modifiedDate) && deleted == p.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
index 52f8177f3..175db577c 100644
--- 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
@@ -3,13 +3,14 @@
* ONAP-REST
* ================================================================================
* Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2019 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -17,6 +18,7 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.policy.rest.jpa;
import java.io.Serializable;
@@ -27,34 +29,23 @@ import javax.persistence.Id;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
+import lombok.Getter;
+import lombok.Setter;
+
@Entity
-@Table(name="PolicyGroupEntity")
-@NamedQuery(name="PolicyGroupEntity.findAll", query="SELECT p FROM PolicyGroupEntity p ")
-public class PolicyGroupEntity implements Serializable{
+@Table(name = "PolicyGroupEntity")
+@NamedQuery(name = "PolicyGroupEntity.findAll", query = "SELECT p FROM PolicyGroupEntity p ")
+@Getter
+@Setter
+public class PolicyGroupEntity implements Serializable {
private static final long serialVersionUID = 1L;
@Id
- @Column(name="groupKey")
+ @Column(name = "groupKey")
private int groupKey;
@Id
- @Column(name="policyid")
+ @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/PolicyRoles.java b/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/PolicyRoles.java
index f220570bd..10680313b 100644
--- 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
@@ -3,13 +3,14 @@
* ONAP-REST
* ================================================================================
* Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2019 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -19,6 +20,7 @@
*/
package org.onap.policy.rest.jpa;
+
/*
*/
import java.io.Serializable;
@@ -34,70 +36,44 @@ import javax.persistence.NamedQuery;
import javax.persistence.OrderBy;
import javax.persistence.Table;
-import org.onap.policy.rest.jpa.UserInfo;
-
+import lombok.Getter;
+import lombok.NoArgsConstructor;
+import lombok.Setter;
/**
* The persistent class for the roles database table.
- *
*/
@Entity
-@Table(name="roles")
-@NamedQuery(name="PolicyRoles.findAll", query="SELECT r FROM PolicyRoles r ")
+@Table(name = "roles")
+@NamedQuery(name = "PolicyRoles.findAll", query = "SELECT r FROM PolicyRoles r ")
+@Getter
+@Setter
+@NoArgsConstructor
public class PolicyRoles implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
- @Column(name="id")
+ @Column(name = "id")
private int id;
@ManyToOne
- @JoinColumn(name="loginid")
+ @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)
+ @Column(name = "scope", nullable = true, length = 45)
private String scope;
- @Column(name="role", nullable=false, length=45)
+ @Column(name = "role", nullable = false, length = 45)
private String role;
- public PolicyRoles() {
- // Empty constructor
- }
-
- 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 UserInfo getLoginId() {
+ return loginId;
}
- public void setRole(String role) {
- this.role = role;
+ public void setLoginId(UserInfo loginId) {
+ this.loginId = loginId;
}
-
}
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
index c1597741e..7e0bba3be 100644
--- 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
@@ -3,13 +3,14 @@
* ONAP-REST
* ================================================================================
* Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2019 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -19,8 +20,7 @@
*/
package org.onap.policy.rest.jpa;
-/*
- */
+
import java.io.Serializable;
import javax.persistence.Column;
@@ -32,46 +32,26 @@ import javax.persistence.NamedQuery;
import javax.persistence.OrderBy;
import javax.persistence.Table;
+import lombok.Getter;
+import lombok.Setter;
@Entity
-@Table(name="PolicyScopeClosedLoop")
-@NamedQuery(name="PolicyScopeClosedLoop.findAll", query="SELECT e FROM PolicyScopeClosedLoop e ")
+@Table(name = "PolicyScopeClosedLoop")
+@NamedQuery(name = "PolicyScopeClosedLoop.findAll", query = "SELECT e FROM PolicyScopeClosedLoop e ")
+@Getter
+@Setter
public class PolicyScopeClosedLoop implements Serializable {
private static final long serialVersionUID = 1L;
-
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
- @Column(name="id")
+ @Column(name = "id")
private int id;
- @Column(name="name", nullable=false)
+ @Column(name = "name", nullable = false)
@OrderBy("asc")
private String name;
- @Column(name="description ")
- private String 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;
-
- }
- public String getDescriptionValue() {
- return this.description ;
- }
-
- public void setDescriptionValue(String description ) {
- this.description = description ;
- }
+ @Column(name = "description ")
+ private String 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
index 323275624..ebc570fa8 100644
--- 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
@@ -3,13 +3,14 @@
* ONAP-REST
* ================================================================================
* Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2019 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -19,8 +20,7 @@
*/
package org.onap.policy.rest.jpa;
-/*
- */
+
import java.io.Serializable;
import javax.persistence.Column;
@@ -32,45 +32,26 @@ import javax.persistence.NamedQuery;
import javax.persistence.OrderBy;
import javax.persistence.Table;
+import lombok.Getter;
+import lombok.Setter;
@Entity
-@Table(name="PolicyScopeResource")
-@NamedQuery(name="PolicyScopeResource.findAll", query="SELECT e FROM PolicyScopeResource e ")
+@Table(name = "PolicyScopeResource")
+@NamedQuery(name = "PolicyScopeResource.findAll", query = "SELECT e FROM PolicyScopeResource e ")
+@Getter
+@Setter
public class PolicyScopeResource implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
- @Column(name="id")
+ @Column(name = "id")
private int id;
- @Column(name="name", nullable=false)
+ @Column(name = "name", nullable = false)
@OrderBy("asc")
private String name;
- @Column(name="description ")
- private String 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;
-
- }
- public String getDescriptionValue() {
- return this.description ;
- }
-
- public void setDescriptionValue(String description ) {
- this.description = description ;
- }
+ @Column(name = "description ")
+ private String 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
index 8238110f0..7af22e338 100644
--- 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
@@ -3,13 +3,14 @@
* ONAP-REST
* ================================================================================
* Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2019 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -19,8 +20,7 @@
*/
package org.onap.policy.rest.jpa;
-/*
- */
+
import java.io.Serializable;
import javax.persistence.Column;
@@ -32,46 +32,26 @@ import javax.persistence.NamedQuery;
import javax.persistence.OrderBy;
import javax.persistence.Table;
+import lombok.Getter;
+import lombok.Setter;
@Entity
-@Table(name="PolicyScopeService")
-@NamedQuery(name="PolicyScopeService.findAll", query="SELECT e FROM PolicyScopeService e ")
+@Table(name = "PolicyScopeService")
+@NamedQuery(name = "PolicyScopeService.findAll", query = "SELECT e FROM PolicyScopeService e ")
+@Getter
+@Setter
public class PolicyScopeService implements Serializable {
private static final long serialVersionUID = 1L;
-
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
- @Column(name="id")
+ @Column(name = "id")
private int id;
- @Column(name="name", nullable=false)
+ @Column(name = "name", nullable = false)
@OrderBy("asc")
private String name;
- @Column(name="description ")
- private String 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;
-
- }
- public String getDescriptionValue() {
- return this.description ;
- }
-
- public void setDescriptionValue(String description ) {
- this.description = description ;
- }
+ @Column(name = "description ")
+ private String 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
index 04f20c330..e53a1acbf 100644
--- 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
@@ -3,13 +3,14 @@
* ONAP-REST
* ================================================================================
* Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2019 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -19,8 +20,7 @@
*/
package org.onap.policy.rest.jpa;
-/*
- */
+
import java.io.Serializable;
import javax.persistence.Column;
@@ -32,45 +32,26 @@ import javax.persistence.NamedQuery;
import javax.persistence.OrderBy;
import javax.persistence.Table;
+import lombok.Getter;
+import lombok.Setter;
@Entity
-@Table(name="PolicyScopeType")
-@NamedQuery(name="PolicyScopeType.findAll", query="SELECT e FROM PolicyScopeType e ")
+@Table(name = "PolicyScopeType")
+@NamedQuery(name = "PolicyScopeType.findAll", query = "SELECT e FROM PolicyScopeType e ")
+@Getter
+@Setter
public class PolicyScopeType implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
- @Column(name="id")
+ @Column(name = "id")
private int id;
- @Column(name="name", nullable=false)
+ @Column(name = "name", nullable = false)
@OrderBy("asc")
private String name;
- @Column(name="description ")
- private String 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;
-
- }
- public String getDescriptionValue() {
- return this.description ;
- }
-
- public void setDescriptionValue(String description ) {
- this.description = description ;
- }
+ @Column(name = "description ")
+ private String 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
index 3bb0919b7..74b53babb 100644
--- 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
@@ -3,13 +3,14 @@
* ONAP-REST
* ================================================================================
* Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2019 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -19,6 +20,7 @@
*/
package org.onap.policy.rest.jpa;
+
import java.io.Serializable;
import javax.persistence.Column;
@@ -31,60 +33,45 @@ import javax.persistence.NamedQuery;
import javax.persistence.OrderBy;
import javax.persistence.Table;
+import lombok.Getter;
+import lombok.Setter;
+// @formatter:off
@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")
-})
+@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"
+ )
+ }
+)
+@Getter
+@Setter
+// @formatter:on
public class PolicyScore implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
- @Column(name="id")
+ @Column(name = "id")
private int id;
- @Column(name="POLICY_NAME", nullable=false)
+ @Column(name = "POLICY_NAME", nullable = false)
@OrderBy("asc")
- private String PolicyName;
+ private String policyName;
- @Column(name="VERSIONEXTENSION", nullable=false)
+ @Column(name = "VERSIONEXTENSION", nullable = false)
@OrderBy("asc")
- private String VersionExtension;
-
- @Column(name="POLICY_SCORE", nullable=true)
- private String PolicyScore;
-
- 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;
- }
-
+ private String versionExtension;
+ @Column(name = "POLICY_SCORE", nullable = true)
+ private String score;
}
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
index f6512af88..0332dcbfd 100644
--- 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
@@ -3,6 +3,7 @@
* ONAP-REST
* ================================================================================
* Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2019 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -22,7 +23,7 @@ package org.onap.policy.rest.jpa;
import java.io.Serializable;
import java.util.Date;
-import java.util.Objects;
+
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
@@ -36,169 +37,112 @@ import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
+import lombok.EqualsAndHashCode;
+import lombok.Getter;
+import lombok.Setter;
+/**
+ * The Class PolicyVersion.
+ */
+// @formatter:off
@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")
-})
+@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"
+ )
+ }
+)
+@Getter
+@Setter
+@EqualsAndHashCode
+// @formatter:on
public class PolicyVersion implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
- @Column(name="id")
+ @Column(name = "id")
private int id;
- @Column(name="POLICY_NAME", nullable=false, length=255)
+ @Column(name = "POLICY_NAME", nullable = false, length = 255)
private String policyName;
- @Column(name="ACTIVE_VERSION")
+ @Column(name = "ACTIVE_VERSION")
private int activeVersion;
- @Column(name="HIGHEST_VERSION")
+ @Column(name = "HIGHEST_VERSION")
private int higherVersion;
@Temporal(TemporalType.TIMESTAMP)
- @Column(name="created_date", nullable=false)
+ @Column(name = "created_date", nullable = false)
private Date createdDate;
- @Column(name="CREATED_BY", nullable=false, length=45)
+ @Column(name = "CREATED_BY", nullable = false, length = 45)
private String createdBy;
@Temporal(TemporalType.TIMESTAMP)
- @Column(name="modified_date", nullable=false)
+ @Column(name = "modified_date", nullable = false)
private Date modifiedDate;
-
- @Column(name="modified_by", nullable=false, length=45)
+ @Column(name = "modified_by", nullable = false, length = 45)
private String modifiedBy;
+ /**
+ * Instantiates a new policy version.
+ */
public PolicyVersion() {
this.modifiedDate = new Date();
this.createdDate = new Date();
}
+ /**
+ * Instantiates a new policy version.
+ *
+ * @param domain the domain
+ * @param loginUserId the login user id
+ */
public PolicyVersion(String domain, String loginUserId) {
this(domain);
this.createdBy = loginUserId;
this.modifiedBy = loginUserId;
}
+ /**
+ * Instantiates a new policy version.
+ *
+ * @param domain the domain
+ */
public PolicyVersion(String domain) {
this.policyName = domain;
}
- 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;
- }
-
-
+ /**
+ * Pre persist.
+ */
@PrePersist
- public void prePersist() {
+ public void prePersist() {
Date date = new Date();
this.createdDate = date;
this.modifiedDate = date;
}
+ /**
+ * Pre update.
+ */
@PreUpdate
public void preUpdate() {
- this.modifiedDate = new Date();
- }
-
- 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(Date 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(Date modifiedDate) {
- this.modifiedDate = modifiedDate;
- }
-
- public String getModifiedBy() {
- return modifiedBy;
- }
-
- public void setModifiedBy(String modifiedBy) {
- this.modifiedBy = modifiedBy;
- }
-
- @Override
- public int hashCode() {
- return Objects.hash(id, policyName, activeVersion, higherVersion, createdDate,
- createdBy, modifiedDate, modifiedBy);
- }
-
- @Override
- public boolean equals(Object obj) {
- if(obj == null){
- return false;
- }
- if(obj == this){
- return true;
- }
- if(!(obj instanceof PolicyVersion)){
- return false;
- }
-
- PolicyVersion p = (PolicyVersion) obj;
-
- return id == p.id &&
- policyName.equals(p.policyName) &&
- activeVersion == p.activeVersion &&
- higherVersion == p.higherVersion &&
- createdDate.equals(p.createdDate) &&
- createdBy.equals(p.createdBy) &&
- modifiedDate.equals(p.modifiedDate) &&
- modifiedBy.equals(p.modifiedBy);
+ this.modifiedDate = new Date();
}
-
}
-
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
index 93732ffcd..6e26ed93f 100644
--- 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
@@ -3,13 +3,14 @@
* ONAP-REST
* ================================================================================
* Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2019 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -19,8 +20,7 @@
*/
package org.onap.policy.rest.jpa;
-/*
- */
+
import java.io.Serializable;
import javax.persistence.Column;
@@ -32,45 +32,26 @@ import javax.persistence.NamedQuery;
import javax.persistence.OrderBy;
import javax.persistence.Table;
+import lombok.Getter;
+import lombok.Setter;
+
@Entity
-@Table(name="portlist")
-@NamedQuery(name="PortList.findAll", query="SELECT e FROM PortList e ")
+@Table(name = "portlist")
+@NamedQuery(name = "PortList.findAll", query = "SELECT e FROM PortList e ")
+@Getter
+@Setter
public class PortList implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
- @Column(name="id")
+ @Column(name = "id")
private int id;
- @Column(name="portname", nullable=false)
+ @Column(name = "portname", nullable = false)
@OrderBy("asc")
private String portName;
- @Column(name="description")
+ @Column(name = "description")
private String description;
-
- 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
index 9a0e8aec0..c723ebe39 100644
--- 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
@@ -3,13 +3,14 @@
* ONAP-REST
* ================================================================================
* Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2019 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -19,8 +20,7 @@
*/
package org.onap.policy.rest.jpa;
-/*
- */
+
import java.io.Serializable;
import javax.persistence.Column;
@@ -32,57 +32,29 @@ import javax.persistence.NamedQuery;
import javax.persistence.OrderBy;
import javax.persistence.Table;
+import lombok.Getter;
+import lombok.Setter;
+
@Entity
-@Table(name="PrefixList")
-@NamedQuery(name="PrefixList.findAll", query="SELECT e FROM PrefixList e ")
+@Table(name = "PrefixList")
+@NamedQuery(name = "PrefixList.findAll", query = "SELECT e FROM PrefixList e ")
+@Getter
+@Setter
public class PrefixList implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
- @Column(name="id")
+ @Column(name = "id")
private int id;
- @Column(name="pl_name", nullable=false)
+ @Column(name = "pl_name", nullable = false)
@OrderBy("asc")
private String prefixListName;
- @Column(name="description", nullable=false)
+ @Column(name = "description", nullable = false)
private String description;
- @Column(name="pl_value", nullable=false)
+ @Column(name = "pl_value", nullable = false)
private String prefixListValue;
-
- 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
index 5e79e6785..edb514b3f 100644
--- 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
@@ -3,13 +3,14 @@
* ONAP-REST
* ================================================================================
* Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2019 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -19,8 +20,7 @@
*/
package org.onap.policy.rest.jpa;
-/*
- */
+
import java.io.Serializable;
import javax.persistence.Column;
@@ -32,48 +32,26 @@ import javax.persistence.NamedQuery;
import javax.persistence.OrderBy;
import javax.persistence.Table;
+import lombok.Getter;
+import lombok.Setter;
+
@Entity
-@Table(name="protocollist")
-@NamedQuery(name="ProtocolList.findAll", query="SELECT e FROM ProtocolList e ")
+@Table(name = "protocollist")
+@NamedQuery(name = "ProtocolList.findAll", query = "SELECT e FROM ProtocolList e ")
+@Getter
+@Setter
public class ProtocolList implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
- @Column(name="id")
+ @Column(name = "id")
private int id;
- @Column(name="protocolname", nullable=false)
+ @Column(name = "protocolname", nullable = false)
@OrderBy("asc")
private String protocolName;
- @Column(name="description")
+ @Column(name = "description")
private String description;
-
- 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
index fd1a6b73b..4b1c810af 100644
--- 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
@@ -3,13 +3,14 @@
* ONAP-REST
* ================================================================================
* Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2019 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -20,99 +21,45 @@
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;
-import java.io.Serializable;
+import lombok.Getter;
+import lombok.NoArgsConstructor;
+import lombok.Setter;
/**
* The persistent class for the RainyDayTreatment database table.
- *
*/
@Entity
-@Table(name="RainyDayTreatments")
-@NamedQuery(name="RainyDayTreatments.findAll", query="SELECT e FROM RainyDayTreatments e")
+@Table(name = "RainyDayTreatments")
+@NamedQuery(name = "RainyDayTreatments.findAll", query = "SELECT e FROM RainyDayTreatments e")
+@Getter
+@Setter
+@NoArgsConstructor
public class RainyDayTreatments implements Serializable {
- /**
- *
- */
private static final long serialVersionUID = -2491410352490381323L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
- @Column(name="id")
+ @Column(name = "id")
private int id;
- @Column(name="bbid", nullable=false, length=255)
+ @Column(name = "bbid", nullable = false, length = 255)
@OrderBy("asc")
private String bbid;
- @Column(name="workstep", nullable=true, length=255)
+ @Column(name = "workstep", nullable = true, length = 255)
private String workstep;
- @Column(name="treatments", nullable=true, length=1028)
+ @Column(name = "treatments", nullable = true, length = 1028)
private String treatments;
-
- public RainyDayTreatments() {
- // Empty constructor
- }
-
- 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
index 0cb339adf..b7662539c 100644
--- 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
@@ -3,13 +3,14 @@
* ONAP-REST
* ================================================================================
* Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2019 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -19,8 +20,7 @@
*/
package org.onap.policy.rest.jpa;
-/*
- */
+
import java.io.Serializable;
import javax.persistence.Column;
@@ -32,47 +32,26 @@ import javax.persistence.NamedQuery;
import javax.persistence.OrderBy;
import javax.persistence.Table;
+import lombok.Getter;
+import lombok.Setter;
@Entity
-@Table(name="RemoteCatalogValues")
-@NamedQuery(name="RemoteCatalogValues.findAll", query="SELECT e FROM RemoteCatalogValues e ")
+@Table(name = "RemoteCatalogValues")
+@NamedQuery(name = "RemoteCatalogValues.findAll", query = "SELECT e FROM RemoteCatalogValues e ")
+@Getter
+@Setter
public class RemoteCatalogValues implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
- @Column(name="id")
+ @Column(name = "id")
private int id;
- @Column(name="name", nullable=false)
+ @Column(name = "name", nullable = false)
@OrderBy("asc")
private String name;
- @Column(name="value")
+ @Column(name = "value")
private String value;
-
- 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
index 8239d4ef8..3f7c89ec0 100644
--- 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
@@ -3,13 +3,14 @@
* ONAP-REST
* ================================================================================
* Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2019 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -19,8 +20,7 @@
*/
package org.onap.policy.rest.jpa;
-/*
- */
+
import java.io.Serializable;
import java.util.Date;
@@ -39,106 +39,63 @@ import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
+import lombok.Getter;
+import lombok.Setter;
+/**
+ * The Class RiskType.
+ */
@Entity
-@Table(name="RiskType")
-@NamedQuery(name="RiskType.findAll", query="SELECT e FROM RiskType e ")
+@Table(name = "RiskType")
+@NamedQuery(name = "RiskType.findAll", query = "SELECT e FROM RiskType e ")
+@Getter
+@Setter
public class RiskType implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
- @Column(name="id")
+ @Column(name = "id")
private int id;
- @Column(name="name", nullable=false, unique=true)
+ @Column(name = "name", nullable = false, unique = true)
@OrderBy("asc")
private String name;
@Temporal(TemporalType.TIMESTAMP)
- @Column(name="created_date", updatable=false)
+ @Column(name = "created_date", updatable = false)
private Date createdDate;
- @Column(name="description", nullable=true, length=2048)
+ @Column(name = "description", nullable = true, length = 2048)
private String description;
@Temporal(TemporalType.TIMESTAMP)
- @Column(name="modified_date", nullable=false)
+ @Column(name = "modified_date", nullable = false)
private Date modifiedDate;
@ManyToOne(optional = false)
- @JoinColumn(name="created_by")
+ @JoinColumn(name = "created_by")
private UserInfo userCreatedBy;
@ManyToOne(optional = false)
- @JoinColumn(name="modified_by")
+ @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;
- }
-
+ /**
+ * Pre persist.
+ */
@PrePersist
- public void prePersist() {
+ public void prePersist() {
Date date = new Date();
this.createdDate = date;
this.modifiedDate = date;
}
+ /**
+ * Pre update.
+ */
@PreUpdate
public void preUpdate() {
this.modifiedDate = new Date();
}
- 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
index 905648d5c..aa2ae75bc 100644
--- 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
@@ -3,13 +3,14 @@
* ONAP-REST
* ================================================================================
* Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2019 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -17,8 +18,11 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.policy.rest.jpa;
+import com.att.research.xacml.api.Identifier;
+
import java.io.Serializable;
import javax.persistence.Column;
@@ -30,11 +34,17 @@ import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.persistence.Transient;
-import com.att.research.xacml.api.Identifier;
+import lombok.Getter;
+import lombok.Setter;
+/**
+ * The Class RuleAlgorithms.
+ */
@Entity
-@Table(name="RuleAlgorithms")
-@NamedQuery(name="RuleAlgorithms.findAll", query="SELECT d FROM RuleAlgorithms d")
+@Table(name = "RuleAlgorithms")
+@NamedQuery(name = "RuleAlgorithms.findAll", query = "SELECT d FROM RuleAlgorithms d")
+@Getter
+@Setter
public class RuleAlgorithms implements Serializable {
private static final long serialVersionUID = 1L;
@@ -43,48 +53,47 @@ public class RuleAlgorithms implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
- @Column(name="id")
+ @Column(name = "id")
private int id;
- @Column(name="is_standard", nullable=false)
+ @Column(name = "is_standard", nullable = false)
private char isStandard;
- @Column(name="xacml_id", nullable=false, unique=true, length=255)
+ @Column(name = "xacml_id", nullable = false, unique = true, length = 255)
private String xacmlId;
- @Column(name="short_name", nullable=false, length=64)
+ @Column(name = "short_name", nullable = false, length = 64)
private String shortName;
+ /**
+ * Instantiates a new rule algorithms.
+ *
+ * @param id the id
+ * @param standard the standard
+ */
public RuleAlgorithms(Identifier id, char standard) {
if (id != null) {
this.xacmlId = id.stringValue();
}
this.isStandard = standard;
}
+
+ /**
+ * Instantiates a new rule algorithms.
+ *
+ * @param id the id
+ */
public RuleAlgorithms(Identifier id) {
this(id, RuleAlgorithms.STANDARD);
}
+ /**
+ * Instantiates a new rule algorithms.
+ */
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;
@@ -94,21 +103,4 @@ public class RuleAlgorithms implements Serializable {
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
index adc61506b..9663fd954 100644
--- 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
@@ -3,13 +3,14 @@
* ONAP-REST
* ================================================================================
* Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2019 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -19,8 +20,7 @@
*/
package org.onap.policy.rest.jpa;
-/*
- */
+
import java.io.Serializable;
import javax.persistence.Column;
@@ -32,55 +32,29 @@ import javax.persistence.NamedQuery;
import javax.persistence.OrderBy;
import javax.persistence.Table;
+import lombok.Getter;
+import lombok.Setter;
@Entity
-@Table(name="SafePolicyWarning")
-@NamedQuery(name="SafePolicyWarning.findAll", query="SELECT e FROM SafePolicyWarning e ")
+@Table(name = "SafePolicyWarning")
+@NamedQuery(name = "SafePolicyWarning.findAll", query = "SELECT e FROM SafePolicyWarning e ")
+@Getter
+@Setter
public class SafePolicyWarning implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
- @Column(name="id")
+ @Column(name = "id")
private int id;
- @Column(name="name", nullable=false)
+ @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 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;
-
- }
+ @Column(name = "message")
+ private String message;
+ @Column(name = "riskType")
+ private String riskType;
}
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
index c1d6c0174..fe1c6ac4c 100644
--- 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
@@ -3,13 +3,14 @@
* ONAP-REST
* ================================================================================
* Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2019 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -19,8 +20,7 @@
*/
package org.onap.policy.rest.jpa;
-/*
- */
+
import java.io.Serializable;
import javax.persistence.Column;
@@ -32,45 +32,26 @@ import javax.persistence.NamedQuery;
import javax.persistence.OrderBy;
import javax.persistence.Table;
+import lombok.Getter;
+import lombok.Setter;
+
@Entity
-@Table(name="securityzone")
-@NamedQuery(name="SecurityZone.findAll", query="SELECT e FROM SecurityZone e ")
+@Table(name = "securityzone")
+@NamedQuery(name = "SecurityZone.findAll", query = "SELECT e FROM SecurityZone e ")
+@Getter
+@Setter
public class SecurityZone implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
- @Column(name="id")
+ @Column(name = "id")
private int id;
- @Column(name="name", nullable=false)
+ @Column(name = "name", nullable = false)
@OrderBy("asc")
private String zoneName;
- @Column(name="value")
+ @Column(name = "value")
private String zoneValue;
-
- 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
index 33243b0a5..9be6b2ebf 100644
--- 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
@@ -3,13 +3,14 @@
* ONAP-REST
* ================================================================================
* Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2019 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -19,8 +20,7 @@
*/
package org.onap.policy.rest.jpa;
-/*
- */
+
import java.io.Serializable;
import javax.persistence.Column;
@@ -32,92 +32,38 @@ import javax.persistence.NamedQuery;
import javax.persistence.OrderBy;
import javax.persistence.Table;
+import lombok.Getter;
+import lombok.Setter;
+
@Entity
-@Table(name="servicegroup")
-@NamedQuery(name="ServiceList.findAll", query="SELECT e FROM ServiceList e ")
+@Table(name = "servicegroup")
+@NamedQuery(name = "ServiceList.findAll", query = "SELECT e FROM ServiceList e ")
+@Getter
+@Setter
public class ServiceList implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
- @Column(name="id")
+ @Column(name = "id")
private int id;
- @Column(name="name", nullable=false)
+ @Column(name = "name", nullable = false)
@OrderBy("asc")
private String serviceName;
- @Column(name="description")
- private String serviceDesc;
+ @Column(name = "description")
+ private String serviceDescription;
- @Column(name="type")
+ @Column(name = "type")
private String serviceType;
- @Column(name="transportprotocol")
- private String serviceTrasProtocol;
+ @Column(name = "transportprotocol")
+ private String serviceTransportProtocol;
- @Column(name="appprotocol ")
+ @Column(name = "appprotocol ")
private String serviceAppProtocol;
- @Column(name="ports")
+ @Column(name = "ports")
private String servicePorts;
-
- 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
index 9dbfc52ee..9b8845fea 100644
--- 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
@@ -3,13 +3,14 @@
* ONAP-REST
* ================================================================================
* Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2019 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -17,6 +18,7 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.policy.rest.jpa;
import java.io.Serializable;
@@ -32,47 +34,62 @@ import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
+import lombok.Getter;
+import lombok.Setter;
+
/**
- * The persistent class for the system log database table.
- *
-*/
+ * 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 {
+@Table(name = "SystemLogDb")
+@NamedQuery(name = "SystemLogDb.findAll", query = "SELECT o FROM SystemLogDb o")
+@Getter
+@Setter
+public class SystemLogDb implements Serializable {
private static final long serialVersionUID = 1L;
-
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
- @Column(name="id")
+ @Column(name = "id")
private int id;
- @Column(name="type", nullable=false)
+ @Column(name = "type", nullable = false)
private String type;
- @Column(name="system", nullable=false, length=255)
+ @Column(name = "system", nullable = false, length = 255)
private String system;
- @Column(name="description", nullable=true, length=2048)
+ @Column(name = "description", nullable = true, length = 2048)
private String description;
- @Column(name="remote", nullable=false, length=255)
+ @Column(name = "remote", nullable = false, length = 255)
private String remote;
- @Column(name="logtype", nullable=false, length=255)
+ @Column(name = "logtype", nullable = false, length = 255)
private String logtype;
@Temporal(TemporalType.TIMESTAMP)
- @Column(name="date", nullable=false, updatable=false)
+ @Column(name = "date", nullable = false, updatable = false)
private Date date;
- public SystemLogDB() {
+ /**
+ * Instantiates a new system log db.
+ */
+ public SystemLogDb() {
super();
}
- public SystemLogDB(int id, String system, String description, String remote,
- String type, String logtype) {
+ /**
+ * Instantiates a new system log db.
+ *
+ * @param id the id
+ * @param system the system
+ * @param description the description
+ * @param remote the remote
+ * @param type the type
+ * @param logtype the logtype
+ */
+ public SystemLogDb(int id, String system, String description, String remote, String type, String logtype) {
this.id = id;
this.system = system;
this.description = description;
@@ -80,62 +97,4 @@ public class SystemLogDB implements Serializable {
this.type = type;
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
index a87cf2a6b..63dce9390 100644
--- 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
@@ -3,6 +3,7 @@
* ONAP-REST
* ================================================================================
* Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2019 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -22,6 +23,7 @@ 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;
@@ -37,209 +39,97 @@ import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
+import lombok.Getter;
+import lombok.Setter;
+/**
+ * The Class TermList.
+ */
@Entity
-@Table(name="TERM")
-@NamedQuery(name="TermList.findAll", query="SELECT e FROM TermList e")
+@Table(name = "TERM")
+@NamedQuery(name = "TermList.findAll", query = "SELECT e FROM TermList e")
+@Getter
+@Setter
public class TermList implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
- @Column(name="id")
+ @Column(name = "id")
private int id;
- @Column(name="termName", nullable=false)
+ @Column(name = "termName", nullable = false)
@OrderBy("asc")
private String termName;
- @Column(name="description")
- private String termDescription;
+ @Column(name = "description")
+ private String description;
- @Column(name="fromzone")
+ @Column(name = "fromzone")
private String fromZone;
- @Column(name="tozone")
+ @Column(name = "tozone")
private String toZone;
- @Column(name="srcIPList")
- private String srcIPList;
+ @Column(name = "srcIPList")
+ private String srcIpList;
- @Column(name="destIPList")
- private String destIPList;
+ @Column(name = "destIPList")
+ private String destIpList;
- @Column(name="protocolList")
+ @Column(name = "protocolList")
private String protocolList;
- @Column(name="portList")
+ @Column(name = "portList")
private String portList;
- @Column(name="srcPortList")
+ @Column(name = "srcPortList")
private String srcPortList;
- @Column(name="destPortList")
+ @Column(name = "destPortList")
private String destPortList;
- @Column(name="action")
+ @Column(name = "action")
private String action;
@Temporal(TemporalType.TIMESTAMP)
- @Column(name="created_date", updatable=false)
+ @Column(name = "created_date", updatable = false)
private Date createdDate;
@Temporal(TemporalType.TIMESTAMP)
- @Column(name="modified_date", nullable=false)
+ @Column(name = "modified_date", nullable = false)
private Date modifiedDate;
@ManyToOne(optional = false)
- @JoinColumn(name="created_by")
+ @JoinColumn(name = "created_by")
private UserInfo userCreatedBy;
@ManyToOne(optional = false)
- @JoinColumn(name="modified_by")
+ @JoinColumn(name = "modified_by")
private UserInfo userModifiedBy;
+ /**
+ * Instantiates a new term list.
+ */
public TermList() {
this.modifiedDate = new Date();
}
- 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;
- }
-
+ /**
+ * Pre persist.
+ */
@PrePersist
- public void prePersist() {
+ public void prePersist() {
Date date = new Date();
this.createdDate = date;
this.modifiedDate = date;
}
+ /**
+ * Pre update.
+ */
@PreUpdate
public void preUpdate() {
this.modifiedDate = new Date();
}
-
- 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
index da1438010..38d14f848 100644
--- 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
@@ -3,13 +3,14 @@
* ONAP-REST
* ================================================================================
* Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2019 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -20,6 +21,10 @@
package org.onap.policy.rest.jpa;
+import com.att.research.xacml.api.Identifier;
+import com.att.research.xacml.std.IdentifierImpl;
+import com.fasterxml.jackson.annotation.JsonBackReference;
+
import java.io.Serializable;
import javax.persistence.Column;
@@ -29,44 +34,29 @@ 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;
+import lombok.Getter;
+import lombok.Setter;
@Entity
@Table(name = "UserInfo")
-@NamedQuery(name="UserInfo.findAll", query="SELECT u FROM UserInfo u ")
+@NamedQuery(name = "UserInfo.findAll", query = "SELECT u FROM UserInfo u ")
+@Getter
+@Setter
public class UserInfo implements Serializable {
private static final long serialVersionUID = 1L;
@Id
- @Column(name="loginid", nullable=false, length=45)
+ @Column(name = "loginid", nullable = false, length = 45)
private String userLoginId;
@Column(name = "name", nullable = false, unique = true)
private String userName;
- public UserInfo(){
+ 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() {
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
index aee187e6f..070cf7a56 100644
--- 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
@@ -3,6 +3,7 @@
* ONAP-REST
* ================================================================================
* Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2019 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -22,6 +23,7 @@ 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;
@@ -37,10 +39,18 @@ import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
+import lombok.Getter;
+import lombok.Setter;
+
+/**
+ * The Class VarbindDictionary.
+ */
@Entity
-@Table(name="VarbindDictionary")
+@Table(name = "VarbindDictionary")
@NamedQuery(name = "VarbindDictionary.findAll", query = "Select v FROM VarbindDictionary v")
-public class VarbindDictionary implements Serializable{
+@Getter
+@Setter
+public class VarbindDictionary implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@@ -48,7 +58,7 @@ public class VarbindDictionary implements Serializable{
@Column(name = "Id")
private int id;
- @Column(name ="varbind_Name", nullable = false, unique = true)
+ @Column(name = "varbind_Name", nullable = false, unique = true)
@OrderBy("asc")
private String varbindName;
@@ -56,104 +66,46 @@ public class VarbindDictionary implements Serializable{
private String varbindDescription;
@Column(name = "varbind_oid", nullable = false)
- private String varbindOID;
+ private String varbindOid;
@Temporal(TemporalType.TIMESTAMP)
- @Column(name="created_date", updatable=false)
+ @Column(name = "created_date", updatable = false)
private Date createdDate;
@Temporal(TemporalType.TIMESTAMP)
- @Column(name="modified_date", nullable=false)
+ @Column(name = "modified_date", nullable = false)
private Date modifiedDate;
@ManyToOne(optional = false)
- @JoinColumn(name="created_by")
+ @JoinColumn(name = "created_by")
private UserInfo userCreatedBy;
@ManyToOne(optional = false)
- @JoinColumn(name="modified_by")
+ @JoinColumn(name = "modified_by")
private UserInfo userModifiedBy;
+ /**
+ * Instantiates a new varbind dictionary.
+ */
public VarbindDictionary() {
this.setModifiedDate(new Date());
}
-
- 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;
- }
-
+ /**
+ * Pre persist.
+ */
@PrePersist
- public void prePersist() {
+ public void prePersist() {
Date date = new Date();
this.createdDate = date;
this.modifiedDate = date;
}
+ /**
+ * Pre update.
+ */
@PreUpdate
public void preUpdate() {
this.modifiedDate = new Date();
}
-
- 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/DCAEUsers.java b/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/VmType.java
index 31dd66056..51c3f657d 100644
--- a/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/DCAEUsers.java
+++ b/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/VmType.java
@@ -3,13 +3,14 @@
* ONAP-REST
* ================================================================================
* Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2019 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -19,8 +20,7 @@
*/
package org.onap.policy.rest.jpa;
-/*
- */
+
import java.io.Serializable;
import javax.persistence.Column;
@@ -32,46 +32,26 @@ import javax.persistence.NamedQuery;
import javax.persistence.OrderBy;
import javax.persistence.Table;
+import lombok.Getter;
+import lombok.Setter;
@Entity
-@Table(name="DCAEUsers")
-@NamedQuery(name="DCAEUsers.findAll", query="SELECT e FROM DCAEUsers e ")
-public class DCAEUsers implements Serializable {
+@Table(name = "VmType")
+@NamedQuery(name = "VmType.findAll", query = "SELECT e FROM VmType e ")
+@Getter
+@Setter
+public class VmType implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
- @Column(name="id")
+ @Column(name = "id")
private int id;
- @Column(name="name", nullable=false)
+ @Column(name = "name", nullable = false)
@OrderBy("asc")
private String name;
- @Column(name="description ")
- private String 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;
-
- }
- public String getDescriptionValue() {
- return this.description ;
- }
-
- public void setDescriptionValue(String description ) {
- this.description = description ;
- }
-
+ @Column(name = "description")
+ private String description;
}
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/VnfType.java
index f9413b860..1a5c679af 100644
--- a/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/PEPOptions.java
+++ b/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/VnfType.java
@@ -3,6 +3,7 @@
* ONAP-REST
* ================================================================================
* Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2019 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -19,11 +20,10 @@
*/
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;
@@ -39,121 +39,70 @@ import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
+import lombok.Getter;
+import lombok.Setter;
+/**
+ * The Class VnfType.
+ */
@Entity
-@Table(name = "PEPOptions")
-@NamedQuery(name = "PEPOptions.findAll", query= "Select p from PEPOptions p")
-public class PEPOptions implements Serializable {
+@Table(name = "VnfType")
+@NamedQuery(name = "VnfType.findAll", query = "SELECT v FROM VnfType v ")
+@Getter
+@Setter
+public class VnfType implements Serializable {
private static final long serialVersionUID = 1L;
+
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
- @Column(name = "Id")
+ @Column(name = "id")
private int id;
- @Column(name="PEP_NAME", nullable=false)
+ @Column(name = "vnf_type", nullable = false, unique = true)
@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;
+ private String type;
@Temporal(TemporalType.TIMESTAMP)
- @Column(name="created_date", updatable=false)
+ @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)
+ @Column(name = "modified_date", nullable = false)
private Date modifiedDate;
@ManyToOne(optional = false)
- @JoinColumn(name="created_by")
+ @JoinColumn(name = "created_by")
private UserInfo userCreatedBy;
@ManyToOne(optional = false)
- @JoinColumn(name="modified_by")
+ @JoinColumn(name = "modified_by")
private UserInfo userModifiedBy;
- public PEPOptions() {
+ /**
+ * Instantiates a new VNF type.
+ */
+ public VnfType() {
this.modifiedDate = new Date();
}
- 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;
- }
-
+ /**
+ * Pre persist.
+ */
@PrePersist
- public void prePersist() {
+ public void prePersist() {
Date date = new Date();
this.createdDate = date;
this.modifiedDate = date;
}
+ /**
+ * Pre update.
+ */
@PreUpdate
public void preUpdate() {
this.modifiedDate = new Date();
}
-
- 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/VSCLAction.java b/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/VsclAction.java
index e5aac971d..5506bc5b3 100644
--- 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
@@ -3,6 +3,7 @@
* ONAP-REST
* ================================================================================
* Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2019 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -22,6 +23,7 @@ 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;
@@ -37,111 +39,71 @@ import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
+import lombok.Getter;
+import lombok.Setter;
+/**
+ * The Class VsclAction.
+ */
@Entity
-@Table(name="VSCLAction")
-@NamedQuery(name="VSCLAction.findAll", query="SELECT v FROM VSCLAction v ")
-public class VSCLAction implements Serializable {
+@Table(name = "VsclAction")
+@NamedQuery(name = "VsclAction.findAll", query = "SELECT v FROM VsclAction v ")
+@Getter
+@Setter
+public class VsclAction implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
- @Column(name="id")
+ @Column(name = "id")
private int id;
- @Column(name="vscl_action", nullable=false, unique=true)
+ @Column(name = "vscl_action", nullable = false, unique = true)
@OrderBy("asc")
- private String vsclaction;
+ private String action;
@Temporal(TemporalType.TIMESTAMP)
- @Column(name="created_date", updatable=false)
+ @Column(name = "created_date", updatable = false)
private Date createdDate;
- @Column(name="description", nullable=true, length=2048)
+ @Column(name = "description", nullable = true, length = 2048)
private String description;
@Temporal(TemporalType.TIMESTAMP)
- @Column(name="modified_date", nullable=false)
+ @Column(name = "modified_date", nullable = false)
private Date modifiedDate;
@ManyToOne(optional = false)
- @JoinColumn(name="created_by")
+ @JoinColumn(name = "created_by")
private UserInfo userCreatedBy;
@ManyToOne(optional = false)
- @JoinColumn(name="modified_by")
+ @JoinColumn(name = "modified_by")
private UserInfo userModifiedBy;
- public VSCLAction() {
+ /**
+ * Instantiates a new vscl action.
+ */
+ public VsclAction() {
this.setModifiedDate(new Date());
}
- 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;
- }
-
+ /**
+ * Pre persist.
+ */
@PrePersist
- public void prePersist() {
+ public void prePersist() {
Date date = new Date();
this.createdDate = date;
this.modifiedDate = date;
}
+ /**
+ * Pre update.
+ */
@PreUpdate
public void preUpdate() {
this.modifiedDate = new Date();
}
- 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/WatchPolicyNotificationTable.java b/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/WatchPolicyNotificationTable.java
index 9f2cbfdf1..5c288a8a6 100644
--- 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
@@ -3,13 +3,14 @@
* ONAP-REST
* ================================================================================
* Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2019 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -19,13 +20,8 @@
*/
package org.onap.policy.rest.jpa;
-/*
- *
- *
- * */
import java.io.Serializable;
-import java.util.Objects;
import javax.persistence.Column;
import javax.persistence.Entity;
@@ -36,70 +32,29 @@ import javax.persistence.NamedQuery;
import javax.persistence.OrderBy;
import javax.persistence.Table;
+import lombok.EqualsAndHashCode;
+import lombok.Getter;
+import lombok.Setter;
+
@Entity
@Table(name = "WatchPolicyNotificationTable")
-@NamedQuery(name="WatchPolicyNotificationTable.findAll", query="SELECT e FROM WatchPolicyNotificationTable e ")
-public class WatchPolicyNotificationTable implements Serializable{
+@NamedQuery(name = "WatchPolicyNotificationTable.findAll", query = "SELECT e FROM WatchPolicyNotificationTable e ")
+@Getter
+@Setter
+@EqualsAndHashCode
+public class WatchPolicyNotificationTable implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
- @Column(name="id")
+ @Column(name = "id")
private int id;
- @Column(name="policyName", nullable=false, unique=true)
+ @Column(name = "policyName", nullable = false, unique = true)
@OrderBy("asc")
private String policyName;
- @Column(name="loginIds", nullable=false, unique=true)
+ @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;
- }
-
- @Override
- public int hashCode() {
- return Objects.hash(id, policyName, loginIds);
- }
-
- @Override
- public boolean equals(Object obj) {
- if(obj == null){
- return false;
- }
- if(obj == this){
- return true;
- }
- if(!(obj instanceof WatchPolicyNotificationTable)){
- return false;
- }
-
- return id == ((WatchPolicyNotificationTable)obj).id &&
- policyName.equals(((WatchPolicyNotificationTable)obj).policyName) &&
- loginIds.equals(((WatchPolicyNotificationTable)obj).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
index 58c1a275a..71252ed05 100644
--- 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
@@ -3,13 +3,14 @@
* ONAP-REST
* ================================================================================
* Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2019 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -19,8 +20,7 @@
*/
package org.onap.policy.rest.jpa;
-/*
- */
+
import java.io.Serializable;
import javax.persistence.Column;
@@ -32,45 +32,26 @@ import javax.persistence.NamedQuery;
import javax.persistence.OrderBy;
import javax.persistence.Table;
+import lombok.Getter;
+import lombok.Setter;
+
@Entity
-@Table(name="zone")
-@NamedQuery(name="Zone.findAll", query="SELECT e FROM Zone e ")
+@Table(name = "zone")
+@NamedQuery(name = "Zone.findAll", query = "SELECT e FROM Zone e ")
+@Getter
+@Setter
public class Zone implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
- @Column(name="id")
+ @Column(name = "id")
private int id;
- @Column(name="zonename", nullable=false)
+ @Column(name = "zonename", nullable = false)
@OrderBy("asc")
private String zoneName;
- @Column(name="zonevalue")
+ @Column(name = "zonevalue")
private String zoneValue;
-
- 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/util/LockdownListener.java b/ONAP-REST/src/main/java/org/onap/policy/rest/util/LockdownListener.java
index 1111609d8..019e15db7 100644
--- 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
@@ -3,13 +3,14 @@
* ONAP-REST
* ================================================================================
* Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2019 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -18,19 +19,16 @@
* ============LICENSE_END=========================================================
*/
-/**
- *
- */
package org.onap.policy.rest.util;
public interface LockdownListener {
/**
- * lockdown has been set in database
+ * lockdown has been set in database.
*/
public void lockdownSet();
/**
- * lockdown has been unset in the database
+ * 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
index 3d27499da..a022f58fa 100644
--- 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
@@ -3,6 +3,7 @@
* ONAP-REST
* ================================================================================
* Copyright (C) 2017,2019 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2019 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -23,7 +24,12 @@ package org.onap.policy.rest.util;
import java.util.HashMap;
import java.util.Map;
-public class MSAttributeObject {
+import lombok.Getter;
+import lombok.Setter;
+
+@Getter
+@Setter
+public class MsAttributeObject {
private String className;
private Map<String, String> attribute = new HashMap<>();
@@ -36,38 +42,6 @@ public class MSAttributeObject {
private String ruleFormation;
private String dataOrderInfo;
- public Map<String, String> getRefAttribute() {
- return refAttribute;
- }
-
- public void setRefAttribute(Map<String, String> refAttribute) {
- this.refAttribute = refAttribute;
- }
-
- public String getClassName() {
- return className;
- }
-
- public void setClassName(String className) {
- this.className = className;
- }
-
- public Map<String, String> getAttribute() {
- return attribute;
- }
-
- public void setAttribute(Map<String, String> attribute) {
- this.attribute = attribute;
- }
-
- public Map<String, String> getEnumType() {
- return enumType;
- }
-
- public void setEnumType(Map<String, String> enumType) {
- this.enumType = enumType;
- }
-
public void addAttribute(String key, String value) {
this.attribute.put(key, value);
}
@@ -84,38 +58,14 @@ public class MSAttributeObject {
this.refAttribute.putAll(map);
}
- public Map<String, Object> getSubClass() {
- return subClass;
- }
-
- public void setSubClass(Map<String, Object> subClass) {
- this.subClass = subClass;
- }
-
public void addAllSubClass(Map<String, Object> 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 Map<String, String> getMatchingSet() {
- return matchingSet;
- }
-
- public void setMatchingSet(Map<String, String> matchingSet) {
- this.matchingSet = matchingSet;
- }
-
public void addMatchingSet(String key, String value) {
this.matchingSet.put(key, value);
}
@@ -123,28 +73,4 @@ public class MSAttributeObject {
public void addMatchingSet(Map<String, String> matchingSet) {
this.matchingSet.putAll(matchingSet);
}
-
- public boolean isPolicyTempalate() {
- return policyTempalate;
- }
-
- public void setPolicyTempalate(boolean policyTempalate) {
- this.policyTempalate = policyTempalate;
- }
-
- public String getRuleFormation() {
- return ruleFormation;
- }
-
- public void setRuleFormation(String ruleFormation) {
- this.ruleFormation = ruleFormation;
- }
-
- public String getDataOrderInfo() {
- return dataOrderInfo;
- }
-
- public void setDataOrderInfo(String dataOrderInfo) {
- this.dataOrderInfo = dataOrderInfo;
- }
}
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
index c8a217d9f..0d550e45a 100644
--- 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
@@ -3,13 +3,14 @@
* ONAP-REST
* ================================================================================
* Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2019 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -20,41 +21,15 @@
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;
- }
+import lombok.Getter;
+import lombok.Setter;
+
+@Getter
+@Setter
+public class MsAttributeValue {
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
index 56e110019..fad26daa4 100644
--- 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
@@ -4,6 +4,7 @@
* ================================================================================
* Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
* Modified Copyright (C) 2018 Samsung Electronics Co., Ltd.
+ * Modifications Copyright (C) 2019 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -23,6 +24,7 @@ package org.onap.policy.rest.util;
import com.att.research.xacml.util.XACMLProperties;
import com.google.gson.Gson;
+
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
@@ -39,7 +41,11 @@ import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
-import org.apache.commons.lang.StringUtils;
+
+import lombok.Getter;
+import lombok.Setter;
+
+import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.eclipse.emf.common.util.EList;
@@ -63,24 +69,59 @@ 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 org.onap.policy.rest.XacmlRestProperties;
import org.onap.policy.rest.dao.CommonClassDao;
import org.onap.policy.rest.jpa.DictionaryData;
import org.yaml.snakeyaml.Yaml;
+@Getter
+@Setter
+public class MsModelUtils {
-public class MSModelUtils {
+ private static final Log logger = LogFactory.getLog(MsModelUtils.class);
- private static final Log logger = LogFactory.getLog(MSModelUtils.class);
+ // String constants
+ private static final String BOOLEAN = "boolean";
+ private static final String CONFIGURATION = "configuration";
+ private static final String DATATYPE = "data_types.policy.data.";
+ private static final String DATA_TYPE = "data_types";
+ private static final String DEFAULT = ".default";
+ private static final String DEFAULTVALUE = ":defaultValue-";
+ private static final String DESCRIPTION = ".description";
+ private static final String DESCRIPTION_KEY = "description";
+ private static final String DESCRIPTION_TOKEN = ":description-";
+ private static final String DICTIONARY = "dictionary:";
+ private static final String DICTIONARYNAME = "dictionaryName";
+ private static final String ERROR = "error";
+ private static final String E_PROXY_URI = "eProxyURI:";
+ private static final String INTEGER = "integer";
+ private static final String JSON_MODEL = "JSON_MODEL";
+ private static final String LIST = "list";
+ private static final String MANYFALSE = ":MANY-false";
+ private static final String MANYTRUE = ":MANY-true";
+ private static final String MAP = "map";
+ private static final String MATCHABLE = ".matchable";
+ private static final String MATCHABLEKEY = "matchable";
+ private static final String MATCHINGTRUE = "matching-true";
+ private static final String NODE_TYPE = "node_types";
+ private static final String PROPERTIES = ".properties.";
+ private static final String PROPERTIES_KEY = "properties";
+ private static final String REQUIRED = ".required";
+ private static final String REQUIREDFALSE = ":required-false";
+ private static final String REQUIREDTRUE = ":required-true";
+ private static final String REQUIREDVALUE = ":required-";
+ private static final String STRING = "string";
+ private static final String TOSCA_DEFINITION_VERSION = "tosca_definitions_version";
+ private static final String TOSCA_SIMPLE_YAML_1_0_0 = "tosca_simple_yaml_1_0_0";
+ private static final String TYPE = ".type";
+
+ private static CommonClassDao commonClassDao;
- private HashMap<String, MSAttributeObject> classMap = new HashMap<>();
+ private HashMap<String, MsAttributeObject> classMap = new HashMap<>();
private HashMap<String, String> enumMap = new HashMap<>();
private HashMap<String, String> matchingClass = new HashMap<>();
- private String configuration = "configuration";
- private String dictionary = "dictionary";
private String onap = "";
private String policy = "";
- private String eProxyURI = "eProxyURI:";
private List<String> orderedElements = new ArrayList<>();
private String dataOrderInfo = "";
private Set<String> uniqueDataKeys = new HashSet<>();
@@ -89,80 +130,86 @@ public class MSModelUtils {
private String referenceAttributes;
private LinkedHashMap<String, Object> retmap = new LinkedHashMap<>();
private Map<String, String> matchableValues;
- private static final String PROPERTIES = ".properties.";
- private static final String DATATYPE = "data_types.policy.data.";
- private static final String TYPE = ".type";
- private static final String REQUIRED = ".required";
- private static final String DICTIONARYNAME = "dictionaryName";
- private static final String DICTIONARY = "dictionary:";
- private static final String MATCHABLE = ".matchable";
- public static final String STRING = "string";
- public static final String INTEGER = "integer";
- private static final String BOOLEAN = "boolean";
- public static final String LIST = "list";
- public static final String MAP = "map";
- private static final String DEFAULT = ".default";
- private static final String MANYFALSE = ":MANY-false";
- private static final String DESCRIPTION = ".description";
-
- private static final String MANYTRUE = ":MANY-true";
- private static final String DEFAULTVALUE = ":defaultValue-";
- private static final String REQUIREDVALUE = ":required-";
- private static final String MATCHABLEKEY = "matchable";
- private static final String REQUIREDFALSE = ":required-false";
- private static final String REQUIREDTRUE = ":required-true";
- private static final String MATCHINGTRUE = "matching-true";
- private static final String DESCRIPTION_KEY = "description";
- private static final String DESCRIPTION_TOKEN = ":description-";
- private static final String PROPERTIES_KEY = "properties";
- private static final String DATA_TYPE = "data_types";
- private static final String ERROR = "error";
- private static final String NODE_TYPE = "node_types";
- private static final String TOSCA_DEFINITION_VERSION = "tosca_definitions_version";
- private static final String TOSCA_SIMPLE_YAML_1_0_0 = "tosca_simple_yaml_1_0_0";
- private static final String JSON_MODEL = "JSON_MODEL";
private StringBuilder dataListBuffer = new StringBuilder();
private List<String> dataConstraints = new ArrayList<>();
private String attributeString = null;
private boolean isDuplicatedAttributes = false;
private String jsonRuleFormation = null;
- private static CommonClassDao commonClassDao;
-
- public MSModelUtils() {
- // Default Constructor
+ /**
+ * The Enum AnnotationType.
+ */
+ private enum AnnotationType {
+ MATCHING,
+ VALIDATION,
+ DICTIONARY
}
- public MSModelUtils(CommonClassDao commonClassDao) {
- MSModelUtils.commonClassDao = commonClassDao;
+ /**
+ * The Enum ModelType.
+ */
+ public enum ModelType {
+ XMI
}
- public MSModelUtils(String onap, String policy) {
- this.onap = onap;
- this.policy = policy;
+ /**
+ * The Enum SearchType.
+ */
+ public enum SearchType {
+ TOSCA_DEFINITION_VERSION,
+ TOSCA_SIMPLE_YAML_1_0_0,
+ NODE_TYPE,
+ DATA_TYPE,
+ JSON_MODEL
}
- private enum ANNOTATION_TYPE {
- MATCHING, VALIDATION, DICTIONARY
- };
+ /**
+ * Instantiates a new ms model utils.
+ */
+ public MsModelUtils() {
+ // Default Constructor
+ }
- public enum MODEL_TYPE {
- XMI
- };
+ /**
+ * Instantiates a new ms model utils.
+ *
+ * @param commonClassDao the common class dao
+ */
+ public MsModelUtils(CommonClassDao commonClassDao) {
+ MsModelUtils.commonClassDao = commonClassDao;
+ }
- public enum SearchType {
- TOSCA_DEFINITION_VERSION, TOSCA_SIMPLE_YAML_1_0_0, NODE_TYPE, DATA_TYPE, JSON_MODEL
+ /**
+ * Instantiates a new ms model utils.
+ *
+ * @param onap the onap
+ * @param policy the policy
+ */
+ public MsModelUtils(String onap, String policy) {
+ this.onap = onap;
+ this.policy = policy;
}
- public Map<String, MSAttributeObject> processEpackage(String file, MODEL_TYPE model) {
- if (model == MODEL_TYPE.XMI) {
- processXMIEpackage(file);
+ /**
+ * Process epackage.
+ *
+ * @param file the file
+ * @param model the model
+ * @return the map
+ */
+ public Map<String, MsAttributeObject> processEpackage(String file, ModelType model) {
+ if (model == ModelType.XMI) {
+ processXmiEpackage(file);
}
return classMap;
-
}
- private void processXMIEpackage(String xmiFile) {
+ /**
+ * Process XMI epackage.
+ *
+ * @param xmiFile the xmi file
+ */
+ private void processXmiEpackage(String xmiFile) {
EPackage root = getEpackage(xmiFile);
TreeIterator<EObject> treeItr = root.eAllContents();
String className;
@@ -172,14 +219,16 @@ public class MSModelUtils {
while (treeItr.hasNext()) {
EObject obj = treeItr.next();
if (obj instanceof EClassifier) {
- EClassifier eClassifier = (EClassifier) obj;
- className = eClassifier.getName();
+ EClassifier eclassifier = (EClassifier) obj;
+ className = eclassifier.getName();
if (obj instanceof EEnum) {
enumMap.putAll(getEEnum(obj));
} else if (obj instanceof EClass) {
- String temp = getDependencyList(eClassifier).toString();
- returnValue = StringUtils.replaceEach(temp, new String[] {"[", "]"}, new String[] {"", ""});
+ String temp = getDependencyList(eclassifier).toString();
+ returnValue = StringUtils.replaceEach(temp, new String[]
+ { "[", "]" }, new String[]
+ { "", "" });
getAttributes(className, returnValue, root);
}
}
@@ -193,6 +242,9 @@ public class MSModelUtils {
}
}
+ /**
+ * Check for matching class.
+ */
private void checkForMatchingClass() {
HashMap<String, String> tempAttribute = new HashMap<>();
@@ -201,12 +253,12 @@ public class MSModelUtils {
if (classMap.containsKey(key)) {
Map<String, String> listAttributes = classMap.get(key).getAttribute();
Map<String, String> listRef = classMap.get(key).getRefAttribute();
- for (Entry<String, String> eSet : listAttributes.entrySet()) {
- String key2 = eSet.getKey();
+ for (Entry<String, String> eset : listAttributes.entrySet()) {
+ String key2 = eset.getKey();
tempAttribute.put(key2, MATCHINGTRUE);
}
- for (Entry<String, String> eSet : listRef.entrySet()) {
- String key3 = eSet.getKey();
+ for (Entry<String, String> eset : listRef.entrySet()) {
+ String key3 = eset.getKey();
tempAttribute.put(key3, MATCHINGTRUE);
}
@@ -216,12 +268,16 @@ public class MSModelUtils {
}
-
-
+ /**
+ * Update matching.
+ *
+ * @param tempAttribute the temp attribute
+ * @param key the key
+ */
private void updateMatching(HashMap<String, String> tempAttribute, String key) {
- Map<String, MSAttributeObject> newClass = classMap;
+ Map<String, MsAttributeObject> newClass = classMap;
- for (Entry<String, MSAttributeObject> updateClass : newClass.entrySet()) {
+ for (Entry<String, MsAttributeObject> updateClass : newClass.entrySet()) {
Map<String, String> valueMap = updateClass.getValue().getMatchingSet();
String keymap = updateClass.getKey();
if (valueMap.containsKey(key)) {
@@ -234,17 +290,26 @@ public class MSModelUtils {
}
}
+ /**
+ * Adds the enum class map.
+ */
private void addEnumClassMap() {
- for (Entry<String, MSAttributeObject> value : classMap.entrySet()) {
+ for (Entry<String, MsAttributeObject> value : classMap.entrySet()) {
value.getValue().setEnumType(enumMap);
}
}
+ /**
+ * Gets the epackage.
+ *
+ * @param xmiFile the xmi file
+ * @return the epackage
+ */
private EPackage getEpackage(String xmiFile) {
ResourceSet resSet = new ResourceSetImpl();
Resource.Factory.Registry reg = Resource.Factory.Registry.INSTANCE;
- Map<String, Object> m = reg.getExtensionToFactoryMap();
- m.put("xmi", new XMIResourceFactoryImpl());
+ Map<String, Object> objectMap = reg.getExtensionToFactoryMap();
+ objectMap.put("xmi", new XMIResourceFactoryImpl());
Resource resource = resSet.getResource(URI.createFileURI(xmiFile), true);
try {
resource.load(Collections.emptyMap());
@@ -255,14 +320,20 @@ public class MSModelUtils {
return (EPackage) resource.getContents().get(0);
}
+ /**
+ * Gets the e enum.
+ *
+ * @param obj the obj
+ * @return the e enum
+ */
private HashMap<String, String> getEEnum(EObject obj) {
List<String> valueList = new ArrayList<>();
HashMap<String, String> returnMap = new HashMap<>();
EEnum eenum = (EEnum) obj;
String name = eenum.getName();
- for (EEnumLiteral eEnumLiteral : eenum.getELiterals()) {
- Enumerator instance = eEnumLiteral.getInstance();
+ for (EEnumLiteral enumLiteral : eenum.getELiterals()) {
+ Enumerator instance = enumLiteral.getInstance();
String value = instance.getLiteral();
valueList.add(value);
}
@@ -270,12 +341,19 @@ public class MSModelUtils {
return returnMap;
}
+ /**
+ * Gets the attributes.
+ *
+ * @param className the class name
+ * @param dependency the dependency
+ * @param root the root
+ */
public void getAttributes(String className, String dependency, EPackage root) {
List<String> dpendList = new ArrayList<>();
if (dependency != null) {
dpendList = new ArrayList<>(Arrays.asList(dependency.split(",")));
}
- MSAttributeObject msAttributeObject = new MSAttributeObject();
+ MsAttributeObject msAttributeObject = new MsAttributeObject();
msAttributeObject.setClassName(className);
String extendClass = getSubTypes(root, className);
Map<String, String> returnRefList = getRefAttributeList(root, className, extendClass);
@@ -292,6 +370,14 @@ public class MSModelUtils {
this.classMap.put(className, msAttributeObject);
}
+ /**
+ * Gets the annotation.
+ *
+ * @param root the root
+ * @param className the class name
+ * @param extendClass the extend class
+ * @return the annotation
+ */
private HashMap<String, String> getAnnotation(EPackage root, String className, String extendClass) {
TreeIterator<EObject> treeItr = root.eAllContents();
boolean requiredAttribute = false;
@@ -317,43 +403,63 @@ public class MSModelUtils {
return annotationSet;
}
+ /**
+ * Find matching annotation.
+ *
+ * @param annotationSet the annotation set
+ * @param obj the obj
+ */
private void findMatchingAnnotation(HashMap<String, String> annotationSet, EObject obj) {
- EStructuralFeature eStrucClassifier = (EStructuralFeature) obj;
- if (eStrucClassifier.getEAnnotations().isEmpty()) {
+ EStructuralFeature estrucClassifier = (EStructuralFeature) obj;
+ if (estrucClassifier.getEAnnotations().isEmpty()) {
return;
}
- String matching = annotationValue(eStrucClassifier, ANNOTATION_TYPE.MATCHING, policy);
+ String matching = annotationValue(estrucClassifier, AnnotationType.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);
+ annotationSet.put(estrucClassifier.getName(), matching);
}
}
}
+ /**
+ * Check annotation.
+ *
+ * @param annotationSet the annotation set
+ * @param obj the obj
+ */
private void checkAnnotation(HashMap<String, String> annotationSet, EStructuralFeature obj) {
- EStructuralFeature eStrucClassifier = obj;
- if (eStrucClassifier.getEAnnotations().isEmpty()) {
+ EStructuralFeature estrucClassifier = obj;
+ if (estrucClassifier.getEAnnotations().isEmpty()) {
return;
}
- String matching = annotationValue(eStrucClassifier, ANNOTATION_TYPE.MATCHING, policy);
+ String matching = annotationValue(estrucClassifier, AnnotationType.MATCHING, policy);
if (matching != null) {
- annotationSet.put(eStrucClassifier.getName(), matching);
+ annotationSet.put(estrucClassifier.getName(), matching);
}
- String range = annotationValue(eStrucClassifier, ANNOTATION_TYPE.VALIDATION, policy);
+ String range = annotationValue(estrucClassifier, AnnotationType.VALIDATION, policy);
if (range != null) {
- annotationSet.put(eStrucClassifier.getName(), range);
+ annotationSet.put(estrucClassifier.getName(), range);
}
- String annotationDict = annotationValue(eStrucClassifier, ANNOTATION_TYPE.DICTIONARY, policy);
+ String annotationDict = annotationValue(estrucClassifier, AnnotationType.DICTIONARY, policy);
if (annotationDict != null) {
- annotationSet.put(eStrucClassifier.getName(), annotationDict);
+ annotationSet.put(estrucClassifier.getName(), annotationDict);
}
}
+ /**
+ * Gets the sub attribute list.
+ *
+ * @param root the root
+ * @param className the class name
+ * @param superClass the super class
+ * @return the sub attribute list
+ */
private Map<String, Object> getSubAttributeList(EPackage root, String className, String superClass) {
TreeIterator<EObject> treeItr = root.eAllContents();
boolean requiredAttribute = false;
@@ -374,32 +480,45 @@ public class MSModelUtils {
}
if (requiredAttribute && (obj instanceof EStructuralFeature)) {
- EStructuralFeature eStrucClassifier = (EStructuralFeature) obj;
- if (!eStrucClassifier.getEAnnotations().isEmpty()) {
- updateSubAttributes(subAttribute, obj, eStrucClassifier);
+ EStructuralFeature estrucClassifier = (EStructuralFeature) obj;
+ if (!estrucClassifier.getEAnnotations().isEmpty()) {
+ updateSubAttributes(subAttribute, obj, estrucClassifier);
}
}
}
return subAttribute;
}
+ /**
+ * Update sub attributes.
+ *
+ * @param subAttribute the sub attribute
+ * @param obj the obj
+ * @param estrucClassifier the e struc classifier
+ */
private void updateSubAttributes(Map<String, Object> subAttribute, EObject obj,
- EStructuralFeature eStrucClassifier) {
+ EStructuralFeature estrucClassifier) {
if (!(obj instanceof EReference)) {
return;
}
- if (annotationTest(eStrucClassifier, configuration, onap)) {
+ if (annotationTest(estrucClassifier, CONFIGURATION, onap)) {
EClass refType = ((EReference) obj).getEReferenceType();
- if (!refType.toString().contains(eProxyURI)) {
+ if (!refType.toString().contains(E_PROXY_URI)) {
String required = REQUIREDFALSE;
- if (eStrucClassifier.getLowerBound() == 1) {
+ if (estrucClassifier.getLowerBound() == 1) {
required = REQUIREDTRUE;
}
- subAttribute.put(eStrucClassifier.getName(), refType.getName() + required);
+ subAttribute.put(estrucClassifier.getName(), refType.getName() + required);
}
}
}
+ /**
+ * Check defult value.
+ *
+ * @param defultValue the defult value
+ * @return the string
+ */
public String checkDefultValue(String defultValue) {
if (defultValue != null) {
return DEFAULTVALUE + defultValue;
@@ -408,19 +527,40 @@ public class MSModelUtils {
}
+ /**
+ * Check required pattern.
+ *
+ * @param upper the upper
+ * @param lower the lower
+ * @return the string
+ */
public String checkRequiredPattern(int upper, int lower) {
- String pattern = XACMLProperties.getProperty(XACMLRestProperties.PROP_XCORE_REQUIRED_PATTERN);
+ String pattern = XACMLProperties.getProperty(XacmlRestProperties.PROP_XCORE_REQUIRED_PATTERN);
if (pattern != null && upper == Integer.parseInt(pattern.split(",")[1])
- && lower == Integer.parseInt(pattern.split(",")[0])) {
+ && lower == Integer.parseInt(pattern.split(",")[0])) {
return REQUIREDTRUE;
}
return REQUIREDFALSE;
}
+ /**
+ * Builds the java object.
+ *
+ * @param map the map
+ * @return the JSON object
+ */
public JSONObject buildJavaObject(Map<String, String> map) {
return new JSONObject(map);
}
+ /**
+ * Gets the ref attribute list.
+ *
+ * @param root the root
+ * @param className the class name
+ * @param superClass the super class
+ * @return the ref attribute list
+ */
public Map<String, String> getRefAttributeList(EPackage root, String className, String superClass) {
TreeIterator<EObject> treeItr = root.eAllContents();
@@ -441,13 +581,13 @@ public class MSModelUtils {
}
if (requiredAttribute && (obj instanceof EStructuralFeature)) {
- EStructuralFeature eStrucClassifier = (EStructuralFeature) obj;
- if (!eStrucClassifier.getEAnnotations().isEmpty()) {
- annotation = annotationTest(eStrucClassifier, configuration, onap);
+ EStructuralFeature estrucClassifier = (EStructuralFeature) obj;
+ if (!estrucClassifier.getEAnnotations().isEmpty()) {
+ annotation = annotationTest(estrucClassifier, CONFIGURATION, onap);
if (annotation && obj instanceof EReference) {
- updRefAttributes(refAttribute, (EStructuralFeature) obj, eStrucClassifier);
+ updRefAttributes(refAttribute, (EStructuralFeature) obj, estrucClassifier);
} else if (annotation && obj instanceof EAttributeImpl) {
- updEnumTypeRefAttrib(refAttribute, (EStructuralFeature) obj, eStrucClassifier);
+ updEnumTypeRefAttrib(refAttribute, (EStructuralFeature) obj, estrucClassifier);
}
}
}
@@ -456,8 +596,15 @@ public class MSModelUtils {
return refAttribute;
}
+ /**
+ * Upd enum type ref attrib.
+ *
+ * @param refAttribute the ref attribute
+ * @param obj the obj
+ * @param estrucClassifier the e struc classifier
+ */
private void updEnumTypeRefAttrib(HashMap<String, String> refAttribute, EStructuralFeature obj,
- EStructuralFeature eStrucClassifier) {
+ EStructuralFeature estrucClassifier) {
EClassifier refType = ((EAttributeImpl) obj).getEType();
if (!(refType instanceof EEnumImpl)) {
return;
@@ -468,40 +615,56 @@ public class MSModelUtils {
if (obj.getLowerBound() == 1) {
required = REQUIREDTRUE;
}
- refAttribute.put(eStrucClassifier.getName(), refType.getName() + array + required);
+ refAttribute.put(estrucClassifier.getName(), refType.getName() + array + required);
}
+ /**
+ * Upd ref attributes.
+ *
+ * @param refAttribute the ref attribute
+ * @param obj the obj
+ * @param estrucClassifier the e struc classifier
+ */
private void updRefAttributes(HashMap<String, String> refAttribute, EStructuralFeature obj,
- EStructuralFeature eStrucClassifier) {
+ EStructuralFeature estrucClassifier) {
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);
+ if (refType.toString().contains(E_PROXY_URI)) {
+ String one = refType.toString().split(E_PROXY_URI)[1];
+ String refValue = StringUtils.replaceEach(one.split("#")[1], new String[]
+ { "//", ")" }, new String[]
+ { "", "" });
+ refAttribute.put(estrucClassifier.getName(), refValue);
} else {
String required = REQUIREDFALSE;
if (obj.getLowerBound() == 1) {
required = REQUIREDTRUE;
}
- refAttribute.put(eStrucClassifier.getName(),
- refType.getName() + arrayCheck(obj.getUpperBound()) + required);
+ refAttribute.put(estrucClassifier.getName(),
+ refType.getName() + arrayCheck(obj.getUpperBound()) + required);
}
}
- private boolean annotationTest(EStructuralFeature eStrucClassifier, String annotation, String type) {
+ /**
+ * Annotation test.
+ *
+ * @param estrucClassifier the e struc classifier
+ * @param annotation the annotation
+ * @param type the type
+ * @return true, if successful
+ */
+ private boolean annotationTest(EStructuralFeature estrucClassifier, String annotation, String type) {
String annotationType;
- EAnnotation eAnnotation;
+ EAnnotation eannotation;
String onapType;
String onapValue;
- EList<EAnnotation> value = eStrucClassifier.getEAnnotations();
+ EList<EAnnotation> 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();
+ 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;
@@ -515,22 +678,29 @@ public class MSModelUtils {
return false;
}
-
- private String annotationValue(EStructuralFeature eStrucClassifier, ANNOTATION_TYPE annotation, String type) {
+ /**
+ * Annotation value.
+ *
+ * @param estrucClassifier the e struc classifier
+ * @param annotation the annotation
+ * @param type the type
+ * @return the string
+ */
+ private String annotationValue(EStructuralFeature estrucClassifier, AnnotationType annotation, String type) {
String annotationType;
- EAnnotation eAnnotation;
+ EAnnotation eannotation;
String onapType;
String onapValue = null;
- EList<EAnnotation> value = eStrucClassifier.getEAnnotations();
+ EList<EAnnotation> 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();
+ 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) {
+ onapValue = eannotation.getDetails().get(0).getValue();
+ if (annotation == AnnotationType.VALIDATION) {
return onapValue;
} else {
return onapType + "-" + onapValue;
@@ -541,23 +711,33 @@ public class MSModelUtils {
return onapValue;
}
+ /**
+ * Checks if is required attribute.
+ *
+ * @param obj the obj
+ * @param className the class name
+ * @return true, if is required attribute
+ */
public boolean isRequiredAttribute(EObject obj, String className) {
- EClassifier eClassifier = (EClassifier) obj;
- String workingClass = eClassifier.getName().trim();
- if (workingClass.equalsIgnoreCase(className)) {
- return true;
- }
-
- return false;
+ EClassifier eclassifier = (EClassifier) obj;
+ String workingClass = eclassifier.getName().trim();
+ return workingClass.equalsIgnoreCase(className);
}
+ /**
+ * Checks if is policy template.
+ *
+ * @param root the root
+ * @param className the class name
+ * @return true, if is policy template
+ */
private boolean isPolicyTemplate(EPackage root, String className) {
boolean result = false;
for (EClassifier classifier : root.getEClassifiers()) {
if (classifier instanceof EClass) {
- EClass eClass = (EClass) classifier;
- if (eClass.getName().contentEquals(className)) {
- result = checkPolicyTemplate(eClass);
+ EClass eclass = (EClass) classifier;
+ if (eclass.getName().contentEquals(className)) {
+ result = checkPolicyTemplate(eclass);
break;
}
}
@@ -565,8 +745,14 @@ public class MSModelUtils {
return result;
}
- private boolean checkPolicyTemplate(EClass eClass) {
- EList<EAnnotation> value = eClass.getEAnnotations();
+ /**
+ * Check policy template.
+ *
+ * @param eclass the e class
+ * @return true, if successful
+ */
+ private boolean checkPolicyTemplate(EClass eclass) {
+ EList<EAnnotation> value = eclass.getEAnnotations();
for (EAnnotation workingValue : value) {
EMap<String, String> keyMap = workingValue.getDetails();
if (keyMap.containsKey("policyTemplate")) {
@@ -576,6 +762,13 @@ public class MSModelUtils {
return false;
}
+ /**
+ * Gets the sub types.
+ *
+ * @param root the root
+ * @param className the class name
+ * @return the sub types
+ */
private String getSubTypes(EPackage root, String className) {
String returnSubTypes = null;
for (EClassifier classifier : root.getEClassifiers()) {
@@ -586,17 +779,33 @@ public class MSModelUtils {
return returnSubTypes;
}
+ /**
+ * Find sub types.
+ *
+ * @param className the class name
+ * @param returnSubTypes the return sub types
+ * @param classifier the classifier
+ * @return the string
+ */
private String findSubTypes(String className, String returnSubTypes, EClass classifier) {
- EClass eClass = classifier;
+ EClass eclass = classifier;
- for (EClass eSuperType : eClass.getEAllSuperTypes()) {
- if (eClass.getName().contentEquals(className)) {
- returnSubTypes = eSuperType.getName();
+ for (EClass esuperType : eclass.getEAllSuperTypes()) {
+ if (eclass.getName().contentEquals(className)) {
+ returnSubTypes = esuperType.getName();
}
}
return returnSubTypes;
}
+ /**
+ * Gets the attribute list.
+ *
+ * @param root the root
+ * @param className the class name
+ * @param superClass the super class
+ * @return the attribute list
+ */
public Map<String, String> getAttributeList(EPackage root, String className, String superClass) {
TreeIterator<EObject> treeItr = root.eAllContents();
@@ -611,9 +820,9 @@ public class MSModelUtils {
}
if (requiredAttribute && (obj instanceof EStructuralFeature)) {
- EStructuralFeature eStrucClassifier = (EStructuralFeature) obj;
- if (!eStrucClassifier.getEAnnotations().isEmpty()) {
- checkStrucClassifier(refAttribute, obj, eStrucClassifier);
+ EStructuralFeature estrucClassifier = (EStructuralFeature) obj;
+ if (!estrucClassifier.getEAnnotations().isEmpty()) {
+ checkStrucClassifier(refAttribute, obj, estrucClassifier);
}
}
}
@@ -621,31 +830,52 @@ public class MSModelUtils {
}
+ /**
+ * Check struc classifier.
+ *
+ * @param refAttribute the ref attribute
+ * @param obj the obj
+ * @param estrucClassifier the e struc classifier
+ */
private void checkStrucClassifier(HashMap<String, String> refAttribute, EObject obj,
- EStructuralFeature eStrucClassifier) {
+ EStructuralFeature estrucClassifier) {
EClassifier refType = ((EStructuralFeature) obj).getEType();
- boolean annotation = annotationTest(eStrucClassifier, configuration, onap);
- boolean dictionaryTest = annotationTest(eStrucClassifier, dictionary, policy);
+ boolean annotation = annotationTest(estrucClassifier, CONFIGURATION, onap);
+ boolean dictionaryTest = annotationTest(estrucClassifier, DICTIONARY, policy);
if (annotation && !(obj instanceof EReference) && !(refType instanceof EEnumImpl)) {
- updEReferenceAttrib(refAttribute, dictionaryTest, (EStructuralFeature) obj, eStrucClassifier);
+ updEReferenceAttrib(refAttribute, dictionaryTest, (EStructuralFeature) obj, estrucClassifier);
}
}
+ /**
+ * Upd E reference attrib.
+ *
+ * @param refAttribute the ref attribute
+ * @param dictionaryTest the dictionary test
+ * @param obj the obj
+ * @param estrucClassifier the e struc classifier
+ */
private void updEReferenceAttrib(HashMap<String, String> refAttribute, boolean dictionaryTest,
- EStructuralFeature obj, EStructuralFeature eStrucClassifier) {
- String eType;
- String name = eStrucClassifier.getName();
+ EStructuralFeature obj, EStructuralFeature estrucClassifier) {
+ String etype;
+ String name = estrucClassifier.getName();
if (dictionaryTest) {
- eType = annotationValue(eStrucClassifier, ANNOTATION_TYPE.DICTIONARY, policy);
+ etype = annotationValue(estrucClassifier, AnnotationType.DICTIONARY, policy);
} else {
- eType = eStrucClassifier.getEType().getInstanceClassName();
+ etype = estrucClassifier.getEType().getInstanceClassName();
}
String defaultValue = checkDefultValue(obj.getDefaultValueLiteral());
String array = arrayCheck(obj.getUpperBound());
String required = checkRequiredPattern(obj.getUpperBound(), obj.getLowerBound());
- refAttribute.put(name, eType + defaultValue + required + array);
+ refAttribute.put(name, etype + defaultValue + required + array);
}
+ /**
+ * Array check.
+ *
+ * @param upperBound the upper bound
+ * @return the string
+ */
public String arrayCheck(int upperBound) {
if (upperBound == -1) {
@@ -655,17 +885,25 @@ public class MSModelUtils {
return MANYFALSE;
}
- public List<String> getDependencyList(EClassifier eClassifier) {
- List<String> returnValue = new ArrayList<>();;
- EList<EClass> somelist = ((EClass) eClassifier).getEAllSuperTypes();
+ /**
+ * Gets the dependency list.
+ *
+ * @param eclassifier the e classifier
+ * @return the dependency list
+ */
+ public List<String> getDependencyList(EClassifier eclassifier) {
+ List<String> returnValue = new ArrayList<>();
+ ;
+ EList<EClass> 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[] {"", ""});
+ if (depend.toString().contains(E_PROXY_URI)) {
+ String one = depend.toString().split(E_PROXY_URI)[1];
+ String value = StringUtils.replaceEach(one.split("#")[1], new String[]
+ { "//", ")" }, new String[]
+ { "", "" });
returnValue.add(value);
}
}
@@ -673,8 +911,16 @@ public class MSModelUtils {
return returnValue;
}
+ /**
+ * Builds the sub list.
+ *
+ * @param subClassAttributes the sub class attributes
+ * @param classMap the class map
+ * @param className the class name
+ * @return the map
+ */
public Map<String, String> buildSubList(Map<String, String> subClassAttributes,
- Map<String, MSAttributeObject> classMap, String className) {
+ Map<String, MsAttributeObject> classMap, String className) {
Map<String, String> missingValues = new HashMap<>();
Map<String, String> workingMap;
boolean enumType;
@@ -700,15 +946,22 @@ public class MSModelUtils {
return missingValues;
}
- public Map<String, Map<String, String>> recursiveReference(Map<String, MSAttributeObject> classMap,
- String className) {
+ /**
+ * Recursive reference.
+ *
+ * @param classMap the class map
+ * @param className the class name
+ * @return the map
+ */
+ public Map<String, Map<String, String>> recursiveReference(Map<String, MsAttributeObject> classMap,
+ String className) {
Map<String, Map<String, String>> returnObject = new HashMap<>();
Map<String, String> returnClass = getRefclass(classMap, className);
returnObject.put(className, returnClass);
for (Entry<String, String> reAttribute : returnClass.entrySet()) {
if (reAttribute.getValue().split(":")[1].contains("MANY")
- && classMap.get(reAttribute.getValue().split(":")[0]) != null) {
+ && classMap.get(reAttribute.getValue().split(":")[0]) != null) {
returnObject.putAll(recursiveReference(classMap, reAttribute.getValue().split(":")[0]));
}
@@ -718,7 +971,14 @@ public class MSModelUtils {
}
- public String createJson(Map<String, MSAttributeObject> classMap, String className) {
+ /**
+ * Creates the json.
+ *
+ * @param classMap the class map
+ * @param className the class name
+ * @return the string
+ */
+ public String createJson(Map<String, MsAttributeObject> classMap, String className) {
boolean enumType;
Map<String, Map<String, String>> myObject = new HashMap<>();
for (Entry<String, String> map : classMap.get(className).getRefAttribute().entrySet()) {
@@ -726,8 +986,8 @@ public class MSModelUtils {
if (value != null) {
enumType = classMap.get(className).getEnumType().containsKey(value);
if (!enumType && map.getValue().split(":")[1].contains("MANY")) {
- Map<String, Map<String, String>> testRecursive =
- recursiveReference(classMap, map.getValue().split(":")[0]);
+ Map<String, Map<String, String>> testRecursive = recursiveReference(classMap,
+ map.getValue().split(":")[0]);
myObject.putAll(testRecursive);
}
}
@@ -737,7 +997,14 @@ public class MSModelUtils {
return gson.toJson(myObject);
}
- public Map<String, String> getRefclass(Map<String, MSAttributeObject> classMap, String className) {
+ /**
+ * Gets the refclass.
+ *
+ * @param classMap the class map
+ * @param className the class name
+ * @return the refclass
+ */
+ public Map<String, String> getRefclass(Map<String, MsAttributeObject> classMap, String className) {
HashMap<String, String> missingValues = new HashMap<>();
if (classMap.get(className).getAttribute() != null || !classMap.get(className).getAttribute().isEmpty()) {
@@ -751,11 +1018,19 @@ public class MSModelUtils {
return missingValues;
}
- public String createSubAttributes(List<String> dependency, Map<String, MSAttributeObject> classMap,
- String modelName) {
+ /**
+ * Creates the sub attributes.
+ *
+ * @param dependency the dependency
+ * @param classMap the class map
+ * @param modelName the model name
+ * @return the string
+ */
+ public String createSubAttributes(List<String> dependency, Map<String, MsAttributeObject> classMap,
+ String modelName) {
HashMap<String, Object> workingMap = new HashMap<>();
- MSAttributeObject tempObject;
+ MsAttributeObject tempObject;
if (dependency != null) {
if (dependency.isEmpty()) {
return "{}";
@@ -772,15 +1047,23 @@ public class MSModelUtils {
return createJson(classMap, modelName);
}
- public List<String> getFullDependencyList(List<String> dependency, Map<String, MSAttributeObject> classMap) {
+ /**
+ * Gets the full dependency list.
+ *
+ * @param dependency the dependency
+ * @param classMap the class map
+ * @return the full dependency list
+ */
+ public List<String> getFullDependencyList(List<String> dependency, Map<String, MsAttributeObject> classMap) {
ArrayList<String> returnList = new ArrayList<>();
ArrayList<String> workingList;
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[] {"", ""});
+ 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) {
updDependencyList(returnList, depend);
@@ -791,14 +1074,23 @@ public class MSModelUtils {
return returnList;
}
+ /**
+ * Upd dependency list.
+ *
+ * @param returnList the return list
+ * @param depend the depend
+ */
private void updDependencyList(ArrayList<String> returnList, String depend) {
if (!returnList.contains(depend) && !depend.isEmpty()) {
returnList.add(depend.trim());
}
}
- /*
- * For TOSCA Model
+ /**
+ * Parses the TOSCA model.
+ *
+ * @param fileName the file name
+ * @return the string
*/
public String parseTosca(String fileName) {
Map<String, String> map = new LinkedHashMap<>();
@@ -823,14 +1115,21 @@ public class MSModelUtils {
return null;
}
- @SuppressWarnings("unchecked")
+ /**
+ * Load.
+ *
+ * @param fileName the file name
+ * @return the map
+ * @throws IOException Signals that an I/O exception has occurred.
+ * @throws ParserException the parser exception
+ */
public Map<String, String> load(String fileName) throws IOException, ParserException {
File newConfiguration = new File(fileName);
StringBuilder orderInfo = new StringBuilder("[");
Yaml yaml = new Yaml();
LinkedHashMap<Object, Object> yamlMap = null;
try (InputStream is = new FileInputStream(newConfiguration)) {
- yamlMap = (LinkedHashMap<Object, Object>) yaml.load(is);
+ yamlMap = yaml.load(is);
} catch (FileNotFoundException e) {
logger.error(e);
} catch (Exception e) {
@@ -838,7 +1137,6 @@ public class MSModelUtils {
throw new ParserException("Invalid TOSCA Model format. Please make sure it is a valid YAML file");
}
- StringBuilder sb = new StringBuilder();
LinkedHashMap<String, String> settings = new LinkedHashMap<>();
if (yamlMap == null) {
return settings;
@@ -869,10 +1167,16 @@ public class MSModelUtils {
}
List<String> path = new ArrayList<>();
- serializeMap(settings, sb, path, yamlMap);
+ serializeMap(settings, new StringBuilder(), path, yamlMap);
return settings;
}
+ /**
+ * Validations.
+ *
+ * @param yamlMap the yaml map
+ * @return the string
+ */
@SuppressWarnings("unchecked")
private String validations(@SuppressWarnings("rawtypes") Map yamlMap) {
@@ -887,8 +1191,7 @@ public class MSModelUtils {
// Get a set of the entries
@SuppressWarnings("rawtypes")
Set<Entry> entries = yamlMap.entrySet();
- for (@SuppressWarnings("rawtypes")
- Map.Entry me : entries) {
+ for (Map.Entry<Object, Object> me : entries) {
if (TOSCA_SIMPLE_YAML_1_0_0.equals(me.getValue())) {
isToscaVersionValueFound = true;
}
@@ -944,9 +1247,18 @@ public class MSModelUtils {
return null;
}
- @SuppressWarnings({"unchecked", "rawtypes"})
+ /**
+ * Serialize map.
+ *
+ * @param settings the settings
+ * @param sb the sb
+ * @param path the path
+ * @param yamlMap the yaml map
+ */
+ @SuppressWarnings(
+ { "unchecked", "rawtypes" })
private void serializeMap(LinkedHashMap<String, String> settings, StringBuilder sb, List<String> path,
- Map<Object, Object> yamlMap) {
+ Map<Object, Object> yamlMap) {
for (Map.Entry<Object, Object> entry : yamlMap.entrySet()) {
if (entry.getValue() instanceof Map) {
@@ -963,9 +1275,17 @@ public class MSModelUtils {
}
}
+ /**
+ * Serialize list.
+ *
+ * @param settings the settings
+ * @param sb the sb
+ * @param path the path
+ * @param yamlList the yaml list
+ */
@SuppressWarnings("unchecked")
private void serializeList(LinkedHashMap<String, String> settings, StringBuilder sb, List<String> path,
- List<String> yamlList) {
+ List<String> yamlList) {
int counter = 0;
for (Object listEle : yamlList) {
if (listEle instanceof Map) {
@@ -983,8 +1303,17 @@ public class MSModelUtils {
}
}
+ /**
+ * Serialize value.
+ *
+ * @param settings the settings
+ * @param sb the sb
+ * @param path the path
+ * @param name the name
+ * @param value the value
+ */
private void serializeValue(LinkedHashMap<String, String> settings, StringBuilder sb, List<String> path,
- String name, Object value) {
+ String name, Object value) {
if (value == null) {
return;
}
@@ -996,7 +1325,11 @@ public class MSModelUtils {
settings.put(sb.toString(), value.toString());
}
-
+ /**
+ * Parses the data and policy nodes.
+ *
+ * @param map the map
+ */
void parseDataAndPolicyNodes(Map<String, String> map) {
for (String key : map.keySet()) {
if (key.contains("policy.nodes.Root")) {
@@ -1017,6 +1350,12 @@ public class MSModelUtils {
}
}
+ /**
+ * String between dots.
+ *
+ * @param str the str
+ * @return the int
+ */
// Second index of dot should be returned.
public int stringBetweenDots(String str) {
String stringToSearch = str;
@@ -1031,7 +1370,11 @@ public class MSModelUtils {
return uniqueKeys.size();
}
-
+ /**
+ * String between dots for data fields.
+ *
+ * @param str the str
+ */
public void stringBetweenDotsForDataFields(String str) {
String stringToSearch = str;
String[] ss = stringToSearch.split("\\.");
@@ -1044,6 +1387,11 @@ public class MSModelUtils {
}
}
+ /**
+ * Construct json for data fields.
+ *
+ * @param dataMapForJson the data map for json
+ */
void constructJsonForDataFields(LinkedHashMap<String, String> dataMapForJson) {
LinkedHashMap<String, LinkedHashMap<String, String>> dataMapKey = new LinkedHashMap<>();
LinkedHashMap<String, String> hmSub;
@@ -1065,14 +1413,14 @@ public class MSModelUtils {
JSONObject mainObject = new JSONObject();
JSONObject json;
for (Map.Entry<String, LinkedHashMap<String, String>> entry : dataMapKey.entrySet()) {
- String s = entry.getKey();
+ String keyString = entry.getKey();
json = new JSONObject();
- HashMap<String, String> jsonHm = dataMapKey.get(s);
+ HashMap<String, String> jsonHm = dataMapKey.get(keyString);
for (Map.Entry<String, String> entryMap : jsonHm.entrySet()) {
String key = entryMap.getKey();
json.put(key, jsonHm.get(key));
}
- mainObject.put(s, json);
+ mainObject.put(keyString, json);
}
Iterator<String> keysItr = mainObject.keys();
while (keysItr.hasNext()) {
@@ -1086,6 +1434,12 @@ public class MSModelUtils {
logger.info("###############################################################################");
}
+ /**
+ * Parses the data nodes.
+ *
+ * @param map the map
+ * @return the linked hash map
+ */
LinkedHashMap<String, String> parseDataNodes(Map<String, String> map) {
LinkedHashMap<String, String> dataMapForJson = new LinkedHashMap<>();
matchableValues = new HashMap<>();
@@ -1112,13 +1466,10 @@ public class MSModelUtils {
requiredValue = "false";
}
if (INTEGER.equalsIgnoreCase(typeValue) || STRING.equalsIgnoreCase(typeValue)
- || typeValue.equalsIgnoreCase(BOOLEAN)) {
- String findDefault =
- DATATYPE + uniqueDataKeySplit[0] + PROPERTIES + uniqueDataKeySplit[1] + DEFAULT;
- String findDescription =
- DATATYPE + uniqueDataKeySplit[0] + PROPERTIES + uniqueDataKeySplit[1] + DESCRIPTION;
+ || typeValue.equalsIgnoreCase(BOOLEAN)) {
+ String findDefault = DATATYPE + uniqueDataKeySplit[0] + PROPERTIES + uniqueDataKeySplit[1]
+ + DEFAULT;
String defaultValue = map.get(findDefault);
- String descriptionDefined = map.get(findDescription);
logger.info("defaultValue is:" + defaultValue);
logger.info("requiredValue is:" + requiredValue);
@@ -1126,16 +1477,19 @@ public class MSModelUtils {
attributeIndividualStringBuilder.append(typeValue + DEFAULTVALUE);
attributeIndividualStringBuilder.append(defaultValue + REQUIREDVALUE);
attributeIndividualStringBuilder.append(requiredValue + MANYFALSE);
- attributeIndividualStringBuilder.append(DESCRIPTION_TOKEN + descriptionDefined);
+
+ String findDescription = DATATYPE + uniqueDataKeySplit[0] + PROPERTIES + uniqueDataKeySplit[1]
+ + DESCRIPTION;
+ attributeIndividualStringBuilder.append(DESCRIPTION_TOKEN + map.get(findDescription));
dataMapForJson.put(uniqueDataKey, attributeIndividualStringBuilder.toString());
} else if (LIST.equalsIgnoreCase(typeValue) || MAP.equalsIgnoreCase(typeValue)) {
logger.info("requiredValue is:" + requiredValue);
String findList = DATATYPE + uniqueDataKeySplit[0] + PROPERTIES + uniqueDataKeySplit[1]
- + ".entry_schema.type";
+ + ".entry_schema.type";
String findDefaultValue = DATATYPE + uniqueDataKeySplit[0] + PROPERTIES + uniqueDataKeySplit[1]
- + ".entry_schema.default";
+ + ".entry_schema.default";
String findDescription = DATATYPE + uniqueDataKeySplit[0] + PROPERTIES + uniqueDataKeySplit[1]
- + ".entry_schema.description";
+ + ".entry_schema.description";
String listValue = map.get(findList);
String defaultValue = map.get(findDefaultValue);
String description = map.get(findDescription);
@@ -1153,16 +1507,19 @@ public class MSModelUtils {
StringBuilder stringListItems = new StringBuilder();
if (LIST.equalsIgnoreCase(typeValue)) {
stringListItems.append(uniqueDataKeySplit[1].toUpperCase() + DEFAULTVALUE + defaultValue
- + REQUIREDVALUE + requiredValue + MANYFALSE + DESCRIPTION_TOKEN + description);
+ + REQUIREDVALUE + requiredValue + MANYFALSE + DESCRIPTION_TOKEN
+ + description);
} else if (MAP.equalsIgnoreCase(typeValue)) {
stringListItems.append(uniqueDataKeySplit[1].toUpperCase() + DEFAULTVALUE + defaultValue
- + REQUIREDVALUE + requiredValue + MANYTRUE + DESCRIPTION_TOKEN + description);
+ + REQUIREDVALUE + requiredValue + MANYTRUE + DESCRIPTION_TOKEN
+ + description);
}
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;
+ + uniqueDataKeySplit[1] + ".entry_schema.constraints.0.valid_values."
+ + i;
String constraintsValue = map.get(findConstraints);
logger.info(constraintsValue);
boolean ruleCheck = false;
@@ -1177,19 +1534,19 @@ public class MSModelUtils {
ruleCheck = true;
dictionaryNameValRule = dictionaryNameVal.split("#");
dictFromDB = commonClassDao.getDataById(DictionaryData.class, DICTIONARYNAME,
- dictionaryNameValRule[0]);
+ dictionaryNameValRule[0]);
} else {
dictFromDB = commonClassDao.getDataById(DictionaryData.class, DICTIONARYNAME,
- dictionaryName[1]);
+ dictionaryName[1]);
}
if (dictFromDB != null && !dictFromDB.isEmpty()) {
DictionaryData data = (DictionaryData) dictFromDB.get(0);
if (ruleCheck) {
constraintsValue = DICTIONARY + data.getDictionaryUrl() + "@"
- + data.getDictionaryDataByName() + "&Rule";
+ + data.getDictionaryDataByName() + "&Rule";
} else {
constraintsValue = DICTIONARY + data.getDictionaryUrl() + "@"
- + data.getDictionaryDataByName();
+ + data.getDictionaryDataByName();
}
}
dataListBuffer.append(constraintsValue + ",");
@@ -1208,9 +1565,9 @@ public class MSModelUtils {
}
} else {
String findUserDefined = DATATYPE + uniqueDataKeySplit[0] + "." + PROPERTIES_KEY + "."
- + uniqueDataKeySplit[1] + TYPE;
+ + uniqueDataKeySplit[1] + TYPE;
String findDescription = DATATYPE + uniqueDataKeySplit[0] + "." + PROPERTIES_KEY + "."
- + uniqueDataKeySplit[1] + DESCRIPTION;
+ + uniqueDataKeySplit[1] + DESCRIPTION;
String userDefinedValue = map.get(findUserDefined);
String description = map.get(findDescription);
String trimValue = userDefinedValue.substring(userDefinedValue.lastIndexOf('.') + 1);
@@ -1229,8 +1586,15 @@ public class MSModelUtils {
return dataMapForJson;
}
+ /**
+ * Parses the policy nodes.
+ *
+ * @param map the map
+ * @return the linked hash map
+ * @throws ParserException the parser exception
+ */
LinkedHashMap<String, LinkedHashMap<String, String>> parsePolicyNodes(Map<String, String> map)
- throws ParserException {
+ throws ParserException {
LinkedHashMap<String, LinkedHashMap<String, String>> mapKey = new LinkedHashMap<>();
for (String uniqueKey : uniqueKeys) {
LinkedHashMap<String, String> hm;
@@ -1243,10 +1607,9 @@ public class MSModelUtils {
String keyStr = key.substring(key.lastIndexOf('.') + 1);
String valueStr = map.get(key);
if ("type".equalsIgnoreCase(keyStr) && key.contains("entry_schema.0.type")
- || key.contains("entry_schema.type") && valueStr.contains("policy.data.")) {
- throw new ParserException(
- "For user defined object type, Please make sure no space between 'type:' and object "
- + valueStr);
+ || key.contains("entry_schema.type") && valueStr.contains("policy.data.")) {
+ throw new ParserException("For user defined object type,"
+ + " Please make sure no space between 'type:' and object " + valueStr);
}
if ("type".equals(keyStr)) {
@@ -1277,6 +1640,11 @@ public class MSModelUtils {
return mapKey;
}
+ /**
+ * Creates the attributes.
+ *
+ * @param mapKey the map key
+ */
private void createAttributes(LinkedHashMap<String, LinkedHashMap<String, String>> mapKey) {
StringBuilder attributeStringBuilder = new StringBuilder();
StringBuilder referenceStringBuilder = new StringBuilder();
@@ -1286,8 +1654,8 @@ public class MSModelUtils {
String keySetString = entry.getKey();
LinkedHashMap<String, String> keyValues = mapKey.get(keySetString);
if (keyValues.get("type") != null && (STRING.equalsIgnoreCase(keyValues.get("type"))
- || INTEGER.equalsIgnoreCase(keyValues.get("type"))
- || BOOLEAN.equalsIgnoreCase(keyValues.get("type")))) {
+ || INTEGER.equalsIgnoreCase(keyValues.get("type"))
+ || BOOLEAN.equalsIgnoreCase(keyValues.get("type")))) {
StringBuilder attributeIndividualStringBuilder = new StringBuilder();
attributeIndividualStringBuilder.append(keySetString + "=");
attributeIndividualStringBuilder.append(keyValues.get("type") + DEFAULTVALUE);
@@ -1321,7 +1689,7 @@ public class MSModelUtils {
String trimValue = value.substring(value.lastIndexOf('.') + 1);
StringBuilder referenceIndividualStringBuilder = new StringBuilder();
referenceIndividualStringBuilder.append(keySetString + "=" + trimValue + MANYTRUE
- + DESCRIPTION_TOKEN + keyValues.get(DESCRIPTION_KEY));
+ + DESCRIPTION_TOKEN + keyValues.get(DESCRIPTION_KEY));
referenceStringBuilder.append(referenceIndividualStringBuilder + ",");
isDefinedType = true;
}
@@ -1330,7 +1698,7 @@ public class MSModelUtils {
}
if (!isDefinedType && LIST.equalsIgnoreCase(keyValues.get("type"))
- && (constraints == null || constraints.isEmpty())) {
+ && (constraints == null || constraints.isEmpty())) {
referenceStringBuilder.append(keySetString + "=MANY-true" + ",");
}
} else {
@@ -1343,7 +1711,7 @@ public class MSModelUtils {
String trimValue = value.substring(value.lastIndexOf('.') + 1);
StringBuilder referenceIndividualStringBuilder = new StringBuilder();
referenceIndividualStringBuilder.append(keySetString + "=" + trimValue + MANYFALSE
- + DESCRIPTION_TOKEN + keyValues.get(DESCRIPTION_KEY));
+ + DESCRIPTION_TOKEN + keyValues.get(DESCRIPTION_KEY));
referenceStringBuilder.append(referenceIndividualStringBuilder + ",");
} else {
logger.info("keyValues.get(type) is null/empty");
@@ -1356,8 +1724,8 @@ public class MSModelUtils {
for (String str : constraints) {
if (str.contains(DICTIONARY)) {
String[] dictionaryName = str.split(":");
- List<Object> dictFromDB =
- commonClassDao.getDataById(DictionaryData.class, DICTIONARYNAME, dictionaryName[1]);
+ List<Object> dictFromDB = commonClassDao.getDataById(DictionaryData.class, DICTIONARYNAME,
+ dictionaryName[1]);
if (dictFromDB != null && !dictFromDB.isEmpty()) {
DictionaryData data = (DictionaryData) dictFromDB.get(0);
str = DICTIONARY + data.getDictionaryUrl() + "@" + data.getDictionaryDataByName();
@@ -1368,7 +1736,6 @@ public class MSModelUtils {
listBuffer.append("]#");
logger.info(listBuffer);
-
StringBuilder referenceIndividualStringBuilder = new StringBuilder();
referenceIndividualStringBuilder.append(keySetString + "=" + keySetString.toUpperCase() + MANYFALSE);
referenceStringBuilder.append(referenceIndividualStringBuilder + ",");
@@ -1378,7 +1745,6 @@ public class MSModelUtils {
dataListBuffer.append(listBuffer);
-
logger.info("$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$");
logger.info("Whole attribute String is:" + attributeStringBuilder);
logger.info("Whole reference String is:" + referenceStringBuilder);
@@ -1391,6 +1757,11 @@ public class MSModelUtils {
this.attributeString = attributeStringBuilder.toString();
}
+ /**
+ * Find node.
+ *
+ * @param map the map
+ */
@SuppressWarnings("unchecked")
private void findNode(LinkedHashMap<Object, Object> map) {
@@ -1412,6 +1783,11 @@ public class MSModelUtils {
}
+ /**
+ * Save nodes.
+ *
+ * @param map the map
+ */
private void saveNodes(LinkedHashMap<?, ?> map) {
for (Entry<?, ?> entry : map.entrySet()) {
@@ -1424,61 +1800,4 @@ public class MSModelUtils {
}
}
}
-
- public String getAttributeString() {
- return attributeString;
- }
-
- public void setAttributeString(String attributeString) {
- this.attributeString = attributeString;
- }
-
- public LinkedHashMap<String, Object> getRetmap() {
- return retmap;
- }
-
- public void setRetmap(LinkedHashMap<String, Object> retmap) {
- this.retmap = retmap;
- }
-
- public Map<String, String> getMatchableValues() {
- return matchableValues;
- }
-
- public void setMatchableValues(Map<String, String> matchableValues) {
- this.matchableValues = matchableValues;
- }
-
- public String getReferenceAttributes() {
- return referenceAttributes;
- }
-
- public void setReferenceAttributes(String referenceAttributes) {
- this.referenceAttributes = referenceAttributes;
- }
-
- public String getListConstraints() {
- return listConstraints;
- }
-
- public void setListConstraints(String listConstraints) {
- this.listConstraints = listConstraints;
- }
-
- public String getDataOrderInfo() {
- return dataOrderInfo;
- }
-
- public void setDataOrderInfo(String dataOrderInfo) {
- this.dataOrderInfo = dataOrderInfo;
- }
-
- public String getJsonRuleFormation() {
- return jsonRuleFormation;
- }
-
- public void setJsonRuleFormation(String jsonRuleFormation) {
- this.jsonRuleFormation = jsonRuleFormation;
- }
-
}
diff --git a/ONAP-REST/src/main/java/org/onap/policy/rest/util/ParserException.java b/ONAP-REST/src/main/java/org/onap/policy/rest/util/ParserException.java
index 50e30f05b..5e034d29b 100644
--- a/ONAP-REST/src/main/java/org/onap/policy/rest/util/ParserException.java
+++ b/ONAP-REST/src/main/java/org/onap/policy/rest/util/ParserException.java
@@ -2,14 +2,15 @@
* ============LICENSE_START=======================================================
* ONAP-REST
* ================================================================================
- * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2018-2019 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2019 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -17,14 +18,13 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.policy.rest.util;
-public class ParserException extends Exception{
- String message;
- ParserException(String message) {
- this.message = message;
- }
- public String getMessage(){
- return message ;
- }
+public class ParserException extends Exception {
+ private static final long serialVersionUID = -1166704711958410424L;
+
+ public ParserException(String message) {
+ super(message);
+ }
} \ No newline at end of file
diff --git a/ONAP-REST/src/main/java/org/onap/policy/rest/util/PDPPolicyContainer.java b/ONAP-REST/src/main/java/org/onap/policy/rest/util/PdpPolicyContainer.java
index f5c4c3b38..d6bd3f831 100644
--- a/ONAP-REST/src/main/java/org/onap/policy/rest/util/PDPPolicyContainer.java
+++ b/ONAP-REST/src/main/java/org/onap/policy/rest/util/PdpPolicyContainer.java
@@ -3,13 +3,14 @@
* ONAP Policy Engine
* ================================================================================
* Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2019 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -20,6 +21,11 @@
package org.onap.policy.rest.util;
+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;
import java.util.ArrayList;
import java.util.Collection;
@@ -32,69 +38,56 @@ import org.onap.policy.common.logging.flexlogger.Logger;
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 {
+public class PdpPolicyContainer extends PolicyItemSetChangeNotifier implements PolicyContainer.Indexed {
private static final long serialVersionUID = 1L;
- private static final Logger LOGGER = FlexLogger.getLogger(PDPPolicyContainer.class);
+ private static final Logger LOGGER = FlexLogger.getLogger(PdpPolicyContainer.class);
- /**
- * String identifier of a file's "Id" property.
- */
private static final String PROPERTY_ID = "Id";
-
- /**
- * String identifier of a file's "name" property.
- */
private static final String PROPERTY_NAME = "Name";
-
- /**
- * String identifier of a file's "name" property.
- */
private static final String PROPERTY_VERSION = "Version";
-
- /**
- * String identifier of a file's "Description" property.
- */
private static final String PROPERTY_DESCRIPTION = "Description";
-
- /**
- * String identifier of a file's "IsRoot" property.
- */
private static final String PROPERTY_ISROOT = "Root";
/**
* List of the string identifiers for the available properties.
*/
private static Collection<String> pDPPolicyProperties;
-
+
private final transient Object data;
private transient List<PDPPolicy> policies;
-
+
+ /**
+ * Instantiates a new pdp policy container.
+ *
+ * @param data the data
+ */
@SuppressWarnings("unchecked")
- public PDPPolicyContainer(Object data) {
+ public PdpPolicyContainer(Object data) {
super();
this.data = data;
if (this.data instanceof PDPGroup) {
- policies = new ArrayList<> (((PDPGroup) this.data).getPolicies());
+ policies = new ArrayList<>(((PDPGroup) this.data).getPolicies());
}
if (this.data instanceof PDP) {
- policies = new ArrayList<> (((PDP) this.data).getPolicies());
+ policies = new ArrayList<>(((PDP) this.data).getPolicies());
}
if (this.data instanceof Set) {
- policies = new ArrayList<> ((Set<PDPPolicy>)data);
+ policies = new ArrayList<>((Set<PDPPolicy>) data);
}
if (this.policies == null) {
LOGGER.info("NULL policies");
- throw new NullPointerException("PDPPolicyContainer created with unexpected Object type '" + data.getClass().getName() + "'");
+ throw new NullPointerException("PDPPolicyContainer created with unexpected Object type '"
+ + data.getClass().getName() + "'");
}
this.setContainer(this);
}
+ /**
+ * Next item id.
+ *
+ * @param itemId the item id
+ * @return the object
+ */
@Override
public Object nextItemId(Object itemId) {
if (LOGGER.isTraceEnabled()) {
@@ -104,9 +97,15 @@ public class PDPPolicyContainer extends PolicyItemSetChangeNotifier implements P
if (index == -1 || ((index + 1) >= this.policies.size())) {
return null;
}
- return new PDPPolicyItem(this.policies.get(index + 1));
+ return new PdpPolicyItem(this.policies.get(index + 1));
}
+ /**
+ * Prev item id.
+ *
+ * @param itemId the item id
+ * @return the object
+ */
@Override
public Object prevItemId(Object itemId) {
if (LOGGER.isTraceEnabled()) {
@@ -116,9 +115,14 @@ public class PDPPolicyContainer extends PolicyItemSetChangeNotifier implements P
if (index <= 0) {
return null;
}
- return new PDPPolicyItem(this.policies.get(index - 1));
+ return new PdpPolicyItem(this.policies.get(index - 1));
}
+ /**
+ * First item id.
+ *
+ * @return the object
+ */
@Override
public Object firstItemId() {
if (LOGGER.isTraceEnabled()) {
@@ -127,9 +131,14 @@ public class PDPPolicyContainer extends PolicyItemSetChangeNotifier implements P
if (this.policies.isEmpty()) {
return null;
}
- return new PDPPolicyItem(this.policies.get(0));
+ return new PdpPolicyItem(this.policies.get(0));
}
+ /**
+ * Last item id.
+ *
+ * @return the object
+ */
@Override
public Object lastItemId() {
if (LOGGER.isTraceEnabled()) {
@@ -138,9 +147,15 @@ public class PDPPolicyContainer extends PolicyItemSetChangeNotifier implements P
if (this.policies.isEmpty()) {
return null;
}
- return new PDPPolicyItem(this.policies.get(this.policies.size() - 1));
+ return new PdpPolicyItem(this.policies.get(this.policies.size() - 1));
}
+ /**
+ * Checks if is first id.
+ *
+ * @param itemId the item id
+ * @return true, if is first id
+ */
@Override
public boolean isFirstId(Object itemId) {
if (LOGGER.isTraceEnabled()) {
@@ -152,6 +167,12 @@ public class PDPPolicyContainer extends PolicyItemSetChangeNotifier implements P
return itemId.equals(this.policies.get(0));
}
+ /**
+ * Checks if is last id.
+ *
+ * @param itemId the item id
+ * @return true, if is last id
+ */
@Override
public boolean isLastId(Object itemId) {
if (LOGGER.isTraceEnabled()) {
@@ -163,16 +184,32 @@ public class PDPPolicyContainer extends PolicyItemSetChangeNotifier implements P
return itemId.equals(this.policies.get(this.policies.size() - 1));
}
+ /**
+ * Adds the item after.
+ *
+ * @param previousItemId the previous item id
+ * @return the object
+ */
@Override
public Object addItemAfter(Object previousItemId) {
return null;
}
+ /**
+ * Gets the container property ids.
+ *
+ * @return the container property ids
+ */
@Override
public Collection<?> getContainerPropertyIds() {
return pDPPolicyProperties;
}
+ /**
+ * Gets the item ids.
+ *
+ * @return the item ids
+ */
@Override
public Collection<?> getItemIds() {
final Collection<Object> items = new ArrayList<>();
@@ -180,7 +217,30 @@ public class PDPPolicyContainer extends PolicyItemSetChangeNotifier implements P
return Collections.unmodifiableCollection(items);
}
+ /**
+ * Gets the item ids.
+ *
+ * @param startIndex the start index
+ * @param numberOfItems the number of items
+ * @return the item ids
+ */
+ @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);
+ }
+ /**
+ * Gets the type.
+ *
+ * @param propertyId the property id
+ * @return the type
+ */
@Override
public Class<?> getType(Object propertyId) {
if (propertyId.equals(PROPERTY_ID)) {
@@ -201,6 +261,11 @@ public class PDPPolicyContainer extends PolicyItemSetChangeNotifier implements P
return null;
}
+ /**
+ * Size.
+ *
+ * @return the int
+ */
@Override
public int size() {
if (LOGGER.isTraceEnabled()) {
@@ -209,6 +274,12 @@ public class PDPPolicyContainer extends PolicyItemSetChangeNotifier implements P
return this.policies.size();
}
+ /**
+ * Contains id.
+ *
+ * @param itemId the item id
+ * @return true, if successful
+ */
@Override
public boolean containsId(Object itemId) {
if (LOGGER.isTraceEnabled()) {
@@ -217,11 +288,22 @@ public class PDPPolicyContainer extends PolicyItemSetChangeNotifier implements P
return this.policies.contains(itemId);
}
+ /**
+ * Adds the item.
+ *
+ * @return the object
+ */
@Override
public Object addItem() {
throw new UnsupportedOperationException("Cannot add an empty policy.");
}
+ /**
+ * Removes the item.
+ *
+ * @param itemId the item id
+ * @return true, if successful
+ */
@Override
public boolean removeItem(Object itemId) {
if (LOGGER.isTraceEnabled()) {
@@ -231,34 +313,59 @@ public class PDPPolicyContainer extends PolicyItemSetChangeNotifier implements P
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())){
+ 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);
+ 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);
}
+ /**
+ * Adds the container property.
+ *
+ * @param propertyId the property id
+ * @param type the type
+ * @param defaultValue the default value
+ * @return true, if successful
+ */
@Override
- public boolean addContainerProperty(Object propertyId, Class<?> type,
- Object defaultValue) {
+ public boolean addContainerProperty(Object propertyId, Class<?> type, Object defaultValue) {
return false;
}
+ /**
+ * Removes the container property.
+ *
+ * @param propertyId the property id
+ * @return true, if successful
+ */
@Override
public boolean removeContainerProperty(Object propertyId) {
return false;
}
+ /**
+ * Removes the all items.
+ *
+ * @return true, if successful
+ */
@Override
public boolean removeAllItems() {
return false;
}
+ /**
+ * Index of id.
+ *
+ * @param itemId the item id
+ * @return the int
+ */
@Override
public int indexOfId(Object itemId) {
if (LOGGER.isTraceEnabled()) {
@@ -267,6 +374,12 @@ public class PDPPolicyContainer extends PolicyItemSetChangeNotifier implements P
return this.policies.indexOf(itemId);
}
+ /**
+ * Gets the id by index.
+ *
+ * @param index the index
+ * @return the id by index
+ */
@Override
public Object getIdByIndex(int index) {
if (LOGGER.isTraceEnabled()) {
@@ -275,17 +388,12 @@ public class PDPPolicyContainer extends PolicyItemSetChangeNotifier implements P
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);
- }
-
+ /**
+ * Adds the item at.
+ *
+ * @param index the index
+ * @return the object
+ */
@Override
public Object addItemAt(int index) {
if (LOGGER.isTraceEnabled()) {
@@ -294,13 +402,23 @@ public class PDPPolicyContainer extends PolicyItemSetChangeNotifier implements P
return null;
}
- public class PDPPolicyItem {
+ public class PdpPolicyItem {
private final PDPPolicy policy;
- public PDPPolicyItem(PDPPolicy itemId) {
+ /**
+ * Instantiates a new PDP policy item.
+ *
+ * @param itemId the item id
+ */
+ public PdpPolicyItem(PDPPolicy itemId) {
this.policy = itemId;
}
+ /**
+ * Gets the id.
+ *
+ * @return the id
+ */
public String getId() {
if (LOGGER.isTraceEnabled()) {
LOGGER.trace("getId: " + this.policy);
@@ -308,6 +426,11 @@ public class PDPPolicyContainer extends PolicyItemSetChangeNotifier implements P
return this.policy.getId();
}
+ /**
+ * Gets the name.
+ *
+ * @return the name
+ */
public String getName() {
if (LOGGER.isTraceEnabled()) {
LOGGER.trace("getName: " + this.policy);
@@ -315,6 +438,11 @@ public class PDPPolicyContainer extends PolicyItemSetChangeNotifier implements P
return this.policy.getName();
}
+ /**
+ * Gets the version.
+ *
+ * @return the version
+ */
public String getVersion() {
if (LOGGER.isTraceEnabled()) {
LOGGER.trace("getVersion: " + this.policy);
@@ -322,6 +450,11 @@ public class PDPPolicyContainer extends PolicyItemSetChangeNotifier implements P
return this.policy.getVersion();
}
+ /**
+ * Gets the description.
+ *
+ * @return the description
+ */
public String getDescription() {
if (LOGGER.isTraceEnabled()) {
LOGGER.trace("getDescription: " + this.policy);
@@ -329,6 +462,11 @@ public class PDPPolicyContainer extends PolicyItemSetChangeNotifier implements P
return this.policy.getDescription();
}
+ /**
+ * Gets the root.
+ *
+ * @return the root
+ */
public boolean getRoot() {
if (LOGGER.isTraceEnabled()) {
LOGGER.trace("isRoot: " + this.policy);
@@ -336,8 +474,13 @@ public class PDPPolicyContainer extends PolicyItemSetChangeNotifier implements P
return this.policy.isRoot();
}
+ /**
+ * Sets the root.
+ *
+ * @param root the new root
+ */
public void setRoot(Boolean root) {
- ((StdPDPPolicy)this.policy).setRoot(root);
+ ((StdPDPPolicy) this.policy).setRoot(root);
}
}
diff --git a/ONAP-REST/src/main/java/org/onap/policy/rest/util/PolicyContainer.java b/ONAP-REST/src/main/java/org/onap/policy/rest/util/PolicyContainer.java
index 80bb16d54..42bee49b5 100644
--- a/ONAP-REST/src/main/java/org/onap/policy/rest/util/PolicyContainer.java
+++ b/ONAP-REST/src/main/java/org/onap/policy/rest/util/PolicyContainer.java
@@ -3,13 +3,14 @@
* ONAP Policy Engine
* ================================================================================
* Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2019 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -24,26 +25,24 @@ import java.io.Serializable;
import java.util.Collection;
import java.util.List;
-
-public interface PolicyContainer extends Serializable{
+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();
-
+
public boolean removeItem(Object itemId);
- public boolean addContainerProperty(Object propertyId, Class<?> type,
- Object defaultValue);
-
+ public boolean addContainerProperty(Object propertyId, Class<?> type, Object defaultValue);
+
public boolean removeContainerProperty(Object propertyId);
public boolean removeAllItems();
@@ -63,10 +62,9 @@ public interface PolicyContainer extends Serializable{
public boolean isLastId(Object itemId);
public Object addItemAfter(Object previousItemId);
-
+
}
-
public interface Indexed extends Ordered {
public int indexOfId(Object itemId);
@@ -74,7 +72,7 @@ public interface PolicyContainer extends Serializable{
public Object getIdByIndex(int index);
public List<?> getItemIds(int startIndex, int numberOfItems);
-
+
public Object addItemAt(int index);
public interface ItemAddEvent extends ItemSetChangeEvent {
@@ -86,9 +84,8 @@ public interface PolicyContainer extends Serializable{
public int getAddedItemsCount();
}
-
public interface ItemRemoveEvent extends ItemSetChangeEvent {
-
+
public Object getFirstItemId();
public int getFirstIndex();
@@ -96,23 +93,21 @@ public interface PolicyContainer extends Serializable{
public int getRemovedItemsCount();
}
}
-
- public interface ItemSetChangeEvent extends Serializable {
+ @FunctionalInterface
+ public interface ItemSetChangeEvent {
public PolicyContainer getContainer();
}
- public interface ItemSetChangeListener extends Serializable {
-
+ @FunctionalInterface
+ public interface ItemSetChangeListener {
public void containerItemSetChange(PolicyContainer.ItemSetChangeEvent event);
}
public interface ItemSetChangeNotifier extends Serializable {
- public void addItemSetChangeListener(
- PolicyContainer.ItemSetChangeListener listener);
+ public void addItemSetChangeListener(PolicyContainer.ItemSetChangeListener listener);
- public void removeItemSetChangeListener(
- PolicyContainer.ItemSetChangeListener listener);
+ public void removeItemSetChangeListener(PolicyContainer.ItemSetChangeListener listener);
}
}
diff --git a/ONAP-REST/src/main/java/org/onap/policy/rest/util/PolicyItemSetChangeNotifier.java b/ONAP-REST/src/main/java/org/onap/policy/rest/util/PolicyItemSetChangeNotifier.java
index 16e467041..d70830118 100644
--- a/ONAP-REST/src/main/java/org/onap/policy/rest/util/PolicyItemSetChangeNotifier.java
+++ b/ONAP-REST/src/main/java/org/onap/policy/rest/util/PolicyItemSetChangeNotifier.java
@@ -3,13 +3,14 @@
* ONAP Policy Engine
* ================================================================================
* Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2019 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -20,7 +21,6 @@
package org.onap.policy.rest.util;
-
import java.io.Serializable;
import java.util.Collection;
import java.util.EventObject;
@@ -29,19 +29,18 @@ import java.util.LinkedList;
import org.onap.policy.rest.util.PolicyContainer.ItemSetChangeEvent;
import org.onap.policy.rest.util.PolicyContainer.ItemSetChangeListener;
-
-
public class PolicyItemSetChangeNotifier implements PolicyContainer.ItemSetChangeNotifier {
private static final long serialVersionUID = 1L;
+
private Collection<PolicyContainer.ItemSetChangeListener> itemSetChangeListeners = null;
private PolicyContainer container = null;
-
+
public PolicyItemSetChangeNotifier() {
// Empty constructor
}
-
- protected void setContainer(PolicyContainer c) {
- this.container = c;
+
+ protected void setContainer(PolicyContainer container) {
+ this.container = container;
}
@Override
@@ -49,7 +48,8 @@ public class PolicyItemSetChangeNotifier implements PolicyContainer.ItemSetChang
if (getItemSetChangeListeners() == null) {
setItemSetChangeListeners(new LinkedList<PolicyContainer.ItemSetChangeListener>());
}
- getItemSetChangeListeners().add(listener); }
+ getItemSetChangeListeners().add(listener);
+ }
@Override
public void removeItemSetChangeListener(ItemSetChangeListener listener) {
@@ -58,8 +58,8 @@ public class PolicyItemSetChangeNotifier implements PolicyContainer.ItemSetChang
}
}
- protected static class BaseItemSetChangeEvent extends EventObject implements
- PolicyContainer.ItemSetChangeEvent, Serializable {
+ protected static class BaseItemSetChangeEvent extends EventObject
+ implements PolicyContainer.ItemSetChangeEvent, Serializable {
private static final long serialVersionUID = 1L;
protected BaseItemSetChangeEvent(PolicyContainer source) {
@@ -72,14 +72,14 @@ public class PolicyItemSetChangeNotifier implements PolicyContainer.ItemSetChang
}
}
- protected void setItemSetChangeListeners(
- Collection<PolicyContainer.ItemSetChangeListener> itemSetChangeListeners) {
+ protected void setItemSetChangeListeners(Collection<PolicyContainer.ItemSetChangeListener> itemSetChangeListeners) {
this.itemSetChangeListeners = itemSetChangeListeners;
}
+
protected Collection<PolicyContainer.ItemSetChangeListener> getItemSetChangeListeners() {
return itemSetChangeListeners;
}
-
+
protected void fireItemSetChange() {
fireItemSetChange(new BaseItemSetChangeEvent(this.container));
}
@@ -88,8 +88,7 @@ public class PolicyItemSetChangeNotifier implements PolicyContainer.ItemSetChang
if (getItemSetChangeListeners() != null) {
final Object[] l = getItemSetChangeListeners().toArray();
for (int i = 0; i < l.length; i++) {
- ((PolicyContainer.ItemSetChangeListener) l[i])
- .containerItemSetChange(event);
+ ((PolicyContainer.ItemSetChangeListener) l[i]).containerItemSetChange(event);
}
}
}
diff --git a/ONAP-REST/src/main/java/org/onap/policy/rest/util/PolicyValidation.java b/ONAP-REST/src/main/java/org/onap/policy/rest/util/PolicyValidation.java
index de20cd3f8..70be83208 100644
--- a/ONAP-REST/src/main/java/org/onap/policy/rest/util/PolicyValidation.java
+++ b/ONAP-REST/src/main/java/org/onap/policy/rest/util/PolicyValidation.java
@@ -3,13 +3,14 @@
* ONAP Policy Engine
* ================================================================================
* Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2019 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -26,9 +27,6 @@ import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.base.Splitter;
import com.google.common.base.Strings;
-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 java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.StringReader;
@@ -42,12 +40,18 @@ import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
+
import javax.json.Json;
import javax.json.JsonException;
import javax.json.JsonObject;
import javax.json.JsonReader;
import javax.json.JsonValue;
+import lombok.Getter;
+
+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.lang3.StringEscapeUtils;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONArray;
@@ -67,42 +71,56 @@ import org.onap.policy.xacml.util.XACMLPolicyScanner;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
-
@Service
public class PolicyValidation {
-
private static final Logger LOGGER = FlexLogger.getLogger(PolicyValidation.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 DECISION_POLICY_MS = "Decision_MS";
- 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";
- public static final String FIREWALL = "Firewall Config";
- public static final String OPTIMIZATION="Optimization";
- public static final String BRMSPARAM = "BRMS_Param";
- public static final String BRMSRAW = "BRMS_Raw";
- public static final String HTML_ITALICS_LNBREAK = "</i><br>";
- public static final String SUCCESS = "success";
- public static final String EMPTY_COMPONENT_ATTR =
- "Component Attributes: One or more Fields in Component Attributes is Empty.";
- public static final String ISREQUIRED = " is required";
- public static final String SPACESINVALIDCHARS = " : value has spaces or invalid characters</i><br>";
- private static final String REQUIRED_ATTRIBUTE = "required-true";
+ private static final String ACTION_POLICY = "Action";
+ private static final String BOOLEAN = "boolean";
+ private static final String BRMSPARAM = "BRMS_Param";
+ private static final String BRMSRAW = "BRMS_Raw";
+ private static final String CLOSEDLOOP_PM = "ClosedLoop_PM";
+ private static final String CLOSEDLOOP_POLICY = "ClosedLoop_Fault";
+ private static final String CONFIG_POLICY = "Config";
private static final String DECISION_MS_MODEL = "MicroService_Model";
+ private static final String DECISION_POLICY = "Decision";
+ private static final String DECISION_POLICY_MS = "Decision_MS";
+ private static final String ENFORCER_CONFIG_POLICY = "Enforcer Config";
+ private static final String FIREWALL = "Firewall Config";
+ private static final String HTML_ITALICS_LNBREAK = "</i><br>";
+ private static final String INTEGER = "integer";
+ private static final String ISREQUIRED = " is required";
+ private static final String JAVA = "java";
+ private static final String LIST = "list";
+ private static final String MAP = "map";
+ private static final String MICROSERVICES = "Micro Service";
+ private static final String MISSING_COMPONENT_ATTRIBUTE_VALUE = "<b>Component Attributes</b>:"
+ + "<i> has one missing Component Attribute value</i><br>";
+ private static final String MISSING_ATTRIBUTE_VALUE = "<b>Rule Attributes</b>:"
+ + "<i> has one missing Attribute value</i><br>";
+ private static final String MISSING_COMPONENT_ATTRIBUTE_KEY = "<b>Component Attributes</b>:"
+ + "<i> has one missing Component Attribute key</i><br>";
+ private static final String OPTIMIZATION = "Optimization";
private static final String RAW = "Raw";
+ private static final String REQUIRED_ATTRIBUTE = "required-true";
+ private static final String RULE_ALGORITHMS = "<b>Rule Algorithms</b>:<i>";
+ private static final String SELECT_AT_LEAST_ONE_D2_VIRTUALIZED_SERVICES = "<b>D2/Virtualized Services</b>: "
+ + "<i>Select at least one D2/Virtualized Services";
+ private static final String SPACESINVALIDCHARS = " : value has spaces or invalid characters</i><br>";
+ private static final String STRING = "string";
+ private static final String SUCCESS = "success";
+ private static final String VALUE = "value";
private static Map<String, String> mapAttribute = new HashMap<>();
private static Map<String, String> jsonRequestMap = new HashMap<>();
private static List<String> modelRequiredFieldsList = new ArrayList<>();
- private Set<String> allReqTrueKeys = new HashSet<>();
- private Set<String> allOptReqTrueKeys = new HashSet<>();
+ @Getter
private static CommonClassDao commonClassDao;
+ private Set<String> allReqTrueKeys = new HashSet<>();
+ private Set<String> allOptReqTrueKeys = new HashSet<>();
+
@Autowired
public PolicyValidation(CommonClassDao commonClassDao) {
PolicyValidation.commonClassDao = commonClassDao;
@@ -115,7 +133,6 @@ public class PolicyValidation {
// Empty constructor
}
-
/**
* Validate policy.
*
@@ -148,68 +165,64 @@ public class PolicyValidation {
}
if (!"API".equals(policyData.getApiflag()) && policyData.getAttributes() != null
- && !policyData.getAttributes().isEmpty()) {
+ && !policyData.getAttributes().isEmpty()) {
for (Object attribute : policyData.getAttributes()) {
if (attribute instanceof LinkedHashMap<?, ?>) {
- String value = null;
+ String attValue = null;
String key = null;
if (((LinkedHashMap<?, ?>) attribute).get("key") != null) {
key = ((LinkedHashMap<?, ?>) attribute).get("key").toString();
if (!PolicyUtils.policySpecialCharWithDashValidator(key).contains(SUCCESS)) {
- responseString.append("<b>Attributes or Component Attributes</b>:<i>" + value
- + SPACESINVALIDCHARS);
+ responseString.append("<b>Attributes or Component Attributes</b>:<i>" + attValue
+ + SPACESINVALIDCHARS);
valid = false;
}
} else {
if (CONFIG_POLICY.equals(policyData.getPolicyType())) {
if ("Base".equals(policyData.getConfigPolicyType())) {
- responseString
- .append("<b>Attributes</b>:<i> has one missing Attribute key</i><br>");
+ responseString.append(
+ "<b>Attributes</b>:<i> has one missing Attribute key</i><br>");
}
if (BRMSPARAM.equals(policyData.getConfigPolicyType())
- || BRMSRAW.equals(policyData.getConfigPolicyType())) {
- responseString
- .append("<b>Rule Attributes</b>:<i> has one missing Attribute key</i><br>");
+ || BRMSRAW.equals(policyData.getConfigPolicyType())) {
+ responseString.append(
+ "<b>Rule Attributes</b>:<i> has one missing Attribute key</i><br>");
}
} else {
- responseString.append(
- "<b>Component Attributes</b>:<i> has one missing Component Attribute key</i><br>");
+ responseString.append(MISSING_COMPONENT_ATTRIBUTE_KEY);
}
valid = false;
}
- if (((LinkedHashMap<?, ?>) attribute).get("value") != null) {
- value = ((LinkedHashMap<?, ?>) attribute).get("value").toString();
- if (!PolicyUtils.policySpecialCharWithDashValidator(value).contains(SUCCESS)) {
+ if (((LinkedHashMap<?, ?>) attribute).get(VALUE) != null) {
+ attValue = ((LinkedHashMap<?, ?>) attribute).get(VALUE).toString();
+ if (!PolicyUtils.policySpecialCharWithDashValidator(attValue).contains(SUCCESS)) {
if (CONFIG_POLICY.equals(policyData.getPolicyType())) {
if ("Base".equals(policyData.getConfigPolicyType())) {
- responseString.append("<b>Attributes</b>:<i>" + value
- + SPACESINVALIDCHARS);
+ responseString.append("<b>Attributes</b>:<i>" + attValue + SPACESINVALIDCHARS);
}
if (BRMSPARAM.equals(policyData.getConfigPolicyType())
- || BRMSRAW.equals(policyData.getConfigPolicyType())) {
- responseString.append("<b>Rule Attributes</b>:<i>" + value
- + SPACESINVALIDCHARS);
+ || BRMSRAW.equals(policyData.getConfigPolicyType())) {
+ responseString.append(
+ "<b>Rule Attributes</b>:<i>" + attValue + SPACESINVALIDCHARS);
}
} else {
- responseString.append("<b>Component Attributes</b>:<i>" + value
- + SPACESINVALIDCHARS);
+ responseString.append(
+ "<b>Component Attributes</b>:<i>" + attValue + SPACESINVALIDCHARS);
}
valid = false;
}
} else {
if (CONFIG_POLICY.equals(policyData.getPolicyType())) {
if ("Base".equals(policyData.getConfigPolicyType())) {
- responseString
- .append("<b>Attributes</b>:<i> has one missing Attribute value</i><br>");
+ responseString.append(
+ "<b>Attributes</b>:<i> has one missing Attribute value</i><br>");
}
if (BRMSPARAM.equals(policyData.getConfigPolicyType())
- || BRMSRAW.equals(policyData.getConfigPolicyType())) {
- responseString.append(
- "<b>Rule Attributes</b>:<i> has one missing Attribute value</i><br>");
+ || BRMSRAW.equals(policyData.getConfigPolicyType())) {
+ responseString.append(MISSING_ATTRIBUTE_VALUE);
}
} else {
- responseString.append(
- "<b>Component Attributes</b>:<i> has one missing Component Attribute value</i><br>");
+ responseString.append(MISSING_COMPONENT_ATTRIBUTE_VALUE);
}
valid = false;
}
@@ -219,25 +232,24 @@ public class PolicyValidation {
// Decision Policy Attributes Validation
if (!"API".equals(policyData.getApiflag()) && policyData.getSettings() != null
- && !policyData.getSettings().isEmpty()) {
- for (Object attribute : policyData.getAttributes()) {
+ && !policyData.getSettings().isEmpty()) {
+ for (Object attribute : policyData.getSettings()) {
if (attribute instanceof LinkedHashMap<?, ?>) {
String value = null;
if (((LinkedHashMap<?, ?>) attribute).get("key") == null) {
- responseString
- .append("<b>Settings Attributes</b>:<i> has one missing Attribute key</i><br>");
+ responseString.append(
+ "<b>Settings Attributes</b>:<i> has one missing Attribute key</i><br>");
valid = false;
}
- if (((LinkedHashMap<?, ?>) attribute).get("value") != null) {
- value = ((LinkedHashMap<?, ?>) attribute).get("value").toString();
+ if (((LinkedHashMap<?, ?>) attribute).get(VALUE) != null) {
+ value = ((LinkedHashMap<?, ?>) attribute).get(VALUE).toString();
if (!PolicyUtils.policySpecialCharValidator(value).contains(SUCCESS)) {
- responseString.append("<b>Settings Attributes</b>:<i>" + value
- + SPACESINVALIDCHARS);
+ responseString.append("<b>Settings Attributes</b>:<i>" + value + SPACESINVALIDCHARS);
valid = false;
}
} else {
- responseString
- .append("<b>Settings Attributes</b>:<i> has one missing Attribute Value</i><br>");
+ responseString.append(
+ "<b>Settings Attributes</b>:<i> has one missing Attribute Value</i><br>");
valid = false;
}
}
@@ -245,31 +257,28 @@ public class PolicyValidation {
}
if (!"API".equals(policyData.getApiflag()) && policyData.getRuleAlgorithmschoices() != null
- && !policyData.getRuleAlgorithmschoices().isEmpty()) {
+ && !policyData.getRuleAlgorithmschoices().isEmpty()) {
for (Object attribute : policyData.getRuleAlgorithmschoices()) {
if (attribute instanceof LinkedHashMap<?, ?>) {
String label = ((LinkedHashMap<?, ?>) attribute).get("id").toString();
if (((LinkedHashMap<?, ?>) attribute).get("dynamicRuleAlgorithmField1") == null) {
- responseString.append(
- "<b>Rule Algorithms</b>:<i>" + label + " : Field 1 value is not selected</i><br>");
+ responseString.append(RULE_ALGORITHMS + label + " : Field 1 value is not selected</i><br>");
valid = false;
}
if (((LinkedHashMap<?, ?>) attribute).get("dynamicRuleAlgorithmCombo") == null) {
- responseString.append(
- "<b>Rule Algorithms</b>:<i>" + label + " : Field 2 value is not selected</i><br>");
+ responseString.append(RULE_ALGORITHMS + label + " : Field 2 value is not selected</i><br>");
valid = false;
}
if (((LinkedHashMap<?, ?>) attribute).get("dynamicRuleAlgorithmField2") != null) {
- String value =
- ((LinkedHashMap<?, ?>) attribute).get("dynamicRuleAlgorithmField2").toString();
+ String value = ((LinkedHashMap<?, ?>) attribute).get("dynamicRuleAlgorithmField2")
+ .toString();
if (!PolicyUtils.policySpecialCharValidator(value).contains(SUCCESS)) {
- responseString.append("<b>Rule Algorithms</b>:<i>" + label
- + " : Field 3 value has special characters</i><br>");
+ responseString.append(RULE_ALGORITHMS + label
+ + " : Field 3 value has special characters</i><br>");
valid = false;
}
} else {
- responseString
- .append("<b>Rule Algorithms</b>:<i>" + label + " : Field 3 value is empty</i><br>");
+ responseString.append(RULE_ALGORITHMS + label + " : Field 3 value is empty</i><br>");
valid = false;
}
}
@@ -278,14 +287,15 @@ public class PolicyValidation {
if (CONFIG_POLICY.equalsIgnoreCase(policyData.getPolicyType())) {
if ("Base".equals(policyData.getConfigPolicyType())
- || CLOSEDLOOP_POLICY.equals(policyData.getConfigPolicyType())
- || CLOSEDLOOP_PM.equals(policyData.getConfigPolicyType())
- || ENFORCER_CONFIG_POLICY.equals(policyData.getConfigPolicyType())
- || MICROSERVICES.equals(policyData.getConfigPolicyType())
- || OPTIMIZATION.equals(policyData.getConfigPolicyType())) {
+ || CLOSEDLOOP_POLICY.equals(policyData.getConfigPolicyType())
+ || CLOSEDLOOP_PM.equals(policyData.getConfigPolicyType())
+ || ENFORCER_CONFIG_POLICY.equals(policyData.getConfigPolicyType())
+ || MICROSERVICES.equals(policyData.getConfigPolicyType())
+ || OPTIMIZATION.equals(policyData.getConfigPolicyType())) {
if (!Strings.isNullOrEmpty(policyData.getOnapName())) {
- String onapNameValidate = PolicyUtils.policySpecialCharWithDashValidator(policyData.getOnapName());
+ String onapNameValidate = PolicyUtils
+ .policySpecialCharWithDashValidator(policyData.getOnapName());
if (!onapNameValidate.contains(SUCCESS)) {
responseString.append("<b>OnapName</b>:<i>" + onapNameValidate + HTML_ITALICS_LNBREAK);
valid = false;
@@ -357,26 +367,22 @@ public class PolicyValidation {
if (configType != null) {
if ("JSON".equals(configType)) {
if (!PolicyUtils.isJSONValid(configBodyData)) {
- responseString
- .append("Config Body: JSON Content is not valid" + HTML_ITALICS_LNBREAK);
+ responseString.append(
+ "Config Body: JSON Content is not valid" + HTML_ITALICS_LNBREAK);
valid = false;
}
} else if ("XML".equals(configType)) {
if (!PolicyUtils.isXMLValid(configBodyData)) {
- responseString.append(
- "Config Body: XML Content data is not valid" + HTML_ITALICS_LNBREAK);
+ responseString.append("Config Body: XML Content data is not valid"
+ + HTML_ITALICS_LNBREAK);
valid = false;
}
} else if ("PROPERTIES".equals(configType)) {
- if (!PolicyUtils.isPropValid(configBodyData) || "".equals(configBodyData)) {
- responseString
- .append("Config Body: Property data is not valid" + HTML_ITALICS_LNBREAK);
+ if (!PolicyUtils.isPropValid(configBodyData)) {
+ responseString.append(
+ "Config Body: Property data is not valid" + HTML_ITALICS_LNBREAK);
valid = false;
}
- } else if ("OTHER".equals(configType) && ("".equals(configBodyData))) {
- responseString
- .append("Config Body: Config Body Should not be Empty" + HTML_ITALICS_LNBREAK);
- valid = false;
}
}
} else {
@@ -397,14 +403,14 @@ public class PolicyValidation {
valid = false;
}
if (policyData.getSecurityZone() == null || policyData.getSecurityZone().isEmpty()) {
- responseString
- .append("<b>Security Zone</b>:<i> Security Zone is required" + HTML_ITALICS_LNBREAK);
+ responseString.append(
+ "<b>Security Zone</b>:<i> Security Zone is required" + HTML_ITALICS_LNBREAK);
valid = false;
}
}
// Validate BRMS_Param Policy Data
if (BRMSPARAM.equalsIgnoreCase(policyData.getConfigPolicyType())
- && Strings.isNullOrEmpty(policyData.getRuleName())) {
+ && Strings.isNullOrEmpty(policyData.getRuleName())) {
responseString.append("<b>BRMS Template</b>:<i>BRMS Template is required" + HTML_ITALICS_LNBREAK);
valid = false;
}
@@ -415,8 +421,8 @@ public class PolicyValidation {
// If there are any error other than Annotations then this is not Valid
if (message.contains("[ERR")) {
- responseString.append(
- "<b>Raw Rule Validate</b>:<i>Raw Rule has error" + message + HTML_ITALICS_LNBREAK);
+ responseString.append("<b>Raw Rule Validate</b>:<i>Raw Rule has error" + message
+ + HTML_ITALICS_LNBREAK);
valid = false;
}
} else {
@@ -427,17 +433,17 @@ public class PolicyValidation {
// Validate ClosedLoop_PM Policy Data
if (CLOSEDLOOP_PM.equalsIgnoreCase(policyData.getConfigPolicyType())) {
try {
- if (Strings.isNullOrEmpty(
- policyData.getServiceTypePolicyName().get("serviceTypePolicyName").toString())) {
+ if (Strings.isNullOrEmpty(policyData.getServiceTypePolicyName().get("serviceTypePolicyName")
+ .toString())) {
responseString.append("<b>ServiceType PolicyName</b>:<i>ServiceType PolicyName is required"
- + HTML_ITALICS_LNBREAK);
+ + HTML_ITALICS_LNBREAK);
valid = false;
}
} catch (Exception e) {
LOGGER.error("ERROR in ClosedLoop_PM PolicyName", e);
responseString.append("<b>ServiceType PolicyName</b>:<i>ServiceType PolicyName is required"
- + HTML_ITALICS_LNBREAK);
+ + HTML_ITALICS_LNBREAK);
valid = false;
}
@@ -451,11 +457,9 @@ public class PolicyValidation {
valid = false;
}
}
- if ((pmBody.isGamma() || pmBody.isMcr() || pmBody.isTrinity() || pmBody.isvDNS()
- || pmBody.isvUSP()) != true) {
- responseString
- .append("<b>D2/Virtualized Services</b>: <i>Select at least one D2/Virtualized Services"
- + HTML_ITALICS_LNBREAK);
+ if (!pmBody.isGamma() && !pmBody.isMcr() && !pmBody.isTrinity() && !pmBody.isvDNS()
+ && !pmBody.isvUSP()) {
+ responseString.append(SELECT_AT_LEAST_ONE_D2_VIRTUALIZED_SERVICES + HTML_ITALICS_LNBREAK);
valid = false;
}
if (pmBody.getGeoLink() != null && !pmBody.getGeoLink().isEmpty()) {
@@ -473,16 +477,17 @@ public class PolicyValidation {
String attributeValidate = PolicyUtils.policySpecialCharValidator(value);
if (!attributeValidate.contains(SUCCESS)) {
responseString.append("<b>Attributes</b>:<i>" + key
- + " : value has spaces or invalid characters" + HTML_ITALICS_LNBREAK);
+ + " : value has spaces or invalid characters"
+ + HTML_ITALICS_LNBREAK);
valid = false;
}
}
}
}
} else {
- responseString
- .append("<b>D2/Virtualized Services</b>:<i>Select atleast one D2/Virtualized Services"
- + HTML_ITALICS_LNBREAK);
+ responseString.append(
+ "<b>D2/Virtualized Services</b>:<i>Select at least one D2/Virtualized Services"
+ + HTML_ITALICS_LNBREAK);
valid = false;
}
}
@@ -497,38 +502,40 @@ public class PolicyValidation {
String apiCondition = (String) json.get("conditions");
if (Strings.isNullOrEmpty(apiCondition)) {
responseString.append("<b>Conditions</b>: <i>Select At least one Condition"
- + HTML_ITALICS_LNBREAK);
+ + HTML_ITALICS_LNBREAK);
return responseString;
}
} else {
- responseString
- .append("<b>Conditions</b>: <i>There were no conditions provided in configBody json"
- + HTML_ITALICS_LNBREAK);
+ responseString.append("<b>Conditions</b>:"
+ + " <i>There were no conditions provided in configBody json"
+ + HTML_ITALICS_LNBREAK);
return responseString;
}
} else {
if (policyData.getTrapDatas().getTrap1() != null) {
if (policyData.getClearTimeOut() == null) {
- responseString.append(
- "<b>Trigger Clear TimeOut</b>: <i>Trigger Clear TimeOut is required when atleast One Trigger Signature is enabled</i><br>");
+ responseString.append("<b>Trigger Clear TimeOut</b>: "
+ + "<i>Trigger Clear TimeOut is required when at "
+ + "least One Trigger Signature is enabled</i><br>");
valid = false;
}
if (policyData.getTrapMaxAge() == null) {
- responseString.append(
- "<b>Trap Max Age</b>: <i>Trap Max Age is required when atleast One Trigger Signature is enabled</i><br>");
+ responseString.append("<b>Trap Max Age</b>: <i>Trap Max Age is required when at "
+ + "least One Trigger Signature is enabled</i><br>");
valid = false;
}
}
if (policyData.getFaultDatas().getTrap1() != null
- && policyData.getVerificationclearTimeOut() == null) {
+ && policyData.getVerificationclearTimeOut() == null) {
responseString.append(
- "<b>Fault Clear TimeOut</b>: <i>Fault Clear TimeOut is required when atleast One Fault Signature is enabled</i><br>");
+ "<b>Fault Clear TimeOut</b>: <i>Fault Clear TimeOut is required when at"
+ + "least One Fault Signature is enabled</i><br>");
valid = false;
}
}
- ClosedLoopFaultBody faultBody =
- mapper.readValue(policyData.getJsonBody(), ClosedLoopFaultBody.class);
+ ClosedLoopFaultBody faultBody = mapper.readValue(policyData.getJsonBody(),
+ ClosedLoopFaultBody.class);
if (faultBody.getEmailAddress() != null && !faultBody.getEmailAddress().isEmpty()) {
String result = emailValidation(faultBody.getEmailAddress(), responseString.toString());
if (!SUCCESS.equals(result)) {
@@ -537,26 +544,24 @@ public class PolicyValidation {
}
}
if (!(faultBody.isGamma() || faultBody.isMcr() || faultBody.isTrinity() || faultBody.isvDNS()
- || faultBody.isvUSP())) {
- responseString
- .append("<b>D2/Virtualized Services</b>: <i>Select at least one D2/Virtualized Services"
- + HTML_ITALICS_LNBREAK);
+ || faultBody.isvUSP())) {
+ responseString.append(SELECT_AT_LEAST_ONE_D2_VIRTUALIZED_SERVICES + HTML_ITALICS_LNBREAK);
valid = false;
}
if (faultBody.getActions() == null || faultBody.getActions().isEmpty()) {
- responseString
- .append("<b>vPRO Actions</b>: <i>vPRO Actions is required" + HTML_ITALICS_LNBREAK);
+ responseString.append(
+ "<b>vPRO Actions</b>: <i>vPRO Actions is required" + HTML_ITALICS_LNBREAK);
valid = false;
}
if (faultBody.getClosedLoopPolicyStatus() == null
- || faultBody.getClosedLoopPolicyStatus().isEmpty()) {
- responseString.append(
- "<b>Policy Status</b>: <i>Policy Status is required" + HTML_ITALICS_LNBREAK);
+ || faultBody.getClosedLoopPolicyStatus().isEmpty()) {
+ responseString.append("<b>Policy Status</b>: <i>Policy Status is required"
+ + HTML_ITALICS_LNBREAK);
valid = false;
}
if (faultBody.getConditions() == null) {
- responseString.append(
- "<b>Conditions</b>: <i>Select At least one Condition" + HTML_ITALICS_LNBREAK);
+ responseString.append("<b>Conditions</b>: <i>Select At least one Condition"
+ + HTML_ITALICS_LNBREAK);
valid = false;
}
if (faultBody.getGeoLink() != null && !faultBody.getGeoLink().isEmpty()) {
@@ -567,28 +572,28 @@ public class PolicyValidation {
}
}
if (faultBody.getAgingWindow() == 0) {
- responseString
- .append("<b>Aging Window</b>: <i>Aging Window is required" + HTML_ITALICS_LNBREAK);
+ responseString.append(
+ "<b>Aging Window</b>: <i>Aging Window is required" + HTML_ITALICS_LNBREAK);
valid = false;
}
if (faultBody.getTimeInterval() == 0) {
- responseString.append(
- "<b>Time Interval</b>: <i>Time Interval is required" + HTML_ITALICS_LNBREAK);
+ responseString.append("<b>Time Interval</b>: <i>Time Interval is required"
+ + HTML_ITALICS_LNBREAK);
valid = false;
}
if (faultBody.getRetrys() == 0) {
responseString.append("<b>Number of Retries</b>: <i>Number of Retries is required"
- + HTML_ITALICS_LNBREAK);
+ + HTML_ITALICS_LNBREAK);
valid = false;
}
if (faultBody.getTimeOutvPRO() == 0) {
- responseString.append(
- "<b>APP-C Timeout</b>: <i>APP-C Timeout is required" + HTML_ITALICS_LNBREAK);
+ responseString.append("<b>APP-C Timeout</b>: <i>APP-C Timeout is required"
+ + HTML_ITALICS_LNBREAK);
valid = false;
}
if (faultBody.getTimeOutRuby() == 0) {
- responseString
- .append("<b>TimeOutRuby</b>: <i>TimeOutRuby is required" + HTML_ITALICS_LNBREAK);
+ responseString.append(
+ "<b>TimeOutRuby</b>: <i>TimeOutRuby is required" + HTML_ITALICS_LNBREAK);
valid = false;
}
if (faultBody.getVnfType() == null || faultBody.getVnfType().isEmpty()) {
@@ -596,31 +601,31 @@ public class PolicyValidation {
valid = false;
}
} else {
- responseString
- .append("<b>D2/Virtualized Services</b>: <i>Select atleast one D2/Virtualized Services"
- + HTML_ITALICS_LNBREAK);
- responseString
- .append("<b>vPRO Actions</b>: <i>vPRO Actions is required" + HTML_ITALICS_LNBREAK);
- responseString
- .append("<b>Aging Window</b>: <i>Aging Window is required" + HTML_ITALICS_LNBREAK);
- responseString
- .append("<b>Policy Status</b>: <i>Policy Status is required" + HTML_ITALICS_LNBREAK);
- responseString
- .append("<b>Conditions</b>: <i>Select Atleast one Condition" + HTML_ITALICS_LNBREAK);
+ responseString.append(
+ "<b>D2/Virtualized Services</b>: <i>Select at least one D2/Virtualized Services"
+ + HTML_ITALICS_LNBREAK);
+ responseString.append(
+ "<b>vPRO Actions</b>: <i>vPRO Actions is required" + HTML_ITALICS_LNBREAK);
+ responseString.append(
+ "<b>Aging Window</b>: <i>Aging Window is required" + HTML_ITALICS_LNBREAK);
+ responseString.append(
+ "<b>Policy Status</b>: <i>Policy Status is required" + HTML_ITALICS_LNBREAK);
+ responseString.append(
+ "<b>Conditions</b>: <i>Select Atleast one Condition" + HTML_ITALICS_LNBREAK);
responseString.append("<b>PEP Name</b>: <i>PEP Name is required" + HTML_ITALICS_LNBREAK);
responseString.append("<b>PEP Action</b>: <i>PEP Action is required" + HTML_ITALICS_LNBREAK);
- responseString
- .append("<b>Time Interval</b>: <i>Time Interval is required" + HTML_ITALICS_LNBREAK);
responseString.append(
- "<b>Number of Retries</b>: <i>Number of Retries is required" + HTML_ITALICS_LNBREAK);
- responseString
- .append("<b>APP-C Timeout</b>: <i>APP-C Timeout is required" + HTML_ITALICS_LNBREAK);
+ "<b>Time Interval</b>: <i>Time Interval is required" + HTML_ITALICS_LNBREAK);
+ responseString.append("<b>Number of Retries</b>: <i>Number of Retries is required"
+ + HTML_ITALICS_LNBREAK);
+ responseString.append(
+ "<b>APP-C Timeout</b>: <i>APP-C Timeout is required" + HTML_ITALICS_LNBREAK);
responseString.append("<b>TimeOutRuby</b>: <i>TimeOutRuby is required" + HTML_ITALICS_LNBREAK);
responseString.append("<b>Vnf Type</b>: <i>Vnf Type is required" + HTML_ITALICS_LNBREAK);
valid = false;
}
}
-
+
// Validate MicroService Policy Data
if (MICROSERVICES.equals(policyData.getConfigPolicyType())) {
boolean tmpValid = validateMsModel(policyData, responseString);
@@ -630,7 +635,7 @@ public class PolicyValidation {
}
// Validate Optimization Policy Data
- if (OPTIMIZATION.equals(policyData.getConfigPolicyType())){
+ if (OPTIMIZATION.equals(policyData.getConfigPolicyType())) {
boolean tmpValid = validateOptimization(policyData, responseString);
if (!tmpValid) {
valid = false;
@@ -639,7 +644,7 @@ public class PolicyValidation {
}
if ((DECISION_POLICY.equalsIgnoreCase(policyData.getPolicyType()))
- || (DECISION_POLICY_MS.equalsIgnoreCase(policyData.getPolicyType()))) {
+ || (DECISION_POLICY_MS.equalsIgnoreCase(policyData.getPolicyType()))) {
if (!RAW.equalsIgnoreCase(policyData.getRuleProvider())) {
if (!Strings.isNullOrEmpty(policyData.getOnapName())) {
String onapNameValidate = PolicyUtils.policySpecialCharValidator(policyData.getOnapName());
@@ -653,7 +658,8 @@ public class PolicyValidation {
}
}
if (RAW.equalsIgnoreCase(policyData.getRuleProvider())) {
- Object policy = XACMLPolicyScanner.readPolicy(new ByteArrayInputStream(StringEscapeUtils.unescapeXml(policyData.getRawXacmlPolicy()).getBytes(StandardCharsets.UTF_8)));
+ Object policy = XACMLPolicyScanner.readPolicy(new ByteArrayInputStream(StringEscapeUtils
+ .unescapeXml(policyData.getRawXacmlPolicy()).getBytes(StandardCharsets.UTF_8)));
if (!(policy instanceof PolicySetType || policy instanceof PolicyType)) {
responseString.append("Raw XACML: The XACML Content is not valid" + HTML_ITALICS_LNBREAK);
valid = false;
@@ -690,7 +696,7 @@ public class PolicyValidation {
valid = false;
}
if (!policyData.getRainyday().getTreatmentTableChoices().isEmpty()
- && policyData.getRainyday().getTreatmentTableChoices() != null) {
+ && policyData.getRainyday().getTreatmentTableChoices() != null) {
for (Object treatmentMap : policyData.getRainyday().getTreatmentTableChoices()) {
String errorCode = null;
@@ -706,20 +712,20 @@ public class PolicyValidation {
}
if (Strings.isNullOrEmpty(errorCode) && Strings.isNullOrEmpty(treatment)) {
- responseString.append(
- "Rainy Day <b>Error Code</b> and <b>Desired Treatment</b> cannot be empty<br>");
+ responseString.append("Rainy Day <b>Error Code</b> and "
+ + "<b>Desired Treatment</b> cannot be empty<br>");
valid = false;
break;
}
if (Strings.isNullOrEmpty(errorCode)) {
- responseString.append(
- "Rainy Day <b>Error Code</b> is Required for each Desired Treatment<br>");
+ responseString.append("Rainy Day <b>Error Code</b> is Required "
+ + "for each Desired Treatment<br>");
valid = false;
break;
}
if (Strings.isNullOrEmpty(treatment)) {
- responseString.append(
- "Rainy Day <b>Desired Treatment</b> is Required for each Error Code<br>");
+ responseString.append("Rainy Day <b>Desired Treatment"
+ + "</b> is Required for each Error Code<br>");
valid = false;
break;
}
@@ -733,8 +739,8 @@ public class PolicyValidation {
}
if ("GUARD_YAML".equals(policyData.getRuleProvider())
- || "GUARD_BL_YAML".equals(policyData.getRuleProvider())
- || "GUARD_MIN_MAX".equals(policyData.getRuleProvider())) {
+ || "GUARD_BL_YAML".equals(policyData.getRuleProvider())
+ || "GUARD_MIN_MAX".equals(policyData.getRuleProvider())) {
if (policyData.getYamlparams() == null) {
responseString.append("<b> Guard Params are Required </b>" + HTML_ITALICS_LNBREAK);
valid = false;
@@ -748,13 +754,13 @@ public class PolicyValidation {
valid = false;
}
if (Strings.isNullOrEmpty(policyData.getYamlparams().getGuardActiveStart())) {
- responseString.append(
- "Guard Params <b>Guard Active Start</b> is Required " + HTML_ITALICS_LNBREAK);
+ responseString.append("Guard Params <b>Guard Active Start</b> is Required "
+ + HTML_ITALICS_LNBREAK);
valid = false;
}
if (Strings.isNullOrEmpty(policyData.getYamlparams().getGuardActiveEnd())) {
- responseString
- .append("Guard Params <b>Guard Active End</b> is Required " + HTML_ITALICS_LNBREAK);
+ responseString.append(
+ "Guard Params <b>Guard Active End</b> is Required " + HTML_ITALICS_LNBREAK);
valid = false;
}
if ("GUARD_YAML".equals(policyData.getRuleProvider())) {
@@ -762,22 +768,22 @@ public class PolicyValidation {
responseString.append(" Guard Params <b>Limit</b> is Required " + HTML_ITALICS_LNBREAK);
valid = false;
} else if (!PolicyUtils.isInteger(policyData.getYamlparams().getLimit())) {
- responseString
- .append(" Guard Params <b>Limit</b> Should be Integer " + HTML_ITALICS_LNBREAK);
+ responseString.append(
+ " Guard Params <b>Limit</b> Should be Integer " + HTML_ITALICS_LNBREAK);
valid = false;
}
if (Strings.isNullOrEmpty(policyData.getYamlparams().getTimeWindow())) {
- responseString
- .append("Guard Params <b>Time Window</b> is Required" + HTML_ITALICS_LNBREAK);
+ responseString.append(
+ "Guard Params <b>Time Window</b> is Required" + HTML_ITALICS_LNBREAK);
valid = false;
} else if (!PolicyUtils.isInteger(policyData.getYamlparams().getTimeWindow())) {
- responseString.append(
- " Guard Params <b>Time Window</b> Should be Integer " + HTML_ITALICS_LNBREAK);
+ responseString.append(" Guard Params <b>Time Window</b> Should be Integer "
+ + HTML_ITALICS_LNBREAK);
valid = false;
}
if (Strings.isNullOrEmpty(policyData.getYamlparams().getTimeUnits())) {
- responseString
- .append("Guard Params <b>Time Units</b> is Required" + HTML_ITALICS_LNBREAK);
+ responseString.append(
+ "Guard Params <b>Time Units</b> is Required" + HTML_ITALICS_LNBREAK);
valid = false;
}
} else if ("GUARD_MIN_MAX".equals(policyData.getRuleProvider())) {
@@ -785,32 +791,32 @@ public class PolicyValidation {
responseString.append(" Guard Params <b>Min</b> is Required " + HTML_ITALICS_LNBREAK);
valid = false;
} else if (!PolicyUtils.isInteger(policyData.getYamlparams().getMin())) {
- responseString
- .append(" Guard Params <b>Min</b> Should be Integer " + HTML_ITALICS_LNBREAK);
+ responseString.append(
+ " Guard Params <b>Min</b> Should be Integer " + HTML_ITALICS_LNBREAK);
valid = false;
}
if (Strings.isNullOrEmpty(policyData.getYamlparams().getMax())) {
responseString.append(" Guard Params <b>Max</b> is Required " + HTML_ITALICS_LNBREAK);
valid = false;
} else if (!PolicyUtils.isInteger(policyData.getYamlparams().getMax())) {
- responseString
- .append(" Guard Params <b>Max</b> Should be Integer " + HTML_ITALICS_LNBREAK);
+ responseString.append(
+ " Guard Params <b>Max</b> Should be Integer " + HTML_ITALICS_LNBREAK);
valid = false;
}
} else if ("GUARD_BL_YAML".equals(policyData.getRuleProvider())
- && "Use Manual Entry".equals(policyData.getBlackListEntryType())) {
+ && "Use Manual Entry".equals(policyData.getBlackListEntryType())) {
if (policyData.getYamlparams().getBlackList() == null
- || policyData.getYamlparams().getBlackList().isEmpty()) {
- responseString
- .append(" Guard Params <b>BlackList</b> is Required " + HTML_ITALICS_LNBREAK);
+ || policyData.getYamlparams().getBlackList().isEmpty()) {
+ responseString.append(
+ " Guard Params <b>BlackList</b> is Required " + HTML_ITALICS_LNBREAK);
valid = false;
} else {
for (String blackList : policyData.getYamlparams().getBlackList()) {
- if (blackList == null
- || !(SUCCESS.equals(PolicyUtils.policySpecialCharValidator(blackList)))) {
+ if (blackList == null || !(SUCCESS
+ .equals(PolicyUtils.policySpecialCharValidator(blackList)))) {
responseString.append(" Guard Params <b>BlackList</b> Should be valid String"
- + HTML_ITALICS_LNBREAK);
+ + HTML_ITALICS_LNBREAK);
valid = false;
break;
}
@@ -829,21 +835,21 @@ public class PolicyValidation {
valid = false;
}
} else {
- responseString.append(
- "<b>ActionPerformer</b>:<i> ActionPerformer Should not be empty" + HTML_ITALICS_LNBREAK);
+ responseString.append("<b>ActionPerformer</b>:<i> ActionPerformer Should not be empty"
+ + HTML_ITALICS_LNBREAK);
valid = false;
}
if (!Strings.isNullOrEmpty(policyData.getActionAttributeValue())) {
- String actionAttribute =
- PolicyUtils.policySpecialCharValidator(policyData.getActionAttributeValue());
+ String actionAttribute = PolicyUtils
+ .policySpecialCharValidator(policyData.getActionAttributeValue());
if (!actionAttribute.contains(SUCCESS)) {
responseString.append("<b>ActionAttribute</b>:<i>" + actionAttribute + HTML_ITALICS_LNBREAK);
valid = false;
}
} else {
- responseString.append(
- "<b>ActionAttribute</b>:<i> ActionAttribute Should not be empty" + HTML_ITALICS_LNBREAK);
+ responseString.append("<b>ActionAttribute</b>:<i> ActionAttribute Should not be empty"
+ + HTML_ITALICS_LNBREAK);
valid = false;
}
}
@@ -853,7 +859,7 @@ public class PolicyValidation {
if (valid) {
if (commonClassDao != null) {
List<Object> spData = commonClassDao.getDataById(SafePolicyWarning.class, "riskType",
- policyData.getRiskType());
+ policyData.getRiskType());
if (!spData.isEmpty()) {
SafePolicyWarning safePolicyWarningData = (SafePolicyWarning) spData.get(0);
value = "<b>Message</b>:<i>" + safePolicyWarningData.getMessage() + "</i>";
@@ -874,7 +880,7 @@ public class PolicyValidation {
}
}
- protected String emailValidation(String email, String response) {
+ private String emailValidation(String email, String response) {
String res = response;
if (email != null) {
String validateEmail = PolicyUtils.validateEmailAddress(email.replace("\"", ""));
@@ -890,14 +896,14 @@ public class PolicyValidation {
private MicroServiceModels getAttributeObject(String name, String version) {
MicroServiceModels workingModel = null;
try {
- List<Object> microServiceModelsData =
- commonClassDao.getDataById(MicroServiceModels.class, "modelName:version", name + ":" + version);
+ List<Object> microServiceModelsData = commonClassDao.getDataById(MicroServiceModels.class,
+ "modelName:version", name + ":" + version);
if (microServiceModelsData != null) {
workingModel = (MicroServiceModels) microServiceModelsData.get(0);
}
} catch (Exception e) {
String message = XACMLErrorConstants.ERROR_DATA_ISSUE + "Invalid Template. The template name, " + name
- + " was not found in the dictionary: ";
+ + " was not found in the dictionary: ";
LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + message + e);
return null;
}
@@ -905,16 +911,17 @@ public class PolicyValidation {
return workingModel;
}
- private OptimizationModels getOptimizationModelData(String name, String version) {
+ private OptimizationModels getOptimizationModelData(String name, String version) {
OptimizationModels workingModel = null;
- try{
- List<Object> optimizationModelsData = commonClassDao.getDataById(OptimizationModels.class, "modelName:version", name+":"+version);
- if(optimizationModelsData != null){
+ try {
+ List<Object> optimizationModelsData = commonClassDao.getDataById(OptimizationModels.class,
+ "modelName:version", name + ":" + version);
+ if (optimizationModelsData != null) {
workingModel = (OptimizationModels) optimizationModelsData.get(0);
}
- }catch(Exception e){
- String message = XACMLErrorConstants.ERROR_DATA_ISSUE + "Invalid Template. The template name, "
- + name + " was not found in the dictionary: ";
+ } catch (Exception e) {
+ String message = XACMLErrorConstants.ERROR_DATA_ISSUE + "Invalid Template. The template name, " + name
+ + " was not found in the dictionary: ";
LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + message + e);
return null;
}
@@ -933,8 +940,9 @@ public class PolicyValidation {
pullJsonKeyPairs(value); // RECURSIVE CALL
} else {
if (value.isArray()) {
- String newValue = StringUtils.replaceEach(value.toString(), new String[] {"[", "]", "\""},
- new String[] {"", "", ""});
+ String newValue = StringUtils.replaceEach(value.toString(), new String[]
+ { "[", "]", "\"" }, new String[]
+ { "", "", "" });
mapAttribute.put(key, newValue);
} else {
mapAttribute.put(key, value.toString().trim());
@@ -958,11 +966,11 @@ public class PolicyValidation {
try {
String valueStr = value.toString();
String stringValue = valueStr.substring(valueStr.indexOf('[') + 1, valueStr.lastIndexOf(']'));
-
+
if (stringValue.isEmpty()) {
stringValue = "{\"test\":\"test\"}";
}
-
+
ObjectMapper mapper = new ObjectMapper();
JsonNode newValue = mapper.readTree(stringValue);
jsonRequestMap.put(key.trim(), value.toString().trim());
@@ -981,10 +989,9 @@ public class PolicyValidation {
try (JsonReader jsonReader = Json.createReader(new StringReader(value))) {
return jsonReader.readObject();
} catch (JsonException | IllegalStateException e) {
- LOGGER.info(
- XACMLErrorConstants.ERROR_DATA_ISSUE
- + "Improper JSON format... may or may not cause issues in validating the policy: " + value,
- e);
+ LOGGER.info(XACMLErrorConstants.ERROR_DATA_ISSUE
+ + "Improper JSON format... may or may not cause issues in validating the policy: " + value,
+ e);
return null;
}
}
@@ -1044,13 +1051,13 @@ public class PolicyValidation {
if (obj instanceof String && ((String) obj).contains(REQUIRED_ATTRIBUTE)) {
LOGGER.debug("key : " + key);
LOGGER.debug("obj : " + obj);
- allReqTrueKeys.add(key); //For MicroService policies
- allOptReqTrueKeys.add(key); //For Optimization policies
-
+ allReqTrueKeys.add(key); // For MicroService policies
+ allOptReqTrueKeys.add(key); // For Optimization policies
+
// get the type from value and add that one also
String type = StringUtils.substringBefore((String) obj, ":");
- if (!StringUtils.isBlank(type) && !StringUtils.containsAny(type.toLowerCase(), MSModelUtils.STRING,
- MSModelUtils.INTEGER, MSModelUtils.LIST, MSModelUtils.MAP, "java", "boolean")) {
+ if (!StringUtils.isBlank(type) && !StringUtils.containsAny(type.toLowerCase(), STRING, INTEGER, LIST,
+ MAP, JAVA, BOOLEAN)) {
allReqTrueKeys.add(type);
}
}
@@ -1066,7 +1073,7 @@ public class PolicyValidation {
}
private boolean validateMsModel(PolicyRestAdapter policyData, StringBuilder responseString)
- throws JsonProcessingException {
+ throws JsonProcessingException {
boolean valid = true;
if (!Strings.isNullOrEmpty(policyData.getServiceType())) {
@@ -1089,8 +1096,8 @@ public class PolicyValidation {
if (returnModel != null) {
String annotation = returnModel.getAnnotation();
- String refAttributes = returnModel.getRef_attributes();
- String subAttributes = returnModel.getSub_attributes();
+ String refAttributes = returnModel.getRefAttributes();
+ String subAttributes = returnModel.getSubAttributes();
String modelAttributes = returnModel.getAttributes();
if (!Strings.isNullOrEmpty(annotation)) {
@@ -1102,7 +1109,7 @@ public class PolicyValidation {
int startNum = Integer.parseInt(tempString[0]);
int endNum = Integer.parseInt(tempString[1]);
String returnString = "InvalidreturnModel Range:" + raMap.getKey() + " must be between "
- + startNum + " - " + endNum + ",";
+ + startNum + " - " + endNum + ",";
if (value != null) {
if (PolicyUtils.isInteger(value.replace("\"", ""))) {
@@ -1117,8 +1124,8 @@ public class PolicyValidation {
}
} else {
responseString.append("<b>" + raMap.getKey() + "</b>:<i>" + raMap.getKey()
- + " is required for the MicroService model " + service
- + HTML_ITALICS_LNBREAK);
+ + " is required for the MicroService model " + service
+ + HTML_ITALICS_LNBREAK);
valid = false;
}
@@ -1129,26 +1136,26 @@ public class PolicyValidation {
// model
if (Strings.isNullOrEmpty(policyData.getLocation())) {
responseString.append("<b>Micro Service Model</b>:<i> location is required for this model"
- + HTML_ITALICS_LNBREAK);
+ + HTML_ITALICS_LNBREAK);
valid = false;
}
if (Strings.isNullOrEmpty(policyData.getConfigName())) {
responseString.append("<b>Micro Service Model</b>:<i> configName is required for this model"
- + HTML_ITALICS_LNBREAK);
+ + HTML_ITALICS_LNBREAK);
valid = false;
}
if (Strings.isNullOrEmpty(policyData.getUuid())) {
responseString.append("<b>Micro Service Model</b>:<i> uuid is required for this model"
- + HTML_ITALICS_LNBREAK);
+ + HTML_ITALICS_LNBREAK);
valid = false;
}
-
+
if (Strings.isNullOrEmpty(policyData.getPolicyScope())) {
- responseString
- .append("<b>Micro Service Model</b>:<i> policyScope is required for this model"
- + HTML_ITALICS_LNBREAK);
+ responseString.append(
+ "<b>Micro Service Model</b>:<i> policyScope is required for this model"
+ + HTML_ITALICS_LNBREAK);
valid = false;
}
}
@@ -1157,11 +1164,12 @@ public class PolicyValidation {
// GUI request are already validated from the SDK-APP
if ("API".equals(policyData.getApiflag())) {
// first , get the complete set of required fields
- populateReqFieldSet(new String[] {refAttributes, modelAttributes}, subAttributes);
+ populateReqFieldSet(new String[]
+ { refAttributes, modelAttributes }, subAttributes);
// ignore req fields in which parent is not reqd
- populateRequiredFields(new String[] {refAttributes, modelAttributes}, subAttributes,
- modelAttributes);
+ populateRequiredFields(new String[]
+ { refAttributes, modelAttributes }, subAttributes, modelAttributes);
if (modelRequiredFieldsList != null && !modelRequiredFieldsList.isEmpty()) {
// create jsonRequestMap with all json keys and values from request
@@ -1175,12 +1183,12 @@ public class PolicyValidation {
String value = jsonRequestMap.get(requiredField);
if (StringUtils.isBlank(value) || "\"\"".equals(value)) {
responseString.append("<b>Micro Service Model</b>:<i> " + requiredField
- + ISREQUIRED + HTML_ITALICS_LNBREAK);
+ + ISREQUIRED + HTML_ITALICS_LNBREAK);
valid = false;
}
} else {
- responseString.append("<b>Micro Service Model</b>:<i> " + requiredField
- + ISREQUIRED + HTML_ITALICS_LNBREAK);
+ responseString.append("<b>Micro Service Model</b>:<i> " + requiredField + ISREQUIRED
+ + HTML_ITALICS_LNBREAK);
valid = false;
}
}
@@ -1188,12 +1196,13 @@ public class PolicyValidation {
}
} else {
responseString.append("<b>Micro Service Model</b>:<i> Invalid Model. The model name, " + service
- + " of version, " + version + " was not found in the dictionary" + HTML_ITALICS_LNBREAK);
+ + " of version, " + version + " was not found in the dictionary"
+ + HTML_ITALICS_LNBREAK);
valid = false;
}
} else {
- responseString.append(
- "<b>Micro Service Version</b>:<i> Micro Service Version is required" + HTML_ITALICS_LNBREAK);
+ responseString.append("<b>Micro Service Version</b>:<i> Micro Service Version is required"
+ + HTML_ITALICS_LNBREAK);
valid = false;
}
} else {
@@ -1202,28 +1211,26 @@ public class PolicyValidation {
}
if (Strings.isNullOrEmpty(policyData.getPriority())
- && !DECISION_MS_MODEL.equals(policyData.getRuleProvider())) {
+ && !DECISION_MS_MODEL.equals(policyData.getRuleProvider())) {
responseString.append("<b>Priority</b>:<i> Priority is required" + HTML_ITALICS_LNBREAK);
}
-
return valid;
}
-
+
private boolean validateOptimization(PolicyRestAdapter policyData, StringBuilder responseString) {
boolean valid = true;
-
+
// Checks for required policy data in request
if (Strings.isNullOrEmpty(policyData.getServiceType())) {
- responseString.append(
- "<b>Optimization Service</b>:<i> Optimization policy data is missing or invalid Json."
+ responseString.append("<b>Optimization Service</b>:<i> Optimization policy data is missing or invalid Json."
+ HTML_ITALICS_LNBREAK);
return false;
}
-
+
modelRequiredFieldsList.clear();
pullJsonKeyPairs((JsonNode) policyData.getPolicyJSON());
-
+
// parse the service and version from the policy data
String service;
String version;
@@ -1234,22 +1241,20 @@ public class PolicyValidation {
service = policyData.getServiceType();
version = policyData.getVersion();
}
-
+
// Checks for required version in policy data
if (Strings.isNullOrEmpty(version)) {
- responseString.append(
- "<b>Optimization Service Version</b>:<i> Optimization Service Version is required"
+ responseString.append("<b>Optimization Service Version</b>:<i> Optimization Service Version is required"
+ HTML_ITALICS_LNBREAK);
return false;
}
-
+
OptimizationModels returnModel = getOptimizationModelData(service, version);
-
+
// Checks if valid model exists in the database
if (returnModel == null) {
- responseString.append("<b>Optimization Service Model</b>:<i> Invalid Model. The model name, "
- + service + " of version, " + version
- + " was not found in the dictionary" + HTML_ITALICS_LNBREAK);
+ responseString.append("<b>Optimization Service Model</b>:<i> Invalid Model. The model name, " + service
+ + " of version, " + version + " was not found in the dictionary" + HTML_ITALICS_LNBREAK);
return false;
}
@@ -1259,16 +1264,15 @@ public class PolicyValidation {
String modelAttributes = returnModel.getAttributes();
if (!Strings.isNullOrEmpty(annotation)) {
- Map<String, String> rangeMap = Splitter.on(",").withKeyValueSeparator("=")
- .split(annotation);
- for (Entry<String, String> rMap : rangeMap.entrySet()) {
- if (rMap.getValue().contains("range::")) {
- String value = mapAttribute.get(rMap.getKey().trim());
- String[] tempString = rMap.getValue().split("::")[1].split("-");
+ Map<String, String> rangeMap = Splitter.on(",").withKeyValueSeparator("=").split(annotation);
+ for (Entry<String, String> rangeMapEntry : rangeMap.entrySet()) {
+ if (rangeMapEntry.getValue().contains("range::")) {
+ String value = mapAttribute.get(rangeMapEntry.getKey().trim());
+ String[] tempString = rangeMapEntry.getValue().split("::")[1].split("-");
int startNum = Integer.parseInt(tempString[0]);
int endNum = Integer.parseInt(tempString[1]);
- String returnString = "InvalidreturnModel Range:" + rMap.getKey()
- + " must be between " + startNum + " - " + endNum + ",";
+ String returnString = "InvalidreturnModel Range:" + rangeMapEntry.getKey() + " must be between "
+ + startNum + " - " + endNum + ",";
if (value != null) {
if (PolicyUtils.isInteger(value.replace("\"", ""))) {
@@ -1282,9 +1286,8 @@ public class PolicyValidation {
valid = false;
}
} else {
- responseString.append("<b>" + rMap.getKey() + "</b>:<i>" + rMap.getKey()
- + " is required for the Optimization model " + service
- + HTML_ITALICS_LNBREAK);
+ responseString.append("<b>" + rangeMapEntry.getKey() + "</b>:<i>" + rangeMapEntry.getKey()
+ + " is required for the Optimization model " + service + HTML_ITALICS_LNBREAK);
valid = false;
}
@@ -1296,12 +1299,13 @@ public class PolicyValidation {
// GUI request are already validated from the SDK-APP
if ("API".equals(policyData.getApiflag())) {
// first , get the complete set of required fields
- populateReqFieldSet(new String[] {refAttributes, modelAttributes}, subAttributes);
+ populateReqFieldSet(new String[]
+ { refAttributes, modelAttributes }, subAttributes);
modelRequiredFieldsList.addAll(allOptReqTrueKeys);
-
+
if (modelRequiredFieldsList != null && !modelRequiredFieldsList.isEmpty()) {
-
+
// create jsonRequestMap with all json keys and values from request
JsonNode rootNode = (JsonNode) policyData.getPolicyJSON();
jsonRequestMap.clear();
@@ -1312,13 +1316,13 @@ public class PolicyValidation {
if (jsonRequestMap.containsKey(requiredField)) {
String value = jsonRequestMap.get(requiredField);
if (StringUtils.isBlank(value) || "\"\"".equals(value)) {
- responseString.append("<b>Optimization Service Model</b>:<i> "
- + requiredField + ISREQUIRED + HTML_ITALICS_LNBREAK);
+ responseString.append("<b>Optimization Service Model</b>:<i> " + requiredField + ISREQUIRED
+ + HTML_ITALICS_LNBREAK);
valid = false;
}
} else {
- responseString.append("<b>Optimization Service Model</b>:<i> "
- + requiredField + ISREQUIRED + HTML_ITALICS_LNBREAK);
+ responseString.append("<b>Optimization Service Model</b>:<i> " + requiredField + ISREQUIRED
+ + HTML_ITALICS_LNBREAK);
valid = false;
}
}
@@ -1334,7 +1338,7 @@ public class PolicyValidation {
}
private void populateRequiredFields(String[] attrArr, String subAttributes, String modelAttributes)
- throws JsonProcessingException {
+ throws JsonProcessingException {
// get list of required fields from the ref_Attributes of the Model
for (String attributes : attrArr) {
if (!StringUtils.isBlank(attributes)) {
@@ -1367,7 +1371,6 @@ public class PolicyValidation {
// Get all keys with "required-true" defined in their value from subAttribute
getAllKeys(jsonSub);
-
// parse refAttrbutes
for (String attr : attrArr) {
if (attr != null) {
@@ -1383,5 +1386,4 @@ public class PolicyValidation {
}
}
-
-} \ No newline at end of file
+}
diff --git a/ONAP-REST/src/main/java/org/onap/policy/rest/util/PolicyValidationRequestWrapper.java b/ONAP-REST/src/main/java/org/onap/policy/rest/util/PolicyValidationRequestWrapper.java
index 779c5227a..ad60a7512 100644
--- a/ONAP-REST/src/main/java/org/onap/policy/rest/util/PolicyValidationRequestWrapper.java
+++ b/ONAP-REST/src/main/java/org/onap/policy/rest/util/PolicyValidationRequestWrapper.java
@@ -3,20 +3,28 @@
* ONAP Policy Engine
* ================================================================================
* Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2019 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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;
+ */
+
+package org.onap.policy.rest.util;
+
+import com.fasterxml.jackson.databind.DeserializationFeature;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.google.common.base.Strings;
import java.io.IOException;
import java.io.StringReader;
@@ -34,6 +42,7 @@ import javax.json.JsonReader;
import javax.servlet.http.HttpServletRequest;
import org.onap.policy.api.AttributeType;
+import org.onap.policy.api.PolicyClass;
import org.onap.policy.api.PolicyParameters;
import org.onap.policy.common.logging.flexlogger.FlexLogger;
import org.onap.policy.common.logging.flexlogger.Logger;
@@ -43,31 +52,32 @@ import org.onap.policy.rest.adapter.RainyDayParams;
import org.onap.policy.rest.adapter.YAMLParams;
import org.onap.policy.xacml.api.XACMLErrorConstants;
-import com.fasterxml.jackson.databind.DeserializationFeature;
-import com.fasterxml.jackson.databind.JsonNode;
-import com.fasterxml.jackson.databind.ObjectMapper;
-import com.google.common.base.Strings;
-
public class PolicyValidationRequestWrapper {
-
- private static final Logger LOGGER = FlexLogger.getLogger(PolicyValidationRequestWrapper.class);
- public static final String CONFIG_NAME="configName";
- public static final String INVALIDJSON = " improper JSON format: ";
- public static final String ONAPNAME = "onapname";
- public static final String CONTENT = "content";
- public static final String GUARD = "guard";
- public static final String LOCATION = "location";
- public static final String POLICYSCOPE = "policyScope";
- public static final String PRIORITY = "priority";
- public static final String RISKLEVEL = "riskLevel";
- public static final String RISKTYPE = "riskType";
- public static final String SERVICE = "service";
- public static final String VERSION = "version";
-
- public static final String SERVICETYPE_POLICY_NAME = "serviceTypePolicyName";
-
+ private static final Logger LOGGER = FlexLogger.getLogger(PolicyValidationRequestWrapper.class);
+
+ private static final String CONFIG_NAME = "configName";
+ private static final String CONTENT = "content";
+ private static final String GUARD = "guard";
+ private static final String INVALIDJSON = " improper JSON format: ";
+ private static final String LOCATION = "location";
+ private static final String ONAPNAME = "onapname";
+ private static final String POLICYSCOPE = "policyScope";
+ private static final String PRIORITY = "priority";
+ private static final String RISKLEVEL = "riskLevel";
+ private static final String RISKTYPE = "riskType";
+ private static final String SECURITY_ZONE_ID = "securityZoneId";
+ private static final String SERVICE = "service";
+ private static final String SERVICETYPE_POLICY_NAME = "serviceTypePolicyName";
+ private static final String UUID = "uuid";
+ private static final String VERSION = "version";
+
+ /**
+ * Populate request parameters.
+ *
+ * @param request the request
+ * @return the policy rest adapter
+ */
public PolicyRestAdapter populateRequestParameters(HttpServletRequest request) {
-
PolicyRestAdapter policyData = null;
ClosedLoopFaultTrapDatas trapDatas = null;
ClosedLoopFaultTrapDatas faultDatas = null;
@@ -76,402 +86,389 @@ public class PolicyValidationRequestWrapper {
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
JsonNode root = mapper.readTree(request.getReader());
policyData = mapper.readValue(root.get("policyData").toString(), PolicyRestAdapter.class);
- if(root.get("trapData") != null){
+ if (root.get("trapData") != null) {
trapDatas = mapper.readValue(root.get("trapData").toString(), ClosedLoopFaultTrapDatas.class);
policyData.setTrapDatas(trapDatas);
}
- if(root.get("faultData") != null){
+ if (root.get("faultData") != null) {
faultDatas = mapper.readValue(root.get("faultData").toString(), ClosedLoopFaultTrapDatas.class);
policyData.setFaultDatas(faultDatas);
}
- JsonObject json;
- json = stringToJsonObject(root.toString());
-
- if(json != null){
- if(json.containsKey("policyJSON")){
- policyData.setPolicyJSON(root.get("policyJSON"));
- }else{
- String jsonBodyData = json.getJsonObject("policyData").get("jsonBodyData").toString();
- policyData.setJsonBody(jsonBodyData);
- }
+ JsonObject json = stringToJsonObject(root.toString());
+ if (json.containsKey("policyJSON")) {
+ policyData.setPolicyJSON(root.get("policyJSON"));
+ } else {
+ String jsonBodyData = json.getJsonObject("policyData").get("jsonBodyData").toString();
+ policyData.setJsonBody(jsonBodyData);
}
-
} catch (Exception e) {
- LOGGER.error("Exception Occured while populating request parameters: " +e);
+ LOGGER.error("Exception Occured while populating request parameters: " + e);
}
return policyData;
}
+ /**
+ * Populate request parameters.
+ *
+ * @param parameters the parameters
+ * @return the policy rest adapter
+ */
public PolicyRestAdapter populateRequestParameters(PolicyParameters parameters) {
-
PolicyRestAdapter policyData = new PolicyRestAdapter();
-
+
/*
* set policy adapter values for Building JSON object containing policy data
*/
- //Common Policy Fields
+ // Common Policy Fields
policyData.setPolicyName(parameters.getPolicyName());
policyData.setOnapName(parameters.getOnapName());
- policyData.setPriority(parameters.getPriority()); //Micro Service
- policyData.setConfigName(parameters.getConfigName()); //Base and Firewall
- policyData.setRiskType(parameters.getRiskType()); //Safe parameters Attributes
- policyData.setRiskLevel(parameters.getRiskLevel());//Safe parameters Attributes
- policyData.setGuard(String.valueOf(parameters.getGuard()));//Safe parameters Attributes
- policyData.setTtlDate(convertDate(parameters.getTtlDate()));//Safe parameters Attributes
+ policyData.setPriority(parameters.getPriority()); // Micro Service
+ policyData.setConfigName(parameters.getConfigName()); // Base and Firewall
+ policyData.setRiskType(parameters.getRiskType()); // Safe parameters Attributes
+ policyData.setRiskLevel(parameters.getRiskLevel());// Safe parameters Attributes
+ policyData.setGuard(String.valueOf(parameters.getGuard()));// Safe parameters Attributes
+ policyData.setTtlDate(convertDate(parameters.getTtlDate()));// Safe parameters Attributes
policyData.setApiflag("API");
- //Some policies require jsonObject conversion from String for configBody (i.e. MicroService and Firewall)
+ // Some policies require jsonObject conversion from String for configBody (i.e. MicroService and Firewall)
JsonObject json = null;
- try{
- if(parameters.getConfigBody()!= null){
+ try {
+ if (parameters.getConfigBody() != null) {
json = stringToJsonObject(parameters.getConfigBody());
}
- } catch(JsonException| IllegalStateException e){
- String message = XACMLErrorConstants.ERROR_DATA_ISSUE+ INVALIDJSON + parameters.getConfigBody();
+ } catch (JsonException | IllegalStateException e) {
+ String message = XACMLErrorConstants.ERROR_DATA_ISSUE + INVALIDJSON + parameters.getConfigBody();
LOGGER.error(message, e);
return null;
}
-
- if(parameters.getPolicyClass()!=null && !"Config".equals(parameters.getPolicyClass().toString())){
- policyData.setPolicyType(parameters.getPolicyClass().toString());
+ if (parameters.getPolicyClass() == null) {
+ parameters.setPolicyClass(PolicyClass.Config);
+ }
+
+ policyData.setPolicyType(parameters.getPolicyClass().toString());
+
+ switch (parameters.getPolicyClass()) {
+ case Config:
+ return populateConfigParameters(parameters, policyData, json);
+
+ case Decision:
+ return populateDecisionParameters(parameters, policyData, getMatchingAttributeValues(parameters));
+
+ case Action:
+ return populateActionParameters(parameters, policyData, getMatchingAttributeValues(parameters));
+
+ default:
+ return null;
+ }
+ }
+
+ private PolicyRestAdapter populateConfigParameters(PolicyParameters parameters, PolicyRestAdapter policyData,
+ JsonObject json) {
+ policyData.setConfigPolicyType(parameters.getPolicyConfigType().toString());
+
+ // Config Specific
+ policyData.setConfigBodyData(parameters.getConfigBody()); // Base
+ policyData.setConfigType((parameters.getConfigBodyType() != null)
+ ? parameters.getConfigBodyType().toString().toUpperCase()
+ : null); // Base
+
+ switch (parameters.getPolicyConfigType()) {
+ case Firewall:
+ return populateConfigFirewallParameters(policyData, json);
+ case MicroService:
+ return populateConfigMicroserviceParameters(parameters, policyData, json);
+ case Optimization:
+ return populateConfigOptimizationParameters(parameters, policyData, json);
+ case ClosedLoop_Fault:
+ return populateConfigClosedLoopFaultParameters(policyData, json);
+ case ClosedLoop_PM:
+ return populateConfigClosedLoopPmParameters(policyData, json);
+ case BRMS_PARAM:
+ return populateConfigBrmsParameters(parameters, policyData);
+
+ // case BRMS_RAW:, case Base:, and case Extended: handled as default cases
+ default:
+ return policyData;
+ }
+ }
+
+ private PolicyRestAdapter populateConfigFirewallParameters(PolicyRestAdapter policyData, JsonObject json) {
+ policyData.setConfigPolicyType("Firewall Config");
+
+ // get values and attributes from the JsonObject
+ if (json != null) {
+ policyData.setSecurityZone(getNewOrExistingKeyValue(json, SECURITY_ZONE_ID, policyData.getSecurityZone()));
+ policyData.setConfigName(getNewOrExistingKeyValue(json, CONFIG_NAME, policyData.getConfigName()));
+ }
+ return policyData;
+ }
+
+ private PolicyRestAdapter populateConfigMicroserviceParameters(PolicyParameters parameters,
+ PolicyRestAdapter policyData, JsonObject json) {
+ policyData.setConfigPolicyType("Micro Service");
+
+ // Get values and attributes from the JsonObject
+ if (json != null) {
+ return getJsonObjectValuesAndAttributes(parameters, policyData, json);
+ } else {
+ String message = XACMLErrorConstants.ERROR_DATA_ISSUE + INVALIDJSON + parameters.getConfigBody();
+ LOGGER.error(message);
+ return null;
+ }
+ }
+
+ private PolicyRestAdapter populateConfigOptimizationParameters(PolicyParameters parameters,
+ PolicyRestAdapter policyData, JsonObject json) {
+ policyData.setConfigPolicyType("Optimization");
+
+ // get values and attributes from the JsonObject
+ if (json != null) {
+ return getJsonObjectValuesAndAttributes(parameters, policyData, json);
+ } else {
+ return policyData;
+ }
+ }
+
+ private PolicyRestAdapter populateConfigClosedLoopFaultParameters(PolicyRestAdapter policyData, JsonObject json) {
+ policyData.setConfigPolicyType("ClosedLoop_Fault");
- //Get Matching attribute values
- Map<AttributeType, Map<String, String>> attributes = parameters.getAttributes();
- Map<String, String> matching = null;
- if(attributes != null){
- matching = attributes.get(AttributeType.MATCHING);
+ if (json != null) {
+ policyData.setJsonBody(json.toString());
+ policyData.setOnapName(getNewOrExistingKeyValue(json, ONAPNAME, policyData.getOnapName()));
+ }
+ return policyData;
+ }
+
+ private PolicyRestAdapter populateConfigClosedLoopPmParameters(PolicyRestAdapter policyData, JsonObject json) {
+ policyData.setConfigPolicyType("ClosedLoop_PM");
+
+ if (json != null) {
+ policyData.setJsonBody(json.toString());
+ policyData.setOnapName(getNewOrExistingKeyValue(json, ONAPNAME, policyData.getOnapName()));
+ if (json.get(SERVICETYPE_POLICY_NAME) != null) {
+ String serviceType = json.get(SERVICETYPE_POLICY_NAME).toString().replace("\"", "");
+ LinkedHashMap<String, String> serviceTypePolicyName = new LinkedHashMap<>();
+ serviceTypePolicyName.put(SERVICETYPE_POLICY_NAME, serviceType);
+ policyData.setServiceTypePolicyName(serviceTypePolicyName);
}
+ }
+ return policyData;
+ }
- if("Decision".equals(parameters.getPolicyClass().toString())){
+ private PolicyRestAdapter populateConfigBrmsParameters(PolicyParameters parameters, PolicyRestAdapter policyData) {
+ Map<AttributeType, Map<String, String>> drlRuleAndUiParams = parameters.getAttributes();
+ Map<String, String> rule = drlRuleAndUiParams.get(AttributeType.RULE);
+ policyData.setRuleName(rule.get("templateName"));
- String ruleProvider = parameters.getRuleProvider().toString();
- policyData.setRuleProvider(ruleProvider);
+ return policyData;
+ }
+
+ private PolicyRestAdapter populateDecisionParameters(PolicyParameters parameters, PolicyRestAdapter policyData,
+ Map<String, String> matching) {
+ policyData.setRuleProvider(parameters.getRuleProvider().toString());
+
+ switch (parameters.getRuleProvider()) {
+ case RAINY_DAY:
+ return populateDecisionRainyDayParameters(parameters, policyData, matching);
- if("Rainy_Day".equals(ruleProvider)){
+ case GUARD_BL_YAML:
+ case GUARD_MIN_MAX:
+ case GUARD_YAML:
+ return populateDecisionGuardParameters(policyData, matching);
- // Set Matching attributes in RainyDayParams in adapter
- RainyDayParams rainyday = new RainyDayParams();
+ case AAF:
+ case CUSTOM:
+ case RAW:
+ default:
+ return policyData;
+ }
+ }
- if(matching != null) {
- rainyday.setServiceType(matching.get("ServiceType"));
- rainyday.setVnfType(matching.get("VNFType"));
- rainyday.setBbid(matching.get("BB_ID"));
- rainyday.setWorkstep(matching.get("WorkStep"));
- }
-
- Map<String, String> treatments = parameters.getTreatments();
- ArrayList<Object> treatmentsTableChoices = new ArrayList<>();
+ private PolicyRestAdapter populateDecisionRainyDayParameters(PolicyParameters parameters,
+ PolicyRestAdapter policyData, Map<String, String> matching) {
+ // Set Matching attributes in RainyDayParams in adapter
+ RainyDayParams rainyday = new RainyDayParams();
- for (String keyField : treatments.keySet()) {
- LinkedHashMap<String, String> treatmentMap = new LinkedHashMap<>();
- String errorcode = keyField;
- String treatment = treatments.get(errorcode);
- treatmentMap.put("errorcode", errorcode);
- treatmentMap.put("treatment", treatment);
- treatmentsTableChoices.add(treatmentMap);
- }
- rainyday.setTreatmentTableChoices(treatmentsTableChoices);
- policyData.setRainyday(rainyday);
+ if (matching != null) {
+ rainyday.setServiceType(matching.get("ServiceType"));
+ rainyday.setVnfType(matching.get("VNFType"));
+ rainyday.setBbid(matching.get("BB_ID"));
+ rainyday.setWorkstep(matching.get("WorkStep"));
+ }
- } else if ("GUARD_YAML".equals(ruleProvider) || "GUARD_BL_YAML".equals(ruleProvider)
- || "GUARD_MIN_MAX".equals(ruleProvider)) {
+ Map<String, String> treatments = parameters.getTreatments();
+ ArrayList<Object> treatmentsTableChoices = new ArrayList<>();
- // Set Matching attributes in YAMLParams in adapter
- YAMLParams yamlparams = new YAMLParams();
+ for (String keyField : treatments.keySet()) {
+ LinkedHashMap<String, String> treatmentMap = new LinkedHashMap<>();
+ String errorcode = keyField;
+ String treatment = treatments.get(errorcode);
+ treatmentMap.put("errorcode", errorcode);
+ treatmentMap.put("treatment", treatment);
+ treatmentsTableChoices.add(treatmentMap);
+ }
+ rainyday.setTreatmentTableChoices(treatmentsTableChoices);
+ policyData.setRainyday(rainyday);
- if (matching != null) {
- yamlparams.setActor(matching.get("actor"));
- yamlparams.setRecipe(matching.get("recipe"));
- yamlparams.setGuardActiveStart(matching.get("guardActiveStart"));
- yamlparams.setGuardActiveEnd(matching.get("guardActiveEnd"));
+ return policyData;
+ }
- if("GUARD_YAML".equals(ruleProvider)){
- yamlparams.setLimit(matching.get("limit"));
- yamlparams.setTimeWindow(matching.get("timeWindow"));
- yamlparams.setTimeUnits(matching.get("timeUnits"));
- } else if ("GUARD_MIN_MAX".equals(ruleProvider)) {
- yamlparams.setMin(matching.get("min"));
- yamlparams.setMax(matching.get("max"));
- }else{
+ private PolicyRestAdapter populateDecisionGuardParameters(PolicyRestAdapter policyData,
+ Map<String, String> matching) {
+ // Set Matching attributes in YAMLParams in adapter
+ YAMLParams yamlparams = new YAMLParams();
- List<String> blackList = new ArrayList<>();
+ if (matching == null) {
+ policyData.setYamlparams(yamlparams);
+ return policyData;
+ }
- if(!Strings.isNullOrEmpty(matching.get("blackList"))){
- String[] blackListArray = matching.get("blackList").split(",");
- for(String element : blackListArray){
- blackList.add(element);
- }
- }
+ yamlparams.setActor(matching.get("actor"));
+ yamlparams.setRecipe(matching.get("recipe"));
+ yamlparams.setGuardActiveStart(matching.get("guardActiveStart"));
+ yamlparams.setGuardActiveEnd(matching.get("guardActiveEnd"));
- yamlparams.setBlackList(blackList);
+ yamlparams.setLimit(matching.get("limit"));
+ yamlparams.setTimeWindow(matching.get("timeWindow"));
+ yamlparams.setTimeUnits(matching.get("timeUnits"));
- }
- }
- policyData.setYamlparams(yamlparams);
- }
+ yamlparams.setMin(matching.get("min"));
+ yamlparams.setMax(matching.get("max"));
- } else if("Action".equals(parameters.getPolicyClass().toString())){
+ List<String> blackList = new ArrayList<>();
- ArrayList<Object> ruleAlgorithmChoices = new ArrayList<>();
+ if (!Strings.isNullOrEmpty(matching.get("blackList"))) {
+ String[] blackListArray = matching.get("blackList").split(",");
+ for (String element : blackListArray) {
+ blackList.add(element);
+ }
+ }
- List<String> dynamicLabelRuleAlgorithms = parameters.getDynamicRuleAlgorithmLabels();
- List<String> dynamicFieldFunctionRuleAlgorithms = parameters.getDynamicRuleAlgorithmFunctions();
- List<String> dynamicFieldOneRuleAlgorithms = parameters.getDynamicRuleAlgorithmField1();
- List<String> dyrnamicFieldTwoRuleAlgorithms = parameters.getDynamicRuleAlgorithmField2();
+ yamlparams.setBlackList(blackList);
- if (dynamicLabelRuleAlgorithms != null && !dynamicLabelRuleAlgorithms.isEmpty()) {
- int i = dynamicLabelRuleAlgorithms.size() - 1;
+ policyData.setYamlparams(yamlparams);
+ return policyData;
+ }
- for (String labelAttr : dynamicLabelRuleAlgorithms) {
- LinkedHashMap<String, String> ruleAlgorithm = new LinkedHashMap<>();
+ private PolicyRestAdapter populateActionParameters(PolicyParameters parameters, PolicyRestAdapter policyData,
+ Map<String, String> matching) {
+ ArrayList<Object> ruleAlgorithmChoices = new ArrayList<>();
- String id = dynamicLabelRuleAlgorithms.get(i);
- String dynamicRuleAlgorithmField1 = dynamicFieldOneRuleAlgorithms.get(i);
- String dynamicRuleAlgorithmCombo = dynamicFieldFunctionRuleAlgorithms.get(i);
- String dynamicRuleAlgorithmField2 = dyrnamicFieldTwoRuleAlgorithms.get(i);
+ List<String> dynamicLabelRuleAlgorithms = parameters.getDynamicRuleAlgorithmLabels();
+ List<String> dynamicFieldFunctionRuleAlgorithms = parameters.getDynamicRuleAlgorithmFunctions();
+ List<String> dynamicFieldOneRuleAlgorithms = parameters.getDynamicRuleAlgorithmField1();
+ List<String> dynamicFieldTwoRuleAlgorithms = parameters.getDynamicRuleAlgorithmField2();
- ruleAlgorithm.put("id", id);
- ruleAlgorithm.put("dynamicRuleAlgorithmField1", dynamicRuleAlgorithmField1);
- ruleAlgorithm.put("dynamicRuleAlgorithmCombo", dynamicRuleAlgorithmCombo);
- ruleAlgorithm.put("dynamicRuleAlgorithmField2", dynamicRuleAlgorithmField2);
+ if (dynamicLabelRuleAlgorithms != null && !dynamicLabelRuleAlgorithms.isEmpty()) {
- ruleAlgorithmChoices.add(ruleAlgorithm);
+ for (int i = dynamicLabelRuleAlgorithms.size() - 1; i >= 0; i--) {
+ LinkedHashMap<String, String> ruleAlgorithm = new LinkedHashMap<>();
- i--;
+ String id = dynamicLabelRuleAlgorithms.get(i);
+ String dynamicRuleAlgorithmField1 = dynamicFieldOneRuleAlgorithms.get(i);
+ String dynamicRuleAlgorithmCombo = dynamicFieldFunctionRuleAlgorithms.get(i);
+ String dynamicRuleAlgorithmField2 = dynamicFieldTwoRuleAlgorithms.get(i);
- }
- }
+ ruleAlgorithm.put("id", id);
+ ruleAlgorithm.put("dynamicRuleAlgorithmField1", dynamicRuleAlgorithmField1);
+ ruleAlgorithm.put("dynamicRuleAlgorithmCombo", dynamicRuleAlgorithmCombo);
+ ruleAlgorithm.put("dynamicRuleAlgorithmField2", dynamicRuleAlgorithmField2);
- policyData.setRuleAlgorithmschoices(ruleAlgorithmChoices);
-
- ArrayList<Object> attributeList = new ArrayList<>();
- if (matching != null) {
- for (Map.Entry<String, String> entry : matching.entrySet()) {
- LinkedHashMap<String, String> attributeMap = new LinkedHashMap<>();
- String key = entry.getKey();
- String value = entry.getValue();
- attributeMap.put("key", key);
- attributeMap.put("value", value);
- attributeList.add(attributeMap);
- }
- }
-
- policyData.setAttributes(attributeList);
- policyData.setActionAttributeValue(parameters.getActionAttribute());
- policyData.setActionPerformer(parameters.getActionPerformer());
+ ruleAlgorithmChoices.add(ruleAlgorithm);
+ }
+ }
+ policyData.setRuleAlgorithmschoices(ruleAlgorithmChoices);
+
+ ArrayList<Object> attributeList = new ArrayList<>();
+ if (matching != null) {
+ for (Map.Entry<String, String> entry : matching.entrySet()) {
+ LinkedHashMap<String, String> attributeMap = new LinkedHashMap<>();
+ String key = entry.getKey();
+ String value = entry.getValue();
+ attributeMap.put("key", key);
+ attributeMap.put("value", value);
+ attributeList.add(attributeMap);
}
- }else {
-
- policyData.setPolicyType("Config");
- policyData.setConfigPolicyType(parameters.getPolicyConfigType().toString());
-
- //Config Specific
- policyData.setConfigBodyData(parameters.getConfigBody()); //Base
- policyData.setConfigType((parameters.getConfigBodyType()!=null) ? parameters.getConfigBodyType().toString().toUpperCase(): null); //Base
-
- if("FW".equalsIgnoreCase(parameters.getPolicyConfigType().toString())){
-
- policyData.setConfigPolicyType("Firewall Config");
-
- // get values and attributes from the JsonObject
- if(json != null){
- if (json.get("securityZoneId")!=null){
- String securityZone = json.get("securityZoneId").toString().replace("\"", "");
- policyData.setSecurityZone(securityZone);
- }
- if (json.get(CONFIG_NAME)!=null){
- String configName = json.get(CONFIG_NAME).toString().replace("\"", "");
- policyData.setConfigName(configName);
- }
- }
-
- }else if("MS".equals(parameters.getPolicyConfigType().toString())){
-
- policyData.setConfigPolicyType("Micro Service");
-
- // get values and attributes from the JsonObject
- if(json != null){
- if (json.containsKey(CONTENT)){
- String content = json.get(CONTENT).toString();
- ObjectMapper mapper = new ObjectMapper();
- JsonNode policyJSON = null;
- try {
- policyJSON = mapper.readTree(content);
- } catch (IOException e) {
- String message = XACMLErrorConstants.ERROR_DATA_ISSUE+ INVALIDJSON + parameters.getConfigBody();
- LOGGER.error(message, e);
- return null;
- }
- policyData.setPolicyJSON(policyJSON);
- }
- if (json.containsKey(SERVICE)){
- String serviceType = json.get(SERVICE).toString().replace("\"", "");
- policyData.setServiceType(serviceType);
- }
- if (json.containsKey("uuid")){
- String uuid = json.get("uuid").toString().replace("\"", "");
- policyData.setUuid(uuid);
- }
- if (json.containsKey(LOCATION)){
- String msLocation = json.get(LOCATION).toString().replace("\"", "");
- policyData.setLocation(msLocation);
- }
- if (json.containsKey(CONFIG_NAME)){
- String configName = json.get(CONFIG_NAME).toString().replace("\"", "");
- policyData.setConfigName(configName);
- }
- if(json.containsKey(PRIORITY)){
- String priority = json.get(PRIORITY).toString().replace("\"", "");
- policyData.setPriority(priority);
- }
- if(json.containsKey(VERSION)){
- String version = json.get(VERSION).toString().replace("\"", "");
- policyData.setVersion(version);
- }
- if(json.containsKey(POLICYSCOPE)){
- String policyScope = json.get(POLICYSCOPE).toString().replace("\"", "");
- policyData.setPolicyScope(policyScope);
- }
- if(json.containsKey(RISKTYPE)){
- String riskType = json.get(RISKTYPE).toString().replace("\"", "");
- policyData.setRiskType(riskType);
- }
- if(json.containsKey(RISKLEVEL)){
- String riskLevel = json.get(RISKLEVEL).toString().replace("\"", "");
- policyData.setRiskLevel(riskLevel);
- }
- if(json.containsKey(GUARD)){
- String guard = json.get(GUARD).toString().replace("\"", "");
- policyData.setGuard(guard);
- }
- } else {
- String message = XACMLErrorConstants.ERROR_DATA_ISSUE+ INVALIDJSON + parameters.getConfigBody();
- LOGGER.error(message);
- return null;
- }
-
- }else if("Optimization".equals(parameters.getPolicyConfigType().toString())){
-
- policyData.setConfigPolicyType("Optimization");
-
- // get values and attributes from the JsonObject
- if(json != null){
- if (json.containsKey(CONTENT)){
- String content = json.get(CONTENT).toString();
- ObjectMapper mapper = new ObjectMapper();
- JsonNode policyJSON = null;
- try {
- policyJSON = mapper.readTree(content);
- } catch (IOException e) {
- String message = XACMLErrorConstants.ERROR_DATA_ISSUE+ INVALIDJSON + parameters.getConfigBody();
- LOGGER.error(message, e);
- return null;
- }
- policyData.setPolicyJSON(policyJSON);
- }
- if (json.containsKey(SERVICE)){
- String serviceType = json.get(SERVICE).toString().replace("\"", "");
- policyData.setServiceType(serviceType);
- }
- if (json.containsKey("uuid")){
- String uuid = json.get("uuid").toString().replace("\"", "");
- policyData.setUuid(uuid);
- }
- if (json.containsKey(LOCATION)){
- String msLocation = json.get(LOCATION).toString().replace("\"", "");
- policyData.setLocation(msLocation);
- }
- if (json.containsKey(CONFIG_NAME)){
- String configName = json.get(CONFIG_NAME).toString().replace("\"", "");
- policyData.setConfigName(configName);
- }
- if(json.containsKey(PRIORITY)){
- String priority = json.get(PRIORITY).toString().replace("\"", "");
- policyData.setPriority(priority);
- }
- if(json.containsKey(VERSION)){
- String version = json.get(VERSION).toString().replace("\"", "");
- policyData.setVersion(version);
- }
- if(json.containsKey(POLICYSCOPE)){
- String policyScope = json.get(POLICYSCOPE).toString().replace("\"", "");
- policyData.setPolicyScope(policyScope);
- }
- if(json.containsKey(RISKTYPE)){
- String riskType = json.get(RISKTYPE).toString().replace("\"", "");
- policyData.setRiskType(riskType);
- }
- if(json.containsKey(RISKLEVEL)){
- String riskLevel = json.get(RISKLEVEL).toString().replace("\"", "");
- policyData.setRiskLevel(riskLevel);
- }
- if(json.containsKey(GUARD)){
- String guard = json.get(GUARD).toString().replace("\"", "");
- policyData.setGuard(guard);
- }
- }
-
- } else if("Fault".equals(parameters.getPolicyConfigType().toString())){
-
- policyData.setConfigPolicyType("ClosedLoop_Fault");
-
- if(json != null){
- policyData.setJsonBody(json.toString());
- if (json.get(ONAPNAME)!=null){
- String onapName = json.get(ONAPNAME).toString().replace("\"", "");
- policyData.setOnapName(onapName);
- }
- }
-
- } else if("PM".equals(parameters.getPolicyConfigType().toString())){
-
- policyData.setConfigPolicyType("ClosedLoop_PM");
-
- if(json != null){
- policyData.setJsonBody(json.toString());
- if (json.get(ONAPNAME)!=null){
- String onapName = json.get(ONAPNAME).toString().replace("\"", "");
- policyData.setOnapName(onapName);
- }
- if (json.get(SERVICETYPE_POLICY_NAME)!=null){
- String serviceType = json.get(SERVICETYPE_POLICY_NAME).toString().replace("\"", "");
- LinkedHashMap<String, String> serviceTypePolicyName = new LinkedHashMap<>();
- serviceTypePolicyName.put(SERVICETYPE_POLICY_NAME, serviceType);
- policyData.setServiceTypePolicyName(serviceTypePolicyName);
- }
- }
- } else if("BRMS_Param".equals(parameters.getPolicyConfigType().toString())){
- Map<AttributeType, Map<String, String>> drlRuleAndUIParams = parameters.getAttributes();
- Map<String, String> rule = drlRuleAndUIParams.get(AttributeType.RULE);
- policyData.setRuleName(rule.get("templateName"));
+ }
+
+ policyData.setAttributes(attributeList);
+ policyData.setActionAttributeValue(parameters.getActionAttribute());
+ policyData.setActionPerformer(parameters.getActionPerformer());
+
+ return policyData;
+ }
+ private PolicyRestAdapter getJsonObjectValuesAndAttributes(PolicyParameters parameters,
+ PolicyRestAdapter policyData, JsonObject json) {
+ if (json.containsKey(CONTENT)) {
+ String content = json.get(CONTENT).toString();
+ JsonNode policyJson = null;
+ try {
+ policyJson = new ObjectMapper().readTree(content);
+ } catch (IOException e) {
+ String message = XACMLErrorConstants.ERROR_DATA_ISSUE + INVALIDJSON + parameters.getConfigBody();
+ LOGGER.error(message, e);
+ return null;
}
+ policyData.setPolicyJSON(policyJson);
}
+ // @formatter:off
+ policyData.setServiceType(getNewOrExistingKeyValue(json, SERVICE, policyData.getServiceType()));
+ policyData.setUuid(getNewOrExistingKeyValue( json, UUID, policyData.getUuid()));
+ policyData.setLocation(getNewOrExistingKeyValue( json, LOCATION, policyData.getLocation()));
+ policyData.setConfigName(getNewOrExistingKeyValue( json, CONFIG_NAME, policyData.getConfigName()));
+ policyData.setPriority(getNewOrExistingKeyValue( json, PRIORITY, policyData.getPriority()));
+ policyData.setVersion(getNewOrExistingKeyValue( json, VERSION, policyData.getVersion()));
+ policyData.setPolicyScope(getNewOrExistingKeyValue(json, POLICYSCOPE, policyData.getPolicyScope()));
+ policyData.setRiskType(getNewOrExistingKeyValue( json, RISKTYPE, policyData.getRiskType()));
+ policyData.setRiskLevel(getNewOrExistingKeyValue( json, RISKLEVEL, policyData.getRiskLevel()));
+ policyData.setGuard(getNewOrExistingKeyValue( json, GUARD, policyData.getGuard()));
+ // @formatter:on
+
return policyData;
+ }
+
+ private String getNewOrExistingKeyValue(final JsonObject json, final String key, final String existingValue) {
+ if (json.containsKey(key)) {
+ return json.get(key).toString().replace("\"", "");
+ } else {
+ return existingValue;
+ }
+ }
+ private Map<String, String> getMatchingAttributeValues(PolicyParameters parameters) {
+ // Get Matching attribute values
+ Map<AttributeType, Map<String, String>> attributes = parameters.getAttributes();
+
+ if (attributes != null) {
+ return attributes.get(AttributeType.MATCHING);
+ }
+ return null;
}
-
+
private JsonObject stringToJsonObject(String value) {
- try(JsonReader jsonReader = Json.createReader(new StringReader(value))){
+ try (JsonReader jsonReader = Json.createReader(new StringReader(value))) {
return jsonReader.readObject();
- } catch(JsonException| IllegalStateException e){
- LOGGER.info(XACMLErrorConstants.ERROR_DATA_ISSUE+ "Improper JSON format... may or may not cause issues in validating the policy: " + value, e);
- return null;
+ } catch (JsonException | IllegalStateException jsonHandlingException) {
+ LOGGER.info(XACMLErrorConstants.ERROR_DATA_ISSUE
+ + "Improper JSON format... may or may not cause issues in validating the policy: " + value,
+ jsonHandlingException);
+ throw jsonHandlingException;
}
}
-
+
private String convertDate(Date date) {
String strDate = null;
- if (date!=null) {
+ if (date != null) {
SimpleDateFormat dateformatJava = new SimpleDateFormat("dd-MM-yyyy");
strDate = dateformatJava.format(date);
}
- return (strDate==null) ? "NA": strDate;
+ return (strDate == null) ? "NA" : strDate;
}
}
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
deleted file mode 100644
index 5b8513823..000000000
--- a/ONAP-REST/src/test/java/org/onap/policy/rest/XACMLRestTest.java
+++ /dev/null
@@ -1,111 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * ONAP-REST
- * ================================================================================
- * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
-
-import java.io.IOException;
-import java.lang.reflect.Constructor;
-import java.lang.reflect.InvocationTargetException;
-import java.lang.reflect.Modifier;
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.List;
-
-import javax.servlet.ServletConfig;
-import javax.servlet.ServletOutputStream;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.apache.log4j.Level;
-import org.apache.log4j.Logger;
-import org.junit.Before;
-import org.junit.Test;
-import org.mockito.Mockito;
-import org.springframework.mock.web.MockHttpServletResponse;
-import org.springframework.mock.web.MockServletConfig;
-
-public class XACMLRestTest extends Mockito{
- private static Log logger = LogFactory.getLog(XACMLRestTest.class);
-
- private List<String> headers = new ArrayList<>();
-
- private HttpServletRequest httpServletRequest;
- private HttpServletResponse httpServletResponse;
- private ServletOutputStream mockOutput;
- 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));
- 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 testXacmlInit(){
- logger.info("XACMLRestTest - testInit");
- try {
- XACMLRest.xacmlInit(servletConfig);
- Logger.getRootLogger().setLevel(Level.DEBUG);
- XACMLRest.dumpRequest(httpServletRequest);
- XACMLRest.loadXacmlProperties(null, null);
- } catch (Exception e) {
- fail();
- }
- }
-
- @Test
- public void testConstructorIsPrivate() throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
- Constructor<XACMLRestProperties> constructor = XACMLRestProperties.class.getDeclaredConstructor();
- assertTrue(Modifier.isPrivate(constructor.getModifiers()));
- constructor.setAccessible(true);
- constructor.newInstance();
- }
-} \ No newline at end of file
diff --git a/ONAP-REST/src/test/java/org/onap/policy/rest/XacmlAdminAuthorizationTest.java b/ONAP-REST/src/test/java/org/onap/policy/rest/XacmlAdminAuthorizationTest.java
new file mode 100644
index 000000000..75abb4f53
--- /dev/null
+++ b/ONAP-REST/src/test/java/org/onap/policy/rest/XacmlAdminAuthorizationTest.java
@@ -0,0 +1,38 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * Copyright (C) 2019 Nordix Foundation.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ * SPDX-License-Identifier: Apache-2.0
+ * ============LICENSE_END=========================================================
+ */
+
+package org.onap.policy.rest;
+
+import static org.junit.Assert.assertNotNull;
+
+import org.junit.Test;
+
+/**
+ * Test the XacmlAdminAuthorizaiton class.
+ *
+ * @author Liam Fallon (liam.fallon@est.tech)
+ */
+public class XacmlAdminAuthorizationTest {
+
+ @Test
+ public void test() {
+ assertNotNull(new XacmlAdminAuthorization());
+ }
+}
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..3b03bdcc8
--- /dev/null
+++ b/ONAP-REST/src/test/java/org/onap/policy/rest/XacmlRestTest.java
@@ -0,0 +1,303 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP-REST
+ * ================================================================================
+ * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2019 Nordix Foundation.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
+
+import com.att.research.xacml.util.XACMLProperties;
+
+import java.io.IOException;
+import java.lang.reflect.Constructor;
+import java.lang.reflect.InvocationTargetException;
+import java.lang.reflect.Modifier;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Properties;
+
+import javax.servlet.ServletConfig;
+import javax.servlet.ServletInputStream;
+import javax.servlet.ServletOutputStream;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.log4j.Level;
+import org.apache.log4j.Logger;
+import org.junit.Before;
+import org.junit.Test;
+import org.mockito.Mockito;
+import org.springframework.mock.web.MockHttpServletResponse;
+import org.springframework.mock.web.MockServletConfig;
+
+public class XacmlRestTest extends Mockito {
+ private static Log logger = LogFactory.getLog(XacmlRestTest.class);
+
+ private List<String> headers = new ArrayList<>();
+
+ private HttpServletRequest httpServletRequest;
+ private HttpServletResponse httpServletResponse;
+ private ServletOutputStream mockOutput;
+ private ServletConfig servletConfig;
+ private ServletInputStream servletInputStream;
+
+ /**
+ * Prepare for the test.
+ */
+ @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));
+ Mockito.when(servletConfig.getInitParameter("XACML_PROPERTIES_NAME")).thenReturn("xacml.pdp.properties");
+
+ System.setProperty(XACMLProperties.XACML_PROPERTIES_NAME, "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");
+
+ servletInputStream = Mockito.mock(ServletInputStream.class);
+ }
+
+ @Test
+ public void testXacmlInit() {
+ logger.info("XACMLRestTest - testInit");
+
+ try {
+ XacmlRest.xacmlInit(servletConfig);
+ Logger.getRootLogger().setLevel(Level.DEBUG);
+ XacmlRest.dumpRequest(httpServletRequest);
+ XacmlRest.loadXacmlProperties(null, null);
+ } catch (Exception e) {
+ fail("Normal case of initiation of XACML REST failed");
+ }
+
+ System.clearProperty(XACMLProperties.XACML_PROPERTIES_NAME);
+ try {
+ XacmlRest.xacmlInit(servletConfig);
+ Logger.getRootLogger().setLevel(Level.DEBUG);
+ XacmlRest.dumpRequest(httpServletRequest);
+ XacmlRest.loadXacmlProperties(null, null);
+ } catch (Exception e) {
+ fail("Normal case of initiation of XACML REST failed");
+ }
+
+ System.clearProperty(XACMLProperties.XACML_PROPERTIES_NAME);
+ try {
+ Logger.getRootLogger().setLevel(Level.INFO);
+ XacmlRest.xacmlInit(servletConfig);
+ Logger.getRootLogger().setLevel(Level.DEBUG);
+ XacmlRest.dumpRequest(httpServletRequest);
+ XacmlRest.loadXacmlProperties(null, null);
+ } catch (Exception e) {
+ fail("Normal case of initiation of XACML REST failed");
+ }
+
+ System.setProperty(XACMLProperties.XACML_PROPERTIES_NAME, "xacml.pdp.properties");
+
+ try {
+ Logger.getRootLogger().setLevel(Level.DEBUG);
+ XacmlRest.xacmlInit(servletConfig);
+ XacmlRest.dumpRequest(httpServletRequest);
+ XacmlRest.loadXacmlProperties(null, null);
+ } catch (Exception e) {
+ fail("Normal case of initiation of XACML REST failed");
+ }
+
+ Mockito.when(servletConfig.getInitParameter("XACML_PROPERTIES_NAME")).thenReturn(null);
+ try {
+ XacmlRest.xacmlInit(servletConfig);
+ Logger.getRootLogger().setLevel(Level.DEBUG);
+ XacmlRest.dumpRequest(httpServletRequest);
+ XacmlRest.loadXacmlProperties(null, null);
+ } catch (Exception e) {
+ fail("Normal case of initiation of XACML REST failed");
+ }
+
+ try {
+ Logger.getRootLogger().setLevel(Level.INFO);
+ XacmlRest.xacmlInit(servletConfig);
+ Logger.getRootLogger().setLevel(Level.DEBUG);
+ XacmlRest.dumpRequest(httpServletRequest);
+ XacmlRest.loadXacmlProperties(null, null);
+ } catch (Exception e) {
+ fail("Normal case of initiation of XACML REST failed");
+ }
+
+ Mockito.when(servletConfig.getInitParameter("XACML_PROPERTIES_NAME")).thenReturn("xacml.pdp.properties");
+
+ List<String> parNameList = new ArrayList<String>() {
+ private static final long serialVersionUID = 1L;
+
+ {
+ add("Name0");
+ add("Name1");
+ add("Name2");
+ add("XACML_PROPERTIES_NAME");
+ }
+ };
+
+ Mockito.when(servletConfig.getInitParameterNames()).thenReturn(Collections.enumeration(parNameList));
+ Mockito.when(servletConfig.getInitParameter("Name0")).thenReturn("Value0");
+ Mockito.when(servletConfig.getInitParameter("Name1")).thenReturn("Value1");
+ Mockito.when(servletConfig.getInitParameter("Name2")).thenReturn("Value2");
+ try {
+ XacmlRest.xacmlInit(servletConfig);
+ Logger.getRootLogger().setLevel(Level.DEBUG);
+ XacmlRest.dumpRequest(httpServletRequest);
+ XacmlRest.loadXacmlProperties(null, null);
+ } catch (Exception e) {
+ e.printStackTrace();
+ fail("Normal case of initiation of XACML REST failed");
+ }
+
+ }
+
+ @Test
+ public void testConstructorIsPrivate() throws NoSuchMethodException, IllegalAccessException,
+ InvocationTargetException, InstantiationException {
+ Constructor<XacmlRestProperties> constructor = XacmlRestProperties.class.getDeclaredConstructor();
+ assertTrue(Modifier.isPrivate(constructor.getModifiers()));
+ constructor.setAccessible(true);
+ constructor.newInstance();
+ }
+
+ @Test
+ public void testLoadXacmlProperties() {
+ XacmlRest.xacmlInit(servletConfig);
+ XacmlRest.loadXacmlProperties(null, null);
+
+ XacmlRest.loadXacmlProperties(new Properties(), new Properties());
+
+ Logger.getRootLogger().setLevel(Level.INFO);
+ XacmlRest.loadXacmlProperties(new Properties(), new Properties());
+ }
+
+ @Test
+ public void testDumpRequest() throws IOException {
+ XacmlRest.xacmlInit(servletConfig);
+
+ Logger.getRootLogger().setLevel(Level.INFO);
+ XacmlRest.dumpRequest(httpServletRequest);
+ Logger.getRootLogger().setLevel(Level.DEBUG);
+
+ Mockito.when(httpServletRequest.getMethod()).thenReturn("GET");
+ XacmlRest.dumpRequest(httpServletRequest);
+ Mockito.when(httpServletRequest.getParameter("type")).thenReturn("hb");
+ XacmlRest.dumpRequest(httpServletRequest);
+ Mockito.when(httpServletRequest.getMethod()).thenReturn("POST");
+
+ List<String> headerNameList = new ArrayList<String>() {
+ private static final long serialVersionUID = 1L;
+
+ {
+ add("Name0");
+ add("Name1");
+ }
+ };
+
+ List<String> header0List = new ArrayList<String>() {
+ private static final long serialVersionUID = 1L;
+
+ {
+ add("Name0H0");
+ add("Name0H1");
+ add("Name0H2");
+ }
+ };
+
+ List<String> header1List = new ArrayList<String>() {
+ private static final long serialVersionUID = 1L;
+
+ {
+ add("Name1H0");
+ add("Name1H1");
+ add("Name1H2");
+ }
+ };
+
+ Mockito.when(httpServletRequest.getHeaderNames()).thenReturn(Collections.enumeration(headerNameList));
+ Mockito.when(httpServletRequest.getHeaders("Name0")).thenReturn(Collections.enumeration(header0List));
+ Mockito.when(httpServletRequest.getHeaders("Name1")).thenReturn(Collections.enumeration(header1List));
+ XacmlRest.dumpRequest(httpServletRequest);
+
+ List<String> attributeList = new ArrayList<String>() {
+ private static final long serialVersionUID = 1L;
+
+ {
+ add("Attribute0");
+ add("Attribute1");
+ }
+ };
+ Mockito.when(httpServletRequest.getAttributeNames()).thenReturn(Collections.enumeration(attributeList));
+ Mockito.when(httpServletRequest.getAttribute("Attribute0")).thenReturn("AttributeValue0");
+ Mockito.when(httpServletRequest.getAttribute("Attribute1")).thenReturn("AttributeValue1");
+ XacmlRest.dumpRequest(httpServletRequest);
+
+ Mockito.when(httpServletRequest.getInputStream()).thenReturn(servletInputStream);
+ XacmlRest.dumpRequest(httpServletRequest);
+
+ Mockito.when(httpServletRequest.getInputStream()).thenThrow(new IOException());
+ XacmlRest.dumpRequest(httpServletRequest);
+
+ Mockito.when(httpServletRequest.getMethod()).thenReturn("PUT");
+ XacmlRest.dumpRequest(httpServletRequest);
+
+ Map<String, String[]> parameterMap = new LinkedHashMap<>();
+ String[] mapValue0 =
+ { "MapValue0" };
+ String[] mapValue1 =
+ { "MapValue0" };
+ String[] mapValue2 =
+ {};
+ parameterMap.put("Key0", mapValue0);
+ parameterMap.put("Key1", mapValue1);
+ parameterMap.put("Key2", mapValue2);
+
+ Mockito.when(httpServletRequest.getMethod()).thenReturn("DELETE");
+ Mockito.when(httpServletRequest.getParameterMap()).thenReturn(parameterMap);
+ XacmlRest.dumpRequest(httpServletRequest);
+ Mockito.when(httpServletRequest.getMethod()).thenReturn("POST");
+ }
+}
diff --git a/ONAP-REST/src/test/java/org/onap/policy/rest/adapter/PolicyRestAdapterTest.java b/ONAP-REST/src/test/java/org/onap/policy/rest/adapter/PolicyRestAdapterTest.java
index 971614359..61a63ce0c 100644
--- a/ONAP-REST/src/test/java/org/onap/policy/rest/adapter/PolicyRestAdapterTest.java
+++ b/ONAP-REST/src/test/java/org/onap/policy/rest/adapter/PolicyRestAdapterTest.java
@@ -2,14 +2,14 @@
* ============LICENSE_START=======================================================
* ONAP Policy Engine
* ================================================================================
- * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2018-2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -19,6 +19,8 @@
*/
package org.onap.policy.rest.adapter;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import java.util.ArrayList;
@@ -31,14 +33,14 @@ import org.onap.policy.rest.jpa.OnapName;
public class PolicyRestAdapterTest {
@Test
- public void testPolicyExportAdapter(){
+ public void testPolicyExportAdapter() {
PolicyExportAdapter adapter = new PolicyExportAdapter();
adapter.setPolicyDatas(new ArrayList<>());
assertTrue(adapter.getPolicyDatas() != null);
}
@Test
- public void testPolicyRestAdapter(){
+ public void testPolicyRestAdapter() {
PolicyRestAdapter adapter = new PolicyRestAdapter();
adapter.setData(new Object());
assertTrue(adapter.getData() != null);
@@ -115,27 +117,27 @@ public class PolicyRestAdapterTest {
adapter.setExistingCLName("Test");
assertTrue("Test".equals(adapter.getExistingCLName()));
adapter.setOnapNameField(new OnapName());
- assertTrue(adapter.getOnapNameField()!=null);
+ assertTrue(adapter.getOnapNameField() != null);
adapter.setJsonBodyData(new Object());
- assertTrue(adapter.getJsonBodyData()!=null);
+ assertTrue(adapter.getJsonBodyData() != null);
adapter.setDirPath("Test");
assertTrue("Test".equals(adapter.getDirPath()));
adapter.setConfigBodyPath("Test");
assertTrue("Test".equals(adapter.getConfigBodyPath()));
adapter.setAttributes(new ArrayList<>());
- assertTrue(adapter.getAttributes()!=null);
+ assertTrue(adapter.getAttributes() != null);
adapter.setSettings(new ArrayList<>());
- assertTrue(adapter.getSettings()!=null);
+ assertTrue(adapter.getSettings() != null);
adapter.setRuleAlgorithmschoices(new ArrayList<>());
- assertTrue(adapter.getRuleAlgorithmschoices()!=null);
+ assertTrue(adapter.getRuleAlgorithmschoices() != null);
adapter.setServiceTypePolicyName(new HashMap<>());
- assertTrue(adapter.getServiceTypePolicyName()!=null);
+ assertTrue(adapter.getServiceTypePolicyName() != null);
adapter.setVerticaMetrics(new HashMap<>());
- assertTrue(adapter.getVerticaMetrics()!=null);
+ assertTrue(adapter.getVerticaMetrics() != null);
adapter.setDescription(new LinkedHashMap<>());
- assertTrue(adapter.getVerticaMetrics()!=null);
+ assertTrue(adapter.getVerticaMetrics() != null);
adapter.setAttributeFields(new LinkedHashMap<>());
- assertTrue(adapter.getAttributeFields()!=null);
+ assertTrue(adapter.getAttributeFields() != null);
adapter.setClearTimeOut("Test");
assertTrue("Test".equals(adapter.getClearTimeOut()));
adapter.setTrapMaxAge("Test");
@@ -143,15 +145,15 @@ public class PolicyRestAdapterTest {
adapter.setVerificationclearTimeOut("Test");
assertTrue("Test".equals(adapter.getVerificationclearTimeOut()));
adapter.setDynamicLayoutMap(new HashMap<>());
- assertTrue(adapter.getDynamicLayoutMap()!=null);
+ assertTrue(adapter.getDynamicLayoutMap() != null);
adapter.setTrapDatas(new ClosedLoopFaultTrapDatas());
- assertTrue(adapter.getTrapDatas()!=null);
+ assertTrue(adapter.getTrapDatas() != null);
adapter.setFaultDatas(new ClosedLoopFaultTrapDatas());
- assertTrue(adapter.getFaultDatas()!=null);
+ assertTrue(adapter.getFaultDatas() != null);
adapter.setFwPolicyType("Test");
assertTrue("Test".equals(adapter.getFwPolicyType()));
adapter.setFwattributes(new ArrayList<>());
- assertTrue(adapter.getFwattributes()!=null);
+ assertTrue(adapter.getFwattributes() != null);
adapter.setParentForChild("Test");
assertTrue("Test".equals(adapter.getParentForChild()));
adapter.setSecurityZone("Test");
@@ -159,27 +161,27 @@ public class PolicyRestAdapterTest {
adapter.setRuleCombiningAlgId("Test");
assertTrue("Test".equals(adapter.getRuleCombiningAlgId()));
adapter.setDynamicFieldConfigAttributes(new HashMap<>());
- assertTrue(adapter.getDynamicFieldConfigAttributes()!=null);
+ assertTrue(adapter.getDynamicFieldConfigAttributes() != null);
adapter.setDynamicSettingsMap(new HashMap<>());
- assertTrue(adapter.getDynamicSettingsMap()!=null);
+ assertTrue(adapter.getDynamicSettingsMap() != null);
adapter.setDropDownMap(new HashMap<>());
- assertTrue(adapter.getDropDownMap()!=null);
+ assertTrue(adapter.getDropDownMap() != null);
adapter.setActionPerformer("Test");
assertTrue("Test".equals(adapter.getActionPerformer()));
adapter.setActionAttribute("Test");
assertTrue("Test".equals(adapter.getActionAttribute()));
adapter.setDynamicRuleAlgorithmLabels(new ArrayList<>());
- assertTrue(adapter.getDynamicRuleAlgorithmLabels()!=null);
+ assertTrue(adapter.getDynamicRuleAlgorithmLabels() != null);
adapter.setDynamicRuleAlgorithmCombo(new ArrayList<>());
- assertTrue(adapter.getDynamicRuleAlgorithmCombo()!=null);
+ assertTrue(adapter.getDynamicRuleAlgorithmCombo() != null);
adapter.setDynamicRuleAlgorithmField1(new ArrayList<>());
- assertTrue(adapter.getDynamicRuleAlgorithmField1()!=null);
+ assertTrue(adapter.getDynamicRuleAlgorithmField1() != null);
adapter.setDynamicRuleAlgorithmField2(new ArrayList<>());
- assertTrue(adapter.getDynamicRuleAlgorithmField2()!=null);
+ assertTrue(adapter.getDynamicRuleAlgorithmField2() != null);
adapter.setDynamicVariableList(new ArrayList<>());
- assertTrue(adapter.getDynamicVariableList()!=null);
+ assertTrue(adapter.getDynamicVariableList() != null);
adapter.setDataTypeList(new ArrayList<>());
- assertTrue(adapter.getDataTypeList()!=null);
+ assertTrue(adapter.getDataTypeList() != null);
adapter.setActionAttributeValue("Test");
assertTrue("Test".equals(adapter.getActionAttributeValue()));
adapter.setRuleProvider("Test");
@@ -195,15 +197,15 @@ public class PolicyRestAdapterTest {
adapter.setActionDictMethod("Test");
assertTrue("Test".equals(adapter.getActionDictMethod()));
adapter.setYamlparams(new YAMLParams());
- assertTrue(adapter.getYamlparams()!=null);
+ assertTrue(adapter.getYamlparams() != null);
adapter.setRainyday(new RainyDayParams());
- assertTrue(adapter.getRainyday()!=null);
+ assertTrue(adapter.getRainyday() != null);
adapter.setRainydayMap(new HashMap<>());
- assertTrue(adapter.getRainydayMap()!=null);
+ assertTrue(adapter.getRainydayMap() != null);
adapter.setErrorCodeList(new ArrayList<>());
- assertTrue(adapter.getErrorCodeList()!=null);
+ assertTrue(adapter.getErrorCodeList() != null);
adapter.setTreatmentList(new ArrayList<>());
- assertTrue(adapter.getTreatmentList()!=null);
+ assertTrue(adapter.getTreatmentList() != null);
adapter.setServiceType("Test");
assertTrue("Test".equals(adapter.getServiceType()));
adapter.setUuid("Test");
@@ -219,17 +221,17 @@ public class PolicyRestAdapterTest {
adapter.setRuleName("Test");
assertTrue("Test".equals(adapter.getRuleName()));
adapter.setBrmsParamBody(new HashMap<>());
- assertTrue(adapter.getBrmsParamBody()!=null);
+ assertTrue(adapter.getBrmsParamBody() != null);
adapter.setBrmsController("Test");
assertTrue("Test".equals(adapter.getBrmsController()));
adapter.setBrmsDependency(new ArrayList<>());
- assertTrue(adapter.getBrmsDependency()!=null);
+ assertTrue(adapter.getBrmsDependency() != null);
adapter.setRuleData(new LinkedHashMap<>());
- assertTrue(adapter.getRuleData()!=null);
+ assertTrue(adapter.getRuleData() != null);
adapter.setRuleListData(new LinkedHashMap<>());
- assertTrue(adapter.getRuleListData()!=null);
+ assertTrue(adapter.getRuleListData() != null);
adapter.setDrlRuleAndUIParams(new LinkedHashMap<>());
- assertTrue(adapter.getDrlRuleAndUIParams()!=null);
+ assertTrue(adapter.getDrlRuleAndUIParams() != null);
adapter.setPolicyScope("Test");
assertTrue("Test".equals(adapter.getPolicyScope()));
adapter.setProviderComboBox("Test");
@@ -243,11 +245,11 @@ public class PolicyRestAdapterTest {
adapter.setTtlDate("Test");
assertTrue("Test".equals(adapter.getTtlDate()));
adapter.setMatching(new LinkedHashMap<>());
- assertTrue(adapter.getMatching()!=null);
+ assertTrue(adapter.getMatching() != null);
adapter.setTriggerSignatures(new ArrayList<>());
- assertTrue(adapter.getTriggerSignatures()!=null);
+ assertTrue(adapter.getTriggerSignatures() != null);
adapter.setSymptomSignatures(new ArrayList<>());
- assertTrue(adapter.getSymptomSignatures()!=null);
+ assertTrue(adapter.getSymptomSignatures() != null);
adapter.setLogicalConnector("Test");
assertTrue("Test".equals(adapter.getLogicalConnector()));
adapter.setPolicyStatus("Test");
@@ -257,4 +259,26 @@ public class PolicyRestAdapterTest {
adapter.setSupressionType("Test");
assertTrue("Test".equals(adapter.getSupressionType()));
}
+
+ @Test
+ public void testPublic() {
+ PolicyRestAdapter adapter = new PolicyRestAdapter();
+ adapter.setupUsingAttribute("ONAPName", "onapvalue");
+ adapter.setupUsingAttribute("RiskType", "riskvalue");
+ adapter.setupUsingAttribute("RiskLevel", "risklevel");
+ adapter.setupUsingAttribute("guard", "guardvalue");
+ adapter.setupUsingAttribute("ConfigName", "configvalue");
+ adapter.setupUsingAttribute("uuid", "uuidvalue");
+ adapter.setupUsingAttribute("location", "locationvalue");
+ assertEquals("riskvalue", adapter.getRiskType());
+ assertEquals("risklevel", adapter.getRiskLevel());
+ assertEquals("guardvalue", adapter.getGuard());
+ assertEquals("onapvalue", adapter.getOnapName());
+ assertEquals("onapvalue", adapter.getOnapNameField().getName());
+ assertEquals("uuidvalue", adapter.getUuid());
+ assertEquals("locationvalue", adapter.getLocation());
+ assertEquals("configvalue", adapter.getConfigName());
+
+ assertFalse(adapter.setupUsingAttribute("foobar", "foo"));
+ }
}
diff --git a/ONAP-REST/src/test/java/org/onap/policy/rest/dao/PolicyDBExceptionTest.java b/ONAP-REST/src/test/java/org/onap/policy/rest/dao/PolicyDbExceptionTest.java
index 0cd89a40e..5293477e8 100644
--- a/ONAP-REST/src/test/java/org/onap/policy/rest/dao/PolicyDBExceptionTest.java
+++ b/ONAP-REST/src/test/java/org/onap/policy/rest/dao/PolicyDbExceptionTest.java
@@ -3,13 +3,14 @@
* PolicyEngineUtils
* ================================================================================
* Copyright (C) 2018 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2019 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -23,32 +24,32 @@ package org.onap.policy.rest.dao;
import java.io.IOException;
import org.junit.Test;
-public class PolicyDBExceptionTest {
- @Test(expected = PolicyDBException.class)
- public void testException1() throws PolicyDBException {
- throw new PolicyDBException();
- }
+public class PolicyDbExceptionTest {
+ @Test(expected = PolicyDbException.class)
+ public void testException1() throws PolicyDbException {
+ throw new PolicyDbException();
+ }
- @Test(expected = PolicyDBException.class)
- public void testException2() throws PolicyDBException {
- throw new PolicyDBException("test");
- }
+ @Test(expected = PolicyDbException.class)
+ public void testException2() throws PolicyDbException {
+ throw new PolicyDbException("test");
+ }
- @Test(expected = PolicyDBException.class)
- public void testException3() throws PolicyDBException {
- Throwable cause = new IOException();
- throw new PolicyDBException(cause);
- }
+ @Test(expected = PolicyDbException.class)
+ public void testException3() throws PolicyDbException {
+ Throwable cause = new IOException();
+ throw new PolicyDbException(cause);
+ }
- @Test(expected = PolicyDBException.class)
- public void testException4() throws PolicyDBException {
- Throwable cause = new IOException();
- throw new PolicyDBException("test", cause);
- }
+ @Test(expected = PolicyDbException.class)
+ public void testException4() throws PolicyDbException {
+ Throwable cause = new IOException();
+ throw new PolicyDbException("test", cause);
+ }
- @Test(expected = PolicyDBException.class)
- public void testException5() throws PolicyDBException {
- Throwable cause = new IOException();
- throw new PolicyDBException("test", cause, true, true);
- }
+ @Test(expected = PolicyDbException.class)
+ public void testException5() throws PolicyDbException {
+ Throwable cause = new IOException();
+ throw new PolicyDbException("test", cause, true, true);
+ }
}
diff --git a/ONAP-REST/src/test/java/org/onap/policy/rest/daoimpl/PolicyValidationDaoImplTest.java b/ONAP-REST/src/test/java/org/onap/policy/rest/daoimpl/PolicyValidationDaoImplTest.java
index f5d968b14..3cedd2312 100644
--- a/ONAP-REST/src/test/java/org/onap/policy/rest/daoimpl/PolicyValidationDaoImplTest.java
+++ b/ONAP-REST/src/test/java/org/onap/policy/rest/daoimpl/PolicyValidationDaoImplTest.java
@@ -3,13 +3,15 @@
* ONAP-REST
* ================================================================================
* Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Modifications copyright (c) 2019 Nokia
+ * Modifications Copyright (C) 2019 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -17,11 +19,19 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.policy.rest.daoimpl;
-import static org.junit.Assert.*;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
import java.io.File;
+import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
@@ -31,411 +41,633 @@ import javax.script.SimpleBindings;
import org.apache.tomcat.dbcp.dbcp2.BasicDataSource;
import org.h2.tools.Server;
+import org.hibernate.Query;
+import org.hibernate.Session;
import org.hibernate.SessionFactory;
+import org.hibernate.Transaction;
import org.junit.After;
-import org.junit.Before;
+import org.junit.AfterClass;
+import org.junit.BeforeClass;
import org.junit.Test;
import org.onap.policy.common.logging.flexlogger.FlexLogger;
import org.onap.policy.common.logging.flexlogger.Logger;
-//import org.onap.policy.conf.HibernateSession;
-//import org.onap.policy.controller.PolicyController;
import org.onap.policy.rest.jpa.OnapName;
import org.onap.policy.rest.jpa.PolicyEntity;
import org.onap.policy.rest.jpa.PolicyRoles;
import org.onap.policy.rest.jpa.PolicyVersion;
-import org.onap.policy.rest.jpa.SystemLogDB;
+import org.onap.policy.rest.jpa.SystemLogDb;
import org.onap.policy.rest.jpa.UserInfo;
import org.onap.policy.rest.jpa.WatchPolicyNotificationTable;
import org.springframework.orm.hibernate4.LocalSessionFactoryBuilder;
-import org.springframework.transaction.annotation.Transactional;
import org.springframework.test.annotation.Rollback;
-
+import org.springframework.transaction.annotation.Transactional;
public class PolicyValidationDaoImplTest {
private static Logger logger = FlexLogger.getLogger(PolicyValidationDaoImplTest.class);
- SessionFactory sessionFactory;
- Server server;
- PolicyValidationDaoImpl commonClassDao;
-
- @Before
- public void setUp() throws Exception{
- try{
- BasicDataSource dataSource = new BasicDataSource();
- dataSource.setDriverClassName("org.h2.Driver");
- // In-memory DB for testing
- dataSource.setUrl("jdbc:h2:mem:test");
- dataSource.setUsername("sa");
- dataSource.setPassword("");
- LocalSessionFactoryBuilder sessionBuilder = new LocalSessionFactoryBuilder(dataSource);
- sessionBuilder.scanPackages("org.onap.*", "com.*");
-
- Properties properties = new Properties();
- properties.put("hibernate.show_sql", "false");
- properties.put("hibernate.dialect", "org.hibernate.dialect.H2Dialect");
- properties.put("hibernate.hbm2ddl.auto", "drop");
- properties.put("hibernate.hbm2ddl.auto", "create");
-
- sessionBuilder.addProperties(properties);
- sessionFactory = sessionBuilder.buildSessionFactory();
-
- // Set up dao with SessionFactory
- commonClassDao = new PolicyValidationDaoImpl();
- PolicyValidationDaoImpl.setSessionfactory(sessionFactory);
- //PolicyController.setLogTableLimit("1");
- //HibernateSession.setSession(sessionFactory);
- SystemLogDB data1 = new SystemLogDB();
- data1.setDate(new Date());
- data1.setLogtype("INFO");
- data1.setRemote("Test");
- data1.setSystem("Test");
- data1.setType("Test");
- SystemLogDB data2 = new SystemLogDB();
- data2.setDate(new Date());
- data2.setLogtype("error");
- data2.setRemote("Test");
- data2.setSystem("Test");
- data2.setType("Test");
- //HibernateSession.getSession().save(data1);
- //HibernateSession.getSession().save(data2);
-
- // Create TCP server for troubleshooting
- server = Server.createTcpServer("-tcpAllowOthers").start();
- System.out.println("URL: jdbc:h2:" + server.getURL() + "/mem:test");
-
- }catch(Exception e){
- System.err.println(e);
- fail();
- }
+ static SessionFactory sessionFactory;
+ static Server server;
+ static PolicyValidationDaoImpl commonClassDao;
+
+ /**
+ * Set up all unit tests.
+ *
+ * @throws SQLException on SQL exceptions
+ */
+ @BeforeClass
+ public static void setupAll() throws SQLException {
+ BasicDataSource dataSource = new BasicDataSource();
+ dataSource.setDriverClassName("org.h2.Driver");
+ // In-memory DB for testing
+ dataSource.setUrl("jdbc:h2:mem:test");
+ dataSource.setUsername("sa");
+ dataSource.setPassword("");
+ LocalSessionFactoryBuilder sessionBuilder = new LocalSessionFactoryBuilder(dataSource);
+ sessionBuilder.scanPackages("org.onap.*", "com.*");
+
+ Properties properties = new Properties();
+ properties.put("hibernate.show_sql", "false");
+ properties.put("hibernate.dialect", "org.hibernate.dialect.H2Dialect");
+ properties.put("hibernate.hbm2ddl.auto", "drop");
+ properties.put("hibernate.hbm2ddl.auto", "create");
+
+ sessionBuilder.addProperties(properties);
+ sessionFactory = sessionBuilder.buildSessionFactory();
+
+ // Set up dao with SessionFactory
+ commonClassDao = new PolicyValidationDaoImpl();
+ PolicyValidationDaoImpl.setSessionfactory(sessionFactory);
+ // PolicyController.setLogTableLimit("1");
+ // HibernateSession.setSession(sessionFactory);
+ SystemLogDb data1 = new SystemLogDb();
+ data1.setDate(new Date());
+ data1.setLogtype("INFO");
+ data1.setRemote("Test");
+ data1.setSystem("Test");
+ data1.setType("Test");
+ SystemLogDb data2 = new SystemLogDb();
+ data2.setDate(new Date());
+ data2.setLogtype("error");
+ data2.setRemote("Test");
+ data2.setSystem("Test");
+ data2.setType("Test");
+
+ // Create TCP server for troubleshooting
+ server = Server.createTcpServer("-tcpAllowOthers").start();
+ System.out.println("URL: jdbc:h2:" + server.getURL() + "/mem:test");
+ }
+
+ @AfterClass
+ public static void deleteDB() {
+ sessionFactory.close();
+ server.stop();
+ }
+
+ @After
+ public void tearDown() {
+ truncateAllTables();
}
@Test
@Transactional
@Rollback(true)
- public void testDB(){
- try{
- // Add data
- UserInfo userinfo = new UserInfo();
- userinfo.setUserLoginId("Test");
- userinfo.setUserName("Test");
- commonClassDao.save(userinfo);
- OnapName onapName = new OnapName();
- onapName.setOnapName("Test");
- onapName.setUserCreatedBy(userinfo);
- onapName.setUserModifiedBy(userinfo);
- onapName.setModifiedDate(new Date());
- commonClassDao.save(onapName);
-
-
- List<Object> list = commonClassDao.getData(OnapName.class);
- assertTrue(list.size() == 1);
- logger.debug(list.size());
- logger.debug(list.get(0));
- }catch(Exception e){
- logger.debug("Exception Occured"+e);
- fail();
- }
+ public void testDB() {
+ // Add data
+ UserInfo userinfo = new UserInfo();
+ userinfo.setUserLoginId("Test");
+ userinfo.setUserName("Test");
+ commonClassDao.save(userinfo);
+ OnapName onapName = new OnapName();
+ onapName.setName("Test");
+ onapName.setUserCreatedBy(userinfo);
+ onapName.setUserModifiedBy(userinfo);
+ onapName.setModifiedDate(new Date());
+ commonClassDao.save(onapName);
+
+ List<Object> list = commonClassDao.getData(OnapName.class);
+ assertTrue(list.size() == 1);
+ logger.debug(list.size());
+ logger.debug(list.get(0));
}
@Test
@Transactional
@Rollback(true)
- public void testUser(){
- try{
- // Add data
- UserInfo userinfo = new UserInfo();
- String loginId_userName = "Test";
- userinfo.setUserLoginId(loginId_userName);
- userinfo.setUserName(loginId_userName);
- commonClassDao.save(userinfo);
-
-
- List<Object> dataCur = commonClassDao.getDataByQuery("from UserInfo", new SimpleBindings());
-
- assertEquals(1, dataCur.size());
- UserInfo cur = (UserInfo) dataCur.get(0);
- assertEquals(loginId_userName, cur.getUserLoginId());
- assertEquals(loginId_userName, cur.getUserName());
-
- assertFalse(dataCur.isEmpty());
-
- }catch(Exception e){
- logger.debug("Exception Occured"+e);
- fail();
- }
+ public void testUser() {
+ // Add data
+ UserInfo userinfo = new UserInfo();
+ String loginIdUserName = "Test";
+ userinfo.setUserLoginId(loginIdUserName);
+ userinfo.setUserName(loginIdUserName);
+ commonClassDao.save(userinfo);
+
+ List<Object> dataCur = commonClassDao.getDataByQuery("from UserInfo", new SimpleBindings());
+
+ assertEquals(1, dataCur.size());
+ UserInfo cur = (UserInfo) dataCur.get(0);
+ assertEquals(loginIdUserName, cur.getUserLoginId());
+ assertEquals(loginIdUserName, cur.getUserName());
+
+ assertFalse(dataCur.isEmpty());
}
@Test
@Transactional
@Rollback(true)
- public void getDataByQuery_DashboardController(){
- try{
- // Add data
- PolicyEntity pe = new PolicyEntity();
- String name = "TestPolicy";
- pe.setPolicyName(name);
- pe.setPolicyData("dummyData");
- pe.prePersist();
- pe.setScope("dummyScope");
- pe.setDescription("descr");
- pe.setDeleted(false);
- pe.setCreatedBy("Test");
- commonClassDao.save(pe);
-
- List<Object> dataCur = commonClassDao.getDataByQuery("from PolicyEntity", new SimpleBindings());
-
- assertTrue(1 == dataCur.size());
- assertTrue( dataCur.get(0) instanceof PolicyEntity);
- assertEquals( name, ((PolicyEntity)dataCur.get(0)).getPolicyName());
- assertEquals( pe, ((PolicyEntity)dataCur.get(0)));
-
-
- }catch(Exception e){
- logger.debug("Exception Occured"+e);
- fail();
- }
+ public void getDataByQuery_DashboardController() {
+ // Add data
+ PolicyEntity pe = new PolicyEntity();
+ String name = "TestPolicy";
+ pe.setPolicyName(name);
+ pe.setPolicyData("dummyData");
+ pe.prePersist();
+ pe.setScope("dummyScope");
+ pe.setDescription("descr");
+ pe.setDeleted(false);
+ pe.setCreatedBy("Test");
+ commonClassDao.save(pe);
+
+ List<Object> dataCur = commonClassDao.getDataByQuery("from PolicyEntity", new SimpleBindings());
+
+ assertTrue(1 == dataCur.size());
+ assertTrue(dataCur.get(0) instanceof PolicyEntity);
+ assertEquals(name, ((PolicyEntity) dataCur.get(0)).getPolicyName());
+ assertEquals(pe, (dataCur.get(0)));
}
@Test
@Transactional
@Rollback(true)
- public void getDataByQuery_AutoPushController(){
- try{
- // Add data
- PolicyVersion pv = new PolicyVersion();
- pv.setActiveVersion(2);
- pv.setPolicyName("myPname");
- pv.prePersist();
- pv.setCreatedBy("Test");
- pv.setModifiedBy("Test");
-
- PolicyVersion pv2 = new PolicyVersion();
- pv2.setActiveVersion(1);
- pv2.setPolicyName("test");
- pv2.prePersist();
- pv2.setCreatedBy("Test");
- pv2.setModifiedBy("Test");
-
- commonClassDao.save(pv);
- commonClassDao.save(pv2);
-
- String scope = "my";
- scope += "%";
- String query = "From PolicyVersion where policy_name like :scope and id > 0";
- SimpleBindings params = new SimpleBindings();
- params.put("scope", scope);
- List<Object> dataCur = commonClassDao.getDataByQuery(query, params);
-
-
- assertTrue(1 == dataCur.size());
- assertEquals(pv, (PolicyVersion) dataCur.get(0));
-
- }catch(Exception e){
- logger.debug("Exception Occured"+e);
- fail();
- }
+ public void getDataByQuery_AutoPushController() {
+ // Add data
+ PolicyVersion pv = new PolicyVersion();
+ pv.setActiveVersion(2);
+ pv.setPolicyName("myPname");
+ pv.prePersist();
+ pv.setCreatedBy("Test");
+ pv.setModifiedBy("Test");
+
+ PolicyVersion pv2 = new PolicyVersion();
+ pv2.setActiveVersion(1);
+ pv2.setPolicyName("test");
+ pv2.prePersist();
+ pv2.setCreatedBy("Test");
+ pv2.setModifiedBy("Test");
+
+ commonClassDao.save(pv);
+ commonClassDao.save(pv2);
+
+ String scope = "my";
+ scope += "%";
+ String query = "From PolicyVersion where policy_name like :scope and id > 0";
+ SimpleBindings params = new SimpleBindings();
+ params.put("scope", scope);
+ List<Object> dataCur = commonClassDao.getDataByQuery(query, params);
+
+ assertTrue(1 == dataCur.size());
+ assertEquals(pv, dataCur.get(0));
}
@Test
@Transactional
@Rollback(true)
- public void getDataByQuery_PolicyNotificationMail(){
- try{
- // Add data
- WatchPolicyNotificationTable watch = new WatchPolicyNotificationTable();
- String policyFileName = "banana";
- watch.setLoginIds("Test");
- watch.setPolicyName("bananaWatch");
- commonClassDao.save(watch);
-
- 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("\\", "\\\\");
- }
-
-
- // Current Implementation
- policyFileName += "%";
- String query = "from WatchPolicyNotificationTable where policyName like:policyFileName";
- SimpleBindings params = new SimpleBindings();
- params.put("policyFileName", policyFileName);
- List<Object> dataCur = commonClassDao.getDataByQuery(query, params);
-
- // Assertions
- assertTrue(dataCur.size() == 1);
- assertTrue(dataCur.get(0) instanceof WatchPolicyNotificationTable);
- assertEquals(watch, (WatchPolicyNotificationTable) dataCur.get(0));
-
- }catch(Exception e){
- logger.debug("Exception Occured"+e);
- fail();
+ public void getDataByQuery_PolicyNotificationMail() {
+ // Add data
+ WatchPolicyNotificationTable watch = new WatchPolicyNotificationTable();
+ watch.setLoginIds("Test");
+
+ // Add data
+ UserInfo userinfo = new UserInfo();
+ String loginIdUserName = "Test";
+ userinfo.setUserLoginId(loginIdUserName);
+ userinfo.setUserName(loginIdUserName);
+ commonClassDao.save(userinfo);
+
+ List<Object> dataCur = commonClassDao.getDataByQuery("from UserInfo", new SimpleBindings());
+
+ assertEquals(1, dataCur.size());
+ UserInfo cur = (UserInfo) dataCur.get(0);
+ assertEquals(loginIdUserName, cur.getUserLoginId());
+ assertEquals(loginIdUserName, cur.getUserName());
+
+ assertFalse(dataCur.isEmpty());
+
+ watch.setPolicyName("bananaWatch");
+ commonClassDao.save(watch);
+
+ String policyFileName = "banana";
+ 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("\\", "\\\\");
}
- }
+ // Current Implementation
+ policyFileName += "%";
+ String query = "from WatchPolicyNotificationTable where policyName like:policyFileName";
+ SimpleBindings params = new SimpleBindings();
+ params.put("policyFileName", policyFileName);
+ dataCur = commonClassDao.getDataByQuery(query, params);
+
+ // Assertions
+ assertTrue(dataCur.size() == 1);
+ assertTrue(dataCur.get(0) instanceof WatchPolicyNotificationTable);
+ assertEquals(watch, dataCur.get(0));
+ }
@Test
@Transactional
@Rollback(true)
- public void getDataByQuery_PolicyController(){
- try{
- // Add data
- PolicyEntity pe = new PolicyEntity();
- String name = "actionDummy";
- pe.setPolicyName(name);
- pe.setPolicyData("dummyData");
- pe.prePersist();
- pe.setScope("dummyScope");
- pe.setDescription("descr");
- pe.setDeleted(false);
- pe.setCreatedBy("Test");
- commonClassDao.save(pe);
-
- String dbCheckName = "dummyScope:action";
- String[] splitDBCheckName = dbCheckName.split(":");
-
-
- // Current Implementation
- String query = "FROM PolicyEntity where policyName like :splitDBCheckName1 and scope = :splitDBCheckName0";
- SimpleBindings params = new SimpleBindings();
- params.put("splitDBCheckName1", splitDBCheckName[1] + "%");
- params.put("splitDBCheckName0", splitDBCheckName[0]);
- List<Object> dataCur = commonClassDao.getDataByQuery(query, params);
-
- // Assertions
- assertTrue(dataCur.size() == 1);
- assertTrue(dataCur.get(0) instanceof PolicyEntity);
- assertEquals(pe, (PolicyEntity) dataCur.get(0));
-
- }catch(Exception e){
- logger.debug("Exception Occured"+e);
- fail();
- }
+ public void getDataByQuery_PolicyController() {
+ // Add data
+ PolicyEntity pe = new PolicyEntity();
+ String name = "actionDummy";
+ pe.setPolicyName(name);
+ pe.setPolicyData("dummyData");
+ pe.prePersist();
+ pe.setScope("dummyScope");
+ pe.setDescription("descr");
+ pe.setDeleted(false);
+ pe.setCreatedBy("Test");
+ commonClassDao.save(pe);
+
+ String dbCheckName = "dummyScope:action";
+ String[] splitDbCheckName = dbCheckName.split(":");
+
+ // Current Implementation
+ String query = "FROM PolicyEntity where policyName like :splitDBCheckName1 and scope = :splitDBCheckName0";
+ SimpleBindings params = new SimpleBindings();
+ params.put("splitDBCheckName1", splitDbCheckName[1] + "%");
+ params.put("splitDBCheckName0", splitDbCheckName[0]);
+ List<Object> dataCur = commonClassDao.getDataByQuery(query, params);
+
+ // Assertions
+ assertTrue(dataCur.size() == 1);
+ assertTrue(dataCur.get(0) instanceof PolicyEntity);
+ assertEquals(pe, dataCur.get(0));
}
@Test
@Transactional
@Rollback(true)
- public void getDataByQuery_PolicyNotificationController(){
- try{
- // Add data
- WatchPolicyNotificationTable watch = new WatchPolicyNotificationTable();
- String finalName = "banana"; // Policy File Name
- String userId = "Test";
- watch.setLoginIds(userId);
- watch.setPolicyName(finalName);
- commonClassDao.save(watch);
-
-
- // Current Implementation
- String query = "from WatchPolicyNotificationTable where POLICYNAME = :finalName and LOGINIDS = :userId";
- SimpleBindings params = new SimpleBindings();
- params.put("finalName", finalName);
- params.put("userId", userId);
- List<Object> dataCur = commonClassDao.getDataByQuery(query, params);
-
- // Assertions
- assertTrue(dataCur.size() == 1);
- assertTrue(dataCur.get(0) instanceof WatchPolicyNotificationTable);
- assertEquals(watch, (WatchPolicyNotificationTable) dataCur.get(0) );
-
- }catch(Exception e){
- logger.debug("Exception Occured"+e);
- fail();
- }
+ public void getDataByQuery_PolicyNotificationController() {
+ // Add data
+ WatchPolicyNotificationTable watch = new WatchPolicyNotificationTable();
+ String finalName = "banana"; // Policy File Name
+ String userId = "Test";
+ watch.setLoginIds(userId);
+ watch.setPolicyName(finalName);
+ commonClassDao.save(watch);
+
+ // Current Implementation
+ String query = "from WatchPolicyNotificationTable where POLICYNAME = :finalName and LOGINIDS = :userId";
+ SimpleBindings params = new SimpleBindings();
+ params.put("finalName", finalName);
+ params.put("userId", userId);
+ List<Object> dataCur = commonClassDao.getDataByQuery(query, params);
+
+ // Assertions
+ assertTrue(dataCur.size() == 1);
+ assertTrue(dataCur.get(0) instanceof WatchPolicyNotificationTable);
+ assertEquals(watch, dataCur.get(0));
+
+ WatchPolicyNotificationTable table0 = new WatchPolicyNotificationTable();
+ WatchPolicyNotificationTable table1 = new WatchPolicyNotificationTable();
+ assertEquals(table0, table0);
+ assertEquals(table0, table1);
+ assertNotEquals(table0, null);
+ String helloString = "Hello";
+ Object helloObject = helloString;
+ assertNotEquals(table0, helloObject);
+
+ table0.setId(1);
+ assertNotEquals(table0, table1);
+ table1.setId(1);
+ assertEquals(table0, table1);
+
+ table0.setPolicyName("GoToOz");
+ assertNotEquals(table0, table1);
+ table1.setPolicyName("GoToOz");
+ assertEquals(table0, table1);
+ table1.setPolicyName(null);
+ assertNotEquals(table0, table1);
+ table0.setPolicyName(null);
+ assertEquals(table0, table1);
+ table1.setPolicyName("GoToOz");
+ assertNotEquals(table0, table1);
+ table0.setPolicyName("GoToOz");
+ assertEquals(table0, table1);
+ assertEquals(table0, table1);
+ table1.setPolicyName("InOz");
+ assertNotEquals(table0, table1);
+ table0.setPolicyName("InOz");
+ assertEquals(table0, table1);
+
+ table0.setLoginIds("Wizard");
+ assertNotEquals(table0, table1);
+ table1.setLoginIds("Wizard");
+ assertEquals(table0, table1);
+ table1.setLoginIds(null);
+ assertNotEquals(table0, table1);
+ table0.setLoginIds(null);
+ assertEquals(table0, table1);
+ table0.setLoginIds("Wizard");
+ assertNotEquals(table0, table1);
+ table1.setLoginIds("Wizard");
+ assertEquals(table0, table1);
+ table1.setLoginIds(null);
+ table1.setLoginIds("Witch");
+ assertNotEquals(table0, table1);
+ table0.setLoginIds("Witch");
+ assertEquals(table0, table1);
+
+ assertNotNull(table0.hashCode());
+ assertNotNull(table1.hashCode());
+ assertEquals(table0.hashCode(), table0.hashCode());
+
+ table0.setLoginIds("Witci");
+ assertNotEquals(table0, table1);
+ assertNotEquals(table0.hashCode(), table1.hashCode());
}
-
- /* Test for SQL Injection Protection
+ /*
+ * Test for SQL Injection Protection
*/
@Test
@Transactional
@Rollback(true)
- public void getDataByQuery_PolicyNotificationController_Injection(){
- try{
- // Add data
- WatchPolicyNotificationTable watch = new WatchPolicyNotificationTable();
- String userId = "Test";
- watch.setLoginIds(userId);
- watch.setPolicyName("banana");
- commonClassDao.save(watch);
-
- WatchPolicyNotificationTable watch2 = new WatchPolicyNotificationTable();
- watch2.setLoginIds(userId);
- watch2.setPolicyName("banana2");
- commonClassDao.save(watch2);
-
- // SQL Injection attempt
- String finalName = "banana' OR '1'='1";
-
-
- // Current Implementation
- String query = "from WatchPolicyNotificationTable where POLICYNAME = :finalName and LOGINIDS = :userId";
- SimpleBindings params = new SimpleBindings();
- params.put("finalName", finalName);
- params.put("userId", userId);
- List<Object> dataCur = commonClassDao.getDataByQuery(query, params);
-
- // Assertions
- assertTrue(dataCur.size() <= 1);
-
- if(dataCur.size() >= 1){
- assertTrue(dataCur.get(0) instanceof WatchPolicyNotificationTable);
- assertFalse(watch.equals((WatchPolicyNotificationTable) dataCur.get(0)));
- assertFalse(watch.equals((WatchPolicyNotificationTable) dataCur.get(0)));
- }
- }catch(Exception e){
- logger.debug("Exception Occured"+e);
- fail();
+ public void getDataByQuery_PolicyNotificationController_Injection() {
+ // Add data
+ WatchPolicyNotificationTable watch = new WatchPolicyNotificationTable();
+ String userId = "Test";
+ watch.setLoginIds(userId);
+ watch.setPolicyName("banana");
+ commonClassDao.save(watch);
+
+ WatchPolicyNotificationTable watch2 = new WatchPolicyNotificationTable();
+ watch2.setLoginIds(userId);
+ watch2.setPolicyName("banana2");
+ commonClassDao.save(watch2);
+
+ // SQL Injection attempt
+ String finalName = "banana' OR '1'='1";
+
+ // Current Implementation
+ String query = "from WatchPolicyNotificationTable where POLICYNAME = :finalName and LOGINIDS = :userId";
+ SimpleBindings params = new SimpleBindings();
+ params.put("finalName", finalName);
+ params.put("userId", userId);
+ List<Object> dataCur = commonClassDao.getDataByQuery(query, params);
+
+ // Assertions
+ assertTrue(dataCur.size() <= 1);
+
+ if (dataCur.size() >= 1) {
+ assertTrue(dataCur.get(0) instanceof WatchPolicyNotificationTable);
+ assertFalse(watch.equals(dataCur.get(0)));
+ assertFalse(watch.equals(dataCur.get(0)));
}
}
@Test
- public void testCommonClassDaoImplMethods(){
- try{
- UserInfo userInfo = new UserInfo();
- userInfo.setUserLoginId("TestID");
- userInfo.setUserName("Test");
- commonClassDao.save(userInfo);
- List<Object> data = commonClassDao.getDataById(UserInfo.class, "userLoginId:userName", "TestID:Test");
- assertTrue(data.size() == 1);
- UserInfo userInfoUpdate = (UserInfo) data.get(0);
- userInfoUpdate.setUserName("Test1");
- commonClassDao.update(userInfoUpdate);
- List<String> data1 = commonClassDao.getDataByColumn(UserInfo.class, "userLoginId");
- assertTrue(data1.size() == 1);
- UserInfo data2 = (UserInfo) commonClassDao.getEntityItem(UserInfo.class, "userLoginId:userName", "TestID:Test1");
- assertTrue("TestID".equals(data2.getUserLoginId()));
- List<Object> data3 = commonClassDao.checkDuplicateEntry("TestID:Test1", "userLoginId:userName", UserInfo.class);
- assertTrue(data3.size() == 1);
- PolicyRoles roles = new PolicyRoles();
- roles.setRole("admin");
- roles.setLoginId(userInfo);
- roles.setScope("test");
- commonClassDao.save(roles);
- List<PolicyRoles> roles1 = commonClassDao.getUserRoles();
- assertTrue(roles1.size() == 1);
- List<String> multipleData = new ArrayList<>();
- multipleData.add("TestID:Test1");
- List<Object> data4 = commonClassDao.getMultipleDataOnAddingConjunction(UserInfo.class, "userLoginId:userName", multipleData);
- assertTrue(data4.size() == 1);
- commonClassDao.delete(data2);
- }catch(Exception e){
- logger.debug("Exception Occured"+e);
- fail();
- }
+ public void testCommonClassDaoImplMethods() {
+ UserInfo userInfo = new UserInfo();
+ userInfo.setUserLoginId("TestID");
+ userInfo.setUserName("Test");
+ commonClassDao.save(userInfo);
+ List<Object> data = commonClassDao.getDataById(UserInfo.class, "userLoginId:userName", "TestID:Test");
+ assertTrue(data.size() == 1);
+ UserInfo userInfoUpdate = (UserInfo) data.get(0);
+ userInfoUpdate.setUserName("Test1");
+ commonClassDao.update(userInfoUpdate);
+ List<String> data1 = commonClassDao.getDataByColumn(UserInfo.class, "userLoginId");
+ assertTrue(data1.size() == 1);
+ UserInfo data2 = (UserInfo) commonClassDao.getEntityItem(UserInfo.class, "userLoginId:userName",
+ "TestID:Test1");
+ assertTrue("TestID".equals(data2.getUserLoginId()));
+ List<Object> data3 = commonClassDao.checkDuplicateEntry("TestID:Test1", "userLoginId:userName", UserInfo.class);
+ assertTrue(data3.size() == 1);
+ PolicyRoles roles = new PolicyRoles();
+ roles.setRole("admin");
+ roles.setLoginId(userInfo);
+ roles.setScope("test");
+ commonClassDao.save(roles);
+ List<PolicyRoles> roles1 = commonClassDao.getUserRoles();
+ assertTrue(roles1.size() == 1);
+ List<String> multipleData = new ArrayList<>();
+ multipleData.add("TestID:Test1");
+ List<Object> data4 = commonClassDao.getMultipleDataOnAddingConjunction(UserInfo.class, "userLoginId:userName",
+ multipleData);
+ assertTrue(data4.size() == 1);
+ commonClassDao.delete(data2);
}
- @After
- public void deleteDB(){
- sessionFactory.close();
- server.stop();
+ @Test
+ public void testGetDataByIdparameters() {
+ UserInfo userInfo = new UserInfo();
+ userInfo.setUserLoginId("TestID");
+ userInfo.setUserName("Test");
+ commonClassDao.save(userInfo);
+ List<Object> data = commonClassDao.getDataById(UserInfo.class, "userLoginId:userName", "TestID:Test");
+ assertTrue(data.size() == 1);
+ data = commonClassDao.getDataById(UserInfo.class, null, null);
+ assertNull(data);
+ data = commonClassDao.getDataById(UserInfo.class, "userLoginId:userName", null);
+ assertNull(data);
+ data = commonClassDao.getDataById(UserInfo.class, null, "TestID:Test");
+ assertNull(data);
+ data = commonClassDao.getDataById(UserInfo.class, "userLoginIduserName", "TestID:Test");
+ assertNull(data);
+ data = commonClassDao.getDataById(UserInfo.class, "userLoginIduserName", "TestIDTest");
+ assertNull(data);
+ data = commonClassDao.getDataById(UserInfo.class, "userLoginId data2.getUserLoginId()" + ":userName",
+ "TestIDTest");
+ assertNull(data);
+ commonClassDao.delete(data);
+ }
+
+ @Test
+ public void testGetDataByColumnParameters() {
+ UserInfo userInfo = new UserInfo();
+ userInfo.setUserLoginId("TestID");
+ userInfo.setUserName("Test");
+ commonClassDao.save(userInfo);
+ List<String> data = commonClassDao.getDataByColumn(UserInfo.class, "userLoginId");
+ assertTrue(data.size() == 1);
+ data = commonClassDao.getDataByColumn(null, null);
+ assertNull(data);
+ data = commonClassDao.getDataByColumn(UserInfo.class, null);
+ assertNull(data);
+ data = commonClassDao.getDataByColumn(null, "userLoginId");
+ assertNull(data);
+ commonClassDao.delete(data);
+ }
+
+ @Test
+ public void testGetMultipleDataOnAddingConjunctionParameters() {
+ UserInfo userInfo = new UserInfo();
+ userInfo.setUserLoginId("TestID");
+ userInfo.setUserName("Test");
+ assertEquals("Test", userInfo.getIdentiferByUserId().getUri().getPath());
+ commonClassDao.save(userInfo);
+ List<String> multipleData = new ArrayList<>();
+ multipleData.add("TestID:Test1");
+ List<Object> data = commonClassDao.getMultipleDataOnAddingConjunction(UserInfo.class, "userLoginId:userName",
+ multipleData);
+ assertTrue(data.size() == 0);
+ data = commonClassDao.getMultipleDataOnAddingConjunction(null, null, null);
+ assertNull(data);
+ data = commonClassDao.getMultipleDataOnAddingConjunction(null, null, multipleData);
+ assertNull(data);
+ data = commonClassDao.getMultipleDataOnAddingConjunction(null, "userLoginId:userName", null);
+ assertNull(data);
+ data = commonClassDao.getMultipleDataOnAddingConjunction(null, "userLoginId:userName", multipleData);
+ assertNull(data);
+ data = commonClassDao.getMultipleDataOnAddingConjunction(UserInfo.class, null, null);
+ assertNull(data);
+ data = commonClassDao.getMultipleDataOnAddingConjunction(UserInfo.class, null, multipleData);
+ assertNull(data);
+ data = commonClassDao.getMultipleDataOnAddingConjunction(UserInfo.class, "userLoginId:userName", null);
+ assertNull(data);
+ commonClassDao.delete(data);
+ }
+ @Test
+ public void testCheckDuplicateEntryParameters() {
+ UserInfo userInfo = new UserInfo();
+ userInfo.setUserLoginId("TestID");
+ userInfo.setUserName("Test");
+ commonClassDao.save(userInfo);
+ List<Object> data = commonClassDao.checkDuplicateEntry("TestID:Test1", "userLoginId:userName", UserInfo.class);
+ assertTrue(data.size() == 0);
+ data = commonClassDao.checkDuplicateEntry(null, null, UserInfo.class);
+ assertNull(data);
+ data = commonClassDao.checkDuplicateEntry("userLoginId:userName", null, UserInfo.class);
+ assertNull(data);
+ data = commonClassDao.checkDuplicateEntry(null, "TestID:Test", UserInfo.class);
+ assertNull(data);
+ data = commonClassDao.checkDuplicateEntry("userLoginIduserName", "TestID:Test", UserInfo.class);
+ assertNull(data);
+ data = commonClassDao.checkDuplicateEntry("userLoginId:userName", "TestID:Test:zooby", UserInfo.class);
+ assertNull(data);
+ data = commonClassDao.checkDuplicateEntry("userLoginId:userName", "TestID", UserInfo.class);
+ assertNull(data);
+ commonClassDao.delete(data);
+ }
+
+ @Test
+ public void testGetEntityItemParameters() {
+ UserInfo userInfo = new UserInfo();
+ userInfo.setUserLoginId("TestID");
+ userInfo.setUserName("Test");
+ commonClassDao.save(userInfo);
+ List<Object> data = commonClassDao.getDataById(UserInfo.class, "userLoginId:userName", "TestID:Test");
+ assertTrue(data.size() == 1);
+ UserInfo userInfoUpdate = (UserInfo) data.get(0);
+ userInfoUpdate.setUserName("Test1");
+ commonClassDao.update(userInfoUpdate);
+ List<String> data1 = commonClassDao.getDataByColumn(UserInfo.class, "userLoginId");
+ assertTrue(data1.size() == 1);
+ UserInfo data2 = (UserInfo) commonClassDao.getEntityItem(UserInfo.class, "userLoginId:userName",
+ "TestID:Test1");
+ assertTrue("TestID".equals(data2.getUserLoginId()));
+ data2 = (UserInfo) commonClassDao.getEntityItem(null, null, null);
+ assertNull(data2);
+ data2 = (UserInfo) commonClassDao.getEntityItem(null, null, "TestID:Test1");
+ assertNull(data2);
+ data2 = (UserInfo) commonClassDao.getEntityItem(null, "userLoginId:userName", null);
+ assertNull(data2);
+ data2 = (UserInfo) commonClassDao.getEntityItem(null, "userLoginId:userName", "TestID:Test1");
+ assertNull(data2);
+ data2 = (UserInfo) commonClassDao.getEntityItem(UserInfo.class, null, null);
+ assertNull(data2);
+ data2 = (UserInfo) commonClassDao.getEntityItem(UserInfo.class, null, "TestID:Test1");
+ assertNull(data2);
+ data2 = (UserInfo) commonClassDao.getEntityItem(UserInfo.class, "userLoginId:userName", null);
+ assertNull(data2);
+ data2 = (UserInfo) commonClassDao.getEntityItem(UserInfo.class, "userLoginIduserName", "TestID:Test1");
+ assertNull(data2);
+ data2 = (UserInfo) commonClassDao.getEntityItem(UserInfo.class, "userLoginId:userName", "TestIDTest1");
+ assertNull(data2);
+ commonClassDao.delete(data);
+ commonClassDao.delete(data1);
+ commonClassDao.delete(data2);
}
+ @Test
+ public void testOtherMethods() {
+ UserInfo userInfo = new UserInfo();
+ userInfo.setUserLoginId("TestID");
+ userInfo.setUserName("Test");
+ commonClassDao.save(userInfo);
+ commonClassDao.deleteAll();
+ List<Object> data = commonClassDao.getDataById(UserInfo.class, "userLoginId:userName", "TestID:Test");
+ assertTrue(data.size() == 1);
+
+ data = commonClassDao.checkExistingGroupListforUpdate(null, null);
+ assertTrue(data.size() == 0);
+
+ commonClassDao.updateClAlarms(null, null);
+ commonClassDao.updateClYaml(null, null);
+ data = commonClassDao.getDataById(UserInfo.class, "userLoginId:userName", "TestID:Test");
+ assertTrue(data.size() == 1);
+ commonClassDao.update(null);
+ assertTrue(data.size() == 1);
+ commonClassDao.getData(null);
+ assertTrue(data.size() == 1);
+ commonClassDao.delete(data);
+ }
+
+ @Test
+ public void testUpdateQuery() {
+ UserInfo userInfo = new UserInfo();
+ userInfo.setUserLoginId("TestID");
+ userInfo.setUserName("Test");
+ commonClassDao.save(userInfo);
+ commonClassDao.updateQuery("SELECT * FROM userLoginId");
+ List<Object> data = commonClassDao.getDataById(UserInfo.class, "userLoginId:userName", "TestID:Test");
+ assertTrue(data.size() == 1);
+
+ String query = "DELETE FROM org.onap.policy.rest.jpa.FunctionDefinition";
+ commonClassDao.updateQuery(query);
+ data = commonClassDao.getDataById(UserInfo.class, "userLoginId:userName", "TestID:Test");
+ assertTrue(data.size() == 1);
+ commonClassDao.delete(data);
+ }
+
+ @Test
+ public void testGetDataByQueryParameters() {
+ // Add data
+ UserInfo userinfo = new UserInfo();
+ String loginIdUserName = "Test";
+ userinfo.setUserLoginId(loginIdUserName);
+ userinfo.setUserName(loginIdUserName);
+ commonClassDao.save(userinfo);
+
+ SimpleBindings bindings = new SimpleBindings();
+ bindings.put("usercode", 1L);
+
+ try {
+ commonClassDao.getDataByQuery("from UserInfo", bindings);
+ fail("test should throw an exception here");
+ } catch (Exception exc) {
+ assertTrue(exc.getMessage().contains("Parameter usercode does not exist as a named parameter"));
+ }
+ }
+
+ private void truncateAllTables() {
+ Session session = sessionFactory.openSession();
+ Transaction transaction = session.beginTransaction();
+ sessionFactory.getAllClassMetadata().forEach((tableName, x) -> {
+ Query query = session.createQuery("DELETE FROM " + tableName);
+ query.executeUpdate();
+ });
+ transaction.commit();
+ session.close();
+ }
}
diff --git a/ONAP-REST/src/test/java/org/onap/policy/rest/jpa/ActionBodyEntityTest.java b/ONAP-REST/src/test/java/org/onap/policy/rest/jpa/ActionBodyEntityTest.java
index f8777d868..ab74d07f8 100644
--- a/ONAP-REST/src/test/java/org/onap/policy/rest/jpa/ActionBodyEntityTest.java
+++ b/ONAP-REST/src/test/java/org/onap/policy/rest/jpa/ActionBodyEntityTest.java
@@ -3,6 +3,7 @@
* ONAP-REST
* ================================================================================
* Copyright (C) 2018 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2019 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -25,43 +26,46 @@ import static org.hamcrest.CoreMatchers.not;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertThat;
+
import java.util.Date;
+
import org.junit.Test;
public class ActionBodyEntityTest {
- @Test
- public void testEntity() {
- // Set up test data
- String value = "testVal";
- Date date = new Date();
- ActionBodyEntity entity = new ActionBodyEntity();
- entity.prePersist();
- ActionBodyEntity entity2 = new ActionBodyEntity();
- ActionBodyEntity entity3 = new ActionBodyEntity();
+ @Test
+ public void testEntity() {
+ // Set up test data
+ String value = "testVal";
+ ActionBodyEntity entity = new ActionBodyEntity();
+ entity.prePersist();
+
+ // Test set and get
+ ActionBodyEntity entity0 = new ActionBodyEntity();
+ entity0.preUpdate();
+ entity0.setActionBody(value);
+ assertEquals(value, entity0.getActionBody());
+ entity0.setActionBodyName(value);
+ assertEquals(value, entity0.getActionBodyName());
+ entity0.setCreatedBy(value);
+ assertEquals(value, entity0.getCreatedBy());
+ entity0.setModifiedBy(value);
+ assertEquals(value, entity0.getModifiedBy());
- // Test set and get
- entity3.preUpdate();
- entity3.setActionBody(value);
- assertEquals(value, entity3.getActionBody());
- entity3.setActionBodyName(value);
- assertEquals(value, entity3.getActionBodyName());
- entity3.setCreatedBy(value);
- assertEquals(value, entity3.getCreatedBy());
- entity3.setModifiedBy(value);
- assertEquals(value, entity3.getModifiedBy());
- entity3.setModifiedDate(date);
- assertEquals(date, entity3.getModifiedDate());
- assertEquals(0, entity3.getVersion());
- assertNull(entity3.getCreatedDate());
- entity3.setDeleted(true);
- assertEquals(true, entity3.isDeleted());
- assertEquals(0, entity3.getActionBodyId());
+ Date date = new Date();
+ entity0.setModifiedDate(date);
+ assertEquals(date, entity0.getModifiedDate());
+ assertEquals(0, entity0.getVersion());
+ assertNull(entity0.getCreatedDate());
+ entity0.setDeleted(true);
+ assertEquals(true, entity0.isDeleted());
+ assertEquals(0, entity0.getActionBodyId());
- // Test equals method combinations
- assertEquals(false, entity.equals(null));
- assertEquals(true, entity.equals(entity));
- assertEquals(false, entity.equals(value));
- assertEquals(false, entity.equals(entity2));
- assertThat(entity.hashCode(), is(not(0)));
- }
+ // Test equals method combinations
+ assertEquals(false, entity.equals(null));
+ assertEquals(true, entity.equals(entity));
+ assertEquals(false, entity.equals((Object) value));
+ ActionBodyEntity entity1 = new ActionBodyEntity();
+ assertEquals(false, entity.equals(entity1));
+ assertThat(entity.hashCode(), is(not(0)));
+ }
}
diff --git a/ONAP-REST/src/test/java/org/onap/policy/rest/jpa/ActionDictionaryJPATest.java b/ONAP-REST/src/test/java/org/onap/policy/rest/jpa/ActionDictionaryJpaTest.java
index 580b3e35d..501c7fd92 100644
--- a/ONAP-REST/src/test/java/org/onap/policy/rest/jpa/ActionDictionaryJPATest.java
+++ b/ONAP-REST/src/test/java/org/onap/policy/rest/jpa/ActionDictionaryJpaTest.java
@@ -3,13 +3,14 @@
* ONAP-REST
* ================================================================================
* Copyright (C) 2018 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2019 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -17,10 +18,17 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.policy.rest.jpa;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
+import com.att.research.xacml.api.Identifier;
+
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
@@ -30,11 +38,16 @@ import org.junit.Test;
import org.onap.policy.common.logging.flexlogger.FlexLogger;
import org.onap.policy.common.logging.flexlogger.Logger;
-public class ActionDictionaryJPATest {
+public class ActionDictionaryJpaTest {
- private static Logger logger = FlexLogger.getLogger(ActionDictionaryJPATest.class);
+ private static Logger logger = FlexLogger.getLogger(ActionDictionaryJpaTest.class);
private UserInfo userInfo;
+ /**
+ * Set up the test.
+ *
+ * @throws Exception on test errors
+ */
@Before
public void setUp() throws Exception {
logger.info("setUp: Entering");
@@ -45,7 +58,7 @@ public class ActionDictionaryJPATest {
}
@Test
- public void testActionDictionary(){
+ public void testActionDictionary() {
ActionPolicyDict data = new ActionPolicyDict();
data.setId(1);
assertTrue(1 == data.getId());
@@ -66,48 +79,49 @@ public class ActionDictionaryJPATest {
data.prePersist();
data.preUpdate();
data.setCreatedDate(new Date());
- assertTrue(data.getCreatedDate()!=null);
+ assertTrue(data.getCreatedDate() != null);
data.setModifiedDate(new Date());
- assertTrue(data.getModifiedDate()!=null);
+ assertTrue(data.getModifiedDate() != null);
data.setUserCreatedBy(userInfo);
- assertTrue(data.getUserCreatedBy()!=null);
+ assertTrue(data.getUserCreatedBy() != null);
data.setUserModifiedBy(userInfo);
- assertTrue(data.getUserModifiedBy()!=null);
+ assertTrue(data.getUserModifiedBy() != null);
}
@Test
- public void testFunctionArgument(){
+ public void testFunctionArgument() {
FunctionArgument data = new FunctionArgument();
data.setArgIndex(1);
assertTrue(1 == data.getArgIndex());
data.setDatatypeBean(new Datatype());
- assertTrue(data.getDatatypeBean()!=null);
+ assertTrue(data.getDatatypeBean() != null);
data.setFunctionDefinition(new FunctionDefinition());
- assertTrue(data.getFunctionDefinition()!=null);
+ assertTrue(data.getFunctionDefinition() != null);
data.setId(1);
assertTrue(1 == data.getId());
- data.isBag();
- data.toString();
+ assertFalse(data.isBag());
+ assertEquals("FunctionArgument(id=1", data.toString().substring(0, 21));
data.setIsBag(1);
+ assertTrue(data.isBag());
assertTrue(1 == data.getIsBag());
new FunctionArgument(data);
}
@Test
- public void testFunctionDefinition(){
+ public void testFunctionDefinition() {
FunctionDefinition data = new FunctionDefinition();
data.setArgLb(1);
assertTrue(1 == data.getArgLb());
data.setArgUb(1);
assertTrue(1 == data.getArgUb());
data.setDatatypeBean(new Datatype());
- assertTrue(data.getDatatypeBean()!=null);
+ assertTrue(data.getDatatypeBean() != null);
data.setFunctionArguments(new ArrayList<>());
- assertTrue(data.getFunctionArguments()!=null);
- data.setHigherOrderArg_LB(1);
- assertTrue(1 == data.getHigherOrderArg_LB());
- data.setHigherOrderArg_UB(1);
- assertTrue(1 == data.getHigherOrderArg_UB());
+ assertTrue(data.getFunctionArguments() != null);
+ data.setHigherOrderArgLb(1);
+ assertTrue(1 == data.getHigherOrderArgLb());
+ data.setHigherOrderArgUb(1);
+ assertTrue(1 == data.getHigherOrderArgUb());
data.setId(1);
assertTrue(1 == data.getId());
data.setIsBagReturn(1);
@@ -118,15 +132,23 @@ public class ActionDictionaryJPATest {
assertTrue("Test".equals(data.getShortname()));
data.setXacmlid("Test");
assertTrue("Test".equals(data.getXacmlid()));
- data.toString();
- data.isBagReturn();
- data.isHigherOrder();
- data.addFunctionArgument(new FunctionArgument());
- data.removeFunctionArgument(new FunctionArgument());
+ assertTrue(data.toString().startsWith("FunctionDefinition(id=1"));
+ assertTrue(data.isBagReturn());
+ data.setIsBagReturn(0);
+ assertTrue(data.isHigherOrder());
+ assertFalse(data.isBagReturn());
+ data.setIsHigherOrder(0);
+ assertFalse(data.isHigherOrder());
+ FunctionArgument functionArgument = new FunctionArgument();
+ functionArgument.setId(12345);
+ data.addFunctionArgument(functionArgument);
+ assertEquals(12345, data.getFunctionArguments().iterator().next().getId());
+ data.removeFunctionArgument(functionArgument);
+ assertTrue(data.getFunctionArguments().isEmpty());
}
@Test
- public void testCategory(){
+ public void testCategory() {
Category data = new Category();
new Category(null);
data.setAttributes(new HashSet<>());
@@ -134,10 +156,9 @@ public class ActionDictionaryJPATest {
data.removeAttribute(new Attribute());
data.isStandard();
data.isCustom();
- Category.extractGrouping("urn:oasis:names:tc:xacml:1.0:subject-category:intermediary-subject");
data.getIdentifer();
data.toString();
- assertTrue(data.getAttributes()!=null);
+ assertTrue(data.getAttributes() != null);
data.setGrouping("Test");
assertTrue("Test".equals(data.getGrouping()));
data.setId(1);
@@ -146,15 +167,42 @@ public class ActionDictionaryJPATest {
assertTrue("Test".equals(data.getShortName()));
data.setXacmlId("Test");
assertTrue("Test".equals(data.getXacmlId()));
+
+ data.setIsStandard(Category.STANDARD);
+ assertEquals(Category.STANDARD, data.getIsStandard());
+ assertTrue(data.isStandard());
+ assertFalse(data.isCustom());
+
+ data.setIsStandard(Category.CUSTOM);
+ assertEquals(Category.CUSTOM, data.getIsStandard());
+ assertFalse(data.isStandard());
+ assertTrue(data.isCustom());
+
+ Identifier categoryIdentifier = new DummyIdentifier();
+ Category data2 = new Category(categoryIdentifier,
+ "urn:oasis:names:tc:xacml:1.0:subject-category:intermediary-subject", Category.STANDARD);
+ assertEquals(DummyIdentifier.class.getName(), data2.getIdentifer().stringValue());
+
+ Category data3 = new Category(categoryIdentifier,
+ "urn:oasis:names:tc:xacml:1.0:subject-category:intermediary-subject");
+ assertEquals(DummyIdentifier.class.getName(), data3.getIdentifer().stringValue());
+
+ assertEquals("subject",
+ Category.extractGrouping("urn:oasis:names:tc:xacml:1.0:subject-category:intermediary-subject"));
+ assertNull(Category.extractGrouping(null));
+ assertNull(Category.extractGrouping("some random string"));
+ assertNull(Category.extractGrouping(""));
+ assertEquals("intermediary-attribute", Category
+ .extractGrouping("urn:oasis:names:tc:xacml:1.0:attribute-category:intermediary-attribute"));
}
@Test
- public void testConstraintType(){
+ public void testConstraintType() {
ConstraintType data = new ConstraintType();
new ConstraintType("Test", "Test");
ConstraintType.getRangeTypes();
data.setAttributes(new HashSet<>());
- assertTrue(data.getAttributes()!=null);
+ assertTrue(data.getAttributes() != null);
data.setConstraintType("Test");
assertTrue("Test".equals(data.getConstraintType()));
data.setDescription("Test");
@@ -164,13 +212,13 @@ public class ActionDictionaryJPATest {
}
@Test
- public void testConstraintValue(){
+ public void testConstraintValue() {
ConstraintValue data = new ConstraintValue();
data.clone();
new ConstraintValue(new ConstraintValue());
- new ConstraintValue("Test","Test");
+ new ConstraintValue("Test", "Test");
data.setAttribute(new Attribute());
- assertTrue(data.getAttribute()!=null);
+ assertTrue(data.getAttribute() != null);
data.setId(1);
assertTrue(1 == data.getId());
data.setProperty("Test");
@@ -180,14 +228,20 @@ public class ActionDictionaryJPATest {
}
@Test
- public void testObadvice(){
- Obadvice data = new Obadvice();
+ public void testObadvice() {
new Obadvice();
new Obadvice("Test", "Test");
+ new Obadvice(new DummyIdentifier(), "Test");
+ Obadvice data = new Obadvice();
data.clone();
data.addObadviceExpression(new ObadviceExpression());
+ assertNotNull(data.clone());
data.removeObadviceExpression(new ObadviceExpression());
data.removeAllExpressions();
+ assertEquals(0, data.getObadviceExpressions().size());
+ data.setObadviceExpressions(null);
+ assertNull(data.getObadviceExpressions());
+ data.removeAllExpressions();
data.prePersist();
data.preUpdate();
data.setId(1);
@@ -201,29 +255,30 @@ public class ActionDictionaryJPATest {
data.setModifiedBy("Test");
assertTrue("Test".equals(data.getModifiedBy()));
data.setObadviceExpressions(new HashSet<>());
- assertTrue(data.getObadviceExpressions()!=null);
+ assertTrue(data.getObadviceExpressions() != null);
data.setType("Test");
assertTrue("Test".equals(data.getType()));
data.setXacmlId("Test");
assertTrue("Test".equals(data.getXacmlId()));
+
}
@Test
- public void testObadviceExpression(){
+ public void testObadviceExpression() {
ObadviceExpression data = new ObadviceExpression();
data.clone();
data.setAttribute(new Attribute());
- assertTrue(data.getAttribute()!=null);
+ assertTrue(data.getAttribute() != null);
data.setId(1);
assertTrue(1 == data.getId());
data.setObadvice(new Obadvice());
- assertTrue(data.getObadvice()!=null);
+ assertTrue(data.getObadvice() != null);
data.setType("Test");
assertTrue("Test".equals(data.getType()));
}
@Test
- public void testRuleAlgorithms(){
+ public void testRuleAlgorithms() {
RuleAlgorithms data = new RuleAlgorithms();
data.isCustom();
data.isStandard();
@@ -234,10 +289,17 @@ public class ActionDictionaryJPATest {
data.setXacmlId("Test");
assertTrue("Test".equals(data.getXacmlId()));
data.toString();
+
+ RuleAlgorithms ra0 = new RuleAlgorithms(new DummyIdentifier());
+ assertTrue(ra0.isStandard());
+ assertFalse(ra0.isCustom());
+ RuleAlgorithms ra1 = new RuleAlgorithms(new DummyIdentifier(), 'C');
+ assertFalse(ra1.isStandard());
+ assertTrue(ra1.isCustom());
}
@Test
- public void testAttributeAssignment(){
+ public void testAttributeAssignment() {
AttributeAssignment data = new AttributeAssignment();
data.setId(1);
assertTrue(1 == data.getId());
@@ -248,16 +310,16 @@ public class ActionDictionaryJPATest {
}
@Test
- public void testDatatype(){
+ public void testDatatype() {
Datatype data = new Datatype();
new Datatype(null);
new Datatype(1, new Datatype());
data.setArguments(new HashSet<>());
- assertTrue(data.getArguments()!=null);
+ assertTrue(data.getArguments() != null);
data.setAttributes(new HashSet<>());
- assertTrue(data.getAttributes()!=null);
+ assertTrue(data.getAttributes() != null);
data.setFunctions(new HashSet<>());
- assertTrue(data.getFunctions()!=null);
+ assertTrue(data.getFunctions() != null);
data.setId(1);
assertTrue(1 == data.getId());
data.setShortName("Test");
@@ -270,16 +332,29 @@ public class ActionDictionaryJPATest {
data.removeArgument(new FunctionArgument());
data.removeAttribute(new Attribute());
data.removeAttribute(new FunctionDefinition());
- assertTrue(data.getIdentifer()!=null);
- assertTrue(data.getIdentiferByShortName()!=null);
+ assertTrue(data.getIdentifer() != null);
+ assertTrue(data.getIdentiferByShortName() != null);
data.setIsStandard(Datatype.STANDARD);
assertTrue(data.isStandard());
data.setIsStandard(Datatype.CUSTOM);
assertTrue(data.isCustom());
+
+ data.setIsStandard(Category.STANDARD);
+ assertEquals(Category.STANDARD, data.getIsStandard());
+ assertTrue(data.isStandard());
+ assertFalse(data.isCustom());
+
+ data.setIsStandard(Category.CUSTOM);
+ assertEquals(Category.CUSTOM, data.getIsStandard());
+ assertFalse(data.isStandard());
+ assertTrue(data.isCustom());
+
+ Datatype data2 = new Datatype(new DummyIdentifier(), Datatype.STANDARD);
+ assertEquals(DummyIdentifier.class.getName(), data2.getIdentifer().stringValue());
}
@Test
- public void testPolicyAlgorithms(){
+ public void testPolicyAlgorithms() {
PolicyAlgorithms data = new PolicyAlgorithms();
data.setId(1);
assertTrue(1 == data.getId());
@@ -289,5 +364,13 @@ public class ActionDictionaryJPATest {
assertTrue("Test".equals(data.getXacmlId()));
data.setIsStandard(PolicyAlgorithms.STANDARD);
assertTrue(data.isStandard());
+ assertFalse(data.isCustom());
+ data.setIsStandard(PolicyAlgorithms.CUSTOM);
+ assertFalse(data.isStandard());
+ assertTrue(data.isCustom());
+
+ DummyIdentifier identifier = new DummyIdentifier();
+ assertNotNull(new PolicyAlgorithms(identifier));
+ assertNotNull(new PolicyAlgorithms(identifier, 'C'));
}
}
diff --git a/ONAP-REST/src/test/java/org/onap/policy/rest/jpa/BRMSDictionaryJPATest.java b/ONAP-REST/src/test/java/org/onap/policy/rest/jpa/BrmsDictionaryJpaTest.java
index 9012cca28..abfef0c35 100644
--- a/ONAP-REST/src/test/java/org/onap/policy/rest/jpa/BRMSDictionaryJPATest.java
+++ b/ONAP-REST/src/test/java/org/onap/policy/rest/jpa/BrmsDictionaryJpaTest.java
@@ -3,13 +3,14 @@
* ONAP-REST
* ================================================================================
* Copyright (C) 2018 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2019 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -17,6 +18,7 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.policy.rest.jpa;
import static org.junit.Assert.assertTrue;
@@ -28,11 +30,19 @@ import org.junit.Test;
import org.onap.policy.common.logging.flexlogger.FlexLogger;
import org.onap.policy.common.logging.flexlogger.Logger;
-public class BRMSDictionaryJPATest {
+/**
+ * The Class BrmsDictionaryJpaTest.
+ */
+public class BrmsDictionaryJpaTest {
- private static Logger logger = FlexLogger.getLogger(BRMSDictionaryJPATest.class);
+ private static Logger logger = FlexLogger.getLogger(BrmsDictionaryJpaTest.class);
private UserInfo userInfo;
+ /**
+ * Sets the up.
+ *
+ * @throws Exception the exception
+ */
@Before
public void setUp() throws Exception {
logger.info("setUp: Entering");
@@ -42,9 +52,12 @@ public class BRMSDictionaryJPATest {
logger.info("setUp: exit");
}
+ /**
+ * Test BRMS param template.
+ */
@Test
- public void testBRMSParamTemplate(){
- BRMSParamTemplate data = new BRMSParamTemplate();
+ public void testBrmsParamTemplate() {
+ BrmsParamTemplate data = new BrmsParamTemplate();
data.prePersist();
data.setId(1);
assertTrue(1 == data.getId());
@@ -55,14 +68,17 @@ public class BRMSDictionaryJPATest {
data.setDescription("Test");
assertTrue("Test".equals(data.getDescription()));
data.setCreatedDate(new Date());
- assertTrue(data.getCreatedDate()!=null);
+ assertTrue(data.getCreatedDate() != null);
data.setUserCreatedBy(userInfo);
- assertTrue(data.getUserCreatedBy()!=null);
+ assertTrue(data.getUserCreatedBy() != null);
}
+ /**
+ * Test BRMS controller.
+ */
@Test
- public void testBRMSController(){
- BRMSController data = new BRMSController();
+ public void testBrmsController() {
+ BrmsController data = new BrmsController();
data.preUpdate();
data.prePersist();
data.setId(1);
@@ -74,18 +90,21 @@ public class BRMSDictionaryJPATest {
data.setDescription("Test");
assertTrue("Test".equals(data.getDescription()));
data.setCreatedDate(new Date());
- assertTrue(data.getCreatedDate()!=null);
+ assertTrue(data.getCreatedDate() != null);
data.setModifiedDate(new Date());
- assertTrue(data.getModifiedDate()!=null);
+ assertTrue(data.getModifiedDate() != null);
data.setUserCreatedBy(userInfo);
- assertTrue(data.getUserCreatedBy()!=null);
+ assertTrue(data.getUserCreatedBy() != null);
data.setUserModifiedBy(userInfo);
- assertTrue(data.getUserModifiedBy()!=null);
+ assertTrue(data.getUserModifiedBy() != null);
}
+ /**
+ * Test BRMS dependency.
+ */
@Test
- public void testBRMSDependency(){
- BRMSDependency data = new BRMSDependency();
+ public void testrmsDependency() {
+ BrmsDependency data = new BrmsDependency();
data.preUpdate();
data.prePersist();
data.setId(1);
@@ -97,13 +116,13 @@ public class BRMSDictionaryJPATest {
data.setDescription("Test");
assertTrue("Test".equals(data.getDescription()));
data.setCreatedDate(new Date());
- assertTrue(data.getCreatedDate()!=null);
+ assertTrue(data.getCreatedDate() != null);
data.setModifiedDate(new Date());
- assertTrue(data.getModifiedDate()!=null);
+ assertTrue(data.getModifiedDate() != null);
data.setUserCreatedBy(userInfo);
- assertTrue(data.getUserCreatedBy()!=null);
+ assertTrue(data.getUserCreatedBy() != null);
data.setUserModifiedBy(userInfo);
- assertTrue(data.getUserModifiedBy()!=null);
+ assertTrue(data.getUserModifiedBy() != null);
}
}
diff --git a/ONAP-REST/src/test/java/org/onap/policy/rest/jpa/ClosedLoopPolicyDictionaryJPATest.java b/ONAP-REST/src/test/java/org/onap/policy/rest/jpa/ClosedLoopPolicyDictionaryJpaTest.java
index 2274855e1..00fba8ca6 100644
--- a/ONAP-REST/src/test/java/org/onap/policy/rest/jpa/ClosedLoopPolicyDictionaryJPATest.java
+++ b/ONAP-REST/src/test/java/org/onap/policy/rest/jpa/ClosedLoopPolicyDictionaryJpaTest.java
@@ -3,13 +3,14 @@
* ONAP-REST
* ================================================================================
* Copyright (C) 2018 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2019 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -17,6 +18,7 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.policy.rest.jpa;
import static org.junit.Assert.assertTrue;
@@ -28,11 +30,19 @@ import org.junit.Test;
import org.onap.policy.common.logging.flexlogger.FlexLogger;
import org.onap.policy.common.logging.flexlogger.Logger;
-public class ClosedLoopPolicyDictionaryJPATest {
+/**
+ * The Class ClosedLoopPolicyDictionaryJpaTest.
+ */
+public class ClosedLoopPolicyDictionaryJpaTest {
- private static Logger logger = FlexLogger.getLogger(ClosedLoopPolicyDictionaryJPATest.class);
+ private static Logger logger = FlexLogger.getLogger(ClosedLoopPolicyDictionaryJpaTest.class);
private UserInfo userInfo;
+ /**
+ * Sets the up.
+ *
+ * @throws Exception the exception
+ */
@Before
public void setUp() throws Exception {
logger.info("setUp: Entering");
@@ -42,51 +52,60 @@ public class ClosedLoopPolicyDictionaryJPATest {
logger.info("setUp: exit");
}
+ /**
+ * Test VSCL action.
+ */
@Test
- public void testVSCLAction(){
- VSCLAction data = new VSCLAction();
+ public void testVsclAction() {
+ VsclAction data = new VsclAction();
data.preUpdate();
data.prePersist();
data.setId(1);
assertTrue(1 == data.getId());
- data.setVsclaction("Test");
- assertTrue("Test".equals(data.getVsclaction()));
+ data.setAction("Test");
+ assertTrue("Test".equals(data.getAction()));
data.setDescription("Test");
assertTrue("Test".equals(data.getDescription()));
data.setCreatedDate(new Date());
- assertTrue(data.getCreatedDate()!= null);
+ assertTrue(data.getCreatedDate() != null);
data.setModifiedDate(new Date());
- assertTrue(data.getModifiedDate()!= null);
+ assertTrue(data.getModifiedDate() != null);
data.setUserCreatedBy(userInfo);
- assertTrue(data.getUserCreatedBy()!= null);
+ assertTrue(data.getUserCreatedBy() != null);
data.setUserModifiedBy(userInfo);
- assertTrue(data.getUserModifiedBy()!= null);
+ assertTrue(data.getUserModifiedBy() != null);
}
+ /**
+ * Test VNF type.
+ */
@Test
- public void testVNFType(){
- VNFType data = new VNFType();
+ public void testVnfType() {
+ VnfType data = new VnfType();
data.preUpdate();
data.prePersist();
data.setId(1);
assertTrue(1 == data.getId());
- data.setVnftype("Test");
- assertTrue("Test".equals(data.getVnftype()));
+ data.setType("Test");
+ assertTrue("Test".equals(data.getType()));
data.setDescription("Test");
assertTrue("Test".equals(data.getDescription()));
data.setCreatedDate(new Date());
- assertTrue(data.getCreatedDate()!= null);
+ assertTrue(data.getCreatedDate() != null);
data.setModifiedDate(new Date());
- assertTrue(data.getModifiedDate()!= null);
+ assertTrue(data.getModifiedDate() != null);
data.setUserCreatedBy(userInfo);
- assertTrue(data.getUserCreatedBy()!= null);
+ assertTrue(data.getUserCreatedBy() != null);
data.setUserModifiedBy(userInfo);
- assertTrue(data.getUserModifiedBy()!= null);
+ assertTrue(data.getUserModifiedBy() != null);
}
+ /**
+ * Test PEP options.
+ */
@Test
- public void testPEPOptions(){
- PEPOptions data = new PEPOptions();
+ public void testPepOptions() {
+ PepOptions data = new PepOptions();
data.preUpdate();
data.prePersist();
data.setId(1);
@@ -96,17 +115,20 @@ public class ClosedLoopPolicyDictionaryJPATest {
data.setDescription("Test");
assertTrue("Test".equals(data.getDescription()));
data.setCreatedDate(new Date());
- assertTrue(data.getCreatedDate()!= null);
+ assertTrue(data.getCreatedDate() != null);
data.setModifiedDate(new Date());
- assertTrue(data.getModifiedDate()!= null);
+ assertTrue(data.getModifiedDate() != null);
data.setUserCreatedBy(userInfo);
- assertTrue(data.getUserCreatedBy()!= null);
+ assertTrue(data.getUserCreatedBy() != null);
data.setUserModifiedBy(userInfo);
- assertTrue(data.getUserModifiedBy()!= null);
+ assertTrue(data.getUserModifiedBy() != null);
}
+ /**
+ * Test varbind dictionary.
+ */
@Test
- public void testVarbindDictionary(){
+ public void testVarbindDictionary() {
VarbindDictionary data = new VarbindDictionary();
data.preUpdate();
data.prePersist();
@@ -116,20 +138,23 @@ public class ClosedLoopPolicyDictionaryJPATest {
assertTrue("Test".equals(data.getVarbindName()));
data.setVarbindDescription("Test");
assertTrue("Test".equals(data.getVarbindDescription()));
- data.setVarbindOID("Test");
- assertTrue("Test".equals(data.getVarbindOID()));
+ data.setVarbindOid("Test");
+ assertTrue("Test".equals(data.getVarbindOid()));
data.setCreatedDate(new Date());
- assertTrue(data.getCreatedDate()!= null);
+ assertTrue(data.getCreatedDate() != null);
data.setModifiedDate(new Date());
- assertTrue(data.getModifiedDate()!= null);
+ assertTrue(data.getModifiedDate() != null);
data.setUserCreatedBy(userInfo);
- assertTrue(data.getUserCreatedBy()!= null);
+ assertTrue(data.getUserCreatedBy() != null);
data.setUserModifiedBy(userInfo);
- assertTrue(data.getUserModifiedBy()!= null);
+ assertTrue(data.getUserModifiedBy() != null);
}
+ /**
+ * Test closed loop D 2 services.
+ */
@Test
- public void testClosedLoopD2Services(){
+ public void testClosedLoopD2Services() {
ClosedLoopD2Services data = new ClosedLoopD2Services();
data.preUpdate();
data.prePersist();
@@ -140,17 +165,20 @@ public class ClosedLoopPolicyDictionaryJPATest {
data.setDescription("Test");
assertTrue("Test".equals(data.getDescription()));
data.setCreatedDate(new Date());
- assertTrue(data.getCreatedDate()!= null);
+ assertTrue(data.getCreatedDate() != null);
data.setModifiedDate(new Date());
- assertTrue(data.getModifiedDate()!= null);
+ assertTrue(data.getModifiedDate() != null);
data.setUserCreatedBy(userInfo);
- assertTrue(data.getUserCreatedBy()!= null);
+ assertTrue(data.getUserCreatedBy() != null);
data.setUserModifiedBy(userInfo);
- assertTrue(data.getUserModifiedBy()!= null);
+ assertTrue(data.getUserModifiedBy() != null);
}
+ /**
+ * Test closed loop site.
+ */
@Test
- public void testClosedLoopSite(){
+ public void testClosedLoopSite() {
ClosedLoopSite data = new ClosedLoopSite();
data.preUpdate();
data.prePersist();
@@ -161,12 +189,12 @@ public class ClosedLoopPolicyDictionaryJPATest {
data.setDescription("Test");
assertTrue("Test".equals(data.getDescription()));
data.setCreatedDate(new Date());
- assertTrue(data.getCreatedDate()!= null);
+ assertTrue(data.getCreatedDate() != null);
data.setModifiedDate(new Date());
- assertTrue(data.getModifiedDate()!= null);
+ assertTrue(data.getModifiedDate() != null);
data.setUserCreatedBy(userInfo);
- assertTrue(data.getUserCreatedBy()!= null);
+ assertTrue(data.getUserCreatedBy() != null);
data.setUserModifiedBy(userInfo);
- assertTrue(data.getUserModifiedBy()!= null);
+ assertTrue(data.getUserModifiedBy() != null);
}
}
diff --git a/ONAP-REST/src/test/java/org/onap/policy/rest/jpa/CommonDictionaryJPATest.java b/ONAP-REST/src/test/java/org/onap/policy/rest/jpa/CommonDictionaryJpaTest.java
index 230844a64..a6505a3f6 100644
--- a/ONAP-REST/src/test/java/org/onap/policy/rest/jpa/CommonDictionaryJPATest.java
+++ b/ONAP-REST/src/test/java/org/onap/policy/rest/jpa/CommonDictionaryJpaTest.java
@@ -3,13 +3,14 @@
* ONAP-REST
* ================================================================================
* Copyright (C) 2018 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2019 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -17,23 +18,34 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.policy.rest.jpa;
+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 java.util.Date;
import java.util.HashSet;
+import java.util.LinkedHashSet;
+import java.util.Set;
import org.junit.Before;
import org.junit.Test;
import org.onap.policy.common.logging.flexlogger.FlexLogger;
import org.onap.policy.common.logging.flexlogger.Logger;
-public class CommonDictionaryJPATest {
+public class CommonDictionaryJpaTest {
- private static Logger logger = FlexLogger.getLogger(CommonDictionaryJPATest.class);
+ private static Logger logger = FlexLogger.getLogger(CommonDictionaryJpaTest.class);
private UserInfo userInfo;
+ /**
+ * Initiations for testing.
+ *
+ * @throws Exception on test initiation errors
+ */
@Before
public void setUp() throws Exception {
logger.info("setUp: Entering");
@@ -44,16 +56,16 @@ public class CommonDictionaryJPATest {
}
@Test
- public void testAttribute(){
+ public void testAttribute() {
Attribute data = new Attribute();
data.setId(1);
assertTrue(1 == data.getId());
data.setCategoryBean(new Category());
- assertTrue(data.getCategoryBean()!=null);
+ assertTrue(data.getCategoryBean() != null);
data.setConstraintType(new ConstraintType());
- assertTrue(data.getConstraintType()!=null);
+ assertTrue(data.getConstraintType() != null);
data.setConstraintValues(new HashSet<>());
- assertTrue(data.getConstraintValues()!=null);
+ assertTrue(data.getConstraintValues() != null);
data.addConstraintValue(new ConstraintValue());
data.removeConstraintValue(new ConstraintValue());
data.removeAllConstraintValues();
@@ -68,7 +80,7 @@ public class CommonDictionaryJPATest {
data.setXacmlId("Test");
assertTrue("Test".equals(data.getXacmlId()));
data.setDatatypeBean(new Datatype());
- assertTrue(data.getDatatypeBean()!=null);
+ assertTrue(data.getDatatypeBean() != null);
data.setIsDesignator(true);
assertTrue(data.isDesignator());
data.setIssuer("Test");
@@ -80,59 +92,108 @@ public class CommonDictionaryJPATest {
data.setSelectorPath("Test");
assertTrue("Test".equals(data.getSelectorPath()));
data.setCreatedDate(new Date());
- assertTrue(data.getCreatedDate()!=null);
+ assertTrue(data.getCreatedDate() != null);
data.setModifiedDate(new Date());
- assertTrue(data.getModifiedDate()!=null);
+ assertTrue(data.getModifiedDate() != null);
data.setUserCreatedBy(userInfo);
- assertTrue(data.getUserCreatedBy()!=null);
+ assertTrue(data.getUserCreatedBy() != null);
data.setUserModifiedBy(userInfo);
- assertTrue(data.getUserModifiedBy()!=null);
+ assertTrue(data.getUserModifiedBy() != null);
+
+ ConstraintValue constraintValue = new ConstraintValue("Greeting", "Hello");
+ data.getConstraintValues().add(constraintValue);
+ assertEquals("Hello", data.getConstraintValues().iterator().next().getValue());
+
+ data.removeConstraintValue(constraintValue);
+ assertTrue(data.getConstraintValues().isEmpty());
+
+ data.addConstraintValue(constraintValue);
+ assertEquals("Hello", data.getConstraintValues().iterator().next().getValue());
+
+ data.setConstraintValues(null);
+ assertNull(data.getConstraintValues());
+
+ data.addConstraintValue(constraintValue);
+ assertEquals("Hello", data.getConstraintValues().iterator().next().getValue());
+
+ data.removeAllConstraintValues();
+ assertTrue(data.getConstraintValues().isEmpty());
+
+ data.setConstraintValues(null);
+ assertNull(data.getConstraintValues());
+
+ data.removeAllConstraintValues();
+ assertNull(data.getConstraintValues());
+
+ data.addConstraintValue(constraintValue);
+ assertEquals("Hello", data.getConstraintValues().iterator().next().getValue());
+
+ data.setConstraintValues(null);
+ assertNull(data.getConstraintValues());
+
+ Set<ConstraintValue> constraintValueSet = new LinkedHashSet<>();
+ constraintValueSet.add(constraintValue);
+
+ data.setConstraintValues(null);
+ assertNull(data.getConstraintValues());
+
+ data.setConstraintValues(constraintValueSet);
+ assertEquals("Hello", data.getConstraintValues().iterator().next().getValue());
+
+ Attribute data2 = new Attribute(data);
+ assertEquals("Hello", data2.getConstraintValues().iterator().next().getValue());
+
+ data.setIsDesignator(true);
+ assertTrue(data.isDesignator());
+
+ data.setIsDesignator(false);
+ assertFalse(data.isDesignator());
}
@Test
- public void testOnapName(){
+ public void testOnapName() {
OnapName data = new OnapName();
data.preUpdate();
data.prePersist();
data.setId(1);
assertTrue(1 == data.getId());
- data.setOnapName("Test");
- assertTrue("Test".equals(data.getOnapName()));
+ data.setName("Test");
+ assertTrue("Test".equals(data.getName()));
data.setDescription("Test");
assertTrue("Test".equals(data.getDescription()));
data.setCreatedDate(new Date());
- assertTrue(data.getCreatedDate()!=null);
+ assertTrue(data.getCreatedDate() != null);
data.setModifiedDate(new Date());
- assertTrue(data.getModifiedDate()!=null);
+ assertTrue(data.getModifiedDate() != null);
data.setUserCreatedBy(userInfo);
- assertTrue(data.getUserCreatedBy()!=null);
+ assertTrue(data.getUserCreatedBy() != null);
data.setUserModifiedBy(userInfo);
- assertTrue(data.getUserModifiedBy()!=null);
+ assertTrue(data.getUserModifiedBy() != null);
}
@Test
- public void testRiskType(){
+ public void testRiskType() {
RiskType data = new RiskType();
data.preUpdate();
data.prePersist();
data.setId(1);
assertTrue(1 == data.getId());
- data.setRiskName("Test");
- assertTrue("Test".equals(data.getRiskName()));
+ data.setName("Test");
+ assertTrue("Test".equals(data.getName()));
data.setDescription("Test");
assertTrue("Test".equals(data.getDescription()));
data.setCreatedDate(new Date());
- assertTrue(data.getCreatedDate()!=null);
+ assertTrue(data.getCreatedDate() != null);
data.setModifiedDate(new Date());
- assertTrue(data.getModifiedDate()!=null);
+ assertTrue(data.getModifiedDate() != null);
data.setUserCreatedBy(userInfo);
- assertTrue(data.getUserCreatedBy()!=null);
+ assertTrue(data.getUserCreatedBy() != null);
data.setUserModifiedBy(userInfo);
- assertTrue(data.getUserModifiedBy()!=null);
+ assertTrue(data.getUserModifiedBy() != null);
}
@Test
- public void testSafePolicyWarning(){
+ public void testSafePolicyWarning() {
SafePolicyWarning data = new SafePolicyWarning();
data.setId(1);
assertTrue(1 == data.getId());
diff --git a/ONAP-REST/src/test/java/org/onap/policy/rest/jpa/ConfigurationDataEntityTest.java b/ONAP-REST/src/test/java/org/onap/policy/rest/jpa/ConfigurationDataEntityTest.java
index da5dd5005..a18fcbae3 100644
--- a/ONAP-REST/src/test/java/org/onap/policy/rest/jpa/ConfigurationDataEntityTest.java
+++ b/ONAP-REST/src/test/java/org/onap/policy/rest/jpa/ConfigurationDataEntityTest.java
@@ -3,13 +3,14 @@
* ONAP-REST
* ================================================================================
* Copyright (C) 2018 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2019 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -25,47 +26,51 @@ import static org.hamcrest.CoreMatchers.not;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertThat;
+
import java.util.Date;
+
import org.junit.Test;
public class ConfigurationDataEntityTest {
- @Test
- public void testEquals() {
- // Set up test data
- String value = "testVal";
- Date date = new Date();
- ConfigurationDataEntity entity = new ConfigurationDataEntity();
- entity.prePersist();
- ConfigurationDataEntity entity2 = new ConfigurationDataEntity();
- ConfigurationDataEntity entity3 = new ConfigurationDataEntity();
+ @Test
+ public void testEquals() {
+ // Set up test data
+ String value = "testVal";
+ ConfigurationDataEntity entity = new ConfigurationDataEntity();
+ entity.prePersist();
+ ConfigurationDataEntity entity3 = new ConfigurationDataEntity();
+
+ // Test set and get
+ entity3.preUpdate();
+ entity3.setConfigBody(value);
+ assertEquals(value, entity3.getConfigBody());
+ entity3.setCreatedBy(value);
+ assertEquals(value, entity3.getCreatedBy());
+ entity3.setModifiedBy(value);
+ assertEquals(value, entity3.getModifiedBy());
+
+ Date date = new Date();
+ entity3.setModifiedDate(date);
+ assertEquals(date, entity3.getModifiedDate());
+ assertEquals(0, entity3.getVersion());
+ assertNull(entity3.getCreatedDate());
+ entity3.setDeleted(true);
+ assertEquals(true, entity3.isDeleted());
+ entity3.setDescription(value);
+ assertEquals(value, entity3.getDescription());
+ entity3.setConfigType(value);
+ assertEquals(value, entity3.getConfigType());
+ entity3.setConfigurationName(value);
+ assertEquals(value, entity3.getConfigurationName());
+ assertEquals(0, entity3.getConfigurationDataId());
- // Test set and get
- entity3.preUpdate();
- entity3.setConfigBody(value);
- assertEquals(value, entity3.getConfigBody());
- entity3.setCreatedBy(value);
- assertEquals(value, entity3.getCreatedBy());
- entity3.setModifiedBy(value);
- assertEquals(value, entity3.getModifiedBy());
- entity3.setModifiedDate(date);
- assertEquals(date, entity3.getModifiedDate());
- assertEquals(0, entity3.getVersion());
- assertNull(entity3.getCreatedDate());
- entity3.setDeleted(true);
- assertEquals(true, entity3.isDeleted());
- entity3.setDescription(value);
- assertEquals(value, entity3.getDescription());
- entity3.setConfigType(value);
- assertEquals(value, entity3.getConfigType());
- entity3.setConfigurationName(value);
- assertEquals(value, entity3.getConfigurationName());
- assertEquals(0, entity3.getConfigurationDataId());
+ // Test method combinations
+ assertEquals(false, entity.equals(null));
+ assertEquals(true, entity.equals(entity));
+ assertEquals(false, entity.equals(value));
- // Test method combinations
- assertEquals(false, entity.equals(null));
- assertEquals(true, entity.equals(entity));
- assertEquals(false, entity.equals(value));
- assertEquals(false, entity.equals(entity2));
- assertThat(entity.hashCode(), is(not(0)));
- }
+ ConfigurationDataEntity entity2 = new ConfigurationDataEntity();
+ assertEquals(false, entity.equals(entity2));
+ assertThat(entity.hashCode(), is(not(0)));
+ }
}
diff --git a/ONAP-REST/src/test/java/org/onap/policy/rest/jpa/DecisionDictionaryJPATest.java b/ONAP-REST/src/test/java/org/onap/policy/rest/jpa/DecisionDictionaryJpaTest.java
index b1fc69903..b664cf3ed 100644
--- a/ONAP-REST/src/test/java/org/onap/policy/rest/jpa/DecisionDictionaryJPATest.java
+++ b/ONAP-REST/src/test/java/org/onap/policy/rest/jpa/DecisionDictionaryJpaTest.java
@@ -3,13 +3,14 @@
* ONAP-REST
* ================================================================================
* Copyright (C) 2018 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2019 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -17,6 +18,7 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.policy.rest.jpa;
import static org.junit.Assert.assertTrue;
@@ -28,11 +30,19 @@ import org.junit.Test;
import org.onap.policy.common.logging.flexlogger.FlexLogger;
import org.onap.policy.common.logging.flexlogger.Logger;
-public class DecisionDictionaryJPATest {
+/**
+ * The Class DecisionDictionaryJpaTest.
+ */
+public class DecisionDictionaryJpaTest {
- private static Logger logger = FlexLogger.getLogger(DecisionDictionaryJPATest.class);
+ private static Logger logger = FlexLogger.getLogger(DecisionDictionaryJpaTest.class);
private UserInfo userInfo;
+ /**
+ * Sets the up.
+ *
+ * @throws Exception the exception
+ */
@Before
public void setUp() throws Exception {
logger.info("setUp: Entering");
@@ -42,8 +52,11 @@ public class DecisionDictionaryJPATest {
logger.info("setUp: exit");
}
+ /**
+ * Test decision settings.
+ */
@Test
- public void testDecisionSettings(){
+ public void testDecisionSettings() {
DecisionSettings data = new DecisionSettings();
data.setId(1);
assertTrue(1 == data.getId());
@@ -54,7 +67,7 @@ public class DecisionDictionaryJPATest {
data.setXacmlId("Test");
assertTrue("Test".equals(data.getXacmlId()));
data.setDatatypeBean(new Datatype());
- assertTrue(data.getDatatypeBean()!=null);
+ assertTrue(data.getDatatypeBean() != null);
data.setIssuer("Test");
assertTrue("Test".equals(data.getIssuer()));
data.setMustBePresent(true);
@@ -62,17 +75,20 @@ public class DecisionDictionaryJPATest {
data.setPriority("Test");
assertTrue("Test".equals(data.getPriority()));
data.setCreatedDate(new Date());
- assertTrue(data.getCreatedDate()!=null);
+ assertTrue(data.getCreatedDate() != null);
data.setModifiedDate(new Date());
- assertTrue(data.getModifiedDate()!=null);
+ assertTrue(data.getModifiedDate() != null);
data.setUserCreatedBy(userInfo);
- assertTrue(data.getUserCreatedBy()!=null);
+ assertTrue(data.getUserCreatedBy() != null);
data.setUserModifiedBy(userInfo);
- assertTrue(data.getUserModifiedBy()!=null);
+ assertTrue(data.getUserModifiedBy() != null);
}
+ /**
+ * Test rainy day treatments.
+ */
@Test
- public void testRainyDayTreatments(){
+ public void testRainyDayTreatments() {
RainyDayTreatments data = new RainyDayTreatments();
data.setId(1);
assertTrue(1 == data.getId());
diff --git a/ONAP-REST/src/test/java/org/onap/policy/rest/jpa/DictionaryDataTest.java b/ONAP-REST/src/test/java/org/onap/policy/rest/jpa/DictionaryDataTest.java
index 486d36442..1b4bb7114 100644
--- a/ONAP-REST/src/test/java/org/onap/policy/rest/jpa/DictionaryDataTest.java
+++ b/ONAP-REST/src/test/java/org/onap/policy/rest/jpa/DictionaryDataTest.java
@@ -5,6 +5,7 @@
* Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Modifications Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2019 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -23,6 +24,7 @@
package org.onap.policy.rest.jpa;
import static org.junit.Assert.assertEquals;
+
import org.junit.Test;
public class DictionaryDataTest {
@@ -34,7 +36,7 @@ public class DictionaryDataTest {
String value = "testData1";
// Set Data
- dictData.setId(1);;
+ dictData.setId(1);
dictData.setDictionaryDataByName(value);
dictData.setDictionaryName(value);
dictData.setDictionaryUrl(value);
diff --git a/ONAP-REST/src/test/java/org/onap/policy/rest/jpa/DummyIdentifier.java b/ONAP-REST/src/test/java/org/onap/policy/rest/jpa/DummyIdentifier.java
new file mode 100644
index 000000000..bd88db29a
--- /dev/null
+++ b/ONAP-REST/src/test/java/org/onap/policy/rest/jpa/DummyIdentifier.java
@@ -0,0 +1,46 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * Copyright (C) 2019 Nordix Foundation.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ * SPDX-License-Identifier: Apache-2.0
+ * ============LICENSE_END=========================================================
+ */
+
+package org.onap.policy.rest.jpa;
+
+import com.att.research.xacml.api.Identifier;
+
+import java.net.URI;
+import java.net.URISyntaxException;
+
+/**
+ * Dummy category identifier class.
+ */
+public class DummyIdentifier implements Identifier {
+
+ @Override
+ public String stringValue() {
+ return this.getClass().getName();
+ }
+
+ @Override
+ public URI getUri() {
+ try {
+ return new URI(this.getClass().getName());
+ } catch (URISyntaxException e) {
+ return null;
+ }
+ }
+}
diff --git a/ONAP-REST/src/test/java/org/onap/policy/rest/jpa/FWDictionaryJPATest.java b/ONAP-REST/src/test/java/org/onap/policy/rest/jpa/FwDictionaryJpaTest.java
index b3b23e429..42df1c93d 100644
--- a/ONAP-REST/src/test/java/org/onap/policy/rest/jpa/FWDictionaryJPATest.java
+++ b/ONAP-REST/src/test/java/org/onap/policy/rest/jpa/FwDictionaryJpaTest.java
@@ -3,13 +3,14 @@
* ONAP-REST
* ================================================================================
* Copyright (C) 2018 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2019 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -17,6 +18,7 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.policy.rest.jpa;
import static org.junit.Assert.assertTrue;
@@ -28,11 +30,19 @@ import org.junit.Test;
import org.onap.policy.common.logging.flexlogger.FlexLogger;
import org.onap.policy.common.logging.flexlogger.Logger;
-public class FWDictionaryJPATest {
+/**
+ * The Class FWDictionaryJPATest.
+ */
+public class FwDictionaryJpaTest {
- private static Logger logger = FlexLogger.getLogger(FWDictionaryJPATest.class);
+ private static Logger logger = FlexLogger.getLogger(FwDictionaryJpaTest.class);
private UserInfo userInfo;
+ /**
+ * Sets the up.
+ *
+ * @throws Exception the exception
+ */
@Before
public void setUp() throws Exception {
logger.info("setUp: Entering");
@@ -42,8 +52,11 @@ public class FWDictionaryJPATest {
logger.info("setUp: exit");
}
+ /**
+ * Test action list.
+ */
@Test
- public void testActionList(){
+ public void testActionList() {
ActionList data = new ActionList();
data.setId(1);
assertTrue(1 == data.getId());
@@ -53,8 +66,11 @@ public class FWDictionaryJPATest {
assertTrue("Test".equals(data.getDescription()));
}
+ /**
+ * Test port list.
+ */
@Test
- public void testPortList(){
+ public void testPortList() {
PortList data = new PortList();
data.setId(1);
assertTrue(1 == data.getId());
@@ -64,8 +80,11 @@ public class FWDictionaryJPATest {
assertTrue("Test".equals(data.getDescription()));
}
+ /**
+ * Test protocol list.
+ */
@Test
- public void testProtocolList(){
+ public void testProtocolList() {
ProtocolList data = new ProtocolList();
data.setId(1);
assertTrue(1 == data.getId());
@@ -75,8 +94,11 @@ public class FWDictionaryJPATest {
assertTrue("Test".equals(data.getDescription()));
}
+ /**
+ * Test security zone.
+ */
@Test
- public void testSecurityZone(){
+ public void testSecurityZone() {
SecurityZone data = new SecurityZone();
data.setId(1);
assertTrue(1 == data.getId());
@@ -86,8 +108,11 @@ public class FWDictionaryJPATest {
assertTrue("Test".equals(data.getZoneValue()));
}
+ /**
+ * Test zone.
+ */
@Test
- public void testZone(){
+ public void testZone() {
Zone data = new Zone();
data.setId(1);
assertTrue(1 == data.getId());
@@ -97,8 +122,11 @@ public class FWDictionaryJPATest {
assertTrue("Test".equals(data.getZoneValue()));
}
+ /**
+ * Test address group.
+ */
@Test
- public void testAddressGroup(){
+ public void testAddressGroup() {
AddressGroup data = new AddressGroup();
data.setId(1);
assertTrue(1 == data.getId());
@@ -110,8 +138,11 @@ public class FWDictionaryJPATest {
assertTrue("Test".equals(data.getDescription()));
}
+ /**
+ * Test prefix list.
+ */
@Test
- public void testPrefixList(){
+ public void testPrefixList() {
PrefixList data = new PrefixList();
data.setId(1);
assertTrue(1 == data.getId());
@@ -123,8 +154,11 @@ public class FWDictionaryJPATest {
assertTrue("Test".equals(data.getDescription()));
}
+ /**
+ * Test FW dictionary list.
+ */
@Test
- public void testFWDictionaryList(){
+ public void testFwDictionaryList() {
FirewallDictionaryList data = new FirewallDictionaryList();
data.setId(1);
assertTrue(1 == data.getId());
@@ -138,9 +172,12 @@ public class FWDictionaryJPATest {
assertTrue("Test".equals(data.getServiceList()));
}
+ /**
+ * Test FW tag.
+ */
@Test
- public void testFWTag(){
- FWTag data = new FWTag();
+ public void testFwTag() {
+ FwTag data = new FwTag();
data.preUpdate();
data.prePersist();
data.setId(1);
@@ -152,18 +189,21 @@ public class FWDictionaryJPATest {
data.setTagValues("Test");
assertTrue("Test".equals(data.getTagValues()));
data.setCreatedDate(new Date());
- assertTrue(data.getCreatedDate()!=null);
+ assertTrue(data.getCreatedDate() != null);
data.setModifiedDate(new Date());
- assertTrue(data.getModifiedDate()!=null);
+ assertTrue(data.getModifiedDate() != null);
data.setUserCreatedBy(userInfo);
- assertTrue(data.getUserCreatedBy()!=null);
+ assertTrue(data.getUserCreatedBy() != null);
data.setUserModifiedBy(userInfo);
- assertTrue(data.getUserModifiedBy()!=null);
+ assertTrue(data.getUserModifiedBy() != null);
}
+ /**
+ * Test FW tag picker.
+ */
@Test
- public void testFWTagPicker(){
- FWTagPicker data = new FWTagPicker();
+ public void testFwTagPicker() {
+ FwTagPicker data = new FwTagPicker();
data.preUpdate();
data.prePersist();
data.setId(1);
@@ -177,17 +217,20 @@ public class FWDictionaryJPATest {
data.setTagValues("Test");
assertTrue("Test".equals(data.getTagValues()));
data.setCreatedDate(new Date());
- assertTrue(data.getCreatedDate()!=null);
+ assertTrue(data.getCreatedDate() != null);
data.setModifiedDate(new Date());
- assertTrue(data.getModifiedDate()!=null);
+ assertTrue(data.getModifiedDate() != null);
data.setUserCreatedBy(userInfo);
- assertTrue(data.getUserCreatedBy()!=null);
+ assertTrue(data.getUserCreatedBy() != null);
data.setUserModifiedBy(userInfo);
- assertTrue(data.getUserModifiedBy()!=null);
+ assertTrue(data.getUserModifiedBy() != null);
}
+ /**
+ * Test service list.
+ */
@Test
- public void testServiceList(){
+ public void testServiceList() {
ServiceList data = new ServiceList();
data.setId(1);
assertTrue(1 == data.getId());
@@ -197,16 +240,19 @@ public class FWDictionaryJPATest {
assertTrue("Test".equals(data.getServiceDescription()));
data.setServiceType("Test");
assertTrue("Test".equals(data.getServiceType()));
- data.setServiceTransProtocol("Test");
- assertTrue("Test".equals(data.getServiceTransProtocol()));
+ data.setServiceTransportProtocol("Test");
+ assertTrue("Test".equals(data.getServiceTransportProtocol()));
data.setServiceAppProtocol("Test");
assertTrue("Test".equals(data.getServiceAppProtocol()));
data.setServicePorts("Test");
assertTrue("Test".equals(data.getServicePorts()));
}
+ /**
+ * Test term list.
+ */
@Test
- public void testTermList(){
+ public void testTermList() {
TermList data = new TermList();
data.preUpdate();
data.prePersist();
@@ -215,15 +261,15 @@ public class FWDictionaryJPATest {
data.setTermName("Test");
assertTrue("Test".equals(data.getTermName()));
data.setDescription("Test");
- assertTrue("Test".equals(data.getTermDescription()));
- data.setFromZones("Test");
+ assertTrue("Test".equals(data.getDescription()));
+ data.setFromZone("Test");
assertTrue("Test".equals(data.getFromZone()));
- data.setToZones("Test");
+ data.setToZone("Test");
assertTrue("Test".equals(data.getToZone()));
- data.setSrcIPList("Test");
- assertTrue("Test".equals(data.getSrcIPList()));
- data.setDestIPList("Test");
- assertTrue("Test".equals(data.getDestIPList()));
+ data.setSrcIpList("Test");
+ assertTrue("Test".equals(data.getSrcIpList()));
+ data.setDestIpList("Test");
+ assertTrue("Test".equals(data.getDestIpList()));
data.setProtocolList("Test");
assertTrue("Test".equals(data.getProtocolList()));
data.setPortList("Test");
@@ -235,17 +281,20 @@ public class FWDictionaryJPATest {
data.setAction("Test");
assertTrue("Test".equals(data.getAction()));
data.setCreatedDate(new Date());
- assertTrue(data.getCreatedDate()!=null);
+ assertTrue(data.getCreatedDate() != null);
data.setModifiedDate(new Date());
- assertTrue(data.getModifiedDate()!=null);
+ assertTrue(data.getModifiedDate() != null);
data.setUserCreatedBy(userInfo);
- assertTrue(data.getUserCreatedBy()!=null);
+ assertTrue(data.getUserCreatedBy() != null);
data.setUserModifiedBy(userInfo);
- assertTrue(data.getUserModifiedBy()!=null);
+ assertTrue(data.getUserModifiedBy() != null);
}
+ /**
+ * Test group service list.
+ */
@Test
- public void testGroupServiceList(){
+ public void testGroupServiceList() {
GroupServiceList data = new GroupServiceList();
data.setId(1);
assertTrue(1 == data.getId());
diff --git a/ONAP-REST/src/test/java/org/onap/policy/rest/jpa/GetterSetterToStringTest.java b/ONAP-REST/src/test/java/org/onap/policy/rest/jpa/GetterSetterToStringTest.java
new file mode 100644
index 000000000..62d486c63
--- /dev/null
+++ b/ONAP-REST/src/test/java/org/onap/policy/rest/jpa/GetterSetterToStringTest.java
@@ -0,0 +1,57 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * Copyright (C) 2019 Nordix Foundation.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ * SPDX-License-Identifier: Apache-2.0
+ * ============LICENSE_END=========================================================
+ */
+
+package org.onap.policy.rest.jpa;
+
+import com.openpojo.reflection.filters.FilterClassName;
+import com.openpojo.reflection.filters.FilterPackageInfo;
+import com.openpojo.validation.Validator;
+import com.openpojo.validation.ValidatorBuilder;
+import com.openpojo.validation.test.impl.GetterTester;
+import com.openpojo.validation.test.impl.SetterTester;
+
+import org.junit.Test;
+import org.onap.policy.common.utils.test.ToStringTester;
+
+/**
+ * Class to perform unit testing of POJOs.
+ */
+public class GetterSetterToStringTest {
+ private static final String POJO_PACKAGE = "org.onap.policy.rest.jpa";
+
+ @Test
+ public void testPdpModels() {
+ // @formatter:off
+ final Validator validator =
+ ValidatorBuilder.create()
+ .with(new ToStringTester())
+ .with(new SetterTester())
+ .with(new GetterTester())
+ .build();
+
+ // exclude Test classes and PdpMessage
+ validator.validate(
+ POJO_PACKAGE,
+ new FilterPackageInfo(),
+ new FilterClassName("^((?!Test$).)*$")
+ );
+ // @formatter:on
+ }
+}
diff --git a/ONAP-REST/src/test/java/org/onap/policy/rest/jpa/MicroServiceDictionaryJPATest.java b/ONAP-REST/src/test/java/org/onap/policy/rest/jpa/MicroServiceDictionaryJpaTest.java
index 548e3fc84..174d63506 100644
--- a/ONAP-REST/src/test/java/org/onap/policy/rest/jpa/MicroServiceDictionaryJPATest.java
+++ b/ONAP-REST/src/test/java/org/onap/policy/rest/jpa/MicroServiceDictionaryJpaTest.java
@@ -3,13 +3,14 @@
* ONAP-REST
* ================================================================================
* Copyright (C) 2018 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2019 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -17,8 +18,10 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.policy.rest.jpa;
+import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import org.junit.Before;
@@ -26,11 +29,19 @@ import org.junit.Test;
import org.onap.policy.common.logging.flexlogger.FlexLogger;
import org.onap.policy.common.logging.flexlogger.Logger;
-public class MicroServiceDictionaryJPATest {
+/**
+ * The Class MicroServiceDictionaryJpaTest.
+ */
+public class MicroServiceDictionaryJpaTest {
- private static Logger logger = FlexLogger.getLogger(MicroServiceDictionaryJPATest.class);
+ private static Logger logger = FlexLogger.getLogger(MicroServiceDictionaryJpaTest.class);
private UserInfo userInfo;
+ /**
+ * Sets the up.
+ *
+ * @throws Exception the exception
+ */
@Before
public void setUp() throws Exception {
logger.info("setUp: Entering");
@@ -40,9 +51,12 @@ public class MicroServiceDictionaryJPATest {
logger.info("setUp: exit");
}
+ /**
+ * Test DCAE users.
+ */
@Test
- public void testDCAEUsers(){
- DCAEUsers data = new DCAEUsers();
+ public void testDcaeUsers() {
+ DcaeUsers data = new DcaeUsers();
data.setId(1);
assertTrue(1 == data.getId());
data.setName("Test");
@@ -51,9 +65,12 @@ public class MicroServiceDictionaryJPATest {
assertTrue("Test".equals(data.getDescriptionValue()));
}
+ /**
+ * Test DCA euuid.
+ */
@Test
- public void testDCAEuuid(){
- DCAEuuid data = new DCAEuuid();
+ public void testDcaeUuid() {
+ DcaeUuid data = new DcaeUuid();
data.setId(1);
assertTrue(1 == data.getId());
data.setName("Test");
@@ -62,30 +79,39 @@ public class MicroServiceDictionaryJPATest {
assertTrue("Test".equals(data.getDescription()));
}
+ /**
+ * Test MS config name.
+ */
@Test
- public void testMSConfigName(){
+ public void testMsConfigName() {
MicroServiceConfigName data = new MicroServiceConfigName();
data.setId(1);
assertTrue(1 == data.getId());
data.setName("Test");
assertTrue("Test".equals(data.getName()));
- data.setDescriptionValue("Test");
- assertTrue("Test".equals(data.getDescriptionValue()));
+ data.setDescription("Test");
+ assertTrue("Test".equals(data.getDescription()));
}
+ /**
+ * Test MS config location.
+ */
@Test
- public void testMSConfigLocation(){
+ public void testMsConfigLocation() {
MicroServiceLocation data = new MicroServiceLocation();
data.setId(1);
assertTrue(1 == data.getId());
data.setName("Test");
assertTrue("Test".equals(data.getName()));
- data.setDescriptionValue("Test");
- assertTrue("Test".equals(data.getDescriptionValue()));
+ data.setDescription("Test");
+ assertTrue("Test".equals(data.getDescription()));
}
+ /**
+ * Test MS models.
+ */
@Test
- public void testMSModels(){
+ public void testMsModels() {
MicroServiceModels data = new MicroServiceModels();
data.setId(1);
assertTrue(1 == data.getId());
@@ -101,18 +127,22 @@ public class MicroServiceDictionaryJPATest {
assertTrue("Test".equals(data.getAnnotation()));
data.setAttributes("Test");
assertTrue("Test".equals(data.getAttributes()));
- data.setRef_attributes("Test");
- assertTrue("Test".equals(data.getRef_attributes()));
+ data.setRefAttributes("Test");
+ assertTrue("Test".equals(data.getRefAttributes()));
data.setUserCreatedBy(userInfo);
- assertTrue(data.getUserCreatedBy()!=null);
- data.setSub_attributes("Test");
- assertTrue("Test".equals(data.getSub_attributes()));
+ assertTrue(data.getUserCreatedBy() != null);
+ data.setSubAttributes("Test");
+ assertTrue("Test".equals(data.getSubAttributes()));
data.setVersion("Test");
assertTrue("Test".equals(data.getVersion()));
+ assertFalse(data.isDecisionModel());
}
+ /**
+ * Test MS attribute dictionary.
+ */
@Test
- public void testMSAttributeDictionary(){
+ public void testMsAttributeDictionary() {
MicroServiceAttribute data = new MicroServiceAttribute();
data.setId(1);
assertTrue(1 == data.getId());
@@ -124,52 +154,67 @@ public class MicroServiceDictionaryJPATest {
assertTrue("Test".equals(data.getModelName()));
}
+ /**
+ * Test policy scope service.
+ */
@Test
- public void testPolicyScopeService(){
+ public void testPolicyScopeService() {
PolicyScopeService data = new PolicyScopeService();
data.setId(1);
assertTrue(1 == data.getId());
data.setName("Test");
assertTrue("Test".equals(data.getName()));
- data.setDescriptionValue("Test");
- assertTrue("Test".equals(data.getDescriptionValue()));
+ data.setDescription("Test");
+ assertTrue("Test".equals(data.getDescription()));
}
+ /**
+ * Test policy scope resource.
+ */
@Test
- public void testPolicyScopeResource(){
+ public void testPolicyScopeResource() {
PolicyScopeResource data = new PolicyScopeResource();
data.setId(1);
assertTrue(1 == data.getId());
data.setName("Test");
assertTrue("Test".equals(data.getName()));
- data.setDescriptionValue("Test");
- assertTrue("Test".equals(data.getDescriptionValue()));
+ data.setDescription("Test");
+ assertTrue("Test".equals(data.getDescription()));
}
+ /**
+ * Test policy scope type.
+ */
@Test
- public void testPolicyScopeType(){
+ public void testPolicyScopeType() {
PolicyScopeType data = new PolicyScopeType();
data.setId(1);
assertTrue(1 == data.getId());
data.setName("Test");
assertTrue("Test".equals(data.getName()));
- data.setDescriptionValue("Test");
- assertTrue("Test".equals(data.getDescriptionValue()));
+ data.setDescription("Test");
+ assertTrue("Test".equals(data.getDescription()));
}
+ /**
+ * Test policy scope closed loop.
+ */
@Test
- public void testPolicyScopeClosedLoop(){
+ public void testPolicyScopeClosedLoop() {
PolicyScopeClosedLoop data = new PolicyScopeClosedLoop();
data.setId(1);
assertTrue(1 == data.getId());
data.setName("Test");
assertTrue("Test".equals(data.getName()));
- data.setDescriptionValue("Test");
- assertTrue("Test".equals(data.getDescriptionValue()));
+ data.setDescription("Test");
+ assertTrue("Test".equals(data.getDescription()));
}
+ /**
+ * Test policy scope group policy scope list.
+ */
@Test
- public void testPolicyScopeGroupPolicyScopeList(){
+ public void testPolicyScopeGroupPolicyScopeList() {
GroupPolicyScopeList data = new GroupPolicyScopeList();
data.setId(1);
assertTrue(1 == data.getId());
@@ -181,8 +226,11 @@ public class MicroServiceDictionaryJPATest {
assertTrue("Test".equals(data.getGroupList()));
}
+ /**
+ * Test closed loops.
+ */
@Test
- public void testClosedLoops(){
+ public void testClosedLoops() {
ClosedLoops data = new ClosedLoops();
data.setId(1);
assertTrue(1 == data.getId());
@@ -194,9 +242,12 @@ public class MicroServiceDictionaryJPATest {
assertTrue("Test".equals(data.getYaml()));
}
+ /**
+ * Test VM type.
+ */
@Test
- public void testVMType(){
- VMType data = new VMType();
+ public void testVmType() {
+ VmType data = new VmType();
data.setId(1);
assertTrue(1 == data.getId());
data.setName("Test");
diff --git a/ONAP-REST/src/test/java/org/onap/policy/rest/jpa/MicroserviceHeaderdeFaultsTest.java b/ONAP-REST/src/test/java/org/onap/policy/rest/jpa/MicroserviceHeaderdeFaultsTest.java
index 62452dcb0..cbccc3b96 100644
--- a/ONAP-REST/src/test/java/org/onap/policy/rest/jpa/MicroserviceHeaderdeFaultsTest.java
+++ b/ONAP-REST/src/test/java/org/onap/policy/rest/jpa/MicroserviceHeaderdeFaultsTest.java
@@ -3,13 +3,14 @@
* ONAP-REST
* ================================================================================
* Copyright (C) 2018 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2019 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -21,33 +22,34 @@
package org.onap.policy.rest.jpa;
import static org.junit.Assert.assertEquals;
+
import org.junit.Test;
public class MicroserviceHeaderdeFaultsTest {
- @Test
- public void testHeader() {
- // Set up test data
- String value = "testVal";
- MicroserviceHeaderdeFaults header = new MicroserviceHeaderdeFaults();
- header.prePersist();
- header.preUpdate();
+ @Test
+ public void testHeader() {
+ // Set up test data
+ String value = "testVal";
+ MicroserviceHeaderdeFaults header = new MicroserviceHeaderdeFaults();
+ header.prePersist();
+ header.preUpdate();
- // Set data
- header.setGuard(value);
- header.setId(1);
- header.setModelName(value);
- header.setOnapName(value);
- header.setPriority(value);
- header.setRiskLevel(value);
- header.setRiskType(value);
+ // Set data
+ header.setGuard(value);
+ header.setId(1);
+ header.setModelName(value);
+ header.setOnapName(value);
+ header.setPriority(value);
+ header.setRiskLevel(value);
+ header.setRiskType(value);
- // Test gets
- assertEquals(value, header.getGuard());
- assertEquals(1, header.getId());
- assertEquals(value, header.getModelName());
- assertEquals(value, header.getOnapName());
- assertEquals(value, header.getPriority());
- assertEquals(value, header.getRiskLevel());
- assertEquals(value, header.getRiskType());
- }
+ // Test gets
+ assertEquals(value, header.getGuard());
+ assertEquals(1, header.getId());
+ assertEquals(value, header.getModelName());
+ assertEquals(value, header.getOnapName());
+ assertEquals(value, header.getPriority());
+ assertEquals(value, header.getRiskLevel());
+ assertEquals(value, header.getRiskType());
+ }
}
diff --git a/ONAP-REST/src/test/java/org/onap/policy/rest/jpa/OptimizationModelsJPATest.java b/ONAP-REST/src/test/java/org/onap/policy/rest/jpa/OptimizationModelsJpaTest.java
index 243cb5106..81481e191 100644
--- a/ONAP-REST/src/test/java/org/onap/policy/rest/jpa/OptimizationModelsJPATest.java
+++ b/ONAP-REST/src/test/java/org/onap/policy/rest/jpa/OptimizationModelsJpaTest.java
@@ -3,13 +3,14 @@
* ONAP-REST
* ================================================================================
* Copyright (C) 2018 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2019 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -17,6 +18,7 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.policy.rest.jpa;
import static org.junit.Assert.assertTrue;
@@ -26,11 +28,19 @@ import org.junit.Test;
import org.onap.policy.common.logging.flexlogger.FlexLogger;
import org.onap.policy.common.logging.flexlogger.Logger;
-public class OptimizationModelsJPATest {
+/**
+ * The Class OptimizationModelsJpaTest.
+ */
+public class OptimizationModelsJpaTest {
- private static Logger logger = FlexLogger.getLogger(OptimizationModelsJPATest.class);
+ private static Logger logger = FlexLogger.getLogger(OptimizationModelsJpaTest.class);
private UserInfo userInfo;
+ /**
+ * Sets the up.
+ *
+ * @throws Exception the exception
+ */
@Before
public void setUp() throws Exception {
logger.info("setUp: Entering");
@@ -40,8 +50,11 @@ public class OptimizationModelsJPATest {
logger.info("setUp: exit");
}
+ /**
+ * Test ms models.
+ */
@Test
- public void testMSModels(){
+ public void testMsModels() {
OptimizationModels data = new OptimizationModels();
data.setId(1);
assertTrue(1 == data.getId());
@@ -60,12 +73,11 @@ public class OptimizationModelsJPATest {
data.setRefattributes("Test");
assertTrue("Test".equals(data.getRefattributes()));
data.setUserCreatedBy(userInfo);
- assertTrue(data.getUserCreatedBy()!=null);
+ assertTrue(data.getUserCreatedBy() != null);
data.setSubattributes("Test");
assertTrue("Test".equals(data.getSubattributes()));
data.setVersion("Test");
assertTrue("Test".equals(data.getVersion()));
}
-
}
diff --git a/ONAP-REST/src/test/java/org/onap/policy/rest/jpa/PIPConfigurationTest.java b/ONAP-REST/src/test/java/org/onap/policy/rest/jpa/PIPConfigurationTest.java
deleted file mode 100644
index 1a4c2756b..000000000
--- a/ONAP-REST/src/test/java/org/onap/policy/rest/jpa/PIPConfigurationTest.java
+++ /dev/null
@@ -1,121 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * ONAP-REST
- * ================================================================================
- * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import java.util.Date;
-import java.util.HashSet;
-import java.util.Properties;
-import java.util.Set;
-import org.junit.Test;
-import com.att.research.xacml.api.pip.PIPException;
-import com.att.research.xacml.util.XACMLProperties;
-
-public class PIPConfigurationTest {
- @Test
- public void testConfig() throws PIPException {
- String value = "testVal";
- String id = "1";
- PIPConfigParam param = new PIPConfigParam();
- param.setParamName(value);
- param.setParamValue(value);
- Set<PIPConfigParam> params = new HashSet<PIPConfigParam>();
- PIPResolver resolver = new PIPResolver();
- resolver.setClassname(value);
- resolver.setName(value);
- params.add(param);
- Set<PIPResolver> resolvers = new HashSet<PIPResolver>();
- resolvers.add(resolver);
- Properties props = new Properties();
- props.setProperty(id + ".classname", value);
- props.setProperty(XACMLProperties.PROP_PIP_ENGINES, id);
- PIPType type = new PIPType();
- Date date = new Date();
-
- // Test constructors
- PIPConfiguration config = new PIPConfiguration();
- assertNotNull(config);
- config.setPipconfigParams(params);
- config.setPipresolvers(resolvers);
- PIPConfiguration config2 = new PIPConfiguration(config, value);
- assertNotNull(config2);
- config2.prePersist();
- config2.preUpdate();
- PIPConfiguration config3 = new PIPConfiguration(id, props);
- assertNotNull(config3);
- PIPConfiguration config4 = new PIPConfiguration(id, props, value);
- assertNotNull(config4);
-
- // Test set and get
- config.setId(1);
- assertEquals(1, config.getId());
- config.setDescription(value);
- assertEquals(value, config.getDescription());
- config.setName(id);
- assertEquals(id, config.getName());
- config.setClassname(value);
- assertEquals(value, config.getClassname());
- config.setIssuer(value);
- assertEquals(value, config.getIssuer());
- config.setReadOnly(true);
- assertEquals('1', config.getReadOnly());
- config.setReadOnly('0');
- assertEquals('0', config.getReadOnly());
- assertEquals(false, config.isReadOnly());
- config.setRequiresResolvers('t');
- assertEquals('t', config.getRequiresResolvers());
- config.setReadOnly(false);
- assertEquals('0', config.getReadOnly());
- config.setPiptype(type);
- assertEquals(type, config.getPiptype());
- config.setRequiresResolvers(false);
- assertEquals('0', config.getRequiresResolvers());
- config.setCreatedBy(value);
- assertEquals(value, config.getCreatedBy());
- config.setCreatedDate(date);
- assertEquals(date, config.getCreatedDate());
- config.setModifiedBy(value);
- assertEquals(value, config.getModifiedBy());
- config.setModifiedDate(date);
- assertEquals(date, config.getModifiedDate());
- config.setRequiresResolvers(true);
- assertEquals(true, config.requiresResolvers());
- assertEquals(8, config.getConfiguration(id).size());
- assertEquals(9, config.generateProperties(id).size());
-
- // Test remove and clear
- assertEquals(param, config.removePipconfigParam(param));
- config.clearConfigParams();
- assertEquals(0, config.getPipconfigParams().size());
- config.removePipresolver(resolver);
- assertEquals(0, config.getPipresolvers().size());
-
- // Test import
- assertEquals(1, PIPConfiguration.importPIPConfigurations(props).size());
- config.readProperties(id, props);
- assertEquals(id, config.getName());
-
- // Test toString
- String configString = config.toString().replaceAll("@[0-9a-f]*", "");
- assertEquals(323, configString.length());
- }
-}
diff --git a/ONAP-REST/src/test/java/org/onap/policy/rest/jpa/PipConfigurationTest.java b/ONAP-REST/src/test/java/org/onap/policy/rest/jpa/PipConfigurationTest.java
new file mode 100644
index 000000000..9bc95dc5f
--- /dev/null
+++ b/ONAP-REST/src/test/java/org/onap/policy/rest/jpa/PipConfigurationTest.java
@@ -0,0 +1,196 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP-REST
+ * ================================================================================
+ * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2019 Nordix Foundation.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 static org.assertj.core.api.Assertions.assertThatThrownBy;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertTrue;
+
+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 java.util.Date;
+import java.util.HashSet;
+import java.util.LinkedHashSet;
+import java.util.Properties;
+import java.util.Set;
+
+import org.junit.Test;
+
+public class PipConfigurationTest {
+ @Test
+ public void testConfig() throws PIPException {
+ String value = "testVal";
+ PipConfigParam param = new PipConfigParam();
+ param.setParamName(value);
+ param.setParamValue(value);
+ Set<PipConfigParam> params = new HashSet<PipConfigParam>();
+ PipResolver resolver = new PipResolver();
+ resolver.setClassname(value);
+ resolver.setName(value);
+ params.add(param);
+ Set<PipResolver> resolvers = new HashSet<PipResolver>();
+ resolvers.add(resolver);
+ Properties props = new Properties();
+
+ String id = "1";
+ props.setProperty(id + ".classname", value);
+ props.setProperty(XACMLProperties.PROP_PIP_ENGINES, id);
+
+ // Test constructors
+ PipConfiguration config = new PipConfiguration();
+ assertNotNull(config);
+ config.setPipconfigParams(params);
+ config.setPipresolvers(resolvers);
+ PipConfiguration config2 = new PipConfiguration(config, value);
+ assertNotNull(config2);
+ config2.prePersist();
+ config2.preUpdate();
+ PipConfiguration config3 = new PipConfiguration(id, props);
+ assertNotNull(config3);
+ PipConfiguration config4 = new PipConfiguration(id, props, value);
+ assertNotNull(config4);
+
+ // Test set and get
+ config.setId(1);
+ assertEquals(1, config.getId());
+ config.setDescription(value);
+ assertEquals(value, config.getDescription());
+ config.setName(id);
+ assertEquals(id, config.getName());
+ config.setClassname(value);
+ assertEquals(value, config.getClassname());
+ config.setIssuer(value);
+ assertEquals(value, config.getIssuer());
+ config.setReadOnlyFlag(true);
+ assertEquals('1', config.getReadOnly());
+ config.setReadOnly('0');
+ assertEquals('0', config.getReadOnly());
+ assertEquals(false, config.isReadOnly());
+ config.setRequiresResolvers('t');
+ assertEquals('t', config.getRequiresResolvers());
+ config.setReadOnlyFlag(false);
+ assertEquals('0', config.getReadOnly());
+
+ PipType type = new PipType();
+ config.setPiptype(type);
+ assertEquals(type, config.getPiptype());
+ config.setRequiresResolversFlag(false);
+ assertEquals('0', config.getRequiresResolvers());
+ config.setCreatedBy(value);
+ assertEquals(value, config.getCreatedBy());
+
+ Date date = new Date();
+ config.setCreatedDate(date);
+ assertEquals(date, config.getCreatedDate());
+ config.setModifiedBy(value);
+ assertEquals(value, config.getModifiedBy());
+ config.setModifiedDate(date);
+ assertEquals(date, config.getModifiedDate());
+ config.setRequiresResolversFlag(true);
+ assertTrue(config.requiresResolvers());
+ config.setRequiresResolversFlag(false);
+ assertFalse(config.requiresResolvers());
+ assertEquals(8, config.getConfiguration(id).size());
+ assertEquals(9, config.generateProperties(id).size());
+
+ // Test remove and clear
+ assertEquals(param, config.removePipconfigParam(param));
+ assertNull(config.removePipconfigParam(null));
+ config.clearConfigParams();
+ assertEquals(0, config.getPipconfigParams().size());
+ config.removePipresolver(resolver);
+ assertEquals(0, config.getPipresolvers().size());
+
+ assertEquals(param, config.addPipconfigParam(param));
+ config.clearConfigParams();
+ assertEquals(0, config.getPipconfigParams().size());
+ config.removePipresolver(resolver);
+ assertEquals(0, config.getPipresolvers().size());
+
+ // Test import
+ assertEquals(1, PipConfiguration.importPipConfigurations(props).size());
+ config.readProperties(id, props);
+ assertEquals(id, config.getName());
+
+ // Test toString
+ String configString = config.toString().replaceAll("@[0-9a-f]*", "");
+ assertEquals(322, configString.length());
+
+ assertEquals(0, PipConfiguration.importPipConfigurations(new Properties()).size());
+
+ Properties otherProperties = new Properties();
+ otherProperties.put(XACMLProperties.PROP_PIP_ENGINES, "");
+ assertEquals(0, PipConfiguration.importPipConfigurations(otherProperties).size());
+
+ otherProperties.put(XACMLProperties.PROP_PIP_ENGINES, "badvalue:evenworse");
+ assertEquals(0, PipConfiguration.importPipConfigurations(otherProperties).size());
+
+ // Test readProperties
+ props.setProperty(id + "." + StdConfigurableEngine.PROP_ISSUER, "himself");
+ props.setProperty(id + ".resolvers", "");
+ props.setProperty(id + ".resolver", "");
+ props.setProperty(id + ".anotherproperty", "");
+ config.readProperties(id, props);
+ assertEquals("himself", config.getIssuer());
+ assertEquals(49, config.getRequiresResolvers());
+
+ props.setProperty(id + ".resolvers", "aaa");
+ assertThatThrownBy(() -> config.readProperties(id, props)).hasMessage("PIP Engine defined without a classname");
+
+ props.setProperty(id + ".resolver.aaa.classname", "somewhere.over.the.Rainbow");
+ props.setProperty(id + ".resolver.aaa." + StdConfigurableEngine.PROP_NAME, "Dorothy");
+ props.setProperty(id + ".resolver.aaa." + StdConfigurableEngine.PROP_DESCRIPTION, "Oz");
+ props.setProperty(id + ".resolver.aaa." + StdConfigurableEngine.PROP_ISSUER, "Wizard");
+ props.setProperty(id + ".resolver.aaa.witch", "North");
+ config.readProperties(id, props);
+
+ PipResolver pipResolver = config.getPipresolvers().iterator().next();
+
+ assertEquals("somewhere.over.the.Rainbow", pipResolver.getClassname());
+ assertEquals("Dorothy", pipResolver.getName());
+ assertEquals("Oz", pipResolver.getDescription());
+ assertEquals("Wizard", pipResolver.getIssuer());
+
+ // Test getConfiguration
+ assertEquals(10, config.getConfiguration(null).size());
+ assertEquals(10, config.getConfiguration("kansas").size());
+ assertEquals(10, config.getConfiguration("kansas.").size());
+ config.setDescription(null);
+ assertEquals(9, config.getConfiguration(null).size());
+ config.setIssuer(null);
+ assertEquals(8, config.getConfiguration(null).size());
+ config.setPipresolvers(new LinkedHashSet<PipResolver>());
+ assertEquals(3, config.getConfiguration(null).size());
+
+ // Test generateProperties
+ assertEquals(4, config.generateProperties(null).size());
+ assertEquals(4, config.generateProperties("kansas").size());
+ assertEquals(4, config.generateProperties("kansas.").size());
+ config.setIssuer("");
+ assertEquals(4, config.generateProperties("kansas.").size());
+ }
+}
diff --git a/ONAP-REST/src/test/java/org/onap/policy/rest/jpa/PIPJPATest.java b/ONAP-REST/src/test/java/org/onap/policy/rest/jpa/PipJpaTest.java
index 7421d79c9..2a5dff61f 100644
--- a/ONAP-REST/src/test/java/org/onap/policy/rest/jpa/PIPJPATest.java
+++ b/ONAP-REST/src/test/java/org/onap/policy/rest/jpa/PipJpaTest.java
@@ -3,13 +3,14 @@
* ONAP-REST
* ================================================================================
* Copyright (C) 2018 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2019 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -17,25 +18,33 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.policy.rest.jpa;
-import static org.junit.Assert.*;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
+
+import com.att.research.xacml.api.pip.PIPException;
import java.util.Date;
import java.util.HashSet;
+import java.util.LinkedHashSet;
import java.util.Properties;
+import java.util.Set;
import org.junit.Test;
-import com.att.research.xacml.api.pip.PIPException;
-
-public class PIPJPATest {
+public class PipJpaTest {
@Test
- public void testPIPConfigParam(){
- PIPConfigParam data = new PIPConfigParam();
- new PIPConfigParam("test");
- new PIPConfigParam(new PIPConfigParam());
+ public void testPipConfigParam() {
+ PipConfigParam data = new PipConfigParam();
+ new PipConfigParam("test");
+ new PipConfigParam(new PipConfigParam());
data.setId(1);
assertTrue(1 == data.getId());
data.setParamName("Test");
@@ -44,18 +53,20 @@ public class PIPJPATest {
assertTrue("Test".equals(data.getParamValue()));
data.setParamDefault("Test");
assertTrue("Test".equals(data.getParamDefault()));
- data.setPipconfiguration(new PIPConfiguration());
- assertTrue(data.getPipconfiguration()!=null);
- data.setRequired(true);
+ data.setPipconfiguration(new PipConfiguration());
+ assertTrue(data.getPipconfiguration() != null);
+ data.setRequiredFlag(true);
assertTrue(data.isRequired());
+ data.setRequiredFlag(false);
+ assertFalse(data.isRequired());
data.toString();
}
@Test
- public void testPIPResolverParam(){
- PIPResolverParam data = new PIPResolverParam();
- new PIPResolverParam("test");
- new PIPResolverParam(new PIPResolverParam());
+ public void testPipResolverParam() {
+ PipResolverParam data = new PipResolverParam();
+ new PipResolverParam("test");
+ new PipResolverParam(new PipResolverParam());
data.setId(1);
assertTrue(1 == data.getId());
data.setParamName("Test");
@@ -64,40 +75,42 @@ public class PIPJPATest {
assertTrue("Test".equals(data.getParamValue()));
data.setParamDefault("Test");
assertTrue("Test".equals(data.getParamDefault()));
- data.setPipresolver(new PIPResolver());
- assertTrue(data.getPipresolver()!=null);
+ data.setPipresolver(new PipResolver());
+ assertTrue(data.getPipresolver() != null);
data.setRequired(true);
assertTrue(data.isRequired());
+ data.setRequired(false);
+ assertFalse(data.isRequired());
data.toString();
}
@Test
- public void testPIPType(){
- PIPType data = new PIPType();
+ public void testPipType() {
+ PipType data = new PipType();
data.setId(1);
assertTrue(1 == data.getId());
data.setType("Test");
assertTrue("Test".equals(data.getType()));
data.setPipconfigurations(new HashSet<>());
- assertTrue(data.getPipconfigurations()!=null);
- data.addPipconfiguration(new PIPConfiguration());
- data.removePipconfiguration(new PIPConfiguration());
+ assertTrue(data.getPipconfigurations() != null);
+ data.addPipconfiguration(new PipConfiguration());
+ data.removePipconfiguration(new PipConfiguration());
data.setType("SQL");
- assertTrue(data.isSQL());
+ assertTrue(data.isSql());
data.setType("LDAP");
- assertTrue(data.isLDAP());
+ assertTrue(data.isLdap());
data.setType("CSV");
- assertTrue(data.isCSV());
+ assertTrue(data.isCsv());
data.setType("Hyper-CSV");
- assertTrue(data.isHyperCSV());
+ assertTrue(data.isHyperCsv());
data.setType("Custom");
assertTrue(data.isCustom());
}
@Test
- public void testPIPResolver(){
- PIPResolver data = new PIPResolver();
- new PIPResolver(new PIPResolver());
+ public void testPipResolver() {
+ PipResolver data = new PipResolver();
+ new PipResolver(new PipResolver());
data.prePersist();
data.preUpdate();
data.setId(1);
@@ -115,32 +128,50 @@ public class PIPJPATest {
data.setModifiedBy("Test");
assertTrue("Test".equals(data.getModifiedBy()));
data.setCreatedDate(new Date());
- assertTrue(data.getCreatedDate()!=null);
+ assertTrue(data.getCreatedDate() != null);
data.setModifiedDate(new Date());
- assertTrue(data.getModifiedDate()!=null);
- data.setPipconfiguration(new PIPConfiguration());
- assertTrue(data.getPipconfiguration()!=null);
+ assertTrue(data.getModifiedDate() != null);
+ data.setPipconfiguration(new PipConfiguration());
+ assertTrue(data.getPipconfiguration() != null);
data.setPipresolverParams(new HashSet<>());
- assertTrue(data.getPipresolverParams()!=null);
- data.addPipresolverParam(new PIPResolverParam());
- data.removePipresolverParam(new PIPResolverParam());
+ assertTrue(data.getPipresolverParams() != null);
+ data.addPipresolverParam(new PipResolverParam());
+ data.removePipresolverParam(new PipResolverParam());
+ assertNull(data.removePipresolverParam(null));
data.clearParams();
data.getConfiguration("test");
+ assertNotNull(data.getConfiguration("test."));
data.setReadOnly(true);
assertTrue(data.isReadOnly());
+ data.setReadOnly(false);
+ assertFalse(data.isReadOnly());
data.toString();
Properties properties = new Properties();
- data.generateProperties(properties,"test");
+ data.generateProperties(properties, "test");
try {
data.readProperties("test", properties);
} catch (PIPException e) {
fail();
}
+ data.setIssuer("");
+ assertEquals(4, data.getConfiguration("test").size());
+ data.generateProperties(properties, "test.");
+ assertEquals(4, data.getConfiguration("test").size());
+
+ Set<PipResolverParam> pipresolverParams = new LinkedHashSet<>();
+ PipResolverParam prp = new PipResolverParam();
+ prp.setParamName("Dorothy");
+ prp.setParamValue("Gale");
+ pipresolverParams.add(prp);
+ data.setPipresolverParams(pipresolverParams);
+ data.generateProperties(properties, "test");
+ assertEquals(5, data.getConfiguration("test").size());
+ assertEquals(5, new PipResolver(data).getConfiguration("test").size());
}
@Test
- public void testPIPConfiguration(){
- PIPConfiguration data = new PIPConfiguration();
+ public void testPipConfiguration() {
+ PipConfiguration data = new PipConfiguration();
data.prePersist();
data.preUpdate();
data.setId(1);
@@ -158,24 +189,24 @@ public class PIPJPATest {
data.setModifiedBy("Test");
assertTrue("Test".equals(data.getModifiedBy()));
data.setCreatedDate(new Date());
- assertTrue(data.getCreatedDate()!=null);
+ assertTrue(data.getCreatedDate() != null);
data.setModifiedDate(new Date());
- assertTrue(data.getModifiedDate()!=null);
+ assertTrue(data.getModifiedDate() != null);
try {
data.readProperties("test", data.generateProperties("test"));
} catch (PIPException e) {
fail();
}
- data.setPiptype(new PIPType());
- assertTrue(data.getPiptype()!=null);
+ data.setPiptype(new PipType());
+ assertTrue(data.getPiptype() != null);
data.setPipresolvers(new HashSet<>());
- assertTrue(data.getPipresolvers()!=null);
- data.addPipresolver(new PIPResolver());
- data.removePipresolver(new PIPResolver());
+ assertTrue(data.getPipresolvers() != null);
+ data.addPipresolver(new PipResolver());
+ data.removePipresolver(new PipResolver());
data.getConfiguration("test");
- data.setReadOnly(true);
+ data.setReadOnlyFlag(true);
assertTrue(data.isReadOnly());
- data.setRequiresResolvers(true);
+ data.setRequiresResolversFlag(true);
assertTrue(data.requiresResolvers());
data.toString();
}
diff --git a/ONAP-REST/src/test/java/org/onap/policy/rest/jpa/PolicyAuditlogTest.java b/ONAP-REST/src/test/java/org/onap/policy/rest/jpa/PolicyAuditlogTest.java
index 15e28b142..1ae1cb3e2 100644
--- a/ONAP-REST/src/test/java/org/onap/policy/rest/jpa/PolicyAuditlogTest.java
+++ b/ONAP-REST/src/test/java/org/onap/policy/rest/jpa/PolicyAuditlogTest.java
@@ -3,6 +3,7 @@
* ONAP-REST
* ================================================================================
* Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2019 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -21,7 +22,9 @@
package org.onap.policy.rest.jpa;
import static org.junit.Assert.assertEquals;
+
import java.text.ParseException;
+
import org.junit.Test;
public class PolicyAuditlogTest {
diff --git a/ONAP-REST/src/test/java/org/onap/policy/rest/jpa/PolicyEntityJPATest.java b/ONAP-REST/src/test/java/org/onap/policy/rest/jpa/PolicyEntityJPATest.java
deleted file mode 100644
index 706471281..000000000
--- a/ONAP-REST/src/test/java/org/onap/policy/rest/jpa/PolicyEntityJPATest.java
+++ /dev/null
@@ -1,206 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * ONAP-REST
- * ================================================================================
- * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 static org.junit.Assert.assertTrue;
-
-import java.util.Date;
-
-import org.junit.Before;
-import org.junit.Test;
-import org.onap.policy.common.logging.flexlogger.FlexLogger;
-import org.onap.policy.common.logging.flexlogger.Logger;
-
-public class PolicyEntityJPATest {
-
- private static Logger logger = FlexLogger.getLogger(PolicyEntityJPATest.class);
- private UserInfo userInfo;
-
- @Before
- public void setUp() throws Exception {
- logger.info("setUp: Entering");
- userInfo = new UserInfo();
- userInfo.setUserLoginId("Test");
- userInfo.setUserName("Test");
- logger.info("setUp: exit");
- }
-
- @Test
- public void testPolicyGroupEntity(){
- PolicyGroupEntity data = new PolicyGroupEntity();
- data.setGroupKey(1);
- assertTrue(1 == data.getGroupKey());
- data.setPolicyid(1);
- assertTrue(1 == data.getPolicyid());
- }
-
- @Test
- public void testPolicyDBDaoEntity(){
- PolicyDBDaoEntity data = new PolicyDBDaoEntity();
- data.prePersist();
- data.preUpdate();
- data.setPolicyDBDaoUrl("Test");
- assertTrue("Test".equals(data.getPolicyDBDaoUrl()));
- data.setDescription("Test");
- assertTrue("Test".equals(data.getDescription()));
- assertTrue(data.getCreatedDate()!=null);
- assertTrue(data.getModifiedDate()!=null);
- data.setUsername("Test");
- assertTrue("Test".equals(data.getUsername()));
- data.setPassword("Test");
- assertTrue("Test".equals(data.getPassword()));
- }
-
- @Test
- public void testDatabaseLockEntity(){
- DatabaseLockEntity data = new DatabaseLockEntity();
- data.setKey(1);
- assertTrue(1 == data.getKey());
- }
-
- @Test
- public void testPolicyEntity(){
- PolicyEntity data = new PolicyEntity();
- data.prePersist();
- data.preUpdate();
- data.setPolicyName("Test");
- assertTrue("Test".equals(data.getPolicyName()));
- data.setDescription("Test");
- assertTrue("Test".equals(data.getDescription()));
- assertTrue(data.getCreatedDate()!=null);
- assertTrue(data.getModifiedDate()!=null);
- data.setPolicyData("Test");
- assertTrue("Test".equals(data.getPolicyData()));
- data.setConfigurationData(new ConfigurationDataEntity());
- assertTrue(data.getConfigurationData()!=null);
- data.setActionBodyEntity(new ActionBodyEntity());
- assertTrue(data.getActionBodyEntity()!=null);
- data.setScope("Test");
- assertTrue("Test".equals(data.getScope()));
- data.setCreatedBy("Test");
- assertTrue("Test".equals(data.getCreatedBy()));
- data.setModifiedBy("Test");
- assertTrue("Test".equals(data.getModifiedBy()));
- data.setDeleted(true);
- assertTrue(data.isDeleted());
- data.equals(new PolicyEntity());
- data.hashCode();
- }
-
- @Test
- public void testActionBodyEntity(){
- ActionBodyEntity data = new ActionBodyEntity();
- data.prePersist();
- data.preUpdate();
- data.setActionBodyName("Test");
- assertTrue("Test".equals(data.getActionBodyName()));
- data.setActionBody("Test");
- assertTrue("Test".equals(data.getActionBody()));
- data.setCreatedBy("Test");
- assertTrue("Test".equals(data.getCreatedBy()));
- data.setModifiedBy("Test");
- assertTrue("Test".equals(data.getModifiedBy()));
- data.setModifiedDate(new Date());
- assertTrue(data.getCreatedDate()!=null);
- assertTrue(data.getModifiedDate()!=null);
- data.setDeleted(true);
- assertTrue(data.isDeleted());
- assertTrue(data.getCreatedDate()!=null);
- assertTrue(data.getModifiedDate()!=null);
- data.equals(new ConfigurationDataEntity());
- data.hashCode();
- }
-
- @Test
- public void testConfigurationDataEntity(){
- ConfigurationDataEntity data = new ConfigurationDataEntity();
- data.prePersist();
- data.preUpdate();
- data.setConfigurationName("Test");
- assertTrue("Test".equals(data.getConfigurationName()));
- data.setConfigType("Test");
- assertTrue("Test".equals(data.getConfigType()));
- data.setConfigBody("Test");
- assertTrue("Test".equals(data.getConfigBody()));
- data.setCreatedBy("Test");
- assertTrue("Test".equals(data.getCreatedBy()));
- data.setDescription("Test");
- assertTrue("Test".equals(data.getDescription()));
- data.setModifiedBy("Test");
- assertTrue("Test".equals(data.getModifiedBy()));
- data.setModifiedDate(new Date());
- assertTrue(data.getCreatedDate()!=null);
- assertTrue(data.getModifiedDate()!=null);
- data.setDeleted(true);
- assertTrue(data.isDeleted());
- assertTrue(data.getCreatedDate()!=null);
- assertTrue(data.getModifiedDate()!=null);
- data.equals(new ConfigurationDataEntity());
- data.hashCode();
- }
-
- @Test
- public void testPdpEntity(){
- PdpEntity data = new PdpEntity();
- data.prePersist();
- data.preUpdate();
- data.setPdpId("Test");
- assertTrue("Test".equals(data.getPdpId()));
- data.setPdpName("Test");
- assertTrue("Test".equals(data.getPdpName()));
- data.setGroup(new GroupEntity());
- assertTrue(data.getGroup()!=null);
- data.setCreatedBy("Test");
- assertTrue("Test".equals(data.getCreatedBy()));
- data.setDescription("Test");
- assertTrue("Test".equals(data.getDescription()));
- data.setModifiedBy("Test");
- assertTrue("Test".equals(data.getModifiedBy()));
- data.setJmxPort(1);
- assertTrue(1 == data.getJmxPort());
- data.setDeleted(true);
- assertTrue(data.isDeleted());
- assertTrue(data.getCreatedDate()!=null);
- assertTrue(data.getModifiedDate()!=null);
- }
-
- @Test
- public void testGroupEntity(){
- GroupEntity data = new GroupEntity();
- data.prePersist();
- data.preUpdate();
- data.setGroupId("Test");
- assertTrue("Test".equals(data.getGroupId()));
- data.setGroupName("Test");
- assertTrue("Test".equals(data.getgroupName()));
- data.setCreatedBy("Test");
- assertTrue("Test".equals(data.getCreatedBy()));
- data.setDescription("Test");
- assertTrue("Test".equals(data.getDescription()));
- data.setModifiedBy("Test");
- assertTrue("Test".equals(data.getModifiedBy()));
- data.setDefaultGroup(true);
- assertTrue(data.isDefaultGroup());
- data.setDeleted(true);
- assertTrue(data.isDeleted());
- assertTrue(data.getCreatedDate()!=null);
- assertTrue(data.getModifiedDate()!=null);
- }
-}
diff --git a/ONAP-REST/src/test/java/org/onap/policy/rest/jpa/PolicyEntityJpaTest.java b/ONAP-REST/src/test/java/org/onap/policy/rest/jpa/PolicyEntityJpaTest.java
new file mode 100644
index 000000000..a55ff8d6e
--- /dev/null
+++ b/ONAP-REST/src/test/java/org/onap/policy/rest/jpa/PolicyEntityJpaTest.java
@@ -0,0 +1,528 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP-REST
+ * ================================================================================
+ * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2019 Nordix Foundation.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertTrue;
+
+import java.util.Date;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.onap.policy.common.logging.flexlogger.FlexLogger;
+import org.onap.policy.common.logging.flexlogger.Logger;
+
+/**
+ * The Class PolicyEntityJpaTest.
+ */
+public class PolicyEntityJpaTest {
+
+ private static Logger logger = FlexLogger.getLogger(PolicyEntityJpaTest.class);
+ private UserInfo userInfo;
+
+ /**
+ * Sets the up.
+ *
+ * @throws Exception the exception
+ */
+ @Before
+ public void setUp() throws Exception {
+ logger.info("setUp: Entering");
+ userInfo = new UserInfo();
+ userInfo.setUserLoginId("Test");
+ userInfo.setUserName("Test");
+ logger.info("setUp: exit");
+ }
+
+ /**
+ * Test policy group entity.
+ */
+ @Test
+ public void testPolicyGroupEntity() {
+ PolicyGroupEntity data = new PolicyGroupEntity();
+ data.setGroupKey(1);
+ assertTrue(1 == data.getGroupKey());
+ data.setPolicyid(1);
+ assertTrue(1 == data.getPolicyid());
+ }
+
+ /**
+ * Test policy DB dao entity.
+ */
+ @Test
+ public void testPolicyDbDaoEntity() {
+ PolicyDbDaoEntity data = new PolicyDbDaoEntity();
+ data.prePersist();
+ data.preUpdate();
+ data.setPolicyDbDaoUrl("Test");
+ assertTrue("Test".equals(data.getPolicyDbDaoUrl()));
+ data.setDescription("Test");
+ assertTrue("Test".equals(data.getDescription()));
+ assertTrue(data.getCreatedDate() != null);
+ assertTrue(data.getModifiedDate() != null);
+ data.setUsername("Test");
+ assertTrue("Test".equals(data.getUsername()));
+ data.setPassword("Test");
+ assertTrue("Test".equals(data.getPassword()));
+ }
+
+ /**
+ * Test database lock entity.
+ */
+ @Test
+ public void testDatabaseLockEntity() {
+ DatabaseLockEntity data = new DatabaseLockEntity();
+ data.setKey(1);
+ assertTrue(1 == data.getKey());
+ }
+
+ /**
+ * Test policy entity.
+ */
+ @Test
+ public void testPolicyEntity() {
+ PolicyEntity data = new PolicyEntity();
+ data.prePersist();
+ data.preUpdate();
+ data.setPolicyName("Test");
+ assertTrue("Test".equals(data.getPolicyName()));
+ data.setDescription("Test");
+ assertTrue("Test".equals(data.getDescription()));
+ assertTrue(data.getCreatedDate() != null);
+ assertTrue(data.getModifiedDate() != null);
+ data.setPolicyData("Test");
+ assertTrue("Test".equals(data.getPolicyData()));
+ data.setConfigurationData(new ConfigurationDataEntity());
+ assertTrue(data.getConfigurationData() != null);
+ data.setActionBodyEntity(new ActionBodyEntity());
+ assertTrue(data.getActionBodyEntity() != null);
+ data.setScope("Test");
+ assertTrue("Test".equals(data.getScope()));
+ data.setCreatedBy("Test");
+ assertTrue("Test".equals(data.getCreatedBy()));
+ data.setModifiedBy("Test");
+ assertTrue("Test".equals(data.getModifiedBy()));
+ data.setDeleted(true);
+ assertTrue(data.isDeleted());
+ data.equals(new PolicyEntity());
+ data.hashCode();
+
+ PolicyEntity entity0 = new PolicyEntity();
+ PolicyEntity entity1 = new PolicyEntity();
+ assertEquals(entity0, entity0);
+ assertEquals(entity0, entity1);
+ assertNotEquals(entity0, null);
+ String helloString = "Hello";
+ Object helloObject = helloString;
+ assertNotEquals(entity0, helloObject);
+
+ entity0.setPolicyId(1);
+ assertNotEquals(entity0, entity1);
+ entity1.setPolicyId(1);
+ assertEquals(entity0, entity1);
+ entity0.setPolicyId(2);
+ assertNotEquals(entity0, entity1);
+ entity1.setPolicyId(2);
+ assertEquals(entity0, entity1);
+
+ entity0.setPolicyName("GoToOz");
+ assertNotEquals(entity0, entity1);
+ entity1.setPolicyName("GoToOz");
+ assertEquals(entity0, entity1);
+ entity1.setPolicyName(null);
+ assertNotEquals(entity0, entity1);
+ entity0.setPolicyName(null);
+ assertEquals(entity0, entity1);
+ entity1.setPolicyName("GoToOz");
+ assertNotEquals(entity0, entity1);
+ entity0.setPolicyName("GoToOz");
+ assertEquals(entity0, entity1);
+ entity1.setPolicyName("GoToOzNow");
+ assertNotEquals(entity0, entity1);
+ entity0.setPolicyName("GoToOzNow");
+ assertEquals(entity0, entity1);
+
+ entity0.setScope("All");
+ assertNotEquals(entity0, entity1);
+ entity1.setScope("All");
+ assertEquals(entity0, entity1);
+ entity1.setScope(null);
+ assertNotEquals(entity0, entity1);
+ entity0.setScope(null);
+ assertEquals(entity0, entity1);
+ entity1.setScope("All");
+ assertNotEquals(entity0, entity1);
+ entity0.setScope("All");
+ assertEquals(entity0, entity1);
+ entity1.setScope("AllIn");
+ assertNotEquals(entity0, entity1);
+ entity0.setScope("AllIn");
+ assertEquals(entity0, entity1);
+
+ entity0.setVersion(1);
+ assertNotEquals(entity0, entity1);
+ entity1.setVersion(1);
+ assertEquals(entity0, entity1);
+
+ entity0.setPolicyVersion(1);
+ assertNotEquals(entity0, entity1);
+ entity1.setPolicyVersion(1);
+ assertEquals(entity0, entity1);
+ entity0.setPolicyVersion(2);
+ assertNotEquals(entity0, entity1);
+ entity1.setPolicyVersion(2);
+ assertEquals(entity0, entity1);
+
+ entity0.setPolicyData("SomeData");
+ assertNotEquals(entity0, entity1);
+ entity1.setPolicyData("SomeData");
+ assertEquals(entity0, entity1);
+ entity1.setPolicyData(null);
+ assertNotEquals(entity0, entity1);
+ entity0.setPolicyData(null);
+ assertEquals(entity0, entity1);
+ entity1.setPolicyData("SomeData");
+ assertNotEquals(entity0, entity1);
+ entity0.setPolicyData("SomeData");
+ assertEquals(entity0, entity1);
+ entity1.setPolicyData("SomeMoreData");
+ assertNotEquals(entity0, entity1);
+ entity0.setPolicyData("SomeMoreData");
+ assertEquals(entity0, entity1);
+
+ ConfigurationDataEntity cde0 = new ConfigurationDataEntity();
+ entity0.setConfigurationDataEntity(cde0);
+ assertNotEquals(entity0, entity1);
+ entity1.setConfigurationDataEntity(cde0);
+ assertEquals(entity0, entity1);
+ entity1.setConfigurationDataEntity(null);
+ assertNotEquals(entity0, entity1);
+ entity0.setConfigurationDataEntity(null);
+ assertEquals(entity0, entity1);
+ ConfigurationDataEntity cde1 = new ConfigurationDataEntity();
+ entity1.setConfigurationDataEntity(cde1);
+ assertNotEquals(entity0, entity1);
+ entity0.setConfigurationDataEntity(cde1);
+ assertEquals(entity0, entity1);
+
+ ActionBodyEntity abe0 = new ActionBodyEntity();
+ entity0.setActionBodyEntity(abe0);
+ assertNotEquals(entity0, entity1);
+ entity1.setActionBodyEntity(abe0);
+ assertEquals(entity0, entity1);
+ entity1.setActionBodyEntity(null);
+ assertNotEquals(entity0, entity1);
+ entity0.setActionBodyEntity(null);
+ assertEquals(entity0, entity1);
+ entity1.setActionBodyEntity(abe0);
+ assertNotEquals(entity0, entity1);
+ entity0.setActionBodyEntity(abe0);
+ assertEquals(entity0, entity1);
+ ActionBodyEntity abe1 = new ActionBodyEntity();
+ entity1.setActionBodyEntity(abe1);
+ assertNotEquals(entity0, entity1);
+ entity0.setActionBodyEntity(abe1);
+ assertEquals(entity0, entity1);
+
+ entity0.setDescription("Description");
+ assertNotEquals(entity0, entity1);
+ entity1.setDescription("Description");
+ assertEquals(entity0, entity1);
+ entity1.setDescription(null);
+ assertNotEquals(entity0, entity1);
+ entity0.setDescription(null);
+ assertEquals(entity0, entity1);
+ entity1.setDescription("Description");
+ assertNotEquals(entity0, entity1);
+ entity0.setDescription("Description");
+ assertEquals(entity0, entity1);
+ assertEquals(entity0, entity1);
+ entity1.setDescription("Description Extra");
+ assertNotEquals(entity0, entity1);
+ entity0.setDescription("Description Extra");
+ assertEquals(entity0, entity1);
+
+ entity0.setDeleted(true);
+ assertNotEquals(entity0, entity1);
+ entity1.setDeleted(true);
+ assertEquals(entity0, entity1);
+ entity0.setDeleted(false);
+ assertNotEquals(entity0, entity1);
+ entity1.setDeleted(false);
+ assertEquals(entity0, entity1);
+
+ entity0.setDeleteReasonCode("NoReason");
+ assertNotEquals(entity0, entity1);
+ entity1.setDeleteReasonCode("NoReason");
+ assertEquals(entity0, entity1);
+ entity1.setDeleteReasonCode(null);
+ assertNotEquals(entity0, entity1);
+ entity0.setDeleteReasonCode(null);
+ assertEquals(entity0, entity1);
+ entity1.setDeleteReasonCode("NoReason");
+ assertNotEquals(entity0, entity1);
+ entity0.setDeleteReasonCode("NoReason");
+ assertEquals(entity0, entity1);
+ assertEquals(entity0, entity1);
+ entity1.setDeleteReasonCode("NoOtherReason");
+ assertNotEquals(entity0, entity1);
+ entity0.setDeleteReasonCode("NoOtherReason");
+ assertEquals(entity0, entity1);
+
+ entity0.setCreatedBy("Dorothy");
+ assertNotEquals(entity0, entity1);
+ entity1.setCreatedBy("Dorothy");
+ assertEquals(entity0, entity1);
+ entity1.setCreatedBy(null);
+ assertNotEquals(entity0, entity1);
+ entity0.setCreatedBy(null);
+ assertEquals(entity0, entity1);
+ entity1.setCreatedBy("Dorothy");
+ assertNotEquals(entity0, entity1);
+ entity0.setCreatedBy("Dorothy");
+ assertEquals(entity0, entity1);
+ entity1.setCreatedBy("Toto");
+ assertNotEquals(entity0, entity1);
+ entity0.setCreatedBy("Toto");
+ assertEquals(entity0, entity1);
+
+ entity0.setCreatedDate(new Date(12345L));
+ assertNotEquals(entity0, entity1);
+ entity1.setCreatedDate(new Date(12345L));
+ assertEquals(entity0, entity1);
+ entity1.setCreatedDate(null);
+ assertNotEquals(entity0, entity1);
+ entity0.setCreatedDate(null);
+ assertEquals(entity0, entity1);
+ entity1.setCreatedDate(new Date(12345L));
+ assertNotEquals(entity0, entity1);
+ entity0.setCreatedDate(new Date(12345L));
+ assertEquals(entity0, entity1);
+ assertEquals(entity0, entity1);
+ entity1.setCreatedDate(new Date(123456L));
+ assertNotEquals(entity0, entity1);
+ entity0.setCreatedDate(new Date(123456L));
+ assertEquals(entity0, entity1);
+
+ entity0.setModifiedBy("Dorothy");
+ assertNotEquals(entity0, entity1);
+ entity1.setModifiedBy("Dorothy");
+ assertEquals(entity0, entity1);
+ entity1.setModifiedBy(null);
+ assertNotEquals(entity0, entity1);
+ entity0.setModifiedBy(null);
+ assertEquals(entity0, entity1);
+ entity1.setModifiedBy("Dorothy");
+ assertNotEquals(entity0, entity1);
+ entity0.setModifiedBy("Dorothy");
+ assertEquals(entity0, entity1);
+ entity1.setModifiedBy("Toto");
+ assertNotEquals(entity0, entity1);
+ entity0.setModifiedBy("Toto");
+ assertEquals(entity0, entity1);
+
+ entity0.setModifiedDate(new Date(12345L));
+ assertNotEquals(entity0, entity1);
+ entity1.setModifiedDate(new Date(12345L));
+ assertEquals(entity0, entity1);
+ entity1.setModifiedDate(null);
+ assertNotEquals(entity0, entity1);
+ entity0.setModifiedDate(null);
+ assertEquals(entity0, entity1);
+ entity1.setModifiedDate(new Date(12345L));
+ assertNotEquals(entity0, entity1);
+ entity0.setModifiedDate(new Date(12345L));
+ assertEquals(entity0, entity1);
+ assertEquals(entity0, entity1);
+ entity1.setModifiedDate(new Date(123456L));
+ assertNotEquals(entity0, entity1);
+ entity0.setModifiedDate(new Date(123456L));
+ assertEquals(entity0, entity1);
+
+ entity0.setDeletedBy("Dorothy");
+ assertNotEquals(entity0, entity1);
+ entity1.setDeletedBy("Dorothy");
+ assertEquals(entity0, entity1);
+ entity1.setDeletedBy(null);
+ assertNotEquals(entity0, entity1);
+ entity0.setDeletedBy(null);
+ assertEquals(entity0, entity1);
+ entity1.setDeletedBy("Dorothy");
+ assertNotEquals(entity0, entity1);
+ entity0.setDeletedBy("Dorothy");
+ assertEquals(entity0, entity1);
+ assertEquals(entity0, entity1);
+ entity1.setDeletedBy("Toto");
+ assertNotEquals(entity0, entity1);
+ entity0.setDeletedBy("Toto");
+ assertEquals(entity0, entity1);
+
+ assertNotNull(entity0.hashCode());
+ assertNotNull(entity1.hashCode());
+ assertEquals(entity0.hashCode(), entity0.hashCode());
+
+ entity0.setDeletedBy("Totp");
+ assertNotEquals(entity0, entity1);
+ assertNotEquals(entity0.hashCode(), entity1.hashCode());
+ }
+
+ /**
+ * Test action body entity.
+ */
+ @Test
+ public void testActionBodyEntity() {
+ ActionBodyEntity data = new ActionBodyEntity();
+ data.prePersist();
+ data.preUpdate();
+ data.setActionBodyName("Test");
+ assertTrue("Test".equals(data.getActionBodyName()));
+ data.setActionBody("Test");
+ assertTrue("Test".equals(data.getActionBody()));
+ data.setCreatedBy("Test");
+ assertTrue("Test".equals(data.getCreatedBy()));
+ data.setModifiedBy("Test");
+ assertTrue("Test".equals(data.getModifiedBy()));
+ data.setModifiedDate(new Date());
+ assertTrue(data.getCreatedDate() != null);
+ assertTrue(data.getModifiedDate() != null);
+ data.setDeleted(true);
+ assertTrue(data.isDeleted());
+ assertTrue(data.getCreatedDate() != null);
+ assertTrue(data.getModifiedDate() != null);
+ String helloString = "Hello";
+ Object helloObject = helloString;
+ assertNotEquals(data, helloObject);
+ data.hashCode();
+ }
+
+ /**
+ * Test configuration data entity.
+ */
+ @Test
+ public void testConfigurationDataEntity() {
+ ConfigurationDataEntity data = new ConfigurationDataEntity();
+ data.prePersist();
+ data.preUpdate();
+ data.setConfigurationName("Test");
+ assertTrue("Test".equals(data.getConfigurationName()));
+ data.setConfigType("Test");
+ assertTrue("Test".equals(data.getConfigType()));
+ data.setConfigBody("Test");
+ assertTrue("Test".equals(data.getConfigBody()));
+ data.setCreatedBy("Test");
+ assertTrue("Test".equals(data.getCreatedBy()));
+ data.setDescription("Test");
+ assertTrue("Test".equals(data.getDescription()));
+ data.setModifiedBy("Test");
+ assertTrue("Test".equals(data.getModifiedBy()));
+ data.setModifiedDate(new Date());
+ assertTrue(data.getCreatedDate() != null);
+ assertTrue(data.getModifiedDate() != null);
+ data.setDeleted(true);
+ assertTrue(data.isDeleted());
+ assertTrue(data.getCreatedDate() != null);
+ assertTrue(data.getModifiedDate() != null);
+ data.equals(new ConfigurationDataEntity());
+ data.hashCode();
+ }
+
+ /**
+ * Test pdp entity.
+ */
+ @Test
+ public void testPdpEntity() {
+ PdpEntity data = new PdpEntity();
+ data.prePersist();
+ data.preUpdate();
+ data.setPdpId("Test");
+ assertTrue("Test".equals(data.getPdpId()));
+ data.setPdpName("Test");
+ assertTrue("Test".equals(data.getPdpName()));
+ data.setGroup(new GroupEntity());
+ assertTrue(data.getGroup() != null);
+ data.setCreatedBy("Test");
+ assertTrue("Test".equals(data.getCreatedBy()));
+ data.setDescription("Test");
+ assertTrue("Test".equals(data.getDescription()));
+ data.setModifiedBy("Test");
+ assertTrue("Test".equals(data.getModifiedBy()));
+ data.setJmxPort(1);
+ assertTrue(1 == data.getJmxPort());
+ data.setDeleted(true);
+ assertTrue(data.isDeleted());
+ assertTrue(data.getCreatedDate() != null);
+ assertTrue(data.getModifiedDate() != null);
+ }
+
+ /**
+ * Test group entity.
+ */
+ @Test
+ public void testGroupEntity() {
+ GroupEntity data = new GroupEntity();
+ data.prePersist();
+ data.preUpdate();
+ data.setGroupId("Test");
+ assertTrue("Test".equals(data.getGroupId()));
+ data.setGroupName("Test");
+ assertTrue("Test".equals(data.getGroupName()));
+ data.setCreatedBy("Test");
+ assertTrue("Test".equals(data.getCreatedBy()));
+ data.setDescription("Test");
+ assertTrue("Test".equals(data.getDescription()));
+ data.setModifiedBy("Test");
+ assertTrue("Test".equals(data.getModifiedBy()));
+ data.setDefaultGroup(true);
+ assertTrue(data.isDefaultGroup());
+ data.setDeleted(true);
+ assertTrue(data.isDeleted());
+ assertTrue(data.getCreatedDate() != null);
+ assertTrue(data.getModifiedDate() != null);
+
+ assertNull(data.getPolicies());
+ PolicyEntity policy0 = new PolicyEntity();
+ policy0.setPolicyName("PolicyName0");
+ data.addPolicyToGroup(policy0);
+ PolicyEntity policy1 = new PolicyEntity();
+ policy1.setPolicyName("PolicyName1");
+ assertTrue(data.getPolicies().contains(policy0));
+ assertFalse(data.getPolicies().contains(policy1));
+ data.addPolicyToGroup(policy1);
+ assertTrue(data.getPolicies().contains(policy0));
+ assertTrue(data.getPolicies().contains(policy1));
+ data.addPolicyToGroup(policy1);
+ assertTrue(data.getPolicies().contains(policy0));
+ assertTrue(data.getPolicies().contains(policy1));
+ data.removePolicyFromGroup(policy0);
+ assertFalse(data.getPolicies().contains(policy0));
+ assertTrue(data.getPolicies().contains(policy1));
+ data.removePolicyFromGroup(policy0);
+ assertFalse(data.getPolicies().contains(policy0));
+ assertTrue(data.getPolicies().contains(policy1));
+ data.removePolicyFromGroup(policy1);
+ assertNull(data.getPolicies());
+ }
+}
diff --git a/ONAP-REST/src/test/java/org/onap/policy/rest/jpa/PolicyUtilsJPATest.java b/ONAP-REST/src/test/java/org/onap/policy/rest/jpa/PolicyUtilsJPATest.java
deleted file mode 100644
index 3ada4dfca..000000000
--- a/ONAP-REST/src/test/java/org/onap/policy/rest/jpa/PolicyUtilsJPATest.java
+++ /dev/null
@@ -1,190 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * ONAP-REST
- * ================================================================================
- * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 static org.junit.Assert.assertTrue;
-
-import java.util.Date;
-
-import org.junit.Before;
-import org.junit.Test;
-import org.onap.policy.common.logging.flexlogger.FlexLogger;
-import org.onap.policy.common.logging.flexlogger.Logger;
-
-public class PolicyUtilsJPATest {
-
- private static Logger logger = FlexLogger.getLogger(PolicyUtilsJPATest.class);
- private UserInfo userInfo;
-
- @Before
- public void setUp() throws Exception {
- logger.info("setUp: Entering");
- userInfo = new UserInfo();
- userInfo.setUserLoginId("Test");
- userInfo.setUserName("Test");
- logger.info("setUp: exit");
- }
-
- @Test
- public void testWatchPolicyNotificationTable(){
- WatchPolicyNotificationTable data = new WatchPolicyNotificationTable();
- data.setId(1);
- assertTrue(1 == data.getId());
- data.setPolicyName("Test");
- assertTrue("Test".equals(data.getPolicyName()));
- data.setLoginIds("Test");
- assertTrue("Test".equals(data.getLoginIds()));
- data.equals(data);
- data.hashCode();
- }
-
- @Test
- public void testPolicyRoles(){
- PolicyRoles data = new PolicyRoles();
- data.setId(1);
- assertTrue(1 == data.getId());
- data.setScope("Test");
- assertTrue("Test".equals(data.getScope()));
- data.setRole("Test");
- assertTrue("Test".equals(data.getRole()));
- data.setLoginId(userInfo);
- assertTrue("Test".equals(data.getLoginId().getUserLoginId()));
- }
-
- @Test
- public void testPolicyVersion(){
- PolicyVersion data = new PolicyVersion();
- new PolicyVersion("Test", "Test");
- data.prePersist();
- data.preUpdate();
- data.setId(1);
- assertTrue(1 == data.getId());
- data.setActiveVersion(1);
- assertTrue(1 == data.getActiveVersion());
- data.setHigherVersion(1);
- assertTrue(1 == data.getHigherVersion());
- data.setPolicyName("Test");
- assertTrue("Test".equals(data.getPolicyName()));
- data.setCreatedBy("Test");
- assertTrue("Test".equals(data.getCreatedBy()));
- data.setModifiedBy("Test");
- assertTrue("Test".equals(data.getModifiedBy()));
- data.setCreatedDate(new Date());
- assertTrue(data.getCreatedDate()!=null);
- data.setModifiedDate(new Date());
- assertTrue(data.getModifiedDate()!=null);
- data.equals(data);
- data.hashCode();
- }
-
- @Test
- public void testSystemLogDB(){
- SystemLogDB data = new SystemLogDB();
- new SystemLogDB(1, "","","","","");
- data.setId(1);
- assertTrue(1 == data.getId());
- data.setDescription("Test");
- assertTrue("Test".equals(data.getDescription()));
- data.setType("Test");
- assertTrue("Test".equals(data.getType()));
- data.setSystem("Test");
- assertTrue("Test".equals(data.getSystem()));
- data.setRemote("Test");
- assertTrue("Test".equals(data.getRemote()));
- data.setLogtype("Test");
- assertTrue("Test".equals(data.getLogtype()));
- data.setDate(new Date());
- assertTrue(data.getDate()!=null);
- }
-
- @Test
- public void testRemoteCatalogValues(){
- RemoteCatalogValues data = new RemoteCatalogValues();
- data.setId(1);
- assertTrue(1 == data.getId());
- data.setName("Test");
- assertTrue("Test".equals(data.getName()));
- data.setValue("Test");
- assertTrue("Test".equals(data.getValue()));
- }
-
- @Test
- public void testPolicyScore(){
- PolicyScore data = new PolicyScore();
- data.setId(1);
- assertTrue(1 == data.getId());
- data.setPolicyName("Test");
- assertTrue("Test".equals(data.getPolicyName()));
- data.setVersionExtension("Test");
- assertTrue("Test".equals(data.getVersionExtension()));
- data.setPolicyScore("Test");
- assertTrue("Test".equals(data.getPolicyScore()));
- }
-
- @Test
- public void testPolicyEditorScopes(){
- PolicyEditorScopes data = new PolicyEditorScopes();
- data.prePersist();
- data.preUpdate();
- data.setId(1);
- assertTrue(1 == data.getId());
- data.setScopeName("Test");
- assertTrue("Test".equals(data.getScopeName()));
- data.setCreatedDate(new Date());
- assertTrue(data.getCreatedDate()!=null);
- data.setModifiedDate(new Date());
- assertTrue(data.getModifiedDate()!=null);
- data.setUserCreatedBy(userInfo);
- assertTrue(data.getUserCreatedBy()!=null);
- data.setUserModifiedBy(userInfo);
- assertTrue(data.getUserModifiedBy()!=null);
- }
-
- @Test
- public void testDescriptiveScope(){
- DescriptiveScope data = new DescriptiveScope();
- data.prePersist();
- data.preUpdate();
- data.setId(1);
- assertTrue(1 == data.getId());
- data.setScopeName("Test");
- assertTrue("Test".equals(data.getScopeName()));
- data.setSearch("Test");
- assertTrue("Test".equals(data.getSearch()));
- data.setCreatedDate(new Date());
- assertTrue(data.getCreatedDate()!=null);
- data.setModifiedDate(new Date());
- assertTrue(data.getModifiedDate()!=null);
- data.setUserCreatedBy(userInfo);
- assertTrue(data.getUserCreatedBy()!=null);
- data.setUserModifiedBy(userInfo);
- assertTrue(data.getUserModifiedBy()!=null);
- }
-
- @Test
- public void testGlobalRoleSettings(){
- GlobalRoleSettings data = new GlobalRoleSettings();
- new GlobalRoleSettings(true);
- data.setRole("Test");
- assertTrue("Test".equals(data.getRole()));
- data.setLockdown(true);
- assertTrue(data.isLockdown());
- }
-}
diff --git a/ONAP-REST/src/test/java/org/onap/policy/rest/jpa/PolicyUtilsJpaTest.java b/ONAP-REST/src/test/java/org/onap/policy/rest/jpa/PolicyUtilsJpaTest.java
new file mode 100644
index 000000000..f56e55783
--- /dev/null
+++ b/ONAP-REST/src/test/java/org/onap/policy/rest/jpa/PolicyUtilsJpaTest.java
@@ -0,0 +1,320 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP-REST
+ * ================================================================================
+ * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2019 Nordix Foundation.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertTrue;
+
+import java.util.Date;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.onap.policy.common.logging.flexlogger.FlexLogger;
+import org.onap.policy.common.logging.flexlogger.Logger;
+
+/**
+ * The Class PolicyUtilsJpaTest.
+ */
+public class PolicyUtilsJpaTest {
+
+ private static Logger logger = FlexLogger.getLogger(PolicyUtilsJpaTest.class);
+ private UserInfo userInfo;
+
+ /**
+ * Sets the up.
+ *
+ * @throws Exception the exception
+ */
+ @Before
+ public void setUp() throws Exception {
+ logger.info("setUp: Entering");
+ userInfo = new UserInfo();
+ userInfo.setUserLoginId("Test");
+ userInfo.setUserName("Test");
+ logger.info("setUp: exit");
+ }
+
+ /**
+ * Test watch policy notification table.
+ */
+ @Test
+ public void testWatchPolicyNotificationTable() {
+ WatchPolicyNotificationTable data = new WatchPolicyNotificationTable();
+ data.setId(1);
+ assertTrue(1 == data.getId());
+ data.setPolicyName("Test");
+ assertTrue("Test".equals(data.getPolicyName()));
+ data.setLoginIds("Test");
+ assertTrue("Test".equals(data.getLoginIds()));
+ data.equals(data);
+ data.hashCode();
+ }
+
+ /**
+ * Test policy roles.
+ */
+ @Test
+ public void testPolicyRoles() {
+ PolicyRoles data = new PolicyRoles();
+ data.setId(1);
+ assertTrue(1 == data.getId());
+ data.setScope("Test");
+ assertTrue("Test".equals(data.getScope()));
+ data.setRole("Test");
+ assertTrue("Test".equals(data.getRole()));
+ data.setLoginId(userInfo);
+ assertTrue("Test".equals(data.getLoginId().getUserLoginId()));
+ }
+
+ /**
+ * Test policy version.
+ */
+ @Test
+ public void testPolicyVersion() {
+ PolicyVersion data = new PolicyVersion();
+ new PolicyVersion("Test", "Test");
+ data.prePersist();
+ data.preUpdate();
+ data.setId(1);
+ assertTrue(1 == data.getId());
+ data.setActiveVersion(1);
+ assertTrue(1 == data.getActiveVersion());
+ data.setHigherVersion(1);
+ assertTrue(1 == data.getHigherVersion());
+ data.setPolicyName("Test");
+ assertTrue("Test".equals(data.getPolicyName()));
+ data.setCreatedBy("Test");
+ assertTrue("Test".equals(data.getCreatedBy()));
+ data.setModifiedBy("Test");
+ assertTrue("Test".equals(data.getModifiedBy()));
+ data.setCreatedDate(new Date());
+ assertTrue(data.getCreatedDate() != null);
+ data.setModifiedDate(new Date());
+ assertTrue(data.getModifiedDate() != null);
+
+ assertNotNull(data.hashCode());
+
+ PolicyVersion version0 = new PolicyVersion();
+ PolicyVersion version1 = new PolicyVersion();
+ assertEquals(version0, version0);
+ assertEquals(version0, version1);
+ assertNotEquals(version0, null);
+ String helloString = "Hello";
+ Object helloObject = helloString;
+ assertNotEquals(version0, helloObject);
+
+ version0.setId(1);
+ assertNotEquals(version0, version1);
+ version1.setId(1);
+ assertEquals(version0, version1);
+ version0.setActiveVersion(1);
+ assertNotEquals(version0, version1);
+ version1.setActiveVersion(1);
+ assertEquals(version0, version1);
+ version0.setCreatedBy("Dorothy");
+ assertNotEquals(version0, version1);
+ version1.setCreatedBy("Dorothy");
+ assertEquals(version0, version1);
+ version1.setCreatedBy(null);
+ assertNotEquals(version0, version1);
+ version0.setCreatedBy(null);
+ assertEquals(version0, version1);
+ version1.setCreatedBy("Dorothy");
+ assertNotEquals(version0, version1);
+ version0.setCreatedBy("Dorothy");
+ assertEquals(version0, version1);
+ version0.setCreatedDate(new Date(12345L));
+ assertNotEquals(version0, version1);
+ version1.setCreatedDate(new Date(12345L));
+ assertEquals(version0, version1);
+ version1.setCreatedDate(null);
+ assertNotEquals(version0, version1);
+ version0.setCreatedDate(null);
+ assertEquals(version0, version1);
+ version1.setCreatedDate(new Date(12345L));
+ assertNotEquals(version0, version1);
+ version0.setCreatedDate(new Date(12345L));
+ assertEquals(version0, version1);
+ version0.setHigherVersion(1);
+ assertNotEquals(version0, version1);
+ version1.setHigherVersion(1);
+ assertEquals(version0, version1);
+ version0.setModifiedBy("Dorothy");
+ assertNotEquals(version0, version1);
+ version1.setModifiedBy("Dorothy");
+ assertEquals(version0, version1);
+ version1.setModifiedBy(null);
+ assertNotEquals(version0, version1);
+ version0.setModifiedBy(null);
+ assertEquals(version0, version1);
+ version1.setModifiedBy("Dorothy");
+ assertNotEquals(version0, version1);
+ version0.setModifiedBy("Dorothy");
+ assertEquals(version0, version1);
+ version0.setModifiedDate(new Date(12345L));
+ assertNotEquals(version0, version1);
+ version1.setModifiedDate(new Date(12345L));
+ assertEquals(version0, version1);
+ version1.setModifiedDate(null);
+ assertNotEquals(version0, version1);
+ version0.setModifiedDate(null);
+ assertEquals(version0, version1);
+ version1.setModifiedDate(new Date(12345L));
+ assertNotEquals(version0, version1);
+ version0.setModifiedDate(new Date(12345L));
+ assertEquals(version0, version1);
+ version0.setPolicyName("GoToOz");
+ assertNotEquals(version0, version1);
+ version1.setPolicyName("GoToOz");
+ assertEquals(version0, version1);
+ version1.setPolicyName(null);
+ assertNotEquals(version0, version1);
+ version0.setPolicyName(null);
+ assertEquals(version0, version1);
+ version1.setPolicyName("GoToOz");
+ assertNotEquals(version0, version1);
+ version0.setPolicyName("GoToOz");
+ assertEquals(version0, version1);
+
+ assertNotNull(version0.hashCode());
+ assertNotNull(version1.hashCode());
+ assertEquals(version0.hashCode(), version0.hashCode());
+
+ version0.setPolicyName("GoToOy");
+ assertNotEquals(version0, version1);
+ assertNotEquals(version0.hashCode(), version1.hashCode());
+ }
+
+ /**
+ * Test system log DB.
+ */
+ @Test
+ public void testSystemLogDb() {
+ SystemLogDb data = new SystemLogDb();
+ new SystemLogDb(1, "", "", "", "", "");
+ data.setId(1);
+ assertTrue(1 == data.getId());
+ data.setDescription("Test");
+ assertTrue("Test".equals(data.getDescription()));
+ data.setType("Test");
+ assertTrue("Test".equals(data.getType()));
+ data.setSystem("Test");
+ assertTrue("Test".equals(data.getSystem()));
+ data.setRemote("Test");
+ assertTrue("Test".equals(data.getRemote()));
+ data.setLogtype("Test");
+ assertTrue("Test".equals(data.getLogtype()));
+ data.setDate(new Date());
+ assertTrue(data.getDate() != null);
+ }
+
+ /**
+ * Test remote catalog values.
+ */
+ @Test
+ public void testRemoteCatalogValues() {
+ RemoteCatalogValues data = new RemoteCatalogValues();
+ data.setId(1);
+ assertTrue(1 == data.getId());
+ data.setName("Test");
+ assertTrue("Test".equals(data.getName()));
+ data.setValue("Test");
+ assertTrue("Test".equals(data.getValue()));
+ }
+
+ /**
+ * Test policy score.
+ */
+ @Test
+ public void testPolicyScore() {
+ PolicyScore data = new PolicyScore();
+ data.setId(1);
+ assertTrue(1 == data.getId());
+ data.setPolicyName("Test");
+ assertTrue("Test".equals(data.getPolicyName()));
+ data.setVersionExtension("Test");
+ assertTrue("Test".equals(data.getVersionExtension()));
+ data.setScore("Test");
+ assertTrue("Test".equals(data.getScore()));
+ }
+
+ /**
+ * Test policy editor scopes.
+ */
+ @Test
+ public void testPolicyEditorScopes() {
+ PolicyEditorScopes data = new PolicyEditorScopes();
+ data.prePersist();
+ data.preUpdate();
+ data.setId(1);
+ assertTrue(1 == data.getId());
+ data.setScopeName("Test");
+ assertTrue("Test".equals(data.getScopeName()));
+ data.setCreatedDate(new Date());
+ assertTrue(data.getCreatedDate() != null);
+ data.setModifiedDate(new Date());
+ assertTrue(data.getModifiedDate() != null);
+ data.setUserCreatedBy(userInfo);
+ assertTrue(data.getUserCreatedBy() != null);
+ data.setUserModifiedBy(userInfo);
+ assertTrue(data.getUserModifiedBy() != null);
+ }
+
+ /**
+ * Test descriptive scope.
+ */
+ @Test
+ public void testDescriptiveScope() {
+ DescriptiveScope data = new DescriptiveScope();
+ data.prePersist();
+ data.preUpdate();
+ data.setId(1);
+ assertTrue(1 == data.getId());
+ data.setScopeName("Test");
+ assertTrue("Test".equals(data.getScopeName()));
+ data.setSearch("Test");
+ assertTrue("Test".equals(data.getSearch()));
+ data.setCreatedDate(new Date());
+ assertTrue(data.getCreatedDate() != null);
+ data.setModifiedDate(new Date());
+ assertTrue(data.getModifiedDate() != null);
+ data.setUserCreatedBy(userInfo);
+ assertTrue(data.getUserCreatedBy() != null);
+ data.setUserModifiedBy(userInfo);
+ assertTrue(data.getUserModifiedBy() != null);
+ }
+
+ /**
+ * Test global role settings.
+ */
+ @Test
+ public void testGlobalRoleSettings() {
+ GlobalRoleSettings data = new GlobalRoleSettings();
+ new GlobalRoleSettings(true);
+ data.setRole("Test");
+ assertTrue("Test".equals(data.getRole()));
+ data.setLockdown(true);
+ assertTrue(data.isLockdown());
+ }
+}
diff --git a/ONAP-REST/src/test/java/org/onap/policy/rest/util/DummyPolicyContainer.java b/ONAP-REST/src/test/java/org/onap/policy/rest/util/DummyPolicyContainer.java
new file mode 100644
index 000000000..385576744
--- /dev/null
+++ b/ONAP-REST/src/test/java/org/onap/policy/rest/util/DummyPolicyContainer.java
@@ -0,0 +1,77 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * Copyright (C) 2019 Nordix Foundation.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ * SPDX-License-Identifier: Apache-2.0
+ * ============LICENSE_END=========================================================
+ */
+
+package org.onap.policy.rest.util;
+
+import java.util.Collection;
+
+public class DummyPolicyContainer implements PolicyContainer {
+ private static final long serialVersionUID = 1L;
+
+ @Override
+ public Collection<?> getContainerPropertyIds() {
+ return null;
+ }
+
+ @Override
+ public Collection<?> getItemIds() {
+ return null;
+ }
+
+ @Override
+ public Class<?> getType(Object propertyId) {
+ return null;
+ }
+
+ @Override
+ public int size() {
+ return 0;
+ }
+
+ @Override
+ public boolean containsId(Object itemId) {
+ return false;
+ }
+
+ @Override
+ public Object addItem() {
+ return null;
+ }
+
+ @Override
+ public boolean removeItem(Object itemId) {
+ return false;
+ }
+
+ @Override
+ public boolean addContainerProperty(Object propertyId, Class<?> type, Object defaultValue) {
+ return false;
+ }
+
+ @Override
+ public boolean removeContainerProperty(Object propertyId) {
+ return false;
+ }
+
+ @Override
+ public boolean removeAllItems() {
+ return false;
+ }
+}
diff --git a/ONAP-REST/src/test/java/org/onap/policy/rest/util/MSAttributeObjectTest.java b/ONAP-REST/src/test/java/org/onap/policy/rest/util/MsAttributeObjectTest.java
index a39eb4996..8ec47fb0b 100644
--- a/ONAP-REST/src/test/java/org/onap/policy/rest/util/MSAttributeObjectTest.java
+++ b/ONAP-REST/src/test/java/org/onap/policy/rest/util/MsAttributeObjectTest.java
@@ -3,6 +3,7 @@
* ONAP-REST
* ================================================================================
* Copyright (C) 2018-2019 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2019 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -21,14 +22,16 @@
package org.onap.policy.rest.util;
import static org.junit.Assert.assertTrue;
+
import java.util.HashMap;
+
import org.junit.Test;
-public class MSAttributeObjectTest {
+public class MsAttributeObjectTest {
@Test
- public void testMSAttributeObject() {
- MSAttributeObject data = new MSAttributeObject();
+ public void testMsAttributeObject() {
+ MsAttributeObject data = new MsAttributeObject();
data.setClassName("Test");
assertTrue("Test".equals(data.getClassName()));
data.setRefAttribute(new HashMap<>());
@@ -60,8 +63,8 @@ public class MSAttributeObjectTest {
}
@Test
- public void testMSAttributeValue() {
- MSAttributeValue data = new MSAttributeValue();
+ public void testMsAttributeValue() {
+ MsAttributeValue data = new MsAttributeValue();
data.setName("Test");
assertTrue("Test".equals(data.getName()));
data.setType("Test");
diff --git a/ONAP-REST/src/test/java/org/onap/policy/rest/util/MSModelUtilsTest.java b/ONAP-REST/src/test/java/org/onap/policy/rest/util/MsModelUtilsTest.java
index 34d555062..6d12d57a3 100644
--- a/ONAP-REST/src/test/java/org/onap/policy/rest/util/MSModelUtilsTest.java
+++ b/ONAP-REST/src/test/java/org/onap/policy/rest/util/MsModelUtilsTest.java
@@ -3,6 +3,7 @@
* ONAP-REST
* ================================================================================
* Copyright (C) 2018-2019 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2019 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -25,6 +26,7 @@ import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
+
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
@@ -32,19 +34,25 @@ import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
-import org.apache.commons.lang.StringUtils;
+
+import org.apache.commons.lang3.StringUtils;
import org.junit.Before;
import org.junit.Test;
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.DictionaryData;
-import org.onap.policy.rest.util.MSModelUtils.MODEL_TYPE;
+import org.onap.policy.rest.util.MsModelUtils.ModelType;
-public class MSModelUtilsTest {
- private static Logger logger = FlexLogger.getLogger(MSModelUtilsTest.class);
+public class MsModelUtilsTest {
+ private static Logger logger = FlexLogger.getLogger(MsModelUtilsTest.class);
private static CommonClassDao commonClassDao;
+ /**
+ * Set tests up.
+ *
+ * @throws Exception on setup failures
+ */
@Before
public void setUp() throws Exception {
List<Object> dictionaryData = new ArrayList<Object>();
@@ -55,28 +63,28 @@ public class MSModelUtilsTest {
logger.info("setUp: Entering");
commonClassDao = mock(CommonClassDao.class);
when(commonClassDao.getDataById(DictionaryData.class, "dictionaryName", "GocVNFType"))
- .thenReturn(dictionaryData);
+ .thenReturn(dictionaryData);
}
@Test
- public void testMSModelUtils() {
- HashMap<String, MSAttributeObject> classMap = new HashMap<>();
+ public void testMsModelUtils() {
+ HashMap<String, MsAttributeObject> classMap = new HashMap<>();
ClassLoader classLoader = getClass().getClassLoader();
File file = new File(classLoader.getResource("DKaTVESPolicy-v1802.xmi").getFile());
- MSModelUtils utils = new MSModelUtils("http://org.onap", "http://org.onap.policy");
- Map<String, MSAttributeObject> tempMap =
- utils.processEpackage(file.getAbsolutePath().toString(), MODEL_TYPE.XMI);
+ MsModelUtils utils = new MsModelUtils("http://org.onap", "http://org.onap.policy");
+ Map<String, MsAttributeObject> tempMap = utils.processEpackage(file.getAbsolutePath().toString(),
+ ModelType.XMI);
classMap.putAll(tempMap);
- MSAttributeObject mainClass = classMap.get("StandardDeviationThreshold");
- String dependTemp = StringUtils.replaceEach(mainClass.getDependency(), new String[] {"[", "]", " "},
- new String[] {"", "", ""});
+ MsAttributeObject mainClass = classMap.get("StandardDeviationThreshold");
+ String dependTemp = StringUtils.replaceEach(mainClass.getDependency(), new String[]
+ { "[", "]", " " }, new String[]
+ { "", "", "" });
List<String> dependency = new ArrayList<String>(Arrays.asList(dependTemp.split(",")));
dependency = utils.getFullDependencyList(dependency, classMap);
String subAttribute = utils.createSubAttributes(dependency, classMap, "StandardDeviationThreshold");
assertTrue(subAttribute != null);
}
-
/**
* Run the void stringBetweenDots(String, String) method test.
*/
@@ -85,25 +93,24 @@ public class MSModelUtilsTest {
public void testStringBetweenDots() {
// expect: uniqueKeys should contain a string value
- MSModelUtils controllerA = new MSModelUtils();
+ MsModelUtils controllerA = new MsModelUtils();
String str = "testing\\.byCorrectWay\\.OfDATA";
assertEquals(1, controllerA.stringBetweenDots(str));
// expect: uniqueKeys should not contain a string value
str = "testing\byWrongtWay.\\OfDATA";
- MSModelUtils controllerB = new MSModelUtils();
+ MsModelUtils controllerB = new MsModelUtils();
assertEquals(0, controllerB.stringBetweenDots(str));
}
/**
- * Run the Map<String,String> load(String) method test.
+ * Run the load method test.
*/
-
@Test
public void testLoad() {
boolean isLocalTesting = true;
- MSModelUtils controller = new MSModelUtils();
+ MsModelUtils controller = new MsModelUtils();
String fileName = null;
Map<String, String> result = null;
try {
@@ -146,7 +153,7 @@ public class MSModelUtilsTest {
logger.error("Exception Occured while loading file" + e1);
}
- MSModelUtils controller = new MSModelUtils(commonClassDao);
+ MsModelUtils controller = new MsModelUtils(commonClassDao);
if (isLocalTesting) {
try {
controller.parseTosca(fileName);
diff --git a/ONAP-REST/src/test/java/org/onap/policy/rest/util/PDPPolicyContainerTest.java b/ONAP-REST/src/test/java/org/onap/policy/rest/util/PDPPolicyContainerTest.java
deleted file mode 100644
index 9302df3b5..000000000
--- a/ONAP-REST/src/test/java/org/onap/policy/rest/util/PDPPolicyContainerTest.java
+++ /dev/null
@@ -1,138 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * ONAP Policy Engine
- * ================================================================================
- * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertTrue;
-import java.util.HashSet;
-import java.util.Set;
-import org.junit.Before;
-import org.junit.Test;
-import org.onap.policy.rest.util.PDPPolicyContainer.PDPPolicyItem;
-import org.onap.policy.xacml.std.pap.StdPDP;
-import org.onap.policy.xacml.std.pap.StdPDPGroup;
-import org.onap.policy.xacml.std.pap.StdPDPPolicy;
-import com.att.research.xacml.api.pap.PDP;
-import com.att.research.xacml.api.pap.PDPPolicy;
-
-public class PDPPolicyContainerTest {
- StdPDPGroup group;
- PDPPolicyContainer container;
- StdPDPPolicy policy;
-
- @Before
- public void setUp() {
- group = new StdPDPGroup();
- group.setDefault(true);
- group.setDefaultGroup(true);
- group.setDescription("Test");
- group.setId("Test");
- group.setName("Test");
- group.setOnapPdps(new HashSet<>());
- group.setOperation("Test");
- group.setPipConfigs(new HashSet<>());
- HashSet<PDPPolicy> policies = new HashSet<>();
- policy = new StdPDPPolicy();
- policy.setName("Config_test.1.xml");
- policy.setId("Config_test");
- policy.setVersion("1.0");
- policy.setDescription("testDescription");
- policies.add(policy);
- group.setPolicies(policies);
- group.setSelectedPolicies(new HashSet<>());
- container = new PDPPolicyContainer(group);
- }
-
- @Test
- public void testPDPPolicyContainer() {
- container.nextItemId(policy);
- container.prevItemId(policy);
- container.firstItemId();
- container.lastItemId();
- container.isFirstId(policy);
- container.isLastId(policy);
- container.addItemAfter(policy);
- container.getContainerPropertyIds();
- container.getItemIds();
- container.getType("Id");
- assertTrue(String.class.equals(String.class));
- container.getType("Name");
- assertTrue(String.class.equals(String.class));
- container.getType("Version");
- assertTrue(String.class.equals(String.class));
- container.getType("Description");
- assertTrue(String.class.equals(String.class));
- container.getType("Root");
- assertTrue(Boolean.class.equals(Boolean.class));
- assertTrue(container.size() == 1);
- container.containsId(policy);
- container.removeItem(policy);
- container.addContainerProperty(null, null, null);
- container.removeContainerProperty(policy);
- container.removeAllItems();
- container.addItemAt(0);
- }
-
- @Test(expected = NullPointerException.class)
- public void testConstructor() {
- // Test PDP based constructor
- PDP pdp = new StdPDP();
- PDPPolicyContainer container1 = new PDPPolicyContainer(pdp);
- assertNotNull(container1);
-
- // Test set based constructor
- Set<PDPPolicy> set = new HashSet<PDPPolicy>();
- PDPPolicyContainer container2 = new PDPPolicyContainer(set);
- assertNotNull(container2);
-
- // Test object based constructor
- PDPPolicyContainer container3 = new PDPPolicyContainer("testObject");
- assertNotNull(container3);
- }
-
- @Test(expected = UnsupportedOperationException.class)
- public void testAddItem() {
- container.addItem();
- }
-
- @Test
- public void testGetters() {
- assertNull(container.nextItemId("testItem"));
- assertNull(container.prevItemId("testItem"));
- assertNotNull(container.firstItemId());
- assertNotNull(container.lastItemId());
- assertEquals(container.indexOfId("testItem"), -1);
- assertNotNull(container.getIdByIndex(0));
- assertNotNull(container.getItemIds(0, 1));
- }
-
- @Test
- public void testPDPPolicyItem() {
- PDPPolicyItem item = container.new PDPPolicyItem(policy);
- assertEquals("Config_test", item.getId());
- assertEquals("Config_test.1.xml", item.getName());
- assertEquals("1.0", item.getVersion());
- assertEquals("testDescription", item.getDescription());
- item.setRoot(true);
- assertEquals(true, item.getRoot());
- }
-}
diff --git a/ONAP-REST/src/test/java/org/onap/policy/rest/util/ParserExceptionTest.java b/ONAP-REST/src/test/java/org/onap/policy/rest/util/ParserExceptionTest.java
new file mode 100644
index 000000000..92b56a146
--- /dev/null
+++ b/ONAP-REST/src/test/java/org/onap/policy/rest/util/ParserExceptionTest.java
@@ -0,0 +1,34 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * Copyright (C) 2019 Nordix Foundation.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ * SPDX-License-Identifier: Apache-2.0
+ * ============LICENSE_END=========================================================
+ */
+
+package org.onap.policy.rest.util;
+
+import static org.junit.Assert.assertEquals;
+
+import org.junit.Test;
+
+public class ParserExceptionTest {
+
+ @Test
+ public void test() {
+ ParserException pe = new ParserException("A Message");
+ assertEquals("A Message", pe.getMessage());
+ }
+}
diff --git a/ONAP-REST/src/test/java/org/onap/policy/rest/util/PdpPolicyContainerTest.java b/ONAP-REST/src/test/java/org/onap/policy/rest/util/PdpPolicyContainerTest.java
new file mode 100644
index 000000000..32d9e5255
--- /dev/null
+++ b/ONAP-REST/src/test/java/org/onap/policy/rest/util/PdpPolicyContainerTest.java
@@ -0,0 +1,267 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP Policy Engine
+ * ================================================================================
+ * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2019 Nordix Foundation.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 static org.assertj.core.api.Assertions.assertThatThrownBy;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertTrue;
+
+import com.att.eelf.configuration.EELFLogger;
+import com.att.eelf.configuration.EELFLogger.Level;
+import com.att.eelf.configuration.EELFManager;
+import com.att.research.xacml.api.pap.PDP;
+import com.att.research.xacml.api.pap.PDPPolicy;
+import com.fasterxml.jackson.databind.ObjectMapper;
+
+import java.io.IOException;
+import java.util.HashSet;
+import java.util.Set;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.onap.policy.common.logging.eelf.PolicyLogger;
+import org.onap.policy.rest.util.PdpPolicyContainer.PdpPolicyItem;
+import org.onap.policy.xacml.std.pap.StdPDP;
+import org.onap.policy.xacml.std.pap.StdPDPGroup;
+import org.onap.policy.xacml.std.pap.StdPDPPolicy;
+
+public class PdpPolicyContainerTest {
+ StdPDPGroup group;
+ PdpPolicyContainer container;
+ StdPDPPolicy policy;
+
+ /**
+ * Set test up.
+ */
+ @Before
+ public void setUp() {
+ group = new StdPDPGroup();
+ group.setDefault(true);
+ group.setDefaultGroup(true);
+ group.setDescription("Test");
+ group.setId("Test");
+ group.setName("Test");
+ group.setOnapPdps(new HashSet<>());
+ group.setOperation("Test");
+ group.setPipConfigs(new HashSet<>());
+ policy = new StdPDPPolicy();
+ policy.setName("Config_test.1.xml");
+ policy.setId("Config_test");
+ policy.setVersion("1.0");
+ policy.setDescription("testDescription");
+
+ HashSet<PDPPolicy> policies = new HashSet<>();
+ policies.add(policy);
+ group.setPolicies(policies);
+ group.setSelectedPolicies(new HashSet<>());
+ container = new PdpPolicyContainer(group);
+ }
+
+ @Test
+ public void testPdpPolicyContainer() {
+ container.nextItemId(policy);
+ container.prevItemId(policy);
+ container.firstItemId();
+ container.lastItemId();
+ container.isFirstId(policy);
+ container.isLastId(policy);
+ container.addItemAfter(policy);
+ container.getContainerPropertyIds();
+ container.getItemIds();
+ container.getType("Id");
+ assertNull(container.getType("NonExistant"));
+ assertTrue(String.class.equals(String.class));
+ container.getType("Name");
+ assertTrue(String.class.equals(String.class));
+ container.getType("Version");
+ assertTrue(String.class.equals(String.class));
+ container.getType("Description");
+ assertTrue(String.class.equals(String.class));
+ container.getType("Root");
+ assertTrue(Boolean.class.equals(Boolean.class));
+ assertTrue(container.size() == 1);
+ container.containsId(policy);
+ container.removeItem(policy);
+ container.addContainerProperty(null, null, null);
+ container.removeContainerProperty(policy);
+ container.removeAllItems();
+
+ assertFalse(container.isFirstId(policy));
+ assertFalse(container.isLastId(policy));
+ assertNull(container.firstItemId());
+ assertNull(container.lastItemId());
+ assertNull(container.prevItemId(policy));
+
+ assertThatThrownBy(() -> container.getItemIds(0, -1)).isInstanceOf(IllegalArgumentException.class);
+
+ container.addItemAt(0);
+ }
+
+ @Test
+ public void testPdpPolicyContainerWithTrace() {
+ EELFLogger debugLogger = EELFManager.getInstance().getDebugLogger();
+
+ final Level currentLevel = PolicyLogger.getDebugLevel();
+ debugLogger.setLevel(Level.TRACE);
+
+ testPdpPolicyContainer();
+ debugLogger.setLevel(currentLevel);
+ }
+
+ @Test(expected = NullPointerException.class)
+ public void testConstructor() {
+ // Test PDP based constructor
+ PDP pdp = new StdPDP();
+ PdpPolicyContainer container1 = new PdpPolicyContainer(pdp);
+ assertNotNull(container1);
+
+ // Test set based constructor
+ Set<PDPPolicy> set = new HashSet<PDPPolicy>();
+ PdpPolicyContainer container2 = new PdpPolicyContainer(set);
+ assertNotNull(container2);
+
+ // Test object based constructor
+ PdpPolicyContainer container3 = new PdpPolicyContainer("testObject");
+ assertNotNull(container3);
+ }
+
+ @Test(expected = UnsupportedOperationException.class)
+ public void testAddItem() {
+ container.addItem();
+ }
+
+ @Test
+ public void testGettersWithTrace() {
+ EELFLogger debugLogger = EELFManager.getInstance().getDebugLogger();
+
+ final Level currentLevel = PolicyLogger.getDebugLevel();
+ debugLogger.setLevel(Level.TRACE);
+
+ testGetters();
+ debugLogger.setLevel(currentLevel);
+ }
+
+ @Test
+ public void testGetters() {
+ assertNull(container.nextItemId("testItem"));
+ assertNull(container.prevItemId("testItem"));
+ assertNotNull(container.firstItemId());
+ assertNotNull(container.lastItemId());
+ assertEquals(container.indexOfId("testItem"), -1);
+ assertNotNull(container.getIdByIndex(0));
+ assertNotNull(container.getItemIds(0, 1));
+ }
+
+ @Test
+ public void testPdpPolicyItemWithTrace() {
+ EELFLogger debugLogger = EELFManager.getInstance().getDebugLogger();
+
+ final Level currentLevel = PolicyLogger.getDebugLevel();
+ debugLogger.setLevel(Level.TRACE);
+
+ testPdpPolicyItem();
+ debugLogger.setLevel(currentLevel);
+ }
+
+ @Test
+ public void testPdpPolicyItem() {
+ PdpPolicyItem item = container.new PdpPolicyItem(policy);
+ assertEquals("Config_test", item.getId());
+ assertEquals("Config_test.1.xml", item.getName());
+ assertEquals("1.0", item.getVersion());
+ assertEquals("testDescription", item.getDescription());
+ item.setRoot(true);
+ assertEquals(true, item.getRoot());
+ }
+
+ @Test
+ public void testContainerListOfPolicies() {
+ StdPDPGroup testGroup = new StdPDPGroup();
+ testGroup.setDefault(true);
+ testGroup.setDefaultGroup(true);
+ testGroup.setDescription("Test");
+ testGroup.setId("Test");
+ testGroup.setName("Test");
+ testGroup.setOnapPdps(new HashSet<>());
+ testGroup.setOperation("Test");
+ testGroup.setPipConfigs(new HashSet<>());
+
+ StdPDPPolicy testPolicy0 = new StdPDPPolicy();
+ testPolicy0.setName("Config_test.0.xml");
+ testPolicy0.setId("Config_test0");
+ testPolicy0.setVersion("1.0");
+ testPolicy0.setDescription("testDescription0");
+
+ StdPDPPolicy testPolicy1 = new StdPDPPolicy();
+ testPolicy1.setName("Config_test.1.xml");
+ testPolicy1.setId("Config_test1");
+ testPolicy1.setVersion("1.0");
+ testPolicy1.setDescription("testDescription1");
+
+ HashSet<PDPPolicy> policies = new HashSet<>();
+ policies.add(testPolicy0);
+ policies.add(testPolicy1);
+
+ testGroup.setPolicies(policies);
+ testGroup.setSelectedPolicies(new HashSet<>());
+ PdpPolicyContainer testContainer = new PdpPolicyContainer(testGroup);
+
+ assertEquals("Config_test0", ((PdpPolicyItem) testContainer.nextItemId(testPolicy1)).getId());
+ assertEquals("Config_test1", ((PdpPolicyItem) testContainer.prevItemId(testPolicy0)).getId());
+
+ ObjectMapper mapper = new ObjectMapper();
+ try {
+ mapper.writeValue(System.err, testPolicy0);
+ } catch (IOException e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ }
+
+ // @formatter:off
+ assertTrue(testContainer.removeItem("{"
+ + "\"PDPPolicyType\":\"StdPDPPolicy\","
+ + "\"id\":\"Config_test0\","
+ + "\"name\":\"Config_test.0.xml\","
+ + "\"policyId\":null,"
+ + "\"description\":\"testDescription0\","
+ + "\"version\":\"1.0\","
+ + "\"location\":null,"
+ + "\"valid\":false,"
+ + "\"root\":false"
+ + "}"));
+ assertFalse(testContainer.removeItem("{"
+ + "\"PDPPolicyType\":\"StdPDPPolicy\","
+ + "\"id\":\"Config_test99\","
+ + "\"name\":\"Config_test.0.xml\","
+ + "\"policyId\":null,"
+ + "\"description\":\"testDescription0\","
+ + "\"version\":\"1.0\","
+ + "\"location\":null,"
+ + "\"valid\":false,"
+ + "\"root\":false"
+ + "}"));
+ // @formatter:on
+ }
+}
diff --git a/ONAP-REST/src/test/java/org/onap/policy/rest/util/PolicyItemSetChangeNotifierTest.java b/ONAP-REST/src/test/java/org/onap/policy/rest/util/PolicyItemSetChangeNotifierTest.java
index 9e5ff5d9f..5e42ec6f6 100644
--- a/ONAP-REST/src/test/java/org/onap/policy/rest/util/PolicyItemSetChangeNotifierTest.java
+++ b/ONAP-REST/src/test/java/org/onap/policy/rest/util/PolicyItemSetChangeNotifierTest.java
@@ -3,13 +3,14 @@
* ONAP Policy Engine
* ================================================================================
* Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2019 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -20,31 +21,57 @@
package org.onap.policy.rest.util;
+import static org.assertj.core.api.Assertions.assertThatCode;
+import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.fail;
+
import org.junit.Test;
import org.mockito.Mockito;
import org.onap.policy.rest.util.PolicyContainer.ItemSetChangeEvent;
import org.onap.policy.rest.util.PolicyContainer.ItemSetChangeListener;
public class PolicyItemSetChangeNotifierTest {
- @Test
- public void testNotifier() {
- // Setup test data
- ItemSetChangeListener listener = Mockito.mock(ItemSetChangeListener.class);
- ItemSetChangeEvent event = Mockito.mock(ItemSetChangeEvent.class);
-
- // Test constructor
- PolicyItemSetChangeNotifier notifier = new PolicyItemSetChangeNotifier();
- assertNotNull(notifier);
-
- // Test listener methods
- try {
- notifier.addItemSetChangeListener(listener);
- notifier.fireItemSetChange(event);
- notifier.removeItemSetChangeListener(listener);
- } catch (Exception ex) {
- fail("Not expecting any exceptions: " + ex);
+ @Test
+ public void testNotifier() {
+
+ // Test constructor
+ PolicyItemSetChangeNotifier notifier = new PolicyItemSetChangeNotifier();
+ assertNotNull(notifier);
+
+ assertEquals(null, notifier.getItemSetChangeListeners());
+
+ ItemSetChangeListener listener1 = Mockito.mock(ItemSetChangeListener.class);
+ notifier.addItemSetChangeListener(listener1);
+ assertEquals(1, notifier.getItemSetChangeListeners().size());
+ ItemSetChangeListener listener2 = Mockito.mock(ItemSetChangeListener.class);
+ notifier.addItemSetChangeListener(listener2);
+ assertEquals(2, notifier.getItemSetChangeListeners().size());
+
+ notifier.removeItemSetChangeListener(listener1);
+ assertEquals(1, notifier.getItemSetChangeListeners().size());
+ notifier.addItemSetChangeListener(listener1);
+ assertEquals(2, notifier.getItemSetChangeListeners().size());
+
+ ItemSetChangeEvent event = Mockito.mock(ItemSetChangeEvent.class);
+ notifier.fireItemSetChange(event);
+
+ notifier.removeItemSetChangeListener(listener1);
+ assertEquals(1, notifier.getItemSetChangeListeners().size());
+ notifier.removeItemSetChangeListener(listener2);
+ assertEquals(0, notifier.getItemSetChangeListeners().size());
+ notifier.removeItemSetChangeListener(listener2);
+ assertEquals(0, notifier.getItemSetChangeListeners().size());
+
+ notifier.setItemSetChangeListeners(null);
+ notifier.removeItemSetChangeListener(listener2);
+ assertEquals(null, notifier.getItemSetChangeListeners());
+
+ assertThatCode(() -> notifier.fireItemSetChange(event)).doesNotThrowAnyException();
+
+ notifier.setContainer(new DummyPolicyContainer());
+ assertThatCode(() -> notifier.fireItemSetChange()).doesNotThrowAnyException();
+
+ PolicyContainer dummySource = new DummyPolicyContainer();
+ assertEquals(dummySource, new PolicyItemSetChangeNotifier.BaseItemSetChangeEvent(dummySource).getContainer());
}
- }
}
diff --git a/ONAP-REST/src/test/java/org/onap/policy/rest/util/PolicyValidationRequestWrapperTest.java b/ONAP-REST/src/test/java/org/onap/policy/rest/util/PolicyValidationRequestWrapperTest.java
new file mode 100644
index 000000000..517058309
--- /dev/null
+++ b/ONAP-REST/src/test/java/org/onap/policy/rest/util/PolicyValidationRequestWrapperTest.java
@@ -0,0 +1,422 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * Copyright (C) 2019 Nordix Foundation.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ * SPDX-License-Identifier: Apache-2.0
+ * ============LICENSE_END=========================================================
+ */
+
+package org.onap.policy.rest.util;
+
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertTrue;
+
+import java.io.BufferedReader;
+import java.io.StringReader;
+import java.util.ArrayList;
+import java.util.Date;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+
+import javax.servlet.http.HttpServletRequest;
+
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.Mock;
+import org.mockito.Mockito;
+import org.mockito.runners.MockitoJUnitRunner;
+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;
+import org.onap.policy.api.RuleProvider;
+import org.onap.policy.common.utils.resources.TextFileUtils;
+import org.onap.policy.rest.adapter.PolicyRestAdapter;
+
+@RunWith(MockitoJUnitRunner.class)
+public class PolicyValidationRequestWrapperTest {
+
+ @Mock
+ HttpServletRequest request;
+
+ @Test
+ public void testHttpRequest() throws Exception {
+ PolicyValidationRequestWrapper wrapper = new PolicyValidationRequestWrapper();
+
+ assertNull(wrapper.populateRequestParameters((HttpServletRequest) null));
+
+ BufferedReader decisionPolicyReader = new BufferedReader(new StringReader(
+ TextFileUtils.getTextFileAsString("src/test/resources/policies/DecisionPolicy.json")));
+
+ Mockito.when(request.getReader()).thenReturn(decisionPolicyReader);
+
+ wrapper.populateRequestParameters(request);
+
+ BufferedReader policyJsonTrapFaultReader = new BufferedReader(new StringReader(
+ TextFileUtils.getTextFileAsString("src/test/resources/policies/PolicyJsonTrapFault.json")));
+
+ Mockito.when(request.getReader()).thenReturn(policyJsonTrapFaultReader);
+
+ wrapper.populateRequestParameters(request);
+
+ BufferedReader badJsonReader = new BufferedReader(new StringReader("{"));
+
+ Mockito.when(request.getReader()).thenReturn(badJsonReader);
+
+ wrapper.populateRequestParameters(request);
+ }
+
+ @Test
+ public void testDefaultParameterHandling() throws Exception {
+ PolicyParameters parameters = createParametersObject();
+
+ PolicyValidationRequestWrapper wrapper = new PolicyValidationRequestWrapper();
+
+ assertThatThrownBy(() -> wrapper.populateRequestParameters(parameters))
+ .isInstanceOf(NullPointerException.class);
+
+ parameters.setPolicyConfigType(PolicyConfigType.Firewall);
+ PolicyRestAdapter adapter = wrapper.populateRequestParameters((parameters));
+ assertEquals("Firewall Config", adapter.getConfigPolicyType());
+
+ parameters.setConfigBody("");
+ assertNull(wrapper.populateRequestParameters((parameters)));
+
+ parameters.setConfigBody("{\"name");
+ assertNull(wrapper.populateRequestParameters((parameters)));
+
+ parameters.setConfigBodyType(PolicyType.OTHER);
+ parameters.setConfigBody(null);
+ adapter = wrapper.populateRequestParameters((parameters));
+ assertEquals("Firewall Config", adapter.getConfigPolicyType());
+
+ parameters.setPolicyConfigType(PolicyConfigType.Extended);
+ adapter = wrapper.populateRequestParameters((parameters));
+ assertEquals("EXTENDED", adapter.getConfigPolicyType());
+
+ parameters.setTtlDate(null);
+ adapter = wrapper.populateRequestParameters((parameters));
+ assertEquals("NA", adapter.getTtlDate());
+ }
+
+ @Test
+ public void testConfigFirewallParameterHandling() throws Exception {
+ PolicyParameters parameters = createParametersObject();
+ parameters.setPolicyConfigType(PolicyConfigType.Firewall);
+
+ PolicyValidationRequestWrapper wrapper = new PolicyValidationRequestWrapper();
+
+ PolicyRestAdapter adapter = wrapper.populateRequestParameters((parameters));
+ assertEquals("Firewall Config", adapter.getConfigPolicyType());
+
+ parameters.setConfigBody("{\"someParameter\": \"someValue\"}");
+ adapter = wrapper.populateRequestParameters((parameters));
+ assertEquals(null, adapter.getSecurityZone());
+ assertEquals("ConfigName", adapter.getConfigName());
+
+ parameters.setConfigBody("{\"securityZoneId\": \"SecurityZone\"}");
+ adapter = wrapper.populateRequestParameters((parameters));
+ assertEquals("SecurityZone", adapter.getSecurityZone());
+
+ parameters.setConfigBody("{\"configName\": \"AnotherConfigName\"}");
+ adapter = wrapper.populateRequestParameters((parameters));
+ assertEquals("AnotherConfigName", adapter.getConfigName());
+ }
+
+ @Test
+ public void testConfigMicroserviceParameterHandling() throws Exception {
+ PolicyParameters parameters = createParametersObject();
+ parameters.setPolicyConfigType(PolicyConfigType.MicroService);
+
+ PolicyValidationRequestWrapper wrapper = new PolicyValidationRequestWrapper();
+
+ assertNull(wrapper.populateRequestParameters((parameters)));
+
+ parameters.setConfigBody("{\"someParameter\": \"someValue\"}");
+
+ PolicyRestAdapter adapter = wrapper.populateRequestParameters((parameters));
+ assertEquals("Micro Service", adapter.getConfigPolicyType());
+
+ parameters.setConfigBody("{\"service\": \"MyService\"}");
+ adapter = wrapper.populateRequestParameters((parameters));
+ assertEquals("MyService", adapter.getServiceType());
+
+ parameters.setConfigBody("{\"content\": \"{}\"}");
+ adapter = wrapper.populateRequestParameters((parameters));
+ assertEquals("\"{}\"", adapter.getPolicyJSON().toString());
+
+ parameters.setConfigBody("{\"content\": {hess:}}");
+ assertNull(wrapper.populateRequestParameters((parameters)));
+ }
+
+ @Test
+ public void testConfigOptimizationParameterHandling() throws Exception {
+ PolicyParameters parameters = createParametersObject();
+ parameters.setPolicyConfigType(PolicyConfigType.Optimization);
+
+ PolicyValidationRequestWrapper wrapper = new PolicyValidationRequestWrapper();
+
+ PolicyRestAdapter adapter = wrapper.populateRequestParameters((parameters));
+ assertEquals("Optimization", adapter.getConfigPolicyType());
+
+ parameters.setConfigBody("{\"someParameter\": \"someValue\"}");
+
+ adapter = wrapper.populateRequestParameters((parameters));
+ assertEquals("Optimization", adapter.getConfigPolicyType());
+
+ parameters.setConfigBody("{\"service\": \"MyService\"}");
+ adapter = wrapper.populateRequestParameters((parameters));
+ assertEquals("MyService", adapter.getServiceType());
+ }
+
+ @Test
+ public void testConfigClosedLoopFaultParameterHandling() throws Exception {
+ PolicyParameters parameters = createParametersObject();
+ parameters.setPolicyConfigType(PolicyConfigType.ClosedLoop_Fault);
+
+ PolicyValidationRequestWrapper wrapper = new PolicyValidationRequestWrapper();
+
+ PolicyRestAdapter adapter = wrapper.populateRequestParameters((parameters));
+ assertEquals("ClosedLoop_Fault", adapter.getConfigPolicyType());
+
+ parameters.setConfigBody("{\"someParameter\": \"someValue\"}");
+
+ adapter = wrapper.populateRequestParameters((parameters));
+ assertEquals("ClosedLoop_Fault", adapter.getConfigPolicyType());
+
+ parameters.setConfigBody("{\"onapname\": \"MyOnapName\"}");
+ adapter = wrapper.populateRequestParameters((parameters));
+ assertEquals("MyOnapName", adapter.getOnapName());
+ }
+
+ @Test
+ public void testConfigClosedLoopPmParameterHandling() throws Exception {
+ PolicyParameters parameters = createParametersObject();
+ parameters.setPolicyConfigType(PolicyConfigType.ClosedLoop_PM);
+
+ PolicyValidationRequestWrapper wrapper = new PolicyValidationRequestWrapper();
+
+ PolicyRestAdapter adapter = wrapper.populateRequestParameters((parameters));
+ assertEquals("ClosedLoop_PM", adapter.getConfigPolicyType());
+
+ parameters.setConfigBody("{\"someParameter\": \"someValue\"}");
+
+ adapter = wrapper.populateRequestParameters((parameters));
+ assertEquals("ClosedLoop_PM", adapter.getConfigPolicyType());
+
+ parameters.setConfigBody(
+ "{\"onapname\": \"MyOnapName\",\"serviceTypePolicyName\":\"Service Type Policy Name\"}");
+ adapter = wrapper.populateRequestParameters((parameters));
+ assertEquals("MyOnapName", adapter.getOnapName());
+ }
+
+ @Test
+ public void testConfigBrmsParameterHandling() throws Exception {
+ PolicyParameters parameters = createParametersObject();
+ parameters.setPolicyConfigType(PolicyConfigType.BRMS_PARAM);
+
+ PolicyValidationRequestWrapper wrapper = new PolicyValidationRequestWrapper();
+ assertThatThrownBy(() -> wrapper.populateRequestParameters(parameters))
+ .isInstanceOf(NullPointerException.class);
+
+ Map<AttributeType, Map<String, String>> attributes = new LinkedHashMap<>();
+ parameters.setAttributes(attributes);
+ assertThatThrownBy(() -> wrapper.populateRequestParameters(parameters))
+ .isInstanceOf(NullPointerException.class);
+
+ Map<String, String> templateMap = new LinkedHashMap<>();
+ templateMap.put("templateName", "Template Name");
+ attributes.put(AttributeType.RULE, templateMap);
+ PolicyRestAdapter adapter = wrapper.populateRequestParameters((parameters));
+ assertEquals("BRMS_Param", adapter.getConfigPolicyType());
+ assertEquals("Template Name", adapter.getRuleName());
+
+ parameters.setConfigBody("{\"someParameter\": \"someValue\"}");
+
+ adapter = wrapper.populateRequestParameters((parameters));
+ assertEquals("BRMS_Param", adapter.getConfigPolicyType());
+ }
+
+ @SuppressWarnings("unchecked")
+ @Test
+ public void testDecisionRainyDayParameterHandling() throws Exception {
+ PolicyParameters parameters = createParametersObject();
+ parameters.setPolicyClass(PolicyClass.Decision);
+
+ PolicyValidationRequestWrapper wrapper = new PolicyValidationRequestWrapper();
+ assertThatThrownBy(() -> wrapper.populateRequestParameters(parameters))
+ .isInstanceOf(NullPointerException.class);
+
+ Map<AttributeType, Map<String, String>> attributes = new LinkedHashMap<>();
+ parameters.setAttributes(attributes);
+ assertThatThrownBy(() -> wrapper.populateRequestParameters(parameters))
+ .isInstanceOf(NullPointerException.class);
+
+ parameters.setRuleProvider(RuleProvider.RAINY_DAY);
+ assertThatThrownBy(() -> wrapper.populateRequestParameters(parameters))
+ .isInstanceOf(NullPointerException.class);
+
+ Map<String, String> treatments = new LinkedHashMap<>();
+ parameters.setTreatments(treatments);
+
+ PolicyRestAdapter adapter = wrapper.populateRequestParameters((parameters));
+ assertEquals("Rainy_Day", adapter.getRuleProvider());
+
+ treatments.put("ATreatment", "A Treatment Value");
+ adapter = wrapper.populateRequestParameters((parameters));
+ assertEquals("ATreatment", ((Map<String, String>) adapter.getRainyday().getTreatmentTableChoices().get(0))
+ .get("errorcode"));
+ assertEquals("A Treatment Value",
+ ((Map<String, String>) adapter.getRainyday().getTreatmentTableChoices().get(0))
+ .get("treatment"));
+
+ Map<String, String> matchingMap = new LinkedHashMap<>();
+ matchingMap.put("ServiceType", "AServiceType");
+ attributes.put(AttributeType.MATCHING, matchingMap);
+ parameters.setAttributes(attributes);
+ adapter = wrapper.populateRequestParameters((parameters));
+ assertEquals("AServiceType", adapter.getRainyday().getServiceType());
+ }
+
+ @Test
+ public void testDecisionGuardParameterHandling() throws Exception {
+ PolicyParameters parameters = createParametersObject();
+ parameters.setPolicyClass(PolicyClass.Decision);
+
+ PolicyValidationRequestWrapper wrapper = new PolicyValidationRequestWrapper();
+ assertThatThrownBy(() -> wrapper.populateRequestParameters(parameters))
+ .isInstanceOf(NullPointerException.class);
+
+ Map<AttributeType, Map<String, String>> attributes = new LinkedHashMap<>();
+ parameters.setAttributes(attributes);
+ assertThatThrownBy(() -> wrapper.populateRequestParameters(parameters))
+ .isInstanceOf(NullPointerException.class);
+
+ parameters.setRuleProvider(RuleProvider.GUARD_BL_YAML);
+
+ PolicyRestAdapter adapter = wrapper.populateRequestParameters((parameters));
+ assertEquals("GUARD_BL_YAML", adapter.getRuleProvider());
+
+ parameters.setRuleProvider(RuleProvider.GUARD_MIN_MAX);
+
+ adapter = wrapper.populateRequestParameters((parameters));
+ assertEquals("GUARD_MIN_MAX", adapter.getRuleProvider());
+
+ parameters.setRuleProvider(RuleProvider.GUARD_YAML);
+
+ adapter = wrapper.populateRequestParameters((parameters));
+ assertEquals("GUARD_YAML", adapter.getRuleProvider());
+
+ Map<String, String> matchingMap = new LinkedHashMap<>();
+ matchingMap.put("actor", "Actor");
+ matchingMap.put("recipe", "Recipe");
+ matchingMap.put("guardActiveStart", "GuardActiveStart");
+ matchingMap.put("guardActiveEnd", "GuardActiveEnd");
+ matchingMap.put("limit", "Limit");
+ matchingMap.put("timeWindow", "Window");
+ matchingMap.put("timeUnits", "Units");
+
+ attributes.put(AttributeType.MATCHING, matchingMap);
+ parameters.setAttributes(attributes);
+ adapter = wrapper.populateRequestParameters((parameters));
+ assertEquals("Actor", adapter.getYamlparams().getActor());
+ assertEquals("Recipe", adapter.getYamlparams().getRecipe());
+ assertEquals("GuardActiveStart", adapter.getYamlparams().getGuardActiveStart());
+ assertEquals("GuardActiveEnd", adapter.getYamlparams().getGuardActiveEnd());
+ assertEquals("Limit", adapter.getYamlparams().getLimit());
+ assertEquals("Window", adapter.getYamlparams().getTimeWindow());
+ assertEquals("Units", adapter.getYamlparams().getTimeUnits());
+
+ parameters.setRuleProvider(RuleProvider.GUARD_MIN_MAX);
+ matchingMap.put("min", "TheMin");
+ matchingMap.put("max", "TheMax");
+ adapter = wrapper.populateRequestParameters((parameters));
+ assertEquals("TheMin", adapter.getYamlparams().getMin());
+ assertEquals("TheMax", adapter.getYamlparams().getMax());
+
+ parameters.setRuleProvider(RuleProvider.GUARD_BL_YAML);
+ adapter = wrapper.populateRequestParameters((parameters));
+ assertTrue(adapter.getYamlparams().getBlackList().isEmpty());
+
+ matchingMap.put("blackList", "Bad0,Bad1");
+ adapter = wrapper.populateRequestParameters((parameters));
+ assertEquals("Bad0", adapter.getYamlparams().getBlackList().get(0));
+ assertEquals("Bad1", adapter.getYamlparams().getBlackList().get(1));
+
+ parameters.setRuleProvider(RuleProvider.AAF);
+ adapter = wrapper.populateRequestParameters((parameters));
+ assertNull(adapter.getYamlparams());
+ }
+
+ @SuppressWarnings("unchecked")
+ @Test
+ public void testActionParameterHandling() throws Exception {
+ PolicyParameters parameters = createParametersObject();
+ parameters.setPolicyClass(PolicyClass.Action);
+
+ PolicyValidationRequestWrapper wrapper = new PolicyValidationRequestWrapper();
+
+ PolicyRestAdapter adapter = wrapper.populateRequestParameters((parameters));
+ assertTrue(adapter.getRuleAlgorithmschoices().isEmpty());
+
+ List<String> dynamicRuleAlgorithmLabels = new ArrayList<>();
+ parameters.setDynamicRuleAlgorithmLabels(dynamicRuleAlgorithmLabels);
+ adapter = wrapper.populateRequestParameters((parameters));
+ assertTrue(adapter.getRuleAlgorithmschoices().isEmpty());
+
+ dynamicRuleAlgorithmLabels.add("Label0");
+ List<String> dynamicRuleAlgorithmFunctions = new ArrayList<>();
+ dynamicRuleAlgorithmFunctions.add("FirstAlgorithmFunction");
+ parameters.setDynamicRuleAlgorithmFunctions(dynamicRuleAlgorithmFunctions);
+ List<String> dynamicRuleAlgorithmField1 = new ArrayList<>();
+ dynamicRuleAlgorithmField1.add("FirstAlgorithmFunctionField1");
+ parameters.setDynamicRuleAlgorithmField1(dynamicRuleAlgorithmField1);
+ List<String> dynamicRuleAlgorithmField2 = new ArrayList<>();
+ dynamicRuleAlgorithmField2.add("FirstAlgorithmFunctionField2");
+ parameters.setDynamicRuleAlgorithmField2(dynamicRuleAlgorithmField2);
+ parameters.setDynamicRuleAlgorithmLabels(dynamicRuleAlgorithmLabels);
+ adapter = wrapper.populateRequestParameters((parameters));
+ assertEquals(1, adapter.getRuleAlgorithmschoices().size());
+ assertEquals("Label0", ((LinkedHashMap<String, String>) adapter.getRuleAlgorithmschoices().get(0)).get("id"));
+
+ Map<String, String> matchingMap = new LinkedHashMap<>();
+ matchingMap.put("AKey", "AValue");
+
+ Map<AttributeType, Map<String, String>> attributes = new LinkedHashMap<>();
+ attributes.put(AttributeType.MATCHING, matchingMap);
+ parameters.setAttributes(attributes);
+ adapter = wrapper.populateRequestParameters((parameters));
+ assertEquals("AKey", ((LinkedHashMap<String, String>) adapter.getAttributes().get(0)).get("key"));
+ }
+
+ private PolicyParameters createParametersObject() {
+ PolicyParameters parameters = new PolicyParameters();
+
+ parameters.setPolicyName("PolicyName");
+ parameters.setOnapName("ONAPName");
+ parameters.setPriority("SomePriority");
+ parameters.setConfigName("ConfigName");
+ parameters.setRiskType("RiskType");
+ parameters.setRiskLevel("RiskLevel");
+ parameters.setGuard(false);
+ parameters.setTtlDate(new Date());
+
+ return parameters;
+ }
+}
diff --git a/ONAP-REST/src/test/java/org/onap/policy/rest/util/PolicyValidationTest.java b/ONAP-REST/src/test/java/org/onap/policy/rest/util/PolicyValidationTest.java
index 6051db4c3..d019c6370 100644
--- a/ONAP-REST/src/test/java/org/onap/policy/rest/util/PolicyValidationTest.java
+++ b/ONAP-REST/src/test/java/org/onap/policy/rest/util/PolicyValidationTest.java
@@ -3,13 +3,14 @@
* ONAP-REST
* ================================================================================
* Copyright (C) 2018 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2019 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -17,20 +18,44 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.policy.rest.util;
-import static org.junit.Assert.*;
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotSame;
+import static org.junit.Assert.assertNull;
+
+import com.fasterxml.jackson.databind.ObjectMapper;
+
+import java.io.IOException;
import java.text.SimpleDateFormat;
+import java.util.ArrayList;
import java.util.Date;
+import java.util.LinkedHashMap;
+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.junit.runner.RunWith;
+import org.mockito.Mock;
+import org.mockito.Mockito;
+import org.mockito.runners.MockitoJUnitRunner;
import org.onap.policy.api.PolicyConfigType;
import org.onap.policy.api.PolicyParameters;
+import org.onap.policy.common.utils.resources.TextFileUtils;
+import org.onap.policy.rest.adapter.ClosedLoopFaultTrapDatas;
import org.onap.policy.rest.adapter.PolicyRestAdapter;
+import org.onap.policy.rest.dao.CommonClassDao;
+import org.onap.policy.rest.jpa.MicroServiceModels;
+@RunWith(MockitoJUnitRunner.class)
public class PolicyValidationTest {
+ @Mock
+ private CommonClassDao commonClassDao;
@Before
public void setUp() throws Exception {
@@ -41,9 +66,7 @@ public class PolicyValidationTest {
}
@Test
- public void microServicePolicyTests() throws Exception{
- PolicyValidation validation = new PolicyValidation();
- PolicyValidationRequestWrapper wrapper = new PolicyValidationRequestWrapper();
+ public void microServicePolicyTests() throws Exception {
PolicyParameters policyParameters = new PolicyParameters();
policyParameters.setPolicyConfigType(PolicyConfigType.MicroService);
@@ -51,8 +74,8 @@ public class PolicyValidationTest {
policyParameters.setPolicyDescription("This is a sample Micro Service policy Create example");
policyParameters.setOnapName("DCAE");
policyParameters.setPriority("1");
- String MSjsonString = "{\"service\":\"TOSCA_namingJenny\",\"location\":\"Test DictMSLoc\",\"uuid\":\"testDict DCAEUIID\",\"policyName\":\"testModelValidation\",\"description\":\"test\",\"configName\":\"testDict MSConfName\",\"templateVersion\":\"1607\",\"version\":\"gw12181031\",\"priority\":\"5\",\"policyScope\":\"resource=ResourcetypeVenktest1,service=ServiceName1707,type=Name1707,closedLoopControlName=Retest_retest1\",\"riskType\":\"Test\",\"riskLevel\":\"3\",\"guard\":\"True\",\"content\":{\"police-instance-name\":\"testing\",\"naming-models\":[{\"naming-properties\":[{\"property-value\":\"test\",\"source-endpoint\":\"test\",\"property-name\":\"testPropertyname\",\"increment-sequence\":{\"scope\":\"VNF\",\"start-value\":\"1\",\"length\":\"3\",\"increment\":\"2\"},\"source-system\":\"TOSCA\"}],\"naming-type\":\"testNamingType\",\"naming-recipe\":\"testNamingRecipe\"}]}}";;
- policyParameters.setConfigBody(MSjsonString);
+ String msJsonString = TextFileUtils.getTextFileAsString("src/test/resources/policies/MicroServicePolicy.json");
+ policyParameters.setConfigBody(msJsonString);
policyParameters.setRequestID(UUID.randomUUID());
SimpleDateFormat dateformat3 = new SimpleDateFormat("dd/MM/yyyy");
Date date = dateformat3.parse("15/10/2016");
@@ -62,19 +85,1202 @@ public class PolicyValidationTest {
policyParameters.setRiskType("TEST");
policyParameters.setRequestID(UUID.randomUUID());
-
+ PolicyValidationRequestWrapper wrapper = new PolicyValidationRequestWrapper();
PolicyRestAdapter policyData = wrapper.populateRequestParameters(policyParameters);
- StringBuilder responseString = validation.validatePolicy(policyData);
+ PolicyValidation validation = new PolicyValidation();
+ String responseString = validation.validatePolicy(policyData).toString();
+
+ assertNotSame("success", responseString);
+
+ new PolicyValidation(null);
+ assertNull(PolicyValidation.getCommonClassDao());
+
+ policyData.setConfigPolicyType("ClosedLoop_Fault");
+ responseString = validation.validatePolicy(policyData).toString();
+ assertThat(responseString).doesNotContain("success");
+
+ policyData.setConfigPolicyType("ClosedLoop_PM");
+ responseString = validation.validatePolicy(policyData).toString();
+ assertThat(responseString).doesNotContain("success");
+
+ policyData.setConfigPolicyType("Enforcer Config");
+ responseString = validation.validatePolicy(policyData).toString();
+ assertThat(responseString).doesNotContain("success");
+
+ policyData.setConfigPolicyType("Optimization");
+ responseString = validation.validatePolicy(policyData).toString();
+ assertThat(responseString).doesNotContain("success");
+
+ policyData.setConfigPolicyType("Strange");
+ responseString = validation.validatePolicy(policyData).toString();
+ assertThat(responseString).doesNotContain("success");
+ }
+
+ @Test
+ public void testPolicyHeadingValidation() throws IOException {
+ PolicyValidation validation = new PolicyValidation();
+ PolicyRestAdapter policyData = new PolicyRestAdapter();
+
+ String responseString = validation.validatePolicy(policyData).toString();
+ assertThat(responseString).contains("PolicyName Should not be empty");
+
+ policyData.setPolicyName("%%%~~~%%%");
+ responseString = validation.validatePolicy(policyData).toString();
+ assertThat(responseString).contains("The Value in Required Field will allow only '{0-9}, {a-z}, {A-Z}");
+
+ policyData.setPolicyName("ALegalPolicyName");
+ policyData.setPolicyDescription("@CreatedBy:");
+ responseString = validation.validatePolicy(policyData).toString();
+ assertThat(responseString)
+ .contains("The value in the description shouldn't contain @CreatedBy: or @ModifiedBy:");
+ policyData.setPolicyDescription("@CreatedBy:");
+
+ policyData.setPolicyDescription("A Legal Description");
+ responseString = validation.validatePolicy(policyData).toString();
+ assertThat(responseString)
+ .doesNotContain("The value in the description shouldn't contain @CreatedBy: or @ModifiedBy:");
+ }
+
+ @Test
+ public void testPolicyAttributeValidation() throws IOException {
+ PolicyValidation validation = new PolicyValidation();
+ PolicyRestAdapter policyData = new PolicyRestAdapter();
+ policyData.setPolicyName("ALegalPolicyName");
+ policyData.setPolicyDescription("A Valid Description");
+
+ String responseString = validation.validatePolicy(policyData).toString();
+ assertEquals("success", responseString);
+
+ policyData.setApiflag("API");
+ responseString = validation.validatePolicy(policyData).toString();
+ assertEquals("success", responseString);
+
+ policyData.setApiflag("NOTAPI");
+ responseString = validation.validatePolicy(policyData).toString();
+ assertEquals("success", responseString);
+
+ List<Object> attributes = new ArrayList<>();
+ policyData.setAttributes(attributes);
+ responseString = validation.validatePolicy(policyData).toString();
+ assertEquals("success", responseString);
+
+ attributes.add(new String("hello"));
+ responseString = validation.validatePolicy(policyData).toString();
+ assertEquals("success", responseString);
+ attributes.clear();
+
+ Map<String, String> mapAttribute = new LinkedHashMap<>();
+ attributes.add(mapAttribute);
+ responseString = validation.validatePolicy(policyData).toString();
+ assertThat(responseString).contains("Component Attributes</b>:<i> has one missing Component Attribute value");
+
+ mapAttribute.put("key", "value");
+ responseString = validation.validatePolicy(policyData).toString();
+ assertEquals("<b>Component Attributes</b>:<i> has one missing Component Attribute value</i><br>",
+ responseString);
+
+ mapAttribute.put("key", "");
+ responseString = validation.validatePolicy(policyData).toString();
+ assertEquals("<b>Attributes or Component Attributes</b>:<i>null : value has spaces or invalid characters</i>"
+ + "<br><b>Component Attributes</b>:<i> has one missing Component Attribute value</i><br>",
+ responseString);
+ mapAttribute.clear();
+
+ responseString = validation.validatePolicy(policyData).toString();
+ mapAttribute.put("hello", "aaa");
+ responseString = validation.validatePolicy(policyData).toString();
+ assertEquals("<b>Component Attributes</b>:<i> has one missing Component Attribute key</i><br>"
+ + "<b>Component Attributes</b>:<i> has one missing Component Attribute value</i><br>",
+ responseString);
+
+ policyData.setPolicyType("Config");
+ responseString = validation.validatePolicy(policyData).toString();
+ assertEquals("<b>RiskType</b>: Risk Type Should not be Empty</i><br>"
+ + "<b>RiskLevel</b>: Risk Level Should not be Empty</i><br>"
+ + "<b>Guard</b>: Guard Value Should not be Empty</i><br>", responseString);
+
+ policyData.setConfigPolicyType("Base");
+ responseString = validation.validatePolicy(policyData).toString();
+ assertThat(responseString).contains("has one missing Attribute key");
+
+ policyData.setConfigPolicyType("BRMS_Param");
+ responseString = validation.validatePolicy(policyData).toString();
+ assertThat(responseString).contains("has one missing Attribute key");
+
+ policyData.setConfigPolicyType("BRMS_Raw");
+ responseString = validation.validatePolicy(policyData).toString();
+ assertThat(responseString).contains("has one missing Attribute key");
+
+ policyData.setConfigPolicyType(null);
+ responseString = validation.validatePolicy(policyData).toString();
+ assertThat(responseString).contains("Risk Level Should not be Empty");
+
+ mapAttribute.clear();
+ mapAttribute.put("value", "thevalue");
+ responseString = validation.validatePolicy(policyData).toString();
+ assertThat(responseString).contains("Risk Level Should not be Empty");
+
+ mapAttribute.put("value", "$$$%%%%");
+ responseString = validation.validatePolicy(policyData).toString();
+ assertThat(responseString).contains("Risk Level Should not be Empty");
+
+ policyData.setConfigPolicyType("Base");
+ responseString = validation.validatePolicy(policyData).toString();
+ assertThat(responseString).contains("value has spaces or invalid characters");
+
+ policyData.setConfigPolicyType("BRMS_Param");
+ responseString = validation.validatePolicy(policyData).toString();
+ assertThat(responseString).contains("value has spaces or invalid characters");
+
+ policyData.setConfigPolicyType("BRMS_Raw");
+ responseString = validation.validatePolicy(policyData).toString();
+ assertThat(responseString).contains("value has spaces or invalid characters");
+
+ policyData.setConfigPolicyType(null);
+ policyData.setPolicyType(null);
+ responseString = validation.validatePolicy(policyData).toString();
+ assertThat(responseString).contains("value has spaces or invalid characters");
+ }
+
+ @Test
+ public void testPolicySettingsValidation() throws IOException {
+ PolicyValidation validation = new PolicyValidation();
+ PolicyRestAdapter policyData = new PolicyRestAdapter();
+ policyData.setPolicyName("ALegalPolicyName");
+ policyData.setPolicyDescription("A Valid Description");
+
+ String responseString = validation.validatePolicy(policyData).toString();
+ assertEquals("success", responseString);
+
+ policyData.setApiflag("API");
+ responseString = validation.validatePolicy(policyData).toString();
+ assertEquals("success", responseString);
+
+ policyData.setApiflag("NOTAPI");
+ responseString = validation.validatePolicy(policyData).toString();
+ assertEquals("success", responseString);
+
+ List<Object> settings = new ArrayList<>();
+ policyData.setSettings(settings);
+ responseString = validation.validatePolicy(policyData).toString();
+ assertEquals("success", responseString);
+
+ settings.add("hello");
+ responseString = validation.validatePolicy(policyData).toString();
+ assertEquals("success", responseString);
+ settings.clear();
+
+ Map<String, String> mapSetting = new LinkedHashMap<>();
+ settings.add(mapSetting);
+ responseString = validation.validatePolicy(policyData).toString();
+ assertThat(responseString).contains("Settings Attributes</b>:<i> has one missing Attribute key");
+
+ mapSetting.put("key", "value");
+ responseString = validation.validatePolicy(policyData).toString();
+ assertEquals("<b>Settings Attributes</b>:<i> has one missing Attribute Value</i><br>", responseString);
+
+ mapSetting.put("key", "");
+ responseString = validation.validatePolicy(policyData).toString();
+ assertEquals("<b>Settings Attributes</b>:<i> has one missing Attribute Value</i><br>", responseString);
+ mapSetting.clear();
+
+ mapSetting.put("value", "thevalue");
+ responseString = validation.validatePolicy(policyData).toString();
+ assertThat(responseString).contains("has one missing Attribute key");
+
+ mapSetting.put("value", "$$$%%%");
+ responseString = validation.validatePolicy(policyData).toString();
+ assertThat(responseString).contains("value has spaces or invalid characters");
+ }
+
+ @Test
+ public void testPolicyRuleAlgorithmsValidation() throws IOException {
+ PolicyValidation validation = new PolicyValidation();
+ PolicyRestAdapter policyData = new PolicyRestAdapter();
+ policyData.setPolicyName("ALegalPolicyName");
+ policyData.setPolicyDescription("A Valid Description");
+
+ String responseString = validation.validatePolicy(policyData).toString();
+ assertEquals("success", responseString);
+
+ policyData.setApiflag("API");
+ responseString = validation.validatePolicy(policyData).toString();
+ assertEquals("success", responseString);
+
+ policyData.setApiflag("NOTAPI");
+ responseString = validation.validatePolicy(policyData).toString();
+ assertEquals("success", responseString);
+
+ List<Object> ruleAlgorithmschoices = new ArrayList<>();
+ policyData.setRuleAlgorithmschoices(ruleAlgorithmschoices);
+ responseString = validation.validatePolicy(policyData).toString();
+ assertEquals("success", responseString);
+
+ ruleAlgorithmschoices.add("hello");
+ responseString = validation.validatePolicy(policyData).toString();
+ assertEquals("success", responseString);
+ ruleAlgorithmschoices.clear();
+
+ Map<String, String> mapChoice = new LinkedHashMap<>();
+ ruleAlgorithmschoices.add(mapChoice);
+ assertNull(validation.validatePolicy(policyData));
+
+ mapChoice.clear();
+ mapChoice.put("id", "TheID");
+ responseString = validation.validatePolicy(policyData).toString();
+ assertThat(responseString).contains("Field 1 value is not selected");
+
+ mapChoice.put("dynamicRuleAlgorithmField1", "Field1");
+ responseString = validation.validatePolicy(policyData).toString();
+ assertThat(responseString).contains("Field 2 value is not selected");
+
+ mapChoice.put("dynamicRuleAlgorithmCombo", "Combo");
+ responseString = validation.validatePolicy(policyData).toString();
+ assertThat(responseString).contains("Field 3 value is empty");
+
+ mapChoice.put("dynamicRuleAlgorithmField2", "Field2");
+ responseString = validation.validatePolicy(policyData).toString();
+ assertEquals("success", responseString);
+
+ mapChoice.put("dynamicRuleAlgorithmField2", "%%%$$$");
+ responseString = validation.validatePolicy(policyData).toString();
+ assertThat(responseString).contains("Field 3 value has special characters");
+ }
+
+ @Test
+ public void testPolicyConfigBaseValidation() throws IOException {
+ PolicyValidation validation = new PolicyValidation();
+ PolicyRestAdapter policyData = new PolicyRestAdapter();
+ policyData.setPolicyName("ALegalPolicyName");
+ policyData.setPolicyDescription("A Valid Description");
+
+ String responseString = validation.validatePolicy(policyData).toString();
+ assertEquals("success", responseString);
+
+ policyData.setApiflag("API");
+ responseString = validation.validatePolicy(policyData).toString();
+ assertEquals("success", responseString);
+
+ policyData.setPolicyType("Config");
+ policyData.setConfigPolicyType("Base");
+ responseString = validation.validatePolicy(policyData).toString();
+ assertThat(responseString).contains("Onap Name Should not be empty");
+
+ policyData.setOnapName("%%%$$$$");
+ responseString = validation.validatePolicy(policyData).toString();
+ assertThat(responseString).contains("<b>OnapName</b>:<i>The Value in Required Field");
+
+ policyData.setOnapName("AValidOnapName");
+ responseString = validation.validatePolicy(policyData).toString();
+ assertThat(responseString).contains("Risk Level Should not be Empty");
+
+ policyData.setRiskType("%%%$$$$");
+ responseString = validation.validatePolicy(policyData).toString();
+ assertThat(responseString).contains("<b>RiskType</b>:<i>The Value in Required Field");
+
+ policyData.setRiskType("AValidRiskType");
+ responseString = validation.validatePolicy(policyData).toString();
+ assertThat(responseString).contains("Risk Level Should not be Empty");
+
+ policyData.setRiskLevel("%%%$$$$");
+ responseString = validation.validatePolicy(policyData).toString();
+ assertThat(responseString).contains("<b>RiskLevel</b>:<i>The Value in Required Field");
+
+ policyData.setRiskLevel("AValidRiskLevel");
+ responseString = validation.validatePolicy(policyData).toString();
+ assertThat(responseString).contains("Guard Value Should not be Empty");
+
+ policyData.setGuard("%%%$$$$");
+ responseString = validation.validatePolicy(policyData).toString();
+ assertThat(responseString).contains("<b>Guard</b>:<i>The Value in Required Field");
+
+ policyData.setGuard("AValidGuard");
+ responseString = validation.validatePolicy(policyData).toString();
+ assertThat(responseString).contains("Config Name Should not be Empty");
+
+ policyData.setConfigName("%%%$$$$");
+ responseString = validation.validatePolicy(policyData).toString();
+ assertThat(responseString).contains("ConfigName:The Value in Required Field");
+
+ policyData.setConfigName("AValidConfigName");
+ responseString = validation.validatePolicy(policyData).toString();
+ assertThat(responseString).contains("Config Type Should not be Empty");
+
+ policyData.setConfigType("%%%$$$$");
+ responseString = validation.validatePolicy(policyData).toString();
+ assertThat(responseString).contains("ConfigType:The Value in Required Field");
+
+ policyData.setConfigType("AValidConfigType");
+ responseString = validation.validatePolicy(policyData).toString();
+ assertThat(responseString).contains("Config Body Should not be Empty");
+
+ policyData.setConfigBodyData("");
+ responseString = validation.validatePolicy(policyData).toString();
+ assertThat(responseString).contains("Config Body Should not be Empty");
+
+ policyData.setConfigBodyData("%%%$$$$");
+ responseString = validation.validatePolicy(policyData).toString();
+ assertEquals("success@#", responseString);
+
+ policyData.setConfigType(null);
+ policyData.setConfigBodyData("ValidConfigBodyData");
+ responseString = validation.validatePolicy(policyData).toString();
+ assertThat(responseString).contains("Config Type Should not be Empty");
+
+ policyData.setConfigType("JSON");
+ policyData.setConfigBodyData("{");
+ responseString = validation.validatePolicy(policyData).toString();
+ assertThat(responseString).contains("Config Body: JSON Content is not valid");
+
+ policyData.setConfigBodyData("ValidConfigBodyData");
+ responseString = validation.validatePolicy(policyData).toString();
+ assertEquals("success@#", responseString);
+
+ policyData.setConfigType("XML");
+ policyData.setConfigBodyData("{");
+ responseString = validation.validatePolicy(policyData).toString();
+ assertThat(responseString).contains("Config Body: XML Content data is not valid");
+
+ policyData.setConfigBodyData("<tag>value</tag>");
+ responseString = validation.validatePolicy(policyData).toString();
+ assertEquals("success@#", responseString);
+
+ policyData.setConfigType("PROPERTIES");
+ policyData.setConfigBodyData("{");
+ responseString = validation.validatePolicy(policyData).toString();
+ assertThat(responseString).contains("Config Body: Property data is not valid");
+
+ policyData.setConfigBodyData("propertyName=PropertyValue");
+ responseString = validation.validatePolicy(policyData).toString();
+ assertEquals("success@#", responseString);
+ }
+
+ @Test
+ public void testPolicyConfigFirewallValidation() throws IOException {
+ PolicyValidation validation = new PolicyValidation();
+ PolicyRestAdapter policyData = new PolicyRestAdapter();
+ policyData.setPolicyName("ALegalPolicyName");
+ policyData.setPolicyDescription("A Valid Description");
+
+ String responseString = validation.validatePolicy(policyData).toString();
+ assertEquals("success", responseString);
+
+ policyData.setApiflag("API");
+ responseString = validation.validatePolicy(policyData).toString();
+ assertEquals("success", responseString);
+
+ // Invalid values tested in config base test
+ policyData.setOnapName("AValidOnapName");
+ policyData.setRiskType("AValidRiskType");
+ policyData.setRiskLevel("AValidRiskLevel");
+ policyData.setGuard("AValidGuard");
+ assertEquals("success", responseString);
+
+ policyData.setPolicyType("Config");
+ policyData.setConfigPolicyType("Firewall Config");
+ responseString = validation.validatePolicy(policyData).toString();
+ assertThat(responseString).contains("Config Name is required");
+
+ policyData.setConfigName("");
+ responseString = validation.validatePolicy(policyData).toString();
+ assertThat(responseString).contains("Config Name is required");
+
+ policyData.setConfigName("%%%$$$$");
+ responseString = validation.validatePolicy(policyData).toString();
+ assertThat(responseString).contains("<b>ConfigName</b>:<i>The Value in Required Field");
+
+ policyData.setConfigName("AValidConfigName");
+ responseString = validation.validatePolicy(policyData).toString();
+ assertThat(responseString).contains("Security Zone is required");
+
+ policyData.setSecurityZone("");
+ responseString = validation.validatePolicy(policyData).toString();
+ assertThat(responseString).contains("Security Zone is required");
+
+ policyData.setSecurityZone("AValidSeurityZone");
+ responseString = validation.validatePolicy(policyData).toString();
+ assertEquals("success@#", responseString);
+ }
+
+ @Test
+ public void testPolicyConfigBRMSValidation() throws IOException {
+ PolicyValidation validation = new PolicyValidation();
+ PolicyRestAdapter policyData = new PolicyRestAdapter();
+ policyData.setPolicyName("ALegalPolicyName");
+ policyData.setPolicyDescription("A Valid Description");
+
+ String responseString = validation.validatePolicy(policyData).toString();
+ assertEquals("success", responseString);
+
+ policyData.setApiflag("API");
+ responseString = validation.validatePolicy(policyData).toString();
+ assertEquals("success", responseString);
+
+ // Invalid values tested in config base test
+ policyData.setOnapName("AValidOnapName");
+ policyData.setRiskType("AValidRiskType");
+ policyData.setRiskLevel("AValidRiskLevel");
+ policyData.setGuard("AValidGuard");
+ assertEquals("success", responseString);
+
+ policyData.setPolicyType("Config");
+ policyData.setConfigPolicyType("BRMS_Param");
+ responseString = validation.validatePolicy(policyData).toString();
+ assertThat(responseString).contains("BRMS Template is required");
+
+ policyData.setRuleName("");
+ responseString = validation.validatePolicy(policyData).toString();
+ assertThat(responseString).contains("BRMS Template is required");
+
+ policyData.setRuleName("AValidRuleName");
+ responseString = validation.validatePolicy(policyData).toString();
+ assertEquals("success@#", responseString);
+ policyData.setRuleName(null);
+
+ policyData.setConfigPolicyType("BRMS_Raw");
+ responseString = validation.validatePolicy(policyData).toString();
+ assertThat(responseString).contains("Raw Rule is required");
+
+ policyData.setConfigBodyData("");
+ responseString = validation.validatePolicy(policyData).toString();
+ assertThat(responseString).contains("Raw Rule is required");
+
+ policyData.setConfigBodyData("InvalidConfigBodyData");
+ responseString = validation.validatePolicy(policyData).toString();
+ assertThat(responseString).contains("expecting one of the following tokens");
+
+ policyData.setConfigBodyData("import org.onap.policy.test.DummyTestSomething;");
+ responseString = validation.validatePolicy(policyData).toString();
+ assertEquals("success@#", responseString);
+ }
+
+ @Test
+ public void testPolicyConfigCloseLoopPmValidation() throws IOException {
+ PolicyValidation validation = new PolicyValidation();
+ PolicyRestAdapter policyData = new PolicyRestAdapter();
+ policyData.setPolicyName("ALegalPolicyName");
+ policyData.setPolicyDescription("A Valid Description");
+
+ String responseString = validation.validatePolicy(policyData).toString();
+ assertEquals("success", responseString);
- assertNotSame("success", responseString.toString());
+ policyData.setApiflag("API");
+ responseString = validation.validatePolicy(policyData).toString();
+ assertEquals("success", responseString);
+ // Invalid values tested in config base test
+ policyData.setOnapName("AValidOnapName");
+ policyData.setRiskType("AValidRiskType");
+ policyData.setRiskLevel("AValidRiskLevel");
+ policyData.setGuard("AValidGuard");
+ assertEquals("success", responseString);
+
+ policyData.setPolicyType("Config");
+ policyData.setConfigPolicyType("ClosedLoop_PM");
+ responseString = validation.validatePolicy(policyData).toString();
+ assertThat(responseString).contains("ServiceType PolicyName is required");
+
+ Map<String, String> serviceTypePolicyName = null;
+ policyData.setServiceTypePolicyName(serviceTypePolicyName);
+ responseString = validation.validatePolicy(policyData).toString();
+ assertThat(responseString).contains("ServiceType PolicyName is required");
+
+ serviceTypePolicyName = new LinkedHashMap<>();
+ policyData.setServiceTypePolicyName(serviceTypePolicyName);
+ responseString = validation.validatePolicy(policyData).toString();
+ assertThat(responseString).contains("ServiceType PolicyName is required");
+
+ serviceTypePolicyName.put("AKey", "AValue");
+ policyData.setServiceTypePolicyName(serviceTypePolicyName);
+ responseString = validation.validatePolicy(policyData).toString();
+ assertThat(responseString).contains("ServiceType PolicyName is required");
+ serviceTypePolicyName.clear();
+
+ serviceTypePolicyName.put("serviceTypePolicyName", "");
+ policyData.setServiceTypePolicyName(serviceTypePolicyName);
+ responseString = validation.validatePolicy(policyData).toString();
+ assertThat(responseString).contains("ServiceType PolicyName is required");
+
+ serviceTypePolicyName.put("serviceTypePolicyName", "AValidserviceTypePolicyName");
+ policyData.setServiceTypePolicyName(serviceTypePolicyName);
+ responseString = validation.validatePolicy(policyData).toString();
+ assertThat(responseString).contains("Select at least one D2");
+
+ policyData.setJsonBody("");
+ assertNull(validation.validatePolicy(policyData));
+
+ policyData.setJsonBody("InvalidConfigBodyData");
+ assertNull(validation.validatePolicy(policyData));
+
+ policyData.setJsonBody("{}");
+ responseString = validation.validatePolicy(policyData).toString();
+ assertThat(responseString).contains("Select at least one D2");
+
+ policyData.setJsonBody("{\"gamma\": false}");
+ responseString = validation.validatePolicy(policyData).toString();
+ assertThat(responseString).contains("Select at least one D2");
+
+ policyData.setJsonBody("{\"gamma\": true}");
+ responseString = validation.validatePolicy(policyData).toString();
+ assertEquals("success@#", responseString);
+
+ policyData.setJsonBody("{\"mcr\": false}");
+ responseString = validation.validatePolicy(policyData).toString();
+ assertThat(responseString).contains("Select at least one D2");
+
+ policyData.setJsonBody("{\"mcr\": true}");
+ responseString = validation.validatePolicy(policyData).toString();
+ assertEquals("success@#", responseString);
+
+ policyData.setJsonBody("{\"trinity\": false}");
+ responseString = validation.validatePolicy(policyData).toString();
+ assertThat(responseString).contains("Select at least one D2");
+
+ policyData.setJsonBody("{\"trinity\": true}");
+ responseString = validation.validatePolicy(policyData).toString();
+ assertEquals("success@#", responseString);
+
+ policyData.setJsonBody("{\"vDNS\": false}");
+ responseString = validation.validatePolicy(policyData).toString();
+ assertThat(responseString).contains("Select at least one D2");
+
+ policyData.setJsonBody("{\"vDNS\": true}");
+ responseString = validation.validatePolicy(policyData).toString();
+ assertEquals("success@#", responseString);
+
+ policyData.setJsonBody("{\"vUSP\": false}");
+ responseString = validation.validatePolicy(policyData).toString();
+ assertThat(responseString).contains("Select at least one D2");
+
+ policyData.setJsonBody("{\"vUSP\": true}");
+ responseString = validation.validatePolicy(policyData).toString();
+ assertEquals("success@#", responseString);
+
+ policyData.setJsonBody("{\"trinity\": true, \"emailAddress\": null}");
+ responseString = validation.validatePolicy(policyData).toString();
+ assertEquals("success@#", responseString);
+
+ policyData.setJsonBody("{\"trinity\": true, \"emailAddress\": \"\"}");
+ responseString = validation.validatePolicy(policyData).toString();
+ assertThat(responseString).contains("Email Address is not Valid");
+
+ policyData.setJsonBody("{\"trinity\": true, \"emailAddress\": \"%%%$$$\"}");
+ responseString = validation.validatePolicy(policyData).toString();
+ assertThat(responseString).contains("Email Address is not Valid");
+
+ policyData.setJsonBody("{\"trinity\": true, \"emailAddress\": \"dorothy@emealdcity.oz\"}");
+ responseString = validation.validatePolicy(policyData).toString();
+ assertEquals("success@#", responseString);
+
+ policyData.setJsonBody("{\"trinity\": true, \"geoLink\": null}");
+ responseString = validation.validatePolicy(policyData).toString();
+ assertEquals("success@#", responseString);
+
+ policyData.setJsonBody("{\"trinity\": true, \"geoLink\": \"\"}");
+ responseString = validation.validatePolicy(policyData).toString();
+ assertEquals("success@#", responseString);
+
+ policyData.setJsonBody("{\"trinity\": true, \"geoLink\": \"$$$%%%\"}");
+ responseString = validation.validatePolicy(policyData).toString();
+ assertThat(responseString).contains("The Value in Required Field");
+
+ policyData.setJsonBody("{\"trinity\": true, \"geoLink\": \"AValidGeoLink\"}");
+ responseString = validation.validatePolicy(policyData).toString();
+ assertEquals("success@#", responseString);
+
+ policyData.setJsonBody("{\"trinity\": true, \"attributes\": null}");
+ responseString = validation.validatePolicy(policyData).toString();
+ assertEquals("success@#", responseString);
+
+ policyData.setJsonBody("{\"trinity\": true, \"attributes\": {}}");
+ responseString = validation.validatePolicy(policyData).toString();
+ assertEquals("success@#", responseString);
+
+ policyData.setJsonBody("{\"trinity\": true, \"attributes\": {\"an0\":\"av0\"}}");
+ responseString = validation.validatePolicy(policyData).toString();
+ assertEquals("success@#", responseString);
+
+ policyData.setJsonBody("{\"trinity\": true, \"attributes\": {\"an0\":\"$$$%%%\"}}");
+ responseString = validation.validatePolicy(policyData).toString();
+ assertThat(responseString).contains("value has spaces or invalid characters");
+
+ policyData.setJsonBody("{\"trinity\": true, \"attributes\": {\"Message\":\"$$$%%%\"}}");
+ responseString = validation.validatePolicy(policyData).toString();
+ assertEquals("success@#", responseString);
}
@Test
- public final void testEmailValidation() {
+ public void testPolicyConfigCloseLoopFaultValidation() throws IOException {
PolicyValidation validation = new PolicyValidation();
- String result = validation.emailValidation("testemail@test.com", "SUCCESS");
- assertEquals("success", result);
+ PolicyRestAdapter policyData = new PolicyRestAdapter();
+ policyData.setPolicyName("ALegalPolicyName");
+ policyData.setPolicyDescription("A Valid Description");
+
+ String responseString = validation.validatePolicy(policyData).toString();
+ assertEquals("success", responseString);
+
+ policyData.setApiflag("API");
+ responseString = validation.validatePolicy(policyData).toString();
+ assertEquals("success", responseString);
+
+ // Invalid values tested in config base test
+ policyData.setOnapName("AValidOnapName");
+ policyData.setRiskType("AValidRiskType");
+ policyData.setRiskLevel("AValidRiskLevel");
+ policyData.setGuard("AValidGuard");
+ assertEquals("success", responseString);
+
+ policyData.setPolicyType("Config");
+ policyData.setConfigPolicyType("ClosedLoop_Fault");
+ responseString = validation.validatePolicy(policyData).toString();
+ assertThat(responseString).contains("Select at least one D2");
+
+ policyData.setJsonBody("");
+ assertNull(validation.validatePolicy(policyData));
+
+ policyData.setJsonBody("InvalidConfigBodyData");
+ assertNull(validation.validatePolicy(policyData));
+
+ policyData.setJsonBody("{}");
+ responseString = validation.validatePolicy(policyData).toString();
+ assertThat(responseString).contains("There were no conditions provided in configBody json");
+
+ policyData.setJsonBody("{\"conditions\": null}");
+ responseString = validation.validatePolicy(policyData).toString();
+ assertThat(responseString).contains("There were no conditions provided in configBody json");
+
+ policyData.setJsonBody("{\"conditions\": \"\"}");
+ responseString = validation.validatePolicy(policyData).toString();
+ assertThat(responseString).contains("Select At least one Condition");
+
+ policyData.setJsonBody("{\"conditions\": \"AValidCondition\"}");
+ assertNull(validation.validatePolicy(policyData));
+
+ policyData.setApiflag("NOAPI");
+
+ policyData.setJsonBody("");
+ assertNull(validation.validatePolicy(policyData));
+
+ policyData.setJsonBody("InvalidConfigBodyData");
+ assertNull(validation.validatePolicy(policyData));
+
+ ClosedLoopFaultTrapDatas trapDatas = new ClosedLoopFaultTrapDatas();
+ policyData.setTrapDatas(trapDatas);
+
+ ClosedLoopFaultTrapDatas faultDatas = new ClosedLoopFaultTrapDatas();
+ policyData.setFaultDatas(faultDatas);
+
+ policyData.setJsonBody("{}");
+ assertThat(responseString).contains("Select At least one Condition");
+
+ List<Object> trap1 = new ArrayList<>();
+ trapDatas.setTrap1(trap1);
+ responseString = validation.validatePolicy(policyData).toString();
+ assertThat(responseString).contains("Trigger Clear TimeOut is required");
+
+ policyData.setClearTimeOut("AValidClearTimeout");
+ responseString = validation.validatePolicy(policyData).toString();
+ assertThat(responseString).contains("Trap Max Age is required");
+
+ policyData.setTrapMaxAge("AValidTrapMaxAge");
+ responseString = validation.validatePolicy(policyData).toString();
+ assertThat(responseString).contains("Select at least one D2");
+
+ trapDatas.setTrap1(null);
+ responseString = validation.validatePolicy(policyData).toString();
+ assertThat(responseString).contains("Select at least one D2");
+
+ faultDatas.setTrap1(null);
+ responseString = validation.validatePolicy(policyData).toString();
+ assertThat(responseString).contains("Select at least one D2");
+
+ faultDatas.setTrap1(trap1);
+ responseString = validation.validatePolicy(policyData).toString();
+ assertThat(responseString).contains("Fault Clear TimeOut is required when");
+
+ policyData.setVerificationclearTimeOut("AValidVerificationClearTimeout");
+ responseString = validation.validatePolicy(policyData).toString();
+ assertThat(responseString).contains("Select at least one D2");
+
+ policyData.setJsonBody("{\"gamma\": false}");
+ responseString = validation.validatePolicy(policyData).toString();
+ assertThat(responseString).contains("Select at least one D2");
+
+ policyData.setJsonBody("{\"gamma\": true}");
+ responseString = validation.validatePolicy(policyData).toString();
+ assertThat(responseString).contains("vPRO Actions is required");
+
+ policyData.setJsonBody("{\"mcr\": false}");
+ responseString = validation.validatePolicy(policyData).toString();
+ assertThat(responseString).contains("Select at least one D2");
+
+ policyData.setJsonBody("{\"mcr\": true}");
+ responseString = validation.validatePolicy(policyData).toString();
+ assertThat(responseString).contains("vPRO Actions is required");
+
+ policyData.setJsonBody("{\"trinity\": false}");
+ responseString = validation.validatePolicy(policyData).toString();
+ assertThat(responseString).contains("Select at least one D2");
+
+ policyData.setJsonBody("{\"trinity\": true}");
+ responseString = validation.validatePolicy(policyData).toString();
+ assertThat(responseString).contains("vPRO Actions is required");
+
+ policyData.setJsonBody("{\"vDNS\": false}");
+ responseString = validation.validatePolicy(policyData).toString();
+ assertThat(responseString).contains("Select at least one D2");
+
+ policyData.setJsonBody("{\"vDNS\": true}");
+ responseString = validation.validatePolicy(policyData).toString();
+ assertThat(responseString).contains("vPRO Actions is required");
+
+ policyData.setJsonBody("{\"vUSP\": false}");
+ responseString = validation.validatePolicy(policyData).toString();
+ assertThat(responseString).contains("Select at least one D2");
+
+ policyData.setJsonBody("{\"vUSP\": true}");
+ responseString = validation.validatePolicy(policyData).toString();
+ assertThat(responseString).contains("vPRO Actions is required");
+
+ policyData.setJsonBody("{\"trinity\": true, \"emailAddress\": null}");
+ responseString = validation.validatePolicy(policyData).toString();
+ assertThat(responseString).contains("vPRO Actions is required");
+
+ policyData.setJsonBody("{\"trinity\": true, \"emailAddress\": \"\"}");
+ responseString = validation.validatePolicy(policyData).toString();
+ assertThat(responseString).contains("vPRO Actions is required");
+
+ policyData.setJsonBody("{\"trinity\": true, \"emailAddress\": \"%%%$$$\"}");
+ responseString = validation.validatePolicy(policyData).toString();
+ assertThat(responseString).contains("Email Address is not Valid");
+
+ policyData.setJsonBody("{\"trinity\": true, \"emailAddress\": \"dorothy@emealdcity.oz\"}");
+ responseString = validation.validatePolicy(policyData).toString();
+ assertThat(responseString).contains("vPRO Actions is required");
+
+ policyData.setJsonBody("{\"trinity\": true, \"actions\": null}");
+ responseString = validation.validatePolicy(policyData).toString();
+ assertThat(responseString).contains("vPRO Actions is required");
+
+ policyData.setJsonBody("{\"trinity\": true, \"actions\": \"\"}");
+ responseString = validation.validatePolicy(policyData).toString();
+ assertThat(responseString).contains("vPRO Actions is required");
+
+ policyData.setJsonBody("{\"trinity\": true, \"actions\": \"$$$%%%\"}");
+ responseString = validation.validatePolicy(policyData).toString();
+ assertThat(responseString).contains("Policy Status is required");
+ assertThat(responseString).contains("Vnf Type is required");
+
+ policyData.setJsonBody("{\"trinity\": true, \"actions\": \"ValidActions\"}");
+ responseString = validation.validatePolicy(policyData).toString();
+ assertThat(responseString).contains("Policy Status is required");
+
+ policyData.setJsonBody("{\"trinity\": true, \"actions\": \"ValidActions\", \"closedLoopPolicyStatus\": null}");
+ responseString = validation.validatePolicy(policyData).toString();
+ assertThat(responseString).contains("Policy Status is required");
+
+ policyData.setJsonBody("{\"trinity\": true, \"actions\": \"ValidActions\", \"closedLoopPolicyStatus\": \"\"}");
+ responseString = validation.validatePolicy(policyData).toString();
+ assertThat(responseString).contains("Policy Status is required");
+
+ policyData.setJsonBody(
+ "{\"trinity\": true, \"actions\": \"ValidActions\", \"closedLoopPolicyStatus\": \"$$$%%%\"}");
+ responseString = validation.validatePolicy(policyData).toString();
+ assertThat(responseString).contains("Select At least one Condition");
+
+ // @formatter:off
+ policyData.setJsonBody("{"
+ + "\"trinity\": true,"
+ + "\"actions\": \"ValidActions\","
+ + "\"closedLoopPolicyStatus\": \"AValidStatus\""
+ + "}");
+ // @formatter:on
+ responseString = validation.validatePolicy(policyData).toString();
+ assertThat(responseString).contains("Select At least one Condition");
+
+ // @formatter:off
+ policyData.setJsonBody("{"
+ + "\"trinity\": true,"
+ + "\"actions\": \"ValidActions\","
+ + "\"closedLoopPolicyStatus\": \"AValidStatus\","
+ + "\"conditions\": null"
+ + "}");
+ // @formatter:on
+ responseString = validation.validatePolicy(policyData).toString();
+ assertThat(responseString).contains("Select At least one Condition");
+
+ // @formatter:off
+ policyData.setJsonBody("{"
+ + "\"trinity\": true,"
+ + "\"actions\": \"ValidActions\","
+ + "\"closedLoopPolicyStatus\": \"AValidStatus\","
+ + "\"conditions\": \"SEND\""
+ + "}");
+ // @formatter:on
+ responseString = validation.validatePolicy(policyData).toString();
+ assertThat(responseString).contains("Aging Window is required");
+
+ // @formatter:off
+ policyData.setJsonBody("{"
+ + "\"trinity\": true,"
+ + "\"actions\": \"ValidActions\","
+ + "\"closedLoopPolicyStatus\": \"AValidStatus\","
+ + "\"conditions\": \"SEND\","
+ + "\"geoLink\": null"
+ + "}");
+ // @formatter:on
+ responseString = validation.validatePolicy(policyData).toString();
+ assertThat(responseString).contains("Aging Window is required");
+
+ // @formatter:off
+ policyData.setJsonBody("{"
+ + "\"trinity\": true,"
+ + "\"actions\": \"ValidActions\","
+ + "\"closedLoopPolicyStatus\": \"AValidStatus\","
+ + "\"conditions\": \"SEND\","
+ + "\"geoLink\": \"\""
+ + "}");
+ // @formatter:on
+ responseString = validation.validatePolicy(policyData).toString();
+ assertThat(responseString).contains("Aging Window is required");
+
+ // @formatter:off
+ policyData.setJsonBody("{"
+ + "\"trinity\": true,"
+ + "\"actions\": \"ValidActions\","
+ + "\"closedLoopPolicyStatus\": \"AValidStatus\","
+ + "\"conditions\": \"SEND\","
+ + "\"geoLink\": \"%%%$$$\""
+ + "}");
+ // @formatter:on
+ responseString = validation.validatePolicy(policyData).toString();
+ assertThat(responseString).contains("GeoLink</b>:<i>The Value in Required Field");
+
+ // @formatter:off
+ policyData.setJsonBody("{"
+ + "\"trinity\": true,"
+ + "\"actions\": \"ValidActions\","
+ + "\"closedLoopPolicyStatus\": \"AValidStatus\","
+ + "\"conditions\": \"SEND\","
+ + "\"geoLink\": \"AValidGeoLink\""
+ + "}");
+ // @formatter:on
+ responseString = validation.validatePolicy(policyData).toString();
+ assertThat(responseString).contains("Aging Window is required");
+
+ // @formatter:off
+ policyData.setJsonBody("{"
+ + "\"trinity\": true,"
+ + "\"actions\": \"ValidActions\","
+ + "\"closedLoopPolicyStatus\": \"AValidStatus\","
+ + "\"conditions\": \"SEND\","
+ + "\"agingWindow\": -1"
+ + "}");
+ // @formatter:on
+ responseString = validation.validatePolicy(policyData).toString();
+ assertThat(responseString).contains("Time Interval is required");
+
+ // @formatter:off
+ policyData.setJsonBody("{"
+ + "\"trinity\": true,"
+ + "\"actions\": \"ValidActions\","
+ + "\"closedLoopPolicyStatus\": \"AValidStatus\","
+ + "\"conditions\": \"SEND\","
+ + "\"agingWindow\": -1,"
+ + "\"timeInterval\": -1"
+ + "}");
+ // @formatter:on
+ responseString = validation.validatePolicy(policyData).toString();
+ assertThat(responseString).contains("Number of Retries is required");
+
+ // @formatter:off
+ policyData.setJsonBody("{"
+ + "\"trinity\": true,"
+ + "\"actions\": \"ValidActions\","
+ + "\"closedLoopPolicyStatus\": \"AValidStatus\","
+ + "\"conditions\": \"SEND\","
+ + "\"agingWindow\": -1,"
+ + "\"timeInterval\": -1,"
+ + "\"retrys\": -1"
+ + "}");
+ // @formatter:on
+ responseString = validation.validatePolicy(policyData).toString();
+ assertThat(responseString).contains("APP-C Timeout is required");
+
+ // @formatter:off
+ policyData.setJsonBody("{"
+ + "\"trinity\": true,"
+ + "\"actions\": \"ValidActions\","
+ + "\"closedLoopPolicyStatus\": \"AValidStatus\","
+ + "\"conditions\": \"SEND\","
+ + "\"agingWindow\": -1,"
+ + "\"timeInterval\": -1,"
+ + "\"retrys\": -1,"
+ + "\"timeOutvPRO\": -1"
+ + "}");
+ // @formatter:on
+ responseString = validation.validatePolicy(policyData).toString();
+ assertThat(responseString).contains("TimeOutRuby is required");
+
+ // @formatter:off
+ policyData.setJsonBody("{"
+ + "\"trinity\": true,"
+ + "\"actions\": \"ValidActions\","
+ + "\"closedLoopPolicyStatus\": \"AValidStatus\","
+ + "\"conditions\": \"SEND\","
+ + "\"agingWindow\": -1,"
+ + "\"timeInterval\": -1,"
+ + "\"retrys\": -1,"
+ + "\"timeOutvPRO\": -1,"
+ + "\"timeOutRuby\": -1"
+ + "}");
+ // @formatter:on
+ responseString = validation.validatePolicy(policyData).toString();
+ assertThat(responseString).contains("Vnf Type is required");
+
+ // @formatter:off
+ policyData.setJsonBody("{"
+ + "\"trinity\": true,"
+ + "\"actions\": \"ValidActions\","
+ + "\"closedLoopPolicyStatus\": \"AValidStatus\","
+ + "\"conditions\": \"SEND\","
+ + "\"agingWindow\": -1,"
+ + "\"timeInterval\": -1,"
+ + "\"retrys\": -1,"
+ + "\"timeOutvPRO\": -1,"
+ + "\"timeOutRuby\": -1,"
+ + "\"vnfType\": null"
+ + "}");
+ // @formatter:on
+ responseString = validation.validatePolicy(policyData).toString();
+ assertThat(responseString).contains("Vnf Type is required");
+
+ // @formatter:off
+ policyData.setJsonBody("{"
+ + "\"trinity\": true,"
+ + "\"actions\": \"ValidActions\","
+ + "\"closedLoopPolicyStatus\": \"AValidStatus\","
+ + "\"conditions\": \"SEND\","
+ + "\"agingWindow\": -1,"
+ + "\"timeInterval\": -1,"
+ + "\"retrys\": -1,"
+ + "\"timeOutvPRO\": -1,"
+ + "\"timeOutRuby\": -1,"
+ + "\"vnfType\": \"\""
+ + "}");
+ // @formatter:on
+ responseString = validation.validatePolicy(policyData).toString();
+ assertThat(responseString).contains("Vnf Type is required");
+
+ // @formatter:off
+ policyData.setJsonBody("{"
+ + "\"trinity\": true,"
+ + "\"actions\": \"ValidActions\","
+ + "\"closedLoopPolicyStatus\": \"AValidStatus\","
+ + "\"conditions\": \"SEND\","
+ + "\"agingWindow\": -1,"
+ + "\"timeInterval\": -1,"
+ + "\"retrys\": -1,"
+ + "\"timeOutvPRO\": -1,"
+ + "\"timeOutRuby\": -1,"
+ + "\"vnfType\": \"AValid VNF Type\""
+ + "}");
+ // @formatter:on
+ responseString = validation.validatePolicy(policyData).toString();
+ assertEquals("success@#", responseString);
}
+ @Test
+ public void testPolicyConfigMicroServiceValidation() throws IOException {
+ PolicyValidation validation = new PolicyValidation(commonClassDao);
+ PolicyRestAdapter policyData = new PolicyRestAdapter();
+ policyData.setPolicyName("ALegalPolicyName");
+ policyData.setPolicyDescription("A Valid Description");
+
+ String responseString = validation.validatePolicy(policyData).toString();
+ assertEquals("success", responseString);
+
+ policyData.setApiflag("NOAPI");
+ responseString = validation.validatePolicy(policyData).toString();
+ assertEquals("success", responseString);
+
+ // Invalid values tested in config base test
+ policyData.setOnapName("AValidOnapName");
+ policyData.setRiskType("AValidRiskType");
+ policyData.setRiskLevel("AValidRiskLevel");
+ policyData.setGuard("AValidGuard");
+ assertEquals("success", responseString);
+
+ policyData.setPolicyType("Config");
+ policyData.setConfigPolicyType("Micro Service");
+ responseString = validation.validatePolicy(policyData).toString();
+ assertThat(responseString).contains("Micro Service Model is required");
+
+ policyData.setServiceType("");
+ responseString = validation.validatePolicy(policyData).toString();
+ assertThat(responseString).contains("Micro Service Model is required");
+
+ policyData.setServiceType("ServiceType");
+ assertNull(validation.validatePolicy(policyData));
+
+ policyData.setPolicyJSON("");
+ assertNull(validation.validatePolicy(policyData));
+
+ String msJsonContentString0 = TextFileUtils
+ .getTextFileAsString("src/test/resources/policies/MicroServicePolicyContent0.json");
+ policyData.setPolicyJSON(new ObjectMapper().readTree(msJsonContentString0));
+ responseString = validation.validatePolicy(policyData).toString();
+ assertThat(responseString).contains("Micro Service Version is required");
+
+ String msJsonContentString1 = TextFileUtils
+ .getTextFileAsString("src/test/resources/policies/MicroServicePolicyContent1.json");
+ policyData.setPolicyJSON(new ObjectMapper().readTree(msJsonContentString1));
+ responseString = validation.validatePolicy(policyData).toString();
+ assertThat(responseString).contains("Micro Service Version is required");
+
+ policyData.setServiceType("ServiceType-vServiceVersion");
+ responseString = validation.validatePolicy(policyData).toString();
+ assertThat(responseString).contains("The model name, ServiceType of version, ServiceVersion was not found");
+
+ policyData.setServiceType("ServiceType");
+ policyData.setRuleProvider("MicroService_Model");
+ responseString = validation.validatePolicy(policyData).toString();
+ assertThat(responseString).doesNotContain("Priority is required");
+
+ policyData.setVersion("ServiceVersion");
+ Mockito.when(commonClassDao.getDataById(MicroServiceModels.class, "modelName:version",
+ "ServiceType:ServiceVersion")).thenReturn(null);
+ responseString = validation.validatePolicy(policyData).toString();
+ assertThat(responseString).contains("The model name, ServiceType of version, ServiceVersion was not found");
+
+ List<Object> msModelsList = new ArrayList<>();
+ MicroServiceModels msModels = new MicroServiceModels();
+ msModelsList.add(msModels);
+ Mockito.when(commonClassDao.getDataById(MicroServiceModels.class, "modelName:version",
+ "ServiceType:ServiceVersion")).thenReturn(msModelsList);
+ responseString = validation.validatePolicy(policyData).toString();
+ assertEquals("success@#", responseString);
+
+ msModels.setAnnotation("SomeAnntation");
+ assertNull(validation.validatePolicy(policyData));
+
+ msModels.setAnnotation("annotation0Key=annotation0Value");
+ responseString = validation.validatePolicy(policyData).toString();
+ assertEquals("success@#", responseString);
+
+ msModels.setAnnotation("annotation0Key=range::10-100");
+ responseString = validation.validatePolicy(policyData).toString();
+ assertThat(responseString).contains("annotation0Key is required for the MicroService model");
+
+ msModels.setAnnotation("police-instance-name=range::10-100");
+ responseString = validation.validatePolicy(policyData).toString();
+ assertThat(responseString).contains("Model Range:police-instance-name must be between 10 - 100");
+
+ msModels.setAnnotation("police-instance-range=range::12-100");
+ responseString = validation.validatePolicy(policyData).toString();
+ assertThat(responseString).contains("Model Range:police-instance-range must be between 12 - 100");
+
+ msModels.setAnnotation("police-instance-range=range::0-10");
+ responseString = validation.validatePolicy(policyData).toString();
+ assertThat(responseString).contains("Model Range:police-instance-range must be between 0 - 10");
+
+ msModels.setAnnotation("police-instance-range=range::10-100");
+ responseString = validation.validatePolicy(policyData).toString();
+ assertEquals("success@#", responseString);
+
+ msModels.setAnnotation(null);
+ responseString = validation.validatePolicy(policyData).toString();
+ assertEquals("success@#", responseString);
+
+ policyData.setRuleProvider("Not_MicroService_Model");
+ responseString = validation.validatePolicy(policyData).toString();
+ assertThat(responseString).contains("<b>Micro Service Model</b>:<i> location is required for this model");
+
+ policyData.setLocation("AValidLocation");
+ responseString = validation.validatePolicy(policyData).toString();
+ assertThat(responseString).contains("<b>Micro Service Model</b>:<i> configName is required for this model");
+
+ policyData.setConfigName("AValidConfigname");
+ responseString = validation.validatePolicy(policyData).toString();
+ assertThat(responseString).contains("<b>Micro Service Model</b>:<i> uuid is required for this model");
+
+ policyData.setUuid("AValidUUID");
+ responseString = validation.validatePolicy(policyData).toString();
+ assertThat(responseString).contains("<b>Micro Service Model</b>:<i> policyScope is required for this model");
+
+ policyData.setPolicyScope("AValidPolicyScope");
+ responseString = validation.validatePolicy(policyData).toString();
+ assertThat(responseString).contains("<b>Priority</b>:<i> Priority is required");
+
+ policyData.setPriority("AValidPriority");
+ responseString = validation.validatePolicy(policyData).toString();
+ assertEquals("success@#", responseString);
+
+ policyData.setApiflag("API");
+ assertNull(validation.validatePolicy(policyData));
+
+ msModels.setSubAttributes("{}");
+ responseString = validation.validatePolicy(policyData).toString();
+ assertEquals("success@#", responseString);
+
+ msModels.setSubAttributes("{\"subAttrName0\": \"subAttrValue0\"}");
+ responseString = validation.validatePolicy(policyData).toString();
+ assertEquals("success@#", responseString);
+
+ msModels.setSubAttributes("{\"subAttrName0\": 10}");
+ responseString = validation.validatePolicy(policyData).toString();
+ assertEquals("success@#", responseString);
+
+ msModels.setSubAttributes("{\"subAttrName0\": {}}");
+ responseString = validation.validatePolicy(policyData).toString();
+ assertEquals("success@#", responseString);
+
+ msModels.setSubAttributes("{\"subAttrName0\": []}");
+ responseString = validation.validatePolicy(policyData).toString();
+ assertEquals("success@#", responseString);
+
+ msModels.setSubAttributes("{\"subAttrName0\": \"subAttrValue0-required-true\"}");
+ responseString = validation.validatePolicy(policyData).toString();
+ assertThat(responseString).contains("<b>Micro Service Model</b>:<i> subAttrName0 is required");
+
+ msModels.setSubAttributes("{\"subAttrName0\": \":subAttrValue0-required-true\"}");
+ responseString = validation.validatePolicy(policyData).toString();
+ assertThat(responseString).contains("<b>Micro Service Model</b>:<i> subAttrName0 is required");
+
+ msModels.setSubAttributes("{\"subAttrName0\": \"UnknownType:subAttrValue0-required-true\"}");
+ responseString = validation.validatePolicy(policyData).toString();
+ assertThat(responseString).contains("<b>Micro Service Model</b>:<i> subAttrName0 is required");
+
+ msModels.setSubAttributes("{\"subAttrName0\": \"string:subAttrValue0-required-true\"}");
+ responseString = validation.validatePolicy(policyData).toString();
+ assertThat(responseString).contains("<b>Micro Service Model</b>:<i> subAttrName0 is required");
+
+ msModels.setRefAttributes("refAttrName0=");
+ responseString = validation.validatePolicy(policyData).toString();
+ assertThat(responseString).contains("<b>Micro Service Model</b>:<i> subAttrName0 is required");
+
+ msModels.setRefAttributes("refAttrName0=refAttrValue0");
+ responseString = validation.validatePolicy(policyData).toString();
+ assertThat(responseString).contains("<b>Micro Service Model</b>:<i> subAttrName0 is required");
+
+ msModels.setRefAttributes("refAttrName0=refAttrValue0-required-true");
+ responseString = validation.validatePolicy(policyData).toString();
+ assertThat(responseString).contains("<b>Micro Service Model</b>:<i> subAttrName0 is required");
+
+ msModels.setAttributes("");
+ responseString = validation.validatePolicy(policyData).toString();
+ assertThat(responseString).contains("<b>Micro Service Model</b>:<i> subAttrName0 is required");
+
+ msModels.setAttributes("modelAttrName0=modelAttrValue0");
+ responseString = validation.validatePolicy(policyData).toString();
+ assertThat(responseString).contains("<b>Micro Service Model</b>:<i> subAttrName0 is required");
+
+ msModels.setRefAttributes("refAttrName0=refAttrValue0-required-true,");
+ responseString = validation.validatePolicy(policyData).toString();
+ assertThat(responseString).contains("refAttrName0 is required");
+
+ msModels.setRefAttributes("police-instance-range=refAttrValue0-required-true,");
+ responseString = validation.validatePolicy(policyData).toString();
+ assertThat(responseString).doesNotContain("police-instance-range is required");
+ }
}
diff --git a/ONAP-REST/src/test/resources/policies/DecisionPolicy.json b/ONAP-REST/src/test/resources/policies/DecisionPolicy.json
new file mode 100644
index 000000000..a316b0e7e
--- /dev/null
+++ b/ONAP-REST/src/test/resources/policies/DecisionPolicy.json
@@ -0,0 +1,1556 @@
+{
+ "policyData": {
+ "data": {
+ "description": "SampelGuardBLOne@CreatedBy:demo@CreatedBy:@ModifiedBy:demo@ModifiedBy:",
+ "policyIssuer": null,
+ "policyDefaults": null,
+ "target": {
+ "anyOf": [
+ {
+ "allOf": [
+ {
+ "match": [
+ {
+ "attributeValue": {
+ "content": [
+ "com.Decision_SampelGuardBLOne.4.xml"
+ ],
+ "dataType": "http://www.w3.org/2001/XMLSchema#string",
+ "otherAttributes": {
+ }
+ },
+ "attributeDesignator": {
+ "category": "urn:oasis:names:tc:xacml:1.0:subject-category:access-subject",
+ "attributeId": "PolicyName",
+ "dataType": "http://www.w3.org/2001/XMLSchema#string",
+ "issuer": null,
+ "mustBePresent": false
+ },
+ "attributeSelector": null,
+ "matchId": "org.onap.function.regex-match"
+ }
+ ]
+ },
+ {
+ "match": [
+ {
+ "attributeValue": {
+ "content": [
+ "Test"
+ ],
+ "dataType": "http://www.w3.org/2001/XMLSchema#string",
+ "otherAttributes": {
+ }
+ },
+ "attributeDesignator": {
+ "category": "urn:oasis:names:tc:xacml:1.0:subject-category:access-subject",
+ "attributeId": "ONAPName",
+ "dataType": "http://www.w3.org/2001/XMLSchema#string",
+ "issuer": null,
+ "mustBePresent": false
+ },
+ "attributeSelector": null,
+ "matchId": "org.onap.function.regex-match"
+ },
+ {
+ "attributeValue": {
+ "content": [
+ "(?i)testActor"
+ ],
+ "dataType": "http://www.w3.org/2001/XMLSchema#string",
+ "otherAttributes": {
+ }
+ },
+ "attributeDesignator": {
+ "category": "urn:oasis:names:tc:xacml:3.0:attribute-category:resource",
+ "attributeId": "actor",
+ "dataType": "http://www.w3.org/2001/XMLSchema#string",
+ "issuer": null,
+ "mustBePresent": false
+ },
+ "attributeSelector": null,
+ "matchId": "urn:oasis:names:tc:xacml:1.0:function:string-regexp-match"
+ },
+ {
+ "attributeValue": {
+ "content": [
+ "(?i)testRecipe"
+ ],
+ "dataType": "http://www.w3.org/2001/XMLSchema#string",
+ "otherAttributes": {
+ }
+ },
+ "attributeDesignator": {
+ "category": "urn:oasis:names:tc:xacml:3.0:attribute-category:resource",
+ "attributeId": "recipe",
+ "dataType": "http://www.w3.org/2001/XMLSchema#string",
+ "issuer": null,
+ "mustBePresent": false
+ },
+ "attributeSelector": null,
+ "matchId": "urn:oasis:names:tc:xacml:1.0:function:string-regexp-match"
+ },
+ {
+ "attributeValue": {
+ "content": [
+ "testCLName"
+ ],
+ "dataType": "http://www.w3.org/2001/XMLSchema#string",
+ "otherAttributes": {
+ }
+ },
+ "attributeDesignator": {
+ "category": "urn:oasis:names:tc:xacml:3.0:attribute-category:resource",
+ "attributeId": "clname",
+ "dataType": "http://www.w3.org/2001/XMLSchema#string",
+ "issuer": null,
+ "mustBePresent": false
+ },
+ "attributeSelector": null,
+ "matchId": "urn:oasis:names:tc:xacml:1.0:function:string-regexp-match"
+ },
+ {
+ "attributeValue": {
+ "content": [
+ "Use Manual Entry"
+ ],
+ "dataType": "http://www.w3.org/2001/XMLSchema#string",
+ "otherAttributes": {
+ }
+ },
+ "attributeDesignator": {
+ "category": "urn:oasis:names:tc:xacml:3.0:attribute-category:resource",
+ "attributeId": "blackListEntryType",
+ "dataType": "http://www.w3.org/2001/XMLSchema#string",
+ "issuer": null,
+ "mustBePresent": false
+ },
+ "attributeSelector": null,
+ "matchId": "urn:oasis:names:tc:xacml:1.0:function:string-regexp-match"
+ }
+ ]
+ }
+ ]
+ }
+ ]
+ },
+ "combinerParametersOrRuleCombinerParametersOrVariableDefinition": [
+ {
+ "description": null,
+ "target": {
+ "anyOf": [
+ {
+ "allOf": [
+ {
+ "match": [
+ {
+ "attributeValue": {
+ "content": [
+ "DECIDE"
+ ],
+ "dataType": "http://www.w3.org/2001/XMLSchema#string",
+ "otherAttributes": {
+ }
+ },
+ "attributeDesignator": {
+ "category": "urn:oasis:names:tc:xacml:3.0:attribute-category:action",
+ "attributeId": "urn:oasis:names:tc:xacml:1.0:action:action-id",
+ "dataType": "http://www.w3.org/2001/XMLSchema#string",
+ "issuer": null,
+ "mustBePresent": false
+ },
+ "attributeSelector": null,
+ "matchId": "urn:oasis:names:tc:xacml:3.0:function:string-equal-ignore-case"
+ }
+ ]
+ }
+ ]
+ }
+ ]
+ },
+ "condition": {
+ "expression": {
+ "name": "{urn:oasis:names:tc:xacml:3.0:core:schema:wd-17}Apply",
+ "declaredType": "oasis.names.tc.xacml._3_0.core.schema.wd_17.ApplyType",
+ "scope": "javax.xml.bind.JAXBElement$GlobalScope",
+ "value": {
+ "description": null,
+ "expression": [
+ {
+ "name": "{urn:oasis:names:tc:xacml:3.0:core:schema:wd-17}Apply",
+ "declaredType": "oasis.names.tc.xacml._3_0.core.schema.wd_17.ApplyType",
+ "scope": "javax.xml.bind.JAXBElement$GlobalScope",
+ "value": {
+ "description": null,
+ "expression": [
+ {
+ "name": "{urn:oasis:names:tc:xacml:3.0:core:schema:wd-17}Apply",
+ "declaredType": "oasis.names.tc.xacml._3_0.core.schema.wd_17.ApplyType",
+ "scope": "javax.xml.bind.JAXBElement$GlobalScope",
+ "value": {
+ "description": null,
+ "expression": [
+ {
+ "name": "{urn:oasis:names:tc:xacml:3.0:core:schema:wd-17}Apply",
+ "declaredType": "oasis.names.tc.xacml._3_0.core.schema.wd_17.ApplyType",
+ "scope": "javax.xml.bind.JAXBElement$GlobalScope",
+ "value": {
+ "description": null,
+ "expression": [
+ {
+ "name": "{urn:oasis:names:tc:xacml:3.0:core:schema:wd-17}AttributeDesignator",
+ "declaredType": "oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeDesignatorType",
+ "scope": "javax.xml.bind.JAXBElement$GlobalScope",
+ "value": {
+ "category": "urn:oasis:names:tc:xacml:3.0:attribute-category:environment",
+ "attributeId": "urn:oasis:names:tc:xacml:1.0:environment:current-time",
+ "dataType": "http://www.w3.org/2001/XMLSchema#time",
+ "issuer": null,
+ "mustBePresent": false
+ },
+ "nil": false,
+ "globalScope": true,
+ "typeSubstituted": false
+ }
+ ],
+ "functionId": "urn:oasis:names:tc:xacml:1.0:function:time-one-and-only"
+ },
+ "nil": false,
+ "globalScope": true,
+ "typeSubstituted": false
+ },
+ {
+ "name": "{urn:oasis:names:tc:xacml:3.0:core:schema:wd-17}AttributeValue",
+ "declaredType": "oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType",
+ "scope": "javax.xml.bind.JAXBElement$GlobalScope",
+ "value": {
+ "content": [
+ "5:00"
+ ],
+ "dataType": "http://www.w3.org/2001/XMLSchema#time",
+ "otherAttributes": {
+ }
+ },
+ "nil": false,
+ "globalScope": true,
+ "typeSubstituted": false
+ },
+ {
+ "name": "{urn:oasis:names:tc:xacml:3.0:core:schema:wd-17}AttributeValue",
+ "declaredType": "oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType",
+ "scope": "javax.xml.bind.JAXBElement$GlobalScope",
+ "value": {
+ "content": [
+ "10:00"
+ ],
+ "dataType": "http://www.w3.org/2001/XMLSchema#time",
+ "otherAttributes": {
+ }
+ },
+ "nil": false,
+ "globalScope": true,
+ "typeSubstituted": false
+ }
+ ],
+ "functionId": "urn:oasis:names:tc:xacml:2.0:function:time-in-range"
+ },
+ "nil": false,
+ "globalScope": true,
+ "typeSubstituted": false
+ },
+ {
+ "name": "{urn:oasis:names:tc:xacml:3.0:core:schema:wd-17}Apply",
+ "declaredType": "oasis.names.tc.xacml._3_0.core.schema.wd_17.ApplyType",
+ "scope": "javax.xml.bind.JAXBElement$GlobalScope",
+ "value": {
+ "description": null,
+ "expression": [
+ {
+ "name": "{urn:oasis:names:tc:xacml:3.0:core:schema:wd-17}Function",
+ "declaredType": "oasis.names.tc.xacml._3_0.core.schema.wd_17.FunctionType",
+ "scope": "javax.xml.bind.JAXBElement$GlobalScope",
+ "value": {
+ "functionId": "urn:oasis:names:tc:xacml:1.0:function:string-equal"
+ },
+ "nil": false,
+ "globalScope": true,
+ "typeSubstituted": false
+ },
+ {
+ "name": "{urn:oasis:names:tc:xacml:3.0:core:schema:wd-17}Apply",
+ "declaredType": "oasis.names.tc.xacml._3_0.core.schema.wd_17.ApplyType",
+ "scope": "javax.xml.bind.JAXBElement$GlobalScope",
+ "value": {
+ "description": null,
+ "expression": [
+ {
+ "name": "{urn:oasis:names:tc:xacml:3.0:core:schema:wd-17}AttributeDesignator",
+ "declaredType": "oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeDesignatorType",
+ "scope": "javax.xml.bind.JAXBElement$GlobalScope",
+ "value": {
+ "category": "urn:oasis:names:tc:xacml:3.0:attribute-category:resource",
+ "attributeId": "target",
+ "dataType": "http://www.w3.org/2001/XMLSchema#string",
+ "issuer": null,
+ "mustBePresent": false
+ },
+ "nil": false,
+ "globalScope": true,
+ "typeSubstituted": false
+ }
+ ],
+ "functionId": "urn:oasis:names:tc:xacml:1.0:function:string-one-and-only"
+ },
+ "nil": false,
+ "globalScope": true,
+ "typeSubstituted": false
+ },
+ {
+ "name": "{urn:oasis:names:tc:xacml:3.0:core:schema:wd-17}Apply",
+ "declaredType": "oasis.names.tc.xacml._3_0.core.schema.wd_17.ApplyType",
+ "scope": "javax.xml.bind.JAXBElement$GlobalScope",
+ "value": {
+ "description": null,
+ "expression": [
+ {
+ "name": "{urn:oasis:names:tc:xacml:3.0:core:schema:wd-17}AttributeValue",
+ "declaredType": "oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType",
+ "scope": "javax.xml.bind.JAXBElement$GlobalScope",
+ "value": {
+ "content": [
+ "testBL2"
+ ],
+ "dataType": "http://www.w3.org/2001/XMLSchema#string",
+ "otherAttributes": {
+ }
+ },
+ "nil": false,
+ "globalScope": true,
+ "typeSubstituted": false
+ },
+ {
+ "name": "{urn:oasis:names:tc:xacml:3.0:core:schema:wd-17}AttributeValue",
+ "declaredType": "oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType",
+ "scope": "javax.xml.bind.JAXBElement$GlobalScope",
+ "value": {
+ "content": [
+ "testBL3"
+ ],
+ "dataType": "http://www.w3.org/2001/XMLSchema#string",
+ "otherAttributes": {
+ }
+ },
+ "nil": false,
+ "globalScope": true,
+ "typeSubstituted": false
+ },
+ {
+ "name": "{urn:oasis:names:tc:xacml:3.0:core:schema:wd-17}AttributeValue",
+ "declaredType": "oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType",
+ "scope": "javax.xml.bind.JAXBElement$GlobalScope",
+ "value": {
+ "content": [
+ "testBL4"
+ ],
+ "dataType": "http://www.w3.org/2001/XMLSchema#string",
+ "otherAttributes": {
+ }
+ },
+ "nil": false,
+ "globalScope": true,
+ "typeSubstituted": false
+ }
+ ],
+ "functionId": "urn:oasis:names:tc:xacml:1.0:function:string-bag"
+ },
+ "nil": false,
+ "globalScope": true,
+ "typeSubstituted": false
+ }
+ ],
+ "functionId": "urn:oasis:names:tc:xacml:3.0:function:any-of"
+ },
+ "nil": false,
+ "globalScope": true,
+ "typeSubstituted": false
+ }
+ ],
+ "functionId": "urn:oasis:names:tc:xacml:1.0:function:and"
+ },
+ "nil": false,
+ "globalScope": true,
+ "typeSubstituted": false
+ }
+ ],
+ "functionId": "urn:oasis:names:tc:xacml:1.0:function:not"
+ },
+ "nil": false,
+ "globalScope": true,
+ "typeSubstituted": false
+ }
+ },
+ "obligationExpressions": null,
+ "adviceExpressions": null,
+ "ruleId": "urn:com:xacml:rule:id:284d9393-f861-4250-b62d-fc36640a363a",
+ "effect": "PERMIT"
+ },
+ {
+ "description": null,
+ "target": {
+ "anyOf": [
+ {
+ "allOf": [
+ {
+ "match": [
+ {
+ "attributeValue": {
+ "content": [
+ "DECIDE"
+ ],
+ "dataType": "http://www.w3.org/2001/XMLSchema#string",
+ "otherAttributes": {
+ }
+ },
+ "attributeDesignator": {
+ "category": "urn:oasis:names:tc:xacml:3.0:attribute-category:action",
+ "attributeId": "urn:oasis:names:tc:xacml:1.0:action:action-id",
+ "dataType": "http://www.w3.org/2001/XMLSchema#string",
+ "issuer": null,
+ "mustBePresent": false
+ },
+ "attributeSelector": null,
+ "matchId": "urn:oasis:names:tc:xacml:3.0:function:string-equal-ignore-case"
+ }
+ ]
+ }
+ ]
+ }
+ ]
+ },
+ "condition": {
+ "expression": {
+ "name": "{urn:oasis:names:tc:xacml:3.0:core:schema:wd-17}Apply",
+ "declaredType": "oasis.names.tc.xacml._3_0.core.schema.wd_17.ApplyType",
+ "scope": "javax.xml.bind.JAXBElement$GlobalScope",
+ "value": {
+ "description": null,
+ "expression": [
+ {
+ "name": "{urn:oasis:names:tc:xacml:3.0:core:schema:wd-17}Apply",
+ "declaredType": "oasis.names.tc.xacml._3_0.core.schema.wd_17.ApplyType",
+ "scope": "javax.xml.bind.JAXBElement$GlobalScope",
+ "value": {
+ "description": null,
+ "expression": [
+ {
+ "name": "{urn:oasis:names:tc:xacml:3.0:core:schema:wd-17}Apply",
+ "declaredType": "oasis.names.tc.xacml._3_0.core.schema.wd_17.ApplyType",
+ "scope": "javax.xml.bind.JAXBElement$GlobalScope",
+ "value": {
+ "description": null,
+ "expression": [
+ {
+ "name": "{urn:oasis:names:tc:xacml:3.0:core:schema:wd-17}Apply",
+ "declaredType": "oasis.names.tc.xacml._3_0.core.schema.wd_17.ApplyType",
+ "scope": "javax.xml.bind.JAXBElement$GlobalScope",
+ "value": {
+ "description": null,
+ "expression": [
+ {
+ "name": "{urn:oasis:names:tc:xacml:3.0:core:schema:wd-17}Apply",
+ "declaredType": "oasis.names.tc.xacml._3_0.core.schema.wd_17.ApplyType",
+ "scope": "javax.xml.bind.JAXBElement$GlobalScope",
+ "value": {
+ "description": null,
+ "expression": [
+ {
+ "name": "{urn:oasis:names:tc:xacml:3.0:core:schema:wd-17}AttributeDesignator",
+ "declaredType": "oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeDesignatorType",
+ "scope": "javax.xml.bind.JAXBElement$GlobalScope",
+ "value": {
+ "category": "urn:oasis:names:tc:xacml:3.0:attribute-category:environment",
+ "attributeId": "urn:oasis:names:tc:xacml:1.0:environment:current-time",
+ "dataType": "http://www.w3.org/2001/XMLSchema#time",
+ "issuer": null,
+ "mustBePresent": false
+ },
+ "nil": false,
+ "globalScope": true,
+ "typeSubstituted": false
+ }
+ ],
+ "functionId": "urn:oasis:names:tc:xacml:1.0:function:time-one-and-only"
+ },
+ "nil": false,
+ "globalScope": true,
+ "typeSubstituted": false
+ },
+ {
+ "name": "{urn:oasis:names:tc:xacml:3.0:core:schema:wd-17}AttributeValue",
+ "declaredType": "oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType",
+ "scope": "javax.xml.bind.JAXBElement$GlobalScope",
+ "value": {
+ "content": [
+ "5:00"
+ ],
+ "dataType": "http://www.w3.org/2001/XMLSchema#time",
+ "otherAttributes": {
+ }
+ },
+ "nil": false,
+ "globalScope": true,
+ "typeSubstituted": false
+ },
+ {
+ "name": "{urn:oasis:names:tc:xacml:3.0:core:schema:wd-17}AttributeValue",
+ "declaredType": "oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType",
+ "scope": "javax.xml.bind.JAXBElement$GlobalScope",
+ "value": {
+ "content": [
+ "10:00"
+ ],
+ "dataType": "http://www.w3.org/2001/XMLSchema#time",
+ "otherAttributes": {
+ }
+ },
+ "nil": false,
+ "globalScope": true,
+ "typeSubstituted": false
+ }
+ ],
+ "functionId": "urn:oasis:names:tc:xacml:2.0:function:time-in-range"
+ },
+ "nil": false,
+ "globalScope": true,
+ "typeSubstituted": false
+ },
+ {
+ "name": "{urn:oasis:names:tc:xacml:3.0:core:schema:wd-17}Apply",
+ "declaredType": "oasis.names.tc.xacml._3_0.core.schema.wd_17.ApplyType",
+ "scope": "javax.xml.bind.JAXBElement$GlobalScope",
+ "value": {
+ "description": null,
+ "expression": [
+ {
+ "name": "{urn:oasis:names:tc:xacml:3.0:core:schema:wd-17}Function",
+ "declaredType": "oasis.names.tc.xacml._3_0.core.schema.wd_17.FunctionType",
+ "scope": "javax.xml.bind.JAXBElement$GlobalScope",
+ "value": {
+ "functionId": "urn:oasis:names:tc:xacml:1.0:function:string-equal"
+ },
+ "nil": false,
+ "globalScope": true,
+ "typeSubstituted": false
+ },
+ {
+ "name": "{urn:oasis:names:tc:xacml:3.0:core:schema:wd-17}Apply",
+ "declaredType": "oasis.names.tc.xacml._3_0.core.schema.wd_17.ApplyType",
+ "scope": "javax.xml.bind.JAXBElement$GlobalScope",
+ "value": {
+ "description": null,
+ "expression": [
+ {
+ "name": "{urn:oasis:names:tc:xacml:3.0:core:schema:wd-17}AttributeDesignator",
+ "declaredType": "oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeDesignatorType",
+ "scope": "javax.xml.bind.JAXBElement$GlobalScope",
+ "value": {
+ "category": "urn:oasis:names:tc:xacml:3.0:attribute-category:resource",
+ "attributeId": "target",
+ "dataType": "http://www.w3.org/2001/XMLSchema#string",
+ "issuer": null,
+ "mustBePresent": false
+ },
+ "nil": false,
+ "globalScope": true,
+ "typeSubstituted": false
+ }
+ ],
+ "functionId": "urn:oasis:names:tc:xacml:1.0:function:string-one-and-only"
+ },
+ "nil": false,
+ "globalScope": true,
+ "typeSubstituted": false
+ },
+ {
+ "name": "{urn:oasis:names:tc:xacml:3.0:core:schema:wd-17}Apply",
+ "declaredType": "oasis.names.tc.xacml._3_0.core.schema.wd_17.ApplyType",
+ "scope": "javax.xml.bind.JAXBElement$GlobalScope",
+ "value": {
+ "description": null,
+ "expression": [
+ {
+ "name": "{urn:oasis:names:tc:xacml:3.0:core:schema:wd-17}AttributeValue",
+ "declaredType": "oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType",
+ "scope": "javax.xml.bind.JAXBElement$GlobalScope",
+ "value": {
+ "content": [
+ "testBL2"
+ ],
+ "dataType": "http://www.w3.org/2001/XMLSchema#string",
+ "otherAttributes": {
+ }
+ },
+ "nil": false,
+ "globalScope": true,
+ "typeSubstituted": false
+ },
+ {
+ "name": "{urn:oasis:names:tc:xacml:3.0:core:schema:wd-17}AttributeValue",
+ "declaredType": "oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType",
+ "scope": "javax.xml.bind.JAXBElement$GlobalScope",
+ "value": {
+ "content": [
+ "testBL3"
+ ],
+ "dataType": "http://www.w3.org/2001/XMLSchema#string",
+ "otherAttributes": {
+ }
+ },
+ "nil": false,
+ "globalScope": true,
+ "typeSubstituted": false
+ },
+ {
+ "name": "{urn:oasis:names:tc:xacml:3.0:core:schema:wd-17}AttributeValue",
+ "declaredType": "oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType",
+ "scope": "javax.xml.bind.JAXBElement$GlobalScope",
+ "value": {
+ "content": [
+ "testBL4"
+ ],
+ "dataType": "http://www.w3.org/2001/XMLSchema#string",
+ "otherAttributes": {
+ }
+ },
+ "nil": false,
+ "globalScope": true,
+ "typeSubstituted": false
+ }
+ ],
+ "functionId": "urn:oasis:names:tc:xacml:1.0:function:string-bag"
+ },
+ "nil": false,
+ "globalScope": true,
+ "typeSubstituted": false
+ }
+ ],
+ "functionId": "urn:oasis:names:tc:xacml:3.0:function:any-of"
+ },
+ "nil": false,
+ "globalScope": true,
+ "typeSubstituted": false
+ }
+ ],
+ "functionId": "urn:oasis:names:tc:xacml:1.0:function:and"
+ },
+ "nil": false,
+ "globalScope": true,
+ "typeSubstituted": false
+ }
+ ],
+ "functionId": "urn:oasis:names:tc:xacml:1.0:function:not"
+ },
+ "nil": false,
+ "globalScope": true,
+ "typeSubstituted": false
+ }
+ ],
+ "functionId": "urn:oasis:names:tc:xacml:1.0:function:not"
+ },
+ "nil": false,
+ "globalScope": true,
+ "typeSubstituted": false
+ }
+ },
+ "obligationExpressions": null,
+ "adviceExpressions": {
+ "adviceExpression": [
+ {
+ "attributeAssignmentExpression": [
+ {
+ "expression": {
+ "name": "{urn:oasis:names:tc:xacml:3.0:core:schema:wd-17}AttributeValue",
+ "declaredType": "oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType",
+ "scope": "javax.xml.bind.JAXBElement$GlobalScope",
+ "value": {
+ "content": [
+ "Denied!"
+ ],
+ "dataType": "http://www.w3.org/2001/XMLSchema#string",
+ "otherAttributes": {
+ }
+ },
+ "nil": false,
+ "globalScope": true,
+ "typeSubstituted": false
+ },
+ "attributeId": "guard.response",
+ "category": "urn:oasis:names:tc:xacml:3.0:attribute-category:resource",
+ "issuer": null
+ }
+ ],
+ "adviceId": "GUARD_BL_YAML",
+ "appliesTo": "DENY"
+ }
+ ]
+ },
+ "ruleId": "urn:com:xacml:rule:id:284d9393-f861-4250-b62d-fc36640a363a",
+ "effect": "DENY"
+ }
+ ],
+ "obligationExpressions": null,
+ "adviceExpressions": null,
+ "policyId": "urn:com:xacml:policy:id:d56af069-6cf1-430c-ba07-e26602e06a52",
+ "version": "4",
+ "ruleCombiningAlgId": "urn:oasis:names:tc:xacml:3.0:rule-combining-algorithm:permit-overrides",
+ "maxDelegationDepth": null
+ },
+ "policyName": "SampelGuardBLOne",
+ "configBodyData": null,
+ "configType": null,
+ "policyID": null,
+ "policyType": "Decision",
+ "comboPolicyType": null,
+ "configPolicyType": null,
+ "policyDescription": "SampelGuardBLOne",
+ "onapName": "Test",
+ "configName": null,
+ "ruleID": null,
+ "parentPath": null,
+ "adminNotification": null,
+ "policyData": {
+ "description": "SampelGuardBLOne@CreatedBy:demo@CreatedBy:@ModifiedBy:demo@ModifiedBy:",
+ "policyIssuer": null,
+ "policyDefaults": null,
+ "target": {
+ "anyOf": [
+ {
+ "allOf": [
+ {
+ "match": [
+ {
+ "attributeValue": {
+ "content": [
+ "com.Decision_SampelGuardBLOne.4.xml"
+ ],
+ "dataType": "http://www.w3.org/2001/XMLSchema#string",
+ "otherAttributes": {
+ }
+ },
+ "attributeDesignator": {
+ "category": "urn:oasis:names:tc:xacml:1.0:subject-category:access-subject",
+ "attributeId": "PolicyName",
+ "dataType": "http://www.w3.org/2001/XMLSchema#string",
+ "issuer": null,
+ "mustBePresent": false
+ },
+ "attributeSelector": null,
+ "matchId": "org.onap.function.regex-match"
+ }
+ ]
+ },
+ {
+ "match": [
+ {
+ "attributeValue": {
+ "content": [
+ "Test"
+ ],
+ "dataType": "http://www.w3.org/2001/XMLSchema#string",
+ "otherAttributes": {
+ }
+ },
+ "attributeDesignator": {
+ "category": "urn:oasis:names:tc:xacml:1.0:subject-category:access-subject",
+ "attributeId": "ONAPName",
+ "dataType": "http://www.w3.org/2001/XMLSchema#string",
+ "issuer": null,
+ "mustBePresent": false
+ },
+ "attributeSelector": null,
+ "matchId": "org.onap.function.regex-match"
+ },
+ {
+ "attributeValue": {
+ "content": [
+ "(?i)testActor"
+ ],
+ "dataType": "http://www.w3.org/2001/XMLSchema#string",
+ "otherAttributes": {
+ }
+ },
+ "attributeDesignator": {
+ "category": "urn:oasis:names:tc:xacml:3.0:attribute-category:resource",
+ "attributeId": "actor",
+ "dataType": "http://www.w3.org/2001/XMLSchema#string",
+ "issuer": null,
+ "mustBePresent": false
+ },
+ "attributeSelector": null,
+ "matchId": "urn:oasis:names:tc:xacml:1.0:function:string-regexp-match"
+ },
+ {
+ "attributeValue": {
+ "content": [
+ "(?i)testRecipe"
+ ],
+ "dataType": "http://www.w3.org/2001/XMLSchema#string",
+ "otherAttributes": {
+ }
+ },
+ "attributeDesignator": {
+ "category": "urn:oasis:names:tc:xacml:3.0:attribute-category:resource",
+ "attributeId": "recipe",
+ "dataType": "http://www.w3.org/2001/XMLSchema#string",
+ "issuer": null,
+ "mustBePresent": false
+ },
+ "attributeSelector": null,
+ "matchId": "urn:oasis:names:tc:xacml:1.0:function:string-regexp-match"
+ },
+ {
+ "attributeValue": {
+ "content": [
+ "testCLName"
+ ],
+ "dataType": "http://www.w3.org/2001/XMLSchema#string",
+ "otherAttributes": {
+ }
+ },
+ "attributeDesignator": {
+ "category": "urn:oasis:names:tc:xacml:3.0:attribute-category:resource",
+ "attributeId": "clname",
+ "dataType": "http://www.w3.org/2001/XMLSchema#string",
+ "issuer": null,
+ "mustBePresent": false
+ },
+ "attributeSelector": null,
+ "matchId": "urn:oasis:names:tc:xacml:1.0:function:string-regexp-match"
+ },
+ {
+ "attributeValue": {
+ "content": [
+ "Use Manual Entry"
+ ],
+ "dataType": "http://www.w3.org/2001/XMLSchema#string",
+ "otherAttributes": {
+ }
+ },
+ "attributeDesignator": {
+ "category": "urn:oasis:names:tc:xacml:3.0:attribute-category:resource",
+ "attributeId": "blackListEntryType",
+ "dataType": "http://www.w3.org/2001/XMLSchema#string",
+ "issuer": null,
+ "mustBePresent": false
+ },
+ "attributeSelector": null,
+ "matchId": "urn:oasis:names:tc:xacml:1.0:function:string-regexp-match"
+ }
+ ]
+ }
+ ]
+ }
+ ]
+ },
+ "combinerParametersOrRuleCombinerParametersOrVariableDefinition": [
+ {
+ "description": null,
+ "target": {
+ "anyOf": [
+ {
+ "allOf": [
+ {
+ "match": [
+ {
+ "attributeValue": {
+ "content": [
+ "DECIDE"
+ ],
+ "dataType": "http://www.w3.org/2001/XMLSchema#string",
+ "otherAttributes": {
+ }
+ },
+ "attributeDesignator": {
+ "category": "urn:oasis:names:tc:xacml:3.0:attribute-category:action",
+ "attributeId": "urn:oasis:names:tc:xacml:1.0:action:action-id",
+ "dataType": "http://www.w3.org/2001/XMLSchema#string",
+ "issuer": null,
+ "mustBePresent": false
+ },
+ "attributeSelector": null,
+ "matchId": "urn:oasis:names:tc:xacml:3.0:function:string-equal-ignore-case"
+ }
+ ]
+ }
+ ]
+ }
+ ]
+ },
+ "condition": {
+ "expression": {
+ "name": "{urn:oasis:names:tc:xacml:3.0:core:schema:wd-17}Apply",
+ "declaredType": "oasis.names.tc.xacml._3_0.core.schema.wd_17.ApplyType",
+ "scope": "javax.xml.bind.JAXBElement$GlobalScope",
+ "value": {
+ "description": null,
+ "expression": [
+ {
+ "name": "{urn:oasis:names:tc:xacml:3.0:core:schema:wd-17}Apply",
+ "declaredType": "oasis.names.tc.xacml._3_0.core.schema.wd_17.ApplyType",
+ "scope": "javax.xml.bind.JAXBElement$GlobalScope",
+ "value": {
+ "description": null,
+ "expression": [
+ {
+ "name": "{urn:oasis:names:tc:xacml:3.0:core:schema:wd-17}Apply",
+ "declaredType": "oasis.names.tc.xacml._3_0.core.schema.wd_17.ApplyType",
+ "scope": "javax.xml.bind.JAXBElement$GlobalScope",
+ "value": {
+ "description": null,
+ "expression": [
+ {
+ "name": "{urn:oasis:names:tc:xacml:3.0:core:schema:wd-17}Apply",
+ "declaredType": "oasis.names.tc.xacml._3_0.core.schema.wd_17.ApplyType",
+ "scope": "javax.xml.bind.JAXBElement$GlobalScope",
+ "value": {
+ "description": null,
+ "expression": [
+ {
+ "name": "{urn:oasis:names:tc:xacml:3.0:core:schema:wd-17}AttributeDesignator",
+ "declaredType": "oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeDesignatorType",
+ "scope": "javax.xml.bind.JAXBElement$GlobalScope",
+ "value": {
+ "category": "urn:oasis:names:tc:xacml:3.0:attribute-category:environment",
+ "attributeId": "urn:oasis:names:tc:xacml:1.0:environment:current-time",
+ "dataType": "http://www.w3.org/2001/XMLSchema#time",
+ "issuer": null,
+ "mustBePresent": false
+ },
+ "nil": false,
+ "globalScope": true,
+ "typeSubstituted": false
+ }
+ ],
+ "functionId": "urn:oasis:names:tc:xacml:1.0:function:time-one-and-only"
+ },
+ "nil": false,
+ "globalScope": true,
+ "typeSubstituted": false
+ },
+ {
+ "name": "{urn:oasis:names:tc:xacml:3.0:core:schema:wd-17}AttributeValue",
+ "declaredType": "oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType",
+ "scope": "javax.xml.bind.JAXBElement$GlobalScope",
+ "value": {
+ "content": [
+ "5:00"
+ ],
+ "dataType": "http://www.w3.org/2001/XMLSchema#time",
+ "otherAttributes": {
+ }
+ },
+ "nil": false,
+ "globalScope": true,
+ "typeSubstituted": false
+ },
+ {
+ "name": "{urn:oasis:names:tc:xacml:3.0:core:schema:wd-17}AttributeValue",
+ "declaredType": "oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType",
+ "scope": "javax.xml.bind.JAXBElement$GlobalScope",
+ "value": {
+ "content": [
+ "10:00"
+ ],
+ "dataType": "http://www.w3.org/2001/XMLSchema#time",
+ "otherAttributes": {
+ }
+ },
+ "nil": false,
+ "globalScope": true,
+ "typeSubstituted": false
+ }
+ ],
+ "functionId": "urn:oasis:names:tc:xacml:2.0:function:time-in-range"
+ },
+ "nil": false,
+ "globalScope": true,
+ "typeSubstituted": false
+ },
+ {
+ "name": "{urn:oasis:names:tc:xacml:3.0:core:schema:wd-17}Apply",
+ "declaredType": "oasis.names.tc.xacml._3_0.core.schema.wd_17.ApplyType",
+ "scope": "javax.xml.bind.JAXBElement$GlobalScope",
+ "value": {
+ "description": null,
+ "expression": [
+ {
+ "name": "{urn:oasis:names:tc:xacml:3.0:core:schema:wd-17}Function",
+ "declaredType": "oasis.names.tc.xacml._3_0.core.schema.wd_17.FunctionType",
+ "scope": "javax.xml.bind.JAXBElement$GlobalScope",
+ "value": {
+ "functionId": "urn:oasis:names:tc:xacml:1.0:function:string-equal"
+ },
+ "nil": false,
+ "globalScope": true,
+ "typeSubstituted": false
+ },
+ {
+ "name": "{urn:oasis:names:tc:xacml:3.0:core:schema:wd-17}Apply",
+ "declaredType": "oasis.names.tc.xacml._3_0.core.schema.wd_17.ApplyType",
+ "scope": "javax.xml.bind.JAXBElement$GlobalScope",
+ "value": {
+ "description": null,
+ "expression": [
+ {
+ "name": "{urn:oasis:names:tc:xacml:3.0:core:schema:wd-17}AttributeDesignator",
+ "declaredType": "oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeDesignatorType",
+ "scope": "javax.xml.bind.JAXBElement$GlobalScope",
+ "value": {
+ "category": "urn:oasis:names:tc:xacml:3.0:attribute-category:resource",
+ "attributeId": "target",
+ "dataType": "http://www.w3.org/2001/XMLSchema#string",
+ "issuer": null,
+ "mustBePresent": false
+ },
+ "nil": false,
+ "globalScope": true,
+ "typeSubstituted": false
+ }
+ ],
+ "functionId": "urn:oasis:names:tc:xacml:1.0:function:string-one-and-only"
+ },
+ "nil": false,
+ "globalScope": true,
+ "typeSubstituted": false
+ },
+ {
+ "name": "{urn:oasis:names:tc:xacml:3.0:core:schema:wd-17}Apply",
+ "declaredType": "oasis.names.tc.xacml._3_0.core.schema.wd_17.ApplyType",
+ "scope": "javax.xml.bind.JAXBElement$GlobalScope",
+ "value": {
+ "description": null,
+ "expression": [
+ {
+ "name": "{urn:oasis:names:tc:xacml:3.0:core:schema:wd-17}AttributeValue",
+ "declaredType": "oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType",
+ "scope": "javax.xml.bind.JAXBElement$GlobalScope",
+ "value": {
+ "content": [
+ "testBL2"
+ ],
+ "dataType": "http://www.w3.org/2001/XMLSchema#string",
+ "otherAttributes": {
+ }
+ },
+ "nil": false,
+ "globalScope": true,
+ "typeSubstituted": false
+ },
+ {
+ "name": "{urn:oasis:names:tc:xacml:3.0:core:schema:wd-17}AttributeValue",
+ "declaredType": "oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType",
+ "scope": "javax.xml.bind.JAXBElement$GlobalScope",
+ "value": {
+ "content": [
+ "testBL3"
+ ],
+ "dataType": "http://www.w3.org/2001/XMLSchema#string",
+ "otherAttributes": {
+ }
+ },
+ "nil": false,
+ "globalScope": true,
+ "typeSubstituted": false
+ },
+ {
+ "name": "{urn:oasis:names:tc:xacml:3.0:core:schema:wd-17}AttributeValue",
+ "declaredType": "oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType",
+ "scope": "javax.xml.bind.JAXBElement$GlobalScope",
+ "value": {
+ "content": [
+ "testBL4"
+ ],
+ "dataType": "http://www.w3.org/2001/XMLSchema#string",
+ "otherAttributes": {
+ }
+ },
+ "nil": false,
+ "globalScope": true,
+ "typeSubstituted": false
+ }
+ ],
+ "functionId": "urn:oasis:names:tc:xacml:1.0:function:string-bag"
+ },
+ "nil": false,
+ "globalScope": true,
+ "typeSubstituted": false
+ }
+ ],
+ "functionId": "urn:oasis:names:tc:xacml:3.0:function:any-of"
+ },
+ "nil": false,
+ "globalScope": true,
+ "typeSubstituted": false
+ }
+ ],
+ "functionId": "urn:oasis:names:tc:xacml:1.0:function:and"
+ },
+ "nil": false,
+ "globalScope": true,
+ "typeSubstituted": false
+ }
+ ],
+ "functionId": "urn:oasis:names:tc:xacml:1.0:function:not"
+ },
+ "nil": false,
+ "globalScope": true,
+ "typeSubstituted": false
+ }
+ },
+ "obligationExpressions": null,
+ "adviceExpressions": null,
+ "ruleId": "urn:com:xacml:rule:id:284d9393-f861-4250-b62d-fc36640a363a",
+ "effect": "PERMIT"
+ },
+ {
+ "description": null,
+ "target": {
+ "anyOf": [
+ {
+ "allOf": [
+ {
+ "match": [
+ {
+ "attributeValue": {
+ "content": [
+ "DECIDE"
+ ],
+ "dataType": "http://www.w3.org/2001/XMLSchema#string",
+ "otherAttributes": {
+ }
+ },
+ "attributeDesignator": {
+ "category": "urn:oasis:names:tc:xacml:3.0:attribute-category:action",
+ "attributeId": "urn:oasis:names:tc:xacml:1.0:action:action-id",
+ "dataType": "http://www.w3.org/2001/XMLSchema#string",
+ "issuer": null,
+ "mustBePresent": false
+ },
+ "attributeSelector": null,
+ "matchId": "urn:oasis:names:tc:xacml:3.0:function:string-equal-ignore-case"
+ }
+ ]
+ }
+ ]
+ }
+ ]
+ },
+ "condition": {
+ "expression": {
+ "name": "{urn:oasis:names:tc:xacml:3.0:core:schema:wd-17}Apply",
+ "declaredType": "oasis.names.tc.xacml._3_0.core.schema.wd_17.ApplyType",
+ "scope": "javax.xml.bind.JAXBElement$GlobalScope",
+ "value": {
+ "description": null,
+ "expression": [
+ {
+ "name": "{urn:oasis:names:tc:xacml:3.0:core:schema:wd-17}Apply",
+ "declaredType": "oasis.names.tc.xacml._3_0.core.schema.wd_17.ApplyType",
+ "scope": "javax.xml.bind.JAXBElement$GlobalScope",
+ "value": {
+ "description": null,
+ "expression": [
+ {
+ "name": "{urn:oasis:names:tc:xacml:3.0:core:schema:wd-17}Apply",
+ "declaredType": "oasis.names.tc.xacml._3_0.core.schema.wd_17.ApplyType",
+ "scope": "javax.xml.bind.JAXBElement$GlobalScope",
+ "value": {
+ "description": null,
+ "expression": [
+ {
+ "name": "{urn:oasis:names:tc:xacml:3.0:core:schema:wd-17}Apply",
+ "declaredType": "oasis.names.tc.xacml._3_0.core.schema.wd_17.ApplyType",
+ "scope": "javax.xml.bind.JAXBElement$GlobalScope",
+ "value": {
+ "description": null,
+ "expression": [
+ {
+ "name": "{urn:oasis:names:tc:xacml:3.0:core:schema:wd-17}Apply",
+ "declaredType": "oasis.names.tc.xacml._3_0.core.schema.wd_17.ApplyType",
+ "scope": "javax.xml.bind.JAXBElement$GlobalScope",
+ "value": {
+ "description": null,
+ "expression": [
+ {
+ "name": "{urn:oasis:names:tc:xacml:3.0:core:schema:wd-17}AttributeDesignator",
+ "declaredType": "oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeDesignatorType",
+ "scope": "javax.xml.bind.JAXBElement$GlobalScope",
+ "value": {
+ "category": "urn:oasis:names:tc:xacml:3.0:attribute-category:environment",
+ "attributeId": "urn:oasis:names:tc:xacml:1.0:environment:current-time",
+ "dataType": "http://www.w3.org/2001/XMLSchema#time",
+ "issuer": null,
+ "mustBePresent": false
+ },
+ "nil": false,
+ "globalScope": true,
+ "typeSubstituted": false
+ }
+ ],
+ "functionId": "urn:oasis:names:tc:xacml:1.0:function:time-one-and-only"
+ },
+ "nil": false,
+ "globalScope": true,
+ "typeSubstituted": false
+ },
+ {
+ "name": "{urn:oasis:names:tc:xacml:3.0:core:schema:wd-17}AttributeValue",
+ "declaredType": "oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType",
+ "scope": "javax.xml.bind.JAXBElement$GlobalScope",
+ "value": {
+ "content": [
+ "5:00"
+ ],
+ "dataType": "http://www.w3.org/2001/XMLSchema#time",
+ "otherAttributes": {
+ }
+ },
+ "nil": false,
+ "globalScope": true,
+ "typeSubstituted": false
+ },
+ {
+ "name": "{urn:oasis:names:tc:xacml:3.0:core:schema:wd-17}AttributeValue",
+ "declaredType": "oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType",
+ "scope": "javax.xml.bind.JAXBElement$GlobalScope",
+ "value": {
+ "content": [
+ "10:00"
+ ],
+ "dataType": "http://www.w3.org/2001/XMLSchema#time",
+ "otherAttributes": {
+ }
+ },
+ "nil": false,
+ "globalScope": true,
+ "typeSubstituted": false
+ }
+ ],
+ "functionId": "urn:oasis:names:tc:xacml:2.0:function:time-in-range"
+ },
+ "nil": false,
+ "globalScope": true,
+ "typeSubstituted": false
+ },
+ {
+ "name": "{urn:oasis:names:tc:xacml:3.0:core:schema:wd-17}Apply",
+ "declaredType": "oasis.names.tc.xacml._3_0.core.schema.wd_17.ApplyType",
+ "scope": "javax.xml.bind.JAXBElement$GlobalScope",
+ "value": {
+ "description": null,
+ "expression": [
+ {
+ "name": "{urn:oasis:names:tc:xacml:3.0:core:schema:wd-17}Function",
+ "declaredType": "oasis.names.tc.xacml._3_0.core.schema.wd_17.FunctionType",
+ "scope": "javax.xml.bind.JAXBElement$GlobalScope",
+ "value": {
+ "functionId": "urn:oasis:names:tc:xacml:1.0:function:string-equal"
+ },
+ "nil": false,
+ "globalScope": true,
+ "typeSubstituted": false
+ },
+ {
+ "name": "{urn:oasis:names:tc:xacml:3.0:core:schema:wd-17}Apply",
+ "declaredType": "oasis.names.tc.xacml._3_0.core.schema.wd_17.ApplyType",
+ "scope": "javax.xml.bind.JAXBElement$GlobalScope",
+ "value": {
+ "description": null,
+ "expression": [
+ {
+ "name": "{urn:oasis:names:tc:xacml:3.0:core:schema:wd-17}AttributeDesignator",
+ "declaredType": "oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeDesignatorType",
+ "scope": "javax.xml.bind.JAXBElement$GlobalScope",
+ "value": {
+ "category": "urn:oasis:names:tc:xacml:3.0:attribute-category:resource",
+ "attributeId": "target",
+ "dataType": "http://www.w3.org/2001/XMLSchema#string",
+ "issuer": null,
+ "mustBePresent": false
+ },
+ "nil": false,
+ "globalScope": true,
+ "typeSubstituted": false
+ }
+ ],
+ "functionId": "urn:oasis:names:tc:xacml:1.0:function:string-one-and-only"
+ },
+ "nil": false,
+ "globalScope": true,
+ "typeSubstituted": false
+ },
+ {
+ "name": "{urn:oasis:names:tc:xacml:3.0:core:schema:wd-17}Apply",
+ "declaredType": "oasis.names.tc.xacml._3_0.core.schema.wd_17.ApplyType",
+ "scope": "javax.xml.bind.JAXBElement$GlobalScope",
+ "value": {
+ "description": null,
+ "expression": [
+ {
+ "name": "{urn:oasis:names:tc:xacml:3.0:core:schema:wd-17}AttributeValue",
+ "declaredType": "oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType",
+ "scope": "javax.xml.bind.JAXBElement$GlobalScope",
+ "value": {
+ "content": [
+ "testBL2"
+ ],
+ "dataType": "http://www.w3.org/2001/XMLSchema#string",
+ "otherAttributes": {
+ }
+ },
+ "nil": false,
+ "globalScope": true,
+ "typeSubstituted": false
+ },
+ {
+ "name": "{urn:oasis:names:tc:xacml:3.0:core:schema:wd-17}AttributeValue",
+ "declaredType": "oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType",
+ "scope": "javax.xml.bind.JAXBElement$GlobalScope",
+ "value": {
+ "content": [
+ "testBL3"
+ ],
+ "dataType": "http://www.w3.org/2001/XMLSchema#string",
+ "otherAttributes": {
+ }
+ },
+ "nil": false,
+ "globalScope": true,
+ "typeSubstituted": false
+ },
+ {
+ "name": "{urn:oasis:names:tc:xacml:3.0:core:schema:wd-17}AttributeValue",
+ "declaredType": "oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType",
+ "scope": "javax.xml.bind.JAXBElement$GlobalScope",
+ "value": {
+ "content": [
+ "testBL4"
+ ],
+ "dataType": "http://www.w3.org/2001/XMLSchema#string",
+ "otherAttributes": {
+ }
+ },
+ "nil": false,
+ "globalScope": true,
+ "typeSubstituted": false
+ }
+ ],
+ "functionId": "urn:oasis:names:tc:xacml:1.0:function:string-bag"
+ },
+ "nil": false,
+ "globalScope": true,
+ "typeSubstituted": false
+ }
+ ],
+ "functionId": "urn:oasis:names:tc:xacml:3.0:function:any-of"
+ },
+ "nil": false,
+ "globalScope": true,
+ "typeSubstituted": false
+ }
+ ],
+ "functionId": "urn:oasis:names:tc:xacml:1.0:function:and"
+ },
+ "nil": false,
+ "globalScope": true,
+ "typeSubstituted": false
+ }
+ ],
+ "functionId": "urn:oasis:names:tc:xacml:1.0:function:not"
+ },
+ "nil": false,
+ "globalScope": true,
+ "typeSubstituted": false
+ }
+ ],
+ "functionId": "urn:oasis:names:tc:xacml:1.0:function:not"
+ },
+ "nil": false,
+ "globalScope": true,
+ "typeSubstituted": false
+ }
+ },
+ "obligationExpressions": null,
+ "adviceExpressions": {
+ "adviceExpression": [
+ {
+ "attributeAssignmentExpression": [
+ {
+ "expression": {
+ "name": "{urn:oasis:names:tc:xacml:3.0:core:schema:wd-17}AttributeValue",
+ "declaredType": "oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType",
+ "scope": "javax.xml.bind.JAXBElement$GlobalScope",
+ "value": {
+ "content": [
+ "Denied!"
+ ],
+ "dataType": "http://www.w3.org/2001/XMLSchema#string",
+ "otherAttributes": {
+ }
+ },
+ "nil": false,
+ "globalScope": true,
+ "typeSubstituted": false
+ },
+ "attributeId": "guard.response",
+ "category": "urn:oasis:names:tc:xacml:3.0:attribute-category:resource",
+ "issuer": null
+ }
+ ],
+ "adviceId": "GUARD_BL_YAML",
+ "appliesTo": "DENY"
+ }
+ ]
+ },
+ "ruleId": "urn:com:xacml:rule:id:284d9393-f861-4250-b62d-fc36640a363a",
+ "effect": "DENY"
+ }
+ ],
+ "obligationExpressions": null,
+ "adviceExpressions": null,
+ "policyId": "urn:com:xacml:policy:id:d56af069-6cf1-430c-ba07-e26602e06a52",
+ "version": "4",
+ "ruleCombiningAlgId": "urn:oasis:names:tc:xacml:3.0:rule-combining-algorithm:permit-overrides",
+ "maxDelegationDepth": null
+ },
+ "gitPath": null,
+ "readOnly": false,
+ "configHome": null,
+ "configUrl": null,
+ "finalPolicyPath": null,
+ "version": null,
+ "jsonBody": null,
+ "apiflag": null,
+ "prevJsonBody": null,
+ "highestVersion": null,
+ "entityManagerFactory": null,
+ "policyExists": false,
+ "oldPolicyFileName": "Decision_SampelGuardBLOne",
+ "userId": null,
+ "newFileName": null,
+ "clWarning": null,
+ "newCLName": null,
+ "existingCLName": null,
+ "onapNameField": null,
+ "jsonBodyData": null,
+ "dirPath": null,
+ "configBodyPath": null,
+ "attributes": [
+ ],
+ "settings": [
+ ],
+ "ruleAlgorithmschoices": [
+ ],
+ "serviceTypePolicyName": null,
+ "verticaMetrics": null,
+ "description": null,
+ "attributeFields": null,
+ "clearTimeOut": null,
+ "trapMaxAge": null,
+ "verificationclearTimeOut": null,
+ "dynamicLayoutMap": null,
+ "trapDatas": null,
+ "faultDatas": null,
+ "fwPolicyType": null,
+ "fwattributes": null,
+ "parentForChild": null,
+ "securityZone": null,
+ "ruleCombiningAlgId": null,
+ "dynamicFieldConfigAttributes": null,
+ "dynamicSettingsMap": null,
+ "dropDownMap": null,
+ "actionPerformer": null,
+ "actionAttribute": null,
+ "dynamicRuleAlgorithmLabels": null,
+ "dynamicRuleAlgorithmCombo": null,
+ "dynamicRuleAlgorithmField1": null,
+ "dynamicRuleAlgorithmField2": null,
+ "dynamicVariableList": null,
+ "dataTypeList": null,
+ "actionAttributeValue": null,
+ "ruleProvider": "GUARD_BL_YAML",
+ "actionBody": null,
+ "actionDictHeader": null,
+ "actionDictType": null,
+ "actionDictUrl": null,
+ "actionDictMethod": null,
+ "yamlparams": {
+ "actor": "testActor",
+ "recipe": "testRecipe",
+ "clname": "testCLName",
+ "limit": null,
+ "timeWindow": null,
+ "timeUnits": null,
+ "guardActiveStart": "5:00",
+ "guardActiveEnd": "10:00",
+ "blackList": [
+ "testBL2",
+ "testBL3",
+ "testBL4"
+ ],
+ "targets": null,
+ "blackListEntryType": "Use Manual Entry"
+ },
+ "blackListEntries": [
+ ],
+ "appendBlackListEntries": [
+ ],
+ "rainyday": {
+ "serviceType": null,
+ "vnfType": null,
+ "bbid": null,
+ "workstep": null,
+ "treatmentTableChoices": [
+ ],
+ "errorcode": null,
+ "treatment": null
+ },
+ "rainydayMap": null,
+ "errorCodeList": null,
+ "treatmentList": null,
+ "serviceType": null,
+ "uuid": null,
+ "location": null,
+ "priority": null,
+ "msLocation": null,
+ "policyJSON": null,
+ "ruleName": null,
+ "brmsParamBody": null,
+ "brmsController": null,
+ "brmsDependency": null,
+ "ruleData": null,
+ "ruleListData": null,
+ "drlRuleAndUIParams": null,
+ "policyScope": null,
+ "providerComboBox": null,
+ "riskType": null,
+ "riskLevel": null,
+ "guard": null,
+ "ttlDate": null,
+ "matching": null,
+ "triggerSignatures": null,
+ "symptomSignatures": null,
+ "logicalConnector": null,
+ "policyStatus": null,
+ "gocServerScope": null,
+ "supressionType": null,
+ "editPolicy": true,
+ "domainDir": "com",
+ "validData": false,
+ "draft": false,
+ "viewPolicy": false,
+ "blackListEntryType": "Use Manual Entry"
+ },
+ "date": "2018-03-27 13:36:12.0",
+ "version": 4
+}
diff --git a/ONAP-REST/src/test/resources/policies/MicroServicePolicy.json b/ONAP-REST/src/test/resources/policies/MicroServicePolicy.json
new file mode 100644
index 000000000..b9c06e536
--- /dev/null
+++ b/ONAP-REST/src/test/resources/policies/MicroServicePolicy.json
@@ -0,0 +1,38 @@
+{
+ "service": "TOSCA_namingJenny",
+ "location": "Test DictMSLoc",
+ "uuid": "testDict DCAEUIID",
+ "policyName": "testModelValidation",
+ "description": "test",
+ "configName": "testDict MSConfName",
+ "templateVersion": "1607",
+ "version": "gw12181031",
+ "priority": "5",
+ "policyScope": "resource=ResourcetypeVenktest1,service=ServiceName1707,type=Name1707,closedLoopControlName=Retest_retest1",
+ "riskType": "Test",
+ "riskLevel": "3",
+ "guard": "True",
+ "content": {
+ "police-instance-name": "testing",
+ "naming-models": [
+ {
+ "naming-properties": [
+ {
+ "property-value": "test",
+ "source-endpoint": "test",
+ "property-name": "testPropertyname",
+ "increment-sequence": {
+ "scope": "VNF",
+ "start-value": "1",
+ "length": "3",
+ "increment": "2"
+ },
+ "source-system": "TOSCA"
+ }
+ ],
+ "naming-type": "testNamingType",
+ "naming-recipe": "testNamingRecipe"
+ }
+ ]
+ }
+}
diff --git a/ONAP-REST/src/test/resources/policies/MicroServicePolicyContent0.json b/ONAP-REST/src/test/resources/policies/MicroServicePolicyContent0.json
new file mode 100644
index 000000000..f06d2f21c
--- /dev/null
+++ b/ONAP-REST/src/test/resources/policies/MicroServicePolicyContent0.json
@@ -0,0 +1,23 @@
+{
+ "police-instance-name": "content0",
+ "naming-models": [
+ {
+ "naming-properties": [
+ {
+ "property-value": "test",
+ "source-endpoint": "test",
+ "property-name": "testPropertyname",
+ "increment-sequence": {
+ "scope": "VNF",
+ "start-value": "1",
+ "length": "3",
+ "increment": "2"
+ },
+ "source-system": "TOSCA"
+ }
+ ],
+ "naming-type": "testNamingType",
+ "naming-recipe": "testNamingRecipe"
+ }
+ ]
+}
diff --git a/ONAP-REST/src/test/resources/policies/MicroServicePolicyContent1.json b/ONAP-REST/src/test/resources/policies/MicroServicePolicyContent1.json
new file mode 100644
index 000000000..dac78c0bb
--- /dev/null
+++ b/ONAP-REST/src/test/resources/policies/MicroServicePolicyContent1.json
@@ -0,0 +1,27 @@
+{
+ "police-instance-name": "content1",
+ "police-instance-range": "11",
+ "naming-models": [
+ {
+ "naming-properties": [
+ {
+ "property-value": "test",
+ "source-endpoint": "test",
+ "property-name": "testPropertyname",
+ "increment-sequence": {
+ "scope": "VNF",
+ "start-value": "1",
+ "length": "3",
+ "increment": "2"
+ },
+ "source-system": "TOSCA"
+ }
+ ],
+ "naming-type": "testNamingType",
+ "naming-recipe": "testNamingRecipe"
+ }
+ ],
+ "some-container": {
+ "container-name": "container-value"
+ }
+}
diff --git a/ONAP-REST/src/test/resources/policies/PolicyJsonTrapFault.json b/ONAP-REST/src/test/resources/policies/PolicyJsonTrapFault.json
new file mode 100644
index 000000000..8eafe2c2b
--- /dev/null
+++ b/ONAP-REST/src/test/resources/policies/PolicyJsonTrapFault.json
@@ -0,0 +1,9 @@
+{
+ "policyData": {
+ },
+ "trapData": {
+ },
+ "faultData": {
+ },
+ "policyJSON": "Policy JSON String"
+}
diff --git a/ONAP-SDK-APP/pom.xml b/ONAP-SDK-APP/pom.xml
index 340ca4f98..0d753fb13 100644
--- a/ONAP-SDK-APP/pom.xml
+++ b/ONAP-SDK-APP/pom.xml
@@ -2,7 +2,7 @@
============LICENSE_START=======================================================
ONAP Policy Engine
================================================================================
- Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ Copyright (C) 2017-2018, 2020 AT&T Intellectual Property. All rights reserved.
================================================================================
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
@@ -22,14 +22,14 @@
<parent>
<groupId>org.onap.policy.engine</groupId>
<artifactId>PolicyEngineSuite</artifactId>
- <version>1.4.1-SNAPSHOT</version>
+ <version>1.6.4-SNAPSHOT</version>
</parent>
<artifactId>ONAP-SDK-APP</artifactId>
<packaging>war</packaging>
<properties>
<encoding>UTF-8</encoding>
- <epsdk.version>2.4.0</epsdk.version>
- <springframework.version>4.2.0.RELEASE</springframework.version>
+ <epsdk.version>2.6.0</epsdk.version>
+ <springframework.version>4.3.24.RELEASE</springframework.version>
<hibernate.version>4.3.11.Final</hibernate.version>
<!-- Skip assembling the zip; assemble via mvn -Dskipassembly=false .. -->
<skipassembly>true</skipassembly>
@@ -63,14 +63,6 @@
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-compiler-plugin</artifactId>
- <configuration>
- <source>1.8</source>
- <target>1.8</target>
- </configuration>
- </plugin>
- <plugin>
- <groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<skipTests>${skiptests}</skipTests>
@@ -185,6 +177,11 @@
</plugins>
</build>
<dependencies>
+ <dependency>
+ <groupId>org.powermock</groupId>
+ <artifactId>powermock-api-mockito2</artifactId>
+ <scope>test</scope>
+ </dependency>
<!-- Policy overlay war -->
<dependency>
<groupId>org.onap.policy.engine</groupId>
@@ -196,6 +193,14 @@
<groupId>org.onap.portal.sdk</groupId>
<artifactId>epsdk-core</artifactId>
</exclusion>
+ <exclusion>
+ <groupId>org.apache.xmlbeans</groupId>
+ <artifactId>xmlbeans</artifactId>
+ </exclusion>
+ <exclusion>
+ <groupId>dom4j</groupId>
+ <artifactId>dom4j</artifactId>
+ </exclusion>
</exclusions>
</dependency>
<dependency>
@@ -209,6 +214,10 @@
<groupId>org.onap.portal.sdk</groupId>
<artifactId>epsdk-core</artifactId>
</exclusion>
+ <exclusion>
+ <groupId>org.springframework</groupId>
+ <artifactId>spring-expression</artifactId>
+ </exclusion>
</exclusions>
</dependency>
<dependency>
@@ -248,6 +257,22 @@
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
</exclusion>
+ <exclusion>
+ <groupId>xerces</groupId>
+ <artifactId>xercesImpl</artifactId>
+ </exclusion>
+ <exclusion>
+ <groupId>xalan</groupId>
+ <artifactId>xalan</artifactId>
+ </exclusion>
+ <exclusion>
+ <groupId>xml-apis</groupId>
+ <artifactId>xml-apis-ext</artifactId>
+ </exclusion>
+ <exclusion>
+ <groupId>xom</groupId>
+ <artifactId>xom</artifactId>
+ </exclusion>
</exclusions>
</dependency>
<!-- SDK components -->
@@ -262,6 +287,16 @@
<version>3.2.2</version>
</dependency>
<dependency>
+ <groupId>org.springframework</groupId>
+ <artifactId>spring-aop</artifactId>
+ <version>${springframework.version}</version>
+ </dependency>
+ <dependency>
+ <groupId>org.springframework</groupId>
+ <artifactId>spring-orm</artifactId>
+ <version>${springframework.version}</version>
+ </dependency>
+ <dependency>
<groupId>org.onap.portal.sdk</groupId>
<artifactId>epsdk-core</artifactId>
<version>${epsdk.version}</version>
@@ -291,6 +326,26 @@
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
</exclusion>
+ <exclusion>
+ <groupId>org.springframework</groupId>
+ <artifactId>spring-aop</artifactId>
+ </exclusion>
+ <exclusion>
+ <groupId>org.springframework</groupId>
+ <artifactId>spring-orm</artifactId>
+ </exclusion>
+ <exclusion>
+ <groupId>xalan</groupId>
+ <artifactId>xalan</artifactId>
+ </exclusion>
+ <exclusion>
+ <groupId>org.aspectj</groupId>
+ <artifactId>aspectjrt</artifactId>
+ </exclusion>
+ <exclusion>
+ <groupId>org.aspectj</groupId>
+ <artifactId>aspectjweaver</artifactId>
+ </exclusion>
</exclusions>
</dependency>
<dependency>
@@ -344,6 +399,21 @@
<!-- Spring -->
<!-- Added dependencies to fix issue with duplicate jars of different versions -->
<dependency>
+ <groupId>org.aspectj</groupId>
+ <artifactId>aspectjrt</artifactId>
+ <version>1.8.14</version>
+ </dependency>
+ <dependency>
+ <groupId>org.aspectj</groupId>
+ <artifactId>aspectjweaver</artifactId>
+ <version>1.8.14</version>
+ </dependency>
+ <dependency>
+ <groupId>org.springframework</groupId>
+ <artifactId>spring-expression</artifactId>
+ <version>${springframework.version}</version>
+ </dependency>
+ <dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${springframework.version}</version>
@@ -358,11 +428,23 @@
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${springframework.version}</version>
+ <exclusions>
+ <exclusion>
+ <groupId>org.springframework</groupId>
+ <artifactId>spring-expression</artifactId>
+ </exclusion>
+ </exclusions>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${springframework.version}</version>
+ <exclusions>
+ <exclusion>
+ <groupId>org.springframework</groupId>
+ <artifactId>spring-expression</artifactId>
+ </exclusion>
+ </exclusions>
</dependency>
<!-- bridge to implement commons-logging using slf4j -->
<dependency>
diff --git a/ONAP-SDK-APP/src/main/resources/logback.xml b/ONAP-SDK-APP/src/main/resources/logback.xml
index 134ecb8ab..e12ca87c6 100644
--- a/ONAP-SDK-APP/src/main/resources/logback.xml
+++ b/ONAP-SDK-APP/src/main/resources/logback.xml
@@ -3,14 +3,14 @@
================================================================================
ONAP Portal SDK
================================================================================
- Copyright (C) 2017-2018 AT&T Intellectual Property
+ Copyright (C) 2017-2019 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.
@@ -20,25 +20,25 @@
-->
<configuration scan="true" scanPeriod="3 seconds" debug="true">
- <!--
+ <!--
Logback files for the ONAP Portal SDK Application "epsdk-app-os"
are created in directory ${catalina.base}/logs/epsdk_app_os;
- e.g., apache-tomcat-8.0.35/logs/epsdk_app_os/application.log
+ e.g., apache-tomcat-8.0.35/logs/epsdk_app_os/application.log
-->
<!--<jmxConfigurator /> -->
<!-- specify the component name -->
<property name="componentName" value="policy"></property>
<property name="subComponentName" value="console"></property>
-
+
<!-- specify the base path of the log directory -->
<property name="logDirPrefix" value="${POLICY_LOGS}"></property>
-
+
<!-- The directories where logs are written -->
<property name="logDirectory" value="${logDirPrefix}/${componentName}/${subComponentName}" />
<!-- Can easily relocate debug logs by modifying this path. -->
<property name="debugLogDirectory" value="${logDirPrefix}/${componentName}/${subComponentName}" />
-
+
<!-- log file names -->
<property name="generalLogName" value="application" />
<property name="errorLogName" value="error" />
@@ -46,29 +46,29 @@
<property name="auditLogName" value="audit" />
<property name="debugLogName" value="debug" />
<!--
- These loggers are not used in code (yet).
+ These loggers are not used in code (yet).
<property name="securityLogName" value="security" />
<property name="policyLogName" value="policy" />
<property name="performanceLogName" value="performance" />
<property name="serverLogName" value="server" />
-->
-
- <!-- 1610 Logging Fields Format Revisions -->
+
+ <!-- 1610 Logging Fields Format Revisions -->
<property name="auditLoggerPattern"
- value="%X{AuditLogBeginTimestamp}|%X{AuditLogEndTimestamp}|%X{RequestId}|%X{ServiceInstanceId}|%thread|%X{VirtualServerName}|%X{ServiceName}|%X{PartnerName}|%X{StatusCode}|%X{ResponseCode}|%X{ResponseDescription}|%X{InstanceUUID}|%.-5level|%X{AlertSeverity}|%X{ServerIPAddress}|%X{Timer}|%X{ServerFQDN}|%X{ClientIPAddress}|%X{ClassName}|%X{Unused}|%X{ProcessKey}|%X{CustomField1}|%X{CustomField2}|%X{CustomField3}|%X{CustomField4}| %msg%n" />
+ value="%X{AuditLogBeginTimestamp}|%X{AuditLogEndTimestamp}|%X{RequestId}|%X{ServiceInstanceId}|%thread|%X{VirtualServerName}|%X{ServiceName}|%X{PartnerName}|%X{StatusCode}|%X{ResponseCode}|%X{ResponseDescription}|%X{InstanceUUID}|%.-5level|%X{Severity}|%X{ServerIPAddress}|%X{Timer}|%X{ServerFQDN}|%X{ClientIPAddress}|%X{ClassName}|%X{Unused}|%X{ProcessKey}|%X{CustomField1}|%X{CustomField2}|%X{CustomField3}|%X{CustomField4}| %msg%n" />
<property name="metricsLoggerPattern"
- value="%X{MetricsLogBeginTimestamp}|%X{MetricsLogEndTimestamp}|%X{RequestId}|%X{ServiceInstanceId}|%thread|%X{VirtualServerName}|%X{ServiceName}|%X{PartnerName}|%X{TargetEntity}|%X{TargetServiceName}|%X{StatusCode}|%X{ResponseCode}|%X{ResponseDescription}|%X{InstanceUUID}|%.-5level|%X{AlertSeverity}|%X{ServerIPAddress}|%X{Timer}|%X{ServerFQDN}|%X{ClientIPAddress}|%X{ClassName}|%X{Unused}|%X{ProcessKey}|%X{TargetVisualEntity}|%X{CustomField1}|%X{CustomField2}|%X{CustomField3}|%X{CustomField4}| %msg%n" />
+ value="%X{MetricsLogBeginTimestamp}|%X{MetricsLogEndTimestamp}|%X{RequestId}|%X{ServiceInstanceId}|%thread|%X{VirtualServerName}|%X{ServiceName}|%X{PartnerName}|%X{TargetEntity}|%X{TargetServiceName}|%X{StatusCode}|%X{ResponseCode}|%X{ResponseDescription}|%X{InstanceUUID}|%.-5level|%X{Severity}|%X{ServerIPAddress}|%X{Timer}|%X{ServerFQDN}|%X{ClientIPAddress}|%X{ClassName}|%X{Unused}|%X{ProcessKey}|%X{TargetVisualEntity}|%X{CustomField1}|%X{CustomField2}|%X{CustomField3}|%X{CustomField4}| %msg%n" />
<property name="errorLoggerPattern"
- value="%date{yyyy-MM-dd'T'HH:mm:ss.SSSXXX}|%X{RequestId}|%thread|%X{ServiceName}|%X{PartnerName}|%X{TargetEntity}|%X{TargetServiceName}|%X{ClassName}|%X{AlertSeverity}|%X{ErrorCode}|%X{ErrorDescription}| %msg%n" />
+ value="%date{yyyy-MM-dd'T'HH:mm:ss.SSSXXX}|%X{RequestId}|%thread|%X{ServiceName}|%X{PartnerName}|%X{TargetEntity}|%X{TargetServiceName}|%X{ClassName}|%X{Severity}|%X{ErrorCode}|%X{ErrorDescription}| %msg%n" />
<property name="defaultLoggerPattern"
- value="%date{yyyy-MM-dd'T'HH:mm:ss.SSSXXX}|%X{RequestId}|%thread|%X{ClassName}| %msg%n" />
+ value="%date{yyyy-MM-dd'T'HH:mm:ss.SSSXXX}|%X{RequestId}|%thread|%X{ClassName}| %msg%n" />
<!-- use %class so library logging calls yield their class name -->
<property name="applicationLoggerPattern"
- value="%date{yyyy-MM-dd'T'HH:mm:ss.SSSXXX}|%X{RequestId}|%thread|%class{36}| %msg%n" />
+ value="%date{yyyy-MM-dd'T'HH:mm:ss.SSSXXX}|%X{RequestId}|%thread|%class{36}| %msg%n" />
<!-- Example evaluator filter applied against console appender -->
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
@@ -81,53 +81,53 @@
<!-- EELF Appenders -->
<!-- ============================================================================ -->
- <!-- The EELFAppender is used to record events to the general application
+ <!-- The EELFAppender is used to record events to the general application
log -->
-
-
+
+
<appender name="EELF"
class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>${logDirectory}/${generalLogName}.log</file>
- <rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
- <!-- daily rollover -->
- <fileNamePattern>${logDirectory}/${generalLogName}.%d{yyyy-MM-dd}.%i.log.zip</fileNamePattern>
-
- <!-- keep 30 days' worth of history capped at 3GB total size -->
+ <rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
+ <!-- daily rollover -->
+ <fileNamePattern>${logDirectory}/${generalLogName}.%d{yyyy-MM-dd}.%i.log.zip</fileNamePattern>
+
+ <!-- keep 30 days' worth of history capped at 3GB total size -->
<maxFileSize>50MB</maxFileSize>
<maxHistory>30</maxHistory>
- <totalSizeCap>10GB</totalSizeCap>
-
+ <totalSizeCap>10GB</totalSizeCap>
+
</rollingPolicy>
<encoder>
<pattern>${applicationLoggerPattern}</pattern>
</encoder>
<filter class="org.onap.portalapp.util.CustomLoggingFilter" />
</appender>
-
+
<appender name="asyncEELF" class="ch.qos.logback.classic.AsyncAppender">
<queueSize>256</queueSize>
<!-- Class name is part of caller data -->
<includeCallerData>true</includeCallerData>
<appender-ref ref="EELF" />
</appender>
- <!-- EELF Audit Appender. This appender is used to record audit engine
- related logging events. The audit logger and appender are specializations
- of the EELF application root logger and appender. This can be used to segregate
- Policy engine events from other components, or it can be eliminated to record
+ <!-- EELF Audit Appender. This appender is used to record audit engine
+ related logging events. The audit logger and appender are specializations
+ of the EELF application root logger and appender. This can be used to segregate
+ Policy engine events from other components, or it can be eliminated to record
these events as part of the application root log. -->
-
+
<appender name="EELFAudit"
class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>${logDirectory}/${auditLogName}.log</file>
- <rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
- <!-- daily rollover -->
- <fileNamePattern>${logDirectory}/${auditLogName}.%d{yyyy-MM-dd}.%i.log.zip</fileNamePattern>
-
- <!-- keep 30 days' worth of history capped at 3GB total size -->
+ <rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
+ <!-- daily rollover -->
+ <fileNamePattern>${logDirectory}/${auditLogName}.%d{yyyy-MM-dd}.%i.log.zip</fileNamePattern>
+
+ <!-- keep 30 days' worth of history capped at 3GB total size -->
<maxFileSize>50MB</maxFileSize>
<maxHistory>30</maxHistory>
- <totalSizeCap>10GB</totalSizeCap>
-
+ <totalSizeCap>10GB</totalSizeCap>
+
</rollingPolicy>
<encoder>
<pattern>${auditLoggerPattern}</pattern>
@@ -141,75 +141,75 @@
<appender name="EELFMetrics"
class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>${logDirectory}/${metricsLogName}.log</file>
- <rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
- <!-- daily rollover -->
- <fileNamePattern>${logDirectory}/${metricsLogName}.%d{yyyy-MM-dd}.%i.log.zip</fileNamePattern>
-
- <!-- keep 30 days' worth of history capped at 3GB total size -->
+ <rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
+ <!-- daily rollover -->
+ <fileNamePattern>${logDirectory}/${metricsLogName}.%d{yyyy-MM-dd}.%i.log.zip</fileNamePattern>
+
+ <!-- keep 30 days' worth of history capped at 3GB total size -->
<maxFileSize>50MB</maxFileSize>
<maxHistory>30</maxHistory>
- <totalSizeCap>10GB</totalSizeCap>
-
+ <totalSizeCap>10GB</totalSizeCap>
+
</rollingPolicy>
<encoder>
<pattern>${metricsLoggerPattern}</pattern>
</encoder>
</appender>
-
-
+
+
<appender name="asyncEELFMetrics" class="ch.qos.logback.classic.AsyncAppender">
<queueSize>256</queueSize>
<appender-ref ref="EELFMetrics"/>
</appender>
-
+
<appender name="EELFError"
class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>${logDirectory}/${errorLogName}.log</file>
- <rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
- <!-- daily rollover -->
- <fileNamePattern>${logDirectory}/${errorLogName}.%d{yyyy-MM-dd}.%i.log.zip</fileNamePattern>
-
- <!-- keep 30 days' worth of history capped at 3GB total size -->
+ <rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
+ <!-- daily rollover -->
+ <fileNamePattern>${logDirectory}/${errorLogName}.%d{yyyy-MM-dd}.%i.log.zip</fileNamePattern>
+
+ <!-- keep 30 days' worth of history capped at 3GB total size -->
<maxFileSize>50MB</maxFileSize>
<maxHistory>30</maxHistory>
- <totalSizeCap>10GB</totalSizeCap>
-
+ <totalSizeCap>10GB</totalSizeCap>
+
</rollingPolicy>
<encoder>
<pattern>${errorLoggerPattern}</pattern>
</encoder>
</appender>
-
+
<appender name="asyncEELFError" class="ch.qos.logback.classic.AsyncAppender">
<queueSize>256</queueSize>
<appender-ref ref="EELFError"/>
</appender>
-
+
<appender name="EELFDebug"
class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>${debugLogDirectory}/${debugLogName}.log</file>
- <rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
- <!-- daily rollover -->
- <fileNamePattern>${logDirectory}/${debugLogName}.%d{yyyy-MM-dd}.%i.log.zip</fileNamePattern>
-
- <!-- keep 30 days' worth of history capped at 3GB total size -->
+ <rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
+ <!-- daily rollover -->
+ <fileNamePattern>${logDirectory}/${debugLogName}.%d{yyyy-MM-dd}.%i.log.zip</fileNamePattern>
+
+ <!-- keep 30 days' worth of history capped at 3GB total size -->
<maxFileSize>50MB</maxFileSize>
<maxHistory>30</maxHistory>
- <totalSizeCap>10GB</totalSizeCap>
-
+ <totalSizeCap>10GB</totalSizeCap>
+
</rollingPolicy>
<encoder>
<pattern>${defaultLoggerPattern}</pattern>
</encoder>
</appender>
-
+
<appender name="asyncEELFDebug" class="ch.qos.logback.classic.AsyncAppender">
<queueSize>256</queueSize>
<appender-ref ref="EELFDebug" />
</appender>
-
-
-
+
+
+
<logger name="org.onap.eelf" level="info" additivity="false">
<appender-ref ref="asyncEELF" />
@@ -218,21 +218,21 @@
<logger name="org.onap.eelf.audit" level="info" additivity="false">
<appender-ref ref="asyncEELFAudit" />
</logger>
-
+
<logger name="org.onap.eelf.debug" level="debug" additivity="false">
<appender-ref ref="asyncEELFDebug" />
</logger>
-
+
<logger name="org.onap.eelf.error" level="info" additivity="false">
<appender-ref ref="asyncEELFError" />
</logger>
<logger name="org.onap.eelf.metrics" level="info" additivity="false">
<appender-ref ref="asyncEELFMetrics" />
- </logger>
-
+ </logger>
+
<root level="DEBUG">
<appender-ref ref="asyncEELF" />
</root>
-</configuration> \ No newline at end of file
+</configuration>
diff --git a/ONAP-SDK-APP/src/main/webapp/WEB-INF/defs/definitions.xml b/ONAP-SDK-APP/src/main/webapp/WEB-INF/defs/definitions.xml
index 2d1f38e44..88e4b70e4 100644
--- a/ONAP-SDK-APP/src/main/webapp/WEB-INF/defs/definitions.xml
+++ b/ONAP-SDK-APP/src/main/webapp/WEB-INF/defs/definitions.xml
@@ -3,14 +3,14 @@
============LICENSE_START==================================================
ONAP Policy Engine
===========================================================================
- Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ Copyright (C) 2017-2018, 2020 AT&T Intellectual Property. All rights reserved.
===========================================================================
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
-
+
http://www.apache.org/licenses/LICENSE-2.0
-
+
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -21,17 +21,18 @@
<!DOCTYPE tiles-definitions PUBLIC
"-//Apache Software Foundation//DTD Tiles Configuration 3.0//EN"
"http://tiles.apache.org/dtds/tiles-config_3_0.dtd">
-
+
<!--
- This tiles definitions file is defs/definitions.xml.
- It maps tokens used by app controllers to JSP file paths.
- Applications that use JSP pages should modify this file.
- Configured by ExternalAppConfig#addTileDefinitions().
+ This tiles definitions file is defs/definitions.xml.
+ It maps tokens used by app controllers to JSP file paths.
+ Applications that use JSP pages should modify this file.
+ Configured by ExternalAppConfig#addTileDefinitions().
-->
<tiles-definitions>
- <definition name="tileKey" template="/path/to/page_template.html"/>
- <definition name="policy_Editor" template="/app/policyApp/main/policyEditor.html"/>
-
+ <definition name="tileKey" template="/path/to/page_template.html"/>
+ <definition name="policy_Editor" template="/app/policyApp/main/policyEditor.html"/>
+ <definition name="welcome" template="/app/fusion/scripts/DS2-view-models/welcome.html" />
+
</tiles-definitions>
diff --git a/ONAP-SDK-APP/src/test/java/org/onap/portalapp/scheduler/RegisterTest.java b/ONAP-SDK-APP/src/test/java/org/onap/portalapp/scheduler/RegisterTest.java
index 675a87e43..68454112d 100644
--- a/ONAP-SDK-APP/src/test/java/org/onap/portalapp/scheduler/RegisterTest.java
+++ b/ONAP-SDK-APP/src/test/java/org/onap/portalapp/scheduler/RegisterTest.java
@@ -40,8 +40,8 @@ public class RegisterTest {
triggers.add(trigger);
register.setScheduleTriggers(triggers);
- assertEquals(register.getScheduleTriggers(), triggers);
- assertEquals(register.getTriggers().length, 1);
+ assertEquals(triggers, register.getScheduleTriggers());
+ assertEquals(1, register.getTriggers().length);
}
@Test(expected = NullPointerException.class)
@@ -54,7 +54,6 @@ public class RegisterTest {
@Test(expected = NullPointerException.class)
public void testRegisterNegativeCase2() {
// Setup test data
- String value = "testVal";
Register register = new Register();
List<Trigger> triggers = new ArrayList<Trigger>();
register.setScheduleTriggers(triggers);
diff --git a/ONAP-XACML/pom.xml b/ONAP-XACML/pom.xml
index d168ccfad..490789266 100644
--- a/ONAP-XACML/pom.xml
+++ b/ONAP-XACML/pom.xml
@@ -3,7 +3,7 @@
============LICENSE_START=======================================================
ONAP Policy Engine
================================================================================
- Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ Copyright (C) 2017-2018, 2020 AT&T Intellectual Property. All rights reserved.
================================================================================
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
@@ -24,7 +24,7 @@
<parent>
<groupId>org.onap.policy.engine</groupId>
<artifactId>PolicyEngineSuite</artifactId>
- <version>1.4.1-SNAPSHOT</version>
+ <version>1.6.4-SNAPSHOT</version>
</parent>
<artifactId>ONAP-XACML</artifactId>
<packaging>jar</packaging>
@@ -48,9 +48,24 @@
<artifactId>httpcore</artifactId>
</dependency>
<dependency>
+ <groupId>javax.xml.bind</groupId>
+ <artifactId>jaxb-api</artifactId>
+ <version>${version.javax.bind}</version>
+ </dependency>
+ <dependency>
+ <groupId>org.glassfish.jaxb</groupId>
+ <artifactId>jaxb-runtime</artifactId>
+ <version>2.3.2</version>
+ </dependency>
+ <dependency>
+ <groupId>javax.activation</groupId>
+ <artifactId>javax.activation-api</artifactId>
+ <version>1.2.0</version>
+ </dependency>
+ <dependency>
<groupId>com.att.research.xacml</groupId>
<artifactId>xacml</artifactId>
- <version>1.0.2</version>
+ <version>2.0.1</version>
<exclusions>
<!-- The LDAP PIP uses velocity which pulls this insecure jar in. We
are not using that PIP and can safely exclude this jar to resolve CLM issue.
@@ -59,6 +74,10 @@
<groupId>commons-collections</groupId>
<artifactId>commons-collections</artifactId>
</exclusion>
+ <exclusion>
+ <groupId>xml-apis</groupId>
+ <artifactId>xml-apis</artifactId>
+ </exclusion>
</exclusions>
</dependency>
</dependencies>
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
index 0cbba2f19..b8a68d10a 100644
--- 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
@@ -2,14 +2,14 @@
* ============LICENSE_START=======================================================
* ONAP-XACML
* ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017, 2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -17,44 +17,46 @@
* 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
- *
+ * 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: ";
-
- // Static class, hide constructor
+ // 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: ";
+
+ // Static class, hide constructor
private XACMLErrorConstants() {
- super();
+ super();
}
}
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
index eacbeb216..a78dc3250 100644
--- 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
@@ -2,14 +2,14 @@
* ============LICENSE_START=======================================================
* ONAP-XACML
* ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017,2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -20,39 +20,40 @@
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 <code>PAPEngineFactory</code> instance using the given class name and the default thread class loader.
- *
- * @param factoryClassName the <code>String</code> name of the factory class to instantiate
- * @return an instance of an object that extends <code>ONAPPapEngineFactory</code> to use in creating <code>PAPPolicyEngine</code> objects.
- */
- public static ONAPPapEngineFactory newInstance(String factoryClassName) throws FactoryException {
- return FactoryFinder.newInstance(factoryClassName, ONAPPapEngineFactory.class, null, true);
- }
-
- /**
- * Creates a new <code>PAPPolicyEngine</code> based on the configured <code>ONAPPapEngineFactory</code>.
- *
- * @return a new <code>PAPPolicyEngine</code>
- * @throws PAPException
- */
- public abstract PAPPolicyEngine newEngine() throws FactoryException, PAPException;
-
- /**
- * Creates a new <code>PAPPolicyEngine</code> based on the configured <code>ONAPPapEngineFactory</code>.
- *
- * @return a new <code>PAPPolicyEngine</code>
- * @throws PAPException
- */
- public abstract PAPPolicyEngine newEngine(Properties properties) throws FactoryException, PAPException;
+import java.util.Properties;
+public abstract class ONAPPapEngineFactory {
+
+ /**
+ * Creates a new <code>PAPEngineFactory</code> instance using the given class name and the default thread class
+ * loader.
+ *
+ * @param factoryClassName the <code>String</code> name of the factory class to instantiate
+ * @return an instance of an object that extends <code>ONAPPapEngineFactory</code> to use in creating
+ * <code>PAPPolicyEngine</code> objects.
+ */
+ public static ONAPPapEngineFactory newInstance(String factoryClassName) throws FactoryException {
+ return FactoryFinder.newInstance(factoryClassName, ONAPPapEngineFactory.class, null, true);
+ }
+
+ /**
+ * Creates a new <code>PAPPolicyEngine</code> based on the configured <code>ONAPPapEngineFactory</code>.
+ *
+ * @return a new <code>PAPPolicyEngine</code>
+ * @throws PAPException PAPException
+ */
+ public abstract PAPPolicyEngine newEngine() throws FactoryException, PAPException;
+
+ /**
+ * Creates a new <code>PAPPolicyEngine</code> based on the configured <code>ONAPPapEngineFactory</code>.
+ *
+ * @return a new <code>PAPPolicyEngine</code>
+ * @throws PAPException 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
index 4539b4225..5879c098c 100644
--- 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
@@ -2,14 +2,14 @@
* ============LICENSE_START=======================================================
* ONAP-XACML
* ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017, 2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -17,73 +17,115 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.policy.xacml.api.pap;
+import com.fasterxml.jackson.annotation.JsonSubTypes;
+import com.fasterxml.jackson.annotation.JsonSubTypes.Type;
+import com.fasterxml.jackson.annotation.JsonTypeInfo;
+
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") })
+@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<String, String> getDynamicFieldConfigAttributes();
- public Map<String, String> getTreatments();
- public Map<String, String> getDynamicSettingsMap();
- public List<String> getDynamicRuleAlgorithmLabels();
- public List<String> getDynamicRuleAlgorithmCombo();
- public List<String> getDynamicRuleAlgorithmField1();
- public List<String> getDynamicRuleAlgorithmField2();
- public List<Object> getDynamicVariableList();
- public List<String> 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<String, String> 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 getPolicyName();
+
+ public String getOldPolicyFileName();
+
+ public String getPolicyDescription();
+
+ public String getOnapName();
+
+ public String getConfigName();
+
+ public Map<String, String> getDynamicFieldConfigAttributes();
+
+ public Map<String, String> getTreatments();
+
+ public Map<String, String> getDynamicSettingsMap();
+
+ public List<String> getDynamicRuleAlgorithmLabels();
+
+ public List<String> getDynamicRuleAlgorithmCombo();
+
+ public List<String> getDynamicRuleAlgorithmField1();
+
+ public List<String> getDynamicRuleAlgorithmField2();
+
+ public List<Object> getDynamicVariableList();
+
+ public List<String> 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<String, String> 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();
+
+ 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
index 65db0b980..6224e38cd 100644
--- 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
@@ -2,14 +2,14 @@
* ============LICENSE_START=======================================================
* ONAP-XACML
* ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017, 2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -17,28 +17,25 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-package org.onap.policy.xacml.api.pap;
-import org.onap.policy.xacml.std.pap.StdPDP;
+package org.onap.policy.xacml.api.pap;
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;
+import org.onap.policy.xacml.std.pap.StdPDP;
+
/*
* 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") })
+@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);
-
+ 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
index 7d3ad0c63..77561652a 100644
--- 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
@@ -2,14 +2,14 @@
* ============LICENSE_START=======================================================
* ONAP-XACML
* ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017, 2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -20,16 +20,16 @@
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;
+import java.util.Set;
+
public interface OnapPDPGroup extends PDPGroup {
- public Set<OnapPDP> getOnapPdps();
-
- public Set<PDPPolicy> getSelectedPolicies();
-
- public String getOperation();
+ public Set<OnapPDP> getOnapPdps();
+
+ public Set<PDPPolicy> 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
index cae7456bc..62255ff8f 100644
--- 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
@@ -23,6 +23,7 @@ package org.onap.policy.xacml.api.pap;
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 java.io.InputStream;
import java.util.Set;
@@ -60,7 +61,7 @@ public interface PAPPolicyEngine {
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 copyPolicy(PDPPolicy policy, OnapPDPGroup group, String userId) 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
index 8e55300b1..d2d50a597 100644
--- 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
@@ -30,6 +30,7 @@ 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;
+
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
@@ -48,6 +49,7 @@ 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;
@@ -64,9 +66,13 @@ import org.onap.policy.xacml.api.pap.PAPPolicyEngine;
*
*/
public class StdEngine extends StdPDPItemSetChangeNotifier implements PAPPolicyEngine {
- public static final String pipPropertyFile = "pip.properties";
+ public static final String PIP_PROPERTY_FILE = "pip.properties";
- private static final String addGroup = "addGroup ";
+ private static final String STR_ADDGROUP = "addGroup ";
+ private static final String STR_CLASS = "StdEngine";
+ private static final String STR_APPEND_NAME = ".name";
+ private static final String STR_APPEND_DESCRIPTION = ".description";
+ private static final String STR_APPEND_PDPS = ".pdps";
private static Log logger = LogFactory.getLog(StdEngine.class);
@@ -81,6 +87,12 @@ public class StdEngine extends StdPDPItemSetChangeNotifier implements PAPPolicyE
protected final Path repository;
protected Set<StdPDPGroup> groups;
+ /**
+ * StdEngine constructor.
+ *
+ * @throws PAPException PAPException
+ * @throws IOException IOException
+ */
public StdEngine() throws PAPException, IOException {
//
// Get the location in the file system of our repository
@@ -92,6 +104,13 @@ public class StdEngine extends StdPDPItemSetChangeNotifier implements PAPPolicyE
this.intialize();
}
+ /**
+ * StdEngine constructor.
+ *
+ * @param properties Properties
+ * @throws PAPException PAPException
+ * @throws IOException IOException
+ */
public StdEngine(Properties properties) throws PAPException, IOException {
//
// Get the location in the file system of our repository
@@ -103,6 +122,13 @@ public class StdEngine extends StdPDPItemSetChangeNotifier implements PAPPolicyE
this.intialize();
}
+ /**
+ * StdEngine constructor.
+ *
+ * @param repository Path
+ * @throws PAPException PAPException
+ * @throws IOException IOException
+ */
public StdEngine(Path repository) throws PAPException, IOException {
//
// Save our location
@@ -121,13 +147,13 @@ public class StdEngine extends StdPDPItemSetChangeNotifier implements PAPPolicyE
if (this.repository == null) {
throw new PAPException("No repository specified.");
}
- if (Files.notExists(this.repository)) {
+ if (! this.repository.toFile().exists()) {
Files.createDirectory(repository);
}
- if (!Files.isDirectory(this.repository)) {
+ if (! this.repository.toFile().isDirectory()) {
throw new PAPException("Repository is NOT a directory: " + this.repository.toAbsolutePath());
}
- if (!Files.isWritable(this.repository)) {
+ if (! this.repository.toFile().canWrite()) {
throw new PAPException("Repository is NOT writable: " + this.repository.toAbsolutePath());
}
//
@@ -155,7 +181,7 @@ public class StdEngine extends StdPDPItemSetChangeNotifier implements PAPPolicyE
//
this.groups = this.readProperties(this.repository, properties);
} catch (IOException e) {
- PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "StdEngine", "Failed to load properties file");
+ PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, STR_CLASS, "Failed to load properties file");
this.groups = new HashSet<>();
}
//
@@ -188,7 +214,7 @@ public class StdEngine extends StdPDPItemSetChangeNotifier implements PAPPolicyE
//
// Does it exist?
//
- if (Files.notExists(defaultPath)) {
+ if (! defaultPath.toFile().exists()) {
//
// Create its directory
//
@@ -205,19 +231,19 @@ public class StdEngine extends StdPDPItemSetChangeNotifier implements PAPPolicyE
try (OutputStream os = Files.newOutputStream(policyPath)) {
props.store(os, "");
} catch (IOException e) {
- PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "StdEngine",
+ PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, STR_CLASS,
"Failed to write default policy properties");
}
}
{
Properties props = new Properties();
- props = setPIPProperties(props);
+ 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",
+ PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, STR_CLASS,
"Failed to write default pip properties");
}
}
@@ -225,7 +251,7 @@ public class StdEngine extends StdPDPItemSetChangeNotifier implements PAPPolicyE
//
// Create the default group
//
- StdPDPGroup newDefault = new StdPDPGroup(defaultId, true, "default",
+ StdPDPGroup newDefault = new StdPDPGroup(defaultId, true, PROP_PAP_GROUPS_DEFAULT_NAME,
"The default group where new PDP's are put.", defaultPath);
//
// Add it to our list
@@ -244,7 +270,7 @@ public class StdEngine extends StdPDPItemSetChangeNotifier implements PAPPolicyE
properties.store(os, "");
}
} catch (IOException e) {
- PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "StdEngine",
+ PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, STR_CLASS,
"Failed to save properties with new default group information.");
}
//
@@ -253,7 +279,7 @@ public class StdEngine extends StdPDPItemSetChangeNotifier implements PAPPolicyE
wasDefaultGroupJustAdded = true;
return newDefault;
} catch (IOException e) {
- PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "StdEngine", "Failed to create default group");
+ PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, STR_CLASS, "Failed to create default group");
throw new PAPException("Failed to create default group");
}
}
@@ -282,7 +308,7 @@ public class StdEngine extends StdPDPItemSetChangeNotifier implements PAPPolicyE
}
@Override
- public void newGroup(String name, String description) throws PAPException, NullPointerException {
+ public void newGroup(String name, String description) throws PAPException {
//
// Null check
//
@@ -298,12 +324,10 @@ public class StdEngine extends StdPDPItemSetChangeNotifier implements PAPPolicyE
}
}
-
// 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);
-
+ String id = createNewPdpGroupId(name);
//
// Construct the directory path
@@ -313,7 +337,7 @@ public class StdEngine extends StdPDPItemSetChangeNotifier implements PAPPolicyE
// If it exists already
//
if (Files.exists(groupPath)) {
- logger.warn(addGroup + id + " directory exists");
+ logger.warn(STR_ADDGROUP + id + " directory exists");
} else {
try {
//
@@ -321,7 +345,7 @@ public class StdEngine extends StdPDPItemSetChangeNotifier implements PAPPolicyE
//
Files.createDirectory(groupPath);
} catch (IOException e) {
- PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "StdEngine", "Failed to create " + groupPath);
+ PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, STR_CLASS, "Failed to create " + groupPath);
throw new PAPException("Failed to create " + id);
}
}
@@ -330,8 +354,8 @@ public class StdEngine extends StdPDPItemSetChangeNotifier implements PAPPolicyE
//
Path policyProperties = Paths.get(groupPath.toString(), "xacml.policy.properties");
- if (Files.exists(policyProperties)) {
- logger.warn(addGroup + id + " file exists");
+ if (policyProperties.toFile().exists()) {
+ logger.warn(STR_ADDGROUP + id + " file exists");
} else {
Properties props = new Properties();
props.setProperty(XACMLProperties.PROP_REFERENCEDPOLICIES, "");
@@ -342,7 +366,7 @@ public class StdEngine extends StdPDPItemSetChangeNotifier implements PAPPolicyE
props.store(os, "");
}
} catch (IOException e) {
- PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "StdEngine", "Failed to create policyProperties");
+ PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, STR_CLASS, "Failed to create policyProperties");
throw new PAPException("Failed to create " + id);
}
}
@@ -351,17 +375,17 @@ public class StdEngine extends StdPDPItemSetChangeNotifier implements PAPPolicyE
//
Path pipProperties = Paths.get(groupPath.toString(), "xacml.pip.properties");
Properties props = new Properties();
- if (Files.exists(pipProperties)) {
- logger.warn(addGroup + id + " file exists.");
+ if (pipProperties.toFile().exists()) {
+ logger.warn(STR_ADDGROUP + id + " file exists.");
} else {
try {
- props = setPIPProperties(props);
+ 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");
+ PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, STR_CLASS, "Failed to create pipProperties");
throw new PAPException("Failed to create " + id);
}
@@ -389,17 +413,15 @@ public class StdEngine extends StdPDPItemSetChangeNotifier implements PAPPolicyE
}
-
-
/**
* 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
+ * @param name String
+ * @return String
*/
- private String createNewPDPGroupId(String name) {
+ 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_");
@@ -420,7 +442,6 @@ public class StdEngine extends StdPDPItemSetChangeNotifier implements PAPPolicyE
return id;
}
-
@Override
public OnapPDP getPDP(String pdpId) throws PAPException {
for (OnapPDPGroup group : this.groups) {
@@ -433,7 +454,6 @@ public class StdEngine extends StdPDPItemSetChangeNotifier implements PAPPolicyE
return null;
}
-
@Override
public void movePDP(OnapPDP pdp, OnapPDPGroup newGroup) throws PAPException {
if (newGroup == null) {
@@ -471,21 +491,20 @@ public class StdEngine extends StdPDPItemSetChangeNotifier implements PAPPolicyE
}
}
-
@Override
public void updatePDP(OnapPDP pdp) throws PAPException {
- PDP currentPDP = this.getPDP(pdp.getId());
- if (currentPDP == null) {
+ 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) {
- ((OnapPDP) currentPDP).setJmxPort(pdp.getJmxPort());
+ currentPdp.setDescription(pdp.getDescription());
+ currentPdp.setName(pdp.getName());
+ if (currentPdp instanceof OnapPDP) {
+ ((OnapPDP) currentPdp).setJmxPort(pdp.getJmxPort());
}
this.doSave();
}
@@ -508,7 +527,6 @@ public class StdEngine extends StdPDPItemSetChangeNotifier implements PAPPolicyE
throw new PAPException(message);
}
-
@Override
/**
* Should never be called - Detailed status is held on the PDP, not the PAP
@@ -531,15 +549,13 @@ public class StdEngine extends StdPDPItemSetChangeNotifier implements PAPPolicyE
throw new PAPException("Unknown PDP Group: " + group.getId());
}
-
@Override
- public void copyPolicy(PDPPolicy policy, OnapPDPGroup group) throws PAPException {
+ public void copyPolicy(PDPPolicy policy, OnapPDPGroup group, String userId) throws PAPException {
//
// Currently not used on the PAP side. This is done by ((StdPDPGroup) group).copyPolicyToFile
//
}
-
@Override
public void removePolicy(PDPPolicy policy, OnapPDPGroup group) throws PAPException {
if (group == null) {
@@ -553,7 +569,6 @@ public class StdEngine extends StdPDPItemSetChangeNotifier implements PAPPolicyE
throw new PAPException("Unknown PDP Group: " + group.getId());
}
-
//
// HELPER methods
//
@@ -578,14 +593,14 @@ public class StdEngine extends StdPDPItemSetChangeNotifier implements PAPPolicyE
//
// Add our Group Object
//
- StdPDPGroup g = new StdPDPGroup(id.trim(),
+ StdPDPGroup newGroup = 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
//
- pdpGroups.add(g);
+ pdpGroups.add(newGroup);
}
//
// Dump what we got
@@ -617,8 +632,8 @@ public class StdEngine extends StdPDPItemSetChangeNotifier implements PAPPolicyE
List<String> 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",
+ properties.setProperty(group.getId() + STR_APPEND_NAME, group.getName() == null ? "" : group.getName());
+ properties.setProperty(group.getId() + STR_APPEND_DESCRIPTION,
group.getDescription() == null ? "" : group.getDescription());
//
// Iterate its PDPs
@@ -626,8 +641,8 @@ public class StdEngine extends StdPDPItemSetChangeNotifier implements PAPPolicyE
List<String> 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",
+ properties.setProperty(pdp.getId() + STR_APPEND_NAME, pdp.getName() == null ? "" : pdp.getName());
+ properties.setProperty(pdp.getId() + STR_APPEND_DESCRIPTION,
pdp.getDescription() == null ? "" : pdp.getDescription());
if (pdp instanceof OnapPDP) {
properties.setProperty(pdp.getId() + ".jmxport",
@@ -643,7 +658,7 @@ public class StdEngine extends StdPDPItemSetChangeNotifier implements PAPPolicyE
if (logger.isDebugEnabled()) {
logger.debug("Group " + group.getId() + " PDPS: " + pdpList);
}
- properties.setProperty(group.getId() + ".pdps", pdpList);
+ properties.setProperty(group.getId() + STR_APPEND_PDPS, pdpList);
}
if (ids.isEmpty()) {
throw new PAPException("Inconsistency - we have NO groups. We should have at least one.");
@@ -674,14 +689,12 @@ public class StdEngine extends StdPDPItemSetChangeNotifier implements PAPPolicyE
}
}
- public static void removeGroupProperties(String id, Properties properties) {
- for (Object key : properties.keySet()) {
- if (key.toString().startsWith(id + ".")) {
- properties.remove(key);
- }
- }
- }
-
+ /**
+ * setGroupProperties.
+ *
+ * @param group PDPGroup
+ * @param properties Properties
+ */
public static void setGroupProperties(PDPGroup group, Properties properties) {
//
// make sure its in the list of groups
@@ -711,8 +724,8 @@ public class StdEngine extends StdPDPItemSetChangeNotifier implements PAPPolicyE
//
// Set its properties
//
- properties.setProperty(group.getId() + ".name", group.getName());
- properties.setProperty(group.getId() + ".description", group.getDescription());
+ properties.setProperty(group.getId() + STR_APPEND_NAME, group.getName());
+ properties.setProperty(group.getId() + STR_APPEND_DESCRIPTION, group.getDescription());
//
// Set its PDP list
//
@@ -727,13 +740,15 @@ public class StdEngine extends StdPDPItemSetChangeNotifier implements PAPPolicyE
}
pdpList = Joiner.on(',').skipNulls().join(ids);
}
- properties.setProperty(group.getId() + ".pdps", pdpList);
+ properties.setProperty(group.getId() + STR_APPEND_PDPS, pdpList);
} else {
- properties.setProperty(group.getId() + ".pdps", "");
+ properties.setProperty(group.getId() + STR_APPEND_PDPS, "");
}
}
-
+ /**
+ * changed.
+ */
public void changed() {
if (logger.isDebugEnabled()) {
logger.debug("changed");
@@ -742,6 +757,11 @@ public class StdEngine extends StdPDPItemSetChangeNotifier implements PAPPolicyE
this.fireChanged();
}
+ /**
+ * groupChanged.
+ *
+ * @param group OnapPDPGroup
+ */
public void groupChanged(OnapPDPGroup group) {
if (logger.isDebugEnabled()) {
logger.debug("groupChanged: " + group);
@@ -750,7 +770,11 @@ public class StdEngine extends StdPDPItemSetChangeNotifier implements PAPPolicyE
this.firePDPGroupChanged(group);
}
-
+ /**
+ * pdpChanged.
+ *
+ * @param pdp OnapPDP
+ */
public void pdpChanged(OnapPDP pdp) {
if (logger.isDebugEnabled()) {
logger.debug("pdpChanged: " + pdp);
@@ -766,18 +790,18 @@ public class StdEngine extends StdPDPItemSetChangeNotifier implements PAPPolicyE
//
this.saveConfiguration();
} catch (IOException | PAPException e) {
- PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "StdEngine", "Failed to save configuration");
+ PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, STR_CLASS, "Failed to save configuration");
}
}
- private Properties setPIPProperties(Properties props) {
+ 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)) {
+ Path file = Paths.get(PIP_PROPERTY_FILE);
+ if (file.toFile().exists()) {
InputStream in;
Properties prop = new Properties();
try {
@@ -792,7 +816,6 @@ public class StdEngine extends StdPDPItemSetChangeNotifier implements PAPPolicyE
return props;
}
-
@Override
public Set<OnapPDPGroup> getOnapPDPGroups() throws PAPException {
final Set<OnapPDPGroup> grps = new HashSet<>();
@@ -815,26 +838,26 @@ public class StdEngine extends StdPDPItemSetChangeNotifier implements PAPPolicyE
@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);
+ for (OnapPDPGroup theGroup : groups) {
+ if (theGroup.getId().equals(group.getId())) {
+ if (!theGroup.isDefaultGroup()) {
+ if (theGroup instanceof StdPDPGroup) {
+ ((StdPDPGroup) theGroup).setDefault(true);
changesMade = true;
} else {
throw new IllegalArgumentException(
- "Group in groups of unknown type '" + aGroup.getClass().getName() + "'");
+ "Group in groups of unknown type '" + theGroup.getClass().getName() + "'");
}
}
} else {
// not the new default group
- if (aGroup.isDefaultGroup()) {
- if (aGroup instanceof StdPDPGroup) {
- ((StdPDPGroup) aGroup).setDefault(false);
+ if (theGroup.isDefaultGroup()) {
+ if (theGroup instanceof StdPDPGroup) {
+ ((StdPDPGroup) theGroup).setDefault(false);
changesMade = true;
} else {
throw new IllegalArgumentException(
- "Group in groups of unknown type '" + aGroup.getClass().getName() + "'");
+ "Group in groups of unknown type '" + theGroup.getClass().getName() + "'");
}
}
}
@@ -842,14 +865,11 @@ public class StdEngine extends StdPDPItemSetChangeNotifier implements PAPPolicyE
if (changesMade) {
this.doSave();
}
-
- return;
-
}
@Override
public void newPDP(String id, OnapPDPGroup group, String name, String description, int jmxport)
- throws PAPException, NullPointerException {
+ throws PAPException {
if (group == null) {
throw new PAPException("You must specify which group the PDP will belong to.");
}
@@ -868,10 +888,13 @@ public class StdEngine extends StdPDPItemSetChangeNotifier implements PAPPolicyE
// Save the properties and notify any listeners
//
pdpChanged(pdp);
- return;
}
}
- return;
+ }
+
+ @Override
+ public void updateGroup(OnapPDPGroup group, String userName) throws PAPException {
+ // To pass the userId for PDP Audit log maintenance.
}
@@ -888,7 +911,6 @@ public class StdEngine extends StdPDPItemSetChangeNotifier implements PAPPolicyE
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.
@@ -908,7 +930,7 @@ public class StdEngine extends StdPDPItemSetChangeNotifier implements PAPPolicyE
} else {
// the name/identity of the group has changed
// generate the new id
- String newId = createNewPDPGroupId(group.getName());
+ String newId = createNewPdpGroupId(group.getName());
// make sure no other group uses the new id
for (OnapPDPGroup g : groups) {
@@ -929,7 +951,7 @@ public class StdEngine extends StdPDPItemSetChangeNotifier implements PAPPolicyE
throw new PAPException("Unable to rename directory; reason unknown");
}
} catch (Exception e) {
- PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "StdEngine", "Unable to rename directory");
+ PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, STR_CLASS, "Unable to rename directory");
throw new PAPException(
"Unable to move directory from '" + oldPath + "' to '" + newPath + "': " + e.getMessage(), e);
}
@@ -950,11 +972,10 @@ public class StdEngine extends StdPDPItemSetChangeNotifier implements PAPPolicyE
// 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 {
+ public void removeGroup(OnapPDPGroup group, OnapPDPGroup newGroup) throws PAPException {
if (group == null) {
throw new NullPointerException();
}
@@ -1005,7 +1026,7 @@ public class StdEngine extends StdPDPItemSetChangeNotifier implements PAPPolicyE
//
// If it exists already
//
- if (!Files.exists(groupPath)) {
+ if (! groupPath.toFile().exists()) {
logger.warn("removeGroup " + id + " directory does not exist" + groupPath.toString());
} else {
try {
@@ -1023,7 +1044,7 @@ public class StdEngine extends StdPDPItemSetChangeNotifier implements PAPPolicyE
//
Files.delete(groupPath);
} catch (IOException e) {
- PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "StdEngine", "Failed to delete " + groupPath);
+ PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, STR_CLASS, "Failed to delete " + groupPath);
throw new PAPException("Failed to delete " + id);
}
}
@@ -1036,14 +1057,6 @@ public class StdEngine extends StdPDPItemSetChangeNotifier implements PAPPolicyE
//
changed();
this.doSave();
- return;
-
- }
-
- @Override
- public void updateGroup(OnapPDPGroup group, String userName) throws PAPException {
- // To pass the userId for PDP Audit log maintenance.
-
}
}
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
index dd8a92135..b6a194361 100644
--- 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
@@ -2,14 +2,14 @@
* ============LICENSE_START=======================================================
* ONAP-XACML
* ================================================================================
- * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -17,41 +17,40 @@
* 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 com.att.research.xacml.api.pap.PAPException;
+import com.att.research.xacml.util.FactoryException;
import java.io.IOException;
import java.util.Properties;
+import org.onap.policy.common.logging.eelf.MessageCodes;
+import org.onap.policy.common.logging.eelf.PolicyLogger;
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 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 new StdEngine(properties);
- } catch (IOException e) {
- PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "StdEngineFactory", "Failed to create engine");
- return null;
- }
- }
-
+
+ @Override
+ public PAPPolicyEngine newEngine() throws FactoryException, PAPException {
+ try {
+ return 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 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
index 2f752a0aa..41b0c05d7 100644
--- 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
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP-XACML
* ================================================================================
- * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
* Modifications Copyright (C) 2018 Samsung Electronics Co., Ltd.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
@@ -18,6 +18,7 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.policy.xacml.std.pap;
import java.io.Serializable;
@@ -89,12 +90,19 @@ public class StdPAPPolicy implements OnapPAPPolicy, Serializable {
//
}
- //Constructor for sending location when pushing policies
+ // Constructor for sending location when pushing policies
public StdPAPPolicy(URI location) {
this.location = location;
}
- //Constructor for Validating Config Policies
+ /**
+ * Constructor for Validating Config Policies.
+ *
+ * @param policyName String
+ * @param body String
+ * @param configType String
+ * @param configPolicyType String
+ */
public StdPAPPolicy(String policyName, String body, String configType, String configPolicyType) {
this.policyName = policyName;
this.configBodyData = body;
@@ -103,15 +111,16 @@ public class StdPAPPolicy implements OnapPAPPolicy, Serializable {
}
/**
- * Constructor for
- * Create Config Policies from API and Admin Console
- * Updating Config Policies from the API
- * Create/Update Action Policies from API
- * Create/Update Decision Policies
+ * Constructor.
+ * Create Config Policies from API and Admin Console
+ * Updating Config Policies from the API
+ * Create/Update Action Policies from API
+ * Create/Update Decision Policies
+ *
* @param stdPAPPolicyParams Input params object
*/
public StdPAPPolicy(StdPAPPolicyParams stdPAPPolicyParams) {
- this.configPolicyType=stdPAPPolicyParams.getConfigPolicyType();
+ this.configPolicyType = stdPAPPolicyParams.getConfigPolicyType();
this.policyName = stdPAPPolicyParams.getPolicyName();
this.policyDescription = stdPAPPolicyParams.getDescription();
this.onapName = stdPAPPolicyParams.getOnapName();
@@ -391,31 +400,25 @@ public class StdPAPPolicy implements OnapPAPPolicy, Serializable {
@Override
public String toString() {
return "StdPAPPolicy [policyName=" + policyName + ", policyDescription=" + policyDescription + ", onapName="
- + onapName + ", configName=" + configName + ", dynamicFieldConfigAttributes=" +
- dynamicFieldConfigAttributes + ", 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
- + ",treatments=" + treatments + "]";
+ + onapName + ", configName=" + configName + ", dynamicFieldConfigAttributes="
+ + dynamicFieldConfigAttributes + ", 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 + ",treatments=" + treatments
+ + "]";
}
// Methods needed for JSON Deserialization
@@ -435,8 +438,7 @@ public class StdPAPPolicy implements OnapPAPPolicy, Serializable {
this.configName = configName;
}
- public void setDynamicFieldConfigAttributes(
- Map<String, String> dynamicFieldConfigAttributes) {
+ public void setDynamicFieldConfigAttributes(Map<String, String> dynamicFieldConfigAttributes) {
this.dynamicFieldConfigAttributes = dynamicFieldConfigAttributes;
}
@@ -484,8 +486,7 @@ public class StdPAPPolicy implements OnapPAPPolicy, Serializable {
this.location = location;
}
- public void setDynamicRuleAlgorithmLabels(
- List<String> dynamicRuleAlgorithmLabels) {
+ public void setDynamicRuleAlgorithmLabels(List<String> dynamicRuleAlgorithmLabels) {
this.dynamicRuleAlgorithmLabels = dynamicRuleAlgorithmLabels;
}
@@ -493,13 +494,11 @@ public class StdPAPPolicy implements OnapPAPPolicy, Serializable {
this.dynamicRuleAlgorithmCombo = dynamicRuleAlgorithmCombo;
}
- public void setDynamicRuleAlgorithmField1(
- List<String> dynamicRuleAlgorithmField1) {
+ public void setDynamicRuleAlgorithmField1(List<String> dynamicRuleAlgorithmField1) {
this.dynamicRuleAlgorithmField1 = dynamicRuleAlgorithmField1;
}
- public void setDynamicRuleAlgorithmField2(
- List<String> dynamicRuleAlgorithmField2) {
+ public void setDynamicRuleAlgorithmField2(List<String> dynamicRuleAlgorithmField2) {
this.dynamicRuleAlgorithmField2 = dynamicRuleAlgorithmField2;
}
@@ -638,7 +637,7 @@ public class StdPAPPolicy implements OnapPAPPolicy, Serializable {
public void setTreatments(Map<String, String> treatments) {
this.treatments = treatments;
}
-
+
public String getRawXacmlPolicy() {
return rawXacmlPolicy;
}
diff --git a/ONAP-XACML/src/main/java/org/onap/policy/xacml/std/pap/StdPAPPolicyParams.java b/ONAP-XACML/src/main/java/org/onap/policy/xacml/std/pap/StdPAPPolicyParams.java
index 1780dfc96..b7057175e 100644
--- a/ONAP-XACML/src/main/java/org/onap/policy/xacml/std/pap/StdPAPPolicyParams.java
+++ b/ONAP-XACML/src/main/java/org/onap/policy/xacml/std/pap/StdPAPPolicyParams.java
@@ -3,7 +3,7 @@
* ONAP-XACML
* ================================================================================
* Copyright (C) 2018 Samsung Electronics Co., Ltd. All rights reserved.
- * Modifications Copyright (C) 2018 AT&T Intellectual Property.
+ * Modifications Copyright (C) 2018-2019 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.
@@ -54,14 +54,14 @@ public class StdPAPPolicyParams {
private List<Object> dynamicVariableList;
private List<String> dataTypeList;
private Map<String, String> dropDownMap;
- private Map<String,String> treatments;
+ private Map<String, String> treatments;
private String policyID;
private String ruleID;
private String version;
private String jsonBody;
private String brmsController;
private List<String> brmsDependency;
- private Map<String,String> drlRuleAndUIParams;
+ private Map<String, String> drlRuleAndUIParams;
private boolean draft;
private String oldPolicyFileName;
private String serviceType;
@@ -75,8 +75,7 @@ public class StdPAPPolicyParams {
private String rawXacmlPolicy = null;
/**
-
- * Default constructor
+ * Default constructor.
*/
private StdPAPPolicyParams() {
super();
@@ -186,7 +185,7 @@ public class StdPAPPolicyParams {
return providerComboBox;
}
- public Map<String,String> getDynamicSettingsMap() {
+ public Map<String, String> getDynamicSettingsMap() {
return dynamicSettingsMap;
}
@@ -198,11 +197,11 @@ public class StdPAPPolicyParams {
return dataTypeList;
}
- public Map<String,String> getDropDownMap() {
+ public Map<String, String> getDropDownMap() {
return dropDownMap;
}
- public Map<String,String> getTreatments() {
+ public Map<String, String> getTreatments() {
return treatments;
}
@@ -230,7 +229,7 @@ public class StdPAPPolicyParams {
return brmsDependency;
}
- public Map<String,String> getDrlRuleAndUIParams() {
+ public Map<String, String> getDrlRuleAndUIParams() {
return drlRuleAndUIParams;
}
@@ -269,8 +268,9 @@ public class StdPAPPolicyParams {
public String getRawXacmlPolicy() {
return rawXacmlPolicy;
}
+
/**
- * Builder class for the Policy parameters
+ * Builder class for the Policy parameters.
*/
public static class StdPAPPolicyParamsBuilder {
StdPAPPolicyParams m = new StdPAPPolicyParams();
@@ -284,7 +284,6 @@ public class StdPAPPolicyParams {
return this;
}
-
public StdPAPPolicyParamsBuilder policyName(String policyName) {
m.policyName = policyName;
return this;
@@ -405,12 +404,12 @@ public class StdPAPPolicyParams {
return this;
}
- public StdPAPPolicyParamsBuilder dropDownMap(Map<String, String> dropDownMap){
+ public StdPAPPolicyParamsBuilder dropDownMap(Map<String, String> dropDownMap) {
m.dropDownMap = dropDownMap;
return this;
}
- public StdPAPPolicyParamsBuilder treatments(Map<String,String> treatments) {
+ public StdPAPPolicyParamsBuilder treatments(Map<String, String> treatments) {
m.treatments = treatments;
return this;
}
@@ -445,13 +444,13 @@ public class StdPAPPolicyParams {
return this;
}
- public StdPAPPolicyParamsBuilder drlRuleAndUIParams(Map<String,String> drlRuleAndUIParams) {
+ public StdPAPPolicyParamsBuilder drlRuleAndUIParams(Map<String, String> drlRuleAndUIParams) {
m.drlRuleAndUIParams = drlRuleAndUIParams;
return this;
}
- public StdPAPPolicyParamsBuilder draft(boolean b) {
- m.draft = b;
+ public StdPAPPolicyParamsBuilder draft(boolean isDraft) {
+ m.draft = isDraft;
return this;
}
@@ -460,8 +459,8 @@ public class StdPAPPolicyParams {
return this;
}
- public StdPAPPolicyParamsBuilder serviceType(String s) {
- m.serviceType = s;
+ public StdPAPPolicyParamsBuilder serviceType(String serviceType) {
+ m.serviceType = serviceType;
return this;
}
@@ -499,7 +498,7 @@ public class StdPAPPolicyParams {
m.dictionaryFields = dictionaryFields;
return this;
}
-
+
public StdPAPPolicyParamsBuilder rawXacmlPolicy(String rawXacmlPolicy) {
m.rawXacmlPolicy = rawXacmlPolicy;
return this;
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
index 8727b8185..dcebc86fc 100644
--- 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
@@ -2,14 +2,14 @@
* ============LICENSE_START=======================================================
* ONAP-XACML
* ================================================================================
- * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -17,8 +17,13 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.policy.xacml.std.pap;
+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 java.io.Serializable;
import java.util.Collections;
import java.util.HashSet;
@@ -27,196 +32,209 @@ 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<StdPDP>, 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 transient PDPStatus status = new StdPDPStatus();
-
- private transient Set<PDPPolicy> policies = new HashSet<>();
-
- private transient Set<PDPPIPConfig> pipConfigs = new HashSet<>();
-
- public StdPDP() {
- //
- // Default constructor
- //
- }
-
- 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")) {
- 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<PDPPolicy> getPolicies() {
- return Collections.unmodifiableSet(this.policies);
- }
-
- public void setPolicies(Set<PDPPolicy> policies) {
- this.policies = policies;
- }
-
- @Override
- public Set<PDPPIPConfig> getPipConfigs() {
- return Collections.unmodifiableSet(this.pipConfigs);
- }
-
- public void setPipConfigs(Set<PDPPIPConfig> pipConfigs) {
- this.pipConfigs = pipConfigs;
- }
-
- @Override
- 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.name == null) {
- return -1;
- }
- if (name == null) {
- return 1;
- }
- return name.compareTo(o.name);
- }
-
+ private static final long serialVersionUID = 1L;
+
+ private String id;
+
+ private String name;
+
+ private String description;
+
+ private Integer jmxport = 0;
+
+ private transient PDPStatus status = new StdPDPStatus();
+
+ private transient Set<PDPPolicy> policies = new HashSet<>();
+
+ private transient Set<PDPPIPConfig> pipConfigs = new HashSet<>();
+
+ public StdPDP() {
+ //
+ // Default constructor
+ //
+ }
+
+ public StdPDP(String id, Integer jmxport) {
+ this(id, null, null, jmxport);
+ }
+
+ public StdPDP(String id, String name, Integer jmxport) {
+ this(id, name, null, jmxport);
+ }
+
+ /**
+ * StdPDP.
+ *
+ * @param id String
+ * @param name String
+ * @param description String
+ * @param jmxport Integer
+ */
+ 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;
+ }
+ }
+
+ /**
+ * StdPDP.
+ *
+ * @param id String
+ * @param properties Properties
+ */
+ public StdPDP(String id, Properties properties) {
+ this(id, 0);
+
+ this.initialize(properties);
+ }
+
+ /**
+ * initialize.
+ *
+ * @param properties Properties
+ */
+ public void initialize(Properties 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(".jmxport")) {
+ if (properties.getProperty(key.toString()) != null
+ && properties.getProperty(key.toString()).trim().length() > 0) {
+ this.jmxport = Integer.valueOf(properties.getProperty(key.toString()));
+ } 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<PDPPolicy> getPolicies() {
+ return Collections.unmodifiableSet(this.policies);
+ }
+
+ public void setPolicies(Set<PDPPolicy> policies) {
+ this.policies = policies;
+ }
+
+ @Override
+ public Set<PDPPIPConfig> getPipConfigs() {
+ return Collections.unmodifiableSet(this.pipConfigs);
+ }
+
+ public void setPipConfigs(Set<PDPPIPConfig> pipConfigs) {
+ this.pipConfigs = pipConfigs;
+ }
+
+ @Override
+ 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 object) {
+ if (object == null) {
+ return -1;
+ }
+ if (object.name == null) {
+ return -1;
+ }
+ if (name == null) {
+ return 1;
+ }
+ return name.compareTo(object.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
index bdbbf33f7..daa3764d8 100644
--- 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
@@ -2,14 +2,14 @@
* ============LICENSE_START=======================================================
* ONAP-XACML
* ================================================================================
- * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -17,8 +17,21 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.policy.xacml.std.pap;
+import com.att.research.xacml.api.pap.PAPException;
+import com.att.research.xacml.api.pap.PDP;
+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;
+
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
@@ -35,7 +48,8 @@ import java.util.List;
import java.util.Properties;
import java.util.Set;
import java.util.TreeSet;
-
+import lombok.EqualsAndHashCode;
+import lombok.ToString;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.onap.policy.common.logging.eelf.MessageCodes;
@@ -45,1000 +59,995 @@ 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.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;
+@EqualsAndHashCode(callSuper = false)
+@ToString
+public class StdPDPGroup extends StdPDPItemSetChangeNotifier
+ implements OnapPDPGroup, StdItemSetChangeListener, Comparable<Object>, Serializable {
+
+ private static final long serialVersionUID = 1L;
+ private static final String MSG_GROUPNOTEXIST = "Group directory does NOT exist";
+ private static final String MSG_LOADFAILURE = "Failed to load group policy properties file: ";
+ private static final String STR_APPEND_NAME = ".name";
+ private static final String STR_APPEND_DESCRIPTION = ".description";
+ private static final String STR_APPEND_PDPS = ".pdps";
+ private static final String STR_CLASS = "StdPDPGroup";
+ private static final String PROPS_POLICY = "xacml.policy.properties";
+ private static final String PROPS_PIP = "xacml.pip.properties";
+
+ private static Log logger = LogFactory.getLog(StdPDPGroup.class);
+
+ private String id;
+
+ private boolean isDefault = false;
+
+ private String name;
+
+ private String description;
+
+ private transient StdPDPGroupStatus status = new StdPDPGroupStatus(Status.UNKNOWN);
+
+ private transient Set<OnapPDP> pdps = new HashSet<>();
+
+ private transient Set<PDPPolicy> policies = new HashSet<>();
+
+ private transient Set<PDPPolicy> selectedPolicies = new HashSet<>();
+
+ private transient Set<PDPPIPConfig> pipConfigs = new HashSet<>();
+
+ private String operation;
+
+ @JsonIgnore
+ private transient Path directory;
+
+ @JsonIgnore
+ private Integer jmxport;
+
+ public StdPDPGroup() {
+ //
+ // Methods needed for JSON deserialization
+ //
+ }
+
+ /**
+ * StdPDPGroup constructor.
+ *
+ * @param group OnapPDPGroup
+ */
+ 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 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;
+ }
+
+ /**
+ * StdPDPGroup.
+ *
+ * @param id String
+ * @param isDefault boolean
+ * @param name String
+ * @param description String
+ * @param directory Path
+ */
+ 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();
+ }
+
+ /**
+ * StdPDPGroup.
+ *
+ * @param id String
+ * @param isDefault boolean
+ * @param properties Properties
+ * @param directory Path
+ * @throws PAPException PAPException
+ */
+ 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(STR_APPEND_NAME)) {
+ this.name = properties.getProperty(key.toString());
+ } else if (key.toString().endsWith(STR_APPEND_DESCRIPTION)) {
+ this.description = properties.getProperty(key.toString());
+ } else if (key.toString().endsWith(STR_APPEND_PDPS)) {
+ String pdpList = properties.getProperty(key.toString());
+ if (pdpList != null && pdpList.length() > 0) {
+ for (String pdpId : Splitter.on(',').omitEmptyStrings().trimResults().split(pdpList)) {
+ StdPDP pdp = new StdPDP(pdpId, 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 (! directory.toFile().exists()) {
+ logger.warn("Group directory does NOT exist: " + directory.toString());
+ try {
+ Files.createDirectory(directory);
+ this.status.addLoadWarning(MSG_GROUPNOTEXIST);
+ } catch (IOException e) {
+ PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, STR_CLASS, MSG_GROUPNOTEXIST);
+ this.status.addLoadError(MSG_GROUPNOTEXIST);
+ this.status.setStatus(PDPGroupStatus.Status.LOAD_ERRORS);
+ }
+ }
+ //
+ // Parse policies
+ //
+ this.loadPolicies(Paths.get(directory.toString(), PROPS_POLICY));
+ //
+ // Parse pip config
+ //
+ this.loadPIPConfig(Paths.get(directory.toString(), PROPS_PIP));
+ }
+
+ /**
+ * loadPolicies.
+ *
+ * @param file Path
+ * @throws PAPException PAPException
+ */
+ 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 + "'", e);
+ }
+ } 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(MSG_LOADFAILURE + file, e);
+ this.status.addLoadError("Not policy properties defined");
+ this.status.setStatus(Status.LOAD_ERRORS);
+ throw new PAPException(MSG_LOADFAILURE + file);
+ }
+ }
+ }
+
+ /**
+ * loadPIPConfig.
+ *
+ * @param file Path
+ * @throws PAPException PAPException
+ */
+ 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 + "'", e);
+ }
+ // Even if we create a new pip file, we still need to parse and load the properties
+ try {
+ this.readPipProperties(pipProperties);
+ } catch (Exception e) {
+ throw new PAPException("Failed to load the new pip properties file", e);
+ }
+ } 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 ("".equals(pipProperties.get(XACMLProperties.PROP_PIP_ENGINES).toString().trim())) {
+ pipProperties = setPipProperties(pipProperties);
+ try (OutputStream os = Files.newOutputStream(file)) {
+ pipProperties.store(os, "");
+ }
+ }
+ //
+ // Parse the pips
+ //
+ this.readPipProperties(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(MSG_LOADFAILURE + file);
+
+ }
+ }
+ }
+
+ /**
+ * resetStatus.
+ */
+ public void resetStatus() {
+ //
+ // 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().isEmpty()) {
+ this.status.setStatus(Status.UNKNOWN);
+ } else if (!this.status.getFailedPDPs().isEmpty() || !this.status.getLastUpdateFailedPDPs().isEmpty()) {
+ this.status.setStatus(Status.LOAD_ERRORS);
+ } else if (!this.status.getOutOfSynchPDPs().isEmpty()) {
+ this.status.setStatus(Status.OUT_OF_SYNCH);
+ } else if (!this.status.getUpdatingPDPs().isEmpty()) {
+ 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;
+ }
+
+ /**
+ * setDefaultGroup.
+ *
+ * @param isDefault boolean
+ */
+ 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.
+ }
+
+ @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<PDPPolicy> getSelectedPolicies() {
+ return this.selectedPolicies;
+ }
+
+ @Override
+ public String getOperation() {
+ return this.operation;
+ }
+
+ @Override
+ public Set<PDP> getPdps() {
+ return Collections.unmodifiableSet(pdps);
+ }
+
+ public void setOnapPdps(Set<OnapPDP> pdps) {
+ this.pdps = pdps;
+ }
+
+ @Override
+ public Set<OnapPDP> 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<PDPPolicy> 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;
+ }
+
+ @Override
+ 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<Object> keys() {
+ return Collections.enumeration(new TreeSet<Object>(super.keySet()));
+ }
+ };
+ List<String> roots = new ArrayList<>();
+ List<String> 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() + STR_APPEND_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;
+ }
+
+ /**
+ * publishPolicy.
+ *
+ * @param id String
+ * @param name String
+ * @param isRoot boolean
+ * @param policy InputStream
+ * @return PDPPolicy
+ * @throws PAPException PAPException
+ */
+ 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()) {
+ try {
+ Files.delete(tempFile);
+ } catch (Exception ee) {
+ PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, ee, STR_CLASS,
+ "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, STR_CLASS, "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 String
+ * @param policy InputStream
+ * @throws PAPException PAPException
+ */
+ public void copyPolicyToFile(String id, InputStream policy) throws PAPException {
+ copyPolicyToFile(id, this.name, policy);
+ }
+
+ /**
+ * Policy Engine API Copy one policy file into the Group's directory but do not change the configuration.
+ *
+ * @param id String
+ * @param fileName String
+ * @param policy InputStream
+ * @throws PAPException PAPException
+ */
+ public void copyPolicyToFile(String id, String fileName, InputStream policy) throws PAPException {
+ try {
+ //
+ // Copy the policy over
+ //
+ long num;
+ Path policyFilePath = Paths.get(this.directory.toAbsolutePath().toString(), id);
+
+ Path policyFile;
+ if (policyFilePath.toFile().exists()) {
+ 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 " + fileName);
+ 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, fileName, policyFile.toUri());
+ if (!tempRootPolicy.isValid()) {
+ try {
+ Files.delete(policyFile);
+ } catch (Exception ee) {
+ PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, ee, STR_CLASS,
+ "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, STR_CLASS, "Failed to copyPolicyToFile");
+ throw new PAPException("Failed to copy policy to file: " + e);
+ }
+ }
+
+ /**
+ * removePolicyFromGroup.
+ *
+ * @param policy PDPPolicy
+ * @return boolean
+ */
+ 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, STR_CLASS, "Failed to delete policy");
+ }
+ return false;
+ }
+
+ /**
+ * removePolicy.
+ *
+ * @param policy PDPPolicy
+ * @return boolean
+ */
+ public boolean removePolicy(PDPPolicy policy) {
+ PDPPolicy currentPolicy = 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, STR_CLASS, "Failed to delete policy " + policy);
+ }
+ return false;
+ }
+
+ @Override
+ public Set<PDPPIPConfig> 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<PDPPIPConfig> pipConfigs) {
+ this.pipConfigs = pipConfigs;
+ this.firePDPGroupChanged(this);
+ }
+
+ public void removeAllPIPConfigs() {
+ this.pipConfigs.clear();
+ this.firePDPGroupChanged(this);
+ }
+
+ @Override
+ public Properties getPipConfigProperties() {
+ Properties properties = new Properties();
+ List<String> 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 (! directory.toFile().exists()) {
+ 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, STR_CLASS,
+ "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(), PROPS_PIP);
+ if (! pipPropertiesFile.toFile().exists()) {
+ try {
+ Files.createFile(pipPropertiesFile);
+ fire = true;
+ this.status.addLoadWarning("Created missing PIP properties file");
+ } catch (IOException e) {
+ PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, STR_CLASS,
+ "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(), PROPS_POLICY);
+ if (! policyPropertiesFile.toFile().exists()) {
+ try {
+ Files.createFile(policyPropertiesFile);
+ fire = true;
+ this.status.addLoadWarning("Created missing Policy properties file");
+ } catch (IOException e) {
+ PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, STR_CLASS,
+ "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<String> policyList = Splitter.on(',').trimResults().omitEmptyStrings().split(list);
+ //
+ // Was there actually a list
+ //
+ if (policyList == null) {
+ isRoot = false;
+ continue;
+ }
+ for (String policyId : policyList) {
+ //
+ // Construct the policy filename
+ //
+ Path policyPath = Paths.get(directory.toString(), policyId);
+ //
+ // 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, STR_CLASS,
+ "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(Properties properties) {
+ String list = properties.getProperty(XACMLProperties.PROP_PIP_ENGINES);
+ if (list == null || list.length() == 0) {
+ return;
+ }
+ for (String pipId : list.split("[,]")) {
+ StdPDPPIPConfig config = new StdPDPPIPConfig(pipId, 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 void changed() {
+
+ // save the (changed) properties
+ try {
+ saveGroupConfiguration();
+ } catch (PAPException | IOException e) {
+ PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, STR_CLASS,
+ "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();
+ }
+
+ public boolean isDefault() {
+ return isDefault;
+ }
-public class StdPDPGroup extends StdPDPItemSetChangeNotifier implements OnapPDPGroup, StdItemSetChangeListener, Comparable<Object>, Serializable {
-
- private static final long serialVersionUID = 1L;
- private static final String groupNotExist= "Group directory does NOT exist";
- private static Log logger = LogFactory.getLog(StdPDPGroup.class);
-
- private String id;
-
- private boolean isDefault = false;
-
- private String name;
-
- private String description;
-
- private transient StdPDPGroupStatus status = new StdPDPGroupStatus(Status.UNKNOWN);
-
- private transient Set<OnapPDP> pdps = new HashSet<>();
-
- private transient Set<PDPPolicy> policies = new HashSet<>();
-
- private transient Set<PDPPolicy> selectedPolicies = new HashSet<>();
-
- private transient Set<PDPPIPConfig> pipConfigs = new HashSet<>();
-
- private String operation;
-
- @JsonIgnore
- private transient Path directory;
-
- @JsonIgnore
- private Integer jmxport;
-
- public StdPDPGroup() {
- //
- // Methods needed for JSON deserialization
- //
- }
-
- 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 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 pdpId : Splitter.on(',').omitEmptyStrings().trimResults().split(pdpList)) {
- StdPDP pdp = new StdPDP(pdpId, 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(groupNotExist);
- } catch (IOException e) {
- PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "StdPDPGroup", groupNotExist);
- this.status.addLoadError(groupNotExist);
- 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 +"'", e);
- }
- } 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 +"'", e);
- }
- //Even if we create a new pip file, we still need to parse and load the properties
- try{
- this.readPIPProperties(pipProperties);
- }catch(Exception e){
- throw new PAPException("Failed to load the new pip properties file", e);
- }
- } 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("".equals(pipProperties.get(XACMLProperties.PROP_PIP_ENGINES).toString().trim())){
- pipProperties = setPIPProperties(pipProperties);
- try (OutputStream os = Files.newOutputStream(file)) {
- pipProperties.store(os, "");
- }
- }
- //
- // Parse the pips
- //
- this.readPIPProperties(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() {
- //
- // 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().isEmpty()) {
- this.status.setStatus(Status.UNKNOWN);
- } else if (!this.status.getFailedPDPs().isEmpty() || !this.status.getLastUpdateFailedPDPs().isEmpty()) {
- this.status.setStatus(Status.LOAD_ERRORS);
- } else if (!this.status.getOutOfSynchPDPs().isEmpty()) {
- this.status.setStatus(Status.OUT_OF_SYNCH);
- } else if (!this.status.getUpdatingPDPs().isEmpty()) {
- 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.
- }
-
- @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<PDPPolicy> getSelectedPolicies() {
- return this.selectedPolicies;
- }
-
- @Override
- public String getOperation() {
- return this.operation;
- }
-
- @Override
- public Set<PDP> getPdps() {
- return Collections.unmodifiableSet(pdps);
- }
-
- public void setOnapPdps(Set<OnapPDP> pdps) {
- this.pdps = pdps;
- }
-
- @Override
- public Set<OnapPDP> 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<PDPPolicy> 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;
- }
-
- @Override
- 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<Object> keys() {
- return Collections.enumeration(new TreeSet<Object>(super.keySet()));
- }
- };
- List<String> roots = new ArrayList<>();
- List<String> 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()) {
- 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()) {
- 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()) {
- 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) {
- PDPPolicy currentPolicy = 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<PDPPIPConfig> 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<PDPPIPConfig> pipConfigs) {
- this.pipConfigs = pipConfigs;
- this.firePDPGroupChanged(this);
- }
-
- public void removeAllPIPConfigs() {
- this.pipConfigs.clear();
- this.firePDPGroupChanged(this);
- }
-
- @Override
- public Properties getPipConfigProperties() {
- Properties properties = new Properties();
- List<String> 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<String> policyList = Splitter.on(',').trimResults().omitEmptyStrings().split(list);
- //
- // Was there actually a list
- //
- if (policyList == null) {
- isRoot = false;
- continue;
- }
- for (String policyId : policyList) {
- //
- // Construct the policy filename
- //
- Path policyPath = Paths.get(directory.toString(), policyId );
- //
- // 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(Properties properties) {
- String list = properties.getProperty(XACMLProperties.PROP_PIP_ENGINES);
- if (list == null || list.length() == 0) {
- return;
- }
- for (String pipId : list.split("[,]")) {
- StdPDPPIPConfig config = new StdPDPPIPConfig(pipId, 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();
- }
-
- 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<PDPPolicy> policies) {
- this.policies = policies;
- }
- public void setSelectedPolicies(Set<PDPPolicy> 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;
- }
+ public void setStatus(PDPGroupStatus status) {
+ this.status = new StdPDPGroupStatus(status);
+ }
+
+ public void setPolicies(Set<PDPPolicy> policies) {
+ this.policies = policies;
+ }
+
+ public void setSelectedPolicies(Set<PDPPolicy> selectedPolicies) {
+ this.selectedPolicies = selectedPolicies;
+ }
+
+ public void setOperation(String operation) {
+ this.operation = operation;
+ }
+
+ /**
+ * saveGroupConfiguration.
+ *
+ * @throws PAPException PAPException
+ * @throws IOException IOException
+ */
+ 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() + STR_APPEND_NAME, policy.getName());
+ }
+
+ //
+ // Now we can save the file
+ //
+ Path file = Paths.get(this.directory.toString(), PROPS_POLICY);
+ 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(), PROPS_PIP);
+ try (OutputStream os = Files.newOutputStream(file)) {
+ pipProperties.store(os, "");
+ } catch (Exception e) {
+ PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, STR_CLASS, "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.PIP_PROPERTY_FILE);
+ if (file.toFile().exists()) {
+ 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
index dd9bf0a2c..3b93b8d66 100644
--- 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
@@ -2,14 +2,14 @@
* ============LICENSE_START=======================================================
* ONAP-XACML
* ================================================================================
- * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -17,11 +17,8 @@
* 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;
+package org.onap.policy.xacml.std.pap;
import com.att.research.xacml.api.pap.PDP;
import com.att.research.xacml.api.pap.PDPGroupStatus;
@@ -29,391 +26,318 @@ import com.att.research.xacml.api.pap.PDPPIPConfig;
import com.att.research.xacml.api.pap.PDPPolicy;
import com.fasterxml.jackson.annotation.JsonIgnore;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.Set;
+import lombok.EqualsAndHashCode;
+import lombok.ToString;
+
+@EqualsAndHashCode(callSuper=false)
+@ToString
public class StdPDPGroupStatus implements PDPGroupStatus {
-
- private Status status = Status.UNKNOWN;
-
- private Set<String> loadErrors = new HashSet<>();
-
- private Set<String> loadWarnings = new HashSet<>();
-
- private Set<PDPPolicy> loadedPolicies = new HashSet<>();
-
- private Set<PDPPolicy> failedPolicies = new HashSet<>();
-
- private Set<PDPPIPConfig> loadedPIPConfigs = new HashSet<>();
-
- private Set<PDPPIPConfig> failedPIPConfigs = new HashSet<>();
-
- private Set<PDP> inSynchPDPs = new HashSet<>();
-
- private Set<PDP> outOfSynchPDPs = new HashSet<>();
-
- private Set<PDP> failedPDPs = new HashSet<>();
-
- private Set<PDP> updatingPDPs = new HashSet<>();
-
- private Set<PDP> lastUpdateFailedPDPs = new HashSet<>();
-
- private Set<PDP> unknownPDPs = new HashSet<>();
-
-
-
- public StdPDPGroupStatus() {
- //
- // Constructor needed for JSON deserialization
- //
- }
-
- 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<PDPPIPConfig> getLoadedPIPConfigs() {
- return loadedPIPConfigs;
- }
- public void setLoadedPIPConfigs(Set<PDPPIPConfig> loadedPIPConfigs) {
- this.loadedPIPConfigs = loadedPIPConfigs;
- }
- public Set<PDPPIPConfig> getFailedPIPConfigs() {
- return failedPIPConfigs;
- }
- public void setFailedPIPConfigs(Set<PDPPIPConfig> failedPIPConfigs) {
- this.failedPIPConfigs = failedPIPConfigs;
- }
- public Set<PDP> getUnknownPDPs() {
- return unknownPDPs;
- }
- public void setUnknownPDPs(Set<PDP> unknownPDPs) {
- this.unknownPDPs = unknownPDPs;
- }
- public void setLoadErrors(Set<String> loadErrors) {
- this.loadErrors = loadErrors;
- }
- public void setLoadWarnings(Set<String> loadWarnings) {
- this.loadWarnings = loadWarnings;
- }
- public void setLoadedPolicies(Set<PDPPolicy> loadedPolicies) {
- this.loadedPolicies = loadedPolicies;
- }
- public void setFailedPolicies(Set<PDPPolicy> failedPolicies) {
- this.failedPolicies = failedPolicies;
- }
- public void setInSynchPDPs(Set<PDP> inSynchPDPs) {
- this.inSynchPDPs = inSynchPDPs;
- }
- public void setOutOfSynchPDPs(Set<PDP> outOfSynchPDPs) {
- this.outOfSynchPDPs = outOfSynchPDPs;
- }
- public void setFailedPDPs(Set<PDP> failedPDPs) {
- this.failedPDPs = failedPDPs;
- }
- public void setUpdatingPDPs(Set<PDP> updatingPDPs) {
- this.updatingPDPs = updatingPDPs;
- }
- public void setLastUpdateFailedPDPs(Set<PDP> lastUpdateFailedPDPs) {
- this.lastUpdateFailedPDPs = lastUpdateFailedPDPs;
- }
-
-
- @Override
- public Status getStatus() {
- return status;
- }
-
- public void setStatus(Status status) {
- this.status = status;
- }
-
- @Override
- public Set<String> getLoadErrors() {
- return Collections.unmodifiableSet(this.loadErrors);
- }
-
- public void addLoadError(String error) {
- this.loadErrors.add(error);
- }
-
- @Override
- public Set<String> getLoadWarnings() {
- return Collections.unmodifiableSet(this.loadWarnings);
- }
-
- public void addLoadWarning(String warning) {
- this.loadWarnings.add(warning);
- }
-
- @Override
- public Set<PDPPolicy> getLoadedPolicies() {
- return Collections.unmodifiableSet(this.loadedPolicies);
- }
-
- public void addLoadedPolicy(PDPPolicy policy) {
- this.loadedPolicies.add(policy);
- }
-
- @Override
- public Set<PDPPolicy> getFailedPolicies() {
- return Collections.unmodifiableSet(this.failedPolicies);
- }
-
- public void addFailedPolicy(PDPPolicy policy) {
- this.failedPolicies.add(policy);
- }
-
- @Override
- public boolean policiesOK() {
- if (!this.failedPolicies.isEmpty()) {
- return false;
- }
- return true;
- }
-
- @Override
- public Set<PDPPIPConfig> getLoadedPipConfigs() {
- return Collections.unmodifiableSet(this.loadedPIPConfigs);
- }
-
- public void addLoadedPipConfig(PDPPIPConfig config) {
- this.loadedPIPConfigs.add(config);
- }
-
- @Override
- public Set<PDPPIPConfig> getFailedPipConfigs() {
- return Collections.unmodifiableSet(this.failedPIPConfigs);
- }
-
- public void addFailedPipConfig(PDPPIPConfig config) {
- this.failedPIPConfigs.add(config);
- }
-
- @Override
- public boolean pipConfigOK() {
- if (!this.failedPIPConfigs.isEmpty()) {
- return false;
- }
- return true;
- }
-
- @Override
- public Set<PDP> getInSynchPDPs() {
- return Collections.unmodifiableSet(this.inSynchPDPs);
- }
-
- public void addInSynchPDP(PDP pdp) {
- this.inSynchPDPs.add(pdp);
- }
-
- @Override
- public Set<PDP> getOutOfSynchPDPs() {
- return Collections.unmodifiableSet(this.outOfSynchPDPs);
- }
-
- public void addOutOfSynchPDP(PDP pdp) {
- this.outOfSynchPDPs.add(pdp);
- }
-
- @Override
- public Set<PDP> getFailedPDPs() {
- return Collections.unmodifiableSet(this.failedPDPs);
- }
-
- public void addFailedPDP(PDP pdp) {
- this.failedPDPs.add(pdp);
- }
-
- @Override
- public Set<PDP> getUpdatingPDPs() {
- return Collections.unmodifiableSet(this.updatingPDPs);
- }
-
- public void addUpdatingPDP(PDP pdp) {
- this.updatingPDPs.add(pdp);
- }
-
- @Override
- public Set<PDP> getLastUpdateFailedPDPs() {
- return Collections.unmodifiableSet(this.lastUpdateFailedPDPs);
- }
-
- public void addLastUpdateFailedPDP(PDP pdp) {
- this.lastUpdateFailedPDPs.add(pdp);
- }
-
- @Override
- @JsonIgnore
- public Set<PDP> getUnknownStatusPDPs() {
- return Collections.unmodifiableSet(this.unknownPDPs);
- }
-
- public void addUnknownPDP(PDP pdp) {
- this.unknownPDPs.add(pdp);
- }
-
- @Override
- public boolean pdpsOK() {
- if (!this.outOfSynchPDPs.isEmpty()) {
- return false;
- }
- if (!this.failedPDPs.isEmpty()) {
- return false;
- }
- if (!this.lastUpdateFailedPDPs.isEmpty()) {
- return false;
- }
- if (!this.unknownPDPs.isEmpty()) {
- return false;
- }
- return true;
- }
-
- @Override
- @JsonIgnore
- public boolean isGroupOk() {
- if (!this.policiesOK()) {
- return false;
- }
- if (!this.pipConfigOK()) {
- return false;
- }
- if (!this.pdpsOK()) {
- return false;
- }
- if (!this.loadErrors.isEmpty()) {
- 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 + "]";
- }
+
+ private Status status = Status.UNKNOWN;
+
+ private Set<String> loadErrors = new HashSet<>();
+
+ private Set<String> loadWarnings = new HashSet<>();
+
+ private Set<PDPPolicy> loadedPolicies = new HashSet<>();
+
+ private Set<PDPPolicy> failedPolicies = new HashSet<>();
+
+ private Set<PDPPIPConfig> loadedPIPConfigs = new HashSet<>();
+
+ private Set<PDPPIPConfig> failedPIPConfigs = new HashSet<>();
+
+ private Set<PDP> inSynchPDPs = new HashSet<>();
+
+ private Set<PDP> outOfSynchPDPs = new HashSet<>();
+
+ private Set<PDP> failedPDPs = new HashSet<>();
+
+ private Set<PDP> updatingPDPs = new HashSet<>();
+
+ private Set<PDP> lastUpdateFailedPDPs = new HashSet<>();
+
+ private Set<PDP> unknownPDPs = new HashSet<>();
+
+ public StdPDPGroupStatus() {
+ //
+ // Constructor needed for JSON deserialization
+ //
+ }
+
+ 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<PDPPIPConfig> getLoadedPIPConfigs() {
+ return loadedPIPConfigs;
+ }
+
+ public void setLoadedPIPConfigs(Set<PDPPIPConfig> loadedPIPConfigs) {
+ this.loadedPIPConfigs = loadedPIPConfigs;
+ }
+
+ public Set<PDPPIPConfig> getFailedPIPConfigs() {
+ return failedPIPConfigs;
+ }
+
+ public void setFailedPIPConfigs(Set<PDPPIPConfig> failedPIPConfigs) {
+ this.failedPIPConfigs = failedPIPConfigs;
+ }
+
+ public Set<PDP> getUnknownPDPs() {
+ return unknownPDPs;
+ }
+
+ public void setUnknownPDPs(Set<PDP> unknownPDPs) {
+ this.unknownPDPs = unknownPDPs;
+ }
+
+ public void setLoadErrors(Set<String> loadErrors) {
+ this.loadErrors = loadErrors;
+ }
+
+ public void setLoadWarnings(Set<String> loadWarnings) {
+ this.loadWarnings = loadWarnings;
+ }
+
+ public void setLoadedPolicies(Set<PDPPolicy> loadedPolicies) {
+ this.loadedPolicies = loadedPolicies;
+ }
+
+ public void setFailedPolicies(Set<PDPPolicy> failedPolicies) {
+ this.failedPolicies = failedPolicies;
+ }
+
+ public void setInSynchPDPs(Set<PDP> inSynchPDPs) {
+ this.inSynchPDPs = inSynchPDPs;
+ }
+
+ public void setOutOfSynchPDPs(Set<PDP> outOfSynchPDPs) {
+ this.outOfSynchPDPs = outOfSynchPDPs;
+ }
+
+ public void setFailedPDPs(Set<PDP> failedPDPs) {
+ this.failedPDPs = failedPDPs;
+ }
+
+ public void setUpdatingPDPs(Set<PDP> updatingPDPs) {
+ this.updatingPDPs = updatingPDPs;
+ }
+
+ public void setLastUpdateFailedPDPs(Set<PDP> lastUpdateFailedPDPs) {
+ this.lastUpdateFailedPDPs = lastUpdateFailedPDPs;
+ }
+
+ @Override
+ public Status getStatus() {
+ return status;
+ }
+
+ public void setStatus(Status status) {
+ this.status = status;
+ }
+
+ @Override
+ public Set<String> getLoadErrors() {
+ return Collections.unmodifiableSet(this.loadErrors);
+ }
+
+ public void addLoadError(String error) {
+ this.loadErrors.add(error);
+ }
+
+ @Override
+ public Set<String> getLoadWarnings() {
+ return Collections.unmodifiableSet(this.loadWarnings);
+ }
+
+ public void addLoadWarning(String warning) {
+ this.loadWarnings.add(warning);
+ }
+
+ @Override
+ public Set<PDPPolicy> getLoadedPolicies() {
+ return Collections.unmodifiableSet(this.loadedPolicies);
+ }
+
+ public void addLoadedPolicy(PDPPolicy policy) {
+ this.loadedPolicies.add(policy);
+ }
+
+ @Override
+ public Set<PDPPolicy> getFailedPolicies() {
+ return Collections.unmodifiableSet(this.failedPolicies);
+ }
+
+ public void addFailedPolicy(PDPPolicy policy) {
+ this.failedPolicies.add(policy);
+ }
+
+ @Override
+ public boolean policiesOK() {
+ return this.failedPolicies.isEmpty();
+ }
+
+ @Override
+ public Set<PDPPIPConfig> getLoadedPipConfigs() {
+ return Collections.unmodifiableSet(this.loadedPIPConfigs);
+ }
+
+ public void addLoadedPipConfig(PDPPIPConfig config) {
+ this.loadedPIPConfigs.add(config);
+ }
+
+ @Override
+ public Set<PDPPIPConfig> getFailedPipConfigs() {
+ return Collections.unmodifiableSet(this.failedPIPConfigs);
+ }
+
+ public void addFailedPipConfig(PDPPIPConfig config) {
+ this.failedPIPConfigs.add(config);
+ }
+
+ @Override
+ public boolean pipConfigOK() {
+ return this.failedPIPConfigs.isEmpty();
+ }
+
+ @Override
+ public Set<PDP> getInSynchPDPs() {
+ return Collections.unmodifiableSet(this.inSynchPDPs);
+ }
+
+ public void addInSynchPDP(PDP pdp) {
+ this.inSynchPDPs.add(pdp);
+ }
+
+ @Override
+ public Set<PDP> getOutOfSynchPDPs() {
+ return Collections.unmodifiableSet(this.outOfSynchPDPs);
+ }
+
+ public void addOutOfSynchPDP(PDP pdp) {
+ this.outOfSynchPDPs.add(pdp);
+ }
+
+ @Override
+ public Set<PDP> getFailedPDPs() {
+ return Collections.unmodifiableSet(this.failedPDPs);
+ }
+
+ public void addFailedPDP(PDP pdp) {
+ this.failedPDPs.add(pdp);
+ }
+
+ @Override
+ public Set<PDP> getUpdatingPDPs() {
+ return Collections.unmodifiableSet(this.updatingPDPs);
+ }
+
+ public void addUpdatingPDP(PDP pdp) {
+ this.updatingPDPs.add(pdp);
+ }
+
+ @Override
+ public Set<PDP> getLastUpdateFailedPDPs() {
+ return Collections.unmodifiableSet(this.lastUpdateFailedPDPs);
+ }
+
+ public void addLastUpdateFailedPDP(PDP pdp) {
+ this.lastUpdateFailedPDPs.add(pdp);
+ }
+
+ @Override
+ @JsonIgnore
+ public Set<PDP> getUnknownStatusPDPs() {
+ return Collections.unmodifiableSet(this.unknownPDPs);
+ }
+
+ public void addUnknownPDP(PDP pdp) {
+ this.unknownPDPs.add(pdp);
+ }
+
+ @Override
+ public boolean pdpsOK() {
+ if (!this.outOfSynchPDPs.isEmpty()) {
+ return false;
+ }
+ if (!this.failedPDPs.isEmpty()) {
+ return false;
+ }
+ if (!this.lastUpdateFailedPDPs.isEmpty()) {
+ return false;
+ }
+ return this.unknownPDPs.isEmpty();
+ }
+
+ @Override
+ @JsonIgnore
+ public boolean isGroupOk() {
+ if (!this.policiesOK()) {
+ return false;
+ }
+ if (!this.pipConfigOK()) {
+ return false;
+ }
+ if (!this.pdpsOK()) {
+ return false;
+ }
+ if (!this.loadErrors.isEmpty()) {
+ return false;
+ }
+ return this.status == Status.OK;
+ }
+
+ /**
+ * reset.
+ */
+ 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();
+ }
}
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
index cc80b62c2..bf986b38e 100644
--- 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
@@ -2,14 +2,14 @@
* ============LICENSE_START=======================================================
* ONAP-XACML
* ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017, 2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -17,6 +17,7 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.policy.xacml.std.pap;
import java.util.Collection;
@@ -26,56 +27,79 @@ import org.onap.policy.xacml.api.pap.OnapPDP;
import org.onap.policy.xacml.api.pap.OnapPDPGroup;
public class StdPDPItemSetChangeNotifier {
-
- private Collection<StdItemSetChangeListener> 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);
- }
- }
+ private Collection<StdItemSetChangeListener> listeners = null;
+
+ public interface StdItemSetChangeListener {
+
+ public void changed();
+
+ public void groupChanged(OnapPDPGroup group);
+
+ public void pdpChanged(OnapPDP pdp);
+
+ }
+
+ /**
+ * addItemSetChangeListener.
+ *
+ * @param listener StdItemSetChangeListener
+ */
+ public void addItemSetChangeListener(StdItemSetChangeListener listener) {
+ if (this.listeners == null) {
+ this.listeners = new LinkedList<>();
+ }
+ this.listeners.add(listener);
+ }
+
+ /**
+ * removeItemSetChangeListener.
+ *
+ * @param listener StdItemSetChangeListener
+ */
+ 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();
- }
- }
+ /**
+ * fireChanged.
+ */
+ 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);
- }
- }
+ /**
+ * firePDPGroupChanged.
+ *
+ * @param group OnapPDPGroup
+ */
+ 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);
- }
- }
+ /**
+ * firePDPChanged.
+ *
+ * @param pdp OnapPDP
+ */
+ 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
index 9a65d50b2..3b7699467 100644
--- 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
@@ -2,14 +2,14 @@
* ============LICENSE_START=======================================================
* ONAP-XACML
* ================================================================================
- * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -17,202 +17,161 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.policy.xacml.std.pap;
+import com.att.research.xacml.api.pap.PDPPIPConfig;
+import com.fasterxml.jackson.annotation.JsonIgnore;
+
import java.io.Serializable;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
+import lombok.EqualsAndHashCode;
+import lombok.ToString;
-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;
-
+@EqualsAndHashCode(callSuper = false)
+@ToString
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<String,String> config = new HashMap<>();
-
- public StdPDPPIPConfig() {
- //
- // Default constructor
- //
- }
-
- 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<String,String> getConfiguration() {
- return Collections.unmodifiableMap(this.config);
- }
-
- public void setValues(Map<String,String> 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<String, String> getConfig() {
- return config;
- }
- public void setConfig(Map<String, String> config) {
- this.config = config;
- }
-
+ private static final long serialVersionUID = 1L;
+
+ private String id;
+
+ private String name;
+
+ private String description;
+
+ private String classname;
+
+ private Map<String, String> config = new HashMap<>();
+
+ public StdPDPPIPConfig() {
+ //
+ // Default constructor
+ //
+ }
+
+ public StdPDPPIPConfig(String id) {
+ this.id = id;
+ }
+
+ /**
+ * Constructor.
+ *
+ * @param id String
+ * @param name String
+ * @param description String
+ */
+ public StdPDPPIPConfig(String id, String name, String description) {
+ this(id);
+ this.name = name;
+ this.description = description;
+ }
+
+ /**
+ * Constructor.
+ *
+ * @param id String
+ * @param properties Properties
+ */
+ public StdPDPPIPConfig(String id, Properties properties) {
+ this(id);
+ if (!this.initialize(properties)) {
+ throw new IllegalArgumentException("PIP Engine '" + id + "' has no classname property in config");
+ }
+ }
+
+ /**
+ * initialize.
+ *
+ * @param properties Properties
+ * @return boolean
+ */
+ public boolean initialize(Properties properties) {
+ boolean classnameSeen = false;
+ for (Object key : properties.keySet()) {
+ if (key.toString().startsWith(this.id + ".")) {
+ 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<String, String> getConfiguration() {
+ return Collections.unmodifiableMap(this.config);
+ }
+
+ public void setValues(Map<String, String> 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;
+ }
+
+ //
+ // Methods needed for JSON serialization/deserialization
+ //
+
+ public Map<String, String> getConfig() {
+ return config;
+ }
+
+ public void setConfig(Map<String, String> 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
index 2b198f5e7..5288435aa 100644
--- 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
@@ -2,15 +2,15 @@
* ============LICENSE_START=======================================================
* ONAP-XACML
* ================================================================================
- * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
* Modified Copyright (C) 2018 Samsung Electronics Co., Ltd.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -18,9 +18,14 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.policy.xacml.std.pap;
-import org.onap.policy.common.logging.eelf.PolicyLogger;
+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;
import java.io.FileNotFoundException;
import java.io.IOException;
@@ -36,15 +41,9 @@ 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.common.logging.eelf.PolicyLogger;
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);
@@ -57,7 +56,7 @@ public class StdPDPPolicy implements PDPPolicy, Serializable {
private String description = null;
- private int[] version = null;
+ private int[] version = null;
private boolean isRoot = false;
@@ -81,7 +80,15 @@ public class StdPDPPolicy implements PDPPolicy, Serializable {
this.name = name;
}
-
+ /**
+ * StdPDPPolicy.
+ *
+ * @param id String
+ * @param isRoot boolean
+ * @param name String
+ * @param location URI
+ * @throws IOException IOException
+ */
public StdPDPPolicy(String id, boolean isRoot, String name, URI location) throws IOException {
this(id, isRoot);
this.name = name;
@@ -97,11 +104,17 @@ public class StdPDPPolicy implements PDPPolicy, Serializable {
this.id = theID;
}
- logger.debug("The final outcome of the constructor returned the following: id = " + id +
- ", location = " + location + ", name = " + name);
+ logger.debug("The final outcome of the constructor returned the following: id = " + id + ", location = "
+ + location + ", name = " + name);
}
+ /**
+ * StdPDPPolicy constructor.
+ *
+ * @param stdPDPPolicyParams StdPDPPolicyParams
+ * @throws IOException IOException
+ */
public StdPDPPolicy(StdPDPPolicyParams stdPDPPolicyParams) throws IOException {
this(stdPDPPolicyParams.getId(), stdPDPPolicyParams.isRoot());
this.name = stdPDPPolicyParams.getName();
@@ -111,23 +124,43 @@ public class StdPDPPolicy implements PDPPolicy, Serializable {
this.version = versionStringToArray(stdPDPPolicyParams.getVersion());
this.isValid = stdPDPPolicyParams.isValid();
- logger.debug("The final outcome of the constructor returned the following: id = " + stdPDPPolicyParams.getId() +
- ", location = " + stdPDPPolicyParams.getLocation() + ", name = " + stdPDPPolicyParams.getName() + ", policyId = " + stdPDPPolicyParams.getPolicyId() +
- ", description = " + stdPDPPolicyParams.getDescription() + ", Version = " + stdPDPPolicyParams.getVersion());
+ logger.debug("The final outcome of the constructor returned the following: id = " + stdPDPPolicyParams.getId()
+ + ", location = " + stdPDPPolicyParams.getLocation() + ", name = " + stdPDPPolicyParams.getName()
+ + ", policyId = " + stdPDPPolicyParams.getPolicyId() + ", description = "
+ + stdPDPPolicyParams.getDescription() + ", Version = " + stdPDPPolicyParams.getVersion());
}
+ /**
+ * StdPDPPolicy.
+ *
+ * @param id String
+ * @param isRoot boolean
+ * @param name String
+ * @param location URI
+ * @param isFromAPI boolean
+ * @throws IOException IOException
+ */
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);
+ logger.debug("The final outcome of the constructor returned the following: id = " + id + ", location = "
+ + location + ", name = " + name);
}
+ /**
+ * StdPDPPolicy.
+ *
+ * @param id String
+ * @param isRoot boolean
+ * @param location URI
+ * @param properties boolean
+ * @throws IOException IOException
+ */
public StdPDPPolicy(String id, boolean isRoot, URI location, Properties properties) throws IOException {
this(id, isRoot);
this.location = location;
@@ -146,31 +179,26 @@ public class StdPDPPolicy implements PDPPolicy, Serializable {
}
}
-
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)
- ) ) {
+ 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.policyId = ((PolicySetType) rootElement).getPolicySetId();
+ this.description = ((PolicySetType) rootElement).getDescription();
this.isValid = true;
- this.version = versionStringToArray(((PolicySetType)rootElement).getVersion());
+ 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.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());
@@ -230,8 +258,7 @@ public class StdPDPPolicy implements PDPPolicy, Serializable {
}
@Override
- public boolean isValid()
- {
+ public boolean isValid() {
return this.isValid;
}
@@ -259,8 +286,7 @@ public class StdPDPPolicy implements PDPPolicy, Serializable {
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 + ((policyId == null) ? 0 : policyId.hashCode());
result = prime * result;
if (version != null) {
for (int i = 0; i < version.length; i++) {
@@ -272,45 +298,50 @@ public class StdPDPPolicy implements PDPPolicy, Serializable {
@Override
public boolean equals(Object obj) {
- if (this == obj)
+ if (this == obj) {
return true;
- if (obj == null)
+ }
+ if (obj == null) {
return false;
- if (getClass() != obj.getClass())
+ }
+ if (getClass() != obj.getClass()) {
return false;
+ }
StdPDPPolicy other = (StdPDPPolicy) obj;
if (id == null) {
- if (other.id != null)
+ if (other.id != null) {
return false;
- } else if (!id.equals(other.id))
+ }
+ } else if (!id.equals(other.id)) {
return false;
+ }
if (policyId == null) {
- if (other.policyId != null)
+ if (other.policyId != null) {
return false;
- } else if (!policyId.equals(other.policyId))
+ }
+ } else if (!policyId.equals(other.policyId)) {
return false;
- if (version != other.version)
+ }
+ 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 + "]";
+ 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
+ * @param version String
+ * @return int array
*/
- public static int[] versionStringToArray(String version) throws NumberFormatException {
+ public static int[] versionStringToArray(String version) {
if (version == null || version.length() == 0) {
return new int[0];
}
@@ -325,8 +356,8 @@ public class StdPDPPolicy implements PDPPolicy, Serializable {
/**
* Given an array representing a version, create the corresponding dot-separated string.
*
- * @param array
- * @return
+ * @param array int array
+ * @return String
*/
public static String versionArrayToString(int[] array) {
if (array == null || array.length == 0) {
@@ -345,18 +376,23 @@ public class StdPDPPolicy implements PDPPolicy, Serializable {
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/StdPDPPolicyParams.java b/ONAP-XACML/src/main/java/org/onap/policy/xacml/std/pap/StdPDPPolicyParams.java
index dddfe2576..f5251214f 100644
--- a/ONAP-XACML/src/main/java/org/onap/policy/xacml/std/pap/StdPDPPolicyParams.java
+++ b/ONAP-XACML/src/main/java/org/onap/policy/xacml/std/pap/StdPDPPolicyParams.java
@@ -3,6 +3,7 @@
* ONAP-XACML
* ================================================================================
* Copyright (C) 2018 Samsung Electronics Co., Ltd. All rights reserved.
+ * Modifications Copyright (C) 2019 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.
@@ -23,7 +24,7 @@ package org.onap.policy.xacml.std.pap;
import java.net.URI;
/**
- * Parameters class for StdPDPPolicy
+ * Parameters class for StdPDPPolicy.
*/
public class StdPDPPolicyParams {
private String id;
@@ -36,14 +37,15 @@ public class StdPDPPolicyParams {
private String version;
/**
- * Private constructor
+ * Private constructor.
*/
- private StdPDPPolicyParams(){
+ private StdPDPPolicyParams() {
super();
}
/**
- * Get an instance of builder class
+ * Get an instance of builder class.
+ *
* @return StdPDPPolicyParamsBuilder
*/
public static StdPDPPolicyParamsBuilder builder() {
@@ -51,15 +53,17 @@ public class StdPDPPolicyParams {
}
/**
- * Return id
- * @return id
+ * Return id.
+ *
+ * @return id String
*/
public String getId() {
return id;
}
/**
- * Boolean to indicate root
+ * Boolean to indicate root.
+ *
* @return isRoot
*/
public boolean isRoot() {
@@ -67,7 +71,8 @@ public class StdPDPPolicyParams {
}
/**
- * Get name of policy
+ * Get name of policy.
+ *
* @return name
*/
public String getName() {
@@ -75,7 +80,8 @@ public class StdPDPPolicyParams {
}
/**
- * Retrieve the uri
+ * Retrieve the uri.
+ *
* @return location
*/
public URI getLocation() {
@@ -83,7 +89,8 @@ public class StdPDPPolicyParams {
}
/**
- * Check policy valid
+ * Check policy valid.
+ *
* @return isValid
*/
public boolean isValid() {
@@ -91,7 +98,8 @@ public class StdPDPPolicyParams {
}
/**
- * Retrieve policy id
+ * Retrieve policy id.
+ *
* @return policy id
*/
public String getPolicyId() {
@@ -99,7 +107,8 @@ public class StdPDPPolicyParams {
}
/**
- * Description of policy
+ * Description of policy.
+ *
* @return description
*/
public String getDescription() {
@@ -107,7 +116,8 @@ public class StdPDPPolicyParams {
}
/**
- * Retrieve version of policy
+ * Retrieve version of policy.
+ *
* @return version
*/
public String getVersion() {
@@ -115,96 +125,105 @@ public class StdPDPPolicyParams {
}
/**
- * Builder class for std pdp policy params class
+ * Builder class for std pdp policy params class.
*/
public static class StdPDPPolicyParamsBuilder {
- StdPDPPolicyParams m = new StdPDPPolicyParams();
+ StdPDPPolicyParams params = new StdPDPPolicyParams();
/**
- * Build the policy params
+ * Build the policy params.
+ *
* @return stdPdpPolicyParams object
*/
public StdPDPPolicyParams build() {
- return m;
+ return params;
}
/**
- * Set id
+ * Set id.
+ *
* @param id - provide id
* @return builder
*/
public StdPDPPolicyParamsBuilder id(String id) {
- m.id = id;
+ params.id = id;
return this;
}
/**
- * Set whether isRoot
+ * Set whether isRoot.
+ *
* @param isRoot - true/false
* @return builder
*/
public StdPDPPolicyParamsBuilder isRoot(boolean isRoot) {
- m.isRoot = isRoot;
+ params.isRoot = isRoot;
return this;
}
/**
- * Set name
+ * Set name.
+ *
* @param name - name of policy
* @return builder
*/
public StdPDPPolicyParamsBuilder name(String name) {
- m.name = name;
+ params.name = name;
return this;
}
/**
- * Set location uri
+ * Set location uri.
+ *
* @param uri - for location
* @return builder
*/
public StdPDPPolicyParamsBuilder location(URI uri) {
- m.location = uri;
+ params.location = uri;
return this;
}
/**
- * Set valid flag
+ * Set valid flag.
+ *
* @param isValid - whether the policy is valid
* @return builder
*/
public StdPDPPolicyParamsBuilder isValid(boolean isValid) {
- m.isValid = isValid;
+ params.isValid = isValid;
return this;
}
/**
- * Set policy id
+ * Set policy id.
+ *
* @param policyId - policy id
* @return builder
*/
public StdPDPPolicyParamsBuilder policyId(String policyId) {
- m.policyId = policyId;
+ params.policyId = policyId;
return this;
}
/**
- * Set description of policy
+ * Set description of policy.
+ *
* @param description - of policy
* @return builder
*/
public StdPDPPolicyParamsBuilder description(String description) {
- m.description = description;
+ params.description = description;
return this;
}
/**
- * Set version of policy
+ * Set version of policy.
+ *
* @param version - of policy
* @return builder
*/
public StdPDPPolicyParamsBuilder version(String version) {
- m.version = version;
+ params.version = version;
return this;
}
}
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
index a39ea3630..4f61cd61b 100644
--- 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
@@ -2,14 +2,14 @@
* ============LICENSE_START=======================================================
* ONAP-XACML
* ================================================================================
- * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -17,254 +17,240 @@
* 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;
+package org.onap.policy.xacml.std.pap;
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;
+import java.io.Serializable;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.Set;
+import lombok.ToString;
+
+@ToString
public class StdPDPStatus implements Serializable, PDPStatus {
- private static final long serialVersionUID = 1L;
-
- private Status status = Status.UNKNOWN;
-
- private Set<String> loadErrors = new HashSet<>();
-
- private Set<String> loadWarnings = new HashSet<>();
-
- private transient Set<PDPPolicy> loadedPolicies = new HashSet<>();
-
- private transient Set<PDPPolicy> loadedRootPolicies = new HashSet<>();
-
- private transient Set<PDPPolicy> failedPolicies = new HashSet<>();
-
- private transient Set<PDPPIPConfig> loadedPIPConfigs = new HashSet<>();
-
- private transient Set<PDPPIPConfig> failedPIPConfigs = new HashSet<>();
-
- public StdPDPStatus() {
- //
- // Default constructor
- //
- }
-
- 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<String> getLoadErrors() {
- return Collections.unmodifiableSet(this.loadErrors);
- }
-
- public void setLoadErrors(Set<String> errors) {
- this.loadErrors = errors;
- }
-
- public void addLoadError(String error) {
- this.loadErrors.add(error);
- }
-
- @Override
- public Set<String> getLoadWarnings() {
- return Collections.unmodifiableSet(this.loadWarnings);
- }
-
- public void setLoadWarnings(Set<String> warnings) {
- this.loadWarnings = warnings;
- }
-
- public void addLoadWarning(String warning) {
- this.loadWarnings.add(warning);
- }
-
- @Override
- public Set<PDPPolicy> getLoadedPolicies() {
- return Collections.unmodifiableSet(this.loadedPolicies);
- }
-
- public void setLoadedPolicies(Set<PDPPolicy> policies) {
- this.loadedPolicies = policies;
- }
-
- public void addLoadedPolicy(PDPPolicy policy) {
- this.loadedPolicies.add(policy);
- }
-
- @Override
- public Set<PDPPolicy> getLoadedRootPolicies() {
- return Collections.unmodifiableSet(this.loadedRootPolicies);
- }
-
- public void setLoadedRootPolicies(Set<PDPPolicy> policies) {
- this.loadedRootPolicies = policies;
- }
-
- public void addRootPolicy(PDPPolicy policy) {
- this.loadedRootPolicies.add(policy);
- }
-
- public void addAllLoadedRootPolicies(Set<PDPPolicy> policies) {
- this.loadedRootPolicies.addAll(policies);
- }
-
- @Override
- public Set<PDPPolicy> getFailedPolicies() {
- return Collections.unmodifiableSet(this.failedPolicies);
- }
-
- public void setFailedPolicies(Set<PDPPolicy> policies) {
- this.failedPolicies = policies;
- }
-
- public void addFailedPolicy(PDPPolicy policy) {
- this.failedPolicies.add(policy);
- }
-
- @Override
- public boolean policiesOK() {
- if (!this.failedPolicies.isEmpty()) {
- return false;
- }
- return true;
- }
-
- @Override
- public Set<PDPPIPConfig> getLoadedPipConfigs() {
- return Collections.unmodifiableSet(this.loadedPIPConfigs);
- }
-
- public void setLoadedPipConfigs(Set<PDPPIPConfig> configs) {
- this.loadedPIPConfigs = configs;
- }
-
- public void addLoadedPipConfig(PDPPIPConfig config) {
- this.loadedPIPConfigs.add(config);
- }
-
- @Override
- public Set<PDPPIPConfig> getFailedPipConfigs() {
- return Collections.unmodifiableSet(this.failedPIPConfigs);
- }
-
- public void setFailedPipConfigs(Set<PDPPIPConfig> configs) {
- this.failedPIPConfigs = configs;
- }
-
- public void addFailedPipConfig(PDPPIPConfig config) {
- this.failedPIPConfigs.add(config);
- }
-
- @Override
- public boolean pipConfigOK() {
- if (!this.failedPIPConfigs.isEmpty()) {
- return false;
- }
- return true;
- }
-
- @Override
- @JsonIgnore
- public boolean isOk() {
- if (!this.policiesOK()) {
- return false;
- }
- if (!this.pipConfigOK()) {
- 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 (!loadedRootPolicies.equals(other.loadedRootPolicies))
- 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 + "]";
- }
+ private static final long serialVersionUID = 1L;
+
+ private Status status = Status.UNKNOWN;
+
+ private Set<String> loadErrors = new HashSet<>();
+
+ private Set<String> loadWarnings = new HashSet<>();
+
+ private transient Set<PDPPolicy> loadedPolicies = new HashSet<>();
+
+ private transient Set<PDPPolicy> loadedRootPolicies = new HashSet<>();
+
+ private transient Set<PDPPolicy> failedPolicies = new HashSet<>();
+
+ private transient Set<PDPPIPConfig> loadedPIPConfigs = new HashSet<>();
+
+ private transient Set<PDPPIPConfig> failedPIPConfigs = new HashSet<>();
+
+ public StdPDPStatus() {
+ //
+ // Default constructor
+ //
+ }
+
+ 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<String> getLoadErrors() {
+ return Collections.unmodifiableSet(this.loadErrors);
+ }
+
+ public void setLoadErrors(Set<String> errors) {
+ this.loadErrors = errors;
+ }
+
+ public void addLoadError(String error) {
+ this.loadErrors.add(error);
+ }
+
+ @Override
+ public Set<String> getLoadWarnings() {
+ return Collections.unmodifiableSet(this.loadWarnings);
+ }
+
+ public void setLoadWarnings(Set<String> warnings) {
+ this.loadWarnings = warnings;
+ }
+
+ public void addLoadWarning(String warning) {
+ this.loadWarnings.add(warning);
+ }
+
+ @Override
+ public Set<PDPPolicy> getLoadedPolicies() {
+ return Collections.unmodifiableSet(this.loadedPolicies);
+ }
+ public void setLoadedPolicies(Set<PDPPolicy> policies) {
+ this.loadedPolicies = policies;
+ }
+ public void addLoadedPolicy(PDPPolicy policy) {
+ this.loadedPolicies.add(policy);
+ }
+
+ @Override
+ public Set<PDPPolicy> getLoadedRootPolicies() {
+ return Collections.unmodifiableSet(this.loadedRootPolicies);
+ }
+
+ public void setLoadedRootPolicies(Set<PDPPolicy> policies) {
+ this.loadedRootPolicies = policies;
+ }
+
+ public void addRootPolicy(PDPPolicy policy) {
+ this.loadedRootPolicies.add(policy);
+ }
+
+ public void addAllLoadedRootPolicies(Set<PDPPolicy> policies) {
+ this.loadedRootPolicies.addAll(policies);
+ }
+
+ @Override
+ public Set<PDPPolicy> getFailedPolicies() {
+ return Collections.unmodifiableSet(this.failedPolicies);
+ }
+
+ public void setFailedPolicies(Set<PDPPolicy> policies) {
+ this.failedPolicies = policies;
+ }
+
+ public void addFailedPolicy(PDPPolicy policy) {
+ this.failedPolicies.add(policy);
+ }
+
+ @Override
+ public boolean policiesOK() {
+ return this.failedPolicies.isEmpty();
+ }
+
+ @Override
+ public Set<PDPPIPConfig> getLoadedPipConfigs() {
+ return Collections.unmodifiableSet(this.loadedPIPConfigs);
+ }
+
+ public void setLoadedPipConfigs(Set<PDPPIPConfig> configs) {
+ this.loadedPIPConfigs = configs;
+ }
+
+ public void addLoadedPipConfig(PDPPIPConfig config) {
+ this.loadedPIPConfigs.add(config);
+ }
+
+ @Override
+ public Set<PDPPIPConfig> getFailedPipConfigs() {
+ return Collections.unmodifiableSet(this.failedPIPConfigs);
+ }
+
+ public void setFailedPipConfigs(Set<PDPPIPConfig> configs) {
+ this.failedPIPConfigs = configs;
+ }
+
+ public void addFailedPipConfig(PDPPIPConfig config) {
+ this.failedPIPConfigs.add(config);
+ }
+
+ @Override
+ public boolean pipConfigOK() {
+ return this.failedPIPConfigs.isEmpty();
+ }
+
+ @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 (!loadedRootPolicies.equals(other.loadedRootPolicies)) {
+ return false;
+ }
+ if (status != other.status) {
+ return false;
+ }
+ return true;
+ }
+
+ @Override
+ @JsonIgnore
+ public boolean isOk() {
+ if (!this.policiesOK()) {
+ return false;
+ }
+ if (!this.pipConfigOK()) {
+ return false;
+ }
+ return this.status == Status.UP_TO_DATE;
+ }
}
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
index 355a6f644..bb7421e94 100644
--- 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
@@ -2,14 +2,14 @@
* ============LICENSE_START=======================================================
* ONAP-XACML
* ================================================================================
- * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -20,22 +20,6 @@
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.eclipse.persistence.config.PersistenceUnitProperties;
-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.Identifier;
@@ -54,244 +38,210 @@ import com.att.research.xacml.std.pip.StdPIPResponse;
import com.att.research.xacml.std.pip.engines.StdConfigurableEngine;
import com.att.research.xacml.util.XACMLProperties;
+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.eclipse.persistence.config.PersistenceUnitProperties;
+import org.onap.policy.common.logging.flexlogger.FlexLogger;
+import org.onap.policy.common.logging.flexlogger.Logger;
+
/**
* PIP Engine for Implementing {@link com.att.research.xacml.std.pip.engines.ConfigurableEngine} interface to provide
- * attribute retrieval from Operation History Table.
- *
+ * 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 Logger LOGGER= FlexLogger.getLogger(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);
-
- public OperationHistoryEngine() {
- super();
- }
-
- private void addIntegerAttribute(StdMutablePIPResponse stdPIPResponse, Identifier category, Identifier attributeId, int value, PIPRequest pipRequest) {
- AttributeValue<BigInteger> attributeValue = null;
- try {
- attributeValue = DataTypes.DT_INTEGER.createAttributeValue(value);
- } catch (Exception ex) {
- LOGGER.error("Failed to convert " + value + " to an AttributeValue<Boolean>", ex);
- }
- if (attributeValue != null) {
- stdPIPResponse.addAttribute(new StdMutableAttribute(category, attributeId, attributeValue, pipRequest.getIssuer()/*this.getIssuer()*/, false));
- }
- }
-
- @Override
- public Collection<PIPRequest> attributesRequired() {
- return new ArrayList<>();
- }
-
- @Override
- public Collection<PIPRequest> 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<String> 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<Attribute> listATTUIDs = pipResponseATTUID.getAttributes();
- Set<String> setATTUIDs = new HashSet<>();
- for (Attribute attributeATTUID: listATTUIDs) {
- Iterator<AttributeValue<String>> 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<String> 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<Attribute> listATTUIDs = pipResponseATTUID.getAttributes();
- Set<String> setATTUIDs = new HashSet<>();
- for (Attribute attributeATTUID: listATTUIDs) {
- Iterator<AttributeValue<String>> 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<String> 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<Attribute> listATTUIDs = pipResponseATTUID.getAttributes();
- Set<String> setATTUIDs = new HashSet<>();
- for (Attribute attributeATTUID: listATTUIDs) {
- Iterator<AttributeValue<String>> 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 ("minute".equalsIgnoreCase(timeUnits) || "hour".equalsIgnoreCase(timeUnits) || "day".equalsIgnoreCase(timeUnits)
- || "week".equalsIgnoreCase(timeUnits) || "month".equalsIgnoreCase(timeUnits)|| "year".equalsIgnoreCase(timeUnits))?
- true: false;
- }
+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 Logger LOGGER = FlexLogger.getLogger(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);
+
+ public OperationHistoryEngine() {
+ super();
+ }
+
+ private void addIntegerAttribute(StdMutablePIPResponse stdPipResponse, Identifier category, Identifier attributeId,
+ int value, PIPRequest pipRequest) {
+ AttributeValue<BigInteger> attributeValue = null;
+ try {
+ attributeValue = DataTypes.DT_INTEGER.createAttributeValue(value);
+ } catch (Exception ex) {
+ LOGGER.error("Failed to convert " + value + " to an AttributeValue<Boolean>", ex);
+ }
+ if (attributeValue != null) {
+ stdPipResponse.addAttribute(new StdMutableAttribute(category, attributeId, attributeValue,
+ pipRequest.getIssuer()/* this.getIssuer() */, false));
+ }
+ }
+
+ @Override
+ public Collection<PIPRequest> attributesRequired() {
+ return new ArrayList<>();
+ }
+
+ @Override
+ public Collection<PIPRequest> 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<String> getActor(PIPFinder pipFinder) {
+ return getUuids(this.getAttribute(PIP_REQUEST_ACTOR, pipFinder));
+ }
+
+ private Set<String> getRecipe(PIPFinder pipFinder) {
+ return getUuids(this.getAttribute(PIP_REQUEST_RECIPE, pipFinder));
+ }
+
+ private Set<String> getTarget(PIPFinder pipFinder) {
+ return getUuids(this.getAttribute(PIP_REQUEST_TARGET, pipFinder));
+ }
+
+ private Set<String> getUuids(PIPResponse pipResponseAttUid) {
+ /*
+ * Get the UID from either the subject id or the attuid property
+ */
+ if (pipResponseAttUid == null) {
+ return new HashSet<>();
+ }
+ /*
+ * Iterate over all of the returned results and do the LDAP requests
+ */
+ Set<String> setAttUids = new HashSet<>();
+ for (Attribute attributeAttUid : pipResponseAttUid.getAttributes()) {
+ Iterator<AttributeValue<String>> 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 ("minute".equalsIgnoreCase(timeUnits) || "hour".equalsIgnoreCase(timeUnits)
+ || "day".equalsIgnoreCase(timeUnits) || "week".equalsIgnoreCase(timeUnits)
+ || "month".equalsIgnoreCase(timeUnits) || "year".equalsIgnoreCase(timeUnits)) ? 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
index de35e0eb8..c488e51ef 100644
--- 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
@@ -2,14 +2,14 @@
* ============LICENSE_START=======================================================
* ONAP-XACML
* ================================================================================
- * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -17,21 +17,8 @@
* 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;
+package org.onap.policy.xacml.std.pip.engines.aaf;
import com.att.research.xacml.api.Attribute;
import com.att.research.xacml.api.AttributeValue;
@@ -50,101 +37,129 @@ import com.att.research.xacml.std.pip.StdPIPResponse;
import com.att.research.xacml.std.pip.engines.StdConfigurableEngine;
import com.att.research.xacml.util.XACMLProperties;
+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;
+
/**
* PIP Engine for Implementing {@link com.att.research.xacml.std.pip.engines.ConfigurableEngine} interface to provide
- * attribute retrieval from AAF interface.
- *
+ * 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<PIPRequest> 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<PIPRequest, String> 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<Attribute> listAttributes = pipResponse.getAttributes();
- for(Attribute attribute: listAttributes){
- Iterator<AttributeValue<String>> 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 {
+
+ 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<PIPRequest> 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<PIPRequest, String> 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<Attribute> listAttributes = pipResponse.getAttributes();
+ for (Attribute attribute : listAttributes) {
+ Iterator<AttributeValue<String>> 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) {
@@ -152,121 +167,127 @@ public class AAFEngine extends StdConfigurableEngine {
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<String> attributeValue = null;
- try {
- attributeValue = DataTypes.DT_STRING.createAttributeValue(value);
- } catch (Exception ex) {
- this.logger.error("Failed to convert " + value + " to an AttributeValue<String>", ex);
- }
- if (attributeValue != null) {
- stdPIPResponse.addAttribute(new StdMutableAttribute(category, attributeId, attributeValue, this.getIssuer(), false));
- }
- }
- }
+ 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<String> attributeValue = null;
+ try {
+ attributeValue = DataTypes.DT_STRING.createAttributeValue(value);
+ } catch (Exception ex) {
+ this.logger.error("Failed to convert " + value + " to an AttributeValue<String>", 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<Boolean> attributeValue = null;
+ try {
+ attributeValue = DataTypes.DT_BOOLEAN.createAttributeValue(value);
+ } catch (Exception ex) {
+ this.logger.error("Failed to convert " + value + " to an AttributeValue<Boolean>", 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;
- private void addBooleanAttribute(StdMutablePIPResponse stdPIPResponse, Identifier category, Identifier attributeId, boolean value) {
- AttributeValue<Boolean> attributeValue = null;
- try {
- attributeValue = DataTypes.DT_BOOLEAN.createAttributeValue(value);
- } catch (Exception ex) {
- this.logger.error("Failed to convert " + value + " to an AttributeValue<Boolean>", 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;
+ }
- 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);
+ }
+ }
- /*
- * 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 Collection<PIPRequest> attributesRequired() {
+ List<PIPRequest> attributes = new ArrayList<>();
+ for (PIPRequest attribute : mapRequiredAttributes) {
+ attributes.add(new StdPIPRequest(attribute));
+ }
+ return attributes;
+ }
- @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<PIPRequest> attributesRequired() {
- List<PIPRequest> attributes = new ArrayList<>();
- for (PIPRequest attribute: mapRequiredAttributes) {
- attributes.add(new StdPIPRequest(attribute));
- }
- return attributes;
- }
+ @Override
+ public Collection<PIPRequest> attributesProvided() {
+ List<PIPRequest> attributes = new ArrayList<>();
+ for (PIPRequest attribute : mapSupportedAttributes.keySet()) {
+ attributes.add(new StdPIPRequest(attribute));
+ }
+ return attributes;
+ }
- @Override
- public Collection<PIPRequest> attributesProvided() {
- List<PIPRequest> 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
index 58f5a49e1..42dbd851b 100644
--- 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
@@ -2,14 +2,14 @@
* ============LICENSE_START=======================================================
* ONAP-XACML
* ================================================================================
- * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -17,70 +17,71 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.policy.xacml.util;
public class MetricsUtil {
-
- private MetricsUtil() {
- //
- // private constructor to hide the implicit public one for utility class
- //
- }
-
- 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;
- }
- }
+
+ private MetricsUtil() {
+ //
+ // private constructor to hide the implicit public one for utility class
+ //
+ }
+
+ 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
index 0003e12c6..228354c4f 100644
--- 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
@@ -2,14 +2,14 @@
* ============LICENSE_START=======================================================
* ONAP-XACML
* ================================================================================
- * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -17,8 +17,19 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.policy.xacml.util;
+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 java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
@@ -33,26 +44,6 @@ 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;
@@ -71,598 +62,603 @@ 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 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.w3c.dom.Document;
+import org.w3c.dom.Element;
+
/**
- * 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.
- *
+ * class XACMLPolicyScanner.
+ *
+ * <p>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 && 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 && 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<JAXBElement<?>> list = policySet.getPolicySetOrPolicyOrPolicySetIdReference();
- for (JAXBElement<?> element: list) {
- if ("PolicySet".equals(element.getName().getLocalPart()) &&
- this.scanPolicySet(policySet, (PolicySetType)element.getValue()) == CallbackResult.STOP) {
- return CallbackResult.STOP;
- } else if ("Policy".equals(element.getName().getLocalPart()) &&
- this.scanPolicy(policySet, (PolicyType)element.getValue()) == CallbackResult.STOP) {
- return CallbackResult.STOP;
- } else {
- logger.warn("generating policy sets found unsupported element: " + element.getName().getNamespaceURI());
- }
- }
- if (this.callback != null && 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 && 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<Object> 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 && 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 && this.callback.onPostVisitRule(policy, rule) == CallbackResult.STOP) {
- return CallbackResult.STOP;
- }
- } else if (o instanceof VariableDefinitionType) {
- if (this.callback != null && 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 && 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<AnyOfType> anyOfList = target.getAnyOf();
- if (anyOfList != null) {
- Iterator<AnyOfType> iterAnyOf = anyOfList.iterator();
- while (iterAnyOf.hasNext()) {
- AnyOfType anyOf = iterAnyOf.next();
- List<AllOfType> allOfList = anyOf.getAllOf();
- if (allOfList != null) {
- Iterator<AllOfType> iterAllOf = allOfList.iterator();
- while (iterAllOf.hasNext()) {
- AllOfType allOf = iterAllOf.next();
- List<MatchType> matchList = allOf.getMatch();
- if (matchList != null) {
- Iterator<MatchType> 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<List<?>>(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<List<?>>(new IdentifierImpl(value.getDataType()), value.getContent()),
- null,
- false);
- } else {
- logger.warn("NULL designator/selector or value for match.");
- }
- if (attribute != null && this.callback != null && 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<ObligationExpressionType> expressions = obligationExpressionsType.getObligationExpression();
- if (expressions == null || expressions.isEmpty()) {
- return CallbackResult.CONTINUE;
- }
- for (ObligationExpressionType expression : expressions) {
- StdMutableObligation ob = new StdMutableObligation(new IdentifierImpl(expression.getObligationId()));
- List<AttributeAssignmentExpressionType> 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<Object>(null, null)
- );
- ob.addAttributeAssignment(attribute);
- }
- }
- if (this.callback != null && 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<AdviceExpressionType> expressions = adviceExpressionstype.getAdviceExpression();
- if (expressions == null || expressions.isEmpty()) {
- return CallbackResult.CONTINUE;
- }
- for (AdviceExpressionType expression : expressions) {
- StdMutableAdvice ob = new StdMutableAdvice(new IdentifierImpl(expression.getAdviceId()));
- List<AttributeAssignmentExpressionType> 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<Object>(null, null)
- );
- ob.addAttributeAssignment(attribute);
- }
- }
- if (this.callback != null && 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<Object> list) {
- if (list == null) {
- return CallbackResult.CONTINUE;
- }
- for (Object o : list) {
- if (o instanceof VariableDefinitionType && this.callback != null && 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 && this.callback != null && 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<String> 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("<Description>") && 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("<Description>") && 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("<Description>") && 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);
- Element e = doc.getDocumentElement();
- //
- // Is it a 3.0 policy?
- //
- if ("urn:oasis:names:tc:xacml:3.0:core:schema:wd-17".equals(e.getNamespaceURI())) {
- //
- // 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<PolicyType> 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<PolicySetType> 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());
- }
- } catch (Exception e) {
- PolicyLogger.error(MessageCodes.ERROR_SCHEMA_INVALID, e, "XACMLPolicyScanner", "Exception in readPolicy");
- }
- return null;
- }
-
- /**
- * @return the policyObject
- */
- public Object getPolicyObject() {
- return policyObject;
- }
+
+ private static final Log logger = LogFactory.getLog(XACMLPolicyScanner.class);
+ private Object policyObject = null;
+ private Callback callback = null;
+
+ /**
+ * constructor.
+ *
+ * @param filename Path
+ * @param callback Callback
+ */
+ 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;
+ }
+
+ /**
+ * Constructor.
+ *
+ * @param filename InputStream
+ * @param 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 Callback object
+ */
+ public void setCallback(Callback cb) {
+ this.callback = cb;
+ }
+
+ /**
+ * Saves the given callback object then calls the scan() method.
+ *
+ * @param cb Callback object
+ * @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 && 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.
+ */
+ protected CallbackResult scanPolicySet(PolicySetType parent, PolicySetType policySet) {
+ if (logger.isTraceEnabled()) {
+ logger.trace("scanning policy set: " + policySet.getPolicySetId() + " " + policySet.getDescription());
+ }
+ if (this.callback != null && 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<JAXBElement<?>> list = policySet.getPolicySetOrPolicyOrPolicySetIdReference();
+ for (JAXBElement<?> element : list) {
+ if ("PolicySet".equals(element.getName().getLocalPart())
+ && this.scanPolicySet(policySet, (PolicySetType) element.getValue()) == CallbackResult.STOP) {
+ return CallbackResult.STOP;
+ } else if ("Policy".equals(element.getName().getLocalPart())
+ && this.scanPolicy(policySet, (PolicyType) element.getValue()) == CallbackResult.STOP) {
+ return CallbackResult.STOP;
+ } else {
+ logger.warn("generating policy sets found unsupported element: " + element.getName().getNamespaceURI());
+ }
+ }
+ if (this.callback != null && 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 && 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<Object> 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 && 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 && this.callback.onPostVisitRule(policy, rule) == CallbackResult.STOP) {
+ return CallbackResult.STOP;
+ }
+ } else if (o instanceof VariableDefinitionType) {
+ if (this.callback != null
+ && 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 && 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;
+ }
+ for (AnyOfType anyOf : target.getAnyOf()) {
+ for (AllOfType allOf : anyOf.getAllOf()) {
+ for (MatchType match : allOf.getMatch()) {
+ //
+ // 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<List<?>>(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<List<?>>(new IdentifierImpl(value.getDataType()),
+ value.getContent()),
+ null, false);
+ } else {
+ logger.warn("NULL designator/selector or value for match.");
+ }
+ if (attribute != null && this.callback != null && 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<ObligationExpressionType> expressions = obligationExpressionsType.getObligationExpression();
+ for (ObligationExpressionType expression : expressions) {
+ StdMutableObligation ob = new StdMutableObligation(new IdentifierImpl(expression.getObligationId()));
+ for (AttributeAssignmentExpressionType assignment : expression.getAttributeAssignmentExpression()) {
+ // 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<Object>(null, null));
+ ob.addAttributeAssignment(attribute);
+ }
+ if (this.callback != null && 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<AdviceExpressionType> expressions = adviceExpressionstype.getAdviceExpression();
+ for (AdviceExpressionType expression : expressions) {
+ StdMutableAdvice ob = new StdMutableAdvice(new IdentifierImpl(expression.getAdviceId()));
+ for (AttributeAssignmentExpressionType assignment : expression.getAttributeAssignmentExpression()) {
+ 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<Object>(null, null));
+ ob.addAttributeAssignment(attribute);
+ }
+ if (this.callback != null && 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<Object> list) {
+ if (list == null) {
+ return CallbackResult.CONTINUE;
+ }
+ for (Object o : list) {
+ if (o instanceof VariableDefinitionType && this.callback != null
+ && this.callback.onVariable(policy, (VariableDefinitionType) o) == CallbackResult.STOP) {
+ return CallbackResult.STOP;
+ }
+ }
+
+ return CallbackResult.CONTINUE;
+ }
+
+ /**
+ * Scans the list of conditions.
+ *
+ * @param rule RuleType
+ * @param condition ConditionType
+ * @return CallbackResult
+ */
+ protected CallbackResult scanConditions(RuleType rule, ConditionType condition) {
+ if (condition != null && this.callback != null
+ && 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 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;
+ 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;
+ }
+ logger.warn("No version set in policy");
+ 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;
+ }
+ }
+
+ /**
+ * getCreatedByModifiedBy.
+ *
+ * @param policyPath Path
+ * @return List of String
+ * @throws IOException IOException
+ */
+ public static List<String> getCreatedByModifiedBy(Path policyPath) throws IOException {
+ String createdBy = "";
+ String modifiedBy = "";
+ String createdValue = "@CreatedBy:";
+ String modifiedValue = "@ModifiedBy:";
+ for (String line : Files.readAllLines(policyPath)) {
+ line = line.replaceAll("\\s+", "");
+ if (line.isEmpty()) {
+ continue;
+ }
+ if (line.contains("<Description>") && line.contains(createdValue) && line.contains(modifiedValue)) {
+ createdBy = line.substring(line.indexOf(createdValue) + createdValue.length(),
+ line.lastIndexOf(createdValue));
+ modifiedBy = line.substring(line.indexOf(modifiedValue) + modifiedValue.length(),
+ line.lastIndexOf(modifiedValue));
+ break;
+ }
+ }
+ return Arrays.asList(createdBy, modifiedBy);
+ }
+
+ // get the Created Name of the User on reading the Xml file
+ /**
+ * getCreatedBy.
+ *
+ * @param policyPath Path
+ * @return String
+ * @throws IOException IOException
+ */
+ 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("<Description>") && 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
+ /**
+ * getModifiedBy.
+ *
+ * @param policyPath Path
+ * @return String
+ * @throws IOException IOException
+ */
+ 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("<Description>") && 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 is - 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);
+ Element element = doc.getDocumentElement();
+ //
+ // Is it a 3.0 policy?
+ //
+ if ("urn:oasis:names:tc:xacml:3.0:core:schema:wd-17".equals(element.getNamespaceURI())) {
+ //
+ // A policyset or policy could be the root
+ //
+ if (element.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<PolicyType> root = um.unmarshal(element, PolicyType.class);
+ //
+ // Here is our policy set class
+ //
+ return root.getValue();
+ } else if (element.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<PolicySetType> root = um.unmarshal(element, PolicySetType.class);
+ //
+ // Here is our policy set class
+ //
+ return root.getValue();
+ } else {
+ if (logger.isDebugEnabled()) {
+ logger.debug("Not supported yet: " + element.getNodeName());
+ }
+ }
+ } else {
+ logger.warn("unsupported namespace: " + element.getNamespaceURI());
+ }
+ } catch (Exception e) {
+ PolicyLogger.error(MessageCodes.ERROR_SCHEMA_INVALID, e, "XACMLPolicyScanner", "Exception in readPolicy");
+ }
+ return null;
+ }
+
+ /**
+ * getPolicyObject.
+ *
+ * @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
index fb65bb715..f28d829ee 100644
--- 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
@@ -30,13 +30,13 @@ 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;
@@ -52,6 +52,9 @@ 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.eelf.MessageCodes;
+import org.onap.policy.common.logging.eelf.PolicyLogger;
+
/**
* Helper static class for policy writing.
*
@@ -128,7 +131,6 @@ public class XACMLPolicyWriter {
}
}
-
/**
* Helper static class that does the work to write a policy to a file on disk.
*
@@ -148,6 +150,7 @@ public class XACMLPolicyWriter {
/**
* Helper static class that reads the JAXB element and return policy input stream.
+ *
* @param policyElement
* @param className (PolicyType or PolicySetType ?).
* @return ByteArrayInputStream.
@@ -203,21 +206,24 @@ public class XACMLPolicyWriter {
}
}
- @SuppressWarnings({ "unchecked", "rawtypes" })
+ @SuppressWarnings({"unchecked", "rawtypes"})
public static String changeFileNameInXmlWhenRenamePolicy(Path filename) {
String extension = "";
String domain = null;
String repository = "repository";
- if(filename.toString().contains("Config_")){
- domain = filename.toString().substring(filename.toString().indexOf(repository) + (repository.length()+1), filename.toString().indexOf("Config_"));
- }else if(filename.toString().contains("Action_")){
- domain = filename.toString().substring(filename.toString().indexOf(repository) + (repository.length()+1), filename.toString().indexOf("Action_"));
- }else if(filename.toString().contains("Decision_")){
- domain = filename.toString().substring(filename.toString().indexOf(repository) + (repository.length()+1), filename.toString().indexOf("Decision_"));
+ if (filename.toString().contains("Config_")) {
+ domain = filename.toString().substring(filename.toString().indexOf(repository) + (repository.length() + 1),
+ filename.toString().indexOf("Config_"));
+ } else if (filename.toString().contains("Action_")) {
+ domain = filename.toString().substring(filename.toString().indexOf(repository) + (repository.length() + 1),
+ filename.toString().indexOf("Action_"));
+ } else if (filename.toString().contains("Decision_")) {
+ domain = filename.toString().substring(filename.toString().indexOf(repository) + (repository.length() + 1),
+ filename.toString().indexOf("Decision_"));
}
- if(domain.contains(File.separator)){
- domain = domain.replace(File.separator, ".");
+ if (domain.contains(File.separator)) {
+ domain = domain.replace(File.separator, ".");
}
try {
JAXBContext context = JAXBContext.newInstance(PolicyType.class);
@@ -227,73 +233,100 @@ public class XACMLPolicyWriter {
if (policyType != null) {
TargetType targetType = policyType.getTarget();
List<AnyOfType> anyOfTypes = targetType.getAnyOf();
- for( Iterator anyOfIte = anyOfTypes.iterator(); anyOfIte.hasNext(); ){
+ for (Iterator anyOfIte = anyOfTypes.iterator(); anyOfIte.hasNext();) {
AnyOfType anyOfType = (AnyOfType) anyOfIte.next();
List<AllOfType> allOf = anyOfType.getAllOf();
- for( Iterator allOfIte = allOf.iterator(); allOfIte.hasNext(); ){
+ for (Iterator allOfIte = allOf.iterator(); allOfIte.hasNext();) {
AllOfType allOfType = (AllOfType) allOfIte.next();
List<MatchType> match = allOfType.getMatch();
- for( Iterator matchIte = match.iterator(); matchIte.hasNext();) {
- MatchType matchType = (MatchType) matchIte.next();
- if("PolicyName".equals(matchType.getAttributeDesignator().getAttributeId())){
+ for (Iterator matchIte = match.iterator(); matchIte.hasNext();) {
+ MatchType matchType = (MatchType) matchIte.next();
+ if ("PolicyName".equals(matchType.getAttributeDesignator().getAttributeId())) {
AttributeValueType attributeValueType = matchType.getAttributeValue();
List<Object> contents = attributeValueType.getContent();
if (contents != null && !contents.isEmpty()) {
- String tmp = filename.getFileName()+"";
+ String tmp = filename.getFileName() + "";
String newName = tmp.substring(0, tmp.lastIndexOf("."));
attributeValueType.getContent().clear();
- attributeValueType.getContent().add(domain + newName + "." + "xml");
+ attributeValueType.getContent().add(domain + newName + "." + "xml");
}
}
}
}
}
- if(filename.toString().contains("Config_") || filename.toString().contains("Action_")){
- List<Object> objects = policyType.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition();
+ if (filename.toString().contains("Config_") || filename.toString().contains("Action_")) {
+ List<Object> objects =
+ policyType.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition();
if (objects != null && !objects.isEmpty()) {
for (Iterator ite = objects.iterator(); ite.hasNext();) {
- RuleType ruleType = (RuleType ) ite.next();
+ RuleType ruleType = (RuleType) ite.next();
AdviceExpressionsType adviceExpressionsType = ruleType.getAdviceExpressions();
if (adviceExpressionsType != null) {
- List<AdviceExpressionType> adviceExpressionTypes = adviceExpressionsType.getAdviceExpression();
+ List<AdviceExpressionType> adviceExpressionTypes =
+ adviceExpressionsType.getAdviceExpression();
if (adviceExpressionTypes != null && !adviceExpressionTypes.isEmpty()) {
- for (Iterator iterator = adviceExpressionTypes
- .iterator(); iterator.hasNext();) {
- AdviceExpressionType adviceExpressionType = (AdviceExpressionType) iterator
- .next();
- if (adviceExpressionType.getAdviceId() != null && !"".equals(adviceExpressionType.getAdviceId()) && ("configID".equals(adviceExpressionType.getAdviceId())
- || "faultID".equals(adviceExpressionType.getAdviceId()) || "PMID".equals(adviceExpressionType.getAdviceId())||"firewallConfigID".equals(adviceExpressionType.getAdviceId()) || "OptimizationID".equals(adviceExpressionType.getAdviceId())
- || "MSID".equals(adviceExpressionType.getAdviceId())) || "GocID".equals(adviceExpressionType.getAdviceId())||"GocHPID".equals(adviceExpressionType.getAdviceId())||"BRMSRAWID".equals(adviceExpressionType.getAdviceId())
- || "BRMSPARAMID".equals(adviceExpressionType.getAdviceId())|| "HPSuppID".equals(adviceExpressionType.getAdviceId()) || "HPFlapID".equals(adviceExpressionType.getAdviceId()) || "HPOverID".equals(adviceExpressionType.getAdviceId()))
- {
- List<AttributeAssignmentExpressionType> attributeAssignmentExpressionTypes = adviceExpressionType.getAttributeAssignmentExpression();
- if (attributeAssignmentExpressionTypes != null && !attributeAssignmentExpressionTypes.isEmpty()) {
- for (Iterator iterator2 = attributeAssignmentExpressionTypes
- .iterator(); iterator2.hasNext();) {
- AttributeAssignmentExpressionType attributeAssignmentExpressionType = (AttributeAssignmentExpressionType) iterator2
- .next();
- if ("URLID".equals(attributeAssignmentExpressionType.getAttributeId())) {
- JAXBElement<AttributeValueType> attributeValueType = (JAXBElement<AttributeValueType>) attributeAssignmentExpressionType.getExpression();
- AttributeValueType attributeValueType1 = attributeValueType.getValue();
+ for (Iterator iterator = adviceExpressionTypes.iterator(); iterator.hasNext();) {
+ AdviceExpressionType adviceExpressionType =
+ (AdviceExpressionType) iterator.next();
+ if (adviceExpressionType.getAdviceId() != null
+ && !"".equals(adviceExpressionType.getAdviceId())
+ && ("configID".equals(adviceExpressionType.getAdviceId())
+ || "faultID".equals(adviceExpressionType.getAdviceId())
+ || "PMID".equals(adviceExpressionType.getAdviceId())
+ || "firewallConfigID".equals(adviceExpressionType.getAdviceId())
+ || "OptimizationID".equals(adviceExpressionType.getAdviceId())
+ || "MSID".equals(adviceExpressionType.getAdviceId()))
+ || "GocID".equals(adviceExpressionType.getAdviceId())
+ || "GocHPID".equals(adviceExpressionType.getAdviceId())
+ || "BRMSRAWID".equals(adviceExpressionType.getAdviceId())
+ || "BRMSPARAMID".equals(adviceExpressionType.getAdviceId())
+ || "HPSuppID".equals(adviceExpressionType.getAdviceId())
+ || "HPFlapID".equals(adviceExpressionType.getAdviceId())
+ || "HPOverID".equals(adviceExpressionType.getAdviceId())) {
+ List<AttributeAssignmentExpressionType> attributeAssignmentExpressionTypes =
+ adviceExpressionType.getAttributeAssignmentExpression();
+ if (attributeAssignmentExpressionTypes != null
+ && !attributeAssignmentExpressionTypes.isEmpty()) {
+ for (Iterator iterator2 =
+ attributeAssignmentExpressionTypes.iterator(); iterator2
+ .hasNext();) {
+ AttributeAssignmentExpressionType attributeAssignmentExpressionType =
+ (AttributeAssignmentExpressionType) iterator2.next();
+ if ("URLID".equals(
+ attributeAssignmentExpressionType.getAttributeId())) {
+ JAXBElement<AttributeValueType> attributeValueType =
+ (JAXBElement<AttributeValueType>) attributeAssignmentExpressionType
+ .getExpression();
+ AttributeValueType attributeValueType1 =
+ attributeValueType.getValue();
String configUrl = "$URL";
- String urlVal = (String) attributeValueType1.getContent().get(0);
- String origExtension = urlVal.substring(urlVal.lastIndexOf('.')+1).trim();
+ 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;
+ txtFileName = txtFileName.substring(0,
+ txtFileName.lastIndexOf(".") + 1) + origExtension;
+ txtFileName = configUrl + File.separator + "Config"
+ + File.separator + domain + txtFileName;
attributeValueType1.getContent().add(txtFileName);
- } else if ("PolicyName".equals(attributeAssignmentExpressionType.getAttributeId())) {
- JAXBElement<AttributeValueType> attributeValueType = (JAXBElement<AttributeValueType>) attributeAssignmentExpressionType.getExpression();
- AttributeValueType attributeValueType1 = attributeValueType.getValue();
+ } else if ("PolicyName".equals(
+ attributeAssignmentExpressionType.getAttributeId())) {
+ JAXBElement<AttributeValueType> attributeValueType =
+ (JAXBElement<AttributeValueType>) attributeAssignmentExpressionType
+ .getExpression();
+ AttributeValueType attributeValueType1 =
+ attributeValueType.getValue();
List<Object> contents = attributeValueType1.getContent();
if (contents != null && !contents.isEmpty()) {
- String tmp = filename.getFileName()+"";
+ String tmp = filename.getFileName() + "";
String newName = tmp.substring(0, tmp.lastIndexOf("."));
attributeValueType1.getContent().clear();
- attributeValueType1.getContent().add(domain + newName + "." + "xml");
+ attributeValueType1.getContent()
+ .add(domain + newName + "." + "xml");
}
}
@@ -308,33 +341,47 @@ public class XACMLPolicyWriter {
if (objects != null && !objects.isEmpty()) {
for (Iterator ite1 = objects.iterator(); ite1.hasNext();) {
- RuleType ruleType1 = (RuleType ) ite1.next();
- ObligationExpressionsType obligationExpressionsType = ruleType1.getObligationExpressions();
+ RuleType ruleType1 = (RuleType) ite1.next();
+ ObligationExpressionsType obligationExpressionsType =
+ ruleType1.getObligationExpressions();
if (obligationExpressionsType != null) {
- List<ObligationExpressionType> obligationExpressionType = obligationExpressionsType.getObligationExpression();
+ List<ObligationExpressionType> obligationExpressionType =
+ obligationExpressionsType.getObligationExpression();
if (obligationExpressionType != null && !obligationExpressionType.isEmpty()) {
- for (Iterator iterator = obligationExpressionType
- .iterator(); iterator.hasNext();) {
- ObligationExpressionType obligationExpressionTypes = (ObligationExpressionType) iterator
- .next();
- if (obligationExpressionTypes.getObligationId() != null && !"".equals(obligationExpressionTypes.getObligationId())) {
- List<AttributeAssignmentExpressionType> attributeAssignmentExpressionTypes = obligationExpressionTypes.getAttributeAssignmentExpression();
- if (attributeAssignmentExpressionTypes != null && !attributeAssignmentExpressionTypes.isEmpty()) {
- for (Iterator iterator2 = attributeAssignmentExpressionTypes
- .iterator(); iterator2.hasNext();) {
- AttributeAssignmentExpressionType attributeAssignmentExpressionType = (AttributeAssignmentExpressionType) iterator2
- .next();
- if ("body".equals(attributeAssignmentExpressionType.getAttributeId())) {
- JAXBElement<AttributeValueType> attributeValueType = (JAXBElement<AttributeValueType>) attributeAssignmentExpressionType.getExpression();
- AttributeValueType attributeValueType1 = attributeValueType.getValue();
+ for (Iterator iterator = obligationExpressionType.iterator(); iterator
+ .hasNext();) {
+ ObligationExpressionType obligationExpressionTypes =
+ (ObligationExpressionType) iterator.next();
+ if (obligationExpressionTypes.getObligationId() != null
+ && !"".equals(obligationExpressionTypes.getObligationId())) {
+ List<AttributeAssignmentExpressionType> attributeAssignmentExpressionTypes =
+ obligationExpressionTypes.getAttributeAssignmentExpression();
+ if (attributeAssignmentExpressionTypes != null
+ && !attributeAssignmentExpressionTypes.isEmpty()) {
+ for (Iterator iterator2 =
+ attributeAssignmentExpressionTypes.iterator(); iterator2
+ .hasNext();) {
+ AttributeAssignmentExpressionType attributeAssignmentExpressionType =
+ (AttributeAssignmentExpressionType) iterator2.next();
+ if ("body".equals(
+ attributeAssignmentExpressionType.getAttributeId())) {
+ JAXBElement<AttributeValueType> attributeValueType =
+ (JAXBElement<AttributeValueType>) attributeAssignmentExpressionType
+ .getExpression();
+ AttributeValueType attributeValueType1 =
+ attributeValueType.getValue();
String configUrl = "$URL";
- String urlVal = (String) attributeValueType1.getContent().get(0);
- String origExtension = urlVal.substring(urlVal.lastIndexOf('.')+1).trim();
+ 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;
+ txtFileName = txtFileName.substring(0,
+ txtFileName.lastIndexOf(".") + 1) + origExtension;
+ txtFileName = configUrl + File.separator + "Action"
+ + File.separator + domain + txtFileName;
attributeValueType1.getContent().add(txtFileName);
}
@@ -352,7 +399,7 @@ public class XACMLPolicyWriter {
}
writePolicyFile(filename, policyType);
}
- }catch (JAXBException e) {
+ } catch (JAXBException e) {
PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "XACMLPolicyWriter", "writePolicyFile failed");
}
diff --git a/ONAP-XACML/src/test/java/org/onap/policy/xacml/api/pap/ONAPPapEngineFactoryTest.java b/ONAP-XACML/src/test/java/org/onap/policy/xacml/api/pap/ONAPPapEngineFactoryTest.java
new file mode 100644
index 000000000..94b28b260
--- /dev/null
+++ b/ONAP-XACML/src/test/java/org/onap/policy/xacml/api/pap/ONAPPapEngineFactoryTest.java
@@ -0,0 +1,38 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP-XACML
+ * ================================================================================
+ * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 static org.junit.Assert.assertNotNull;
+
+import com.att.research.xacml.util.FactoryException;
+import org.junit.Test;
+import org.onap.policy.xacml.std.pap.StdEngineFactory;
+
+public class ONAPPapEngineFactoryTest {
+
+ @Test
+ public void test() throws FactoryException {
+ ONAPPapEngineFactory factory =
+ ONAPPapEngineFactory.newInstance(StdEngineFactory.class.getName());
+ assertNotNull(factory);
+ }
+
+}
diff --git a/ONAP-XACML/src/test/java/org/onap/policy/xacml/test/api/XACMLErrorConstantsTest.java b/ONAP-XACML/src/test/java/org/onap/policy/xacml/test/api/XACMLErrorConstantsTest.java
index 0166a128a..3f9c99bcd 100644
--- a/ONAP-XACML/src/test/java/org/onap/policy/xacml/test/api/XACMLErrorConstantsTest.java
+++ b/ONAP-XACML/src/test/java/org/onap/policy/xacml/test/api/XACMLErrorConstantsTest.java
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP-XACML
* ================================================================================
- * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2018-2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Modifications Copyright (C) 2019 Samsung
* ================================================================================
@@ -23,18 +23,19 @@
package org.onap.policy.xacml.test.api;
import static org.junit.Assert.assertTrue;
+
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Modifier;
+
import org.junit.Test;
import org.onap.policy.xacml.api.XACMLErrorConstants;
public class XACMLErrorConstantsTest {
@Test
- public void testConstructorIsPrivate1() throws NoSuchMethodException, IllegalAccessException,
- InvocationTargetException, InstantiationException {
- Constructor<XACMLErrorConstants> constructor =
- XACMLErrorConstants.class.getDeclaredConstructor();
+ public void testConstructorIsPrivate1()
+ throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
+ Constructor<XACMLErrorConstants> constructor = XACMLErrorConstants.class.getDeclaredConstructor();
assertTrue(Modifier.isPrivate(constructor.getModifiers()));
constructor.setAccessible(true);
constructor.newInstance();
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
index 6ab9790c1..660bbd6e9 100644
--- 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
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP-XACML
* ================================================================================
- * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2020 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Modifications Copyright (C) 2019 Samsung
* ================================================================================
@@ -19,31 +19,76 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.policy.xacml.test.std.pap;
-import static org.junit.Assert.assertTrue;
+import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.catchThrowable;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertNull;
import static org.junit.Assert.fail;
+
+import com.att.research.xacml.api.pap.PAPException;
+import com.att.research.xacml.std.pap.StdEngine;
+import com.att.research.xacml.util.FactoryException;
+import java.io.File;
import java.io.IOException;
import java.util.Properties;
+import org.junit.AfterClass;
+import org.junit.BeforeClass;
+import org.junit.Rule;
import org.junit.Test;
+import org.junit.rules.TemporaryFolder;
+import org.onap.policy.xacml.api.pap.PAPPolicyEngine;
import org.onap.policy.xacml.std.pap.StdEngineFactory;
-import com.att.research.xacml.api.pap.PAPException;
-import com.att.research.xacml.std.pap.StdEngine;
-import com.att.research.xacml.util.FactoryException;
public class StdEngineFactoryTest {
+
+ private static String systemProperty;
+
+ @Rule
+ public TemporaryFolder folder = new TemporaryFolder();
+
+ @BeforeClass
+ public static void saveSystemProperty() {
+ systemProperty = System.getProperty(StdEngine.PROP_PAP_REPO);
+ }
+
+ /**
+ * restoreSystemProperty.
+ */
+ @AfterClass
+ public static void restoreSystemProperty() {
+ if (systemProperty != null) {
+ System.setProperty(StdEngine.PROP_PAP_REPO, systemProperty);
+ } else {
+ System.clearProperty(StdEngine.PROP_PAP_REPO);
+ }
+ }
+
@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);
+ assertNotNull(stdFactory.newEngine());
Properties properties = new Properties();
properties.setProperty("xacml.pap.pdps", "src/test/resources/pdps");
- assertTrue(stdFactory.newEngine(properties) != null);
+ assertNotNull(stdFactory.newEngine(properties));
StdEngineFactory stdFactoryNew = new StdEngineFactory();
System.setProperty("xacml.pap.pdps", "src/test/resources/pdpstest");
- assertTrue(stdFactoryNew.newEngine() != null);
+ PAPPolicyEngine engine = stdFactoryNew.newEngine();
+ assertNotNull(engine);
+
+ assertThatExceptionOfType(NullPointerException.class).isThrownBy(() ->
+ engine.newGroup(null, null)
+ );
+
+ assertThatExceptionOfType(NullPointerException.class).isThrownBy(() ->
+ engine.movePDP(null, null)
+ );
+
}
@Test
@@ -53,25 +98,53 @@ public class StdEngineFactoryTest {
String tmpdir = System.getProperty("java.io.tmpdir");
props.setProperty(StdEngine.PROP_PAP_REPO, tmpdir);
- // Set the system property temporarily
- String systemKey = StdEngine.PROP_PAP_REPO;
- String oldProperty = System.getProperty(systemKey);
- System.setProperty(systemKey, tmpdir);
-
// Test factory failure cases
try {
StdEngineFactory factory = new StdEngineFactory();
- factory.newEngine();
- factory.newEngine(props);
+ assertNotNull(factory.newEngine());
+ assertNotNull(factory.newEngine(props));
} catch (Exception ex) {
fail("Not expecting any exceptions: " + ex);
}
- // Restore the original system property
- if (oldProperty != null) {
- System.setProperty(systemKey, oldProperty);
- } else {
- System.clearProperty(systemKey);
- }
+ }
+
+ @Test
+ public void testException() throws FactoryException, PAPException, IOException {
+ Properties props = new Properties();
+ File myFolder = folder.newFolder("idontexist");
+ props.setProperty(StdEngine.PROP_PAP_REPO, myFolder.getAbsolutePath());
+ StdEngineFactory factory = new StdEngineFactory();
+ assertNotNull(factory.newEngine(props));
+
+ //
+ //
+ //
+ myFolder.setReadOnly();
+ assertThat(catchThrowable(() -> { throw new PAPException(); }))
+ .isInstanceOf(PAPException.class);
+
+ //
+ //
+ //
+ File myFile = folder.newFile("iamafile");
+ props.setProperty(StdEngine.PROP_PAP_REPO, myFile.getAbsolutePath());
+ assertThatExceptionOfType(PAPException.class).isThrownBy(() ->
+ factory.newEngine(props)
+ );
+
+ //
+ //
+ //
+ props.setProperty(StdEngine.PROP_PAP_REPO, myFolder.getAbsolutePath() + "/badparent/dontexist");
+ assertNull(factory.newEngine(props));
+
+ //
+ //
+ //
+ System.setProperty(StdEngine.PROP_PAP_REPO, myFolder.getAbsolutePath() + "/badparent/dontexist");
+
+ assertNull(factory.newEngine());
+
}
}
diff --git a/ONAP-XACML/src/test/java/org/onap/policy/xacml/test/std/pap/StdEngineTest.java b/ONAP-XACML/src/test/java/org/onap/policy/xacml/test/std/pap/StdEngineTest.java
index 79b43b130..79c2893ff 100644
--- a/ONAP-XACML/src/test/java/org/onap/policy/xacml/test/std/pap/StdEngineTest.java
+++ b/ONAP-XACML/src/test/java/org/onap/policy/xacml/test/std/pap/StdEngineTest.java
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP-XACML
* ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017, 2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Modifications Copyright (C) 2019 Samsung
* ================================================================================
@@ -19,12 +19,17 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.policy.xacml.test.std.pap;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
+
+import com.att.research.xacml.api.pap.PAPException;
+import com.att.research.xacml.api.pap.PDPPolicy;
+
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
@@ -35,6 +40,7 @@ import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.Properties;
+
import org.apache.commons.io.FileUtils;
import org.junit.After;
import org.junit.Before;
@@ -46,8 +52,6 @@ import org.onap.policy.xacml.api.pap.OnapPDP;
import org.onap.policy.xacml.api.pap.OnapPDPGroup;
import org.onap.policy.xacml.std.pap.StdEngine;
import org.onap.policy.xacml.std.pap.StdPDPGroup;
-import com.att.research.xacml.api.pap.PAPException;
-import com.att.research.xacml.api.pap.PDPPolicy;
public class StdEngineTest {
@@ -58,18 +62,28 @@ public class StdEngineTest {
@Rule
public ExpectedException expectedException = ExpectedException.none();
+ /**
+ * setUpClass.
+ *
+ * @throws IOException IOException
+ */
@BeforeClass
public static void setUpClass() throws IOException {
new File("target/test/resources/pdps").mkdirs();
new File("target/test/resources/emptyPapGroupsDefault").mkdirs();
Files.copy(Paths.get("src/test/resources/pdps/xacml.properties"),
- Paths.get("target/test/resources/pdps/xacml.properties"),
- StandardCopyOption.REPLACE_EXISTING);
+ Paths.get("target/test/resources/pdps/xacml.properties"), StandardCopyOption.REPLACE_EXISTING);
Files.copy(Paths.get("src/test/resources/emptyPapGroupsDefault/xacml.properties"),
Paths.get("target/test/resources/emptyPapGroupsDefault/xacml.properties"),
StandardCopyOption.REPLACE_EXISTING);
}
+ /**
+ * setUp.
+ *
+ * @throws PAPException PAPException
+ * @throws IOException IOException
+ */
@Before
public void setUp() throws PAPException, IOException {
@@ -114,10 +128,8 @@ public class StdEngineTest {
repository = Paths.get("target/test/resources/nonExisting");
new StdEngine(repository);
- assertTrue(Files.exists(
- Paths.get("target/test/resources/nonExisting/default/xacml.pip.properties")));
- assertTrue(Files.exists(
- Paths.get("target/test/resources/nonExisting/default/xacml.policy.properties")));
+ assertTrue(Files.exists(Paths.get("target/test/resources/nonExisting/default/xacml.pip.properties")));
+ assertTrue(Files.exists(Paths.get("target/test/resources/nonExisting/default/xacml.policy.properties")));
assertTrue(Files.exists(Paths.get("target/test/resources/nonExisting/xacml.properties")));
FileUtils.deleteDirectory(repository.toFile());
}
@@ -128,17 +140,14 @@ public class StdEngineTest {
repository = Paths.get("target/test/resources/emptyPapGroupsDefault");
new StdEngine(repository);
- assertTrue(Files.exists(Paths
- .get("target/test/resources/emptyPapGroupsDefault/default/xacml.pip.properties")));
- assertTrue(Files.exists(Paths.get(
- "target/test/resources/emptyPapGroupsDefault/default/xacml.policy.properties")));
- assertTrue(Files
- .exists(Paths.get("target/test/resources/emptyPapGroupsDefault/xacml.properties")));
+ assertTrue(Files.exists(Paths.get("target/test/resources/emptyPapGroupsDefault/default/xacml.pip.properties")));
+ assertTrue(
+ Files.exists(Paths.get("target/test/resources/emptyPapGroupsDefault/default/xacml.policy.properties")));
+ assertTrue(Files.exists(Paths.get("target/test/resources/emptyPapGroupsDefault/xacml.properties")));
}
@Test
- public void testNewGroupAndRemoveGroup()
- throws NullPointerException, PAPException, IOException {
+ public void testNewGroupAndRemoveGroup() throws NullPointerException, PAPException, IOException {
OnapPDPGroup newGroup = createGroup("newGroup", "Description of new group");
assertNotNull(newGroup);
@@ -270,8 +279,7 @@ public class StdEngineTest {
assertEquals(0, group2.getPdps().size());
expectedException.expect(NullPointerException.class);
- expectedException.expectMessage(
- "Group targeted for deletion has PDPs, you must provide a new group for them.");
+ expectedException.expectMessage("Group targeted for deletion has PDPs, you must provide a new group for them.");
stdEngine.removeGroup(group1, null);
}
@@ -285,17 +293,15 @@ public class StdEngineTest {
assertNull(stdEngine.getGroup("newGroup"));
assertNotNull(stdEngine.getGroup("AnUpdatedName"));
assertEquals("AnUpdatedName", stdEngine.getGroup("AnUpdatedName").getName());
- assertEquals("Description of new group",
- stdEngine.getGroup("AnUpdatedName").getDescription());
+ assertEquals("Description of new group", stdEngine.getGroup("AnUpdatedName").getDescription());
}
@Test
- public void testUpdateGroupDescription()
- throws NullPointerException, PAPException, IOException {
+ public void testUpdateGroupDescription() throws NullPointerException, PAPException, IOException {
OnapPDPGroup newGroup = createGroup("newGroup", "Description of new group");
- OnapPDPGroup updatedGroup = new StdPDPGroup(newGroup.getId(), newGroup.getName(),
- "An updated description", Paths.get("target/test/resources/pdps/newGroup"));
+ OnapPDPGroup updatedGroup = new StdPDPGroup(newGroup.getId(), newGroup.getName(), "An updated description",
+ Paths.get("target/test/resources/pdps/newGroup"));
updatedGroup.setDescription("An updated description");
stdEngine.updateGroup(updatedGroup);
assertEquals("newGroup", stdEngine.getGroup("newGroup").getName());
@@ -326,8 +332,7 @@ public class StdEngineTest {
}
@Test
- public void testUpdateGroupNameEmptyString()
- throws NullPointerException, PAPException, IOException {
+ public void testUpdateGroupNameEmptyString() throws NullPointerException, PAPException, IOException {
StdPDPGroup group = new StdPDPGroup("groupId", "", "description", null);
expectedException.expect(PAPException.class);
expectedException.expectMessage("New name for group cannot be null or blank");
@@ -343,8 +348,7 @@ public class StdEngineTest {
}
@Test
- public void testPublishAndRemovePolicy()
- throws NullPointerException, PAPException, FileNotFoundException {
+ public void testPublishAndRemovePolicy() throws NullPointerException, PAPException, FileNotFoundException {
OnapPDPGroup newGroup = createGroup("newGroup", "Description of new group");
InputStream inputStream = new FileInputStream(
"src/test/resources/pdps/default/com.Config_BRMS_Param_BRMSParamvFWDemoPolicy.1.xml");
@@ -358,15 +362,13 @@ public class StdEngineTest {
}
@Test
- public void testPublishPolicyNull()
- throws NullPointerException, PAPException, FileNotFoundException {
+ public void testPublishPolicyNull() throws NullPointerException, PAPException, FileNotFoundException {
expectedException.expect(NullPointerException.class);
stdEngine.publishPolicy(null, null, true, null, null);
}
@Test
- public void testPublishPolicyUnknownGroup()
- throws NullPointerException, PAPException, FileNotFoundException {
+ public void testPublishPolicyUnknownGroup() throws NullPointerException, PAPException, FileNotFoundException {
OnapPDPGroup unknownGroup = new StdPDPGroup("unknownId", null);
expectedException.expect(PAPException.class);
@@ -375,15 +377,13 @@ public class StdEngineTest {
}
@Test
- public void testRemovePolicyNull()
- throws NullPointerException, PAPException, FileNotFoundException {
+ public void testRemovePolicyNull() throws NullPointerException, PAPException, FileNotFoundException {
expectedException.expect(NullPointerException.class);
stdEngine.removePolicy(null, null);
}
@Test
- public void testRemovePolicyUnknownGroup()
- throws NullPointerException, PAPException, FileNotFoundException {
+ public void testRemovePolicyUnknownGroup() throws NullPointerException, PAPException, FileNotFoundException {
OnapPDPGroup unknownGroup = new StdPDPGroup("unknownId", null);
expectedException.expect(PAPException.class);
diff --git a/ONAP-XACML/src/test/java/org/onap/policy/xacml/test/std/pap/StdPAPPolicyTest.java b/ONAP-XACML/src/test/java/org/onap/policy/xacml/test/std/pap/StdPAPPolicyTest.java
index d5146d05a..3c32cb24f 100644
--- a/ONAP-XACML/src/test/java/org/onap/policy/xacml/test/std/pap/StdPAPPolicyTest.java
+++ b/ONAP-XACML/src/test/java/org/onap/policy/xacml/test/std/pap/StdPAPPolicyTest.java
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP-XACML
* ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017, 2019 AT&T Intellectual Property. All rights reserved.
* Modifications Copyright (C) 2018 Samsung Electronics Co., Ltd.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
@@ -18,14 +18,15 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.policy.xacml.test.std.pap;
import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import java.net.URI;
import java.net.URISyntaxException;
-import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
@@ -47,556 +48,146 @@ public class StdPAPPolicyTest {
@Before
public void setUp() {
-
- Paths.get("src/test/resources/pdps");
- try {
- stdPAPPolicy = new StdPAPPolicy();
- } catch (Exception e) {
- logger.info(e);
- }
- }
-
- @Test
- public void testGetActionAttribute() {
- try {
- stdPAPPolicy.setActionAttribute("test");
- assertTrue(stdPAPPolicy.getActionAttribute() != null);
- } catch (Exception e) {
- logger.info(e);
- }
- }
-
- @Test
- public void testGetActionBody() {
- try {
- stdPAPPolicy.setActionBody("actionBody");
- assertTrue(stdPAPPolicy.getActionBody() != null);
- } catch (Exception e) {
- logger.info(e);
- }
-
- }
-
- @Test
- public void testGetActionDictHeader() {
- try {
- stdPAPPolicy.setActionDictHeader("actionDictHeader");
- assertTrue(stdPAPPolicy.getActionDictHeader() != null);
- } catch (Exception e) {
- logger.info(e);
- }
- }
-
- @Test
- public void testGetActionDictMethod() {
- try {
- stdPAPPolicy.setActionDictMethod("actionDictMethod");
- assertTrue(stdPAPPolicy.getActionDictMethod() != null);
- } catch (Exception e) {
- logger.info(e);
- }
- }
-
- @Test
- public void testGetActionDictType() {
- try {
- stdPAPPolicy.setActionDictType("actionDictType");
- assertTrue(stdPAPPolicy.getActionDictType() != null);
- } catch (Exception e) {
- logger.info(e);
- }
- }
-
- @Test
- public void testGetActionDictUrl() {
- try {
- stdPAPPolicy.setActionDictUrl("actionDictUrl");
- assertTrue(stdPAPPolicy.getActionDictUrl() != null);
- } catch (Exception e) {
- logger.info(e);
- }
- }
-
- @Test
- public void testGetActionPerformer() {
- try {
- stdPAPPolicy.setActionPerformer("actionPerformer");
- assertTrue(stdPAPPolicy.getActionPerformer() != null);
- } catch (Exception e) {
- logger.info(e);
- }
-
- }
-
- @Test
- public void testGetBrmsController() {
- try {
- stdPAPPolicy.setBrmsController("brmsController");
- assertTrue(stdPAPPolicy.getBrmsController() != null);
- } catch (Exception e) {
- logger.info(e);
- }
- }
-
- @Test
- public void testGetBrmsDependency() {
- try {
- stdPAPPolicy.setBrmsDependency(new ArrayList<>());
- assertTrue(stdPAPPolicy.getBrmsDependency() != null);
- } catch (Exception e) {
- logger.info(e);
- }
- }
-
- @Test
- public void testGetConfigBodyData() {
- try {
- stdPAPPolicy.setConfigBodyData("configBodyData");
- assertTrue(stdPAPPolicy.getConfigBodyData() != null);
- } catch (Exception e) {
- logger.info(e);
- }
- }
-
-
- @Test
- public void testGetConfigName() {
- try {
- stdPAPPolicy.setConfigName("configName");
- assertTrue(stdPAPPolicy.getConfigName() != null);
- } catch (Exception e) {
- logger.info(e);
- }
- }
-
- @Test
- public void testGetConfigPolicyType() {
- try {
- stdPAPPolicy.setConfigPolicyType("configPolicyType");
- assertTrue(stdPAPPolicy.getConfigPolicyType() != null);
- } catch (Exception e) {
- logger.info(e);
- }
-
- }
-
- @Test
- public void testGetConfigType() {
- try {
- stdPAPPolicy.setConfigType("configType");
- assertTrue(stdPAPPolicy.getConfigType() != null);
- } catch (Exception e) {
- logger.info(e);
- }
- }
-
- @Test
- public void testGetDataTypeList() {
- try {
- stdPAPPolicy.setDataTypeList(new ArrayList<String>());
- assertTrue(stdPAPPolicy.getDataTypeList() != null);
- } catch (Exception e) {
- logger.info(e);
- }
- }
-
- @Test
- public void testGetDeleteCondition() {
- try {
- stdPAPPolicy.setDeleteCondition("deleteCondition");
- assertTrue(stdPAPPolicy.getDeleteCondition() != null);
- } catch (Exception e) {
- logger.info(e);
- }
- }
-
-
- @Test
- public void testGetDrlRuleAndUIParams() {
- try {
- stdPAPPolicy.setDrlRuleAndUIParams(new HashMap<>());
- assertTrue(stdPAPPolicy.getDrlRuleAndUIParams() != null);
- } catch (Exception e) {
- logger.info(e);
- }
- }
-
- @Test
- public void testGetDropDownMap() {
- try {
- stdPAPPolicy.setDropDownMap(new HashMap<>());
- assertTrue(stdPAPPolicy.getDropDownMap() != null);
- } catch (Exception e) {
- logger.info(e);
- }
-
- }
-
- @Test
- public void testGetDynamicFieldConfigAttributes() {
- try {
- assertTrue(stdPAPPolicy.getDynamicFieldConfigAttributes() != null);
- } catch (Exception e) {
- logger.info(e);
- }
- }
-
- @Test
- public void testGetDynamicRuleAlgorithmCombo() {
- try {
- stdPAPPolicy.setDynamicRuleAlgorithmCombo(new ArrayList<>());
- assertTrue(stdPAPPolicy.getDynamicRuleAlgorithmCombo() != null);
- } catch (Exception e) {
- logger.info(e);
- }
- }
-
- @Test
- public void testGetDynamicRuleAlgorithmField1() {
- try {
- stdPAPPolicy.setDynamicRuleAlgorithmField1(new ArrayList<>());
- assertTrue(stdPAPPolicy.getDynamicRuleAlgorithmField1() != null);
- } catch (Exception e) {
- logger.info(e);
- }
- }
-
- @Test
- public void testGetDictionary() {
- try {
- stdPAPPolicy.setDictionary("dictionary");
- assertTrue(stdPAPPolicy.getDictionary() != null);
- } catch (Exception e) {
- logger.info(e);
- }
- }
-
- @Test
- public void testGetDictionaryFields() {
- try {
- stdPAPPolicy.setDictionaryFields("dictionaryFields");
- assertTrue(stdPAPPolicy.getDictionaryFields() != null);
- } catch (Exception e) {
- logger.info(e);
- }
-
- }
-
- @Test
- public void testGetDictionaryType() {
- try {
- stdPAPPolicy.setDictionaryType("dictionaryType");
- assertTrue(stdPAPPolicy.getDictionaryType() != null);
- } catch (Exception e) {
- logger.info(e);
- }
- }
-
- @Test
- public void testGetDomainDir() {
- try {
- stdPAPPolicy.setDomainDir("domain");
- assertTrue(stdPAPPolicy.getDomainDir() != null);
- } catch (Exception e) {
- logger.info(e);
- }
- }
-
- @Test
- public void testIsDraft() {
- try {
- stdPAPPolicy.setDraft(true);
- assertTrue(stdPAPPolicy.isDraft() == true);
- } catch (Exception e) {
- logger.info(e);
- }
- }
-
- @Test
- public void testGetDynamicRuleAlgorithmLabels() {
- try {
- stdPAPPolicy.setDynamicRuleAlgorithmLabels(new ArrayList<>());
- assertTrue(stdPAPPolicy.getDynamicRuleAlgorithmLabels() != null);
- } catch (Exception e) {
- logger.info(e);
- }
- }
-
- @Test
- public void testGetDynamicSettingsMap() {
- try {
- stdPAPPolicy.setDynamicSettingsMap(new HashMap<>());
- assertTrue(stdPAPPolicy.getDynamicSettingsMap() != null);
- } catch (Exception e) {
- logger.info(e);
- }
-
- }
-
- @Test
- public void testGetDynamicVariableList() {
- try {
- stdPAPPolicy.setDynamicVariableList(new ArrayList<>());
- assertTrue(stdPAPPolicy.getDynamicVariableList() != null);
- } catch (Exception e) {
- logger.info(e);
- }
- }
-
- @Test
- public void testGetGuard() {
- try {
- stdPAPPolicy.setGuard("domain");
- assertTrue(stdPAPPolicy.getGuard() != null);
- } catch (Exception e) {
- logger.info(e);
- }
- }
-
- @Test
- public void testGetHighestVersion() {
- try {
- stdPAPPolicy.setHighestVersion(123);
- assertTrue(stdPAPPolicy.getHighestVersion() != null);
- } catch (Exception e) {
- logger.info(e);
- }
- }
-
- @Test
- public void testgGtJsonBody() {
- try {
- stdPAPPolicy.setJsonBody("jsonBoby");
- assertTrue(stdPAPPolicy.getJsonBody() != null);
- } catch (Exception e) {
- logger.info(e);
- }
- }
-
- @Test
- public void testGetLocation() {
- try {
- stdPAPPolicy.setLocation(new URI("test"));
- assertTrue(stdPAPPolicy.getLocation() != null);
- } catch (Exception e) {
- logger.info(e);
- }
-
- }
-
- @Test
- public void testGetMsLocation() {
- try {
- stdPAPPolicy.setMsLocation("MsLocation");
- assertTrue(stdPAPPolicy.getMsLocation() != null);
- } catch (Exception e) {
- logger.info(e);
- }
- }
-
- @Test
- public void testSetOldPolicyFileName() {
- try {
- stdPAPPolicy.setOldPolicyFileName("domain");
- assertTrue(stdPAPPolicy.getOldPolicyFileName() != null);
- } catch (Exception e) {
- logger.info(e);
- }
- }
-
- @Test
- public void testGetOnapName() {
- try {
- stdPAPPolicy.setOnapName("onap");
- assertTrue(stdPAPPolicy.getOnapName() != null);
- } catch (Exception e) {
- logger.info(e);
- }
- }
-
- @Test
- public void testGetPolicyDescription() {
- try {
- stdPAPPolicy.setPolicyDescription("description test");
- assertTrue(stdPAPPolicy.getPolicyDescription() != null);
- } catch (Exception e) {
- logger.info(e);
- }
- }
-
- @Test
- public void testGetPolicyID() {
- try {
- stdPAPPolicy.setPolicyID("test");
- assertTrue(stdPAPPolicy.getPolicyID() != null);
- } catch (Exception e) {
- logger.info(e);
- }
-
- }
-
- @Test
- public void testSetPolicyName() {
- try {
- stdPAPPolicy.setPolicyName("MsLocation");
- assertTrue(stdPAPPolicy.getPolicyName() != null);
- } catch (Exception e) {
- logger.info(e);
- }
- }
-
- @Test
- public void testSetPriority() {
- try {
- stdPAPPolicy.setPriority("domain");
- assertTrue(stdPAPPolicy.getPriority() != null);
- } catch (Exception e) {
- logger.info(e);
- }
- }
-
- @Test
- public void testGetProviderComboBox() {
- try {
- stdPAPPolicy.setProviderComboBox("onap");
- assertTrue(stdPAPPolicy.getProviderComboBox() != null);
- } catch (Exception e) {
- logger.info(e);
- }
- }
-
- @Test
- public void testGetRiskLevel() {
- try {
- stdPAPPolicy.setRiskLevel("test");
- assertTrue(stdPAPPolicy.getRiskLevel() != null);
- } catch (Exception e) {
- logger.info(e);
- }
- }
-
- @Test
- public void testGetRiskType() {
- try {
- stdPAPPolicy.setRiskType("test");
- assertTrue(stdPAPPolicy.getRiskType() != null);
- } catch (Exception e) {
- logger.info(e);
- }
-
- }
-
- @Test
- public void testGetRuleID() {
- try {
- stdPAPPolicy.setRuleID("MsLocation");
- assertTrue(stdPAPPolicy.getRuleID() != null);
- } catch (Exception e) {
- logger.info(e);
- }
- }
-
- @Test
- public void testGetServiceType() {
- try {
- stdPAPPolicy.setServiceType("domain");
- assertTrue(stdPAPPolicy.getServiceType() != null);
- } catch (Exception e) {
- logger.info(e);
- }
- }
-
- @Test
- public void testGetTTLDate() {
- try {
- stdPAPPolicy.setTTLDate("09/20/17");
- assertTrue(stdPAPPolicy.getTTLDate() != null);
- } catch (Exception e) {
- logger.info(e);
- }
- }
-
-
- @Test
- public void testGetUuid() {
- try {
- stdPAPPolicy.setUuid("11212122");
- assertTrue(stdPAPPolicy.getUuid() != null);
- } catch (Exception e) {
- logger.info(e);
- }
- }
-
- @Test
- public void testGetVersion() {
- try {
- stdPAPPolicy.setVersion("testv01");
- assertTrue(stdPAPPolicy.getVersion() != null);
- } catch (Exception e) {
- logger.info(e);
- }
-
- }
-
- @Test
- public void testIsEditPolicy() {
- try {
- stdPAPPolicy.setEditPolicy(true);
- assertTrue(stdPAPPolicy.isEditPolicy() == true);
- } catch (Exception e) {
- logger.info(e);
- }
- }
-
- @Test
- public void testToString() {
- try {
- assertTrue(stdPAPPolicy.toString() != null);
- } catch (Exception e) {
- logger.info(e);
- }
+ stdPAPPolicy = new StdPAPPolicy();
+ }
+
+ @Test
+ public void testGetActionAttribute() throws URISyntaxException {
+ stdPAPPolicy.setActionAttribute("test");
+ assertEquals("test", stdPAPPolicy.getActionAttribute());
+ stdPAPPolicy.setActionBody("actionBody");
+ assertNotNull(stdPAPPolicy.getActionBody());
+ stdPAPPolicy.setActionDictHeader("actionDictHeader");
+ assertNotNull(stdPAPPolicy.getActionDictHeader());
+ stdPAPPolicy.setActionDictMethod("actionDictMethod");
+ assertNotNull(stdPAPPolicy.getActionDictMethod());
+ stdPAPPolicy.setActionDictType("actionDictType");
+ assertNotNull(stdPAPPolicy.getActionDictType());
+ stdPAPPolicy.setActionDictUrl("actionDictUrl");
+ assertNotNull(stdPAPPolicy.getActionDictUrl());
+ stdPAPPolicy.setActionPerformer("actionPerformer");
+ assertNotNull(stdPAPPolicy.getActionPerformer());
+ stdPAPPolicy.setBrmsController("brmsController");
+ assertNotNull(stdPAPPolicy.getBrmsController());
+ stdPAPPolicy.setBrmsDependency(new ArrayList<>());
+ assertNotNull(stdPAPPolicy.getBrmsDependency());
+ stdPAPPolicy.setConfigBodyData("configBodyData");
+ assertNotNull(stdPAPPolicy.getConfigBodyData());
+ stdPAPPolicy.setConfigName("configName");
+ assertNotNull(stdPAPPolicy.getConfigName());
+ stdPAPPolicy.setConfigPolicyType("configPolicyType");
+ assertNotNull(stdPAPPolicy.getConfigPolicyType());
+ stdPAPPolicy.setConfigType("configType");
+ assertNotNull(stdPAPPolicy.getConfigType());
+ stdPAPPolicy.setDataTypeList(new ArrayList<String>());
+ assertNotNull(stdPAPPolicy.getDataTypeList());
+ stdPAPPolicy.setDeleteCondition("deleteCondition");
+ assertNotNull(stdPAPPolicy.getDeleteCondition());
+ stdPAPPolicy.setDrlRuleAndUIParams(new HashMap<>());
+ assertNotNull(stdPAPPolicy.getDrlRuleAndUIParams());
+ stdPAPPolicy.setDropDownMap(new HashMap<>());
+ assertNotNull(stdPAPPolicy.getDropDownMap() );
+ Map<String, String> dynamic = new HashMap<>();
+ dynamic.put("foo", "bar");
+ stdPAPPolicy.setDynamicFieldConfigAttributes(dynamic);
+ assertEquals(dynamic, stdPAPPolicy.getDynamicFieldConfigAttributes());
+ stdPAPPolicy.setDynamicRuleAlgorithmCombo(new ArrayList<>());
+ assertNotNull(stdPAPPolicy.getDynamicRuleAlgorithmCombo());
+ stdPAPPolicy.setDynamicRuleAlgorithmField1(new ArrayList<>());
+ assertNotNull(stdPAPPolicy.getDynamicRuleAlgorithmField1());
+ stdPAPPolicy.setDynamicRuleAlgorithmField2(new ArrayList<>());
+ assertNotNull(stdPAPPolicy.getDynamicRuleAlgorithmField2());
+ stdPAPPolicy.setDictionary("dictionary");
+ assertNotNull(stdPAPPolicy.getDictionary());
+ stdPAPPolicy.setDictionaryFields("dictionaryFields");
+ assertNotNull(stdPAPPolicy.getDictionaryFields());
+ stdPAPPolicy.setDictionaryType("dictionaryType");
+ assertNotNull(stdPAPPolicy.getDictionaryType());
+ stdPAPPolicy.setDomainDir("domain");
+ assertNotNull(stdPAPPolicy.getDomainDir());
+ stdPAPPolicy.setDraft(true);
+ assertTrue(stdPAPPolicy.isDraft() == true);
+ stdPAPPolicy.setDynamicRuleAlgorithmLabels(new ArrayList<>());
+ assertNotNull(stdPAPPolicy.getDynamicRuleAlgorithmLabels());
+ stdPAPPolicy.setDynamicSettingsMap(new HashMap<>());
+ assertNotNull(stdPAPPolicy.getDynamicSettingsMap());
+ stdPAPPolicy.setDynamicVariableList(new ArrayList<>());
+ assertNotNull(stdPAPPolicy.getDynamicVariableList());
+ stdPAPPolicy.setGuard("domain");
+ assertNotNull(stdPAPPolicy.getGuard());
+ stdPAPPolicy.setHighestVersion(123);
+ assertNotNull(stdPAPPolicy.getHighestVersion());
+ stdPAPPolicy.setJsonBody("jsonBoby");
+ assertNotNull(stdPAPPolicy.getJsonBody());
+ stdPAPPolicy.setLocation(new URI("test"));
+ assertNotNull(stdPAPPolicy.getLocation());
+ stdPAPPolicy.setMsLocation("MsLocation");
+ assertNotNull(stdPAPPolicy.getMsLocation());
+ stdPAPPolicy.setOldPolicyFileName("domain");
+ assertNotNull(stdPAPPolicy.getOldPolicyFileName());
+ stdPAPPolicy.setOnapName("onap");
+ assertTrue(stdPAPPolicy.getOnapName() != null);
+ stdPAPPolicy.setPolicyDescription("description test");
+ assertNotNull(stdPAPPolicy.getPolicyDescription());
+ stdPAPPolicy.setPolicyID("test");
+ assertNotNull(stdPAPPolicy.getPolicyID());
+ stdPAPPolicy.setPolicyName("MsLocation");
+ assertNotNull(stdPAPPolicy.getPolicyName());
+ stdPAPPolicy.setPriority("domain");
+ assertNotNull(stdPAPPolicy.getPriority());
+ stdPAPPolicy.setProviderComboBox("onap");
+ assertNotNull(stdPAPPolicy.getProviderComboBox());
+ stdPAPPolicy.setRiskLevel("test");
+ assertNotNull(stdPAPPolicy.getRiskLevel());
+ stdPAPPolicy.setRiskType("test");
+ assertNotNull(stdPAPPolicy.getRiskType());
+ stdPAPPolicy.setRuleID("MsLocation");
+ assertNotNull(stdPAPPolicy.getRuleID());
+ stdPAPPolicy.setServiceType("domain");
+ assertNotNull(stdPAPPolicy.getServiceType());
+ stdPAPPolicy.setTTLDate("09/20/17");
+ assertNotNull(stdPAPPolicy.getTTLDate());
+ stdPAPPolicy.setUuid("11212122");
+ assertNotNull(stdPAPPolicy.getUuid());
+ stdPAPPolicy.setVersion("testv01");
+ assertNotNull(stdPAPPolicy.getVersion());
+ stdPAPPolicy.setEditPolicy(true);
+ assertTrue(stdPAPPolicy.isEditPolicy());
+ assertNotNull(stdPAPPolicy.toString());
+ Map<String, String> treatments = new HashMap<>();
+ stdPAPPolicy.setTreatments(treatments);
+ assertEquals(treatments, stdPAPPolicy.getTreatments());
+ stdPAPPolicy.setRawXacmlPolicy("raw");
+ assertEquals("raw", stdPAPPolicy.getRawXacmlPolicy());
}
@Test
public void testConstructorUri() throws URISyntaxException {
URI location = new URI("testUri");
- StdPAPPolicy stdPAPPolicy = new StdPAPPolicy(location);
- assertEquals(location, stdPAPPolicy.getLocation());
+ StdPAPPolicy stdPapPolicy = new StdPAPPolicy(location);
+ assertEquals(location, stdPapPolicy.getLocation());
}
@Test
public void testConstructorStringStringStringString() throws URISyntaxException {
- StdPAPPolicy stdPAPPolicy = new StdPAPPolicy("policyName", "body", "configType", "configTypePolicy");
- assertEquals("policyName", stdPAPPolicy.getPolicyName());
- assertEquals("body", stdPAPPolicy.getConfigBodyData());
- assertEquals("configType", stdPAPPolicy.getConfigType());
- assertEquals("configTypePolicy", stdPAPPolicy.getConfigPolicyType());
+ StdPAPPolicy stdPapPolicy = new StdPAPPolicy("policyName", "body", "configType", "configTypePolicy");
+ assertEquals("policyName", stdPapPolicy.getPolicyName());
+ assertEquals("body", stdPapPolicy.getConfigBodyData());
+ assertEquals("configType", stdPapPolicy.getConfigType());
+ assertEquals("configTypePolicy", stdPapPolicy.getConfigPolicyType());
}
-
@Test
public void testConstructorStringStringStringStringStringMapStringStringStringStringBooleanStringStringStringStringString()
throws URISyntaxException {
Map<String, String> attributes = new HashMap<>();
attributes.put("aKey", "aValue");
- StdPAPPolicy stdPAPPolicy = new StdPAPPolicy(
- StdPAPPolicyParams.builder()
- .configPolicyType("configTypePolicy")
- .policyName("policyName")
- .description("description")
- .onapName("onapName")
- .configName("configName")
- .dynamicFieldConfigAttributes(attributes)
- .configType("configType")
- .configBodyData("body")
- .editPolicy(true)
- .domain("domain")
- .highestVersion(1)
- .riskLevel("riskLevel")
- .riskType("riskType")
- .guard("guard")
- .ttlDate("ttlDate").build());
+ StdPAPPolicy stdPAPPolicy = new StdPAPPolicy(StdPAPPolicyParams.builder().configPolicyType("configTypePolicy")
+ .policyName("policyName").description("description").onapName("onapName").configName("configName")
+ .dynamicFieldConfigAttributes(attributes).configType("configType").configBodyData("body")
+ .editPolicy(true).domain("domain").highestVersion(1).riskLevel("riskLevel").riskType("riskType")
+ .guard("guard").ttlDate("ttlDate").build());
assertEquals("configTypePolicy", stdPAPPolicy.getConfigPolicyType());
assertEquals("policyName", stdPAPPolicy.getPolicyName());
assertEquals("description", stdPAPPolicy.getPolicyDescription());
@@ -625,18 +216,13 @@ public class StdPAPPolicyTest {
dynamicRuleAlgorithmField1.add("dynamicRuleAlgorithmField1");
List<String> dynamicRuleAlgorithmField2 = new ArrayList<>();
dynamicRuleAlgorithmField2.add("dynamicRuleAlgorithmField2");
- StdPAPPolicy stdPAPPolicy = new StdPAPPolicy(StdPAPPolicyParams.builder().policyName("policyName").description("description")
- .dynamicFieldConfigAttributes(attributes)
+ StdPAPPolicy stdPAPPolicy = new StdPAPPolicy(StdPAPPolicyParams.builder().policyName("policyName")
+ .description("description").dynamicFieldConfigAttributes(attributes)
.dynamicRuleAlgorithmLabels(dynamicRuleAlgorithmLabels)
.dynamicRuleAlgorithmCombo(dynamicRuleAlgorithmCombo)
.dynamicRuleAlgorithmField1(dynamicRuleAlgorithmField1)
- .dynamicRuleAlgorithmField2(dynamicRuleAlgorithmField2)
- .actionPerformer("actionPerformer")
- .actionAttribute("actionAttribute")
- .editPolicy(true)
- .domain("domain")
- .highestVersion(1)
- .build());
+ .dynamicRuleAlgorithmField2(dynamicRuleAlgorithmField2).actionPerformer("actionPerformer")
+ .actionAttribute("actionAttribute").editPolicy(true).domain("domain").highestVersion(1).build());
assertEquals("policyName", stdPAPPolicy.getPolicyName());
assertEquals("description", stdPAPPolicy.getPolicyDescription());
assertEquals(attributes, stdPAPPolicy.getDynamicFieldConfigAttributes());
@@ -673,25 +259,15 @@ public class StdPAPPolicyTest {
dynamicVariableList.add("dynamicVariableList");
List<String> dataTypeList = new ArrayList<>();
dataTypeList.add("dataTypeList");
- StdPAPPolicy stdPAPPolicy = new StdPAPPolicy(StdPAPPolicyParams.builder()
- .policyName("policyName")
- .description("description")
- .onapName("onapName")
- .providerComboBox("providerComboBox")
- .dynamicFieldConfigAttributes(attributes)
- .dynamicSettingsMap(settings)
- .treatments(treatments)
+ StdPAPPolicy stdPAPPolicy = new StdPAPPolicy(StdPAPPolicyParams.builder().policyName("policyName")
+ .description("description").onapName("onapName").providerComboBox("providerComboBox")
+ .dynamicFieldConfigAttributes(attributes).dynamicSettingsMap(settings).treatments(treatments)
.dynamicRuleAlgorithmLabels(dynamicRuleAlgorithmLabels)
.dynamicRuleAlgorithmCombo(dynamicRuleAlgorithmCombo)
.dynamicRuleAlgorithmField1(dynamicRuleAlgorithmField1)
- .dynamicRuleAlgorithmField2(dynamicRuleAlgorithmField2)
- .dropDownMap(dropDownMap)
- .dynamicVariableList(dynamicVariableList)
- .dataTypeList(dataTypeList)
- .editPolicy(true)
- .domain("domain")
- .highestVersion(1)
- .build());
+ .dynamicRuleAlgorithmField2(dynamicRuleAlgorithmField2).dropDownMap(dropDownMap)
+ .dynamicVariableList(dynamicVariableList).dataTypeList(dataTypeList).editPolicy(true).domain("domain")
+ .highestVersion(1).build());
assertEquals("policyName", stdPAPPolicy.getPolicyName());
assertEquals("description", stdPAPPolicy.getPolicyDescription());
assertEquals("onapName", stdPAPPolicy.getOnapName());
@@ -716,26 +292,11 @@ public class StdPAPPolicyTest {
throws URISyntaxException {
Map<String, String> attributes = new HashMap<>();
attributes.put("aKey", "aValue");
- StdPAPPolicy stdPAPPolicy = new StdPAPPolicy(StdPAPPolicyParams.builder()
- .configPolicyType("configTypePolicy")
- .policyName("policyName")
- .description("description")
- .onapName("onapName")
- .configName("configName")
- .dynamicFieldConfigAttributes(attributes)
- .configBodyData("body")
- .policyID("policyId")
- .ruleID("ruleId")
- .configType("configType")
- .editPolicy(true)
- .version("version")
- .domain("domain")
- .highestVersion(1)
- .riskLevel("riskLevel")
- .riskType("riskType")
- .guard("guard")
- .ttlDate("ttlDate")
- .build());
+ StdPAPPolicy stdPAPPolicy = new StdPAPPolicy(StdPAPPolicyParams.builder().configPolicyType("configTypePolicy")
+ .policyName("policyName").description("description").onapName("onapName").configName("configName")
+ .dynamicFieldConfigAttributes(attributes).configBodyData("body").policyID("policyId").ruleID("ruleId")
+ .configType("configType").editPolicy(true).version("version").domain("domain").highestVersion(1)
+ .riskLevel("riskLevel").riskType("riskType").guard("guard").ttlDate("ttlDate").build());
assertEquals("configTypePolicy", stdPAPPolicy.getConfigPolicyType());
assertEquals("policyName", stdPAPPolicy.getPolicyName());
assertEquals("description", stdPAPPolicy.getPolicyDescription());
@@ -759,20 +320,10 @@ public class StdPAPPolicyTest {
@Test
public void testConstructorStringStringStringStringBooleanStringStringIntegerStringStringStringString()
throws URISyntaxException {
- StdPAPPolicy stdPAPPolicy = new StdPAPPolicy(StdPAPPolicyParams.builder()
- .configPolicyType("configTypePolicy")
- .policyName("policyName")
- .description("description")
- .configName("configName")
- .editPolicy(true)
- .domain("domain")
- .jsonBody("jasonBody")
- .highestVersion(1)
- .riskLevel("riskLevel")
- .riskType("riskType")
- .guard("guard")
- .ttlDate("ttlDate")
- .build());
+ StdPAPPolicy stdPAPPolicy = new StdPAPPolicy(StdPAPPolicyParams.builder().configPolicyType("configTypePolicy")
+ .policyName("policyName").description("description").configName("configName").editPolicy(true)
+ .domain("domain").jsonBody("jasonBody").highestVersion(1).riskLevel("riskLevel").riskType("riskType")
+ .guard("guard").ttlDate("ttlDate").build());
assertEquals("configTypePolicy", stdPAPPolicy.getConfigPolicyType());
assertEquals("policyName", stdPAPPolicy.getPolicyName());
assertEquals("description", stdPAPPolicy.getPolicyDescription());
@@ -790,21 +341,10 @@ public class StdPAPPolicyTest {
@Test
public void testConstructorStringStringStringStringBooleanStringStringIntegerStringStringStringStringString()
throws URISyntaxException {
- StdPAPPolicy stdPAPPolicy = new StdPAPPolicy(StdPAPPolicyParams.builder()
- .configPolicyType("configTypePolicy")
- .policyName("policyName")
- .description("description")
- .configName("configName")
- .editPolicy(true)
- .domain("domain")
- .jsonBody("jasonBody")
- .highestVersion(1)
- .onapName("eCompName")
- .riskLevel("riskLevel")
- .riskType("riskType")
- .guard("guard")
- .ttlDate("ttlDate")
- .build());
+ StdPAPPolicy stdPAPPolicy = new StdPAPPolicy(StdPAPPolicyParams.builder().configPolicyType("configTypePolicy")
+ .policyName("policyName").description("description").configName("configName").editPolicy(true)
+ .domain("domain").jsonBody("jasonBody").highestVersion(1).onapName("eCompName").riskLevel("riskLevel")
+ .riskType("riskType").guard("guard").ttlDate("ttlDate").build());
assertEquals("configTypePolicy", stdPAPPolicy.getConfigPolicyType());
assertEquals("policyName", stdPAPPolicy.getPolicyName());
assertEquals("description", stdPAPPolicy.getPolicyDescription());
@@ -827,23 +367,11 @@ public class StdPAPPolicyTest {
dyanamicFieldConfigAttributes.put("aKey", "aValue");
ArrayList<String> brmsDependency = new ArrayList<>();
brmsDependency.add("brmsDependency");
- StdPAPPolicy stdPAPPolicy = new StdPAPPolicy(StdPAPPolicyParams.builder()
- .configPolicyType("configTypePolicy")
- .policyName("policyName")
- .description("description")
- .configName("configName")
- .editPolicy(true)
- .domain("domain")
- .dynamicFieldConfigAttributes(dyanamicFieldConfigAttributes)
- .highestVersion(1)
- .onapName("eCompName")
- .configBodyData("configBodyData")
- .riskLevel("riskLevel")
- .riskType("riskType")
- .guard("guard")
- .ttlDate("ttlDate")
- .brmsController("brmsController")
- .brmsDependency(brmsDependency)
+ StdPAPPolicy stdPAPPolicy = new StdPAPPolicy(StdPAPPolicyParams.builder().configPolicyType("configTypePolicy")
+ .policyName("policyName").description("description").configName("configName").editPolicy(true)
+ .domain("domain").dynamicFieldConfigAttributes(dyanamicFieldConfigAttributes).highestVersion(1)
+ .onapName("eCompName").configBodyData("configBodyData").riskLevel("riskLevel").riskType("riskType")
+ .guard("guard").ttlDate("ttlDate").brmsController("brmsController").brmsDependency(brmsDependency)
.build());
assertEquals("configTypePolicy", stdPAPPolicy.getConfigPolicyType());
assertEquals("policyName", stdPAPPolicy.getPolicyName());
@@ -872,26 +400,13 @@ public class StdPAPPolicyTest {
drlRuleAndUIParams.put("aDrlRuleKey", "aDrlRuleValue");
ArrayList<String> brmsDependency = new ArrayList<>();
brmsDependency.add("brmsDependency");
- //Creating BRMS Param Policies from the Admin Console
- StdPAPPolicy stdPAPPolicy = new StdPAPPolicy(StdPAPPolicyParams.builder()
- .configPolicyType("configTypePolicy")
- .policyName("policyName")
- .description("description")
- .configName("configName")
- .editPolicy(true)
- .domain("domain")
- .dynamicFieldConfigAttributes(dyanamicFieldConfigAttributes)
- .highestVersion(1)
- .onapName("eCompName")
- .configBodyData("configBodyData")
- .drlRuleAndUIParams(drlRuleAndUIParams)
- .riskLevel("riskLevel")
- .riskType("riskType")
- .guard("guard")
- .ttlDate("ttlDate")
- .brmsController("brmsController")
- .brmsDependency(brmsDependency)
- .build());
+ // Creating BRMS Param Policies from the Admin Console
+ StdPAPPolicy stdPAPPolicy = new StdPAPPolicy(StdPAPPolicyParams.builder().configPolicyType("configTypePolicy")
+ .policyName("policyName").description("description").configName("configName").editPolicy(true)
+ .domain("domain").dynamicFieldConfigAttributes(dyanamicFieldConfigAttributes).highestVersion(1)
+ .onapName("eCompName").configBodyData("configBodyData").drlRuleAndUIParams(drlRuleAndUIParams)
+ .riskLevel("riskLevel").riskType("riskType").guard("guard").ttlDate("ttlDate")
+ .brmsController("brmsController").brmsDependency(brmsDependency).build());
assertEquals("configTypePolicy", stdPAPPolicy.getConfigPolicyType());
assertEquals("policyName", stdPAPPolicy.getPolicyName());
assertEquals("description", stdPAPPolicy.getPolicyDescription());
@@ -914,24 +429,12 @@ public class StdPAPPolicyTest {
@Test
public void testConstructorStringStringStringStringStringBooleanStringStringBooleanStringIntegerStringStringStringString()
throws URISyntaxException {
- //Creating CloseLoop_Fault and Performance Metric Policies
- StdPAPPolicy stdPAPPolicy = new StdPAPPolicy(StdPAPPolicyParams.builder()
- .configPolicyType("configTypePolicy")
- .policyName("policyName")
- .description("description")
- .onapName("onapName")
- .jsonBody("jasonBody")
- .draft(true)
- .oldPolicyFileName("oldPolicyFileName")
- .serviceType("serviceType")
- .editPolicy(true)
- .domain("domain")
- .highestVersion(1)
- .riskLevel("riskLevel")
- .riskType("riskType")
- .guard("guard")
- .ttlDate("ttlDate")
- .build());
+ // Creating CloseLoop_Fault and Performance Metric Policies
+ StdPAPPolicy stdPAPPolicy = new StdPAPPolicy(StdPAPPolicyParams.builder().configPolicyType("configTypePolicy")
+ .policyName("policyName").description("description").onapName("onapName").jsonBody("jasonBody")
+ .draft(true).oldPolicyFileName("oldPolicyFileName").serviceType("serviceType").editPolicy(true)
+ .domain("domain").highestVersion(1).riskLevel("riskLevel").riskType("riskType").guard("guard")
+ .ttlDate("ttlDate").build());
assertEquals("configTypePolicy", stdPAPPolicy.getConfigPolicyType());
assertEquals("policyName", stdPAPPolicy.getPolicyName());
assertEquals("description", stdPAPPolicy.getPolicyDescription());
@@ -952,23 +455,11 @@ public class StdPAPPolicyTest {
@Test
public void testConstructorStringStringStringStringBooleanStringStringStringStringStringIntegerStringStringStringString()
throws URISyntaxException {
- //test for Updating Config Firewall Policies from the Admin Console
- StdPAPPolicy stdPAPPolicy = new StdPAPPolicy(StdPAPPolicyParams.builder()
- .configPolicyType("configTypePolicy")
- .policyName("policyName")
- .description("description")
- .configName("configName")
- .editPolicy(true)
- .domain("domain")
- .policyID("policyId")
- .ruleID("ruleId")
- .version("version")
- .jsonBody("jasonBody")
- .highestVersion(1)
- .riskLevel("riskLevel")
- .riskType("riskType")
- .guard("guard")
- .ttlDate("ttlDate")
+ // test for Updating Config Firewall Policies from the Admin Console
+ StdPAPPolicy stdPAPPolicy = new StdPAPPolicy(StdPAPPolicyParams.builder().configPolicyType("configTypePolicy")
+ .policyName("policyName").description("description").configName("configName").editPolicy(true)
+ .domain("domain").policyID("policyId").ruleID("ruleId").version("version").jsonBody("jasonBody")
+ .highestVersion(1).riskLevel("riskLevel").riskType("riskType").guard("guard").ttlDate("ttlDate")
.build());
assertEquals("configTypePolicy", stdPAPPolicy.getConfigPolicyType());
assertEquals("policyName", stdPAPPolicy.getPolicyName());
@@ -990,27 +481,12 @@ public class StdPAPPolicyTest {
@Test
public void testConstructorStringStringStringStringStringStringStringStringStringStringStringBooleanStringintStringStringStringString()
throws URISyntaxException {
- //for Micro Service Creating/Updating Policies from the Admin Console
- StdPAPPolicy stdPAPPolicy = new StdPAPPolicy(StdPAPPolicyParams.builder()
- .configPolicyType("configTypePolicy")
- .policyName("policyName")
- .description("description")
- .onapName("onapName")
- .configName("configName")
- .serviceType("serviceType")
- .uuid("uuid")
- .msLocation("msLocation")
- .jsonBody("jasonBody")
- .priority("priority")
- .version("version")
- .editPolicy(true)
- .domain("domain")
- .highestVersion(1)
- .riskLevel("riskLevel")
- .riskType("riskType")
- .guard("guard")
- .ttlDate("ttlDate")
- .build());
+ // for Micro Service Creating/Updating Policies from the Admin Console
+ StdPAPPolicy stdPAPPolicy = new StdPAPPolicy(StdPAPPolicyParams.builder().configPolicyType("configTypePolicy")
+ .policyName("policyName").description("description").onapName("onapName").configName("configName")
+ .serviceType("serviceType").uuid("uuid").msLocation("msLocation").jsonBody("jasonBody")
+ .priority("priority").version("version").editPolicy(true).domain("domain").highestVersion(1)
+ .riskLevel("riskLevel").riskType("riskType").guard("guard").ttlDate("ttlDate").build());
assertEquals("configTypePolicy", stdPAPPolicy.getConfigPolicyType());
assertEquals("policyName", stdPAPPolicy.getPolicyName());
assertEquals("description", stdPAPPolicy.getPolicyDescription());
@@ -1034,25 +510,12 @@ public class StdPAPPolicyTest {
@Test
public void testConstructorStringStringStringStringBooleanStringStringStringStringStringIntegerStringStringStringStringString()
throws URISyntaxException {
- //test for Updating Goc Policies from the Admin Console
- StdPAPPolicy stdPAPPolicy = new StdPAPPolicy(StdPAPPolicyParams.builder()
- .configPolicyType("configTypePolicy")
- .policyName("policyName")
- .description("description")
- .configName("configName")
- .editPolicy(true)
- .domain("domain")
- .policyID("policyId")
- .ruleID("ruleId")
- .version("version")
- .jsonBody("jasonBody")
- .highestVersion(1)
- .onapName("ecompName")
- .riskLevel("riskLevel")
- .riskType("riskType")
- .guard("guard")
- .ttlDate("ttlDate")
- .build());
+ // test for Updating Goc Policies from the Admin Console
+ StdPAPPolicy stdPAPPolicy = new StdPAPPolicy(StdPAPPolicyParams.builder().configPolicyType("configTypePolicy")
+ .policyName("policyName").description("description").configName("configName").editPolicy(true)
+ .domain("domain").policyID("policyId").ruleID("ruleId").version("version").jsonBody("jasonBody")
+ .highestVersion(1).onapName("ecompName").riskLevel("riskLevel").riskType("riskType").guard("guard")
+ .ttlDate("ttlDate").build());
assertEquals("configTypePolicy", stdPAPPolicy.getConfigPolicyType());
assertEquals("policyName", stdPAPPolicy.getPolicyName());
assertEquals("description", stdPAPPolicy.getPolicyDescription());
@@ -1074,28 +537,15 @@ public class StdPAPPolicyTest {
@Test
public void testConstructorStringStringStringStringBooleanStringStringStringStringMapStringStringIntegerStringStringStringStringString()
throws URISyntaxException {
- //for Updating Brms Policies from the Admin Console
+ // for Updating Brms Policies from the Admin Console
Map<String, String> dyanamicFieldConfigAttributes = new HashMap<>();
dyanamicFieldConfigAttributes.put("aKey", "aValue");
- StdPAPPolicy stdPAPPolicy = new StdPAPPolicy(StdPAPPolicyParams.builder()
- .configPolicyType("configTypePolicy")
- .policyName("policyName")
- .description("description")
- .configName("configName")
- .editPolicy(true)
- .domain("domain")
- .policyID("policyId")
- .ruleID("ruleId")
- .version("version")
- .dynamicFieldConfigAttributes(dyanamicFieldConfigAttributes)
- .highestVersion(1)
- .onapName("eCompName")
- .configBodyData("configBodyData")
- .riskLevel("riskLevel")
- .riskType("riskType")
- .guard("guard")
- .ttlDate("ttlDate")
- .build());
+ StdPAPPolicy stdPAPPolicy = new StdPAPPolicy(StdPAPPolicyParams.builder().configPolicyType("configTypePolicy")
+ .policyName("policyName").description("description").configName("configName").editPolicy(true)
+ .domain("domain").policyID("policyId").ruleID("ruleId").version("version")
+ .dynamicFieldConfigAttributes(dyanamicFieldConfigAttributes).highestVersion(1).onapName("eCompName")
+ .configBodyData("configBodyData").riskLevel("riskLevel").riskType("riskType").guard("guard")
+ .ttlDate("ttlDate").build());
assertEquals("configTypePolicy", stdPAPPolicy.getConfigPolicyType());
assertEquals("policyName", stdPAPPolicy.getPolicyName());
assertEquals("description", stdPAPPolicy.getPolicyDescription());
@@ -1118,30 +568,17 @@ public class StdPAPPolicyTest {
@Test
public void testConstructorStringStringStringStringBooleanStringStringStringStringMapStringStringIntegerStringMapStringStringStringStringStringString()
throws URISyntaxException {
- //for Updating Brms Param Policies from the Admin Console
- Map<String, String> dyanamicFieldConfigAttributes = new HashMap<>();
- dyanamicFieldConfigAttributes.put("aKey", "aValue");
+ // for Updating Brms Param Policies from the Admin Console
Map<String, String> drlRuleAndUIParams = new HashMap<>();
drlRuleAndUIParams.put("aDrlRuleKey", "aDrlRuleValue");
- StdPAPPolicy stdPAPPolicy = new StdPAPPolicy(StdPAPPolicyParams.builder()
- .configPolicyType("configTypePolicy")
- .policyName("policyName")
- .description("description")
- .configName("configName")
- .editPolicy(true)
- .domain("domain")
- .policyID("policyId")
- .ruleID("ruleId")
- .version("version")
- .dynamicFieldConfigAttributes(dyanamicFieldConfigAttributes)
- .highestVersion(1)
- .onapName("eCompName")
- .drlRuleAndUIParams(drlRuleAndUIParams)
- .riskLevel("riskLevel")
- .riskType("riskType")
- .guard("guard")
- .ttlDate("ttlDate")
- .build());
+ Map<String, String> dynamicFieldConfigAttributes = new HashMap<>();
+ dynamicFieldConfigAttributes.put("foo", "bar");
+ StdPAPPolicy stdPAPPolicy = new StdPAPPolicy(StdPAPPolicyParams.builder().configPolicyType("configTypePolicy")
+ .policyName("policyName").description("description").configName("configName").editPolicy(true)
+ .domain("domain").policyID("policyId").ruleID("ruleId").version("version")
+ .dynamicFieldConfigAttributes(dynamicFieldConfigAttributes).highestVersion(1).onapName("eCompName")
+ .drlRuleAndUIParams(drlRuleAndUIParams).riskLevel("riskLevel").riskType("riskType").guard("guard")
+ .priority("high").ttlDate("ttlDate").build());
assertEquals("configTypePolicy", stdPAPPolicy.getConfigPolicyType());
assertEquals("policyName", stdPAPPolicy.getPolicyName());
assertEquals("description", stdPAPPolicy.getPolicyDescription());
@@ -1151,23 +588,22 @@ public class StdPAPPolicyTest {
assertEquals("policyId", stdPAPPolicy.getPolicyID());
assertEquals("ruleId", stdPAPPolicy.getRuleID());
assertEquals("version", stdPAPPolicy.getVersion());
- assertEquals(dyanamicFieldConfigAttributes, stdPAPPolicy.getDynamicFieldConfigAttributes());
+ assertEquals(dynamicFieldConfigAttributes, stdPAPPolicy.getDynamicFieldConfigAttributes());
assertEquals(Integer.valueOf(1), stdPAPPolicy.getHighestVersion());
assertEquals("eCompName", stdPAPPolicy.getOnapName());
assertEquals(drlRuleAndUIParams, stdPAPPolicy.getDrlRuleAndUIParams());
assertEquals("riskLevel", stdPAPPolicy.getRiskLevel());
assertEquals("riskType", stdPAPPolicy.getRiskType());
assertEquals("guard", stdPAPPolicy.getGuard());
+ assertEquals("high", stdPAPPolicy.getPriority());
assertEquals("ttlDate", stdPAPPolicy.getTTLDate());
}
@Test
public void testConstructorStringString() {
// for deleting policies from the API
- StdPAPPolicy stdPAPPolicy = new StdPAPPolicy(StdPAPPolicyParams.builder()
- .policyName("policyName")
- .deleteCondition("deleteCondition")
- .build());
+ StdPAPPolicy stdPAPPolicy = new StdPAPPolicy(
+ StdPAPPolicyParams.builder().policyName("policyName").deleteCondition("deleteCondition").build());
assertEquals("policyName", stdPAPPolicy.getPolicyName());
assertEquals("deleteCondition", stdPAPPolicy.getDeleteCondition());
}
@@ -1175,12 +611,8 @@ public class StdPAPPolicyTest {
@Test
public void testConstructorStringStringString() {
// for creating dictionary items from the API>
- StdPAPPolicy stdPAPPolicy = new StdPAPPolicy(
- StdPAPPolicyParams.builder()
- .dictionaryType("dictionaryType")
- .dictionary("dictionary")
- .dictionaryFields("dictionaryFields")
- .build());
+ StdPAPPolicy stdPAPPolicy = new StdPAPPolicy(StdPAPPolicyParams.builder().dictionaryType("dictionaryType")
+ .dictionary("dictionary").dictionaryFields("dictionaryFields").build());
assertEquals("dictionaryType", stdPAPPolicy.getDictionaryType());
assertEquals("dictionary", stdPAPPolicy.getDictionary());
assertEquals("dictionaryFields", stdPAPPolicy.getDictionaryFields());
diff --git a/ONAP-XACML/src/test/java/org/onap/policy/xacml/test/std/pap/StdPDPGroupStatusTest.java b/ONAP-XACML/src/test/java/org/onap/policy/xacml/test/std/pap/StdPDPGroupStatusTest.java
index 55413d83b..5dcebcd89 100644
--- a/ONAP-XACML/src/test/java/org/onap/policy/xacml/test/std/pap/StdPDPGroupStatusTest.java
+++ b/ONAP-XACML/src/test/java/org/onap/policy/xacml/test/std/pap/StdPDPGroupStatusTest.java
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP-XACML
* ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017, 2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Modifications Copyright (C) 2019 Samsung
* ================================================================================
@@ -19,13 +19,22 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.policy.xacml.test.std.pap;
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 com.att.research.xacml.api.pap.PDP;
+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 java.util.HashSet;
import java.util.Set;
+
import org.junit.Before;
import org.junit.Test;
import org.onap.policy.common.logging.flexlogger.FlexLogger;
@@ -34,10 +43,6 @@ import org.onap.policy.xacml.std.pap.StdPDP;
import org.onap.policy.xacml.std.pap.StdPDPGroupStatus;
import org.onap.policy.xacml.std.pap.StdPDPPIPConfig;
import org.onap.policy.xacml.std.pap.StdPDPPolicy;
-import com.att.research.xacml.api.pap.PDP;
-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;
public class StdPDPGroupStatusTest {
@@ -45,6 +50,9 @@ public class StdPDPGroupStatusTest {
private StdPDPGroupStatus stdPDPGroupStatus;
+ /**
+ * setUp.
+ */
@Before
public void setUp() {
@@ -96,7 +104,9 @@ public class StdPDPGroupStatusTest {
public void testGetLoadWarnings() {
try {
stdPDPGroupStatus.setLoadWarnings(new HashSet<>());
- assertTrue(stdPDPGroupStatus.getLoadWarnings() != null);
+ assertNotNull(stdPDPGroupStatus.getLoadWarnings());
+ stdPDPGroupStatus.addLoadWarning("warn");
+ assertEquals(1, stdPDPGroupStatus.getLoadWarnings().size());
} catch (Exception e) {
logger.error(e);
}
@@ -322,7 +332,6 @@ public class StdPDPGroupStatusTest {
Set<PDP> updatingPDPs = new HashSet<>();
updatingPDPs.add(new StdPDP());
-
stdPDPGroupStatus.setStatus(status);
stdPDPGroupStatus.setFailedPDPs(failedPDPs);
stdPDPGroupStatus.setFailedPIPConfigs(failedPIPConfigs);
diff --git a/ONAP-XACML/src/test/java/org/onap/policy/xacml/test/std/pap/StdPDPGroupTest.java b/ONAP-XACML/src/test/java/org/onap/policy/xacml/test/std/pap/StdPDPGroupTest.java
index e5e058a5c..3391b2097 100644
--- a/ONAP-XACML/src/test/java/org/onap/policy/xacml/test/std/pap/StdPDPGroupTest.java
+++ b/ONAP-XACML/src/test/java/org/onap/policy/xacml/test/std/pap/StdPDPGroupTest.java
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP-XACML
* ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017, 2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Modifications Copyright (C) 2019 Samsung
* ================================================================================
@@ -19,13 +19,16 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.policy.xacml.test.std.pap;
import static org.junit.Assert.assertTrue;
+
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashSet;
import java.util.Set;
+
import org.junit.Before;
import org.junit.Test;
import org.onap.policy.common.logging.flexlogger.FlexLogger;
@@ -35,7 +38,6 @@ import org.onap.policy.xacml.std.pap.StdPDPGroup;
public class StdPDPGroupTest {
-
private static Logger logger = FlexLogger.getLogger(StdPDPGroupTest.class);
private StdPDPGroup stdPDPGroup;
diff --git a/ONAP-XACML/src/test/java/org/onap/policy/xacml/test/std/pap/StdPDPPIPConfigTest.java b/ONAP-XACML/src/test/java/org/onap/policy/xacml/test/std/pap/StdPDPPIPConfigTest.java
index b5713d362..746aace3d 100644
--- a/ONAP-XACML/src/test/java/org/onap/policy/xacml/test/std/pap/StdPDPPIPConfigTest.java
+++ b/ONAP-XACML/src/test/java/org/onap/policy/xacml/test/std/pap/StdPDPPIPConfigTest.java
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP-XACML
* ================================================================================
- * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Modifications Copyright (C) 2019 Samsung
* ================================================================================
@@ -22,14 +22,17 @@
package org.onap.policy.xacml.test.std.pap;
+import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.not;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertThat;
+
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
+
import org.junit.Test;
import org.onap.policy.xacml.std.pap.StdPDPPIPConfig;
@@ -41,6 +44,8 @@ public class StdPDPPIPConfigTest {
String value = "testVal";
Properties props = new Properties();
props.setProperty(id + ".classname", value);
+ props.setProperty(id + ".dontcare", "blah");
+ props.setProperty("foo", "bar");
Map<String, String> map = new HashMap<String, String>();
map.put(id, value);
@@ -106,4 +111,13 @@ public class StdPDPPIPConfigTest {
// Test toString
assertThat(config.toString().length(), is(not(0)));
}
+
+ @Test
+ public void testBadProperties() {
+ Properties props = new Properties();
+ props.setProperty("foo", "bar");
+ assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(() -> {
+ new StdPDPPIPConfig("myid", props);
+ });
+ }
}
diff --git a/ONAP-XACML/src/test/java/org/onap/policy/xacml/test/std/pap/StdPDPPolicyTest.java b/ONAP-XACML/src/test/java/org/onap/policy/xacml/test/std/pap/StdPDPPolicyTest.java
index 7aaa381ce..98dc4d61c 100644
--- a/ONAP-XACML/src/test/java/org/onap/policy/xacml/test/std/pap/StdPDPPolicyTest.java
+++ b/ONAP-XACML/src/test/java/org/onap/policy/xacml/test/std/pap/StdPDPPolicyTest.java
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP-XACML
* ================================================================================
- * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2018-2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Modifications Copyright (C) 2019 Samsung
* ================================================================================
@@ -27,14 +27,17 @@ import static org.hamcrest.CoreMatchers.not;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertThat;
+
+import com.att.research.xacml.api.pap.PAPException;
+
import java.io.IOException;
import java.net.ConnectException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Properties;
+
import org.junit.Test;
import org.onap.policy.xacml.std.pap.StdPDPPolicy;
-import com.att.research.xacml.api.pap.PAPException;
import org.onap.policy.xacml.std.pap.StdPDPPolicyParams;
public class StdPDPPolicyTest {
@@ -53,9 +56,8 @@ public class StdPDPPolicyTest {
StdPDPPolicy policy4 = new StdPDPPolicy();
assertNotNull(policy4);
- StdPDPPolicy policy5 = new StdPDPPolicy(
- StdPDPPolicyParams.builder().id(value).isRoot(true).name(value).location(uri)
- .isValid(false).policyId(value).description(value).version("1").build());
+ StdPDPPolicy policy5 = new StdPDPPolicy(StdPDPPolicyParams.builder().id(value).isRoot(true).name(value)
+ .location(uri).isValid(false).policyId(value).description(value).version("1").build());
assertNotNull(policy5);
StdPDPPolicy policy6 = new StdPDPPolicy(value, true, value, uri, false);
assertNotNull(policy6);
@@ -117,9 +119,8 @@ public class StdPDPPolicyTest {
// Set up test data
String value = "testVal";
URI uri = new URI("http://localhost:54287");
- StdPDPPolicy policy = new StdPDPPolicy(
- StdPDPPolicyParams.builder().id(value).isRoot(true).name(value).location(uri)
- .isValid(false).policyId(value).description(value).version("1").build());
+ StdPDPPolicy policy = new StdPDPPolicy(StdPDPPolicyParams.builder().id(value).isRoot(true).name(value)
+ .location(uri).isValid(false).policyId(value).description(value).version("1").build());
// Negative test stream
policy.getStream();
diff --git a/ONAP-XACML/src/test/java/org/onap/policy/xacml/test/std/pap/StdPDPStatusTest.java b/ONAP-XACML/src/test/java/org/onap/policy/xacml/test/std/pap/StdPDPStatusTest.java
index dfdbf5f16..7d3ce5e19 100644
--- a/ONAP-XACML/src/test/java/org/onap/policy/xacml/test/std/pap/StdPDPStatusTest.java
+++ b/ONAP-XACML/src/test/java/org/onap/policy/xacml/test/std/pap/StdPDPStatusTest.java
@@ -1,8 +1,8 @@
/*-
* ============LICENSE_START=======================================================
* Copyright (C) 2018 Ericsson. All rights reserved.
- * ================================================================================
* Modifications Copyright (C) 2019 Samsung
+ * Modifications Copyright (C) 2019 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.
@@ -17,18 +17,24 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.policy.xacml.test.std.pap;
-import static org.junit.Assert.*;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+
+import com.att.research.xacml.api.pap.PDPPIPConfig;
+import com.att.research.xacml.api.pap.PDPPolicy;
+import com.att.research.xacml.api.pap.PDPStatus.Status;
+
import java.util.HashSet;
import java.util.Set;
+
import org.junit.Test;
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.api.pap.PDPPIPConfig;
-import com.att.research.xacml.api.pap.PDPPolicy;
-import com.att.research.xacml.api.pap.PDPStatus.Status;
public class StdPDPStatusTest {
@@ -179,13 +185,13 @@ public class StdPDPStatusTest {
@Test
public void testSet() {
- Status status = Status.UP_TO_DATE;
- Set<PDPPIPConfig> failedPIPConfigs = new HashSet<>();
- failedPIPConfigs.add(new StdPDPPIPConfig());
+ final Status status = Status.UP_TO_DATE;
+ Set<PDPPIPConfig> failedPipConfigs = new HashSet<>();
+ failedPipConfigs.add(new StdPDPPIPConfig());
Set<PDPPolicy> failedPolicies = new HashSet<>();
failedPolicies.add(new StdPDPPolicy());
- Set<PDPPIPConfig> loadedPIPConfigs = new HashSet<>();
- loadedPIPConfigs.add(new StdPDPPIPConfig());
+ Set<PDPPIPConfig> loadedPipConfigs = new HashSet<>();
+ loadedPipConfigs.add(new StdPDPPIPConfig());
Set<PDPPolicy> loadedPolicies = new HashSet<>();
loadedPolicies.add(new StdPDPPolicy());
Set<PDPPolicy> loadedRootPolicies = new HashSet<>();
@@ -196,48 +202,38 @@ public class StdPDPStatusTest {
loadWarnings.add("An error");
stdPDPStatus.setStatus(status);
- stdPDPStatus.setFailedPipConfigs(failedPIPConfigs);
+ stdPDPStatus.setFailedPipConfigs(failedPipConfigs);
stdPDPStatus.setFailedPolicies(failedPolicies);
- stdPDPStatus.setLoadedPipConfigs(loadedPIPConfigs);
+ stdPDPStatus.setLoadedPipConfigs(loadedPipConfigs);
stdPDPStatus.setLoadedPolicies(loadedPolicies);
stdPDPStatus.setLoadedRootPolicies(loadedRootPolicies);
stdPDPStatus.setLoadErrors(loadErrors);
stdPDPStatus.setLoadWarnings(loadWarnings);
- StdPDPStatus stdPDPStatus1 = new StdPDPStatus();
- stdPDPStatus1.set(stdPDPStatus);
-
- assertEquals(status, stdPDPStatus1.getStatus());
- assertEquals(loadErrors, stdPDPStatus1.getLoadErrors());
- assertEquals(loadWarnings, stdPDPStatus1.getLoadWarnings());
- assertEquals(loadedPolicies, stdPDPStatus1.getLoadedPolicies());
- assertEquals(loadedRootPolicies, stdPDPStatus1.getLoadedRootPolicies());
- assertEquals(failedPolicies, stdPDPStatus1.getFailedPolicies());
- assertEquals(loadedPIPConfigs, stdPDPStatus1.getLoadedPipConfigs());
- assertEquals(failedPIPConfigs, stdPDPStatus1.getFailedPipConfigs());
-
- assertEquals(
- "StdPDPStatus [status=UP_TO_DATE, loadErrors=[An error], loadWarnings=[An error],"
- + " loadedPolicies=[StdPDPPolicy [id=null, name=null, policyId=null, description=null,"
- + " version=, isRoot=false, isValid=false, location=null]],"
- + " loadedRootPolicies=[StdPDPPolicy [id=null, name=null, policyId=null, description=null,"
- + " version=, isRoot=false, isValid=false, location=null]],"
- + " failedPolicies=[StdPDPPolicy [id=null, name=null, policyId=null, description=null,"
- + " version=, isRoot=false, isValid=false, location=null]], loadedPIPConfigs=[StdPDPPIPConfig"
- + " [id=null, name=null, description=null, classname=null, config={}]], failedPIPConfigs="
- + "[StdPDPPIPConfig [id=null, name=null, description=null, classname=null, config={}]]]",
- stdPDPStatus1.toString());
+ StdPDPStatus stdPdpStatus1 = new StdPDPStatus();
+ stdPdpStatus1.set(stdPDPStatus);
+
+ assertEquals(status, stdPdpStatus1.getStatus());
+ assertEquals(loadErrors, stdPdpStatus1.getLoadErrors());
+ assertEquals(loadWarnings, stdPdpStatus1.getLoadWarnings());
+ assertEquals(loadedPolicies, stdPdpStatus1.getLoadedPolicies());
+ assertEquals(loadedRootPolicies, stdPdpStatus1.getLoadedRootPolicies());
+ assertEquals(failedPolicies, stdPdpStatus1.getFailedPolicies());
+ assertEquals(loadedPipConfigs, stdPdpStatus1.getLoadedPipConfigs());
+ assertEquals(failedPipConfigs, stdPdpStatus1.getFailedPipConfigs());
+
+ assertTrue(stdPdpStatus1.toString().startsWith("StdPDPStatus"));
}
@Test
public void testEqualsAndHashCode() {
- Status status = Status.UP_TO_DATE;
- Set<PDPPIPConfig> failedPIPConfigs = new HashSet<>();
- failedPIPConfigs.add(new StdPDPPIPConfig());
+ final Status status = Status.UP_TO_DATE;
+ Set<PDPPIPConfig> failedPipConfigs = new HashSet<>();
+ failedPipConfigs.add(new StdPDPPIPConfig());
Set<PDPPolicy> failedPolicies = new HashSet<>();
failedPolicies.add(new StdPDPPolicy());
- Set<PDPPIPConfig> loadedPIPConfigs = new HashSet<>();
- loadedPIPConfigs.add(new StdPDPPIPConfig());
+ Set<PDPPIPConfig> loadedPipConfigs = new HashSet<>();
+ loadedPipConfigs.add(new StdPDPPIPConfig());
Set<PDPPolicy> loadedPolicies = new HashSet<>();
loadedPolicies.add(new StdPDPPolicy());
Set<PDPPolicy> loadedRootPolicies = new HashSet<>();
@@ -247,57 +243,57 @@ public class StdPDPStatusTest {
Set<String> loadWarnings = new HashSet<>();
loadWarnings.add("An error");
- StdPDPStatus stdPDPStatus1 = new StdPDPStatus();
+ StdPDPStatus stdPdpStatus1 = new StdPDPStatus();
- assertTrue(stdPDPStatus.equals(stdPDPStatus1));
+ assertTrue(stdPDPStatus.equals(stdPdpStatus1));
stdPDPStatus.setStatus(status);
- assertFalse(stdPDPStatus.equals(stdPDPStatus1));
- stdPDPStatus1.setStatus(status);
- assertTrue(stdPDPStatus.equals(stdPDPStatus1));
- assertEquals(stdPDPStatus.hashCode(), stdPDPStatus1.hashCode());
+ assertFalse(stdPDPStatus.equals(stdPdpStatus1));
+ stdPdpStatus1.setStatus(status);
+ assertTrue(stdPDPStatus.equals(stdPdpStatus1));
+ assertEquals(stdPDPStatus.hashCode(), stdPdpStatus1.hashCode());
- stdPDPStatus.setFailedPipConfigs(failedPIPConfigs);
- assertFalse(stdPDPStatus.equals(stdPDPStatus1));
- stdPDPStatus1.setFailedPipConfigs(failedPIPConfigs);
- assertTrue(stdPDPStatus.equals(stdPDPStatus1));
- assertEquals(stdPDPStatus.hashCode(), stdPDPStatus1.hashCode());
+ stdPDPStatus.setFailedPipConfigs(failedPipConfigs);
+ assertFalse(stdPDPStatus.equals(stdPdpStatus1));
+ stdPdpStatus1.setFailedPipConfigs(failedPipConfigs);
+ assertTrue(stdPDPStatus.equals(stdPdpStatus1));
+ assertEquals(stdPDPStatus.hashCode(), stdPdpStatus1.hashCode());
stdPDPStatus.setFailedPolicies(failedPolicies);
- assertFalse(stdPDPStatus.equals(stdPDPStatus1));
- stdPDPStatus1.setFailedPolicies(failedPolicies);
- assertTrue(stdPDPStatus.equals(stdPDPStatus1));
- assertEquals(stdPDPStatus.hashCode(), stdPDPStatus1.hashCode());
+ assertFalse(stdPDPStatus.equals(stdPdpStatus1));
+ stdPdpStatus1.setFailedPolicies(failedPolicies);
+ assertTrue(stdPDPStatus.equals(stdPdpStatus1));
+ assertEquals(stdPDPStatus.hashCode(), stdPdpStatus1.hashCode());
- stdPDPStatus.setLoadedPipConfigs(loadedPIPConfigs);
- assertFalse(stdPDPStatus.equals(stdPDPStatus1));
- stdPDPStatus1.setLoadedPipConfigs(loadedPIPConfigs);
- assertTrue(stdPDPStatus.equals(stdPDPStatus1));
- assertEquals(stdPDPStatus.hashCode(), stdPDPStatus1.hashCode());
+ stdPDPStatus.setLoadedPipConfigs(loadedPipConfigs);
+ assertFalse(stdPDPStatus.equals(stdPdpStatus1));
+ stdPdpStatus1.setLoadedPipConfigs(loadedPipConfigs);
+ assertTrue(stdPDPStatus.equals(stdPdpStatus1));
+ assertEquals(stdPDPStatus.hashCode(), stdPdpStatus1.hashCode());
stdPDPStatus.setLoadedPolicies(loadedPolicies);
- assertFalse(stdPDPStatus.equals(stdPDPStatus1));
- stdPDPStatus1.setLoadedPolicies(loadedPolicies);
- assertTrue(stdPDPStatus.equals(stdPDPStatus1));
- assertEquals(stdPDPStatus.hashCode(), stdPDPStatus1.hashCode());
+ assertFalse(stdPDPStatus.equals(stdPdpStatus1));
+ stdPdpStatus1.setLoadedPolicies(loadedPolicies);
+ assertTrue(stdPDPStatus.equals(stdPdpStatus1));
+ assertEquals(stdPDPStatus.hashCode(), stdPdpStatus1.hashCode());
stdPDPStatus.setLoadedRootPolicies(loadedRootPolicies);
- assertFalse(stdPDPStatus.equals(stdPDPStatus1));
- stdPDPStatus1.setLoadedRootPolicies(loadedRootPolicies);
- assertTrue(stdPDPStatus.equals(stdPDPStatus1));
- assertEquals(stdPDPStatus.hashCode(), stdPDPStatus1.hashCode());
+ assertFalse(stdPDPStatus.equals(stdPdpStatus1));
+ stdPdpStatus1.setLoadedRootPolicies(loadedRootPolicies);
+ assertTrue(stdPDPStatus.equals(stdPdpStatus1));
+ assertEquals(stdPDPStatus.hashCode(), stdPdpStatus1.hashCode());
stdPDPStatus.setLoadErrors(loadErrors);
- assertFalse(stdPDPStatus.equals(stdPDPStatus1));
- stdPDPStatus1.setLoadErrors(loadErrors);
- assertTrue(stdPDPStatus.equals(stdPDPStatus1));
- assertEquals(stdPDPStatus.hashCode(), stdPDPStatus1.hashCode());
+ assertFalse(stdPDPStatus.equals(stdPdpStatus1));
+ stdPdpStatus1.setLoadErrors(loadErrors);
+ assertTrue(stdPDPStatus.equals(stdPdpStatus1));
+ assertEquals(stdPDPStatus.hashCode(), stdPdpStatus1.hashCode());
stdPDPStatus.setLoadWarnings(loadWarnings);
- assertFalse(stdPDPStatus.equals(stdPDPStatus1));
- stdPDPStatus1.setLoadWarnings(loadWarnings);
- assertTrue(stdPDPStatus.equals(stdPDPStatus1));
- assertEquals(stdPDPStatus.hashCode(), stdPDPStatus1.hashCode());
+ assertFalse(stdPDPStatus.equals(stdPdpStatus1));
+ stdPdpStatus1.setLoadWarnings(loadWarnings);
+ assertTrue(stdPDPStatus.equals(stdPdpStatus1));
+ assertEquals(stdPDPStatus.hashCode(), stdPdpStatus1.hashCode());
}
@Test
diff --git a/ONAP-XACML/src/test/java/org/onap/policy/xacml/test/std/pap/StdPDPTest.java b/ONAP-XACML/src/test/java/org/onap/policy/xacml/test/std/pap/StdPDPTest.java
index 0beb28275..75ebe4801 100644
--- a/ONAP-XACML/src/test/java/org/onap/policy/xacml/test/std/pap/StdPDPTest.java
+++ b/ONAP-XACML/src/test/java/org/onap/policy/xacml/test/std/pap/StdPDPTest.java
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP-XACML
* ================================================================================
- * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Modifications Copyright (C) 2019 Samsung
* ================================================================================
@@ -28,17 +28,20 @@ import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
+
+import com.att.research.xacml.api.pap.PDPPIPConfig;
+import com.att.research.xacml.api.pap.PDPPolicy;
+
import java.util.HashSet;
import java.util.Properties;
import java.util.Set;
+
import org.junit.Before;
import org.junit.Test;
import org.onap.policy.common.logging.flexlogger.FlexLogger;
import org.onap.policy.common.logging.flexlogger.Logger;
import org.onap.policy.xacml.std.pap.StdPDP;
import org.onap.policy.xacml.std.pap.StdPDPStatus;
-import com.att.research.xacml.api.pap.PDPPIPConfig;
-import com.att.research.xacml.api.pap.PDPPolicy;
public class StdPDPTest {
@@ -116,7 +119,7 @@ public class StdPDPTest {
}
@Test
- public void testPDP() {
+ public void testPdp() {
// Set up test data
String id = "testID";
String value = "testVal";
@@ -124,8 +127,8 @@ public class StdPDPTest {
props.setProperty(id + ".name", value);
props.setProperty(id + ".description", value);
props.setProperty(id + ".jmxport", "0");
- Set<PDPPIPConfig> pipConfigs = new HashSet<PDPPIPConfig>();
- Set<PDPPolicy> policies = new HashSet<PDPPolicy>();
+ props.setProperty(id + ".foo", "0");
+ props.setProperty("foo" + ".jmxport", "0");
// Test constructors
StdPDP pdp = new StdPDP(id, 0);
@@ -138,8 +141,12 @@ public class StdPDPTest {
assertNotNull(pdp4);
StdPDP pdp5 = new StdPDP(id, props);
assertNotNull(pdp5);
+ StdPDP pdp6 = new StdPDP(id, value, value, null);
+ assertNotNull(pdp6);
// Test set and get
+ Set<PDPPIPConfig> pipConfigs = new HashSet<PDPPIPConfig>();
+ Set<PDPPolicy> policies = new HashSet<PDPPolicy>();
pdp.setPipConfigs(pipConfigs);
assertEquals(pipConfigs, pdp.getPipConfigs());
pdp.setPolicies(policies);
diff --git a/ONAP-XACML/src/test/java/org/onap/policy/xacml/test/std/pip/engines/OperationHistoryEngineTest.java b/ONAP-XACML/src/test/java/org/onap/policy/xacml/test/std/pip/engines/OperationHistoryEngineTest.java
index 2b43ce753..fb90ab379 100644
--- a/ONAP-XACML/src/test/java/org/onap/policy/xacml/test/std/pip/engines/OperationHistoryEngineTest.java
+++ b/ONAP-XACML/src/test/java/org/onap/policy/xacml/test/std/pip/engines/OperationHistoryEngineTest.java
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP-XACML
* ================================================================================
- * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2018-2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Modifications Copyright (C) 2019 Samsung
* ================================================================================
@@ -23,9 +23,7 @@
package org.onap.policy.xacml.test.std.pip.engines;
import static org.junit.Assert.assertEquals;
-import java.util.Collection;
-import org.junit.Test;
-import org.onap.policy.xacml.std.pip.engines.OperationHistoryEngine;
+
import com.att.research.xacml.api.Attribute;
import com.att.research.xacml.api.pip.PIPException;
import com.att.research.xacml.api.pip.PIPRequest;
@@ -33,6 +31,11 @@ import com.att.research.xacml.api.pip.PIPResponse;
import com.att.research.xacml.std.StdMutableAttribute;
import com.att.research.xacml.std.pip.StdPIPRequest;
+import java.util.Collection;
+
+import org.junit.Test;
+import org.onap.policy.xacml.std.pip.engines.OperationHistoryEngine;
+
public class OperationHistoryEngineTest {
@Test
public void testBaseNegativeCase() throws PIPException {
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
index 319198e69..703541db3 100644
--- 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
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP-XACML
* ================================================================================
- * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Modifications Copyright (C) 2019 Samsung
* ================================================================================
@@ -19,21 +19,25 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.policy.xacml.test.util;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
-import java.util.Properties;
-import org.junit.Test;
-import org.onap.policy.xacml.std.pip.engines.aaf.AAFEngine;
+
+import com.att.research.xacml.api.XACML3;
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.pip.StdPIPFinderFactory;
import com.att.research.xacml.std.pip.StdPIPRequest;
import com.att.research.xacml.util.XACMLProperties;
-import com.att.research.xacml.api.XACML3;
+
+import java.util.Properties;
+
+import org.junit.Test;
+import org.onap.policy.xacml.std.pip.engines.aaf.AAFEngine;
public class AAFEngineTest {
@Test
@@ -54,8 +58,8 @@ public class AAFEngineTest {
assertEquals(aafEngine.attributesProvided().size(), 2);
assertEquals(aafEngine.attributesRequired().size(), 5);
- PIPRequest pipRequest = new StdPIPRequest(XACML3.ID_ATTRIBUTE_CATEGORY_RESOURCE,
- AAFEngine.AAF_RESPONSE_ID, XACML3.ID_DATATYPE_STRING);
+ PIPRequest pipRequest = new StdPIPRequest(XACML3.ID_ATTRIBUTE_CATEGORY_RESOURCE, AAFEngine.AAF_RESPONSE_ID,
+ XACML3.ID_DATATYPE_STRING);
StdPIPFinderFactory pipFactory = new StdPIPFinderFactory();
PIPFinder pipFinder = pipFactory.getFinder();
assertEquals(pipFinder.getPIPEngines().size(), 0);
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
index 291bae808..17d9c249d 100644
--- 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
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP-XACML
* ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017, 2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Modifications Copyright (C) 2019 Samsung
* ================================================================================
@@ -19,9 +19,11 @@
* 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;
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
index 0270a8901..08d899949 100644
--- 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
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP-XACML
* ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017, 2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Modifications Copyright (C) 2019 Samsung
* ================================================================================
@@ -19,20 +19,38 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.policy.xacml.test.util;
+import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
+import com.att.research.xacml.api.Advice;
+import com.att.research.xacml.api.Attribute;
+import com.att.research.xacml.api.Obligation;
+import com.att.research.xacml.util.XACMLPolicyScanner.Callback;
+import com.att.research.xacml.util.XACMLPolicyScanner.CallbackResult;
import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
+import java.nio.file.Paths;
import java.util.List;
+import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionType;
+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.ObligationExpressionType;
+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.VariableDefinitionType;
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 {
@@ -40,16 +58,17 @@ public class XACMLPolicyScannerTest {
private static Path configPolicyPathValue;
private static Path actionPolicyPathValue;
+ /**
+ * setUp.
+ */
@Before
public void setUp() {
File templateFile;
ClassLoader classLoader = getClass().getClassLoader();
try {
- templateFile =
- new File(classLoader.getResource("Config_SampleTest1206.1.xml").getFile());
+ templateFile = new File(classLoader.getResource("Config_SampleTest1206.1.xml").getFile());
configPolicyPathValue = templateFile.toPath();
- templateFile =
- new File(classLoader.getResource("Action_TestActionPolicy.1.xml").getFile());
+ templateFile = new File(classLoader.getResource("Action_TestActionPolicy.1.xml").getFile());
actionPolicyPathValue = templateFile.toPath();
} catch (Exception e1) {
logger.error("Exception Occured" + e1);
@@ -60,11 +79,10 @@ public class XACMLPolicyScannerTest {
public void xacmlPolicyScannerTest() throws IOException {
Callback callback = null;
try {
- XACMLPolicyScanner actionScanner =
- new XACMLPolicyScanner(actionPolicyPathValue, callback);
- assertTrue(actionScanner.getPolicyObject() != null);
+ XACMLPolicyScanner actionScanner = new XACMLPolicyScanner(actionPolicyPathValue, callback);
+ assertNotNull(actionScanner.getPolicyObject());
Object actionObject = actionScanner.scan();
- assertTrue(actionObject != null);
+ assertNotNull(actionObject);
XACMLPolicyScanner scanner = new XACMLPolicyScanner(configPolicyPathValue, callback);
assertTrue(scanner.getPolicyObject() != null);
@@ -76,8 +94,7 @@ public class XACMLPolicyScannerTest {
assertTrue(version.equals("1"));
String versionFromPath = XACMLPolicyScanner.getVersion(configPolicyPathValue);
assertTrue(versionFromPath.equals("1"));
- List<String> returnValue =
- XACMLPolicyScanner.getCreatedByModifiedBy(configPolicyPathValue);
+ List<String> returnValue = XACMLPolicyScanner.getCreatedByModifiedBy(configPolicyPathValue);
assertTrue(returnValue.get(0).equals("test"));
String createdBy = XACMLPolicyScanner.getCreatedBy(configPolicyPathValue);
assertTrue(createdBy.equals("test"));
@@ -88,4 +105,143 @@ public class XACMLPolicyScannerTest {
logger.error("Exception Occured" + e);
}
}
+
+ @Test
+ public void badPolicies() throws IOException {
+ Path unknown = Paths.get("foobar.xml");
+ XACMLPolicyScanner scanner = new XACMLPolicyScanner(unknown, null);
+ assertNull(scanner.getPolicyObject());
+ assertNull(scanner.scan());
+
+ assertThatExceptionOfType(IOException.class).isThrownBy(() -> {
+ XACMLPolicyScanner.getVersion(unknown);
+ });
+
+ Path logback = Paths.get("logback-test.xml");
+ scanner = new XACMLPolicyScanner(logback, null);
+ }
+
+ @Test
+ public void testRest() {
+ PolicySetType policySet = new PolicySetType();
+ policySet.setPolicySetId("id1");
+ policySet.setVersion("v1");
+ XACMLPolicyScanner scanner = new XACMLPolicyScanner(policySet);
+ assertNotNull(scanner);
+ assertEquals(policySet, scanner.getPolicyObject());
+ assertEquals(policySet.getPolicySetId(), XACMLPolicyScanner.getID(policySet));
+ assertEquals(policySet.getVersion(), XACMLPolicyScanner.getVersion(policySet));
+
+ scanner.setCallback(new TestCallback(CallbackResult.CONTINUE));
+ assertEquals(policySet, scanner.scan());
+ assertEquals(policySet, scanner.scan(new TestCallback(CallbackResult.CONTINUE)));
+ assertEquals(policySet, scanner.scan(new TestCallback(CallbackResult.STOP)));
+
+ PolicyType policy = new PolicyType();
+ policy.setPolicyId("id2");
+ policy.setVersion("v2");
+ scanner = new XACMLPolicyScanner(policy);
+ assertNotNull(scanner);
+ assertEquals(policy, scanner.getPolicyObject());
+ assertEquals(policy.getPolicyId(), XACMLPolicyScanner.getID(policy));
+ assertEquals(policy.getVersion(), XACMLPolicyScanner.getVersion(policy));
+ policy.setVersion(null);
+ assertNull(XACMLPolicyScanner.getVersion(policy));
+
+ assertNull(XACMLPolicyScanner.getID(new String()));
+ assertNull(XACMLPolicyScanner.getVersion(new String()));
+
+ }
+
+ @Test
+ public void testPolicySet() {
+ PolicySetType policySet = new PolicySetType();
+ policySet.setPolicySetId("id1");
+ policySet.setVersion("v1");
+
+ }
+
+ class TestCallback implements Callback {
+
+ CallbackResult begin = CallbackResult.CONTINUE;
+
+ TestCallback(CallbackResult onBegin) {
+ begin = onBegin;
+ }
+
+ @Override
+ public CallbackResult onBeginScan(Object root) {
+ return begin;
+ }
+
+ @Override
+ public void onFinishScan(Object root) {
+ }
+
+ @Override
+ public CallbackResult onPreVisitPolicySet(PolicySetType parent, PolicySetType policySet) {
+ return CallbackResult.CONTINUE;
+ }
+
+ @Override
+ public CallbackResult onPostVisitPolicySet(PolicySetType parent, PolicySetType policySet) {
+ return CallbackResult.CONTINUE;
+ }
+
+ @Override
+ public CallbackResult onPreVisitPolicy(PolicySetType parent, PolicyType policy) {
+ return CallbackResult.CONTINUE;
+ }
+
+ @Override
+ public CallbackResult onPostVisitPolicy(PolicySetType parent, PolicyType policy) {
+ return CallbackResult.CONTINUE;
+ }
+
+ @Override
+ public CallbackResult onPreVisitRule(PolicyType parent, RuleType rule) {
+ return CallbackResult.CONTINUE;
+ }
+
+ @Override
+ public CallbackResult onPostVisitRule(PolicyType parent, RuleType rule) {
+ return CallbackResult.CONTINUE;
+ }
+
+ @Override
+ public CallbackResult onAttribute(Object parent, Object container, Attribute attribute) {
+ return CallbackResult.CONTINUE;
+ }
+
+ @Override
+ public CallbackResult onObligation(Object parent, ObligationExpressionType expression, Obligation obligation) {
+ return CallbackResult.CONTINUE;
+ }
+
+ @Override
+ public CallbackResult onAdvice(Object parent, AdviceExpressionType expression, Advice advice) {
+ return CallbackResult.CONTINUE;
+ }
+
+ @Override
+ public CallbackResult onVariable(PolicyType policy, VariableDefinitionType variable) {
+ return CallbackResult.CONTINUE;
+ }
+
+ @Override
+ public CallbackResult onCondition(RuleType rule, ConditionType condition) {
+ return CallbackResult.CONTINUE;
+ }
+
+ @Override
+ public CallbackResult onPolicySetIdReference(IdReferenceType reference, PolicySetType parent) {
+ return CallbackResult.CONTINUE;
+ }
+
+ @Override
+ public CallbackResult onPolicyIdReference(IdReferenceType reference, PolicySetType parent) {
+ return CallbackResult.CONTINUE;
+ }
+
+ }
}
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
index 4cf40a315..1ec1616ef 100644
--- 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
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP-XACML
* ================================================================================
- * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Modifications Copyright (C) 2019 Samsung
* ================================================================================
@@ -19,22 +19,26 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.policy.xacml.test.util;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
+
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.file.Path;
+
+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.junit.Before;
import org.junit.Test;
import org.onap.policy.xacml.util.XACMLPolicyWriter;
-import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicySetType;
-import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType;
public class XACMLPolicyWriterTest {
private static final Log logger = LogFactory.getLog(XACMLPolicyWriterTest.class);
@@ -46,11 +50,9 @@ public class XACMLPolicyWriterTest {
File templateFile;
ClassLoader classLoader = getClass().getClassLoader();
try {
- templateFile =
- new File(classLoader.getResource("Config_SampleTest1206.1.xml").getFile());
+ templateFile = new File(classLoader.getResource("Config_SampleTest1206.1.xml").getFile());
configPolicyPathValue = templateFile.toPath();
- templateFile =
- new File(classLoader.getResource("Action_TestActionPolicy.1.xml").getFile());
+ templateFile = new File(classLoader.getResource("Action_TestActionPolicy.1.xml").getFile());
actionPolicyPathValue = templateFile.toPath();
} catch (Exception e1) {
logger.error("Exception Occured" + e1);
@@ -61,11 +63,9 @@ public class XACMLPolicyWriterTest {
@Test
public void xacmlPolicyWriterTest() throws IOException {
XACMLPolicyWriter writer = new XACMLPolicyWriter();
- String configResponseValue =
- writer.changeFileNameInXmlWhenRenamePolicy(configPolicyPathValue);
+ String configResponseValue = writer.changeFileNameInXmlWhenRenamePolicy(configPolicyPathValue);
assertTrue(configResponseValue.equals("txt"));
- String actionResponseValue =
- writer.changeFileNameInXmlWhenRenamePolicy(actionPolicyPathValue);
+ String actionResponseValue = writer.changeFileNameInXmlWhenRenamePolicy(actionPolicyPathValue);
assertTrue(actionResponseValue.equals("json"));
}
diff --git a/ONAP-XACML/src/test/resources/logback-test.xml b/ONAP-XACML/src/test/resources/logback-test.xml
index cdfdac958..37a07841f 100644
--- a/ONAP-XACML/src/test/resources/logback-test.xml
+++ b/ONAP-XACML/src/test/resources/logback-test.xml
@@ -2,14 +2,14 @@
============LICENSE_START=======================================================
ONAP-XACML
================================================================================
- Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
================================================================================
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
-
+
http://www.apache.org/licenses/LICENSE-2.0
-
+
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -22,73 +22,73 @@
<!--<jmxConfigurator /> -->
<!-- directory path for all other type logs -->
<property name="logDir" value="logs" />
-
+
<!-- directory path for debugging type logs -->
<property name="debugDir" value="logs" />
-
- <!-- specify the component name
+
+ <!-- specify the component name
<ONAP-component-name>::= "MSO" | "DCAE" | "ASDC " | "AAI" |"Policy" | "SDNC" | "AC" -->
<property name="componentName" value="Policy"></property>
<property name="subComponentName" value="XACML"></property>
-
+
<!-- log file names -->
<property name="errorLogName" value="error" />
<property name="metricsLogName" value="metrics" />
<property name="auditLogName" value="audit" />
<property name="debugLogName" value="debug" />
-
-
+
+
<!-- modified time stamp format -->
-
- <!-- A U D I T
- <property name="defaultAuditPattern" value="%X{BeginTimestamp}|%X{EndTimestamp}|%X{RequestId}|%X{ServiceInstanceId}|%thread|%X{ServerName}|%X{ServiceName}|%X{PartnerName}|%X{StatusCode}|%X{ResponseCode}|%X{ResponseDescription}|%X{InstanceUUID}|%.-5level|%X{AlertSeverity}|%X{ServerIPAddress}|%X{ElapsedTime}|%X{ServerFQDN}|%X{RemoteHost}|%X{ClassName}||%X{ProcessKey}|%X{TargetVirtualEntity}|%X{CustomField1}|%X{CustomField2}|%X{CustomField3}|%X{CustomField4}|%msg%n" />
+
+ <!-- A U D I T
+ <property name="defaultAuditPattern" value="%X{BeginTimestamp}|%X{EndTimestamp}|%X{RequestId}|%X{ServiceInstanceId}|%thread|%X{ServerName}|%X{ServiceName}|%X{PartnerName}|%X{StatusCode}|%X{ResponseCode}|%X{ResponseDescription}|%X{InstanceUUID}|%.-5level|%X{Severity}|%X{ServerIPAddress}|%X{ElapsedTime}|%X{ServerFQDN}|%X{RemoteHost}|%X{ClassName}||%X{ProcessKey}|%X{TargetVirtualEntity}|%X{CustomField1}|%X{CustomField2}|%X{CustomField3}|%X{CustomField4}|%msg%n" />
<property name="defaultAuditPattern" value="%X{BeginTimestamp}|%X{EndTimestamp}|%X{requestId}|%X{serviceInstanceId}|%t|%X{serverName}|%X{serviceName}|%X{PartnerName}|%X{StatusCode}|%X{ResponseCode}|%X{ResponseDescription}|%X{instanceUuid}|%p|%X{severity}|%X{serverIpAddress}|%X{ElapsedTime}|%X{server}|%X{clientIpAddress}|%c||%X{ProcessKey}|%X{TargetVirtualEntity}|%X{CustomField1}|%X{CustomField2}|%X{CustomField3}|%X{CustomField4}|%msg%n" />
-->
<property name="defaultAuditPattern" value="%X{TransactionBeginTimestamp}|%X{TransactionEndTimestamp}|%X{requestId}|%X{serviceInstanceId}|%t|%X{serverName}|%X{serviceName}|%X{partnerName}|%X{statusCode}|%X{ResponseCode}|%X{ResponseDescription}|%X{instanceUuid}|%p|%X{severity}|%X{serverIpAddress}|%X{TransactionElapsedTime}|%X{server}|%X{clientIpAddress}|%c||%X{ProcessKey}|%X{CustomField1}|%X{CustomField2}|%X{CustomField3}|%X{CustomField4}|%msg%n" />
-
-
-
- <!-- M E T R I C
- <property name="defaultMetricPattern" value="%X{BeginTimestamp}|%X{EndTimestamp}|%X{RequestId}|%X{ServiceInstanceId}|%thread|%X{ServerName}|%X{ServiceName}|%X{PartnerName}|%X{TargetEntity}|%X{TargetServiceName}|%X{StatusCode}|%X{ResponseCode}|%X{ResponseDescription}|%X{InstanceUUID}|%.-5level|%X{AlertSeverity}|%X{ServerIPAddress}|%X{ElapsedTime}|%X{ServerFQDN}|%X{RemoteHost}|%X{ClassName}||%X{ProcessKey}|%X{TargetVirtualEntity}|%X{CustomField1}|%X{CustomField2}|%X{CustomField3}|%X{CustomField4}|%msg%n" />
+
+
+
+ <!-- M E T R I C
+ <property name="defaultMetricPattern" value="%X{BeginTimestamp}|%X{EndTimestamp}|%X{RequestId}|%X{ServiceInstanceId}|%thread|%X{ServerName}|%X{ServiceName}|%X{PartnerName}|%X{TargetEntity}|%X{TargetServiceName}|%X{StatusCode}|%X{ResponseCode}|%X{ResponseDescription}|%X{InstanceUUID}|%.-5level|%X{Severity}|%X{ServerIPAddress}|%X{ElapsedTime}|%X{ServerFQDN}|%X{RemoteHost}|%X{ClassName}||%X{ProcessKey}|%X{TargetVirtualEntity}|%X{CustomField1}|%X{CustomField2}|%X{CustomField3}|%X{CustomField4}|%msg%n" />
-->
<property name="defaultMetricPattern" value="%X{MetricBeginTimestamp}|%X{MetricEndTimestamp}|%X{requestId}|%X{serviceInstanceId}|%t|%X{serverName}|%X{serviceName}|%X{partnerName}|%X{targetEntity}|%X{targetServiceName}|%X{statusCode}|%X{ResponseCode}|%X{ResponseDescription}|%X{InstanceUUID}|%p|%X{severity}|%X{serverIpAddress}|%X{MetricElapsedTime}|%X{server}|%X{clientIpAddress}|%c||%X{ProcessKey}|%X{TargetVirtualEntity}|%X{CustomField1}|%X{CustomField2}|%X{CustomField3}|%X{CustomField4}|%msg%n" />
-
-
-
-
+
+
+
+
<!-- E R R O R
<property name="defaultErrorPattern" value="%d{yyyy-MM-dd'T'HH:mm:ss.SSS+00:00, UTC}|%X{RequestId}|%thread|%X{ServiceName}|%X{PartnerName}|%X{TargetEntity}|%X{TargetServiceName}|%X{ErrorCategory}|%X{ErrorCode}|%X{ErrorDesciption}|%msg%n" />
-->
<property name="defaultErrorPattern" value="%d{yyyy-MM-dd'T'HH:mm:ss.SSS+00:00, UTC}|%X{requestId}|%t|%X{serviceName}|%X{PartnerName}|%X{TargetEntity}|%X{TargetServiceName}|%X{ErrorCategory}|%X{ErrorCode}|%X{ErrorDesciption}|%msg%n" />
-
-
-
+
+
+
<!-- D E B U G
- <property name="debugLoggerPatternOld" value="%d{MM/dd-HH:mm:ss.SSS}|%X{RequestId}|%X{ServiceInstanceId}|%thread|%X{ServiceName}|%X{InstanceUUID}|%.-5level|%X{AlertSeverity}|%X{ServerIPAddress}|%X{ServerFQDN}|%X{RemoteHost}|%X{Timer}|[%caller{3}]|%msg%n" />
- <property name="debugLoggerPattern" value="%X{BeginTimestamp}|%X{EndTimestamp}|%X{RequestId}|%X{ServiceInstanceId}|%thread|%X{ServerName}|%X{ServiceName}|%X{PartnerName}|%X{StatusCode}|%X{ResponseCode}|%X{ResponseDescription}|%X{ServiceName}|%X{InstanceUUID}|%.-5level|%X{AlertSeverity}|%X{ServerIPAddress}|%X{ElapsedTime}|%X{ServerFQDN}|%X{RemoteHost}|%X{ClassName}||%X{ProcessKey}|%X{CustomField1}|%X{CustomField2}|%X{CustomField3}|%X{CustomField4}|%msg%n" /> -->
+ <property name="debugLoggerPatternOld" value="%d{MM/dd-HH:mm:ss.SSS}|%X{RequestId}|%X{ServiceInstanceId}|%thread|%X{ServiceName}|%X{InstanceUUID}|%.-5level|%X{Severity}|%X{ServerIPAddress}|%X{ServerFQDN}|%X{RemoteHost}|%X{Timer}|[%caller{3}]|%msg%n" />
+ <property name="debugLoggerPattern" value="%X{BeginTimestamp}|%X{EndTimestamp}|%X{RequestId}|%X{ServiceInstanceId}|%thread|%X{ServerName}|%X{ServiceName}|%X{PartnerName}|%X{StatusCode}|%X{ResponseCode}|%X{ResponseDescription}|%X{ServiceName}|%X{InstanceUUID}|%.-5level|%X{Severity}|%X{ServerIPAddress}|%X{ElapsedTime}|%X{ServerFQDN}|%X{RemoteHost}|%X{ClassName}||%X{ProcessKey}|%X{CustomField1}|%X{CustomField2}|%X{CustomField3}|%X{CustomField4}|%msg%n" /> -->
-->
- <property name="debugLoggerPattern" value="%d{yyyy-MM-dd'T'HH:mm:ss.SSS+00:00, UTC}|%X{RequestId}|%msg%n" />
-
-
-
- <!-- D E F A U L T
- <property name="defaultPatternOld" value="%d{MM/dd-HH:mm:ss.SSS}|%logger|%X{RequestId}|%X{ServiceInstanceId}|%thread|%X{ServiceName}|%X{InstanceUUID}|%.-5level|%X{AlertSeverity}|%X{ServerIPAddress}|%X{ServerFQDN}|%X{RemoteHost}|%X{ClassName}|%X{Timer}|%msg%n" />
- <property name="defaultPattern" value="%X{BeginTimestamp}|%X{EndTimestamp}|%X{RequestId}|%X{ServiceInstanceId}|%thread|%X{ServerName}|%X{ServiceName}|%X{PartnerName}|%X{TargetEntity}|%X{TargetServiceName}|%X{StatusCode}|%X{ResponseCode}|%X{ResponseDescription}|%X{InstanceUUID}|%.-5level|%X{AlertSeverity}|%X{ServerIPAddress}|%X{ElapsedTime}|%X{ServerFQDN}|%X{RemoteHost}|%X{ClassName}||%X{ProcessKey}|%X{TargetVirtualEntity}|%X{CustomField1}|%X{CustomField2}|%X{CustomField3}|%X{CustomField4}|%msg%n" />
+ <property name="debugLoggerPattern" value="%d{yyyy-MM-dd'T'HH:mm:ss.SSS+00:00, UTC}|%X{RequestId}|%msg%n" />
+
+
+
+ <!-- D E F A U L T
+ <property name="defaultPatternOld" value="%d{MM/dd-HH:mm:ss.SSS}|%logger|%X{RequestId}|%X{ServiceInstanceId}|%thread|%X{ServiceName}|%X{InstanceUUID}|%.-5level|%X{Severity}|%X{ServerIPAddress}|%X{ServerFQDN}|%X{RemoteHost}|%X{ClassName}|%X{Timer}|%msg%n" />
+ <property name="defaultPattern" value="%X{BeginTimestamp}|%X{EndTimestamp}|%X{RequestId}|%X{ServiceInstanceId}|%thread|%X{ServerName}|%X{ServiceName}|%X{PartnerName}|%X{TargetEntity}|%X{TargetServiceName}|%X{StatusCode}|%X{ResponseCode}|%X{ResponseDescription}|%X{InstanceUUID}|%.-5level|%X{Severity}|%X{ServerIPAddress}|%X{ElapsedTime}|%X{ServerFQDN}|%X{RemoteHost}|%X{ClassName}||%X{ProcessKey}|%X{TargetVirtualEntity}|%X{CustomField1}|%X{CustomField2}|%X{CustomField3}|%X{CustomField4}|%msg%n" />
-->
<property name="defaultPattern" value="%d{yyyy-MM-dd'T'HH:mm:ss.SSSXXX, UTC}|%X{requestId}|%X{serviceInstanceId}|%t|%X{serverName}|%X{serviceName}|%X{instanceUuid}|%p|%X{severity}|%X{serverIpAddress}|%X{server}|%X{clientIpAddress}|%c||%msg%n" />
-
-
-
+
+
+
<!-- P A T H
<property name="logDirectory" value="${catalina.base}/${logDir}/${componentName}/${subComponentName}" />
- <property name="debugLogDirectory" value="${catalina.base}/${debugDir}/${componentName}/${subComponentName}" />
- -->
+ <property name="debugLogDirectory" value="${catalina.base}/${debugDir}/${componentName}/${subComponentName}" />
+ -->
<property name="logDirectory" value="${logDir}/${componentName}/${subComponentName}" />
<property name="debugLogDirectory" value="${debugDir}/${componentName}/${subComponentName}" />
-
-
-
+
+
+
<!-- Example evaluator filter applied against console appender -->
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
@@ -100,15 +100,15 @@
<!-- EELF Appenders -->
<!-- ============================================================================ -->
- <!-- The EELFAppender is used to record events to the general application
+ <!-- The EELFAppender is used to record events to the general application
log -->
-
- <!-- EELF Audit Appender. This appender is used to record audit engine
- related logging events. The audit logger and appender are specializations
- of the EELF application root logger and appender. This can be used to segregate
- Policy engine events from other components, or it can be eliminated to record
+
+ <!-- EELF Audit Appender. This appender is used to record audit engine
+ related logging events. The audit logger and appender are specializations
+ of the EELF application root logger and appender. This can be used to segregate
+ Policy engine events from other components, or it can be eliminated to record
these events as part of the application root log. -->
-
+
<appender name="EELFAudit"
class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>${logDirectory}/${auditLogName}.log</file>
@@ -151,12 +151,12 @@
<maxFileSize>5MB</maxFileSize>
</triggeringPolicy>
<encoder>
- <!-- <pattern>"%d{HH:mm:ss.SSS} [%thread] %-5level %logger{1024} -
+ <!-- <pattern>"%d{HH:mm:ss.SSS} [%thread] %-5level %logger{1024} -
%msg%n"</pattern> -->
<pattern>${defaultMetricPattern}</pattern>
</encoder>
</appender>
-
+
<appender name="asyncEELFMetrics" class="ch.qos.logback.classic.AsyncAppender">
<queueSize>256</queueSize>
<appender-ref ref="EELFMetrics"/>
@@ -164,7 +164,7 @@
-
+
<appender name="EELFError"
class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>${logDirectory}/${errorLogName}.log</file>
@@ -186,14 +186,14 @@
<pattern>${defaultErrorPattern}</pattern>
</encoder>
</appender>
-
+
<appender name="asyncEELFError" class="ch.qos.logback.classic.AsyncAppender">
<queueSize>256</queueSize>
<appender-ref ref="EELFError"/>
</appender>
-
+
<appender name="EELFDebug"
class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>${debugLogDirectory}/${debugLogName}.log</file>
@@ -215,36 +215,36 @@
<pattern>${debugLoggerPattern}</pattern>
</encoder>
</appender>
-
+
<appender name="asyncEELFDebug" class="ch.qos.logback.classic.AsyncAppender">
<queueSize>256</queueSize>
<appender-ref ref="EELFDebug" />
<includeCallerData>true</includeCallerData>
</appender>
-
-
+
+
<!-- ============================================================================ -->
<!-- EELF loggers -->
<!-- ============================================================================ -->
-
+
<logger name="com.att.eelf.audit" level="info" additivity="false">
<appender-ref ref="asyncEELFAudit" />
</logger>
-
+
<logger name="com.att.eelf.metrics" level="info" additivity="false">
<appender-ref ref="asyncEELFMetrics" />
</logger>
-
+
<logger name="com.att.eelf.error" level="error" additivity="false">
<appender-ref ref="asyncEELFError" />
</logger>
-
+
<logger name="com.att.eelf.debug" level="info" additivity="false">
<appender-ref ref="asyncEELFDebug" />
</logger>
-
-
-
+
+
+
<root level="INFO">
<appender-ref ref="asyncEELFDebug" />
<appender-ref ref="asyncEELFError" />
diff --git a/POLICY-SDK-APP/pom.xml b/POLICY-SDK-APP/pom.xml
index c0d387321..b1b1f03e8 100644
--- a/POLICY-SDK-APP/pom.xml
+++ b/POLICY-SDK-APP/pom.xml
@@ -2,7 +2,7 @@
============LICENSE_START=======================================================
ONAP Policy Engine
================================================================================
- Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ Copyright (C) 2017-2018, 2020 AT&T Intellectual Property. All rights reserved.
================================================================================
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
@@ -22,7 +22,7 @@
<parent>
<groupId>org.onap.policy.engine</groupId>
<artifactId>PolicyEngineSuite</artifactId>
- <version>1.4.1-SNAPSHOT</version>
+ <version>1.6.4-SNAPSHOT</version>
</parent>
<artifactId>POLICY-SDK-APP</artifactId>
<packaging>war</packaging>
@@ -37,13 +37,6 @@
</configuration>
</plugin>
<plugin>
- <artifactId>maven-compiler-plugin</artifactId>
- <configuration>
- <source>1.8</source>
- <target>1.8</target>
- </configuration>
- </plugin>
- <plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
@@ -65,18 +58,21 @@
</build>
<properties>
<encoding>UTF-8</encoding>
- <epsdk.version>2.4.0</epsdk.version>
- <springframework.version>4.2.0.RELEASE</springframework.version>
+ <epsdk.version>2.6.0</epsdk.version>
+ <springframework.version>4.3.24.RELEASE</springframework.version>
<hibernate.version>4.3.11.Final</hibernate.version>
<logback.version>1.2.3</logback.version>
<skipassembly>true</skipassembly>
<skiptests>false</skiptests>
- <!-- When ONAP brings back Javascript requirement for code coverage, let's move back to this exclusion. Keeping for reference. -->
- <!-- sonar.exclusions>**/gen/**,**/generated-sources/**,**/yang-gen**,**/pax/**,src/main/webapp/app/policyApp/CSS/**/*,src/main/webapp/app/policyApp/libs.bower_components/**/*</sonar.exclusions -->
- <sonar.exclusions>**/gen/**,**/generated-sources/**,**/yang-gen**,**/pax/**,src/main/webapp/app/policyApp/**/*</sonar.exclusions>
+ <sonar.exclusions>**/gen/**,**/generated-sources/**,**/yang-gen**,**/pax/**,src/main/webapp/app/policyApp/CSS/**/*,src/main/webapp/app/policyApp/libs.bower_components/**/*</sonar.exclusions>
</properties>
<dependencies>
<dependency>
+ <groupId>org.powermock</groupId>
+ <artifactId>powermock-api-mockito2</artifactId>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
</dependency>
@@ -111,8 +107,55 @@
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
</exclusion>
+ <exclusion>
+ <groupId>org.springframework</groupId>
+ <artifactId>spring-aop</artifactId>
+ </exclusion>
+ <exclusion>
+ <groupId>xalan</groupId>
+ <artifactId>xalan</artifactId>
+ </exclusion>
+ <exclusion>
+ <groupId>xml-apis</groupId>
+ <artifactId>xml-apis-ext</artifactId>
+ </exclusion>
+ <exclusion>
+ <groupId>xom</groupId>
+ <artifactId>xom</artifactId>
+ </exclusion>
+ <exclusion>
+ <groupId>xml-apis</groupId>
+ <artifactId>xml-apis</artifactId>
+ </exclusion>
+ <exclusion>
+ <groupId>org.hibernate</groupId>
+ <artifactId>hibernate-core</artifactId>
+ </exclusion>
+ <exclusion>
+ <groupId>org.aspectj</groupId>
+ <artifactId>aspectjrt</artifactId>
+ </exclusion>
+ <exclusion>
+ <groupId>org.aspectj</groupId>
+ <artifactId>aspectjweaver</artifactId>
+ </exclusion>
</exclusions>
</dependency>
+ <dependency>
+ <groupId>org.springframework</groupId>
+ <artifactId>spring-expression</artifactId>
+ <version>${springframework.version}</version>
+ </dependency>
+ <dependency>
+ <groupId>org.aspectj</groupId>
+ <artifactId>aspectjrt</artifactId>
+ <version>1.8.14</version>
+ </dependency>
+ <dependency>
+ <groupId>org.aspectj</groupId>
+ <artifactId>aspectjweaver</artifactId>
+ <version>1.8.14</version>
+ </dependency>
<!-- Spring -->
<dependency>
<groupId>org.springframework</groupId>
@@ -134,11 +177,23 @@
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${springframework.version}</version>
+ <exclusions>
+ <exclusion>
+ <groupId>org.springframework</groupId>
+ <artifactId>spring-expression</artifactId>
+ </exclusion>
+ </exclusions>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${springframework.version}</version>
+ <exclusions>
+ <exclusion>
+ <groupId>org.springframework</groupId>
+ <artifactId>spring-expression</artifactId>
+ </exclusion>
+ </exclusions>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
@@ -155,6 +210,12 @@
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>${hibernate.version}</version>
+ <exclusions>
+ <exclusion>
+ <groupId>xml-apis</groupId>
+ <artifactId>xml-apis</artifactId>
+ </exclusion>
+ </exclusions>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
@@ -240,6 +301,18 @@
<groupId>com.att.aft</groupId>
<artifactId>dme2</artifactId>
</exclusion>
+ <exclusion>
+ <groupId>xml-apis</groupId>
+ <artifactId>xml-apis</artifactId>
+ </exclusion>
+ <exclusion>
+ <groupId>org.springframework</groupId>
+ <artifactId>spring-orm</artifactId>
+ </exclusion>
+ <exclusion>
+ <groupId>org.springframework</groupId>
+ <artifactId>spring-test</artifactId>
+ </exclusion>
</exclusions>
</dependency>
<dependency>
@@ -255,12 +328,18 @@
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
- <version>3.17</version>
+ <version>4.1.1</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
- <version>3.17</version>
+ <version>4.1.1</version>
+ <exclusions>
+ <exclusion>
+ <groupId>org.apache.xmlbeans</groupId>
+ <artifactId>xmlbeans</artifactId>
+ </exclusion>
+ </exclusions>
</dependency>
<!-- https://mvnrepository.com/artifact/com.esotericsoftware.yamlbeans/yamlbeans -->
<dependency>
@@ -272,7 +351,6 @@
<dependency>
<groupId>org.yaml</groupId>
<artifactId>snakeyaml</artifactId>
- <version>1.16</version>
</dependency>
<dependency>
<groupId>org.apache.tomcat</groupId>
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/CheckPdpProperties.java
index 26b9798ac..925344191 100644
--- a/POLICY-SDK-APP/src/main/java/org/onap/policy/admin/CheckPDP.java
+++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/admin/CheckPdpProperties.java
@@ -22,8 +22,8 @@
package org.onap.policy.admin;
-
import com.att.research.xacml.util.XACMLProperties;
+
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
@@ -39,9 +39,10 @@ import java.util.HashMap;
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 org.onap.policy.rest.XACMLRestProperties;
+import org.onap.policy.rest.XacmlRestProperties;
import org.onap.policy.utils.PeCryptoUtils;
import org.onap.policy.xacml.api.XACMLErrorConstants;
@@ -50,20 +51,20 @@ import org.onap.policy.xacml.api.XACMLErrorConstants;
* may be ok for a highly controlled production environment in which nothing changes, but not a very good
* implementation.
*
- * The reset() method has been added to assist with the above problem in order to acquire >80% JUnit code coverage.
+ * <p>The reset() method has been added to assist with the above problem in order to acquire >80% JUnit code coverage.
*
- * This static class doesn't really check a PDP, it simply loads a properties file and tried to ensure that a valid URL
- * exists for a PDP along with user/password.
+ * <p>This static class doesn't really check a PDP, it simply loads a properties file and tried to ensure
+ * that a valid URL exists for a PDP along with user/password.
*/
-public class CheckPDP {
+public class CheckPdpProperties {
private static Path pdpPath = null;
private static Long oldModified = null;
private static HashMap<String, String> pdpMap = null;
- private static final Logger LOGGER = FlexLogger.getLogger(CheckPDP.class);
+ private static final Logger LOGGER = FlexLogger.getLogger(CheckPdpProperties.class);
- private CheckPDP() {
- //default constructor
+ private CheckPdpProperties() {
+ // default constructor
}
public static Map<String, String> getPdpMap() {
@@ -76,7 +77,13 @@ public class CheckPDP {
pdpMap = null;
}
- public static boolean validateID(String id) {
+ /**
+ * validateId - validates that the ID is in the properties.
+ *
+ * @param id Input ID
+ * @return true it is in the properties
+ */
+ public static boolean validateId(String id) {
// ReadFile
try {
readFile();
@@ -94,7 +101,7 @@ public class CheckPDP {
private static void readFile() {
String pdpFile;
try {
- pdpFile = XACMLProperties.getProperty(XACMLRestProperties.PROP_PDP_IDFILE);
+ pdpFile = XACMLProperties.getProperty(XacmlRestProperties.PROP_PDP_IDFILE);
} catch (Exception e) {
LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Cannot read the PDP ID File" + e);
return;
@@ -104,10 +111,9 @@ public class CheckPDP {
} else if (pdpPath == null) {
pdpPath = Paths.get(pdpFile);
if (!pdpPath.toString().endsWith(".properties") || !pdpPath.toFile().exists()) {
- LOGGER.error(
- XACMLErrorConstants.ERROR_SYSTEM_ERROR + "File doesn't exist in the specified Path : " + pdpPath
- .toString());
- CheckPDP.reset();
+ LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "File doesn't exist in the specified Path : "
+ + pdpPath.toString());
+ CheckPdpProperties.reset();
return;
}
readProps();
@@ -134,18 +140,18 @@ public class CheckPDP {
List<String> sorted = new ArrayList(unsorted);
Collections.sort(sorted);
for (String propKey : sorted) {
- loadPDPProperties(propKey, pdpProp);
+ loadPdpProperties(propKey, pdpProp);
}
} catch (IOException e) {
LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + e);
}
if (pdpMap == null || pdpMap.isEmpty()) {
LOGGER.debug(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Cannot Proceed without PDP_URLs");
- CheckPDP.reset();
+ CheckPdpProperties.reset();
}
}
- private static void loadPDPProperties(String propKey, Properties pdpProp) {
+ private static void loadPdpProperties(String propKey, Properties pdpProp) {
if (propKey.startsWith("PDP_URL")) {
String checkVal = pdpProp.getProperty(propKey);
if (checkVal == null) {
@@ -156,14 +162,14 @@ public class CheckPDP {
int pdpCount = 0;
while (pdpCount < pdpDefault.size()) {
String pdpVal = pdpDefault.get(pdpCount);
- readPDPParam(pdpVal);
+ readPdpParam(pdpVal);
pdpCount++;
}
}
}
}
- private static void readPDPParam(String pdpVal) {
+ private static void readPdpParam(String pdpVal) {
if (pdpVal.contains(",")) {
List<String> pdpValues = new ArrayList<>(Arrays.asList(pdpVal.split("\\s*,\\s*")));
if (pdpValues.size() == 3) {
@@ -173,7 +179,7 @@ public class CheckPDP {
Base64.Encoder encoder = Base64.getEncoder();
// 0 - PDPURL
pdpMap.put(pdpValues.get(0),
- encoder.encodeToString((userID + ":" + pass).getBytes(StandardCharsets.UTF_8)));
+ encoder.encodeToString((userID + ":" + pass).getBytes(StandardCharsets.UTF_8)));
} else {
LOGGER.error(XACMLErrorConstants.ERROR_PERMISSIONS + "No Credentials to send Request: " + pdpValues);
}
@@ -182,6 +188,13 @@ public class CheckPDP {
}
}
+ /**
+ * getEncoding reads in the PDP properties and returns an encoding
+ * for the given pdp.
+ *
+ * @param pdpID Input PDP Id
+ * @return String encoding
+ */
public static String getEncoding(String pdpID) {
try {
readFile();
@@ -196,8 +209,7 @@ public class CheckPDP {
LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + e);
}
return encoding;
- } else {
- return null;
}
+ 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
index 6aa40dacf..343a19f1a 100644
--- 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
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP Policy Engine
* ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017, 2019 AT&T Intellectual Property. All rights reserved.
* Modified Copyright (C) 2018 Samsung Electronics Co., Ltd.
* Modifications Copyright (C) 2019 Bell Canada
* ================================================================================
@@ -22,6 +22,8 @@
package org.onap.policy.admin;
+import com.att.research.xacml.util.XACMLProperties;
+
import org.onap.policy.common.logging.flexlogger.FlexLogger;
import org.onap.policy.common.logging.flexlogger.Logger;
import org.onap.policy.controller.ActionPolicyController;
@@ -37,12 +39,16 @@ 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);
+ /**
+ * configure.
+ *
+ * @param policyAdapter PolicyRestAdapter object
+ * @param entity PolicyEntity object
+ */
public void configure(PolicyRestAdapter policyAdapter, PolicyEntity entity) {
String policyNameValue = policyAdapter.getPolicyName().substring(0, policyAdapter.getPolicyName().indexOf('_'));
String configPolicyName = getConfigPolicyName(policyAdapter);
@@ -63,28 +69,25 @@ public class PolicyAdapter {
}
private String getConfigPolicyName(PolicyRestAdapter policyAdapter) {
- String configPolicyName = null;
if (policyAdapter.getPolicyName().startsWith("Config_PM")) {
- configPolicyName = "ClosedLoop_PM";
+ return "ClosedLoop_PM";
} else if (policyAdapter.getPolicyName().startsWith("Config_Fault")) {
- configPolicyName = "ClosedLoop_Fault";
+ return "ClosedLoop_Fault";
} else if (policyAdapter.getPolicyName().startsWith("Config_FW")) {
- configPolicyName = "Firewall Config";
+ return "Firewall Config";
} else if (policyAdapter.getPolicyName().startsWith("Config_BRMS_Raw")) {
- configPolicyName = "BRMS_Raw";
+ return "BRMS_Raw";
} else if (policyAdapter.getPolicyName().startsWith("Config_BRMS_Param")) {
- configPolicyName = "BRMS_Param";
+ return "BRMS_Param";
} else if (policyAdapter.getPolicyName().startsWith("Config_MS")) {
- configPolicyName = "Micro Service";
+ return "Micro Service";
} else if (policyAdapter.getPolicyName().startsWith("Config_OOF")) {
- configPolicyName = "Optimization";
- } else if (policyAdapter.getPolicyName().startsWith("Action") || policyAdapter.getPolicyName()
- .startsWith("Decision")) {
- // No configPolicyName is applicable
- } else {
- configPolicyName = "Base";
+ return "Optimization";
+ } else if (policyAdapter.getPolicyName().startsWith("Action")
+ || policyAdapter.getPolicyName().startsWith("Decision")) {
+ return null;
}
- return configPolicyName;
+ return "Base";
}
private void prePopulatePolicyData(PolicyRestAdapter policyAdapter, PolicyEntity entity) {
@@ -107,12 +110,18 @@ public class PolicyAdapter {
}
}
+ /**
+ * getInstance.
+ *
+ * @return Returns a PolicyAdapter instance
+ */
public static PolicyAdapter getInstance() {
try {
- Class<?> policyAdapter = Class
- .forName(XACMLProperties.getProperty("policyAdapter.impl.className", PolicyAdapter.class.getName()));
+ Class<?> policyAdapter = Class.forName(
+ XACMLProperties.getProperty("policyAdapter.impl.className", PolicyAdapter.class.getName()));
return (PolicyAdapter) policyAdapter.newInstance();
- } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | IllegalArgumentException e) {
+ } catch (ClassNotFoundException | InstantiationException | IllegalAccessException
+ | IllegalArgumentException e) {
LOGGER.error("Exception Occurred" + 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
index 513fc5795..a23a0e821 100644
--- 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
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP Policy Engine
* ================================================================================
- * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2020 AT&T Intellectual Property. All rights reserved.
* Modified Copyright (C) 2018 Samsung Electronics Co., Ltd.
* Modifications Copyright (C) 2019 Bell Canada
* ================================================================================
@@ -63,6 +63,7 @@ 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.lang3.StringUtils;
import org.apache.http.HttpStatus;
import org.elasticsearch.common.Strings;
import org.json.JSONArray;
@@ -73,8 +74,8 @@ 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.rest.XACMLRest;
-import org.onap.policy.rest.XACMLRestProperties;
+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;
@@ -87,11 +88,16 @@ import org.onap.policy.utils.PolicyUtils;
import org.onap.policy.utils.UserUtils.Pair;
import org.onap.policy.xacml.api.XACMLErrorConstants;
import org.onap.policy.xacml.util.XACMLPolicyScanner;
+import org.onap.portalsdk.core.domain.User;
import org.onap.portalsdk.core.web.support.UserUtils;
-
-@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.") })
+@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;
@@ -126,11 +132,13 @@ public class PolicyManagerServlet extends HttpServlet {
private static final String BACKSLASH = "\\";
private static final String ESCAPE_BACKSLASH = "\\\\";
private static final String BACKSLASH_8TIMES = "\\\\\\\\";
- private static final String DELETE_POLICY_VERSION_WHERE_POLICY_NAME = "delete from PolicyVersion where policy_name ='";
+ private static final String DELETE_POLICY_VERSION_WHERE_POLICY_NAME =
+ "delete from PolicyVersion where policy_name ='";
private static final String UPDATE_POLICY_VERSION_SET_ACTIVE_VERSION = "update PolicyVersion set active_version='";
private static final String SPLIT_1 = "split_1";
private static final String SPLIT_0 = "split_0";
- private static final String FROM_POLICY_EDITOR_SCOPES_WHERE_SCOPENAME_LIKE_SCOPE_NAME = "from PolicyEditorScopes where SCOPENAME like :scopeName";
+ private static final String FROM_POLICY_EDITOR_SCOPES_WHERE_SCOPENAME_LIKE_SCOPE_NAME =
+ "from PolicyEditorScopes where SCOPENAME like :scopeName";
private static final String SCOPE_NAME = "scopeName";
private static final String SUCCESS = "success";
private static final String SUB_SCOPENAME = "subScopename";
@@ -141,8 +149,18 @@ public class PolicyManagerServlet extends HttpServlet {
private static String testUserId = null;
private enum Mode {
- LIST, RENAME, COPY, DELETE, EDITFILE, ADDFOLDER, DESCRIBEPOLICYFILE, VIEWPOLICY, ADDSUBSCOPE, SWITCHVERSION,
- EXPORT, SEARCHLIST
+ LIST,
+ RENAME,
+ COPY,
+ DELETE,
+ EDITFILE,
+ ADDFOLDER,
+ DESCRIBEPOLICYFILE,
+ VIEWPOLICY,
+ ADDSUBSCOPE,
+ SWITCHVERSION,
+ EXPORT,
+ SEARCHLIST
}
private static PolicyController policyController;
@@ -173,17 +191,17 @@ public class PolicyManagerServlet extends HttpServlet {
//
// Common initialization
//
- XACMLRest.xacmlInit(servletConfig);
+ XacmlRest.xacmlInit(servletConfig);
// init aes key from prop or env
- PeCryptoUtils.initAesKey(XACMLProperties.getProperty(XACMLRestProperties.PROP_AES_KEY));
+ PeCryptoUtils.initAesKey(XACMLProperties.getProperty(XacmlRestProperties.PROP_AES_KEY));
//
// Initialize ClosedLoop JSON
//
- PolicyManagerServlet.initializeJSONLoad();
+ PolicyManagerServlet.initializeJsonLoad();
}
- private static void initializeJSONLoad() {
- Path closedLoopJsonLocation = Paths.get(XACMLProperties.getProperty(XACMLRestProperties.PROP_ADMIN_CLOSEDLOOP));
+ private static void initializeJsonLoad() {
+ Path closedLoopJsonLocation = Paths.get(XACMLProperties.getProperty(XacmlRestProperties.PROP_ADMIN_CLOSEDLOOP));
String location = closedLoopJsonLocation.toString();
if (!location.endsWith("json")) {
LOGGER.warn("JSONConfig file does not end with extension .json");
@@ -208,7 +226,7 @@ public class PolicyManagerServlet extends HttpServlet {
LOGGER.debug("doPost");
try {
// if request contains multipart-form-data
- if (ServletFileUpload.isMultipartContent(request)) {
+ if (isMultipartContent(request)) {
uploadFile(request, response);
}
// all other post request has json params in body
@@ -224,10 +242,14 @@ public class PolicyManagerServlet extends HttpServlet {
}
}
+ protected boolean isMultipartContent(HttpServletRequest request) {
+ return ServletFileUpload.isMultipartContent(request);
+ }
+
// Set Error Message for Exception
- private void setError(Exception t, HttpServletResponse response) throws IOException {
+ private void setError(Exception exception, HttpServletResponse response) throws IOException {
try {
- JSONObject responseJsonObject = error(t.getMessage());
+ JSONObject responseJsonObject = error(exception.getMessage());
response.setContentType(CONTENTTYPE);
PrintWriter out = response.getWriter();
out.print(responseJsonObject);
@@ -242,20 +264,24 @@ public class PolicyManagerServlet extends HttpServlet {
private void uploadFile(HttpServletRequest request, HttpServletResponse response) throws ServletException {
try {
Map<String, InputStream> files = new HashMap<>();
-
+ String resp = null;
List<FileItem> 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());
- processFormFile(request, item);
+ resp = processFormFile(request, item, response);
}
}
- JSONObject responseJsonObject;
- responseJsonObject = this.success();
response.setContentType(CONTENTTYPE);
PrintWriter out = response.getWriter();
+ JSONObject responseJsonObject;
+ if (!StringUtils.isBlank(resp)) {
+ responseJsonObject = this.error("Import Issue " + resp);
+ } else {
+ responseJsonObject = this.success();
+ }
out.print(responseJsonObject);
out.flush();
} catch (Exception e) {
@@ -264,23 +290,35 @@ public class PolicyManagerServlet extends HttpServlet {
}
}
- private void processFormFile(HttpServletRequest request, FileItem item) {
+ private String processFormFile(HttpServletRequest request, FileItem item, HttpServletResponse response) {
String newFile;
- if (item.getName().endsWith(".xls") && item.getSize() <= PolicyController.getFileSizeLimit()) {
+ String outPutResp = null;
+ if (item.getName().endsWith(".xls") && item.getSize() <= getFileSizeLimit()) {
File file = new File(item.getName());
try (OutputStream outputStream = new FileOutputStream(file)) {
IOUtils.copy(item.getInputStream(), outputStream);
newFile = file.toString();
PolicyExportAndImportController importController = new PolicyExportAndImportController();
- importController.importRepositoryFile(newFile, request);
+ return importController.importRepositoryFile(newFile, request);
} catch (Exception e) {
LOGGER.error("Upload error : " + e);
}
} else if (!item.getName().endsWith(".xls")) {
- LOGGER.error("Non .xls filetype uploaded: " + item.getName());
+ outPutResp = "Non .xls filetype uploaded: " + item.getName();
+ LOGGER.error(outPutResp);
} else { // uploaded file size is greater than allowed
- LOGGER.error("Upload file size limit exceeded! File size (Bytes) is: " + item.getSize());
+ outPutResp = "Upload file size limit exceeded! File size (Bytes) is: " + item.getSize();
+ LOGGER.error(outPutResp);
}
+ return outPutResp;
+ }
+
+ protected long copyStream(InputStream inputStream, OutputStream outputStream) throws IOException {
+ return IOUtils.copy(inputStream, outputStream);
+ }
+
+ protected long getFileSizeLimit() {
+ return PolicyController.getFileSizeLimit();
}
// File Operation Functionality
@@ -299,17 +337,17 @@ public class PolicyManagerServlet extends HttpServlet {
return;
}
try {
- JSONObject jObj = new JSONObject(sb.toString());
- JSONObject params = jObj.getJSONObject("params");
+ JSONObject jsonObject = new JSONObject(sb.toString());
+ JSONObject params = jsonObject.getJSONObject("params");
Mode mode = Mode.valueOf(params.getString("mode"));
- String userId = UserUtils.getUserSession(request).getOrgUserId();
+ String userId = getUserSession(request).getOrgUserId();
LOGGER.info(
- "****************************************Logging UserID while doing actions on Editor tab*******************************************");
+ "********************Logging UserID while doing actions on Editor tab****************************");
LOGGER.info(
"UserId: " + userId + "Action Mode: " + mode.toString() + "Action Params: " + params.toString());
LOGGER.info(
- "***********************************************************************************************************************************");
+ "************************************************************************************************");
responseJsonObject = operateBasedOnMode(mode, params, request);
} catch (Exception e) {
LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Exception Occured While Processing Json" + e);
@@ -318,6 +356,10 @@ public class PolicyManagerServlet extends HttpServlet {
setResponse(response, responseJsonObject);
}
+ protected User getUserSession(HttpServletRequest request) {
+ return UserUtils.getUserSession(request);
+ }
+
private void setResponse(HttpServletResponse response, JSONObject responseJsonObject) {
response.setContentType(CONTENTTYPE);
try (PrintWriter out = response.getWriter()) {
@@ -371,7 +413,6 @@ public class PolicyManagerServlet extends HttpServlet {
}
private JSONObject searchPolicyList(JSONObject params, HttpServletRequest request) {
- List<Object> policyData = new ArrayList<>();
JSONArray policyList = null;
if (params.has("policyList")) {
policyList = (JSONArray) params.get("policyList");
@@ -379,9 +420,9 @@ public class PolicyManagerServlet extends HttpServlet {
PolicyController controller = getPolicyControllerInstance();
List<JSONObject> resultList = new ArrayList<>();
try {
- if (!lookupPolicyData(request, policyData, policyList, controller, resultList))
+ if (!lookupPolicyData(request, new ArrayList<>(), policyList, controller, resultList)) {
return error("No Scopes has been Assigned to the User. Please, Contact Super-Admin");
-
+ }
} catch (Exception e) {
LOGGER.error(
"Exception occured while reading policy Data from Policy Version table for Policy Search Data" + e);
@@ -392,13 +433,11 @@ public class PolicyManagerServlet extends HttpServlet {
private boolean lookupPolicyData(HttpServletRequest request, List<Object> policyData, JSONArray policyList,
PolicyController controller, List<JSONObject> resultList) {
- List<String> roles;
- Set<String> scopes;// Get the Login Id of the User from Request
- String userId = UserUtils.getUserSession(request).getOrgUserId();
+ String userId = getUserSession(request).getOrgUserId();
List<Object> userRoles = controller.getRoles(userId);
- Pair<Set<String>, List<String>> pair = org.onap.policy.utils.UserUtils.checkRoleAndScope(userRoles);
- roles = pair.u;
- scopes = pair.t;
+ Pair<Set<String>, List<String>> pair = checkRoleAndScope(userRoles);
+ List<String> roles = pair.second;
+ Set<String> scopes = pair.first;
if (roles.contains(ADMIN) || roles.contains(EDITOR) || roles.contains(GUEST)) {
if (scopes.isEmpty()) {
return false;
@@ -415,12 +454,16 @@ public class PolicyManagerServlet extends HttpServlet {
parsePolicyList(resultList, controller, policyName, version);
}
} else {
- getPolicyDataForSUPERRoles(policyData, controller, resultList, roles, scopes);
+ getPolicyDataForSuperRoles(policyData, controller, resultList, roles, scopes);
}
return true;
}
- private void getPolicyDataForSUPERRoles(List<Object> policyData, PolicyController controller,
+ protected Pair<Set<String>, List<String>> checkRoleAndScope(List<Object> userRoles) {
+ return org.onap.policy.utils.UserUtils.checkRoleAndScope(userRoles);
+ }
+
+ private void getPolicyDataForSuperRoles(List<Object> policyData, PolicyController controller,
List<JSONObject> resultList, List<String> roles, Set<String> scopes) {
if (roles.contains(SUPERADMIN) || roles.contains(SUPEREDITOR) || roles.contains(SUPERGUEST)) {
policyData = controller.getData(PolicyVersion.class);
@@ -448,8 +491,8 @@ public class PolicyManagerServlet extends HttpServlet {
}
private void updateResultList(List<Object> policyData, List<JSONObject> resultList) {
- for (Object aPolicyData : policyData) {
- PolicyVersion policy = (PolicyVersion) aPolicyData;
+ for (Object data : policyData) {
+ PolicyVersion policy = (PolicyVersion) data;
JSONObject el = new JSONObject();
el.put(NAME, policy.getPolicyName().replace(File.separator, FORWARD_SLASH));
el.put(DATE, policy.getModifiedDate());
@@ -467,7 +510,8 @@ public class PolicyManagerServlet extends HttpServlet {
if (policyName.contains(BACKSLASH)) {
policyName = policyName.replace(BACKSLASH, ESCAPE_BACKSLASH);
}
- String policyVersionQuery = "From PolicyVersion where policy_name = :policyName and active_version = :version and id >0";
+ String policyVersionQuery =
+ "From PolicyVersion where policy_name = :policyName and active_version = :version and id >0";
SimpleBindings pvParams = new SimpleBindings();
pvParams.put("policyName", policyName);
pvParams.put(VERSION, version);
@@ -489,8 +533,8 @@ public class PolicyManagerServlet extends HttpServlet {
private void addScope(Set<String> scopes, String scope) {
List<Object> scopesList = queryPolicyEditorScopes(scope);
if (!scopesList.isEmpty()) {
- for (Object aScopesList : scopesList) {
- PolicyEditorScopes tempScope = (PolicyEditorScopes) aScopesList;
+ for (Object scopeItem : scopesList) {
+ PolicyEditorScopes tempScope = (PolicyEditorScopes) scopeItem;
scopes.add(tempScope.getScopeName());
}
}
@@ -501,7 +545,7 @@ public class PolicyManagerServlet extends HttpServlet {
String path = params.getString("path");
String userId = null;
try {
- userId = UserUtils.getUserSession(request).getOrgUserId();
+ userId = getUserSession(request).getOrgUserId();
} catch (Exception e) {
LOGGER.error("Exception Occured while reading userid from cookie" + e);
}
@@ -524,11 +568,11 @@ public class PolicyManagerServlet extends HttpServlet {
return error("The Version shouldn't be greater than Highest Value");
}
activePolicy = policyName + "." + activeVersion + ".xml";
- String[] splitDBCheckName = modifyPolicyName(activePolicy);
+ String[] splitDbCheckName = modifyPolicyName(activePolicy);
String peQuery = "FROM PolicyEntity where policyName = :splitDBCheckName_1 and scope = :splitDBCheckName_0";
SimpleBindings policyParams = new SimpleBindings();
- policyParams.put("splitDBCheckName_1", splitDBCheckName[1]);
- policyParams.put("splitDBCheckName_0", splitDBCheckName[0]);
+ policyParams.put("splitDBCheckName_1", splitDbCheckName[1]);
+ policyParams.put("splitDBCheckName_0", splitDbCheckName[0]);
List<Object> policyEntity = controller.getDataByQuery(peQuery, policyParams);
PolicyEntity pentity = (PolicyEntity) policyEntity.get(0);
if (pentity.isDeleted()) {
@@ -541,8 +585,8 @@ public class PolicyManagerServlet extends HttpServlet {
if (policyName.contains(BACKSLASH)) {
policyName = policyName.replace(File.separator, BACKSLASH);
}
- policyName = splitDBCheckName[0].replace(".", File.separator) + File.separator + policyName;
- String watchPolicyName = policyName;
+ policyName = splitDbCheckName[0].replace(".", File.separator) + File.separator + policyName;
+ final String watchPolicyName = policyName;
if (policyName.contains(FORWARD_SLASH)) {
policyName = policyName.replace(FORWARD_SLASH, File.separator);
}
@@ -564,7 +608,6 @@ public class PolicyManagerServlet extends HttpServlet {
// Describe Policy
private JSONObject describePolicy(JSONObject params) throws ServletException {
- JSONObject object;
String path = params.getString("path");
String policyName;
if (path.startsWith(FORWARD_SLASH)) {
@@ -582,13 +625,12 @@ public class PolicyManagerServlet extends HttpServlet {
} else if (path.contains(DECISION2)) {
path = path.replace(DECISION, DECISION1);
}
- PolicyController controller = getPolicyControllerInstance();
String[] split = path.split(":");
String query = "FROM PolicyEntity where policyName = :split_1 and scope = :split_0";
SimpleBindings peParams = new SimpleBindings();
peParams.put(SPLIT_1, split[1]);
peParams.put(SPLIT_0, split[0]);
- List<Object> queryData = getDataByQueryFromController(controller, query, peParams);
+ List<Object> queryData = getDataByQueryFromController(getPolicyControllerInstance(), query, peParams);
if (queryData.isEmpty()) {
return error("Error Occured while Describing the Policy - query is empty");
}
@@ -606,7 +648,7 @@ public class PolicyManagerServlet extends HttpServlet {
} catch (IOException e) {
LOGGER.error("Exception Occured while Describing the Policy" + e);
}
- object = HumanPolicyComponent.DescribePolicy(temp);
+ JSONObject object = HumanPolicyComponent.DescribePolicy(temp);
try {
Files.delete(temp.toPath());
} catch (IOException e) {
@@ -626,14 +668,13 @@ public class PolicyManagerServlet extends HttpServlet {
}
private JSONObject processPolicyList(JSONObject params, HttpServletRequest request) throws ServletException {
- PolicyController controller = getPolicyControllerInstance();
// Get the Login Id of the User from Request
String testUserID = getTestUserId();
- String userId = testUserID != null ? testUserID : UserUtils.getUserSession(request).getOrgUserId();
- List<Object> userRoles = controller.getRoles(userId);
- Pair<Set<String>, List<String>> pair = org.onap.policy.utils.UserUtils.checkRoleAndScope(userRoles);
- List<String> roles = pair.u;
- Set<String> scopes = pair.t;
+ String userId = testUserID != null ? testUserID : getUserSession(request).getOrgUserId();
+ List<Object> userRoles = getPolicyControllerInstance().getRoles(userId);
+ Pair<Set<String>, List<String>> pair = checkRoleAndScope(userRoles);
+ List<String> roles = pair.second;
+ Set<String> scopes = pair.first;
Map<String, String> roleByScope = org.onap.policy.utils.UserUtils.getRoleByScope(userRoles);
List<JSONObject> resultList = new ArrayList<>();
@@ -672,39 +713,37 @@ public class PolicyManagerServlet extends HttpServlet {
Map<String, String> roleByScope) {
if (roles.contains(SUPERADMIN) || roles.contains(SUPEREDITOR) || roles.contains(SUPERGUEST)) {
List<Object> scopesList = queryPolicyEditorScopes(null);
- scopesList.stream()
- .map(list -> (PolicyEditorScopes) list)
- .filter(scope -> !(scope.getScopeName().contains(File.separator))
- && !scopes.contains(scope.getScopeName()))
- .forEach(scope -> {
- JSONObject el = new JSONObject();
- el.put(NAME, scope.getScopeName());
- el.put(DATE, scope.getModifiedDate());
- el.put(SIZE, "");
- el.put(TYPE, "dir");
- el.put(CREATED_BY, scope.getUserCreatedBy().getUserName());
- el.put(MODIFIED_BY, scope.getUserModifiedBy().getUserName());
- el.put(ROLETYPE, roleByScope.get(ALLSCOPES));
- resultList.add(el);
- });
+ scopesList.stream().map(list -> (PolicyEditorScopes) list).filter(
+ scope -> !(scope.getScopeName().contains(File.separator)) && !scopes.contains(scope.getScopeName()))
+ .forEach(scope -> {
+ JSONObject el = new JSONObject();
+ el.put(NAME, scope.getScopeName());
+ el.put(DATE, scope.getModifiedDate());
+ el.put(SIZE, "");
+ el.put(TYPE, "dir");
+ el.put(CREATED_BY, scope.getUserCreatedBy().getUserName());
+ el.put(MODIFIED_BY, scope.getUserModifiedBy().getUserName());
+ el.put(ROLETYPE, roleByScope.get(ALLSCOPES));
+ resultList.add(el);
+ });
}
if (roles.contains(ADMIN) || roles.contains(EDITOR) || roles.contains(GUEST)) {
- scopes.stream().map(this::queryPolicyEditorScopes)
- .filter(scopesList -> !scopesList.isEmpty())
- .forEach(scopesList -> {
- JSONObject el = new JSONObject();
- PolicyEditorScopes scopeById = (PolicyEditorScopes) scopesList.get(0);
- el.put(NAME, scopeById.getScopeName());
- el.put(DATE, scopeById.getModifiedDate());
- el.put(SIZE, "");
- el.put(TYPE, "dir");
- el.put(CREATED_BY, scopeById.getUserCreatedBy().getUserName());
- el.put(MODIFIED_BY, scopeById.getUserModifiedBy().getUserName());
- if ((resultList).stream().noneMatch(item -> item.get("name").equals(scopeById.getScopeName()))) {
- el.put(ROLETYPE, roleByScope.get(scopeById.getScopeName()));
- resultList.add(el);
- }
- });
+ scopes.stream().map(this::queryPolicyEditorScopes).filter(scopesList -> !scopesList.isEmpty())
+ .forEach(scopesList -> {
+ JSONObject el = new JSONObject();
+ PolicyEditorScopes scopeById = (PolicyEditorScopes) scopesList.get(0);
+ el.put(NAME, scopeById.getScopeName());
+ el.put(DATE, scopeById.getModifiedDate());
+ el.put(SIZE, "");
+ el.put(TYPE, "dir");
+ el.put(CREATED_BY, scopeById.getUserCreatedBy().getUserName());
+ el.put(MODIFIED_BY, scopeById.getUserModifiedBy().getUserName());
+ if ((resultList).stream()
+ .noneMatch(item -> item.get("name").equals(scopeById.getScopeName()))) {
+ el.put(ROLETYPE, roleByScope.get(scopeById.getScopeName()));
+ resultList.add(el);
+ }
+ });
}
}
@@ -724,7 +763,6 @@ public class PolicyManagerServlet extends HttpServlet {
// Get Active Policy List based on Scope Selection from Policy Version table
private void activePolicyList(String inScopeName, List<JSONObject> resultList, List<String> roles,
Set<String> scopes, Map<String, String> roleByScope) {
- PolicyController controller = getPolicyControllerInstance();
String scopeName = inScopeName;
if (scopeName.contains(FORWARD_SLASH)) {
scopeName = scopeName.replace(FORWARD_SLASH, File.separator);
@@ -737,20 +775,20 @@ public class PolicyManagerServlet extends HttpServlet {
SimpleBindings params = new SimpleBindings();
params.put(SCOPE_NAME, scopeName + "%");
- List<Object> activePolicies = getDataByQueryFromController(controller, query, params);
- List<Object> scopesList = getDataByQueryFromController(controller,
- FROM_POLICY_EDITOR_SCOPES_WHERE_SCOPENAME_LIKE_SCOPE_NAME, params);
+ List<Object> activePolicies = getDataByQueryFromController(getPolicyControllerInstance(), query, params);
+ List<Object> scopesList = getDataByQueryFromController(getPolicyControllerInstance(),
+ FROM_POLICY_EDITOR_SCOPES_WHERE_SCOPENAME_LIKE_SCOPE_NAME, params);
for (Object list : scopesList) {
scopeName = checkScope(resultList, scopeName, (PolicyEditorScopes) list, roleByScope);
}
for (Object list : activePolicies) {
PolicyVersion policy = (PolicyVersion) list;
- String scopeNameValue = policy.getPolicyName().substring(0,
- policy.getPolicyName().lastIndexOf(File.separator));
+ String scopeNameValue =
+ policy.getPolicyName().substring(0, policy.getPolicyName().lastIndexOf(File.separator));
if (roles.contains(SUPERADMIN) || roles.contains(SUPEREDITOR) || roles.contains(SUPERGUEST)) {
String scopeNameCheck =
- scopeName.contains(ESCAPE_BACKSLASH) ? scopeName.replace(ESCAPE_BACKSLASH, File.separator) :
- scopeName;
+ scopeName.contains(ESCAPE_BACKSLASH) ? scopeName.replace(ESCAPE_BACKSLASH, File.separator)
+ : scopeName;
if (!scopeNameValue.equals(scopeNameCheck)) {
continue;
}
@@ -762,8 +800,8 @@ public class PolicyManagerServlet extends HttpServlet {
el.put(TYPE, "file");
el.put(CREATED_BY, getUserName(policy.getCreatedBy()));
el.put(MODIFIED_BY, getUserName(policy.getModifiedBy()));
- String roleType = Strings.isNullOrEmpty(roleByScope.get(scopeNameValue)) ?
- roleByScope.get(ALLSCOPES) : roleByScope.get(scopeNameValue);
+ String roleType = Strings.isNullOrEmpty(roleByScope.get(scopeNameValue)) ? roleByScope.get(ALLSCOPES)
+ : roleByScope.get(scopeNameValue);
el.put(ROLETYPE, roleType);
resultList.add(el);
} else if (!scopes.isEmpty() && scopes.contains(scopeNameValue)) {
@@ -781,7 +819,7 @@ public class PolicyManagerServlet extends HttpServlet {
}
private List<Object> getDataByQueryFromController(final PolicyController controller, final String query,
- final SimpleBindings params) {
+ final SimpleBindings params) {
final List<Object> activePolicies;
if (PolicyController.isjUnit()) {
activePolicies = controller.getDataByQuery(query, null);
@@ -828,8 +866,8 @@ public class PolicyManagerServlet extends HttpServlet {
}
private String getUserName(String loginId) {
- PolicyController controller = getPolicyControllerInstance();
- UserInfo userInfo = (UserInfo) controller.getEntityItem(UserInfo.class, "userLoginId", loginId);
+ UserInfo userInfo = (UserInfo) getPolicyControllerInstance().getEntityItem(UserInfo.class, "userLoginId",
+ loginId);
if (userInfo == null) {
return SUPERADMIN;
}
@@ -848,9 +886,9 @@ public class PolicyManagerServlet extends HttpServlet {
private JSONObject handlePolicyRename(JSONObject params, HttpServletRequest request) throws ServletException {
boolean isActive = false;
- List<String> policyActiveInPDP = new ArrayList<>();
- Set<String> scopeOfPolicyActiveInPDP = new HashSet<>();
- String userId = UserUtils.getUserSession(request).getOrgUserId();
+ List<String> policyActiveInPdp = new ArrayList<>();
+ Set<String> scopeOfPolicyActiveInPdp = new HashSet<>();
+ String userId = getUserSession(request).getOrgUserId();
String oldPath = params.getString("path");
String newPath = params.getString("newPath");
oldPath = oldPath.substring(oldPath.indexOf('/') + 1);
@@ -858,8 +896,8 @@ public class PolicyManagerServlet extends HttpServlet {
String checkValidation;
if (oldPath.endsWith(".xml")) {
checkValidation = newPath.replace(".xml", "");
- checkValidation = checkValidation.substring(checkValidation.indexOf('_') + 1,
- checkValidation.lastIndexOf('.'));
+ checkValidation =
+ checkValidation.substring(checkValidation.indexOf('_') + 1, checkValidation.lastIndexOf('.'));
checkValidation = checkValidation.substring(checkValidation.lastIndexOf(FORWARD_SLASH) + 1);
if (!PolicyUtils.policySpecialCharValidator(checkValidation).contains(SUCCESS)) {
return error("Policy Rename Failed. The Name contains special characters.");
@@ -888,7 +926,8 @@ public class PolicyManagerServlet extends HttpServlet {
SimpleBindings pvParams = new SimpleBindings();
pvParams.put(SCOPE_NAME, scopeName + "%");
List<Object> activePolicies = controller.getDataByQuery(query, pvParams);
- List<Object> scopesList = controller.getDataByQuery(FROM_POLICY_EDITOR_SCOPES_WHERE_SCOPENAME_LIKE_SCOPE_NAME, pvParams);
+ List<Object> scopesList =
+ controller.getDataByQuery(FROM_POLICY_EDITOR_SCOPES_WHERE_SCOPENAME_LIKE_SCOPE_NAME, pvParams);
for (Object object : activePolicies) {
PolicyVersion activeVersion = (PolicyVersion) object;
String policyOldPath = activeVersion.getPolicyName().replace(File.separator, FORWARD_SLASH) + "."
@@ -897,19 +936,19 @@ public class PolicyManagerServlet extends HttpServlet {
JSONObject result = policyRename(policyOldPath, policyNewPath, userId);
if (!(Boolean) (result.getJSONObject("result").get(SUCCESS))) {
isActive = true;
- policyActiveInPDP.add(policyOldPath);
+ policyActiveInPdp.add(policyOldPath);
String scope = policyOldPath.substring(0, policyOldPath.lastIndexOf('/'));
- scopeOfPolicyActiveInPDP.add(scope.replace(FORWARD_SLASH, File.separator));
+ scopeOfPolicyActiveInPdp.add(scope.replace(FORWARD_SLASH, File.separator));
}
}
- boolean rename = activePolicies.size() != policyActiveInPDP.size();
- if (policyActiveInPDP.isEmpty()) {
+ boolean rename = activePolicies.size() != policyActiveInPdp.size();
+ if (policyActiveInPdp.isEmpty()) {
renameScope(scopesList, scopeName, newScopeName, controller);
} else if (rename) {
renameScope(scopesList, scopeName, newScopeName, controller);
UserInfo userInfo = new UserInfo();
userInfo.setUserLoginId(userId);
- scopeOfPolicyActiveInPDP.forEach(scope -> {
+ scopeOfPolicyActiveInPdp.forEach(scope -> {
PolicyEditorScopes editorScopeEntity = new PolicyEditorScopes();
editorScopeEntity.setScopeName(scope.replace(BACKSLASH, BACKSLASH_8TIMES));
editorScopeEntity.setUserCreatedBy(userInfo);
@@ -919,7 +958,7 @@ public class PolicyManagerServlet extends HttpServlet {
}
if (isActive) {
return error("The Following policies rename failed. Since they are active in PDP Groups"
- + policyActiveInPDP);
+ + policyActiveInPdp);
}
}
return success();
@@ -955,10 +994,11 @@ public class PolicyManagerServlet extends HttpServlet {
String newpolicyName = newPath.replace("/", ".");
String[] newPolicySplit = modifyPolicyName(newPath);
- String[] oldPolicySplit = modifyPolicyName(oldPath);
+ final String[] oldPolicySplit = modifyPolicyName(oldPath);
// Check PolicyEntity table with newPolicy Name
- String policyEntityquery = "FROM PolicyEntity where policyName = :newPolicySplit_1 and scope = :newPolicySplit_0";
+ String policyEntityquery =
+ "FROM PolicyEntity where policyName = :newPolicySplit_1 and scope = :newPolicySplit_0";
SimpleBindings policyParams = new SimpleBindings();
policyParams.put("newPolicySplit_1", newPolicySplit[1]);
policyParams.put("newPolicySplit_0", newPolicySplit[0]);
@@ -969,15 +1009,15 @@ public class PolicyManagerServlet extends HttpServlet {
// 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";
+ String oldPolicyEntityQuery =
+ "FROM PolicyEntity where policyName like :policyEntityCheck and scope = " + ":oldPolicySplit_0";
SimpleBindings params = new SimpleBindings();
params.put("policyEntityCheck", policyEntityCheck + "%");
params.put("oldPolicySplit_0", oldPolicySplit[0]);
List<Object> oldEntityData = controller.getDataByQuery(oldPolicyEntityQuery, params);
if (oldEntityData.isEmpty()) {
return error(
- "Policy rename failed due to policy not able to retrieve from database. Please, contact super-admin.");
+ "Policy rename failed due to policy not able to retrieve from database. Contact super-admin.");
}
StringBuilder groupQuery = new StringBuilder();
@@ -1042,10 +1082,10 @@ public class PolicyManagerServlet extends HttpServlet {
String oldPolicyNameWithoutExtension = removeOldPolicyExtension;
String newPolicyNameWithoutExtension = removeNewPolicyExtension;
if (removeOldPolicyExtension.endsWith(".xml")) {
- oldPolicyNameWithoutExtension = oldPolicyNameWithoutExtension.substring(0,
- oldPolicyNameWithoutExtension.indexOf('.'));
- newPolicyNameWithoutExtension = newPolicyNameWithoutExtension.substring(0,
- newPolicyNameWithoutExtension.indexOf('.'));
+ oldPolicyNameWithoutExtension =
+ oldPolicyNameWithoutExtension.substring(0, oldPolicyNameWithoutExtension.indexOf('.'));
+ newPolicyNameWithoutExtension =
+ newPolicyNameWithoutExtension.substring(0, newPolicyNameWithoutExtension.indexOf('.'));
}
entity.setPolicyName(
entity.getPolicyName().replace(oldPolicyNameWithoutExtension, newPolicyNameWithoutExtension));
@@ -1065,8 +1105,8 @@ public class PolicyManagerServlet extends HttpServlet {
newConfigurationName = configEntity.getConfigurationName();
File file = new File(PolicyController.getConfigHome() + File.separator + oldConfigurationName);
if (file.exists()) {
- File renameFile = new File(
- PolicyController.getConfigHome() + File.separator + newConfigurationName);
+ File renameFile =
+ new File(PolicyController.getConfigHome() + File.separator + newConfigurationName);
file.renameTo(renameFile);
}
} else if (newPolicyName.contains(ACTION2)) {
@@ -1078,17 +1118,17 @@ public class PolicyManagerServlet extends HttpServlet {
newConfigurationName = actionEntity.getActionBodyName();
File file = new File(PolicyController.getActionHome() + File.separator + oldConfigurationName);
if (file.exists()) {
- File renameFile = new File(
- PolicyController.getActionHome() + File.separator + newConfigurationName);
+ File renameFile =
+ new File(PolicyController.getActionHome() + File.separator + newConfigurationName);
file.renameTo(renameFile);
}
}
controller.updateData(entity);
PolicyRestController restController = new PolicyRestController();
- restController.notifyOtherPAPSToUpdateConfigurations("rename", newConfigurationName, oldConfigurationName);
- PolicyVersion versionEntity = (PolicyVersion) controller.getEntityItem(PolicyVersion.class, "policyName",
- oldPolicyName);
+ restController.notifyOtherPapsToUpdateConfigurations("rename", newConfigurationName, oldConfigurationName);
+ PolicyVersion versionEntity =
+ (PolicyVersion) controller.getEntityItem(PolicyVersion.class, "policyName", oldPolicyName);
versionEntity.setPolicyName(policyName);
versionEntity.setModifiedBy(userId);
controller.updateData(versionEntity);
@@ -1136,8 +1176,8 @@ public class PolicyManagerServlet extends HttpServlet {
.getEntityItem(ConfigurationDataEntity.class, "configurationName", queryEntityName);
cloneEntity.setConfigurationData(configEntiy);
newConfigurationName = configEntiy.getConfigurationName();
- try (FileWriter fw = new FileWriter(
- PolicyController.getConfigHome() + File.separator + newConfigurationName);
+ try (FileWriter fw =
+ new FileWriter(PolicyController.getConfigHome() + File.separator + newConfigurationName);
BufferedWriter bw = new BufferedWriter(fw)) {
bw.write(configEntiy.getConfigBody());
} catch (IOException e) {
@@ -1158,8 +1198,8 @@ public class PolicyManagerServlet extends HttpServlet {
"actionBodyName", queryEntityName);
cloneEntity.setActionBodyEntity(actionEntiy);
newConfigurationName = actionEntiy.getActionBodyName();
- try (FileWriter fw = new FileWriter(
- PolicyController.getActionHome() + File.separator + newConfigurationName);
+ try (FileWriter fw =
+ new FileWriter(PolicyController.getActionHome() + File.separator + newConfigurationName);
BufferedWriter bw = new BufferedWriter(fw)) {
bw.write(actionEntiy.getActionBody());
} catch (IOException e) {
@@ -1175,13 +1215,13 @@ public class PolicyManagerServlet extends HttpServlet {
// Notify others paps regarding clone policy.
PolicyRestController restController = new PolicyRestController();
- restController.notifyOtherPAPSToUpdateConfigurations("clonePolicy", newConfigurationName, null);
+ restController.notifyOtherPapsToUpdateConfigurations("clonePolicy", newConfigurationName, null);
}
// Clone the Policy
private JSONObject copy(JSONObject params, HttpServletRequest request) throws ServletException {
try {
- String userId = UserUtils.getUserSession(request).getOrgUserId();
+ String userId = getUserSession(request).getOrgUserId();
String oldPath = params.getString("path");
String newPath = params.getString("newPath");
oldPath = oldPath.substring(oldPath.indexOf('/') + 1);
@@ -1194,8 +1234,6 @@ public class PolicyManagerServlet extends HttpServlet {
String newPolicyName = newPath.replace(FORWARD_SLASH, ".");
- String originalPolicyName = oldPath.replace(FORWARD_SLASH, ".");
-
String newPolicyCheck = newPolicyName;
if (newPolicyCheck.contains(CONFIG2)) {
newPolicyCheck = newPolicyCheck.replace(CONFIG, CONFIG1);
@@ -1210,13 +1248,15 @@ public class PolicyManagerServlet extends HttpServlet {
String[] newPolicySplit = newPolicyCheck.split(":");
String checkValidation = newPolicySplit[1].replace(".xml", "");
- checkValidation = checkValidation.substring(checkValidation.indexOf('_') + 1,
- checkValidation.lastIndexOf('.'));
+ checkValidation =
+ checkValidation.substring(checkValidation.indexOf('_') + 1, checkValidation.lastIndexOf('.'));
if (!PolicyUtils.policySpecialCharValidator(checkValidation).contains(SUCCESS)) {
return error("Policy Clone Failed. The Name contains special characters.");
}
- String[] oldPolicySplit = modifyPolicyName(originalPolicyName);
+ String originalPolicyName = oldPath.replace(FORWARD_SLASH, ".");
+
+ final String[] oldPolicySplit = modifyPolicyName(originalPolicyName);
PolicyController controller = getPolicyControllerInstance();
@@ -1224,7 +1264,8 @@ public class PolicyManagerServlet extends HttpServlet {
boolean success = false;
// Check PolicyEntity table with newPolicy Name
- String policyEntityquery = "FROM PolicyEntity where policyName = :newPolicySplit_1 and scope = :newPolicySplit_0";
+ String policyEntityquery =
+ "FROM PolicyEntity where policyName = :newPolicySplit_1 and scope = :newPolicySplit_0";
SimpleBindings policyParams = new SimpleBindings();
policyParams.put("newPolicySplit_1", newPolicySplit[1]);
policyParams.put("newPolicySplit_0", newPolicySplit[0]);
@@ -1272,7 +1313,7 @@ public class PolicyManagerServlet extends HttpServlet {
PolicyEntity policyEntity = null;
String policyNamewithoutExtension;
try {
- String userId = UserUtils.getUserSession(request).getOrgUserId();
+ String userId = getUserSession(request).getOrgUserId();
String deleteVersion = "";
String path = params.getString("path");
LOGGER.debug("delete {}" + path);
@@ -1307,8 +1348,8 @@ public class PolicyManagerServlet extends HttpServlet {
if (!policyEntityObjects.isEmpty()) {
for (Object object : policyEntityObjects) {
policyEntity = (PolicyEntity) object;
- String groupEntityquery = "from PolicyGroupEntity where policyid ='"
- + policyEntity.getPolicyId() + "'";
+ String groupEntityquery =
+ "from PolicyGroupEntity where policyid ='" + policyEntity.getPolicyId() + "'";
SimpleBindings pgeParams = new SimpleBindings();
List<Object> groupobject = controller.getDataByQuery(groupEntityquery, pgeParams);
if (!groupobject.isEmpty()) {
@@ -1316,7 +1357,7 @@ public class PolicyManagerServlet extends HttpServlet {
activePolicyName = policyEntity.getScope() + "." + policyEntity.getPolicyName();
} else {
deleteEntityFromEsAndPolicyEntityTable(controller, restController, policyEntity,
- policyNamewithoutExtension);
+ policyNamewithoutExtension);
}
}
}
@@ -1327,15 +1368,15 @@ public class PolicyManagerServlet extends HttpServlet {
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_POLICY_VERSION_SET_ACTIVE_VERSION + getActivePDPPolicyVersion
- + "' , highest_version='" + getActivePDPPolicyVersion + "' where policy_name ='"
+ String getActivePdpPolicyVersion = activePolicyName.replace(".xml", "");
+ getActivePdpPolicyVersion =
+ getActivePdpPolicyVersion.substring(getActivePdpPolicyVersion.lastIndexOf('.') + 1);
+ String policyVersionQuery = UPDATE_POLICY_VERSION_SET_ACTIVE_VERSION + getActivePdpPolicyVersion
+ + "' , highest_version='" + getActivePdpPolicyVersion + "' where policy_name ='"
+ policyNamewithoutExtension.replace(BACKSLASH, ESCAPE_BACKSLASH) + "' and id >0";
controller.executeQuery(policyVersionQuery);
return error(
- "Policies with Same name has been deleted. Except the Active Policy in PDP. PolicyName: "
+ "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
@@ -1344,12 +1385,13 @@ public class PolicyManagerServlet extends HttpServlet {
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";
+ 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";
SimpleBindings peParams = new SimpleBindings();
peParams.put("currentVersionPolicyName", currentVersionPolicyName);
@@ -1363,7 +1405,8 @@ public class PolicyManagerServlet extends HttpServlet {
return success();
}
- String groupEntityquery = "from PolicyGroupEntity where policyid = :policyEntityId and policyid > 0";
+ String groupEntityquery =
+ "from PolicyGroupEntity where policyid = :policyEntityId and policyid > 0";
SimpleBindings geParams = new SimpleBindings();
geParams.put("policyEntityId", policyEntity.getPolicyId());
List<Object> groupobject = controller.getDataByQuery(groupEntityquery, geParams);
@@ -1374,7 +1417,7 @@ public class PolicyManagerServlet extends HttpServlet {
// Delete the entity from Elastic Search Database
deleteEntityFromEsAndPolicyEntityTable(controller, restController, policyEntity,
- policyNamewithoutExtension);
+ policyNamewithoutExtension);
if (version > 1) {
int highestVersion = 0;
@@ -1414,7 +1457,7 @@ public class PolicyManagerServlet extends HttpServlet {
}
}
} else {
- List<String> activePoliciesInPDP = new ArrayList<>();
+ List<String> activePoliciesInPdp = new ArrayList<>();
if (policyEntityObjects.isEmpty()) {
String policyScopeQuery = "delete PolicyEditorScopes where SCOPENAME like '"
+ path.replace(BACKSLASH, ESCAPE_BACKSLASH) + PERCENT_AND_ID_GT_0;
@@ -1429,7 +1472,7 @@ public class PolicyManagerServlet extends HttpServlet {
List<Object> groupobject = controller.getDataByQuery(groupEntityQuery, geParams);
if (!groupobject.isEmpty()) {
pdpCheck = true;
- activePoliciesInPDP.add(policyEntity.getScope() + "." + policyEntity.getPolicyName());
+ activePoliciesInPdp.add(policyEntity.getScope() + "." + policyEntity.getPolicyName());
} else {
// Delete the entity from Elastic Search Database
String searchFileName = policyEntity.getScope() + "." + policyEntity.getPolicyName();
@@ -1441,13 +1484,13 @@ public class PolicyManagerServlet extends HttpServlet {
Files.deleteIfExists(Paths.get(PolicyController.getConfigHome() + File.separator
+ policyEntity.getConfigurationData().getConfigurationName()));
controller.deleteData(policyEntity.getConfigurationData());
- restController.notifyOtherPAPSToUpdateConfigurations(DELETE, null,
+ restController.notifyOtherPapsToUpdateConfigurations(DELETE, null,
policyEntity.getConfigurationData().getConfigurationName());
} else if (policyNamewithoutExtension.contains(ACTION2)) {
Files.deleteIfExists(Paths.get(PolicyController.getActionHome() + File.separator
+ policyEntity.getActionBodyEntity().getActionBodyName()));
controller.deleteData(policyEntity.getActionBodyEntity());
- restController.notifyOtherPAPSToUpdateConfigurations(DELETE, null,
+ restController.notifyOtherPapsToUpdateConfigurations(DELETE, null,
policyEntity.getActionBodyEntity().getActionBodyName());
}
}
@@ -1464,22 +1507,22 @@ public class PolicyManagerServlet extends HttpServlet {
controller.watchPolicyFunction(entity, path, "DeleteScope");
if (pdpCheck) {
// Add Active Policies List to PolicyVersionTable
- for (String anActivePoliciesInPDP : activePoliciesInPDP) {
- String activePDPPolicyName = anActivePoliciesInPDP.replace(".xml", "");
- int activePDPPolicyVersion = Integer
- .parseInt(activePDPPolicyName.substring(activePDPPolicyName.lastIndexOf('.') + 1));
- activePDPPolicyName = activePDPPolicyName.substring(0, activePDPPolicyName.lastIndexOf('.'))
+ for (String anActivePoliciesInPdp : activePoliciesInPdp) {
+ String activePdpPolicyName = anActivePoliciesInPdp.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);
+ 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);
+ + activePoliciesInPdp);
} else {
String policyScopeQuery = "delete PolicyEditorScopes where SCOPENAME like '"
+ path.replace(BACKSLASH, ESCAPE_BACKSLASH) + PERCENT_AND_ID_GT_0;
@@ -1495,8 +1538,8 @@ public class PolicyManagerServlet extends HttpServlet {
}
private void deleteEntityFromEsAndPolicyEntityTable(final PolicyController controller,
- final PolicyRestController restController, final PolicyEntity policyEntity,
- final String policyNamewithoutExtension) throws IOException {
+ final PolicyRestController restController, final PolicyEntity policyEntity,
+ final String policyNamewithoutExtension) throws IOException {
// Delete the entity from Elastic Search Database
String searchFileName = policyEntity.getScope() + "." + policyEntity.getPolicyName();
restController.deleteElasticData(searchFileName);
@@ -1504,16 +1547,16 @@ public class PolicyManagerServlet extends HttpServlet {
controller.deleteData(policyEntity);
if (policyNamewithoutExtension.contains(CONFIG2)) {
Files.deleteIfExists(Paths.get(PolicyController.getConfigHome() + File.separator
- + policyEntity.getConfigurationData().getConfigurationName()));
+ + policyEntity.getConfigurationData().getConfigurationName()));
controller.deleteData(policyEntity.getConfigurationData());
- restController.notifyOtherPAPSToUpdateConfigurations(DELETE, null,
- policyEntity.getConfigurationData().getConfigurationName());
+ restController.notifyOtherPapsToUpdateConfigurations(DELETE, null,
+ policyEntity.getConfigurationData().getConfigurationName());
} else if (policyNamewithoutExtension.contains(ACTION2)) {
Files.deleteIfExists(Paths.get(PolicyController.getActionHome() + File.separator
- + policyEntity.getActionBodyEntity().getActionBodyName()));
+ + policyEntity.getActionBodyEntity().getActionBodyName()));
controller.deleteData(policyEntity.getActionBodyEntity());
- restController.notifyOtherPAPSToUpdateConfigurations(DELETE, null,
- policyEntity.getActionBodyEntity().getActionBodyName());
+ restController.notifyOtherPapsToUpdateConfigurations(DELETE, null,
+ policyEntity.getActionBodyEntity().getActionBodyName());
}
}
@@ -1521,8 +1564,7 @@ public class PolicyManagerServlet extends HttpServlet {
private JSONObject editFile(JSONObject params) throws ServletException {
// get content
try {
- PolicyController controller = getPolicyControllerInstance();
- String mode = params.getString("mode");
+ final String mode = params.getString("mode");
String path = params.getString("path");
LOGGER.debug("editFile path: {}" + path);
@@ -1538,7 +1580,7 @@ public class PolicyManagerServlet extends HttpServlet {
SimpleBindings peParams = new SimpleBindings();
peParams.put(SPLIT_1, split[1]);
peParams.put(SPLIT_0, split[0]);
- List<Object> queryData = getDataByQueryFromController(controller, query, peParams);
+ List<Object> queryData = getDataByQueryFromController(getPolicyControllerInstance(), query, peParams);
PolicyEntity entity = (PolicyEntity) queryData.get(0);
InputStream stream = new ByteArrayInputStream(entity.getPolicyData().getBytes(StandardCharsets.UTF_8));
@@ -1577,11 +1619,10 @@ public class PolicyManagerServlet extends HttpServlet {
// Add Scopes
private JSONObject addFolder(JSONObject params, HttpServletRequest request) throws ServletException {
- PolicyController controller = getPolicyControllerInstance();
try {
String name = getNameFromParams(params);
String validateName =
- name.contains(File.separator) ? name.substring(name.lastIndexOf(File.separator) + 1) : name;
+ name.contains(File.separator) ? name.substring(name.lastIndexOf(File.separator) + 1) : name;
if (!name.isEmpty()) {
String validate = PolicyUtils.policySpecialCharValidator(validateName);
if (!validate.contains(SUCCESS)) {
@@ -1591,19 +1632,20 @@ public class PolicyManagerServlet extends HttpServlet {
if (name.startsWith(File.separator)) {
name = name.substring(1);
}
- PolicyEditorScopes entity = (PolicyEditorScopes) controller.getEntityItem(PolicyEditorScopes.class,
- SCOPE_NAME, name);
+ PolicyEditorScopes entity =
+ (PolicyEditorScopes) getPolicyControllerInstance().getEntityItem(
+ PolicyEditorScopes.class, SCOPE_NAME, name);
if (entity != null) {
return error("Scope Already Exists");
}
- String userId = UserUtils.getUserSession(request).getOrgUserId();
+ String userId = getUserSession(request).getOrgUserId();
UserInfo userInfo = new UserInfo();
userInfo.setUserLoginId(userId);
PolicyEditorScopes newScope = new PolicyEditorScopes();
newScope.setScopeName(name);
newScope.setUserCreatedBy(userInfo);
newScope.setUserModifiedBy(userInfo);
- controller.saveData(newScope);
+ getPolicyControllerInstance().saveData(newScope);
}
return success();
} catch (Exception e) {
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
index 1fccfda78..34a95d98b 100644
--- 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
@@ -2,16 +2,16 @@
* ============LICENSE_START=======================================================
* ONAP Policy Engine
* ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017, 2019 AT&T Intellectual Property. All rights reserved.
* Modified Copyright (C) 2018 Samsung Electronics Co., Ltd.
* Modifications Copyright (C) 2019 Bell Canada
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -48,20 +48,26 @@ import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
/**
- * Send policy notification mail depending on the mode for every policy being watched
+ * Send policy notification mail depending on the mode for every policy being watched.
*/
@Configurable
-public class PolicyNotificationMail{
+public class PolicyNotificationMail {
private static final String POLICY_WATCHING_MESSAGE = "The Policy Which you are watching in ";
- private static final String EMAIL_MESSAGE_POSTSCRIPT = "Policy Notification System (please don't respond to this email)";
+ private static final String EMAIL_MESSAGE_POSTSCRIPT =
+ "Policy Notification System (please don't respond to this email)";
private static final String ACTIVE_VERSION = "Active Version : ";
private static final String SCOPE_POLICY_NAME = "Scope + Policy Name : ";
private static final String DELETED_TIME = "Deleted Time : ";
private static final String DELETED_BY = "Deleted By : ";
- private static Logger policyLogger = FlexLogger.getLogger(PolicyNotificationMail.class);
+ private static Logger policyLogger = FlexLogger.getLogger(PolicyNotificationMail.class);
+ /**
+ * javaMailSenderImpl.
+ *
+ * @return JavaMailSenderImpl object
+ */
@Bean
- public JavaMailSenderImpl javaMailSenderImpl(){
+ public JavaMailSenderImpl javaMailSenderImpl() {
JavaMailSenderImpl mailSender = new JavaMailSenderImpl();
mailSender.setHost(PolicyController.getSmtpHost());
mailSender.setPort(Integer.parseInt(PolicyController.getSmtpPort()));
@@ -79,51 +85,71 @@ public class PolicyNotificationMail{
* Depending on the mode of operation on the policy, compose the subject and message.
* Invoke another internal method to actual send the mail. If the watch list is empty , then
* this method returns without sending notification mail
+ *
* @param entityItem Database item from which policy name could be extracted
* @param policyName Name of the policy for which notification is to be sent
* @param mode kind of operation done on the policy
* @param policyNotificationDao database access object for policy
*/
- public void sendMail(PolicyVersion entityItem, String policyName, String mode, CommonClassDao policyNotificationDao) {
+ public void sendMail(PolicyVersion entityItem, String policyName, String mode,
+ CommonClassDao policyNotificationDao) {
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 = POLICY_WATCHING_MESSAGE + 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' + EMAIL_MESSAGE_POSTSCRIPT;
+ if ("EditPolicy".equalsIgnoreCase(mode)) {
+ subject = "Policy has been Updated : " + entityItem.getPolicyName();
+ message = POLICY_WATCHING_MESSAGE + 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'
+ + EMAIL_MESSAGE_POSTSCRIPT;
}
- if("Rename".equalsIgnoreCase(mode)){
- subject = "Policy has been Renamed : "+entityItem.getPolicyName();
- message = POLICY_WATCHING_MESSAGE + 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' + EMAIL_MESSAGE_POSTSCRIPT;
+ if ("Rename".equalsIgnoreCase(mode)) {
+ subject = "Policy has been Renamed : " + entityItem.getPolicyName();
+ message = POLICY_WATCHING_MESSAGE + 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'
+ + EMAIL_MESSAGE_POSTSCRIPT;
}
- if("DeleteAll".equalsIgnoreCase(mode)){
- subject = "Policy has been Deleted : "+entityItem.getPolicyName();
- message = POLICY_WATCHING_MESSAGE + 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' + EMAIL_MESSAGE_POSTSCRIPT;
+ if ("DeleteAll".equalsIgnoreCase(mode)) {
+ subject = "Policy has been Deleted : " + entityItem.getPolicyName();
+ message = POLICY_WATCHING_MESSAGE + 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' + EMAIL_MESSAGE_POSTSCRIPT;
}
- if("DeleteOne".equalsIgnoreCase(mode)){
- subject = "Policy has been Deleted : "+entityItem.getPolicyName();
- message = POLICY_WATCHING_MESSAGE + 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' + EMAIL_MESSAGE_POSTSCRIPT;
+ if ("DeleteOne".equalsIgnoreCase(mode)) {
+ subject = "Policy has been Deleted : " + entityItem.getPolicyName();
+ message = POLICY_WATCHING_MESSAGE + 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' + EMAIL_MESSAGE_POSTSCRIPT;
}
- 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' + EMAIL_MESSAGE_POSTSCRIPT;
+ 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' + EMAIL_MESSAGE_POSTSCRIPT;
}
- if("SwitchVersion".equalsIgnoreCase(mode)){
- subject = "Policy has been SwitchedVersion : "+entityItem.getPolicyName();
- message = POLICY_WATCHING_MESSAGE + 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' + EMAIL_MESSAGE_POSTSCRIPT;
+ if ("SwitchVersion".equalsIgnoreCase(mode)) {
+ subject = "Policy has been SwitchedVersion : " + entityItem.getPolicyName();
+ message = POLICY_WATCHING_MESSAGE + 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'
+ + EMAIL_MESSAGE_POSTSCRIPT;
}
- if("Move".equalsIgnoreCase(mode)){
- subject = "Policy has been Moved to Other Scope : "+entityItem.getPolicyName();
- message = POLICY_WATCHING_MESSAGE + 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' + EMAIL_MESSAGE_POSTSCRIPT;
+ if ("Move".equalsIgnoreCase(mode)) {
+ subject = "Policy has been Moved to Other Scope : " + entityItem.getPolicyName();
+ message = POLICY_WATCHING_MESSAGE + 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' + EMAIL_MESSAGE_POSTSCRIPT;
}
String checkPolicyName = findCheckPolicyName(policyName);
@@ -147,7 +173,7 @@ public class PolicyNotificationMail{
if (watchList == null || watchList.isEmpty()) {
policyLogger
- .debug("List of policy being watched is either null or empty, hence return without sending mail");
+ .debug("List of policy being watched is either null or empty, hence return without sending mail");
watchList = new ArrayList<>();
}
return watchList;
@@ -155,11 +181,11 @@ public class PolicyNotificationMail{
private String findPolicyFileName(PolicyVersion entityItem) {
String policyFileName = entityItem.getPolicyName();
- if(policyFileName.contains("/")){
+ if (policyFileName.contains("/")) {
policyFileName = policyFileName.substring(0, policyFileName.indexOf('/'));
policyFileName = policyFileName.replace("/", File.separator);
}
- if(policyFileName.contains("\\")){
+ if (policyFileName.contains("\\")) {
policyFileName = policyFileName.substring(0, policyFileName.indexOf('\\'));
policyFileName = policyFileName.replace("\\", "\\\\");
}
@@ -170,7 +196,7 @@ public class PolicyNotificationMail{
private String findCheckPolicyName(String policyName) {
String checkPolicyName = policyName;
- if(checkPolicyName.endsWith(".xml") || checkPolicyName.contains(".")){
+ if (checkPolicyName.endsWith(".xml") || checkPolicyName.contains(".")) {
checkPolicyName = checkPolicyName.substring(0, checkPolicyName.indexOf('.'));
}
return checkPolicyName;
@@ -178,29 +204,31 @@ public class PolicyNotificationMail{
/**
* For every policy being watched and when the policy name is one of the Config_, Action_ or Decision_,
- * send the notification
- * @param mode
- * @param policyNotificationDao
- * @param subject
- * @param message
- * @param checkPolicyName
- * @param watchList
+ * send the notification.
+ *
+ * @param mode String for the mode
+ * @param policyNotificationDao CommonClassDao
+ * @param subject String subject
+ * @param message String message
+ * @param checkPolicyName String check policy name
+ * @param watchList List of watch objects
*/
- private void composeAndSendMail(String mode, CommonClassDao policyNotificationDao, String subject, String message, String checkPolicyName, List<Object> watchList) {
+ private void composeAndSendMail(String mode, CommonClassDao policyNotificationDao, String subject, String message,
+ String checkPolicyName, List<Object> watchList) {
String from = PolicyController.getSmtpUsername();
String to;
- for(Object watch : watchList){
+ for (Object watch : watchList) {
WatchPolicyNotificationTable list = (WatchPolicyNotificationTable) watch;
String watchPolicyName = list.getPolicyName();
- //this conditino check for specific stringin policy name being watched and
- //also if the policy being checked is different from the watched ones,
- //then there is no need to send mail, hence continue with next policy in the loop
- if((watchPolicyName.contains("Config_") || watchPolicyName.contains("Action_") || watchPolicyName.contains("Decision_"))
- && !watchPolicyName.equals(checkPolicyName)){
+ // this condition check for specific stringin policy name being watched and
+ // also if the policy being checked is different from the watched ones,
+ // then there is no need to send mail, hence continue with next policy in the loop
+ if ((watchPolicyName.contains("Config_") || watchPolicyName.contains("Action_")
+ || watchPolicyName.contains("Decision_")) && !watchPolicyName.equals(checkPolicyName)) {
continue;
}
try (AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext()) {
- to = list.getLoginIds()+"@"+PolicyController.getSmtpEmailExtension();
+ to = list.getLoginIds() + "@" + PolicyController.getSmtpEmailExtension();
to = to.trim();
ctx.register(PolicyNotificationMail.class);
ctx.refresh();
@@ -212,11 +240,12 @@ public class PolicyNotificationMail{
mailMsg.setSubject(subject);
mailMsg.setText(message);
mailSender.send(mimeMessage);
- if("Rename".equalsIgnoreCase(mode) || mode.contains("Delete") || mode.contains("Move")){
+ if ("Rename".equalsIgnoreCase(mode) || mode.contains("Delete") || mode.contains("Move")) {
policyNotificationDao.delete(watch);
}
} catch (Exception e) {
- policyLogger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW+"Exception Occured in Policy Notification" +e);
+ policyLogger
+ .error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Exception Occured in Policy Notification" + e);
}
}
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
index 03dbccfd9..76bb04945 100644
--- 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
@@ -27,6 +27,7 @@ import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
+
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
@@ -39,8 +40,10 @@ 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;
@@ -53,7 +56,7 @@ import org.onap.policy.controller.CreateDcaeMicroServiceController;
import org.onap.policy.controller.CreateFirewallController;
import org.onap.policy.controller.CreateOptimizationController;
import org.onap.policy.controller.PolicyController;
-import org.onap.policy.rest.XACMLRestProperties;
+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;
@@ -121,29 +124,32 @@ public class PolicyRestController extends RestrictedBaseController {
PolicyRestController.commonClassDao = commonClassDao;
}
-
-
+ /**
+ * policyCreationController.
+ *
+ * @param request Request
+ * @param response Response
+ */
@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 {
- updateAndSendToPAP(request, response, userId, mapper);
+ updateAndSendToPap(request, response, UserUtils.getUserSession(request).getOrgUserId(), mapper);
} catch (Exception e) {
policyLogger.error("Exception Occured while saving policy", e);
}
}
- private void updateAndSendToPAP(HttpServletRequest request, HttpServletResponse response, String userId,
+ private void updateAndSendToPap(HttpServletRequest request, HttpServletResponse response, String userId,
ObjectMapper mapper) throws IOException {
JsonNode root = mapper.readTree(request.getReader());
policyLogger.info(
- "****************************************Logging UserID while Create/Update Policy**************************************************");
+ "********************Logging UserID while Create/Update Policy***********************************");
policyLogger.info(USER_ID + userId + "Policy Data Object: "
+ root.get(PolicyController.getPolicydata()).get("policy").toString());
policyLogger.info(
- "***********************************************************************************************************************************");
+ "************************************************************************************************");
PolicyRestAdapter policyData = mapper.readValue(
root.get(PolicyController.getPolicydata()).get("policy").toString(), PolicyRestAdapter.class);
@@ -164,17 +170,16 @@ public class PolicyRestController extends RestrictedBaseController {
policyData.setUserId(userId);
String result;
- String body = PolicyUtils.objectToJsonString(policyData);
- String uri = request.getRequestURI();
- ResponseEntity<?> responseEntity = sendToPAP(body, uri, HttpMethod.POST);
+ ResponseEntity<?> responseEntity = sendToPap(PolicyUtils.objectToJsonString(policyData),
+ request.getRequestURI(), 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(POLICY_NAME).get(0);
if (policyData.isEditPolicy() && SUCCESS.equalsIgnoreCase(result)) {
- PolicyNotificationMail email = new PolicyNotificationMail();
- String mode = "EditPolicy";
+ final PolicyNotificationMail email = new PolicyNotificationMail();
+ final String mode = "EditPolicy";
String watchPolicyName = policyName.replace(XML, "");
String version = watchPolicyName.substring(watchPolicyName.lastIndexOf('.') + 1);
watchPolicyName =
@@ -197,8 +202,8 @@ public class PolicyRestController extends RestrictedBaseController {
PrintWriter out = response.getWriter();
String responseString = mapper.writeValueAsString(result);
- JSONObject j = new JSONObject("{policyData: " + responseString + "}");
- out.write(j.toString());
+ JSONObject json = new JSONObject("{policyData: " + responseString + "}");
+ out.write(json.toString());
}
private void modifyPolicyData(JsonNode root, PolicyRestAdapter policyData) {
@@ -227,13 +232,12 @@ public class PolicyRestController extends RestrictedBaseController {
}
}
-
- private ResponseEntity<?> sendToPAP(String body, String requestURI, HttpMethod method) {
+ private ResponseEntity<?> sendToPap(String body, String requestUri, HttpMethod method) {
String papUrl = PolicyController.getPapUrl();
- String papID = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_USERID);
- String papPass = PeCryptoUtils.decrypt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_PASS));
- Base64.Encoder encoder = Base64.getEncoder();
- String encoding = encoder.encodeToString((papID + ":" + papPass).getBytes(StandardCharsets.UTF_8));
+ String papPass = PeCryptoUtils.decrypt(XACMLProperties.getProperty(XacmlRestProperties.PROP_PAP_PASS));
+ String encoding = Base64.getEncoder().encodeToString(
+ (XACMLProperties.getProperty(XacmlRestProperties.PROP_PAP_USERID)
+ + ":" + papPass).getBytes(StandardCharsets.UTF_8));
HttpHeaders headers = new HttpHeaders();
headers.set(AUTHORIZATION, BASIC + encoding);
headers.set(CONTENT_TYPE, PolicyController.getContenttype());
@@ -242,7 +246,7 @@ public class PolicyRestController extends RestrictedBaseController {
HttpEntity<?> requestEntity = new HttpEntity<>(body, headers);
ResponseEntity<?> result = null;
HttpClientErrorException exception = null;
- String uri = requestURI;
+ String uri = requestUri;
if (uri.startsWith("/")) {
uri = uri.substring(uri.indexOf('/') + 1);
}
@@ -279,27 +283,24 @@ public class PolicyRestController extends RestrictedBaseController {
return result;
}
- private String callPAP(HttpServletRequest request, String method, String uriValue) {
- String uri = uriValue;
- String papUrl = PolicyController.getPapUrl();
- String papID = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_USERID);
- PeCryptoUtils.initAesKey(XACMLProperties.getProperty(XACMLRestProperties.PROP_AES_KEY));
- String papPass = PeCryptoUtils.decrypt((XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_PASS)));
+ private String callPap(HttpServletRequest request, String method, String uriValue) {
+ PeCryptoUtils.initAesKey(XACMLProperties.getProperty(XacmlRestProperties.PROP_AES_KEY));
+ String papPass = PeCryptoUtils.decrypt((XACMLProperties.getProperty(XacmlRestProperties.PROP_PAP_PASS)));
Base64.Encoder encoder = Base64.getEncoder();
- String encoding = encoder.encodeToString((papID + ":" + papPass).getBytes(StandardCharsets.UTF_8));
+ String encoding = encoder.encodeToString((XACMLProperties.getProperty(XacmlRestProperties.PROP_PAP_USERID)
+ + ":" + papPass).getBytes(StandardCharsets.UTF_8));
HttpHeaders headers = new HttpHeaders();
headers.set(AUTHORIZATION, BASIC + encoding);
headers.set(CONTENT_TYPE, PolicyController.getContenttype());
-
HttpURLConnection connection = null;
- List<FileItem> items;
FileItem item = null;
File file = null;
+ String uri = uriValue;
if (uri.contains(IMPORT_DICTIONARY)) {
try {
- items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
+ List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
item = items.get(0);
file = new File(item.getName());
String newFile = file.toString();
@@ -310,7 +311,7 @@ public class PolicyRestController extends RestrictedBaseController {
}
try {
- URL url = new URL(papUrl + uri);
+ URL url = new URL(PolicyController.getPapUrl() + uri);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod(method);
connection.setUseCaches(false);
@@ -324,7 +325,7 @@ public class PolicyRestController extends RestrictedBaseController {
return doConnect(connection);
}
- checkURI(request, uri, connection, item);
+ checkUri(request, uri, connection, item);
return doConnect(connection);
} catch (Exception e) {
@@ -351,9 +352,8 @@ public class PolicyRestController extends RestrictedBaseController {
return null;
}
- private void checkURI(HttpServletRequest request, String uri, HttpURLConnection connection, FileItem item)
+ private void checkUri(HttpServletRequest request, String uri, HttpURLConnection connection, FileItem item)
throws IOException {
- String boundary;
if (!(uri.endsWith("set_BRMSParamData") || uri.contains(IMPORT_DICTIONARY))) {
connection.setRequestProperty(CONTENT_TYPE, PolicyController.getContenttype());
ObjectMapper mapper = new ObjectMapper();
@@ -380,7 +380,7 @@ public class PolicyRestController extends RestrictedBaseController {
IOUtils.copy(request.getInputStream(), os);
}
} else {
- boundary = "===" + System.currentTimeMillis() + "===";
+ String boundary = "===" + System.currentTimeMillis() + "===";
connection.setRequestProperty(CONTENT_TYPE, "multipart/form-data; boundary=" + boundary);
try (OutputStream os = connection.getOutputStream()) {
if (item != null) {
@@ -402,8 +402,7 @@ public class PolicyRestController extends RestrictedBaseController {
private String doConnect(final HttpURLConnection connection) throws IOException {
connection.connect();
- int responseCode = connection.getResponseCode();
- if (responseCode == 200) {
+ if (connection.getResponseCode() == 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)
@@ -425,11 +424,17 @@ public class PolicyRestController extends RestrictedBaseController {
return null;
}
+ /**
+ * getDictionaryController.
+ *
+ * @param request Request
+ * @param response Response
+ */
@RequestMapping(value = {"/getDictionary/*"}, method = {RequestMethod.GET})
public void getDictionaryController(HttpServletRequest request, HttpServletResponse response) {
- String uri = request.getRequestURI().replace("/getDictionary", "");
String body;
- ResponseEntity<?> responseEntity = sendToPAP(null, uri, HttpMethod.GET);
+ ResponseEntity<?> responseEntity = sendToPap(null, request.getRequestURI().replace("/getDictionary", ""),
+ HttpMethod.GET);
if (responseEntity != null) {
body = responseEntity.getBody().toString();
} else {
@@ -442,6 +447,13 @@ public class PolicyRestController extends RestrictedBaseController {
}
}
+ /**
+ * saveDictionaryController.
+ *
+ * @param request Request
+ * @param response Response
+ * @throws IOException IO Exception
+ */
@RequestMapping(value = {"/saveDictionary/*/*"}, method = {RequestMethod.POST})
public void saveDictionaryController(HttpServletRequest request, HttpServletResponse response) throws IOException {
String userId = "";
@@ -456,12 +468,12 @@ public class PolicyRestController extends RestrictedBaseController {
}
policyLogger.info(
- "****************************************Logging UserID while Saving Dictionary*****************************************************");
+ "********************Logging UserID while Saving Dictionary**************************************");
policyLogger.info(USER_ID + userId);
policyLogger.info(
- "***********************************************************************************************************************************");
+ "************************************************************************************************");
- String body = callPAP(request, "POST", uri.replaceFirst("/", "").trim());
+ String body = callPap(request, "POST", uri.replaceFirst("/", "").trim());
if (body != null && !body.isEmpty()) {
response.getWriter().write(body);
} else {
@@ -469,6 +481,13 @@ public class PolicyRestController extends RestrictedBaseController {
}
}
+ /**
+ * deletetDictionaryController.
+ *
+ * @param request Request
+ * @param response Response
+ * @throws IOException IO Exception
+ */
@RequestMapping(value = {"/deleteDictionary/*/*"}, method = {RequestMethod.POST})
public void deletetDictionaryController(HttpServletRequest request, HttpServletResponse response)
throws IOException {
@@ -480,12 +499,12 @@ public class PolicyRestController extends RestrictedBaseController {
String userId = UserUtils.getUserSession(request).getOrgUserId();
policyLogger.info(
- "****************************************Logging UserID while Deleting Dictionary*****************************************************");
+ "**********************Logging UserID while Deleting Dictionary*************************************");
policyLogger.info(USER_ID + userId);
policyLogger.info(
- "*************************************************************************************************************************************");
+ "***************************************************************************************************");
- String body = callPAP(request, "POST", uri.replaceFirst("/", "").trim());
+ String body = callPap(request, "POST", uri.replaceFirst("/", "").trim());
if (body != null && !body.isEmpty()) {
response.getWriter().write(body);
} else {
@@ -493,6 +512,14 @@ public class PolicyRestController extends RestrictedBaseController {
}
}
+ /**
+ * searchDictionaryController.
+ *
+ * @param request Request
+ * @param response Response
+ * @return ModelAndView object
+ * @throws IOException IO Exception
+ */
@RequestMapping(value = {"/searchDictionary"}, method = {RequestMethod.POST})
public ModelAndView searchDictionaryController(HttpServletRequest request, HttpServletResponse response)
throws IOException {
@@ -503,14 +530,13 @@ public class PolicyRestController extends RestrictedBaseController {
}
uri = ONAP + uri.substring(uri.indexOf('/'));
try {
- String body = callPAP(request, "POST", uri.replaceFirst("/", "").trim());
+ String body = callPap(request, "POST", uri.replaceFirst("/", "").trim());
if (body.contains("CouldNotConnectException")) {
List<String> data = new ArrayList<>();
data.add("Elastic Search Server is down");
resultList = data;
} else {
- JSONObject json = new JSONObject(body);
- resultList = json.get("policyresult");
+ resultList = new JSONObject(body).get("policyresult");
}
} catch (Exception e) {
policyLogger.error(
@@ -522,12 +548,18 @@ public class PolicyRestController extends RestrictedBaseController {
response.setCharacterEncoding(PolicyController.getCharacterencoding());
response.setContentType(PolicyController.getContenttype());
- PrintWriter out = response.getWriter();
- JSONObject j = new JSONObject("{result: " + resultList + "}");
- out.write(j.toString());
+ response.getWriter().write(new JSONObject("{result: " + resultList + "}").toString());
return null;
}
+ /**
+ * searchPolicy.
+ *
+ * @param request request
+ * @param response response
+ * @return ModelAndView object
+ * @throws IOException IO exception
+ */
@RequestMapping(value = {"/searchPolicy"}, method = {RequestMethod.POST})
public ModelAndView searchPolicy(HttpServletRequest request, HttpServletResponse response) throws IOException {
Object resultList;
@@ -536,7 +568,7 @@ public class PolicyRestController extends RestrictedBaseController {
uri = uri.substring(uri.indexOf('/') + 1);
}
uri = ONAP + uri.substring(uri.indexOf('/'));
- String body = callPAP(request, "POST", uri.replaceFirst("/", "").trim());
+ String body = callPap(request, "POST", uri.replaceFirst("/", "").trim());
JSONObject json = new JSONObject(body);
try {
@@ -554,21 +586,27 @@ public class PolicyRestController extends RestrictedBaseController {
response.setContentType("application / json");
request.setCharacterEncoding(UTF_8);
- PrintWriter out = response.getWriter();
- JSONObject j = new JSONObject("{result: " + resultList + "}");
- out.write(j.toString());
+ response.getWriter().write(new JSONObject("{result: " + resultList + "}").toString());
return null;
}
public void deleteElasticData(String fileName) {
String uri = "searchPolicy?action=delete&policyName='" + fileName + "'";
- callPAP(null, "POST", uri.trim());
+ callPap(null, "POST", uri.trim());
}
- public String notifyOtherPAPSToUpdateConfigurations(String mode, String newName, String oldName) {
+ /**
+ * notifyOtherPAPSToUpdateConfigurations.
+ *
+ * @param mode Mode
+ * @param newName New Name
+ * @param oldName Old Name
+ * @return String
+ */
+ public String notifyOtherPapsToUpdateConfigurations(String mode, String newName, String oldName) {
String uri =
"onap/notifyOtherPAPs?action=" + mode + "&newPolicyName=" + newName + "&oldPolicyName=" + oldName + "";
- return callPAP(null, "POST", uri.trim());
+ return callPap(null, "POST", uri.trim());
}
}
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
index 7e0aef2e9..9cf647954 100644
--- 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
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP Policy Engine
* ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017, 2019 AT&T Intellectual Property. All rights reserved.
* Modifications Copyright (C) 2019 Bell Canada
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
@@ -18,8 +18,11 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.policy.admin;
+import com.fasterxml.jackson.databind.ObjectMapper;
+
import java.util.HashMap;
import java.util.Map;
@@ -36,25 +39,26 @@ 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);
+ /**
+ * getPolicyUserInfo - fills the HTTP response with user information.
+ *
+ * @param request HttpServletRequest
+ * @param response HttpServletResponse
+ */
@RequestMapping(value = "/get_PolicyUserInfo", method = RequestMethod.GET)
public void getPolicyUserInfo(HttpServletRequest request, HttpServletResponse response) {
- JsonMessage msg;
try {
String userId = UserUtils.getUserSession(request).getOrgUserId();
Map<String, Object> 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());
+ response.getWriter().write(new JSONObject(new JsonMessage(
+ new ObjectMapper().writeValueAsString(model))).toString());
} catch (Exception e) {
LOGGER.error("Exception Occurred" + 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
index a500c1dbe..d89dd2784 100644
--- 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
@@ -29,6 +29,7 @@ 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 java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
@@ -37,6 +38,7 @@ import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
+import java.net.URLConnection;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
@@ -45,10 +47,12 @@ import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
+
import org.apache.commons.io.IOUtils;
+import org.apache.commons.lang.StringUtils;
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.XacmlRestProperties;
import org.onap.policy.rest.adapter.PolicyRestAdapter;
import org.onap.policy.utils.PeCryptoUtils;
import org.onap.policy.xacml.api.XACMLErrorConstants;
@@ -64,7 +68,7 @@ import org.onap.policy.xacml.std.pap.StdPDPStatus;
/**
* Implementation of the PAPEngine interface that communicates with a PAP engine in a remote servlet through a RESTful
- * interface
+ * interface.
*
*
*/
@@ -72,25 +76,29 @@ public class RESTfulPAPEngine extends StdPDPItemSetChangeNotifier implements PAP
private static final Logger LOGGER = FlexLogger.getLogger(RESTfulPAPEngine.class);
private static final String GROUP_ID = "groupId=";
+ private static final String UNABLE_MSG = "Unable to PUT policy '";
+ private static final String EXCEPTION_MSG = "', e:";
+ private static final String ERROR_MSG = "error";
+ private static final String PDPID_MSG = "pdpId=";
//
// URL of the PAP Servlet that this Admin Console talks to
//
- private String papServletURLString;
+ private String papServletUrlString;
/**
- * Set up link with PAP Servlet and get our initial set of Groups
+ * Set up link with PAP Servlet and get our initial set of Groups.
*
* @throws PAPException When failing to register with PAP
*/
- public RESTfulPAPEngine(String myURLString) throws PAPException {
+ public RESTfulPAPEngine(String myUrlString) throws PAPException {
//
// 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.";
+ this.papServletUrlString = XACMLProperties.getProperty(XacmlRestProperties.PROP_PAP_URL);
+ if (StringUtils.isBlank(this.papServletUrlString)) {
+ String message = "The property 'POLICYENGINE_ADMIN_ACTIVE' was not set during installation. "
+ + "Admin Console cannot call PAP.";
LOGGER.error(message);
throw new PAPException(message);
}
@@ -98,14 +106,14 @@ public class RESTfulPAPEngine extends StdPDPItemSetChangeNotifier implements PAP
//
// register this Admin Console with the PAP Servlet to get updates
//
- Object newURL = sendToPAP("PUT", null, null, null, "adminConsoleURL=" + myURLString);
- if (newURL != null) {
+ 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);
+ 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");
}
}
@@ -117,25 +125,25 @@ public class RESTfulPAPEngine extends StdPDPItemSetChangeNotifier implements PAP
@Override
public OnapPDPGroup getDefaultGroup() throws PAPException {
- return (OnapPDPGroup) sendToPAP("GET", null, null, StdPDPGroup.class, GROUP_ID, "default=");
+ return (OnapPDPGroup) sendToPap("GET", null, null, StdPDPGroup.class, GROUP_ID, "default=");
}
@Override
public void setDefaultGroup(OnapPDPGroup group) throws PAPException {
- sendToPAP("POST", null, null, null, GROUP_ID + group.getId(), "default=true");
+ sendToPap("POST", null, null, null, GROUP_ID + group.getId(), "default=true");
}
@SuppressWarnings("unchecked")
@Override
public Set<OnapPDPGroup> getOnapPDPGroups() throws PAPException {
Set<OnapPDPGroup> newGroupSet;
- newGroupSet = (Set<OnapPDPGroup>) this.sendToPAP("GET", null, Set.class, StdPDPGroup.class, GROUP_ID);
+ newGroupSet = (Set<OnapPDPGroup>) this.sendToPap("GET", null, Set.class, StdPDPGroup.class, GROUP_ID);
return Collections.unmodifiableSet(newGroupSet);
}
@Override
public OnapPDPGroup getGroup(String id) throws PAPException {
- return (OnapPDPGroup) sendToPAP("GET", null, null, StdPDPGroup.class, GROUP_ID + id);
+ return (OnapPDPGroup) sendToPap("GET", null, null, StdPDPGroup.class, GROUP_ID + id);
}
@Override
@@ -149,17 +157,10 @@ public class RESTfulPAPEngine extends StdPDPItemSetChangeNotifier implements PAP
throw new PAPException("Unable to send name or description to PAP: " + e.getMessage() + e);
}
- this.sendToPAP("POST", null, null, null, GROUP_ID, "groupName=" + escapedName,
+ this.sendToPap("POST", null, null, null, GROUP_ID, "groupName=" + escapedName,
"groupDescription=" + escapedDescription);
}
- /**
- * Update the configuration on the PAP for a single Group.
- *
- * @param group
- * @return
- * @throws PAPException
- */
@Override
public void updateGroup(OnapPDPGroup group) throws PAPException {
try {
@@ -175,9 +176,9 @@ public class RESTfulPAPEngine extends StdPDPItemSetChangeNotifier implements PAP
// 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, GROUP_ID + group.getId());
+ sendToPap("PUT", group, null, null, GROUP_ID + group.getId());
} catch (Exception e) {
- String message = "Unable to PUT policy '" + group.getId() + "', e:" + e;
+ String message = UNABLE_MSG + group.getId() + EXCEPTION_MSG + e;
LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + message, e);
throw new PAPException(message);
}
@@ -192,9 +193,9 @@ public class RESTfulPAPEngine extends StdPDPItemSetChangeNotifier implements PAP
@Override
public void updateGroup(OnapPDPGroup group, String userName) throws PAPException {
try {
- sendToPAP("PUT", group, null, null, GROUP_ID + group.getId(), "userId=" + userName);
+ sendToPap("PUT", group, null, null, GROUP_ID + group.getId(), "userId=" + userName);
} catch (Exception e) {
- String message = "Unable to PUT policy '" + group.getId() + "', e:" + e;
+ String message = UNABLE_MSG + group.getId() + EXCEPTION_MSG + e;
LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + message, e);
throw new PAPException(message);
}
@@ -206,7 +207,7 @@ public class RESTfulPAPEngine extends StdPDPItemSetChangeNotifier implements PAP
if (newGroup != null) {
moveToGroupString = "movePDPsToGroupId=" + newGroup.getId();
}
- sendToPAP("DELETE", null, null, null, GROUP_ID + group.getId(), moveToGroupString);
+ sendToPap("DELETE", null, null, null, GROUP_ID + group.getId(), moveToGroupString);
}
@Override
@@ -215,56 +216,61 @@ public class RESTfulPAPEngine extends StdPDPItemSetChangeNotifier implements PAP
}
public OnapPDPGroup getPDPGroup(String pdpId) throws PAPException {
- return (OnapPDPGroup) sendToPAP("GET", null, null, StdPDPGroup.class, GROUP_ID, "pdpId=" + pdpId,
+ return (OnapPDPGroup) sendToPap("GET", null, null, StdPDPGroup.class, GROUP_ID, PDPID_MSG + pdpId,
"getPDPGroup=");
}
@Override
public OnapPDP getPDP(String pdpId) throws PAPException {
- return (OnapPDP) sendToPAP("GET", null, null, StdPDP.class, GROUP_ID, "pdpId=" + pdpId);
+ return (OnapPDP) sendToPap("GET", null, null, StdPDP.class, GROUP_ID, PDPID_MSG + pdpId);
}
@Override
public void newPDP(String id, OnapPDPGroup group, String name, String description, int jmxport)
throws PAPException {
- StdPDP newPDP = new StdPDP(id, name, description, jmxport);
- sendToPAP("PUT", newPDP, null, null, GROUP_ID + group.getId(), "pdpId=" + id);
+ StdPDP newPdp = new StdPDP(id, name, description, jmxport);
+ sendToPap("PUT", newPdp, null, null, GROUP_ID + group.getId(), PDPID_MSG + id);
}
@Override
public void movePDP(OnapPDP pdp, OnapPDPGroup newGroup) throws PAPException {
- sendToPAP("POST", null, null, null, GROUP_ID + newGroup.getId(), "pdpId=" + pdp.getId());
+ sendToPap("POST", null, null, null, GROUP_ID + newGroup.getId(), PDPID_MSG + pdp.getId());
}
@Override
public void updatePDP(OnapPDP pdp) throws PAPException {
OnapPDPGroup group = getPDPGroup(pdp);
- sendToPAP("PUT", pdp, null, null, GROUP_ID + group.getId(), "pdpId=" + pdp.getId());
+ sendToPap("PUT", pdp, null, null, GROUP_ID + group.getId(), PDPID_MSG + pdp.getId());
}
@Override
public void removePDP(OnapPDP pdp) throws PAPException {
OnapPDPGroup group = getPDPGroup(pdp);
- sendToPAP("DELETE", null, null, null, GROUP_ID + group.getId(), "pdpId=" + pdp.getId());
+ sendToPap("DELETE", null, null, null, GROUP_ID + group.getId(), PDPID_MSG + pdp.getId());
}
- // Validate the Policy Data
+ /**
+ * validatePolicyRequest Creates a pap policy and then send to pap.
+ *
+ * @param policyAdapter Input Adapter
+ * @param policyType Type of Policy
+ * @return true if validated
+ * @throws PAPException exception if invalid
+ */
public boolean validatePolicyRequest(PolicyRestAdapter policyAdapter, String policyType) throws PAPException {
- StdPAPPolicy newPAPPolicy = new StdPAPPolicy(policyAdapter.getPolicyName(), policyAdapter.getConfigBodyData(),
+ StdPAPPolicy newPapPolicy = new StdPAPPolicy(policyAdapter.getPolicyName(), policyAdapter.getConfigBodyData(),
policyAdapter.getConfigType(), "Base");
// send JSON object to PAP
- return (Boolean) sendToPAP("PUT", newPAPPolicy, null, null, "operation=validate", "apiflag=admin",
+ return (Boolean) sendToPap("PUT", newPapPolicy, null, null, "operation=validate", "apiflag=admin",
"policyType=" + policyType);
}
-
-
@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);
+ copyFile(id, group, policy, null);
// adjust the local copy of the group to include the new policy
PDPPolicy pdpPolicy = new StdPDPPolicy(id, isRoot, name);
@@ -278,32 +284,31 @@ public class RESTfulPAPEngine extends StdPDPItemSetChangeNotifier implements PAP
* 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
+ * @param policyId ID of policy
+ * @param group PDP Group
+ * @param policy Input stream of policy
+ * @throws PAPException exception
*/
- public void copyFile(String policyId, OnapPDPGroup group, InputStream policy) throws PAPException {
+ public void copyFile(String policyId, OnapPDPGroup group, InputStream policy, String usrId) throws PAPException {
// send the policy file to the PAP Servlet
try {
- sendToPAP("POST", policy, null, null, GROUP_ID + group.getId(), "policyId=" + policyId);
+ sendToPap("POST", policy, null, null, GROUP_ID + group.getId(), "policyId=" + policyId, "userId=" + usrId );
} catch (Exception e) {
- String message = "Unable to PUT policy '" + policyId + "', e:" + e;
+ String message = UNABLE_MSG + policyId + EXCEPTION_MSG + e;
LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + message, e);
throw new PAPException(message);
}
}
@Override
- public void copyPolicy(PDPPolicy policy, OnapPDPGroup group) throws PAPException {
+ public void copyPolicy(PDPPolicy policy, OnapPDPGroup group, String userId) 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);
+ copyFile(policy.getId(), group, is, userId);
} catch (Exception e) {
- String message = "Unable to PUT policy '" + policy.getId() + "', e:" + e;
+ String message = UNABLE_MSG + policy.getId() + EXCEPTION_MSG + e;
LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + message, e);
throw new PAPException(message);
}
@@ -318,13 +323,13 @@ public class RESTfulPAPEngine extends StdPDPItemSetChangeNotifier implements PAP
* 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
+ * @param pdp PDP to get status
+ * @return PDPStatus object
+ * @throws PAPException Exception
*/
@Override
public PDPStatus getStatus(OnapPDP pdp) throws PAPException {
- return (StdPDPStatus) sendToPAP("GET", pdp, null, StdPDPStatus.class);
+ return (StdPDPStatus) sendToPap("GET", pdp, null, StdPDPStatus.class);
}
//
@@ -334,57 +339,56 @@ public class RESTfulPAPEngine extends StdPDPItemSetChangeNotifier implements PAP
/**
* 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
+ * <p>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.
+ * <p>The Request parameters may be encoded in multiple "name=value" sets, or parameters may be
+ * combined by the caller.
*
- * @param method
+ * @param method method
* @param content - EITHER an InputStream OR an Object to be encoded in JSON
- * @param collectionTypeClass
- * @param responseContentClass
- * @param parameters
- * @return
- * @throws PAPException
+ * @param collectionTypeClass Collection
+ * @param responseContentClass Response Content
+ * @param parameters List of parameters
+ * @return Object
+ * @throws PAPException exception
*/
@SuppressWarnings({"rawtypes", "unchecked"})
- private Object sendToPAP(String method, Object content, Class collectionTypeClass, Class responseContentClass,
+ 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);
+ String papID = XACMLProperties.getProperty(XacmlRestProperties.PROP_PAP_USERID);
LOGGER.info("User Id is " + papID);
- PeCryptoUtils.initAesKey(XACMLProperties.getProperty(XACMLRestProperties.PROP_AES_KEY));
+ PeCryptoUtils.initAesKey(XACMLProperties.getProperty(XacmlRestProperties.PROP_AES_KEY));
String papPass = PeCryptoUtils
- .decrypt(PeCryptoUtils.decrypt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_PASS)));
+ .decrypt(PeCryptoUtils.decrypt(XACMLProperties.getProperty(XacmlRestProperties.PROP_PAP_PASS)));
Base64.Encoder encoder = Base64.getEncoder();
String encoding = encoder.encodeToString((papID + ":" + papPass).getBytes(StandardCharsets.UTF_8));
Object contentObj = content;
LOGGER.info("Encoding for the PAP is: " + encoding);
try {
- String fullURL = papServletURLString;
+ String fullUrl = papServletUrlString;
if (parameters != null && parameters.length > 0) {
StringBuilder queryString = new StringBuilder();
Arrays.stream(parameters).map(p -> "&" + p).forEach(queryString::append);
- fullURL += "?" + queryString.substring(1);
+ fullUrl += "?" + queryString.substring(1);
}
// special case - Status (actually the detailed status) comes from the PDP directly, not the PAP
if ("GET".equals(method) && (contentObj instanceof OnapPDP) && responseContentClass == StdPDPStatus.class) {
// Adjust the url and properties appropriately
String pdpID = ((OnapPDP) contentObj).getId();
- fullURL = pdpID + "?type=Status";
+ fullUrl = pdpID + "?type=Status";
contentObj = null;
- if (CheckPDP.validateID(pdpID)) {
- encoding = CheckPDP.getEncoding(pdpID);
+ if (CheckPdpProperties.validateId(pdpID)) {
+ encoding = CheckPdpProperties.getEncoding(pdpID);
}
}
- URL url = new URL(fullURL);
-
//
// Open up the connection
//
- connection = (HttpURLConnection) url.openConnection();
+ connection = (HttpURLConnection) makeConnection(fullUrl);
//
// Setup our method and headers
//
@@ -434,9 +438,9 @@ public class RESTfulPAPEngine extends StdPDPItemSetChangeNotifier implements PAP
String finalPolicyPath = connection.getHeaderField("finalPolicyPath");
successMap.put("success", finalPolicyPath);
return successMap;
- } else if ("error".equalsIgnoreCase(isSuccess)) {
+ } else if (ERROR_MSG.equalsIgnoreCase(isSuccess)) {
LOGGER.info("There was an error while creating the policy!");
- successMap.put("error", "error");
+ successMap.put(ERROR_MSG, ERROR_MSG);
return successMap;
} else {
// get the response content into a String
@@ -457,19 +461,19 @@ public class RESTfulPAPEngine extends StdPDPItemSetChangeNotifier implements PAP
}
} else if (connection.getResponseCode() >= 300 && connection.getResponseCode() <= 399) {
// redirection
- String newURL = connection.getHeaderField("Location");
- if (newURL == null) {
+ 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);
+ int qindex = newUrl.indexOf('?');
+ if (qindex > 0) {
+ newUrl = newUrl.substring(0, qindex);
}
- LOGGER.info("Redirect seen. Redirecting " + fullURL + " to " + newURL);
- return newURL;
+ LOGGER.info("Redirect seen. Redirecting " + fullUrl + " to " + newUrl);
+ return newUrl;
} else {
LOGGER.warn("Unexpected response code: " + connection.getResponseCode() + " message: "
+ connection.getResponseMessage());
@@ -527,4 +531,10 @@ public class RESTfulPAPEngine extends StdPDPItemSetChangeNotifier implements PAP
LOGGER.info("JSON response from PAP: " + json);
return json;
}
+
+ // these may be overridden by junit tests
+
+ protected URLConnection makeConnection(String fullUrl) throws IOException {
+ return new URL(fullUrl).openConnection();
+ }
}
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
index b116af6ef..f2c3a5d7a 100644
--- 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
@@ -2,15 +2,15 @@
* ============LICENSE_START=======================================================
* ONAP Policy Engine
* ================================================================================
- * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
* Modifications Copyright (C) 2019 Bell Canada
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -39,7 +39,9 @@ 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;
@@ -57,6 +59,7 @@ 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;
+
import org.apache.commons.io.FilenameUtils;
import org.json.JSONObject;
import org.onap.policy.common.logging.flexlogger.FlexLogger;
@@ -95,7 +98,6 @@ public class HumanPolicyComponent {
public static final String EMPTY_STRING = "";
private static final String ENTER = "ENTER";
-
private static HtmlProcessor htmlProcessor;
private static File policyFile;
@@ -104,9 +106,16 @@ public class HumanPolicyComponent {
// Default Constructor
}
+ /**
+ * DescribePolicy.
+ *
+ * @param policyFile File
+ * @return JSONObject
+ */
public static JSONObject DescribePolicy(final File policyFile) {
- if (LOGGER.isTraceEnabled())
+ if (LOGGER.isTraceEnabled()) {
LOGGER.trace(ENTER);
+ }
HumanPolicyComponent.policyFile = policyFile;
return humanPolicyLayout();
@@ -114,8 +123,9 @@ public class HumanPolicyComponent {
}
private static JSONObject humanPolicyLayout() {
- if (LOGGER.isTraceEnabled())
+ if (LOGGER.isTraceEnabled()) {
LOGGER.trace(ENTER);
+ }
try {
String html = processPolicy();
@@ -135,8 +145,9 @@ public class HumanPolicyComponent {
}
try (FileInputStream pIS = new FileInputStream(policyFile)) {
Object policy = XACMLPolicyScanner.readPolicy(pIS);
- if (policy == null)
+ if (policy == null) {
throw new IllegalArgumentException("Policy File " + policyFile.getName() + " cannot be unmarshalled");
+ }
HumanPolicyComponent.htmlProcessor = new HtmlProcessor(HumanPolicyComponent.policyFile, policy);
@@ -144,8 +155,9 @@ public class HumanPolicyComponent {
XACMLPolicyScanner xacmlScanner = new XACMLPolicyScanner(policyPath, htmlProcessor);
xacmlScanner.scan();
String html = htmlProcessor.html();
- if (LOGGER.isDebugEnabled())
+ if (LOGGER.isDebugEnabled()) {
LOGGER.debug(policyPath + System.lineSeparator() + html);
+ }
return html;
@@ -165,6 +177,7 @@ class HtmlProcessor extends SimpleCallback {
private static final String ENTER = "ENTER";
private static Map<String, String> function2human;
+
static {
function2human = new HashMap<>();
function2human.put(HumanPolicyComponent.FUNCTION_STRING_EQUAL, "equal");
@@ -175,6 +188,7 @@ class HtmlProcessor extends SimpleCallback {
}
private static Map<String, String> combiningAlgo2human;
+
static {
combiningAlgo2human = new HashMap<>();
combiningAlgo2human.put("deny-overrides", "to deny if any $placeholder$ below evaluates to <i>deny</i>");
@@ -203,8 +217,9 @@ class HtmlProcessor extends SimpleCallback {
private final Object rootPolicyObject;
public HtmlProcessor(File policyFile, Object policyObject) {
- if (LOGGER.isTraceEnabled())
+ if (LOGGER.isTraceEnabled()) {
LOGGER.trace(ENTER);
+ }
if (policyFile == null) {
LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Null Policy File");
@@ -259,6 +274,8 @@ class HtmlProcessor extends SimpleCallback {
}
/**
+ * getAttributeIdentifiersMap.
+ *
* @return the attributeIdentifiersMap
*/
public Map<String, AttributeIdentifiers> getAttributeIdentifiersMap() {
@@ -267,8 +284,9 @@ class HtmlProcessor extends SimpleCallback {
@Override
public void onFinishScan(Object root) {
- if (LOGGER.isTraceEnabled())
+ if (LOGGER.isTraceEnabled()) {
LOGGER.trace(ENTER);
+ }
if (rootPolicyObject instanceof PolicySetType) {
htmlOut.println("</dl>");
@@ -306,43 +324,52 @@ class HtmlProcessor extends SimpleCallback {
@Override
public CallbackResult onPreVisitPolicySet(PolicySetType parent, PolicySetType policySet) {
- if (LOGGER.isTraceEnabled())
+ if (LOGGER.isTraceEnabled()) {
LOGGER.trace("PolicySet: " + policySet.getPolicySetId() + " Version: " + policySet.getVersion());
+ }
- if (parent != null && LOGGER.isTraceEnabled())
+ 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())
+ if (description != null && LOGGER.isTraceEnabled()) {
LOGGER.trace("PolicySet: " + policySet.getPolicySetId() + " Description: " + policySet.getDescription());
+ }
- if (parent == null) // root
+ if (parent == null) { // root
policySet(policySet, "dl");
- else
+ } else {
policySet(policySet, "li");
+ }
- if (!policySet.getPolicySetOrPolicyOrPolicySetIdReference().isEmpty())
+ if (!policySet.getPolicySetOrPolicyOrPolicySetIdReference().isEmpty()) {
htmlOut.println("<ol>");
+ }
return super.onPreVisitPolicySet(parent, policySet);
}
@Override
public CallbackResult onPostVisitPolicySet(PolicySetType parent, PolicySetType policySet) {
- if (LOGGER.isTraceEnabled())
+ if (LOGGER.isTraceEnabled()) {
LOGGER.trace("PolicySet: " + policySet.getPolicySetId() + " Version: " + policySet.getVersion());
+ }
- if (parent != null && LOGGER.isTraceEnabled())
+ 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())
+ if (description != null && LOGGER.isTraceEnabled()) {
LOGGER.trace("PolicySet: " + policySet.getPolicySetId() + " Description: " + policySet.getDescription());
+ }
- if (!policySet.getPolicySetOrPolicyOrPolicySetIdReference().isEmpty())
+ if (!policySet.getPolicySetOrPolicyOrPolicySetIdReference().isEmpty()) {
htmlOut.println("</ol>");
+ }
htmlOut.println("<p></p>");
@@ -350,23 +377,25 @@ class HtmlProcessor extends SimpleCallback {
}
public void policySet(PolicySetType policySet, String htmlListElement) {
- if (LOGGER.isTraceEnabled())
+ if (LOGGER.isTraceEnabled()) {
LOGGER.trace("PolicySet: " + policySet.getPolicySetId());
+ }
String combiningAlgorithm = "-";
String id = "-";
String version = "-";
-
- if (policySet.getPolicyCombiningAlgId() != null)
+ if (policySet.getPolicyCombiningAlgId() != null) {
combiningAlgorithm = extractLastIdentifier(policySet.getPolicyCombiningAlgId(), ":");
+ }
- if (policySet.getPolicySetId() != null)
+ if (policySet.getPolicySetId() != null) {
id = extractLastIdentifier(policySet.getPolicySetId(), ":");
+ }
- if (policySet.getVersion() != null)
+ if (policySet.getVersion() != null) {
version = policySet.getVersion();
-
+ }
htmlOut.println("<" + htmlListElement + "><b>Policy Set ID</b>: <i>" + id + "</i> (v" + version + ") " + "</"
+ htmlListElement + ">");
@@ -378,8 +407,7 @@ class HtmlProcessor extends SimpleCallback {
htmlOut.print("<p>");
htmlOut.print("This policy set applies to requests with attributes ");
- List<AnyOfType> anyOf_s = policySet.getTarget().getAnyOf();
- target(anyOf_s);
+ target(policySet.getTarget().getAnyOf());
htmlOut.println(".</p>");
}
@@ -398,58 +426,68 @@ class HtmlProcessor extends SimpleCallback {
@Override
public CallbackResult onPreVisitPolicy(PolicySetType parent, PolicyType policy) {
- if (LOGGER.isTraceEnabled())
+ if (LOGGER.isTraceEnabled()) {
LOGGER.trace("PolicySet: " + policy.getPolicyId() + " Version: " + policy.getVersion());
+ }
- if (parent != null && LOGGER.isTraceEnabled())
+ 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())
+ if (description != null && LOGGER.isTraceEnabled()) {
LOGGER.trace("PolicySet: " + policy.getPolicyId() + " Description: " + policy.getDescription());
+ }
policy(policy);
- if (!policy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition().isEmpty())
+ if (!policy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition().isEmpty()) {
htmlOut.println("<ol type=\"i\">");
+ }
return super.onPreVisitPolicy(parent, policy);
}
@Override
public CallbackResult onPostVisitPolicy(PolicySetType parent, PolicyType policy) {
- if (LOGGER.isTraceEnabled())
+ if (LOGGER.isTraceEnabled()) {
LOGGER.trace("PolicySet: " + policy.getPolicyId() + " Version: " + policy.getVersion());
+ }
- if (parent != null && LOGGER.isTraceEnabled())
+ if (parent != null && LOGGER.isTraceEnabled()) {
LOGGER.trace("PolicySet: " + policy.getPolicyId() + "Parent PolicySet: " + parent.getPolicySetId()
+ " Version: " + parent.getVersion());
+ }
- if (!policy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition().isEmpty())
+ if (!policy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition().isEmpty()) {
htmlOut.println("</ol>");
+ }
htmlOut.println("<p></p>");
return super.onPostVisitPolicy(parent, policy);
}
public void policy(PolicyType policy) {
- if (LOGGER.isTraceEnabled())
+ if (LOGGER.isTraceEnabled()) {
LOGGER.trace("Policy: " + policy.getPolicyId());
+ }
String combiningAlgorithm = "-";
String id = "-";
String version = "-";
-
- if (policy.getRuleCombiningAlgId() != null)
+ if (policy.getRuleCombiningAlgId() != null) {
combiningAlgorithm = extractLastIdentifier(policy.getRuleCombiningAlgId(), ":");
+ }
- if (policy.getPolicyId() != null)
+ if (policy.getPolicyId() != null) {
id = extractLastIdentifier(policy.getPolicyId(), ":");
+ }
- if (policy.getVersion() != null)
+ if (policy.getVersion() != null) {
version = policy.getVersion();
+ }
htmlOut.println("<li><b>Policy ID</b>: <i>" + id + "</i> (v" + version + ") " + "</li>");
@@ -460,8 +498,7 @@ class HtmlProcessor extends SimpleCallback {
htmlOut.print("<p>");
htmlOut.print("This policy applies to requests with attributes ");
- List<AnyOfType> anyOf_s = policy.getTarget().getAnyOf();
- target(anyOf_s);
+ target(policy.getTarget().getAnyOf());
htmlOut.println(".</p>");
}
@@ -477,14 +514,15 @@ class HtmlProcessor extends SimpleCallback {
}
}
-
@Override
public CallbackResult onPreVisitRule(PolicyType parent, RuleType rule) {
- if (LOGGER.isTraceEnabled())
+ if (LOGGER.isTraceEnabled()) {
LOGGER.trace("Rule: " + rule.getRuleId());
+ }
- if (parent != null && LOGGER.isTraceEnabled())
+ if (parent != null && LOGGER.isTraceEnabled()) {
LOGGER.trace("Parent Policy: " + parent.getPolicyId() + " Version: " + parent.getVersion());
+ }
String description = rule.getDescription();
if (description != null && LOGGER.isTraceEnabled()) {
@@ -498,23 +536,21 @@ class HtmlProcessor extends SimpleCallback {
@Override
public CallbackResult onPostVisitRule(PolicyType parent, RuleType rule) {
- if (LOGGER.isTraceEnabled())
- LOGGER.trace("Rule: " + rule.getRuleId());
- if (parent != null && LOGGER.isTraceEnabled())
+ 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)
+ if (rule.getRuleId() != null) {
id = extractLastIdentifier(rule.getRuleId(), ":");
+ }
htmlOut.println("<li><b>Rule ID</b>: <i>" + id + "</i></li>");
@@ -526,9 +562,8 @@ class HtmlProcessor extends SimpleCallback {
if (rule.getTarget() == null || rule.getTarget().getAnyOf() == null || rule.getTarget().getAnyOf().isEmpty()) {
htmlOut.print(" for all requests");
} else {
- List<AnyOfType> anyOf_s = rule.getTarget().getAnyOf();
htmlOut.print(" for requests with attributes ");
- target(anyOf_s);
+ target(rule.getTarget().getAnyOf());
}
if (rule.getCondition() != null) {
@@ -540,8 +575,9 @@ class HtmlProcessor extends SimpleCallback {
if (rule.getAdviceExpressions() != null) {
advice(rule.getAdviceExpressions());
- if (rule.getObligationExpressions() != null)
+ if (rule.getObligationExpressions() != null) {
htmlOut.println(" and ");
+ }
}
if (rule.getObligationExpressions() != null) {
@@ -552,8 +588,9 @@ class HtmlProcessor extends SimpleCallback {
}
private void advice(AdviceExpressionsType adviceExpressions) {
- if (LOGGER.isTraceEnabled())
+ if (LOGGER.isTraceEnabled()) {
LOGGER.trace(ENTER);
+ }
List<AdviceExpressionType> ae = adviceExpressions.getAdviceExpression();
for (AdviceExpressionType expression : ae) {
@@ -569,8 +606,9 @@ class HtmlProcessor extends SimpleCallback {
}
private void obligation(ObligationExpressionsType obligationExpressions) {
- if (LOGGER.isTraceEnabled())
+ if (LOGGER.isTraceEnabled()) {
LOGGER.trace(ENTER);
+ }
List<ObligationExpressionType> oe = obligationExpressions.getObligationExpression();
for (ObligationExpressionType expression : oe) {
@@ -586,11 +624,14 @@ class HtmlProcessor extends SimpleCallback {
}
/**
- * @param assignments
+ * processAttributeAssignments.
+ *
+ * @param assignments List of AttributeAssignmentExpressionType
*/
private void processAttributeAssignments(List<AttributeAssignmentExpressionType> assignments) {
- if (LOGGER.isTraceEnabled())
+ if (LOGGER.isTraceEnabled()) {
LOGGER.trace(ENTER);
+ }
for (AttributeAssignmentExpressionType assignment : assignments) {
String succintIdentifier = extractLastIdentifier(assignment.getCategory(), ":") + ":"
@@ -620,8 +661,9 @@ class HtmlProcessor extends SimpleCallback {
for (Object c : avt.getContent()) {
countContent++;
htmlOut.print("<i>" + c + "</i>");
- if (countContent < numContent)
+ if (countContent < numContent) {
htmlOut.print(" or ");
+ }
}
htmlOut.println("</li>");
} else if (assignmentObject instanceof AttributeDesignatorType
@@ -634,118 +676,118 @@ class HtmlProcessor extends SimpleCallback {
}
/**
- *
- * @param anyOfList
+ * target.
+ *
+ * @param anyOfList List of AnyOfType's
*/
public void target(List<AnyOfType> anyOfList) {
- if (LOGGER.isTraceEnabled())
+ if (LOGGER.isTraceEnabled()) {
LOGGER.trace(ENTER);
+ }
- if (anyOfList != null) {
- Iterator<AnyOfType> iterAnyOf = anyOfList.iterator();
- StringBuilder targetInHuman = new StringBuilder();
- while (iterAnyOf.hasNext()) {
- AnyOfType anyOf = iterAnyOf.next();
- List<AllOfType> allOfList = anyOf.getAllOf();
- if (allOfList != null) {
- Iterator<AllOfType> iterAllOf = allOfList.iterator();
- while (iterAllOf.hasNext()) {
- AllOfType allOf = iterAllOf.next();
- List<MatchType> matchList = allOf.getMatch();
- if (matchList != null) {
- Iterator<MatchType> iterMatch = matchList.iterator();
- if (matchList.size() > 1)
- targetInHuman.append("(");
- while (iterMatch.hasNext()) {
- MatchType match = iterMatch.next();
- //
- // Finally down to the actual attribute
- //
- StdAttribute attribute = null;
- AttributeValueType value = match.getAttributeValue();
- String attributeDataType;
- if (match.getAttributeDesignator() != null && value != null) {
- AttributeDesignatorType designator = match.getAttributeDesignator();
- attribute = new StdAttribute(new IdentifierImpl(designator.getCategory()),
- new IdentifierImpl(designator.getAttributeId()),
- new StdAttributeValue<List<?>>(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<List<?>>(new IdentifierImpl(value.getDataType()),
- value.getContent()),
- null, false);
- attributeDataType = selector.getDataType();
- } else {
- LOGGER.warn("NULL designator/selector or value for match.");
- attributeDataType = "NA";
- }
+ if (anyOfList == null) {
+ return;
+ }
+ Iterator<AnyOfType> iterAnyOf = anyOfList.iterator();
+ StringBuilder targetInHuman = new StringBuilder();
+ while (iterAnyOf.hasNext()) {
+ AnyOfType anyOf = iterAnyOf.next();
+ List<AllOfType> allOfList = anyOf.getAllOf();
+ Iterator<AllOfType> iterAllOf = allOfList.iterator();
+ while (iterAllOf.hasNext()) {
+ AllOfType allOf = iterAllOf.next();
+ List<MatchType> matchList = allOf.getMatch();
+ Iterator<MatchType> iterMatch = matchList.iterator();
+ if (matchList.size() > 1) {
+ targetInHuman.append("(");
+ }
+ while (iterMatch.hasNext()) {
+ MatchType match = iterMatch.next();
+ //
+ // Finally down to the actual attribute
+ //
+ StdAttribute attribute = null;
+ AttributeValueType value = match.getAttributeValue();
+ String attributeDataType;
+ if (match.getAttributeDesignator() != null && value != null) {
+ AttributeDesignatorType designator = match.getAttributeDesignator();
+ attribute = new StdAttribute(new IdentifierImpl(designator.getCategory()),
+ new IdentifierImpl(designator.getAttributeId()),
+ new StdAttributeValue<List<?>>(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<List<?>>(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.append("<i><a href=\"#" + succintIdentifier + "\">"
- + succintIdentifier + "</a></i> " + 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.append(" <I>" + o + "</I>");
- if (countValues < numValues) {
- targetInHuman.append(", or");
- }
- }
- } else {
- targetInHuman.append(" <I>" + v.getValue() + "</I>");
- if (count < numAttributes) {
- targetInHuman.append(", or ");
- }
- }
+ 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.append("<i><a href=\"#" + succintIdentifier + "\">"
+ + succintIdentifier + "</a></i> " + functionName + " ");
+
+ int numAttributes = attribute.getValues().size();
+ int count = 0;
+ for (AttributeValue<?> v : attribute.getValues()) {
+ count++;
+ if (v.getValue() instanceof Collection<?>) {
+ Collection<?> collectionValues = (Collection<?>) v.getValue();
+ int numValues = collectionValues.size();
+ int countValues = 0;
+ for (Object o : collectionValues) {
+ countValues++;
+ targetInHuman.append(" <I>" + o + "</I>");
+ if (countValues < numValues) {
+ targetInHuman.append(", or");
}
}
-
- if (iterMatch.hasNext()) {
- targetInHuman.append(" and ");
+ } else {
+ targetInHuman.append(" <I>" + v.getValue() + "</I>");
+ if (count < numAttributes) {
+ targetInHuman.append(", or ");
}
- } // end iterMatch
- if (matchList.size() > 1) {
- targetInHuman.append(")");
}
}
- if (iterAllOf.hasNext()) {
- targetInHuman.append(" or ");
- }
- } // end iterAllOf
- }
- if (iterAnyOf.hasNext()) {
- targetInHuman = new StringBuilder();
- targetInHuman.append("(" + targetInHuman + ")" + " or ");
- } else {
- if (anyOfList.size() > 1) {
- targetInHuman.append(")");
}
+
+ if (iterMatch.hasNext()) {
+ targetInHuman.append(" and ");
+ }
+ } // end iterMatch
+ if (matchList.size() > 1) {
+ targetInHuman.append(")");
}
- } // end iterAnyOf
- htmlOut.println(targetInHuman);
+ }
+ if (iterAllOf.hasNext()) {
+ targetInHuman.append(" or ");
+ }
+ } // end iterAllOf
+ if (iterAnyOf.hasNext()) {
+ targetInHuman = new StringBuilder();
+ targetInHuman.append("(" + targetInHuman + ")" + " or ");
+ } else {
+ if (anyOfList.size() > 1) {
+ targetInHuman.append(")");
+ }
}
+ htmlOut.println(targetInHuman);
}
private String getHumanFunction(String matchId) {
@@ -815,12 +857,12 @@ class HtmlProcessor extends SimpleCallback {
} else {
StringBuilder forResult = new StringBuilder();
for (JAXBElement<?> e : exps) {
- Object v = e.getValue();
+ Object theValue = e.getValue();
if (LOGGER.isDebugEnabled()) {
- LOGGER.debug("one-and-only children: " + v);
+ LOGGER.debug("one-and-only children: " + theValue);
}
- if (v != null) {
- forResult.append(stringifyExpression(v));
+ if (theValue != null) {
+ forResult.append(stringifyExpression(theValue));
}
}
return forResult.toString();
@@ -840,8 +882,8 @@ class HtmlProcessor extends SimpleCallback {
}
StringBuilder applySubresult = new StringBuilder();
for (JAXBElement<?> e : apply.getExpression()) {
- Object v = e.getValue();
- if (v != null) {
+ Object theValue = e.getValue();
+ if (theValue != null) {
applySubresult.append(this.stringifyExpression(e.getValue()));
}
}
@@ -906,11 +948,12 @@ class HtmlProcessor extends SimpleCallback {
if (expression instanceof AttributeValueType) {
AttributeValueType avt = (AttributeValueType) expression;
List<Object> content = avt.getContent();
- StringBuilder value_s = new StringBuilder();
+ StringBuilder stringValue = new StringBuilder(" ");
for (Object o : content) {
- value_s.append(" " + o.toString());
+ stringValue.append(" ");
+ stringValue.append(o.toString());
}
- return " " + value_s.toString();
+ return stringValue.toString();
}
if (expression instanceof VariableReferenceType) {
//
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
index 0e1be9349..ef6b98803 100644
--- 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
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP Policy Engine
* ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017, 2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -32,44 +32,43 @@ 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;
+import org.onap.policy.rest.jpa.SystemLogDb;
@SuppressWarnings("deprecation")
-public class HibernateSession{
+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);
- }
- }
+ private static final Logger LOGGER = FlexLogger.getLogger(HibernateSession.class);
- private HibernateSession(){
- /**
- empty implementation
- */
- }
+ private static SessionFactory logSessionFactory;
- public static Session getSession(){
- return logSessionFactory.openSession();
- }
-
- public static void setSession(SessionFactory logSessionFactory1){
- logSessionFactory = logSessionFactory1;
- }
+ 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);
+ }
+ }
+ private HibernateSession() {
+ /**
+ * empty implementation
+ */
+ }
+
+ public static Session getSession() {
+ return logSessionFactory.openSession();
+ }
+
+ public static void setSession(SessionFactory logSessionFactory1) {
+ logSessionFactory = logSessionFactory1;
+ }
}
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
index 578258403..666923b43 100644
--- 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
@@ -2,15 +2,15 @@
* ============LICENSE_START=======================================================
* ONAP Policy Engine
* ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017, 2019 AT&T Intellectual Property. All rights reserved.
* Modifications Copyright (C) 2019 Bell Canada
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -27,32 +27,28 @@ import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
-
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.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;
+import org.onap.policy.rest.adapter.PolicyRestAdapter;
+import org.onap.portalsdk.core.controller.RestrictedBaseController;
+import org.springframework.stereotype.Controller;
+import org.springframework.web.bind.annotation.RequestMapping;
@Controller
-@RequestMapping({ "/" })
+@RequestMapping({"/"})
public class ActionPolicyController extends RestrictedBaseController {
private static final Logger LOGGER = FlexLogger.getLogger(ActionPolicyController.class);
private static final String PERFORMER_ATTRIBUTE_ID = "performer";
@@ -66,41 +62,47 @@ public class ActionPolicyController extends RestrictedBaseController {
// Default Constructor
}
+ /**
+ * prePopulateActionPolicyData.
+ *
+ * @param policyAdapter PolicyRestAdapter
+ */
public void prePopulateActionPolicyData(PolicyRestAdapter policyAdapter) {
ruleAlgorithmList = new ArrayList<>();
performer.put("PDP", "PDPAction");
performer.put("PEP", "PEPAction");
- if (policyAdapter.getPolicyData() instanceof PolicyType) {
- PolicyType policy = (PolicyType) policyAdapter.getPolicyData();
+ if (! (policyAdapter.getPolicyData() instanceof PolicyType)) {
+ return;
+ }
+ PolicyType policy = (PolicyType) policyAdapter.getPolicyData();
- // 1. Set policy-name, policy-filename and description to Policy Adapter
- setPolicyAdapterPolicyNameAndDesc(policyAdapter, policy);
+ // 1. Set policy-name, policy-filename and description to Policy Adapter
+ setPolicyAdapterPolicyNameAndDesc(policyAdapter, policy);
- // 2a. Get the target data under policy for Action.
- TargetType target = policy.getTarget();
- if (target == null) {
- return;
- }
+ // 2a. Get the target data under policy for Action.
+ TargetType target = policy.getTarget();
+ if (target == null) {
+ return;
+ }
- // 2b. Set attributes to Policy Adapter
- setPolicyAdapterAttributes(policyAdapter, target.getAnyOf());
+ // 2b. Set attributes to Policy Adapter
+ setPolicyAdapterAttributes(policyAdapter, target.getAnyOf());
- List<Object> ruleList = policy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition();
- // Under rule we have Condition and obligation.
- for (Object o : ruleList) {
- if (!(o instanceof RuleType)) {
- continue;
- }
- // 3. Set rule-algorithm choices to Policy Adapter
- setPolicyAdapterRuleAlgorithmschoices(policyAdapter, (RuleType) o);
+ List<Object> ruleList = policy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition();
+ // Under rule we have Condition and obligation.
+ for (Object o : ruleList) {
+ if (!(o instanceof RuleType)) {
+ continue;
+ }
+ // 3. Set rule-algorithm choices to Policy Adapter
+ setPolicyAdapterRuleAlgorithmschoices(policyAdapter, (RuleType) o);
- // 4a. Get the Obligation data under the rule for Form elements.
- ObligationExpressionsType obligations = ((RuleType) o).getObligationExpressions();
+ // 4a. Get the Obligation data under the rule for Form elements.
+ ObligationExpressionsType obligations = ((RuleType) o).getObligationExpressions();
- // 4b. Set action attribute-value and action-performer to Policy Adapter
- setPolicyAdapterActionData(policyAdapter, obligations);
- }
+ // 4b. Set action attribute-value and action-performer to Policy Adapter
+ setPolicyAdapterActionData(policyAdapter, obligations);
}
}
@@ -109,22 +111,23 @@ public class ActionPolicyController extends RestrictedBaseController {
return;
}
// Under the obligationExpressions we have obligationExpression.
- List<ObligationExpressionType> obligationList = obligations.getObligationExpression();
- if (obligationList == null) {
- return;
- }
- for (ObligationExpressionType obligation : obligationList) {
+ // NOTE: getObligationExpression() will never return NULL.
+ //
+ for (ObligationExpressionType obligation : obligations.getObligationExpression()) {
policyAdapter.setActionAttributeValue(obligation.getObligationId());
// Under the obligationExpression we have attributeAssignmentExpression.
- List<AttributeAssignmentExpressionType> attributeAssignmentExpressionList = obligation
- .getAttributeAssignmentExpression();
- if (attributeAssignmentExpressionList == null) {
- continue;
- }
- for (AttributeAssignmentExpressionType attributeAssignmentExpression : attributeAssignmentExpressionList) {
+ //
+ // NOTE: obligation.getAttributeAssignmentExpression() will NEVER be null
+ // It will always return a list.
+ //
+ for (AttributeAssignmentExpressionType attributeAssignmentExpression :
+ obligation.getAttributeAssignmentExpression()) {
+ //
+ //
+ //
String attributeID = attributeAssignmentExpression.getAttributeId();
- AttributeValueType attributeValue = (AttributeValueType) attributeAssignmentExpression
- .getExpression().getValue();
+ AttributeValueType attributeValue =
+ (AttributeValueType) attributeAssignmentExpression.getExpression().getValue();
if (!attributeID.equals(PERFORMER_ATTRIBUTE_ID)) {
continue;
}
@@ -139,8 +142,8 @@ public class ActionPolicyController extends RestrictedBaseController {
private void setPolicyAdapterPolicyNameAndDesc(PolicyRestAdapter policyAdapter, PolicyType policy) {
policyAdapter.setOldPolicyFileName(policyAdapter.getPolicyName());
- String policyNameValue = policyAdapter.getPolicyName()
- .substring(policyAdapter.getPolicyName().indexOf('_') + 1);
+ String policyNameValue =
+ policyAdapter.getPolicyName().substring(policyAdapter.getPolicyName().indexOf('_') + 1);
policyAdapter.setPolicyName(policyNameValue);
String description;
try {
@@ -152,11 +155,10 @@ public class ActionPolicyController extends RestrictedBaseController {
policyAdapter.setPolicyDescription(description);
}
- private void setPolicyAdapterRuleAlgorithmschoices(PolicyRestAdapter policyAdapter, RuleType o) {
- ConditionType condition = o.getCondition();
- if (condition != null) {
+ private void setPolicyAdapterRuleAlgorithmschoices(PolicyRestAdapter policyAdapter, RuleType ruleType) {
+ if (ruleType.getCondition() != null) {
int index = 0;
- ApplyType actionApply = (ApplyType) condition.getExpression().getValue();
+ ApplyType actionApply = (ApplyType) ruleType.getCondition().getExpression().getValue();
ruleAlgorithmTracker = new LinkedList<>();
// Populating Rule Algorithms starting from compound.
prePopulateCompoundRuleAlgorithm(index, actionApply);
@@ -166,36 +168,43 @@ public class ActionPolicyController extends RestrictedBaseController {
private void setPolicyAdapterAttributes(PolicyRestAdapter policyAdapter, List<AnyOfType> anyOfList) {
List<Object> attributeList = new ArrayList<>();
- if (anyOfList == null) {
- return;
- }
+ //
+ // NOTE: If using xacml3 code and doing a getAnyOf(), the anyOfList will
+ // NEVER be null as that code will create it if it is null.
+ //
+ // Remove the null check as its impossible to cover it.
+ //
// under target we have AnyOFType
for (AnyOfType anyOf : anyOfList) {
// Under AntOfType we have AllOfType
+ //
+ // NOTE: This will NEVER be null as the method call in the
+ // previous line getAllOf() will never return a null. It
+ // always creates it if its empty.
+ //
List<AllOfType> allOfList = anyOf.getAllOf();
- if (allOfList == null) {
- continue;
- }
// Under AllOfType we have Match.
for (AllOfType allOfType : allOfList) {
- List<MatchType> matchList = allOfType.getMatch();
- if (matchList != null) {
- //
- // Under the match we have attributeValue and
- // attributeDesignator. So,finally down to the actual attribute.
- //
- // 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.
- matchList.forEach(match -> {
- AttributeValueType attributeValue = match.getAttributeValue();
- String value = (String) attributeValue.getContent().get(0);
- AttributeDesignatorType designator = match.getAttributeDesignator();
- String attributeId = designator.getAttributeId();
- Map<String, String> attribute = new HashMap<>();
- attribute.put("key", attributeId);
- attribute.put("value", value);
- attributeList.add(attribute);
- });
+ //
+ // NOTE: allOfType.getMatch() will NEVER be null as the method
+ // call getMatch will always return something. If its
+ // not there it will create it.
+ //
+ //
+ // Under the match we have attributeValue and
+ // attributeDesignator. So,finally down to the actual attribute.
+ //
+ // 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.
+ for (MatchType match : allOfType.getMatch()) {
+ AttributeValueType attributeValue = match.getAttributeValue();
+ String value = (String) attributeValue.getContent().get(0);
+ AttributeDesignatorType designator = match.getAttributeDesignator();
+ String attributeId = designator.getAttributeId();
+ Map<String, String> attribute = new HashMap<>();
+ attribute.put("key", attributeId);
+ attribute.put("value", value);
+ attributeList.add(attribute);
}
policyAdapter.setAttributes(attributeList);
}
@@ -211,41 +220,41 @@ public class ActionPolicyController extends RestrictedBaseController {
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) {
+ if (jaxbElement.getValue() instanceof AttributeValueType
+ || jaxbElement.getValue() instanceof AttributeDesignatorType) {
prePopulateRuleAlgorithms(index, actionApply, jaxbActionTypes);
ruleAlgorithmTracker.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<String, String> rule = new HashMap<>();
- for (String key : PolicyController.getDropDownMap().keySet()) {
- String keyValue = PolicyController.getDropDownMap().get(key);
- if (keyValue.equals(actionApply.getFunctionId())) {
- rule.put("dynamicRuleAlgorithmCombo", key);
- }
+ if (!isCompoundRule) {
+ return index;
+ }
+ // 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<String, String> rule = new HashMap<>();
+ for ( Entry<String, String> entrySet : PolicyController.getDropDownMap().entrySet()) {
+ if (entrySet.getValue().equals(actionApply.getFunctionId())) {
+ rule.put("dynamicRuleAlgorithmCombo", entrySet.getKey());
}
- rule.put("id", "A" + (index + 1));
- // Populate Key and values for Compound Rule
- rule.put(DYNAMIC_RULE_ALGORITHM_FIELD_1, "A" + (ruleAlgorithmTracker.getLast() + 1));
- ruleAlgorithmTracker.removeLast();
- rule.put(DYNAMIC_RULE_ALGORITHM_FIELD_2, "A" + (ruleAlgorithmTracker.getLast() + 1));
- ruleAlgorithmTracker.removeLast();
- ruleAlgorithmTracker.addLast(index);
- ruleAlgorithmList.add(rule);
- index++;
}
- return index;
+ rule.put("id", "A" + (index + 1));
+ // Populate Key and values for Compound Rule
+ rule.put(DYNAMIC_RULE_ALGORITHM_FIELD_1, "A" + (ruleAlgorithmTracker.getLast() + 1));
+ ruleAlgorithmTracker.removeLast();
+ rule.put(DYNAMIC_RULE_ALGORITHM_FIELD_2, "A" + (ruleAlgorithmTracker.getLast() + 1));
+ ruleAlgorithmTracker.removeLast();
+ ruleAlgorithmTracker.addLast(index);
+ ruleAlgorithmList.add(rule);
+ return ++index;
}
private void prePopulateRuleAlgorithms(int index, ApplyType actionApply, List<JAXBElement<?>> jaxbActionTypes) {
@@ -253,7 +262,7 @@ public class ActionPolicyController extends RestrictedBaseController {
ruleMap.put("id", "A" + (index + 1));
// Populate combo box
Map<String, String> dropDownMap = PolicyController.getDropDownMap();
- for ( Entry<String, String> entry : dropDownMap.entrySet()) {
+ for (Entry<String, String> entry : dropDownMap.entrySet()) {
if (entry.getValue().equals(actionApply.getFunctionId())) {
ruleMap.put("dynamicRuleAlgorithmCombo", entry.getKey());
}
@@ -264,8 +273,8 @@ public class ActionPolicyController extends RestrictedBaseController {
// Get from Attribute Designator
ApplyType innerActionApply = (ApplyType) jaxbActionTypes.get(0).getValue();
List<JAXBElement<?>> jaxbInnerActionTypes = innerActionApply.getExpression();
- AttributeDesignatorType attributeDesignator = (AttributeDesignatorType) jaxbInnerActionTypes.get(0)
- .getValue();
+ AttributeDesignatorType attributeDesignator =
+ (AttributeDesignatorType) jaxbInnerActionTypes.get(0).getValue();
ruleMap.put(DYNAMIC_RULE_ALGORITHM_FIELD_1, attributeDesignator.getAttributeId());
// Get from Attribute Value
@@ -279,11 +288,20 @@ public class ActionPolicyController extends RestrictedBaseController {
String attributeValue = (String) actionConditionAttributeValue.getContent().get(0);
ruleMap.put(DYNAMIC_RULE_ALGORITHM_FIELD_2, attributeValue);
- ApplyType innerActionApply = (ApplyType) jaxbActionTypes.get(1).getValue();
- List<JAXBElement<?>> jaxbInnerActionTypes = innerActionApply.getExpression();
- AttributeDesignatorType attributeDesignator = (AttributeDesignatorType) jaxbInnerActionTypes.get(0)
- .getValue();
- ruleMap.put(DYNAMIC_RULE_ALGORITHM_FIELD_1, attributeDesignator.getAttributeId());
+ //
+ // This is making a BIG assumption here that there exists an innerApply. This IF
+ // statement was added to support JUnit code coverage. For lack of any example of what
+ // this policy should actually look like.
+ //
+ if (jaxbActionTypes.size() > 1) {
+ ApplyType innerActionApply = (ApplyType) jaxbActionTypes.get(1).getValue();
+ List<JAXBElement<?>> jaxbInnerActionTypes = innerActionApply.getExpression();
+ if (! jaxbInnerActionTypes.isEmpty()) {
+ AttributeDesignatorType attributeDesignator =
+ (AttributeDesignatorType) jaxbInnerActionTypes.get(0).getValue();
+ ruleMap.put(DYNAMIC_RULE_ALGORITHM_FIELD_1, 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
index fc25e29f0..139b2b87f 100644
--- 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
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP Policy Engine
* ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017, 2019 AT&T Intellectual Property. All rights reserved.
* Modifications Copyright (C) 2019 Bell Canada
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
@@ -21,8 +21,11 @@
package org.onap.policy.controller;
+import com.fasterxml.jackson.databind.DeserializationFeature;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+
import java.io.IOException;
-import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;
@@ -44,21 +47,16 @@ 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 final String CHARACTER_ENCODING = "UTF-8";
private static CommonClassDao commonClassDao;
public AdminTabController() {
- //default constructor
+ // default constructor
}
@Autowired
@@ -74,57 +72,66 @@ public class AdminTabController extends RestrictedBaseController {
AdminTabController.commonClassDao = commonClassDao;
}
- @RequestMapping(value = {"/get_LockDownData"}, method = {
- org.springframework.web.bind.annotation.RequestMethod.GET}, produces = MediaType.APPLICATION_JSON_VALUE)
+ /**
+ * getAdminTabEntityData.
+ *
+ * @param request HttpServletRequest
+ * @param response HttpServletResponse
+ */
+ @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<String, Object> 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());
+ response.getWriter().write(new JSONObject(new JsonMessage(mapper.writeValueAsString(model))).toString());
} catch (Exception e) {
LOGGER.error("Exception Occured" + e);
}
}
- @RequestMapping(value = {"/adminTabController/save_LockDownValue.htm"}, method = {
- org.springframework.web.bind.annotation.RequestMethod.POST})
+ /**
+ * saveAdminTabLockdownValue.
+ *
+ * @param request HttpServletRequest
+ * @param response HttpServletResponse
+ * @return ModelAndView object
+ * @throws IOException IOException
+ */
+ @RequestMapping(
+ value = {"/adminTabController/save_LockDownValue.htm"},
+ method = {org.springframework.web.bind.annotation.RequestMethod.POST})
public ModelAndView saveAdminTabLockdownValue(HttpServletRequest request, HttpServletResponse response)
- throws IOException {
+ throws IOException {
+ response.setCharacterEncoding(PolicyUtils.CHARACTER_ENCODING);
+ request.setCharacterEncoding(PolicyUtils.CHARACTER_ENCODING);
try {
ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
String userId = UserUtils.getUserSession(request).getOrgUserId();
LOGGER.info(
- "****************************************Logging UserID for Application Lockdown Function*****************************************");
+ "********************Logging UserID for Application Lockdown Function**************************");
LOGGER.info("UserId: " + userId);
LOGGER.info(
- "*********************************************************************************************************************************");
+ "**********************************************************************************************");
JsonNode root = mapper.readTree(request.getReader());
- GlobalRoleSettings globalRole = mapper
- .readValue(root.get("lockdowndata").toString(), GlobalRoleSettings.class);
+ GlobalRoleSettings globalRole =
+ mapper.readValue(root.get("lockdowndata").toString(), GlobalRoleSettings.class);
globalRole.setRole("super-admin");
commonClassDao.update(globalRole);
- response.setCharacterEncoding(CHARACTER_ENCODING);
- response.setContentType("application / json");
- request.setCharacterEncoding(CHARACTER_ENCODING);
+ response.setContentType(PolicyUtils.APPLICATION_JSON);
- PrintWriter out = response.getWriter();
String responseString = mapper.writeValueAsString(commonClassDao.getData(GlobalRoleSettings.class));
- JSONObject j = new JSONObject("{descriptiveScopeDictionaryDatas: " + responseString + "}");
-
- out.write(j.toString());
- return null;
+ response.getWriter().write(new JSONObject("{descriptiveScopeDictionaryDatas: " + responseString
+ + "}").toString());
} catch (Exception e) {
LOGGER.error("Exception Occured" + e);
- response.setCharacterEncoding(CHARACTER_ENCODING);
- request.setCharacterEncoding(CHARACTER_ENCODING);
- PrintWriter out = response.getWriter();
- out.write(PolicyUtils.CATCH_EXCEPTION);
+ response.getWriter().write(PolicyUtils.CATCH_EXCEPTION);
}
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
index 44a133068..dc342eeed 100644
--- 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
@@ -26,12 +26,11 @@ 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;
+
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;
@@ -45,9 +44,11 @@ import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.Stream;
+
import javax.script.SimpleBindings;
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;
@@ -57,7 +58,7 @@ 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.rest.util.PDPPolicyContainer;
+import org.onap.policy.rest.util.PdpPolicyContainer;
import org.onap.policy.utils.PolicyUtils;
import org.onap.policy.xacml.api.XACMLErrorConstants;
import org.onap.policy.xacml.api.pap.OnapPDPGroup;
@@ -78,13 +79,12 @@ import org.springframework.web.servlet.ModelAndView;
public class AutoPushController extends RestrictedBaseController {
private static final Logger logger = FlexLogger.getLogger(AutoPushController.class);
- private static final String UTF8 = "UTF-8";
@Autowired
CommonClassDao commonClassDao;
private PDPGroupContainer container;
- private PDPPolicyContainer policyContainer;
+ private PdpPolicyContainer policyContainer;
private PolicyController policyController;
protected List<OnapPDPGroup> groups = Collections.synchronizedList(new ArrayList<>());
@@ -96,6 +96,9 @@ public class AutoPushController extends RestrictedBaseController {
this.policyController = policyController;
}
+ /**
+ * refreshGroups.
+ */
public synchronized void refreshGroups() {
synchronized (this.groups) {
this.groups.clear();
@@ -114,7 +117,22 @@ public class AutoPushController extends RestrictedBaseController {
return policyController != null ? getPolicyController() : new PolicyController();
}
- @RequestMapping(value = {"/get_AutoPushPoliciesContainerData"}, method = {RequestMethod.GET},
+ private Set<String> addAllScopes(Roles userRole, Set<String> scopes) {
+ if (userRole.getScope() != null) {
+ scopes.addAll(Stream.of(userRole.getScope().split(",")).collect(Collectors.toSet()));
+ }
+ return scopes;
+ }
+
+ /**
+ * getPolicyGroupContainerData.
+ *
+ * @param request HttpServletRequest
+ * @param response HttpServletResponse
+ */
+ @RequestMapping(
+ value = {"/get_AutoPushPoliciesContainerData"},
+ method = {RequestMethod.GET},
produces = MediaType.APPLICATION_JSON_VALUE)
public void getPolicyGroupContainerData(HttpServletRequest request, HttpServletResponse response) {
try {
@@ -130,8 +148,9 @@ public class AutoPushController extends RestrictedBaseController {
for (Object role : userRoles) {
Roles userRole = (Roles) role;
roles.add(userRole.getRole());
- scopes.addAll(Stream.of(userRole.getScope().split(",")).collect(Collectors.toSet()));
+ addAllScopes(userRole, scopes);
}
+
if (roles.contains("super-admin") || roles.contains("super-editor") || roles.contains("super-guest")) {
data = commonClassDao.getData(PolicyVersion.class);
} else {
@@ -156,18 +175,30 @@ public class AutoPushController extends RestrictedBaseController {
ObjectMapper mapper = new ObjectMapper();
model.put("policydatas", mapper.writeValueAsString(data));
JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
- JSONObject j = new JSONObject(msg);
- response.getWriter().write(j.toString());
+ response.getWriter().write(new JSONObject(msg).toString());
} catch (Exception e) {
logger.error("Exception Occurred" + e);
}
}
+ /**
+ * pushPolicyToPDPGroup.
+ *
+ * @param request HttpServletRequest
+ * @param response HttpServletResponse
+ * @return ModelAndView
+ * @throws IOException IOException
+ */
@RequestMapping(value = {"/auto_Push/PushPolicyToPDP.htm"}, method = {RequestMethod.POST})
public ModelAndView pushPolicyToPDPGroup(HttpServletRequest request, HttpServletResponse response)
throws IOException {
try {
- ArrayList<Object> selectedPDPS = new ArrayList<>();
+ response.setCharacterEncoding(PolicyUtils.CHARACTER_ENCODING);
+ request.setCharacterEncoding(PolicyUtils.CHARACTER_ENCODING);
+ //
+ //
+ //
+ ArrayList<Object> selectedPdps = new ArrayList<>();
ArrayList<String> selectedPoliciesInUI = new ArrayList<>();
PolicyController controller = getPolicyControllerInstance();
this.groups.addAll(controller.getPapEngine().getOnapPDPGroups());
@@ -178,17 +209,17 @@ public class AutoPushController extends RestrictedBaseController {
String userId = UserUtils.getUserSession(request).getOrgUserId();
logger.info(
- "****************************************Logging UserID while Pushing Policy to PDP Group*****************************************");
+ "**********************Logging UserID while Pushing Policy to PDP Group***********************");
logger.info("UserId: " + userId + "Push Policy Data: " + root.get("pushTabData").toString());
logger.info(
- "***********************************************************************************************************************************");
+ "**********************************************************************************************");
AutoPushTabAdapter adapter = mapper.readValue(root.get("pushTabData").toString(), AutoPushTabAdapter.class);
for (Object pdpGroupId : adapter.getPdpDatas()) {
- LinkedHashMap<?, ?> selectedPDP = (LinkedHashMap<?, ?>) pdpGroupId;
+ LinkedHashMap<?, ?> selectedPdp = (LinkedHashMap<?, ?>) pdpGroupId;
for (OnapPDPGroup pdpGroup : this.groups) {
- if (pdpGroup.getId().equals(selectedPDP.get("id"))) {
- selectedPDPS.add(pdpGroup);
+ if (pdpGroup.getId().equals(selectedPdp.get("id"))) {
+ selectedPdps.add(pdpGroup);
}
}
}
@@ -200,7 +231,7 @@ public class AutoPushController extends RestrictedBaseController {
selectedPoliciesInUI.add(policyName);
}
- for (Object pdpDestinationGroupId : selectedPDPS) {
+ for (Object pdpDestinationGroupId : selectedPdps) {
Set<PDPPolicy> currentPoliciesInGroup = new HashSet<>();
Set<PDPPolicy> selectedPolicies = new HashSet<>();
for (String policyId : selectedPoliciesInUI) {
@@ -246,10 +277,9 @@ public class AutoPushController extends RestrictedBaseController {
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);
+ selectedPolicy = new StdPDPPolicy(name, true, id, temp.toURI());
} catch (IOException e) {
logger.error("Unable to create policy '" + name + "': " + e.getMessage(), e);
}
@@ -263,7 +293,7 @@ public class AutoPushController extends RestrictedBaseController {
}
// copy policy to PAP
try {
- controller.getPapEngine().copyPolicy(selectedPolicy, (StdPDPGroup) pdpDestinationGroupId);
+ controller.getPapEngine().copyPolicy(selectedPolicy, (StdPDPGroup) pdpDestinationGroupId, userId);
} catch (PAPException e) {
logger.error("Exception Occured" + e);
return null;
@@ -307,53 +337,47 @@ public class AutoPushController extends RestrictedBaseController {
currentPoliciesInGroup.addAll(selectedPolicies);
updatedGroupObject.setPolicies(currentPoliciesInGroup);
this.container.updateGroup(updatedGroupObject, userId);
-
- response.setCharacterEncoding(UTF8);
- response.setContentType("application / json");
- request.setCharacterEncoding(UTF8);
-
- PrintWriter out = response.getWriter();
+ response.setContentType(PolicyUtils.APPLICATION_JSON);
refreshGroups();
- JsonMessage msg = new JsonMessage(mapper.writeValueAsString(groups));
- JSONObject j = new JSONObject(msg);
- out.write(j.toString());
- //
- // Why is this here? This defeats the purpose of the loop??
- // Sonar says to remove it or make it conditional
- //
- return null;
+ response.getWriter().write(new JSONObject(
+ new JsonMessage(mapper.writeValueAsString(groups))).toString());
}
} catch (Exception e) {
- response.setCharacterEncoding(UTF8);
- request.setCharacterEncoding(UTF8);
- PrintWriter out = response.getWriter();
logger.error(e);
- out.write(PolicyUtils.CATCH_EXCEPTION);
+ response.getWriter().write(PolicyUtils.CATCH_EXCEPTION);
}
return null;
}
+ /**
+ * removePDPGroup.
+ */
@SuppressWarnings("unchecked")
@RequestMapping(value = {"/auto_Push/remove_GroupPolicies.htm"}, method = {RequestMethod.POST})
public ModelAndView removePDPGroup(HttpServletRequest request, HttpServletResponse response) throws IOException {
try {
+ response.setCharacterEncoding(PolicyUtils.CHARACTER_ENCODING);
+ request.setCharacterEncoding(PolicyUtils.CHARACTER_ENCODING);
+ //
+ //
+ //
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 = mapper.readValue(root.get("activePdpGroup").toString(), StdPDPGroup.class);
- JsonNode removePolicyData = root.get("data");
+ final StdPDPGroup group = mapper.readValue(root.get("activePdpGroup").toString(), StdPDPGroup.class);
+ final JsonNode removePolicyData = root.get("data");
String userId = UserUtils.getUserSession(request).getOrgUserId();
logger.info(
- "****************************************Logging UserID while Removing Policy from PDP Group*****************************************");
+ "**********************Logging UserID while Removing Policy from PDP Group*********************");
logger.info("UserId: " + userId + "PDP Group Data: " + root.get("activePdpGroup").toString()
+ "Remove Policy Data: " + root.get("data"));
logger.info(
- "***********************************************************************************************************************************");
+ "**********************************************************************************************");
- policyContainer = new PDPPolicyContainer(group);
+ policyContainer = new PdpPolicyContainer(group);
if (removePolicyData.size() > 0) {
IntStream.range(0, removePolicyData.size()).mapToObj(i -> removePolicyData.get(i).toString())
.forEach(polData -> this.policyContainer.removeItem(polData));
@@ -366,27 +390,16 @@ public class AutoPushController extends RestrictedBaseController {
updatedGroupObject.setPipConfigs(group.getPipConfigs());
updatedGroupObject.setStatus(group.getStatus());
updatedGroupObject.setOperation("delete");
- this.container.updateGroup(updatedGroupObject);
+ this.container.updateGroup(updatedGroupObject, userId);
}
- response.setCharacterEncoding(UTF8);
- response.setContentType("application / json");
- request.setCharacterEncoding(UTF8);
+ response.setContentType(PolicyUtils.APPLICATION_JSON);
- PrintWriter out = response.getWriter();
refreshGroups();
- JsonMessage msg = new JsonMessage(mapper.writeValueAsString(groups));
- JSONObject j = new JSONObject(msg);
-
- out.write(j.toString());
-
- return null;
+ response.getWriter().write(new JSONObject(new JsonMessage(mapper.writeValueAsString(groups))).toString());
} catch (Exception e) {
- response.setCharacterEncoding(UTF8);
- request.setCharacterEncoding(UTF8);
- PrintWriter out = response.getWriter();
logger.error(e);
- out.write(PolicyUtils.CATCH_EXCEPTION);
+ response.getWriter().write(PolicyUtils.CATCH_EXCEPTION);
}
return null;
}
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
index 8c14048c4..143d675bf 100644
--- 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
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP Policy Engine
* ================================================================================
- * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
* Modified Copyright (C) 2018 Samsung Electronics Co., Ltd.
* Modifications Copyright (C) 2019 Bell Canada
* ================================================================================
@@ -22,7 +22,10 @@
package org.onap.policy.controller;
-import java.io.PrintWriter;
+import com.fasterxml.jackson.databind.DeserializationFeature;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
@@ -36,20 +39,32 @@ import java.util.Objects;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
-
import java.util.stream.Collectors;
+
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
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.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.apache.commons.collections.CollectionUtils;
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.BrmsParamTemplate;
import org.onap.policy.rest.jpa.PolicyEntity;
+import org.onap.policy.utils.PolicyUtils;
import org.onap.policy.xacml.api.XACMLErrorConstants;
import org.onap.portalsdk.core.controller.RestrictedBaseController;
import org.springframework.beans.factory.annotation.Autowired;
@@ -57,21 +72,6 @@ import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
-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.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 {
@@ -104,8 +104,13 @@ public class CreateBRMSParamController extends RestrictedBaseController {
private static String brmsTemplateVlaue = "<$%BRMSParamTemplate=";
private static String string = "String";
-
- @RequestMapping(value = {"/policyController/getBRMSTemplateData.htm"}, method = { RequestMethod.POST})
+ /**
+ * getBRMSParamPolicyRuleData.
+ *
+ * @param request HttpServletRequest
+ * @param response HttpServletResponse
+ */
+ @RequestMapping(value = {"/policyController/getBRMSTemplateData.htm"}, method = {RequestMethod.POST})
public void getBRMSParamPolicyRuleData(HttpServletRequest request, HttpServletResponse response) {
try {
dynamicLayoutMap = new HashMap<>();
@@ -118,20 +123,17 @@ public class CreateBRMSParamController extends RestrictedBaseController {
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());
+ response.getWriter().write(new JSONObject("{policyData: " + mapper.writeValueAsString(dynamicLayoutMap)
+ + "}").toString());
} catch (Exception e) {
policyLogger.error("Exception Occured while getting BRMS Rule data", e);
}
}
private String findRule(String ruleTemplate) {
- List<Object> datas = commonClassDao.getDataById(BRMSParamTemplate.class, "ruleName", ruleTemplate);
- if(CollectionUtils.isNotEmpty(datas)){
- BRMSParamTemplate bRMSParamTemplate = (BRMSParamTemplate) datas.get(0);
- return bRMSParamTemplate.getRule();
+ List<Object> datas = commonClassDao.getDataById(BrmsParamTemplate.class, "ruleName", ruleTemplate);
+ if (CollectionUtils.isNotEmpty(datas)) {
+ return ((BrmsParamTemplate) datas.get(0)).getRule();
}
return null;
}
@@ -151,7 +153,7 @@ public class CreateBRMSParamController extends RestrictedBaseController {
private void processRule(String rule) {
StringBuilder params = getParamsBuilderFromRule(rule);
params = new StringBuilder(
- params.toString().replace("declare Params", "").replace("end", "").replaceAll("\\s+", ""));
+ params.toString().replace("declare Params", "").replace("end", "").replaceAll("\\s+", ""));
String[] components = params.toString().split(":");
String caption = "";
for (int i = 0; i < components.length; i++) {
@@ -243,79 +245,85 @@ public class CreateBRMSParamController extends RestrictedBaseController {
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
+ /**
+ * prePopulateBRMSParamPolicyData.
+ * 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.
+ *
+ * @param policyAdapter PolicyRestAdapter
+ * @param entity PolicyEntity
*/
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
+ if (! (policyAdapter.getPolicyData() instanceof PolicyType)) {
+ return;
+ }
+ 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("Error getting description: " + e);
- description = policy.getDescription();
- }
- policyAdapter.setPolicyDescription(description);
- setDataAdapterFromAdviceExpressions(policy, policyAdapter);
+ }
+ policyAdapter.setPolicyName(policyNameValue);
+ String description;
+ try {
+ description = policy.getDescription().substring(0, policy.getDescription().indexOf("@CreatedBy:"));
+ } catch (Exception e) {
+ policyLogger.info("Error getting description: " + e);
+ description = policy.getDescription();
+ }
+ policyAdapter.setPolicyDescription(description);
+ setDataAdapterFromAdviceExpressions(policy, policyAdapter);
- // Generate Param UI
- try {
- paramUIGenerate(policyAdapter, entity);
- } catch (Exception e) {
- policyLogger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + e.getMessage() + e);
- }
+ // Generate Param UI
+ try {
+ paramUiGenerate(policyAdapter, entity);
+ } catch (Exception e) {
+ policyLogger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + e.getMessage() + e);
+ }
- // Get the target data under policy.
- policyAdapter.setDynamicLayoutMap(dynamicLayoutMap);
- if (policyAdapter.getDynamicLayoutMap().size() > 0) {
- LinkedHashMap<String, String> drlRule = policyAdapter.getDynamicLayoutMap()
- .keySet().stream()
- .collect(Collectors
- .toMap(String::toString, keyValue -> policyAdapter.getDynamicLayoutMap().get(keyValue),
- (a, b) -> b, LinkedHashMap::new));
- policyAdapter.setRuleData(drlRule);
- }
- TargetType target = policy.getTarget();
- if (target != null) {
- setDataToAdapterFromTarget(target, policyAdapter);
- }
+ // Get the target data under policy.
+ policyAdapter.setDynamicLayoutMap(dynamicLayoutMap);
+ if (policyAdapter.getDynamicLayoutMap().size() > 0) {
+ LinkedHashMap<String, String> drlRule = policyAdapter.getDynamicLayoutMap().keySet().stream()
+ .collect(Collectors.toMap(String::toString,
+ keyValue -> policyAdapter.getDynamicLayoutMap().get(keyValue), (a, b) -> b,
+ LinkedHashMap::new));
+ policyAdapter.setRuleData(drlRule);
+ }
+ TargetType target = policy.getTarget();
+ if (target != null) {
+ setDataToAdapterFromTarget(target, policyAdapter);
}
}
private void setDataAdapterFromAdviceExpressions(PolicyType policy, PolicyRestAdapter policyAdapter) {
ArrayList<Object> attributeList = new ArrayList<>();
// Set Attributes.
- AdviceExpressionsType expressionTypes = ((RuleType) policy
- .getCombinerParametersOrRuleCombinerParametersOrVariableDefinition().get(0)).getAdviceExpressions();
+ AdviceExpressionsType expressionTypes =
+ ((RuleType) policy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition().get(0))
+ .getAdviceExpressions();
for (AdviceExpressionType adviceExpression : expressionTypes.getAdviceExpression()) {
for (AttributeAssignmentExpressionType attributeAssignment : adviceExpression
- .getAttributeAssignmentExpression()) {
+ .getAttributeAssignmentExpression()) {
if (attributeAssignment.getAttributeId().startsWith("key:")) {
Map<String, String> attribute = new HashMap<>();
String key = attributeAssignment.getAttributeId().replace("key:", "");
attribute.put("key", key);
@SuppressWarnings("unchecked")
- JAXBElement<AttributeValueType> attributeValue = (JAXBElement<AttributeValueType>) attributeAssignment
- .getExpression();
+ JAXBElement<AttributeValueType> attributeValue =
+ (JAXBElement<AttributeValueType>) attributeAssignment.getExpression();
String value = (String) attributeValue.getValue().getContent().get(0);
attribute.put("value", value);
attributeList.add(attribute);
} else if (attributeAssignment.getAttributeId().startsWith("dependencies:")) {
- ArrayList<String> dependencies = new ArrayList<>(
- Arrays.asList(attributeAssignment.getAttributeId().replace("dependencies:", "").split(",")));
+ ArrayList<String> dependencies = new ArrayList<>(Arrays
+ .asList(attributeAssignment.getAttributeId().replace("dependencies:", "").split(",")));
dependencies.remove("");
policyAdapter.setBrmsDependency(dependencies);
} else if (attributeAssignment.getAttributeId().startsWith("controller:")) {
@@ -328,14 +336,11 @@ public class CreateBRMSParamController extends RestrictedBaseController {
private void setDataToAdapterFromTarget(TargetType target, PolicyRestAdapter policyAdapter) {
// Under target we have AnyOFType
- List<AnyOfType> anyOfList = target.getAnyOf();
- if (anyOfList == null) {
+ if (target.getAnyOf() == null) {
return;
}
- anyOfList.stream().map(AnyOfType::getAllOf)
- .filter(Objects::nonNull)
- .flatMap(Collection::stream)
- .forEach(allOf -> setDataToAdapterFromMatchList(allOf.getMatch(), policyAdapter));
+ target.getAnyOf().stream().map(AnyOfType::getAllOf).filter(Objects::nonNull).flatMap(Collection::stream)
+ .forEach(allOf -> setDataToAdapterFromMatchList(allOf.getMatch(), policyAdapter));
}
private void setDataToAdapterFromMatchList(List<MatchType> matchList, PolicyRestAdapter policyAdapter) {
@@ -351,25 +356,12 @@ public class CreateBRMSParamController extends RestrictedBaseController {
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")) {
- PolicyController controller = new PolicyController();
- String newDate = controller.convertDate(value);
- policyAdapter.setTtlDate(newDate);
- }
+ policyAdapter.setupUsingAttribute(attributeId, value);
}
}
// This method generates the UI from rule configuration
- private void paramUIGenerate(PolicyRestAdapter policyAdapter, PolicyEntity entity) {
+ private void paramUiGenerate(PolicyRestAdapter policyAdapter, PolicyEntity entity) {
String data = entity.getConfigurationData().getConfigBody();
if (data == null) {
return;
@@ -390,8 +382,8 @@ public class CreateBRMSParamController extends RestrictedBaseController {
String value = line.substring(line.indexOf("<%$"), line.indexOf("$%>"));
value = value.replaceAll("<%\\$Values=", "");
Arrays.stream(value.split(":\\|:")).map(keyValue -> keyValue.split(":-:"))
- .filter(pair -> pair.length > 0)
- .forEach(pair -> dynamicLayoutMap.put(pair[0], (pair.length > 1) ? pair[1] : ""));
+ .filter(pair -> pair.length > 0)
+ .forEach(pair -> dynamicLayoutMap.put(pair[0], (pair.length > 1) ? pair[1] : ""));
return;
}
if (line.startsWith("/*")) {
@@ -429,32 +421,26 @@ public class CreateBRMSParamController extends RestrictedBaseController {
}
}
params = new StringBuilder(params.substring(params.indexOf(".Params\"") + 11));
- params = new StringBuilder(params.toString().replaceAll("\\s+", "")
- .replace("salience1000whenthenParamsparams=newParams();", "")
- .replace("insert(params);end", "")
- .replace("params.set", ""));
+ params = new StringBuilder(
+ params.toString().replaceAll("\\s+", "").replace("salience1000whenthenParamsparams=newParams();", "")
+ .replace("insert(params);end", "").replace("params.set", ""));
updateCaptionToDynamicLayoutMap(params);
}
private void updateCaptionToDynamicLayoutMap(final StringBuilder params) {
String[] components = params.toString().split("\\);");
- if(components.length > 0){
+ if (components.length > 0) {
for (int i = 0; i < components.length; i++) {
String value;
components[i] = components[i] + ")";
- String caption = components[i].substring(0,
- components[i].indexOf('('));
+ 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("\")", "");
+ 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(")", "");
+ value = components[i].substring(components[i].indexOf('('), components[i].indexOf(')'))
+ .replace("(", "").replace(")", "");
}
dynamicLayoutMap.put(caption, value);
}
@@ -473,8 +459,7 @@ public class CreateBRMSParamController extends RestrictedBaseController {
private String processMultiLineFullComment(String line) {
try {
- line = splitMultiLineStartComment(line)
- + splitMultiLineEndComment(line);
+ line = splitMultiLineStartComment(line) + splitMultiLineEndComment(line);
} catch (Exception e) {
policyLogger.info("Just for Logging" + e);
line = splitMultiLineStartComment(line);
@@ -482,28 +467,33 @@ public class CreateBRMSParamController extends RestrictedBaseController {
return line;
}
- // set View Rule
+ /**
+ * setViewRule.
+ *
+ * @param request HttpServletRequest
+ * @param response HttpServletResponse
+ */
@SuppressWarnings("unchecked")
- @RequestMapping(value = {"/policyController/ViewBRMSParamPolicyRule.htm"}, method = { RequestMethod.POST})
+ @RequestMapping(value = {"/policyController/ViewBRMSParamPolicyRule.htm"}, method = {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);
+ 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("\"", ""));
+ root.get(PolicyController.getPolicydata()).get("model").get("name").toString().replace("\"", ""));
if (root.get(PolicyController.getPolicydata()).get("model").get("type").toString().replace("\"", "")
- .equals(PolicyController.getFile())) {
+ .equals(PolicyController.getFile())) {
policyData.setEditPolicy(true);
}
String body = findRule(policyData.getRuleName()) + "\n";
StringBuilder generatedMetadata = new StringBuilder().append(
- "/* Autogenerated Code Please Don't change/remove this comment section. This is for the UI purpose. \n\t ")
- .append(brmsTemplateVlaue).append(policyData.getRuleName()).append("%$> \n */ \n");
+ "/* Autogenerated Code Please Don't change/remove this comment section. "
+ + "This is for the UI purpose. \n\t ")
+ .append(brmsTemplateVlaue).append(policyData.getRuleName()).append("%$> \n */ \n");
if (policyData.getDynamicLayoutMap().size() > 0) {
generatedMetadata.append("/* <%$Values=");
@@ -518,36 +508,31 @@ public class CreateBRMSParamController extends RestrictedBaseController {
policyLogger.info("Metadata generated with :" + generatedMetadata.toString());
body = generatedMetadata.toString() + body;
// Expand the body.
- Map<String, String> copyMap = new HashMap<>(
- (Map<? extends String, ? extends String>) policyData.getRuleData());
+ Map<String, String> copyMap =
+ new HashMap<>((Map<? extends String, ? extends String>) policyData.getRuleData());
copyMap.put("policyName",
- policyData.getDomainDir().replace("\\", ".") + ".Config_BRMS_Param_" + policyData.getPolicyName());
+ 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.
+ // Finding all the keys in the Map data-structure.
Set<String> keySet = copyMap.keySet();
Iterator<String> iterator = keySet.iterator();
- Pattern p;
- Matcher m;
while (iterator.hasNext()) {
- //Converting the first character of the key into a lower case.
+ // 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());
+ String output = Character.toLowerCase(input.charAt(0)) + (input.length() > 1 ? input.substring(1) : "");
+ // Searching for a pattern in the String using the key.
+ Pattern pattern = Pattern.compile("\\$\\{" + output + "\\}");
+ Matcher matcher = pattern.matcher(body);
+ // Replacing the value with the inputs provided by the user in the editor.
+ body = matcher.replaceAll(copyMap.get(input));
+ }
+ response.setCharacterEncoding(PolicyUtils.CHARACTER_ENCODING);
+ response.setContentType(PolicyUtils.APPLICATION_JSON);
+ request.setCharacterEncoding(PolicyUtils.CHARACTER_ENCODING);
+
+ response.getWriter().write(new JSONObject("{policyData: " + mapper.writeValueAsString(body)
+ + "}").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
index 93ca28190..487165b56 100644
--- 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
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP Policy Engine
* ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017, 2019 AT&T Intellectual Property. All rights reserved.
* Modifications Copyright (C) 2019 Bell Canada
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
@@ -27,8 +27,8 @@ import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
-
import java.util.Objects;
+
import javax.xml.bind.JAXBElement;
import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionType;
@@ -36,7 +36,6 @@ 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.PolicyType;
import oasis.names.tc.xacml._3_0.core.schema.wd_17.RuleType;
@@ -53,74 +52,65 @@ public class CreateBRMSRawController {
protected PolicyRestAdapter policyAdapter = null;
- @SuppressWarnings("unchecked")
+ /**
+ * prePopulateBRMSRawPolicyData.
+ *
+ * @param policyAdapter PolicyRestAdapter
+ * @param entity PolicyEntity
+ */
public void prePopulateBRMSRawPolicyData(PolicyRestAdapter policyAdapter, PolicyEntity entity) {
- if (policyAdapter.getPolicyData() instanceof PolicyType) {
- PolicyType policy = (PolicyType) policyAdapter.getPolicyData();
- policyAdapter.setOldPolicyFileName(policyAdapter.getPolicyName());
-
- // Set PolicyAdapter name value
- setPolicyAdapterNameValue(policyAdapter);
+ if (! (policyAdapter.getPolicyData() instanceof PolicyType)) {
+ return;
+ }
+ PolicyType policy = (PolicyType) policyAdapter.getPolicyData();
+ policyAdapter.setOldPolicyFileName(policyAdapter.getPolicyName());
- // Set PolicyAdapter description.
- setPolicyAdapterDescription(policyAdapter, policy);
+ // Set PolicyAdapter name value
+ setPolicyAdapterNameValue(policyAdapter);
- // Set PolicyAdapter attributes.
- setPolicyAdapterAttributes(policyAdapter, policy);
+ // Set PolicyAdapter description.
+ setPolicyAdapterDescription(policyAdapter, policy);
- // Set PolicyAdapter configBodyData
- policyAdapter.setConfigBodyData(entity.getConfigurationData().getConfigBody());
+ // Set PolicyAdapter attributes.
+ setPolicyAdapterAttributes(policyAdapter, policy);
- // Get the target data under policy.
- TargetType target = policy.getTarget();
- if (target == null) {
- return;
- }
- // Under target we have AnyOFType
- List<AnyOfType> anyOfList = target.getAnyOf();
- if (anyOfList == null) {
- return;
- }
+ // Set PolicyAdapter configBodyData
+ policyAdapter.setConfigBodyData(entity.getConfigurationData().getConfigBody());
- // Set PolicyAdapter riskType, riskLevel, guard, ttlDate from match attributes
- setPolicyAdapterMatchAttributes(policyAdapter, policy.getTarget().getAnyOf());
+ // Get the target data under policy.
+ TargetType target = policy.getTarget();
+ if (target == null) {
+ return;
+ }
+ // Under target we have AnyOFType
+ List<AnyOfType> anyOfList = target.getAnyOf();
+ if (anyOfList == null) {
+ return;
}
+
+ // Set PolicyAdapter riskType, riskLevel, guard, ttlDate from match attributes
+ setPolicyAdapterMatchAttributes(policyAdapter, policy.getTarget().getAnyOf());
}
private void setPolicyAdapterMatchAttributes(PolicyRestAdapter policyAdapter, List<AnyOfType> anyOfList) {
anyOfList.stream()
- //Extract nonNull list of AllOfType objs from each AnyOfType obj
- .map(AnyOfType::getAllOf).filter(Objects::nonNull)
- .forEach(allOfList ->
- //Extract nonNull list of MatchType objs from each AllOFType obj
- allOfList.stream().map(AllOfType::getMatch).filter(Objects::nonNull)
- .flatMap(Collection::stream)
- .forEach(match -> {
- // 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);
- } else if ("RiskLevel".equals(attributeId)) {
- policyAdapter.setRiskLevel(value);
- } else if ("guard".equals(attributeId)) {
- policyAdapter.setGuard(value);
- } else if ("TTLDate".equals(attributeId) && !value.contains("NA")) {
- PolicyController controller = new PolicyController();
- String newDate = controller.convertDate(value);
- policyAdapter.setTtlDate(newDate);
- }
- }));
+ // Extract nonNull list of AllOfType objs from each AnyOfType obj
+ .map(AnyOfType::getAllOf).filter(Objects::nonNull).forEach(allOfList ->
+ // Extract nonNull list of MatchType objs from each AllOFType obj
+ allOfList.stream().map(AllOfType::getMatch).filter(Objects::nonNull).flatMap(Collection::stream)
+ .forEach(match -> {
+ // Under the match we have attribute value and
+ // attributeDesignator. So,finally down to the actual attribute.
+ policyAdapter.setupUsingAttribute(match.getAttributeDesignator().getAttributeId(),
+ (String) match.getAttributeValue().getContent().get(0));
+ }));
}
private void setPolicyAdapterNameValue(final PolicyRestAdapter policyAdapter) {
// policy name value is the policy name without any prefix and extensions.
- String policyNameValue = policyAdapter.getPolicyName()
- .substring(policyAdapter.getPolicyName().indexOf("BRMS_Raw_") + 9);
+ 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());
}
@@ -138,30 +128,31 @@ public class CreateBRMSRawController {
policyAdapter.setPolicyDescription(description);
}
+ @SuppressWarnings("unchecked")
private void setPolicyAdapterAttributes(final PolicyRestAdapter policyAdapter, final PolicyType policy) {
ArrayList<Object> attributeList = new ArrayList<>();
- AdviceExpressionsType expressionTypes = ((RuleType) policy
- .getCombinerParametersOrRuleCombinerParametersOrVariableDefinition().get(0)).getAdviceExpressions();
+ AdviceExpressionsType expressionTypes =
+ ((RuleType) policy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition().get(0))
+ .getAdviceExpressions();
for (AdviceExpressionType adviceExpression : expressionTypes.getAdviceExpression()) {
for (AttributeAssignmentExpressionType attributeAssignment : adviceExpression
- .getAttributeAssignmentExpression()) {
+ .getAttributeAssignmentExpression()) {
if (attributeAssignment.getAttributeId().startsWith("key:")) {
Map<String, String> attribute = new HashMap<>();
String key = attributeAssignment.getAttributeId().replace("key:", "");
attribute.put("key", key);
- JAXBElement<AttributeValueType> attributeValue = (JAXBElement<AttributeValueType>) attributeAssignment
- .getExpression();
+ JAXBElement<AttributeValueType> attributeValue =
+ (JAXBElement<AttributeValueType>) attributeAssignment.getExpression();
String value = (String) attributeValue.getValue().getContent().get(0);
attribute.put("value", value);
attributeList.add(attribute);
} else if (attributeAssignment.getAttributeId().startsWith("dependencies:")) {
ArrayList<String> dependencies = new ArrayList<>(Arrays
- .asList(attributeAssignment.getAttributeId().replace("dependencies:", "").split(",")));
+ .asList(attributeAssignment.getAttributeId().replace("dependencies:", "").split(",")));
dependencies.remove("");
policyAdapter.setBrmsDependency(dependencies);
} else if (attributeAssignment.getAttributeId().startsWith("controller:")) {
- policyAdapter
- .setBrmsController(attributeAssignment.getAttributeId().replace("controller:", ""));
+ policyAdapter.setBrmsController(attributeAssignment.getAttributeId().replace("controller:", ""));
}
}
policyAdapter.setAttributes(attributeList);
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
index 4c3249311..58765ded1 100644
--- 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
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP Policy Engine
* ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017, 2019 AT&T Intellectual Property. All rights reserved.
* Modifications Copyright (C) 2019 Bell Canada
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
@@ -21,6 +21,10 @@
package org.onap.policy.controller;
+import com.fasterxml.jackson.databind.DeserializationFeature;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
@@ -29,9 +33,15 @@ import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
-
import java.util.Objects;
import java.util.stream.IntStream;
+import lombok.Getter;
+import lombok.Setter;
+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.PolicyType;
+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.ClosedLoopFaultBody;
@@ -40,26 +50,14 @@ 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.onap.policy.utils.PolicyUtils;
import org.onap.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.PolicyType;
-import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType;
-
@Controller
@RequestMapping("/")
public class CreateClosedLoopFaultController extends RestrictedBaseController {
@@ -74,7 +72,6 @@ public class CreateClosedLoopFaultController extends RestrictedBaseController {
private static final String CONNECT_TRAP_2 = "connectTrap2";
private static final String TRAP_COUNT_2 = "trapCount2";
private static final String TRIGGER_1 = "trigger1";
- private static final String ENC_UTF_8 = "UTF-8";
private static final String TRIGGER_2 = "trigger2";
protected PolicyRestAdapter policyAdapter = null;
@@ -90,19 +87,25 @@ public class CreateClosedLoopFaultController extends RestrictedBaseController {
// Empty constructor
}
+ /**
+ * setDataToPolicyRestAdapter.
+ *
+ * @param policyData PolicyRestAdapter
+ * @param root JsonNode
+ * @return PolicyRestAdapter
+ */
public PolicyRestAdapter setDataToPolicyRestAdapter(PolicyRestAdapter policyData, JsonNode root) {
try {
ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
- ClosedLoopFaultTrapDatas trapDatas = mapper
- .readValue(root.get("trapData").toString(), ClosedLoopFaultTrapDatas.class);
- ClosedLoopFaultTrapDatas faultDatas = mapper
- .readValue(root.get("faultData").toString(), ClosedLoopFaultTrapDatas.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);
+ final ClosedLoopFaultTrapDatas trapDatas =
+ mapper.readValue(root.get("trapData").toString(), ClosedLoopFaultTrapDatas.class);
+ final ClosedLoopFaultTrapDatas faultDatas =
+ mapper.readValue(root.get("faultData").toString(), ClosedLoopFaultTrapDatas.class);
+ final ClosedLoopGridJsonData policyJsonData =
+ mapper.readValue(root.get("policyData").get("policy").toString(), ClosedLoopGridJsonData.class);
+ final ClosedLoopFaultBody jsonBody = mapper.readValue(
+ root.get("policyData").get("policy").get("jsonBodyData").toString(), ClosedLoopFaultBody.class);
// Build trapSignatureDatas list from faultData
List<Object> trapSignatureDatas = new ArrayList<>();
@@ -118,10 +121,10 @@ public class CreateClosedLoopFaultController extends RestrictedBaseController {
triggerSignatures.setTrapMaxAge(Integer.parseInt(policyData.getTrapMaxAge()));
ClosedLoopFaultTriggerUISignatures uiTriggerSignatures = new ClosedLoopFaultTriggerUISignatures();
if (!trapSignatureDatas.isEmpty()) {
- uiTriggerSignatures.setSignatures(getUITriggerSignature(TRAP, trapSignatureDatas.get(0)));
+ uiTriggerSignatures.setSignatures(getUiTriggerSignature(TRAP, trapSignatureDatas.get(0)));
if (!policyJsonData.getConnecttriggerSignatures().isEmpty()) {
uiTriggerSignatures
- .setConnectSignatures(getUIConnectTraps(policyJsonData.getConnecttriggerSignatures()));
+ .setConnectSignatures(getUiConnectTraps(policyJsonData.getConnecttriggerSignatures()));
}
}
jsonBody.setTriggerSignaturesUsedForUI(uiTriggerSignatures);
@@ -144,19 +147,17 @@ public class CreateClosedLoopFaultController extends RestrictedBaseController {
faultSignatures.setTimeWindow(Integer.parseInt(policyData.getVerificationclearTimeOut()));
ClosedLoopFaultTriggerUISignatures uifaultSignatures = new ClosedLoopFaultTriggerUISignatures();
if (!faultSignatureDatas.isEmpty()) {
- uifaultSignatures.setSignatures(getUITriggerSignature(FAULT, faultSignatureDatas.get(0)));
+ uifaultSignatures.setSignatures(getUiTriggerSignature(FAULT, faultSignatureDatas.get(0)));
if (!policyJsonData.getConnectVerificationSignatures().isEmpty()) {
- uifaultSignatures
- .setConnectSignatures(getUIConnectTraps(policyJsonData.getConnectVerificationSignatures()));
+ uifaultSignatures.setConnectSignatures(
+ getUiConnectTraps(policyJsonData.getConnectVerificationSignatures()));
}
}
jsonBody.setVerificationSignaturesUsedForUI(uifaultSignatures);
jsonBody.setVerificationTimeWindowUsedForUI(Integer.parseInt(policyData.getVerificationclearTimeOut()));
}
jsonBody.setVerificationSignatures(faultSignatures);
- ObjectWriter om = new ObjectMapper().writer();
- String json = om.writeValueAsString(jsonBody);
- policyData.setJsonBody(json);
+ policyData.setJsonBody(new ObjectMapper().writer().writeValueAsString(jsonBody));
} catch (Exception e) {
policyLogger.error("Exception Occured while setting data to Adapter", e);
@@ -165,13 +166,14 @@ public class CreateClosedLoopFaultController extends RestrictedBaseController {
}
// TODO: Can getResultBody() and getFaultBody() be merged?
- private String getResultBody(final ClosedLoopGridJSONData policyJsonData, final List<Object> trapSignatureDatas) {
+ private String getResultBody(final ClosedLoopGridJsonData policyJsonData, final List<Object> trapSignatureDatas) {
StringBuilder resultBody = new StringBuilder();
if (!policyJsonData.getConnecttriggerSignatures().isEmpty()) {
resultBody.append("(");
IntStream.range(0, policyJsonData.getConnecttriggerSignatures().size())
- .mapToObj(i -> connectTriggerSignature(i, policyJsonData.getConnecttriggerSignatures(),
- trapSignatureDatas.get(0))).forEach(resultBody::append);
+ .mapToObj(i -> connectTriggerSignature(i, policyJsonData.getConnecttriggerSignatures(),
+ trapSignatureDatas.get(0)))
+ .forEach(resultBody::append);
resultBody.append(resultBody).append(")");
} else {
if (!trapSignatureDatas.isEmpty()) {
@@ -181,13 +183,14 @@ public class CreateClosedLoopFaultController extends RestrictedBaseController {
return resultBody.toString();
}
- private String getFaultBody(final ClosedLoopGridJSONData policyJsonData, final List<Object> faultSignatureDatas) {
+ private String getFaultBody(final ClosedLoopGridJsonData policyJsonData, final List<Object> faultSignatureDatas) {
StringBuilder faultBody = new StringBuilder();
if (!policyJsonData.getConnectVerificationSignatures().isEmpty()) {
faultBody.append("(");
IntStream.range(0, policyJsonData.getConnectVerificationSignatures().size())
- .mapToObj(i -> connectTriggerSignature(i, policyJsonData.getConnectVerificationSignatures(),
- faultSignatureDatas.get(0))).forEach(faultBody::append);
+ .mapToObj(i -> connectTriggerSignature(i, policyJsonData.getConnectVerificationSignatures(),
+ faultSignatureDatas.get(0)))
+ .forEach(faultBody::append);
faultBody.append(")");
} else {
if (!faultSignatureDatas.isEmpty()) {
@@ -237,7 +240,7 @@ public class CreateClosedLoopFaultController extends RestrictedBaseController {
}
private void appendTrapToResultBody(List<Object> triggerSignatures, Object object, StringBuilder resultBody,
- Map<String, String> connectTraps, String connectTrapName) {
+ Map<String, String> connectTraps, String connectTrapName) {
String connectTrap = connectTraps.get(connectTrapName);
if (connectTrap.startsWith(TRAP) || connectTrap.startsWith(FAULT)) {
String trapBody = callTrap(connectTrap, object);
@@ -339,16 +342,18 @@ public class CreateClosedLoopFaultController extends RestrictedBaseController {
attributesStr = attributesStr + "(" + readAttributes(objectList, iy) + ")";
} catch (NumberFormatException e) {
try {
- trap1Attrib = getVarbindOID(trap1Attrib);
- attributesStr = attributesStr + "(" + URLEncoder.encode(trap1Attrib, ENC_UTF_8) + ")";
+ trap1Attrib = getVarbindOid(trap1Attrib);
+ attributesStr = attributesStr + "(" + URLEncoder.encode(trap1Attrib,
+ PolicyUtils.CHARACTER_ENCODING) + ")";
} catch (UnsupportedEncodingException e1) {
policyLogger.error("Caused Exception while Encoding Varbind Dictionary Values", e1);
}
}
} else {
try {
- trap1Attrib = getVarbindOID(trap1Attrib);
- attributesStr = attributesStr + "(" + URLEncoder.encode(trap1Attrib, ENC_UTF_8) + ")";
+ trap1Attrib = getVarbindOid(trap1Attrib);
+ attributesStr = attributesStr + "(" + URLEncoder.encode(trap1Attrib,
+ PolicyUtils.CHARACTER_ENCODING) + ")";
} catch (UnsupportedEncodingException e) {
policyLogger.error("Caused Exception while Encoding Varbind Dictionary Values", e);
}
@@ -356,21 +361,21 @@ public class CreateClosedLoopFaultController extends RestrictedBaseController {
return attributesStr;
}
- private String getVarbindOID(String attrib) {
+ private String getVarbindOid(String attrib) {
VarbindDictionary varbindId;
try {
- varbindId = (VarbindDictionary) commonclassdao
- .getEntityItem(VarbindDictionary.class, "varbindName", attrib);
- return varbindId.getVarbindOID();
+ varbindId =
+ (VarbindDictionary) commonclassdao.getEntityItem(VarbindDictionary.class, "varbindName", attrib);
+ return varbindId.getVarbindOid();
} catch (Exception e) {
policyLogger.error("Error during retrieving varbindName " + attrib, e);
return attrib;
}
}
- //connect traps data set to JSON Body as String
+ // connect traps data set to JSON Body as String
@SuppressWarnings({"unchecked", "rawtypes"})
- private String getUIConnectTraps(List<Object> connectTrapSignatures) {
+ private String getUiConnectTraps(List<Object> connectTrapSignatures) {
StringBuilder resultBody = new StringBuilder();
String connectMainBody = "";
for (Object connectTrapSignature : connectTrapSignatures) {
@@ -401,9 +406,8 @@ public class CreateClosedLoopFaultController extends RestrictedBaseController {
if (((LinkedHashMap) connectTraps).get(TRAP_COUNT_2) != null) {
trapCount2 = ((LinkedHashMap) connectTraps).get(TRAP_COUNT_2).toString();
}
- connectBody =
- notBox + "@!" + connectTrap1 + "@!" + trapCount1 + "@!" + operatorBox + "@!" + connectTrap2 + "@!"
- + trapCount2 + "#!?!";
+ connectBody = notBox + "@!" + connectTrap1 + "@!" + trapCount1 + "@!" + operatorBox + "@!"
+ + connectTrap2 + "@!" + trapCount2 + "#!?!";
}
resultBody.append(connectBody);
}
@@ -412,7 +416,7 @@ public class CreateClosedLoopFaultController extends RestrictedBaseController {
}
// get Trigger signature from JSON body
- private String getUITriggerSignature(String trap, Object object2) {
+ private String getUiTriggerSignature(String trap, Object object2) {
ClosedLoopFaultTrapDatas trapDatas = (ClosedLoopFaultTrapDatas) object2;
List<Object> attributeList = new ArrayList<>();
// Read the Trap
@@ -473,89 +477,69 @@ public class CreateClosedLoopFaultController extends RestrictedBaseController {
return triggerBody.toString();
}
+ /**
+ * prePopulateClosedLoopFaultPolicyData.
+ *
+ * @param policyAdapter PolicyRestAdapter
+ * @param entity PolicyEntity
+ */
public void prePopulateClosedLoopFaultPolicyData(PolicyRestAdapter policyAdapter, PolicyEntity entity) {
- if (policyAdapter.getPolicyData() instanceof PolicyType) {
- PolicyType policy = (PolicyType) policyAdapter.getPolicyData();
-
- // Set PolicyAdapter policyName, description
- setPolicyAdapterPolicyNameAndDescription(policyAdapter, policy);
-
- // Set PolicyAdapter JsonBodyData, timeout settings
- setClosedLoopJSONFile(policyAdapter, entity);
+ if (! (policyAdapter.getPolicyData() instanceof PolicyType)) {
+ return;
+ }
+ PolicyType policy = (PolicyType) policyAdapter.getPolicyData();
- // Get the target data under policy.
- TargetType target = policy.getTarget();
- if (target == null) {
- return;
- }
+ // Set PolicyAdapter policyName, description
+ setPolicyAdapterPolicyNameAndDescription(policyAdapter, policy);
- // Under target we have AnyOFType
- List<AnyOfType> anyOfList = target.getAnyOf();
- if (anyOfList == null) {
- return;
- }
+ // Set PolicyAdapter JsonBodyData, timeout settings
+ setClosedLoopJsonFile(policyAdapter, entity);
- // Set PolicyAdapter OnapNameField, riskType, riskLevel, guard, ttlDate from match attributes
- setPolicyAdapterMatchAttributes(policyAdapter, anyOfList);
+ // Get the target data under policy.
+ TargetType target = policy.getTarget();
+ if (target == null) {
+ return;
}
+
+ // Set PolicyAdapter OnapNameField, riskType, riskLevel, guard, ttlDate from match attributes
+ setPolicyAdapterMatchAttributes(policyAdapter, target.getAnyOf());
}
private void setPolicyAdapterMatchAttributes(PolicyRestAdapter policyAdapter, List<AnyOfType> anyOfList) {
anyOfList.stream()
- //Extract nonNull list of AllOfType objs from each AnyOfType obj
- .map(AnyOfType::getAllOf).filter(Objects::nonNull)
- .forEach(allOfList ->
- //Extract nonNull list of MatchType objs from each AllOFType obj
- allOfList.stream().map(AllOfType::getMatch).filter(Objects::nonNull)
- .flatMap(Collection::stream)
- .forEach(match -> {
- // 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)) {
- policyAdapter.setOnapName(value);
- OnapName onapName = new OnapName();
- onapName.setOnapName(value);
- policyAdapter.setOnapNameField(onapName);
- } else if ("RiskType".equals(attributeId)) {
- policyAdapter.setRiskType(value);
- } else if ("RiskLevel".equals(attributeId)) {
- policyAdapter.setRiskLevel(value);
- } else if ("guard".equals(attributeId)) {
- policyAdapter.setGuard(value);
- } else if ("TTLDate".equals(attributeId) && !value.contains("NA")) {
- PolicyController controller = new PolicyController();
- String newDate = controller.convertDate(value);
- policyAdapter.setTtlDate(newDate);
- }
- }));
+ // Extract nonNull list of AllOfType objs from each AnyOfType obj
+ .map(AnyOfType::getAllOf).filter(Objects::nonNull).forEach(allOfList ->
+ // Extract nonNull list of MatchType objs from each AllOFType obj
+ allOfList.stream().map(AllOfType::getMatch).filter(Objects::nonNull).flatMap(Collection::stream)
+ .forEach(match -> {
+ // Under the match we have attribute value and
+ // attributeDesignator. So,finally down to the actual attribute.
+ policyAdapter.setupUsingAttribute(match.getAttributeDesignator().getAttributeId(),
+ (String) match.getAttributeValue().getContent().get(0));
+ }));
}
private void setPolicyAdapterPolicyNameAndDescription(PolicyRestAdapter policyAdapter, PolicyType policy) {
policyAdapter.setOldPolicyFileName(policyAdapter.getPolicyName());
- String policyNameValue = policyAdapter.getPolicyName()
- .substring(policyAdapter.getPolicyName().indexOf("Fault_") + 6);
+ 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) {
policyLogger.error(
- "Error during collecting the description tag info for createClosedLoopFault " + policyNameValue, e);
+ "Error during collecting the description tag info for createClosedLoopFault " + policyNameValue, e);
description = policy.getDescription();
}
policyAdapter.setPolicyDescription(description);
}
- private void setClosedLoopJSONFile(PolicyRestAdapter policyAdapter, PolicyEntity entity) {
- ObjectMapper mapper = new ObjectMapper();
+ private void setClosedLoopJsonFile(PolicyRestAdapter policyAdapter, PolicyEntity entity) {
try {
- ClosedLoopFaultBody closedLoopBody = mapper
- .readValue(entity.getConfigurationData().getConfigBody(), ClosedLoopFaultBody.class);
+ ClosedLoopFaultBody closedLoopBody =
+ new ObjectMapper().readValue(entity.getConfigurationData().getConfigBody(),
+ ClosedLoopFaultBody.class);
if ("ACTIVE".equalsIgnoreCase(closedLoopBody.getClosedLoopPolicyStatus())) {
closedLoopBody.setClosedLoopPolicyStatus("Active");
} else {
@@ -570,7 +554,7 @@ public class CreateClosedLoopFaultController extends RestrictedBaseController {
}
if (closedLoopBody.getVerificationTimeWindowUsedForUI() != null) {
policyAdapter
- .setVerificationclearTimeOut(closedLoopBody.getVerificationTimeWindowUsedForUI().toString());
+ .setVerificationclearTimeOut(closedLoopBody.getVerificationTimeWindowUsedForUI().toString());
}
} catch (Exception e) {
policyLogger.error("Exception Occured" + e);
@@ -578,7 +562,10 @@ public class CreateClosedLoopFaultController extends RestrictedBaseController {
}
}
-class ClosedLoopGridJSONData {
+
+@Getter
+@Setter
+class ClosedLoopGridJsonData {
private String clearTimeOut;
private String trapMaxAge;
@@ -586,44 +573,4 @@ class ClosedLoopGridJSONData {
private List<Object> connecttriggerSignatures;
private List<Object> 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 List<Object> getConnecttriggerSignatures() {
- return connecttriggerSignatures;
- }
-
- public void setConnecttriggerSignatures(List<Object> connecttriggerSignatures) {
- this.connecttriggerSignatures = connecttriggerSignatures;
- }
-
- public List<Object> getConnectVerificationSignatures() {
- return connectVerificationSignatures;
- }
-
- public void setConnectVerificationSignatures(List<Object> connectVerificationSignatures) {
- this.connectVerificationSignatures = connectVerificationSignatures;
- }
}
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
index d2b04e024..058542590 100644
--- 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
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP Policy Engine
* ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017, 2019 AT&T Intellectual Property. All rights reserved.
* Modifications Copyright (C) 2019 Bell Canada
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
@@ -21,23 +21,16 @@
package org.onap.policy.controller;
+import com.fasterxml.jackson.databind.ObjectMapper;
+
import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.List;
-
import java.util.Objects;
+
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;
@@ -45,6 +38,13 @@ import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType;
import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType;
import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType;
+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;
+
public class CreateClosedLoopPMController {
private static final Logger LOGGER = FlexLogger.getLogger(CreateClosedLoopPMController.class);
@@ -52,38 +52,40 @@ public class CreateClosedLoopPMController {
protected PolicyRestAdapter policyAdapter = null;
+ /**
+ * prePopulateClosedLoopPMPolicyData.
+ *
+ * @param policyAdapter PolicyRestAdapter
+ * @param entity PolicyEntity
+ */
public void prePopulateClosedLoopPMPolicyData(PolicyRestAdapter policyAdapter, PolicyEntity entity) {
- if (policyAdapter.getPolicyData() instanceof PolicyType) {
- Object policyData = policyAdapter.getPolicyData();
- PolicyType policy = (PolicyType) policyData;
+ if (! (policyAdapter.getPolicyData() instanceof PolicyType)) {
+ return;
+ }
+ Object policyData = policyAdapter.getPolicyData();
+ PolicyType policy = (PolicyType) policyData;
- // Set oldPolicyFileName to PolicyAdapter
- policyAdapter.setOldPolicyFileName(policyAdapter.getPolicyName());
+ // Set oldPolicyFileName to PolicyAdapter
+ policyAdapter.setOldPolicyFileName(policyAdapter.getPolicyName());
- // Set policyNameValue and description to PolicyAdapter
- setPolicyAdapterNameValueAndDescription(policyAdapter, policy);
+ // Set policyNameValue and description to PolicyAdapter
+ setPolicyAdapterNameValueAndDescription(policyAdapter, policy);
- // Set PolicyAdapter JsonBodyData
- setClosedLoopJSONFile(policyAdapter, entity);
+ // Set PolicyAdapter JsonBodyData
+ setClosedLoopJsonFile(policyAdapter, entity);
- // Get the target data under policy.
- TargetType target = policy.getTarget();
- if (target == null) {
- return;
- }
- // Under target we have AnyOFType
- List<AnyOfType> anyOfList = target.getAnyOf();
- if (anyOfList == null) {
- return;
- }
- // Set PolicyAdapter OnapNameField, riskType, riskLevel, guard, ttlDate, ServiceType from match attributes
- setPolicyAdapterMatchAttributes(policyAdapter, anyOfList);
+ // Get the target data under policy.
+ TargetType target = policy.getTarget();
+ if (target == null) {
+ return;
}
+ // Set PolicyAdapter OnapNameField, riskType, riskLevel, guard, ttlDate, ServiceType from match attributes
+ setPolicyAdapterMatchAttributes(policyAdapter, target.getAnyOf());
}
private void setPolicyAdapterNameValueAndDescription(PolicyRestAdapter policyAdapter, PolicyType policy) {
- String policyNameValue = policyAdapter.getPolicyName()
- .substring(policyAdapter.getPolicyName().indexOf("PM_") + 3);
+ String policyNameValue =
+ policyAdapter.getPolicyName().substring(policyAdapter.getPolicyName().indexOf("PM_") + 3);
policyAdapter.setPolicyName(policyNameValue);
String description;
try {
@@ -95,11 +97,10 @@ public class CreateClosedLoopPMController {
policyAdapter.setPolicyDescription(description);
}
- private void setClosedLoopJSONFile(PolicyRestAdapter policyAdapter, PolicyEntity entity) {
- ObjectMapper mapper = new ObjectMapper();
+ private void setClosedLoopJsonFile(PolicyRestAdapter policyAdapter, PolicyEntity entity) {
try {
- ClosedLoopPMBody closedLoopBody = mapper
- .readValue(entity.getConfigurationData().getConfigBody(), ClosedLoopPMBody.class);
+ ClosedLoopPMBody closedLoopBody =
+ new ObjectMapper().readValue(entity.getConfigurationData().getConfigBody(), ClosedLoopPMBody.class);
policyAdapter.setJsonBodyData(closedLoopBody);
} catch (IOException e) {
LOGGER.error("Exception Occured" + e);
@@ -107,51 +108,39 @@ public class CreateClosedLoopPMController {
}
private void setPolicyAdapterMatchAttributes(final PolicyRestAdapter policyAdapter,
- final List<AnyOfType> anyOfList) {
+ final List<AnyOfType> anyOfList) {
anyOfList.stream()
- //Extract nonNull list of AllOfType objs from each AnyOfType obj
- .map(AnyOfType::getAllOf).filter(Objects::nonNull)
- .forEach(allOfList ->
- //Extract nonNull list of MatchType objs from each AllOFType obj
+ // Extract nonNull list of AllOfType objs from each AnyOfType obj
+ .map(AnyOfType::getAllOf).filter(Objects::nonNull).forEach(allOfList ->
+ // Extract nonNull list of MatchType objs from each AllOFType obj
allOfList.stream().map(AllOfType::getMatch).filter(Objects::nonNull)
- .forEach(matchList -> matchList.forEach(match -> {
- // 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)) {
- policyAdapter.setOnapName(value);
- } else if ("RiskType".equals(attributeId)) {
- policyAdapter.setRiskType(value);
- } else if ("RiskLevel".equals(attributeId)) {
- policyAdapter.setRiskLevel(value);
- } else if ("guard".equals(attributeId)) {
- policyAdapter.setGuard(value);
- } else if ("TTLDate".equals(attributeId) && !value.contains("NA")) {
- PolicyController controller = new PolicyController();
- String newDate = controller.convertDate(value);
- policyAdapter.setTtlDate(newDate);
- } else if ("ServiceType".equals(attributeId)) {
- LinkedHashMap<String, String> serviceTypePolicyName1 = new LinkedHashMap<>();
- serviceTypePolicyName1.put(KEY_SERVICE_TYPE_POLICY_NAME, value);
- policyAdapter.setServiceTypePolicyName(serviceTypePolicyName1);
- LinkedHashMap<String, String> vertica = new LinkedHashMap<>();
- vertica.put("verticaMetrics", getVertica(value));
- policyAdapter.setVerticaMetrics(vertica);
- LinkedHashMap<String, String> desc = new LinkedHashMap<>();
- desc.put("policyDescription", getDescription(value));
- policyAdapter.setDescription(desc);
- LinkedHashMap<String, Object> attributes = new LinkedHashMap<>();
- attributes.put("attributes", getAttributes(value));
- policyAdapter.setAttributeFields(attributes);
- }
- })));
+ .forEach(matchList -> matchList.forEach(match -> {
+ // 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.
+ policyAdapter.setupUsingAttribute(attributeId, value);
+ if ("ServiceType".equals(attributeId)) {
+ LinkedHashMap<String, String> serviceTypePolicyName1 = new LinkedHashMap<>();
+ serviceTypePolicyName1.put(KEY_SERVICE_TYPE_POLICY_NAME, value);
+ policyAdapter.setServiceTypePolicyName(serviceTypePolicyName1);
+ LinkedHashMap<String, String> vertica = new LinkedHashMap<>();
+ vertica.put("verticaMetrics", getVertica(value));
+ policyAdapter.setVerticaMetrics(vertica);
+ LinkedHashMap<String, String> desc = new LinkedHashMap<>();
+ desc.put("policyDescription", getDescription(value));
+ policyAdapter.setDescription(desc);
+ LinkedHashMap<String, Object> attributes = new LinkedHashMap<>();
+ attributes.put("attributes", getAttributes(value));
+ policyAdapter.setAttributeFields(attributes);
+ }
+ })));
}
- //get vertica metrics data from the table
+ // get vertica metrics data from the table
private String getVertica(String policyName) {
JsonArray data = PolicyManagerServlet.getPolicyNames();
for (int i = 0; i < data.size(); i++) {
@@ -162,7 +151,7 @@ public class CreateClosedLoopPMController {
return null;
}
- //get policy description from the table
+ // get policy description from the table
private String getDescription(String policyName) {
JsonArray data = PolicyManagerServlet.getPolicyNames();
for (int i = 0; i < data.size(); i++) {
@@ -173,7 +162,7 @@ public class CreateClosedLoopPMController {
return null;
}
- //get Attributes
+ // get Attributes
private JsonObject getAttributes(String policyName) {
JsonArray data = PolicyManagerServlet.getPolicyNames();
for (int i = 0; i < data.size(); i++) {
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
index a8df74add..4be31dd1e 100644
--- 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
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP Policy Engine
* ================================================================================
- * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2020 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -20,7 +20,6 @@
package org.onap.policy.controller;
-
import com.att.research.xacml.util.XACMLProperties;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
@@ -37,12 +36,13 @@ import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
-import java.io.PrintWriter;
import java.io.StringReader;
+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.Base64;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
@@ -68,10 +68,10 @@ import javax.json.JsonReader;
import javax.json.JsonValue;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
+import lombok.Getter;
+import lombok.Setter;
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;
@@ -82,20 +82,22 @@ 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.apache.commons.lang3.StringEscapeUtils;
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.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.MicroserviceHeaderdeFaults;
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.onap.policy.rest.util.MsAttributeObject;
+import org.onap.policy.rest.util.MsModelUtils;
+import org.onap.policy.rest.util.MsModelUtils.ModelType;
+import org.onap.policy.utils.PolicyUtils;
import org.onap.portalsdk.core.controller.RestrictedBaseController;
import org.onap.portalsdk.core.web.support.JsonMessage;
import org.springframework.beans.factory.annotation.Autowired;
@@ -124,7 +126,7 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController {
private String directory;
private List<String> modelList = new ArrayList<>();
private List<String> dirDependencyList = new ArrayList<>();
- private LinkedHashMap<String, MSAttributeObject> classMap = new LinkedHashMap<>();
+ private LinkedHashMap<String, MsAttributeObject> classMap = new LinkedHashMap<>();
String referenceAttributes;
String attributeString;
Set<String> allManyTrueKeys = null;
@@ -158,6 +160,13 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController {
private Map<String, LinkedList<String>> arrayTextList = new HashMap<>();
private Map<String, String> jsonStringValues = new HashMap<>();
+ /**
+ * setDataToPolicyRestAdapter.
+ *
+ * @param policyData PolicyRestAdapter
+ * @param root JsonNode
+ * @return PolicyRestAdapter
+ */
public PolicyRestAdapter setDataToPolicyRestAdapter(PolicyRestAdapter policyData, JsonNode root) {
String jsonContent = null;
@@ -165,10 +174,8 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController {
LOGGER.info("policyJSON :" + (root.get(POLICYJSON)).toString());
String tempJson = root.get(POLICYJSON).toString();
- JSONObject policyJSON = new JSONObject(root.get(POLICYJSON).toString());
- if (policyJSON != null) {
- tempJson = saveOriginalJsonObject(policyJSON, jsonStringValues).toString();
- }
+ JSONObject policyJson = new JSONObject(root.get(POLICYJSON).toString());
+ tempJson = decodeJsonVal(tempJson, policyJson);
// ---replace empty value with the value below before calling decodeContent method.
String dummyValue = "*empty-value*" + UUID.randomUUID().toString();
LOGGER.info("dummyValue:" + dummyValue);
@@ -189,12 +196,28 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController {
JSONObject content = contentJson.getJSONObject("content");
content = setOriginalJsonObject(content, jsonStringValues);
contentJson.put("content", content);
- policyData.setJsonBody(contentJson.toString());
+ policyData.setJsonBody(StringEscapeUtils.unescapeJava(contentJson.toString()));
}
return policyData;
}
+ private String decodeJsonVal(String tempJson, JSONObject policyJson) {
+ if (policyJson != null) {
+ for (Object key : policyJson.keySet()) {
+ String keyStr = (String) key;
+ Object keyvalue = policyJson.get(keyStr);
+ String decodedString = keyvalue.toString();//.replace("\"", "");
+ if(!decodedString.equals("true") && !decodedString.equals("false")) {
+ String decodedJson = new String(Base64.getDecoder().decode(decodedString), StandardCharsets.UTF_8).replace("\"", "\\\"");
+ policyJson.put(keyStr, decodedJson);
+ }
+ }
+ tempJson = saveOriginalJsonObject(policyJson, jsonStringValues).toString();
+ }
+ return tempJson;
+ }
+
private JSONObject saveOriginalJsonObject(JSONObject jsonObj, Map<String, String> jsonStringValues) {
for (Object key : jsonObj.keySet()) {
String keyStr = (String) key;
@@ -259,7 +282,7 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController {
String json = "";
DCAEMicroServiceObject microServiceObject = new DCAEMicroServiceObject();
MicroServiceModels returnModel = new MicroServiceModels();
- microServiceObject.setTemplateVersion(XACMLProperties.getProperty(XACMLRestProperties.TemplateVersion_MS));
+ microServiceObject.setTemplateVersion(XACMLProperties.getProperty(XacmlRestProperties.TEMPLATE_VERSION_MS));
if (policyAdapter.getServiceType() != null) {
microServiceObject.setService(policyAdapter.getServiceType());
microServiceObject.setVersion(policyAdapter.getVersion());
@@ -309,15 +332,11 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController {
modelName + ":" + versionName);
MicroServiceModels model = null;
boolean ruleCheck = false;
- boolean SymptomRuleCheck = false;
if (!triggerData.isEmpty()) {
model = (MicroServiceModels) triggerData.get(0);
if (model.getRuleFormation() != null) {
microServiceObject.setUiContent(jsonContent);
ruleCheck = true;
- if (model.getRuleFormation().contains("@")) {
- SymptomRuleCheck = true;
- }
}
}
try {
@@ -327,7 +346,7 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController {
}
LOGGER.info("input json: " + json);
LOGGER.info("input jsonContent: " + jsonContent);
- String cleanJson = cleanUPJson(json);
+ String cleanJson = cleanUpJson(json);
// --- reset empty value back after called cleanUPJson method and before calling removeNullAttributes
String tempJson =
StringUtils.replaceEach(cleanJson, new String[] {"\"" + dummyValue + "\""}, new String[] {"\"\""});
@@ -340,40 +359,39 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController {
// for Triggers
ObjectMapper mapper = new ObjectMapper();
JsonNode tempJsonNode = mapper.readTree(cleanJson);
- if (ruleCheck) {
- // JsonNode tempJsonNode = mapper.readTree(cleanJson);
- ObjectNode finalJson = (ObjectNode) tempJsonNode;
- JsonNode object = tempJsonNode.get("content");
- String primaryKey1 = model.getRuleFormation();
- String[] primaryKeyForSignatures = primaryKey1.split("@");
- for (String primaryKeyForSignature : primaryKeyForSignatures) {
- String primarykeyAlarm = primaryKeyForSignature.substring(0, primaryKeyForSignature.indexOf('.'));
- JsonNode triggerSig = object.get(primarykeyAlarm);
- sigRules = new HashMap<>();
- String parseKey = primaryKeyForSignature.substring(primaryKeyForSignature.indexOf('.') + 1);
- StringBuilder sb = null;
- if (triggerSig instanceof ArrayNode) {
- for (int i = 0; i < triggerSig.size(); i++) {
- sb = new StringBuilder();
- parseData(triggerSig.get(i), parseKey);
- sb.append("(");
- List<?> keyList = new ArrayList<>(sigRules.keySet());
- for (int j = keyList.size() - 1; j >= 0; j--) {
- String key = (String) keyList.get(j);
- String jsonNode = sigRules.get(key);
- constructRule(sb, jsonNode, sigRules);
- }
- sb.append(")").toString();
- putRuletoJson(tempJsonNode, i, sb, parseKey, primarykeyAlarm);
- sigRules = new HashMap<>();
- }
- } else {
+ if (! ruleCheck) {
+ return policyAdapter;
+ }
+ ObjectNode finalJson = (ObjectNode) tempJsonNode;
+ JsonNode object = tempJsonNode.get("content");
+ String primaryKey1 = model.getRuleFormation();
+ String[] primaryKeyForSignatures = primaryKey1.split("@");
+ for (String primaryKeyForSignature : primaryKeyForSignatures) {
+ String primarykeyAlarm = primaryKeyForSignature.substring(0, primaryKeyForSignature.indexOf('.'));
+ JsonNode triggerSig = object.get(primarykeyAlarm);
+ sigRules = new HashMap<>();
+ String parseKey = primaryKeyForSignature.substring(primaryKeyForSignature.indexOf('.') + 1);
+ StringBuilder sb = null;
+ if (triggerSig instanceof ArrayNode) {
+ for (int i = 0; i < triggerSig.size(); i++) {
sb = new StringBuilder();
- parseData(triggerSig, parseKey);
+ parseData(triggerSig.get(i), parseKey);
+ sb.append("(");
+ List<?> keyList = new ArrayList<>(sigRules.keySet());
+ for (int j = keyList.size() - 1; j >= 0; j--) {
+ String key = (String) keyList.get(j);
+ String jsonNode = sigRules.get(key);
+ constructRule(sb, jsonNode, sigRules);
+ }
+ sb.append(")").toString();
+ putRuletoJson(tempJsonNode, i, sb, parseKey, primarykeyAlarm);
+ sigRules = new HashMap<>();
}
+ } else {
+ parseData(triggerSig, parseKey);
}
- policyAdapter.setJsonBody(finalJson.toString());
}
+ policyAdapter.setJsonBody(finalJson.toString());
return policyAdapter;
}
@@ -486,6 +504,12 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController {
}
}
+ /**
+ * removeNullAttributes.
+ *
+ * @param cleanJson String
+ * @returnString
+ */
public String removeNullAttributes(String cleanJson) {
ObjectMapper mapper = new ObjectMapper();
@@ -529,9 +553,9 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController {
if (contentChanged) {
// set modified content to cleanJson
- JSONObject jObject = new JSONObject(cleanJson);
- jObject.put("content", removed.toString());
- cleanJson = cleanUPJson(jObject.toString());
+ JSONObject jsonObject = new JSONObject(cleanJson);
+ jsonObject.put("content", removed.toString());
+ cleanJson = cleanUpJson(jsonObject.toString());
}
} catch (IOException e) {
@@ -554,90 +578,93 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController {
if (arrOfKeys[i].contains(".")) {
arrOfKeys[i] = arrOfKeys[i].substring(arrOfKeys[i].indexOf(".") + 1);
if (arrOfKeys[i].equals(key)) {
- return StringUtils.replaceEach(jsonStringValues.get(k), new String[] {"\""},
- new String[] {"\\\""});
+ return jsonStringValues.get(k);
}
}
}
}
if (k.endsWith(key)) {
- return StringUtils.replaceEach(jsonStringValues.get(k), new String[] {"\""}, new String[] {"\\\""});
+ return jsonStringValues.get(k);
}
}
return null;
}
+ /**
+ * removeNull.
+ *
+ * @param array JsonArray
+ * @return JsonArray
+ */
public JsonArray removeNull(JsonArray array) {
JsonArrayBuilder builder = Json.createArrayBuilder();
- int i = 0;
- for (Iterator<JsonValue> it = array.iterator(); it.hasNext(); ++i) {
+ int index = 0;
+ for (Iterator<JsonValue> it = array.iterator(); it.hasNext(); ++index) {
JsonValue value = it.next();
switch (value.getValueType()) {
case ARRAY:
- JsonArray a = removeNull(array.getJsonArray(i));
- if (!a.isEmpty())
- builder.add(a);
+ JsonArray tempArray = removeNull(array.getJsonArray(index));
+ if (!tempArray.isEmpty()) {
+ builder.add(tempArray);
+ }
break;
case OBJECT:
- JsonObject object = removeNull(array.getJsonObject(i));
- if (!object.isEmpty())
+ JsonObject object = removeNull(array.getJsonObject(index));
+ if (!object.isEmpty()) {
builder.add(object);
+ }
break;
case STRING:
- String s = array.getString(i);
- if (s != null && !s.isEmpty())
- builder.add(s);
+ String str = array.getString(index);
+ if (str != null && !str.isEmpty()) {
+ builder.add(str);
+ }
break;
case NUMBER:
- builder.add(array.getJsonNumber(i));
+ builder.add(array.getJsonNumber(index));
break;
case TRUE:
case FALSE:
- builder.add(array.getBoolean(i));
+ builder.add(array.getBoolean(index));
break;
case NULL:
+ default:
break;
}
}
return builder.build();
}
+ /**
+ * removeNull.
+ *
+ * @param obj JsonObject
+ * @return JsonObject
+ */
public JsonObject removeNull(JsonObject obj) {
JsonObjectBuilder builder = Json.createObjectBuilder();
for (Iterator<Entry<String, JsonValue>> it = obj.entrySet().iterator(); it.hasNext();) {
- Entry<String, JsonValue> e = it.next();
- String key = e.getKey();
- JsonValue value = e.getValue();
+ Entry<String, JsonValue> entry = it.next();
+ String key = entry.getKey();
+ JsonValue value = entry.getValue();
switch (value.getValueType()) {
case ARRAY:
JsonArray array = removeNull(obj.getJsonArray(key));
- if (!array.isEmpty())
+ if (!array.isEmpty()) {
builder.add(key, array);
+ }
break;
case OBJECT:
JsonObject object = removeNull(obj.getJsonObject(key));
if (!object.isEmpty()) {
- if (!jsonStringValues.isEmpty()) {
- String originalValue = getOriginalValue(key);
- if (originalValue != null) {
- builder.add(key, object.toString());
- break;
- }
- }
builder.add(key, object);
}
break;
case STRING:
- String s = obj.getString(key);
- if (s != null && !s.isEmpty()) {
- if (!jsonStringValues.isEmpty()) {
- String originalValue = getOriginalValue(key);
- if (originalValue != null) {
- s = getOriginalValue(key);
- }
- }
- builder.add(key, s);
+ String str = obj.getString(key);
+ if (str != null && !str.isEmpty()) {
+ builder.add(key, str);
}
break;
case NUMBER:
@@ -648,13 +675,20 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController {
builder.add(key, obj.getBoolean(key));
break;
case NULL:
+ default:
break;
}
}
return builder.build();
}
- public String cleanUPJson(String json) {
+ /**
+ * cleanUpJson.
+ *
+ * @param json String
+ * @return String
+ */
+ public String cleanUpJson(String json) {
String cleanJson = StringUtils.replaceEach(json, new String[] {"\\\\", "\\\\\\", "\\\\\\\\"},
new String[] {"\\", "\\", "\\"});
cleanJson = StringUtils.replaceEach(cleanJson, new String[] {"\\\\\\"}, new String[] {"\\"});
@@ -675,6 +709,12 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController {
return cleanJson;
}
+ /**
+ * decodeContent.
+ *
+ * @param jsonNode JsonNode
+ * @return JsonNode
+ */
public JSONObject decodeContent(JsonNode jsonNode) {
Iterator<JsonNode> jsonElements = jsonNode.elements();
Iterator<String> jsonKeys = jsonNode.fieldNames();
@@ -825,7 +865,8 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController {
return jsonResult;
}
- @RequestMapping(value = {"/policyController/getDCAEMSTemplateData.htm"},
+ @RequestMapping(
+ value = {"/policyController/getDCAEMSTemplateData.htm"},
method = {org.springframework.web.bind.annotation.RequestMethod.POST})
public ModelAndView getDCAEMSTemplateData(HttpServletRequest request, HttpServletResponse response)
throws IOException {
@@ -862,8 +903,8 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController {
// Get all keys with "MANY-true" defined in their value from subAttribute
Set<String> allkeys = null;
- if (returnModel.getSub_attributes() != null && !returnModel.getSub_attributes().isEmpty()) {
- JSONObject json = new JSONObject(returnModel.getSub_attributes());
+ if (returnModel.getSubAttributes() != null && !returnModel.getSubAttributes().isEmpty()) {
+ JSONObject json = new JSONObject(returnModel.getSubAttributes());
getAllKeys(json);
allkeys = allManyTrueKeys;
allManyTrueKeys = new TreeSet<>();
@@ -882,7 +923,7 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController {
allMnyTrueKeys = allkeys.toString();
}
- String jsonModel = createMicroSeriveJson(returnModel, allkeys);
+ String jsonModel = createMicroSeriveJson(returnModel);
JSONObject jsonObject = new JSONObject(jsonModel);
@@ -901,8 +942,8 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController {
jsonModel = finalJsonObject.toString();
}
- // get all properties with "MANY-true" defined in Ref_attributes
- Set<String> manyTrueProperties = getManyTrueProperties(returnModel.getRef_attributes());
+ // get all properties with "MANY-true" defined in RefAttributes
+ Set<String> manyTrueProperties = getManyTrueProperties(returnModel.getRefAttributes());
if (manyTrueProperties != null) {
JSONObject jsonObj = new JSONObject(jsonModel);
for (String s : manyTrueProperties) {
@@ -918,37 +959,36 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController {
}
}
- response.setCharacterEncoding("UTF-8");
- response.setContentType("application / json");
- request.setCharacterEncoding("UTF-8");
+ response.setCharacterEncoding(PolicyUtils.CHARACTER_ENCODING);
+ response.setContentType(PolicyUtils.APPLICATION_JSON);
+ request.setCharacterEncoding(PolicyUtils.CHARACTER_ENCODING);
List<Object> list = new ArrayList<>();
- PrintWriter out = response.getWriter();
String responseString = mapper.writeValueAsString(returnModel);
- JSONObject j = null;
+ JSONObject json = null;
if ("".equals(allMnyTrueKeys)) {
- j = new JSONObject("{dcaeModelData: " + responseString + ",jsonValue: " + jsonModel + ",dataOrderInfo:"
+ json = new JSONObject("{dcaeModelData: " + responseString + ",jsonValue: " + jsonModel + ",dataOrderInfo:"
+ dataOrderInfo + ",headDefautlsData:" + headDefautlsData + "}");
} else {
- j = new JSONObject("{dcaeModelData: " + responseString + ",jsonValue: " + jsonModel + ",allManyTrueKeys: "
- + allMnyTrueKeys + ",dataOrderInfo:" + dataOrderInfo + ",headDefautlsData:" + headDefautlsData
- + "}");
+ json = new JSONObject("{dcaeModelData: " + responseString + ",jsonValue: " + jsonModel
+ + ",allManyTrueKeys: " + allMnyTrueKeys + ",dataOrderInfo:" + dataOrderInfo + ",headDefautlsData:"
+ + headDefautlsData + "}");
}
- list.add(j);
- out.write(list.toString());
+ list.add(json);
+ response.getWriter().write(list.toString());
return null;
}
@SuppressWarnings({"unchecked", "rawtypes"})
- private String createMicroSeriveJson(MicroServiceModels returnModel, Set<String> allkeys) {
+ private String createMicroSeriveJson(MicroServiceModels returnModel) {
Map<String, String> attributeMap = new HashMap<>();
Map<String, String> refAttributeMap = new HashMap<>();
String attribute = returnModel.getAttributes();
if (attribute != null) {
attribute = attribute.trim();
}
- String refAttribute = returnModel.getRef_attributes();
+ String refAttribute = returnModel.getRefAttributes();
if (refAttribute != null) {
refAttribute = refAttribute.trim();
}
@@ -965,7 +1005,7 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController {
Gson gson = new Gson();
- String subAttributes = returnModel.getSub_attributes();
+ String subAttributes = returnModel.getSubAttributes();
if (subAttributes != null) {
subAttributes = subAttributes.trim();
} else {
@@ -975,10 +1015,9 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController {
Map gsonObject = (Map) gson.fromJson(subAttributes, Object.class);
JSONObject object = new JSONObject();
- JSONArray array = new JSONArray();
for (Entry<String, String> keySet : attributeMap.entrySet()) {
- array = new JSONArray();
+ JSONArray array = new JSONArray();
String value = keySet.getValue();
if ("true".equalsIgnoreCase(keySet.getValue().split("MANY-")[1])) {
array.put(value);
@@ -989,7 +1028,7 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController {
}
for (Entry<String, String> keySet : refAttributeMap.entrySet()) {
- array = new JSONArray();
+ JSONArray array = new JSONArray();
String value = keySet.getValue().split(":")[0];
if (gsonObject.containsKey(value)) {
if ("true".equalsIgnoreCase(keySet.getValue().split("MANY-")[1])) {
@@ -1042,7 +1081,6 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController {
return object;
}
-
public JSONObject convertToArrayElement(JSONObject json, String keyValue) {
return convertToArrayElement(json, new HashSet<>(), keyValue);
}
@@ -1070,14 +1108,25 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController {
}
if (obj instanceof JSONArray) {
- convertToArrayElement(json.getJSONArray(key).getJSONObject(0), keyValue);
+ try {
+ if (json.getJSONArray(key).length() > 0) {
+ convertToArrayElement(json.getJSONArray(key).getJSONObject(0), keyValue);
+ }
+ } catch (Exception ex) {
+ LOGGER.info("XMI Model load issue : " + ex);
+ }
}
}
return json;
}
- // call this method to get all MANY-true properties
+ /**
+ * getManyTrueProperties.
+ *
+ * @param referAttributes String
+ * @return a Set of String
+ */
public Set<String> getManyTrueProperties(String referAttributes) {
LOGGER.info("referAttributes : " + referAttributes);
Set<String> manyTrueProperties = new HashSet<>();
@@ -1108,10 +1157,12 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController {
private Set<String> getAllKeys(JSONArray arr, Set<String> keys) {
for (int i = 0; i < arr.length(); i++) {
Object obj = arr.get(i);
- if (obj instanceof JSONObject)
+ if (obj instanceof JSONObject) {
keys.addAll(getAllKeys(arr.getJSONObject(i)));
- if (obj instanceof JSONArray)
+ }
+ if (obj instanceof JSONArray) {
keys.addAll(getAllKeys(arr.getJSONArray(i)));
+ }
}
return keys;
@@ -1126,37 +1177,42 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController {
LOGGER.info("obj : " + obj);
allManyTrueKeys.add(key);
}
- if (obj instanceof JSONObject)
+ if (obj instanceof JSONObject) {
keys.addAll(getAllKeys(json.getJSONObject(key)));
- if (obj instanceof JSONArray)
+ }
+ if (obj instanceof JSONArray) {
keys.addAll(getAllKeys(json.getJSONArray(key)));
+ }
}
return keys;
}
-
- @RequestMapping(value = {"/policyController/getModelServiceVersioneData.htm"},
+ /**
+ * getModelServiceVersionData.
+ *
+ * @param request HttpServletRequest
+ * @param response HttpServletResponse
+ * @return ModelAndView
+ * @throws IOException IOException
+ */
+ @RequestMapping(
+ value = {"/policyController/getModelServiceVersioneData.htm"},
method = {org.springframework.web.bind.annotation.RequestMethod.POST})
public ModelAndView getModelServiceVersionData(HttpServletRequest request, HttpServletResponse response)
throws IOException {
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("^\"|\"$", "");
+ response.setCharacterEncoding(PolicyUtils.CHARACTER_ENCODING);
+ response.setContentType(PolicyUtils.APPLICATION_JSON);
+ request.setCharacterEncoding(PolicyUtils.CHARACTER_ENCODING);
+ List<Object> list = new ArrayList<>();
+ String value = mapper.readTree(request.getReader()).get("policyData").toString().replaceAll("^\"|\"$", "");
String servicename = value.split("-v")[0];
Set<String> returnList = getVersionList(servicename);
-
- response.setCharacterEncoding("UTF-8");
- response.setContentType("application / json");
- request.setCharacterEncoding("UTF-8");
- List<Object> 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());
+ list.add(new JSONObject("{dcaeModelVersionData: " + mapper.writeValueAsString(returnList) + "}"));
+ response.getWriter().write(list.toString());
return null;
}
@@ -1201,7 +1257,8 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController {
modelName);
}
- @RequestMapping(value = {"/get_DCAEPriorityValues"},
+ @RequestMapping(
+ value = {"/get_DCAEPriorityValues"},
method = {org.springframework.web.bind.annotation.RequestMethod.GET},
produces = MediaType.APPLICATION_JSON_VALUE)
public void getDCAEPriorityValuesData(HttpServletRequest request, HttpServletResponse response) {
@@ -1214,93 +1271,64 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController {
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());
+ response.getWriter().write(new JSONObject(new JsonMessage(mapper.writeValueAsString(model))).toString());
} catch (Exception e) {
LOGGER.error(e);
}
}
+ /**
+ * prePopulateDCAEMSPolicyData.
+ *
+ * @param policyAdapter PolicyRestAdapter
+ * @param entity PolicyEntity
+ */
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) {
- LOGGER.error("Error while collecting the desciption tag in ActionPolicy " + policyNameValue, 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<AnyOfType> anyOfList = target.getAnyOf();
- if (anyOfList != null) {
- Iterator<AnyOfType> iterAnyOf = anyOfList.iterator();
- while (iterAnyOf.hasNext()) {
- AnyOfType anyOf = iterAnyOf.next();
- // Under AnyOFType we have AllOFType
- List<AllOfType> allOfList = anyOf.getAllOf();
- if (allOfList != null) {
- Iterator<AllOfType> iterAllOf = allOfList.iterator();
- while (iterAllOf.hasNext()) {
- AllOfType allOf = iterAllOf.next();
- // Under AllOFType we have Match
- List<MatchType> matchList = allOf.getMatch();
- if (matchList != null) {
- Iterator<MatchType> 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 ("ONAPName".equals(attributeId)) {
- policyAdapter.setOnapName(value);
- }
- if ("ConfigName".equals(attributeId)) {
- policyAdapter.setConfigName(value);
- }
- if ("uuid".equals(attributeId)) {
- policyAdapter.setUuid(value);
- }
- if ("location".equals(attributeId)) {
- policyAdapter.setLocation(value);
- }
- 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")) {
- PolicyController controller = new PolicyController();
- String newDate = controller.convertDate(value);
- policyAdapter.setTtlDate(newDate);
- }
- }
- readFile(policyAdapter, entity);
- }
- }
- }
- }
+ if (! (policyAdapter.getPolicyData() instanceof PolicyType)) {
+ return;
+ }
+ 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) {
+ LOGGER.error("Error while collecting the desciption tag in ActionPolicy " + policyNameValue, e);
+ description = policy.getDescription();
+ }
+ policyAdapter.setPolicyDescription(description);
+ // Get the target data under policy.
+ TargetType target = policy.getTarget();
+ if (target == null) {
+ return;
+ }
+ for (AnyOfType anyOf : target.getAnyOf()) {
+ for (AllOfType allOf : anyOf.getAllOf()) {
+ // Under AllOFType we have Match
+ List<MatchType> matchList = allOf.getMatch();
+ if (matchList == null) {
+ continue;
}
+ Iterator<MatchType> iterMatch = matchList.iterator();
+ //
+ // Can someone please explain why the matchList MUST have
+ // more than 1 matches???
+ //
+ 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.
+ //
+ // First match in the target is OnapName, so set that value.
+ policyAdapter.setupUsingAttribute(match.getAttributeDesignator().getAttributeId(),
+ (String) match.getAttributeValue().getContent().get(0));
+ }
+ readFile(policyAdapter, entity);
}
}
}
@@ -1321,7 +1349,6 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController {
return map;
}
-
/**
* Read file.
*
@@ -1330,12 +1357,11 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController {
*/
@SuppressWarnings("unchecked")
public void readFile(PolicyRestAdapter policyAdapter, PolicyEntity entity) {
- String policyScopeName = null;
- ObjectMapper mapper = new ObjectMapper();
try {
DCAEMicroServiceObject msBody =
- mapper.readValue(entity.getConfigurationData().getConfigBody(), DCAEMicroServiceObject.class);
- policyScopeName = getPolicyScope(msBody.getPolicyScope());
+ new ObjectMapper().readValue(entity.getConfigurationData().getConfigBody(),
+ DCAEMicroServiceObject.class);
+ String policyScopeName = getPolicyScope(msBody.getPolicyScope());
policyAdapter.setPolicyScope(policyScopeName);
policyAdapter.setPriority(msBody.getPriority());
@@ -1364,6 +1390,12 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController {
}
+ /**
+ * readRecursivlyJSONContent.
+ *
+ * @param map Map of String to something
+ * @param data Map of String to Object
+ */
@SuppressWarnings({"rawtypes", "unchecked"})
public void readRecursivlyJSONContent(Map<String, ?> map, Map<String, Object> data) {
for (Iterator iterator = map.keySet().iterator(); iterator.hasNext();) {
@@ -1401,16 +1433,27 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController {
}
}
+ /**
+ * getPolicyScope.
+ *
+ * @param value String
+ * @return String
+ */
public String getPolicyScope(String value) {
List<Object> groupList = commonClassDao.getDataById(GroupPolicyScopeList.class, "groupList", value);
if (groupList != null && !groupList.isEmpty()) {
- GroupPolicyScopeList pScope = (GroupPolicyScopeList) groupList.get(0);
- return pScope.getGroupName();
+ return ((GroupPolicyScopeList) groupList.get(0)).getGroupName();
}
return null;
}
- // Convert the map values and set into JSON body
+ /**
+ * Convert the map values and set into JSON body.
+ *
+ * @param attributesMap Map of attributes
+ * @param attributesRefMap Map of attribute references
+ * @return Map
+ */
public Map<String, String> convertMap(Map<String, String> attributesMap, Map<String, String> attributesRefMap) {
Map<String, String> attribute = new HashMap<>();
StringBuilder temp;
@@ -1448,7 +1491,8 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController {
return attribute;
}
- @RequestMapping(value = {"/ms_dictionary/set_MSModelData"},
+ @RequestMapping(
+ value = {"/ms_dictionary/set_MSModelData"},
method = {org.springframework.web.bind.annotation.RequestMethod.POST})
public void SetMSModelData(HttpServletRequest request, HttpServletResponse response)
throws IOException, FileUploadException {
@@ -1490,35 +1534,31 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController {
}
if (!errorMsg.isEmpty()) {
-
- PrintWriter out = response.getWriter();
-
response.setCharacterEncoding("UTF-8");
response.setContentType("application / json");
request.setCharacterEncoding("UTF-8");
- JSONObject j = new JSONObject();
- j.put("errorMsg", errorMsg);
- out.write(j.toString());
+ JSONObject json = new JSONObject();
+ json.put("errorMsg", errorMsg);
+ response.getWriter().write(json.toString());
return;
}
List<File> fileList = new ArrayList<>();
- MSModelUtils msMLUtils = new MSModelUtils(commonClassDao);
+ MsModelUtils msModelUtils = new MsModelUtils(commonClassDao);
this.directory = "model";
if (zip) {
extractFolder(this.newFile);
fileList = listModelFiles(this.directory);
} else if (yml) {
- errorMsg = msMLUtils.parseTosca(this.newFile);
+ errorMsg = msModelUtils.parseTosca(this.newFile);
if (errorMsg != null) {
- PrintWriter out = response.getWriter();
response.setCharacterEncoding("UTF-8");
response.setContentType("application / json");
request.setCharacterEncoding("UTF-8");
- JSONObject j = new JSONObject();
- j.put("errorMsg", errorMsg);
- out.write(j.toString());
+ JSONObject json = new JSONObject();
+ json.put("errorMsg", errorMsg);
+ response.getWriter().write(json.toString());
return;
}
@@ -1533,7 +1573,7 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController {
classMap = new LinkedHashMap<>();
for (File file : fileList) {
if (!file.isDirectory() && file.getName().endsWith(".xmi")) {
- retreiveDependency(file.toString(), true);
+ retrieveDependency(file.toString());
}
}
@@ -1545,25 +1585,25 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController {
modelType = "yml";
modelList.add(this.newModel.getModelName());
String className = this.newModel.getModelName();
- MSAttributeObject msAttributes = new MSAttributeObject();
+ MsAttributeObject msAttributes = new MsAttributeObject();
msAttributes.setClassName(className);
LinkedHashMap<String, String> returnAttributeList = new LinkedHashMap<>();
- returnAttributeList.put(className, msMLUtils.getAttributeString());
+ returnAttributeList.put(className, msModelUtils.getAttributeString());
msAttributes.setAttribute(returnAttributeList);
- msAttributes.setSubClass(msMLUtils.getRetmap());
+ msAttributes.setSubClass(msModelUtils.getRetmap());
- msAttributes.setMatchingSet(msMLUtils.getMatchableValues());
+ msAttributes.setMatchingSet(msModelUtils.getMatchableValues());
LinkedHashMap<String, String> returnReferenceList = new LinkedHashMap<>();
- returnReferenceList.put(className, msMLUtils.getReferenceAttributes());
+ returnReferenceList.put(className, msModelUtils.getReferenceAttributes());
msAttributes.setRefAttribute(returnReferenceList);
- if (msMLUtils.getListConstraints() != "") {
+ if (msModelUtils.getListConstraints() != "") {
LinkedHashMap<String, String> enumList = new LinkedHashMap<>();
- String[] listArray = msMLUtils.getListConstraints().split("#");
+ String[] listArray = msModelUtils.getListConstraints().split("#");
for (String str : listArray) {
String[] strArr = str.split("=");
if (strArr.length > 1) {
@@ -1577,22 +1617,19 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController {
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);
- j.put("dataOrderInfo", msMLUtils.getDataOrderInfo());
- j.put("ruleFormation", msMLUtils.getJsonRuleFormation());
-
- out.write(j.toString());
+ JSONObject json = new JSONObject();
+ json.put("classListDatas", modelList);
+ json.put("modelDatas", mapper.writeValueAsString(classMap));
+ json.put("modelType", modelType);
+ json.put("dataOrderInfo", msModelUtils.getDataOrderInfo());
+ json.put("ruleFormation", msModelUtils.getJsonRuleFormation());
+
+ response.getWriter().write(json.toString());
}
/*
@@ -1600,7 +1637,7 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController {
*/
@SuppressWarnings("rawtypes")
private void extractFolder(String zipFile) {
- int BUFFER = 2048;
+ final int buffer = 2048;
File file = new File(zipFile);
try (ZipFile zip = new ZipFile(file)) {
@@ -1623,10 +1660,10 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController {
if (!entry.isDirectory()) {
BufferedInputStream is = new BufferedInputStream(zip.getInputStream(entry));
int currentByte;
- byte[] data = new byte[BUFFER];
+ byte[] data = new byte[buffer];
try (FileOutputStream fos = new FileOutputStream(destFile);
- BufferedOutputStream dest = new BufferedOutputStream(fos, BUFFER)) {
- while ((currentByte = is.read(data, 0, BUFFER)) != -1) {
+ BufferedOutputStream dest = new BufferedOutputStream(fos, buffer)) {
+ while ((currentByte = is.read(data, 0, buffer)) != -1) {
dest.write(data, 0, currentByte);
}
dest.flush();
@@ -1648,25 +1685,21 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController {
}
}
- private void retreiveDependency(String workingFile, Boolean modelClass) {
+ private void retrieveDependency(String workingFile) {
- MSModelUtils utils = new MSModelUtils(PolicyController.getMsOnapName(), PolicyController.getMsPolicyName());
- Map<String, MSAttributeObject> tempMap;
+ MsModelUtils utils = new MsModelUtils(PolicyController.getMsOnapName(), PolicyController.getMsPolicyName());
+ Map<String, MsAttributeObject> tempMap;
- tempMap = utils.processEpackage(workingFile, MODEL_TYPE.XMI);
+ tempMap = utils.processEpackage(workingFile, ModelType.XMI);
classMap.putAll(tempMap);
LOGGER.info(tempMap);
-
- return;
-
}
private List<File> listModelFiles(String directoryName) {
File fileDirectory = new File(directoryName);
List<File> resultList = new ArrayList<>();
- File[] fList = fileDirectory.listFiles();
- for (File file : fList) {
+ for (File file : fileDirectory.listFiles()) {
if (file.isFile()) {
resultList.add(file);
} else if (file.isDirectory()) {
@@ -1677,6 +1710,11 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController {
return resultList;
}
+ /**
+ * cleanUp.
+ *
+ * @param path String
+ */
public void cleanUp(String path) {
if (path != null) {
try {
@@ -1687,6 +1725,11 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController {
}
}
+ /**
+ * checkZipDirectory.
+ *
+ * @param zipDirectory String
+ */
public void checkZipDirectory(String zipDirectory) {
Path path = Paths.get(zipDirectory);
@@ -1697,9 +1740,9 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController {
private List<String> createList() {
List<String> list = new ArrayList<>();
- for (Entry<String, MSAttributeObject> cMap : classMap.entrySet()) {
- if (cMap.getValue().isPolicyTempalate()) {
- list.add(cMap.getKey());
+ for (Entry<String, MsAttributeObject> entrySet : classMap.entrySet()) {
+ if (entrySet.getValue().isPolicyTempalate()) {
+ list.add(entrySet.getKey());
}
}
@@ -1732,7 +1775,8 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController {
}
-
+@Getter
+@Setter
class DCAEMicroServiceObject {
private String service;
@@ -1749,128 +1793,5 @@ class DCAEMicroServiceObject {
private String riskLevel;
private String guard = null;
private Object uiContent;
-
- 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;
- }
-
- public Object getUiContent() {
- return uiContent;
- }
-
- public void setUiContent(Object uiContent) {
- this.uiContent = uiContent;
- }
-
}
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
index 3e24dc7c4..3da703ab2 100644
--- 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
@@ -2,14 +2,14 @@
* ============LICENSE_START=======================================================
* ONAP Policy Engine
* ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017, 2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -19,11 +19,16 @@
*/
package org.onap.policy.controller;
-import java.io.PrintWriter;
+
+import com.fasterxml.jackson.core.JsonGenerationException;
+import com.fasterxml.jackson.databind.DeserializationFeature;
+import com.fasterxml.jackson.databind.JsonMappingException;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+
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;
@@ -32,6 +37,12 @@ import java.util.Set;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
+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.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;
+import org.apache.commons.lang3.StringUtils;
import org.hibernate.SessionFactory;
import org.json.JSONObject;
import org.onap.policy.common.logging.flexlogger.FlexLogger;
@@ -55,13 +66,14 @@ 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.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.utils.PolicyUtils;
import org.onap.policy.xacml.api.XACMLErrorConstants;
import org.onap.portalsdk.core.controller.RestrictedBaseController;
import org.springframework.beans.factory.annotation.Autowired;
@@ -69,886 +81,832 @@ import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
-import com.fasterxml.jackson.core.JsonGenerationException;
-import com.fasterxml.jackson.databind.DeserializationFeature;
-import com.fasterxml.jackson.databind.JsonMappingException;
-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);
- private static final String ANY="ANY";
- private static final String GROUP="Group_";
-
- @Autowired
- SessionFactory sessionFactory;
-
- private static CommonClassDao commonClassDao;
-
- public static CommonClassDao getCommonClassDao() {
- return commonClassDao;
- }
-
- public static void setCommonClassDao(CommonClassDao commonClassDao) {
- CreateFirewallController.commonClassDao = commonClassDao;
- }
-
- private List<String> tagCollectorList;
-
- List<String> expandablePrefixIPList = new ArrayList<>();
- List<String> expandableServicesList= new ArrayList<>();
- @Autowired
- private CreateFirewallController(CommonClassDao commonClassDao){
- CreateFirewallController.commonClassDao = commonClassDao;
- }
-
- public CreateFirewallController(){
- // Empty constructor
- }
- private List<String> termCollectorList;
-
-
-
- public PolicyRestAdapter setDataToPolicyRestAdapter(PolicyRestAdapter policyData){
- String jsonBody;
- 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 && ! "".equalsIgnoreCase(jsonBody)) {
- policyData.setJsonBody(jsonBody);
- } else {
- policyData.setJsonBody("{}");
- }
- policyData.setJsonBody(jsonBody);
-
- return policyData;
- }
-
- private List<String> mapping(String expandableList) {
- String value;
- String desc;
- List <String> valueDesc= new ArrayList<>();
- List<Object> prefixListData = commonClassDao.getData(PrefixList.class);
- for (int i = 0; i< prefixListData.size(); i++) {
- PrefixList prefixList = (PrefixList) prefixListData.get(i);
- if (prefixList.getPrefixListName().equals(expandableList)) {
- value = prefixList.getPrefixListValue();
- valueDesc.add(value);
- desc= prefixList.getDescription();
- valueDesc.add(desc);
- break;
- }
- }
- return valueDesc;
- }
-
- private ServiceList mappingServiceList(String expandableList) {
- ServiceList serviceList=null;
- List<Object> 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<Object> 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<Object> 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) {
- ArrayList<Object> attributeList;
- 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;
- SecurityZone jpaSecurityZone;
- data = entity.getConfigurationData().getConfigBody();
- tc1 = mapper.readValue(data, TermCollector.class);
- List<Object> 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<String, String> termTagMap;
- if(tc1 != null){
- for(int i=0;i<tc1.getFirewallRuleList().size();i++){
- termTagMap = new HashMap <>();
- 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<AnyOfType> anyOfList = target.getAnyOf();
- if (anyOfList != null) {
- Iterator<AnyOfType> iterAnyOf = anyOfList.iterator();
- while (iterAnyOf.hasNext()) {
- AnyOfType anyOf = iterAnyOf.next();
- // Under AnyOFType we have AllOFType
- List<AllOfType> allOfList = anyOf.getAllOf();
- if (allOfList != null) {
- Iterator<AllOfType> iterAllOf = allOfList.iterator();
- while (iterAllOf.hasNext()) {
- AllOfType allOf = iterAllOf.next();
- // Under AllOFType we have Match
- List<MatchType> matchList = allOf.getMatch();
- if (matchList != null) {
-
- Iterator<MatchType> 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 (("ConfigName").equals(attributeId)) {
- policyAdapter.setConfigName(value);
- }
- 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")){
- PolicyController controller = new PolicyController();
- String newDate = controller.convertDate(value);
- policyAdapter.setTtlDate(newDate);
- }
- }
- }
- }
- }
- }
- }
- }
- }
- }
-
- @RequestMapping(value={"/policyController/ViewFWPolicyRule.htm"}, method={org.springframework.web.bind.annotation.RequestMethod.POST})
- public ModelAndView 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 = 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;
- String ruleDestList;
- String ruleSrcPort;
- String ruleDestPort;
- String ruleAction;
- List <String> valueDesc;
- StringBuilder displayString = new StringBuilder();
- for (String id : termCollectorList) {
- List<Object> tmList = commonClassDao.getDataById(TermList.class, "termName", id);
- jpaTermList = (TermList) tmList.get(0);
- if (jpaTermList != null){
- ruleSrcList= jpaTermList.getSrcIPList();
- if ((ruleSrcList!= null) && (!ruleSrcList.isEmpty()) && !"null".equals(ruleSrcList)){
- displayString.append("Source IP List: " + jpaTermList.getSrcIPList());
- displayString.append(" ; \t\n");
- for(String srcList:ruleSrcList.split(",")){
- if(srcList.startsWith(GROUP)){
- AddressGroup ag;
- ag= mappingAddressGroup(srcList);
- displayString.append("\n\t"+"Group has :"+(ag != null ? ag.getPrefixList() : "") +"\n");
- if (ag != null) {
- 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= jpaTermList.getDestIPList();
- if ( ruleDestList!= null && (!ruleDestList.isEmpty())&& ! "null".equals(ruleDestList)){
- displayString.append("Destination IP List: " + jpaTermList.getDestIPList());
- displayString.append(" ; \t\n");
- for(String destList:ruleDestList.split(",")){
- if(destList.startsWith(GROUP)){
- AddressGroup ag;
- ag= mappingAddressGroup(destList);
- displayString.append("\n\t"+"Group has :"+ (ag != null ? ag.getPrefixList() : "") +"\n");
- if (ag != null) {
- 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=jpaTermList.getSrcPortList();
- if ( ruleSrcPort!= null && (!ruleSrcPort.isEmpty())&& !"null".equals(ruleSrcPort)) {
- displayString.append("\n"+"Source Port List:"
- + ruleSrcPort);
- displayString.append(" ; \t\n");
- }
-
- ruleDestPort= jpaTermList.getDestPortList();
- if (ruleDestPort != null && (!ruleDestPort.isEmpty())&& !"null".equals(ruleDestPort)) {
- displayString.append("\n"+"Destination Port List:"
- + ruleDestPort);
- displayString.append(" ; \t\n");
- for(String destServices:ruleDestPort.split(",")){
- if(destServices.startsWith(GROUP)){
- GroupServiceList sg;
- sg= mappingServiceGroup(destServices);
- displayString.append("\n\t"+"Service Group has :"+ (sg != null ? sg.getServiceList() : "") +"\n");
- if (sg != null) {
- for(String groupItems:sg.getServiceList().split(",")){
- ServiceList sl;
- 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;
- 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());
- return null;
- } catch (Exception e) {
- policyLogger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e);
- }
- return null;
- }
-
- private String constructJson(PolicyRestAdapter policyData) {
- int ruleCount=1;
- //Maps to assosciate the values read from the TermList dictionary
- Map<Integer, String> srcIP_map =null;
- Map<Integer, String> destIP_map=null;
- Map<Integer, String> srcPort_map =null;
- Map<Integer, String> destPort_map =null;
- Map<Integer, String> action_map=null;
- Map<Integer, String> fromZone_map=null;
- Map<Integer, String> 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<String> expandableList = new ArrayList<>();
- TermList jpaTermList;
- TermCollector tc = new TermCollector();
- SecurityZone jpaSecurityZone;
- List<Term> termList = new ArrayList<>();
-
- Tags tags=null;
- List<Tags>tagsList= new ArrayList<>();
-
- TagDefines tagDefine= new TagDefines();
- List<TagDefines> tagList=null;
- ServiceListJson targetSl=null;
- AddressMembers addressMembersJson=null;
- int i=0;
- try{
- String networkRole="";
- for(String tag:tagCollectorList){
- tags= new Tags();
- List<Object> tagListData = commonClassDao.getData(FWTagPicker.class);
- for(int tagCounter=0; tagCounter<tagListData.size(); tagCounter++){
- FWTagPicker jpaTagPickerList=(FWTagPicker) tagListData.get(tagCounter);
- if (jpaTagPickerList.getTagPickerName().equals(tag) ){
- String tagValues=jpaTagPickerList.getTagValues();
- tagList= new ArrayList<>();
- 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();
- targetTerm.setRuleName(termCollectorList.get(tl));
- List<Object> 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<String> fromZone= new ArrayList<>();
- for(String fromZoneStr:fromZone_map.get(tl).split(",") ){
- fromZone.add(fromZoneStr);
- }
- targetTerm.setFromZones(fromZone);
- }
-
- //ToZone arrays
- if(toZone_map!=null){
- List<String> toZone= new ArrayList<>();
- for(String toZoneStr:toZone_map.get(tl).split(",") ){
- toZone.add(toZoneStr);
- }
- targetTerm.setToZones(toZone);
- }
-
- //Destination Services.
- if(destPort_map!=null){
- Set<ServicesJson> 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<AddressJson> 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<AddressJson> 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(Integer.toString (ruleCount++));
- }
-
- List<Object> 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> 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<ServiceListJson> servListArray = new HashSet<>();
- Set<ServiceGroupJson> servGroupArray= new HashSet<>();
- Set<AddressGroupJson> addrGroupArray= new HashSet<>();
- Set<AddressMembers> addrArray= new HashSet<> ();
-
- ServiceGroupJson targetSg;
- AddressGroupJson addressSg;
- ServiceListJson targetAny;
- ServiceListJson targetAnyTcp;
- ServiceListJson targetAnyUdp;
-
- for(String serviceList:expandableServicesList){
- for(String t: serviceList.split(",")){
- if(!t.startsWith(GROUP)){
- if(!t.equals(ANY)){
- ServiceList sl;
- 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;
- 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<ServiceMembers> 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 ;
- 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> prefixIPList = new HashSet<>();
- for(String prefixList:expandablePrefixIPList){
- for(String prefixIP: prefixList.split(",")){
- if(!prefixIP.startsWith(GROUP)){
- if(!prefixIP.equals(ANY)){
- List<AddressMembers> addMembersList= new ArrayList<>();
- List<String> valueDesc;
- 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;
- 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<AddressMembersJson> addrMembersList= new ArrayList<>();
- for(String groupString: ag.getPrefixList().split(",")){
- List<String> valueDesc;
- AddressMembersJson addressMembers= new AddressMembersJson();
- addressMembers.setType("REFERENCES");
- addressMembers.setName(groupString);
- addrMembersList.add(addressMembers);
- //Expand the group Name
- addressMembersJson= new AddressMembers();
- valueDesc= mapping (groupString);
-
- addressMembersJson.setName(groupString);
- addressMembersJson.setType("SUBNET");
- addressMembersJson.setValue(valueDesc.get(0));
-
- addrArray.add(addressMembersJson);
-
- }
- addressSg.setMembers(addrMembersList);
- addrGroupArray.add(addressSg);
- }
-
- }
- }
-
- Set<Object> serviceGroup= new HashSet<>();
-
- for(Object obj1:servGroupArray){
- serviceGroup.add(obj1);
- }
-
- for(Object obj:servListArray){
- serviceGroup.add(obj);
- }
-
- Set<Object> addressGroup= new HashSet<>();
-
- for(Object addObj:prefixIPList){
- addressGroup.add(addObj);
- }
-
- for(Object addObj1:addrGroupArray){
- addressGroup.add(addObj1);
- }
-
- for(Object addObj2:addrArray){
- addressGroup.add(addObj2);
- }
-
-
- tc.setServiceGroups(serviceGroup);
- tc.setAddressGroups(addressGroup);
- tc.setFirewallRuleList(termList);
-
- ObjectWriter om = new ObjectMapper().writer();
- try {
- json = om.writeValueAsString(tc);
- } catch (JsonGenerationException e) {
- policyLogger.error("JsonGenerationException Ocured",e);
- } catch (JsonMappingException e) {
- policyLogger.error("IOException Occured",e);
- }
-
- }catch (Exception e) {
- policyLogger.error("Exception Occured"+e);
- }
-
- return json;
- }
+ private static Logger policyLogger = FlexLogger.getLogger(CreateFirewallController.class);
+ private static final String ANY = "ANY";
+ private static final String GROUP = "Group_";
+ private static CommonClassDao commonClassDao;
+ private List<String> tagCollectorList;
+ private List<String> termCollectorList;
+
+ List<String> expandablePrefixIpList = new ArrayList<>();
+ List<String> expandableServicesList = new ArrayList<>();
+
+ @Autowired
+ SessionFactory sessionFactory;
+
+ public CreateFirewallController() {
+ // Empty constructor
+ }
+
+ public static CommonClassDao getCommonClassDao() {
+ return commonClassDao;
+ }
+
+ public static void setCommonClassDao(CommonClassDao commonClassDao) {
+ CreateFirewallController.commonClassDao = commonClassDao;
+ }
+
+ @Autowired
+ private CreateFirewallController(CommonClassDao commonClassDao) {
+ CreateFirewallController.commonClassDao = commonClassDao;
+ }
+
+ /**
+ * setDataToPolicyRestAdapter.
+ *
+ * @param policyData PolicyRestAdapter
+ * @return PolicyRestAdapter
+ */
+ 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);
+ }
+ }
+ }
+ String jsonBody = constructJson(policyData);
+ if (StringUtils.isBlank(jsonBody)) {
+ policyData.setJsonBody(jsonBody);
+ } else {
+ policyData.setJsonBody("{}");
+ }
+ //
+ // Hmmm - seems to be overriding the previous if statement
+ //
+ policyData.setJsonBody(jsonBody);
+
+ return policyData;
+ }
+
+ private List<String> mapping(String expandableList) {
+ String value;
+ String desc;
+ List<String> valueDesc = new ArrayList<>();
+ List<Object> prefixListData = commonClassDao.getData(PrefixList.class);
+ for (int i = 0; i < prefixListData.size(); i++) {
+ PrefixList prefixList = (PrefixList) prefixListData.get(i);
+ if (prefixList.getPrefixListName().equals(expandableList)) {
+ value = prefixList.getPrefixListValue();
+ valueDesc.add(value);
+ desc = prefixList.getDescription();
+ valueDesc.add(desc);
+ break;
+ }
+ }
+ return valueDesc;
+ }
+
+ private ServiceList mappingServiceList(String expandableList) {
+ ServiceList serviceList = null;
+ List<Object> 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<Object> 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<Object> 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) {
+ ArrayList<Object> attributeList;
+ attributeList = new ArrayList<>();
+ if (! (policyAdapter.getPolicyData() instanceof PolicyType)) {
+ return;
+ }
+ 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;
+ SecurityZone jpaSecurityZone;
+ data = entity.getConfigurationData().getConfigBody();
+ tc1 = mapper.readValue(data, TermCollector.class);
+ List<Object> 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<String, String> termTagMap;
+ if (tc1 != null) {
+ for (int i = 0; i < tc1.getFirewallRuleList().size(); i++) {
+ termTagMap = new HashMap<>();
+ 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) {
+ return;
+ }
+ // Under target we have AnyOFType
+ // NOTE: target.getAnyOf() will never be null
+ for (AnyOfType anyOf : target.getAnyOf()) {
+ for (AllOfType allOf : anyOf.getAllOf()) {
+ for (MatchType match : allOf.getMatch()) {
+ //
+ // Under the match we have attribute value and
+ // attributeDesignator. So,finally down to the actual attribute.
+ //
+ policyAdapter.setupUsingAttribute(match.getAttributeDesignator().getAttributeId(),
+ (String) match.getAttributeValue().getContent().get(0));
+ }
+ }
+ }
+ }
+
+ /**
+ * setFWViewRule.
+ *
+ * @param request HttpServletRequest
+ * @param response HttpServletResponse
+ * @return ModelAndView
+ */
+ @RequestMapping(
+ value = {"/policyController/ViewFWPolicyRule.htm"},
+ method = {org.springframework.web.bind.annotation.RequestMethod.POST})
+ public ModelAndView 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 = 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;
+ String ruleDestList;
+ String ruleSrcPort;
+ String ruleDestPort;
+ String ruleAction;
+ List<String> valueDesc;
+ StringBuilder displayString = new StringBuilder();
+ for (String id : termCollectorList) {
+ List<Object> tmList = commonClassDao.getDataById(TermList.class, "termName", id);
+ jpaTermList = (TermList) tmList.get(0);
+ if (jpaTermList != null) {
+ ruleSrcList = jpaTermList.getSrcIpList();
+ if ((ruleSrcList != null) && (!ruleSrcList.isEmpty()) && !"null".equals(ruleSrcList)) {
+ displayString.append("Source IP List: " + jpaTermList.getSrcIpList());
+ displayString.append(" ; \t\n");
+ for (String srcList : ruleSrcList.split(",")) {
+ if (srcList.startsWith(GROUP)) {
+ AddressGroup ag;
+ ag = mappingAddressGroup(srcList);
+ displayString.append(
+ "\n\t" + "Group has :" + (ag != null ? ag.getPrefixList() : "") + "\n");
+ if (ag != null) {
+ 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 = jpaTermList.getDestIpList();
+ if (ruleDestList != null && (!ruleDestList.isEmpty()) && !"null".equals(ruleDestList)) {
+ displayString.append("Destination IP List: " + jpaTermList.getDestIpList());
+ displayString.append(" ; \t\n");
+ for (String destList : ruleDestList.split(",")) {
+ if (destList.startsWith(GROUP)) {
+ AddressGroup ag;
+ ag = mappingAddressGroup(destList);
+ displayString.append(
+ "\n\t" + "Group has :" + (ag != null ? ag.getPrefixList() : "") + "\n");
+ if (ag != null) {
+ 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 = jpaTermList.getSrcPortList();
+ if (ruleSrcPort != null && (!ruleSrcPort.isEmpty()) && !"null".equals(ruleSrcPort)) {
+ displayString.append("\n" + "Source Port List:" + ruleSrcPort);
+ displayString.append(" ; \t\n");
+ }
+
+ ruleDestPort = jpaTermList.getDestPortList();
+ if (ruleDestPort != null && (!ruleDestPort.isEmpty()) && !"null".equals(ruleDestPort)) {
+ displayString.append("\n" + "Destination Port List:" + ruleDestPort);
+ displayString.append(" ; \t\n");
+ for (String destServices : ruleDestPort.split(",")) {
+ if (destServices.startsWith(GROUP)) {
+ GroupServiceList sg;
+ sg = mappingServiceGroup(destServices);
+ displayString.append("\n\t" + "Service Group has :"
+ + (sg != null ? sg.getServiceList() : "") + "\n");
+ if (sg != null) {
+ for (String groupItems : sg.getServiceList().split(",")) {
+ ServiceList sl;
+ sl = mappingServiceList(groupItems);
+ displayString.append("\n\t" + "Name: " + sl.getServiceName());
+ displayString.append("\n\t" + "Description: " + sl.getServiceDescription());
+ displayString.append(
+ "\n\t" + "Transport-Protocol: " + sl.getServiceTransportProtocol());
+ displayString.append("\n\t" + "Ports: " + sl.getServicePorts());
+ displayString.append("\n");
+ }
+ }
+ } else {
+ if (!destServices.equals(ANY)) {
+ ServiceList sl;
+ sl = mappingServiceList(destServices);
+ displayString.append("\n\t" + "Name: " + sl.getServiceName());
+ displayString.append("\n\t" + "Description: " + sl.getServiceDescription());
+ displayString
+ .append("\n\t" + "Transport-Protocol: " + sl.getServiceTransportProtocol());
+ 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(PolicyUtils.CHARACTER_ENCODING);
+ response.setContentType(PolicyUtils.APPLICATION_JSON);
+ request.setCharacterEncoding(PolicyUtils.CHARACTER_ENCODING);
+
+ String responseString = mapper.writeValueAsString(displayString);
+ response.getWriter().write(new JSONObject("{policyData: " + responseString + "}").toString());
+ return null;
+ } catch (Exception e) {
+ policyLogger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e);
+ }
+ return null;
+ }
+
+ private String constructJson(PolicyRestAdapter policyData) {
+ int ruleCount = 1;
+ // Maps to assosciate the values read from the TermList dictionary
+ Map<Integer, String> mapSrcIp = null;
+ Map<Integer, String> mapDestIP = null;
+ Map<Integer, String> mapSrcPort = null;
+ Map<Integer, String> mapDestPort = null;
+ Map<Integer, String> mapAction = null;
+ Map<Integer, String> mapFromZone = null;
+ Map<Integer, String> mapToZone = 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<String> expandableList = new ArrayList<>();
+ TermList jpaTermList;
+ TermCollector tc = new TermCollector();
+ SecurityZone jpaSecurityZone;
+ List<Term> termList = new ArrayList<>();
+
+ Tags tags = null;
+ List<Tags> tagsList = new ArrayList<>();
+
+ TagDefines tagDefine = new TagDefines();
+ List<TagDefines> tagList = null;
+ ServiceListJson targetSl = null;
+ AddressMembers addressMembersJson = null;
+ int intCounter = 0;
+ try {
+ String networkRole = "";
+ for (String tag : tagCollectorList) {
+ tags = new Tags();
+ List<Object> tagListData = commonClassDao.getData(FwTagPicker.class);
+ for (int tagCounter = 0; tagCounter < tagListData.size(); tagCounter++) {
+ FwTagPicker jpaTagPickerList = (FwTagPicker) tagListData.get(tagCounter);
+ if (jpaTagPickerList.getTagPickerName().equals(tag)) {
+ String tagValues = jpaTagPickerList.getTagValues();
+ tagList = new ArrayList<>();
+ 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(intCounter));
+ tags.setNetworkRole(networkRole);
+ tagsList.add(tags);
+ intCounter++;
+ }
+ tc.setRuleToTag(tagsList);
+
+ for (int tl = 0; tl < termCollectorList.size(); tl++) {
+ expandableList.add(termCollectorList.get(tl));
+ Term targetTerm = new Term();
+ targetTerm.setRuleName(termCollectorList.get(tl));
+ List<Object> 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.getDescription();
+ if ((ruleDesc != null) && (!ruleDesc.isEmpty())) {
+ targetTerm.setDescription(ruleDesc);
+ }
+ ruleFromZone = jpaTermList.getFromZone();
+
+ if ((ruleFromZone != null) && (!ruleFromZone.isEmpty())) {
+ mapFromZone = new HashMap<>();
+ mapFromZone.put(tl, ruleFromZone);
+ }
+ ruleToZone = jpaTermList.getToZone();
+
+ if ((ruleToZone != null) && (!ruleToZone.isEmpty())) {
+ mapToZone = new HashMap<>();
+ mapToZone.put(tl, ruleToZone);
+ }
+ ruleSrcPrefixList = jpaTermList.getSrcIpList();
+
+ if ((ruleSrcPrefixList != null) && (!ruleSrcPrefixList.isEmpty())) {
+ mapSrcIp = new HashMap<>();
+ mapSrcIp.put(tl, ruleSrcPrefixList);
+ }
+
+ ruleDestPrefixList = jpaTermList.getDestIpList();
+ if ((ruleDestPrefixList != null) && (!ruleDestPrefixList.isEmpty())) {
+ mapDestIP = new HashMap<>();
+ mapDestIP.put(tl, ruleDestPrefixList);
+ }
+
+ ruleSrcPort = jpaTermList.getSrcPortList();
+
+ if (ruleSrcPort != null && (!ruleSrcPort.isEmpty())) {
+ mapSrcPort = new HashMap<>();
+ mapSrcPort.put(tl, ruleSrcPort);
+ }
+
+ ruleDestPort = jpaTermList.getDestPortList();
+
+ if (ruleDestPort != null && (!jpaTermList.getDestPortList().isEmpty())) {
+ mapDestPort = new HashMap<>();
+ mapDestPort.put(tl, ruleDestPort);
+ }
+
+ ruleAction = jpaTermList.getAction();
+
+ if ((ruleAction != null) && (!ruleAction.isEmpty())) {
+ mapAction = new HashMap<>();
+ mapAction.put(tl, ruleAction);
+ }
+ }
+ }
+ targetTerm.setEnabled(true);
+ targetTerm.setLog(true);
+ targetTerm.setNegateSource(false);
+ targetTerm.setNegateDestination(false);
+
+ if (mapAction != null) {
+ targetTerm.setAction(mapAction.get(tl));
+ }
+
+ // FromZone arrays
+ if (mapFromZone != null) {
+ List<String> fromZone = new ArrayList<>();
+ for (String fromZoneStr : mapFromZone.get(tl).split(",")) {
+ fromZone.add(fromZoneStr);
+ }
+ targetTerm.setFromZones(fromZone);
+ }
+
+ // ToZone arrays
+ if (mapToZone != null) {
+ List<String> toZone = new ArrayList<>();
+ for (String toZoneStr : mapToZone.get(tl).split(",")) {
+ toZone.add(toZoneStr);
+ }
+ targetTerm.setToZones(toZone);
+ }
+
+ // Destination Services.
+ if (mapDestPort != null) {
+ Set<ServicesJson> destServicesJsonList = new HashSet<>();
+ for (String destServices : mapDestPort.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 ((mapSrcPort != null) && (mapDestPort != null)) {
+ String servicesCollateString = mapSrcPort.get(tl) + "," + mapDestPort.get(tl);
+ expandableServicesList.add(servicesCollateString);
+ } else if (mapSrcPort != null) {
+ expandableServicesList.add(mapSrcPort.get(tl));
+ } else if (mapDestPort != null) {
+ expandableServicesList.add(mapDestPort.get(tl));
+ }
+
+ if (mapSrcIp != null) {
+ // Source List
+ List<AddressJson> sourceListArrayJson = new ArrayList<>();
+ for (String srcList : mapSrcIp.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 (mapDestIP != null) {
+ // Destination List
+ List<AddressJson> destListArrayJson = new ArrayList<>();
+ for (String destList : mapDestIP.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 ((mapSrcIp != null) && (mapDestIP != null)) {
+ String collateString = mapSrcIp.get(tl) + "," + mapDestIP.get(tl);
+ expandablePrefixIpList.add(collateString);
+ } else if (mapSrcIp != null) {
+ expandablePrefixIpList.add(mapSrcIp.get(tl));
+ } else if (mapDestIP != null) {
+ expandablePrefixIpList.add(mapDestIP.get(tl));
+ }
+ termList.add(targetTerm);
+ targetTerm.setPosition(Integer.toString(ruleCount++));
+ }
+
+ List<Object> 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> 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<ServiceListJson> servListArray = new HashSet<>();
+ Set<ServiceGroupJson> servGroupArray = new HashSet<>();
+ Set<AddressGroupJson> addrGroupArray = new HashSet<>();
+ Set<AddressMembers> addrArray = new HashSet<>();
+
+ ServiceGroupJson targetSg;
+ AddressGroupJson addressSg;
+ ServiceListJson targetAny;
+ ServiceListJson targetAnyTcp;
+ ServiceListJson targetAnyUdp;
+
+ for (String serviceList : expandableServicesList) {
+ for (String t : serviceList.split(",")) {
+ if (!t.startsWith(GROUP)) {
+ if (!t.equals(ANY)) {
+ ServiceList sl;
+ targetSl = new ServiceListJson();
+ sl = mappingServiceList(t);
+ targetSl.setName(sl.getServiceName());
+ targetSl.setDescription(sl.getServiceDescription());
+ targetSl.setTransportProtocol(sl.getServiceTransportProtocol());
+ 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;
+ 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<ServiceMembers> 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;
+ targetSl = new ServiceListJson();
+ expandGroupSl = mappingServiceList(groupString);
+
+ targetSl.setName(expandGroupSl.getServiceName());
+ targetSl.setDescription(expandGroupSl.getServiceDescription());
+ targetSl.setTransportProtocol(expandGroupSl.getServiceTransportProtocol());
+ targetSl.setType(expandGroupSl.getServiceType());
+ targetSl.setPorts(expandGroupSl.getServicePorts());
+ servListArray.add(targetSl);
+ }
+
+ targetSg.setMembers(servMembersList);
+ servGroupArray.add(targetSg);
+
+ }
+ }
+ }
+
+ Set<PrefixIPList> prefixIpList = new HashSet<>();
+ for (String prefixList : expandablePrefixIpList) {
+ for (String prefixIP : prefixList.split(",")) {
+ if (!prefixIP.startsWith(GROUP)) {
+ if (!prefixIP.equals(ANY)) {
+ List<String> valueDesc;
+ PrefixIPList targetAddressList = new PrefixIPList();
+ 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 addressMembers = new AddressMembers();
+ addressMembers.setType("SUBNET");
+ if (!valueDesc.isEmpty()) {
+ addressMembers.setValue(valueDesc.get(0));
+ }
+ List<AddressMembers> addMembersList = new ArrayList<>();
+ addMembersList.add(addressMembers);
+
+ targetAddressList.setMembers(addMembersList);
+ prefixIpList.add(targetAddressList);
+ }
+ } else { // This is a group
+ AddressGroup ag;
+ 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<AddressMembersJson> addrMembersList = new ArrayList<>();
+ for (String groupString : ag.getPrefixList().split(",")) {
+ AddressMembersJson addressMembers = new AddressMembersJson();
+ addressMembers.setType("REFERENCES");
+ addressMembers.setName(groupString);
+ addrMembersList.add(addressMembers);
+ // Expand the group Name
+ addressMembersJson = new AddressMembers();
+ List<String> valueDesc = mapping(groupString);
+
+ addressMembersJson.setName(groupString);
+ addressMembersJson.setType("SUBNET");
+ addressMembersJson.setValue(valueDesc.get(0));
+
+ addrArray.add(addressMembersJson);
+
+ }
+ addressSg.setMembers(addrMembersList);
+ addrGroupArray.add(addressSg);
+ }
+
+ }
+ }
+
+ Set<Object> serviceGroup = new HashSet<>();
+
+ for (Object obj1 : servGroupArray) {
+ serviceGroup.add(obj1);
+ }
+
+ for (Object obj : servListArray) {
+ serviceGroup.add(obj);
+ }
+
+ Set<Object> addressGroup = new HashSet<>();
+
+ for (Object addObj : prefixIpList) {
+ addressGroup.add(addObj);
+ }
+
+ for (Object addObj1 : addrGroupArray) {
+ addressGroup.add(addObj1);
+ }
+
+ for (Object addObj2 : addrArray) {
+ addressGroup.add(addObj2);
+ }
+
+ tc.setServiceGroups(serviceGroup);
+ tc.setAddressGroups(addressGroup);
+ tc.setFirewallRuleList(termList);
+
+ try {
+ json = new ObjectMapper().writer().writeValueAsString(tc);
+ } catch (JsonGenerationException e) {
+ policyLogger.error("JsonGenerationException Ocured", e);
+ } catch (JsonMappingException e) {
+ policyLogger.error("IOException 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/CreateOptimizationController.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateOptimizationController.java
index 05fddb50d..37f543f35 100644
--- a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateOptimizationController.java
+++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateOptimizationController.java
@@ -20,7 +20,6 @@
package org.onap.policy.controller;
-
import com.att.research.xacml.util.XACMLProperties;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
@@ -28,13 +27,13 @@ import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectWriter;
import com.google.gson.Gson;
+
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
-import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
@@ -49,15 +48,17 @@ import java.util.Set;
import java.util.UUID;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
+
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
+import lombok.Getter;
+import lombok.Setter;
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;
+
import org.apache.commons.compress.utils.IOUtils;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
@@ -68,15 +69,16 @@ 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.XacmlRestProperties;
import org.onap.policy.rest.adapter.PolicyRestAdapter;
import org.onap.policy.rest.dao.CommonClassDao;
import org.onap.policy.rest.jpa.MicroserviceHeaderdeFaults;
import org.onap.policy.rest.jpa.OptimizationModels;
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.onap.policy.rest.util.MsAttributeObject;
+import org.onap.policy.rest.util.MsModelUtils;
+import org.onap.policy.rest.util.MsModelUtils.ModelType;
+import org.onap.policy.utils.PolicyUtils;
import org.onap.portalsdk.core.controller.RestrictedBaseController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
@@ -87,6 +89,9 @@ import org.springframework.web.servlet.ModelAndView;
@RequestMapping("/")
public class CreateOptimizationController extends RestrictedBaseController {
private static final Logger LOGGER = FlexLogger.getLogger(CreateOptimizationController.class);
+
+ private static final int BUFFER = 2048;
+
private static CommonClassDao commonClassDao;
public static CommonClassDao getCommonClassDao() {
@@ -98,7 +103,7 @@ public class CreateOptimizationController extends RestrictedBaseController {
private String directory;
private List<String> modelList = new ArrayList<>();
private List<String> dirDependencyList = new ArrayList<>();
- private LinkedHashMap<String, MSAttributeObject> classMap = new LinkedHashMap<>();
+ private LinkedHashMap<String, MsAttributeObject> classMap = new LinkedHashMap<>();
String referenceAttributes;
String attributeString;
Set<String> allManyTrueKeys = new HashSet<>();
@@ -115,10 +120,7 @@ public class CreateOptimizationController extends RestrictedBaseController {
public static final String MANYFALSE = ":MANY-false";
public static final String MODEL = "model";
public static final String MANY = "MANY-";
- public static final String UTF8 = "UTF-8";
public static final String MODELNAME = "modelName";
- public static final String APPLICATIONJSON = "application / json";
-
@Autowired
private CreateOptimizationController(CommonClassDao commonClassDao) {
@@ -138,6 +140,13 @@ public class CreateOptimizationController extends RestrictedBaseController {
private Map<String, LinkedList<String>> arrayTextList = new HashMap<>();
CreateDcaeMicroServiceController msController = new CreateDcaeMicroServiceController();
+ /**
+ * setDataToPolicyRestAdapter.
+ *
+ * @param policyData PolicyRestAdapter
+ * @param root JsonNode
+ * @return PolicyRestAdapter
+ */
public PolicyRestAdapter setDataToPolicyRestAdapter(PolicyRestAdapter policyData, JsonNode root) {
String jsonContent = null;
try {
@@ -175,7 +184,7 @@ public class CreateOptimizationController extends RestrictedBaseController {
}
LOGGER.info("input json: " + json);
LOGGER.info("input jsonContent: " + jsonContent);
- String cleanJson = msController.cleanUPJson(json);
+ String cleanJson = msController.cleanUpJson(json);
// --- reset empty value back after called cleanUPJson method and before calling removeNullAttributes
String tempJson =
@@ -186,7 +195,16 @@ public class CreateOptimizationController extends RestrictedBaseController {
return policyAdapter;
}
- @RequestMapping(value = {"/policyController/getOptimizationTemplateData.htm"},
+ /**
+ * getOptimizationTemplateData.
+ *
+ * @param request HttpServletRequest
+ * @param response HttpServletResponse
+ * @return ModelAndView
+ * @throws IOException IOException
+ */
+ @RequestMapping(
+ value = {"/policyController/getOptimizationTemplateData.htm"},
method = {org.springframework.web.bind.annotation.RequestMethod.POST})
public ModelAndView getOptimizationTemplateData(HttpServletRequest request, HttpServletResponse response)
throws IOException {
@@ -196,10 +214,10 @@ public class CreateOptimizationController extends RestrictedBaseController {
JsonNode root = mapper.readTree(request.getReader());
String value = root.get("policyData").toString().replaceAll("^\"|\"$", "");
- String servicename = value.toString().split("-v")[0];
+ String servicename = value.split("-v")[0];
String version = null;
- if (value.toString().contains("-v")) {
- version = value.toString().split("-v")[1];
+ if (value.contains("-v")) {
+ version = value.split("-v")[1];
}
OptimizationModels returnModel = getAttributeObject(servicename, version);
@@ -226,8 +244,7 @@ public class CreateOptimizationController extends RestrictedBaseController {
// Get all keys with "MANY-true" defined in their value from subAttribute
Set<String> allkeys = null;
if (returnModel.getSubattributes() != null && !returnModel.getSubattributes().isEmpty()) {
- JSONObject json = new JSONObject(returnModel.getSubattributes());
- getAllKeys(json);
+ getAllKeys(new JSONObject(returnModel.getSubattributes()));
allkeys = allManyTrueKeys;
allManyTrueKeys = new HashSet<>();
LOGGER.info("allkeys : " + allkeys);
@@ -276,23 +293,22 @@ public class CreateOptimizationController extends RestrictedBaseController {
jsonModel = finalJsonObject.toString();
}
- response.setCharacterEncoding(UTF8);
- response.setContentType(APPLICATIONJSON);
- request.setCharacterEncoding(UTF8);
+ response.setCharacterEncoding(PolicyUtils.CHARACTER_ENCODING);
+ response.setContentType(PolicyUtils.APPLICATION_JSON);
+ request.setCharacterEncoding(PolicyUtils.CHARACTER_ENCODING);
List<Object> list = new ArrayList<>();
- PrintWriter out = response.getWriter();
String responseString = mapper.writeValueAsString(returnModel);
- JSONObject j = null;
+ JSONObject json = null;
if ("".equals(nameOfTrueKeys)) {
- j = new JSONObject("{optimizationModelData: " + responseString + ",jsonValue: " + jsonModel
+ json = new JSONObject("{optimizationModelData: " + responseString + ",jsonValue: " + jsonModel
+ ",dataOrderInfo:" + dataOrderInfo + ",headDefautlsData:" + headDefautlsData + "}");
} else {
- j = new JSONObject("{optimizationModelData: " + responseString + ",jsonValue: " + jsonModel
+ json = new JSONObject("{optimizationModelData: " + responseString + ",jsonValue: " + jsonModel
+ ",allManyTrueKeys: " + allManyTrueKeys + ",dataOrderInfo:" + dataOrderInfo + ",headDefautlsData:"
+ headDefautlsData + "}");
}
- list.add(j);
- out.write(list.toString());
+ list.add(json);
+ response.getWriter().write(list.toString());
return null;
}
@@ -415,10 +431,12 @@ public class CreateOptimizationController extends RestrictedBaseController {
private Set<String> getAllKeys(JSONArray arr, Set<String> keys) {
for (int i = 0; i < arr.length(); i++) {
Object obj = arr.get(i);
- if (obj instanceof JSONObject)
+ if (obj instanceof JSONObject) {
keys.addAll(getAllKeys(arr.getJSONObject(i)));
- if (obj instanceof JSONArray)
+ }
+ if (obj instanceof JSONArray) {
keys.addAll(getAllKeys(arr.getJSONArray(i)));
+ }
}
return keys;
@@ -433,16 +451,27 @@ public class CreateOptimizationController extends RestrictedBaseController {
LOGGER.info("obj : " + obj);
allManyTrueKeys.add(key);
}
- if (obj instanceof JSONObject)
+ if (obj instanceof JSONObject) {
keys.addAll(getAllKeys(json.getJSONObject(key)));
- if (obj instanceof JSONArray)
+ }
+ if (obj instanceof JSONArray) {
keys.addAll(getAllKeys(json.getJSONArray(key)));
+ }
}
return keys;
}
- @RequestMapping(value = {"/policyController/getModelServiceVersionData.htm"},
+ /**
+ * getModelServiceVersionData.
+ *
+ * @param request HttpServletRequest
+ * @param response HttpServletResponse
+ * @return ModelAndView
+ * @throws IOException IOException
+ */
+ @RequestMapping(
+ value = {"/policyController/getModelServiceVersionData.htm"},
method = {org.springframework.web.bind.annotation.RequestMethod.POST})
public ModelAndView getModelServiceVersionData(HttpServletRequest request, HttpServletResponse response)
throws IOException {
@@ -450,19 +479,16 @@ public class CreateOptimizationController extends RestrictedBaseController {
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
JsonNode root = mapper.readTree(request.getReader());
- String value = root.get("policyData").toString().replaceAll("^\"|\"$", "");
- String servicename = value.split("-v")[0];
- Set<String> returnList = getVersionList(servicename);
+ final String value = root.get("policyData").toString().replaceAll("^\"|\"$", "");
+ final String servicename = value.split("-v")[0];
- response.setCharacterEncoding(UTF8);
- response.setContentType(APPLICATIONJSON);
- request.setCharacterEncoding(UTF8);
+ response.setCharacterEncoding(PolicyUtils.CHARACTER_ENCODING);
+ response.setContentType(PolicyUtils.APPLICATION_JSON);
+ request.setCharacterEncoding(PolicyUtils.CHARACTER_ENCODING);
List<Object> list = new ArrayList<>();
- PrintWriter out = response.getWriter();
- String responseString = mapper.writeValueAsString(returnList);
- JSONObject j = new JSONObject("{optimizationModelVersionData: " + responseString + "}");
- list.add(j);
- out.write(list.toString());
+ list.add(new JSONObject("{optimizationModelVersionData: "
+ + mapper.writeValueAsString(getVersionList(servicename)) + "}"));
+ response.getWriter().write(list.toString());
return null;
}
@@ -507,76 +533,46 @@ public class CreateOptimizationController extends RestrictedBaseController {
modelName);
}
+ /**
+ * prePopulatePolicyData.
+ *
+ * @param policyAdapter PolicyRestAdapter
+ * @param entity PolicyEntity
+ */
public void prePopulatePolicyData(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("OOF_") + 4);
- policyAdapter.setPolicyName(policyNameValue);
- String description = "";
- try {
- description = policy.getDescription().substring(0, policy.getDescription().indexOf("@CreatedBy:"));
- } catch (Exception e) {
- LOGGER.error("Error while collecting the description tag in " + policyNameValue, 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<AnyOfType> anyOfList = target.getAnyOf();
- if (anyOfList != null) {
- Iterator<AnyOfType> iterAnyOf = anyOfList.iterator();
- while (iterAnyOf.hasNext()) {
- AnyOfType anyOf = iterAnyOf.next();
- // Under AnyOFType we have AllOFType
- List<AllOfType> allOfList = anyOf.getAllOf();
- if (allOfList != null) {
- Iterator<AllOfType> iterAllOf = allOfList.iterator();
- while (iterAllOf.hasNext()) {
- AllOfType allOf = iterAllOf.next();
- // Under AllOFType we have Match
- List<MatchType> matchList = allOf.getMatch();
- if (matchList != null) {
- Iterator<MatchType> 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 ("ONAPName".equals(attributeId)) {
- policyAdapter.setOnapName(value);
- }
- 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")) {
- PolicyController controller = new PolicyController();
- String newDate = controller.convertDate(value);
- policyAdapter.setTtlDate(newDate);
- }
- }
- readFile(policyAdapter, entity);
- }
- }
- }
- }
+ if (! (policyAdapter.getPolicyData() instanceof PolicyType)) {
+ return;
+ }
+ Object policyData = policyAdapter.getPolicyData();
+ PolicyType policy = (PolicyType) policyData;
+ policyAdapter.setOldPolicyFileName(policyAdapter.getPolicyName());
+ String policyNameValue =
+ policyAdapter.getPolicyName().substring(policyAdapter.getPolicyName().indexOf("OOF_") + 4);
+ policyAdapter.setPolicyName(policyNameValue);
+ String description = "";
+ try {
+ description = policy.getDescription().substring(0, policy.getDescription().indexOf("@CreatedBy:"));
+ } catch (Exception e) {
+ LOGGER.error("Error while collecting the description tag in " + policyNameValue, e);
+ description = policy.getDescription();
+ }
+ policyAdapter.setPolicyDescription(description);
+ // Get the target data under policy.
+ TargetType target = policy.getTarget();
+ if (target == null) {
+ return;
+ }
+ for (AnyOfType anyOf : target.getAnyOf()) {
+ for (AllOfType allOf : anyOf.getAllOf()) {
+ for (MatchType match : allOf.getMatch()) {
+ //
+ // Under the match we have attribute value and
+ // attributeDesignator. So,finally down to the actual attribute.
+ //
+ policyAdapter.setupUsingAttribute(match.getAttributeDesignator().getAttributeId(),
+ (String) match.getAttributeValue().getContent().get(0));
}
+ readFile(policyAdapter, entity);
}
}
}
@@ -612,7 +608,16 @@ public class CreateOptimizationController extends RestrictedBaseController {
}
- @RequestMapping(value = {"/oof_dictionary/set_ModelData"},
+ /**
+ * setModelData.
+ *
+ * @param request HttpServletRequest
+ * @param response HttpServletResponse
+ * @throws IOException IOException
+ * @throws FileUploadException FileUploadException
+ */
+ @RequestMapping(
+ value = {"/oof_dictionary/set_ModelData"},
method = {org.springframework.web.bind.annotation.RequestMethod.POST})
public void setModelData(HttpServletRequest request, HttpServletResponse response)
throws IOException, FileUploadException {
@@ -655,21 +660,15 @@ public class CreateOptimizationController extends RestrictedBaseController {
}
if (!errorMsg.isEmpty()) {
-
- PrintWriter out = response.getWriter();
-
- response.setCharacterEncoding(UTF8);
- response.setContentType(APPLICATIONJSON);
- request.setCharacterEncoding(UTF8);
-
- JSONObject j = new JSONObject();
- j.put("errorMsg", errorMsg);
- out.write(j.toString());
+ response.setCharacterEncoding(PolicyUtils.CHARACTER_ENCODING);
+ response.setContentType(PolicyUtils.APPLICATION_JSON);
+ request.setCharacterEncoding(PolicyUtils.CHARACTER_ENCODING);
+ response.getWriter().write(new JSONObject().put("errorMsg", errorMsg).toString());
return;
}
List<File> fileList = new ArrayList<>();
- MSModelUtils modelUtil = new MSModelUtils();
+ MsModelUtils modelUtil = new MsModelUtils();
this.directory = MODEL;
if (zip) {
extractFolder(this.newFile);
@@ -699,7 +698,7 @@ public class CreateOptimizationController extends RestrictedBaseController {
modelType = "yml";
modelList.add(this.newModel.getModelName());
String className = this.newModel.getModelName();
- MSAttributeObject optimizationAttributes = new MSAttributeObject();
+ MsAttributeObject optimizationAttributes = new MsAttributeObject();
optimizationAttributes.setClassName(className);
LinkedHashMap<String, String> returnAttributeList = new LinkedHashMap<>();
@@ -731,20 +730,18 @@ public class CreateOptimizationController extends RestrictedBaseController {
}
- PrintWriter out = response.getWriter();
-
- response.setCharacterEncoding(UTF8);
- response.setContentType(APPLICATIONJSON);
- request.setCharacterEncoding(UTF8);
+ response.setCharacterEncoding(PolicyUtils.CHARACTER_ENCODING);
+ response.setContentType(PolicyUtils.APPLICATION_JSON);
+ request.setCharacterEncoding(PolicyUtils.CHARACTER_ENCODING);
ObjectMapper mapper = new ObjectMapper();
- JSONObject j = new JSONObject();
- j.put("classListDatas", modelList);
- j.put("modelDatas", mapper.writeValueAsString(classMap));
- j.put("modelType", modelType);
- j.put("dataOrderInfo", modelUtil.getDataOrderInfo());
+ JSONObject json = new JSONObject();
+ json.put("classListDatas", modelList);
+ json.put("modelDatas", mapper.writeValueAsString(classMap));
+ json.put("modelType", modelType);
+ json.put("dataOrderInfo", modelUtil.getDataOrderInfo());
- out.write(j.toString());
+ response.getWriter().write(json.toString());
}
/*
@@ -752,7 +749,6 @@ public class CreateOptimizationController extends RestrictedBaseController {
*/
@SuppressWarnings("rawtypes")
private void extractFolder(String zipFile) {
- int BUFFER = 2048;
File file = new File(zipFile);
try (ZipFile zip = new ZipFile(file)) {
@@ -802,23 +798,19 @@ public class CreateOptimizationController extends RestrictedBaseController {
private void retrieveDependency(String workingFile) {
- MSModelUtils utils = new MSModelUtils(PolicyController.getMsOnapName(), PolicyController.getMsPolicyName());
- Map<String, MSAttributeObject> tempMap;
+ MsModelUtils utils = new MsModelUtils(PolicyController.getMsOnapName(), PolicyController.getMsPolicyName());
+ Map<String, MsAttributeObject> tempMap;
- tempMap = utils.processEpackage(workingFile, MODEL_TYPE.XMI);
+ tempMap = utils.processEpackage(workingFile, ModelType.XMI);
classMap.putAll(tempMap);
LOGGER.info(tempMap);
-
- return;
-
}
private List<File> listModelFiles(String directoryName) {
File fileDirectory = new File(directoryName);
List<File> resultList = new ArrayList<>();
- File[] fList = fileDirectory.listFiles();
- for (File file : fList) {
+ for (File file : fileDirectory.listFiles()) {
if (file.isFile()) {
resultList.add(file);
} else if (file.isDirectory()) {
@@ -831,9 +823,9 @@ public class CreateOptimizationController extends RestrictedBaseController {
private List<String> createList() {
List<String> list = new ArrayList<>();
- for (Entry<String, MSAttributeObject> cMap : classMap.entrySet()) {
- if (cMap.getValue().isPolicyTempalate()) {
- list.add(cMap.getKey());
+ for (Entry<String, MsAttributeObject> entrySet : classMap.entrySet()) {
+ if (entrySet.getValue().isPolicyTempalate()) {
+ list.add(entrySet.getKey());
}
}
@@ -858,7 +850,7 @@ public class CreateOptimizationController extends RestrictedBaseController {
private OptimizationObject setOptimizationObjectValues(PolicyRestAdapter policyAdapter) {
OptimizationObject optimizationObject = new OptimizationObject();
- optimizationObject.setTemplateVersion(XACMLProperties.getProperty(XACMLRestProperties.TemplateVersion_OOF));
+ optimizationObject.setTemplateVersion(XACMLProperties.getProperty(XacmlRestProperties.TEMPLATE_VERSION_OOF));
if (policyAdapter.getServiceType() != null) {
optimizationObject.setService(policyAdapter.getServiceType());
@@ -888,7 +880,8 @@ public class CreateOptimizationController extends RestrictedBaseController {
}
}
-
+@Getter
+@Setter
class OptimizationObject {
private String service;
@@ -901,95 +894,5 @@ class OptimizationObject {
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 getPriority() {
- return priority;
- }
-
- public void setPriority(String priority) {
- this.priority = priority;
- }
-
- public String getPolicyScope() {
- return policyScope;
- }
-
- public void setPolicyScope(String policyScope) {
- this.policyScope = policyScope;
- }
-
- 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 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 getTemplateVersion() {
- return templateVersion;
- }
-
- public void setTemplateVersion(String templateVersion) {
- this.templateVersion = templateVersion;
- }
-
}
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
index 6cd121ee6..a2cf20834 100644
--- 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
@@ -2,14 +2,14 @@
* ============LICENSE_START=======================================================
* ONAP Policy Engine
* ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017, 2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -20,13 +20,18 @@
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 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.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;
@@ -35,117 +40,87 @@ import org.onap.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{
+public class CreatePolicyController extends RestrictedBaseController {
private static Logger policyLogger = FlexLogger.getLogger(CreatePolicyController.class);
- protected PolicyRestAdapter policyAdapter = null;
- private ArrayList<Object> attributeList;
- boolean isValidForm = false;
-
- 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){
- policyLogger.error("Error while collecting the desciption tag in ActionPolicy " + policyNameValue ,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<AnyOfType> anyOfList = target.getAnyOf();
- if (anyOfList != null) {
- Iterator<AnyOfType> iterAnyOf = anyOfList.iterator();
- while (iterAnyOf.hasNext()) {
- AnyOfType anyOf = iterAnyOf.next();
- // Under AnyOFType we have AllOFType
- List<AllOfType> allOfList = anyOf.getAllOf();
- if (allOfList != null) {
- Iterator<AllOfType> iterAllOf = allOfList.iterator();
- int index = 0;
- while (iterAllOf.hasNext()) {
- AllOfType allOf = iterAllOf.next();
- // Under AllOFType we have Match
- List<MatchType> matchList = allOf.getMatch();
- if (matchList != null) {
- Iterator<MatchType> 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)) {
- policyAdapter.setOnapName(value);
- }
- 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")){
- PolicyController controller = new PolicyController();
- String newDate = controller.convertDate(value);
- policyAdapter.setTtlDate(newDate);
- }
- if ("ConfigName".equals(attributeId)){
- 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<String, String> attribute = new HashMap<>();
- attribute.put("key", attributeId);
- attribute.put("value", value);
- attributeList.add(attribute);
- }
- index++;
- }
- }
- }
- }
- }
- }
+ protected PolicyRestAdapter policyAdapter = null;
+ private ArrayList<Object> attributeList;
+ boolean isValidForm = false;
- policyAdapter.setAttributes(attributeList);
- }
- List<Object> 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());
- }
- }
- }
- }
+ /**
+ * prePopulateBaseConfigPolicyData.
+ *
+ * @param policyAdapter PolicyRestAdapter
+ * @param entity PolicyEntity
+ */
+ public void prePopulateBaseConfigPolicyData(PolicyRestAdapter policyAdapter, PolicyEntity entity) {
+ attributeList = new ArrayList<>();
+ if (! (policyAdapter.getPolicyData() instanceof PolicyType)) {
+ return;
+ }
+ 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) {
+ policyLogger.error("Error while collecting the desciption tag in ActionPolicy " + policyNameValue, e);
+ description = policy.getDescription();
+ }
+ policyAdapter.setPolicyDescription(description);
+ // Get the target data under policy.
+ TargetType target = policy.getTarget();
+ //
+ // NOTE: target.getAnyOf() will NEVER return null
+ //
+ if (target != null) {
+ // Under target we have AnyOFType
+ for (AnyOfType anyOf : target.getAnyOf()) {
+ // Under AnyOFType we have AllOFType
+ //
+ // NOTE: anyOf.getAllOf() will NEVER return null
+ //
+ int index = 0;
+ for (AllOfType allOf : anyOf.getAllOf()) {
+ // Under AllOFType we have Match
+ // NOTE: allOf.getMatch() will NEVER be NULL
+ //
+ for (MatchType match : allOf.getMatch()) {
+ //
+ // Under the match we have attribute value and
+ // attributeDesignator. So,finally down to the actual attribute.
+ //
+ String value = (String) match.getAttributeValue().getContent().get(0);
+ String attributeId = match.getAttributeDesignator().getAttributeId();
+ // First match in the target is OnapName, so set that value.
+ policyAdapter.setupUsingAttribute(attributeId, value);
+ // After Onap and Config it is optional to have attributes, so
+ // check weather dynamic values or there or not.
+ if (index >= 7) {
+ Map<String, String> attribute = new HashMap<>();
+ attribute.put("key", attributeId);
+ attribute.put("value", value);
+ attributeList.add(attribute);
+ }
+ index++;
+ }
+ }
+ }
+ policyAdapter.setAttributes(attributeList);
+ }
+ List<Object> ruleList = policy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition();
+ for (Object object : ruleList) {
+ if (object instanceof RuleType) {
+ // get the condition data under the rule for rule Algorithms.
+ policyAdapter.setRuleID(((RuleType) object).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
index d3af75dfd..0ca315bf1 100644
--- 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
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP Policy Engine
* ================================================================================
- * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -29,6 +29,7 @@ import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
+
import java.io.IOException;
import java.io.PrintWriter;
import java.net.MalformedURLException;
@@ -41,6 +42,7 @@ 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;
@@ -53,12 +55,13 @@ import javax.management.remote.JMXServiceURL;
import javax.script.SimpleBindings;
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.dao.SystemLogDbDao;
import org.onap.policy.model.PDPGroupContainer;
-import org.onap.policy.rest.XACMLRestProperties;
+import org.onap.policy.rest.XacmlRestProperties;
import org.onap.policy.rest.dao.CommonClassDao;
import org.onap.policy.rest.jpa.PolicyEntity;
import org.onap.policy.utils.PolicyUtils;
@@ -117,15 +120,14 @@ public class DashboardController extends RestrictedBaseController {
return policyController != null ? getPolicyController() : new PolicyController();
}
-
-
/**
* This method is to retrieve all the data of last 30 days from PolicyEntity table as default.
- *
+ *
* @param request object
* @param response object contains retrieved data
*/
- @RequestMapping(value = {"/get_DashboardPolicyCRUDData"},
+ @RequestMapping(
+ value = {"/get_DashboardPolicyCRUDData"},
method = {org.springframework.web.bind.annotation.RequestMethod.GET},
produces = MediaType.APPLICATION_JSON_VALUE)
public void get_DashboardPolicyCrudData(HttpServletRequest request, HttpServletResponse response) {
@@ -135,9 +137,7 @@ public class DashboardController extends RestrictedBaseController {
mapper.setVisibility(PropertyAccessor.FIELD, Visibility.ANY);
addPolicyCrudInfoToTable();
model.put("papStatusCRUDData", mapper.writeValueAsString(policyStatusCrudData));
- JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
- JSONObject j = new JSONObject(msg);
- response.getWriter().write(j.toString());
+ response.getWriter().write(new JSONObject(new JsonMessage(mapper.writeValueAsString(model))).toString());
} catch (Exception e) {
policyLogger.error(exceptionOccured, e);
}
@@ -145,11 +145,12 @@ public class DashboardController extends RestrictedBaseController {
/**
* This method retrieves data based on input criteria.
- *
+ *
* @param request object
* @param response object contains retrieved data
*/
- @RequestMapping(value = {"/dashboardController/dashboardAdvancedSearch.htm"},
+ @RequestMapping(
+ value = {"/dashboardController/dashboardAdvancedSearch.htm"},
method = {org.springframework.web.bind.annotation.RequestMethod.POST})
public void dashboardAdvancedSearch(HttpServletRequest request, HttpServletResponse response) throws IOException {
String lscope = null;
@@ -185,11 +186,9 @@ public class DashboardController extends RestrictedBaseController {
getPolicyData(lscope, lstage, isDelected, ttlDateAfter, ttlDateBefore);
Map<String, Object> model = new HashMap<>();
model.put("policyStatusCRUDData", mapper.writeValueAsString(policyStatusCrudData));
- JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
- JSONObject j = new JSONObject(msg);
- response.getWriter().write(j.toString());
+ response.getWriter().write(new JSONObject(new JsonMessage(mapper.writeValueAsString(model))).toString());
} catch (Exception e) {
- response.setCharacterEncoding("UTF-8");
+ response.setCharacterEncoding(PolicyUtils.CHARACTER_ENCODING);
PrintWriter out = response.getWriter();
out.write(PolicyUtils.CATCH_EXCEPTION);
}
@@ -198,11 +197,12 @@ public class DashboardController extends RestrictedBaseController {
/**
* This method is to retrieve data from PolicyEntity table.
- *
+ *
* @param request object
* @param response object contains retrieved data
*/
- @RequestMapping(value = {"/get_DashboardPdpPolicyCRUDData"},
+ @RequestMapping(
+ value = {"/get_DashboardPdpPolicyCRUDData"},
method = {org.springframework.web.bind.annotation.RequestMethod.GET},
produces = MediaType.APPLICATION_JSON_VALUE)
public void get_DashboardPdpPolicyCrudData(HttpServletRequest request, HttpServletResponse response) {
@@ -211,15 +211,20 @@ public class DashboardController extends RestrictedBaseController {
ObjectMapper mapper = new ObjectMapper();
mapper.setVisibility(PropertyAccessor.FIELD, Visibility.ANY);
model.put("pdpStatusCRUDData", mapper.writeValueAsString(pdpStatusCrudData));
- JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
- JSONObject j = new JSONObject(msg);
- response.getWriter().write(j.toString());
+ response.getWriter().write(new JSONObject(new JsonMessage(mapper.writeValueAsString(model))).toString());
} catch (Exception e) {
policyLogger.error(exceptionOccured, e);
}
}
- @RequestMapping(value = {"/get_DashboardLoggingData"},
+ /**
+ * getData.
+ *
+ * @param request HttpServletRequest
+ * @param response HttpServletResponse
+ */
+ @RequestMapping(
+ value = {"/get_DashboardLoggingData"},
method = {org.springframework.web.bind.annotation.RequestMethod.GET},
produces = MediaType.APPLICATION_JSON_VALUE)
public void getData(HttpServletRequest request, HttpServletResponse response) {
@@ -227,15 +232,20 @@ public class DashboardController extends RestrictedBaseController {
Map<String, Object> 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());
+ response.getWriter().write(new JSONObject(new JsonMessage(mapper.writeValueAsString(model))).toString());
} catch (Exception e) {
policyLogger.error(exceptionOccured + e);
}
}
- @RequestMapping(value = {"/get_DashboardSystemAlertData"},
+ /**
+ * getSystemAlertData.
+ *
+ * @param request HttpServletRequest
+ * @param response HttpServletResponse
+ */
+ @RequestMapping(
+ value = {"/get_DashboardSystemAlertData"},
method = {org.springframework.web.bind.annotation.RequestMethod.GET},
produces = MediaType.APPLICATION_JSON_VALUE)
public void getSystemAlertData(HttpServletRequest request, HttpServletResponse response) {
@@ -243,15 +253,20 @@ public class DashboardController extends RestrictedBaseController {
Map<String, Object> 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());
+ response.getWriter().write(new JSONObject(new JsonMessage(mapper.writeValueAsString(model))).toString());
} catch (Exception e) {
policyLogger.error(exceptionOccured + e);
}
}
- @RequestMapping(value = {"/get_DashboardPAPStatusData"},
+ /**
+ * getPAPStatusData.
+ *
+ * @param request HttpServletRequest
+ * @param response HttpServletResponse
+ */
+ @RequestMapping(
+ value = {"/get_DashboardPAPStatusData"},
method = {org.springframework.web.bind.annotation.RequestMethod.GET},
produces = MediaType.APPLICATION_JSON_VALUE)
public void getPAPStatusData(HttpServletRequest request, HttpServletResponse response) {
@@ -261,20 +276,25 @@ public class DashboardController extends RestrictedBaseController {
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());
+ response.getWriter().write(new JSONObject(new JsonMessage(mapper.writeValueAsString(model))).toString());
} catch (Exception e) {
policyLogger.error(exceptionOccured + e);
}
}
- @RequestMapping(value = {"/get_DashboardPDPStatusData"},
+ /**
+ * getPDPStatusData.
+ *
+ * @param request HttpServletRequest
+ * @param response HttpServletResponse
+ */
+ @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<String, Object> model = new HashMap<>();
+ final Map<String, Object> model = new HashMap<>();
ObjectMapper mapper = new ObjectMapper();
mapper.setVisibility(PropertyAccessor.FIELD, Visibility.ANY);
PolicyController controller = getPolicyControllerInstance();
@@ -282,28 +302,32 @@ public class DashboardController extends RestrictedBaseController {
addPDPToTable();
model.put("pdpTableDatas", mapper.writeValueAsString(pdpStatusData));
JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
- JSONObject j = new JSONObject(msg);
- response.getWriter().write(j.toString());
+ response.getWriter().write(new JSONObject(msg).toString());
} catch (Exception e) {
policyLogger.error(exceptionOccured + e);
}
}
- @RequestMapping(value = {"/get_DashboardPolicyActivityData"},
+ /**
+ * getPolicyActivityData.
+ *
+ * @param request HttpServletRequest
+ * @param response HttpServletResponse
+ */
+ @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<String, Object> model = new HashMap<>();
+ final Map<String, Object> 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());
+ response.getWriter().write(new JSONObject(new JsonMessage(mapper.writeValueAsString(model))).toString());
} catch (Exception e) {
policyLogger.error(exceptionOccured + e);
}
@@ -327,9 +351,9 @@ public class DashboardController extends RestrictedBaseController {
papStatus = "CANNOT_CONNECT";
policyLogger.error("Error getting PAP status, PAP not responding to requests", e1);
}
- String papURL = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_URL);
+ String papUrl = XACMLProperties.getProperty(XacmlRestProperties.PROP_PAP_URL);
JSONObject object = new JSONObject();
- object.put("system", papURL);
+ object.put("system", papUrl);
object.put("status", papStatus);
List<Object> data = commonClassDao.getDataByQuery("from PolicyEntity", new SimpleBindings());
object.put("noOfPolicy", data.size());
@@ -337,9 +361,8 @@ public class DashboardController extends RestrictedBaseController {
papStatusData.add(0, object);
}
-
- /*
- * Add the PAP Policy information to the PAP Table
+ /**
+ * Add the PAP Policy information to the PAP Table.
*/
public void addPolicyCrudInfoToTable() {
policyStatusCrudData = new ArrayList<>();
@@ -362,7 +385,7 @@ public class DashboardController extends RestrictedBaseController {
object.put(scope, ((PolicyEntity) data).getScope());
object.put("policyName", ((PolicyEntity) data).getPolicyName());
object.put("version", ((PolicyEntity) data).getVersion());
- if (isPushedToPDP(((PolicyEntity) data).getPolicyId())) {
+ if (isPushedToPdp(((PolicyEntity) data).getPolicyId())) {
object.put(stage, "PDP");
} else {
object.put(stage, "PAP");
@@ -388,13 +411,13 @@ public class DashboardController extends RestrictedBaseController {
/*
* Add the PDP Policy information to the PDP Table
*/
- private boolean isPushedToPDP(long policyId) {
+ private boolean isPushedToPdp(long policyId) {
try {
String groupEntityquery = "from PolicyGroupEntity where policyid = :policyEntityId";
SimpleBindings geParams = new SimpleBindings();
geParams.put("policyEntityId", policyId);
List<Object> groupobject = commonClassDao.getDataByQuery(groupEntityquery, geParams);
- if (groupobject != null && groupobject.size() > 0) {
+ if (groupobject != null && ! groupobject.isEmpty()) {
return true;
}
} catch (Exception e) {
@@ -407,7 +430,8 @@ public class DashboardController extends RestrictedBaseController {
/*
* Add the Policy information to the policyStatusCRUDDataTable
*/
- private void getPolicyData(String inputScope, String inputStage, String isDeleted, String createdAfter, String createdBefore) {
+ private void getPolicyData(String inputScope, String inputStage, String isDeleted, String createdAfter,
+ String createdBefore) {
policyStatusCrudData = new ArrayList<>();
List<Object> policyData = null;
SimpleBindings geParams = new SimpleBindings();
@@ -479,7 +503,7 @@ public class DashboardController extends RestrictedBaseController {
object.put(scope, data.getScope());
object.put("policyName", data.getPolicyName());
object.put("version", data.getVersion());
- if (isPushedToPDP(data.getPolicyId())) {
+ if (isPushedToPdp(data.getPolicyId())) {
object.put(stage, "PDP");
} else {
object.put(stage, "PAP");
@@ -503,7 +527,7 @@ public class DashboardController extends RestrictedBaseController {
}
/**
- * Add PDP Information to the PDP Table
+ * Add PDP Information to the PDP Table.
*
*/
public void addPDPToTable() {
@@ -516,7 +540,7 @@ public class DashboardController extends RestrictedBaseController {
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());
+ 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);
@@ -553,7 +577,7 @@ public class DashboardController extends RestrictedBaseController {
}
}
- private static String parseIPSystem(String line) {
+ private static String parseIpSystem(String line) {
Pattern pattern = Pattern.compile("://(.+?):");
Matcher ip = pattern.matcher(line);
if (ip.find()) {
@@ -570,13 +594,12 @@ public class DashboardController extends RestrictedBaseController {
policyLogger.debug("Create an RMI connector client and connect it to the JMX connector server");
HashMap map = null;
- try (JMXConnector jmxConnection = JMXConnectorFactory.newJMXConnector(createConnectionURL(host, port), map)) {
+ try (JMXConnector jmxConnection = JMXConnectorFactory.newJMXConnector(createConnectionUrl(host, port), map)) {
jmxConnection.connect();
- Object o =
- jmxConnection.getMBeanServerConnection().getAttribute(
- new ObjectName("PdpRest:type=PdpRestMonitor"), jmxAttribute);
- policyLogger.debug("pdpEvaluationNA value retreived: " + o);
- return (long) o;
+ Object obj = jmxConnection.getMBeanServerConnection()
+ .getAttribute(new ObjectName("PdpRest:type=PdpRestMonitor"), jmxAttribute);
+ policyLogger.debug("pdpEvaluationNA value retreived: " + obj);
+ return (long) obj;
} catch (MalformedURLException e) {
policyLogger.error("MalformedURLException for JMX connection", e);
} catch (IOException e) {
@@ -597,11 +620,10 @@ public class DashboardController extends RestrictedBaseController {
return -1;
}
- private static JMXServiceURL createConnectionURL(String host, int port) throws MalformedURLException {
+ 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
*/
@@ -626,8 +648,8 @@ public class DashboardController extends RestrictedBaseController {
// 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");
+ String pdpIpAddress = parseIpSystem(pdp.getId());
+ policyList = getPolicy(pdpIpAddress, ((OnapPDP) pdp).getJmxPort());
}
if (policyList != null && policyList.toString().length() > 3) {
String[] splitPolicy = policyList.toString().split(",");
@@ -643,19 +665,15 @@ public class DashboardController extends RestrictedBaseController {
}
}
} else {
+ JSONObject object = new JSONObject();
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);
}
+ object.put("fireCount", "NA");
+ object.put("system", pdp.getId());
+ policyActivityData.add(object);
}
}
}
@@ -665,17 +683,16 @@ public class DashboardController extends RestrictedBaseController {
* 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);
+ private Object getPolicy(String host, int port) {
+ policyLogger
+ .debug("Create an RMI connector client and connect it to the JMX connector server for Policy: " + host);
HashMap map = null;
- try (JMXConnector jmxConnection = JMXConnectorFactory.newJMXConnector(createConnectionURL(host, port), map)) {
+ try (JMXConnector jmxConnection = JMXConnectorFactory.newJMXConnector(createConnectionUrl(host, port), map)) {
jmxConnection.connect();
- Object o =
- jmxConnection.getMBeanServerConnection().getAttribute(
- new ObjectName("PdpRest:type=PdpRestMonitor"), "policyMap");
- policyLogger.debug("policyMap value retreived: " + o);
- return o;
+ Object obj = jmxConnection.getMBeanServerConnection()
+ .getAttribute(new ObjectName("PdpRest:type=PdpRestMonitor"), "policyMap");
+ policyLogger.debug("policyMap value retreived: " + obj);
+ return obj;
} catch (MalformedURLException e) {
policyLogger.error("MalformedURLException for JMX connection", e);
} catch (IOException e) {
@@ -705,8 +722,7 @@ public class DashboardController extends RestrictedBaseController {
private static Integer countPolicyID(String line) {
String[] splitLine = line.split("=");
- String sCount = splitLine[1].replace("}", "");
- return Integer.parseInt(sCount);
+ return Integer.parseInt(splitLine[1].replace("}", ""));
}
}
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
index 4e8c8c141..c3b474521 100644
--- 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
@@ -2,14 +2,14 @@
* ============LICENSE_START=======================================================
* ONAP Policy Engine
* ================================================================================
- * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -25,24 +25,13 @@ import java.io.InputStream;
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 java.util.Map.Entry;
+
import javax.xml.bind.JAXBElement;
-import org.apache.commons.io.IOUtils;
-import org.apache.commons.lang3.StringUtils;
-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.onap.policy.xacml.util.XACMLPolicyWriter;
-import org.onap.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;
@@ -59,28 +48,47 @@ 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;
+import org.apache.commons.io.IOUtils;
+import org.apache.commons.lang3.StringUtils;
+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.onap.policy.xacml.util.XACMLPolicyWriter;
+import org.onap.portalsdk.core.controller.RestrictedBaseController;
+import org.springframework.stereotype.Controller;
+import org.springframework.web.bind.annotation.RequestMapping;
+
@Controller
@RequestMapping("/")
public class DecisionPolicyController extends RestrictedBaseController {
private static final Logger policyLogger = FlexLogger.getLogger(DecisionPolicyController.class);
-
+
public static final String FUNCTION_NOT = "urn:oasis:names:tc:xacml:1.0:function:not";
private static final String BLENTRY = "@blEntry@";
private static final String DECISIONRAWTYPE = "@#RuleProvider@#Decision_Raw@#RuleProvider@#";
- private static final String GUARD_YAML= "GUARD_YAML";
- private static final String GUARD_BL_YAML= "GUARD_BL_YAML";
- private static final String GUARD_MIN_MAX= "GUARD_MIN_MAX";
-
+ private static final String GUARD_YAML = "GUARD_YAML";
+ private static final String GUARD_BL_YAML = "GUARD_BL_YAML";
+ private static final String GUARD_MIN_MAX = "GUARD_MIN_MAX";
+
protected PolicyRestAdapter policyAdapter = null;
private ArrayList<Object> ruleAlgorithmList;
private ArrayList<Object> treatmentList = null;
protected LinkedList<Integer> ruleAlgoirthmTracker;
-
+
public DecisionPolicyController() {
// This constructor is empty
}
-
- public void rawXACMLPolicy(PolicyRestAdapter policyAdapter, PolicyEntity entity) {
+
+ /**
+ * rawXacmlPolicy. Should this method be private?
+ *
+ * @param policyAdapter PolicyRestAdapter
+ * @param entity PolicyEntity
+ */
+ public void rawXacmlPolicy(PolicyRestAdapter policyAdapter, PolicyEntity entity) {
try (InputStream policyXmlStream = XACMLPolicyWriter.getXmlAsInputStream(policyAdapter.getPolicyData())) {
String name = StringUtils.substringAfter(entity.getPolicyName(), "Decision_");
policyAdapter.setPolicyName(name.substring(0, name.indexOf('.')));
@@ -91,6 +99,12 @@ public class DecisionPolicyController extends RestrictedBaseController {
}
}
+ /**
+ * prePopulateDecisionPolicyData.
+ *
+ * @param policyAdapter PolicyRestAdapter
+ * @param entity PolicyEntity
+ */
@SuppressWarnings("unchecked")
public void prePopulateDecisionPolicyData(PolicyRestAdapter policyAdapter, PolicyEntity entity) {
List<Object> attributeList = new ArrayList<>();
@@ -106,237 +120,222 @@ public class DecisionPolicyController extends RestrictedBaseController {
}
if (rawPolicyCheck) {
- rawXACMLPolicy(policyAdapter, entity);
- } else {
- RainyDayParams rainydayParams = new RainyDayParams();
- Object policyData = policyAdapter.getPolicyData();
- PolicyType policy = (PolicyType) policyData;
- policyAdapter.setOldPolicyFileName(policyAdapter.getPolicyName());
-
- policyAdapter.setPolicyName(StringUtils.substringAfter(policyAdapter.getPolicyName(), "Decision_"));
- String description = "";
- String blackListEntryType = "Use Manual Entry";
- try {
- if (policy.getDescription().contains(BLENTRY)) {
- blackListEntryType = policy.getDescription().substring(policy.getDescription().indexOf(BLENTRY) + 9,
- policy.getDescription().lastIndexOf(BLENTRY));
- }
- policyAdapter.setBlackListEntryType(blackListEntryType);
- description = policy.getDescription().substring(0, policy.getDescription().indexOf("@CreatedBy:"));
+ rawXacmlPolicy(policyAdapter, entity);
+ return;
+ }
+ RainyDayParams rainydayParams = new RainyDayParams();
+ Object policyData = policyAdapter.getPolicyData();
+ PolicyType policy = (PolicyType) policyData;
+ policyAdapter.setOldPolicyFileName(policyAdapter.getPolicyName());
- } catch (Exception e) {
- policyLogger.info("General error", e);
- description = policy.getDescription();
+ policyAdapter.setPolicyName(StringUtils.substringAfter(policyAdapter.getPolicyName(), "Decision_"));
+ String description = "";
+ String blackListEntryType = "Use Manual Entry";
+ try {
+ if (policy.getDescription().contains(BLENTRY)) {
+ blackListEntryType = policy.getDescription().substring(policy.getDescription().indexOf(BLENTRY) + 9,
+ policy.getDescription().lastIndexOf(BLENTRY));
}
- policyAdapter.setPolicyDescription(description);
- // Get the target data under policy for Action.
- TargetType target = policy.getTarget();
- if (target != null) {
- // under target we have AnyOFType
- List<AnyOfType> anyOfList = target.getAnyOf();
- if (anyOfList != null) {
- Iterator<AnyOfType> iterAnyOf = anyOfList.iterator();
- while (iterAnyOf.hasNext()) {
- AnyOfType anyOf = iterAnyOf.next();
- // Under AntOfType we have AllOfType
- List<AllOfType> allOfList = anyOf.getAllOf();
- if (allOfList != null) {
- Iterator<AllOfType> iterAllOf = allOfList.iterator();
- while (iterAllOf.hasNext()) {
- AllOfType allOf = iterAllOf.next();
- // Under AllOfType we have Mathch.
- List<MatchType> matchList = allOf.getMatch();
- int index = 0;
- if (matchList != null) {
- Iterator<MatchType> 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);
- if (value != null) {
- value = value.replaceAll("\\(\\?i\\)", "");
- }
- AttributeDesignatorType designator = match.getAttributeDesignator();
- String attributeId = designator.getAttributeId();
- // First match in the target is OnapName, so set that value.
- if ("ONAPName".equals(attributeId)) {
- 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<String, String> 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 < attributeList.size(); i++) {
- Map<String, String> map = (Map<String, String>) attributeList.get(i);
- if ("WorkStep".equals(map.get("key"))) {
- rainydayParams.setWorkstep(map.get("value"));
- rainy = true;
- } else if ("BB_ID".equals(map.get("key"))) {
- rainydayParams.setBbid(map.get("value"));
- rainy = true;
- } else if ("ServiceType".equals(map.get("key"))) {
- rainydayParams.setServiceType(map.get("value"));
- rainy = true;
- } else if ("VNFType".equals(map.get("key"))) {
- rainydayParams.setVnfType(map.get("value"));
- rainy = true;
- }
- }
+ policyAdapter.setBlackListEntryType(blackListEntryType);
+ 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) {
+ rainydayParams.setTreatmentTableChoices(treatmentList);
+ policyAdapter.setRainyday(rainydayParams);
+ policyAdapter.setSettings(decisionList);
+ return;
+ }
+ // under target we have AnyOFType
+ for (AnyOfType anyOf : target.getAnyOf()) {
+ for (AllOfType allOf : anyOf.getAllOf()) {
+ int index = 0;
+ for (MatchType match : allOf.getMatch()) {
+ //
+ // 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);
+ if (value != null) {
+ value = value.replaceAll("\\(\\?i\\)", "");
}
- if (rainy) {
- policyAdapter.setRuleProvider("Rainy_Day");
+ AttributeDesignatorType designator = match.getAttributeDesignator();
+ String attributeId = designator.getAttributeId();
+ // First match in the target is OnapName, so set that value.
+ policyAdapter.setupUsingAttribute(attributeId, 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<String, String> 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 < attributeList.size(); i++) {
+ Map<String, String> map = (Map<String, String>) attributeList.get(i);
+ String key = map.get("key");
+ if ("WorkStep".equals(key)) {
+ rainydayParams.setWorkstep(map.get("value"));
+ rainy = true;
+ } else if ("BB_ID".equals(key)) {
+ rainydayParams.setBbid(map.get("value"));
+ rainy = true;
+ } else if ("ServiceType".equals(key)) {
+ rainydayParams.setServiceType(map.get("value"));
+ rainy = true;
+ } else if ("VNFType".equals(key)) {
+ rainydayParams.setVnfType(map.get("value"));
+ rainy = true;
}
+ }
+ }
+ if (rainy) {
+ policyAdapter.setRuleProvider("Rainy_Day");
+ }
- List<Object> ruleList = policy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition();
- int index = 0;
- for (Object object : ruleList) {
- if (object instanceof VariableDefinitionType) {
- VariableDefinitionType variableDefinitionType = (VariableDefinitionType) object;
- Map<String, String> settings = new HashMap<>();
- settings.put("key", variableDefinitionType.getVariableId());
- JAXBElement<AttributeValueType> attributeValueTypeElement =
- (JAXBElement<AttributeValueType>) variableDefinitionType.getExpression();
- if (attributeValueTypeElement != null) {
- AttributeValueType attributeValueType = attributeValueTypeElement.getValue();
- settings.put("value", attributeValueType.getContent().get(0).toString());
+ List<Object> ruleList = policy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition();
+ int index = 0;
+ for (Object object : ruleList) {
+ if (object instanceof VariableDefinitionType) {
+ VariableDefinitionType variableDefinitionType = (VariableDefinitionType) object;
+ Map<String, String> settings = new HashMap<>();
+ settings.put("key", variableDefinitionType.getVariableId());
+ JAXBElement<AttributeValueType> attributeValueTypeElement =
+ (JAXBElement<AttributeValueType>) 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 ("AAF".equalsIgnoreCase(((RuleType) object).getAdviceExpressions()
+ .getAdviceExpression().get(0).getAdviceId())) {
+ policyAdapter.setRuleProvider("AAF");
+ break;
+ } else if (GUARD_YAML.equalsIgnoreCase(((RuleType) object).getAdviceExpressions()
+ .getAdviceExpression().get(0).getAdviceId())) {
+ policyAdapter.setRuleProvider(GUARD_YAML);
+ } else if (GUARD_BL_YAML.equalsIgnoreCase(((RuleType) object).getAdviceExpressions()
+ .getAdviceExpression().get(0).getAdviceId())) {
+ policyAdapter.setRuleProvider(GUARD_BL_YAML);
+ } else if (GUARD_MIN_MAX.equalsIgnoreCase(((RuleType) object).getAdviceExpressions()
+ .getAdviceExpression().get(0).getAdviceId())) {
+ policyAdapter.setRuleProvider(GUARD_MIN_MAX);
}
- 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 ("AAF".equalsIgnoreCase(((RuleType) object).getAdviceExpressions()
- .getAdviceExpression().get(0).getAdviceId())) {
- policyAdapter.setRuleProvider("AAF");
- break;
- } else if (GUARD_YAML.equalsIgnoreCase(((RuleType) object).getAdviceExpressions()
- .getAdviceExpression().get(0).getAdviceId())) {
- policyAdapter.setRuleProvider(GUARD_YAML);
- } else if (GUARD_BL_YAML.equalsIgnoreCase(((RuleType) object).getAdviceExpressions()
- .getAdviceExpression().get(0).getAdviceId())) {
- policyAdapter.setRuleProvider(GUARD_BL_YAML);
- } else if (GUARD_MIN_MAX.equalsIgnoreCase(((RuleType) object).getAdviceExpressions()
- .getAdviceExpression().get(0).getAdviceId())) {
- policyAdapter.setRuleProvider(GUARD_MIN_MAX);
+ } 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
+ && (GUARD_YAML.equals(policyAdapter.getRuleProvider())
+ || (GUARD_BL_YAML.equals(policyAdapter.getRuleProvider()))
+ || (GUARD_MIN_MAX.equals(policyAdapter.getRuleProvider())))) {
+ YAMLParams yamlParams = new YAMLParams();
+ for (int i = 0; i < attributeList.size(); i++) {
+ Map<String, String> map = (Map<String, String>) attributeList.get(i);
+ String key = map.get("key");
+ if ("actor".equals(key)) {
+ yamlParams.setActor(map.get("value"));
+ } else if ("recipe".equals(key)) {
+ yamlParams.setRecipe(map.get("value"));
+ } else if ("target".equals(key)) {
+ yamlParams.setTargets(Arrays.asList(map.get("value").split("\\|")));
+ } else if ("clname".equals(key)) {
+ yamlParams.setClname(map.get("value"));
+ } else if ("min".equals(key)) {
+ yamlParams.setMin(map.get("value"));
+ } else if ("max".equals(key)) {
+ yamlParams.setMax(map.get("value"));
}
- } 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
- && (GUARD_YAML.equals(policyAdapter.getRuleProvider())
- || (GUARD_BL_YAML.equals(policyAdapter.getRuleProvider()))
- || (GUARD_MIN_MAX.equals(policyAdapter.getRuleProvider())))){
- YAMLParams yamlParams = new YAMLParams();
- for (int i = 0; i < attributeList.size(); i++) {
- Map<String, String> map = (Map<String, String>) attributeList.get(i);
- if ("actor".equals(map.get("key"))) {
- yamlParams.setActor(map.get("value"));
- } else if ("recipe".equals(map.get("key"))) {
- yamlParams.setRecipe(map.get("value"));
- } else if ("target".equals(map.get("key"))) {
- yamlParams.setTargets(Arrays.asList(map.get("value").split("\\|")));
- } else if ("clname".equals(map.get("key"))) {
- yamlParams.setClname(map.get("value"));
- } else if ("min".equals(map.get("key"))) {
- yamlParams.setMin(map.get("value"));
- } else if ("max".equals(map.get("key"))) {
- yamlParams.setMax(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 (GUARD_BL_YAML.equals(policyAdapter.getRuleProvider())) {
- apply = (ApplyType) ((ApplyType) ((ApplyType) decisionApply.getExpression()
- .get(0).getValue()).getExpression().get(1).getValue()).getExpression()
- .get(2).getValue();
- Iterator<JAXBElement<?>> attributes = apply.getExpression().iterator();
- List<String> blackList = new ArrayList<>();
- while (attributes.hasNext()) {
- blackList.add(((AttributeValueType) attributes.next().getValue())
- .getContent().get(0).toString());
- }
- yamlParams.setBlackList(blackList);
- if ("Use File Upload".equals(policyAdapter.getBlackListEntryType())) {
- policyAdapter.setBlackListEntries(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<Object>());
- policyAdapter.setRuleAlgorithmschoices(new ArrayList<Object>());
- break;
+ 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 (GUARD_BL_YAML.equals(policyAdapter.getRuleProvider())) {
+ apply = (ApplyType) ((ApplyType) ((ApplyType) decisionApply.getExpression()
+ .get(0).getValue()).getExpression().get(1).getValue()).getExpression()
+ .get(2).getValue();
+ List<String> blackList = new ArrayList<>();
+ for (JAXBElement<?> attr : apply.getExpression()) {
+ blackList.add(((AttributeValueType) attr.getValue())
+ .getContent().get(0).toString());
}
- // Populating Rule Algorithms starting from compound.
- prePopulateDecisionCompoundRuleAlgorithm(index, decisionApply);
- policyAdapter.setRuleAlgorithmschoices(ruleAlgorithmList);
+ yamlParams.setBlackList(blackList);
+ if ("Use File Upload".equals(policyAdapter.getBlackListEntryType())) {
+ policyAdapter.setBlackListEntries(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(':')));
}
- } else if (policyAdapter.getRuleProvider() != null
- && "Rainy_Day".equals(policyAdapter.getRuleProvider())
- && ((RuleType) object).getEffect().equals(EffectType.PERMIT)) {
+ policyAdapter.setYamlparams(yamlParams);
+ policyAdapter.setAttributes(new ArrayList<Object>());
+ policyAdapter.setRuleAlgorithmschoices(new ArrayList<Object>());
+ break;
+ }
+ // Populating Rule Algorithms starting from compound.
+ prePopulateDecisionCompoundRuleAlgorithm(index, decisionApply);
+ policyAdapter.setRuleAlgorithmschoices(ruleAlgorithmList);
+ }
+ } else if (policyAdapter.getRuleProvider() != null
+ && "Rainy_Day".equals(policyAdapter.getRuleProvider())
+ && ((RuleType) object).getEffect().equals(EffectType.PERMIT)) {
- TargetType ruleTarget = ((RuleType) object).getTarget();
- AdviceExpressionsType adviceExpression = ((RuleType) object).getAdviceExpressions();
+ 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<AttributeValueType> tempTreatmentObj =
- (JAXBElement<AttributeValueType>) adviceExpression.getAdviceExpression().get(0)
- .getAttributeAssignmentExpression().get(0).getExpression();
- String treatment = tempTreatmentObj.getValue().getContent().get(0).toString();
+ String errorcode = ruleTarget.getAnyOf().get(0).getAllOf().get(0).getMatch().get(1)
+ .getAttributeValue().getContent().get(0).toString();
+ JAXBElement<AttributeValueType> tempTreatmentObj =
+ (JAXBElement<AttributeValueType>) adviceExpression.getAdviceExpression().get(0)
+ .getAttributeAssignmentExpression().get(0).getExpression();
+ String treatment = tempTreatmentObj.getValue().getContent().get(0).toString();
- prePopulateRainyDayTreatments(errorcode, treatment);
+ prePopulateRainyDayTreatments(errorcode, treatment);
- }
- }
}
}
-
- rainydayParams.setTreatmentTableChoices(treatmentList);
- policyAdapter.setRainyday(rainydayParams);
- policyAdapter.setSettings(decisionList);
}
+ rainydayParams.setTreatmentTableChoices(treatmentList);
+ policyAdapter.setRainyday(rainydayParams);
+ policyAdapter.setSettings(decisionList);
}
private void prePopulateRainyDayTreatments(String errorcode, String treatment) {
@@ -377,7 +376,6 @@ public class DecisionPolicyController extends RestrictedBaseController {
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);
@@ -402,36 +400,36 @@ public class DecisionPolicyController extends RestrictedBaseController {
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<String, String> 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;
- }
+ if (! isCompoundRule) {
+ return index;
+ }
+ // 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<String, String> 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;
+ 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);
+
+ return ++index;
}
}
diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/ExportAndImportDecisionBlackListEntries.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/ExportAndImportDecisionBlackListEntries.java
index 5c2e96bb5..0c0c15f05 100644
--- a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/ExportAndImportDecisionBlackListEntries.java
+++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/ExportAndImportDecisionBlackListEntries.java
@@ -2,14 +2,14 @@
* ============LICENSE_START=======================================================
* ONAP Policy Engine
* ================================================================================
- * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2018-2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -39,8 +39,10 @@ import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
+
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.FileUploadException;
@@ -59,6 +61,7 @@ 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.ReturnBlackList;
+import org.onap.policy.utils.PolicyUtils;
import org.onap.policy.xacml.api.XACMLErrorConstants;
import org.onap.portalsdk.core.controller.RestrictedBaseController;
import org.onap.portalsdk.core.web.support.JsonMessage;
@@ -66,7 +69,6 @@ import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
-
/**
* This class is used to import and export the black list entries which were used in the Decision Blacklist Guard YAML
* Policy.
@@ -84,7 +86,7 @@ public class ExportAndImportDecisionBlackListEntries extends RestrictedBaseContr
/**
* This method is used to Export the Black List entries data from Decision BlackList Guard YAML Policy. So, user can
* update the file on adding or removing the entries, for updating the policies or using in other Environments.
- *
+ *
* @param request the request contains the policy data. So, based on that we can populate and read and write the
* entries.
* @param response after reading and writing the blacklist list entries to file, the file is copied to tmp directory
@@ -117,7 +119,7 @@ public class ExportAndImportDecisionBlackListEntries extends RestrictedBaseContr
/*
* Export FileName is the combination of BlacList+Scope+PolicyName+Version+PolicyCreatedDate.
- *
+ *
*/
SimpleDateFormat parseFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
@@ -126,7 +128,7 @@ public class ExportAndImportDecisionBlackListEntries extends RestrictedBaseContr
String formatedDate = dateFormat.format(date);
String fileName = "BlackList_Scope_" + adapter.getDomainDir() + "_Name_" + adapter.getPolicyName()
- + "_Version_" + root.get("version").toString() + "_Date_" + formatedDate + ".xls";
+ + "_Version_" + root.get("version").toString() + "_Date_" + formatedDate + ".xls";
String deleteCheckPath = tmpFile + File.separator + fileName;
File deleteCheck = new File(deleteCheckPath);
@@ -145,9 +147,9 @@ public class ExportAndImportDecisionBlackListEntries extends RestrictedBaseContr
workBook.write(fos);
fos.flush();
- response.setCharacterEncoding("UTF-8");
- response.setContentType("application / json");
- request.setCharacterEncoding("UTF-8");
+ response.setCharacterEncoding(PolicyUtils.CHARACTER_ENCODING);
+ response.setContentType(PolicyUtils.APPLICATION_JSON);
+ request.setCharacterEncoding(PolicyUtils.CHARACTER_ENCODING);
PrintWriter out = response.getWriter();
String successMap = file.substring(file.lastIndexOf("webapps") + 8);
@@ -163,7 +165,7 @@ public class ExportAndImportDecisionBlackListEntries extends RestrictedBaseContr
/**
* This method is used to import the BlackList excel file into the system. Which is used to create Decision
* Blacklist Guard YAML Policy.
- *
+ *
* @param request the HTTP request contains file upload stream form GUI.
* @param response the response is send to the GUI after reading the file input stream.
*/
@@ -181,9 +183,7 @@ public class ExportAndImportDecisionBlackListEntries extends RestrictedBaseContr
} else {
readItems(items, errorLogs, model);
}
- JsonMessage msg = new JsonMessage(mapper.toJson(model));
- JSONObject jsonResposne = new JSONObject(msg);
- response.getWriter().write(jsonResposne.toString());
+ response.getWriter().write(new JSONObject(new JsonMessage(mapper.toJson(model))).toString());
} catch (FileUploadException | IOException e) {
policyLogger.error("Exception Occured while importing the BlackListEntry", e);
}
@@ -191,7 +191,7 @@ public class ExportAndImportDecisionBlackListEntries extends RestrictedBaseContr
/**
* This method is used to read the first item, as we expect only one entry in the file upload.
- *
+ *
* @param items The file entries which were uploaded from GUI.
* @param errorLogs on adding all incorrect entries, we can let user know what need to fixed.
* @param model Map which stores key value (blacklist and append list data)
@@ -218,7 +218,7 @@ public class ExportAndImportDecisionBlackListEntries extends RestrictedBaseContr
/**
* This method is used to read the workbook in xls file item.
- *
+ *
* @param fileName fileName as input parameter
* @param errorLogs on adding all incorrect entries, we can let user know what need to fixed.
* @param model Map which stores key value (blacklist and append list data)
@@ -246,7 +246,7 @@ public class ExportAndImportDecisionBlackListEntries extends RestrictedBaseContr
/**
* This method is used to read all the rows from imported Excel sheet and set to respective objects.
- *
+ *
* @param rowIterator Excel Sheet rows are passed as input parameters.
* @param blackListEntries the data is set to this object, which is going to be added.
* @param appendBlackListEntries the data is set to this object which is going to be removed.
@@ -266,7 +266,7 @@ public class ExportAndImportDecisionBlackListEntries extends RestrictedBaseContr
/**
* This method is used to read all the cells in the row.
- *
+ *
* @param cellIterator iterating the cells and will parse based on the cell type.
* @param blackListEntries the data is set to this object, which is going to be added.
* @param appendBlackListEntries the data is set to this object which is going to be removed.
@@ -300,7 +300,7 @@ public class ExportAndImportDecisionBlackListEntries extends RestrictedBaseContr
/**
* This method is used to read the Action cell entry.
- *
+ *
* @param cell reading the action entry cell.
* @param lineNo counts the number of the cell.
* @param errorLogs on adding all incorrect entries, we can let user know what need to fixed.
@@ -328,7 +328,7 @@ public class ExportAndImportDecisionBlackListEntries extends RestrictedBaseContr
/**
* This method is used to read the BlackList cell entry.
- *
+ *
* @param cell reading the blacklist entry cell.
* @param lineNo counts the number of the cell.
* @param errorLogs on adding all incorrect entries, we can let user know what need to fixed.
@@ -353,7 +353,7 @@ public class ExportAndImportDecisionBlackListEntries extends RestrictedBaseContr
/**
* This method is used to add the data to blacklist and append list after parsing each and every row.
- *
+ *
* @param actionEntry it has the input to add or not and holds either 0 or 1.
* @param blackListEntries list to add blacklist entries based on action entry = 1.
* @param appendBlackListEntries list to add append list entries based on action entry = 0.
@@ -370,7 +370,7 @@ public class ExportAndImportDecisionBlackListEntries extends RestrictedBaseContr
/**
* This method is used to identify the header of the cell.
- *
+ *
* @param cell Excel sheet cell is passed as input parameter.
* @return the column header name value
*/
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
index a8a427970..f2f7d57af 100644
--- 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
@@ -2,14 +2,14 @@
* ============LICENSE_START=======================================================
* ONAP Policy Engine
* ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017, 2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -20,9 +20,13 @@
package org.onap.policy.controller;
+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;
import java.io.File;
-import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
@@ -32,16 +36,17 @@ import java.util.Set;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
-
+import lombok.Getter;
+import lombok.Setter;
import org.json.JSONObject;
import org.onap.policy.admin.RESTfulPAPEngine;
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.utils.PolicyUtils;
import org.onap.policy.utils.UserUtils.Pair;
import org.onap.policy.xacml.api.XACMLErrorConstants;
import org.onap.policy.xacml.api.pap.OnapPDPGroup;
-import org.onap.policy.xacml.api.pap.PAPPolicyEngine;
import org.onap.policy.xacml.std.pap.StdPDP;
import org.onap.policy.xacml.std.pap.StdPDPGroup;
import org.onap.portalsdk.core.controller.RestrictedBaseController;
@@ -51,370 +56,377 @@ 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<OnapPDPGroup> groups = Collections.synchronizedList(new ArrayList<OnapPDPGroup>());
- private PDPGroupContainer container;
-
- private static String SUPERADMIN = "super-admin";
- private static String SUPEREDITOR = "super-editor";
- private static String SUPERGUEST = "super-guest";
-
- private Set<OnapPDPGroup> 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<PDPPolicy> filteredPolicies = new HashSet<>();
- Set<String> scopes;
- List<String> roles;
- String userId = isJunit() ? "Test" : UserUtils.getUserSession(request).getOrgUserId();
- List<Object> userRoles = controller.getRoles(userId);
- Pair<Set<String>, List<String>> pair = org.onap.policy.utils.UserUtils.checkRoleAndScope(userRoles);
- roles = pair.u;
- scopes = pair.t;
-
- if(!junit&& controller.getPapEngine()==null){
- setPAPEngine(request);
- }
- 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() && !scopes.isEmpty()){
- this.groups.addAll(controller.getPapEngine().getOnapPDPGroups());
- List<OnapPDPGroup> tempGroups = new ArrayList<>();
- if(!groups.isEmpty()){
- Iterator<OnapPDPGroup> pdpGroup = groups.iterator();
- while(pdpGroup.hasNext()){
- OnapPDPGroup group = pdpGroup.next();
- Set<PDPPolicy> 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);
- }
- }
- }
-
- private void setPAPEngine(HttpServletRequest request) {
- String myRequestURL = request.getRequestURL().toString();
+ private static final Logger policyLogger = FlexLogger.getLogger(PDPController.class);
+
+ protected List<OnapPDPGroup> groups = Collections.synchronizedList(new ArrayList<OnapPDPGroup>());
+ private PDPGroupContainer container;
+
+ private static String SUPERADMIN = "super-admin";
+ private static String SUPEREDITOR = "super-editor";
+ private static String SUPERGUEST = "super-guest";
+
+ private Set<OnapPDPGroup> groupsData;
+
+ private boolean junit = false;
+
+ private PolicyController policyController;
+
+ public PolicyController getPolicyController() {
+ return policyController;
+ }
+
+ public void setPolicyController(PolicyController policyController) {
+ this.policyController = policyController;
+ }
+
+ /**
+ * refreshGroups.
+ *
+ * @param request HttpServletRequest
+ */
+ public synchronized void refreshGroups(HttpServletRequest request) {
+ synchronized (this.groups) {
+ this.groups.clear();
+ try {
+ PolicyController controller = getPolicyControllerInstance();
+ Set<PDPPolicy> filteredPolicies = new HashSet<>();
+ Set<String> scopes;
+ List<String> roles;
+ String userId = isJunit() ? "Test" : UserUtils.getUserSession(request).getOrgUserId();
+ List<Object> userRoles = controller.getRoles(userId);
+ Pair<Set<String>, List<String>> pair = org.onap.policy.utils.UserUtils.checkRoleAndScope(userRoles);
+ roles = pair.second;
+ scopes = pair.first;
+
+ if (!junit && controller.getPapEngine() == null) {
+ setPapEngine(request);
+ }
+ 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() && !scopes.isEmpty()) {
+ this.groups.addAll(controller.getPapEngine().getOnapPDPGroups());
+ List<OnapPDPGroup> tempGroups = new ArrayList<>();
+ if (!groups.isEmpty()) {
+ Iterator<OnapPDPGroup> pdpGroup = groups.iterator();
+ while (pdpGroup.hasNext()) {
+ OnapPDPGroup group = pdpGroup.next();
+ Set<PDPPolicy> 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);
+ }
+ }
+ }
+
+ private void setPapEngine(HttpServletRequest request) {
try {
//
// Set the URL for the RESTful PAP Engine
//
- PolicyController.setPapEngine((PAPPolicyEngine) new RESTfulPAPEngine(myRequestURL));
- }catch(Exception e){
- policyLogger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR+"Exception Occured while loading PAP",e);
+ PolicyController.setPapEngine(new RESTfulPAPEngine(request.getRequestURL().toString()));
+ } catch (Exception e) {
+ policyLogger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Exception Occured while loading PAP", e);
+ }
+ }
+
+ /**
+ * getPDPGroupEntityData.
+ *
+ * @param request HttpServletRequest
+ * @param response HttpServletResponse
+ */
+ @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 {
+ refreshGroups(request);
+ response.getWriter().write(new JSONObject(new JsonMessage(
+ new ObjectMapper().writeValueAsString(groups))).toString());
+ } catch (Exception e) {
+ policyLogger.error(
+ XACMLErrorConstants.ERROR_DATA_ISSUE + "Error Occured while retrieving the PDP Group data" + e);
+ }
+ }
+
+ /**
+ * savePDPGroup.
+ *
+ * @param request HttpServletRequest
+ * @param response HttpServletResponse
+ */
+ @RequestMapping(
+ value = {"/pdp_Group/save_pdp_group"},
+ method = {org.springframework.web.bind.annotation.RequestMethod.POST})
+ public void savePDPGroup(HttpServletRequest request, HttpServletResponse response) {
+ try {
+ response.setCharacterEncoding(PolicyUtils.CHARACTER_ENCODING);
+ request.setCharacterEncoding(PolicyUtils.CHARACTER_ENCODING);
+ //
+ //
+ //
+ 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());
+
+ String userId = UserUtils.getUserSession(request).getOrgUserId();
+ policyLogger.info(
+ "*******************Logging UserID for Save PDP Group Function*******************************");
+ policyLogger.info("UserId: " + userId + "PDP Group Data: " + root.get("pdpGroupData").toString());
+ policyLogger.info(
+ "********************************************************************************************");
+
+ 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.setContentType(PolicyUtils.APPLICATION_JSON);
+
+ refreshGroups(request);
+ response.getWriter().write(new JSONObject(new JsonMessage(mapper.writeValueAsString(groups))).toString());
+ } catch (Exception e) {
+ policyLogger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Error Occured while Saving the PDP Group" + e);
+ try {
+ response.getWriter().write(e.getMessage());
+ } catch (Exception e1) {
+ policyLogger
+ .error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Error Occured while Saving the PDP Group" + e1);
+ }
+ }
+ }
+
+ /**
+ * removePDPGroup.
+ *
+ * @param request HttpServletRequest
+ * @param response HttpServletResponse
+ */
+ @RequestMapping(
+ value = {"/pdp_Group/remove_pdp_group"},
+ method = {org.springframework.web.bind.annotation.RequestMethod.POST})
+ public void removePDPGroup(HttpServletRequest request, HttpServletResponse response) {
+ try {
+ response.setCharacterEncoding(PolicyUtils.CHARACTER_ENCODING);
+ request.setCharacterEncoding(PolicyUtils.CHARACTER_ENCODING);
+ //
+ //
+ //
+ 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 userId = UserUtils.getUserSession(request).getOrgUserId();
+ policyLogger.info(
+ "*********************Logging UserID for Remove PDP Group Function*******************************");
+ policyLogger.info("UserId: " + userId + "PDP Group Data: " + root.get("pdpGroupData").toString());
+ policyLogger.info(
+ "************************************************************************************************");
+
+ StdPDPGroup pdpGroupData = mapper.readValue(root.get("pdpGroupData").toString(), StdPDPGroup.class);
+ if ("Default".equals(pdpGroupData.getName())) {
+ throw new UnsupportedOperationException("You can't remove the Default Group.");
+ } else {
+ this.container.removeGroup(pdpGroupData, null);
+ }
+
+ response.setContentType(PolicyUtils.APPLICATION_JSON);
+ refreshGroups(request);
+ response.getWriter().write(new JSONObject(new JsonMessage(mapper.writeValueAsString(groups))).toString());
+ } catch (Exception e) {
+ policyLogger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Error Occured while Removing the PDP Group" + e);
+ try {
+ response.getWriter().write(e.getMessage());
+ } catch (Exception e1) {
+ policyLogger.error("Exception Occured" + e1);
+ }
+ }
+ }
+
+ /**
+ * savePDPToGroup.
+ *
+ * @param request HttpServletRequest
+ * @param response HttpServletResponse
+ */
+ @RequestMapping(
+ value = {"/pdp_Group/save_pdpTogroup"},
+ method = {org.springframework.web.bind.annotation.RequestMethod.POST})
+ public void savePDPToGroup(HttpServletRequest request, HttpServletResponse response) {
+ try {
+ response.setCharacterEncoding(PolicyUtils.CHARACTER_ENCODING);
+ request.setCharacterEncoding(PolicyUtils.CHARACTER_ENCODING);
+ //
+ //
+ //
+ 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 = mapper.readValue(root.get("pdpInGroup").toString(), PdpData.class);
+ StdPDPGroup activeGroupData = mapper.readValue(root.get("activePDP").toString(), StdPDPGroup.class);
+
+ String userId = UserUtils.getUserSession(request).getOrgUserId();
+ policyLogger.info(
+ "*************Logging UserID while Saving pdp in PDP Group***********************************");
+ policyLogger.info("UserId: " + userId + "PDP Group Data: " + root.get("pdpInGroup").toString()
+ + "Active Group Data: " + root.get("activePDP").toString());
+ policyLogger.info(
+ "**********************************************************************************************");
+
+ 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.setContentType(PolicyUtils.APPLICATION_JSON);
+ refreshGroups(request);
+ response.getWriter().write(new JSONObject(new JsonMessage(mapper.writeValueAsString(groups))).toString());
+ } catch (Exception e) {
+ policyLogger
+ .error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Error Occured while Creating Pdp in PDP Group" + e);
+ try {
+ response.getWriter().write(e.getMessage());
+ } catch (Exception e1) {
+ policyLogger.error("Exception Occured" + e1);
+ }
}
}
- @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());
-
- String userId = UserUtils.getUserSession(request).getOrgUserId();
- policyLogger.info("****************************************Logging UserID for Save PDP Group Function*****************************************");
- policyLogger.info("UserId: " + userId + "PDP Group Data: "+ root.get("pdpGroupData").toString());
- policyLogger.info("***************************************************************************************************************************");
-
- 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());
-
- String userId = UserUtils.getUserSession(request).getOrgUserId();
- policyLogger.info("****************************************Logging UserID for Remove PDP Group Function*****************************************");
- policyLogger.info("UserId: " + userId + "PDP Group Data: "+ root.get("pdpGroupData").toString());
- policyLogger.info("*****************************************************************************************************************************");
-
- StdPDPGroup pdpGroupData = mapper.readValue(root.get("pdpGroupData").toString(), StdPDPGroup.class);
- if("Default".equals(pdpGroupData.getName())) {
- 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 = mapper.readValue(root.get("pdpInGroup").toString(), PdpData.class);
- StdPDPGroup activeGroupData = mapper.readValue(root.get("activePDP").toString(), StdPDPGroup.class);
-
- String userId = UserUtils.getUserSession(request).getOrgUserId();
- policyLogger.info("****************************************Logging UserID while Saving pdp in PDP Group*****************************************");
- policyLogger.info("UserId: " + userId + "PDP Group Data: "+ root.get("pdpInGroup").toString() + "Active Group Data: "+ root.get("activePDP").toString());
- policyLogger.info("*******************************************************************************************************************************");
-
- 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);
-
- String userId = UserUtils.getUserSession(request).getOrgUserId();
- policyLogger.info("****************************************Logging UserID while Removing pdp from PDP Group*****************************************");
- policyLogger.info("UserId: " + userId + "Delete PDP Group Data: "+ root.get("data").toString() + "Active Group Data: "+ root.get("activePDP").toString());
- policyLogger.info("***********************************************************************************************************************************");
-
- this.container.removePDP(deletePdp, activeGroupData);
- 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 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<OnapPDPGroup> getGroupsData() {
- return groupsData;
- }
-
- public void setGroupsData(Set<OnapPDPGroup> groupsData) {
- this.groupsData = groupsData;
- }
+ /**
+ * removePDPFromGroup.
+ *
+ * @param request HttpServletRequest
+ * @param response HttpServletResponse
+ */
+ @RequestMapping(
+ value = {"/pdp_Group/remove_pdpFromGroup"},
+ method = {org.springframework.web.bind.annotation.RequestMethod.POST})
+ public void removePDPFromGroup(HttpServletRequest request, HttpServletResponse response) {
+ try {
+ response.setCharacterEncoding(PolicyUtils.CHARACTER_ENCODING);
+ request.setCharacterEncoding(PolicyUtils.CHARACTER_ENCODING);
+ //
+ //
+ //
+ 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 userId = UserUtils.getUserSession(request).getOrgUserId();
+ policyLogger.info(
+ "********************Logging UserID while Removing pdp from PDP Group**************************");
+ policyLogger.info("UserId: " + userId + "Delete PDP Group Data: " + root.get("data").toString()
+ + "Active Group Data: " + root.get("activePDP").toString());
+ policyLogger.info(
+ "************************************************************************************************");
+
+ 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.setContentType(PolicyUtils.APPLICATION_JSON);
+
+ refreshGroups(request);
+ response.getWriter().write(new JSONObject(new JsonMessage(mapper.writeValueAsString(groups))).toString());
+ } catch (Exception e) {
+ policyLogger.error(
+ XACMLErrorConstants.ERROR_DATA_ISSUE + "Error Occured while Removing Pdp from PDP Group" + e);
+ try {
+ response.getWriter().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<OnapPDPGroup> getGroupsData() {
+ return groupsData;
+ }
+
+ public void setGroupsData(Set<OnapPDPGroup> 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;
- }
-
+@Getter
+@Setter
+class PdpData {
+ String id;
+ int jmxPort;
+ String name;
+ String 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
index 700aa3a57..dbf744829 100644
--- 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
@@ -24,6 +24,7 @@ package org.onap.policy.controller;
import com.att.research.xacml.util.XACMLProperties;
import com.fasterxml.jackson.databind.ObjectMapper;
+
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
@@ -37,12 +38,15 @@ import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.Set;
+
import javax.annotation.PostConstruct;
import javax.script.SimpleBindings;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
+
import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicySetType;
import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType;
+
import org.json.JSONObject;
import org.onap.policy.admin.PolicyNotificationMail;
import org.onap.policy.admin.RESTfulPAPEngine;
@@ -52,7 +56,7 @@ import org.onap.policy.common.logging.flexlogger.FlexLogger;
import org.onap.policy.common.logging.flexlogger.Logger;
import org.onap.policy.model.PDPGroupContainer;
import org.onap.policy.model.Roles;
-import org.onap.policy.rest.XACMLRestProperties;
+import org.onap.policy.rest.XacmlRestProperties;
import org.onap.policy.rest.dao.CommonClassDao;
import org.onap.policy.rest.jpa.Datatype;
import org.onap.policy.rest.jpa.FunctionDefinition;
@@ -60,6 +64,7 @@ import org.onap.policy.rest.jpa.PolicyEntity;
import org.onap.policy.rest.jpa.PolicyVersion;
import org.onap.policy.rest.jpa.UserInfo;
import org.onap.policy.utils.PeCryptoUtils;
+import org.onap.policy.utils.PolicyUtils;
import org.onap.policy.utils.UserUtils.Pair;
import org.onap.policy.xacml.api.XACMLErrorConstants;
import org.onap.policy.xacml.api.pap.PAPPolicyEngine;
@@ -99,7 +104,7 @@ public class PolicyController extends RestrictedBaseController {
}
public static String getDomain() {
- return XACMLProperties.getProperty(XACMLRestProperties.PROP_ADMIN_DOMAIN, "urn");
+ return XACMLProperties.getProperty(XacmlRestProperties.PROP_ADMIN_DOMAIN, "urn");
}
private static final Object mapAccess = new Object();
@@ -108,8 +113,6 @@ public class PolicyController extends RestrictedBaseController {
// Constant variables used across Policy-sdk
private static final String policyData = "policyData";
- private static final String characterEncoding = "UTF-8";
- private static final String contentType = "application/json";
private static final String file = "file";
private static final String SUPERADMIN = "super-admin";
private static final String POLICYGUEST = "Policy Guest";
@@ -160,8 +163,8 @@ public class PolicyController extends RestrictedBaseController {
return jUnit;
}
- public static void setjUnit(boolean jUnit) {
- PolicyController.jUnit = jUnit;
+ public static void setjUnit(boolean isJunit) {
+ PolicyController.jUnit = isJunit;
}
@Autowired
@@ -183,9 +186,8 @@ public class PolicyController extends RestrictedBaseController {
try {
String fileName;
if (jUnit) {
- fileName = new File(".").getCanonicalPath() + File.separator + "src"
- + File.separator + "test" + File.separator + "resources" + File.separator
- + "JSONConfig.json";
+ fileName = new File(".").getCanonicalPath() + File.separator + "src" + File.separator + "test"
+ + File.separator + "resources" + File.separator + "JSONConfig.json";
} else {
fileName = "xacml.admin.properties";
}
@@ -236,19 +238,17 @@ public class PolicyController extends RestrictedBaseController {
// Get the Property Values for Dashboard tab Limit
try {
setLogTableLimit(prop.getProperty("xacml.onap.dashboard.logTableLimit"));
- setSystemAlertTableLimit(
- prop.getProperty("xacml.onap.dashboard.systemAlertTableLimit"));
+ setSystemAlertTableLimit(prop.getProperty("xacml.onap.dashboard.systemAlertTableLimit"));
} catch (Exception e) {
- policyLogger.error(XACMLErrorConstants.ERROR_DATA_ISSUE
- + "Dashboard tab Property fields are missing" + 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);
+ + "Exception Occured while reading the Smtp properties from xacml.admin.properties file" + ex);
}
// Initialize the FunctionDefinition table at Server Start up
@@ -298,8 +298,7 @@ public class PolicyController extends RestrictedBaseController {
FunctionDefinition value = (FunctionDefinition) functiondefinitions.get(i);
mapID2Function.put(value.getXacmlid(), value);
if (!mapDatatype2Function.containsKey(value.getDatatypeBean())) {
- mapDatatype2Function.put(value.getDatatypeBean(),
- new ArrayList<FunctionDefinition>());
+ mapDatatype2Function.put(value.getDatatypeBean(), new ArrayList<FunctionDefinition>());
}
mapDatatype2Function.get(value.getDatatypeBean()).add(value);
}
@@ -311,22 +310,20 @@ public class PolicyController extends RestrictedBaseController {
* @param request HttpServletRequest.
* @param response HttpServletResponse.
*/
- @RequestMapping(value = {"/get_FunctionDefinitionDataByName"},
+ @RequestMapping(
+ value = {"/get_FunctionDefinitionDataByName"},
method = {org.springframework.web.bind.annotation.RequestMethod.GET},
produces = MediaType.APPLICATION_JSON_VALUE)
- public void getFunctionDefinitionData(HttpServletRequest request,
- HttpServletResponse response) {
+ public void getFunctionDefinitionData(HttpServletRequest request, HttpServletResponse response) {
try {
Map<String, Object> model = new HashMap<>();
ObjectMapper mapper = new ObjectMapper();
- model.put("functionDefinitionDatas", mapper.writeValueAsString(
- commonClassDao.getDataByColumn(FunctionDefinition.class, "shortname")));
- JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
- JSONObject j = new JSONObject(msg);
- response.getWriter().write(j.toString());
+ model.put("functionDefinitionDatas",
+ mapper.writeValueAsString(commonClassDao.getDataByColumn(FunctionDefinition.class, "shortname")));
+ response.getWriter().write(new JSONObject(new JsonMessage(mapper.writeValueAsString(model))).toString());
} catch (Exception e) {
- policyLogger.error(XACMLErrorConstants.ERROR_DATA_ISSUE
- + "Error while retriving the Function Definition data" + e);
+ policyLogger.error(
+ XACMLErrorConstants.ERROR_DATA_ISSUE + "Error while retriving the Function Definition data" + e);
}
}
@@ -368,7 +365,8 @@ public class PolicyController extends RestrictedBaseController {
* @param request HttpServletRequest.
* @param response HttpServletResponse.
*/
- @RequestMapping(value = {"/get_UserRolesData"},
+ @RequestMapping(
+ value = {"/get_UserRolesData"},
method = {org.springframework.web.bind.annotation.RequestMethod.GET},
produces = MediaType.APPLICATION_JSON_VALUE)
public void getUserRolesEntityData(HttpServletRequest request, HttpServletResponse response) {
@@ -377,9 +375,7 @@ public class PolicyController extends RestrictedBaseController {
Map<String, Object> model = new HashMap<>();
ObjectMapper mapper = new ObjectMapper();
model.put("userRolesDatas", mapper.writeValueAsString(getRolesOfUser(userId)));
- JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
- JSONObject j = new JSONObject(msg);
- response.getWriter().write(j.toString());
+ response.getWriter().write(new JSONObject(new JsonMessage(mapper.writeValueAsString(model))).toString());
} catch (Exception e) {
policyLogger.error("Exception Occured" + e);
}
@@ -402,8 +398,7 @@ public class PolicyController extends RestrictedBaseController {
setPapEngine(new RESTfulPAPEngine(myRequestUrl));
new PDPGroupContainer(new RESTfulPAPEngine(myRequestUrl));
} catch (Exception e) {
- policyLogger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR
- + "Exception Occured while loading PAP" + e);
+ policyLogger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Exception Occured while loading PAP" + e);
}
Map<String, Object> model = new HashMap<>();
return new ModelAndView("policy_Editor", "model", model);
@@ -438,9 +433,8 @@ public class PolicyController extends RestrictedBaseController {
savePolicyRoles(name, filteredRole, userId);
} else {
userRoles = getRoles(userId);
- Pair<Set<String>, List<String>> pair =
- org.onap.policy.utils.UserUtils.checkRoleAndScope(userRoles);
- roles = pair.u;
+ Pair<Set<String>, List<String>> pair = org.onap.policy.utils.UserUtils.checkRoleAndScope(userRoles);
+ roles = pair.second;
if (!roles.contains(filteredRole)) {
savePolicyRoles(name, filteredRole, userId);
}
@@ -511,8 +505,7 @@ public class PolicyController extends RestrictedBaseController {
roles.clear();
roles.add(SUPERADMIN);
}
- if (!roles.contains(SUPERADMIN)
- || (POLICYGUEST.equalsIgnoreCase(role) && !superCheck)) {
+ if (!roles.contains(SUPERADMIN) || (POLICYGUEST.equalsIgnoreCase(role) && !superCheck)) {
if ("Policy Admin".equalsIgnoreCase(role.trim())) {
roles.add("admin");
} else if ("Policy Editor".equalsIgnoreCase(role.trim())) {
@@ -576,8 +569,7 @@ public class PolicyController extends RestrictedBaseController {
}
public PolicyVersion getPolicyEntityFromPolicyVersion(String query) {
- return (PolicyVersion) commonClassDao.getEntityItem(PolicyVersion.class, "policyName",
- query);
+ return (PolicyVersion) commonClassDao.getEntityItem(PolicyVersion.class, "policyName", query);
}
public List<Object> getDataByQuery(String query, SimpleBindings params) {
@@ -604,11 +596,11 @@ public class PolicyController extends RestrictedBaseController {
/**
* Switch Version Policy Content.
*
- * @param pName which is used to find associated versions.
+ * @param thePolicyName which is used to find associated versions.
* @return list of available versions based on policy name.
*/
- public JSONObject switchVersionPolicyContent(String pName) {
- String policyName = pName;
+ public JSONObject switchVersionPolicyContent(String thePolicyName) {
+ String policyName = thePolicyName;
String dbCheckName = policyName.replace("/", ".");
if (dbCheckName.contains("Config_")) {
dbCheckName = dbCheckName.replace(".Config_", ":Config_");
@@ -620,25 +612,23 @@ public class PolicyController extends RestrictedBaseController {
dbCheckName = dbCheckName.replace(".Decision_", ":Decision_");
}
String[] splitDbCheckName = dbCheckName.split(":");
- String query =
- "FROM PolicyEntity where policyName like :splitDBCheckName1 and scope = :splitDBCheckName0";
+ String query = "FROM PolicyEntity where policyName like :splitDBCheckName1 and scope = :splitDBCheckName0";
SimpleBindings params = new SimpleBindings();
params.put("splitDBCheckName1", splitDbCheckName[1] + "%");
params.put("splitDBCheckName0", splitDbCheckName[0]);
- List<Object> policyEntity = commonClassDao.getDataByQuery(query, params);
List<String> av = new ArrayList<>();
- for (Object entity : policyEntity) {
- PolicyEntity pEntity = (PolicyEntity) entity;
- String removeExtension = pEntity.getPolicyName().replace(".xml", "");
+ for (Object entity : commonClassDao.getDataByQuery(query, params)) {
+ PolicyEntity policyEntity = (PolicyEntity) entity;
+ String removeExtension = policyEntity.getPolicyName().replace(".xml", "");
String version = removeExtension.substring(removeExtension.lastIndexOf('.') + 1);
- String userName = getUserId(pEntity, "@ModifiedBy:");
- av.add(version + " | " + pEntity.getModifiedDate() + " | " + userName);
+ String userName = getUserId(policyEntity, "@ModifiedBy:");
+ av.add(version + " | " + policyEntity.getModifiedDate() + " | " + userName);
}
if (policyName.contains("/")) {
policyName = policyName.replace("/", File.separator);
}
- PolicyVersion entity = (PolicyVersion) commonClassDao.getEntityItem(PolicyVersion.class,
- "policyName", policyName);
+ PolicyVersion entity =
+ (PolicyVersion) commonClassDao.getEntityItem(PolicyVersion.class, "policyName", policyName);
JSONObject el = new JSONObject();
el.put("activeVersion", entity.getActiveVersion());
el.put("availableVersions", av);
@@ -646,13 +636,20 @@ public class PolicyController extends RestrictedBaseController {
return el;
}
+ /**
+ * getUserId.
+ *
+ * @param data PolicyEntity
+ * @param value String
+ * @return String
+ */
public String getUserId(PolicyEntity data, String value) {
String userId = "";
- String uValue = value;
+ String userValue = value; // Why?
String description = getDescription(data);
- if (description.contains(uValue)) {
- userId = description.substring(description.indexOf(uValue) + uValue.length(),
- description.lastIndexOf(uValue));
+ if (description.contains(userValue)) {
+ userId = description.substring(description.indexOf(userValue) + userValue.length(),
+ description.lastIndexOf(userValue));
}
UserInfo userInfo = (UserInfo) getEntityItem(UserInfo.class, "userLoginId", userId);
if (userInfo == null) {
@@ -661,35 +658,43 @@ public class PolicyController extends RestrictedBaseController {
return userInfo.getUserName();
}
+ /**
+ * getDescription.
+ *
+ * @param data PolicyEntity
+ * @return String
+ */
public String getDescription(PolicyEntity data) {
- InputStream stream =
- new ByteArrayInputStream(data.getPolicyData().getBytes(StandardCharsets.UTF_8));
+ InputStream stream = new ByteArrayInputStream(data.getPolicyData().getBytes(StandardCharsets.UTF_8));
Object policy = XACMLPolicyScanner.readPolicy(stream);
if (policy instanceof PolicySetType) {
return ((PolicySetType) policy).getDescription();
} else if (policy instanceof PolicyType) {
return ((PolicyType) policy).getDescription();
- } else {
- PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE
- + "Expecting a PolicySet/Policy/Rule object. Got: "
- + policy.getClass().getCanonicalName());
- return null;
}
+ PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + "Expecting a PolicySet/Policy/Rule object. Got: "
+ + policy.getClass().getCanonicalName());
+ return null;
}
+ /**
+ * getUserInfo.
+ *
+ * @param data PolicyEntity
+ * @param activePolicies list of active policies
+ * @return array of String
+ */
public String[] getUserInfo(PolicyEntity data, List<PolicyVersion> activePolicies) {
String policyName = data.getScope().replace(".", File.separator) + File.separator
+ data.getPolicyName().substring(0, data.getPolicyName().indexOf('.'));
- PolicyVersion polVersion = activePolicies.stream()
- .filter(a -> policyName.equals(a.getPolicyName())).findAny().orElse(null);
+ PolicyVersion polVersion =
+ activePolicies.stream().filter(a -> policyName.equals(a.getPolicyName())).findAny().orElse(null);
String[] result = new String[2];
UserInfo userCreate = null;
UserInfo userModify = null;
if (polVersion != null) {
- userCreate = (UserInfo) getEntityItem(UserInfo.class, "userLoginId",
- polVersion.getCreatedBy());
- userModify = (UserInfo) getEntityItem(UserInfo.class, "userLoginId",
- polVersion.getModifiedBy());
+ userCreate = (UserInfo) getEntityItem(UserInfo.class, "userLoginId", polVersion.getCreatedBy());
+ userModify = (UserInfo) getEntityItem(UserInfo.class, "userLoginId", polVersion.getModifiedBy());
}
result[0] = userCreate != null ? userCreate.getUserName() : SUPERADMIN;
@@ -726,8 +731,7 @@ public class PolicyController extends RestrictedBaseController {
return mapDatatype2Function;
}
- public static void setMapDatatype2Function(
- Map<Datatype, List<FunctionDefinition>> mapDatatype2Function) {
+ public static void setMapDatatype2Function(Map<Datatype, List<FunctionDefinition>> mapDatatype2Function) {
PolicyController.mapDatatype2Function = mapDatatype2Function;
}
@@ -940,11 +944,11 @@ public class PolicyController extends RestrictedBaseController {
}
public static String getCharacterencoding() {
- return characterEncoding;
+ return PolicyUtils.CHARACTER_ENCODING;
}
public static String getContenttype() {
- return contentType;
+ return PolicyUtils.APPLICATION_JSON;
}
public static String getFile() {
@@ -969,17 +973,4 @@ public class PolicyController extends RestrictedBaseController {
return fileSizeLimit;
}
- /**
- * Function to convert date.
- *
- * @param dateTTL input date value.
- * @return
- */
- public String convertDate(String dateTTL) {
- String formateDate = null;
- if (dateTTL.contains("-")) {
- formateDate = dateTTL.replace("-", "/");
- }
- return formateDate;
- }
}
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
index 6c7a0aff3..cf7e62b46 100644
--- 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
@@ -2,14 +2,14 @@
* ============LICENSE_START=======================================================
* ONAP Policy Engine
* ================================================================================
- * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2020 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -38,6 +38,7 @@ import java.util.Set;
import javax.script.SimpleBindings;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
+import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
@@ -52,7 +53,7 @@ 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.DCAEuuid;
+import org.onap.policy.rest.jpa.DcaeUuid;
import org.onap.policy.rest.jpa.GroupPolicyScopeList;
import org.onap.policy.rest.jpa.MicroServiceConfigName;
import org.onap.policy.rest.jpa.MicroServiceLocation;
@@ -61,10 +62,12 @@ 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.utils.UserUtils.Pair;
import org.onap.policy.xacml.api.XACMLErrorConstants;
import org.onap.portalsdk.core.controller.RestrictedBaseController;
import org.onap.portalsdk.core.web.support.UserUtils;
+import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@@ -90,7 +93,6 @@ public class PolicyExportAndImportController extends RestrictedBaseController {
private static final String ACTION = "Action_";
private static CommonClassDao commonClassDao;
-
private PolicyController policyController;
public PolicyController getPolicyController() {
@@ -113,14 +115,20 @@ public class PolicyExportAndImportController extends RestrictedBaseController {
// Empty constructor
}
+ @Autowired
+ private PolicyExportAndImportController(CommonClassDao commonClassDao) {
+ PolicyExportAndImportController.commonClassDao = commonClassDao;
+ }
+
/**
* This is for downloading existing policy.
- *
+ *
* @param request HttpServletRequest
* @param response HttpServletResponse
* @throws IOException error out
*/
- @RequestMapping(value = {"/policy_download/exportPolicy.htm"},
+ @RequestMapping(
+ value = {"/policy_download/exportPolicy.htm"},
method = {org.springframework.web.bind.annotation.RequestMethod.POST})
public void exportPolicy(HttpServletRequest request, HttpServletResponse response) throws IOException {
try (HSSFWorkbook workBook2 = new HSSFWorkbook()) {
@@ -134,9 +142,8 @@ public class PolicyExportAndImportController extends RestrictedBaseController {
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 scope = policyWithScope.substring(0, policyWithScope.lastIndexOf(File.separator))
+ .replace(File.separator, ".");
String policyNamel = policyWithScope.substring(policyWithScope.lastIndexOf(File.separator) + 1);
selectedPolicy.add(policyNamel + ":" + scope);
}
@@ -152,9 +159,8 @@ public class PolicyExportAndImportController extends RestrictedBaseController {
headingRow.createCell(6).setCellValue(BODYSIZE);
headingRow.createCell(7).setCellValue(configurationbody);
- List<Object> entityData =
- commonClassDao.getMultipleDataOnAddingConjunction(PolicyEntity.class, "policyName:scope",
- selectedPolicy);
+ List<Object> entityData = commonClassDao.getMultipleDataOnAddingConjunction(PolicyEntity.class,
+ "policyName:scope", selectedPolicy);
processEntityData(entityData, sheet, headingRow); //
String tmp = System.getProperty("catalina.base") + File.separator + "webapps" + File.separator + "temp";
String deleteCheckPath = tmp + File.separator + "PolicyExport.xls";
@@ -173,14 +179,14 @@ public class PolicyExportAndImportController extends RestrictedBaseController {
workBook2.write(fos);
fos.flush();
- response.setContentType("application / json");
- request.setCharacterEncoding("UTF-8");
+ response.setContentType(PolicyUtils.APPLICATION_JSON);
+ request.setCharacterEncoding(PolicyUtils.CHARACTER_ENCODING);
PrintWriter out = response.getWriter();
String successMap = file.substring(file.lastIndexOf("webapps") + 8);
String responseString = mapper.writeValueAsString(successMap);
- JSONObject j = new JSONObject("{data: " + responseString + "}");
- out.write(j.toString());
+ JSONObject json = new JSONObject("{data: " + responseString + "}");
+ out.write(json.toString());
} catch (Exception e) {
logger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Exception Occured while Exporting Policies" + e);
}
@@ -233,8 +239,8 @@ public class PolicyExportAndImportController extends RestrictedBaseController {
row.createCell(7).setCellValue(body.substring(index, Math.min(index + 30000, body.length())));
} else {
headingRow.createCell(7 + arraySize).setCellValue(configurationbody + arraySize);
- row.createCell(7 + arraySize).setCellValue(
- body.substring(index, Math.min(index + 30000, body.length())));
+ row.createCell(7 + arraySize)
+ .setCellValue(body.substring(index, Math.min(index + 30000, body.length())));
}
index += 30000;
arraySize += 1;
@@ -247,17 +253,15 @@ public class PolicyExportAndImportController extends RestrictedBaseController {
return row;
}
-
-
/**
* This is to upload a policy and save it to database.
- *
+ *
* @param file String
* @param request HttpServletRequest
* @return JSONObject
* @throws IOException error out
*/
- public JSONObject importRepositoryFile(String file, HttpServletRequest request) throws IOException {
+ public String importRepositoryFile(String file, HttpServletRequest request) throws IOException {
boolean configExists = false;
boolean actionExists = false;
String configName = null;
@@ -269,14 +273,14 @@ public class PolicyExportAndImportController extends RestrictedBaseController {
// Check if the Role and Scope Size are Null get the values from db.
List<Object> userRoles = controller.getRoles(userId);
Pair<Set<String>, List<String>> pair = org.onap.policy.utils.UserUtils.checkRoleAndScope(userRoles);
- List<String> roles = pair.u;
- Set<String> scopes = pair.t;
+ List<String> roles = pair.second;
+ Set<String> scopes = pair.first;
try (FileInputStream excelFile = new FileInputStream(new File(file));
HSSFWorkbook workbook = new HSSFWorkbook(excelFile)) {
Sheet datatypeSheet = workbook.getSheetAt(0);
Iterator<Row> rowIterator = datatypeSheet.iterator();
-
+ String sendResult = null;
while (rowIterator.hasNext()) {
finalColumn = false;
PolicyEntity policyEntity = new PolicyEntity();
@@ -291,6 +295,7 @@ public class PolicyExportAndImportController extends RestrictedBaseController {
int bodySize = 0;
int setBodySize = 0;
boolean configurationBodySet = false;
+ boolean errorFlag = false;
while (cellIterator.hasNext()) {
Cell cell = cellIterator.next();
if (policyName.equalsIgnoreCase(getCellHeaderName(cell))) {
@@ -314,13 +319,18 @@ public class PolicyExportAndImportController extends RestrictedBaseController {
configurationDataEntity =
populateConfigurationDataEntity(policyEntity, configurationDataEntity, cell);
actionBodyEntity = populateActionBodyObject(policyEntity, actionBodyEntity, cell);
- JSONObject response = validatRequiredValue(policyEntity, body, finalColumn, configurationBodySet);
- if (response != null) {
- return response;
+ String response = null;
+ response = validatRequiredValue(policyEntity, body, finalColumn, configurationBodySet);
+ if (!StringUtils.isBlank(response)) {
+ sendResult = sendResult + "\n" + response;
+ errorFlag = true;
+ }
+ if (!StringUtils.isBlank(response) && !rowIterator.hasNext()) {
+ return sendResult;
}
savePolicyEntiies(finalColumn, configurationBodySet, configurationDataEntity, policyEntity,
controller, roles, userInfo, scopes, configName, userId, configExists, actionExists,
- actionBodyEntity, body);
+ actionBodyEntity, body, errorFlag);
}
}
@@ -331,9 +341,8 @@ public class PolicyExportAndImportController extends RestrictedBaseController {
}
private void writeConfigurationFile(ConfigurationDataEntity configurationDataEntity) {
- try (FileWriter fw =
- new FileWriter(PolicyController.getConfigHome() + File.separator
- + configurationDataEntity.getConfigurationName())) {
+ try (FileWriter fw = new FileWriter(
+ PolicyController.getConfigHome() + File.separator + configurationDataEntity.getConfigurationName())) {
BufferedWriter bw = new BufferedWriter(fw);
bw.write(configurationDataEntity.getConfigBody());
bw.close();
@@ -343,8 +352,8 @@ public class PolicyExportAndImportController extends RestrictedBaseController {
}
private void writeActionBodyFile(ActionBodyEntity actionBodyEntity) {
- try (FileWriter fw =
- new FileWriter(PolicyController.getActionHome() + File.separator + actionBodyEntity.getActionBodyName())) {
+ try (FileWriter fw = new FileWriter(
+ PolicyController.getActionHome() + File.separator + actionBodyEntity.getActionBodyName())) {
BufferedWriter bw = new BufferedWriter(fw);
bw.write(actionBodyEntity.getActionBody());
bw.close();
@@ -360,49 +369,46 @@ public class PolicyExportAndImportController extends RestrictedBaseController {
/**
* This is to validate all matching required fields.
- *
+ *
* @param policyName String
* @param jsonString String
* @return String
*/
public String validatMatchRequiredFields(String policyName, String jsonString) {
-
+ String errorMsg = "";
try {
JSONObject jsonObject = new JSONObject(jsonString);
- String configName = jsonObject.getString("configName");
- String uuid = jsonObject.getString("uuid");
- String erorMsg = validConfigName(configName);
- if (erorMsg != null) {
- return erorMsg;
+ String confErorMsg = validConfigName(jsonObject.getString("configName"));
+ if (!confErorMsg.isEmpty()) {
+ errorMsg = errorMsg + "\n POLICY :" + policyName + " at " + confErorMsg;
}
- erorMsg = validUuid(uuid);
- if (erorMsg != null) {
- return erorMsg;
+ String uuidErorMsg = validUuid(jsonObject.getString("uuid"));
+ if (!uuidErorMsg.isEmpty()) {
+ errorMsg = errorMsg + "\n POLICY :" + policyName + " at " + uuidErorMsg;
}
- String location = jsonObject.getString("location");
- erorMsg = validLocation(location);
- if (erorMsg != null) {
- return erorMsg;
+ String locErorMsg = validLocation(jsonObject.getString("location"));
+ if (!locErorMsg.isEmpty()) {
+ errorMsg = errorMsg + "\n POLICY :" + policyName + " at " + locErorMsg;
}
- String policyScope = jsonObject.getString("policyScope");
- erorMsg = validPolicyScope(policyScope);
- if (erorMsg != null) {
- return erorMsg;
+ String pScopeErorMsg = validPolicyScope(jsonObject.getString("policyScope"));
+ if (!pScopeErorMsg.isEmpty()) {
+ errorMsg = errorMsg + "\n POLICY :" + policyName + " at " + pScopeErorMsg;
}
String msVersion = jsonObject.getString("version");
String msService = jsonObject.getString("service");
if (!isAttributeObjectFound(msService, msVersion)) {
- return POLICY + policyName + " MS Service: " + msService + " and MS Version: " + msVersion + NOTVALID;
+ errorMsg = errorMsg + "\n POLICY :" + policyName + " at MS Service: " + msService + " and MS Version: "
+ + msVersion + NOTVALID;
}
} catch (Exception e) {
logger.error("Exception Occured While validating required fields", e);
}
- return null;
+ return errorMsg;
}
- private JSONObject validatRequiredValue(PolicyEntity policyEntity, StringBuilder body, boolean finalColumn,
+ private String validatRequiredValue(PolicyEntity policyEntity, StringBuilder body, boolean finalColumn,
boolean configurationBodySet) {
if (finalColumn && configurationBodySet && (policyEntity.getPolicyName().contains(CONFIG_MS))) {
String errorMsg = validatMatchRequiredFields(policyEntity.getPolicyName(), body.toString());
@@ -410,7 +416,7 @@ public class PolicyExportAndImportController extends RestrictedBaseController {
logger.error("errorMsg => " + errorMsg);
JSONObject response = new JSONObject();
response.append("error", errorMsg);
- return response;
+ return errorMsg;
}
}
return null;
@@ -433,7 +439,7 @@ public class PolicyExportAndImportController extends RestrictedBaseController {
private String validUuid(String uuid) {
String message = null;
if (uuid != null) {
- List<String> uuids = commonClassDao.getDataByColumn(DCAEuuid.class, "name");
+ List<String> uuids = commonClassDao.getDataByColumn(DcaeUuid.class, "name");
if (uuids != null && !(uuids.stream().filter(o -> o.equals(uuid)).findFirst().isPresent())) {
message = POLICY + policyName + " uuid: " + uuid + NOTVALID;
}
@@ -565,6 +571,7 @@ public class PolicyExportAndImportController extends RestrictedBaseController {
return false;
}
+ @SuppressWarnings("rawtypes")
private boolean isContinue(List<String> roles, String scope, UserInfo userInfo, Set scopes) {
if (roles.contains(admin) || roles.contains(editor)) {
if (scopes.isEmpty()) {
@@ -605,14 +612,12 @@ public class PolicyExportAndImportController extends RestrictedBaseController {
private void savePolicyEntity(PolicyEntity policyEntity, String configName, String userId) {
if (configName != null) {
if (configName.contains(config) || configName.contains(DECISION_MS)) {
- ConfigurationDataEntity configuration =
- (ConfigurationDataEntity) commonClassDao.getEntityItem(ConfigurationDataEntity.class,
- configurationName, configName);
+ ConfigurationDataEntity configuration = (ConfigurationDataEntity) commonClassDao
+ .getEntityItem(ConfigurationDataEntity.class, configurationName, configName);
policyEntity.setConfigurationData(configuration);
} else {
- ActionBodyEntity actionBody =
- (ActionBodyEntity) commonClassDao.getEntityItem(ActionBodyEntity.class, "actionBodyName",
- configName);
+ ActionBodyEntity actionBody = (ActionBodyEntity) commonClassDao.getEntityItem(ActionBodyEntity.class,
+ "actionBodyName", configName);
policyEntity.setActionBodyEntity(actionBody);
}
}
@@ -639,8 +644,9 @@ public class PolicyExportAndImportController extends RestrictedBaseController {
private int getSetBodySize(PolicyEntity policyEntity, Cell cell, int setBodySize) {
int setBodySizel = setBodySize;
if (configurationbody.equalsIgnoreCase(getCellHeaderName(cell))
- && ((policyEntity.getPolicyName().contains(config) || policyEntity.getPolicyName()
- .contains(DECISION_MS)) && (policyEntity.getPolicyName().contains("Config_BRMS_Param_")))) {
+ && ((policyEntity.getPolicyName().contains(config)
+ || policyEntity.getPolicyName().contains(DECISION_MS))
+ && (policyEntity.getPolicyName().contains("Config_BRMS_Param_")))) {
setBodySizel += 1;
}
return setBodySizel;
@@ -664,29 +670,28 @@ public class PolicyExportAndImportController extends RestrictedBaseController {
boolean configurationBodySet) {
boolean configurationBodySetl = configurationBodySet;
if (configurationbody.equalsIgnoreCase(getCellHeaderName(cell))
- && (policyEntity.getPolicyName().contains(config) || policyEntity.getPolicyName().contains(DECISION_MS))
- && (setBodySize == bodySize)) {
+ && (policyEntity.getPolicyName().contains(config) || policyEntity.getPolicyName().contains(DECISION_MS))
+ && (setBodySize == bodySize)) {
configurationBodySetl = true;
}
if (configurationbody.equalsIgnoreCase(getCellHeaderName(cell))
- && (policyEntity.getPolicyName().contains(config) || policyEntity.getPolicyName().contains(DECISION_MS))
- && (setBodySize == 0)) {
+ && (policyEntity.getPolicyName().contains(config) || policyEntity.getPolicyName().contains(DECISION_MS))
+ && (setBodySize == 0)) {
configurationBodySetl = true;
}
return configurationBodySetl;
}
-
private boolean isConfigExists(PolicyEntity policyEntity, Cell cell, boolean configExists) {
boolean configExistsl = configExists;
if (configurationbody.equalsIgnoreCase(getCellHeaderName(cell))
- && (policyEntity.getPolicyName().contains(config) || policyEntity.getPolicyName().contains(DECISION_MS))) {
+ && (policyEntity.getPolicyName().contains(config)
+ || policyEntity.getPolicyName().contains(DECISION_MS))) {
configExistsl = true;
}
return configExistsl;
}
-
private boolean isActionExists(PolicyEntity policyEntity, Cell cell, boolean actionExists) {
boolean actionExistsl = actionExists;
if (configurationbody.equalsIgnoreCase(getCellHeaderName(cell))
@@ -706,17 +711,18 @@ public class PolicyExportAndImportController extends RestrictedBaseController {
private StringBuilder addCellValue(PolicyEntity policyEntity, Cell cell, StringBuilder body) {
if (configurationbody.equalsIgnoreCase(getCellHeaderName(cell))
- && (policyEntity.getPolicyName().contains(config) || policyEntity.getPolicyName().contains(DECISION_MS))) {
+ && (policyEntity.getPolicyName().contains(config)
+ || policyEntity.getPolicyName().contains(DECISION_MS))) {
body.append(cell.getStringCellValue());
}
return body;
}
- private ActionBodyEntity setActionBodyObject(PolicyEntity policyEntity, ActionBodyEntity actionBodyEntity,
+ private ActionBodyEntity setActionBodyObject(PolicyEntity policyEntity, ActionBodyEntity actionBodyEntity,
Cell cell) {
if (configurationbody.equalsIgnoreCase(getCellHeaderName(cell))
- && (policyEntity.getPolicyName().contains(ACTION))) {
+ && (policyEntity.getPolicyName().contains(ACTION))) {
actionBodyEntity.setActionBody(cell.getStringCellValue());
}
return actionBodyEntity;
@@ -734,7 +740,8 @@ public class PolicyExportAndImportController extends RestrictedBaseController {
private ConfigurationDataEntity populateConfigurationDataEntity(PolicyEntity policyEntity,
ConfigurationDataEntity configurationDataEntity, Cell cell) {
if (configurationName.equalsIgnoreCase(getCellHeaderName(cell))
- && (policyEntity.getPolicyName().contains(config) || policyEntity.getPolicyName().contains(DECISION_MS))) {
+ && (policyEntity.getPolicyName().contains(config)
+ || policyEntity.getPolicyName().contains(DECISION_MS))) {
configurationDataEntity.setConfigurationName(cell.getStringCellValue());
}
return configurationDataEntity;
@@ -751,9 +758,9 @@ public class PolicyExportAndImportController extends RestrictedBaseController {
private void savePolicyEntiies(boolean finalColumn, boolean configurationBodySet,
ConfigurationDataEntity configurationDataEntity, PolicyEntity policyEntity, PolicyController controller,
List<String> roles, UserInfo userInfo, Set<String> scopes, String configName, String userId,
- boolean configExists, boolean actionExists, ActionBodyEntity actionBodyEntity, StringBuilder body) {
+ boolean configExists, boolean actionExists, ActionBodyEntity actionBodyEntity, StringBuilder body, boolean errorFlagSent) {
- if (finalColumn && configurationBodySet) {
+ if (finalColumn && configurationBodySet && !errorFlagSent) {
configurationDataEntity.setConfigBody(body.toString());
String scope = policyEntity.getScope().replace(".", File.separator);
String query = "FROM PolicyEntity where policyName = :policyName and scope = :policyScope";
@@ -771,7 +778,7 @@ public class PolicyExportAndImportController extends RestrictedBaseController {
saveVersion(policyEntity, scope, userId); //
// Notify Other paps regarding Export Policy.
PolicyRestController restController = new PolicyRestController();
- restController.notifyOtherPAPSToUpdateConfigurations("exportPolicy", configName, null);
+ restController.notifyOtherPapsToUpdateConfigurations("exportPolicy", configName, null);
}
}
}
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
index 707bbac09..ebd24dce3 100644
--- 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
@@ -2,14 +2,14 @@
* ============LICENSE_START=======================================================
* ONAP Policy Engine
* ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017, 2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -20,13 +20,16 @@
package org.onap.policy.controller;
-
/*
- *
+ *
* */
+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;
+
import java.io.File;
import java.io.IOException;
-import java.io.PrintWriter;
import java.util.List;
import javax.script.SimpleBindings;
@@ -46,87 +49,87 @@ 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 {
private static Logger logger = FlexLogger.getLogger(PolicyNotificationController.class);
- @Autowired
- CommonClassDao commonClassDao;
-
- @RequestMapping(value={"/watchPolicy"}, method={org.springframework.web.bind.annotation.RequestMethod.POST})
- public ModelAndView watchPolicy(HttpServletRequest request, HttpServletResponse response) throws IOException{
- StringBuilder path = new StringBuilder();
- String responseValue = "";
- try {
- String userId = UserUtils.getUserSession(request).getOrgUserId();
- logger.info("userid info: " + 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.append(individualElement.toString().replace("\"", "").trim());
- }else{
- path.append(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";
- SimpleBindings params = new SimpleBindings();
- params.put("finalName", finalName);
- params.put("userId", userId);
- List<Object> watchList = commonClassDao.getDataByQuery(query, params);
- 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");
+ @Autowired
+ CommonClassDao commonClassDao;
+
+ /**
+ * watchPolicy.
+ *
+ * @param request HttpServletRequest
+ * @param response HttpServletResponse
+ * @return ModelAndView
+ * @throws IOException IOException
+ */
+ @RequestMapping(value = {"/watchPolicy"}, method = {org.springframework.web.bind.annotation.RequestMethod.POST})
+ public ModelAndView watchPolicy(HttpServletRequest request, HttpServletResponse response) throws IOException {
+ StringBuilder path = new StringBuilder();
+ String responseValue = "";
+ try {
+ response.setCharacterEncoding(PolicyUtils.CHARACTER_ENCODING);
+ request.setCharacterEncoding(PolicyUtils.CHARACTER_ENCODING);
+ //
+ //
+ //
+ String userId = UserUtils.getUserSession(request).getOrgUserId();
+ logger.info("userid info: " + 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.append(individualElement.toString().replace("\"", "").trim());
+ } else {
+ path.append(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";
+ SimpleBindings params = new SimpleBindings();
+ params.put("finalName", finalName);
+ params.put("userId", userId);
+ List<Object> watchList = commonClassDao.getDataByQuery(query, params);
+ 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.setContentType(PolicyUtils.APPLICATION_JSON);
- 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");
- logger.error("Error druing watchPolicy function " + e);
- PrintWriter out = response.getWriter();
- out.write(PolicyUtils.CATCH_EXCEPTION);
- }
- return null;
- }
+ response.getWriter().write(new JSONObject("{watchData: "
+ + mapper.writeValueAsString(responseValue) + "}").toString());
+ } catch (Exception e) {
+ logger.error("Error druing watchPolicy function " + e);
+ response.getWriter().write(PolicyUtils.CATCH_EXCEPTION);
+ }
+ 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
index b02da1996..c1c784083 100644
--- 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
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -20,7 +20,12 @@
package org.onap.policy.controller;
-import java.io.PrintWriter;
+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;
+
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
@@ -28,7 +33,8 @@ import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
-
+import lombok.Getter;
+import lombok.Setter;
import org.json.JSONObject;
import org.onap.policy.common.logging.flexlogger.FlexLogger;
import org.onap.policy.common.logging.flexlogger.Logger;
@@ -36,6 +42,7 @@ 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.onap.policy.utils.PolicyUtils;
import org.onap.portalsdk.core.controller.RestrictedBaseController;
import org.onap.portalsdk.core.web.support.JsonMessage;
import org.onap.portalsdk.core.web.support.UserUtils;
@@ -45,12 +52,6 @@ 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 {
@@ -69,19 +70,19 @@ public class PolicyRolesController extends RestrictedBaseController {
/**
* Gets the policy roles entity data.
*
- * @param request the request
+ * @param request the request
* @param response the response
*/
- @RequestMapping(value = { "/get_RolesData" }, method = {
- org.springframework.web.bind.annotation.RequestMethod.GET }, produces = MediaType.APPLICATION_JSON_VALUE)
+ @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<String, Object> 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());
+ response.getWriter().write(new JSONObject(new JsonMessage(mapper.writeValueAsString(model))).toString());
} catch (Exception e) {
LOGGER.error("Exception Occured" + e);
}
@@ -90,12 +91,13 @@ public class PolicyRolesController extends RestrictedBaseController {
/**
* Save roles and Mechid entity data.
*
- * @param request the request
+ * @param request the request
* @param response the response
* @return the model and view
*/
- @RequestMapping(value = { "/save_NonSuperRolesData" }, method = {
- org.springframework.web.bind.annotation.RequestMethod.POST })
+ @RequestMapping(
+ value = {"/save_NonSuperRolesData"},
+ method = {org.springframework.web.bind.annotation.RequestMethod.POST})
public ModelAndView SaveRolesEntityData(HttpServletRequest request, HttpServletResponse response) {
try {
StringBuilder scopeName = new StringBuilder();
@@ -112,11 +114,11 @@ public class PolicyRolesController extends RestrictedBaseController {
}
}
LOGGER.info(
- "****************************************Logging UserID for Roles Function********************************************************");
+ "*************************Logging UserID for Roles Function***********************************");
LOGGER.info("UserId: " + userId + "Updating the Scope for following user" + adapter.getLoginId()
+ "ScopeNames" + adapter.getScope());
LOGGER.info(
- "*********************************************************************************************************************************");
+ "*********************************************************************************************");
UserInfo userInfo = new UserInfo();
userInfo.setUserLoginId(adapter.getLoginId().getUserName());
userInfo.setUserName(adapter.getLoginId().getUserName());
@@ -125,11 +127,11 @@ public class PolicyRolesController extends RestrictedBaseController {
if (adapter.getId() == 0 && "mechid".equals(adapter.getRole())) {
// Save new mechid scopes entity data.
LOGGER.info(
- "****************************************Logging UserID for New Mechid Function***************************************************");
+ "*********************Logging UserID for New Mechid Function********************************");
LOGGER.info("UserId:" + userId + "Adding new mechid-scopes for following user" + adapter.getLoginId()
+ "ScopeNames " + adapter.getScope());
LOGGER.info(
- "*********************************************************************************************************************************");
+ "*******************************************************************************************");
// First add the mechid to userinfo
commonClassDao.save(userInfo);
checkNew = true;
@@ -146,15 +148,11 @@ public class PolicyRolesController extends RestrictedBaseController {
} else {
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());
+ response.setCharacterEncoding(PolicyUtils.CHARACTER_ENCODING);
+ response.setContentType(PolicyUtils.APPLICATION_JSON);
+ request.setCharacterEncoding(PolicyUtils.CHARACTER_ENCODING);
+ response.getWriter().write(new JSONObject("{rolesDatas: "
+ + mapper.writeValueAsString(commonClassDao.getUserRoles()) + "}").toString());
} catch (Exception e) {
LOGGER.error("Exception Occured" + e);
}
@@ -164,11 +162,13 @@ public class PolicyRolesController extends RestrictedBaseController {
/**
* Gets the policy scopes entity data.
*
- * @param request the request
+ * @param request the request
* @param response the response
*/
- @RequestMapping(value = { "/get_PolicyRolesScopeData" }, method = {
- org.springframework.web.bind.annotation.RequestMethod.GET }, produces = MediaType.APPLICATION_JSON_VALUE)
+ @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<>();
@@ -177,51 +177,18 @@ public class PolicyRolesController extends RestrictedBaseController {
mapper.setVisibility(PropertyAccessor.FIELD, Visibility.ANY);
List<String> 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());
+ response.getWriter().write(new JSONObject(new JsonMessage(mapper.writeValueAsString(model))).toString());
} catch (Exception e) {
LOGGER.error("Exception Occured" + e);
}
}
}
+@Setter
+@Getter
class ReadScopes {
private int id;
private UserInfo loginId;
private String role;
private List<String> 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 List<String> getScope() {
- return scope;
- }
-
- public void setScope(List<String> 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
index fca1096ff..05264c8b6 100644
--- 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
@@ -2,14 +2,14 @@
* ============LICENSE_START=======================================================
* ONAP Policy Engine
* ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017, 2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -20,9 +20,9 @@
package org.onap.policy.controller;
+import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
-import java.io.PrintWriter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@@ -40,40 +40,42 @@ import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
-import com.fasterxml.jackson.databind.ObjectMapper;
-
@Controller
@RequestMapping("/")
public class PolicyValidationController extends RestrictedBaseController {
- private static final Logger LOGGER = FlexLogger.getLogger(PolicyValidationController.class);
+ private static final Logger LOGGER = FlexLogger.getLogger(PolicyValidationController.class);
+
+ /**
+ * validatePolicy.
+ *
+ * @param request HttpServletRequest
+ * @param response HttpServletResponse
+ * @return ModelAndView
+ * @throws IOException IOException
+ */
+ @RequestMapping(
+ value = {"/policyController/validate_policy.htm"},
+ method = {org.springframework.web.bind.annotation.RequestMethod.POST})
+ public ModelAndView validatePolicy(HttpServletRequest request, HttpServletResponse response) throws IOException {
+ try {
- @RequestMapping(value={"/policyController/validate_policy.htm"}, method={org.springframework.web.bind.annotation.RequestMethod.POST})
- public ModelAndView validatePolicy(HttpServletRequest request, HttpServletResponse response) throws IOException{
- try{
-
- PolicyValidation validation = new PolicyValidation();
- PolicyValidationRequestWrapper wrapper = new PolicyValidationRequestWrapper();
- StringBuilder responseString;
- ObjectMapper mapper = new ObjectMapper();
+ PolicyValidation validation = new PolicyValidation();
+ PolicyValidationRequestWrapper wrapper = new PolicyValidationRequestWrapper();
+ StringBuilder responseString;
+ ObjectMapper mapper = new ObjectMapper();
- PolicyRestAdapter policyData = wrapper.populateRequestParameters(request);
- responseString = validation.validatePolicy(policyData);
-
- PrintWriter out = response.getWriter();
- JsonMessage msg = new JsonMessage(mapper.writeValueAsString(responseString.toString()));
- JSONObject j = new JSONObject(msg);
- out.write(j.toString());
+ PolicyRestAdapter policyData = wrapper.populateRequestParameters(request);
+ responseString = validation.validatePolicy(policyData);
- return null;
- }
- catch (Exception e){
- LOGGER.error("Exception Occured During Policy Validation" +e);
- response.setCharacterEncoding("UTF-8");
- request.setCharacterEncoding("UTF-8");
- PrintWriter out = response.getWriter();
- out.write(PolicyUtils.CATCH_EXCEPTION);
- }
- return null;
- }
-} \ No newline at end of file
+ response.getWriter().write(new JSONObject(
+ new JsonMessage(mapper.writeValueAsString(responseString.toString()))).toString());
+ } catch (Exception e) {
+ LOGGER.error("Exception Occured During Policy Validation" + e);
+ response.setCharacterEncoding(PolicyUtils.CHARACTER_ENCODING);
+ request.setCharacterEncoding(PolicyUtils.CHARACTER_ENCODING);
+ response.getWriter().write(PolicyUtils.CATCH_EXCEPTION);
+ }
+ return null;
+ }
+}
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
index 9cc6314dd..8883475b8 100644
--- 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
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP Policy Engine
* ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017, 2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -20,14 +20,12 @@
package org.onap.policy.dao;
-
import java.util.List;
-import org.onap.policy.rest.jpa.SystemLogDB;
-
-
+import org.onap.policy.rest.jpa.SystemLogDb;
public abstract interface SystemLogDbDao {
- public abstract List<SystemLogDB> getLoggingData();
- public abstract List<SystemLogDB> getSystemAlertData();
+ public abstract List<SystemLogDb> getLoggingData();
+
+ public abstract List<SystemLogDb> 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
index 170c30838..a4b2c88d2 100644
--- 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
@@ -2,14 +2,14 @@
* ============LICENSE_START=======================================================
* ONAP Policy Engine
* ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017, 2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -48,368 +48,358 @@ import org.springframework.stereotype.Service;
@Service("CommonClassDao")
@Primary
-public class CommonClassDaoImpl implements CommonClassDao{
+public class CommonClassDaoImpl implements CommonClassDao {
+
+ private static final Logger LOGGER = FlexLogger.getLogger(CommonClassDaoImpl.class);
+ private static SessionFactory sessionfactory;
- private static final Logger LOGGER = FlexLogger.getLogger(CommonClassDaoImpl.class);
- private static SessionFactory sessionfactory;
-
public static SessionFactory getSessionfactory() {
- return sessionfactory;
+ return sessionfactory;
}
public static void setSessionfactory(SessionFactory sessionfactory) {
- CommonClassDaoImpl.sessionfactory = sessionfactory;
+ CommonClassDaoImpl.sessionfactory = sessionfactory;
}
@Autowired
- private CommonClassDaoImpl(SessionFactory sessionfactory){
- CommonClassDaoImpl.sessionfactory = sessionfactory;
- }
-
- public CommonClassDaoImpl(){
- //Default Constructor
+ private CommonClassDaoImpl(SessionFactory sessionfactory) {
+ CommonClassDaoImpl.sessionfactory = sessionfactory;
}
-
-
- @SuppressWarnings({ "unchecked", "rawtypes" })
- @Override
- public List<Object> getData(Class className) {
- Session session = sessionfactory.openSession();
- List<Object> 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<Object> getDataById(Class className, String columnName, String key) {
- Session session = sessionfactory.openSession();
- List<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();
- } 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);
- }
- }
-
- }
-
+ public CommonClassDaoImpl() {
+ // Default Constructor
+ }
- @SuppressWarnings({ "unchecked", "rawtypes" })
- @Override
- public List<Object> checkDuplicateEntry(String value, String columnName, Class className) {
- Session session = sessionfactory.openSession();
- Transaction tx = session.beginTransaction();
- List<Object> 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", "rawtypes"})
+ @Override
+ public List<Object> getData(Class className) {
+ Session session = sessionfactory.openSession();
+ List<Object> 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<Object> getDataById(Class className, String columnName, String key) {
+ Session session = sessionfactory.openSession();
+ List<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();
+ } 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")
- @Override
- public List<PolicyRoles> getUserRoles() {
- Session session = sessionfactory.openSession();
- Transaction tx = session.beginTransaction();
- List<PolicyRoles> 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 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 List<Object> checkExistingGroupListforUpdate(String arg0, String arg1) {
- return Collections.emptyList();
- }
+ @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 deleteAll() {}
+ @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")
- @Override
- public List<Object> getDataByQuery(String query, SimpleBindings params) {
- Session session = sessionfactory.openSession();
- Transaction tx = session.beginTransaction();
- List<Object> data = null;
- try {
- Query hbquery = session.createQuery(query);
- for (Map.Entry<String, Object> paramPair : params.entrySet()) {
- if(paramPair.getValue() instanceof java.lang.Long){
- hbquery.setLong(paramPair.getKey(), (long) paramPair.getValue());
- }
- else{
- hbquery.setParameter(paramPair.getKey(), paramPair.getValue());
- }
- }
- data = hbquery.list();
- tx.commit();
- } catch (Exception e) {
- LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Querying Database Table"+e);
- throw e;
- }finally{
- try{
- session.close();
- }catch(HibernateException e1){
- LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1);
- }
- }
- return data;
- }
+ }
+ @SuppressWarnings({"unchecked", "rawtypes"})
+ @Override
+ public List<Object> checkDuplicateEntry(String value, String columnName, Class className) {
+ Session session = sessionfactory.openSession();
+ Transaction tx = session.beginTransaction();
+ List<Object> 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("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<PolicyRoles> getUserRoles() {
+ Session session = sessionfactory.openSession();
+ Transaction tx = session.beginTransaction();
+ List<PolicyRoles> rolesData = null;
+ try {
+ final Criteria cr = session.createCriteria(PolicyRoles.class);
+ final 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<Object> checkExistingGroupListforUpdate(String arg0, String arg1) {
+ return Collections.emptyList();
+ }
- @Override
- public void updateClAlarms(String arg0, String arg1) {}
+ @Override
+ public void deleteAll() {
+ }
+ @SuppressWarnings("unchecked")
+ @Override
+ public List<Object> getDataByQuery(String query, SimpleBindings params) {
+ Session session = sessionfactory.openSession();
+ Transaction tx = session.beginTransaction();
+ List<Object> data = null;
+ try {
+ Query hbquery = session.createQuery(query);
+ for (Map.Entry<String, Object> paramPair : params.entrySet()) {
+ if (paramPair.getValue() instanceof java.lang.Long) {
+ hbquery.setLong(paramPair.getKey(), (long) paramPair.getValue());
+ } else {
+ hbquery.setParameter(paramPair.getKey(), paramPair.getValue());
+ }
+ }
+ data = hbquery.list();
+ tx.commit();
+ } catch (Exception e) {
+ LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Querying Database Table" + e);
+ throw e;
+ } finally {
+ try {
+ session.close();
+ } catch (HibernateException e1) {
+ LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement" + e1);
+ }
+ }
+ return data;
+ }
- @Override
- public void updateClYaml(String arg0, String arg1) {}
+ @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) {
+ // why is there no code here?
+ }
- @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);
- }
- }
-
- }
+ @Override
+ public void updateClYaml(String arg0, String arg1) {
+ // why is there no code here?
+ }
+ @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<String> getDataByColumn(Class className, String columnName) {
- Session session = sessionfactory.openSession();
- List<String> 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<String> getDataByColumn(Class className, String columnName) {
+ Session session = sessionfactory.openSession();
+ List<String> 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<Object> getMultipleDataOnAddingConjunction(Class className, String columnName, List<String> data) {
- Session session = sessionfactory.openSession();
- Transaction tx = session.beginTransaction();
- List<Object> entityData = null;
- try {
- Criteria cr = session.createCriteria(className);
- Disjunction disjunction = Restrictions.disjunction();
- List<Conjunction> 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;
- }
+ @SuppressWarnings({"rawtypes", "unchecked"})
+ @Override
+ public List<Object> getMultipleDataOnAddingConjunction(Class className, String columnName, List<String> data) {
+ Session session = sessionfactory.openSession();
+ Transaction tx = session.beginTransaction();
+ List<Object> entityData = null;
+ try {
+ Criteria cr = session.createCriteria(className);
+ Disjunction disjunction = Restrictions.disjunction();
+ List<Conjunction> 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
index 1727f47c0..46aed213f 100644
--- 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
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP Policy Engine
* ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017, 2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -20,85 +20,83 @@
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.common.logging.flexlogger.FlexLogger;
+import org.onap.policy.common.logging.flexlogger.Logger;
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;
-
+import org.onap.policy.rest.jpa.SystemLogDb;
+import org.onap.policy.xacml.api.XACMLErrorConstants;
+import org.springframework.stereotype.Service;
@Service("SystemLogDbDao")
public class SystemLogDbDaoImpl implements SystemLogDbDao {
- private static final Logger logger = FlexLogger.getLogger(SystemLogDbDaoImpl.class);
-
- @SuppressWarnings("unchecked")
- @Override
- public List<SystemLogDB> getLoggingData() {
- Session session = HibernateSession.getSession();
- Transaction tx = session.beginTransaction();
- List<SystemLogDB> system = null;
+ private static final Logger logger = FlexLogger.getLogger(SystemLogDbDaoImpl.class);
+
+ @SuppressWarnings("unchecked")
+ @Override
+ public List<SystemLogDb> getLoggingData() {
+ Session session = HibernateSession.getSession();
+ Transaction tx = session.beginTransaction();
+ List<SystemLogDb> system = null;
try {
- String sqlWhere = null;
- if(PolicyController.isjUnit()){
- sqlWhere = "";
- }else{
- 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));
+ String sqlWhere = null;
+ if (PolicyController.isjUnit()) {
+ sqlWhere = "";
+ } else {
+ 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;
- }
+ 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<SystemLogDB> getSystemAlertData() {
- Session session = HibernateSession.getSession();
- Transaction tx = session.beginTransaction();
- List<SystemLogDB> system = null;
+ @SuppressWarnings("unchecked")
+ @Override
+ public List<SystemLogDb> getSystemAlertData() {
+ Session session = HibernateSession.getSession();
+ Transaction tx = session.beginTransaction();
+ List<SystemLogDb> system = null;
try {
- String sqlWhere = null;
- if(PolicyController.isjUnit()){
- sqlWhere = "";
- }else{
- 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));
+ String sqlWhere = null;
+ if (PolicyController.isjUnit()) {
+ sqlWhere = "";
+ } else {
+ 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;
- }
+ 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
index e6c375808..6c4fd7e91 100644
--- 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
@@ -20,8 +20,8 @@
package org.onap.policy.model;
-
import com.att.research.xacml.api.pap.PAPException;
+
import java.awt.Checkbox;
import java.util.ArrayList;
import java.util.Collection;
@@ -29,6 +29,7 @@ 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.rest.util.PolicyContainer;
@@ -112,6 +113,9 @@ public class PDPGroupContainer extends PolicyItemSetChangeNotifier
return itemId instanceof OnapPDPGroup;
}
+ /**
+ * refreshGroups.
+ */
public synchronized void refreshGroups() {
synchronized (this.groups) {
this.groups.clear();
@@ -133,6 +137,11 @@ public class PDPGroupContainer extends PolicyItemSetChangeNotifier
return Collections.unmodifiableList(this.groups);
}
+ /**
+ * makeDefault.
+ *
+ * @param group OnapPDPGroup
+ */
public void makeDefault(OnapPDPGroup group) {
try {
this.papEngine.setDefaultGroup(group);
@@ -143,6 +152,13 @@ public class PDPGroupContainer extends PolicyItemSetChangeNotifier
return;
}
+ /**
+ * removeGroup.
+ *
+ * @param group OnapPDPGroup
+ * @param newGroup OnapPDPGroup
+ * @throws PAPException PAPException
+ */
public void removeGroup(OnapPDPGroup group, OnapPDPGroup newGroup) throws PAPException {
if (LOGGER.isTraceEnabled()) {
LOGGER.trace("removeGroup: " + group + " new group for PDPs: " + newGroup);
@@ -158,6 +174,13 @@ public class PDPGroupContainer extends PolicyItemSetChangeNotifier
}
}
+ /**
+ * removePDP.
+ *
+ * @param pdp OnapPDP
+ * @param group OnapPDPGroup
+ * @throws PAPException PAPException
+ */
public void removePDP(OnapPDP pdp, OnapPDPGroup group) throws PAPException {
if (LOGGER.isTraceEnabled()) {
LOGGER.trace("removePDP: " + pdp + " from group: " + group);
@@ -170,6 +193,11 @@ public class PDPGroupContainer extends PolicyItemSetChangeNotifier
}
}
+ /**
+ * updatePDP.
+ *
+ * @param pdp OnapPDP
+ */
public void updatePDP(OnapPDP pdp) {
try {
papEngine.updatePDP(pdp);
@@ -178,6 +206,11 @@ public class PDPGroupContainer extends PolicyItemSetChangeNotifier
}
}
+ /**
+ * updateGroup.
+ *
+ * @param group OnapPDPGroup
+ */
public void updateGroup(OnapPDPGroup group) {
try {
papEngine.updateGroup(group);
@@ -216,6 +249,17 @@ public class PDPGroupContainer extends PolicyItemSetChangeNotifier
}
@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 Class<?> getType(Object propertyId) {
if (propertyId.equals(PROPERTY_ID)) {
return String.class;
@@ -268,6 +312,13 @@ public class PDPGroupContainer extends PolicyItemSetChangeNotifier
throw new UnsupportedOperationException("PDP Container cannot add a given item.");
}
+ /**
+ * addNewGroup.
+ *
+ * @param name String
+ * @param description String
+ * @throws PAPException PAPException
+ */
public void addNewGroup(String name, String description) throws PAPException {
if (LOGGER.isTraceEnabled()) {
LOGGER.trace("addNewGroup " + name + " " + description);
@@ -275,6 +326,16 @@ public class PDPGroupContainer extends PolicyItemSetChangeNotifier
this.papEngine.newGroup(name, description);
}
+ /**
+ * addNewPDP.
+ *
+ * @param id String
+ * @param group OnapPDPGroup
+ * @param name String
+ * @param description String
+ * @param jmxport int
+ * @throws PAPException PAPException
+ */
public void addNewPDP(String id, OnapPDPGroup group, String name, String description, int jmxport)
throws PAPException {
if (LOGGER.isTraceEnabled()) {
@@ -283,6 +344,12 @@ public class PDPGroupContainer extends PolicyItemSetChangeNotifier
this.papEngine.newPDP(id, group, name, description, jmxport);
}
+ /**
+ * movePDP.
+ *
+ * @param pdp OnapPDP
+ * @param group OnapPDPGroup
+ */
public void movePDP(OnapPDP pdp, OnapPDPGroup group) {
try {
this.papEngine.movePDP(pdp, group);
@@ -427,17 +494,6 @@ public class PDPGroupContainer extends PolicyItemSetChangeNotifier
}
@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) {
throw new UnsupportedOperationException("Cannot addItemAt");
}
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
index 2f051f7b4..baaecaee6 100644
--- 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
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP Policy Engine
* ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017, 2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -20,6 +20,7 @@
package org.onap.policy.model;
+import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import java.io.Serializable;
@@ -31,69 +32,69 @@ 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(){
- // Empty constructor
- }
-
- 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;
- }
+@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() {
+ // Empty constructor
+ }
+
+ 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/UserUtils.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/utils/UserUtils.java
index 40c839676..f9f93c0ff 100644
--- a/POLICY-SDK-APP/src/main/java/org/onap/policy/utils/UserUtils.java
+++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/utils/UserUtils.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -17,6 +17,7 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.policy.utils;
import java.util.ArrayList;
@@ -35,18 +36,18 @@ public final class UserUtils {
}
public static class Pair<T, U> {
- public final T t;
- public final U u;
+ public final T first;
+ public final U second;
- public Pair(T t, U u) {
- this.t = t;
- this.u = u;
+ public Pair(T first, U second) {
+ this.first = first;
+ this.second = second;
}
}
/**
* Check Role and its Scopes.
- *
+ *
* @param userRoles list of UserRoles.
* @return return role and scope from UserRole Object.
*/
@@ -75,7 +76,7 @@ public final class UserUtils {
/**
* Get Role by Scope based on UserRole Object.
- *
+ *
* @param userRoles list of UserRoles.
* @return return the map<scope, role>.
*/
@@ -94,8 +95,8 @@ public final class UserUtils {
/**
* Read non super role scopes and add to map.
- *
- * @param userRole Role Object.
+ *
+ * @param userRole Role Object.
* @param rolesList roleList Object.
* @return return the map<scope, role>.
*/
@@ -115,7 +116,7 @@ public final class UserUtils {
/**
* Trim Scope Value.
- *
+ *
* @param scope string scope name.
* @return trim scope.
*/
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 a12eac3ce..4831802ca 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
@@ -44,9 +44,9 @@ decryption_key = AGLDdG4D04BKm2IxIWEr8o==
##########################################################################
#Mysql
db.driver = org.mariadb.jdbc.Driver
-db.connectionURL = jdbc:mariadb://localhost:3306/onapsdk1707
+db.connectionURL = jdbc:mariadb://localhost:3306/onap_sdk
db.userName = root
-db.password =
+db.password =
db.hib.dialect = org.hibernate.dialect.MySQLDialect
db.min_pool_size = 5
db.max_pool_size = 10
diff --git a/POLICY-SDK-APP/src/main/webapp/app/policyApp/CSS/bootstrap/dist/js/bootstrap-modalmanager.min.js b/POLICY-SDK-APP/src/main/webapp/app/policyApp/CSS/bootstrap/dist/js/bootstrap-modalmanager.min.js
new file mode 100644
index 000000000..80e9597e7
--- /dev/null
+++ b/POLICY-SDK-APP/src/main/webapp/app/policyApp/CSS/bootstrap/dist/js/bootstrap-modalmanager.min.js
@@ -0,0 +1,341 @@
+/* ===========================================================
+ * bootstrap-modalmanager.min.js v2.2.5
+ * ===========================================================
+ * Copyright 2012 Jordan Schroter
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ========================================================== */
+
+!function(c) {
+ var a = function(f, e) {
+ this.init(f, e)
+ };
+ a.prototype = {
+ constructor : a,
+ init : function(f, e) {
+ this.$element = c(f);
+ this.options = c.extend({}, c.fn.modalmanager.defaults,
+ this.$element.data(), typeof e == "object" && e);
+ this.stack = [];
+ this.backdropCount = 0;
+ if (this.options.resize) {
+ var h, g = this;
+ c(window).on("resize.modal", function() {
+ h && clearTimeout(h);
+ h = setTimeout(function() {
+ for (var j = 0; j < g.stack.length; j++) {
+ g.stack[j].isShown && g.stack[j].layout()
+ }
+ }, 10)
+ })
+ }
+ },
+ createModal : function(f, e) {
+ c(f).modal(c.extend({
+ manager : this
+ }, e))
+ },
+ appendModal : function(f) {
+ this.stack.push(f);
+ var e = this;
+ f.$element.on("show.modalmanager",
+ b(function(h) {
+ var g = function() {
+ f.isShown = true;
+ var i = c.support.transition
+ && f.$element.hasClass("fade");
+ e.$element.toggleClass("modal-open",
+ e.hasOpenModal()).toggleClass(
+ "page-overflow",
+ c(window).height() < e.$element.height());
+ f.$parent = f.$element.parent();
+ f.$container = e.createContainer(f);
+ f.$element.appendTo(f.$container);
+ e.backdrop(f, function() {
+ f.$element.show();
+ if (i) {
+ f.$element[0].offsetWidth
+ }
+ f.layout();
+ f.$element.addClass("in").attr("aria-hidden",
+ false);
+ var j = function() {
+ e.setFocus();
+ f.$element.trigger("shown")
+ };
+ i ? f.$element.one(c.support.transition.end, j)
+ : j()
+ })
+ };
+ f.options.replace ? e.replace(g) : g()
+ }));
+ f.$element
+ .on(
+ "hidden.modalmanager",
+ b(function(g) {
+ e.backdrop(f);
+ if (!f.$element.parent().length) {
+ e.destroyModal(f)
+ } else {
+ if (f.$backdrop) {
+ var h = c.support.transition
+ && f.$element.hasClass("fade");
+ if (h) {
+ f.$element[0].offsetWidth
+ }
+ c.support.transition
+ && f.$element.hasClass("fade") ? f.$backdrop
+ .one(c.support.transition.end,
+ function() {
+ f.destroy()
+ })
+ : f.destroy()
+ } else {
+ f.destroy()
+ }
+ }
+ }));
+ f.$element.on("destroyed.modalmanager", b(function(g) {
+ e.destroyModal(f)
+ }))
+ },
+ getOpenModals : function() {
+ var f = [];
+ for (var e = 0; e < this.stack.length; e++) {
+ if (this.stack[e].isShown) {
+ f.push(this.stack[e])
+ }
+ }
+ return f
+ },
+ hasOpenModal : function() {
+ return this.getOpenModals().length > 0
+ },
+ setFocus : function() {
+ var f;
+ for (var e = 0; e < this.stack.length; e++) {
+ if (this.stack[e].isShown) {
+ f = this.stack[e]
+ }
+ }
+ if (!f) {
+ return
+ }
+ f.focus()
+ },
+ destroyModal : function(f) {
+ f.$element.off(".modalmanager");
+ if (f.$backdrop) {
+ this.removeBackdrop(f)
+ }
+ this.stack.splice(this.getIndexOfModal(f), 1);
+ var e = this.hasOpenModal();
+ this.$element.toggleClass("modal-open", e);
+ if (!e) {
+ this.$element.removeClass("page-overflow")
+ }
+ this.removeContainer(f);
+ this.setFocus()
+ },
+ getModalAt : function(e) {
+ return this.stack[e]
+ },
+ getIndexOfModal : function(f) {
+ for (var e = 0; e < this.stack.length; e++) {
+ if (f === this.stack[e]) {
+ return e
+ }
+ }
+ },
+ replace : function(g) {
+ var f;
+ for (var e = 0; e < this.stack.length; e++) {
+ if (this.stack[e].isShown) {
+ f = this.stack[e]
+ }
+ }
+ if (f) {
+ this.$backdropHandle = f.$backdrop;
+ f.$backdrop = null;
+ g && f.$element.one("hidden", b(c.proxy(g, this)));
+ f.hide()
+ } else {
+ if (g) {
+ g()
+ }
+ }
+ },
+ removeBackdrop : function(e) {
+ e.$backdrop.remove();
+ e.$backdrop = null
+ },
+ createBackdrop : function(g, f) {
+ var e;
+ if (!this.$backdropHandle) {
+ e = c(f).addClass(g).appendTo(this.$element)
+ } else {
+ e = this.$backdropHandle;
+ e.off(".modalmanager");
+ this.$backdropHandle = null;
+ this.isLoading && this.removeSpinner()
+ }
+ return e
+ },
+ removeContainer : function(e) {
+ e.$container.remove();
+ e.$container = null
+ },
+ createContainer : function(e) {
+ var f;
+ f = c('<div class="modal-scrollable">').css("z-index",
+ d("modal", this.getOpenModals().length)).appendTo(
+ this.$element);
+ if (e && e.options.backdrop != "static") {
+ f.on("click.modal", b(function(g) {
+ e.hide()
+ }))
+ } else {
+ if (e) {
+ f.on("click.modal", b(function(g) {
+ e.attention()
+ }))
+ }
+ }
+ return f
+ },
+ backdrop : function(h, j) {
+ var f = h.$element.hasClass("fade") ? "fade" : "", i = h.options.backdrop
+ && this.backdropCount < this.options.backdropLimit;
+ if (h.isShown && i) {
+ var e = c.support.transition && f && !this.$backdropHandle;
+ h.$backdrop = this
+ .createBackdrop(f, h.options.backdropTemplate);
+ h.$backdrop.css("z-index", d("backdrop",
+ this.getOpenModals().length));
+ if (e) {
+ h.$backdrop[0].offsetWidth
+ }
+ h.$backdrop.addClass("in");
+ this.backdropCount += 1;
+ e ? h.$backdrop.one(c.support.transition.end, j) : j()
+ } else {
+ if (!h.isShown && h.$backdrop) {
+ h.$backdrop.removeClass("in");
+ this.backdropCount -= 1;
+ var g = this;
+ c.support.transition && h.$element.hasClass("fade") ? h.$backdrop
+ .one(c.support.transition.end, function() {
+ g.removeBackdrop(h)
+ })
+ : g.removeBackdrop(h)
+ } else {
+ if (j) {
+ j()
+ }
+ }
+ }
+ },
+ removeSpinner : function() {
+ this.$spinner && this.$spinner.remove();
+ this.$spinner = null;
+ this.isLoading = false
+ },
+ removeLoading : function() {
+ this.$backdropHandle && this.$backdropHandle.remove();
+ this.$backdropHandle = null;
+ this.removeSpinner()
+ },
+ loading : function(h) {
+ h = h || function() {
+ };
+ this.$element.toggleClass("modal-open",
+ !this.isLoading || this.hasOpenModal()).toggleClass(
+ "page-overflow",
+ c(window).height() < this.$element.height());
+ if (!this.isLoading) {
+ this.$backdropHandle = this.createBackdrop("fade",
+ this.options.backdropTemplate);
+ this.$backdropHandle[0].offsetWidth;
+ var e = this.getOpenModals();
+ this.$backdropHandle
+ .css("z-index", d("backdrop", e.length + 1)).addClass(
+ "in");
+ var g = c(this.options.spinner).css("z-index",
+ d("modal", e.length + 1)).appendTo(this.$element)
+ .addClass("in");
+ this.$spinner = c(this.createContainer()).append(g).on(
+ "click.modalmanager", c.proxy(this.loading, this));
+ this.isLoading = true;
+ c.support.transition ? this.$backdropHandle.one(
+ c.support.transition.end, h) : h()
+ } else {
+ if (this.isLoading && this.$backdropHandle) {
+ this.$backdropHandle.removeClass("in");
+ var f = this;
+ c.support.transition ? this.$backdropHandle.one(
+ c.support.transition.end, function() {
+ f.removeLoading()
+ }) : f.removeLoading()
+ } else {
+ if (h) {
+ h(this.isLoading)
+ }
+ }
+ }
+ }
+ };
+ var d = (function() {
+ var f, e = {};
+ return function(g, j) {
+ if (typeof f === "undefined") {
+ var i = c('<div class="modal hide" />').appendTo("body"), h = c(
+ '<div class="modal-backdrop hide" />').appendTo("body");
+ e.modal = +i.css("z-index");
+ e.backdrop = +h.css("z-index");
+ f = e.modal - e.backdrop;
+ i.remove();
+ h.remove();
+ h = i = null
+ }
+ return e[g] + (f * j)
+ }
+ }());
+ function b(e) {
+ return function(f) {
+ if (f && this === f.target) {
+ return e.apply(this, arguments)
+ }
+ }
+ }
+ c.fn.modalmanager = function(f, e) {
+ return this.each(function() {
+ var h = c(this), g = h.data("modalmanager");
+ if (!g) {
+ h.data("modalmanager", (g = new a(this, f)))
+ }
+ if (typeof f === "string") {
+ g[f].apply(g, [].concat(e))
+ }
+ })
+ };
+ c.fn.modalmanager.defaults = {
+ backdropLimit : 999,
+ resize : true,
+ spinner : '<div class="loading-spinner fade" style="width: 200px; margin-left: -100px;"><div class="progress progress-striped active"><div class="bar" style="width: 100%;"></div></div></div>',
+ backdropTemplate : '<div class="modal-backdrop" />'
+ };
+ c.fn.modalmanager.Constructor = a;
+ c(function() {
+ c(document).off("show.bs.modal").off("hidden.bs.modal")
+ })
+}(jQuery); \ No newline at end of file
diff --git a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/AutoPushController.js b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/AutoPushController.js
index 4832da109..264ff567e 100644
--- a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/AutoPushController.js
+++ b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/AutoPushController.js
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP Policy Engine
* ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017, 2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -17,7 +17,8 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-app.controller('policyPushController', function ($scope, PolicyAppService, modalService, $modal, Notification,$filter){
+app.controller('policyPushController',
+ function ($scope, PolicyAppService, modalService, $modal, Notification,$filter){
$( "#dialog" ).hide();
$scope.isDisabled = true;
@@ -32,30 +33,24 @@ app.controller('policyPushController', function ($scope, PolicyAppService, modal
}else{
$scope.isDisabled = false;
}
- console.log($scope.data);
- },function(error){
- console.log("failed");
});
$scope.pdpdata;
PolicyAppService.getData('get_PDPGroupData').then(function (data) {
var j = data;
$scope.pdpdata = JSON.parse(j.data);
- console.log($scope.pdpdata);
$scope.pushTabPDPGrid.data = $scope.pdpdata;
- }, function (error) {
- console.log("failed");
});
$scope.getPDPData = function(){
- $scope.pushTabPDPGrid.data = $scope.pdpdata;
+ $scope.pushTabPDPGrid.data = $scope.pdpdata;
};
$scope.filterPdpGroup;
$scope.filterPDPGroupData = function() {
$scope.pushTabPDPGrid.data = $filter('filter')($scope.pdpdata, $scope.filterPdpGroup, undefined);
};
- $scope.pushTabPDPGrid = {
+ $scope.pushTabPDPGrid = {
onRegisterApi: function(gridApi) {
$scope.gridApi = gridApi;
},
@@ -78,7 +73,7 @@ app.controller('policyPushController', function ($scope, PolicyAppService, modal
Notification.error("Policy Application has been LockDown.");
}else{
var modalInstance = $modal.open({
- backdrop: 'static', keyboard: false,
+ backdrop: 'static', keyboard: false,
templateUrl: 'remove_PDPGroupPolicies_popup.html',
controller: 'removeGroupPoliciesController',
resolve: {
@@ -91,7 +86,6 @@ app.controller('policyPushController', function ($scope, PolicyAppService, modal
}
});
modalInstance.result.then(function (response) {
- console.log('response', response);
$scope.pdpdata = JSON.parse(response.data);
$scope.pushTabPDPGrid.data = $scope.pdpdata;
});
@@ -99,75 +93,66 @@ app.controller('policyPushController', function ($scope, PolicyAppService, modal
};
$scope.gridOptions = {
- data : 'policydatas',
- onRegisterApi: function(gridApi) {
- $scope.gridPolicyApi = gridApi;
- },
- enableSorting: true,
- enableFiltering: true,
- showTreeExpandNoChildren: true,
- paginationPageSizes: [10, 20, 50, 100],
- paginationPageSize: 20,
- columnDefs: [{name: 'policyName', displayName : 'Policy Name', sort: { direction: 'asc', priority: 0 }},
- {name: 'activeVersion', displayName : 'Version'},
- {name: 'modifiedDate', displayName : 'Last Modified',type: 'date', cellFilter: 'date:\'yyyy-MM-dd HH:MM:ss a\'' }]
+ data : 'policydatas',
+ onRegisterApi: function(gridApi) {
+ $scope.gridPolicyApi = gridApi;
+ },
+ enableSorting: true,
+ enableFiltering: true,
+ showTreeExpandNoChildren: true,
+ paginationPageSizes: [10, 20, 50, 100],
+ paginationPageSize: 20,
+ columnDefs: [{name: 'policyName', displayName : 'Policy Name', sort: { direction: 'asc', priority: 0 }},
+ {name: 'activeVersion', displayName : 'Version'},
+ {name: 'modifiedDate', displayName : 'Last Modified',type: 'date', cellFilter: 'date:\'yyyy-MM-dd HH:MM:ss a\'' }]
};
PolicyAppService.getData('get_AutoPushPoliciesContainerData').then(function (data) {
- $scope.loading = false;
- var j = data;
- $scope.data = JSON.parse(j.data);
- console.log($scope.data);
- $scope.policydatas =JSON.parse($scope.data.policydatas);
- console.log($scope.policydatas);
- }, function (error) {
- console.log("failed");
- });
+ $scope.loading = false;
+ var j = data;
+ $scope.data = JSON.parse(j.data);
+ $scope.policydatas =JSON.parse($scope.data.policydatas);
+ });
$scope.pushPoliciesButton = function(){
- var policySelection = $scope.gridPolicyApi.selection.getSelectedRows();
- console.log(policySelection);
- var currentSelection = $scope.gridApi.selection.getSelectedRows();
- if(policySelection.length == 0 && currentSelection.length == 0){
- Notification.error("Please Select Policy and PDP Group to Push");
- }
- if(policySelection.length == 0 && currentSelection.length != 0){
- Notification.error("Please Select Policy to Push");
- }
- if(policySelection.length != 0 && currentSelection.length == 0){
- Notification.error("Please Select PDP Group to Push");
- }
- if(policySelection.length != 0 && currentSelection.length != 0){
- var finalData = {
- "pdpDatas": currentSelection,
- "policyDatas": policySelection
- };
- console.log(finalData);
- var uuu = "auto_Push/PushPolicyToPDP.htm";
- var postData={pushTabData: finalData};
- $.ajax({
- type : 'POST',
- url : uuu,
- dataType: 'json',
- contentType: 'application/json',
- data: JSON.stringify(postData),
- success : function(data){
- $scope.$apply(function(){
- $scope.data=data.data;
- $scope.pdpdata = JSON.parse(data.data);
- $scope.pushTabPDPGrid.data = $scope.pdpdata;
- Notification.success("Policy Pushed Successfully");
- });
- console.log($scope.data);
- },
- error : function(data){
- Notification.error("Error Occured while Pushing Policy.");
- }
- });
+ var policySelection = $scope.gridPolicyApi.selection.getSelectedRows();
+ var currentSelection = $scope.gridApi.selection.getSelectedRows();
+ if(policySelection.length == 0 && currentSelection.length == 0){
+ Notification.error("Please Select Policy and PDP Group to Push");
+ }
+ if(policySelection.length == 0 && currentSelection.length != 0){
+ Notification.error("Please Select Policy to Push");
+ }
+ if(policySelection.length != 0 && currentSelection.length == 0){
+ Notification.error("Please Select PDP Group to Push");
+ }
+ if(policySelection.length != 0 && currentSelection.length != 0){
+ var finalData = {
+ "pdpDatas": currentSelection,
+ "policyDatas": policySelection
+ };
+ var uuu = "auto_Push/PushPolicyToPDP.htm";
+ var postData={pushTabData: finalData};
+ $.ajax({
+ type : 'POST',
+ url : uuu,
+ dataType: 'json',
+ contentType: 'application/json',
+ data: JSON.stringify(postData),
+ success : function(data){
+ $scope.$apply(function(){
+ $scope.data=data.data;
+ $scope.pdpdata = JSON.parse(data.data);
+ $scope.pushTabPDPGrid.data = $scope.pdpdata;
+ Notification.success("Policy Pushed Successfully");
+ });
+ },
+ error : function(data){
+ Notification.error("Error Occured while Pushing Policy.");
+ }
+ });
- }
+ }
};
-
-
});
diff --git a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/AutoPushTabController/RemovePDPGroupPoliciesController.js b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/AutoPushTabController/RemovePDPGroupPoliciesController.js
index 62dcd65b2..b8325b316 100644
--- a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/AutoPushTabController/RemovePDPGroupPoliciesController.js
+++ b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/AutoPushTabController/RemovePDPGroupPoliciesController.js
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP Policy Engine
* ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017, 2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -40,11 +40,9 @@ app.controller('removeGroupPoliciesController' , function ($scope, $modalInstan
//set gridApi on scope
$scope.gridApi = gridApi;
gridApi.selection.on.rowSelectionChanged($scope,function(row){
- var msg = 'row selected ' + row.isSelected;
});
gridApi.selection.on.rowSelectionChangedBatch($scope,function(rows){
- var msg = 'rows changed ' + rows.length;
});
};
diff --git a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/PolicyAddScopeRoleController.js b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/PolicyAddScopeRoleController.js
index 051a9130c..7715c779a 100644
--- a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/PolicyAddScopeRoleController.js
+++ b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/PolicyAddScopeRoleController.js
@@ -17,7 +17,7 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-app.controller('editRoleController' , function ($scope, PolicyAppService, $modalInstance, message){
+app.controller('editRoleController' , function ($scope, PolicyAppService, $modalInstance, message, Notification){
if (message.editRoleData != null) {
$scope.label='Edit Role'
$scope.disableCd=true;
@@ -67,7 +67,7 @@ app.controller('editRoleController' , function ($scope, PolicyAppService, $moda
$modalInstance.close({rolesDatas:$scope.rolesDatas});
},
error : function(data){
- alert("Error while saving Role.");
+ Notification.error("Error while saving Role.");
}
});
};
@@ -90,7 +90,7 @@ app.controller('editRoleController' , function ($scope, PolicyAppService, $moda
$modalInstance.close({rolesDatas:$scope.rolesDatas});
},
error : function(data) {
- alert("Error while Creating Mechid scopes.");
+ Notification.error("Error while Creating Mechid scopes.");
}
});
};
diff --git a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dashboardCRUDController.js b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dashboardCRUDController.js
index ce1af6b1a..d3f093697 100644
--- a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dashboardCRUDController.js
+++ b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dashboardCRUDController.js
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP Policy Engine
* ================================================================================
- * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2018, 2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -19,20 +19,18 @@
*/
app.controller('policyDashboardCRUDDataController', function ($scope, PolicyAppService, modalService, $modal){
- console.log("policyDashboardCRUDDataController called");
-
- $('#dashBoardAdvanceSearch').hide();
-
+
+ $('#dashBoardAdvanceSearch').hide();
+
$scope.papCRUDTableDatasTemp = [];
$scope.dashboardAdsearch = { isDelected: 'both', stage: 'both', scope: "", ttlDate_after: "", ttlDate_before: ""};
PolicyAppService.getData('get_DashboardPolicyCRUDData').then(function(data){
- var j = data;
- $scope.data = JSON.parse(j.data);
- console.log($scope.data);
- $scope.papStatusCRUDDatas =JSON.parse($scope.data.papStatusCRUDData);
+ var j = data;
+ $scope.data = JSON.parse(j.data);
+ $scope.papStatusCRUDDatas =JSON.parse($scope.data.papStatusCRUDData);
if($scope.papStatusCRUDDatas != null){
for(i = 0; i < $scope.papStatusCRUDDatas.length; i++){
$scope.papCRUDTableDatasTemp.push($scope.papStatusCRUDDatas[i].map);
@@ -40,117 +38,106 @@ app.controller('policyDashboardCRUDDataController', function ($scope, PolicyAppS
$scope.papCRUDTableDatas = $scope.papCRUDTableDatasTemp;
}
-
- },function(error){
- console.log("failed");
- });
+
+ });
- $scope.papCRUDStatusDatas = {
- data : 'papCRUDTableDatas',
- enableFiltering: true,
- columnDefs: [{ field: 'id', displayName :'id'},
- {field: 'scope', displayName :'Scope'},
- {field: 'policyName', displayName :'Policy Name'},
- {field: 'version', displayName :'Version'},
- {field: 'stage', displayName :'Stage'},
- {field: 'createdBy', displayName :'Created By'},
- {field: 'deleted', displayName :'Deleted'},
- {field: 'deleteReasonCode', displayName :'Deleted Reason'},
- {field: 'deletedBy' , displayName :'Deleted By'},
- {field: 'modifiedBy' , displayName :'Modified By'},
- {field: 'createdDate', displayName :'Created Date'},
- {field: 'modifiedDate', displayName :'Modified Date'}
- ],
+ $scope.papCRUDStatusDatas = {
+ data : 'papCRUDTableDatas',
+ enableFiltering: true,
+ columnDefs: [{ field: 'id', displayName :'id'},
+ {field: 'scope', displayName :'Scope'},
+ {field: 'policyName', displayName :'Policy Name'},
+ {field: 'version', displayName :'Version'},
+ {field: 'stage', displayName :'Stage'},
+ {field: 'createdBy', displayName :'Created By'},
+ {field: 'deleted', displayName :'Deleted'},
+ {field: 'deleteReasonCode', displayName :'Deleted Reason'},
+ {field: 'deletedBy' , displayName :'Deleted By'},
+ {field: 'modifiedBy' , displayName :'Modified By'},
+ {field: 'createdDate', displayName :'Created Date'},
+ {field: 'modifiedDate', displayName :'Modified Date'}
+ ],
onRegisterApi: function(gridApi){
- $scope.gridApi = gridApi;
+ $scope.gridApi = gridApi;
}
- };
-
+ };
+
$('#ttlDate_after').datepicker({
- dateFormat: 'yy-mm-dd',
- changeMonth: true,
- changeYear: true,
- onSelect: function(date) {
- angular.element($('#ttlDate_after')).triggerHandler('input');
- }
+ dateFormat: 'yy-mm-dd',
+ changeMonth: true,
+ changeYear: true,
+ onSelect: function(date) {
+ angular.element($('#ttlDate_after')).triggerHandler('input');
+ }
});
$('#ttlDate_before').datepicker({
- dateFormat: 'yy-mm-dd',
- changeMonth: true,
- changeYear: true,
- onSelect: function(date) {
- angular.element($('#ttlDate_before')).triggerHandler('input');
- }
+ dateFormat: 'yy-mm-dd',
+ changeMonth: true,
+ changeYear: true,
+ onSelect: function(date) {
+ angular.element($('#ttlDate_before')).triggerHandler('input');
+ }
});
$scope.refresh = function(){
- $scope.modal('advancedSearch', true);
- $scope.temp.policy = "";
+ $scope.modal('advancedSearch', true);
+ $scope.temp.policy = "";
};
- $scope.advancedSearch = function(){
+ $scope.advancedSearch = function(){
- $('#dashBoardAdvanceSearch').toggle();
- if($('#advancedSearchArrow').hasClass('arrowdown')){
- $('#advancedSearchArrow').removeClass("arrowdown");
- $('#advancedSearchArrow').addClass("arrowup");
-
- }else{
- $('#advancedSearchArrow').removeClass("arrowup");
- $('#advancedSearchArrow').addClass("arrowdown");
- }
- }
-
+ $('#dashBoardAdvanceSearch').toggle();
+ if($('#advancedSearchArrow').hasClass('arrowdown')){
+ $('#advancedSearchArrow').removeClass("arrowdown");
+ $('#advancedSearchArrow').addClass("arrowup");
+
+ }else{
+ $('#advancedSearchArrow').removeClass("arrowup");
+ $('#advancedSearchArrow').addClass("arrowdown");
+ }
+ }
+
$scope.startAdvancedSearch = function(data){
-
- console.log("startAdvancedSearch called");
- console.log(data.isDelected);
- console.log(data.stage);
- console.log(data.scope);
- console.log(data.ttlDate_after);
- console.log(data.ttlDate_before);
-
- if(data.scope == null){
- return;
- }
-
+
+
+ if(data.scope == null){
+ return;
+ }
+
var uuu = "dashboardController/dashboardAdvancedSearch.htm";
var postData={policyData: data};
- $.ajax({
- type : 'POST',
- url : uuu,
- dataType: 'json',
- contentType: 'application/json',
- data: JSON.stringify(postData),
- success : function(data){
- console.log("dashboardAdvancedSearch data returned: " + data);
-
+ $.ajax({
+ type : 'POST',
+ url : uuu,
+ dataType: 'json',
+ contentType: 'application/json',
+ data: JSON.stringify(postData),
+ success : function(data){
+
$scope.$apply(function(){
-
- var j = data;
- $scope.data = JSON.parse(j.data);
- console.log($scope.data);
- $scope.papStatusCRUDDatas =JSON.parse($scope.data.policyStatusCRUDData);
-
- $scope.papCRUDTableDatasTemp = [];
-
- for(i = 0; i < $scope.papStatusCRUDDatas.length; i++){
- $scope.papCRUDTableDatasTemp.push($scope.papStatusCRUDDatas[i].map);
- }
-
- $scope.papCRUDTableDatas = $scope.papCRUDTableDatasTemp;
-
- $scope.gridApi.grid.refresh();
+
+ var j = data;
+ $scope.data = JSON.parse(j.data);
+ $scope.papStatusCRUDDatas =JSON.parse($scope.data.policyStatusCRUDData);
+
+ $scope.papCRUDTableDatasTemp = [];
+
+ for(i = 0; i < $scope.papStatusCRUDDatas.length; i++){
+ $scope.papCRUDTableDatasTemp.push($scope.papStatusCRUDDatas[i].map);
+ }
+
+ $scope.papCRUDTableDatas = $scope.papCRUDTableDatasTemp;
+
+ $scope.gridApi.grid.refresh();
});
- },
- error : function(data){
- console.log("dashboardAdvancedSearch Failed: data returned as " + data);
- }
- });
+ },
+ error : function(data){
+ }
+ });
};
}); \ No newline at end of file
diff --git a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/BRMSControllerDictController.js b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/BRMSControllerDictController.js
index 19b473294..a6de84efa 100644
--- a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/BRMSControllerDictController.js
+++ b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/BRMSControllerDictController.js
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP Policy Engine
* ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017, 2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -66,7 +66,7 @@ app.controller('editBRMSControllerController' , function ($scope, $modalInstanc
}
},
error : function(data){
- alert("Error while saving.");
+ Notification.error("Error while saving.");
}
});
}else{
diff --git a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/BRMSDependencyDictController.js b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/BRMSDependencyDictController.js
index 25a19baeb..f1157e878 100644
--- a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/BRMSDependencyDictController.js
+++ b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/BRMSDependencyDictController.js
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP Policy Engine
* ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017, 2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -66,7 +66,7 @@ app.controller('editBRMSDependencyController', function ($scope, $modalInstance,
}
},
error : function(data){
- alert("Error while saving.");
+ Notification.error("Error while saving.");
}
});
}else{
diff --git a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/BRMSParamDictController.js b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/BRMSParamDictController.js
index 678902840..f8d6d311e 100644
--- a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/BRMSParamDictController.js
+++ b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/BRMSParamDictController.js
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP Policy Engine
* ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017, 2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -60,7 +60,6 @@ app.controller('editBRMSParamController' , function ($scope, $modalInstance, mes
if(!regex.test(brmsParamDictionaryData.ruleName)) {
Notification.error("Enter Valid Rule Name without spaces or special characters");
}else{
- var file = $scope.MyFile;
var uuu = "saveDictionary/brms_dictionary/save_BRMSParam";
var postData={brmsParamDictionaryData: brmsParamDictionaryData, userid: userid};
$.ajax({
@@ -94,4 +93,4 @@ app.controller('editBRMSParamController' , function ($scope, $modalInstance, mes
$scope.close = function() {
$modalInstance.close();
};
-}); \ No newline at end of file
+});
diff --git a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/CLPepOptionsDictController.js b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/CLPepOptionsDictController.js
index 9bcf8dd6f..da389a8d2 100644
--- a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/CLPepOptionsDictController.js
+++ b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/CLPepOptionsDictController.js
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP Policy Engine
* ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017, 2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -85,7 +85,7 @@ app.controller('editPEPOptionsController', function ($scope, $modalInstance, me
}
},
error : function(data){
- alert("Error while saving.");
+ Notification.error("Error while saving.");
}
});
}
diff --git a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/CLServiceDictController.js b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/CLServiceDictController.js
index b8bc0f9d1..b3e2fe092 100644
--- a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/CLServiceDictController.js
+++ b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/CLServiceDictController.js
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP Policy Engine
* ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017, 2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -58,7 +58,7 @@ app.controller('editCLServiceController' , function ($scope, $modalInstance, me
}
},
error : function(data){
- alert("Error while saving.");
+ Notification.error("Error while saving.");
}
});
}
diff --git a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/CLSiteDictController.js b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/CLSiteDictController.js
index a673df5a2..cd2d89630 100644
--- a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/CLSiteDictController.js
+++ b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/CLSiteDictController.js
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP Policy Engine
* ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017, 2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -58,7 +58,7 @@ app.controller('editCLSiteController', function ($scope, $modalInstance, messag
}
},
error : function(data){
- alert("Error while saving.");
+ Notofication.error("Error while saving.");
}
});
}
diff --git a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/CLVarbindDictController.js b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/CLVarbindDictController.js
index 3b2a13f4a..44d62c5d9 100644
--- a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/CLVarbindDictController.js
+++ b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/CLVarbindDictController.js
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP Policy Engine
* ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017, 2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -58,7 +58,7 @@ app.controller('editCLVarbindController',function ($scope, $modalInstance, messa
}
},
error : function(data){
- alert("Error while saving.");
+ Notification.error("Error while saving.");
}
});
}
diff --git a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/CLVnfTypeDictController.js b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/CLVnfTypeDictController.js
index 0d033621b..eb71a10df 100644
--- a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/CLVnfTypeDictController.js
+++ b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/CLVnfTypeDictController.js
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP Policy Engine
* ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017, 2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -58,7 +58,7 @@ app.controller('editVnfTypeController' , function ($scope, $modalInstance, mess
}
},
error : function(data){
- alert("Error while saving.");
+ Notification.error("Error while saving.");
}
});
}
diff --git a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/CLVsclActionDictController.js b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/CLVsclActionDictController.js
index 106a8240d..cb78c4a38 100644
--- a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/CLVsclActionDictController.js
+++ b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/CLVsclActionDictController.js
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP Policy Engine
* ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017, 2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -59,7 +59,7 @@ app.controller('editVsclActionController' , function ($scope, $modalInstance, m
}
},
error : function(data){
- alert("Error while saving.");
+ Notification.error("Error while saving.");
}
});
}
diff --git a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/DecisionRainyDayDictController.js b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/DecisionRainyDayDictController.js
index b50becf0b..410ef26a0 100644
--- a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/DecisionRainyDayDictController.js
+++ b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/DecisionRainyDayDictController.js
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP Policy Engine
* ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017, 2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -52,7 +52,6 @@ app.controller('editRainyDayDictController' , function ($scope, $modalInstance,
$scope.editRainyDayTreatment = message.rainyDayDictionaryData;
$scope.saveDecisionTreatments = function(rainyDayDictionaryData) {
- var finalData = extend(rainyDayDictionaryData, $scope.treatmentDatas[0]);
var uuu = "saveDictionary/decision_dictionary/save_RainyDay";
var postData={rainyDayDictionaryData: rainyDayDictionaryData, userid: userid};
$.ajax({
@@ -72,18 +71,11 @@ app.controller('editRainyDayDictController' , function ($scope, $modalInstance,
}
},
error : function(data){
- alert("Error while saving.");
+ Notification.error("Error while saving.");
}
});
};
- function extend(obj, src) {
- for (var key in src) {
- if (src.hasOwnProperty(key)) obj[key] = src[key];
- }
- return obj;
- }
-
$scope.treatmentDatas = [{"userDataTypeValues" : $scope.treatments}];
$scope.addNewTreatment = function() {
$scope.treatments.push({});
@@ -97,4 +89,4 @@ app.controller('editRainyDayDictController' , function ($scope, $modalInstance,
$scope.close = function() {
$modalInstance.close();
};
-}); \ No newline at end of file
+});
diff --git a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/DecisionSettingsDictController.js b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/DecisionSettingsDictController.js
index fb2dd40af..99379fdd7 100644
--- a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/DecisionSettingsDictController.js
+++ b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/DecisionSettingsDictController.js
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP Policy Engine
* ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017, 2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -59,7 +59,7 @@ app.controller('editSettingsDictController' , function ($scope, $modalInstance,
}
},
error : function(data){
- alert("Error while saving.");
+ Notification.error("Error while saving.");
}
});
}
diff --git a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/DescriptiveSearchDictController.js b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/DescriptiveSearchDictController.js
index 266532a20..39d4058d8 100644
--- a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/DescriptiveSearchDictController.js
+++ b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/DescriptiveSearchDictController.js
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP Policy Engine
* ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017, 2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -86,7 +86,7 @@ app.controller('editDescriptiveScopeController' , function ($scope, $modalInstan
},
error : function(data){
- alert("Error while saving.");
+ Notification.error("Error while saving.");
}
});
}
diff --git a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/EnforcerDictController.js b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/EnforcerDictController.js
index 38f8f396f..2c6a6703c 100644
--- a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/EnforcerDictController.js
+++ b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/EnforcerDictController.js
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP Policy Engine
* ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017, 2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -17,7 +17,7 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-var editEnforcerTypeController = function ($scope, $modalInstance, message, UserInfoServiceDS2){
+var editEnforcerTypeController = function ($scope, $modalInstance, message, UserInfoServiceDS2, Notification){
if(message.enforcerDictionaryData==null)
$scope.label='Add Enforcing Type'
else{
@@ -25,14 +25,14 @@ var editEnforcerTypeController = function ($scope, $modalInstance, message, Use
$scope.disableCd=true;
}
$scope.editEnforcerType = message.enforcerDictionaryData;
-
- /*getting user info from session*/
- var userid = null;
- UserInfoServiceDS2.getFunctionalMenuStaticDetailSession()
- .then(function (response) {
- userid = response.userid;
- });
-
+
+ /*getting user info from session*/
+ var userid = null;
+ UserInfoServiceDS2.getFunctionalMenuStaticDetailSession()
+ .then(function (response) {
+ userid = response.userid;
+ });
+
$scope.saveEnforcerType = function(enforcerDictionaryData) {
var uuu = "saveDictionary/enforcer_dictionary/save_enforcerType";
var postData={enforcerDictionaryData: enforcerDictionaryData, userid: userid};
@@ -49,7 +49,7 @@ var editEnforcerTypeController = function ($scope, $modalInstance, message, Use
$modalInstance.close({enforcerDictionaryDatas:$scope.enforcerDictionaryDatas});
},
error : function(data){
- alert("Error while saving.");
+ Notification.error("Error while saving.");
}
});
};
diff --git a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/FWActionListDictController.js b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/FWActionListDictController.js
index 1eff96376..9d09959de 100644
--- a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/FWActionListDictController.js
+++ b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/FWActionListDictController.js
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP Policy Engine
* ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017, 2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -59,7 +59,7 @@ app.controller('editFWActionListController' , function ($scope, $modalInstance,
}
},
error : function(data){
- alert("Error while saving.");
+ Notification.error("Error while saving.");
}
});
}
diff --git a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/FWAddressGroupDictController.js b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/FWAddressGroupDictController.js
index e9e4c3f5d..442eae955 100644
--- a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/FWAddressGroupDictController.js
+++ b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/FWAddressGroupDictController.js
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP Policy Engine
* ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017, 2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -87,7 +87,7 @@ app.controller('editFWAddressGroupController' , function ($scope, $modalInstance
}
},
error : function(data){
- alert("Error while saving.");
+ Notification.error("Error while saving.");
}
});
}
diff --git a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/FWParentListDictController.js b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/FWParentListDictController.js
index 62b4a5b79..46f99762a 100644
--- a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/FWParentListDictController.js
+++ b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/FWParentListDictController.js
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP Policy Engine
* ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017, 2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -111,7 +111,7 @@ app.controller('editFWParentListController' , function ($scope, $modalInstance,
}
},
error : function(data){
- alert("Error while saving.");
+ Notification("Error while saving.");
}
});
}
diff --git a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/FWPortListDictController.js b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/FWPortListDictController.js
index 66caf4d8a..99e543034 100644
--- a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/FWPortListDictController.js
+++ b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/FWPortListDictController.js
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP Policy Engine
* ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017, 2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -59,7 +59,7 @@ app.controller('editFWPortListController' , function ($scope, $modalInstance, me
}
},
error : function(data){
- alert("Error while saving.");
+ Notification.error("Error while saving.");
}
});
}
diff --git a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/FWPrefixListDictController.js b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/FWPrefixListDictController.js
index 1925e5f48..485af3ab6 100644
--- a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/FWPrefixListDictController.js
+++ b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/FWPrefixListDictController.js
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP Policy Engine
* ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017, 2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -60,7 +60,7 @@ app.controller('editFWPrefixListController' , function ($scope, $modalInstance,
}
},
error : function(data){
- alert("Error while saving.");
+ Notification.error("Error while saving.");
}
});
}else{
diff --git a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/FWProtocolListDictController.js b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/FWProtocolListDictController.js
index 82b1be794..5d382c62d 100644
--- a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/FWProtocolListDictController.js
+++ b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/FWProtocolListDictController.js
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP Policy Engine
* ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017, 2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -58,7 +58,7 @@ app.controller('editFWProtocolListController' , function ($scope, $modalInstance
}
},
error : function(data){
- alert("Error while saving.");
+ Notification.error("Error while saving.");
}
});
}
diff --git a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/FWSecurityZoneDictController.js b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/FWSecurityZoneDictController.js
index 7d8da9d2a..a5238eeb4 100644
--- a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/FWSecurityZoneDictController.js
+++ b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/FWSecurityZoneDictController.js
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP Policy Engine
* ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017, 2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -24,44 +24,44 @@ app.controller('editfwSecurityZoneController' , function ($scope, $modalInstanc
$scope.label='Edit Security Zone'
$scope.disableCd=true;
}
-
- /*getting user info from session*/
- var userid = null;
- UserInfoServiceDS2.getFunctionalMenuStaticDetailSession()
- .then(function (response) {
- userid = response.userid;
- });
-
+
+ /*getting user info from session*/
+ var userid = null;
+ UserInfoServiceDS2.getFunctionalMenuStaticDetailSession()
+ .then(function (response) {
+ userid = response.userid;
+ });
+
$scope.editSecurityZone = message.securityZoneDictionaryData;
$scope.saveSecurityZone = function(securityZoneDictionaryData) {
- var regex = new RegExp("^[a-zA-Z0-9_]*$");
- if(!regex.test(securityZoneDictionaryData.zoneName)) {
- Notification.error("Enter Valid Security Zone Name without spaces or special characters");
- }else{
- var uuu = "saveDictionary/fw_dictionary/save_securityZone";
- var postData={securityZoneDictionaryData: securityZoneDictionaryData, userid: userid};
- $.ajax({
- type : 'POST',
- url : uuu,
- dataType: 'json',
- contentType: 'application/json',
- data: JSON.stringify(postData),
- success : function(data){
- $scope.$apply(function(){
- $scope.securityZoneDictionaryDatas=data.securityZoneDictionaryDatas;});
- if($scope.securityZoneDictionaryDatas == "Duplicate"){
- Notification.error("FW SecurityZone Dictionary exists with Same Zone Name.")
- }else{
- console.log($scope.securityZoneDictionaryDatas);
- $modalInstance.close({securityZoneDictionaryDatas:$scope.securityZoneDictionaryDatas});
- }
- },
- error : function(data){
- alert("Error while saving.");
- }
- });
- }
+ var regex = new RegExp("^[a-zA-Z0-9_]*$");
+ if(!regex.test(securityZoneDictionaryData.zoneName)) {
+ Notification.error("Enter Valid Security Zone Name without spaces or special characters");
+ }else{
+ var uuu = "saveDictionary/fw_dictionary/save_securityZone";
+ var postData={securityZoneDictionaryData: securityZoneDictionaryData, userid: userid};
+ $.ajax({
+ type : 'POST',
+ url : uuu,
+ dataType: 'json',
+ contentType: 'application/json',
+ data: JSON.stringify(postData),
+ success : function(data){
+ $scope.$apply(function(){
+ $scope.securityZoneDictionaryDatas=data.securityZoneDictionaryDatas;});
+ if($scope.securityZoneDictionaryDatas == "Duplicate"){
+ Notification.error("FW SecurityZone Dictionary exists with Same Zone Name.")
+ }else{
+ console.log($scope.securityZoneDictionaryDatas);
+ $modalInstance.close({securityZoneDictionaryDatas:$scope.securityZoneDictionaryDatas});
+ }
+ },
+ error : function(data){
+ Notification.error("Error while saving.");
+ }
+ });
+ }
};
$scope.close = function() {
diff --git a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/FWServiceGroupDictController.js b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/FWServiceGroupDictController.js
index 43219bab5..dc3ae6e7d 100644
--- a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/FWServiceGroupDictController.js
+++ b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/FWServiceGroupDictController.js
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP Policy Engine
* ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017, 2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -87,7 +87,7 @@ app.controller('editFWServiceGroupController' , function ($scope, $modalInstanc
}
},
error : function(data){
- alert("Error while saving.");
+ Notification.error("Error while saving.");
}
});
}
diff --git a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/FWServiceListDictController.js b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/FWServiceListDictController.js
index 0a6e8ba64..58b7be300 100644
--- a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/FWServiceListDictController.js
+++ b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/FWServiceListDictController.js
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP Policy Engine
* ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017, 2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -104,7 +104,7 @@ app.controller('editFWServiceListController' , function ($scope, $modalInstance
}
},
error : function(data){
- alert("Error while saving.");
+ Notification.error("Error while saving.");
}
});
}
diff --git a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/FWTagListDictController.js b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/FWTagListDictController.js
index c70b3dd2f..7596e07a1 100644
--- a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/FWTagListDictController.js
+++ b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/FWTagListDictController.js
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP Policy Engine
* ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017, 2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -75,7 +75,7 @@ app.controller('editFWTagListController' , function ($scope, $modalInstance, mes
}
},
error : function(data){
- alert("Error while saving.");
+ Notification.error("Error while saving.");
}
});
}
diff --git a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/FWTagPickerListDictController.js b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/FWTagPickerListDictController.js
index ed6571d4d..d813602fc 100644
--- a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/FWTagPickerListDictController.js
+++ b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/FWTagPickerListDictController.js
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP Policy Engine
* ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017, 2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -121,7 +121,7 @@ app.controller('editFWTagPickerController' , function ($scope, $modalInstance,
},
error : function(data){
- alert("Error while saving.");
+ Notification.error("Error while saving.");
}
});
}
diff --git a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/FWTermListDictController.js b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/FWTermListDictController.js
index 73084195b..98a237ae2 100644
--- a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/FWTermListDictController.js
+++ b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/FWTermListDictController.js
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP Policy Engine
* ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017, 2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -142,77 +142,54 @@ app.controller('editFWTermListController' , function ($scope, $modalInstance, me
PolicyAppService.getData('getDictionary/get_PrefixListDataByName').then(function (data) {
var j = data;
$scope.data = JSON.parse(j.data);
- console.log($scope.data);
$scope.prefixListDictionaryDatas = JSON.parse($scope.data.prefixListDictionaryDatas);
- console.log($scope.prefixListDictionaryDatas);
for(i = 0; i < $scope.prefixListDictionaryDatas.length; i++){
var key = $scope.prefixListDictionaryDatas[i];
$scope.groupAddresses.push(key);
}
- }, function (error) {
- console.log("failed");
});
PolicyAppService.getData('getDictionary/get_ZoneDictionaryDataByName').then(function (data) {
var j = data;
$scope.data = JSON.parse(j.data);
- console.log($scope.data);
$scope.zoneDictionaryDatas = JSON.parse($scope.data.zoneDictionaryDatas);
- console.log($scope.zoneDictionaryDatas);
- }, function (error) {
- console.log("failed");
});
PolicyAppService.getData('getDictionary/get_AddressGroupDictionaryDataByName').then(function (data) {
var j = data;
$scope.data = JSON.parse(j.data);
- console.log($scope.data);
$scope.addressGroupDictionaryDatas = JSON.parse($scope.data.addressGroupDictionaryDatas);
- console.log($scope.addressGroupDictionaryDatas);
for(i = 0; i < $scope.addressGroupDictionaryDatas.length; i++){
var key = $scope.addressGroupDictionaryDatas[i];
$scope.groupAddresses.push(key);
}
- }, function (error) {
- console.log("failed");
});
PolicyAppService.getData('getDictionary/get_ServiceListDictionaryDataByName').then(function (data) {
var j = data;
$scope.data = JSON.parse(j.data);
- console.log($scope.data);
$scope.serviceListDictionaryDatas = JSON.parse($scope.data.serviceListDictionaryDatas);
- console.log($scope.serviceListDictionaryDatas);
for(i = 0; i < $scope.serviceListDictionaryDatas.length; i++){
var key = $scope.serviceListDictionaryDatas[i];
$scope.groupServices.push(key);
}
- }, function (error) {
- console.log("failed");
});
PolicyAppService.getData('getDictionary/get_ServiceGroupDictionaryDataByName').then(function (data) {
var j = data;
$scope.data = JSON.parse(j.data);
- console.log($scope.data);
$scope.serviceGroupDictionaryDatas = JSON.parse($scope.data.serviceGroupDictionaryDatas);
- console.log($scope.serviceGroupDictionaryDatas);
for(i = 0; i < $scope.serviceGroupDictionaryDatas.length; i++){
var key = $scope.serviceGroupDictionaryDatas[i];
$scope.groupServices.push(key);
}
}, function (error) {
- console.log("failed");
});
PolicyAppService.getData('getDictionary/get_ActionListDictionaryDataByName').then(function (data) {
var j = data;
$scope.data = JSON.parse(j.data);
- console.log($scope.data);
$scope.actionListDictionaryDatas = JSON.parse($scope.data.actionListDictionaryDatas);
- console.log($scope.actionListDictionaryDatas);
- }, function (error) {
- console.log("failed");
});
@@ -251,12 +228,11 @@ app.controller('editFWTermListController' , function ($scope, $modalInstance, me
if($scope.termListDictionaryDatas == "Duplicate"){
Notification.error("FW TermList Dictionary exists with Same Term Name.")
}else{
- console.log($scope.termListDictionaryDatas);
$modalInstance.close({termListDictionaryDatas:$scope.termListDictionaryDatas});
}
},
error : function(data){
- alert("Error while saving.");
+ Notification.error("Error while saving.");
}
});
}
diff --git a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/FWZoneDictController.js b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/FWZoneDictController.js
index bdb10f55e..4d1e6057b 100644
--- a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/FWZoneDictController.js
+++ b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/FWZoneDictController.js
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP Policy Engine
* ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017, 2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -58,7 +58,7 @@ app.controller('editFWZoneController' , function ($scope, $modalInstance, messa
}
},
error : function(data){
- alert("Error while saving.");
+ Notification.error("Error while saving.");
}
});
}
diff --git a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/MSConfigNameDictController.js b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/MSConfigNameDictController.js
index a1b703880..743681afd 100644
--- a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/MSConfigNameDictController.js
+++ b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/MSConfigNameDictController.js
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP Policy Engine
* ================================================================================
- * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2018, 2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -59,7 +59,7 @@ app.controller('editMSConfigController' , function ($scope, $modalInstance, mes
}
},
error : function(data){
- alert("Error while saving.");
+ Notification.error("Error while saving.");
}
});
}
diff --git a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/MSDcaeUUIDDictController.js b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/MSDcaeUUIDDictController.js
index 6fbb9b3e5..cd9a78525 100644
--- a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/MSDcaeUUIDDictController.js
+++ b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/MSDcaeUUIDDictController.js
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP Policy Engine
* ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017, 2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -58,7 +58,7 @@ app.controller('editDCAEuuidController' , function ($scope, $modalInstance, mess
}
},
error : function(data){
- alert("Error while saving.");
+ Notification.error("Error while saving.");
}
});
}
diff --git a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/MSDictionaryController.js b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/MSDictionaryController.js
index 21b89697d..a3a9349c5 100644
--- a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/MSDictionaryController.js
+++ b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/MSDictionaryController.js
@@ -59,7 +59,7 @@ app.controller('editMSDictController' , function ($scope, $modalInstance, messa
}
},
error : function(data){
- alert("Error while saving.");
+ Notification.error("Error while saving.");
}
});
}
diff --git a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/MSHeaderDefaultValuesDictController.js b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/MSHeaderDefaultValuesDictController.js
index 960d76bd4..ce84afd84 100644
--- a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/MSHeaderDefaultValuesDictController.js
+++ b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/MSHeaderDefaultValuesDictController.js
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP Policy Engine
* ================================================================================
- * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2018, 2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -17,118 +17,91 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-app.controller('editMSHeaderDefaultValuesController' , function ($scope, $modalInstance, message, PolicyAppService, UserInfoServiceDS2, Notification){
- if(message.modelAttributeDictionaryData==null)
- $scope.label='Set Header Default Values'
- else{
- $scope.label='Edit Header Default Values'
- $scope.disableCd=true;
- }
+app.controller('editMSHeaderDefaultValuesController' ,
+ function ($scope, $modalInstance, message, PolicyAppService, UserInfoServiceDS2, Notification){
+ if(message.modelAttributeDictionaryData==null)
+ $scope.label='Set Header Default Values'
+ else{
+ $scope.label='Edit Header Default Values'
+ $scope.disableCd=true;
+ }
- PolicyAppService.getData('getDictionary/get_MicroServiceHeaderDefaultsData').then(function (data) {
- var j = data;
- $scope.data = JSON.parse(j.data);
- console.log($scope.data);
- $scope.microServiceHeaderDefaultDatas = JSON.parse($scope.data.microServiceHeaderDefaultDatas);
- console.log("microServiceHeaderDefaultDatas:" + $scope.microServiceHeaderDefaultDatas);
- }, function (error) {
- console.log("failed");
- });
+ PolicyAppService.getData('getDictionary/get_MicroServiceHeaderDefaultsData').then(function (data) {
+ var j = data;
+ $scope.data = JSON.parse(j.data);
+ $scope.microServiceHeaderDefaultDatas = JSON.parse($scope.data.microServiceHeaderDefaultDatas);
+ });
- PolicyAppService.getData('getDictionary/get_MicroServiceModelsDataServiceVersion').then(function (data) {
- var j = data;
- $scope.data = JSON.parse(j.data);
- console.log($scope.data);
- $scope.microServiceModelsDictionaryDatas = JSON.parse($scope.data.microServiceModelsDictionaryDatas);
- console.log($scope.microServiceModelsDictionaryDatas);
- }, function (error) {
- console.log("failed");
- });
-
- PolicyAppService.getData('getDictionary/get_RiskTypeDataByName').then(function (data) {
- var j = data;
- $scope.data = JSON.parse(j.data);
- console.log("riskTypeDictionaryDatas = " + $scope.data);
- $scope.riskTypeDictionaryDatas = JSON.parse($scope.data.riskTypeDictionaryDatas);
- console.log($scope.riskTypeDictionaryDatas);
- }, function (error) {
- console.log("failed");
- });
+ PolicyAppService.getData('getDictionary/get_MicroServiceModelsDataServiceVersion').then(function (data) {
+ var j = data;
+ $scope.data = JSON.parse(j.data);
+ $scope.microServiceModelsDictionaryDatas = JSON.parse($scope.data.microServiceModelsDictionaryDatas);
+ });
+
+ PolicyAppService.getData('getDictionary/get_RiskTypeDataByName').then(function (data) {
+ var j = data;
+ $scope.data = JSON.parse(j.data);
+ $scope.riskTypeDictionaryDatas = JSON.parse($scope.data.riskTypeDictionaryDatas);
+ });
- PolicyAppService.getData('getDictionary/get_RiskTypeDataByName').then(function (data) {
- var j = data;
- $scope.data = JSON.parse(j.data);
- console.log("riskTypeDictionaryDatas: " + $scope.data);
- $scope.riskTypeDictionaryDatas = JSON.parse($scope.data.riskTypeDictionaryDatas);
- console.log($scope.riskTypeDictionaryDatas);
- }, function (error) {
- console.log("failed");
- });
-
- PolicyAppService.getData('getDictionary/get_OnapNameDataByName').then(function (data) {
- var j = data;
- $scope.data = JSON.parse(j.data);
- console.log($scope.data);
- $scope.onapNameDictionaryDatas = JSON.parse($scope.data.onapNameDictionaryDatas);
- console.log($scope.onapNameDictionaryDatas);
- }, function (error) {
- console.log("failed");
- });
+ PolicyAppService.getData('getDictionary/get_RiskTypeDataByName').then(function (data) {
+ var j = data;
+ $scope.data = JSON.parse(j.data);
+ $scope.riskTypeDictionaryDatas = JSON.parse($scope.data.riskTypeDictionaryDatas);
+ });
+
+ PolicyAppService.getData('getDictionary/get_OnapNameDataByName').then(function (data) {
+ var j = data;
+ $scope.data = JSON.parse(j.data);
+ $scope.onapNameDictionaryDatas = JSON.parse($scope.data.onapNameDictionaryDatas);
+ });
- PolicyAppService.getData('get_DCAEPriorityValues').then(function (data) {
- var j = data;
- $scope.data = JSON.parse(j.data);
- console.log($scope.data);
- $scope.priorityDatas = JSON.parse($scope.data.priorityDatas);
- console.log($scope.priorityDatas);
- }, function (error) {
- console.log("failed");
- });
-
- /*getting user info from session*/
- var userid = null;
- UserInfoServiceDS2.getFunctionalMenuStaticDetailSession()
- .then(function (response) {
- userid = response.userid;
- });
-
- $scope.editHeaderDefaults = message.modelAttributeDictionaryData;
- $scope.editModelAttribute1 = {microservice: []};
- if($scope.edit){
- if(message.modelAttributeDictionaryData.groupList != null){
- var splitValue = message.modelAttributeDictionaryData.groupList.split(",");
- console.log(splitValue);
- }
- }
- $scope.saveHeaderDefaults = function(editHeaderDefaultsData) {
- console.log("editHeaderDefaultsData :" + editHeaderDefaultsData);
- var uuu = "saveDictionary/ms_dictionary/save_headerDefaults";
- var postData={modelAttributeDictionaryData: editHeaderDefaultsData, userid: userid};
- $.ajax({
- type : 'POST',
- url : uuu,
- dataType: 'json',
- contentType: 'application/json',
- data: JSON.stringify(postData),
- success : function(data){
- $scope.$apply(function(){
- $scope.microServiceHeaderDefaultDatas=data.microServiceHeaderDefaultDatas;});
- console.log("microServiceHeaderDefaultDatas returned after saved: " + $scope.microServiceHeaderDefaultDatas);
- if($scope.microServiceAttributeDictionaryDatas == "Duplicate"){
- Notification.error("Model Attribute Dictionary exists with Same Attribute Name.")
- }else{
- console.log($scope.microServiceHeaderDefaultDatas);
- $modalInstance.close({microServiceHeaderDefaultDatas:$scope.microServiceHeaderDefaultDatas});
- }
- },
- error : function(data){
- alert("Error while saving.");
- }
- });
-
- };
+ PolicyAppService.getData('get_DCAEPriorityValues').then(function (data) {
+ var j = data;
+ $scope.data = JSON.parse(j.data);
+ $scope.priorityDatas = JSON.parse($scope.data.priorityDatas);
+ });
+
+ /*getting user info from session*/
+ var userid = null;
+ UserInfoServiceDS2.getFunctionalMenuStaticDetailSession()
+ .then(function (response) {
+ userid = response.userid;
+ });
+
+ $scope.editHeaderDefaults = message.modelAttributeDictionaryData;
+ $scope.editModelAttribute1 = {microservice: []};
+ if($scope.edit){
+ if(message.modelAttributeDictionaryData.groupList != null){
+ var splitValue = message.modelAttributeDictionaryData.groupList.split(",");
+ }
+ }
+ $scope.saveHeaderDefaults = function(editHeaderDefaultsData) {
+ var uuu = "saveDictionary/ms_dictionary/save_headerDefaults";
+ var postData={modelAttributeDictionaryData: editHeaderDefaultsData, userid: userid};
+ $.ajax({
+ type : 'POST',
+ url : uuu,
+ dataType: 'json',
+ contentType: 'application/json',
+ data: JSON.stringify(postData),
+ success : function(data){
+ $scope.$apply(function(){
+ $scope.microServiceHeaderDefaultDatas=data.microServiceHeaderDefaultDatas;});
+ if($scope.microServiceAttributeDictionaryDatas == "Duplicate"){
+ Notification.error("Model Attribute Dictionary exists with Same Attribute Name.")
+ }else{
+ $modalInstance.close({microServiceHeaderDefaultDatas:$scope.microServiceHeaderDefaultDatas});
+ }
+ },
+ error : function(data){
+ Notification.error("Error while saving.");
+ }
+ });
+
+ };
- $scope.close = function() {
- $modalInstance.close();
- };
- }); \ No newline at end of file
+ $scope.close = function() {
+ $modalInstance.close();
+ };
+ }); \ No newline at end of file
diff --git a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/MSLocationDictController.js b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/MSLocationDictController.js
index fbd8e35e2..198ea480e 100644
--- a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/MSLocationDictController.js
+++ b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/MSLocationDictController.js
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP Policy Engine
* ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017, 2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -58,7 +58,7 @@ app.controller('editMSLocationController' , function ($scope, $modalInstance, m
}
},
error : function(data){
- alert("Error while saving.");
+ Notification.error("Error while saving.");
}
});
}
diff --git a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/ModelAttributeDictController.js b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/ModelAttributeDictController.js
index 242615e09..c03c7de1e 100644
--- a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/ModelAttributeDictController.js
+++ b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/ModelAttributeDictController.js
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP Policy Engine
* ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017, 2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -84,7 +84,7 @@ app.controller('editModelAttributeController' , function ($scope, $modalInstanc
}
},
error : function(data){
- alert("Error while saving.");
+ Notification.error("Error while saving.");
}
});
}
diff --git a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/PSClosedLoopDictController.js b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/PSClosedLoopDictController.js
index 8377a87f9..d2357ba8b 100644
--- a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/PSClosedLoopDictController.js
+++ b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/PSClosedLoopDictController.js
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP Policy Engine
* ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017, 2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -58,7 +58,7 @@ app.controller('editPSClosedLoopController' , function ($scope, $modalInstance,
}
},
error : function(data){
- alert("Error while saving.");
+ Notification.error("Error while saving.");
}
});
}
diff --git a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/PSGroupPolicyScopeDictController.js b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/PSGroupPolicyScopeDictController.js
index b456c57a0..6b65a5938 100644
--- a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/PSGroupPolicyScopeDictController.js
+++ b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/PSGroupPolicyScopeDictController.js
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP Policy Engine
* ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017, 2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -17,8 +17,9 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-app.controller('editPSGroupPolicyScopeController' , function ($scope, $modalInstance, message, PolicyAppService, UserInfoServiceDS2, Notification){
- $scope.edit = false;
+app.controller('editPSGroupPolicyScopeController' ,
+ function ($scope, $modalInstance, message, PolicyAppService, UserInfoServiceDS2, Notification){
+ $scope.edit = false;
if(message.groupPolicyScopeListData==null)
$scope.label='Add New Group Policy Scope'
else{
@@ -26,108 +27,89 @@ app.controller('editPSGroupPolicyScopeController' , function ($scope, $modalIns
$scope.disableCd=true;
$scope.edit = true;
}
-
+
PolicyAppService.getData('getDictionary/get_PSServiceDataByName').then(function (data) {
- var j = data;
- $scope.data = JSON.parse(j.data);
- console.log($scope.data);
- $scope.psServiceDictionaryDatas = JSON.parse($scope.data.psServiceDictionaryDatas);
- console.log($scope.psServiceDictionaryDatas);
- }, function (error) {
- console.log("failed");
+ var j = data;
+ $scope.data = JSON.parse(j.data);
+ $scope.psServiceDictionaryDatas = JSON.parse($scope.data.psServiceDictionaryDatas);
});
PolicyAppService.getData('getDictionary/get_PSTypeDataByName').then(function (data) {
- var j = data;
- $scope.data = JSON.parse(j.data);
- console.log($scope.data);
- $scope.psTypeDictionaryDatas = JSON.parse($scope.data.psTypeDictionaryDatas);
- console.log($scope.psTypeDictionaryDatas);
- }, function (error) {
- console.log("failed");
+ var j = data;
+ $scope.data = JSON.parse(j.data);
+ $scope.psTypeDictionaryDatas = JSON.parse($scope.data.psTypeDictionaryDatas);
});
PolicyAppService.getData('getDictionary/get_PSResourceDataByName').then(function (data) {
- var j = data;
- $scope.data = JSON.parse(j.data);
- console.log($scope.data);
- $scope.psResourceDictionaryDatas = JSON.parse($scope.data.psResourceDictionaryDatas);
- console.log($scope.psResourceDictionaryDatas);
- }, function (error) {
- console.log("failed");
+ var j = data;
+ $scope.data = JSON.parse(j.data);
+ $scope.psResourceDictionaryDatas = JSON.parse($scope.data.psResourceDictionaryDatas);
});
PolicyAppService.getData('getDictionary/get_PSClosedLoopDataByName').then(function (data) {
- var j = data;
- $scope.data = JSON.parse(j.data);
- console.log($scope.data);
- $scope.psClosedLoopDictionaryDatas = JSON.parse($scope.data.psClosedLoopDictionaryDatas);
- console.log($scope.psClosedLoopDictionaryDatas);
- }, function (error) {
- console.log("failed");
+ var j = data;
+ $scope.data = JSON.parse(j.data);
+ $scope.psClosedLoopDictionaryDatas = JSON.parse($scope.data.psClosedLoopDictionaryDatas);
});
-
- /*getting user info from session*/
- var userid = null;
- UserInfoServiceDS2.getFunctionalMenuStaticDetailSession()
- .then(function (response) {
- userid = response.userid;
- });
+
+ /*getting user info from session*/
+ var userid = null;
+ UserInfoServiceDS2.getFunctionalMenuStaticDetailSession()
+ .then(function (response) {
+ userid = response.userid;
+ });
$scope.editPSGroupPolicyScope = message.groupPolicyScopeListData;
$scope.editPSGroupPolicyScope1 = {resource: [], type:[], service: [], closedloop: []};
if($scope.edit){
- if(message.groupPolicyScopeListData.groupList != null){
- var splitValue = message.groupPolicyScopeListData.groupList.split(",");
- console.log(splitValue);
- $scope.splittedGroupListValues = [];
- var splitResource = splitValue[0].split("=");
- $scope.editPSGroupPolicyScope1.resource.push(splitResource[1]);
- var splitType = splitValue[1].split("=");
- $scope.editPSGroupPolicyScope1.type.push(splitType[1]);
- var splitService = splitValue[2].split("=");
- $scope.editPSGroupPolicyScope1.service.push(splitService[1]);
- var splitCloop = splitValue[3].split("=");
- $scope.editPSGroupPolicyScope1.closedloop.push(splitCloop[1]);
- }
+ if(message.groupPolicyScopeListData.groupList != null){
+ var splitValue = message.groupPolicyScopeListData.groupList.split(",");
+ $scope.splittedGroupListValues = [];
+ var splitResource = splitValue[0].split("=");
+ $scope.editPSGroupPolicyScope1.resource.push(splitResource[1]);
+ var splitType = splitValue[1].split("=");
+ $scope.editPSGroupPolicyScope1.type.push(splitType[1]);
+ var splitService = splitValue[2].split("=");
+ $scope.editPSGroupPolicyScope1.service.push(splitService[1]);
+ var splitCloop = splitValue[3].split("=");
+ $scope.editPSGroupPolicyScope1.closedloop.push(splitCloop[1]);
+ }
}
$scope.savePSGroupPolicyScope = function(groupPolicyScopeListData, groupPolicyScopeListData1) {
- var regex = new RegExp("^[a-zA-Z0-9_]*$");
- if(!regex.test(groupPolicyScopeListData.groupName)) {
- Notification.error("Enter Valid Policy Scope Group Name without spaces or special characters");
- }else{
- console.log(groupPolicyScopeListData1);
- if(groupPolicyScopeListData1.resource[0] != undefined && groupPolicyScopeListData1.type[0] != undefined && groupPolicyScopeListData1.service[0] != undefined && groupPolicyScopeListData1.closedloop[0] != undefined){
- var uuu = "saveDictionary/ps_dictionary/save_psGroupPolicyScope";
- var postData={groupPolicyScopeListData: groupPolicyScopeListData,
- groupPolicyScopeListData1: groupPolicyScopeListData1, userid: userid};
- $.ajax({
- type : 'POST',
- url : uuu,
- dataType: 'json',
- contentType: 'application/json',
- data: JSON.stringify(postData),
- success : function(data){
- $scope.$apply(function(){
- $scope.groupPolicyScopeListDatas=data.groupPolicyScopeListDatas;});
- if($scope.groupPolicyScopeListDatas == "Duplicate"){
- Notification.error("GroupPolicyScope Dictionary exists with Same Group Name.")
- }else if($scope.groupPolicyScopeListDatas == "DuplicateGroup"){
- Notification.error("GroupPolicyScope Dictionary exists with Same Group List.")
- }else{
- console.log($scope.groupPolicyScopeListDatas);
- $modalInstance.close({groupPolicyScopeListDatas:$scope.groupPolicyScopeListDatas});
- }
- },
- error : function(data){
- Notification.error("Error while saving.");
- }
- });
- }else{
- Notification.error("Please Select all the required fields to Save");
- }
- }
+ var regex = new RegExp("^[a-zA-Z0-9_]*$");
+ if(!regex.test(groupPolicyScopeListData.groupName)) {
+ Notification.error("Enter Valid Policy Scope Group Name without spaces or special characters");
+ }else{
+ if(groupPolicyScopeListData1.resource[0] != undefined && groupPolicyScopeListData1.type[0] != undefined && groupPolicyScopeListData1.service[0] != undefined && groupPolicyScopeListData1.closedloop[0] != undefined){
+ var uuu = "saveDictionary/ps_dictionary/save_psGroupPolicyScope";
+ var postData={groupPolicyScopeListData: groupPolicyScopeListData,
+ groupPolicyScopeListData1: groupPolicyScopeListData1, userid: userid};
+ $.ajax({
+ type : 'POST',
+ url : uuu,
+ dataType: 'json',
+ contentType: 'application/json',
+ data: JSON.stringify(postData),
+ success : function(data){
+ $scope.$apply(function(){
+ $scope.groupPolicyScopeListDatas=data.groupPolicyScopeListDatas;});
+ if($scope.groupPolicyScopeListDatas == "Duplicate"){
+ Notification.error("GroupPolicyScope Dictionary exists with Same Group Name.")
+ }else if($scope.groupPolicyScopeListDatas == "DuplicateGroup"){
+ Notification.error("GroupPolicyScope Dictionary exists with Same Group List.")
+ }else{
+ $modalInstance.close({groupPolicyScopeListDatas:$scope.groupPolicyScopeListDatas});
+ }
+ },
+ error : function(data){
+ Notification.error("Error while saving.");
+ }
+ });
+ }else{
+ Notification.error("Please Select all the required fields to Save");
+ }
+ }
};
$scope.close = function() {
diff --git a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/PSResourceDictController.js b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/PSResourceDictController.js
index 7aa028397..1afdcd6eb 100644
--- a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/PSResourceDictController.js
+++ b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/PSResourceDictController.js
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP Policy Engine
* ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017, 2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -58,7 +58,7 @@ app.controller('editPSResourceController' , function ($scope, $modalInstance, me
}
},
error : function(data){
- alert("Error while saving.");
+ Notification.error("Error while saving.");
}
});
}
diff --git a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/PSServiceDictController.js b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/PSServiceDictController.js
index 53c6776f5..7946a145f 100644
--- a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/PSServiceDictController.js
+++ b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/PSServiceDictController.js
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP Policy Engine
* ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017, 2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -58,7 +58,7 @@ app.controller('editPSServiceController' , function ($scope, $modalInstance, mes
}
},
error : function(data){
- alert("Error while saving.");
+ Notification.error("Error while saving.");
}
});
}
diff --git a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/PSTypeDictController.js b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/PSTypeDictController.js
index 9305e23e2..de87f130b 100644
--- a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/PSTypeDictController.js
+++ b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/PSTypeDictController.js
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP Policy Engine
* ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017, 2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -59,7 +59,7 @@ app.controller('editPSTypeController' , function ($scope, $modalInstance, messag
}
},
error : function(data){
- alert("Error while saving.");
+ Notification.error("Error while saving.");
}
});
}
diff --git a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/RiskTypeDictController.js b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/RiskTypeDictController.js
index 48ff66339..565091977 100644
--- a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/RiskTypeDictController.js
+++ b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/RiskTypeDictController.js
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP Policy Engine
* ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017, 2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -58,7 +58,7 @@ app.controller('editRiskTypeController', function ($scope, $modalInstance, messa
}
},
error : function(data){
- alert("Error while saving.");
+ Notification.error("Error while saving.");
}
});
}
diff --git a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/SafePolicyWarningDictController.js b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/SafePolicyWarningDictController.js
index e07262298..53810283c 100644
--- a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/SafePolicyWarningDictController.js
+++ b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/SafePolicyWarningDictController.js
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP Policy Engine
* ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017, 2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -91,7 +91,7 @@ app.controller('editSafePolicyWarningController' , function ($scope, $modalInst
}
},
error : function(data){
- alert("Error while saving.");
+ Notification.error("Error while saving.");
}
});
}
diff --git a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/actionPolicyDictController.js b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/actionPolicyDictController.js
index 572211997..4614ed5f4 100644
--- a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/actionPolicyDictController.js
+++ b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/actionPolicyDictController.js
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP Policy Engine
* ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017, 2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -84,7 +84,7 @@ app.controller('editActionPolicyDictController', function ($scope, $modalInstanc
}
},
error : function(data){
- alert("Error while saving.");
+ Notification.error("Error while saving.");
}
});
}
diff --git a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/attributeDictController.js b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/attributeDictController.js
index 4ca3b2266..3e54dd339 100644
--- a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/attributeDictController.js
+++ b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/attributeDictController.js
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP Policy Engine
* ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017, 2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -55,7 +55,6 @@ app.controller('editAttributeController' ,function ($scope, $modalInstance, mess
if(!regex.test(attributeDictionaryData.xacmlId)) {
Notification.error("Enter Valid Attribute Name without spaces or special characters");
}else{
- var finalData = extend(attributeDictionaryData, $scope.attributeDatas[0]);
var uuu = "saveDictionary/attribute_dictionary/save_attribute";
var postData={attributeDictionaryData: attributeDictionaryData, userid: userid};
$.ajax({
@@ -75,7 +74,7 @@ app.controller('editAttributeController' ,function ($scope, $modalInstance, mess
}
},
error : function(data){
- alert("Error while saving.");
+ Notification.error("Error while saving.");
}
});
}
@@ -101,4 +100,4 @@ app.controller('editAttributeController' ,function ($scope, $modalInstance, mess
$scope.close = function() {
$modalInstance.close();
};
-}); \ No newline at end of file
+});
diff --git a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/onapNameEditorController.js b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/onapNameEditorController.js
index 2a2e743fb..c6ae5fffe 100644
--- a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/onapNameEditorController.js
+++ b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/onapNameEditorController.js
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP Policy Engine
* ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017, 2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -58,7 +58,7 @@ app.controller('editOnapNameController' , function ($scope, $modalInstance, mes
}
},
error : function(data){
- alert("Error while saving.");
+ Notification.error("Error while saving.");
}
});
}
diff --git a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryGridController/BRMSParamDictGridController.js b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryGridController/BRMSParamDictGridController.js
index 50e14ea26..af1c34607 100644
--- a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryGridController/BRMSParamDictGridController.js
+++ b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryGridController/BRMSParamDictGridController.js
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP Policy Engine
* ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017, 2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -17,7 +17,7 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-app.controller('brmsParamDictGridController', function ($scope, PolicyAppService,modalService, $modal){
+app.controller('brmsParamDictGridController', function ($scope, PolicyAppService,modalService, $modal, Notification){
$( "#dialog" ).hide();
PolicyAppService.getData('getDictionary/get_BRMSParamData').then(function (data) {
@@ -164,7 +164,7 @@ app.controller('brmsParamDictGridController', function ($scope, PolicyAppService
})}
},
error : function(data){
- alert("Error while Searching.");
+ Notification.error("Error while Searching.");
}
});
};
diff --git a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryGridController/CLPepOptionsDictGridController.js b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryGridController/CLPepOptionsDictGridController.js
index cb79d6d44..1292139c6 100644
--- a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryGridController/CLPepOptionsDictGridController.js
+++ b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryGridController/CLPepOptionsDictGridController.js
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP Policy Engine
* ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017, 2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -17,7 +17,7 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-app.controller('pepOptionsDictGridController', function ($scope, PolicyAppService, modalService, $modal){
+app.controller('pepOptionsDictGridController', function ($scope, PolicyAppService, modalService, $modal, Notification){
$( "#dialog" ).hide();
@@ -189,7 +189,7 @@ app.controller('pepOptionsDictGridController', function ($scope, PolicyAppServic
})}
},
error : function(data){
- alert("Error while Searching.");
+ Notification.error("Error while Searching.");
}
});
};
diff --git a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryGridController/CLServiceDictGridController.js b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryGridController/CLServiceDictGridController.js
index de692a4f4..d41e940b6 100644
--- a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryGridController/CLServiceDictGridController.js
+++ b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryGridController/CLServiceDictGridController.js
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP Policy Engine
* ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017, 2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -17,7 +17,7 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-app.controller('serviceDictGridController', function ($scope, PolicyAppService, modalService, $modal){
+app.controller('serviceDictGridController', function ($scope, PolicyAppService, modalService, $modal, Notification){
$( "#dialog" ).hide();
PolicyAppService.getData('getDictionary/get_ClosedLoopServicesData').then(function (data) {
@@ -187,7 +187,7 @@ app.controller('serviceDictGridController', function ($scope, PolicyAppService,
})}
},
error : function(data){
- alert("Error while Searching.");
+ Notification.error("Error while Searching.");
}
});
};
diff --git a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryGridController/CLSiteDictGridController.js b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryGridController/CLSiteDictGridController.js
index abf44f86a..f72375246 100644
--- a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryGridController/CLSiteDictGridController.js
+++ b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryGridController/CLSiteDictGridController.js
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP Policy Engine
* ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017, 2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -17,7 +17,7 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-app.controller('siteDictGridController', function ($scope, PolicyAppService, modalService, $modal){
+app.controller('siteDictGridController', function ($scope, PolicyAppService, modalService, $modal, Notification){
$( "#dialog" ).hide();
PolicyAppService.getData('getDictionary/get_ClosedLoopSiteData').then(function (data) {
@@ -187,7 +187,7 @@ app.controller('siteDictGridController', function ($scope, PolicyAppService, mod
})}
},
error : function(data){
- alert("Error while Searching.");
+ Notification.error("Error while Searching.");
}
});
};
diff --git a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryGridController/CLVarbindDictGridController.js b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryGridController/CLVarbindDictGridController.js
index 4e13b9779..e2a69bd8d 100644
--- a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryGridController/CLVarbindDictGridController.js
+++ b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryGridController/CLVarbindDictGridController.js
@@ -17,7 +17,7 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-app.controller('varbindDictGridController', function ($scope, PolicyAppService, modalService, $modal){
+app.controller('varbindDictGridController', function ($scope, PolicyAppService, modalService, $modal, Notification){
$( "#dialog" ).hide();
PolicyAppService.getData('getDictionary/get_VarbindDictionaryData').then(function (data) {
@@ -188,7 +188,7 @@ app.controller('varbindDictGridController', function ($scope, PolicyAppService,
})}
},
error : function(data){
- alert("Error while Searching.");
+ Notification.error("Error while Searching.");
}
});
};
diff --git a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryGridController/CLVnfTypeDictGridController.js b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryGridController/CLVnfTypeDictGridController.js
index 90b77e45d..22978ba19 100644
--- a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryGridController/CLVnfTypeDictGridController.js
+++ b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryGridController/CLVnfTypeDictGridController.js
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP Policy Engine
* ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017, 2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -17,7 +17,7 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-app.controller('vnfTypeDictGridController', function ($scope, PolicyAppService, modalService, $modal){
+app.controller('vnfTypeDictGridController', function ($scope, PolicyAppService, modalService, $modal, Notification){
$( "#dialog" ).hide();
PolicyAppService.getData('getDictionary/get_VNFTypeData').then(function (data) {
@@ -187,7 +187,7 @@ app.controller('vnfTypeDictGridController', function ($scope, PolicyAppService,
})}
},
error : function(data){
- alert("Error while Searching.");
+ Notification.error("Error while Searching.");
}
});
};
diff --git a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryGridController/CLVsclActionDictGridController.js b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryGridController/CLVsclActionDictGridController.js
index 1c26c21b0..7077bc5e6 100644
--- a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryGridController/CLVsclActionDictGridController.js
+++ b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryGridController/CLVsclActionDictGridController.js
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP Policy Engine
* ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017, 2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -17,7 +17,7 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-app.controller('vsclActionDictGridController', function ($scope, PolicyAppService, modalService, $modal){
+app.controller('vsclActionDictGridController', function ($scope, PolicyAppService, modalService, $modal, Notification){
$( "#dialog" ).hide();
PolicyAppService.getData('getDictionary/get_VSCLActionData').then(function (data) {
@@ -188,7 +188,7 @@ app.controller('vsclActionDictGridController', function ($scope, PolicyAppServic
})}
},
error : function(data){
- alert("Error while Searching.");
+ Notification.error("Error while Searching.");
}
});
};
diff --git a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryGridController/MSHeaderDefaultValuesDictGridController.js b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryGridController/MSHeaderDefaultValuesDictGridController.js
index 4e6b9696b..e12db92c7 100644
--- a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryGridController/MSHeaderDefaultValuesDictGridController.js
+++ b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryGridController/MSHeaderDefaultValuesDictGridController.js
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP Policy Engine
* ================================================================================
- * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2018, 2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -23,51 +23,31 @@ app.controller('msHeaderDefaultValuesDictGridController', function ($scope, Poli
PolicyAppService.getData('getDictionary/get_MicroServiceHeaderDefaultsData').then(function (data) {
var j = data;
$scope.data = JSON.parse(j.data);
- console.log($scope.data);
$scope.microServiceHeaderDefaultDatas = JSON.parse($scope.data.microServiceHeaderDefaultDatas);
- console.log("microServiceHeaderDefaultDatas: " + $scope.microServiceHeaderDefaultDatas);
- }, function (error) {
- console.log("failed");
});
PolicyAppService.getData('getDictionary/get_MicroServiceModelsDataByName').then(function (data) {
var j = data;
$scope.data = JSON.parse(j.data);
- console.log($scope.data);
$scope.microServiceModelsDictionaryDatas = JSON.parse($scope.data.microServiceModelsDictionaryDatas);
- console.log($scope.microServiceModelsDictionaryDatas);
- }, function (error) {
- console.log("failed");
});
PolicyAppService.getData('getDictionary/get_RiskTypeDataByName').then(function (data) {
var j = data;
$scope.data = JSON.parse(j.data);
- console.log("riskTypeDictionaryDatas: " + $scope.data);
$scope.riskTypeDictionaryDatas = JSON.parse($scope.data.riskTypeDictionaryDatas);
- console.log($scope.riskTypeDictionaryDatas);
- }, function (error) {
- console.log("failed");
});
PolicyAppService.getData('getDictionary/get_OnapNameDataByName').then(function (data) {
var j = data;
$scope.data = JSON.parse(j.data);
- console.log($scope.data);
$scope.onapNameDictionaryDatas = JSON.parse($scope.data.onapNameDictionaryDatas);
- console.log($scope.onapNameDictionaryDatas);
- }, function (error) {
- console.log("failed");
});
PolicyAppService.getData('get_DCAEPriorityValues').then(function (data) {
var j = data;
$scope.data = JSON.parse(j.data);
- console.log($scope.data);
$scope.priorityDatas = JSON.parse($scope.data.priorityDatas);
- console.log($scope.priorityDatas);
- }, function (error) {
- console.log("failed");
});
PolicyAppService.getData('get_LockDownData').then(function(data){
@@ -81,8 +61,6 @@ app.controller('msHeaderDefaultValuesDictGridController', function ($scope, Poli
$scope.msHeaderDefaultValuesDictionaryGrid.columnDefs[0].visible = true;
$scope.gridApi.grid.refresh();
}
- },function(error){
- console.log("failed");
});
$scope.msHeaderDefaultValuesDictionaryGrid = {
@@ -116,7 +94,6 @@ app.controller('msHeaderDefaultValuesDictGridController', function ($scope, Poli
}
});
modalInstance.result.then(function(response){
- console.log('response', response);
$scope.microServiceHeaderDefaultDatas=response.microServiceHeaderDefaultDatas;
});
};
@@ -137,7 +114,6 @@ app.controller('msHeaderDefaultValuesDictGridController', function ($scope, Poli
}
});
modalInstance.result.then(function(response){
- console.log('response', response);
$scope.modelAttributeDictionaryDataa = response.modelAttributeDictionaryDatas;
});
};
@@ -157,7 +133,6 @@ app.controller('msHeaderDefaultValuesDictGridController', function ($scope, Poli
$scope.$apply(function(){$scope.microServiceHeaderDefaultDatas=data.microServiceHeaderDefaultDatas;});
},
error : function(data){
- console.log(data);
modalService.showFailure("Fail","Error while deleting: "+ data.responseText);
}
});
diff --git a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryGridController/attributeDictGridController.js b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryGridController/attributeDictGridController.js
index 760418553..7459bd6e7 100644
--- a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryGridController/attributeDictGridController.js
+++ b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryGridController/attributeDictGridController.js
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP Policy Engine
* ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017, 2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -17,7 +17,7 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-app.controller('attributeDictGridController', function ($scope, PolicyAppService, modalService, $modal){
+app.controller('attributeDictGridController', function ($scope, PolicyAppService, modalService, $modal, Notification){
$( "#dialog" ).hide();
PolicyAppService.getData('getDictionary/get_AttributeData').then(function (data) {
@@ -198,7 +198,7 @@ app.controller('attributeDictGridController', function ($scope, PolicyAppService
})}
},
error : function(data){
- alert("Error while Searching.");
+ Notification.error("Error while Searching.");
}
});
};
diff --git a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryGridController/onapNameDictGridController.js b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryGridController/onapNameDictGridController.js
index 4dd1df8c3..6727a7a30 100644
--- a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryGridController/onapNameDictGridController.js
+++ b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryGridController/onapNameDictGridController.js
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP Policy Engine
* ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017, 2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -17,7 +17,7 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-app.controller('onapNameDictGridController', function ($scope, PolicyAppService, modalService, $modal, uiGridConstants,Grid){
+app.controller('onapNameDictGridController', function ($scope, PolicyAppService, modalService, $modal, uiGridConstants,Grid, Notification){
$( "#dialog" ).hide();
PolicyAppService.getData('getDictionary/get_OnapNameData').then(function (data) {
@@ -58,7 +58,7 @@ app.controller('onapNameDictGridController', function ($scope, PolicyAppService,
'<button type="button" class="btn btn-primary" ng-click="grid.appScope.editOnapNameWindow(row.entity)"><i class="fa fa-pencil-square-o"></i></button> ' +
'<button type="button" class="btn btn-danger" ng-click="grid.appScope.deleteOnapName(row.entity)" ><i class="fa fa-trash-o"></i></button> ', width: '8%'
},
- { field: 'onapName', displayName : 'Onap Name', sort: { direction: 'asc', priority: 0 } },
+ { field: 'name', displayName : 'Onap Name', sort: { direction: 'asc', priority: 0 } },
{ field: 'description', width: '20%' },
{field: 'userCreatedBy.userName', displayName : 'Created By'},
{field: 'userModifiedBy.userName', displayName : 'Modified By' },
@@ -189,7 +189,7 @@ app.controller('onapNameDictGridController', function ($scope, PolicyAppService,
})}
},
error : function(data){
- alert("Error while Searching.");
+ Notification.error("Error while Searching.");
}
});
};
diff --git a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/policyAdminTabController.js b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/policyAdminTabController.js
index 4fabc458d..a0de546d9 100644
--- a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/policyAdminTabController.js
+++ b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/policyAdminTabController.js
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP Policy Engine
* ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017, 2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -17,50 +17,54 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-app.controller("policyAdminController", function($scope, PolicyAppService, modalService, $modal, Notification){
- $( "#dialog" ).hide();
-
+app.controller("policyAdminController", function($scope, PolicyAppService, modalService, $modal, Notification) {
+ $("#dialog").hide();
+
$scope.isDisabled = true;
- PolicyAppService.getData('get_LockDownData').then(function(data){
+ PolicyAppService.getData('get_LockDownData').then(function(data) {
var j = data;
$scope.data = JSON.parse(j.data);
$scope.lockdowndata = JSON.parse($scope.data.lockdowndata);
- if($scope.lockdowndata[0].lockdown == true){
- $scope.isDisabled = true;
- }else{
- $scope.isDisabled = false;
- }
+ if ($scope.lockdowndata[0].lockdown == true) {
+ $scope.isDisabled = true;
+ } else {
+ $scope.isDisabled = false;
+ }
console.log($scope.data);
- },function(error){
+ }, function(error) {
console.log("failed");
});
-
- $scope.saveLockDownValue = function(lockdownValue){
- console.log(lockdownValue);
- if(lockdownValue == true){
- Notification.success("Policy Application has been Locked Successfully");
- $scope.isDisabled = true;
- }else{
- Notification.success("Policy Application has been UnLocked Successfully");
- $scope.isDisabled = false;
- }
- var uuu = "adminTabController/save_LockDownValue.htm";
- var postData={lockdowndata: {lockdown : lockdownValue}};
- $.ajax({
- type : 'POST',
- url : uuu,
- dataType: 'json',
- contentType: 'application/json',
- data: JSON.stringify(postData),
- success : function(data){
- $scope.$apply(function(){
- $scope.data=data.data;
- });
- console.log($scope.data);
- },
- error : function(data){
- alert("Error Occured while saving Lockdown Value.");
- }
- });
- };
+
+ $scope.saveLockDownValue = function(lockdownValue) {
+ console.log(lockdownValue);
+ if (lockdownValue == true) {
+ Notification.success("Policy Application has been Locked Successfully");
+ $scope.isDisabled = true;
+ } else {
+ Notification.success("Policy Application has been UnLocked Successfully");
+ $scope.isDisabled = false;
+ }
+ var uuu = "adminTabController/save_LockDownValue.htm";
+ var postData = {
+ lockdowndata : {
+ lockdown : lockdownValue
+ }
+ };
+ $.ajax({
+ type : 'POST',
+ url : uuu,
+ dataType : 'json',
+ contentType : 'application/json',
+ data : JSON.stringify(postData),
+ success : function(data) {
+ $scope.$apply(function() {
+ $scope.data = data.data;
+ });
+ console.log($scope.data);
+ },
+ error : function(data) {
+ Notification.error("Error Occured while saving Lockdown Value.");
+ }
+ });
+ };
}); \ No newline at end of file
diff --git a/POLICY-SDK-APP/src/main/webapp/app/policyApp/main/modalPopupController.js b/POLICY-SDK-APP/src/main/webapp/app/policyApp/main/modalPopupController.js
index 7eb2b450e..7b3eca291 100644
--- a/POLICY-SDK-APP/src/main/webapp/app/policyApp/main/modalPopupController.js
+++ b/POLICY-SDK-APP/src/main/webapp/app/policyApp/main/modalPopupController.js
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP Policy Engine
* ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017, 2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -17,24 +17,24 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-appDS2.controller('modalpopupController' , function ($scope, $modalInstance, message){
-
- $scope.message = message;
-
-
- $scope.hello = function () {
+appDS2.controller('modalpopupController' , function ($scope, $modalInstance, message, Notification){
+
+ $scope.message = message;
+
+
+ $scope.hello = function () {
$modalInstance.close($scope.digitPattern);
};
- $modalInstance.ok = function() {
+ $modalInstance.ok = function() {
//add the ok functionality
- alert("Logout");
+ Notification.error("Logout");
};
$modalInstance.cancel = function() {
//add the cancel functionality
- alert("Keep Log in");
+ Notification.error("Keep Log in");
};
$modalInstance.cancelbutton = function() {
//add the cancel functionality
- alert("Modal Waring popup close event");
+ Notification.error("Modal Waring popup close event");
};
}); \ No newline at end of file
diff --git a/POLICY-SDK-APP/src/main/webapp/app/policyApp/main/policyEditor.html b/POLICY-SDK-APP/src/main/webapp/app/policyApp/main/policyEditor.html
index 6efb8b637..0493afce1 100644
--- a/POLICY-SDK-APP/src/main/webapp/app/policyApp/main/policyEditor.html
+++ b/POLICY-SDK-APP/src/main/webapp/app/policyApp/main/policyEditor.html
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -20,272 +20,273 @@
<!DOCTYPE html>
<html>
<head>
- <meta charset="ISO-8859-1">
- <title>Policy</title>
+ <meta charset="ISO-8859-1">
+ <title>Policy</title>
- <!-- Resources -->
- <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.4.0/css/font-awesome.min.css">
- <!---------------------------AngularJs-------------------------------->
- <script src= "app/fusion/external/angular-1.4.8/angular.js"></script>
- <script src= "app/fusion/external/angular-1.4.8/angular.min.js"></script>
- <script src= "app/policyApp/libs/bower_components/angular-translate/angular-translate.min.js"></script>
- <script src= "app/policyApp/libs/bower_components/ng-file-upload/ng-file-upload.min.js"></script>
- <script src= "app/fusion/external/angular-1.4.8/angular-messages.js"></script>
- <script src= "app/fusion/external/angular-1.4.8/angular-touch.js"></script>
- <script src= "//ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-animate.js"></script>
- <script src= "app/fusion/external/angular-1.4.8/angular-sanitize.min.js"></script>
- <script src= "app/fusion/external/angular-1.4.8/angular-route.min.js"></script>
- <script src= "app/fusion/external/angular-1.4.8/angular-cookies.min.js"></script>
-
- <script src= "app/fusion/external/b2b/js/b2b-angular/b2b-library.min.js"></script>
- <script src= "app/fusion/external/jquery/dist/jquery.min.js"></script>
- <script src= "app/policyApp/libs/bower_components/bootstrap/dist/js/bootstrap.min.js"></script>
- <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
- <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
-
- <!---------------------------Angular Gridster-------------------------------->
- <link rel="stylesheet" href="app/fusion/external/angular-gridster/dist/angular-gridster.min.css">
- <link rel="stylesheet" href= "app/fusion/external/angular-bootstrap/ui-bootstrap-csp.css">
- <script src= "app/fusion/external/javascript-detect-element-resize/jquery.resize.js"></script>
- <script src= "app/fusion/external/angular-bootstrap/ui-bootstrap-tpls.min.js"></script>
- <script src= "app/fusion/external/angular-gridster/dist/angular-gridster.min.js"></script>
+ <!-- Resources -->
+ <link rel="stylesheet" href="app/policyApp/CSS/font-awesome.min.css">
+ <!---------------------------AngularJs-------------------------------->
+ <script src= "app/fusion/external/angular-1.4.13/angular.js"></script>
+ <script src= "app/fusion/external/angular-1.4.13/angular.min.js"></script>
+ <script src= "app/policyApp/libs/bower_components/angular-translate/angular-translate.min.js"></script>
+ <script src= "app/policyApp/libs/bower_components/ng-file-upload/ng-file-upload.min.js"></script>
+ <script src= "app/fusion/external/angular-1.4.13/angular-messages.js"></script>
+ <script src= "app/fusion/external/angular-1.4.13/angular-touch.js"></script>
+ <script src= "app/fusion/external/angular-1.4.13/angular-animate.js"></script>
+ <script src= "app/fusion/external/angular-1.4.13/angular-sanitize.min.js"></script>
+ <script src= "app/fusion/external/angular-1.4.13/angular-route.min.js"></script>
+ <script src= "app/fusion/external/angular-1.4.13/angular-cookies.min.js"></script>
- <!---------------------------Policy App CSS-------------------------------->
- <link rel="stylesheet" href="app/policyApp/CSS/font-awesome.min.css">
- <link rel="stylesheet" href="app/policyApp/CSS/Notification/angular-csp.css">
- <link rel="stylesheet" href="app/policyApp/CSS/Notification/angular-ui-notification.min.css">
- <link rel="stylesheet" href="app/policyApp/CSS/lockdownIcon.css">
- <link rel="stylesheet" href="app/policyApp/CSS/w3.css">
- <link rel="stylesheet" href="app/policyApp/CSS/select.css">
- <link rel="stylesheet" href="app/policyApp/policy-models/Editor/css/normalize.css">
- <link rel="stylesheet" href="app/policyApp/policy-models/Editor/css/animations.css">
- <link rel="stylesheet" href="app/policyApp/policy-models/Editor/css/dialogs.css">
- <link rel="stylesheet" href="app/policyApp/policy-models/Editor/css/main.css">
- <link rel="stylesheet" href="app/policyApp/policy-models/Editor/css/styles.css">
- <script src= "app/policyApp/CSS/Notification/angular-ui-notification.min.js"></script>
-
- <script src= "app/policyApp/CSS/UIGrid/ui-grid.js"></script>
- <link rel="stylesheet" href="app/policyApp/CSS/UIGrid/ui-grid.css">
-
- <script src= "app/fusion/external/ds2/js/appDS2.js"></script>
+ <script src= "app/fusion/external/b2b/js/b2b-angular/b2b-library.min.js"></script>
+ <script src= "app/fusion/external/jquery/dist/jquery.min.js"></script>
+ <script src= "app/policyApp/CSS/bootstrap/dist/js/bootstrap-modalmanager.min.js"></script>
+ <script src= "app/policyApp/CSS/bootstrap/dist/js/bootstrap.min.js"></script>
+ <!-- <link rel="stylesheet" href="app/fusion/styles/jquery-ui.css"> -->
+ <script src= "static/js/jquery-ui.js"></script>
- <script src= "app/fusion/scripts/DS2-services/headerServiceDS2.js"></script>
- <script src= "app/fusion/scripts/DS2-services/leftMenuServiceDS2.js"></script>
- <script src= "app/fusion/scripts/DS2-services/manifestService.js"></script>
- <script src= "app/fusion/scripts/DS2-directives/footer.js"></script>
- <script src= "app/fusion/scripts/DS2-directives/ds2Header.js"></script>
- <script src= "app/fusion/scripts/DS2-directives/ds2LeftMenu.js"></script>
- <script src="app/fusion/scripts/DS2-directives/b2b-leftnav-ext.js"></script>
- <!-- /*<script src= "app/fusion/scripts/DS2-services/userInfoServiceDS2.js"></script>*/ -->
- <script src= "app/policyApp/service/userInfoServiceDS2.js"></script>
-
- <!---------------------------Policy Editor js-------------------------------->
- <script src= "app/policyApp/policy-models/Editor/js/app.js"></script>
- <script src= "app/policyApp/service/PolicyAppService.js"></script>
- <script src= "app/policyApp/main/modalPopupController.js"></script>
- <script src= "app/policyApp/service/modalService.js"></script>
- <script src= "app/policyApp/policy-models/Editor/PolicyTemplateController/ExportPolicyController.js"></script>
- <script src= "app/policyApp/policy-models/Editor/js/directives/directives.js"></script>
- <script src= "app/policyApp/policy-models/Editor/js/filters/filters.js"></script>
- <script src= "app/policyApp/policy-models/Editor/js/providers/config.js"></script>
- <script src= "app/policyApp/policy-models/Editor/js/entities/item.js"></script>
- <script src= "app/policyApp/policy-models/Editor/js/services/policynavigator.js"></script>
- <script src= "app/policyApp/policy-models/Editor/js/services/policyuploader.js"></script>
- <script src= "app/policyApp/policy-models/Editor/js/controllers/policyManager.js"></script>
- <script src= "app/policyApp/policy-models/Editor/js/controllers/policySearchManager.js"></script>
- <script src= "app/policyApp/policy-models/Editor/js/controllers/selector-controller.js"></script>
- <script src= "app/policyApp/controller/policyController.js"></script>
-
- <!---------------------------Policy Left Menu Controllers-------------------------------->
- <script src= "app/policyApp/controller/policyAdminTabController.js"></script>
- <script src= "app/policyApp/controller/dashboard_Logging_Controller.js"></script>
- <script src= "app/policyApp/controller/dashboardController.js"></script>
+ <!---------------------------Angular Gridster-------------------------------->
+ <link rel="stylesheet" href="app/fusion/external/angular-gridster/dist/angular-gridster.min.css">
+ <link rel="stylesheet" href= "app/fusion/external/angular-bootstrap/ui-bootstrap-csp.css">
+ <script src= "app/fusion/external/javascript-detect-element-resize/jquery.resize.js"></script>
+ <script src= "app/fusion/external/angular-bootstrap/ui-bootstrap-tpls.min.js"></script>
+ <script src= "app/fusion/external/angular-gridster/dist/angular-gridster.min.js"></script>
+
+ <!---------------------------Policy App CSS-------------------------------->
+ <link rel="stylesheet" href="app/policyApp/CSS/font-awesome.min.css">
+ <link rel="stylesheet" href="app/policyApp/CSS/Notification/angular-csp.css">
+ <link rel="stylesheet" href="app/policyApp/CSS/Notification/angular-ui-notification.min.css">
+ <link rel="stylesheet" href="app/policyApp/CSS/lockdownIcon.css">
+ <link rel="stylesheet" href="app/policyApp/CSS/w3.css">
+ <link rel="stylesheet" href="app/policyApp/CSS/select.css">
+ <link rel="stylesheet" href="app/policyApp/policy-models/Editor/css/normalize.css">
+ <link rel="stylesheet" href="app/policyApp/policy-models/Editor/css/animations.css">
+ <link rel="stylesheet" href="app/policyApp/policy-models/Editor/css/dialogs.css">
+ <link rel="stylesheet" href="app/policyApp/policy-models/Editor/css/main.css">
+ <link rel="stylesheet" href="app/policyApp/policy-models/Editor/css/styles.css">
+ <script src= "app/policyApp/CSS/Notification/angular-ui-notification.min.js"></script>
+
+ <script src= "app/policyApp/CSS/UIGrid/ui-grid.js"></script>
+ <link rel="stylesheet" href="app/policyApp/CSS/UIGrid/ui-grid.css">
+
+ <script src= "app/fusion/external/ds2/js/appDS2.js"></script>
+
+ <script src= "app/fusion/scripts/DS2-services/headerServiceDS2.js"></script>
+ <script src= "app/fusion/scripts/DS2-services/leftMenuServiceDS2.js"></script>
+ <script src= "app/fusion/scripts/DS2-services/manifestService.js"></script>
+ <script src= "app/fusion/scripts/DS2-directives/footer.js"></script>
+ <script src= "app/fusion/scripts/DS2-directives/ds2Header.js"></script>
+ <script src= "app/fusion/scripts/DS2-directives/ds2LeftMenu.js"></script>
+ <script src="app/fusion/scripts/DS2-directives/b2b-leftnav-ext.js"></script>
+ <!-- /*<script src= "app/fusion/scripts/DS2-services/userInfoServiceDS2.js"></script>*/ -->
+ <script src= "app/policyApp/service/userInfoServiceDS2.js"></script>
+
+ <!---------------------------Policy Editor js-------------------------------->
+ <script src= "app/policyApp/policy-models/Editor/js/app.js"></script>
+ <script src= "app/policyApp/service/PolicyAppService.js"></script>
+ <script src= "app/policyApp/main/modalPopupController.js"></script>
+ <script src= "app/policyApp/service/modalService.js"></script>
+ <script src= "app/policyApp/policy-models/Editor/PolicyTemplateController/ExportPolicyController.js"></script>
+ <script src= "app/policyApp/policy-models/Editor/js/directives/directives.js"></script>
+ <script src= "app/policyApp/policy-models/Editor/js/filters/filters.js"></script>
+ <script src= "app/policyApp/policy-models/Editor/js/providers/config.js"></script>
+ <script src= "app/policyApp/policy-models/Editor/js/entities/item.js"></script>
+ <script src= "app/policyApp/policy-models/Editor/js/services/policynavigator.js"></script>
+ <script src= "app/policyApp/policy-models/Editor/js/services/policyuploader.js"></script>
+ <script src= "app/policyApp/policy-models/Editor/js/controllers/policyManager.js"></script>
+ <script src= "app/policyApp/policy-models/Editor/js/controllers/policySearchManager.js"></script>
+ <script src= "app/policyApp/policy-models/Editor/js/controllers/selector-controller.js"></script>
+ <script src= "app/policyApp/controller/policyController.js"></script>
+
+ <!---------------------------Policy Left Menu Controllers-------------------------------->
+ <script src= "app/policyApp/controller/policyAdminTabController.js"></script>
+ <script src= "app/policyApp/controller/dashboard_Logging_Controller.js"></script>
+ <script src= "app/policyApp/controller/dashboardController.js"></script>
<script src= "app/policyApp/controller/dashboardCRUDController.js"></script>
- <script src= "app/policyApp/controller/pdpController.js"></script>
- <script src= "app/policyApp/controller/pdpGroupPopUpController.js"></script>
- <script src= "app/policyApp/controller/DictionaryController.js"></script>
- <script src= "app/policyApp/controller/PolicyRolesController.js"></script>
- <script src= "app/policyApp/controller/PolicyAddScopeRoleController.js"></script>
- <script src= "app/policyApp/controller/AutoPushController.js"></script>
- <script src= "app/policyApp/controller/ImportDictionaryController.js"></script>
- <script src= "app/policyApp/controller/PDPTabController/AddorEditPdpInGroup.js"></script>
- <script src= "app/policyApp/controller/PDPTabController/PDPGroupStatusController.js"></script>
- <script src= "app/policyApp/controller/AutoPushTabController/RemovePDPGroupPoliciesController.js"></script>
-
- <!---------------------------Policy Creation resources-------------------------------->
- <script src= "app/policyApp/policy-models/Editor/PolicyTemplateController/BaseConfigPolicyController.js"></script>
- <script src= "app/policyApp/policy-models/Editor/PolicyTemplateController/ClosedLoopFaultController.js"></script>
- <script src= "app/policyApp/policy-models/Editor/PolicyTemplateController/ClosedLoopPMController.js"></script>
- <script src= "app/policyApp/policy-models/Editor/PolicyTemplateController/ActionPolicyController.js"></script>
- <script src= "app/policyApp/policy-models/Editor/PolicyTemplateController/DecisionPolicyController.js"></script>
- <script src= "app/policyApp/policy-models/Editor/PolicyTemplateController/FirewallPolicyController.js"></script>
- <script src= "app/policyApp/policy-models/Editor/PolicyTemplateController/DCAEMicroServicePolicyController.js"></script>
- <script src= "app/policyApp/policy-models/Editor/PolicyTemplateController/OptimizationPolicyController.js"></script>
- <script src= "app/policyApp/policy-models/Editor/PolicyTemplateController/BRMSRawPolicyController.js"></script>
- <script src= "app/policyApp/policy-models/Editor/PolicyTemplateController/BRMSParamPolicyController.js"></script>
-
- <!--------------------------Dictionary resources--------------------------------->
- <script src= "app/policyApp/controller/dictionaryGridController/actionPolicyDictGridController.js"></script>
- <script src= "app/policyApp/controller/dictionaryGridController/attributeDictGridController.js"></script>
- <script src= "app/policyApp/controller/dictionaryGridController/onapNameDictGridController.js"></script>
- <script src= "app/policyApp/controller/dictionaryGridController/BRMSParamDictGridController.js"></script>
- <script src= "app/policyApp/controller/dictionaryGridController/BRMSDependencyDictGridController.js"></script>
- <script src= "app/policyApp/controller/dictionaryGridController/BRMSControllerDictGridController.js"></script>
- <script src= "app/policyApp/controller/dictionaryGridController/CLPepOptionsDictGridController.js"></script>
- <script src= "app/policyApp/controller/dictionaryGridController/CLServiceDictGridController.js"></script>
- <script src= "app/policyApp/controller/dictionaryGridController/CLSiteDictGridController.js"></script>
- <script src= "app/policyApp/controller/dictionaryGridController/CLVarbindDictGridController.js"></script>
- <script src= "app/policyApp/controller/dictionaryGridController/CLVnfTypeDictGridController.js"></script>
- <script src= "app/policyApp/controller/dictionaryGridController/CLVsclActionDictGridController.js"></script>
- <script src= "app/policyApp/controller/dictionaryGridController/DecisionSettingsDictGridController.js"></script>
- <script src= "app/policyApp/controller/dictionaryGridController/DecisionRainyDayDictGridController.js"></script>
- <script src= "app/policyApp/controller/dictionaryGridController/DescriptiveScopeDictGridController.js"></script>
- <script src= "app/policyApp/controller/dictionaryGridController/EnforcerTypeDictGridController.js"></script>
- <script src= "app/policyApp/controller/dictionaryGridController/FWActionListDictGridController.js"></script>
- <script src= "app/policyApp/controller/dictionaryGridController/FWAddressGroupDictGridController.js"></script>
- <script src= "app/policyApp/controller/dictionaryGridController/FWParentListDictGridController.js"></script>
- <script src= "app/policyApp/controller/dictionaryGridController/FWPortListDictGridController.js"></script>
- <script src= "app/policyApp/controller/dictionaryGridController/FWPrefixListDictGridController.js"></script>
- <script src= "app/policyApp/controller/dictionaryGridController/FWProtocolListDictGridController.js"></script>
- <script src= "app/policyApp/controller/dictionaryGridController/FWSecurityZoneDictGridController.js"></script>
- <script src= "app/policyApp/controller/dictionaryGridController/FWServiceGroupDictGridController.js"></script>
- <script src= "app/policyApp/controller/dictionaryGridController/FWServiceListDictGridController.js"></script>
- <script src= "app/policyApp/controller/dictionaryGridController/FWTermListDictGridController.js"></script>
- <script src= "app/policyApp/controller/dictionaryGridController/FWTagListDictGridController.js"></script>
- <script src= "app/policyApp/controller/dictionaryGridController/FWTagPickerListDictGridController.js"></script>
- <script src= "app/policyApp/controller/dictionaryGridController/FWZoneDictGridController.js"></script>
- <script src= "app/policyApp/controller/dictionaryGridController/MSConfigNameDictGridController.js"></script>
- <script src= "app/policyApp/controller/dictionaryGridController/MSHeaderDefaultValuesDictGridController.js"></script>
- <script src= "app/policyApp/controller/dictionaryGridController/MSDcaeUUIDDictGridController.js"></script>
- <script src= "app/policyApp/controller/dictionaryGridController/MSLocationDictGridController.js"></script>
- <script src= "app/policyApp/controller/dictionaryGridController/MSModelDictionaryDataController.js"></script>
- <script src= "app/policyApp/controller/dictionaryGridController/MSModelDictGridController.js"></script>
- <script src= "app/policyApp/controller/dictionaryGridController/ModelAttributeDictGridController.js"></script>
- <script src= "app/policyApp/controller/dictionaryGridController/OptimizationModelDictGridController.js"></script>
-
- <script src= "app/policyApp/controller/dictionaryGridController/PSClosedLoopDictGridController.js"></script>
- <script src= "app/policyApp/controller/dictionaryGridController/PSGroupPolicyScopeDictGridController.js"></script>
- <script src= "app/policyApp/controller/dictionaryGridController/PSResourceDictGridController.js"></script>
- <script src= "app/policyApp/controller/dictionaryGridController/PSServiceDictGridController.js"></script>
- <script src= "app/policyApp/controller/dictionaryGridController/PSTypeDictGridController.js"></script>
- <script src= "app/policyApp/controller/dictionaryGridController/RiskTypeDictGridController.js"></script>
- <script src= "app/policyApp/controller/dictionaryGridController/SafePolicyWarningDictGridController.js"></script>
+ <script src= "app/policyApp/controller/pdpController.js"></script>
+ <script src= "app/policyApp/controller/pdpGroupPopUpController.js"></script>
+ <script src= "app/policyApp/controller/DictionaryController.js"></script>
+ <script src= "app/policyApp/controller/PolicyRolesController.js"></script>
+ <script src= "app/policyApp/controller/PolicyAddScopeRoleController.js"></script>
+ <script src= "app/policyApp/controller/AutoPushController.js"></script>
+ <script src= "app/policyApp/controller/ImportDictionaryController.js"></script>
+ <script src= "app/policyApp/controller/PDPTabController/AddorEditPdpInGroup.js"></script>
+ <script src= "app/policyApp/controller/PDPTabController/PDPGroupStatusController.js"></script>
+ <script src= "app/policyApp/controller/AutoPushTabController/RemovePDPGroupPoliciesController.js"></script>
+
+ <!---------------------------Policy Creation resources-------------------------------->
+ <script src= "app/policyApp/policy-models/Editor/PolicyTemplateController/BaseConfigPolicyController.js"></script>
+ <script src= "app/policyApp/policy-models/Editor/PolicyTemplateController/ClosedLoopFaultController.js"></script>
+ <script src= "app/policyApp/policy-models/Editor/PolicyTemplateController/ClosedLoopPMController.js"></script>
+ <script src= "app/policyApp/policy-models/Editor/PolicyTemplateController/ActionPolicyController.js"></script>
+ <script src= "app/policyApp/policy-models/Editor/PolicyTemplateController/DecisionPolicyController.js"></script>
+ <script src= "app/policyApp/policy-models/Editor/PolicyTemplateController/FirewallPolicyController.js"></script>
+ <script src= "app/policyApp/policy-models/Editor/PolicyTemplateController/DCAEMicroServicePolicyController.js"></script>
+ <script src= "app/policyApp/policy-models/Editor/PolicyTemplateController/OptimizationPolicyController.js"></script>
+ <script src= "app/policyApp/policy-models/Editor/PolicyTemplateController/BRMSRawPolicyController.js"></script>
+ <script src= "app/policyApp/policy-models/Editor/PolicyTemplateController/BRMSParamPolicyController.js"></script>
+
+ <!--------------------------Dictionary resources--------------------------------->
+ <script src= "app/policyApp/controller/dictionaryGridController/actionPolicyDictGridController.js"></script>
+ <script src= "app/policyApp/controller/dictionaryGridController/attributeDictGridController.js"></script>
+ <script src= "app/policyApp/controller/dictionaryGridController/onapNameDictGridController.js"></script>
+ <script src= "app/policyApp/controller/dictionaryGridController/BRMSParamDictGridController.js"></script>
+ <script src= "app/policyApp/controller/dictionaryGridController/BRMSDependencyDictGridController.js"></script>
+ <script src= "app/policyApp/controller/dictionaryGridController/BRMSControllerDictGridController.js"></script>
+ <script src= "app/policyApp/controller/dictionaryGridController/CLPepOptionsDictGridController.js"></script>
+ <script src= "app/policyApp/controller/dictionaryGridController/CLServiceDictGridController.js"></script>
+ <script src= "app/policyApp/controller/dictionaryGridController/CLSiteDictGridController.js"></script>
+ <script src= "app/policyApp/controller/dictionaryGridController/CLVarbindDictGridController.js"></script>
+ <script src= "app/policyApp/controller/dictionaryGridController/CLVnfTypeDictGridController.js"></script>
+ <script src= "app/policyApp/controller/dictionaryGridController/CLVsclActionDictGridController.js"></script>
+ <script src= "app/policyApp/controller/dictionaryGridController/DecisionSettingsDictGridController.js"></script>
+ <script src= "app/policyApp/controller/dictionaryGridController/DecisionRainyDayDictGridController.js"></script>
+ <script src= "app/policyApp/controller/dictionaryGridController/DescriptiveScopeDictGridController.js"></script>
+ <script src= "app/policyApp/controller/dictionaryGridController/EnforcerTypeDictGridController.js"></script>
+ <script src= "app/policyApp/controller/dictionaryGridController/FWActionListDictGridController.js"></script>
+ <script src= "app/policyApp/controller/dictionaryGridController/FWAddressGroupDictGridController.js"></script>
+ <script src= "app/policyApp/controller/dictionaryGridController/FWParentListDictGridController.js"></script>
+ <script src= "app/policyApp/controller/dictionaryGridController/FWPortListDictGridController.js"></script>
+ <script src= "app/policyApp/controller/dictionaryGridController/FWPrefixListDictGridController.js"></script>
+ <script src= "app/policyApp/controller/dictionaryGridController/FWProtocolListDictGridController.js"></script>
+ <script src= "app/policyApp/controller/dictionaryGridController/FWSecurityZoneDictGridController.js"></script>
+ <script src= "app/policyApp/controller/dictionaryGridController/FWServiceGroupDictGridController.js"></script>
+ <script src= "app/policyApp/controller/dictionaryGridController/FWServiceListDictGridController.js"></script>
+ <script src= "app/policyApp/controller/dictionaryGridController/FWTermListDictGridController.js"></script>
+ <script src= "app/policyApp/controller/dictionaryGridController/FWTagListDictGridController.js"></script>
+ <script src= "app/policyApp/controller/dictionaryGridController/FWTagPickerListDictGridController.js"></script>
+ <script src= "app/policyApp/controller/dictionaryGridController/FWZoneDictGridController.js"></script>
+ <script src= "app/policyApp/controller/dictionaryGridController/MSConfigNameDictGridController.js"></script>
+ <script src= "app/policyApp/controller/dictionaryGridController/MSHeaderDefaultValuesDictGridController.js"></script>
+ <script src= "app/policyApp/controller/dictionaryGridController/MSDcaeUUIDDictGridController.js"></script>
+ <script src= "app/policyApp/controller/dictionaryGridController/MSLocationDictGridController.js"></script>
+ <script src= "app/policyApp/controller/dictionaryGridController/MSModelDictionaryDataController.js"></script>
+ <script src= "app/policyApp/controller/dictionaryGridController/MSModelDictGridController.js"></script>
+ <script src= "app/policyApp/controller/dictionaryGridController/ModelAttributeDictGridController.js"></script>
+ <script src= "app/policyApp/controller/dictionaryGridController/OptimizationModelDictGridController.js"></script>
+
+ <script src= "app/policyApp/controller/dictionaryGridController/PSClosedLoopDictGridController.js"></script>
+ <script src= "app/policyApp/controller/dictionaryGridController/PSGroupPolicyScopeDictGridController.js"></script>
+ <script src= "app/policyApp/controller/dictionaryGridController/PSResourceDictGridController.js"></script>
+ <script src= "app/policyApp/controller/dictionaryGridController/PSServiceDictGridController.js"></script>
+ <script src= "app/policyApp/controller/dictionaryGridController/PSTypeDictGridController.js"></script>
+ <script src= "app/policyApp/controller/dictionaryGridController/RiskTypeDictGridController.js"></script>
+ <script src= "app/policyApp/controller/dictionaryGridController/SafePolicyWarningDictGridController.js"></script>
+
+ <script src= "app/policyApp/controller/dictionaryController/actionPolicyDictController.js"></script>
+ <script src= "app/policyApp/controller/dictionaryController/attributeDictController.js"></script>
+ <script src= "app/policyApp/controller/dictionaryController/onapNameEditorController.js"></script>
+ <script src= "app/policyApp/controller/dictionaryController/BRMSParamDictController.js"></script>
+ <script src= "app/policyApp/controller/dictionaryController/BRMSDependencyDictController.js"></script>
+ <script src= "app/policyApp/controller/dictionaryController/BRMSControllerDictController.js"></script>
+ <script src= "app/policyApp/controller/dictionaryController/CLPepOptionsDictController.js"></script>
+ <script src= "app/policyApp/controller/dictionaryController/CLServiceDictController.js"></script>
+ <script src= "app/policyApp/controller/dictionaryController/CLSiteDictController.js"></script>
+ <script src= "app/policyApp/controller/dictionaryController/CLVarbindDictController.js"></script>
+ <script src= "app/policyApp/controller/dictionaryController/CLVnfTypeDictController.js"></script>
+ <script src= "app/policyApp/controller/dictionaryController/CLVsclActionDictController.js"></script>
+ <script src= "app/policyApp/controller/dictionaryController/DecisionSettingsDictController.js"></script>
+ <script src= "app/policyApp/controller/dictionaryController/DecisionRainyDayDictController.js"></script>
+ <script src= "app/policyApp/controller/dictionaryController/DescriptiveSearchDictController.js"></script>
+ <script src= "app/policyApp/controller/dictionaryController/EnforcerDictController.js"></script>
+ <script src= "app/policyApp/controller/dictionaryController/FWActionListDictController.js"></script>
+ <script src= "app/policyApp/controller/dictionaryController/FWAddressGroupDictController.js"></script>
+ <script src= "app/policyApp/controller/dictionaryController/FWParentListDictController.js"></script>
+ <script src= "app/policyApp/controller/dictionaryController/FWPortListDictController.js"></script>
+ <script src= "app/policyApp/controller/dictionaryController/FWPrefixListDictController.js"></script>
+ <script src= "app/policyApp/controller/dictionaryController/FWProtocolListDictController.js"></script>
+ <script src= "app/policyApp/controller/dictionaryController/FWSecurityZoneDictController.js"></script>
+ <script src= "app/policyApp/controller/dictionaryController/FWServiceGroupDictController.js"></script>
+ <script src= "app/policyApp/controller/dictionaryController/FWServiceListDictController.js"></script>
+ <script src= "app/policyApp/controller/dictionaryController/FWTermListDictController.js"></script>
+ <script src= "app/policyApp/controller/dictionaryController/FWTagListDictController.js"></script>
+ <script src= "app/policyApp/controller/dictionaryController/FWTagPickerListDictController.js"></script>
+ <script src= "app/policyApp/controller/dictionaryController/FWZoneDictController.js"></script>
+ <script src= "app/policyApp/controller/dictionaryController/MSHeaderDefaultValuesDictController.js"></script>
+ <script src= "app/policyApp/controller/dictionaryController/MSConfigNameDictController.js"></script>
+ <script src= "app/policyApp/controller/dictionaryController/MSDictionaryController.js"></script>
+ <script src= "app/policyApp/controller/dictionaryController/MSDcaeUUIDDictController.js"></script>
+ <script src= "app/policyApp/controller/dictionaryController/MSLocationDictController.js"></script>
+ <script src= "app/policyApp/controller/dictionaryController/MSModelsDictController.js"></script>
+ <script src= "app/policyApp/controller/dictionaryController/ModelAttributeDictController.js"></script>
+ <script src= "app/policyApp/controller/dictionaryController/OptimizationModelsDictController.js"></script>
+
+ <script src= "app/policyApp/controller/dictionaryController/PSClosedLoopDictController.js"></script>
+ <script src= "app/policyApp/controller/dictionaryController/PSGroupPolicyScopeDictController.js"></script>
+ <script src= "app/policyApp/controller/dictionaryController/PSResourceDictController.js"></script>
+ <script src= "app/policyApp/controller/dictionaryController/PSServiceDictController.js"></script>
+ <script src= "app/policyApp/controller/dictionaryController/PSTypeDictController.js"></script>
+ <script src= "app/policyApp/controller/dictionaryController/RiskTypeDictController.js"></script>
+ <script src= "app/policyApp/controller/dictionaryController/SafePolicyWarningDictController.js"></script>
+
+ <script src= "app/policyApp/controller/ImportDictionaryController.js"></script>
+
+ <!---------------------------DS2 styles-------------------------------->
+ <link rel="stylesheet" href="app/policyApp/CSS/b2b-angular.css">
+ <link rel="stylesheet" href="app/fusion/external/b2b/css/b2b-angular/font_icons.css">
+ <link rel="stylesheet" href="app/policyApp/CSS/bootstrap/dist/css/bootstrap.min.css">
+
+ <!---------------------------DS2 ICONS-------------------------------->
+ <link rel="stylesheet" href="app/fusion/external/ds2/css/digital-ng-library/ionicons.css">
+ <link rel="stylesheet" href="app/fusion/styles/ecomp.css">
+ <link rel="stylesheet" href="app/fusion/external/angular-gridster/dist/angular-gridster.min.css">
- <script src= "app/policyApp/controller/dictionaryController/actionPolicyDictController.js"></script>
- <script src= "app/policyApp/controller/dictionaryController/attributeDictController.js"></script>
- <script src= "app/policyApp/controller/dictionaryController/onapNameEditorController.js"></script>
- <script src= "app/policyApp/controller/dictionaryController/BRMSParamDictController.js"></script>
- <script src= "app/policyApp/controller/dictionaryController/BRMSDependencyDictController.js"></script>
- <script src= "app/policyApp/controller/dictionaryController/BRMSControllerDictController.js"></script>
- <script src= "app/policyApp/controller/dictionaryController/CLPepOptionsDictController.js"></script>
- <script src= "app/policyApp/controller/dictionaryController/CLServiceDictController.js"></script>
- <script src= "app/policyApp/controller/dictionaryController/CLSiteDictController.js"></script>
- <script src= "app/policyApp/controller/dictionaryController/CLVarbindDictController.js"></script>
- <script src= "app/policyApp/controller/dictionaryController/CLVnfTypeDictController.js"></script>
- <script src= "app/policyApp/controller/dictionaryController/CLVsclActionDictController.js"></script>
- <script src= "app/policyApp/controller/dictionaryController/DecisionSettingsDictController.js"></script>
- <script src= "app/policyApp/controller/dictionaryController/DecisionRainyDayDictController.js"></script>
- <script src= "app/policyApp/controller/dictionaryController/DescriptiveSearchDictController.js"></script>
- <script src= "app/policyApp/controller/dictionaryController/EnforcerDictController.js"></script>
- <script src= "app/policyApp/controller/dictionaryController/FWActionListDictController.js"></script>
- <script src= "app/policyApp/controller/dictionaryController/FWAddressGroupDictController.js"></script>
- <script src= "app/policyApp/controller/dictionaryController/FWParentListDictController.js"></script>
- <script src= "app/policyApp/controller/dictionaryController/FWPortListDictController.js"></script>
- <script src= "app/policyApp/controller/dictionaryController/FWPrefixListDictController.js"></script>
- <script src= "app/policyApp/controller/dictionaryController/FWProtocolListDictController.js"></script>
- <script src= "app/policyApp/controller/dictionaryController/FWSecurityZoneDictController.js"></script>
- <script src= "app/policyApp/controller/dictionaryController/FWServiceGroupDictController.js"></script>
- <script src= "app/policyApp/controller/dictionaryController/FWServiceListDictController.js"></script>
- <script src= "app/policyApp/controller/dictionaryController/FWTermListDictController.js"></script>
- <script src= "app/policyApp/controller/dictionaryController/FWTagListDictController.js"></script>
- <script src= "app/policyApp/controller/dictionaryController/FWTagPickerListDictController.js"></script>
- <script src= "app/policyApp/controller/dictionaryController/FWZoneDictController.js"></script>
- <script src= "app/policyApp/controller/dictionaryController/MSHeaderDefaultValuesDictController.js"></script>
- <script src= "app/policyApp/controller/dictionaryController/MSConfigNameDictController.js"></script>
- <script src= "app/policyApp/controller/dictionaryController/MSDictionaryController.js"></script>
- <script src= "app/policyApp/controller/dictionaryController/MSDcaeUUIDDictController.js"></script>
- <script src= "app/policyApp/controller/dictionaryController/MSLocationDictController.js"></script>
- <script src= "app/policyApp/controller/dictionaryController/MSModelsDictController.js"></script>
- <script src= "app/policyApp/controller/dictionaryController/ModelAttributeDictController.js"></script>
- <script src= "app/policyApp/controller/dictionaryController/OptimizationModelsDictController.js"></script>
-
- <script src= "app/policyApp/controller/dictionaryController/PSClosedLoopDictController.js"></script>
- <script src= "app/policyApp/controller/dictionaryController/PSGroupPolicyScopeDictController.js"></script>
- <script src= "app/policyApp/controller/dictionaryController/PSResourceDictController.js"></script>
- <script src= "app/policyApp/controller/dictionaryController/PSServiceDictController.js"></script>
- <script src= "app/policyApp/controller/dictionaryController/PSTypeDictController.js"></script>
- <script src= "app/policyApp/controller/dictionaryController/RiskTypeDictController.js"></script>
- <script src= "app/policyApp/controller/dictionaryController/SafePolicyWarningDictController.js"></script>
-
- <script src= "app/policyApp/controller/ImportDictionaryController.js"></script>
-
- <!---------------------------DS2 styles-------------------------------->
- <link rel="stylesheet" href="app/policyApp/CSS/b2b-angular.css">
- <link rel="stylesheet" href="app/fusion/external/b2b/css/b2b-angular/font_icons.css">
- <link rel="stylesheet" href="app/policyApp/CSS/bootstrap/dist/css/bootstrap.min.css">
-
- <!---------------------------DS2 ICONS-------------------------------->
- <link rel="stylesheet" href="app/fusion/external/ds2/css/digital-ng-library/ionicons.css">
- <link rel="stylesheet" href="app/fusion/styles/ecomp.css">
- <link rel="stylesheet" href="app/fusion/external/angular-gridster/dist/angular-gridster.min.css">
-
</head>
- <body class="appBody" ng-app="abs" style="padding-top: 0px;">
- <div ds2-Header class="header-container" ></div>
- <div ds2-menu id="menuContainer" class="menu-container" ></div>
- <div ng-view id="rightContentProfile" class="content-container">
- </div>
- <!-- Dictionary Windows -->
- <div ng-include src="'app/policyApp/Windows/Dictionary/ActionPolicyDictionary.html'"></div>
- <div ng-include src="'app/policyApp/Windows/Dictionary/AttributeDictionary.html'"></div>
- <div ng-include src="'app/policyApp/Windows/Dictionary/BRMSParamDictionary.html'"></div>
- <div ng-include src="'app/policyApp/Windows/Dictionary/BRMSDependencyDictionary.html'"></div>
- <div ng-include src="'app/policyApp/Windows/Dictionary/BRMSControllerDictionary.html'"></div>
- <div ng-include src="'app/policyApp/Windows/Dictionary/CLPepOptionsDictionary.html'"></div>
- <div ng-include src="'app/policyApp/Windows/Dictionary/CLServiceTypeDictionary.html'"></div>
- <div ng-include src="'app/policyApp/Windows/Dictionary/CLSiteDictionary.html'"></div>
- <div ng-include src="'app/policyApp/Windows/Dictionary/CLVarbindDictionary.html'"></div>
- <div ng-include src="'app/policyApp/Windows/Dictionary/CLVnfTypeDictionary.html'"></div>
- <div ng-include src="'app/policyApp/Windows/Dictionary/CLVsclActionDictionary.html'"></div>
- <div ng-include src="'app/policyApp/Windows/Dictionary/DecisionSettingsDictionary.html'"></div>
- <div ng-include src="'app/policyApp/Windows/Dictionary/DecisionRainyDayDictionary.html'"></div>
- <div ng-include src="'app/policyApp/Windows/Dictionary/DescriptiveScopeDictionary.html'"></div>
- <div ng-include src="'app/policyApp/Windows/Dictionary/OnapNameDictionary.html'"></div>
- <div ng-include src="'app/policyApp/Windows/Dictionary/EnforcerTypeDictionary.html'"></div>
- <div ng-include src="'app/policyApp/Windows/Dictionary/FWActionListDictionary.html'"></div>
- <div ng-include src="'app/policyApp/Windows/Dictionary/FWAddressGroupDictionary.html'"></div>
- <div ng-include src="'app/policyApp/Windows/Dictionary/FWParentListDictionary.html'"></div>
- <div ng-include src="'app/policyApp/Windows/Dictionary/FWPortListDictionary.html'"></div>
- <div ng-include src="'app/policyApp/Windows/Dictionary/FWPrefixListDictionary.html'"></div>
- <div ng-include src="'app/policyApp/Windows/Dictionary/FWProtocolListDictionary.html'"></div>
- <div ng-include src="'app/policyApp/Windows/Dictionary/FWSecurityZoneDictionary.html'"></div>
- <div ng-include src="'app/policyApp/Windows/Dictionary/FWServiceGroupDictionary.html'"></div>
- <div ng-include src="'app/policyApp/Windows/Dictionary/FWServiceListDictionary.html'"></div>
- <div ng-include src="'app/policyApp/Windows/Dictionary/FWTag.html'"></div>
- <div ng-include src="'app/policyApp/Windows/Dictionary/FWTagPicker.html'"></div>
- <div ng-include src="'app/policyApp/Windows/Dictionary/FWTermListDictionary.html'"></div>
- <div ng-include src="'app/policyApp/Windows/Dictionary/FWZoneDictionary.html'"></div>
- <div ng-include src="'app/policyApp/Windows/Dictionary/MSConfigNameDictionary.html'"></div>
- <div ng-include src="'app/policyApp/Windows/Dictionary/MSHeaderDefaultValuesDictionary.html'"></div>
- <div ng-include src="'app/policyApp/Windows/Dictionary/MSDCAEUUIDDictionary.html'"></div>
- <div ng-include src="'app/policyApp/Windows/Dictionary/MSLocationDictionary.html'"></div>
- <div ng-include src="'app/policyApp/Windows/Dictionary/MSModelsDictionary.html'"></div>
- <div ng-include src="'app/policyApp/Windows/Dictionary/MSModelDictionaryData.html'"></div>
- <div ng-include src="'app/policyApp/Windows/Dictionary/ModelAttributeDictionary.html'"></div>
- <div ng-include src="'app/policyApp/Windows/Dictionary/OptimizationModelsDictionary.html'"></div>
- <div ng-include src="'app/policyApp/Windows/Dictionary/PSClosedLoopDictionary.html'"></div>
- <div ng-include src="'app/policyApp/Windows/Dictionary/PSGroupPolicyScopeDictionary.html'"></div>
- <div ng-include src="'app/policyApp/Windows/Dictionary/PSResourceDictionary.html'"></div>
- <div ng-include src="'app/policyApp/Windows/Dictionary/PSServiceDictionary.html'"></div>
- <div ng-include src="'app/policyApp/Windows/Dictionary/PSTypeDictionary.html'"></div>
- <div ng-include src="'app/policyApp/Windows/Dictionary/RiskTypeDictionary.html'"></div>
- <div ng-include src="'app/policyApp/Windows/Dictionary/RiskTypeDictionary.html'"></div>
- <div ng-include src="'app/policyApp/Windows/Dictionary/SafePolicyWarningDictionary.html'"></div>
-
- <div ng-include src="'app/policyApp/Windows/PDPTabWindows/PdpStatusWindow.html'"></div>
- <div ng-include src="'app/policyApp/Windows/Edit_Roles_Window.html'"></div>
- <div ng-include src="'app/policyApp/Windows/PushtabWindow/removeGroupPoliciesWindow.html'"></div>
- <div ng-include src="'app/policyApp/Windows/popup_modal.html'"></div>
- <div ds2-Footer class="footer-container"></div>
- </body>
+ <body class="appBody" ng-app="abs" style="padding-top: 0px;">
+ <div ds2-Header class="header-container" ></div>
+ <div ds2-menu id="menuContainer" class="menu-container" ></div>
+ <div ng-view id="rightContentProfile" class="content-container">
+ </div>
+ <!-- Dictionary Windows -->
+ <div ng-include src="'app/policyApp/Windows/Dictionary/ActionPolicyDictionary.html'"></div>
+ <div ng-include src="'app/policyApp/Windows/Dictionary/AttributeDictionary.html'"></div>
+ <div ng-include src="'app/policyApp/Windows/Dictionary/BRMSParamDictionary.html'"></div>
+ <div ng-include src="'app/policyApp/Windows/Dictionary/BRMSDependencyDictionary.html'"></div>
+ <div ng-include src="'app/policyApp/Windows/Dictionary/BRMSControllerDictionary.html'"></div>
+ <div ng-include src="'app/policyApp/Windows/Dictionary/CLPepOptionsDictionary.html'"></div>
+ <div ng-include src="'app/policyApp/Windows/Dictionary/CLServiceTypeDictionary.html'"></div>
+ <div ng-include src="'app/policyApp/Windows/Dictionary/CLSiteDictionary.html'"></div>
+ <div ng-include src="'app/policyApp/Windows/Dictionary/CLVarbindDictionary.html'"></div>
+ <div ng-include src="'app/policyApp/Windows/Dictionary/CLVnfTypeDictionary.html'"></div>
+ <div ng-include src="'app/policyApp/Windows/Dictionary/CLVsclActionDictionary.html'"></div>
+ <div ng-include src="'app/policyApp/Windows/Dictionary/DecisionSettingsDictionary.html'"></div>
+ <div ng-include src="'app/policyApp/Windows/Dictionary/DecisionRainyDayDictionary.html'"></div>
+ <div ng-include src="'app/policyApp/Windows/Dictionary/DescriptiveScopeDictionary.html'"></div>
+ <div ng-include src="'app/policyApp/Windows/Dictionary/OnapNameDictionary.html'"></div>
+ <div ng-include src="'app/policyApp/Windows/Dictionary/EnforcerTypeDictionary.html'"></div>
+ <div ng-include src="'app/policyApp/Windows/Dictionary/FWActionListDictionary.html'"></div>
+ <div ng-include src="'app/policyApp/Windows/Dictionary/FWAddressGroupDictionary.html'"></div>
+ <div ng-include src="'app/policyApp/Windows/Dictionary/FWParentListDictionary.html'"></div>
+ <div ng-include src="'app/policyApp/Windows/Dictionary/FWPortListDictionary.html'"></div>
+ <div ng-include src="'app/policyApp/Windows/Dictionary/FWPrefixListDictionary.html'"></div>
+ <div ng-include src="'app/policyApp/Windows/Dictionary/FWProtocolListDictionary.html'"></div>
+ <div ng-include src="'app/policyApp/Windows/Dictionary/FWSecurityZoneDictionary.html'"></div>
+ <div ng-include src="'app/policyApp/Windows/Dictionary/FWServiceGroupDictionary.html'"></div>
+ <div ng-include src="'app/policyApp/Windows/Dictionary/FWServiceListDictionary.html'"></div>
+ <div ng-include src="'app/policyApp/Windows/Dictionary/FWTag.html'"></div>
+ <div ng-include src="'app/policyApp/Windows/Dictionary/FWTagPicker.html'"></div>
+ <div ng-include src="'app/policyApp/Windows/Dictionary/FWTermListDictionary.html'"></div>
+ <div ng-include src="'app/policyApp/Windows/Dictionary/FWZoneDictionary.html'"></div>
+ <div ng-include src="'app/policyApp/Windows/Dictionary/MSConfigNameDictionary.html'"></div>
+ <div ng-include src="'app/policyApp/Windows/Dictionary/MSHeaderDefaultValuesDictionary.html'"></div>
+ <div ng-include src="'app/policyApp/Windows/Dictionary/MSDCAEUUIDDictionary.html'"></div>
+ <div ng-include src="'app/policyApp/Windows/Dictionary/MSLocationDictionary.html'"></div>
+ <div ng-include src="'app/policyApp/Windows/Dictionary/MSModelsDictionary.html'"></div>
+ <div ng-include src="'app/policyApp/Windows/Dictionary/MSModelDictionaryData.html'"></div>
+ <div ng-include src="'app/policyApp/Windows/Dictionary/ModelAttributeDictionary.html'"></div>
+ <div ng-include src="'app/policyApp/Windows/Dictionary/OptimizationModelsDictionary.html'"></div>
+ <div ng-include src="'app/policyApp/Windows/Dictionary/PSClosedLoopDictionary.html'"></div>
+ <div ng-include src="'app/policyApp/Windows/Dictionary/PSGroupPolicyScopeDictionary.html'"></div>
+ <div ng-include src="'app/policyApp/Windows/Dictionary/PSResourceDictionary.html'"></div>
+ <div ng-include src="'app/policyApp/Windows/Dictionary/PSServiceDictionary.html'"></div>
+ <div ng-include src="'app/policyApp/Windows/Dictionary/PSTypeDictionary.html'"></div>
+ <div ng-include src="'app/policyApp/Windows/Dictionary/RiskTypeDictionary.html'"></div>
+ <div ng-include src="'app/policyApp/Windows/Dictionary/RiskTypeDictionary.html'"></div>
+ <div ng-include src="'app/policyApp/Windows/Dictionary/SafePolicyWarningDictionary.html'"></div>
+
+ <div ng-include src="'app/policyApp/Windows/PDPTabWindows/PdpStatusWindow.html'"></div>
+ <div ng-include src="'app/policyApp/Windows/Edit_Roles_Window.html'"></div>
+ <div ng-include src="'app/policyApp/Windows/PushtabWindow/removeGroupPoliciesWindow.html'"></div>
+ <div ng-include src="'app/policyApp/Windows/popup_modal.html'"></div>
+ <div ds2-Footer class="footer-container"></div>
+ </body>
</html>
diff --git a/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/PolicyTemplateController/ActionPolicyController.js b/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/PolicyTemplateController/ActionPolicyController.js
index a9097d559..80c11463f 100644
--- a/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/PolicyTemplateController/ActionPolicyController.js
+++ b/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/PolicyTemplateController/ActionPolicyController.js
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP Policy Engine
* ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017, 2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -28,7 +28,7 @@ app.controller('actionPolicyController', ['$scope', 'PolicyAppService', 'policyN
$scope.temp.policy = {
policyType : "Action"
}
- };
+ }
$scope.refresh = function(){
if($scope.refreshCheck){
@@ -36,7 +36,7 @@ app.controller('actionPolicyController', ['$scope', 'PolicyAppService', 'policyN
}
$scope.modal('createNewPolicy', true);
$scope.temp.policy = "";
- };
+ }
$scope.modal = function(id, hide) {
return $('#' + id).modal(hide ? 'hide' : 'show');
@@ -71,13 +71,6 @@ app.controller('actionPolicyController', ['$scope', 'PolicyAppService', 'policyN
}, function (error) {
console.log("failed");
});
-
- function extend(obj, src) {
- for (var key in src) {
- if (src.hasOwnProperty(key)) obj[key] = src[key];
- }
- return obj;
- }
$scope.saveActionPolicy = function(policy){
if(policy.itemContent != undefined){
@@ -191,4 +184,4 @@ app.controller('actionPolicyController', ['$scope', 'PolicyAppService', 'policyN
$scope.temp.policy.ruleAlgorithmschoices.splice(lastItem);
};
-}]); \ No newline at end of file
+}]);
diff --git a/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/PolicyTemplateController/BRMSParamPolicyController.js b/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/PolicyTemplateController/BRMSParamPolicyController.js
index 22511c5a7..35fb3cb81 100644
--- a/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/PolicyTemplateController/BRMSParamPolicyController.js
+++ b/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/PolicyTemplateController/BRMSParamPolicyController.js
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP Policy Engine
* ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017, 2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -17,7 +17,9 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-angular.module('abs').controller('brmsParamPolicyController', ['$scope', '$window', 'PolicyAppService', 'policyNavigator', 'modalService', '$modal', 'Notification', function ($scope, $window, PolicyAppService, PolicyNavigator, modalService, $modal, Notification) {
+angular.module('abs').controller('brmsParamPolicyController',
+ ['$scope', '$window', 'PolicyAppService', 'policyNavigator', 'modalService', '$modal', 'Notification',
+ function ($scope, $window, PolicyAppService, PolicyNavigator, modalService, $modal, Notification) {
$("#dialog").hide();
$scope.policyNavigator;
@@ -25,18 +27,18 @@ angular.module('abs').controller('brmsParamPolicyController', ['$scope', '$windo
$scope.refreshCheck = false;
if(!$scope.temp.policy.editPolicy && !$scope.temp.policy.readOnly){
- $scope.temp.policy = {
- policyType : "Config",
- configPolicyType : "BRMS_Param"
- }
- };
+ $scope.temp.policy = {
+ policyType : "Config",
+ configPolicyType : "BRMS_Param"
+ }
+ }
$scope.refresh = function(){
- if($scope.refreshCheck){
- $scope.policyNavigator.refresh();
- }
- $scope.modal('createNewPolicy', true);
- $scope.temp.policy = "";
+ if($scope.refreshCheck){
+ $scope.policyNavigator.refresh();
+ }
+ $scope.modal('createNewPolicy', true);
+ $scope.temp.policy = "";
};
$scope.modal = function(id, hide) {
@@ -44,66 +46,49 @@ angular.module('abs').controller('brmsParamPolicyController', ['$scope', '$windo
};
$('#ttlDate').datepicker({
- dateFormat: 'dd/mm/yy',
- changeMonth: true,
- changeYear: true,
- onSelect: function(date) {
- angular.element($('#ttlDate')).triggerHandler('input');
- }
+ dateFormat: 'dd/mm/yy',
+ changeMonth: true,
+ changeYear: true,
+ onSelect: function(date) {
+ angular.element($('#ttlDate')).triggerHandler('input');
+ }
});
$scope.validateSuccess = true;
var readValue = $scope.temp.policy.readOnly;
if(readValue){
- $scope.validateSuccess = false;
+ $scope.validateSuccess = false;
}
PolicyAppService.getData('getDictionary/get_BRMSControllerDataByName').then(function (data) {
- var j = data;
- $scope.data = JSON.parse(j.data);
- console.log($scope.data);
- $scope.brmsControllerDatas = JSON.parse($scope.data.brmsControllerDictionaryDatas);
- console.log($scope.brmsControllerDatas);
- }, function (error) {
- console.log("failed");
+ var j = data;
+ $scope.data = JSON.parse(j.data);
+ $scope.brmsControllerDatas = JSON.parse($scope.data.brmsControllerDictionaryDatas);
});
PolicyAppService.getData('getDictionary/get_BRMSDependencyDataByName').then(function (data) {
- var j = data;
- $scope.data = JSON.parse(j.data);
- console.log($scope.data);
- $scope.brmsDependencyDatas = JSON.parse($scope.data.brmsDependencyDictionaryDatas);
- console.log($scope.brmsDependencyDatas);
- }, function (error) {
- console.log("failed");
+ var j = data;
+ $scope.data = JSON.parse(j.data);
+ $scope.brmsDependencyDatas = JSON.parse($scope.data.brmsDependencyDictionaryDatas);
});
PolicyAppService.getData('getDictionary/get_BRMSParamDataByName').then(function (data) {
- var j = data;
- $scope.data = JSON.parse(j.data);
- console.log($scope.data);
- $scope.brmsParamDictionaryDatas = JSON.parse($scope.data.brmsParamDictionaryDatas);
- console.log($scope.brmsParamDictionaryDatas);
- }, function (error) {
- console.log("failed");
+ var j = data;
+ $scope.data = JSON.parse(j.data);
+ $scope.brmsParamDictionaryDatas = JSON.parse($scope.data.brmsParamDictionaryDatas);
});
PolicyAppService.getData('getDictionary/get_RiskTypeDataByName').then(function (data) {
- var j = data;
- $scope.data = JSON.parse(j.data);
- console.log($scope.data);
- $scope.riskTypeDictionaryDatas = JSON.parse($scope.data.riskTypeDictionaryDatas);
- console.log($scope.riskTypeDictionaryDatas);
- }, function (error) {
- console.log("failed");
+ var j = data;
+ $scope.data = JSON.parse(j.data);
+ $scope.riskTypeDictionaryDatas = JSON.parse($scope.data.riskTypeDictionaryDatas);
});
$scope.temp.policy.dynamicLayoutMap = {};
$scope.addDataToFields = function(ruleName){
- console.log(ruleName);
if(ruleName != null){
- var uuu = "policyController/getBRMSTemplateData.htm";
- var postData={policyData: ruleName};
+ var uuu = "policyController/getBRMSTemplateData.htm";
+ var postData={policyData: ruleName};
$.ajax({
type : 'POST',
url : uuu,
@@ -112,12 +97,11 @@ angular.module('abs').controller('brmsParamPolicyController', ['$scope', '$windo
data: JSON.stringify(postData),
success : function(data){
$scope.$apply(function(){
- $scope.temp.policy.dynamicLayoutMap = data.policyData;
+ $scope.temp.policy.dynamicLayoutMap = data.policyData;
});
- console.log( $scope.temp.policy.dynamicLayoutMap);
},
error : function(data){
- alert("Error While Retriving the Template Layout Pattren.");
+ Notification.error("Error While Retriving the Template Layout Pattren.");
}
});
}
@@ -126,7 +110,6 @@ angular.module('abs').controller('brmsParamPolicyController', ['$scope', '$windo
$scope.showbrmsrule = true;
$scope.ShowRule = function(policy){
- console.log(policy);
var uuu = "policyController/ViewBRMSParamPolicyRule.htm";
var postData={policyData: policy};
$.ajax({
@@ -136,30 +119,30 @@ angular.module('abs').controller('brmsParamPolicyController', ['$scope', '$windo
contentType: 'application/json',
data: JSON.stringify(postData),
success : function(data){
- $scope.showbrmsrule = false;
- $scope.validateSuccess = true;
+ $scope.showbrmsrule = false;
+ $scope.validateSuccess = true;
$scope.$apply(function(){
- $scope.datarule = data.policyData;
+ $scope.datarule = data.policyData;
});
},
error : function(data){
- Notification.error("Error Occured while Showing Rule.");
+ Notification.error("Error Occured while Showing Rule.");
}
});
};
$scope.hideRule = function(){
- $scope.showbrmsrule = true;
- $scope.validateSuccess = false;
- $scope.apply();
+ $scope.showbrmsrule = true;
+ $scope.validateSuccess = false;
+ $scope.apply();
};
$scope.saveBrmsParamPolicy = function(policy){
- if(policy.itemContent != undefined){
- $scope.refreshCheck = true;
- $scope.policyNavigator = policy.itemContent;
- policy.itemContent = "";
- }
+ if(policy.itemContent != undefined){
+ $scope.refreshCheck = true;
+ $scope.policyNavigator = policy.itemContent;
+ policy.itemContent = "";
+ }
$scope.savebutton = false;
var uuu = "policycreation/save_policy";
var postData={policyData: policy};
@@ -173,83 +156,73 @@ angular.module('abs').controller('brmsParamPolicyController', ['$scope', '$windo
$scope.$apply(function(){
$scope.data=data.policyData;
if($scope.data == 'success'){
- $scope.temp.policy.readOnly = 'true';
- $scope.safetyChecker = data.policyData.split("#")[2];
- if ($scope.safetyChecker!=undefined) {
- Notification.success($scope.safetyChecker);
- }
- Notification.success("Policy Saved Successfully.");
+ $scope.temp.policy.readOnly = 'true';
+ $scope.safetyChecker = data.policyData.split("#")[2];
+ if ($scope.safetyChecker!=undefined) {
+ Notification.success($scope.safetyChecker);
+ }
+ Notification.success("Policy Saved Successfully.");
}else if ($scope.data == 'PolicyExists'){
- $scope.savebutton = true;
- Notification.error("Policy Already Exists with Same Name in Scope.");
- }
+ $scope.savebutton = true;
+ Notification.error("Policy Already Exists with Same Name in Scope.");
+ }
});
- console.log($scope.data);
},
error : function(data){
- Notification.error("Error Occured while saving Policy.");
- $scope.savebutton = true;
+ Notification.error("Error Occured while saving Policy.");
+ $scope.savebutton = true;
}
});
};
$scope.validatePolicy = function(policy){
- console.log(policy);
- document.getElementById("validate").innerHTML = "";
+ document.getElementById("validate").innerHTML = "";
var uuu = "policyController/validate_policy.htm";
- var postData={policyData: policy};
- $.ajax({
- type : 'POST',
- url : uuu,
- dataType: 'json',
- contentType: 'application/json',
- data: JSON.stringify(postData),
- success : function(data){
- $scope.$apply(function(){
- $scope.validateData = data.data.replace(/\"/g, "");
- $scope.data=data.data.substring(1,8);
- var size = data.data.length;
- if($scope.data == 'success'){
- Notification.success("Validation Success.");
- $scope.savebutton = false;
- if (size > 18){
- var displayWarning = data.data.substring(19,size);
- document.getElementById("validate").innerHTML = "Safe Policy Warning Message : "+displayWarning;
- document.getElementById("validate").style.color = "white";
- document.getElementById("validate").style.backgroundColor = "skyblue";
- }
- $scope.validateSuccess = false;
- }else{
- Notification.error("Validation Failed.");
- document.getElementById("validate").innerHTML = $scope.validateData;
- document.getElementById("validate").style.color = "white";
- document.getElementById("validate").style.backgroundColor = "red";
- $scope.savebutton = true;
- }
-
- });
- console.log($scope.data);
- },
- error : function(data){
- Notification.error("Validation Failed.");
- $scope.savebutton = true;
- }
- });
+ var postData={policyData: policy};
+ $.ajax({
+ type : 'POST',
+ url : uuu,
+ dataType: 'json',
+ contentType: 'application/json',
+ data: JSON.stringify(postData),
+ success : function(data){
+ $scope.$apply(function(){
+ $scope.validateData = data.data.replace(/\"/g, "");
+ $scope.data=data.data.substring(1,8);
+ var size = data.data.length;
+ if($scope.data == 'success'){
+ Notification.success("Validation Success.");
+ $scope.savebutton = false;
+ if (size > 18){
+ var displayWarning = data.data.substring(19,size);
+ document.getElementById("validate").innerHTML = "Safe Policy Warning Message : "+displayWarning;
+ document.getElementById("validate").style.color = "white";
+ document.getElementById("validate").style.backgroundColor = "skyblue";
+ }
+ $scope.validateSuccess = false;
+ }else{
+ Notification.error("Validation Failed.");
+ document.getElementById("validate").innerHTML = $scope.validateData;
+ document.getElementById("validate").style.color = "white";
+ document.getElementById("validate").style.backgroundColor = "red";
+ $scope.savebutton = true;
+ }
+
+ });
+ },
+ error : function(data){
+ Notification.error("Validation Failed.");
+ $scope.savebutton = true;
+ }
+ });
};
- function extend(obj, src) {
- for (var key in src) {
- if (src.hasOwnProperty(key)) obj[key] = src[key];
- }
- return obj;
- }
-
if(!$scope.temp.policy.editPolicy && !$scope.temp.policy.readOnly){
- $scope.temp.policy.attributes = [];
+ $scope.temp.policy.attributes = [];
}else{
- if($scope.temp.policy.attributes.length == 0){
- $scope.temp.policy.attributes = [];
- }
+ if($scope.temp.policy.attributes.length == 0){
+ $scope.temp.policy.attributes = [];
+ }
}
$scope.attributeDatas = [{"attributes" : $scope.temp.policy.attributes}];
@@ -261,4 +234,4 @@ angular.module('abs').controller('brmsParamPolicyController', ['$scope', '$windo
var lastItem = $scope.temp.policy.attributes.length-1;
$scope.temp.policy.attributes.splice(lastItem);
};
-}]); \ No newline at end of file
+}]);
diff --git a/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/PolicyTemplateController/BRMSRawPolicyController.js b/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/PolicyTemplateController/BRMSRawPolicyController.js
index 6061b1ef8..695cb423d 100644
--- a/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/PolicyTemplateController/BRMSRawPolicyController.js
+++ b/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/PolicyTemplateController/BRMSRawPolicyController.js
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP Policy Engine
* ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017, 2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -17,7 +17,9 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-angular.module('abs').controller('brmsRawPolicyController', ['$scope', '$window', 'PolicyAppService', 'policyNavigator', 'modalService', '$modal', 'Notification', function ($scope, $window, PolicyAppService, PolicyNavigator, modalService, $modal, Notification) {
+angular.module('abs').controller('brmsRawPolicyController',
+ ['$scope', '$window', 'PolicyAppService', 'policyNavigator', 'modalService', '$modal', 'Notification',
+ function ($scope, $window, PolicyAppService, PolicyNavigator, modalService, $modal, Notification) {
$("#dialog").hide();
$scope.policyNavigator;
@@ -25,18 +27,18 @@ angular.module('abs').controller('brmsRawPolicyController', ['$scope', '$window'
$scope.refreshCheck = false;
if(!$scope.temp.policy.editPolicy && !$scope.temp.policy.readOnly){
- $scope.temp.policy = {
- policyType : "Config",
- configPolicyType : "BRMS_Raw"
- }
- };
+ $scope.temp.policy = {
+ policyType : "Config",
+ configPolicyType : "BRMS_Raw"
+ }
+ }
$scope.refresh = function(){
- if($scope.refreshCheck){
- $scope.policyNavigator.refresh();
- }
- $scope.modal('createNewPolicy', true);
- $scope.temp.policy = "";
+ if($scope.refreshCheck){
+ $scope.policyNavigator.refresh();
+ }
+ $scope.modal('createNewPolicy', true);
+ $scope.temp.policy = "";
};
$scope.modal = function(id, hide) {
@@ -44,134 +46,112 @@ angular.module('abs').controller('brmsRawPolicyController', ['$scope', '$window'
};
$('#ttlDate').datepicker({
- dateFormat: 'dd/mm/yy',
- changeMonth: true,
- changeYear: true,
- onSelect: function(date) {
- angular.element($('#ttlDate')).triggerHandler('input');
- }
+ dateFormat: 'dd/mm/yy',
+ changeMonth: true,
+ changeYear: true,
+ onSelect: function(date) {
+ angular.element($('#ttlDate')).triggerHandler('input');
+ }
});
PolicyAppService.getData('getDictionary/get_BRMSControllerDataByName').then(function (data) {
- var j = data;
- $scope.data = JSON.parse(j.data);
- console.log($scope.data);
- $scope.brmsControllerDatas = JSON.parse($scope.data.brmsControllerDictionaryDatas);
- console.log($scope.brmsControllerDatas);
- }, function (error) {
- console.log("failed");
+ var j = data;
+ $scope.data = JSON.parse(j.data);
+ $scope.brmsControllerDatas = JSON.parse($scope.data.brmsControllerDictionaryDatas);
});
PolicyAppService.getData('getDictionary/get_BRMSDependencyDataByName').then(function (data) {
- var j = data;
- $scope.data = JSON.parse(j.data);
- console.log($scope.data);
- $scope.brmsDependencyDatas = JSON.parse($scope.data.brmsDependencyDictionaryDatas);
- console.log($scope.brmsDependencyDatas);
- }, function (error) {
- console.log("failed");
+ var j = data;
+ $scope.data = JSON.parse(j.data);
+ $scope.brmsDependencyDatas = JSON.parse($scope.data.brmsDependencyDictionaryDatas);
});
PolicyAppService.getData('getDictionary/get_RiskTypeDataByName').then(function (data) {
- var j = data;
- $scope.data = JSON.parse(j.data);
- console.log($scope.data);
- $scope.riskTypeDictionaryDatas = JSON.parse($scope.data.riskTypeDictionaryDatas);
- console.log($scope.riskTypeDictionaryDatas);
- }, function (error) {
- console.log("failed");
+ var j = data;
+ $scope.data = JSON.parse(j.data);
+ $scope.riskTypeDictionaryDatas = JSON.parse($scope.data.riskTypeDictionaryDatas);
});
$scope.saveBrmsRawPolicy = function(policy){
- if(policy.itemContent != undefined){
- $scope.refreshCheck = true;
- $scope.policyNavigator = policy.itemContent;
- policy.itemContent = "";
- }
+ if(policy.itemContent != undefined){
+ $scope.refreshCheck = true;
+ $scope.policyNavigator = policy.itemContent;
+ policy.itemContent = "";
+ }
$scope.savebutton = false;
var uuu = "policycreation/save_policy";
- var postData={policyData: policy};
- $.ajax({
- type : 'POST',
- url : uuu,
- dataType: 'json',
- contentType: 'application/json',
- data: JSON.stringify(postData),
- success : function(data){
- $scope.$apply(function(){
- $scope.data=data.policyData;
- if($scope.data == 'success'){
- $scope.temp.policy.readOnly = 'true';
- Notification.success("Policy Saved Successfully.");
- }else if ($scope.data == 'PolicyExists'){
- $scope.savebutton = true;
- Notification.error("Policy Already Exists with Same Name in Scope.");
- }
- });
- console.log($scope.data);
- },
- error : function(data){
- Notification.error("Error Occured while saving Policy.");
- $scope.savebutton = true;
- }
- });
+ var postData={policyData: policy};
+ $.ajax({
+ type : 'POST',
+ url : uuu,
+ dataType: 'json',
+ contentType: 'application/json',
+ data: JSON.stringify(postData),
+ success : function(data){
+ $scope.$apply(function(){
+ $scope.data=data.policyData;
+ if($scope.data == 'success'){
+ $scope.temp.policy.readOnly = 'true';
+ Notification.success("Policy Saved Successfully.");
+ }else if ($scope.data == 'PolicyExists'){
+ $scope.savebutton = true;
+ Notification.error("Policy Already Exists with Same Name in Scope.");
+ }
+ });
+ },
+ error : function(data){
+ Notification.error("Error Occured while saving Policy.");
+ $scope.savebutton = true;
+ }
+ });
};
$scope.validatePolicy = function(policy){
- console.log(policy);
- document.getElementById("validate").innerHTML = "";
+ document.getElementById("validate").innerHTML = "";
var uuu = "policyController/validate_policy.htm";
- var postData={policyData: policy};
- $.ajax({
- type : 'POST',
- url : uuu,
- dataType: 'json',
- contentType: 'application/json',
- data: JSON.stringify(postData),
- success : function(data){
- $scope.$apply(function(){
- $scope.validateData = data.data.replace(/\"/g, "");
- $scope.data=data.data.substring(1,8);
- var size = data.data.length;
- if($scope.data == 'success'){
- Notification.success("Validation Success.");
- $scope.savebutton = false;
- if (size > 18){
- var displayWarning = data.data.substring(19,size);
- document.getElementById("validate").innerHTML = "Safe Policy Warning Message : "+displayWarning;
- document.getElementById("validate").style.color = "white";
- document.getElementById("validate").style.backgroundColor = "skyblue";
- }
- }else{
- Notification.error("Validation Failed.");
- document.getElementById("validate").innerHTML = $scope.validateData;
- document.getElementById("validate").style.color = "white";
- document.getElementById("validate").style.backgroundColor = "red";
- $scope.savebutton = true;
- }
-
- });
- console.log($scope.data);
- },
- error : function(data){
- Notification.error("Validation Failed.");
- }
- });
+ var postData={policyData: policy};
+ $.ajax({
+ type : 'POST',
+ url : uuu,
+ dataType: 'json',
+ contentType: 'application/json',
+ data: JSON.stringify(postData),
+ success : function(data){
+ $scope.$apply(function(){
+ $scope.validateData = data.data.replace(/\"/g, "");
+ $scope.data=data.data.substring(1,8);
+ var size = data.data.length;
+ if($scope.data == 'success'){
+ Notification.success("Validation Success.");
+ $scope.savebutton = false;
+ if (size > 18){
+ var displayWarning = data.data.substring(19,size);
+ document.getElementById("validate").innerHTML = "Safe Policy Warning Message : "+displayWarning;
+ document.getElementById("validate").style.color = "white";
+ document.getElementById("validate").style.backgroundColor = "skyblue";
+ }
+ }else{
+ Notification.error("Validation Failed.");
+ document.getElementById("validate").innerHTML = $scope.validateData;
+ document.getElementById("validate").style.color = "white";
+ document.getElementById("validate").style.backgroundColor = "red";
+ $scope.savebutton = true;
+ }
+
+ });
+ },
+ error : function(data){
+ Notification.error("Validation Failed.");
+ }
+ });
};
- function extend(obj, src) {
- for (var key in src) {
- if (src.hasOwnProperty(key)) obj[key] = src[key];
- }
- return obj;
- }
-
if(!$scope.temp.policy.editPolicy && !$scope.temp.policy.readOnly){
- $scope.temp.policy.attributes = [];
+ $scope.temp.policy.attributes = [];
}else{
- if($scope.temp.policy.attributes.length == 0){
- $scope.temp.policy.attributes = [];
- }
+ if($scope.temp.policy.attributes.length == 0){
+ $scope.temp.policy.attributes = [];
+ }
}
$scope.attributeDatas = [{"attributes" : $scope.temp.policy.attributes}];
$scope.addNewChoice = function() {
@@ -182,4 +162,4 @@ angular.module('abs').controller('brmsRawPolicyController', ['$scope', '$window'
var lastItem = $scope.temp.policy.attributes.length-1;
$scope.temp.policy.attributes.splice(lastItem);
};
-}]); \ No newline at end of file
+}]);
diff --git a/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/PolicyTemplateController/BaseConfigPolicyController.js b/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/PolicyTemplateController/BaseConfigPolicyController.js
index 02e10bddd..f950e7434 100644
--- a/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/PolicyTemplateController/BaseConfigPolicyController.js
+++ b/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/PolicyTemplateController/BaseConfigPolicyController.js
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP Policy Engine
* ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017, 2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -30,7 +30,7 @@ app.controller('baseConfigController', ['$scope', 'PolicyAppService', 'policyNav
policyType : "Config",
configPolicyType : "Base"
}
- };
+ }
$scope.refresh = function(){
if($scope.refreshCheck){
@@ -177,4 +177,4 @@ app.controller('baseConfigController', ['$scope', 'PolicyAppService', 'policyNav
var lastItem = $scope.temp.policy.attributes.length-1;
$scope.temp.policy.attributes.splice(lastItem);
};
-}]); \ No newline at end of file
+}]);
diff --git a/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/PolicyTemplateController/ClosedLoopFaultController.js b/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/PolicyTemplateController/ClosedLoopFaultController.js
index ebc9001ab..a8368a05e 100644
--- a/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/PolicyTemplateController/ClosedLoopFaultController.js
+++ b/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/PolicyTemplateController/ClosedLoopFaultController.js
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP Policy Engine
* ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017, 2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -17,26 +17,28 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-angular.module("abs").controller('clFaultController', ['$scope', '$window', 'PolicyAppService', 'policyNavigator', 'modalService', '$modal', 'Notification', function($scope, $window, PolicyAppService, PolicyNavigator, modalService, $modal, Notification){
- $("#dialog").hide();
+angular.module("abs").controller('clFaultController',
+ ['$scope', '$window', 'PolicyAppService', 'policyNavigator', 'modalService', '$modal', 'Notification',
+ function($scope, $window, PolicyAppService, PolicyNavigator, modalService, $modal, Notification){
+ $("#dialog").hide();
- $scope.policyNavigator;
- $scope.savebutton = true;
- $scope.refreshCheck = false;
+ $scope.policyNavigator;
+ $scope.savebutton = true;
+ $scope.refreshCheck = false;
- if(!$scope.temp.policy.editPolicy && !$scope.temp.policy.readOnly){
- $scope.temp.policy = {
- policyType : "Config",
- configPolicyType : "ClosedLoop_Fault"
- }
- };
+ if(!$scope.temp.policy.editPolicy && !$scope.temp.policy.readOnly){
+ $scope.temp.policy = {
+ policyType : "Config",
+ configPolicyType : "ClosedLoop_Fault"
+ }
+ }
$scope.refresh = function(){
- if($scope.refreshCheck){
- $scope.policyNavigator.refresh();
- }
- $scope.modal('createNewPolicy', true);
- $scope.temp.policy = "";
+ if($scope.refreshCheck){
+ $scope.policyNavigator.refresh();
+ }
+ $scope.modal('createNewPolicy', true);
+ $scope.temp.policy = "";
};
$scope.modal = function(id, hide) {
@@ -44,784 +46,749 @@ angular.module("abs").controller('clFaultController', ['$scope', '$window', 'Pol
};
$('#ttlDate').datepicker({
- dateFormat: 'dd/mm/yy',
- changeMonth: true,
- changeYear: true,
- onSelect: function(date) {
- angular.element($('#ttlDate')).triggerHandler('input');
- }
+ dateFormat: 'dd/mm/yy',
+ changeMonth: true,
+ changeYear: true,
+ onSelect: function(date) {
+ angular.element($('#ttlDate')).triggerHandler('input');
+ }
});
-
- if($scope.temp.policy.triggerTrapSignatures == undefined){
- $scope.temp.policy.triggerTrapSignatures = [];
- $scope.temp.policy.triggerfaultSignatures = [];
- }
- var trapCollection = [];
- var faultCollection = [];
- if($scope.varbindDictionaryDatas == undefined){
- $scope.varbindDictionaryDatas = [];
- }
-
- $scope.init = function(data){
- if(data != undefined && $scope.temp.policy.triggerTrapSignatures.length == 0){
- $scope.jsonData = data;
- if($scope.jsonData.triggerSignaturesUsedForUI != null){
- if($scope.jsonData.triggerSignaturesUsedForUI.signatures != null){
- $scope.temp.policy.triggerTrapSignatures = {Trap1 : [], Trap2 : [], Trap3 : [], Trap4 : [], Trap5 : [], Trap6 : []};
- var splitTraps = $scope.jsonData.triggerSignaturesUsedForUI.signatures.split("#!?!");
- if(splitTraps.length > 1){
- $scope.triggerdisabled = false;
- var indexId = "Trap1";
- trapCollection.push(indexId);
- $scope.temp.policy.triggerTrapSignatures[indexId.replace(/['"]+/g, '')] = [];
- $scope.temp.policy.traptriggerSignatures.push({'id':'Trap'+1});
- var splitTrap1 = splitTraps[0];
- var splitEachTrap = splitTrap1.split("#!");
- for(i = 0 ; i < splitEachTrap.length; i++){
- var splitEachRow = splitEachTrap[i].split("@!");
- var count = i +1;
- if(splitEachRow[0] == 'NOT' || splitEachRow[0] ==''){
- var notBox = splitEachRow[0];
- var trigger1 = splitEachRow[1];
- var operatorBox = splitEachRow[2];
- var trigger2 = splitEachRow[3];
- }else{
- var notBox = '';
- var trigger1 = splitEachRow[0];
- var operatorBox = splitEachRow[1];
- var trigger2 = splitEachRow[2];
- }
- $scope.varbindDictionaryDatas.push('A'+count);
- $scope.temp.policy.triggerTrapSignatures["Trap1"].push({'id':'A'+count, 'notBox' : notBox , 'trigger1': trigger1 , 'operatorBox' : operatorBox, 'trigger2': trigger2});
- }
- }
- if(splitTraps.length > 2){
- var indexId = "Trap2";
- trapCollection.push(indexId);
- $scope.temp.policy.triggerTrapSignatures[indexId.replace(/['"]+/g, '')] = [];
- $scope.temp.policy.traptriggerSignatures.push({'id':'Trap'+2});
- var splitTrap1 = splitTraps[1];
- var splitEachTrap = splitTrap1.split("#!");
- for(i = 0 ; i < splitEachTrap.length; i++){
- var splitEachRow = splitEachTrap[i].split("@!");
- var count = i +1;
- if(splitEachRow[0] == 'NOT' || splitEachRow[0] == ''){
- var notBox = splitEachRow[0];
- var trigger1 = splitEachRow[1];
- var operatorBox = splitEachRow[2];
- var trigger2 = splitEachRow[3];
- }else{
- var notBox = '';
- var trigger1 = splitEachRow[0];
- var operatorBox = splitEachRow[1];
- var trigger2 = splitEachRow[2];
- }
- $scope.varbindDictionaryDatas.push('A'+count);
- $scope.temp.policy.triggerTrapSignatures["Trap2"].push({'id':'A'+count, 'notBox' : notBox , 'trigger1': trigger1 , 'operatorBox' : operatorBox, 'trigger2': trigger2});
- }
- }
- if(splitTraps.length > 3){
- var indexId = "Trap3";
- trapCollection.push(indexId);
- $scope.temp.policy.triggerTrapSignatures[indexId.replace(/['"]+/g, '')] = [];
- $scope.temp.policy.traptriggerSignatures.push({'id':'Trap'+3});
- var splitTrap1 = splitTraps[2];
- var splitEachTrap = splitTrap1.split("#!");
- for(i = 0 ; i < splitEachTrap.length; i++){
- var splitEachRow = splitEachTrap[i].split("@!");
- var count = i +1;
- if(splitEachRow[0] == 'NOT' || splitEachRow[0] ==''){
- var notBox = splitEachRow[0];
- var trigger1 = splitEachRow[1];
- var operatorBox = splitEachRow[2];
- var trigger2 = splitEachRow[3];
- }else{
- var notBox = '';
- var trigger1 = splitEachRow[0];
- var operatorBox = splitEachRow[1];
- var trigger2 = splitEachRow[2];
- }
- $scope.varbindDictionaryDatas.push('A'+count);
- $scope.temp.policy.triggerTrapSignatures["Trap3"].push({'id':'A'+count, 'notBox' : notBox , 'trigger1': trigger1 , 'operatorBox' : operatorBox, 'trigger2': trigger2});
- }
- }
- if(splitTraps.length > 4){
- var indexId = "Trap4";
- trapCollection.push(indexId);
- $scope.temp.policy.triggerTrapSignatures[indexId.replace(/['"]+/g, '')] = [];
- $scope.temp.policy.traptriggerSignatures.push({'id':'Trap'+4});
- var splitTrap1 = splitTraps[3];
- var splitEachTrap = splitTrap1.split("#!");
- for(i = 0 ; i < splitEachTrap.length; i++){
- var splitEachRow = splitEachTrap[i].split("@!");
- var count = i +1;
- if(splitEachRow[0] == 'NOT' || splitEachRow[0] ==''){
- var notBox = splitEachRow[0];
- var trigger1 = splitEachRow[1];
- var operatorBox = splitEachRow[2];
- var trigger2 = splitEachRow[3];
- }else{
- var notBox = '';
- var trigger1 = splitEachRow[0];
- var operatorBox = splitEachRow[1];
- var trigger2 = splitEachRow[2];
- }
- $scope.varbindDictionaryDatas.push('A'+count);
- $scope.temp.policy.triggerTrapSignatures["Trap4"].push({'id':'A'+count, 'notBox' : notBox , 'trigger1': trigger1 , 'operatorBox' : operatorBox, 'trigger2': trigger2});
- }
- }
- if(splitTraps.length > 5){
- var indexId = "Trap5";
- trapCollection.push(indexId);
- $scope.temp.policy.triggerTrapSignatures[indexId.replace(/['"]+/g, '')] = [];
- $scope.temp.policy.traptriggerSignatures.push({'id':'Trap'+5});
- var splitTrap1 = splitTraps[4];
- var splitEachTrap = splitTrap1.split("#!");
- for(i = 0 ; i < splitEachTrap.length; i++){
- var splitEachRow = splitEachTrap[i].split("@!");
- var count = i +1;
- if(splitEachRow[0] == 'NOT' || splitEachRow[0] ==''){
- var notBox = splitEachRow[0];
- var trigger1 = splitEachRow[1];
- var operatorBox = splitEachRow[2];
- var trigger2 = splitEachRow[3];
- }else{
- var notBox = '';
- var trigger1 = splitEachRow[0];
- var operatorBox = splitEachRow[1];
- var trigger2 = splitEachRow[2];
- }
- $scope.varbindDictionaryDatas.push('A'+count);
- $scope.temp.policy.triggerTrapSignatures["Trap5"].push({'id':'A'+count, 'notBox' : notBox , 'trigger1': trigger1 , 'operatorBox' : operatorBox, 'trigger2': trigger2});
- }
- }
- if(splitTraps.length > 6){
- var indexId = "Trap6";
- trapCollection.push(indexId);
- $scope.temp.policy.triggerTrapSignatures[indexId.replace(/['"]+/g, '')] = [];
- $scope.temp.policy.traptriggerSignatures.push({'id':'Trap'+6});
- var splitTrap1 = splitTraps[5];
- var splitEachTrap = splitTrap1.split("#!");
- for(i = 0 ; i < splitEachTrap.length; i++){
- var splitEachRow = splitEachTrap[i].split("@!");
- var count = i +1;
- if(splitEachRow[0] == 'NOT' || splitEachRow[0] ==''){
- var notBox = splitEachRow[0];
- var trigger1 = splitEachRow[1];
- var operatorBox = splitEachRow[2];
- var trigger2 = splitEachRow[3];
- }else{
- var notBox = '';
- var trigger1 = splitEachRow[0];
- var operatorBox = splitEachRow[1];
- var trigger2 = splitEachRow[2];
- }
- $scope.varbindDictionaryDatas.push('A'+count);
- $scope.temp.policy.triggerTrapSignatures["Trap6"].push({'id':'A'+count, 'notBox' : notBox , 'trigger1': trigger1 , 'operatorBox' : operatorBox, 'trigger2': trigger2});
- }
- }
- if($scope.jsonData.triggerSignaturesUsedForUI.connectSignatures != null){
- var splitConnectTraps = $scope.jsonData.triggerSignaturesUsedForUI.connectSignatures.split("#!?!");
- for(i=0; i < splitConnectTraps.length; i++){
- if(splitConnectTraps[i] != ""){
- var newConnectTrapItemNo = i+1;
- var connects = splitConnectTraps[i].split("@!");
- if(connects[0] == 'NOT' || connects[0] ==''){
- var notBox = connects[0];
- var connectTrap1 = connects[1];
- var trapCount1 = connects[2];
- var operatorBox = connects[3];
- var connectTrap2 = connects[4];
- var trapCount2 = connects[5];
- }else{
- var notBox = '';
- var connectTrap1 = connects[0];
- var trapCount1 = connects[1];
- var operatorBox = connects[2];
- var connectTrap2 = connects[3];
- var trapCount2 = connects[4];
- }
- $scope.temp.policy.connecttriggerSignatures.push({'id':'C'+newConnectTrapItemNo,'notBox' : notBox , 'connectTrap1': connectTrap1,'trapCount1' : trapCount1,
- 'operatorBox': operatorBox, 'connectTrap2': connectTrap2,'trapCount2' : trapCount2});
- }
- }
- }
- }
- }
- if($scope.jsonData.verificationSignaturesUsedForUI != null){
- if($scope.jsonData.verificationSignaturesUsedForUI.signatures != null){
- $scope.temp.policy.triggerfaultSignatures = {Fault1 : [], Fault2 : [], Fault3 : [], Fault4 : [], Fault5 : [], Fault6 : []};
- var splitTraps = $scope.jsonData.verificationSignaturesUsedForUI.signatures.split("#!?!");
- if(splitTraps.length > 1){
- $scope.verificationdisabled = false;
- var indexId = "Fault1";
- faultCollection.push(indexId);
- $scope.temp.policy.triggerfaultSignatures[indexId.replace(/['"]+/g, '')] = [];
- $scope.temp.policy.faulttriggerSignatures.push({'id':'Fault'+1});
- var splitTrap1 = splitTraps[0];
- var splitEachTrap = splitTrap1.split("#!");
- for(i = 0 ; i < splitEachTrap.length; i++){
- var splitEachRow = splitEachTrap[i].split("@!");
- var count = i +1;
- if(splitEachRow[0] == 'NOT' || splitEachRow[0] ==''){
- var notBox = splitEachRow[0];
- var trigger1 = splitEachRow[1];
- var operatorBox = splitEachRow[2];
- var trigger2 = splitEachRow[3];
- }else{
- var notBox = '';
- var trigger1 = splitEachRow[0];
- var operatorBox = splitEachRow[1];
- var trigger2 = splitEachRow[2];
- }
- $scope.varbindDictionaryDatas.push('A'+count);
- $scope.temp.policy.triggerfaultSignatures["Fault1"].push({'id':'A'+count, 'notBox' : notBox , 'trigger1': trigger1 , 'operatorBox' : operatorBox, 'trigger2': trigger2});
- }
- }
- if(splitTraps.length > 2){
- var indexId = "Fault2";
- faultCollection.push(indexId);
- $scope.temp.policy.triggerfaultSignatures[indexId.replace(/['"]+/g, '')] = [];
- $scope.temp.policy.faulttriggerSignatures.push({'id':'Fault'+2});
- var splitTrap1 = splitTraps[1];
- var splitEachTrap = splitTrap1.split("#!");
- for(i = 0 ; i < splitEachTrap.length; i++){
- var splitEachRow = splitEachTrap[i].split("@!");
- var count = i +1;
- if(splitEachRow[0] == 'NOT' || splitEachRow[0] == ''){
- var notBox = splitEachRow[0];
- var trigger1 = splitEachRow[1];
- var operatorBox = splitEachRow[2];
- var trigger2 = splitEachRow[3];
- }else{
- var notBox = '';
- var trigger1 = splitEachRow[0];
- var operatorBox = splitEachRow[1];
- var trigger2 = splitEachRow[2];
- }
- $scope.varbindDictionaryDatas.push('A'+count);
- $scope.temp.policy.triggerfaultSignatures["Fault2"].push({'id':'A'+count, 'notBox' : notBox , 'trigger1': trigger1 , 'operatorBox' : operatorBox, 'trigger2': trigger2});
- }
- }
- if(splitTraps.length > 3){
- var indexId = "Fault3";
- faultCollection.push(indexId);
- $scope.temp.policy.triggerfaultSignatures[indexId.replace(/['"]+/g, '')] = [];
- $scope.temp.policy.faulttriggerSignatures.push({'id':'Fault'+3});
- var splitTrap1 = splitTraps[2];
- var splitEachTrap = splitTrap1.split("#!");
- for(i = 0 ; i < splitEachTrap.length; i++){
- var splitEachRow = splitEachTrap[i].split("@!");
- var count = i +1;
- if(splitEachRow[0] == 'NOT' || splitEachRow[0] ==''){
- var notBox = splitEachRow[0];
- var trigger1 = splitEachRow[1];
- var operatorBox = splitEachRow[2];
- var trigger2 = splitEachRow[3];
- }else{
- var notBox = '';
- var trigger1 = splitEachRow[0];
- var operatorBox = splitEachRow[1];
- var trigger2 = splitEachRow[2];
- }
- $scope.varbindDictionaryDatas.push('A'+count);
- $scope.temp.policy.triggerfaultSignatures["Fault3"].push({'id':'A'+count, 'notBox' : notBox , 'trigger1': trigger1 , 'operatorBox' : operatorBox, 'trigger2': trigger2});
- }
- }
- if(splitTraps.length > 4){
- var indexId = "Fault4";
- faultCollection.push(indexId);
- $scope.temp.policy.triggerfaultSignatures[indexId.replace(/['"]+/g, '')] = [];
- $scope.temp.policy.faulttriggerSignatures.push({'id':'Fault'+4});
- var splitTrap1 = splitTraps[3];
- var splitEachTrap = splitTrap1.split("#!");
- for(i = 0 ; i < splitEachTrap.length; i++){
- var splitEachRow = splitEachTrap[i].split("@!");
- var count = i +1;
- if(splitEachRow[0] == 'NOT' || splitEachRow[0] ==''){
- var notBox = splitEachRow[0];
- var trigger1 = splitEachRow[1];
- var operatorBox = splitEachRow[2];
- var trigger2 = splitEachRow[3];
- }else{
- var notBox = '';
- var trigger1 = splitEachRow[0];
- var operatorBox = splitEachRow[1];
- var trigger2 = splitEachRow[2];
- }
- $scope.varbindDictionaryDatas.push('A'+count);
- $scope.temp.policy.triggerfaultSignatures["Fault4"].push({'id':'A'+count, 'notBox' : notBox , 'trigger1': trigger1 , 'operatorBox' : operatorBox, 'trigger2': trigger2});
- }
- }
- if(splitTraps.length > 5){
- var indexId = "Fault5";
- faultCollection.push(indexId);
- $scope.temp.policy.triggerfaultSignatures[indexId.replace(/['"]+/g, '')] = [];
- $scope.temp.policy.faulttriggerSignatures.push({'id':'Fault'+5});
- var splitTrap1 = splitTraps[4];
- var splitEachTrap = splitTrap1.split("#!");
- for(i = 0 ; i < splitEachTrap.length; i++){
- var splitEachRow = splitEachTrap[i].split("@!");
- var count = i +1;
- if(splitEachRow[0] == 'NOT' || splitEachRow[0] ==''){
- var notBox = splitEachRow[0];
- var trigger1 = splitEachRow[1];
- var operatorBox = splitEachRow[2];
- var trigger2 = splitEachRow[3];
- }else{
- var notBox = '';
- var trigger1 = splitEachRow[0];
- var operatorBox = splitEachRow[1];
- var trigger2 = splitEachRow[2];
- }
- $scope.varbindDictionaryDatas.push('A'+count);
- $scope.temp.policy.triggerfaultSignatures["Fault5"].push({'id':'A'+count, 'notBox' : notBox , 'trigger1': trigger1 , 'operatorBox' : operatorBox, 'trigger2': trigger2});
- }
- }
- if(splitTraps.length > 6){
- var indexId = "Fault6";
- faultCollection.push(indexId);
- $scope.temp.policy.triggerfaultSignatures[indexId.replace(/['"]+/g, '')] = [];
- $scope.temp.policy.faulttriggerSignatures.push({'id':'Fault'+6});
- var splitTrap1 = splitTraps[5];
- var splitEachTrap = splitTrap1.split("#!");
- for(i = 0 ; i < splitEachTrap.length; i++){
- var splitEachRow = splitEachTrap[i].split("@!");
- var count = i +1;
- if(splitEachRow[0] == 'NOT' || splitEachRow[0] ==''){
- var notBox = splitEachRow[0];
- var trigger1 = splitEachRow[1];
- var operatorBox = splitEachRow[2];
- var trigger2 = splitEachRow[3];
- }else{
- var notBox = '';
- var trigger1 = splitEachRow[0];
- var operatorBox = splitEachRow[1];
- var trigger2 = splitEachRow[2];
- }
- $scope.varbindDictionaryDatas.push('A'+count);
- $scope.temp.policy.triggerfaultSignatures["Fault6"].push({'id':'A'+count, 'notBox' : notBox , 'trigger1': trigger1 , 'operatorBox' : operatorBox, 'trigger2': trigger2});
- }
- }
+
+ if($scope.temp.policy.triggerTrapSignatures == undefined){
+ $scope.temp.policy.triggerTrapSignatures = [];
+ $scope.temp.policy.triggerfaultSignatures = [];
+ }
+ var trapCollection = [];
+ var faultCollection = [];
+ if($scope.varbindDictionaryDatas == undefined){
+ $scope.varbindDictionaryDatas = [];
+ }
+
+ $scope.init = function(data){
+ if(data != undefined && $scope.temp.policy.triggerTrapSignatures.length == 0){
+ $scope.jsonData = data;
+ if($scope.jsonData.triggerSignaturesUsedForUI != null){
+ if($scope.jsonData.triggerSignaturesUsedForUI.signatures != null){
+ $scope.temp.policy.triggerTrapSignatures = {Trap1 : [], Trap2 : [], Trap3 : [], Trap4 : [], Trap5 : [], Trap6 : []};
+ var splitTraps = $scope.jsonData.triggerSignaturesUsedForUI.signatures.split("#!?!");
+ if(splitTraps.length > 1){
+ $scope.triggerdisabled = false;
+ var indexId = "Trap1";
+ trapCollection.push(indexId);
+ $scope.temp.policy.triggerTrapSignatures[indexId.replace(/['"]+/g, '')] = [];
+ $scope.temp.policy.traptriggerSignatures.push({'id':'Trap'+1});
+ var splitTrap1 = splitTraps[0];
+ var splitEachTrap = splitTrap1.split("#!");
+ for(i = 0 ; i < splitEachTrap.length; i++){
+ var splitEachRow = splitEachTrap[i].split("@!");
+ var count = i +1;
+ if(splitEachRow[0] == 'NOT' || splitEachRow[0] ==''){
+ var notBox = splitEachRow[0];
+ var trigger1 = splitEachRow[1];
+ var operatorBox = splitEachRow[2];
+ var trigger2 = splitEachRow[3];
+ }else{
+ var notBox = '';
+ var trigger1 = splitEachRow[0];
+ var operatorBox = splitEachRow[1];
+ var trigger2 = splitEachRow[2];
+ }
+ $scope.varbindDictionaryDatas.push('A'+count);
+ $scope.temp.policy.triggerTrapSignatures["Trap1"].push({'id':'A'+count, 'notBox' : notBox , 'trigger1': trigger1 , 'operatorBox' : operatorBox, 'trigger2': trigger2});
+ }
+ }
+ if(splitTraps.length > 2){
+ var indexId = "Trap2";
+ trapCollection.push(indexId);
+ $scope.temp.policy.triggerTrapSignatures[indexId.replace(/['"]+/g, '')] = [];
+ $scope.temp.policy.traptriggerSignatures.push({'id':'Trap'+2});
+ var splitTrap1 = splitTraps[1];
+ var splitEachTrap = splitTrap1.split("#!");
+ for(i = 0 ; i < splitEachTrap.length; i++){
+ var splitEachRow = splitEachTrap[i].split("@!");
+ var count = i +1;
+ if(splitEachRow[0] == 'NOT' || splitEachRow[0] == ''){
+ var notBox = splitEachRow[0];
+ var trigger1 = splitEachRow[1];
+ var operatorBox = splitEachRow[2];
+ var trigger2 = splitEachRow[3];
+ }else{
+ var notBox = '';
+ var trigger1 = splitEachRow[0];
+ var operatorBox = splitEachRow[1];
+ var trigger2 = splitEachRow[2];
+ }
+ $scope.varbindDictionaryDatas.push('A'+count);
+ $scope.temp.policy.triggerTrapSignatures["Trap2"].push({'id':'A'+count, 'notBox' : notBox , 'trigger1': trigger1 , 'operatorBox' : operatorBox, 'trigger2': trigger2});
+ }
+ }
+ if(splitTraps.length > 3){
+ var indexId = "Trap3";
+ trapCollection.push(indexId);
+ $scope.temp.policy.triggerTrapSignatures[indexId.replace(/['"]+/g, '')] = [];
+ $scope.temp.policy.traptriggerSignatures.push({'id':'Trap'+3});
+ var splitTrap1 = splitTraps[2];
+ var splitEachTrap = splitTrap1.split("#!");
+ for(i = 0 ; i < splitEachTrap.length; i++){
+ var splitEachRow = splitEachTrap[i].split("@!");
+ var count = i +1;
+ if(splitEachRow[0] == 'NOT' || splitEachRow[0] ==''){
+ var notBox = splitEachRow[0];
+ var trigger1 = splitEachRow[1];
+ var operatorBox = splitEachRow[2];
+ var trigger2 = splitEachRow[3];
+ }else{
+ var notBox = '';
+ var trigger1 = splitEachRow[0];
+ var operatorBox = splitEachRow[1];
+ var trigger2 = splitEachRow[2];
+ }
+ $scope.varbindDictionaryDatas.push('A'+count);
+ $scope.temp.policy.triggerTrapSignatures["Trap3"].push({'id':'A'+count, 'notBox' : notBox , 'trigger1': trigger1 , 'operatorBox' : operatorBox, 'trigger2': trigger2});
+ }
+ }
+ if(splitTraps.length > 4){
+ var indexId = "Trap4";
+ trapCollection.push(indexId);
+ $scope.temp.policy.triggerTrapSignatures[indexId.replace(/['"]+/g, '')] = [];
+ $scope.temp.policy.traptriggerSignatures.push({'id':'Trap'+4});
+ var splitTrap1 = splitTraps[3];
+ var splitEachTrap = splitTrap1.split("#!");
+ for(i = 0 ; i < splitEachTrap.length; i++){
+ var splitEachRow = splitEachTrap[i].split("@!");
+ var count = i +1;
+ if(splitEachRow[0] == 'NOT' || splitEachRow[0] ==''){
+ var notBox = splitEachRow[0];
+ var trigger1 = splitEachRow[1];
+ var operatorBox = splitEachRow[2];
+ var trigger2 = splitEachRow[3];
+ }else{
+ var notBox = '';
+ var trigger1 = splitEachRow[0];
+ var operatorBox = splitEachRow[1];
+ var trigger2 = splitEachRow[2];
+ }
+ $scope.varbindDictionaryDatas.push('A'+count);
+ $scope.temp.policy.triggerTrapSignatures["Trap4"].push({'id':'A'+count, 'notBox' : notBox , 'trigger1': trigger1 , 'operatorBox' : operatorBox, 'trigger2': trigger2});
+ }
+ }
+ if(splitTraps.length > 5){
+ var indexId = "Trap5";
+ trapCollection.push(indexId);
+ $scope.temp.policy.triggerTrapSignatures[indexId.replace(/['"]+/g, '')] = [];
+ $scope.temp.policy.traptriggerSignatures.push({'id':'Trap'+5});
+ var splitTrap1 = splitTraps[4];
+ var splitEachTrap = splitTrap1.split("#!");
+ for(i = 0 ; i < splitEachTrap.length; i++){
+ var splitEachRow = splitEachTrap[i].split("@!");
+ var count = i +1;
+ if(splitEachRow[0] == 'NOT' || splitEachRow[0] ==''){
+ var notBox = splitEachRow[0];
+ var trigger1 = splitEachRow[1];
+ var operatorBox = splitEachRow[2];
+ var trigger2 = splitEachRow[3];
+ }else{
+ var notBox = '';
+ var trigger1 = splitEachRow[0];
+ var operatorBox = splitEachRow[1];
+ var trigger2 = splitEachRow[2];
+ }
+ $scope.varbindDictionaryDatas.push('A'+count);
+ $scope.temp.policy.triggerTrapSignatures["Trap5"].push({'id':'A'+count, 'notBox' : notBox , 'trigger1': trigger1 , 'operatorBox' : operatorBox, 'trigger2': trigger2});
+ }
+ }
+ if(splitTraps.length > 6){
+ var indexId = "Trap6";
+ trapCollection.push(indexId);
+ $scope.temp.policy.triggerTrapSignatures[indexId.replace(/['"]+/g, '')] = [];
+ $scope.temp.policy.traptriggerSignatures.push({'id':'Trap'+6});
+ var splitTrap1 = splitTraps[5];
+ var splitEachTrap = splitTrap1.split("#!");
+ for(i = 0 ; i < splitEachTrap.length; i++){
+ var splitEachRow = splitEachTrap[i].split("@!");
+ var count = i +1;
+ if(splitEachRow[0] == 'NOT' || splitEachRow[0] ==''){
+ var notBox = splitEachRow[0];
+ var trigger1 = splitEachRow[1];
+ var operatorBox = splitEachRow[2];
+ var trigger2 = splitEachRow[3];
+ }else{
+ var notBox = '';
+ var trigger1 = splitEachRow[0];
+ var operatorBox = splitEachRow[1];
+ var trigger2 = splitEachRow[2];
+ }
+ $scope.varbindDictionaryDatas.push('A'+count);
+ $scope.temp.policy.triggerTrapSignatures["Trap6"].push({'id':'A'+count, 'notBox' : notBox , 'trigger1': trigger1 , 'operatorBox' : operatorBox, 'trigger2': trigger2});
+ }
+ }
+ if($scope.jsonData.triggerSignaturesUsedForUI.connectSignatures != null){
+ var splitConnectTraps = $scope.jsonData.triggerSignaturesUsedForUI.connectSignatures.split("#!?!");
+ for(i=0; i < splitConnectTraps.length; i++){
+ if(splitConnectTraps[i] != ""){
+ var newConnectTrapItemNo = i+1;
+ var connects = splitConnectTraps[i].split("@!");
+ if(connects[0] == 'NOT' || connects[0] ==''){
+ var notBox = connects[0];
+ var connectTrap1 = connects[1];
+ var trapCount1 = connects[2];
+ var operatorBox = connects[3];
+ var connectTrap2 = connects[4];
+ var trapCount2 = connects[5];
+ }else{
+ var notBox = '';
+ var connectTrap1 = connects[0];
+ var trapCount1 = connects[1];
+ var operatorBox = connects[2];
+ var connectTrap2 = connects[3];
+ var trapCount2 = connects[4];
+ }
+ $scope.temp.policy.connecttriggerSignatures.push({'id':'C'+newConnectTrapItemNo,'notBox' : notBox , 'connectTrap1': connectTrap1,'trapCount1' : trapCount1,
+ 'operatorBox': operatorBox, 'connectTrap2': connectTrap2,'trapCount2' : trapCount2});
+ }
+ }
+ }
+ }
+ }
+ if($scope.jsonData.verificationSignaturesUsedForUI != null){
+ if($scope.jsonData.verificationSignaturesUsedForUI.signatures != null){
+ $scope.temp.policy.triggerfaultSignatures = {Fault1 : [], Fault2 : [], Fault3 : [], Fault4 : [], Fault5 : [], Fault6 : []};
+ var splitTraps = $scope.jsonData.verificationSignaturesUsedForUI.signatures.split("#!?!");
+ if(splitTraps.length > 1){
+ $scope.verificationdisabled = false;
+ var indexId = "Fault1";
+ faultCollection.push(indexId);
+ $scope.temp.policy.triggerfaultSignatures[indexId.replace(/['"]+/g, '')] = [];
+ $scope.temp.policy.faulttriggerSignatures.push({'id':'Fault'+1});
+ var splitTrap1 = splitTraps[0];
+ var splitEachTrap = splitTrap1.split("#!");
+ for(i = 0 ; i < splitEachTrap.length; i++){
+ var splitEachRow = splitEachTrap[i].split("@!");
+ var count = i +1;
+ if(splitEachRow[0] == 'NOT' || splitEachRow[0] ==''){
+ var notBox = splitEachRow[0];
+ var trigger1 = splitEachRow[1];
+ var operatorBox = splitEachRow[2];
+ var trigger2 = splitEachRow[3];
+ }else{
+ var notBox = '';
+ var trigger1 = splitEachRow[0];
+ var operatorBox = splitEachRow[1];
+ var trigger2 = splitEachRow[2];
+ }
+ $scope.varbindDictionaryDatas.push('A'+count);
+ $scope.temp.policy.triggerfaultSignatures["Fault1"].push({'id':'A'+count, 'notBox' : notBox , 'trigger1': trigger1 , 'operatorBox' : operatorBox, 'trigger2': trigger2});
+ }
+ }
+ if(splitTraps.length > 2){
+ var indexId = "Fault2";
+ faultCollection.push(indexId);
+ $scope.temp.policy.triggerfaultSignatures[indexId.replace(/['"]+/g, '')] = [];
+ $scope.temp.policy.faulttriggerSignatures.push({'id':'Fault'+2});
+ var splitTrap1 = splitTraps[1];
+ var splitEachTrap = splitTrap1.split("#!");
+ for(i = 0 ; i < splitEachTrap.length; i++){
+ var splitEachRow = splitEachTrap[i].split("@!");
+ var count = i +1;
+ if(splitEachRow[0] == 'NOT' || splitEachRow[0] == ''){
+ var notBox = splitEachRow[0];
+ var trigger1 = splitEachRow[1];
+ var operatorBox = splitEachRow[2];
+ var trigger2 = splitEachRow[3];
+ }else{
+ var notBox = '';
+ var trigger1 = splitEachRow[0];
+ var operatorBox = splitEachRow[1];
+ var trigger2 = splitEachRow[2];
+ }
+ $scope.varbindDictionaryDatas.push('A'+count);
+ $scope.temp.policy.triggerfaultSignatures["Fault2"].push({'id':'A'+count, 'notBox' : notBox , 'trigger1': trigger1 , 'operatorBox' : operatorBox, 'trigger2': trigger2});
+ }
+ }
+ if(splitTraps.length > 3){
+ var indexId = "Fault3";
+ faultCollection.push(indexId);
+ $scope.temp.policy.triggerfaultSignatures[indexId.replace(/['"]+/g, '')] = [];
+ $scope.temp.policy.faulttriggerSignatures.push({'id':'Fault'+3});
+ var splitTrap1 = splitTraps[2];
+ var splitEachTrap = splitTrap1.split("#!");
+ for(i = 0 ; i < splitEachTrap.length; i++){
+ var splitEachRow = splitEachTrap[i].split("@!");
+ var count = i +1;
+ if(splitEachRow[0] == 'NOT' || splitEachRow[0] ==''){
+ var notBox = splitEachRow[0];
+ var trigger1 = splitEachRow[1];
+ var operatorBox = splitEachRow[2];
+ var trigger2 = splitEachRow[3];
+ }else{
+ var notBox = '';
+ var trigger1 = splitEachRow[0];
+ var operatorBox = splitEachRow[1];
+ var trigger2 = splitEachRow[2];
+ }
+ $scope.varbindDictionaryDatas.push('A'+count);
+ $scope.temp.policy.triggerfaultSignatures["Fault3"].push({'id':'A'+count, 'notBox' : notBox , 'trigger1': trigger1 , 'operatorBox' : operatorBox, 'trigger2': trigger2});
+ }
+ }
+ if(splitTraps.length > 4){
+ var indexId = "Fault4";
+ faultCollection.push(indexId);
+ $scope.temp.policy.triggerfaultSignatures[indexId.replace(/['"]+/g, '')] = [];
+ $scope.temp.policy.faulttriggerSignatures.push({'id':'Fault'+4});
+ var splitTrap1 = splitTraps[3];
+ var splitEachTrap = splitTrap1.split("#!");
+ for(i = 0 ; i < splitEachTrap.length; i++){
+ var splitEachRow = splitEachTrap[i].split("@!");
+ var count = i +1;
+ if(splitEachRow[0] == 'NOT' || splitEachRow[0] ==''){
+ var notBox = splitEachRow[0];
+ var trigger1 = splitEachRow[1];
+ var operatorBox = splitEachRow[2];
+ var trigger2 = splitEachRow[3];
+ }else{
+ var notBox = '';
+ var trigger1 = splitEachRow[0];
+ var operatorBox = splitEachRow[1];
+ var trigger2 = splitEachRow[2];
+ }
+ $scope.varbindDictionaryDatas.push('A'+count);
+ $scope.temp.policy.triggerfaultSignatures["Fault4"].push({'id':'A'+count, 'notBox' : notBox , 'trigger1': trigger1 , 'operatorBox' : operatorBox, 'trigger2': trigger2});
+ }
+ }
+ if(splitTraps.length > 5){
+ var indexId = "Fault5";
+ faultCollection.push(indexId);
+ $scope.temp.policy.triggerfaultSignatures[indexId.replace(/['"]+/g, '')] = [];
+ $scope.temp.policy.faulttriggerSignatures.push({'id':'Fault'+5});
+ var splitTrap1 = splitTraps[4];
+ var splitEachTrap = splitTrap1.split("#!");
+ for(i = 0 ; i < splitEachTrap.length; i++){
+ var splitEachRow = splitEachTrap[i].split("@!");
+ var count = i +1;
+ if(splitEachRow[0] == 'NOT' || splitEachRow[0] ==''){
+ var notBox = splitEachRow[0];
+ var trigger1 = splitEachRow[1];
+ var operatorBox = splitEachRow[2];
+ var trigger2 = splitEachRow[3];
+ }else{
+ var notBox = '';
+ var trigger1 = splitEachRow[0];
+ var operatorBox = splitEachRow[1];
+ var trigger2 = splitEachRow[2];
+ }
+ $scope.varbindDictionaryDatas.push('A'+count);
+ $scope.temp.policy.triggerfaultSignatures["Fault5"].push({'id':'A'+count, 'notBox' : notBox , 'trigger1': trigger1 , 'operatorBox' : operatorBox, 'trigger2': trigger2});
+ }
+ }
+ if(splitTraps.length > 6){
+ var indexId = "Fault6";
+ faultCollection.push(indexId);
+ $scope.temp.policy.triggerfaultSignatures[indexId.replace(/['"]+/g, '')] = [];
+ $scope.temp.policy.faulttriggerSignatures.push({'id':'Fault'+6});
+ var splitTrap1 = splitTraps[5];
+ var splitEachTrap = splitTrap1.split("#!");
+ for(i = 0 ; i < splitEachTrap.length; i++){
+ var splitEachRow = splitEachTrap[i].split("@!");
+ var count = i +1;
+ if(splitEachRow[0] == 'NOT' || splitEachRow[0] ==''){
+ var notBox = splitEachRow[0];
+ var trigger1 = splitEachRow[1];
+ var operatorBox = splitEachRow[2];
+ var trigger2 = splitEachRow[3];
+ }else{
+ var notBox = '';
+ var trigger1 = splitEachRow[0];
+ var operatorBox = splitEachRow[1];
+ var trigger2 = splitEachRow[2];
+ }
+ $scope.varbindDictionaryDatas.push('A'+count);
+ $scope.temp.policy.triggerfaultSignatures["Fault6"].push({'id':'A'+count, 'notBox' : notBox , 'trigger1': trigger1 , 'operatorBox' : operatorBox, 'trigger2': trigger2});
+ }
+ }
- if($scope.jsonData.verificationSignaturesUsedForUI.connectSignatures != null){
- var splitConnectTraps = $scope.jsonData.verificationSignaturesUsedForUI.connectSignatures.split("#!?!");
- for(i=0; i < splitConnectTraps.length; i++){
- if(splitConnectTraps[i] != ""){
- var newConnectTrapItemNo = i+1;
- var connects = splitConnectTraps[i].split("@!");
- if(connects[0] == 'NOT' || connects[0] ==''){
- var notBox = connects[0];
- var connectTrap1 = connects[1];
- var trapCount1 = connects[2];
- var operatorBox = connects[3];
- var connectTrap2 = connects[4];
- var trapCount2 = connects[5];
- }else{
- var notBox = '';
- var connectTrap1 = connects[0];
- var trapCount1 = connects[1];
- var operatorBox = connects[2];
- var connectTrap2 = connects[3];
- var trapCount2 = connects[4];
- }
- $scope.temp.policy.connectVerificationSignatures.push({'id':'C'+newConnectTrapItemNo,'notBox' : notBox , 'connectTrap1': connectTrap1,'trapCount1' : trapCount1,
- 'operatorBox': operatorBox, 'connectTrap2': connectTrap2,'trapCount2' : trapCount2});
- }
- }
- }
- }
- }
- }
+ if($scope.jsonData.verificationSignaturesUsedForUI.connectSignatures != null){
+ var splitConnectTraps = $scope.jsonData.verificationSignaturesUsedForUI.connectSignatures.split("#!?!");
+ for(i=0; i < splitConnectTraps.length; i++){
+ if(splitConnectTraps[i] != ""){
+ var newConnectTrapItemNo = i+1;
+ var connects = splitConnectTraps[i].split("@!");
+ if(connects[0] == 'NOT' || connects[0] ==''){
+ var notBox = connects[0];
+ var connectTrap1 = connects[1];
+ var trapCount1 = connects[2];
+ var operatorBox = connects[3];
+ var connectTrap2 = connects[4];
+ var trapCount2 = connects[5];
+ }else{
+ var notBox = '';
+ var connectTrap1 = connects[0];
+ var trapCount1 = connects[1];
+ var operatorBox = connects[2];
+ var connectTrap2 = connects[3];
+ var trapCount2 = connects[4];
+ }
+ $scope.temp.policy.connectVerificationSignatures.push({'id':'C'+newConnectTrapItemNo,'notBox' : notBox , 'connectTrap1': connectTrap1,'trapCount1' : trapCount1,
+ 'operatorBox': operatorBox, 'connectTrap2': connectTrap2,'trapCount2' : trapCount2});
+ }
+ }
+ }
+ }
+ }
+ }
- };
+ };
- if($scope.temp.policy.readOnly){
- $scope.triggerdisabled = true;
- $scope.verificationdisabled = true;
- }else{
- $scope.triggerdisabled = false;
- $scope.verificationdisabled = false;
- }
-
+ if($scope.temp.policy.readOnly){
+ $scope.triggerdisabled = true;
+ $scope.verificationdisabled = true;
+ }else{
+ $scope.triggerdisabled = false;
+ $scope.verificationdisabled = false;
+ }
+
- PolicyAppService.getData('getDictionary/get_OnapNameDataByName').then(function (data) {
- var j = data;
- $scope.data = JSON.parse(j.data);
- console.log($scope.data);
- $scope.onapNameDictionaryDatas = JSON.parse($scope.data.onapNameDictionaryDatas);
- console.log($scope.onapNameDictionaryDatas);
- }, function (error) {
- console.log("failed");
- });
+ PolicyAppService.getData('getDictionary/get_OnapNameDataByName').then(function (data) {
+ var j = data;
+ $scope.data = JSON.parse(j.data);
+ $scope.onapNameDictionaryDatas = JSON.parse($scope.data.onapNameDictionaryDatas);
+ });
- PolicyAppService.getData('getDictionary/get_PEPOptionsDataByName').then(function (data) {
- var j = data;
- $scope.data = JSON.parse(j.data);
- console.log($scope.data);
- $scope.pepOptionsDictionaryDatas = JSON.parse($scope.data.pepOptionsDictionaryDatas);
- console.log($scope.pepOptionsDictionaryDatas);
- }, function (error) {
- console.log("failed");
- });
+ PolicyAppService.getData('getDictionary/get_PEPOptionsDataByName').then(function (data) {
+ var j = data;
+ $scope.data = JSON.parse(j.data);
+ $scope.pepOptionsDictionaryDatas = JSON.parse($scope.data.pepOptionsDictionaryDatas);
+ });
- PolicyAppService.getData('getDictionary/get_PEPOptionsData').then(function (data) {
- var j = data;
- $scope.data = JSON.parse(j.data);
- console.log($scope.data);
- $scope.pepOptionsDictionaryDataEntity = JSON.parse($scope.data.pepOptionsDictionaryDatas);
- console.log($scope.pepOptionsDictionaryDataEntity);
- }, function (error) {
- console.log("failed");
- });
+ PolicyAppService.getData('getDictionary/get_PEPOptionsData').then(function (data) {
+ var j = data;
+ $scope.data = JSON.parse(j.data);
+ $scope.pepOptionsDictionaryDataEntity = JSON.parse($scope.data.pepOptionsDictionaryDatas);
+ });
- PolicyAppService.getData('getDictionary/get_VarbindDictionaryDataByName').then(function (data) {
- var j = data;
- $scope.data = JSON.parse(j.data);
- console.log($scope.data);
- $scope.varbindDictionaryDatas = JSON.parse($scope.data.varbindDictionaryDatas);
- console.log($scope.varbindDictionaryDatas);
- }, function (error) {
- console.log("failed");
- });
+ PolicyAppService.getData('getDictionary/get_VarbindDictionaryDataByName').then(function (data) {
+ var j = data;
+ $scope.data = JSON.parse(j.data);
+ $scope.varbindDictionaryDatas = JSON.parse($scope.data.varbindDictionaryDatas);
+ });
- PolicyAppService.getData('getDictionary/get_VNFTypeDataByName').then(function (data) {
- var j = data;
- $scope.data = JSON.parse(j.data);
- console.log($scope.data);
- $scope.vnfTypeDictionaryDatas = JSON.parse($scope.data.vnfTypeDictionaryDatas);
- console.log($scope.vnfTypeDictionaryDatas);
- }, function (error) {
- console.log("failed");
- });
+ PolicyAppService.getData('getDictionary/get_VNFTypeDataByName').then(function (data) {
+ var j = data;
+ $scope.data = JSON.parse(j.data);
+ $scope.vnfTypeDictionaryDatas = JSON.parse($scope.data.vnfTypeDictionaryDatas);
+ });
- PolicyAppService.getData('getDictionary/get_VSCLActionDataByName').then(function (data) {
- var j = data;
- $scope.data = JSON.parse(j.data);
- console.log($scope.data);
- $scope.vsclActionDictionaryDatas = JSON.parse($scope.data.vsclActionDictionaryDatas);
- console.log($scope.vsclActionDictionaryDatas);
- }, function (error) {
- console.log("failed");
- });
+ PolicyAppService.getData('getDictionary/get_VSCLActionDataByName').then(function (data) {
+ var j = data;
+ $scope.data = JSON.parse(j.data);
+ $scope.vsclActionDictionaryDatas = JSON.parse($scope.data.vsclActionDictionaryDatas);
+ });
- PolicyAppService.getData('getDictionary/get_RiskTypeDataByName').then(function (data) {
- var j = data;
- $scope.data = JSON.parse(j.data);
- console.log($scope.data);
- $scope.riskTypeDictionaryDatas = JSON.parse($scope.data.riskTypeDictionaryDatas);
- console.log($scope.riskTypeDictionaryDatas);
- }, function (error) {
- console.log("failed");
- });
+ PolicyAppService.getData('getDictionary/get_RiskTypeDataByName').then(function (data) {
+ var j = data;
+ $scope.data = JSON.parse(j.data);
+ $scope.riskTypeDictionaryDatas = JSON.parse($scope.data.riskTypeDictionaryDatas);
+ });
- $scope.pepActionDictionaryDatas = [];
-
- $scope.getPepActionValues = function(pepOptionValue){
- for (var i = 0; i < $scope.pepOptionsDictionaryDataEntity.length; ++i) {
- var obj = $scope.pepOptionsDictionaryDataEntity[i];
- if (obj.pepName == pepOptionValue){
- var splitAlarm = obj.actions.split(':#@');
- for (var j = 0; j < splitAlarm.length; ++j) {
- $scope.pepActionDictionaryDatas.push(splitAlarm[j].split('=#@')[0]);
- }
- }
- }
- };
+ $scope.pepActionDictionaryDatas = [];
- function trapData(){
- var data = {};
- if($scope.temp.policy.triggerTrapSignatures.length == 1 || $scope.temp.policy.triggerTrapSignatures["Trap1"] != null){
- data = {trap1 : $scope.temp.policy.triggerTrapSignatures.Trap1 }
- }
- if($scope.temp.policy.triggerTrapSignatures.length == 2 || $scope.temp.policy.triggerTrapSignatures["Trap2"] != null){
- data = {trap1 : $scope.temp.policy.triggerTrapSignatures.Trap1, trap2 : $scope.temp.policy.triggerTrapSignatures.Trap2}
- }
- if($scope.temp.policy.triggerTrapSignatures.length == 3 || $scope.temp.policy.triggerTrapSignatures["Trap3"] != null){
- data = {trap1 : $scope.temp.policy.triggerTrapSignatures.Trap1, trap2 : $scope.temp.policy.triggerTrapSignatures.Trap2,
- trap3 : $scope.temp.policy.triggerTrapSignatures.Trap3}
- }
- if($scope.temp.policy.triggerTrapSignatures.length == 4 || $scope.temp.policy.triggerTrapSignatures["Trap4"] != null){
- data = {trap1 : $scope.temp.policy.triggerTrapSignatures.Trap1, trap2 : $scope.temp.policy.triggerTrapSignatures.Trap2,
- trap3 : $scope.temp.policy.triggerTrapSignatures.Trap3, trap4 : $scope.temp.policy.triggerTrapSignatures.Trap4}
- }
- if($scope.temp.policy.triggerTrapSignatures.length == 5 || $scope.temp.policy.triggerTrapSignatures["Trap5"] != null){
- data = {trap1 : $scope.temp.policy.triggerTrapSignatures.Trap1, trap2 : $scope.temp.policy.triggerTrapSignatures.Trap2,
- trap3 : $scope.temp.policy.triggerTrapSignatures.Trap3, trap4 : $scope.temp.policy.triggerTrapSignatures.Trap4,
- trap5 : $scope.temp.policy.triggerTrapSignatures.Trap5}
- }
- if($scope.temp.policy.triggerTrapSignatures.length == 6 || $scope.temp.policy.triggerTrapSignatures["Trap6"] != null){
- data = {trap1 : $scope.temp.policy.triggerTrapSignatures.Trap1, trap2 : $scope.temp.policy.triggerTrapSignatures.Trap2,
- trap3 : $scope.temp.policy.triggerTrapSignatures.Trap3, trap4 : $scope.temp.policy.triggerTrapSignatures.Trap4,
- trap5 : $scope.temp.policy.triggerTrapSignatures.Trap5, trap6 : $scope.temp.policy.triggerTrapSignatures.Trap6}
- }
- return data;
- }
-
- function faultDatas(){
- var faultData = {};
- if($scope.temp.policy.triggerfaultSignatures.length == 1 || $scope.temp.policy.triggerfaultSignatures["Fault1"] != null){
- faultData = {trap1 : $scope.temp.policy.triggerfaultSignatures.Fault1 }
- }
- if($scope.temp.policy.triggerfaultSignatures.length == 2 || $scope.temp.policy.triggerfaultSignatures["Fault2"] != null){
- faultData = {trap1 : $scope.temp.policy.triggerfaultSignatures.Fault1, trap2 : $scope.temp.policy.triggerfaultSignatures.Fault2}
- }
- if($scope.temp.policy.triggerfaultSignatures.length == 3 || $scope.temp.policy.triggerfaultSignatures["Fault3"] != null){
- faultData = {trap1 : $scope.temp.policy.triggerfaultSignatures.Fault1, trap2 : $scope.temp.policy.triggerfaultSignatures.Fault2,
- trap3 : $scope.temp.policy.triggerfaultSignatures.Fault3}
- }
- if($scope.temp.policy.triggerTrapSignatures.length == 4 || $scope.temp.policy.triggerfaultSignatures["Fault4"] != null){
- faultData = {trap1 : $scope.temp.policy.triggerfaultSignatures.Fault1, trap2 : $scope.temp.policy.triggerfaultSignatures.Fault2,
- trap3 : $scope.temp.policy.triggerfaultSignatures.Fault3, trap4 : $scope.temp.policy.triggerfaultSignatures.Fault4}
- }
- if($scope.temp.policy.triggerfaultSignatures.length == 5 || $scope.temp.policy.triggerfaultSignatures["Fault5"] != null){
- faultData = {trap1 : $scope.temp.policy.triggerfaultSignatures.Fault1, trap2 : $scope.temp.policy.triggerfaultSignatures.Fault2,
- trap3 : $scope.temp.policy.triggerfaultSignatures.Fault3, trap4 : $scope.temp.policy.triggerfaultSignatures.Fault4,
- trap5 : $scope.temp.policy.triggerfaultSignatures.Fault5}
- }
- if($scope.temp.policy.triggerfaultSignatures.length == 6 || $scope.temp.policy.triggerfaultSignatures["Fault6"] != null){
- faultData = {trap1 : $scope.temp.policy.triggerfaultSignatures.Fault1, trap2 : $scope.temp.policy.triggerfaultSignatures.Fault2,
- trap3 : $scope.temp.policy.triggerfaultSignatures.Fault3, trap4 : $scope.temp.policy.triggerfaultSignatures.Fault4,
- trap5 : $scope.temp.policy.triggerfaultSignatures.Fault5, trap6 : $scope.temp.policy.triggerfaultSignatures.Fault6}
- }
- return faultData;
- }
-
- $scope.saveFaultPolicy = function(policy){
- if(policy.itemContent != undefined){
- $scope.refreshCheck = true;
- $scope.policyNavigator = policy.itemContent;
- policy.itemContent = "";
- }
- $scope.savebutton = false;
- var data = trapData();
- var faultData = faultDatas();
- var uuu = "policycreation/save_policy";
- var postData={policyData: policy,
- trapData : data,
- faultData : faultData
- };
- $.ajax({
- type : 'POST',
- url : uuu,
- dataType: 'json',
- contentType: 'application/json',
- data: JSON.stringify(postData),
- success : function(data){
- $scope.$apply(function(){
- $scope.data=data.policyData;
- if($scope.data == 'success'){
- $scope.temp.policy.readOnly = 'true';
- $scope.pushStatus=data.policyData.split("&")[1];
- if($scope.pushStatus=="successPush"){
- Notification.success("Policy pushed successfully");
- }
- $scope.triggerdisabled = true;
- $scope.verificationdisabled = true;
- Notification.success("Policy Saved Successfully.");
- }else if ($scope.data == 'PolicyExists'){
- $scope.savebutton = true;
- Notification.error("Policy Already Exists with Same Name in Scope.");
- }
- });
- console.log($scope.data);
- },
- error : function(data){
- Notification.error("Error Occured while saving Policy.");
- }
- });
- };
-
- $scope.validatePolicy = function(policy){
- console.log(policy);
- document.getElementById("validate").innerHTML = "";
- var uuu = "policyController/validate_policy.htm";
- var data = trapData();
- var faultData = faultDatas();
- var postData={policyData: policy, trapData : data, faultData : faultData};
- $.ajax({
- type : 'POST',
- url : uuu,
- dataType: 'json',
- contentType: 'application/json',
- data: JSON.stringify(postData),
- success : function(data){
- $scope.$apply(function(){
- $scope.validateData = data.data.replace(/\"/g, "");
- $scope.data=data.data.substring(1,8);
- var size = data.data.length;
- if($scope.data == 'success'){
- Notification.success("Validation Success.");
- $scope.savebutton = false;
- if (size > 18){
- var displayWarning = data.data.substring(19,size);
- document.getElementById("validate").innerHTML = "Safe Policy Warning Message : "+displayWarning;
- document.getElementById("validate").style.color = "white";
- document.getElementById("validate").style.backgroundColor = "skyblue";
- }
- }else{
- Notification.error("Validation Failed.");
- document.getElementById("validate").innerHTML = $scope.validateData;
- document.getElementById("validate").style.color = "white";
- document.getElementById("validate").style.backgroundColor = "red";
- $scope.savebutton = true;
- }
+ $scope.getPepActionValues = function(pepOptionValue){
+ for (var i = 0; i < $scope.pepOptionsDictionaryDataEntity.length; ++i) {
+ var obj = $scope.pepOptionsDictionaryDataEntity[i];
+ if (obj.pepName == pepOptionValue){
+ var splitAlarm = obj.actions.split(':#@');
+ for (var j = 0; j < splitAlarm.length; ++j) {
+ $scope.pepActionDictionaryDatas.push(splitAlarm[j].split('=#@')[0]);
+ }
+ }
+ }
+ };
- });
- console.log($scope.data);
- },
- error : function(data){
- Notification.error("Validation Failed.");
- $scope.savebutton = true;
- }
- });
- };
- if($scope.connectTriggerTrapsList == undefined){
- $scope.connectTriggerTrapsList = [];
- }
- if($scope.temp.policy.traptriggerSignatures == undefined){
- $scope.temp.policy.traptriggerSignatures = [];
- }
-
- $scope.ItemNo = 0;
- $scope.TriggerSignatureDatas = [{"triggerSignatures" : $scope.temp.policy.traptriggerSignatures}];
- $scope.addTriggerButton = function() {
- $scope.triggerdisabled = false;
- var newItemNo = $scope.temp.policy.traptriggerSignatures.length+1;
- $scope.ItemNo = newItemNo;
- $scope.temp.policy.traptriggerSignatures.push({'id':'Trap'+newItemNo});
- $scope.connectTriggerTrapsList.push('Trap'+newItemNo);
- };
- $scope.removeTriggerButton = function() {
- var lastItem = $scope.temp.policy.traptriggerSignatures.length-1;
- $scope.temp.policy.traptriggerSignatures.splice(lastItem);
- $scope.connectTriggerTrapsList.splice('Trap'+lastItem);
- };
+ function trapData(){
+ var data = {};
+ if($scope.temp.policy.triggerTrapSignatures.length == 1 || $scope.temp.policy.triggerTrapSignatures["Trap1"] != null){
+ data = {trap1 : $scope.temp.policy.triggerTrapSignatures.Trap1 }
+ }
+ if($scope.temp.policy.triggerTrapSignatures.length == 2 || $scope.temp.policy.triggerTrapSignatures["Trap2"] != null){
+ data = {trap1 : $scope.temp.policy.triggerTrapSignatures.Trap1, trap2 : $scope.temp.policy.triggerTrapSignatures.Trap2}
+ }
+ if($scope.temp.policy.triggerTrapSignatures.length == 3 || $scope.temp.policy.triggerTrapSignatures["Trap3"] != null){
+ data = {trap1 : $scope.temp.policy.triggerTrapSignatures.Trap1, trap2 : $scope.temp.policy.triggerTrapSignatures.Trap2,
+ trap3 : $scope.temp.policy.triggerTrapSignatures.Trap3}
+ }
+ if($scope.temp.policy.triggerTrapSignatures.length == 4 || $scope.temp.policy.triggerTrapSignatures["Trap4"] != null){
+ data = {trap1 : $scope.temp.policy.triggerTrapSignatures.Trap1, trap2 : $scope.temp.policy.triggerTrapSignatures.Trap2,
+ trap3 : $scope.temp.policy.triggerTrapSignatures.Trap3, trap4 : $scope.temp.policy.triggerTrapSignatures.Trap4}
+ }
+ if($scope.temp.policy.triggerTrapSignatures.length == 5 || $scope.temp.policy.triggerTrapSignatures["Trap5"] != null){
+ data = {trap1 : $scope.temp.policy.triggerTrapSignatures.Trap1, trap2 : $scope.temp.policy.triggerTrapSignatures.Trap2,
+ trap3 : $scope.temp.policy.triggerTrapSignatures.Trap3, trap4 : $scope.temp.policy.triggerTrapSignatures.Trap4,
+ trap5 : $scope.temp.policy.triggerTrapSignatures.Trap5}
+ }
+ if($scope.temp.policy.triggerTrapSignatures.length == 6 || $scope.temp.policy.triggerTrapSignatures["Trap6"] != null){
+ data = {trap1 : $scope.temp.policy.triggerTrapSignatures.Trap1, trap2 : $scope.temp.policy.triggerTrapSignatures.Trap2,
+ trap3 : $scope.temp.policy.triggerTrapSignatures.Trap3, trap4 : $scope.temp.policy.triggerTrapSignatures.Trap4,
+ trap5 : $scope.temp.policy.triggerTrapSignatures.Trap5, trap6 : $scope.temp.policy.triggerTrapSignatures.Trap6}
+ }
+ return data;
+ }
+
+ function faultDatas(){
+ var faultData = {};
+ if($scope.temp.policy.triggerfaultSignatures.length == 1 || $scope.temp.policy.triggerfaultSignatures["Fault1"] != null){
+ faultData = {trap1 : $scope.temp.policy.triggerfaultSignatures.Fault1 }
+ }
+ if($scope.temp.policy.triggerfaultSignatures.length == 2 || $scope.temp.policy.triggerfaultSignatures["Fault2"] != null){
+ faultData = {trap1 : $scope.temp.policy.triggerfaultSignatures.Fault1, trap2 : $scope.temp.policy.triggerfaultSignatures.Fault2}
+ }
+ if($scope.temp.policy.triggerfaultSignatures.length == 3 || $scope.temp.policy.triggerfaultSignatures["Fault3"] != null){
+ faultData = {trap1 : $scope.temp.policy.triggerfaultSignatures.Fault1, trap2 : $scope.temp.policy.triggerfaultSignatures.Fault2,
+ trap3 : $scope.temp.policy.triggerfaultSignatures.Fault3}
+ }
+ if($scope.temp.policy.triggerTrapSignatures.length == 4 || $scope.temp.policy.triggerfaultSignatures["Fault4"] != null){
+ faultData = {trap1 : $scope.temp.policy.triggerfaultSignatures.Fault1, trap2 : $scope.temp.policy.triggerfaultSignatures.Fault2,
+ trap3 : $scope.temp.policy.triggerfaultSignatures.Fault3, trap4 : $scope.temp.policy.triggerfaultSignatures.Fault4}
+ }
+ if($scope.temp.policy.triggerfaultSignatures.length == 5 || $scope.temp.policy.triggerfaultSignatures["Fault5"] != null){
+ faultData = {trap1 : $scope.temp.policy.triggerfaultSignatures.Fault1, trap2 : $scope.temp.policy.triggerfaultSignatures.Fault2,
+ trap3 : $scope.temp.policy.triggerfaultSignatures.Fault3, trap4 : $scope.temp.policy.triggerfaultSignatures.Fault4,
+ trap5 : $scope.temp.policy.triggerfaultSignatures.Fault5}
+ }
+ if($scope.temp.policy.triggerfaultSignatures.length == 6 || $scope.temp.policy.triggerfaultSignatures["Fault6"] != null){
+ faultData = {trap1 : $scope.temp.policy.triggerfaultSignatures.Fault1, trap2 : $scope.temp.policy.triggerfaultSignatures.Fault2,
+ trap3 : $scope.temp.policy.triggerfaultSignatures.Fault3, trap4 : $scope.temp.policy.triggerfaultSignatures.Fault4,
+ trap5 : $scope.temp.policy.triggerfaultSignatures.Fault5, trap6 : $scope.temp.policy.triggerfaultSignatures.Fault6}
+ }
+ return faultData;
+ }
+
+ $scope.saveFaultPolicy = function(policy){
+ if(policy.itemContent != undefined){
+ $scope.refreshCheck = true;
+ $scope.policyNavigator = policy.itemContent;
+ policy.itemContent = "";
+ }
+ $scope.savebutton = false;
+ var data = trapData();
+ var faultData = faultDatas();
+ var uuu = "policycreation/save_policy";
+ var postData={policyData: policy,
+ trapData : data,
+ faultData : faultData
+ };
+ $.ajax({
+ type : 'POST',
+ url : uuu,
+ dataType: 'json',
+ contentType: 'application/json',
+ data: JSON.stringify(postData),
+ success : function(data){
+ $scope.$apply(function(){
+ $scope.data=data.policyData;
+ if($scope.data == 'success'){
+ $scope.temp.policy.readOnly = 'true';
+ $scope.pushStatus=data.policyData.split("&")[1];
+ if($scope.pushStatus=="successPush"){
+ Notification.success("Policy pushed successfully");
+ }
+ $scope.triggerdisabled = true;
+ $scope.verificationdisabled = true;
+ Notification.success("Policy Saved Successfully.");
+ }else if ($scope.data == 'PolicyExists'){
+ $scope.savebutton = true;
+ Notification.error("Policy Already Exists with Same Name in Scope.");
+ }
+ });
+ },
+ error : function(data){
+ Notification.error("Error Occured while saving Policy.");
+ }
+ });
+ };
-
- $scope.trapItemNo = 0;
- $scope.TrapTriggerSignatureDatas = [{"triggermainSignatures" : $scope.temp.policy.triggerTrapSignatures}];
- $scope.addTrapTriggerButton = function(indexId) {
- if(trapCollection.indexOf(indexId) !== -1){
+ $scope.validatePolicy = function(policy){
+ document.getElementById("validate").innerHTML = "";
+ var uuu = "policyController/validate_policy.htm";
+ var data = trapData();
+ var faultData = faultDatas();
+ var postData={policyData: policy, trapData : data, faultData : faultData};
+ $.ajax({
+ type : 'POST',
+ url : uuu,
+ dataType: 'json',
+ contentType: 'application/json',
+ data: JSON.stringify(postData),
+ success : function(data){
+ $scope.$apply(function(){
+ $scope.validateData = data.data.replace(/\"/g, "");
+ $scope.data=data.data.substring(1,8);
+ var size = data.data.length;
+ if($scope.data == 'success'){
+ Notification.success("Validation Success.");
+ $scope.savebutton = false;
+ if (size > 18){
+ var displayWarning = data.data.substring(19,size);
+ document.getElementById("validate").innerHTML = "Safe Policy Warning Message : "+displayWarning;
+ document.getElementById("validate").style.color = "white";
+ document.getElementById("validate").style.backgroundColor = "skyblue";
+ }
+ }else{
+ Notification.error("Validation Failed.");
+ document.getElementById("validate").innerHTML = $scope.validateData;
+ document.getElementById("validate").style.color = "white";
+ document.getElementById("validate").style.backgroundColor = "red";
+ $scope.savebutton = true;
+ }
- }else{
- $scope.temp.policy.triggerTrapSignatures[indexId] = [];
- trapCollection.push(indexId);
- }
- var newTrapItemNo = $scope.temp.policy.triggerTrapSignatures[indexId].length+1;
- $scope.trapItemNo = newTrapItemNo;
- $scope.temp.policy.triggerTrapSignatures.push($scope.temp.policy.triggerTrapSignatures[indexId].push({'id':'A'+newTrapItemNo}));
- if(newTrapItemNo > 1){
- var count = newTrapItemNo-1;
- $scope.varbindDictionaryDatas.push('A'+count);
- }
- };
- $scope.removeTrapTriggerButton = function(indexId) {
- var lastTrapItem = $scope.temp.policy.triggerTrapSignatures[indexId].length-1;
- var checkLastTrapItem = lastTrapItem;
- if(checkLastTrapItem == 0){
- trapCollection.splice(indexId);
- }
- $scope.temp.policy.triggerTrapSignatures[indexId].splice(lastTrapItem);
- };
+ });
+ },
+ error : function(data){
+ Notification.error("Validation Failed.");
+ $scope.savebutton = true;
+ }
+ });
+ };
+ if($scope.connectTriggerTrapsList == undefined){
+ $scope.connectTriggerTrapsList = [];
+ }
+ if($scope.temp.policy.traptriggerSignatures == undefined){
+ $scope.temp.policy.traptriggerSignatures = [];
+ }
+
+ $scope.ItemNo = 0;
+ $scope.TriggerSignatureDatas = [{"triggerSignatures" : $scope.temp.policy.traptriggerSignatures}];
+ $scope.addTriggerButton = function() {
+ $scope.triggerdisabled = false;
+ var newItemNo = $scope.temp.policy.traptriggerSignatures.length+1;
+ $scope.ItemNo = newItemNo;
+ $scope.temp.policy.traptriggerSignatures.push({'id':'Trap'+newItemNo});
+ $scope.connectTriggerTrapsList.push('Trap'+newItemNo);
+ };
+ $scope.removeTriggerButton = function() {
+ var lastItem = $scope.temp.policy.traptriggerSignatures.length-1;
+ $scope.temp.policy.traptriggerSignatures.splice(lastItem);
+ $scope.connectTriggerTrapsList.splice('Trap'+lastItem);
+ };
- if($scope.temp.policy.connecttriggerSignatures == undefined){
- $scope.temp.policy.connecttriggerSignatures = [];
- }
-
- $scope.connecttrapItemNo = 0;
- $scope.TrapConnectTriggerSignatureDatas = [{"connecttriggerSignatures" : $scope.temp.policy.connecttriggerSignatures}];
- $scope.addTriggerConnectButton = function() {
- var newConnectTrapItemNo = $scope.temp.policy.connecttriggerSignatures.length+1;
- $scope.connecttrapItemNo = newConnectTrapItemNo;
- $scope.temp.policy.connecttriggerSignatures.push({'id':'C'+newConnectTrapItemNo});
- if(newConnectTrapItemNo >1){
- var count = newConnectTrapItemNo-1;
- $scope.connectTriggerTrapsList.push('C'+count);
- }
- };
- $scope.removeTriggerConnectButton = function() {
- var lastConnectTrapItem = $scope.temp.policy.connecttriggerSignatures.length-1;
- $scope.temp.policy.connecttriggerSignatures.splice(lastConnectTrapItem);
- if(lastConnectTrapItem < 1){
- var count = lastConnectTrapItem-1;
- $scope.connectTriggerTrapsList.splice('C'+count);
- }
- };
- if($scope.connectTriggerFaultsList == undefined){
- $scope.connectTriggerFaultsList = [];
- }
- if($scope.temp.policy.faulttriggerSignatures == undefined){
- $scope.temp.policy.faulttriggerSignatures = [];
- }
-
- $scope.FaultItemNo = 0;
- $scope.FaultSignatureDatas = [{"verificationmainSignatures" : $scope.temp.policy.faulttriggerSignatures}];
- $scope.addVerFaultButton = function() {
- var newFaultItemNo = $scope.temp.policy.faulttriggerSignatures.length+1;
- $scope.FaultItemNo = newFaultItemNo;
- $scope.temp.policy.faulttriggerSignatures.push({'id':'Fault'+newFaultItemNo});
- $scope.connectTriggerFaultsList.push('Fault'+newFaultItemNo);
- };
- $scope.removeVerFaultButton = function() {
- var lastFaultItem = $scope.temp.policy.faulttriggerSignatures.length-1;
- $scope.temp.policy.faulttriggerSignatures.splice(lastFaultItem);
- $scope.connectTriggerFaultsList.splice('Fault'+lastFaultItem);
- };
- if($scope.temp.policy.triggerfaultSignatures == undefined){
- $scope.temp.policy.triggerfaultSignatures = [];
- }
-
- $scope.faultItemNo1 = 0;
- $scope.FaultTriggerSignatureDatas = [{"verificationSignatures" : $scope.temp.policy.triggerfaultSignatures}];
- $scope.addVerTriggerButton = function(indexId) {
- $scope.verificationdisabled = false;
- if(faultCollection.indexOf(indexId) !== -1){
+
+ $scope.trapItemNo = 0;
+ $scope.TrapTriggerSignatureDatas = [{"triggermainSignatures" : $scope.temp.policy.triggerTrapSignatures}];
+ $scope.addTrapTriggerButton = function(indexId) {
+ if(trapCollection.indexOf(indexId) === -1){
+ $scope.temp.policy.triggerTrapSignatures[indexId] = [];
+ trapCollection.push(indexId);
+ }
+ var newTrapItemNo = $scope.temp.policy.triggerTrapSignatures[indexId].length+1;
+ $scope.trapItemNo = newTrapItemNo;
+ $scope.temp.policy.triggerTrapSignatures.push($scope.temp.policy.triggerTrapSignatures[indexId].push({'id':'A'+newTrapItemNo}));
+ if(newTrapItemNo > 1){
+ var count = newTrapItemNo-1;
+ $scope.varbindDictionaryDatas.push('A'+count);
+ }
+ };
+ $scope.removeTrapTriggerButton = function(indexId) {
+ var lastTrapItem = $scope.temp.policy.triggerTrapSignatures[indexId].length-1;
+ var checkLastTrapItem = lastTrapItem;
+ if(checkLastTrapItem == 0){
+ trapCollection.splice(indexId);
+ }
+ $scope.temp.policy.triggerTrapSignatures[indexId].splice(lastTrapItem);
+ };
- }else{
- $scope.temp.policy.triggerfaultSignatures[indexId] = [];
- faultCollection.push(indexId);
- }
- var newFaultItemNo1 = $scope.temp.policy.triggerfaultSignatures[indexId].length+1;
- $scope.faultItemNo1 = newFaultItemNo1;
- $scope.temp.policy.triggerfaultSignatures.push($scope.temp.policy.triggerfaultSignatures[indexId].push({'id':'A'+newFaultItemNo1}));
- if(newFaultItemNo1 > 1){
- var count = newFaultItemNo1-1;
- $scope.varbindDictionaryDatas.push('A'+count);
- }
- };
- $scope.removeVerTriggerButton = function(indexId) {
- var lastFaultItem1 = $scope.temp.policy.triggerfaultSignatures[indexId].length-1;
- var checkLastFaultItem = lastFaultItem1;
- if(checkLastFaultItem == 0){
- faultCollection.splice(indexId);
- }
- $scope.temp.policy.triggerfaultSignatures[indexId].splice(lastFaultItem1);
- };
+ if($scope.temp.policy.connecttriggerSignatures == undefined){
+ $scope.temp.policy.connecttriggerSignatures = [];
+ }
+
+ $scope.connecttrapItemNo = 0;
+ $scope.TrapConnectTriggerSignatureDatas = [{"connecttriggerSignatures" : $scope.temp.policy.connecttriggerSignatures}];
+ $scope.addTriggerConnectButton = function() {
+ var newConnectTrapItemNo = $scope.temp.policy.connecttriggerSignatures.length+1;
+ $scope.connecttrapItemNo = newConnectTrapItemNo;
+ $scope.temp.policy.connecttriggerSignatures.push({'id':'C'+newConnectTrapItemNo});
+ if(newConnectTrapItemNo >1){
+ var count = newConnectTrapItemNo-1;
+ $scope.connectTriggerTrapsList.push('C'+count);
+ }
+ };
+ $scope.removeTriggerConnectButton = function() {
+ var lastConnectTrapItem = $scope.temp.policy.connecttriggerSignatures.length-1;
+ $scope.temp.policy.connecttriggerSignatures.splice(lastConnectTrapItem);
+ if(lastConnectTrapItem < 1){
+ var count = lastConnectTrapItem-1;
+ $scope.connectTriggerTrapsList.splice('C'+count);
+ }
+ };
+ if($scope.connectTriggerFaultsList == undefined){
+ $scope.connectTriggerFaultsList = [];
+ }
+ if($scope.temp.policy.faulttriggerSignatures == undefined){
+ $scope.temp.policy.faulttriggerSignatures = [];
+ }
+
+ $scope.FaultItemNo = 0;
+ $scope.FaultSignatureDatas = [{"verificationmainSignatures" : $scope.temp.policy.faulttriggerSignatures}];
+ $scope.addVerFaultButton = function() {
+ var newFaultItemNo = $scope.temp.policy.faulttriggerSignatures.length+1;
+ $scope.FaultItemNo = newFaultItemNo;
+ $scope.temp.policy.faulttriggerSignatures.push({'id':'Fault'+newFaultItemNo});
+ $scope.connectTriggerFaultsList.push('Fault'+newFaultItemNo);
+ };
+ $scope.removeVerFaultButton = function() {
+ var lastFaultItem = $scope.temp.policy.faulttriggerSignatures.length-1;
+ $scope.temp.policy.faulttriggerSignatures.splice(lastFaultItem);
+ $scope.connectTriggerFaultsList.splice('Fault'+lastFaultItem);
+ };
+ if($scope.temp.policy.triggerfaultSignatures == undefined){
+ $scope.temp.policy.triggerfaultSignatures = [];
+ }
+
+ $scope.faultItemNo1 = 0;
+ $scope.FaultTriggerSignatureDatas = [{"verificationSignatures" : $scope.temp.policy.triggerfaultSignatures}];
+ $scope.addVerTriggerButton = function(indexId) {
+ $scope.verificationdisabled = false;
+ if(faultCollection.indexOf(indexId) === -1){
+ $scope.temp.policy.triggerfaultSignatures[indexId] = [];
+ faultCollection.push(indexId);
+ }
+ var newFaultItemNo1 = $scope.temp.policy.triggerfaultSignatures[indexId].length+1;
+ $scope.faultItemNo1 = newFaultItemNo1;
+ $scope.temp.policy.triggerfaultSignatures.push($scope.temp.policy.triggerfaultSignatures[indexId].push({'id':'A'+newFaultItemNo1}));
+ if(newFaultItemNo1 > 1){
+ var count = newFaultItemNo1-1;
+ $scope.varbindDictionaryDatas.push('A'+count);
+ }
+ };
+ $scope.removeVerTriggerButton = function(indexId) {
+ var lastFaultItem1 = $scope.temp.policy.triggerfaultSignatures[indexId].length-1;
+ var checkLastFaultItem = lastFaultItem1;
+ if(checkLastFaultItem == 0){
+ faultCollection.splice(indexId);
+ }
+ $scope.temp.policy.triggerfaultSignatures[indexId].splice(lastFaultItem1);
+ };
- if($scope.temp.policy.connectVerificationSignatures == undefined){
- $scope.temp.policy.connectVerificationSignatures = [];
- }
-
- $scope.connectFaultItemNo = 0;
- $scope.FaultConnectTriggerSignatureDatas = [{"connectVerificationSignatures" : $scope.temp.policy.connectVerificationSignatures}];
- $scope.addFaultConnectButton = function() {
- var newConnectFaultItemNo = $scope.temp.policy.connectVerificationSignatures.length+1;
- $scope.connectFaultItemNo = newConnectFaultItemNo;
- $scope.temp.policy.connectVerificationSignatures.push({'id':'C'+newConnectFaultItemNo});
- if(newConnectFaultItemNo >1){
- var count = newConnectFaultItemNo-1;
- $scope.connectTriggerFaultsList.push('C'+count);
- }
- };
- $scope.removeFaultConnectButton = function() {
- var lastConnectFaultItem = $scope.temp.policy.connectVerificationSignatures.length-1;
- $scope.temp.policy.connectVerificationSignatures.splice(lastConnectFaultItem);
- if(lastConnectFaultItem < 1){
- var count = lastConnectFaultItem-1;
- $scope.connectTriggerFaultsList.splice('C'+count);
- }
- };
+ if($scope.temp.policy.connectVerificationSignatures == undefined){
+ $scope.temp.policy.connectVerificationSignatures = [];
+ }
+
+ $scope.connectFaultItemNo = 0;
+ $scope.FaultConnectTriggerSignatureDatas = [{"connectVerificationSignatures" : $scope.temp.policy.connectVerificationSignatures}];
+ $scope.addFaultConnectButton = function() {
+ var newConnectFaultItemNo = $scope.temp.policy.connectVerificationSignatures.length+1;
+ $scope.connectFaultItemNo = newConnectFaultItemNo;
+ $scope.temp.policy.connectVerificationSignatures.push({'id':'C'+newConnectFaultItemNo});
+ if(newConnectFaultItemNo >1){
+ var count = newConnectFaultItemNo-1;
+ $scope.connectTriggerFaultsList.push('C'+count);
+ }
+ };
+ $scope.removeFaultConnectButton = function() {
+ var lastConnectFaultItem = $scope.temp.policy.connectVerificationSignatures.length-1;
+ $scope.temp.policy.connectVerificationSignatures.splice(lastConnectFaultItem);
+ if(lastConnectFaultItem < 1){
+ var count = lastConnectFaultItem-1;
+ $scope.connectTriggerFaultsList.splice('C'+count);
+ }
+ };
-}]); \ No newline at end of file
+}]);
diff --git a/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/PolicyTemplateController/ClosedLoopPMController.js b/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/PolicyTemplateController/ClosedLoopPMController.js
index a67266074..454a724a9 100644
--- a/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/PolicyTemplateController/ClosedLoopPMController.js
+++ b/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/PolicyTemplateController/ClosedLoopPMController.js
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP Policy Engine
* ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017, 2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -29,7 +29,7 @@ angular.module("abs").controller('clPMController', ['$scope', '$window', '$timeo
policyType : "Config",
configPolicyType : "ClosedLoop_PM"
}
- };
+ }
$scope.refresh = function(){
if($scope.refreshCheck){
@@ -193,4 +193,4 @@ angular.module("abs").controller('clPMController', ['$scope', '$window', '$timeo
});
};
-}]); \ No newline at end of file
+}]);
diff --git a/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/PolicyTemplateController/DCAEMicroServicePolicyController.js b/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/PolicyTemplateController/DCAEMicroServicePolicyController.js
index cffa46f53..1e452e830 100644
--- a/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/PolicyTemplateController/DCAEMicroServicePolicyController.js
+++ b/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/PolicyTemplateController/DCAEMicroServicePolicyController.js
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP Policy Engine
* ================================================================================
- * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2020 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -18,7 +18,9 @@
* ============LICENSE_END=========================================================
*/
-angular.module('abs').controller('dcaeMicroServiceController', ['$scope', '$window', '$compile', 'PolicyAppService', 'policyNavigator', 'modalService', '$modal', 'Notification', function ($scope, $window, $compile, PolicyAppService, PolicyNavigator, modalService, $modal, Notification) {
+angular.module('abs').controller('dcaeMicroServiceController',
+ ['$scope', '$window', '$compile', 'PolicyAppService', 'policyNavigator', 'modalService', '$modal', 'Notification',
+ function ($scope, $window, $compile, PolicyAppService, PolicyNavigator, modalService, $modal, Notification) {
$("#dialog").hide();
$scope.policyNavigator;
@@ -29,18 +31,18 @@ angular.module('abs').controller('dcaeMicroServiceController', ['$scope', '$wind
var layer = 0;
if(!$scope.temp.policy.editPolicy && !$scope.temp.policy.readOnly){
- $scope.temp.policy = {
- policyType : "Config",
- configPolicyType : "Micro Service"
- }
- };
+ $scope.temp.policy = {
+ policyType : "Config",
+ configPolicyType : "Micro Service"
+ }
+ }
$scope.refresh = function(){
- if($scope.refreshCheck){
- $scope.policyNavigator.refresh();
- }
- $scope.modal('createNewPolicy', true);
- $scope.temp.policy = "";
+ if($scope.refreshCheck){
+ $scope.policyNavigator.refresh();
+ }
+ $scope.modal('createNewPolicy', true);
+ $scope.temp.policy = "";
};
$scope.modal = function(id, hide) {
@@ -48,328 +50,290 @@ angular.module('abs').controller('dcaeMicroServiceController', ['$scope', '$wind
};
$('#ttlDate').datepicker({
- dateFormat: 'dd/mm/yy',
- changeMonth: true,
- changeYear: true,
- onSelect: function(date) {
- angular.element($('#ttlDate')).triggerHandler('input');
- }
+ dateFormat: 'dd/mm/yy',
+ changeMonth: true,
+ changeYear: true,
+ onSelect: function(date) {
+ angular.element($('#ttlDate')).triggerHandler('input');
+ }
});
- if ($scope.temp.policy.editPolicy != undefined|| $scope.temp.policy.readOnly != undefined){
- if ($scope.temp.policy.configName == undefined){
- $scope.isCheck = false;
- }else{
- $scope.isCheck = true;
- }
- }else {
- $scope.isCheck = false;
- }
-
- PolicyAppService.getData('getDictionary/get_OnapNameDataByName').then(function (data) {
- var j = data;
- $scope.data = JSON.parse(j.data);
- console.log($scope.data);
- $scope.onapNameDictionaryDatas = JSON.parse($scope.data.onapNameDictionaryDatas);
- console.log($scope.onapNameDictionaryDatas);
- }, function (error) {
- console.log("failed");
- });
+ if ($scope.temp.policy.editPolicy != undefined|| $scope.temp.policy.readOnly != undefined){
+ if ($scope.temp.policy.configName == undefined){
+ $scope.isCheck = false;
+ }else{
+ $scope.isCheck = true;
+ }
+ }else {
+ $scope.isCheck = false;
+ }
+
+ PolicyAppService.getData('getDictionary/get_OnapNameDataByName').then(function (data) {
+ var j = data;
+ $scope.data = JSON.parse(j.data);
+ $scope.onapNameDictionaryDatas = JSON.parse($scope.data.onapNameDictionaryDatas);
+ });
- PolicyAppService.getData('get_DCAEPriorityValues').then(function (data) {
- var j = data;
- $scope.data = JSON.parse(j.data);
- console.log($scope.data);
- $scope.priorityDatas = JSON.parse($scope.data.priorityDatas);
- console.log($scope.priorityDatas);
- }, function (error) {
- console.log("failed");
- });
+ PolicyAppService.getData('get_DCAEPriorityValues').then(function (data) {
+ var j = data;
+ $scope.data = JSON.parse(j.data);
+ $scope.priorityDatas = JSON.parse($scope.data.priorityDatas);
+ });
- PolicyAppService.getData('getDictionary/get_GroupPolicyScopeDataByName').then(function (data) {
- var j = data;
- $scope.data = JSON.parse(j.data);
- console.log($scope.data);
- $scope.groupPolicyScopeListDatas = JSON.parse($scope.data.groupPolicyScopeListDatas);
- console.log($scope.groupPolicyScopeListDatas);
- }, function (error) {
- console.log("failed");
- });
+ PolicyAppService.getData('getDictionary/get_GroupPolicyScopeDataByName').then(function (data) {
+ var j = data;
+ $scope.data = JSON.parse(j.data);
+ $scope.groupPolicyScopeListDatas = JSON.parse($scope.data.groupPolicyScopeListDatas);
+ });
- PolicyAppService.getData('getDictionary/get_MicroServiceConfigNameDataByName').then(function (data) {
- var j = data;
- $scope.data = JSON.parse(j.data);
- console.log($scope.data);
- console.log("$scope.data.microServiceConfigNameDictionaryDatas : " + $scope.data.microServiceConfigNameDictionaryDatas);
- if($scope.data.microServiceConfigNameDictionaryDatas){
- $scope.microServiceCongigNameDictionaryDatas = JSON.parse($scope.data.microServiceConfigNameDictionaryDatas);
- }
- console.log($scope.microServiceCongigNameDictionaryDatas);
- }, function (error) {
- console.log("failed");
- });
+ PolicyAppService.getData('getDictionary/get_MicroServiceConfigNameDataByName').then(function (data) {
+ var j = data;
+ $scope.data = JSON.parse(j.data);
+ if($scope.data.microServiceConfigNameDictionaryDatas){
+ $scope.microServiceCongigNameDictionaryDatas = JSON.parse($scope.data.microServiceConfigNameDictionaryDatas);
+ }
+ });
- PolicyAppService.getData('getDictionary/get_MicroServiceLocationDataByName').then(function (data) {
- var j = data;
- $scope.data = JSON.parse(j.data);
- console.log($scope.data);
- $scope.microServiceLocationDictionaryDatas = JSON.parse($scope.data.microServiceLocationDictionaryDatas);
- console.log($scope.microServiceLocationDictionaryDatas);
- }, function (error) {
- console.log("failed");
- });
+ PolicyAppService.getData('getDictionary/get_MicroServiceLocationDataByName').then(function (data) {
+ var j = data;
+ $scope.data = JSON.parse(j.data);
+ $scope.microServiceLocationDictionaryDatas = JSON.parse($scope.data.microServiceLocationDictionaryDatas);
+ });
- PolicyAppService.getData('getDictionary/get_MicroServiceModelsDataByName').then(function (data) {
- var j = data;
- $scope.data = JSON.parse(j.data);
- console.log($scope.data);
- var inputModelList = JSON.parse($scope.data.microServiceModelsDictionaryDatas);
- var unique = {};
- var uniqueList = [];
- for(var i = 0; i < inputModelList.length; i++){
- if(typeof unique[inputModelList[i]] == "undefined"){
- unique[inputModelList[i]] = "";
- uniqueList.push(inputModelList[i]);
- }
- }
- $scope.microServiceModelsDictionaryDatas = uniqueList;
- console.log($scope.microServiceModelsDictionaryDatas);
- }, function (error) {
- console.log("failed");
- });
+ PolicyAppService.getData('getDictionary/get_MicroServiceModelsDataByName').then(function (data) {
+ var j = data;
+ $scope.data = JSON.parse(j.data);
+ var inputModelList = JSON.parse($scope.data.microServiceModelsDictionaryDatas);
+ var unique = {};
+ var uniqueList = [];
+ for(var i = 0; i < inputModelList.length; i++){
+ if(typeof unique[inputModelList[i]] == "undefined"){
+ unique[inputModelList[i]] = "";
+ uniqueList.push(inputModelList[i]);
+ }
+ }
+ $scope.microServiceModelsDictionaryDatas = uniqueList;
+ });
- PolicyAppService.getData('getDictionary/get_DCAEUUIDDataByName').then(function (data) {
- var j = data;
- $scope.data = JSON.parse(j.data);
- console.log($scope.data);
- $scope.dcaeUUIDDictionaryDatas = JSON.parse($scope.data.dcaeUUIDDictionaryDatas);
- console.log($scope.dcaeUUIDDictionaryDatas);
- }, function (error) {
- console.log("failed");
- });
+ PolicyAppService.getData('getDictionary/get_DCAEUUIDDataByName').then(function (data) {
+ var j = data;
+ $scope.data = JSON.parse(j.data);
+ $scope.dcaeUUIDDictionaryDatas = JSON.parse($scope.data.dcaeUUIDDictionaryDatas);
+ });
- PolicyAppService.getData('getDictionary/get_RiskTypeDataByName').then(function (data) {
- var j = data;
- $scope.data = JSON.parse(j.data);
- console.log($scope.data);
- $scope.riskTypeDictionaryDatas = JSON.parse($scope.data.riskTypeDictionaryDatas);
- console.log($scope.riskTypeDictionaryDatas);
- }, function (error) {
- console.log("failed");
- });
+ PolicyAppService.getData('getDictionary/get_RiskTypeDataByName').then(function (data) {
+ var j = data;
+ $scope.data = JSON.parse(j.data);
+ $scope.riskTypeDictionaryDatas = JSON.parse($scope.data.riskTypeDictionaryDatas);
+ });
- PolicyAppService.getData('getDictionary/get_MicroServiceAttributeData').then(function (data) {
- var j = data;
- $scope.data = JSON.parse(j.data);
- console.log($scope.data);
- $scope.microServiceAttributeDictionaryDatas = JSON.parse($scope.data.microServiceAttributeDictionaryDatas);
- console.log($scope.microServiceAttributeDictionaryDatas);
- }, function (error) {
- console.log("failed");
- });
-
+ PolicyAppService.getData('getDictionary/get_MicroServiceAttributeData').then(function (data) {
+ var j = data;
+ $scope.data = JSON.parse(j.data);
+ $scope.microServiceAttributeDictionaryDatas = JSON.parse($scope.data.microServiceAttributeDictionaryDatas);
+ });
+
- $scope.choices = [];
- $scope.attributeDatas = [{"attributes" : $scope.choices}];
- addNewChoice = function(value) {
- console.log("input key : " + value);
- var isFoundInRuleData = false;
- if(value != undefined){
- if (value.startsWith('div.')){
- value = value.replace('div.','');
- }
-
- console.log(" document.getElementById : div."+value);
- var parentElement = document.getElementById("div."+value);
- console.log("parentElement : " + parentElement);
- var div = document.getElementById(value+"@0");
- if(div != null){
- var clone = div.cloneNode(true);
- var addElement = parentElement.childElementCount;
- clone.id = ''+value+'@'+addElement;
- clone.value = '';
- if($scope.temp.policy.editPolicy || $scope.temp.policy.readOnly){ //if it's view or edit
- if($scope.temp.policy.ruleData[clone.id] || $scope.temp.policy.editPolicy){ // Only append child if its value found in ruleData or edit mode
- if($scope.temp.policy.ruleData[clone.id]){
- clone.value = $scope.temp.policy.ruleData[clone.id];
- isFoundInRuleData = true;
- }
- console.log(" clone.value :" + clone.value);
- console.log(" clone.id :" + clone.id);
- if(!isFoundInRuleData && isInitViewEdit){
- return;
- }
- if(!clone.className.includes("child_single")){
- clone.className += ' child_single'; //here cloned is single element
- }
- document.getElementById("div."+value).appendChild(clone);
- plainAttributeKeys.push(''+value+'@'+addElement);
- }
- }else{ //not view or edit
- if(!clone.className.includes("child_single")){
- clone.className += ' child_single'; //here cloned is single element
- }
- document.getElementById("div."+value).appendChild(clone);
- plainAttributeKeys.push(''+value+'@'+addElement);
- }
- }else{
-
- if(parentElement == null){
- return;
- }
- div = document.getElementById("div."+value+"@0");
- if(div){
-
- if(!div.className.includes('children_group border')){
- layer++;
- if(layer > 4){
- layer = 1
- };
- div.className += ' children_group border' + layer; //here is div with a group of children.
- }
- }
- var childElement = parentElement.firstElementChild;
- var countParent = parentElement.childElementCount;
- var childElementString = childElement.innerHTML;
- var find = value+"@0";
- var re = new RegExp(find, 'g');
- childElementString = childElementString.replace(re,value+'@' + countParent);
- var clone = childElement.cloneNode(true);
- for (var ii = 0; ii < parentElement.childNodes.length; ii++){
- var childId = parentElement.childNodes[ii].id;
- if(ii = parentElement.childNodes.length){
- var childnewId = childId.slice(0, -1);
- var count = childId.slice(-1);
- }
- }
- var countvalue = parseInt(count) + 1;
- clone.id = childnewId+countvalue;
- clone.value = '';
- clone.innerHTML=childElementString;
- document.getElementById("div."+value).appendChild(clone);
- var selects = clone.getElementsByTagName("select");
- var inputs = clone.getElementsByTagName("input");
- var removeValues = [];
- for(var i=0; i<inputs.length; i++){
- if ($scope.temp.policy.ruleData!=undefined){
- var checkValue = $scope.temp.policy.ruleData[inputs[i].id];
- console.log(" checkValue.value :" + checkValue);
- console.log(" inputs["+i+"].id :" + inputs[i].id);
- if (checkValue!=undefined && checkValue != "undefined"){
- document.getElementById(inputs[i].id).value = checkValue;
- plainAttributeKeys.push(inputs[i].id);
- } else {
- plainAttributeKeys.push(inputs[i].id);
- }
- }else {
- plainAttributeKeys.push(inputs[i].id);
- }
- }
-
- for(var i=0; i<selects.length; i++){
- if ($scope.temp.policy.ruleData!=undefined){
- var checkValue = $scope.temp.policy.ruleData[selects[i].id];
- if (checkValue!=undefined && checkValue!="undefined"){
- if($scope.temp.policy.ruleData != null){
- var checkValue = $scope.temp.policy.ruleData[selects[i].id];
- var option = document.createElement('option');
- option.setAttribute('value', checkValue);
- option.appendChild(document.createTextNode(checkValue));
- document.getElementById(selects[i].id).appendChild(option);
- document.getElementById(selects[i].id).value = $scope.temp.policy.ruleData[selects[i].id];
- plainAttributeKeys.push(selects[i].id);
- }
- } else {
- plainAttributeKeys.push(selects[i].id);
- }
- }else {
- plainAttributeKeys.push(selects[i].id);
- }
- }
-
- for (var k=0; k<removeValues.length; k++){
- var elem = document.getElementById(removeValues[k]);
- elem.parentNode.removeChild(elem);
- }
- var ele = angular.element(document.getElementById("div."+value));
- $compile(ele.contents())($scope)
- }
- }
- };
-
-
- removeChoice = function(value) {
- console.log(value);
- if(value != undefined){
- var c = document.getElementById("div."+value).childElementCount;
-
- if(c == 1){
- Notification.error("The original one is not removable.");
- return;
- }
- document.getElementById("div."+value).removeChild(document.getElementById("div."+value).lastChild);
- }
- };
-
- function findVal(object, key) {
- var value;
- Object.keys(object).some(function(k) {
- if (k === key) {
- value = object[k];
- return true;
- }
- if (object[k] && typeof object[k] === 'object') {
- value = findVal(object[k], key);
- return value !== undefined;
- }
- });
- return value;
- }
-
- $scope.pullVersion = function(serviceName) {
- console.log(serviceName);
- if(serviceName != undefined){
- var uuu = "policyController/getModelServiceVersioneData.htm";
- var postData={policyData: serviceName};
- $.ajax({
- type : 'POST',
- url : uuu,
- dataType: 'json',
- contentType: 'application/json',
- data: JSON.stringify(postData),
- success : function(data){
- $scope.$apply(function(){
- $scope.microServiceModelsDictionaryVersionDatas = data[0].dcaeModelVersionData;
- });
- },
- error : function(data){
- alert("Error While Retriving the Template Layout Pattren.");
- }
- });
- }
- };
+ $scope.choices = [];
+ $scope.attributeDatas = [{"attributes" : $scope.choices}];
+ addNewChoice = function(value) {
+ var isFoundInRuleData = false;
+ if(value != undefined){
+ if (value.startsWith('div.')){
+ value = value.replace('div.','');
+ }
+
+ var parentElement = document.getElementById("div."+value);
+ var div = document.getElementById(value+"@0");
+ if(div != null){
+ var clone = div.cloneNode(true);
+ var addElement = parentElement.childElementCount;
+ clone.id = ''+value+'@'+addElement;
+ clone.value = '';
+ if($scope.temp.policy.editPolicy || $scope.temp.policy.readOnly){
+ //if it's vi or edit
+ if($scope.temp.policy.ruleData[clone.id] || $scope.temp.policy.editPolicy){
+ //Only append child if its value found in ruleData or edit mode
+ if($scope.temp.policy.ruleData[clone.id]){
+ clone.value = $scope.temp.policy.ruleData[clone.id];
+ isFoundInRuleData = true;
+ }
+ if(!isFoundInRuleData && isInitViewEdit){
+ return;
+ }
+ if(!clone.className.includes("child_single")){
+ clone.className += ' child_single'; // here cloned is single element
+ }
+ document.getElementById("div."+value).appendChild(clone);
+ plainAttributeKeys.push(''+value+'@'+addElement);
+ }
+ }else{ // not view or edit
+ if(!clone.className.includes("child_single")){
+ clone.className += ' child_single'; // here cloned is single element
+ }
+ document.getElementById("div."+value).appendChild(clone);
+ plainAttributeKeys.push(''+value+'@'+addElement);
+ }
+ }else{
+
+ if(parentElement == null){
+ return;
+ }
+ div = document.getElementById("div."+value+"@0");
+ if(div){
+
+ if(!div.className.includes('children_group border')){
+ layer++;
+ if(layer > 4){
+ layer = 1
+ }
+ div.className += ' children_group border' + layer; // here is div with a group of children.
+ }
+ }
+ var childElement = parentElement.firstElementChild;
+ var countParent = parentElement.childElementCount;
+ var childElementString = childElement.innerHTML;
+ var find = value+"@0";
+ var re = new RegExp(find, 'g');
+ childElementString = childElementString.replace(re,value+'@' + countParent);
+ var clone = childElement.cloneNode(true);
+ for (var ii = 0; ii < parentElement.childNodes.length; ii++){
+ var childId = parentElement.childNodes[ii].id;
+ if(ii = parentElement.childNodes.length){
+ var childnewId = childId.slice(0, -1);
+ var count = childId.slice(-1);
+ }
+ }
+ var countvalue = parseInt(count) + 1;
+ clone.id = childnewId+countvalue;
+ clone.value = '';
+ clone.innerHTML=childElementString;
+ document.getElementById("div."+value).appendChild(clone);
+ var selects = clone.getElementsByTagName("select");
+ var inputs = clone.getElementsByTagName("input");
+ var removeValues = [];
+ for(var i=0; i<inputs.length; i++){
+ plainAttributeKeys.push(inputs[i].id);
+ if ($scope.temp.policy.ruleData!=undefined){
+ var checkValue = $scope.temp.policy.ruleData[inputs[i].id];
+ if (checkValue!=undefined && checkValue != "undefined"){
+ if(checkValue == "false"){
+ document.getElementById(inputs[i].id).removeAttribute("checked");
+ }
+ else if(checkValue == "true"){
+ document.getElementById(inputs[i].id).setAttribute("checked", true);
+ }else{
+ document.getElementById(inputs[i].id).value = checkValue;
+ }
+ } else {
+ if(inputs[i].type == "checkbox"){
+ inputs[i].checked = false;
+ }
+ }
+ }else {
+ document.getElementById(inputs[i].id).removeAttribute("checked");
+ }
+ }
+
+ for(var i=0; i<selects.length; i++){
+ if ($scope.temp.policy.ruleData!=undefined){
+ var checkValue = $scope.temp.policy.ruleData[selects[i].id];
+ if (checkValue!=undefined && checkValue!="undefined"){
+ if($scope.temp.policy.ruleData != null){
+ var checkValue = $scope.temp.policy.ruleData[selects[i].id];
+ var option = document.createElement('option');
+ option.setAttribute('value', checkValue);
+ option.appendChild(document.createTextNode(checkValue));
+ document.getElementById(selects[i].id).appendChild(option);
+ document.getElementById(selects[i].id).value = $scope.temp.policy.ruleData[selects[i].id];
+ plainAttributeKeys.push(selects[i].id);
+ }
+ } else {
+ plainAttributeKeys.push(selects[i].id);
+ }
+ }else {
+ plainAttributeKeys.push(selects[i].id);
+ }
+ }
+
+ for (var k=0; k<removeValues.length; k++){
+ var elem = document.getElementById(removeValues[k]);
+ elem.parentNode.removeChild(elem);
+ }
+ var ele = angular.element(document.getElementById("div."+value));
+ $compile(ele.contents())($scope)
+ }
+ }
+ };
+
+
+ removeChoice = function(value) {
+ if(value != undefined){
+ var c = document.getElementById("div."+value).childElementCount;
+
+ if(c == 1){
+ Notification.error("The original one is not removable.");
+ return;
+ }
+ document.getElementById("div."+value).removeChild(document.getElementById("div."+value).lastChild);
+ }
+ };
+
+ function findVal(object, key) {
+ var value;
+ Object.keys(object).some(function(k) {
+ if (k === key) {
+ value = object[k];
+ return true;
+ }
+ if (object[k] && typeof object[k] === 'object') {
+ value = findVal(object[k], key);
+ return value !== undefined;
+ }
+ });
+ return value;
+ }
+
+ $scope.pullVersion = function(serviceName) {
+ if(serviceName != undefined){
+ var uuu = "policyController/getModelServiceVersioneData.htm";
+ var postData={policyData: serviceName};
+ $.ajax({
+ type : 'POST',
+ url : uuu,
+ dataType: 'json',
+ contentType: 'application/json',
+ data: JSON.stringify(postData),
+ success : function(data){
+ $scope.$apply(function(){
+ $scope.microServiceModelsDictionaryVersionDatas = data[0].dcaeModelVersionData;
+ });
+ },
+ error : function(data){
+ Notification.error("Error While Retriving the Template Layout Pattren.");
+ }
+ });
+ }
+ };
- var splitDash = '-';
- var splitEqual = '=';
- var splitComma = ',';
- var splitcolon = ':';
- var splitsemicolon = ";";
- var splitEnum = "],";
- var plainAttributeKeys = [];
- var matching = [];
- var enumKeyList = [];
- var dictionaryList = [];
- var dictionaryNameList = [];
- var isInitViewEdit = false;
+ var splitEqual = '=';
+ var splitComma = ',';
+ var splitcolon = ':';
+ var splitEnum = "],";
+ var plainAttributeKeys = [];
+ var matching = [];
+ var enumKeyList = [];
+ var dictionaryList = [];
+ var dictionaryNameList = [];
+ var isInitViewEdit = false;
$scope.addDataToFields = function(serviceName, version){
if(serviceName != null && version !=null){
- var service=serviceName+"-v"+version;
- var myNode = document.getElementById("DynamicTemplate");
- myNode.innerHTML = '';
+ var service=serviceName+"-v"+version;
+ var myNode = document.getElementById("DynamicTemplate");
+ myNode.innerHTML = '';
var uuu = "policyController/getDCAEMSTemplateData.htm";
var postData={policyData: service};
- console.log("service: " +service);
var dataOrderInfo = "";
@@ -384,217 +348,206 @@ angular.module('abs').controller('dcaeMicroServiceController', ['$scope', '$wind
contentType: 'application/json',
data: JSON.stringify(postData),
success : function(data){
-
- document.getElementById("msPolicyloader").style.visibility = "hidden";
-
+
+ document.getElementById("msPolicyloader").style.visibility = "hidden";
+
$scope.$apply(function(){
- var plainAttributeKeys = [];
- $scope.dcaeModelData = data[0].dcaeModelData;
- $scope.dcaeJsonDate = data[0].jsonValue;
+ $scope.dcaeModelData = data[0].dcaeModelData;
+ $scope.dcaeJsonDate = data[0].jsonValue;
$scope.dataOrderInfo = null;
- $scope.dataOrderInfo = data[0].dataOrderInfo;
- console.log("data[0].dataOrderInfo: " + data[0].dataOrderInfo);
- console.log("$scope.dataOrderInfo: " + $scope.dataOrderInfo);
-
- if(data[0].allManyTrueKeys){
- console.log("$scope.allManyTrueKeys: " + $scope.allManyTrueKeys);
- }
- console.log("$scope.dcaeJsonDate: " + $scope.dcaeJsonDate);
- var attributes = $scope.dcaeModelData.attributes;
- console.log("attributes: " +attributes);
- var refAttributes = $scope.dcaeModelData.ref_attributes;
- var subAttributes = $scope.dcaeModelData.sub_attributes;
- console.log("subAttributes: " + subAttributes);
- console.log("refAttributes: " + refAttributes);
- var headDefautlsData = data[0].headDefautlsData;
- if(headDefautlsData != null){
- $scope.temp.policy.onapName = headDefautlsData.onapName;
- $scope.temp.policy.guard = headDefautlsData.guard;
- $scope.temp.policy.riskType = headDefautlsData.riskType;
- $scope.temp.policy.riskLevel = headDefautlsData.riskLevel;
- $scope.temp.policy.priority = headDefautlsData.priority;
- }
-
- var enumAttributes = $scope.dcaeModelData.enumValues;
- var annotation = $scope.dcaeModelData.annotation;
- var dictionary = $scope.microServiceAttributeDictionaryDatas;
+ $scope.dataOrderInfo = data[0].dataOrderInfo;
+
+ if(data[0].allManyTrueKeys){
+ }
+ var attributes = $scope.dcaeModelData.attributes;
+ var refAttributes = $scope.dcaeModelData.ref_attributes;
+ var subAttributes = $scope.dcaeModelData.sub_attributes;
+ var headDefautlsData = data[0].headDefautlsData;
+ if(headDefautlsData != null){
+ $scope.temp.policy.onapName = headDefautlsData.onapName;
+ $scope.temp.policy.guard = headDefautlsData.guard;
+ $scope.temp.policy.riskType = headDefautlsData.riskType;
+ $scope.temp.policy.riskLevel = headDefautlsData.riskLevel;
+ $scope.temp.policy.priority = headDefautlsData.priority;
+ }
+
+ var annotation = $scope.dcaeModelData.annotation;
+ var dictionary = $scope.microServiceAttributeDictionaryDatas;
- if (annotation == null || annotation.length<1){
- $scope.isCheck = true;
- }else {
- $scope.isCheck = false;
- var annoationList = annotation.split(splitComma);
- for (k = 0; k < annoationList.length; k++){
- var splitAnnotation = annoationList[k].split(splitEqual);
- if (splitAnnotation[1].includes("matching-true")){
- matching.push(splitAnnotation[0].trim());
- }
- }
+ if (annotation == null || annotation.length<1){
+ $scope.isCheck = true;
+ }else {
+ $scope.isCheck = false;
+ var annoationList = annotation.split(splitComma);
+ for (k = 0; k < annoationList.length; k++){
+ var splitAnnotation = annoationList[k].split(splitEqual);
+ if (splitAnnotation[1].includes("matching-true")){
+ matching.push(splitAnnotation[0].trim());
+ }
+ }
- }
+ }
- if (dictionary!= null && dictionary.length>1){
- for (m=0; m < dictionary.length; m += 1){
- var keyCompare = dictionary[m].name;
- var valueCompare = dictionary[m].value;
- var valueModel = dictionary[m].modelName;
- var conpairService = serviceName;
- if (valueModel.includes('-v')){
- conpairService = service;
- }
- if(valueModel.localeCompare(conpairService) == 0){
- console.log(valueCompare);
- dictionaryList.push(dictionary[m]);
- if (!dictionaryNameList.includes(dictionary[m].name)){
- dictionaryNameList.push(dictionary[m].name)
- }
- }
- }
- }
+ if (dictionary!= null && dictionary.length>1){
+ for (m=0; m < dictionary.length; m += 1){
+ var valueCompare = dictionary[m].value;
+ var valueModel = dictionary[m].modelName;
+ var conpairService = serviceName;
+ if (valueModel.includes('-v')){
+ conpairService = service;
+ }
+ if(valueModel.localeCompare(conpairService) == 0){
+ dictionaryList.push(dictionary[m]);
+ if (!dictionaryNameList.includes(dictionary[m].name)){
+ dictionaryNameList.push(dictionary[m].name)
+ }
+ }
+ }
+ }
- $scope.temp.policy.ruleGridData = [];
-
- if($scope.temp.policy.editPolicy || $scope.temp.policy.readOnly){
- dataOrderInfo = $scope.dataOrderInfo;
- }
-
- $scope.jsonLayout($scope.dcaeJsonDate);
-
+ $scope.temp.policy.ruleGridData = [];
+
+ if($scope.temp.policy.editPolicy || $scope.temp.policy.readOnly){
+ dataOrderInfo = $scope.dataOrderInfo;
+ }
+
+ $scope.jsonLayout($scope.dcaeJsonDate);
+
});
if($scope.temp.policy.editPolicy || $scope.temp.policy.readOnly){ // If it's veiw or edit
- isInitViewEdit = true;
- var checkData = [];
- var data = [];
- // If ruleData contains extra elements created by clicked add button
- console.log("$scope.temp.policy.ruleData:" + $scope.temp.policy.ruleData);
- if($scope.temp.policy.ruleData != null){
- var propNames = Object.getOwnPropertyNames($scope.temp.policy.ruleData);
- propNames.forEach(function(name) {
- data.push(name);
- });
-
- var extraElements = data;
-
- if(plainAttributeKeys != null){
- for(var b = 0; b < plainAttributeKeys.length; b++){ // Remove already populated elements from data array
- var newValue = plainAttributeKeys[b].split("*");
- for(var a = 0; a < data.length; a++){
- if(data[a] === newValue[0] || data[a] === (newValue[0]+"@0")){
- extraElements.splice(a, 1);
- }
- }
- }
-
- //--- Populate these extra elements created by clicked add button
- for(var a = 0; a < extraElements.length; a++){
- if(extraElements[a].includes("@")){
- var index = extraElements[a].lastIndexOf("@");
- if(index > 0){
- // Get the number after @
- var n = getNumOfDigits(extraElements[a], index+1);
-
- var key = extraElements[a].substring(0, index+n+1); //include @x in key also by n+2 since x can be 1,12, etc
- console.log("key: " + key);
- checkData.push(key);
- }
- }
- }
- var unique = checkData.filter(onlyUnique);
- var parentLevelElements = [];
- if(unique){
- //--- get all root level exta elments first (only contains one "@")
- for(var i =0; i < unique.length; i++){
- var firstIndex = unique[i].indexOf("@");
- var lastIndex = unique[i].lastIndexOf("@");
- if(firstIndex == lastIndex){
- var newKey = unique[i].substring(0, firstIndex);
- console.log("root element: " + newKey);
- parentLevelElements.push(newKey);
- unique[i] = "*processed*";
- }
- }
- }
-
-
- for (var i = 0; i < $scope.labelManyKeys.length; i++) {
- var label = $scope.labelManyKeys[i];
- if(parentLevelElements){
- for (var k = 0; k < parentLevelElements.length; k++){
- if(label == parentLevelElements[k]){
- addNewChoice(label);
- }
- }
- }
- }
-
- //if no layout order info, keep the process as before
- if(!dataOrderInfo){
- for(var i =0; i < unique.length; i++){
- if(unique[i] != "*processed*"){
- var index = unique[i].lastIndexOf("@");
- var newKey = unique[i].substring(0, index);
- console.log("newKey: " + newKey);
-
- var newElement = document.getElementById("div."+unique[j]);
- //check weather it has been created already
+ isInitViewEdit = true;
+ var checkData = [];
+ var data = [];
+ // If ruleData contains extra elements created by clicked add button
+ if($scope.temp.policy.ruleData != null){
+ var propNames = Object.getOwnPropertyNames($scope.temp.policy.ruleData);
+ propNames.forEach(function(name) {
+ if(document.getElementById(name) != null){
+ if(document.getElementById(name).getAttribute("class") == "onoffswitch-checkbox"){
+ if($scope.temp.policy.ruleData[name] == "true"){
+ document.getElementById(name).setAttribute("checked", true);
+ }
+ else{
+ document.getElementById(name).removeAttribute("checked");
+ }
+ }
+ }
+ data.push(name);
+ });
+ var extraElements = data;
+ if(plainAttributeKeys != null){
+ for(var b = 0; b < plainAttributeKeys.length; b++){ // Remove already populated elements from data array
+ var newValue = plainAttributeKeys[b].split("*");
+ for(var a = 0; a < data.length; a++){
+ if(data[a] === newValue[0] || data[a] === (newValue[0]+"@0")){
+ extraElements.splice(a, 1);
+ }
+ }
+ }
+ // --- Populate these extra elements created by clicked add button
+ for(var a = 0; a < extraElements.length; a++){
+ if(extraElements[a].includes("@")){
+ var index = extraElements[a].lastIndexOf("@");
+ if(index > 0){
+ // Get the number after @
+ var n = getNumOfDigits(extraElements[a], index+1);
+ var key = extraElements[a].substring(0, index+n+1); // include @x in key also by n+2 since x can be 1,12,etc
+ checkData.push(key);
+ }
+ }
+ }
+ var unique = checkData.filter(onlyUnique);
+ var parentLevelElements = [];
+ if(unique){
+ // --- get all root level exta elments first (only contains one "@")
+ for(var i =0; i < unique.length; i++){
+ var firstIndex = unique[i].indexOf("@");
+ var lastIndex = unique[i].lastIndexOf("@");
+ if(firstIndex == lastIndex){
+ var newKey = unique[i].substring(0, firstIndex);
+ parentLevelElements.push(newKey);
+ unique[i] = "*processed*";
+ }
+ }
+ }
+ for (var i = 0; i < $scope.labelManyKeys.length; i++) {
+ var label = $scope.labelManyKeys[i];
+ if(parentLevelElements){
+ for (var k = 0; k < parentLevelElements.length; k++){
+ if(label == parentLevelElements[k]){
+ addNewChoice(label);
+ }
+ }
+ }
+ }
+
+ // if no layout order info, keep the process as before
+ if(!dataOrderInfo){
+ for(var i =0; i < unique.length; i++){
+ if(unique[i] != "*processed*"){
+ var index = unique[i].lastIndexOf("@");
+ var newKey = unique[i].substring(0, index);
+
+ var newElement = document.getElementById("div."+unique[j]);
+ // check weather it has been created already
if(newElement != null){
- continue;
+ continue;
}else{
- newElement = document.getElementById(unique[j]);
- if(newElement != null){
- continue;
- }
+ newElement = document.getElementById(unique[j]);
+ if(newElement != null){
+ continue;
+ }
}
- if(newKey){
- addNewChoice(newKey);
- }
- }
- }
- }else{
- //---reset to default
- dataOrderInfo = [];
- $scope.labelManyKeys = [];
-
- //---process none labels
- for (var j = 0; j < unique.length; j++){
- if(unique[j] != "*processed*"){
- // if not created yet
- if(!document.getElementById(unique[j])){
- var index = unique[j].lastIndexOf("@");
- var newKey = unique[j].substring(0, index);
-
- var newElement = document.getElementById("div."+unique[j]);
-
- //check weather it has been created already
+ if(newKey){
+ addNewChoice(newKey);
+ }
+ }
+ }
+ }else{
+ // ---reset to default
+ dataOrderInfo = [];
+ $scope.labelManyKeys = [];
+
+ // ---process none labels
+ for (var j = 0; j < unique.length; j++){
+ if(unique[j] != "*processed*"){
+ // if not created yet
+ if(!document.getElementById(unique[j])){
+ var index = unique[j].lastIndexOf("@");
+ var newKey = unique[j].substring(0, index);
+
+ var newElement = document.getElementById("div."+unique[j]);
+
+ // check weather it has been created already
if(newElement != null){
- continue;
+ continue;
}else{
- newElement = document.getElementById(unique[j]);
- if(newElement != null){
- continue;
- }
+ newElement = document.getElementById(unique[j]);
+ if(newElement != null){
+ continue;
+ }
}
- //if not created yet, then create it.
- addNewChoice(newKey);
-
- }
- }
- }
- }
- }
- }
+ // if not created yet,then create it.
+ addNewChoice(newKey);
+
+ }
+ }
+ }
+ }
+ }
+ }
}
var ele = angular.element(document.getElementById("DynamicTemplate"));
- $compile(ele.contents())($scope);
+ $compile(ele.contents())($scope);
$scope.$apply();
isInitViewEdit = false;
},
error : function(data){
- alert("Error While Retriving the Template Layout Pattren.");
+ Notification.error("Error While Retriving the Template Layout Pattren.");
}
});
@@ -602,991 +555,967 @@ angular.module('abs').controller('dcaeMicroServiceController', ['$scope', '$wind
};
function getNumOfDigits(str_value, index){
- // Get the number after @
- var str = str_value.substring(index, str_value.length);
- var c = '';
- var n = 0;
- for (var x = 0; x < str.length; x++){
- c = str.charAt(x);
- if(!isNaN(c)){
+ // Get the number after @
+ var str = str_value.substring(index, str_value.length);
+ var c = '';
+ var n = 0;
+ for (var x = 0; x < str.length; x++){
+ c = str.charAt(x);
+ if(!isNaN(c)){
n++;
- }else{
+ }else{
break;
}
- }
- return n;
+ }
+ return n;
}
function getDictionary(attribute){
- var dicName = attribute;
- if(attribute){
- if(attribute.includes(":")){
- dicName = attribute.split(":")[0];
- }
- }
- var dictionaryRegExp = new RegExp(dicName);
- listemunerateValues = [];
- if (dictionaryRegExp.test(dictionaryNameList)) {
- for (p=0; p < dictionaryList.length; p += 1) {
- if (dicName == dictionaryList[p].name) {
- listemunerateValues.push(dictionaryList[p].value);
- }
- }
- }
- return listemunerateValues;
+ var dicName = attribute;
+ if(attribute){
+ if(attribute.includes(":")){
+ dicName = attribute.split(":")[0];
+ }
+ }
+ var dictionaryRegExp = new RegExp(dicName);
+ listemunerateValues = [];
+ if (dictionaryRegExp.test(dictionaryNameList)) {
+ for (p=0; p < dictionaryList.length; p += 1) {
+ if (dicName == dictionaryList[p].name) {
+ listemunerateValues.push(dictionaryList[p].value);
+ }
+ }
+ }
+ return listemunerateValues;
}
function getList(attribute) {
- var enumName = attribute;
- console.log("In getList: attribute => " + attribute);
- if(attribute){
- if(attribute.includes(":")){
- enumName = attribute.split(":")[0];
- }
- }
+ var enumName = attribute;
+ if(attribute){
+ if(attribute.includes(":")){
+ enumName = attribute.split(":")[0];
+ }
+ }
var baseEnum = $scope.dcaeModelData.enumValues;
var enumList = [];
if(baseEnum != null){
- enumList = baseEnum.split(splitEnum);
+ enumList = baseEnum.split(splitEnum);
}
- var enumAttributes;
- var patternTest = new RegExp(enumName);
- for (k=0; k < enumList.length; k += 1){
- if(patternTest.test(enumList[k]) == true){
- enumAttributes = enumList[k].trim();
- }
- }
+ var enumAttributes;
+ var patternTest = new RegExp(enumName);
+ for (k=0; k < enumList.length; k += 1){
+ if(patternTest.test(enumList[k]) == true){
+ enumAttributes = enumList[k].trim();
+ }
+ }
if(enumAttributes){
- enumAttributes = enumAttributes.replace("[", "");
- enumAttributes = enumAttributes.replace("]", "");
- enumAttributes = enumAttributes.replace(/ /g, '');
- var dropListAfterCommaSplit = enumAttributes.split(splitEqual);
- listemunerateValues = dropListAfterCommaSplit[1].split(splitComma);
- //enumKeyList.push(attribute);
- return listemunerateValues;
+ enumAttributes = enumAttributes.replace("[", "");
+ enumAttributes = enumAttributes.replace("]", "");
+ enumAttributes = enumAttributes.replace(/ /g, '');
+ var dropListAfterCommaSplit = enumAttributes.split(splitEqual);
+ listemunerateValues = dropListAfterCommaSplit[1].split(splitComma);
+ // enumKeyList.push(attribute);
+ return listemunerateValues;
}
return [];
- }
-
- function getBooleanList(){
- var booleanList = [];
- booleanList.push(true);
- booleanList.push(false);
- return booleanList;
- }
-
-
- function isArray(arrayTest) {
- return Object.prototype.toString.call(arrayTest) === '[object Array]';
- }
- var lableList = [];
-
- $scope.layOutElementList = [];
- $scope.layOutOnlyLableList = [];
-
- var elementOrderNum = 0;
-
- function deconstructJSON(layOutData, level , name) {
+ }
+
+ function getBooleanList(){
+ var booleanList = [];
+ booleanList.push(true);
+ booleanList.push(false);
+ return booleanList;
+ }
+
- var array = false;
- var label = level;
- var stringValue = "java.lang.String";
- var string = "string";
- var intValue = "int";
- var integerValue = "integer";
- var double = "double";
- var boolean = "boolean";
- var baseLevel = level;
- var list = "list";
- var String = "String";
-
- var attributekey = "";
-
- if (name.length > 1){
- label = label + name + '.';
- }
-
- for (key in layOutData) {
- array = isArray(layOutData[key]);
- console.log("key: " + key , "value: " + layOutData[key]);
-
- if (!!layOutData[key] && typeof(layOutData[key])=="object") {
-
- if (array==false && key!=="0"){
-
- if($scope.dataOrderInfo){
- var labelObject = {"label" : key, "level" : label, "array" : array};
- //save it to the list
- $scope.layOutOnlyLableList.push(labelObject);
-
- }else {
- //call label layout
- $scope.labelLayout(label, key, array );
- }
-
- }
-
- if (array == true && key!=0){
- lableList.push(key);
- }
-
- if (lableList.length > 0){
- array = true;
- }
- if ( key==="0"){
- var newKey = lableList.pop();
-
- if($scope.dataOrderInfo){
-
- var labelObject = {"label" : newKey, "level" : baseLevel, "array" : array};
- //save it to the list
- $scope.layOutOnlyLableList.push(labelObject);
-
- }else {
- //call label layout
- $scope.labelLayout(baseLevel, newKey, array );
- }
-
- if (array){
- label = baseLevel + newKey + '@0.';
- } else {
- label = baseLevel + newKey + '.';
- }
- }
- deconstructJSON(layOutData[key] , label, key);
- } else {
- var attirbuteLabel = label;
- var defaultValue='';
- var description='';
- var isRequired = false;
- if (layOutData[key].includes('defaultValue-')){
- defaultValue = layOutData[key].split('defaultValue-')[1];
- }
-
- if (layOutData[key].includes('description-')){
- description = layOutData[key].split('description-')[1];
- }
-
+ function isArray(arrayTest) {
+ return Object.prototype.toString.call(arrayTest) === '[object Array]';
+ }
+ var lableList = [];
+
+ $scope.layOutElementList = [];
+ $scope.layOutOnlyLableList = [];
+
+ var elementOrderNum = 0;
+
+ function deconstructJSON(layOutData, level , name) {
- if (key==="0"){
- array = true;
- attributekey = lableList.pop();
- attirbuteLabel = baseLevel;
- } else {
- attributekey = key.split();
- }
-
- if (layOutData[key].includes('required-true')){
- isRequired = true;
- }
-
- var subAttributes = $scope.dcaeModelData.sub_attributes;
-
- if(subAttributes){
- var jsonObject = JSON.parse(subAttributes);
-
- var lablInfo = findVal(jsonObject, attributekey);
- console.log("deconstructJSON:findValue : " + attributekey +": "+ lablInfo);
- if (lablInfo){
- if(lablInfo.includes('required-true')){
- isRequired = true;
- }
- if(lablInfo.includes('defaultValue-')){
- defaultValue = lablInfo.split('defaultValue-')[1];
- }
-
- if(lablInfo.includes('description-')){
- description = lablInfo.split('description-')[1];
- }
-
- }else{
- var allkeys = Object.keys(jsonObject);
- if(allkeys){
- for (var k = 0; k < allkeys.length; k++) {
- var keyValue = allkeys[k];
- console.log(" keyValue:jsonObject["+keyValue+ "]: " + jsonObject[keyValue]);
- if(jsonObject[keyValue]){
- var tempObject = jsonObject[keyValue];
- if(tempObject && tempObject[key]){
- if (tempObject[key].includes('required-true')){
- isRequired = true;
- }
-
- if(tempObject[key].includes('defaultValue-')){
- defaultValue = tempObject[key].split('defaultValue-')[1];
- }
-
- if(tempObject[key].includes('description-')){
- description = tempObject[key].split('description-')[1];
- }
+ var array = false;
+ var label = level;
+ var stringValue = "java.lang.String";
+ var string = "string";
+ var intValue = "int";
+ var integerValue = "integer";
+ var double = "double";
+ var boolean = "boolean";
+ var baseLevel = level;
+
+ var attributekey = "";
+
+ if (name.length > 1){
+ label = label + name + '.';
+ }
+
+ for (key in layOutData) {
+ array = isArray(layOutData[key]);
+
+ if (!!layOutData[key] && typeof(layOutData[key])=="object") {
+
+ if (array==false && key!=="0"){
+
+ if($scope.dataOrderInfo){
+ var labelObject = {"label" : key, "level" : label, "array" : array};
+ // save it to the list
+ $scope.layOutOnlyLableList.push(labelObject);
+
+ }else {
+ // call label layout
+ $scope.labelLayout(label, key, array );
+ }
+
+ }
+
+ if (array == true && key!=0){
+ lableList.push(key);
+ }
+
+ if (lableList.length > 0){
+ array = true;
+ }
+ if ( key==="0"){
+ var newKey = lableList.pop();
+
+ if($scope.dataOrderInfo){
+
+ var labelObject = {"label" : newKey, "level" : baseLevel, "array" : array};
+ // save it to the list
+ $scope.layOutOnlyLableList.push(labelObject);
+
+ }else {
+ // call label layout
+ $scope.labelLayout(baseLevel, newKey, array );
+ }
+
+ if (array){
+ label = baseLevel + newKey + '@0.';
+ } else {
+ label = baseLevel + newKey + '.';
+ }
+ }
+ deconstructJSON(layOutData[key] , label, key);
+ } else {
+ var attirbuteLabel = label;
+ var defaultValue='';
+ var description='';
+ var isRequired = false;
+ if (layOutData[key].includes('defaultValue-')){
+ defaultValue = layOutData[key].split('defaultValue-')[1];
+ }
+
+ if (layOutData[key].includes('description-')){
+ description = layOutData[key].split('description-')[1];
+ }
+
- }
- }
- }
- }
- }
- }
-
- var elementObject = {};
- switch (layOutData[key].split(splitcolon)[0]){
-
- case stringValue:
- case string:
- if($scope.dataOrderInfo){
- elementOrderNum++;
- elementObject = {"id": elementOrderNum,"attributekey" : attributekey, "array": array, "attirbuteLabel" : attirbuteLabel, "defaultValue": defaultValue, "isRequired": isRequired, "type":"text", "description":description};
- $scope.layOutElementList.push(elementObject);
- }else{
- $scope.attributeBox(attributekey, array, attirbuteLabel, defaultValue, isRequired, "text");
- }
- break;
- case intValue:
- case integerValue:
- if($scope.dataOrderInfo){
- elementOrderNum++;
- elementObject = {"id": elementOrderNum,"attributekey" : attributekey, "array": array, "attirbuteLabel" : attirbuteLabel, "defaultValue": defaultValue,"isRequired": isRequired, "type":"number" , "description":description};
- $scope.layOutElementList.push(elementObject);
- }else{
- $scope.attributeBox(attributekey, array, attirbuteLabel, defaultValue, isRequired, "number");
- }
- break;
- case double:
- if($scope.dataOrderInfo){
- elementOrderNum++;
- elementObject = {"id": elementOrderNum,"attributekey" : attributekey, "array": array, "attirbuteLabel" : attirbuteLabel, "defaultValue": defaultValue,"isRequired": isRequired, "type":"double", "description":description};
- $scope.layOutElementList.push(elementObject);
- }else{
- $scope.attributeBox(attributekey, array, attirbuteLabel, defaultValue, isRequired, "double");
- }
- break;
- case boolean:
- if($scope.dataOrderInfo){
- elementOrderNum++;
- elementObject = {"id": elementOrderNum,"attributekey" : attributekey, "array": array, "attirbuteLabel" : attirbuteLabel, "defaultValue": defaultValue, "isRequired": isRequired, "type":"boolean", "description":description};
- $scope.layOutElementList.push(elementObject);
- }else{
- $scope.dropBoxLayout(attirbuteLabel, attributekey, array, layOutData[key], getBooleanList());
- }
- break;
- default:
- if (layOutData[key].includes('dictionary-')){
- var list = getDictionary(layOutData[key].split('dictionary-')[1]);
- }else{
- //--- get dropdown values from enumValues
- var list = getList(layOutData[key]);
- }
- if (list.length===0){ //not dropdown element
- if($scope.dataOrderInfo){
- elementOrderNum++;
- elementObject = {"id": elementOrderNum,"attributekey" : attributekey, "array": array, "attirbuteLabel" : attirbuteLabel, "defaultValue": defaultValue,"isRequired": isRequired, "type":"text", "description":description};
- $scope.layOutElementList.push(elementObject);
-
- }else{
- $scope.attributeBox(attributekey, array, attirbuteLabel, defaultValue, isRequired, "text");
- }
- }else{
- if($scope.dataOrderInfo){
- elementOrderNum++;
- elementObject = {"id": elementOrderNum, "attributekey" : attributekey, "array": array, "attirbuteLabel" : attirbuteLabel, "defaultValue": defaultValue,"isRequired": isRequired, "list":list, "type":"dropBox", "description":description};
- $scope.layOutElementList.push(elementObject);
- }else{
- $scope.dropBoxLayout(attirbuteLabel, attributekey, array, layOutData[key], list, isRequired);
- }
- }
- break;
- }
- }
- }
- }
-
-
- $scope.validContionalRequired = function(parentId) {
- console.log("ng-blur event: parentId : " + parentId);
- var c = document.getElementById(parentId).children;
- var i;
- var hasValue = false;
- for (i = 0; i < c.length; i++) {
- if(c[i].getAttribute("data-conditional")){
- console.log(c[i].getAttribute("data-conditional"));
- console.log(c[i].value);
- if(c[i].value != null && c[i].value.trim() != ""){
- hasValue = true;
- }
- }
- }
+ if (key==="0"){
+ array = true;
+ attributekey = lableList.pop();
+ attirbuteLabel = baseLevel;
+ } else {
+ attributekey = key.split();
+ }
+
+ if (layOutData[key].includes('required-true')){
+ isRequired = true;
+ }
+
+ var subAttributes = $scope.dcaeModelData.subAttributes;
+
+ if(subAttributes){
+ var jsonObject = JSON.parse(subAttributes);
+
+ var lablInfo = findVal(jsonObject, attributekey);
+ if (lablInfo){
+ if(lablInfo.includes('required-true')){
+ isRequired = true;
+ }
+ if(lablInfo.includes('defaultValue-')){
+ defaultValue = lablInfo.split('defaultValue-')[1];
+ }
+
+ if(lablInfo.includes('description-')){
+ description = lablInfo.split('description-')[1];
+ }
+
+ }else{
+ var allkeys = Object.keys(jsonObject);
+ if(allkeys){
+ for (var k = 0; k < allkeys.length; k++) {
+ var keyValue = allkeys[k];
+ if(jsonObject[keyValue]){
+ var tempObject = jsonObject[keyValue];
+ if(tempObject && tempObject[key]){
+ if (tempObject[key].includes('required-true')){
+ isRequired = true;
+ }
+
+ if(tempObject[key].includes('defaultValue-')){
+ defaultValue = tempObject[key].split('defaultValue-')[1];
+ }
+
+ if(tempObject[key].includes('description-')){
+ description = tempObject[key].split('description-')[1];
+ }
- for (i = 0; i < c.length; i++) {
- if(c[i].getAttribute("data-conditional")){
- if(hasValue){
- c[i].setAttribute("required", true);
- }else{
- c[i].removeAttribute("required");
- }
- }
- }
- }
-
- $scope.jsonLayout = function(layOutData){
-
- deconstructJSON(layOutData , "", "");
-
- var orderValue = $scope.dataOrderInfo;
- var layOutElementList = $scope.layOutElementList;
- var labelList = $scope.layOutOnlyLableList;
-
- //reset to default
- elementOrderNum = 0;
- $scope.layOutElementList = [];
- $scope.layOutOnlyLableList = [];
-
- // Only layout in order if order info provided
- if(orderValue){
-
- if(orderValue.includes("[")){
- orderValue = orderValue.replace("[", "") ;
- orderValue = orderValue.replace("]", "") ;
- }
-
- orderValue = orderValue.split(',') ;
-
- for (var i = 0; i < orderValue.length; i++) {
- console.log("orderValue["+i+"]"+ orderValue[i]);
- var key = orderValue[i].trim();
-
- //--- Create labels first {"label" : newKey, "level" : baseLevel, "array" : array};
- if(labelList){
- for (var k = 0; k < labelList.length; k++){
-
- var label = labelList[k].label.toString().trim();
- var level = labelList[k].level.toString().trim();
- var array = labelList[k].array;
-
- if(key == label){
- $scope.labelLayout(level, label, array);
- //in case to have duplicate label names
- labelList[k].label = "*processed*";
- break;
- }
- }
- }
- //--- then layout each element based on its order defined in YAML file
- for (var j = 0; j < layOutElementList.length; j++) {
-
- var attributekey = layOutElementList[j].attributekey.toString().trim();
-
- if(key == attributekey){
+ }
+ }
+ }
+ }
+ }
+ }
+
+ var elementObject = {};
+ switch (layOutData[key].split(splitcolon)[0]){
+
+ case stringValue:
+ case string:
+ if($scope.dataOrderInfo){
+ elementOrderNum++;
+ elementObject = {"id": elementOrderNum,"attributekey" : attributekey, "array": array, "attirbuteLabel" : attirbuteLabel, "defaultValue": defaultValue, "isRequired": isRequired, "type":"text", "description":description};
+ $scope.layOutElementList.push(elementObject);
+ }else{
+ $scope.attributeBox(attributekey, array, attirbuteLabel, defaultValue, isRequired, "text");
+ }
+ break;
+ case intValue:
+ case integerValue:
+ if($scope.dataOrderInfo){
+ elementOrderNum++;
+ elementObject = {"id": elementOrderNum,"attributekey" : attributekey, "array": array, "attirbuteLabel" : attirbuteLabel, "defaultValue": defaultValue,"isRequired": isRequired, "type":"number" , "description":description};
+ $scope.layOutElementList.push(elementObject);
+ }else{
+ $scope.attributeBox(attributekey, array, attirbuteLabel, defaultValue, isRequired, "number");
+ }
+ break;
+ case double:
+ if($scope.dataOrderInfo){
+ elementOrderNum++;
+ elementObject = {"id": elementOrderNum,"attributekey" : attributekey, "array": array, "attirbuteLabel" : attirbuteLabel, "defaultValue": defaultValue,"isRequired": isRequired, "type":"double", "description":description};
+ $scope.layOutElementList.push(elementObject);
+ }else{
+ $scope.attributeBox(attributekey, array, attirbuteLabel, defaultValue, isRequired, "double");
+ }
+ break;
+ case boolean:
+ if($scope.dataOrderInfo){
+ elementOrderNum++;
+ elementObject = {"id": elementOrderNum,"attributekey" : attributekey, "array": array, "attirbuteLabel" : attirbuteLabel, "defaultValue": defaultValue, "isRequired": isRequired, "type":"boolean", "description":description};
+ $scope.layOutElementList.push(elementObject);
+ }else{
+ $scope.dropBoxLayout(attirbuteLabel, attributekey, array, layOutData[key], getBooleanList());
+ }
+ break;
+ default:
+ if (layOutData[key].includes('dictionary-')){
+ var list = getDictionary(layOutData[key].split('dictionary-')[1]);
+ }else{
+ // --- get dropdown values from enumValues
+ var list = getList(layOutData[key]);
+ }
+ if (list.length===0){ // not dropdown element
+ if($scope.dataOrderInfo){
+ elementOrderNum++;
+ elementObject = {"id": elementOrderNum,"attributekey" : attributekey, "array": array, "attirbuteLabel" : attirbuteLabel, "defaultValue": defaultValue,"isRequired": isRequired, "type":"text", "description":description};
+ $scope.layOutElementList.push(elementObject);
+
+ }else{
+ $scope.attributeBox(attributekey, array, attirbuteLabel, defaultValue, isRequired, "text");
+ }
+ }else{
+ if($scope.dataOrderInfo){
+ elementOrderNum++;
+ elementObject = {"id": elementOrderNum, "attributekey" : attributekey, "array": array, "attirbuteLabel" : attirbuteLabel, "defaultValue": defaultValue,"isRequired": isRequired, "list":list, "type":"dropBox", "description":description};
+ $scope.layOutElementList.push(elementObject);
+ }else{
+ $scope.dropBoxLayout(attirbuteLabel, attributekey, array, layOutData[key], list, isRequired);
+ }
+ }
+ break;
+ }
+ }
+ }
+ }
+
+
+ $scope.validContionalRequired = function(parentId) {
+ var c = document.getElementById(parentId).children;
+ var i;
+ var hasValue = false;
+ for (i = 0; i < c.length; i++) {
+ if(c[i].getAttribute("data-conditional")){
+ if(c[i].value != null && c[i].value.trim() != ""){
+ hasValue = true;
+ }
+ }
+ }
- var attirbuteLabel = layOutElementList[j].attirbuteLabel.toString().trim();
- var defaultValue = layOutElementList[j].defaultValue.toString().trim();
- var description = layOutElementList[j].description;
- var isRequired = layOutElementList[j].isRequired;
-
- console.log("layOutElementList[" +j+ "]: id:" + layOutElementList[j].id + ", attributekey:"+ layOutElementList[j].attributekey + ", attirbuteLabel:" + layOutElementList[j].attirbuteLabel);
- console.log("layOutElementList[" +j+ "]: type:" + layOutElementList[j].type);
- if (layOutElementList[j].type == "dropBox"){
- $scope.dropBoxLayout(attirbuteLabel, attributekey, layOutElementList[j].array, defaultValue, layOutElementList[j].list, isRequired, description);
-
- }else{
- $scope.attributeBox(attributekey, layOutElementList[j].array, attirbuteLabel, defaultValue, isRequired, layOutElementList[j].type, description);
-
- }
-
- //in case to have duplicate attribute names
- layOutElementList[j].attributekey = "*processed*";
- break;
- }
- }
- }
- }
- }
-
-
- $scope.attributeBox = function(attibuteKey, attributeManyKey, labelValue, defaultValue, isRequired, dataType, description){
- $scope.temp.policy.ruleGridData.push(attibuteKey);
- var br = document.createElement("BR");
-
- var label = document.createElement("Label");
- var labeltext = null;
- var requiredLabName = "";
- if (matching.includes(attibuteKey)){
- labeltext = document.createTextNode(attibuteKey + "*!");
- isRequired = true; //set required as true for matching element
- }else {
- if(isRequired){
- requiredLabName = attibuteKey + " * ";
- labeltext = document.createTextNode(requiredLabName);
- }else{
- labeltext = document.createTextNode(attibuteKey);
- }
- }
+ for (i = 0; i < c.length; i++) {
+ if(c[i].getAttribute("data-conditional")){
+ if(hasValue){
+ c[i].setAttribute("required", true);
+ }else{
+ c[i].removeAttribute("required");
+ }
+ }
+ }
+ }
+
+ $scope.jsonLayout = function(layOutData){
+
+ deconstructJSON(layOutData , "", "");
+
+ var orderValue = $scope.dataOrderInfo;
+ var layOutElementList = $scope.layOutElementList;
+ var labelList = $scope.layOutOnlyLableList;
+
+ // reset to default
+ elementOrderNum = 0;
+ $scope.layOutElementList = [];
+ $scope.layOutOnlyLableList = [];
+
+ // Only layout in order if order info provided
+ if(orderValue){
+
+ if(orderValue.includes("[")){
+ orderValue = orderValue.replace("[", "") ;
+ orderValue = orderValue.replace("]", "") ;
+ }
+
+ orderValue = orderValue.split(',') ;
+
+ for (var i = 0; i < orderValue.length; i++) {
+ var key = orderValue[i].trim();
+
+ // --- Create labels first {"label" : newKey, "level" : baseLevel, "array" : array};
+ if(labelList){
+ for (var k = 0; k < labelList.length; k++){
+
+ var label = labelList[k].label.toString().trim();
+ var level = labelList[k].level.toString().trim();
+ var array = labelList[k].array;
+
+ if(key == label){
+ $scope.labelLayout(level, label, array);
+ // in case to have duplicate label names
+ labelList[k].label = "*processed*";
+ break;
+ }
+ }
+ }
+ // --- then layout each element based on its order defined in YAML file
+ for (var j = 0; j < layOutElementList.length; j++) {
+
+ var attributekey = layOutElementList[j].attributekey.toString().trim();
+
+ if(key == attributekey){
-
- var divID = labelValue;
-
- if (labelValue.length < 1){
- divID = "DynamicTemplate";
- }else if (labelValue.endsWith('.')){
- var divID = 'div.'+ labelValue.substring(0, labelValue.length-1);
- }
-
- label.appendChild(labeltext);
-
- var textField = document.createElement("INPUT");
-
- textField.setAttribute("class" , "form-control");
- if(dataType){
- if(dataType == "double"){
- textField.setAttribute("type" , "number");
- textField.setAttribute("step" , "any");
+ var attirbuteLabel = layOutElementList[j].attirbuteLabel.toString().trim();
+ var defaultValue = layOutElementList[j].defaultValue.toString().trim();
+ var description = layOutElementList[j].description;
+ var isRequired = layOutElementList[j].isRequired;
+
+ if (layOutElementList[j].type == "dropBox"){
+ $scope.dropBoxLayout(attirbuteLabel, attributekey, layOutElementList[j].array, defaultValue, layOutElementList[j].list, isRequired, description);
+
+ }else{
+ $scope.attributeBox(attributekey, layOutElementList[j].array, attirbuteLabel, defaultValue, isRequired, layOutElementList[j].type, description);
+
+ }
+
+ // in case to have duplicate attribute names
+ layOutElementList[j].attributekey = "*processed*";
+ break;
+ }
+ }
+ }
+ }
+ }
+
+
+ $scope.attributeBox = function(attibuteKey, attributeManyKey, labelValue, defaultValue, isRequired, dataType, description){
+ $scope.temp.policy.ruleGridData.push(attibuteKey);
+ var br = document.createElement("BR");
+
+ var label = document.createElement("Label");
+ var labeltext = null;
+ var requiredLabName = "";
+ if (matching.includes(attibuteKey)){
+ labeltext = document.createTextNode(attibuteKey + "*!");
+ isRequired = true; // set required as true for matching element
+ }else {
+ if(isRequired){
+ requiredLabName = attibuteKey + " * ";
+ labeltext = document.createTextNode(requiredLabName);
+ }else{
+ labeltext = document.createTextNode(attibuteKey);
+ }
+ }
- }else if(dataType == "boolean"){ //gw1218 testing boolean
- var booleanDiv = document.createElement("div");
+
+ var divID = labelValue;
+
+ if (labelValue.length < 1){
+ divID = "DynamicTemplate";
+ }else if (labelValue.endsWith('.')){
+ var divID = 'div.'+ labelValue.substring(0, labelValue.length-1);
+ }
+
+ label.appendChild(labeltext);
+
+ var textField = document.createElement("INPUT");
+
+ textField.setAttribute("class" , "form-control");
+ if(dataType){
+ if(dataType == "double"){
+ textField.setAttribute("type" , "number");
+ textField.setAttribute("step" , "any");
- booleanDiv.setAttribute("class" , "onoffswitch");
+ }else if(dataType == "boolean"){ // gw1218 testing boolean
+ var booleanDiv = document.createElement("div");
- //var checkField = document.createElement("INPUT");
- textField.setAttribute("type" , "checkbox");
- textField.setAttribute("name" , "onoffswitch");
- textField.setAttribute("class" , "onoffswitch-checkbox");
- textField.setAttribute("id" , ''+labelValue +attibuteKey+'');
- if(defaultValue.substring(0,defaultValue.indexOf(":")) == "true") {
- textField.setAttribute("checked" , true);
- }else{
- textField.removeAttribute("checked");
- }
+ booleanDiv.setAttribute("class" , "onoffswitch");
- var booleanlabel = document.createElement("Label");
- booleanlabel.setAttribute("class" , "onoffswitch-label");
- booleanlabel.setAttribute("for" , ''+labelValue +attibuteKey+'');
-
- var span1 = document.createElement("span");
- span1.setAttribute("class" , "onoffswitch-inner");
-
- var span2 = document.createElement("span");
- span2.setAttribute("class" , "onoffswitch-switch");
-
-
- booleanlabel.appendChild(span1);
- booleanlabel.appendChild(span2);
- booleanDiv.appendChild(textField);
- booleanDiv.appendChild(booleanlabel);
-
- document.getElementById(divID).appendChild(label);
- document.getElementById(divID).appendChild(booleanDiv);
+ // var checkField = document.createElement("INPUT");
+ textField.setAttribute("type" , "checkbox");
+ textField.setAttribute("name" , "onoffswitch");
+ textField.setAttribute("class" , "onoffswitch-checkbox");
+ textField.setAttribute("id" , ''+labelValue +attibuteKey+'');
+ if(defaultValue.substring(0,defaultValue.indexOf(":")) == "true") {
+ textField.setAttribute("checked" , true);
+ }else{
+ textField.removeAttribute("checked");
+ }
+ textField.setAttribute("ng-click" , "validateOnAndOff('"+labelValue +attibuteKey+"', $event)");
+ var booleanlabel = document.createElement("Label");
+ booleanlabel.setAttribute("class" , "onoffswitch-label");
+ booleanlabel.setAttribute("for" , ''+labelValue +attibuteKey+'');
+
+ var span1 = document.createElement("span");
+ span1.setAttribute("class" , "onoffswitch-inner");
+
+ var span2 = document.createElement("span");
+ span2.setAttribute("class" , "onoffswitch-switch");
+
+
+ booleanlabel.appendChild(span1);
+ booleanlabel.appendChild(span2);
+ booleanDiv.appendChild(textField);
+ booleanDiv.appendChild(booleanlabel);
+
+ document.getElementById(divID).appendChild(label);
+ document.getElementById(divID).appendChild(booleanDiv);
- //return;
- } else{
- textField.setAttribute("type" , dataType);
- }
-
-
+ // return;
+ } else{
+ textField.setAttribute("type" , dataType);
+ }
+
+
- }
-
- if(dataType != "boolean"){
- textField.setAttribute("style" , "width:300px;");
- textField.setAttribute("ng-disabled" , "temp.policy.readOnly");
- if(description && description != "null"){
- textField.setAttribute("title", description);
- }
- }
+ }
+
+ if(dataType != "boolean"){
+ textField.setAttribute("style" , "width:300px;");
+ textField.setAttribute("ng-disabled" , "temp.policy.readOnly");
+ if(description && description != "null"){
+ textField.setAttribute("title", description);
+ }
+ }
- var checkKey;
- var id = "";
- if(attributeManyKey){
- checkKey = labelValue + attibuteKey+'@0';
- textField.setAttribute("id" , ''+labelValue + attibuteKey+'@0'+'');
- var divTag = document.createElement("div");
- divTag.setAttribute("id", "div."+ labelValue +attibuteKey);
- var addButton = document.createElement("BUTTON");
- var buttonaddLabel = document.createTextNode("+");
- addButton.appendChild(buttonaddLabel);
- addButton.setAttribute("id", labelValue + attibuteKey);
- addButton.setAttribute("class", "btn btn-add-remove");
- addButton.setAttribute("onclick" , 'addNewChoice("'+labelValue + attibuteKey+'");');
- addButton.setAttribute("ng-disabled" , "temp.policy.readOnly");
- var removeButton = document.createElement("BUTTON");
- var buttonremoveLabel = document.createTextNode("-");
- removeButton.appendChild(buttonremoveLabel);
- removeButton.setAttribute("class", "btn btn-add-remove");
- removeButton.setAttribute("onclick" , 'removeChoice("'+labelValue + attibuteKey+'");');
- removeButton.setAttribute("ng-disabled" , "temp.policy.readOnly");
- document.getElementById(divID).appendChild(addButton);
- document.getElementById(divID).appendChild(removeButton);
- document.getElementById(divID).appendChild(label);
- id = "div."+labelValue+attibuteKey;
- //var divTag = document.createElement("div");
- divTag.setAttribute("id", id);
- document.getElementById(divID).appendChild(divTag);
- textField.className += ' first_child';
- if(isRequired){
- textField.setAttribute("required", "true");
- }
-
- divTag.appendChild(textField);
- document.getElementById(divID).appendChild(divTag);
-
- }else if (dataType != "boolean"){
- checkKey = labelValue + attibuteKey;
- textField.setAttribute("id" , ''+labelValue +attibuteKey+'');
- if(document.getElementById(divID).hasAttribute('required') || !document.getElementById(divID).hasAttribute('data-conditional')){
- if(requiredLabName.includes("*") || isRequired){
- textField.setAttribute("required", "true");
- }
- }else if (document.getElementById(divID).hasAttribute('data-conditional')){
- if(requiredLabName.includes("*")){
- var requiredNode = document.createElement('span');
- requiredNode.setAttribute("class", "mstooltip");
- requiredNode.textContent = "?";
- label.appendChild(requiredNode);
-
- var requiredNodeToolTip = document.createElement('span');
- requiredNodeToolTip.setAttribute("class", "tooltiptext");
- requiredNodeToolTip.textContent = "Conditional Required";
- requiredNode.appendChild(requiredNodeToolTip);
-
- textField.setAttribute("data-conditional", divID);
- textField.setAttribute("ng-blur", "validContionalRequired('"+divID+"')");
- }
- }
+ var checkKey;
+ var id = "";
+ if(attributeManyKey){
+ checkKey = labelValue + attibuteKey+'@0';
+ textField.setAttribute("id" , ''+labelValue + attibuteKey+'@0'+'');
+ var divTag = document.createElement("div");
+ divTag.setAttribute("id", "div."+ labelValue +attibuteKey);
+ var addButton = document.createElement("BUTTON");
+ var buttonaddLabel = document.createTextNode("+");
+ addButton.appendChild(buttonaddLabel);
+ addButton.setAttribute("id", labelValue + attibuteKey);
+ addButton.setAttribute("class", "btn btn-add-remove");
+ addButton.setAttribute("onclick" , 'addNewChoice("'+labelValue + attibuteKey+'");');
+ addButton.setAttribute("ng-disabled" , "temp.policy.readOnly");
+ var removeButton = document.createElement("BUTTON");
+ var buttonremoveLabel = document.createTextNode("-");
+ removeButton.appendChild(buttonremoveLabel);
+ removeButton.setAttribute("class", "btn btn-add-remove");
+ removeButton.setAttribute("onclick" , 'removeChoice("'+labelValue + attibuteKey+'");');
+ removeButton.setAttribute("ng-disabled" , "temp.policy.readOnly");
+ document.getElementById(divID).appendChild(addButton);
+ document.getElementById(divID).appendChild(removeButton);
+ document.getElementById(divID).appendChild(label);
+ id = "div."+labelValue+attibuteKey;
+ // var divTag = document.createElement("div");
+ divTag.setAttribute("id", id);
+ document.getElementById(divID).appendChild(divTag);
+ textField.className += ' first_child';
+ if(isRequired){
+ textField.setAttribute("required", "true");
+ }
+
+ divTag.appendChild(textField);
+ document.getElementById(divID).appendChild(divTag);
+
+ }else if (dataType != "boolean"){
+ checkKey = labelValue + attibuteKey;
+ textField.setAttribute("id" , ''+labelValue +attibuteKey+'');
+ if(document.getElementById(divID).hasAttribute('required') || !document.getElementById(divID).hasAttribute('data-conditional')){
+ if(requiredLabName.includes("*") || isRequired){
+ textField.setAttribute("required", "true");
+ }
+ }else if (document.getElementById(divID).hasAttribute('data-conditional')){
+ if(requiredLabName.includes("*")){
+ var requiredNode = document.createElement('span');
+ requiredNode.setAttribute("class", "mstooltip");
+ requiredNode.textContent = "?";
+ label.appendChild(requiredNode);
+
+ var requiredNodeToolTip = document.createElement('span');
+ requiredNodeToolTip.setAttribute("class", "tooltiptext");
+ requiredNodeToolTip.textContent = "Conditional Required";
+ requiredNode.appendChild(requiredNodeToolTip);
+
+ textField.setAttribute("data-conditional", divID);
+ textField.setAttribute("ng-blur", "validContionalRequired('"+divID+"')");
+ }
+ }
- document.getElementById(divID).appendChild(label);
- document.getElementById(divID).appendChild(textField);
- document.getElementById(divID).appendChild(br);
+ document.getElementById(divID).appendChild(label);
+ document.getElementById(divID).appendChild(textField);
+ document.getElementById(divID).appendChild(br);
- }
+ }
- if(dataType != "boolean" && divID.includes("@0") && divID.includes("div.")){
- var firstChild_Id = divID.split("@0")[0];
- var firstChild_element = document.getElementById(firstChild_Id);
- if(firstChild_element){
-
- if(!firstChild_element.className.includes('children_group border')){
- layer++;
- if(layer > 4){
- layer = 1
- };
- firstChild_element.className += ' children_group border' + layer; //here is div with a group of children.
- }
- }
- }
- console.log('firstChild_Id: ' + firstChild_Id);
- console.log('divID: ' + divID);
-
- if(dataType != "boolean" && defaultValue.length > 0){
- if(defaultValue.includes(":")){
- defaultValue = defaultValue.split(":")[0];
- if(defaultValue === "NA") {
- defaultValue = "";
- }
- }
- if(defaultValue != "undefined" && defaultValue != undefined && defaultValue != "null"){
- document.getElementById(checkKey).value = defaultValue;
- }
- }
-
- if($scope.temp.policy.ruleData != null){
- //document.getElementById(checkKey).value = $scope.temp.policy.ruleData[checkKey];
- if (attributeManyKey){
- var newCheckKey = checkKey.replace(attibuteKey + '@0',attibuteKey);
- if($scope.temp.policy.ruleData[newCheckKey +'@0'] != undefined && $scope.temp.policy.ruleData[newCheckKey +'@0'] != "undefined"){
- document.getElementById(newCheckKey +'@0').value = $scope.temp.policy.ruleData[newCheckKey +'@0'];
- }
- }else{
- if($scope.temp.policy.ruleData[checkKey] != undefined && $scope.temp.policy.ruleData[checkKey] != "undefined"){
- document.getElementById(checkKey).value = $scope.temp.policy.ruleData[checkKey];
- }
- }
- }
-
- if (dataType != "boolean"){
- plainAttributeKeys.push(labelValue + attibuteKey+'*'+attributeManyKey);
- }else{
- plainAttributeKeys.push(labelValue + attibuteKey+'*'+"boolean");
- }
+ if(dataType != "boolean" && divID.includes("@0") && divID.includes("div.")){
+ var firstChild_Id = divID.split("@0")[0];
+ var firstChild_element = document.getElementById(firstChild_Id);
+ if(firstChild_element){
+
+ if(!firstChild_element.className.includes('children_group border')){
+ layer++;
+ if(layer > 4){
+ layer = 1
+ }
+ firstChild_element.className += ' children_group border' + layer; // here is div with a group of children.
+ }
+ }
+ }
+
+ if(dataType != "boolean" && defaultValue.length > 0){
+ if(defaultValue.includes(":")){
+ defaultValue = defaultValue.split(":")[0];
+ if(defaultValue === "NA") {
+ defaultValue = "";
+ }
+ }
+ if(defaultValue != "undefined" && defaultValue != undefined && defaultValue != "null"){
+ document.getElementById(checkKey).value = defaultValue;
+ }
+ }
+
+ if($scope.temp.policy.ruleData != null){
+ // document.getElementById(checkKey).value =
+ // $scope.temp.policy.ruleData[checkKey];
+ if (attributeManyKey){
+ var newCheckKey = checkKey.replace(attibuteKey + '@0',attibuteKey);
+ if($scope.temp.policy.ruleData[newCheckKey +'@0'] != undefined && $scope.temp.policy.ruleData[newCheckKey +'@0'] != "undefined"){
+ document.getElementById(newCheckKey +'@0').value = $scope.temp.policy.ruleData[newCheckKey +'@0'];
+ }
+ }else{
+ if($scope.temp.policy.ruleData[checkKey] != undefined && $scope.temp.policy.ruleData[checkKey] != "undefined"){
+ document.getElementById(checkKey).value = $scope.temp.policy.ruleData[checkKey];
+ }
+ }
+ }
+
+ if (dataType != "boolean"){
+ plainAttributeKeys.push(labelValue + attibuteKey+'*'+attributeManyKey);
+ }else{
+ plainAttributeKeys.push(labelValue + attibuteKey+'*'+"boolean");
+ }
+ };
+
+ $scope.validateOnAndOff = function(id , value) {
+ console.log(id, value);
+ if (value.target.checked) {
+ document.getElementById(id).setAttribute("checked", true);
+ } else {
+ document.getElementById(id).removeAttribute("checked");
+ }
};
-
+
$scope.labelManyKeys = [];
$scope.labelLayout = function(labelValue, lableName, labelManyKey ){
- var label = document.createElement("Label")
- var divID = labelValue;
- if (labelValue.endsWith('.')){
- var workingLabel = labelValue.substring(0, labelValue.length-1);
- }else {
- var workingLabel = labelValue;
- }
-
- if (labelValue.length < 1){
- divID = "DynamicTemplate";
- } else if (labelValue.endsWith('.')){
- var divID = 'div.'+ labelValue.substring(0, labelValue.length-1);
- }
-
- var subAttributes = $scope.dcaeModelData.sub_attributes;
- var jsonObject = JSON.parse(subAttributes);
- var lablInfo = findVal(jsonObject, lableName);
- console.log("findValue : " + lableName +": "+ lablInfo);
- var star = "";
- var required = null;
- if(lablInfo){
- if(typeof lablInfo === 'string' ){
- if(lablInfo.includes("required-true")){
- star = " *";
- required = true;
- }else if (lablInfo.includes("required-false")){
- required = false
- }
- }
- }
-
- var labeltext = document.createTextNode(lableName + star);
-
- label.appendChild(labeltext);
+ var label = document.createElement("Label")
+ var divID = labelValue;
+ if (labelValue.endsWith('.')){
+ var workingLabel = labelValue.substring(0, labelValue.length-1);
+ }else {
+ var workingLabel = labelValue;
+ }
+ if (labelValue.length < 1){
+ divID = "DynamicTemplate";
+ } else if (labelValue.endsWith('.')){
+ var divID = 'div.'+ labelValue.substring(0, labelValue.length-1);
+ }
+
+ var subAttributes = $scope.dcaeModelData.subAttributes;
+ var jsonObject = JSON.parse(subAttributes);
+ var lablInfo = findVal(jsonObject, lableName);
+ var star = "";
+ var required = null;
+ if(lablInfo){
+ if(typeof lablInfo === 'string' ){
+ if(lablInfo.includes("required-true")){
+ star = " *";
+ required = true;
+ }else if (lablInfo.includes("required-false")){
+ required = false
+ }
+ }
+ }
+
+ var labeltext = document.createTextNode(lableName + star);
+
+ label.appendChild(labeltext);
- if(labelManyKey){
- var addButton = document.createElement("BUTTON");
- var buttonLabel = document.createTextNode("+");
- addButton.appendChild(buttonLabel);
- addButton.setAttribute("class", "btn btn-add-remove");
- addButton.setAttribute("onclick" , 'addNewChoice("'+labelValue + lableName+'");');
- addButton.setAttribute("ng-disabled" , "temp.policy.readOnly");
- var removeButton = document.createElement("BUTTON");
- var buttonremoveLabel = document.createTextNode("-");
- removeButton.appendChild(buttonremoveLabel);
- removeButton.setAttribute("class", "btn btn-add-remove");
- removeButton.setAttribute("onclick" , 'removeChoice("'+labelValue +lableName+'");');
- removeButton.setAttribute("ng-disabled" , "temp.policy.readOnly");
- document.getElementById(divID).appendChild(addButton);
- document.getElementById(divID).appendChild(removeButton);
- document.getElementById(divID).appendChild(label);
- var id = "div."+labelValue+lableName;
- var divTag = document.createElement("div");
- divTag.setAttribute("id", id);
- document.getElementById(divID).appendChild(divTag);
-
- var divTag = document.createElement("div");
- divTag.setAttribute("id", id +'@0');
-
- if(!divTag.className.includes('children_group border')){
- layer++;
- if(layer > 4){
- layer = 1
- };
- divTag.className += ' children_group border' + layer; //here is div with a group of children.
- }
- if(required){
- divTag.setAttribute("required", required);
- }else if(required == false){
- divTag.setAttribute("data-conditional", "yes");
- }
-
- document.getElementById(id).appendChild(divTag);
-
- $scope.labelManyKeys.push(lableName);
-
- }else{
- var divTag = document.createElement("div");
- divTag.setAttribute("id", "div."+labelValue+lableName);
-
- if(!divTag.className.includes('children_group border')){
- layer++;
- if(layer > 4){
- layer = 1
- };
- divTag.className += ' children_group border' + layer; //here is div with a group of children.
- }
- if(required){
- divTag.setAttribute("required", required);
- }else if(required == false){
- divTag.setAttribute("data-conditional", "yes");
- }
- document.getElementById(divID).appendChild(label);
- document.getElementById(divID).appendChild(divTag);
- }
+ if(labelManyKey){
+ var addButton = document.createElement("BUTTON");
+ var buttonLabel = document.createTextNode("+");
+ addButton.appendChild(buttonLabel);
+ addButton.setAttribute("class", "btn btn-add-remove");
+ addButton.setAttribute("onclick" , 'addNewChoice("'+labelValue + lableName+'");');
+ addButton.setAttribute("ng-disabled" , "temp.policy.readOnly");
+ var removeButton = document.createElement("BUTTON");
+ var buttonremoveLabel = document.createTextNode("-");
+ removeButton.appendChild(buttonremoveLabel);
+ removeButton.setAttribute("class", "btn btn-add-remove");
+ removeButton.setAttribute("onclick" , 'removeChoice("'+labelValue +lableName+'");');
+ removeButton.setAttribute("ng-disabled" , "temp.policy.readOnly");
+ document.getElementById(divID).appendChild(addButton);
+ document.getElementById(divID).appendChild(removeButton);
+ document.getElementById(divID).appendChild(label);
+ var id = "div."+labelValue+lableName;
+ var divTag = document.createElement("div");
+ divTag.setAttribute("id", id);
+ document.getElementById(divID).appendChild(divTag);
+
+ var divTag = document.createElement("div");
+ divTag.setAttribute("id", id +'@0');
+
+ if(!divTag.className.includes('children_group border')){
+ layer++;
+ if(layer > 4){
+ layer = 1
+ }
+ divTag.className += ' children_group border' + layer; // here is div with a group of children.
+ }
+ if(required){
+ divTag.setAttribute("required", required);
+ }else if(required == false){
+ divTag.setAttribute("data-conditional", "yes");
+ }
+
+ document.getElementById(id).appendChild(divTag);
+
+ $scope.labelManyKeys.push(lableName);
+
+ }else{
+ var divTag = document.createElement("div");
+ divTag.setAttribute("id", "div."+labelValue+lableName);
+
+ if(!divTag.className.includes('children_group border')){
+ layer++;
+ if(layer > 4){
+ layer = 1
+ }
+ divTag.className += ' children_group border' + layer; // here is div with a group of children.
+ }
+ if(required){
+ divTag.setAttribute("required", required);
+ }else if(required == false){
+ divTag.setAttribute("data-conditional", "yes");
+ }
+ document.getElementById(divID).appendChild(label);
+ document.getElementById(divID).appendChild(divTag);
+ }
};
$scope.dropBoxLayout = function(labelLevel, attributeName, many , defaultValue, listemunerateValues, isRequired, description){
- var br = document.createElement("BR");
-
- if (labelLevel.length < 1){
- var divID = "DynamicTemplate";
- } else if (labelLevel.endsWith('.')){
- var divID = 'div.'+ labelLevel.substring(0, labelLevel.length-1);
- }
-
-
- var label = document.createElement("Label")
-
- var refAttributes = $scope.dcaeModelData.ref_attributes;
- if(isRequired != true && refAttributes){ //check refAttributes also
- var refAttributesList = refAttributes.split(splitComma);
- for (k = 0; k < refAttributesList.length; k++){
- var refAttribute = refAttributesList[k].split(splitEqual);
- if (attributeName == refAttribute[0].trim() && refAttribute[1].includes("required-true")){
- isRequired = true;
- }
- }
- }
-
- if (matching.includes(attributeName)){
- var labeltext = document.createTextNode(attributeName + "*!");
- label.appendChild(labeltext);
- isRequired = true; //set required as true for matching element
- }else {
- var labeltext = document.createTextNode(attributeName);
- if(isRequired){
- var requiredLabName = attributeName+ " * ";
- labeltext = document.createTextNode(requiredLabName);
- }else{
- labeltext = document.createTextNode(attributeName);
- }
-
- label.appendChild(labeltext);
- }
- label.appendChild(labeltext);
- // if this field is required, but its parent is not required
- if(isRequired && document.getElementById(divID).hasAttribute('data-conditional')){
- var requiredNode = document.createElement('span');
- requiredNode.setAttribute("class", "mstooltip");
- requiredNode.textContent = "?";
- label.appendChild(requiredNode);
-
- var requiredNodeToolTip = document.createElement('span');
- requiredNodeToolTip.setAttribute("class", "tooltiptext");
- requiredNodeToolTip.textContent = "Conditional Required";
- requiredNode.appendChild(requiredNodeToolTip);
-
- }
-
- var listField = document.createElement("SELECT");
- listField.setAttribute("class" , "form-control");
- listField.setAttribute("style" , "width:300px;");
- listField.setAttribute("ng-disabled" , "temp.policy.readOnly");
+ var br = document.createElement("BR");
+
+ if (labelLevel.length < 1){
+ var divID = "DynamicTemplate";
+ } else if (labelLevel.endsWith('.')){
+ var divID = 'div.'+ labelLevel.substring(0, labelLevel.length-1);
+ }
+
+
+ var label = document.createElement("Label")
+
+ var refAttributes = $scope.dcaeModelData.refAttributes;
+ if(isRequired != true && refAttributes){ // check refAttributes also
+ var refAttributesList = refAttributes.split(splitComma);
+ for (k = 0; k < refAttributesList.length; k++){
+ var refAttribute = refAttributesList[k].split(splitEqual);
+ if (attributeName == refAttribute[0].trim() && refAttribute[1].includes("required-true")){
+ isRequired = true;
+ }
+ }
+ }
+
+ if (matching.includes(attributeName)){
+ var labeltext = document.createTextNode(attributeName + "*!");
+ label.appendChild(labeltext);
+ isRequired = true; // set required as true for matching element
+ }else {
+ var labeltext = document.createTextNode(attributeName);
+ if(isRequired){
+ var requiredLabName = attributeName+ " * ";
+ labeltext = document.createTextNode(requiredLabName);
+ }else{
+ labeltext = document.createTextNode(attributeName);
+ }
+
+ label.appendChild(labeltext);
+ }
+ label.appendChild(labeltext);
+ // if this field is required, but its parent is not required
+ if(isRequired && document.getElementById(divID).hasAttribute('data-conditional')){
+ var requiredNode = document.createElement('span');
+ requiredNode.setAttribute("class", "mstooltip");
+ requiredNode.textContent = "?";
+ label.appendChild(requiredNode);
+
+ var requiredNodeToolTip = document.createElement('span');
+ requiredNodeToolTip.setAttribute("class", "tooltiptext");
+ requiredNodeToolTip.textContent = "Conditional Required";
+ requiredNode.appendChild(requiredNodeToolTip);
- if(description && description != "null"){
- listField.setAttribute("title", description);
- }
+ }
- if(isRequired){
- if(document.getElementById(divID).hasAttribute('data-conditional')){
- listField.setAttribute("data-conditional", divID);
- listField.setAttribute("ng-blur", "validContionalRequired('"+divID+"')");
- }else{
- listField.setAttribute("required", true);
- }
- }
- if( many != true || isRequired != true){ // add an empty option for not required or not multiple select element
- var optionFirst = document.createElement('option');
- var optionValue = "";
- if($scope.temp.policy.ruleData != null){
- if($scope.temp.policy.ruleData[labelLevel + attributeName] != undefined && $scope.temp.policy.ruleData[labelLevel + attributeName] != "undefined"){
- optionValue = $scope.temp.policy.ruleData[labelLevel + attributeName];
- }
- }
- optionFirst.setAttribute('value', optionValue);
- optionFirst.appendChild(document.createTextNode(optionValue));
- listField.appendChild(optionFirst);
- }
- var ruleFormationCheck = false;
- if(listemunerateValues.length !== 0 && typeof listemunerateValues[0] == "string" && listemunerateValues[0].includes("dictionary:")) {
- var ruleCheck = listemunerateValues[0].split("&");
- var dictParams = ruleCheck[0].split(":");
- var dictParamsSplit = dictParams[1].split("@");
- if (ruleCheck[1] != undefined && ruleCheck[1] == 'Rule') {
- ruleFormationCheck = true;
- }
- PolicyAppService.getData(dictParamsSplit[0]).then(function (data) {
- var j = data;
- $scope.data = JSON.parse(j.data);
- console.log($scope.data);
- $scope.listDictionarys = JSON.parse($scope.data[dictParamsSplit[1]]);
- for (i=0; i < $scope.listDictionarys.length; i += 1) {
- option = document.createElement('option');
- option.setAttribute('value', $scope.listDictionarys[i]);
- option.appendChild(document.createTextNode($scope.listDictionarys[i]));
- listField.appendChild(option);
- }
- }, function (error) {
- console.log("failed");
- });
+ var listField = document.createElement("SELECT");
+ listField.setAttribute("class" , "form-control");
+ listField.setAttribute("style" , "width:300px;");
+ listField.setAttribute("ng-disabled" , "temp.policy.readOnly");
- }
- else{
- for (i=0; i < listemunerateValues.length; i += 1) {
- if(typeof listemunerateValues[i] == "string" && listemunerateValues[i].includes("equal-sign")){
- listemunerateValues[i] = listemunerateValues[i].replace('equal-sign','=');
- }
-
- option = document.createElement('option');
- option.setAttribute('value', listemunerateValues[i]);
- option.appendChild(document.createTextNode(listemunerateValues[i]));
- option.setAttribute('value', listemunerateValues[i]);
- listField.appendChild(option);
- }
- }
- listField.setAttribute("id" , ''+ labelLevel + attributeName + '');
+ if(description && description != "null"){
+ listField.setAttribute("title", description);
+ }
- enumKeyList.push(attributeName);
+ if(isRequired){
+ if(document.getElementById(divID).hasAttribute('data-conditional')){
+ listField.setAttribute("data-conditional", divID);
+ listField.setAttribute("ng-blur", "validContionalRequired('"+divID+"')");
+ }else{
+ listField.setAttribute("required", true);
+ }
+ }
+ if( many != true || isRequired != true){ // add an empty option for not required or not multiple select element
+ var optionFirst = document.createElement('option');
+ var optionValue = "";
+ if($scope.temp.policy.ruleData != null){
+ if($scope.temp.policy.ruleData[labelLevel + attributeName] != undefined && $scope.temp.policy.ruleData[labelLevel + attributeName] != "undefined"){
+ optionValue = $scope.temp.policy.ruleData[labelLevel + attributeName];
+ }
+ }
+ optionFirst.setAttribute('value', optionValue);
+ optionFirst.appendChild(document.createTextNode(optionValue));
+ listField.appendChild(optionFirst);
+ }
+ var ruleFormationCheck = false;
+ if(listemunerateValues.length !== 0 && typeof listemunerateValues[0] == "string" && listemunerateValues[0].includes("dictionary:")) {
+ var ruleCheck = listemunerateValues[0].split("&");
+ var dictParams = ruleCheck[0].split(":");
+ var dictParamsSplit = dictParams[1].split("@");
+ if (ruleCheck[1] != undefined && ruleCheck[1] == 'Rule') {
+ ruleFormationCheck = true;
+ }
+ PolicyAppService.getData(dictParamsSplit[0]).then(function (data) {
+ var j = data;
+ $scope.data = JSON.parse(j.data);
+ $scope.listDictionarys = JSON.parse($scope.data[dictParamsSplit[1]]);
+ for (i=0; i < $scope.listDictionarys.length; i += 1) {
+ option = document.createElement('option');
+ option.setAttribute('value', $scope.listDictionarys[i]);
+ option.appendChild(document.createTextNode($scope.listDictionarys[i]));
+ listField.appendChild(option);
+ }
+ });
- document.getElementById(divID).appendChild(label);
- document.getElementById(divID).appendChild(br);
+ }
+ else{
+ for (i=0; i < listemunerateValues.length; i += 1) {
+ if(typeof listemunerateValues[i] == "string" && listemunerateValues[i].includes("equal-sign")){
+ listemunerateValues[i] = listemunerateValues[i].replace('equal-sign','=');
+ }
+
+ option = document.createElement('option');
+ option.setAttribute('value', listemunerateValues[i]);
+ option.appendChild(document.createTextNode(listemunerateValues[i]));
+ option.setAttribute('value', listemunerateValues[i]);
+ listField.appendChild(option);
+ }
+ }
+ listField.setAttribute("id" , ''+ labelLevel + attributeName + '');
- if(many == true){
- document.getElementById(divID).appendChild(listField).multiple = true;
- plainAttributeKeys.push(labelLevel + attributeName+'*'+true);
- }else {
- document.getElementById(divID).appendChild(listField).multiple = false;
- plainAttributeKeys.push(labelLevel + attributeName+'*'+false);
+ enumKeyList.push(attributeName);
- if (defaultValue){
- if(defaultValue.includes(':')){
- defaultValue = defaultValue.split(':')[0];
- }
- var location = listemunerateValues.indexOf(defaultValue);
- document.getElementById(labelLevel +attributeName).options[location+1].selected = true;
- }
- }
+ document.getElementById(divID).appendChild(label);
+ document.getElementById(divID).appendChild(br);
- if (ruleFormationCheck) {
- var optionInput = document.createElement("INPUT");
- optionInput.setAttribute("type" , "text");
- optionInput.setAttribute("id" , ''+ labelLevel + attributeName + '.input');
- optionInput.setAttribute("name" , "ruleName");
- optionInput.setAttribute("value" , " ");
- optionInput.setAttribute("style" , "width:300px;");
- optionInput.setAttribute("ng-disabled" , "temp.policy.readOnly");
- optionInput.removeAttribute("required");
+ if(many == true){
+ document.getElementById(divID).appendChild(listField).multiple = true;
+ plainAttributeKeys.push(labelLevel + attributeName+'*'+true);
+ }else {
+ document.getElementById(divID).appendChild(listField).multiple = false;
+ plainAttributeKeys.push(labelLevel + attributeName+'*'+false);
- document.getElementById(divID).appendChild(optionInput);
+ if (defaultValue){
+ if(defaultValue.includes(':')){
+ defaultValue = defaultValue.split(':')[0];
+ }
+ var location = listemunerateValues.indexOf(defaultValue);
+ document.getElementById(labelLevel +attributeName).options[location+1].selected = true;
+ }
+ }
- var optionButton = document.createElement("BUTTON");
- optionButton.setAttribute("ng-disabled" , "temp.policy.readOnly");
- var buttonLabel = document.createTextNode("+");
- optionButton.appendChild(buttonLabel);
- optionButton.setAttribute("class", "btn btn-add-remove");
- optionButton.setAttribute("onclick" , 'addDynamicOptions("'+ labelLevel + attributeName + '");');
- optionButton.removeAttribute("required");
+ if (ruleFormationCheck) {
+ var optionInput = document.createElement("INPUT");
+ optionInput.setAttribute("type" , "text");
+ optionInput.setAttribute("id" , ''+ labelLevel + attributeName + '.input');
+ optionInput.setAttribute("name" , "ruleName");
+ optionInput.setAttribute("value" , " ");
+ optionInput.setAttribute("style" , "width:300px;");
+ optionInput.setAttribute("ng-disabled" , "temp.policy.readOnly");
+ optionInput.removeAttribute("required");
+ document.getElementById(divID).appendChild(optionInput);
- document.getElementById(divID).appendChild(optionButton);
- document.getElementById(divID).appendChild(br);
- }
+ var optionButton = document.createElement("BUTTON");
+ optionButton.setAttribute("ng-disabled" , "temp.policy.readOnly");
+ var buttonLabel = document.createTextNode("+");
+ optionButton.appendChild(buttonLabel);
+ optionButton.setAttribute("class", "btn btn-add-remove");
+ optionButton.setAttribute("onclick" , 'addDynamicOptions("'+ labelLevel + attributeName + '");');
+ optionButton.removeAttribute("required");
- if($scope.temp.policy.ruleData != null){
- if (many == true){
- document.getElementById(labelLevel +attributeName).options[0].selected = false;
- for (i=0; i < listemunerateValues.length; i += 1) {
- var testValue = $scope.temp.policy.ruleData[labelLevel +attributeName+'@' + i];
- if (testValue === undefined){
- testValue = $scope.temp.policy.ruleData[labelLevel +attributeName];
- }
- var location = listemunerateValues.indexOf(testValue);
- if (location!=-1){
- document.getElementById(labelLevel +attributeName).options[location].selected = true;
- }
- }
- }else {
- if($scope.temp.policy.ruleData[labelLevel + attributeName] != undefined && $scope.temp.policy.ruleData[labelLevel + attributeName] != "undefined"){
- document.getElementById(labelLevel + attributeName).value = $scope.temp.policy.ruleData[labelLevel + attributeName];
- }
- }
- }
- };
- addDynamicOptions = function(id) {
- var option = document.createElement("option");
- var value = document.getElementById(id+".input").value;
- option.setAttribute('value', value);
- option.appendChild(document.createTextNode(value));
- document.getElementById(id).options.add(option);
- document.getElementById(id+".input").value = "";
- };
+ document.getElementById(divID).appendChild(optionButton);
+ document.getElementById(divID).appendChild(br);
+ }
- function onlyUnique(value, index, self) {
- return self.indexOf(value) === index;
- };
+ if($scope.temp.policy.ruleData != null){
+ if (many == true){
+ document.getElementById(labelLevel +attributeName).options[0].selected = false;
+ for (i=0; i < listemunerateValues.length; i += 1) {
+ var testValue = $scope.temp.policy.ruleData[labelLevel +attributeName+'@' + i];
+ if (testValue === undefined){
+ testValue = $scope.temp.policy.ruleData[labelLevel +attributeName];
+ }
+ var location = listemunerateValues.indexOf(testValue);
+ if (location!=-1){
+ document.getElementById(labelLevel +attributeName).options[location].selected = true;
+ }
+ }
+ }else {
+ if($scope.temp.policy.ruleData[labelLevel + attributeName] != undefined && $scope.temp.policy.ruleData[labelLevel + attributeName] != "undefined"){
+ document.getElementById(labelLevel + attributeName).value = $scope.temp.policy.ruleData[labelLevel + attributeName];
+ }
+ }
+ }
+ };
+ addDynamicOptions = function(id) {
+ var option = document.createElement("option");
+ var value = document.getElementById(id+".input").value;
+ option.setAttribute('value', value);
+ option.appendChild(document.createTextNode(value));
+ document.getElementById(id).options.add(option);
+ document.getElementById(id+".input").value = "";
+ };
- function checkDictionary(value){
- for (i = 0; i < $scope.microServiceAttributeDictionaryDatas.length; i++) {
- if ($scope.microServiceAttributeDictionaryDatas[i].name.localeCompare(value)){
- return true;
- }
- }
+ function onlyUnique(value, index, self) {
+ return self.indexOf(value) === index;
+ }
- }
- $scope.savePolicy = function(policy){
- if(policy.itemContent != undefined){
- $scope.refreshCheck = true;
- $scope.policyNavigator = policy.itemContent;
- policy.itemContent = "";
- }
- $scope.savebutton = false;
- var splitAt = '*';
- var dot ='.';
- var jsonPolicy = {};
- if(plainAttributeKeys != null){
- for(a = 0; a < plainAttributeKeys.length; a++){
- var splitPlainAttributeKey = plainAttributeKeys[a].split(splitAt);
- console.log("splitPlainAttributeKey: " + splitPlainAttributeKey);
- var searchElement = document.getElementById(splitPlainAttributeKey[0]);
- var key = splitPlainAttributeKey[0];
- if(searchElement == null){
- searchElement = document.getElementById(splitPlainAttributeKey[0]+'@0');
- key = splitPlainAttributeKey[0]+'@0';
- }else if (searchElement.nodeName == 'BUTTON'){
- searchElement = document.getElementById(splitPlainAttributeKey[0]+'@0');
- key = splitPlainAttributeKey[0]+'@0';
- }
- if(searchElement != null){
- var keySplit = key.split(dot);
- var elumentLocation = keySplit.length;
- var enumKey = key;
- if (elumentLocation > 1){
- enumKey = keySplit[keySplit.length - 1];
- }
- //check it is undefined or not
- if (enumKeyList != undefined && enumKeyList.indexOf(enumKey) != -1){
- if (splitPlainAttributeKey[1]!= undefined && splitPlainAttributeKey[1].indexOf("true") !== -1){
- var multiSlect = [];
- for ( var i = 0; i < searchElement.selectedOptions.length; i++) {
- multiSlect.push(searchElement.selectedOptions[i].value);
- }
- jsonPolicy[key]= multiSlect;
- }else{
- console.log(" searchElement.value = > " + searchElement.value);
- if(splitPlainAttributeKey[1]!= undefined && splitPlainAttributeKey[1] == "boolean"){
- jsonPolicy[key]= false;
- for(var i=0; i<booleanTrueElements.length; i++){
- if(booleanTrueElements[i] == key){
- jsonPolicy[key]= true;
- }
- }
+ $scope.savePolicy = function(policy){
+ if(policy.itemContent != undefined){
+ $scope.refreshCheck = true;
+ $scope.policyNavigator = policy.itemContent;
+ policy.itemContent = "";
+ }
+ $scope.savebutton = false;
+ var splitAt = '*';
+ var dot ='.';
+ var jsonPolicy = {};
+ if(plainAttributeKeys != null){
+ for(a = 0; a < plainAttributeKeys.length; a++){
+ var splitPlainAttributeKey = plainAttributeKeys[a].split(splitAt);
+ var searchElement = document.getElementById(splitPlainAttributeKey[0]);
+ var key = splitPlainAttributeKey[0];
+ if(searchElement == null){
+ searchElement = document.getElementById(splitPlainAttributeKey[0]+'@0');
+ key = splitPlainAttributeKey[0]+'@0';
+ }else if (searchElement.nodeName == 'BUTTON'){
+ searchElement = document.getElementById(splitPlainAttributeKey[0]+'@0');
+ key = splitPlainAttributeKey[0]+'@0';
+ }
+ if(searchElement != null){
+ var keySplit = key.split(dot);
+ var elumentLocation = keySplit.length;
+ var enumKey = key;
+ if (elumentLocation > 1){
+ enumKey = keySplit[keySplit.length - 1];
+ }
+ // check it is undefined or not
+ if (enumKeyList != undefined && enumKeyList.indexOf(enumKey) != -1){
+ if (splitPlainAttributeKey[1]!= undefined && splitPlainAttributeKey[1].indexOf("true") !== -1){
+ var multiSlect = [];
+ for ( var i = 0; i < searchElement.selectedOptions.length; i++) {
+ multiSlect.push(searchElement.selectedOptions[i].value);
+ }
+ jsonPolicy[key]= multiSlect;
+ }else{
+ if(splitPlainAttributeKey[1]!= undefined && splitPlainAttributeKey[1] == "boolean"){
+ jsonPolicy[key]= false;
+ for(var i=0; i<booleanTrueElements.length; i++){
+ if(booleanTrueElements[i] == key){
+ jsonPolicy[key]= true;
+ }
+ }
- }else{
- jsonPolicy[key]= searchElement.value;
- }
- }
- } else {
- if(searchElement.value != null){
- jsonPolicy[key]= searchElement.value;
- console.log(" searchElement.value = > " + searchElement.value);
- if(splitPlainAttributeKey[1] == "boolean"){
- jsonPolicy[key]= false;
- for(var i=0; i<booleanTrueElements.length; i++){
- if(booleanTrueElements[i] == key){
- jsonPolicy[key]= true;
- }
- }
- }
- }
- }
- }
- }
- }
+ }else{
+ jsonPolicy[key]= searchElement.value;
+ }
+ }
+ } else {
+ if(searchElement.value != null){
+ if(searchElement.parentElement.children[0].checked == true){
+ jsonPolicy[key]= searchElement.checked;
+ }
+ else{
+ jsonPolicy[key]= window.btoa(searchElement.value);
+ }
+ }
+ }
+ }
+ }
+ }
var uuu = "policycreation/save_policy";
var postData={policyData: policy, policyJSON : jsonPolicy};
$.ajax({
@@ -1597,199 +1526,192 @@ angular.module('abs').controller('dcaeMicroServiceController', ['$scope', '$wind
data: JSON.stringify(postData),
success : function(data){
$scope.$apply(function(){
- $scope.data=data.policyData;
- if($scope.data == 'success'){
- $scope.temp.policy.readOnly = 'true';
- $scope.safetyChecker = data.policyData.split("#")[2];
- if ($scope.safetyChecker!=undefined) {
- Notification.success($scope.safetyChecker);
- }
- $scope.pushStatus=data.policyData.split("&")[1];
- if($scope.pushStatus=="successPush"){
- Notification.success("Policy pushed successfully");
- }
- Notification.success("Policy Saved Successfully.");
- }else if ($scope.data == 'PolicyExists'){
- $scope.savebutton = true;
- Notification.error("Policy Already Exists with Same Name in Scope.");
- }
+ $scope.data=data.policyData;
+ if($scope.data == 'success'){
+ $scope.temp.policy.readOnly = 'true';
+ $scope.safetyChecker = data.policyData.split("#")[2];
+ if ($scope.safetyChecker!=undefined) {
+ Notification.success($scope.safetyChecker);
+ }
+ $scope.pushStatus=data.policyData.split("&")[1];
+ if($scope.pushStatus=="successPush"){
+ Notification.success("Policy pushed successfully");
+ }
+ $scope.temp.policy.readOnly = 'true';
+ $scope.savebutton = true;
+ Notification.success("Policy Saved Successfully.");
+ }else if ($scope.data == 'PolicyExists'){
+ $scope.savebutton = true;
+ Notification.error("Policy Already Exists with Same Name in Scope.");
+ }
});
- console.log($scope.data);
},
error : function(data){
- Notification.error("Error Occured while saving Policy.");
+ Notification.error("Error Occured while saving Policy.");
}
});
};
var booleanTrueElements = [];
$scope.validatePolicy = function(policy){
- document.getElementById("validate").innerHTML = "";
- var splitAt = '*';
- var dot ='.';
- var jsonPolicy = {};
- if(plainAttributeKeys != null){
- for(a = 0; a < plainAttributeKeys.length; a++){
- var splitPlainAttributeKey = plainAttributeKeys[a].split(splitAt);
- console.log(splitPlainAttributeKey[1]);
- var searchElement = document.getElementById(splitPlainAttributeKey[0]);
- var key = splitPlainAttributeKey[0];
- if(searchElement == null){
- searchElement = document.getElementById(splitPlainAttributeKey[0]+'@0');
- key = splitPlainAttributeKey[0]+'@0';
- }else if (searchElement.nodeName == 'BUTTON'){
- searchElement = document.getElementById(splitPlainAttributeKey[0]+'@0');
- key = splitPlainAttributeKey[0]+'@0';
- }
- if(searchElement != null){
- if (enumKeyList.indexOf(key) != -1){
- if (splitPlainAttributeKey[1].indexOf("true") !== -1){
- var multiSlect = [];
- for ( var i = 0; i < searchElement.selectedOptions.length; i++) {
- multiSlect.push(searchElement.selectedOptions[i].value);
- }
- jsonPolicy[key]= multiSlect;
- }else{
- jsonPolicy[key]= searchElement.value;
- }
- if(searchElement.getAttribute("required")){
- if(!searchElement.value){
- return;
- }
- }
- } else {
- if(searchElement.value != null){
- jsonPolicy[key]= searchElement.value;
- if(searchElement.getAttribute("required")){
- if(!searchElement.value){
- return;
- }
- }
- }
- }
- }
- }
-
-
- var checkedValue = $('.onoffswitch-checkbox:checked').val();
-
- var x = document.getElementsByClassName("onoffswitch-checkbox");
-
-
- if(checkedValue){
- console.log("checkedValue:" + checkedValue);
- for(var i=0; i<x.length; x++){
- console.log("checkbox id: " + x[i].id);
- booleanTrueElements.push(x[i].id)
- }
- }
- }
+ document.getElementById("validate").innerHTML = "";
+ var splitAt = '*';
+ var jsonPolicy = {};
+ if(plainAttributeKeys != null){
+ for(a = 0; a < plainAttributeKeys.length; a++){
+ var splitPlainAttributeKey = plainAttributeKeys[a].split(splitAt);
+ var searchElement = document.getElementById(splitPlainAttributeKey[0]);
+ var key = splitPlainAttributeKey[0];
+ if(searchElement == null){
+ searchElement = document.getElementById(splitPlainAttributeKey[0]+'@0');
+ key = splitPlainAttributeKey[0]+'@0';
+ }else if (searchElement.nodeName == 'BUTTON'){
+ searchElement = document.getElementById(splitPlainAttributeKey[0]+'@0');
+ key = splitPlainAttributeKey[0]+'@0';
+ }
+ if(searchElement != null){
+ if (enumKeyList.indexOf(key) != -1){
+ if (splitPlainAttributeKey[1].indexOf("true") !== -1){
+ var multiSlect = [];
+ for ( var i = 0; i < searchElement.selectedOptions.length; i++) {
+ multiSlect.push(searchElement.selectedOptions[i].value);
+ }
+ jsonPolicy[key]= multiSlect;
+ }else{
+ jsonPolicy[key]= searchElement.value;
+ }
+ if(searchElement.getAttribute("required")){
+ if(!searchElement.value){
+ return;
+ }
+ }
+ } else {
+ if(searchElement.value != null){
+ if(searchElement.parentElement.children[0].checked == true){
+ jsonPolicy[key]= searchElement.checked;
+ }
+ else{
+ jsonPolicy[key]= searchElement.value;
+ }
+ if(searchElement.getAttribute("required")){
+ if(!searchElement.value){
+ return;
+ }
+ }
+ }
+ }
+ }
+ }
+
+
+ var checkedValue = $('.onoffswitch-checkbox:checked').val();
+
+ var x = document.getElementsByClassName("onoffswitch-checkbox");
+
+
+ if(checkedValue){
+ for(var i=0; i<x.length; x++){
+ booleanTrueElements.push(x[i].id)
+ }
+ }
+ }
var uuu = "policyController/validate_policy.htm";
- console.log("$scope.isCheck:" + $scope.isCheck);
if($scope.isCheck == true){
- if(("configName" in policy) == false){
- Notification.error("Validation Failed: configName is required");
- $scope.savebutton = true;
- return;
- }
- if(("location" in policy) == false){
- Notification.error("Validation Failed: location is required");
- $scope.savebutton = true;
- return;
- }
- if(("uuid" in policy) == false){
- Notification.error("Validation Failed: uuid is required");
- $scope.savebutton = true;
- return;
- }
- if(("policyScope" in policy) == false){
- Notification.error("Validation Failed: policyScope is required");
- $scope.savebutton = true;
- return;
- }
+ if(("configName" in policy) == false){
+ Notification.error("Validation Failed: configName is required");
+ $scope.savebutton = true;
+ return;
+ }
+ if(("location" in policy) == false){
+ Notification.error("Validation Failed: location is required");
+ $scope.savebutton = true;
+ return;
+ }
+ if(("uuid" in policy) == false){
+ Notification.error("Validation Failed: uuid is required");
+ $scope.savebutton = true;
+ return;
+ }
+ if(("policyScope" in policy) == false){
+ Notification.error("Validation Failed: policyScope is required");
+ $scope.savebutton = true;
+ return;
+ }
}
var postData={policyData: policy, policyJSON : jsonPolicy};
- $.ajax({
- type : 'POST',
- url : uuu,
- dataType: 'json',
- contentType: 'application/json',
- data: JSON.stringify(postData),
- success : function(data){
- $scope.$apply(function(){
- $scope.validateData = data.data.replace(/\"/g, "");
- $scope.data=data.data.substring(1,8);
- var size = data.data.length;
- if($scope.data == 'success'){
- Notification.success("Validation Success.");
- $scope.savebutton = false;
- if (size > 18){
- var displayWarning = data.data.substring(19,size - 1);
- document.getElementById("validate").innerHTML = "Safe Policy Warning Message : "+displayWarning;
- document.getElementById("validate").style.color = "white";
- document.getElementById("validate").style.backgroundColor = "skyblue";
- }
- }else{
- Notification.error("Validation Failed.");
- document.getElementById("validate").innerHTML = $scope.validateData;
- document.getElementById("validate").style.color = "white";
- document.getElementById("validate").style.backgroundColor = "red";
- $scope.savebutton = true;
- }
-
- });
- console.log($scope.data);
- },
- error : function(data){
- Notification.error("Validation Failed.");
- $scope.savebutton = true;
- }
- });
+ $.ajax({
+ type : 'POST',
+ url : uuu,
+ dataType: 'json',
+ contentType: 'application/json',
+ data: JSON.stringify(postData),
+ success : function(data){
+ $scope.$apply(function(){
+ $scope.validateData = data.data.replace(/\"/g, "");
+ $scope.data=data.data.substring(1,8);
+ var size = data.data.length;
+ if($scope.data == 'success'){
+ Notification.success("Validation Success.");
+ $scope.savebutton = false;
+ if (size > 18){
+ var displayWarning = data.data.substring(19,size - 1);
+ document.getElementById("validate").innerHTML = "Safe Policy Warning Message : "+displayWarning;
+ document.getElementById("validate").style.color = "white";
+ document.getElementById("validate").style.backgroundColor = "skyblue";
+ }
+ }else{
+ Notification.error("Validation Failed.");
+ document.getElementById("validate").innerHTML = $scope.validateData;
+ document.getElementById("validate").style.color = "white";
+ document.getElementById("validate").style.backgroundColor = "red";
+ $scope.savebutton = true;
+ }
+
+ });
+ },
+ error : function(data){
+ Notification.error("Validation Failed.");
+ $scope.savebutton = true;
+ }
+ });
};
- function extend(obj, src) {
- for (var key in src) {
- if (src.hasOwnProperty(key)) obj[key] = src[key];
+ // Switch Click
+ $('.Switch').click(function() {
+ // Check If Enabled (Has 'On' Class)
+ if ($(this).hasClass('On')){
+ // Try To Find Checkbox Within Parent Div, And Check It
+ $(this).parent().find('input:checkbox').attr('checked', true);
+ // Change Button Style - Remove On Class, Add Off Class
+ $(this).removeClass('On').addClass('Off');
+ } else { // If Button Is Disabled (Has 'Off' Class)
+ // Try To Find Checkbox Within Parent Div, And Uncheck It
+ $(this).parent().find('input:checkbox').attr('checked', false);
+ // Change Button Style - Remove Off Class, Add On Class
+ $(this).removeClass('Off').addClass('On');
+ }
+ });
+ // Loops Through Each Toggle Switch On Page
+ $('.Switch').each(function() {
+ // Search of a checkbox within the parent
+ if ($(this).parent().find('input:checkbox').length){
+
+ // If checkbox doesnt have the show class then hide it
+ if (!$(this).parent().find('input:checkbox').hasClass("show")){
+ $(this).parent().find('input:checkbox').hide(); }
+
+ // Look at the checkbox's checkked state
+ if ($(this).parent().find('input:checkbox').is(':checked')){
+ // Checkbox is not checked, Remove the On Class and Add the Off Class
+ $(this).removeClass('On').addClass('Off');
+ } else {
+ // Checkbox Is Checked Remove Off Class, and Add the On Class
+ $(this).removeClass('Off').addClass('On');
}
- return obj;
}
-
- // Switch Click
- $('.Switch').click(function() {
- // Check If Enabled (Has 'On' Class)
- if ($(this).hasClass('On')){
- // Try To Find Checkbox Within Parent Div, And Check It
- $(this).parent().find('input:checkbox').attr('checked', true);
- // Change Button Style - Remove On Class, Add Off Class
- $(this).removeClass('On').addClass('Off');
- } else { // If Button Is Disabled (Has 'Off' Class)
- // Try To Find Checkbox Within Parent Div, And Uncheck It
- $(this).parent().find('input:checkbox').attr('checked', false);
- // Change Button Style - Remove Off Class, Add On Class
- $(this).removeClass('Off').addClass('On');
- }
- });
- // Loops Through Each Toggle Switch On Page
- $('.Switch').each(function() {
- // Search of a checkbox within the parent
- if ($(this).parent().find('input:checkbox').length){
-
- // If checkbox doesnt have the show class then hide it
- if (!$(this).parent().find('input:checkbox').hasClass("show")){
- $(this).parent().find('input:checkbox').hide(); }
-
- // Look at the checkbox's checkked state
- if ($(this).parent().find('input:checkbox').is(':checked')){
- // Checkbox is not checked, Remove the On Class and Add the Off Class
- $(this).removeClass('On').addClass('Off');
- } else {
- // Checkbox Is Checked Remove Off Class, and Add the On Class
- $(this).removeClass('Off').addClass('On');
- }
- }
- });
+ });
}]);
diff --git a/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/PolicyTemplateController/DecisionPolicyController.js b/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/PolicyTemplateController/DecisionPolicyController.js
index 0e53ce9de..4d63dbe3f 100644
--- a/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/PolicyTemplateController/DecisionPolicyController.js
+++ b/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/PolicyTemplateController/DecisionPolicyController.js
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP Policy Engine
* ================================================================================
- * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -17,447 +17,411 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-angular.module('abs').controller('decisionPolicyController', [ '$scope', 'PolicyAppService', 'policyNavigator', 'modalService', '$modal', 'Notification', '$http', function($scope, PolicyAppService, PolicyNavigator, modalService, $modal, Notification, $http) {
- $("#dialog").hide();
-
- $scope.policyNavigator;
- $scope.savebutton = true;
- $scope.refreshCheck = false;
- $scope.disableOnCreate = false;
- $scope.notRawPolicy = true;
-
- if (!$scope.temp.policy.editPolicy && !$scope.temp.policy.readOnly) {
- $scope.disableOnCreate = true;
- $scope.temp.policy = {
- policyType : "Decision"
- }
- }
- ;
-
- $scope.refresh = function() {
- if ($scope.refreshCheck) {
- $scope.policyNavigator.refresh();
- }
- $scope.modal('createNewPolicy', true);
- $scope.temp.policy = "";
- };
-
- $scope.modal = function(id, hide) {
- return $('#' + id).modal(hide ? 'hide' : 'show');
- };
-
- if ($scope.temp.policy.ruleProvider == undefined) {
- $scope.temp.policy.ruleProvider = "Custom";
- }
-
- if ($scope.temp.policy.blackListEntryType == undefined) {
- $scope.temp.policy.blackListEntryType = "Use Manual Entry";
- }
-
- PolicyAppService.getData('getDictionary/get_OnapNameDataByName').then(function(data) {
- var j = data;
- $scope.data = JSON.parse(j.data);
- console.log($scope.data);
- $scope.onapNameDictionaryDatas = JSON.parse($scope.data.onapNameDictionaryDatas);
- console.log($scope.onapNameDictionaryDatas);
- }, function(error) {
- console.log("failed");
- });
-
- PolicyAppService.getData('getDictionary/get_SettingsDictionaryDataByName').then(function(data) {
- var j = data;
- $scope.data = JSON.parse(j.data);
- console.log($scope.data);
- $scope.settingsDictionaryDatas = JSON.parse($scope.data.settingsDictionaryDatas);
- console.log($scope.settingsDictionaryDatas);
- }, function(error) {
- console.log("failed");
- });
-
- PolicyAppService.getData('get_FunctionDefinitionDataByName').then(function(data) {
- var j = data;
- $scope.data = JSON.parse(j.data);
- console.log($scope.data);
- $scope.functionDefinitionDatas = JSON.parse($scope.data.functionDefinitionDatas);
- console.log($scope.functionDefinitionDatas);
- }, function(error) {
- console.log("failed");
- });
-
- PolicyAppService.getData('getDictionary/get_AttributeDatabyAttributeName').then(function(data) {
- var j = data;
- $scope.data = JSON.parse(j.data);
- console.log($scope.data);
- $scope.attributeDictionaryDatas = JSON.parse($scope.data.attributeDictionaryDatas);
- console.log($scope.attributeDictionaryDatas);
- }, function(error) {
- console.log("failed");
- });
-
- PolicyAppService.getData('getDictionary/get_RainyDayDictionaryDataByName').then(function(data) {
- var j = data;
- $scope.data = JSON.parse(j.data);
- console.log($scope.data);
- $scope.rainyDayDictionaryDatas = JSON.parse($scope.data.rainyDayDictionaryDatas);
- console.log($scope.rainyDayDictionaryDatas);
- }, function(error) {
- console.log("failed");
- });
-
- PolicyAppService.getData('getDictionary/get_RainyDayDictionaryData').then(function(data) {
- var j = data;
- $scope.data = JSON.parse(j.data);
- console.log($scope.data);
- $scope.rainyDayDictionaryDataEntity = JSON.parse($scope.data.rainyDayDictionaryDatas);
- console.log($scope.rainyDayDictionaryDatasEntity);
- }, function(error) {
- console.log("failed");
- });
-
- function extend(obj, src) {
- for (var key in src) {
- if (src.hasOwnProperty(key))
- obj[key] = src[key];
- }
- return obj;
- }
-
- $scope.saveDecisionPolicy = function(policy) {
- if (policy.itemContent != undefined) {
- $scope.refreshCheck = true;
- $scope.policyNavigator = policy.itemContent;
- policy.itemContent = "";
- }
- $scope.savebutton = false;
- console.log(policy);
- var uuu = "policycreation/save_policy";
- var postData = {
- policyData : policy
- };
- $.ajax({
- type : 'POST',
- url : uuu,
- dataType : 'json',
- contentType : 'application/json',
- data : JSON.stringify(postData),
- success : function(data) {
- $scope.$apply(function() {
- $scope.data = data.policyData;
- if ($scope.data == 'success') {
- $scope.temp.policy.readOnly = 'true';
- Notification.success("Policy Saved Successfully.");
- } else if ($scope.data == 'PolicyExists') {
- $scope.savebutton = true;
- Notification.error("Policy Already Exists with Same Name in Scope.");
- }
- });
- console.log($scope.data);
-
- },
- error : function(data) {
- Notification.error("Error Occured while saving Policy.");
- }
- });
- };
-
- $scope.validatePolicy = function(policy) {
- console.log(policy);
- document.getElementById("validate").innerHTML = "";
- var uuu = "policyController/validate_policy.htm";
- var postData = {
- policyData : policy
- };
- $.ajax({
- type : 'POST',
- url : uuu,
- dataType : 'json',
- contentType : 'application/json',
- data : JSON.stringify(postData),
- success : function(data) {
- $scope.$apply(function() {
- $scope.validateData = data.data.replace(/\"/g, "");
- $scope.data = data.data;
- if ($scope.data == '"success"') {
- Notification.success("Validation Success.");
- $scope.savebutton = false;
- } else {
- Notification.error("Validation Failed.");
- document.getElementById("validate").innerHTML = $scope.validateData;
- document.getElementById("validate").style.color = "white";
- document.getElementById("validate").style.backgroundColor = "red";
- $scope.savebutton = true;
- }
-
- });
- console.log($scope.data);
- },
- error : function(data) {
- Notification.error("Validation Failed.");
- $scope.savebutton = true;
- }
- });
- };
-
- if (!$scope.temp.policy.editPolicy && !$scope.temp.policy.readOnly) {
- $scope.temp.policy.attributes = [];
- $scope.temp.policy.settings = [];
- $scope.temp.policy.ruleAlgorithmschoices = [];
- if (!$scope.temp.policy.yamlparams) {
- $scope.temp.policy.yamlparams = {};
- }
- if (!$scope.temp.policy.yamlparams.targets) {
- $scope.temp.policy.yamlparams.targets = [];
- }
- if (!$scope.temp.policy.yamlparams.blackList) {
- $scope.temp.policy.yamlparams.blackList = [];
- }
- if (!$scope.temp.policy.rainyday) {
- $scope.temp.policy.rainyday = {};
- }
- if (!$scope.temp.policy.rainyday.treatmentTableChoices) {
- $scope.temp.policy.rainyday.treatmentTableChoices = [];
- }
-
- } else if ($scope.temp.policy.ruleProvider == "Custom") {
- if ($scope.temp.policy.attributes.length == 0) {
- $scope.temp.policy.attributes = [];
- }
- if ($scope.temp.policy.settings.length == 0) {
- $scope.temp.policy.settings = [];
- }
- if ($scope.temp.policy.ruleAlgorithmschoices == null || $scope.temp.policy.ruleAlgorithmschoices.length == 0) {
- $scope.temp.policy.ruleAlgorithmschoices = [];
- }
- } else if ($scope.temp.policy.ruleProvider == "GUARD_BL_YAML") {
- if ($scope.temp.policy.yamlparams.blackList == null || $scope.temp.policy.yamlparams.blackList.length == 0) {
- $scope.temp.policy.yamlparams.blackList = [];
- }
- if ($scope.temp.policy.blackListEntries == null || $scope.temp.policy.blackListEntries.length == 0) {
- $scope.temp.policy.blackListEntries = [];
- }
- $scope.blackListEntries = [];
- $scope.temp.policy.appendBlackListEntries = [];
- $scope.blackListEntries = arrayUnique($scope.temp.policy.blackListEntries.concat($scope.temp.policy.yamlparams.blackList));
-
+angular.module('abs').controller('decisionPolicyController',
+ [ '$scope', 'PolicyAppService', 'policyNavigator', 'modalService', '$modal', 'Notification', '$http',
+ function($scope, PolicyAppService, PolicyNavigator, modalService, $modal, Notification, $http) {
+ $("#dialog").hide();
+
+ $scope.policyNavigator;
+ $scope.savebutton = true;
+ $scope.refreshCheck = false;
+ $scope.disableOnCreate = false;
+ $scope.notRawPolicy = true;
+
+ if (!$scope.temp.policy.editPolicy && !$scope.temp.policy.readOnly) {
+ $scope.disableOnCreate = true;
+ $scope.temp.policy = {
+ policyType : "Decision"
+ }
+ }
+
+ $scope.refresh = function() {
+ if ($scope.refreshCheck) {
+ $scope.policyNavigator.refresh();
+ }
+ $scope.modal('createNewPolicy', true);
+ $scope.temp.policy = "";
+ };
+
+ $scope.modal = function(id, hide) {
+ return $('#' + id).modal(hide ? 'hide' : 'show');
+ };
+
+ if ($scope.temp.policy.ruleProvider == undefined) {
+ $scope.temp.policy.ruleProvider = "Custom";
+ }
+
+ if ($scope.temp.policy.blackListEntryType == undefined) {
+ $scope.temp.policy.blackListEntryType = "Use Manual Entry";
+ }
+
+ PolicyAppService.getData('getDictionary/get_OnapNameDataByName').then(function(data) {
+ var j = data;
+ $scope.data = JSON.parse(j.data);
+ $scope.onapNameDictionaryDatas = JSON.parse($scope.data.onapNameDictionaryDatas);
+ });
+
+ PolicyAppService.getData('getDictionary/get_SettingsDictionaryDataByName').then(function(data) {
+ var j = data;
+ $scope.data = JSON.parse(j.data);
+ $scope.settingsDictionaryDatas = JSON.parse($scope.data.settingsDictionaryDatas);
+ });
+
+ PolicyAppService.getData('get_FunctionDefinitionDataByName').then(function(data) {
+ var j = data;
+ $scope.data = JSON.parse(j.data);
+ $scope.functionDefinitionDatas = JSON.parse($scope.data.functionDefinitionDatas);
+ });
+
+ PolicyAppService.getData('getDictionary/get_AttributeDatabyAttributeName').then(function(data) {
+ var j = data;
+ $scope.data = JSON.parse(j.data);
+ $scope.attributeDictionaryDatas = JSON.parse($scope.data.attributeDictionaryDatas);
+ });
+
+ PolicyAppService.getData('getDictionary/get_RainyDayDictionaryDataByName').then(function(data) {
+ var j = data;
+ $scope.data = JSON.parse(j.data);
+ $scope.rainyDayDictionaryDatas = JSON.parse($scope.data.rainyDayDictionaryDatas);
+ });
+
+ PolicyAppService.getData('getDictionary/get_RainyDayDictionaryData').then(function(data) {
+ var j = data;
+ $scope.data = JSON.parse(j.data);
+ $scope.rainyDayDictionaryDataEntity = JSON.parse($scope.data.rainyDayDictionaryDatas);
+ });
+
+ $scope.saveDecisionPolicy = function(policy) {
+ if (policy.itemContent != undefined) {
+ $scope.refreshCheck = true;
+ $scope.policyNavigator = policy.itemContent;
+ policy.itemContent = "";
+ }
+ $scope.savebutton = false;
+ var uuu = "policycreation/save_policy";
+ var postData = {
+ policyData : policy
+ };
+ $.ajax({
+ type : 'POST',
+ url : uuu,
+ dataType : 'json',
+ contentType : 'application/json',
+ data : JSON.stringify(postData),
+ success : function(data) {
+ $scope.$apply(function() {
+ $scope.data = data.policyData;
+ if ($scope.data == 'success') {
+ $scope.temp.policy.readOnly = 'true';
+ Notification.success("Policy Saved Successfully.");
+ } else if ($scope.data == 'PolicyExists') {
+ $scope.savebutton = true;
+ Notification.error("Policy Already Exists with Same Name in Scope.");
+ }
+ });
+
+ },
+ error : function(data) {
+ Notification.error("Error Occured while saving Policy.");
+ }
+ });
+ };
+
+ $scope.validatePolicy = function(policy) {
+ document.getElementById("validate").innerHTML = "";
+ var uuu = "policyController/validate_policy.htm";
+ var postData = {
+ policyData : policy
+ };
+ $.ajax({
+ type : 'POST',
+ url : uuu,
+ dataType : 'json',
+ contentType : 'application/json',
+ data : JSON.stringify(postData),
+ success : function(data) {
+ $scope.$apply(function() {
+ $scope.validateData = data.data.replace(/\"/g, "");
+ $scope.data = data.data;
+ if ($scope.data == '"success"') {
+ Notification.success("Validation Success.");
+ $scope.savebutton = false;
+ } else {
+ Notification.error("Validation Failed.");
+ document.getElementById("validate").innerHTML = $scope.validateData;
+ document.getElementById("validate").style.color = "white";
+ document.getElementById("validate").style.backgroundColor = "red";
+ $scope.savebutton = true;
+ }
+
+ });
+ },
+ error : function(data) {
+ Notification.error("Validation Failed.");
+ $scope.savebutton = true;
+ }
+ });
+ };
+
+ if (!$scope.temp.policy.editPolicy && !$scope.temp.policy.readOnly) {
+ $scope.temp.policy.attributes = [];
+ $scope.temp.policy.settings = [];
+ $scope.temp.policy.ruleAlgorithmschoices = [];
+ if (!$scope.temp.policy.yamlparams) {
+ $scope.temp.policy.yamlparams = {};
+ }
+ if (!$scope.temp.policy.yamlparams.targets) {
+ $scope.temp.policy.yamlparams.targets = [];
+ }
+ if (!$scope.temp.policy.yamlparams.blackList) {
+ $scope.temp.policy.yamlparams.blackList = [];
+ }
+ if (!$scope.temp.policy.rainyday) {
+ $scope.temp.policy.rainyday = {};
+ }
+ if (!$scope.temp.policy.rainyday.treatmentTableChoices) {
+ $scope.temp.policy.rainyday.treatmentTableChoices = [];
+ }
+
+ } else if ($scope.temp.policy.ruleProvider == "Custom") {
+ if ($scope.temp.policy.attributes.length == 0) {
+ $scope.temp.policy.attributes = [];
+ }
+ if ($scope.temp.policy.settings.length == 0) {
+ $scope.temp.policy.settings = [];
+ }
+ if ($scope.temp.policy.ruleAlgorithmschoices == null || $scope.temp.policy.ruleAlgorithmschoices.length == 0) {
+ $scope.temp.policy.ruleAlgorithmschoices = [];
+ }
+ } else if ($scope.temp.policy.ruleProvider == "GUARD_BL_YAML") {
+ if ($scope.temp.policy.yamlparams.blackList == null || $scope.temp.policy.yamlparams.blackList.length == 0) {
+ $scope.temp.policy.yamlparams.blackList = [];
+ }
+ if ($scope.temp.policy.blackListEntries == null || $scope.temp.policy.blackListEntries.length == 0) {
+ $scope.temp.policy.blackListEntries = [];
+ }
+ $scope.blackListEntries = [];
+ $scope.temp.policy.appendBlackListEntries = [];
+ $scope.blackListEntries = arrayUnique($scope.temp.policy.blackListEntries.concat($scope.temp.policy.yamlparams.blackList));
+
}else if($scope.temp.policy.ruleProvider=="GUARD_YAML" || $scope.temp.policy.ruleProvider=="GUARD_MIN_MAX"){
- if($scope.temp.policy.yamlparams.targets.length==0){
- $scope.temp.policy.yamlparams.targets = [];
- }
- } else if ($scope.temp.policy.ruleProvider == "Rainy_Day") {
- if ($scope.temp.policy.rainyday.treatmentTableChoices == null || $scope.temp.policy.rainyday.treatmentTableChoices.length == 0) {
- $scope.temp.policy.rainyday.treatmentTableChoices = [];
- }
- }
- $scope.attributeDatas = [ {
- "attributes" : $scope.temp.policy.attributes
- } ];
- $scope.addNewChoice = function() {
- var newItemNo = $scope.temp.policy.attributes.length + 1;
- $scope.temp.policy.attributes.push({
- 'id' : 'choice' + newItemNo
- });
- };
- $scope.removeChoice = function() {
- var lastItem = $scope.temp.policy.attributes.length - 1;
- $scope.temp.policy.attributes.splice(lastItem);
- };
-
- $scope.settingsDatas = [ {
- "settings" : $scope.temp.policy.settings
- } ];
- $scope.addNewSettingsChoice = function() {
- var newItemNo = $scope.temp.policy.settings.length + 1;
- $scope.temp.policy.settings.push({
- 'id' : 'choice' + newItemNo
- });
- };
- $scope.removeSettingsChoice = function() {
- var lastItem = $scope.temp.policy.settings.length - 1;
- $scope.temp.policy.settings.splice(lastItem);
- };
-
- $scope.addNewTarget = function() {
- $scope.temp.policy.yamlparams.targets.push('');
- };
- $scope.removeTarget = function() {
- var lastItem = $scope.temp.policy.yamlparams.targets.length - 1;
- $scope.temp.policy.yamlparams.targets.splice(lastItem);
- };
-
- $scope.addNewBL = function() {
- $scope.temp.policy.yamlparams.blackList.push('');
- };
+ if($scope.temp.policy.yamlparams.targets.length==0){
+ $scope.temp.policy.yamlparams.targets = [];
+ }
+ } else if ($scope.temp.policy.ruleProvider == "Rainy_Day") {
+ if ($scope.temp.policy.rainyday.treatmentTableChoices == null || $scope.temp.policy.rainyday.treatmentTableChoices.length == 0) {
+ $scope.temp.policy.rainyday.treatmentTableChoices = [];
+ }
+ }
+ $scope.attributeDatas = [ {
+ "attributes" : $scope.temp.policy.attributes
+ } ];
+ $scope.addNewChoice = function() {
+ var newItemNo = $scope.temp.policy.attributes.length + 1;
+ $scope.temp.policy.attributes.push({
+ 'id' : 'choice' + newItemNo
+ });
+ };
+ $scope.removeChoice = function() {
+ var lastItem = $scope.temp.policy.attributes.length - 1;
+ $scope.temp.policy.attributes.splice(lastItem);
+ };
+
+ $scope.settingsDatas = [ {
+ "settings" : $scope.temp.policy.settings
+ } ];
+ $scope.addNewSettingsChoice = function() {
+ var newItemNo = $scope.temp.policy.settings.length + 1;
+ $scope.temp.policy.settings.push({
+ 'id' : 'choice' + newItemNo
+ });
+ };
+ $scope.removeSettingsChoice = function() {
+ var lastItem = $scope.temp.policy.settings.length - 1;
+ $scope.temp.policy.settings.splice(lastItem);
+ };
+
+ $scope.addNewTarget = function() {
+ $scope.temp.policy.yamlparams.targets.push('');
+ };
+ $scope.removeTarget = function() {
+ var lastItem = $scope.temp.policy.yamlparams.targets.length - 1;
+ $scope.temp.policy.yamlparams.targets.splice(lastItem);
+ };
+
+ $scope.addNewBL = function() {
+ $scope.temp.policy.yamlparams.blackList.push('');
+ };
$scope.removeBL = function(id) {
- $scope.temp.policy.yamlparams.blackList = $scope.temp.policy.yamlparams.blackList.filter(function (obj){
- return obj !== id;
- });
- };
-
- $scope.treatmentDatas = [ {
- "treatmentValues" : $scope.temp.policy.rainyday.treatmentTableChoices
- } ];
-
- $scope.addNewTreatment = function() {
- $scope.temp.policy.rainyday.treatmentTableChoices.push({});
- };
-
- $scope.removeTreatment = function() {
- var lastItem = $scope.temp.policy.rainyday.treatmentTableChoices.length - 1;
- $scope.temp.policy.rainyday.treatmentTableChoices.splice(lastItem);
- };
-
- $scope.workstepDictionaryDatas = [];
- $scope.getWorkstepValues = function(bbidValue) {
- for (var i = 0; i < $scope.rainyDayDictionaryDataEntity.length; ++i) {
- var obj = $scope.rainyDayDictionaryDataEntity[i];
- if (obj.bbid == bbidValue) {
- $scope.workstepDictionaryDatas.push(obj.workstep);
- }
- }
- };
-
- $scope.allowedTreatmentsDatas = [];
- $scope.getTreatmentValues = function(bbidValue, workstepValue) {
- for (var i = 0; i < $scope.rainyDayDictionaryDataEntity.length; ++i) {
- var obj = $scope.rainyDayDictionaryDataEntity[i];
- if (obj.bbid == bbidValue && obj.workstep == workstepValue) {
- var splitAlarm = obj.treatments.split(',');
- for (var j = 0; j < splitAlarm.length; ++j) {
- $scope.allowedTreatmentsDatas.push(splitAlarm[j]);
- }
- }
- }
- };
-
- $scope.ItemNo = 0;
- $scope.ruleAlgorithmDatas = [ {
- "ruleAlgorithms" : $scope.temp.policy.ruleAlgorithmschoices
- } ];
-
- $scope.addNewRuleAlgorithm = function() {
- if ($scope.temp.policy.ruleAlgorithmschoices != null) {
- var newItemNo = $scope.temp.policy.ruleAlgorithmschoices.length + 1;
- } else {
- var newItemNo = 1;
- }
- if (newItemNo > 1) {
- var value = newItemNo - 1;
- $scope.attributeDictionaryDatas.push('A' + value);
- }
- $scope.temp.policy.ruleAlgorithmschoices.push({
- 'id' : 'A' + newItemNo
- });
- };
-
- $scope.removeRuleAlgorithm = function() {
- var lastItem = $scope.temp.policy.ruleAlgorithmschoices.length - 1;
- $scope.temp.policy.ruleAlgorithmschoices.splice(lastItem);
- };
-
- $scope.providerListener = function(ruleProvider) {
- if (ruleProvider != "Custom") {
- $scope.temp.policy.ruleAlgorithmschoices = [];
- $scope.temp.policy.settings = [];
- $scope.temp.policy.attributes = [];
- }
- if (ruleProvider === "Raw") {
- $scope.notRawPolicy = false;
- }
- };
-
- $scope.importButton = true;
- var fd;
- $scope.uploadBLFile = function(files) {
- fd = new FormData();
- fd.append("file", files[0]);
- var fileExtension = files[0].name.split(".")[1];
- if (fileExtension == "xls") {
- $scope.importButton = false;
- $scope.$apply();
- } else {
- Notification.error("Upload the BlackList file which extends with .xls format.");
- }
- };
-
- function arrayUnique(array) {
- var a = array.concat();
- for (var i = 0; i < a.length; ++i) {
- for (var j = i + 1; j < a.length; ++j) {
- if (a[i] === a[j])
- a.splice(j--, 1);
- }
- }
- return a;
- }
-
- $scope.submitUpload = function() {
- $http.post("policycreation/importBlackListForDecisionPolicy", fd, {
- withCredentials : false,
- headers : {
- 'Content-Type' : undefined
- },
- transformRequest : angular.identity
- }).success(function(data) {
- $scope.data = JSON.parse(data.data);
- $scope.temp.policy.blackListEntries = $scope.data.blackListEntries;
- if ($scope.temp.policy.blackListEntries[0] !== "error") {
- $scope.blackListEntries = arrayUnique($scope.temp.policy.blackListEntries.concat($scope.temp.policy.yamlparams.blackList));
- $scope.temp.policy.appendBlackListEntries = $scope.data.appendBlackListEntries;
- $scope.blackListEntries = $scope.blackListEntries.filter(function(obj) {
- return !$scope.temp.policy.appendBlackListEntries.includes(obj);
- });
- if ($scope.blackListEntries.length == 0) {
- $scope.validateButton = true;
- Notification.error("Black Lists are empty. Minimum one entry required.");
- } else {
- $scope.temp.policy.blackListEntries = $scope.blackListEntries;
- Notification.success("Blacklist File Uploaded Successfully.");
- $scope.validateButton = false;
- $scope.importButton = true;
- }
- } else {
- Notification.error("Blacklist File Upload Failed." + $scope.temp.policy.blackListEntries[1]);
- }
- }).error(function(data) {
- Notification.error("Blacklist File Upload Failed.");
- });
- };
-
- $scope.initializeBlackList = function() {
- if ($scope.temp.policy.blackListEntryType === "Use File Upload") {
- $scope.validateButton = true;
- } else {
- $scope.validateButton = false;
- }
- $("#importFile").val('');
- };
-
- $scope.exportBlackListEntries = function() {
- var uuu = "policycreation/exportDecisionBlackListEntries";
- var postData = {
- policyData : $scope.temp.policy,
- date : $scope.temp.model.modifiedDate,
- version : $scope.temp.model.version
- };
- $.ajax({
- type : 'POST',
- url : uuu,
- dataType : 'json',
- contentType : 'application/json',
- data : JSON.stringify(postData),
- success : function(data) {
- $scope.$apply(function() {
- $scope.data = data.data;
- var url = '../' + $scope.data;
- window.location = url;
- Notification.success("BlackList Entries Exported Successfully.");
- });
- console.log($scope.data);
- },
- error : function(data) {
- Notification.error("Error Occured while Exporting BlackList Entries.");
- }
- });
- };
-} ]); \ No newline at end of file
+ $scope.temp.policy.yamlparams.blackList = $scope.temp.policy.yamlparams.blackList.filter(function (obj){
+ return obj !== id;
+ });
+ };
+
+ $scope.treatmentDatas = [ {
+ "treatmentValues" : $scope.temp.policy.rainyday.treatmentTableChoices
+ } ];
+
+ $scope.addNewTreatment = function() {
+ $scope.temp.policy.rainyday.treatmentTableChoices.push({});
+ };
+
+ $scope.removeTreatment = function() {
+ var lastItem = $scope.temp.policy.rainyday.treatmentTableChoices.length - 1;
+ $scope.temp.policy.rainyday.treatmentTableChoices.splice(lastItem);
+ };
+
+ $scope.workstepDictionaryDatas = [];
+ $scope.getWorkstepValues = function(bbidValue) {
+ for (var i = 0; i < $scope.rainyDayDictionaryDataEntity.length; ++i) {
+ var obj = $scope.rainyDayDictionaryDataEntity[i];
+ if (obj.bbid == bbidValue) {
+ $scope.workstepDictionaryDatas.push(obj.workstep);
+ }
+ }
+ };
+
+ $scope.allowedTreatmentsDatas = [];
+ $scope.getTreatmentValues = function(bbidValue, workstepValue) {
+ for (var i = 0; i < $scope.rainyDayDictionaryDataEntity.length; ++i) {
+ var obj = $scope.rainyDayDictionaryDataEntity[i];
+ if (obj.bbid == bbidValue && obj.workstep == workstepValue) {
+ var splitAlarm = obj.treatments.split(',');
+ for (var j = 0; j < splitAlarm.length; ++j) {
+ $scope.allowedTreatmentsDatas.push(splitAlarm[j]);
+ }
+ }
+ }
+ };
+
+ $scope.ItemNo = 0;
+ $scope.ruleAlgorithmDatas = [ {
+ "ruleAlgorithms" : $scope.temp.policy.ruleAlgorithmschoices
+ } ];
+
+ $scope.addNewRuleAlgorithm = function() {
+ if ($scope.temp.policy.ruleAlgorithmschoices != null) {
+ var newItemNo = $scope.temp.policy.ruleAlgorithmschoices.length + 1;
+ } else {
+ var newItemNo = 1;
+ }
+ if (newItemNo > 1) {
+ var value = newItemNo - 1;
+ $scope.attributeDictionaryDatas.push('A' + value);
+ }
+ $scope.temp.policy.ruleAlgorithmschoices.push({
+ 'id' : 'A' + newItemNo
+ });
+ };
+
+ $scope.removeRuleAlgorithm = function() {
+ var lastItem = $scope.temp.policy.ruleAlgorithmschoices.length - 1;
+ $scope.temp.policy.ruleAlgorithmschoices.splice(lastItem);
+ };
+
+ $scope.providerListener = function(ruleProvider) {
+ if (ruleProvider != "Custom") {
+ $scope.temp.policy.ruleAlgorithmschoices = [];
+ $scope.temp.policy.settings = [];
+ $scope.temp.policy.attributes = [];
+ }
+ if (ruleProvider === "Raw") {
+ $scope.notRawPolicy = false;
+ }
+ };
+
+ $scope.importButton = true;
+ var fd;
+ $scope.uploadBLFile = function(files) {
+ fd = new FormData();
+ fd.append("file", files[0]);
+ var fileExtension = files[0].name.split(".")[1];
+ if (fileExtension == "xls") {
+ $scope.importButton = false;
+ $scope.$apply();
+ } else {
+ Notification.error("Upload the BlackList file which extends with .xls format.");
+ }
+ };
+
+ function arrayUnique(array) {
+ var a = array.concat();
+ for (var i = 0; i < a.length; ++i) {
+ for (var j = i + 1; j < a.length; ++j) {
+ if (a[i] === a[j])
+ a.splice(j--, 1);
+ }
+ }
+ return a;
+ }
+
+ $scope.submitUpload = function() {
+ $http.post("policycreation/importBlackListForDecisionPolicy", fd, {
+ withCredentials : false,
+ headers : {
+ 'Content-Type' : undefined
+ },
+ transformRequest : angular.identity
+ }).success(function(data) {
+ $scope.data = JSON.parse(data.data);
+ $scope.temp.policy.blackListEntries = $scope.data.blackListEntries;
+ if ($scope.temp.policy.blackListEntries[0] !== "error") {
+ $scope.blackListEntries = arrayUnique($scope.temp.policy.blackListEntries.concat($scope.temp.policy.yamlparams.blackList));
+ $scope.temp.policy.appendBlackListEntries = $scope.data.appendBlackListEntries;
+ $scope.blackListEntries = $scope.blackListEntries.filter(function(obj) {
+ return !$scope.temp.policy.appendBlackListEntries.includes(obj);
+ });
+ if ($scope.blackListEntries.length == 0) {
+ $scope.validateButton = true;
+ Notification.error("Black Lists are empty. Minimum one entry required.");
+ } else {
+ $scope.temp.policy.blackListEntries = $scope.blackListEntries;
+ Notification.success("Blacklist File Uploaded Successfully.");
+ $scope.validateButton = false;
+ $scope.importButton = true;
+ }
+ } else {
+ Notification.error("Blacklist File Upload Failed." + $scope.temp.policy.blackListEntries[1]);
+ }
+ }).error(function(data) {
+ Notification.error("Blacklist File Upload Failed.");
+ });
+ };
+
+ $scope.initializeBlackList = function() {
+ if ($scope.temp.policy.blackListEntryType === "Use File Upload") {
+ $scope.validateButton = true;
+ } else {
+ $scope.validateButton = false;
+ }
+ $("#importFile").val('');
+ };
+
+ $scope.exportBlackListEntries = function() {
+ var uuu = "policycreation/exportDecisionBlackListEntries";
+ var postData = {
+ policyData : $scope.temp.policy,
+ date : $scope.temp.model.modifiedDate,
+ version : $scope.temp.model.version
+ };
+ $.ajax({
+ type : 'POST',
+ url : uuu,
+ dataType : 'json',
+ contentType : 'application/json',
+ data : JSON.stringify(postData),
+ success : function(data) {
+ $scope.$apply(function() {
+ $scope.data = data.data;
+ var url = '../' + $scope.data;
+ window.location = url;
+ Notification.success("BlackList Entries Exported Successfully.");
+ });
+ },
+ error : function(data) {
+ Notification.error("Error Occured while Exporting BlackList Entries.");
+ }
+ });
+ };
+} ]);
diff --git a/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/PolicyTemplateController/FirewallPolicyController.js b/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/PolicyTemplateController/FirewallPolicyController.js
index 1051ecd9a..b62f91d0d 100644
--- a/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/PolicyTemplateController/FirewallPolicyController.js
+++ b/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/PolicyTemplateController/FirewallPolicyController.js
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP Policy Engine
* ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017, 2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -17,7 +17,9 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-angular.module('abs').controller('fwPolicyController', ['$scope', '$window', 'PolicyAppService', 'policyNavigator', 'modalService', '$modal', 'Notification', function ($scope, $window, PolicyAppService, PolicyNavigator, modalService, $modal, Notification) {
+angular.module('abs').controller('fwPolicyController',
+ ['$scope', '$window', 'PolicyAppService', 'policyNavigator', 'modalService', '$modal', 'Notification',
+ function ($scope, $window, PolicyAppService, PolicyNavigator, modalService, $modal, Notification) {
$("#dialog").hide();
$scope.policyNavigator;
@@ -25,18 +27,18 @@ angular.module('abs').controller('fwPolicyController', ['$scope', '$window', 'Po
$scope.refreshCheck = false;
if(!$scope.temp.policy.editPolicy && !$scope.temp.policy.readOnly){
- $scope.temp.policy = {
- policyType : "Config",
- configPolicyType : "Firewall Config"
- }
+ $scope.temp.policy = {
+ policyType : "Config",
+ configPolicyType : "Firewall Config"
+ }
};
$scope.refresh = function(){
- if($scope.refreshCheck){
- $scope.policyNavigator.refresh();
- }
- $scope.modal('createNewPolicy', true);
- $scope.temp.policy = "";
+ if($scope.refreshCheck){
+ $scope.policyNavigator.refresh();
+ }
+ $scope.modal('createNewPolicy', true);
+ $scope.temp.policy = "";
};
$scope.modal = function(id, hide) {
@@ -44,83 +46,51 @@ angular.module('abs').controller('fwPolicyController', ['$scope', '$window', 'Po
};
$('#ttlDate').datepicker({
- dateFormat: 'dd/mm/yy',
- changeMonth: true,
- changeYear: true,
- onSelect: function(date) {
- angular.element($('#ttlDate')).triggerHandler('input');
- }
+ dateFormat: 'dd/mm/yy',
+ changeMonth: true,
+ changeYear: true,
+ onSelect: function(date) {
+ angular.element($('#ttlDate')).triggerHandler('input');
+ }
});
-
+
PolicyAppService.getData('getDictionary/get_SecurityZoneDataByName').then(function (data) {
- var j = data;
- $scope.data = JSON.parse(j.data);
- console.log($scope.data);
- $scope.securityZoneDictionaryDatas = JSON.parse($scope.data.securityZoneDictionaryDatas);
- console.log($scope.securityZoneDictionaryDatas);
- }, function (error) {
- console.log("failed");
+ var j = data;
+ $scope.data = JSON.parse(j.data);
+ $scope.securityZoneDictionaryDatas = JSON.parse($scope.data.securityZoneDictionaryDatas);
});
PolicyAppService.getData('getDictionary/get_TermListDataByName').then(function (data) {
- var j = data;
- $scope.data = JSON.parse(j.data);
- console.log($scope.data);
- $scope.termListDictionaryDatas = JSON.parse($scope.data.termListDictionaryDatas);
- console.log($scope.termListDictionaryDatas);
- }, function (error) {
- console.log("failed");
+ var j = data;
+ $scope.data = JSON.parse(j.data);
+ $scope.termListDictionaryDatas = JSON.parse($scope.data.termListDictionaryDatas);
});
PolicyAppService.getData('getDictionary/get_FWDictionaryListDataByName').then(function (data) {
- var j = data;
- $scope.data = JSON.parse(j.data);
- console.log($scope.data);
- $scope.fwDictListDictionaryDatas = JSON.parse($scope.data.fwDictListDictionaryDatas);
- console.log($scope.fwDictListDictionaryDatas);
- }, function (error) {
- console.log("failed");
+ var j = data;
+ $scope.data = JSON.parse(j.data);
+ $scope.fwDictListDictionaryDatas = JSON.parse($scope.data.fwDictListDictionaryDatas);
});
PolicyAppService.getData('getDictionary/get_FWParentListDataByName').then(function (data) {
- var j = data;
- $scope.data = JSON.parse(j.data);
- console.log($scope.data);
- $scope.fwParentListDictionaryDatas = JSON.parse($scope.data.fwParentListDictionaryDatas);
- console.log($scope.fwParentListDictionaryDatas);
- }, function (error) {
- console.log("failed");
+ var j = data;
+ $scope.data = JSON.parse(j.data);
+ $scope.fwParentListDictionaryDatas = JSON.parse($scope.data.fwParentListDictionaryDatas);
});
PolicyAppService.getData('getDictionary/get_TagPickerNameByName').then(function (data) {
- var j = data;
- $scope.data = JSON.parse(j.data);
- console.log($scope.data);
- $scope.fwTagPickerDictionaryDatas = JSON.parse($scope.data.fwTagPickerDictionaryDatas);
- console.log($scope.fwTagPickerDictionaryDatas);
- }, function (error) {
- console.log("failed");
+ var j = data;
+ $scope.data = JSON.parse(j.data);
+ $scope.fwTagPickerDictionaryDatas = JSON.parse($scope.data.fwTagPickerDictionaryDatas);
});
PolicyAppService.getData('getDictionary/get_RiskTypeDataByName').then(function (data) {
- var j = data;
- $scope.data = JSON.parse(j.data);
- console.log($scope.data);
- $scope.riskTypeDictionaryDatas = JSON.parse($scope.data.riskTypeDictionaryDatas);
- console.log($scope.riskTypeDictionaryDatas);
- }, function (error) {
- console.log("failed");
+ var j = data;
+ $scope.data = JSON.parse(j.data);
+ $scope.riskTypeDictionaryDatas = JSON.parse($scope.data.riskTypeDictionaryDatas);
});
- function extend(obj, src) {
- for (var key in src) {
- if (src.hasOwnProperty(key)) obj[key] = src[key];
- }
- return obj;
- }
-
$scope.viewFWRule = function(policy){
- console.log(policy);
var uuu = "policyController/ViewFWPolicyRule.htm";
var postData={policyData: policy};
$.ajax({
@@ -131,110 +101,106 @@ angular.module('abs').controller('fwPolicyController', ['$scope', '$window', 'Po
data: JSON.stringify(postData),
success : function(data){
$scope.$apply(function(){
- window.alert(data.policyData);
+ window.alert(data.policyData);
});
},
error : function(data){
- Notification.error("Error Occured while Showing Rule.");
+ Notification.error("Error Occured while Showing Rule.");
}
});
};
$scope.saveFWPolicy = function(policy){
- if(policy.itemContent != undefined){
- $scope.refreshCheck = true;
- $scope.policyNavigator = policy.itemContent;
- policy.itemContent = "";
- }
- $scope.savebutton = false;
- console.log(policy);
+ if(policy.itemContent != undefined){
+ $scope.refreshCheck = true;
+ $scope.policyNavigator = policy.itemContent;
+ policy.itemContent = "";
+ }
+ $scope.savebutton = false;
var uuu = "policycreation/save_policy";
- var postData={policyData: policy};
- $.ajax({
- type : 'POST',
- url : uuu,
- dataType: 'json',
- contentType: 'application/json',
- data: JSON.stringify(postData),
- success : function(data){
- $scope.$apply(function(){
- $scope.data=data.policyData;
- if($scope.data == 'success'){
- $scope.temp.policy.readOnly = 'true';
- $scope.pushStatus=data.policyData.split("&")[1];
- if($scope.pushStatus=="successPush"){
- Notification.success("Policy pushed successfully");
- }
- Notification.success("Policy Saved Successfully.");
- }else if ($scope.data == 'PolicyExists'){
- $scope.savebutton = true;
- Notification.error("Policy Already Exists with Same Name in Scope.");
- }
- });
- console.log($scope.data);
- },
- error : function(data){
- Notification.error("Error Occured while saving Policy.");
- }
- });
+ var postData={policyData: policy};
+ $.ajax({
+ type : 'POST',
+ url : uuu,
+ dataType: 'json',
+ contentType: 'application/json',
+ data: JSON.stringify(postData),
+ success : function(data){
+ $scope.$apply(function(){
+ $scope.data=data.policyData;
+ if($scope.data == 'success'){
+ $scope.temp.policy.readOnly = 'true';
+ $scope.pushStatus=data.policyData.split("&")[1];
+ if($scope.pushStatus=="successPush"){
+ Notification.success("Policy pushed successfully");
+ }
+ Notification.success("Policy Saved Successfully.");
+ }else if ($scope.data == 'PolicyExists'){
+ $scope.savebutton = true;
+ Notification.error("Policy Already Exists with Same Name in Scope.");
+ }
+ });
+ },
+ error : function(data){
+ Notification.error("Error Occured while saving Policy.");
+ }
+ });
};
$scope.validatePolicy = function(policy){
- console.log(policy);
- document.getElementById("validate").innerHTML = "";
+ document.getElementById("validate").innerHTML = "";
var uuu = "policyController/validate_policy.htm";
- var postData={policyData: policy};
- $.ajax({
- type : 'POST',
- url : uuu,
- dataType: 'json',
- contentType: 'application/json',
- data: JSON.stringify(postData),
- success : function(data){
- $scope.$apply(function(){
- $scope.validateData = data.data.replace(/\"/g, "");
- $scope.data=data.data.substring(1,8);
- var size = data.data.length;
- if($scope.data == 'success'){
- Notification.success("Validation Success.");
- $scope.savebutton = false;
- if (size > 18){
- var displayWarning = data.data.substring(19,size);
- document.getElementById("validate").innerHTML = "Safe Policy Warning Message : "+displayWarning;
- document.getElementById("validate").style.color = "white";
- document.getElementById("validate").style.backgroundColor = "skyblue";
- }
- }else{
- Notification.error("Validation Failed.");
- document.getElementById("validate").innerHTML = $scope.validateData;
- document.getElementById("validate").style.color = "white";
- document.getElementById("validate").style.backgroundColor = "red";
- $scope.savebutton = true;
- }
-
- });
- console.log($scope.data);
-
- },
- error : function(data){
- Notification.error("Validation Failed.");
- $scope.savebutton = true;
- }
- });
+ var postData={policyData: policy};
+ $.ajax({
+ type : 'POST',
+ url : uuu,
+ dataType: 'json',
+ contentType: 'application/json',
+ data: JSON.stringify(postData),
+ success : function(data){
+ $scope.$apply(function(){
+ $scope.validateData = data.data.replace(/\"/g, "");
+ $scope.data=data.data.substring(1,8);
+ var size = data.data.length;
+ if($scope.data == 'success'){
+ Notification.success("Validation Success.");
+ $scope.savebutton = false;
+ if (size > 18){
+ var displayWarning = data.data.substring(19,size);
+ document.getElementById("validate").innerHTML = "Safe Policy Warning Message : "+displayWarning;
+ document.getElementById("validate").style.color = "white";
+ document.getElementById("validate").style.backgroundColor = "skyblue";
+ }
+ }else{
+ Notification.error("Validation Failed.");
+ document.getElementById("validate").innerHTML = $scope.validateData;
+ document.getElementById("validate").style.color = "white";
+ document.getElementById("validate").style.backgroundColor = "red";
+ $scope.savebutton = true;
+ }
+
+ });
+
+ },
+ error : function(data){
+ Notification.error("Validation Failed.");
+ $scope.savebutton = true;
+ }
+ });
};
if(!$scope.temp.policy.editPolicy && !$scope.temp.policy.readOnly){
- $scope.temp.policy.attributes = [];
- $scope.temp.policy.fwattributes = [];
+ $scope.temp.policy.attributes = [];
+ $scope.temp.policy.fwattributes = [];
}else{
if($scope.temp.policy.attributes.length == 0){
- $scope.temp.policy.attributes = [];
+ $scope.temp.policy.attributes = [];
}
if($scope.temp.policy.fwPolicyType == 'Parent Policy'){
- if($scope.temp.policy.fwattributes.length == 0){
- $scope.temp.policy.fwattributes = [];
- }
+ if($scope.temp.policy.fwattributes.length == 0){
+ $scope.temp.policy.fwattributes = [];
+ }
}
}
@@ -258,4 +224,4 @@ angular.module('abs').controller('fwPolicyController', ['$scope', '$window', 'Po
$scope.temp.policy.fwattributes.splice(lastItem);
};
-}]); \ No newline at end of file
+}]);
diff --git a/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/PolicyTemplateController/OptimizationPolicyController.js b/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/PolicyTemplateController/OptimizationPolicyController.js
index cdeaefdea..58594bc43 100644
--- a/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/PolicyTemplateController/OptimizationPolicyController.js
+++ b/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/PolicyTemplateController/OptimizationPolicyController.js
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP Policy Engine
* ================================================================================
- * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2018-2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -17,7 +17,9 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-angular.module('abs').controller('optimizationController', ['$scope', '$window', '$compile', 'PolicyAppService', 'policyNavigator', 'modalService', '$modal', 'Notification', function ($scope, $window, $compile, PolicyAppService, PolicyNavigator, modalService, $modal, Notification) {
+angular.module('abs').controller('optimizationController',
+ ['$scope', '$window', '$compile', 'PolicyAppService', 'policyNavigator', 'modalService', '$modal', 'Notification',
+ function ($scope, $window, $compile, PolicyAppService, PolicyNavigator, modalService, $modal, Notification) {
$("#dialog").hide();
$scope.policyNavigator;
@@ -26,18 +28,18 @@ angular.module('abs').controller('optimizationController', ['$scope', '$window',
$scope.refreshCheck = false;
if(!$scope.temp.policy.editPolicy && !$scope.temp.policy.readOnly){
- $scope.temp.policy = {
- policyType : "Config",
- configPolicyType : "Optimization"
- }
- };
+ $scope.temp.policy = {
+ policyType : "Config",
+ configPolicyType : "Optimization"
+ }
+ }
$scope.refresh = function(){
- if($scope.refreshCheck){
- $scope.policyNavigator.refresh();
- }
- $scope.modal('createNewPolicy', true);
- $scope.temp.policy = "";
+ if($scope.refreshCheck){
+ $scope.policyNavigator.refresh();
+ }
+ $scope.modal('createNewPolicy', true);
+ $scope.temp.policy = "";
};
$scope.modal = function(id, hide) {
@@ -45,247 +47,226 @@ angular.module('abs').controller('optimizationController', ['$scope', '$window',
};
$('#ttlDate').datepicker({
- dateFormat: 'dd/mm/yy',
- changeMonth: true,
- changeYear: true,
- onSelect: function(date) {
- angular.element($('#ttlDate')).triggerHandler('input');
- }
+ dateFormat: 'dd/mm/yy',
+ changeMonth: true,
+ changeYear: true,
+ onSelect: function(date) {
+ angular.element($('#ttlDate')).triggerHandler('input');
+ }
});
- if ($scope.temp.policy.editPolicy != undefined|| $scope.temp.policy.readOnly != undefined){
- if ($scope.temp.policy.configName == undefined){
- $scope.isCheck = false;
- }else{
- $scope.isCheck = true;
- }
- }else {
- $scope.isCheck = false;
- }
-
- PolicyAppService.getData('getDictionary/get_OnapNameDataByName').then(function (data) {
- var j = data;
- $scope.data = JSON.parse(j.data);
- console.log($scope.data);
- $scope.onapNameDictionaryDatas = JSON.parse($scope.data.onapNameDictionaryDatas);
- console.log($scope.onapNameDictionaryDatas);
- }, function (error) {
- console.log("failed");
- });
+ if ($scope.temp.policy.editPolicy != undefined|| $scope.temp.policy.readOnly != undefined){
+ if ($scope.temp.policy.configName == undefined){
+ $scope.isCheck = false;
+ }else{
+ $scope.isCheck = true;
+ }
+ }else {
+ $scope.isCheck = false;
+ }
+
+ PolicyAppService.getData('getDictionary/get_OnapNameDataByName').then(function (data) {
+ var j = data;
+ $scope.data = JSON.parse(j.data);
+ $scope.onapNameDictionaryDatas = JSON.parse($scope.data.onapNameDictionaryDatas);
+ });
- PolicyAppService.getData('get_DCAEPriorityValues').then(function (data) {
- var j = data;
- $scope.data = JSON.parse(j.data);
- console.log($scope.data);
- $scope.priorityDatas = JSON.parse($scope.data.priorityDatas);
- console.log($scope.priorityDatas);
- }, function (error) {
- console.log("failed");
- });
+ PolicyAppService.getData('get_DCAEPriorityValues').then(function (data) {
+ var j = data;
+ $scope.data = JSON.parse(j.data);
+ $scope.priorityDatas = JSON.parse($scope.data.priorityDatas);
+ });
- PolicyAppService.getData('getDictionary/get_OptimizationModelsDataByName').then(function (data) {
- var j = data;
- $scope.data = JSON.parse(j.data);
- console.log($scope.data);
- var inputModelList = JSON.parse($scope.data.optimizationModelsDictionaryDatas);
- var unique = {};
- var uniqueList = [];
- for(var i = 0; i < inputModelList.length; i++){
- if(typeof unique[inputModelList[i]] == "undefined"){
- unique[inputModelList[i]] = "";
- uniqueList.push(inputModelList[i]);
- }
- }
- $scope.optimizationModelsDictionaryDatas = uniqueList;
- console.log($scope.optimizationModelsDictionaryDatas);
- }, function (error) {
- console.log("failed");
- });
+ PolicyAppService.getData('getDictionary/get_OptimizationModelsDataByName').then(function (data) {
+ var j = data;
+ $scope.data = JSON.parse(j.data);
+ var inputModelList = JSON.parse($scope.data.optimizationModelsDictionaryDatas);
+ var unique = {};
+ var uniqueList = [];
+ for(var i = 0; i < inputModelList.length; i++){
+ if(typeof unique[inputModelList[i]] == "undefined"){
+ unique[inputModelList[i]] = "";
+ uniqueList.push(inputModelList[i]);
+ }
+ }
+ $scope.optimizationModelsDictionaryDatas = uniqueList;
+ });
- PolicyAppService.getData('getDictionary/get_RiskTypeDataByName').then(function (data) {
- var j = data;
- $scope.data = JSON.parse(j.data);
- console.log($scope.data);
- $scope.riskTypeDictionaryDatas = JSON.parse($scope.data.riskTypeDictionaryDatas);
- console.log($scope.riskTypeDictionaryDatas);
- }, function (error) {
- console.log("failed");
- });
+ PolicyAppService.getData('getDictionary/get_RiskTypeDataByName').then(function (data) {
+ var j = data;
+ $scope.data = JSON.parse(j.data);
+ $scope.riskTypeDictionaryDatas = JSON.parse($scope.data.riskTypeDictionaryDatas);
+ });
- $scope.choices = [];
- $scope.attributeDatas = [{"attributes" : $scope.choices}];
- $scope.isInitEditTemplate = true; //just initially create the edit template, didn't click add button yet.
- $scope.addNewChoice = function(value) {
- console.log("input value : " + value);
- if(value != undefined){
- if (value.startsWith('div.')){
- value = value.replace('div.','');
- }
- var parentElement = document.getElementById("div."+value);
- var div = document.getElementById(value+"@0");
- if(div != null){
- var clone = div.cloneNode(true);
- var addElement = parentElement.childElementCount;
- clone.id = ''+value+'@'+addElement;
- clone.value = '';
- if($scope.temp.policy.editPolicy || $scope.temp.policy.readOnly){ //if it's view or edit
- if($scope.temp.policy.ruleData[clone.id] || ($scope.temp.policy.editPolicy && !$scope.isInitEditTemplate)){ // Only append child if its value found in ruleData or edit mode
- if($scope.temp.policy.ruleData[clone.id]){
- clone.value = $scope.temp.policy.ruleData[clone.id];
- }
- if(!clone.className.includes("child_single")){
- clone.className += ' child_single'; //single element clone
- }
- document.getElementById("div."+value).appendChild(clone);
- plainAttributeKeys.push(''+value+'@'+addElement);
- }
- }else{ //not view or edit
- if(!clone.className.includes("child_single")){
- clone.className += ' child_single'; //single element clone
- }
- document.getElementById("div."+value).appendChild(clone);
- plainAttributeKeys.push(''+value+'@'+addElement);
- }
- }else{
- div = document.getElementById("div."+value+"@0");
-
- if(div){
- div.className += ' children_group'; //div with a group of children.
- }
- var childElement = parentElement.firstElementChild;
- var countParent = parentElement.childElementCount;
- var childElementString = childElement.innerHTML;
- var find = value+"@0";
- var re = new RegExp(find, 'g');
- childElementString = childElementString.replace(re,value+'@' + countParent);
- var clone = childElement.cloneNode(true);
- for (var ii = 0; ii < parentElement.childNodes.length; ii++){
- var childId = parentElement.childNodes[ii].id;
- if(ii = parentElement.childNodes.length){
- var childnewId = childId.slice(0, -1);
- var count = childId.slice(-1);
- }
- }
- var countvalue = parseInt(count) + 1;
- clone.id = childnewId+countvalue;
- clone.value = '';
- clone.innerHTML=childElementString;
- document.getElementById("div."+value).appendChild(clone);
- var selects = clone.getElementsByTagName("select");
- var inputs = clone.getElementsByTagName("input");
- var removeValues = [];
- for(var i=0; i<inputs.length; i++){
- if ($scope.temp.policy.ruleData!=undefined){
- var checkValue = $scope.temp.policy.ruleData[inputs[i].id];
- if (checkValue!=undefined && checkValue != "undefined"){
- if($scope.temp.policy.ruleData != null){
- var checkValue = $scope.temp.policy.ruleData[inputs[i].id];
- document.getElementById(inputs[i].id).value = $scope.temp.policy.ruleData[inputs[i].id];
- plainAttributeKeys.push(inputs[i].id);
- }
- } else {
- plainAttributeKeys.push(inputs[i].id);
- }
- }else {
- plainAttributeKeys.push(inputs[i].id);
- }
- }
-
- for(var i=0; i<selects.length; i++){
- if ($scope.temp.policy.ruleData!=undefined){
- var checkValue = $scope.temp.policy.ruleData[selects[i].id];
- if (checkValue!=undefined && checkValue!="undefined"){
- if($scope.temp.policy.ruleData != null){
- var checkValue = $scope.temp.policy.ruleData[selects[i].id];
- document.getElementById(selects[i].id).value = $scope.temp.policy.ruleData[selects[i].id];
- plainAttributeKeys.push(selects[i].id);
- }
- } else {
- plainAttributeKeys.push(selects[i].id);
- }
- }else {
- plainAttributeKeys.push(selects[i].id);
- }
- }
-
- for (var k=0; k<removeValues.length; k++){
- var elem = document.getElementById(removeValues[k]);
- elem.parentNode.removeChild(elem);
- }
- var ele = angular.element(document.getElementById("div."+value));
- $compile(ele.contents())($scope);
- $scope.$apply();
- }
- }
- };
-
- function findVal(object, key) {
- var value;
- Object.keys(object).some(function(k) {
- if (k === key) {
- value = object[k];
- return true;
- }
- if (object[k] && typeof object[k] === 'object') {
- value = findVal(object[k], key);
- return value !== undefined;
- }
- });
- return value;
- }
-
- $scope.removeChoice = function(value) {
- console.log(value);
- if(value != undefined){
- var c = document.getElementById("div."+value).childElementCount;
-
- if(c == 1){
- Notification.error("The original one is not removable.");
- return;
- }
- document.getElementById("div."+value).removeChild(document.getElementById("div."+value).lastChild);
- }
- };
-
- $scope.pullVersion = function(serviceName) {
- console.log(serviceName);
- if(serviceName != undefined){
- var uuu = "policyController/getModelServiceVersionData.htm";
- var postData={policyData: serviceName};
- $.ajax({
- type : 'POST',
- url : uuu,
- dataType: 'json',
- contentType: 'application/json',
- data: JSON.stringify(postData),
- success : function(data){
- $scope.$apply(function(){
- $scope.optimizationModelsDictionaryVersionDatas = data[0].optimizationModelVersionData;
- });
- },
- error : function(data){
- alert("Error While Retrieving the Template Layout Pattern.");
- }
- });
- }
- };
+ $scope.choices = [];
+ $scope.attributeDatas = [{"attributes" : $scope.choices}];
+ $scope.isInitEditTemplate = true; //just initially create the edit template, didn't click add button yet.
+ $scope.addNewChoice = function(value) {
+ if(value != undefined){
+ if (value.startsWith('div.')){
+ value = value.replace('div.','');
+ }
+ var parentElement = document.getElementById("div."+value);
+ var div = document.getElementById(value+"@0");
+ if(div != null){
+ var clone = div.cloneNode(true);
+ var addElement = parentElement.childElementCount;
+ clone.id = ''+value+'@'+addElement;
+ clone.value = '';
+ if($scope.temp.policy.editPolicy || $scope.temp.policy.readOnly){ //if it's view or edit
+ if($scope.temp.policy.ruleData[clone.id] || ($scope.temp.policy.editPolicy && !$scope.isInitEditTemplate)){ // Only append child if its value found in ruleData or edit mode
+ if($scope.temp.policy.ruleData[clone.id]){
+ clone.value = $scope.temp.policy.ruleData[clone.id];
+ }
+ if(!clone.className.includes("child_single")){
+ clone.className += ' child_single'; //single element clone
+ }
+ document.getElementById("div."+value).appendChild(clone);
+ plainAttributeKeys.push(''+value+'@'+addElement);
+ }
+ }else{ //not view or edit
+ if(!clone.className.includes("child_single")){
+ clone.className += ' child_single'; //single element clone
+ }
+ document.getElementById("div."+value).appendChild(clone);
+ plainAttributeKeys.push(''+value+'@'+addElement);
+ }
+ }else{
+ div = document.getElementById("div."+value+"@0");
+
+ if(div){
+ div.className += ' children_group'; //div with a group of children.
+ }
+ var childElement = parentElement.firstElementChild;
+ var countParent = parentElement.childElementCount;
+ var childElementString = childElement.innerHTML;
+ var find = value+"@0";
+ var re = new RegExp(find, 'g');
+ childElementString = childElementString.replace(re,value+'@' + countParent);
+ var clone = childElement.cloneNode(true);
+ for (var ii = 0; ii < parentElement.childNodes.length; ii++){
+ var childId = parentElement.childNodes[ii].id;
+ if(ii = parentElement.childNodes.length){
+ var childnewId = childId.slice(0, -1);
+ var count = childId.slice(-1);
+ }
+ }
+ var countvalue = parseInt(count) + 1;
+ clone.id = childnewId+countvalue;
+ clone.value = '';
+ clone.innerHTML=childElementString;
+ document.getElementById("div."+value).appendChild(clone);
+ var selects = clone.getElementsByTagName("select");
+ var inputs = clone.getElementsByTagName("input");
+ var removeValues = [];
+ for(var i=0; i<inputs.length; i++){
+ if ($scope.temp.policy.ruleData!=undefined){
+ var checkValue = $scope.temp.policy.ruleData[inputs[i].id];
+ if (checkValue!=undefined && checkValue != "undefined"){
+ if($scope.temp.policy.ruleData != null){
+ var checkValue = $scope.temp.policy.ruleData[inputs[i].id];
+ document.getElementById(inputs[i].id).value = $scope.temp.policy.ruleData[inputs[i].id];
+ plainAttributeKeys.push(inputs[i].id);
+ }
+ } else {
+ plainAttributeKeys.push(inputs[i].id);
+ }
+ }else {
+ plainAttributeKeys.push(inputs[i].id);
+ }
+ }
+
+ for(var i=0; i<selects.length; i++){
+ if ($scope.temp.policy.ruleData!=undefined){
+ var checkValue = $scope.temp.policy.ruleData[selects[i].id];
+ if (checkValue!=undefined && checkValue!="undefined"){
+ if($scope.temp.policy.ruleData != null){
+ var checkValue = $scope.temp.policy.ruleData[selects[i].id];
+ document.getElementById(selects[i].id).value = $scope.temp.policy.ruleData[selects[i].id];
+ plainAttributeKeys.push(selects[i].id);
+ }
+ } else {
+ plainAttributeKeys.push(selects[i].id);
+ }
+ }else {
+ plainAttributeKeys.push(selects[i].id);
+ }
+ }
+
+ for (var k=0; k<removeValues.length; k++){
+ var elem = document.getElementById(removeValues[k]);
+ elem.parentNode.removeChild(elem);
+ }
+ var ele = angular.element(document.getElementById("div."+value));
+ $compile(ele.contents())($scope);
+ $scope.$apply();
+ }
+ }
+ };
+
+ function findVal(object, key) {
+ var value;
+ Object.keys(object).some(function(k) {
+ if (k === key) {
+ value = object[k];
+ return true;
+ }
+ if (object[k] && typeof object[k] === 'object') {
+ value = findVal(object[k], key);
+ return value !== undefined;
+ }
+ });
+ return value;
+ }
+
+ $scope.removeChoice = function(value) {
+ if(value != undefined){
+ var c = document.getElementById("div."+value).childElementCount;
+
+ if(c == 1){
+ Notification.error("The original one is not removable.");
+ return;
+ }
+ document.getElementById("div."+value).removeChild(document.getElementById("div."+value).lastChild);
+ }
+ };
+
+ $scope.pullVersion = function(serviceName) {
+ if(serviceName != undefined){
+ var uuu = "policyController/getModelServiceVersionData.htm";
+ var postData={policyData: serviceName};
+ $.ajax({
+ type : 'POST',
+ url : uuu,
+ dataType: 'json',
+ contentType: 'application/json',
+ data: JSON.stringify(postData),
+ success : function(data){
+ $scope.$apply(function(){
+ $scope.optimizationModelsDictionaryVersionDatas = data[0].optimizationModelVersionData;
+ });
+ },
+ error : function(data){
+ Notification.error("Error While Retrieving the Template Layout Pattern.");
+ }
+ });
+ }
+ };
- var splitDash = '-';
- var splitEqual = '=';
- var splitComma = ',';
- var splitcolon = ':';
- var splitsemicolon = ";";
- var splitEnum = "],";
- var plainAttributeKeys = [];
- var matching = [];
- var enumKeyList = [];
- var dictionaryList = [];
- var dictionaryNameList = [];
+ var splitEqual = '=';
+ var splitComma = ',';
+ var splitcolon = ':';
+ var splitEnum = "],";
+ var plainAttributeKeys = [];
+ var matching = [];
+ var enumKeyList = [];
+ var dictionaryList = [];
+ var dictionaryNameList = [];
$scope.addDataToFields = function(serviceName, version){
if(serviceName != null && version !=null){
- var service=serviceName+"-v"+version;
- var myNode = document.getElementById("DynamicTemplate");
- myNode.innerHTML = '';
+ var service=serviceName+"-v"+version;
+ var myNode = document.getElementById("DynamicTemplate");
+ myNode.innerHTML = '';
var uuu = "policyController/getOptimizationTemplateData.htm";
var postData={policyData: service};
var dataOrderInfo = "";
@@ -298,967 +279,931 @@ angular.module('abs').controller('optimizationController', ['$scope', '$window',
data: JSON.stringify(postData),
success : function(data){
$scope.$apply(function(){
- var plainAttributeKeys = [];
- $scope.optimizationModelData = data[0].optimizationModelData;
- $scope.optimizationJsonDate = data[0].jsonValue;
+ $scope.optimizationModelData = data[0].optimizationModelData;
+ $scope.optimizationJsonDate = data[0].jsonValue;
$scope.dataOrderInfo = null;
- $scope.dataOrderInfo = data[0].dataOrderInfo;
- console.log("data[0].dataOrderInfo: " + data[0].dataOrderInfo);
- console.log("$scope.dataOrderInfo: " + $scope.dataOrderInfo);
- if(data[0].allManyTrueKeys){
- console.log("$scope.allManyTrueKeys: " + $scope.allManyTrueKeys);
- }
- console.log("$scope.optimizationJsonDate: " + $scope.optimizationJsonDate);
- var attributes = $scope.optimizationModelData.attributes;
- var refAttributes = $scope.optimizationModelData.ref_attributes;
- var subAttributes = $scope.optimizationModelData.sub_attributes;
- console.log("attributes: " +attributes);
- console.log("subAttributes: " + subAttributes);
- console.log("refAttributes: " + refAttributes);
-
- var headDefautlsData = data[0].headDefautlsData;
- if(headDefautlsData != null){
- $scope.temp.policy.onapName = headDefautlsData.onapName;
- $scope.temp.policy.guard = headDefautlsData.guard;
- $scope.temp.policy.riskType = headDefautlsData.riskType;
- $scope.temp.policy.riskLevel = headDefautlsData.riskLevel;
- $scope.temp.policy.priority = headDefautlsData.priority;
-
- }else if(!$scope.temp.policy.editPolicy && !$scope.temp.policy.readOnly){
- $scope.temp.policy.onapName = "";
- $scope.temp.policy.guard = "";
- $scope.temp.policy.riskType = "";
- $scope.temp.policy.riskLevel = "";
- $scope.temp.policy.priority = "";
- }
-
- var enumAttributes = $scope.optimizationModelData.enumValues;
- var annotation = $scope.optimizationModelData.annotation;
- var dictionary = $scope.microServiceAttributeDictionaryDatas;
+ var headDefautlsData = data[0].headDefautlsData;
+ if(headDefautlsData != null){
+ $scope.temp.policy.onapName = headDefautlsData.onapName;
+ $scope.temp.policy.guard = headDefautlsData.guard;
+ $scope.temp.policy.riskType = headDefautlsData.riskType;
+ $scope.temp.policy.riskLevel = headDefautlsData.riskLevel;
+ $scope.temp.policy.priority = headDefautlsData.priority;
+
+ }else if(!$scope.temp.policy.editPolicy && !$scope.temp.policy.readOnly){
+ $scope.temp.policy.onapName = "";
+ $scope.temp.policy.guard = "";
+ $scope.temp.policy.riskType = "";
+ $scope.temp.policy.riskLevel = "";
+ $scope.temp.policy.priority = "";
+ }
+
+ var annotation = $scope.optimizationModelData.annotation;
+ var dictionary = $scope.microServiceAttributeDictionaryDatas;
- if (annotation == null || annotation.length<1){
- $scope.isCheck = true;
- }else {
- $scope.isCheck = false;
- var annoationList = annotation.split(splitComma);
- for (k = 0; k < annoationList.length; k++){
- var splitAnnotation = annoationList[k].split(splitEqual);
- if (splitAnnotation[1].includes("matching-true")){
- matching.push(splitAnnotation[0].trim());
- }
- }
+ if (annotation == null || annotation.length<1){
+ $scope.isCheck = true;
+ }else {
+ $scope.isCheck = false;
+ var annoationList = annotation.split(splitComma);
+ for (k = 0; k < annoationList.length; k++){
+ var splitAnnotation = annoationList[k].split(splitEqual);
+ if (splitAnnotation[1].includes("matching-true")){
+ matching.push(splitAnnotation[0].trim());
+ }
+ }
- }
+ }
- if (dictionary!= null && dictionary.length>1){
- for (m=0; m < dictionary.length; m += 1){
- var keyCompare = dictionary[m].name;
- var valueCompare = dictionary[m].value;
- var valueModel = dictionary[m].modelName;
- var conpairService = serviceName;
- if (valueModel.includes('-v')){
- conpairService = service;
- }
- if(valueModel.localeCompare(conpairService) == 0){
- console.log(valueCompare);
- dictionaryList.push(dictionary[m]);
- if (!dictionaryNameList.includes(dictionary[m].name)){
- dictionaryNameList.push(dictionary[m].name)
- }
- }
- }
- }
+ if (dictionary!= null && dictionary.length>1){
+ for (m=0; m < dictionary.length; m += 1){
+ var valueCompare = dictionary[m].value;
+ var valueModel = dictionary[m].modelName;
+ var conpairService = serviceName;
+ if (valueModel.includes('-v')){
+ conpairService = service;
+ }
+ if(valueModel.localeCompare(conpairService) == 0){
+ dictionaryList.push(dictionary[m]);
+ if (!dictionaryNameList.includes(dictionary[m].name)){
+ dictionaryNameList.push(dictionary[m].name)
+ }
+ }
+ }
+ }
- $scope.temp.policy.ruleGridData = [];
-
- if($scope.temp.policy.editPolicy || $scope.temp.policy.readOnly){
- dataOrderInfo = $scope.dataOrderInfo;
- }
-
- $scope.jsonLayout($scope.optimizationJsonDate);
-
+ $scope.temp.policy.ruleGridData = [];
+
+ if($scope.temp.policy.editPolicy || $scope.temp.policy.readOnly){
+ dataOrderInfo = $scope.dataOrderInfo;
+ }
+
+ $scope.jsonLayout($scope.optimizationJsonDate);
+
});
if($scope.temp.policy.editPolicy || $scope.temp.policy.readOnly){ // If it's veiw or edit
-
- if($scope.temp.policy.editPolicy){
- $scope.isInitEditTemplate = true;
- }
-
- var checkData = [];
- var data = [];
- // If ruleData contains extra elements created by clicked add button
- if($scope.temp.policy.ruleData != null){
- var propNames = Object.getOwnPropertyNames($scope.temp.policy.ruleData);
- propNames.forEach(function(name) {
- data.push(name);
- });
-
- var extraElements = data;
-
- if(plainAttributeKeys != null){
- for(b = 0; b < plainAttributeKeys.length; b++){ // Remove already populated elements from data array
- var newValue = plainAttributeKeys[b].split("*");
- for(a = 0; a < data.length; a++){
- if(data[a] === newValue[0] || data[a] === (newValue[0]+"@0")){
- extraElements.splice(a, 1);
- }
- }
-
- }
-
- //--- Populate these extra elements created by clicked add button
- for(a = 0; a < extraElements.length; a++){
- if(extraElements[a].includes("@")){
- var index = extraElements[a].lastIndexOf("@");
- if(index > 0){
- // Get the number after @
- var n = getNumOfDigits(extraElements[a], index+1);
-
- var key = extraElements[a].substring(0, index+n+1); //include @x in key also by n+2 since x can be 1,12, etc
- console.log("key: " + key);
- checkData.push(key);
- }
- }
- }
- var unique = checkData.filter(onlyUnique);
- //if no layout order info, keep the process as before
- if(!dataOrderInfo){
- for(i =0; i < unique.length; i++){
- //remove @x and let addNewChoice add @1 or @2...
- //var newKey = unique[i].substring(0, unique[i].length-2);
- var index = unique[i].lastIndexOf("@");
- var newKey = unique[i].substring(0, index);
- console.log("newKey: " + newKey);
- $scope.addNewChoice(newKey);
- }
- }else{
+
+ if($scope.temp.policy.editPolicy){
+ $scope.isInitEditTemplate = true;
+ }
+
+ var checkData = [];
+ var data = [];
+ // If ruleData contains extra elements created by clicked add button
+ if($scope.temp.policy.ruleData != null){
+ var propNames = Object.getOwnPropertyNames($scope.temp.policy.ruleData);
+ propNames.forEach(function(name) {
+ data.push(name);
+ });
+
+ var extraElements = data;
+
+ if(plainAttributeKeys != null){
+ for(b = 0; b < plainAttributeKeys.length; b++){ // Remove already populated elements from data array
+ var newValue = plainAttributeKeys[b].split("*");
+ for(a = 0; a < data.length; a++){
+ if(data[a] === newValue[0] || data[a] === (newValue[0]+"@0")){
+ extraElements.splice(a, 1);
+ }
+ }
+
+ }
+
+ //--- Populate these extra elements created by clicked add button
+ for(a = 0; a < extraElements.length; a++){
+ if(extraElements[a].includes("@")){
+ var index = extraElements[a].lastIndexOf("@");
+ if(index > 0){
+ // Get the number after @
+ var n = getNumOfDigits(extraElements[a], index+1);
+
+ var key = extraElements[a].substring(0, index+n+1); //include @x in key also by n+2 since x can be 1,12, etc
+ checkData.push(key);
+ }
+ }
+ }
+ var unique = checkData.filter(onlyUnique);
+ //if no layout order info, keep the process as before
+ if(!dataOrderInfo){
+ for(i =0; i < unique.length; i++){
+ //remove @x and let addNewChoice add @1 or @2...
+ //var newKey = unique[i].substring(0, unique[i].length-2);
+ var index = unique[i].lastIndexOf("@");
+ var newKey = unique[i].substring(0, index);
+ $scope.addNewChoice(newKey);
+ }
+ }else{
- for (i = 0; i < $scope.labelManyKeys.length; i++) {
- console.log("dataOrderInfo["+i+"]"+ dataOrderInfo[i]);
- var label = $scope.labelManyKeys[i];
- // first add parent/label level
- for (k = 0; k < unique.length; k++){
- var newindex = unique[k].lastIndexOf("@");
- var newKey = unique[k].substring(0, index);
- if(label == newKey){
+ for (i = 0; i < $scope.labelManyKeys.length; i++) {
+ var label = $scope.labelManyKeys[i];
+ // first add parent/label level
+ for (k = 0; k < unique.length; k++){
+ var newKey = unique[k].substring(0, index);
+ if(label == newKey){
//Check this label has bee created or not
- if(!document.getElementById(unique[k])){
- $scope.addNewChoice(newKey);
- }
- unique[k] = "*processed*";
- break;
- }
- }
- }
-
- //---reset to default
- dataOrderInfo = [];
- $scope.labelManyKeys = [];
-
- //---process none labels
- for (j = 0; j < unique.length; j++){
- if(unique[j] != "*processed*"){
- // if not created yet
- if(!document.getElementById(unique[j])){
- var index = unique[j].lastIndexOf("@");
- var newKey = unique[j].substring(0, index);
- $scope.addNewChoice(newKey);
- }
- }
- }
- }
- }
- }
-
- if($scope.temp.policy.editPolicy){
- //clean all the events of addNewChoice
- $scope.$on('$destroy', addNewChoice);
- }
-
+ if(!document.getElementById(unique[k])){
+ $scope.addNewChoice(newKey);
+ }
+ unique[k] = "*processed*";
+ break;
+ }
+ }
+ }
+
+ //---reset to default
+ dataOrderInfo = [];
+ $scope.labelManyKeys = [];
+
+ //---process none labels
+ for (j = 0; j < unique.length; j++){
+ if(unique[j] != "*processed*"){
+ // if not created yet
+ if(!document.getElementById(unique[j])){
+ var index = unique[j].lastIndexOf("@");
+ var newKey = unique[j].substring(0, index);
+ $scope.addNewChoice(newKey);
+ }
+ }
+ }
+ }
+ }
+ }
+
+ if($scope.temp.policy.editPolicy){
+ //clean all the events of addNewChoice
+ $scope.$on('$destroy', addNewChoice);
+ }
+
}
var ele = angular.element(document.getElementById("DynamicTemplate"));
- $compile(ele.contents())($scope);
+ $compile(ele.contents())($scope);
$scope.$apply();
},
error : function(data){
- alert("Error While Retrieving the Template Layout Pattern.");
+ Notification.error("Error While Retrieving the Template Layout Pattern.");
}
});
}
};
function getNumOfDigits(str_value, index){
- // Get the number after @
- var str = str_value.substring(index, str_value.length);
- var c = '';
- var n = 0;
- for (var x = 0; x < str.length; x++){
- c = str.charAt(x);
- if(!isNaN(c)){
+ // Get the number after @
+ var str = str_value.substring(index, str_value.length);
+ var c = '';
+ var n = 0;
+ for (var x = 0; x < str.length; x++){
+ c = str.charAt(x);
+ if(!isNaN(c)){
n++;
- }else{
+ }else{
break;
}
- }
- return n;
+ }
+ return n;
}
function getDictionary(attribute){
- var dicName = attribute;
- if(attribute){
- if(attribute.includes(":")){
- dicName = attribute.split(":")[0];
- }
- }
- var dictionaryRegExp = new RegExp(dicName);
- listemunerateValues = [];
- if (dictionaryRegExp.test(dictionaryNameList)) {
- for (p=0; p < dictionaryList.length; p += 1) {
- if (dicName == dictionaryList[p].name) {
- listemunerateValues.push(dictionaryList[p].value);
- }
- }
- }
- return listemunerateValues;
+ var dicName = attribute;
+ if(attribute){
+ if(attribute.includes(":")){
+ dicName = attribute.split(":")[0];
+ }
+ }
+ var dictionaryRegExp = new RegExp(dicName);
+ listemunerateValues = [];
+ if (dictionaryRegExp.test(dictionaryNameList)) {
+ for (p=0; p < dictionaryList.length; p += 1) {
+ if (dicName == dictionaryList[p].name) {
+ listemunerateValues.push(dictionaryList[p].value);
+ }
+ }
+ }
+ return listemunerateValues;
}
function getList(attribute) {
- var enumName = attribute;
- console.log("In getList: attribute => " + attribute);
- if(attribute){
- if(attribute.includes(":")){
- enumName = attribute.split(":")[0];
- }
- }
+ var enumName = attribute;
+ if(attribute){
+ if(attribute.includes(":")){
+ enumName = attribute.split(":")[0];
+ }
+ }
var baseEnum = $scope.optimizationModelData.enumValues;
var enumList = [];
if(baseEnum != null){
- enumList = baseEnum.split(splitEnum);
+ enumList = baseEnum.split(splitEnum);
}
- var enumAttributes;
- var patternTest = new RegExp(enumName);
- for (k=0; k < enumList.length; k += 1){
- if(patternTest.test(enumList[k]) == true){
- enumAttributes = enumList[k].trim();
- }
- }
+ var enumAttributes;
+ var patternTest = new RegExp(enumName);
+ for (k=0; k < enumList.length; k += 1){
+ if(patternTest.test(enumList[k]) == true){
+ enumAttributes = enumList[k].trim();
+ }
+ }
- if(enumAttributes){
- enumAttributes = enumAttributes.replace("[", "");
- enumAttributes = enumAttributes.replace("]", "");
- enumAttributes = enumAttributes.replace(/ /g, '');
- var dropListAfterCommaSplit = enumAttributes.split(splitEqual);
- listemunerateValues = dropListAfterCommaSplit[1].split(splitComma);
- return listemunerateValues;
- }
+ if(enumAttributes){
+ enumAttributes = enumAttributes.replace("[", "");
+ enumAttributes = enumAttributes.replace("]", "");
+ enumAttributes = enumAttributes.replace(/ /g, '');
+ var dropListAfterCommaSplit = enumAttributes.split(splitEqual);
+ listemunerateValues = dropListAfterCommaSplit[1].split(splitComma);
+ return listemunerateValues;
+ }
return [];
}
-
+
function getBooleanList(){
- var booleanList = [];
- booleanList.push(true);
- booleanList.push(false);
- return booleanList;
+ var booleanList = [];
+ booleanList.push(true);
+ booleanList.push(false);
+ return booleanList;
}
function isArray(arrayTest) {
return Object.prototype.toString.call(arrayTest) === '[object Array]';
}
-
- var lableList = [];
-
+
+ var lableList = [];
+
$scope.layOutElementList = [];
$scope.layOutOnlyLableList = [];
var elementOrderNum = 0;
-
- function deconstructJSON(layOutData, level , name) {
+
+ function deconstructJSON(layOutData, level , name) {
- var array = false;
- var label = level;
- var stringValue = "java.lang.String";
- var string = "string";
- var intValue = "int";
- var integerValue = "integer";
- var double = "double";
- var boolean = "boolean";
- var baseLevel = level;
- var list = "list";
- var String = "String";
-
- var attributekey = "";
-
- if (name.length > 1){
- label = label + name + '.';
- }
-
- for (key in layOutData) {
- array = isArray(layOutData[key]);
- console.log("key: " + key , "value: " + layOutData[key]);
-
- if (!!layOutData[key] && typeof(layOutData[key])=="object") {
-
- if (array==false && key!=="0"){
-
- if($scope.dataOrderInfo){
- var labelObject = {"label" : key, "level" : label, "array" : array};
- //save it to the list
- $scope.layOutOnlyLableList.push(labelObject);
-
- }else {
- //call label layout
- $scope.labelLayout(label, key, array );
- }
-
- }
-
- if (array == true && key!=0){
- lableList.push(key);
- }
-
- if (lableList.length > 0){
- array = true;
- }
- if ( key==="0"){
- var newKey = lableList.pop();
-
- if($scope.dataOrderInfo){
-
- var labelObject = {"label" : newKey, "level" : baseLevel, "array" : array};
- //save it to the list
- $scope.layOutOnlyLableList.push(labelObject);
-
- }else {
- //call label layout
- $scope.labelLayout(baseLevel, newKey, array );
- }
-
- if (array){
- label = baseLevel + newKey + '@0.';
- } else {
- label = baseLevel + newKey + '.';
- }
- }
- deconstructJSON(layOutData[key] , label, key);
- } else {
- var attirbuteLabel = label;
- var defaultValue='';
- var isRequired = false;
- if (layOutData[key].includes('defaultValue-')){
- defaultValue = layOutData[key].split('defaultValue-')[1];
- }
+ var array = false;
+ var label = level;
+ var stringValue = "java.lang.String";
+ var string = "string";
+ var intValue = "int";
+ var integerValue = "integer";
+ var double = "double";
+ var boolean = "boolean";
+ var baseLevel = level;
+ var list = "list";
+ var String = "String";
+
+ var attributekey = "";
+
+ if (name.length > 1){
+ label = label + name + '.';
+ }
+
+ for (key in layOutData) {
+ array = isArray(layOutData[key]);
+
+ if (!!layOutData[key] && typeof(layOutData[key])=="object") {
+
+ if (array==false && key!=="0"){
+
+ if($scope.dataOrderInfo){
+ var labelObject = {"label" : key, "level" : label, "array" : array};
+ //save it to the list
+ $scope.layOutOnlyLableList.push(labelObject);
+
+ }else {
+ //call label layout
+ $scope.labelLayout(label, key, array );
+ }
+
+ }
+
+ if (array == true && key!=0){
+ lableList.push(key);
+ }
+
+ if (lableList.length > 0){
+ array = true;
+ }
+ if ( key==="0"){
+ var newKey = lableList.pop();
+
+ if($scope.dataOrderInfo){
+
+ var labelObject = {"label" : newKey, "level" : baseLevel, "array" : array};
+ //save it to the list
+ $scope.layOutOnlyLableList.push(labelObject);
+
+ }else {
+ //call label layout
+ $scope.labelLayout(baseLevel, newKey, array );
+ }
+
+ if (array){
+ label = baseLevel + newKey + '@0.';
+ } else {
+ label = baseLevel + newKey + '.';
+ }
+ }
+ deconstructJSON(layOutData[key] , label, key);
+ } else {
+ var attirbuteLabel = label;
+ var defaultValue='';
+ var isRequired = false;
+ if (layOutData[key].includes('defaultValue-')){
+ defaultValue = layOutData[key].split('defaultValue-')[1];
+ }
- if (key==="0"){
- array = true;
- attributekey = lableList.pop();
- attirbuteLabel = baseLevel;
- } else {
- attributekey = key.split();
- }
-
- if (layOutData[key].includes('required-true')){
- isRequired = true;
- }
-
- var subAttributes = $scope.optimizationModelData.sub_attributes;
-
- if(subAttributes){
- var jsonObject = JSON.parse(subAttributes);
- var allkeys = Object.keys(jsonObject);
- if(allkeys){
- for (var k = 0; k < allkeys.length; k++) {
- var keyValue = allkeys[k];
- console.log(" keyValue:jsonObject["+keyValue+ "]: " + jsonObject[keyValue]);
- if(jsonObject[keyValue]){
- var tempObject = jsonObject[keyValue];
- if(tempObject && tempObject[key]){
- if (tempObject[key].includes('required-true')){
- isRequired = true;
- }
- }
- }
- }
- }
- }
-
- var elementObject = {};
- switch (layOutData[key].split(splitcolon)[0]){
-
- case stringValue:
- case string:
- if($scope.dataOrderInfo){
- elementOrderNum++;
- elementObject = {"id": elementOrderNum,"attributekey" : attributekey, "array": array, "attirbuteLabel" : attirbuteLabel, "defaultValue": defaultValue, "isRequired": isRequired, "type":"text"};
- $scope.layOutElementList.push(elementObject);
- }else{
- $scope.attributeBox(attributekey, array, attirbuteLabel, defaultValue, isRequired, "text");
- }
- break;
- case intValue:
- case integerValue:
- if($scope.dataOrderInfo){
- elementOrderNum++;
- elementObject = {"id": elementOrderNum,"attributekey" : attributekey, "array": array, "attirbuteLabel" : attirbuteLabel, "defaultValue": defaultValue,"isRequired": isRequired, "type":"number"};
- $scope.layOutElementList.push(elementObject);
- }else{
- $scope.attributeBox(attributekey, array, attirbuteLabel, defaultValue, isRequired, "number");
- }
- break;
- case double:
- if($scope.dataOrderInfo){
- elementOrderNum++;
- elementObject = {"id": elementOrderNum,"attributekey" : attributekey, "array": array, "attirbuteLabel" : attirbuteLabel, "defaultValue": defaultValue,"isRequired": isRequired, "type":"double"};
- $scope.layOutElementList.push(elementObject);
- }else{
- $scope.attributeBox(attributekey, array, attirbuteLabel, defaultValue, isRequired, "double");
- }
- break;
- case boolean:
- if($scope.dataOrderInfo){
- elementOrderNum++;
- elementObject = {"id": elementOrderNum,"attributekey" : attributekey, "array": array, "attirbuteLabel" : attirbuteLabel, "defaultValue": layOutData[key], "list": getBooleanList, "isRequired": isRequired, "type":"dropBox"};
- $scope.layOutElementList.push(elementObject);
- }else{
- $scope.dropBoxLayout(attirbuteLabel, attributekey, array, layOutData[key], getBooleanList());
- }
- break;
- default:
- if (layOutData[key].includes('dictionary-')){
- var list = getDictionary(layOutData[key].split('dictionary-')[1]);
- }else{
- //--- get dropdown values from enumValues
- var list = getList(layOutData[key]);
- }
- if (list.length===0){ //not dropdown element
- if($scope.dataOrderInfo){
- elementOrderNum++;
- elementObject = {"id": elementOrderNum,"attributekey" : attributekey, "array": array, "attirbuteLabel" : attirbuteLabel, "defaultValue": defaultValue,"isRequired": isRequired, "type":"text"};
- $scope.layOutElementList.push(elementObject);
-
- }else{
- $scope.attributeBox(attributekey, array, attirbuteLabel, defaultValue, isRequired, "text");
- }
- }else{
- if($scope.dataOrderInfo){
- elementOrderNum++;
- elementObject = {"id": elementOrderNum, "attributekey" : attributekey, "array": array, "attirbuteLabel" : attirbuteLabel, "defaultValue": layOutData[key],"isRequired": isRequired, "list":list, "type":"dropBox"};
- $scope.layOutElementList.push(elementObject);
- }else{
- $scope.dropBoxLayout(attirbuteLabel, attributekey, array, layOutData[key], list, isRequired);
- }
- }
- break;
- }
- }
- }
- }
+ if (key==="0"){
+ array = true;
+ attributekey = lableList.pop();
+ attirbuteLabel = baseLevel;
+ } else {
+ attributekey = key.split();
+ }
+
+ if (layOutData[key].includes('required-true')){
+ isRequired = true;
+ }
+
+ var subAttributes = $scope.optimizationModelData.sub_attributes;
+
+ if(subAttributes){
+ var jsonObject = JSON.parse(subAttributes);
+ var allkeys = Object.keys(jsonObject);
+ if(allkeys){
+ for (var k = 0; k < allkeys.length; k++) {
+ var keyValue = allkeys[k];
+ if(jsonObject[keyValue]){
+ var tempObject = jsonObject[keyValue];
+ if(tempObject && tempObject[key]){
+ if (tempObject[key].includes('required-true')){
+ isRequired = true;
+ }
+ }
+ }
+ }
+ }
+ }
+
+ var elementObject = {};
+ switch (layOutData[key].split(splitcolon)[0]){
+
+ case stringValue:
+ case string:
+ if($scope.dataOrderInfo){
+ elementOrderNum++;
+ elementObject = {"id": elementOrderNum,"attributekey" : attributekey, "array": array, "attirbuteLabel" : attirbuteLabel, "defaultValue": defaultValue, "isRequired": isRequired, "type":"text"};
+ $scope.layOutElementList.push(elementObject);
+ }else{
+ $scope.attributeBox(attributekey, array, attirbuteLabel, defaultValue, isRequired, "text");
+ }
+ break;
+ case intValue:
+ case integerValue:
+ if($scope.dataOrderInfo){
+ elementOrderNum++;
+ elementObject = {"id": elementOrderNum,"attributekey" : attributekey, "array": array, "attirbuteLabel" : attirbuteLabel, "defaultValue": defaultValue,"isRequired": isRequired, "type":"number"};
+ $scope.layOutElementList.push(elementObject);
+ }else{
+ $scope.attributeBox(attributekey, array, attirbuteLabel, defaultValue, isRequired, "number");
+ }
+ break;
+ case double:
+ if($scope.dataOrderInfo){
+ elementOrderNum++;
+ elementObject = {"id": elementOrderNum,"attributekey" : attributekey, "array": array, "attirbuteLabel" : attirbuteLabel, "defaultValue": defaultValue,"isRequired": isRequired, "type":"double"};
+ $scope.layOutElementList.push(elementObject);
+ }else{
+ $scope.attributeBox(attributekey, array, attirbuteLabel, defaultValue, isRequired, "double");
+ }
+ break;
+ case boolean:
+ if($scope.dataOrderInfo){
+ elementOrderNum++;
+ elementObject = {"id": elementOrderNum,"attributekey" : attributekey, "array": array, "attirbuteLabel" : attirbuteLabel, "defaultValue": layOutData[key], "list": getBooleanList, "isRequired": isRequired, "type":"dropBox"};
+ $scope.layOutElementList.push(elementObject);
+ }else{
+ $scope.dropBoxLayout(attirbuteLabel, attributekey, array, layOutData[key], getBooleanList());
+ }
+ break;
+ default:
+ if (layOutData[key].includes('dictionary-')){
+ var list = getDictionary(layOutData[key].split('dictionary-')[1]);
+ }else{
+ //--- get dropdown values from enumValues
+ var list = getList(layOutData[key]);
+ }
+ if (list.length===0){ //not dropdown element
+ if($scope.dataOrderInfo){
+ elementOrderNum++;
+ elementObject = {"id": elementOrderNum,"attributekey" : attributekey, "array": array, "attirbuteLabel" : attirbuteLabel, "defaultValue": defaultValue,"isRequired": isRequired, "type":"text"};
+ $scope.layOutElementList.push(elementObject);
+
+ }else{
+ $scope.attributeBox(attributekey, array, attirbuteLabel, defaultValue, isRequired, "text");
+ }
+ }else{
+ if($scope.dataOrderInfo){
+ elementOrderNum++;
+ elementObject = {"id": elementOrderNum, "attributekey" : attributekey, "array": array, "attirbuteLabel" : attirbuteLabel, "defaultValue": layOutData[key],"isRequired": isRequired, "list":list, "type":"dropBox"};
+ $scope.layOutElementList.push(elementObject);
+ }else{
+ $scope.dropBoxLayout(attirbuteLabel, attributekey, array, layOutData[key], list, isRequired);
+ }
+ }
+ break;
+ }
+ }
+ }
+ }
$scope.validContionalRequired = function(parentId) {
- console.log("ng-blur event: parentId : " + parentId);
var c = document.getElementById(parentId).children;
var i;
var hasValue = false;
for (i = 0; i < c.length; i++) {
- if(c[i].getAttribute("data-conditional")){
- console.log(c[i].getAttribute("data-conditional"));
- console.log(c[i].value);
- if(c[i].value != null && c[i].value.trim() != ""){
- hasValue = true;
- }
- }
+ if(c[i].getAttribute("data-conditional")){
+ if(c[i].value != null && c[i].value.trim() != ""){
+ hasValue = true;
+ }
+ }
}
- for (i = 0; i < c.length; i++) {
- if(c[i].getAttribute("data-conditional")){
- if(hasValue){
- c[i].setAttribute("required", true);
- }else{
- c[i].removeAttribute("required");
- }
- }
- }
+ for (i = 0; i < c.length; i++) {
+ if(c[i].getAttribute("data-conditional")){
+ if(hasValue){
+ c[i].setAttribute("required", true);
+ }else{
+ c[i].removeAttribute("required");
+ }
+ }
+ }
}
-
+
$scope.jsonLayout = function(layOutData){
-
+
deconstructJSON(layOutData , "", "");
-
- var orderValue = $scope.dataOrderInfo;
- var layOutElementList = $scope.layOutElementList;
- var labelList = $scope.layOutOnlyLableList;
-
- //reset to default
- elementOrderNum = 0;
- $scope.layOutElementList = [];
- $scope.layOutOnlyLableList = [];
-
- // Only layout in order if order info provided
- if(orderValue){
-
- if(orderValue.includes("[")){
- orderValue = orderValue.replace("[", "") ;
- orderValue = orderValue.replace("]", "") ;
- }
-
- orderValue = orderValue.split(',') ;
-
- for (i = 0; i < orderValue.length; i++) {
- console.log("orderValue["+i+"]"+ orderValue[i]);
- var key = orderValue[i].trim();
-
- //--- Create labels first {"label" : newKey, "level" : baseLevel, "array" : array};
- if(labelList){
- for (k = 0; k < labelList.length; k++){
-
- var label = labelList[k].label.toString().trim();
- var level = labelList[k].level.toString().trim();
- var array = labelList[k].array;
-
- if(key == label){
- $scope.labelLayout(level, label, array);
- //in case to have duplicate label names
- labelList[k].label = "*processed*";
- break;
- }
- }
- }
- //--- then layout each element based on its order defined in YAML file
- for (j = 0; j < layOutElementList.length; j++) {
-
- var attributekey = layOutElementList[j].attributekey.toString().trim();
-
- if(key == attributekey){
-
- var attirbuteLabel = layOutElementList[j].attirbuteLabel.toString().trim();
- var defaultValue = layOutElementList[j].defaultValue.toString().trim();
- var isRequired = layOutElementList[j].isRequired;
-
- console.log("layOutElementList[" +j+ "]: id:" + layOutElementList[j].id + ", attributekey:"+ layOutElementList[j].attributekey + ", attirbuteLabel:" + layOutElementList[j].attirbuteLabel);
-
- if (layOutElementList[j].type == "dropBox"){
- $scope.dropBoxLayout(attirbuteLabel, attributekey, layOutElementList[j].array, defaultValue, layOutElementList[j].list, isRequired);
-
- }else{
- $scope.attributeBox(attributekey, layOutElementList[j].array, attirbuteLabel, defaultValue, isRequired, layOutElementList[j].type);
-
- }
-
- //in case to have duplicate attribute names
- layOutElementList[j].attributekey = "*processed*";
- break;
- }
-
- }
-
- }
- }
+
+ var orderValue = $scope.dataOrderInfo;
+ var layOutElementList = $scope.layOutElementList;
+ var labelList = $scope.layOutOnlyLableList;
+
+ //reset to default
+ elementOrderNum = 0;
+ $scope.layOutElementList = [];
+ $scope.layOutOnlyLableList = [];
+
+ // Only layout in order if order info provided
+ if(orderValue){
+
+ if(orderValue.includes("[")){
+ orderValue = orderValue.replace("[", "") ;
+ orderValue = orderValue.replace("]", "") ;
+ }
+
+ orderValue = orderValue.split(',') ;
+
+ for (i = 0; i < orderValue.length; i++) {
+ var key = orderValue[i].trim();
+
+ //--- Create labels first {"label" : newKey, "level" : baseLevel, "array" : array};
+ if(labelList){
+ for (k = 0; k < labelList.length; k++){
+
+ var label = labelList[k].label.toString().trim();
+ var level = labelList[k].level.toString().trim();
+ var array = labelList[k].array;
+
+ if(key == label){
+ $scope.labelLayout(level, label, array);
+ //in case to have duplicate label names
+ labelList[k].label = "*processed*";
+ break;
+ }
+ }
+ }
+ //--- then layout each element based on its order defined in YAML file
+ for (j = 0; j < layOutElementList.length; j++) {
+
+ var attributekey = layOutElementList[j].attributekey.toString().trim();
+
+ if(key == attributekey){
+
+ var attirbuteLabel = layOutElementList[j].attirbuteLabel.toString().trim();
+ var defaultValue = layOutElementList[j].defaultValue.toString().trim();
+ var isRequired = layOutElementList[j].isRequired;
+
+
+ if (layOutElementList[j].type == "dropBox"){
+ $scope.dropBoxLayout(attirbuteLabel, attributekey, layOutElementList[j].array, defaultValue, layOutElementList[j].list, isRequired);
+
+ }else{
+ $scope.attributeBox(attributekey, layOutElementList[j].array, attirbuteLabel, defaultValue, isRequired, layOutElementList[j].type);
+
+ }
+
+ //in case to have duplicate attribute names
+ layOutElementList[j].attributekey = "*processed*";
+ break;
+ }
+
+ }
+
+ }
+ }
}
$scope.attributeBox = function(attibuteKey, attributeManyKey, labelValue, defaultValue, isRequired, dataType ){
- $scope.temp.policy.ruleGridData.push(attibuteKey);
- var br = document.createElement("BR");
-
- var label = document.createElement("Label");
- var labeltext = null;
- var requiredLabName = "";
- if (matching.includes(attibuteKey)){
- labeltext = document.createTextNode(attibuteKey + "*!");
- isRequired = true; //set required as true for matching element
- }else {
- if(isRequired){
- requiredLabName = attibuteKey + " * ";
- labeltext = document.createTextNode(requiredLabName);
- }else{
- labeltext = document.createTextNode(attibuteKey);
- }
- }
+ $scope.temp.policy.ruleGridData.push(attibuteKey);
+ var br = document.createElement("BR");
+
+ var label = document.createElement("Label");
+ var labeltext = null;
+ var requiredLabName = "";
+ if (matching.includes(attibuteKey)){
+ labeltext = document.createTextNode(attibuteKey + "*!");
+ isRequired = true; //set required as true for matching element
+ }else {
+ if(isRequired){
+ requiredLabName = attibuteKey + " * ";
+ labeltext = document.createTextNode(requiredLabName);
+ }else{
+ labeltext = document.createTextNode(attibuteKey);
+ }
+ }
-
- var divID = labelValue;
-
- if (labelValue.length < 1){
- divID = "DynamicTemplate";
- }else if (labelValue.endsWith('.')){
- var divID = 'div.'+ labelValue.substring(0, labelValue.length-1);
- }
-
- label.appendChild(labeltext);
-
- var textField = document.createElement("INPUT");
-
- textField.setAttribute("class" , "form-control");
- if(dataType){
- if(dataType == "double"){
- textField.setAttribute("type" , "number");
- textField.setAttribute("step" , "any");
- }else{
- textField.setAttribute("type" , dataType);
- }
- }
- textField.setAttribute("style" , "width:300px;");
- textField.setAttribute("ng-disabled" , "temp.policy.readOnly");
- var checkKey;
- var id = "";
- if(attributeManyKey){
- checkKey = labelValue + attibuteKey+'@0';
- textField.setAttribute("id" , ''+labelValue + attibuteKey+'@0'+'');
- var divTag = document.createElement("div");
- divTag.setAttribute("id", "div."+ labelValue +attibuteKey);
- var addButton = document.createElement("BUTTON");
- var buttonaddLabel = document.createTextNode("+");
- addButton.appendChild(buttonaddLabel);
- addButton.setAttribute("id", labelValue + attibuteKey);
- addButton.setAttribute("class", "btn btn-add-remove");
- addButton.setAttribute("ng-click" , 'addNewChoice("'+labelValue + attibuteKey+'");');
- addButton.setAttribute("ng-disabled" , "temp.policy.readOnly");
- var removeButton = document.createElement("BUTTON");
- var buttonremoveLabel = document.createTextNode("-");
- removeButton.appendChild(buttonremoveLabel);
- removeButton.setAttribute("class", "btn btn-add-remove");
- removeButton.setAttribute("ng-click" , 'removeChoice("'+labelValue + attibuteKey+'");');
- removeButton.setAttribute("ng-disabled" , "temp.policy.readOnly");
- document.getElementById(divID).appendChild(addButton);
- document.getElementById(divID).appendChild(removeButton);
- document.getElementById(divID).appendChild(label);
- id = "div."+labelValue+attibuteKey;
- divTag.setAttribute("id", id);
- document.getElementById(divID).appendChild(divTag);
- textField.className += ' first_child';
- if(isRequired){
- textField.setAttribute("required", "true");
- }
- divTag.appendChild(textField);
- document.getElementById(divID).appendChild(divTag);
-
- }else{
- checkKey = labelValue + attibuteKey;
- textField.setAttribute("id" , ''+labelValue +attibuteKey+'');
- if(document.getElementById(divID).hasAttribute('required') || !document.getElementById(divID).hasAttribute('data-conditional')){
- if(requiredLabName.includes("*") || isRequired){
- textField.setAttribute("required", "true");
- }
- }else if (document.getElementById(divID).hasAttribute('data-conditional')){
- if(requiredLabName.includes("*")){
- var requiredNode = document.createElement('span');
- requiredNode.setAttribute("class", "mstooltip");
- requiredNode.textContent = "?";
- label.appendChild(requiredNode);
-
- var requiredNodeToolTip = document.createElement('span');
- requiredNodeToolTip.setAttribute("class", "tooltiptext");
- requiredNodeToolTip.textContent = "Conditional Required";
- requiredNode.appendChild(requiredNodeToolTip);
-
- textField.setAttribute("data-conditional", divID);
- textField.setAttribute("ng-blur", "validContionalRequired('"+divID+"')");
- }
- }
-
- document.getElementById(divID).appendChild(label);
- document.getElementById(divID).appendChild(textField);
- document.getElementById(divID).appendChild(br);
-
- }
+
+ var divID = labelValue;
+
+ if (labelValue.length < 1){
+ divID = "DynamicTemplate";
+ }else if (labelValue.endsWith('.')){
+ var divID = 'div.'+ labelValue.substring(0, labelValue.length-1);
+ }
+
+ label.appendChild(labeltext);
+
+ var textField = document.createElement("INPUT");
+
+ textField.setAttribute("class" , "form-control");
+ if(dataType){
+ if(dataType == "double"){
+ textField.setAttribute("type" , "number");
+ textField.setAttribute("step" , "any");
+ }else{
+ textField.setAttribute("type" , dataType);
+ }
+ }
+ textField.setAttribute("style" , "width:300px;");
+ textField.setAttribute("ng-disabled" , "temp.policy.readOnly");
+ var checkKey;
+ var id = "";
+ if(attributeManyKey){
+ checkKey = labelValue + attibuteKey+'@0';
+ textField.setAttribute("id" , ''+labelValue + attibuteKey+'@0'+'');
+ var divTag = document.createElement("div");
+ divTag.setAttribute("id", "div."+ labelValue +attibuteKey);
+ var addButton = document.createElement("BUTTON");
+ var buttonaddLabel = document.createTextNode("+");
+ addButton.appendChild(buttonaddLabel);
+ addButton.setAttribute("id", labelValue + attibuteKey);
+ addButton.setAttribute("class", "btn btn-add-remove");
+ addButton.setAttribute("ng-click" , 'addNewChoice("'+labelValue + attibuteKey+'");');
+ addButton.setAttribute("ng-disabled" , "temp.policy.readOnly");
+ var removeButton = document.createElement("BUTTON");
+ var buttonremoveLabel = document.createTextNode("-");
+ removeButton.appendChild(buttonremoveLabel);
+ removeButton.setAttribute("class", "btn btn-add-remove");
+ removeButton.setAttribute("ng-click" , 'removeChoice("'+labelValue + attibuteKey+'");');
+ removeButton.setAttribute("ng-disabled" , "temp.policy.readOnly");
+ document.getElementById(divID).appendChild(addButton);
+ document.getElementById(divID).appendChild(removeButton);
+ document.getElementById(divID).appendChild(label);
+ id = "div."+labelValue+attibuteKey;
+ divTag.setAttribute("id", id);
+ document.getElementById(divID).appendChild(divTag);
+ textField.className += ' first_child';
+ if(isRequired){
+ textField.setAttribute("required", "true");
+ }
+ divTag.appendChild(textField);
+ document.getElementById(divID).appendChild(divTag);
+
+ }else{
+ checkKey = labelValue + attibuteKey;
+ textField.setAttribute("id" , ''+labelValue +attibuteKey+'');
+ if(document.getElementById(divID).hasAttribute('required') || !document.getElementById(divID).hasAttribute('data-conditional')){
+ if(requiredLabName.includes("*") || isRequired){
+ textField.setAttribute("required", "true");
+ }
+ }else if (document.getElementById(divID).hasAttribute('data-conditional')){
+ if(requiredLabName.includes("*")){
+ var requiredNode = document.createElement('span');
+ requiredNode.setAttribute("class", "mstooltip");
+ requiredNode.textContent = "?";
+ label.appendChild(requiredNode);
+
+ var requiredNodeToolTip = document.createElement('span');
+ requiredNodeToolTip.setAttribute("class", "tooltiptext");
+ requiredNodeToolTip.textContent = "Conditional Required";
+ requiredNode.appendChild(requiredNodeToolTip);
+
+ textField.setAttribute("data-conditional", divID);
+ textField.setAttribute("ng-blur", "validContionalRequired('"+divID+"')");
+ }
+ }
+
+ document.getElementById(divID).appendChild(label);
+ document.getElementById(divID).appendChild(textField);
+ document.getElementById(divID).appendChild(br);
+
+ }
- if(divID.includes("@0") && divID.includes("div.")){
- var firstChild_Id = divID.split("@0")[0];
- var firstChild_element = document.getElementById(firstChild_Id);
- if(firstChild_element){
- firstChild_element.className += ' children_group'; //here is a div with a group of children.
- }
- }
- console.log('firstChild_Id: ' + firstChild_Id);
- console.log('divID: ' + divID);
-
- if (defaultValue.length > 0){
- if(defaultValue.includes(":")){
- defaultValue = defaultValue.split(":")[0];
- if(defaultValue === "NA") {
- defaultValue = "";
- }
- }
- if(defaultValue != "undefined" && defaultValue != undefined && defaultValue != "null"){
- document.getElementById(checkKey).value = defaultValue;
- }
- }
-
- if($scope.temp.policy.ruleData != null){
- if (attributeManyKey){
- var newCheckKey = checkKey.replace(attibuteKey + '@0',attibuteKey);
- if($scope.temp.policy.ruleData[newCheckKey +'@0'] != undefined && $scope.temp.policy.ruleData[newCheckKey +'@0'] != "undefined"){
- document.getElementById(newCheckKey +'@0').value = $scope.temp.policy.ruleData[newCheckKey +'@0'];
- }
- }else{
- if($scope.temp.policy.ruleData[checkKey] != undefined && $scope.temp.policy.ruleData[checkKey] != "undefined"){
- document.getElementById(checkKey).value = $scope.temp.policy.ruleData[checkKey];
- }
- }
- }
- plainAttributeKeys.push(labelValue + attibuteKey+'*'+attributeManyKey);
+ if(divID.includes("@0") && divID.includes("div.")){
+ var firstChild_Id = divID.split("@0")[0];
+ var firstChild_element = document.getElementById(firstChild_Id);
+ if(firstChild_element){
+ firstChild_element.className += ' children_group'; //here is a div with a group of children.
+ }
+ }
+
+ if (defaultValue.length > 0){
+ if(defaultValue.includes(":")){
+ defaultValue = defaultValue.split(":")[0];
+ if(defaultValue === "NA") {
+ defaultValue = "";
+ }
+ }
+ if(defaultValue != "undefined" && defaultValue != undefined && defaultValue != "null"){
+ document.getElementById(checkKey).value = defaultValue;
+ }
+ }
+
+ if($scope.temp.policy.ruleData != null){
+ if (attributeManyKey){
+ var newCheckKey = checkKey.replace(attibuteKey + '@0',attibuteKey);
+ if($scope.temp.policy.ruleData[newCheckKey +'@0'] != undefined && $scope.temp.policy.ruleData[newCheckKey +'@0'] != "undefined"){
+ document.getElementById(newCheckKey +'@0').value = $scope.temp.policy.ruleData[newCheckKey +'@0'];
+ }
+ }else{
+ if($scope.temp.policy.ruleData[checkKey] != undefined && $scope.temp.policy.ruleData[checkKey] != "undefined"){
+ document.getElementById(checkKey).value = $scope.temp.policy.ruleData[checkKey];
+ }
+ }
+ }
+ plainAttributeKeys.push(labelValue + attibuteKey+'*'+attributeManyKey);
};
$scope.labelManyKeys = [];
$scope.labelLayout = function(labelValue, lableName, labelManyKey ){
- var label = document.createElement("Label")
- var divID = labelValue;
- if (labelValue.endsWith('.')){
- var workingLabel = labelValue.substring(0, labelValue.length-1);
- }else {
- var workingLabel = labelValue;
- }
-
- if (labelValue.length < 1){
- divID = "DynamicTemplate";
- } else if (labelValue.endsWith('.')){
- var divID = 'div.'+ labelValue.substring(0, labelValue.length-1);
- }
-
- var subAttributes = $scope.optimizationModelData.subattributes;
- var jsonObject = JSON.parse(subAttributes);
- var lablInfo = findVal(jsonObject, lableName);
- console.log("findValue : " + lableName +": "+ lablInfo);
- var star = "";
- var required = null;
- if(lablInfo){
- if(lablInfo.includes("required-true")){
- star = " *";
- required = true;
- }else if (lablInfo.includes("required-false")){
- required = false
- }
- }
-
- var labeltext = document.createTextNode(lableName + star);
-
- label.appendChild(labeltext);
+ var label = document.createElement("Label")
+ var divID = labelValue;
+ if (labelValue.endsWith('.')){
+ var workingLabel = labelValue.substring(0, labelValue.length-1);
+ }else {
+ var workingLabel = labelValue;
+ }
+
+ if (labelValue.length < 1){
+ divID = "DynamicTemplate";
+ } else if (labelValue.endsWith('.')){
+ var divID = 'div.'+ labelValue.substring(0, labelValue.length-1);
+ }
+
+ var subAttributes = $scope.optimizationModelData.subattributes;
+ var jsonObject = JSON.parse(subAttributes);
+ var lablInfo = findVal(jsonObject, lableName);
+ var star = "";
+ var required = null;
+ if(lablInfo){
+ if(lablInfo.includes("required-true")){
+ star = " *";
+ required = true;
+ }else if (lablInfo.includes("required-false")){
+ required = false
+ }
+ }
+
+ var labeltext = document.createTextNode(lableName + star);
+
+ label.appendChild(labeltext);
- if(labelManyKey){
- var addButton = document.createElement("BUTTON");
- var buttonLabel = document.createTextNode("+");
- addButton.appendChild(buttonLabel);
- addButton.setAttribute("class", "btn btn-add-remove");
- addButton.setAttribute("ng-click" , 'addNewChoice("'+labelValue + lableName+'");');
- addButton.setAttribute("ng-disabled" , "temp.policy.readOnly");
- var removeButton = document.createElement("BUTTON");
- var buttonremoveLabel = document.createTextNode("-");
- removeButton.appendChild(buttonremoveLabel);
- removeButton.setAttribute("class", "btn btn-add-remove");
- removeButton.setAttribute("ng-click" , 'removeChoice("'+labelValue +lableName+'");');
- removeButton.setAttribute("ng-disabled" , "temp.policy.readOnly");
- document.getElementById(divID).appendChild(addButton);
- document.getElementById(divID).appendChild(removeButton);
- document.getElementById(divID).appendChild(label);
- var id = "div."+labelValue+lableName;
- var divTag = document.createElement("div");
- divTag.setAttribute("id", id);
- document.getElementById(divID).appendChild(divTag);
-
- var divTag = document.createElement("div");
- divTag.setAttribute("id", id +'@0');
-
- divTag.className += ' children_group'; //here is div with a group of children.
-
- if(required){
- divTag.setAttribute("required", required);
- }else if(required == false){
- divTag.setAttribute("data-conditional", "yes");
- }
-
- document.getElementById(id).appendChild(divTag);
-
- $scope.labelManyKeys.push(lableName);
-
- }else{
- var divTag = document.createElement("div");
- divTag.setAttribute("id", "div."+labelValue+lableName);
- divTag.className += ' children_group'; //here is div with a group of children.
- if(required){
- divTag.setAttribute("required", required);
- }else if(required == false){
- divTag.setAttribute("data-conditional", "yes");
- }
- document.getElementById(divID).appendChild(label);
- document.getElementById(divID).appendChild(divTag);
- }
+ if(labelManyKey){
+ var addButton = document.createElement("BUTTON");
+ var buttonLabel = document.createTextNode("+");
+ addButton.appendChild(buttonLabel);
+ addButton.setAttribute("class", "btn btn-add-remove");
+ addButton.setAttribute("ng-click" , 'addNewChoice("'+labelValue + lableName+'");');
+ addButton.setAttribute("ng-disabled" , "temp.policy.readOnly");
+ var removeButton = document.createElement("BUTTON");
+ var buttonremoveLabel = document.createTextNode("-");
+ removeButton.appendChild(buttonremoveLabel);
+ removeButton.setAttribute("class", "btn btn-add-remove");
+ removeButton.setAttribute("ng-click" , 'removeChoice("'+labelValue +lableName+'");');
+ removeButton.setAttribute("ng-disabled" , "temp.policy.readOnly");
+ document.getElementById(divID).appendChild(addButton);
+ document.getElementById(divID).appendChild(removeButton);
+ document.getElementById(divID).appendChild(label);
+ var id = "div."+labelValue+lableName;
+ var divTag = document.createElement("div");
+ divTag.setAttribute("id", id);
+ document.getElementById(divID).appendChild(divTag);
+
+ var divTag = document.createElement("div");
+ divTag.setAttribute("id", id +'@0');
+
+ divTag.className += ' children_group'; //here is div with a group of children.
+
+ if(required){
+ divTag.setAttribute("required", required);
+ }else if(required == false){
+ divTag.setAttribute("data-conditional", "yes");
+ }
+
+ document.getElementById(id).appendChild(divTag);
+
+ $scope.labelManyKeys.push(lableName);
+
+ }else{
+ var divTag = document.createElement("div");
+ divTag.setAttribute("id", "div."+labelValue+lableName);
+ divTag.className += ' children_group'; //here is div with a group of children.
+ if(required){
+ divTag.setAttribute("required", required);
+ }else if(required == false){
+ divTag.setAttribute("data-conditional", "yes");
+ }
+ document.getElementById(divID).appendChild(label);
+ document.getElementById(divID).appendChild(divTag);
+ }
};
$scope.dropBoxLayout = function(labelLevel, attributeName, many , refValue, listemunerateValues, isRequired){
- var br = document.createElement("BR");
-
- if (labelLevel.length < 1){
- var divID = "DynamicTemplate";
- } else if (labelLevel.endsWith('.')){
- var divID = 'div.'+ labelLevel.substring(0, labelLevel.length-1);
- }
-
-
- var label = document.createElement("Label")
-
- var refAttributes = $scope.optimizationModelData.ref_attributes;
- if(isRequired != true && refAttributes){ //check refAttributes also
- var refAttributesList = refAttributes.split(splitComma);
- for (k = 0; k < refAttributesList.length; k++){
- var refAttribute = refAttributesList[k].split(splitEqual);
- if (attributeName == refAttribute[0].trim() && refAttribute[1].includes("required-true")){
- isRequired = true;
- }
- }
- }
-
- if (matching.includes(attributeName)){
- var labeltext = document.createTextNode(attributeName + "*!");
- label.appendChild(labeltext);
- isRequired = true; //set required as true for matching element
- }else {
- var labeltext = document.createTextNode(attributeName);
- if(isRequired){
- var requiredLabName = attributeName+ " * ";
- labeltext = document.createTextNode(requiredLabName);
- }else{
- labeltext = document.createTextNode(attributeName);
- }
-
- label.appendChild(labeltext);
- }
- label.appendChild(labeltext);
- // if this field is required, but its parent is not required
- if(isRequired && document.getElementById(divID).hasAttribute('data-conditional')){
- var requiredNode = document.createElement('span');
- requiredNode.setAttribute("class", "mstooltip");
- requiredNode.textContent = "?";
- label.appendChild(requiredNode);
-
- var requiredNodeToolTip = document.createElement('span');
- requiredNodeToolTip.setAttribute("class", "tooltiptext");
- requiredNodeToolTip.textContent = "Conditional Required";
- requiredNode.appendChild(requiredNodeToolTip);
+ var br = document.createElement("BR");
+
+ if (labelLevel.length < 1){
+ var divID = "DynamicTemplate";
+ } else if (labelLevel.endsWith('.')){
+ var divID = 'div.'+ labelLevel.substring(0, labelLevel.length-1);
+ }
+
+
+ var label = document.createElement("Label")
+
+ var refAttributes = $scope.optimizationModelData.ref_attributes;
+ if(isRequired != true && refAttributes){ //check refAttributes also
+ var refAttributesList = refAttributes.split(splitComma);
+ for (k = 0; k < refAttributesList.length; k++){
+ var refAttribute = refAttributesList[k].split(splitEqual);
+ if (attributeName == refAttribute[0].trim() && refAttribute[1].includes("required-true")){
+ isRequired = true;
+ }
+ }
+ }
+
+ if (matching.includes(attributeName)){
+ var labeltext = document.createTextNode(attributeName + "*!");
+ label.appendChild(labeltext);
+ isRequired = true; //set required as true for matching element
+ }else {
+ var labeltext = document.createTextNode(attributeName);
+ if(isRequired){
+ var requiredLabName = attributeName+ " * ";
+ labeltext = document.createTextNode(requiredLabName);
+ }else{
+ labeltext = document.createTextNode(attributeName);
+ }
+
+ label.appendChild(labeltext);
+ }
+ label.appendChild(labeltext);
+ // if this field is required, but its parent is not required
+ if(isRequired && document.getElementById(divID).hasAttribute('data-conditional')){
+ var requiredNode = document.createElement('span');
+ requiredNode.setAttribute("class", "mstooltip");
+ requiredNode.textContent = "?";
+ label.appendChild(requiredNode);
+
+ var requiredNodeToolTip = document.createElement('span');
+ requiredNodeToolTip.setAttribute("class", "tooltiptext");
+ requiredNodeToolTip.textContent = "Conditional Required";
+ requiredNode.appendChild(requiredNodeToolTip);
- }
-
- var listField = document.createElement("SELECT");
- listField.setAttribute("class" , "form-control");
- listField.setAttribute("style" , "width:300px;");
- listField.setAttribute("ng-disabled" , "temp.policy.readOnly");
-
- if(isRequired){
- if(document.getElementById(divID).hasAttribute('data-conditional')){
- listField.setAttribute("data-conditional", divID);
- listField.setAttribute("ng-blur", "validContionalRequired('"+divID+"')");
- }else{
- listField.setAttribute("required", true);
- }
- }
- if( many != true || isRequired != true){ // add an empty option for not required or not multiple select element
- var optionFirst = document.createElement('option');
- optionFirst.setAttribute('value', "");
- listField.appendChild(optionFirst);
- }
-
- for (var i=0; i < listemunerateValues.length; i += 1) {
- if(typeof listemunerateValues[i] == "string" && listemunerateValues[i].includes("equal-sign")){
- listemunerateValues[i] = listemunerateValues[i].replace('equal-sign','=');
- }
- var option = document.createElement('option');
- option.setAttribute('value', listemunerateValues[i]);
- option.appendChild(document.createTextNode(listemunerateValues[i]));
- option.setAttribute('value', listemunerateValues[i]);
- listField.appendChild(option);
- }
- listField.setAttribute("id" , ''+ labelLevel + attributeName + '');
-
- enumKeyList.push(attributeName);
-
- document.getElementById(divID).appendChild(label);
- document.getElementById(divID).appendChild(br);
-
- if(many == true){
- document.getElementById(divID).appendChild(listField).multiple = true;
- plainAttributeKeys.push(labelLevel + attributeName+'*'+true);
- }else {
- document.getElementById(divID).appendChild(listField).multiple = false;
- plainAttributeKeys.push(labelLevel + attributeName+'*'+false);
- }
-
- if($scope.temp.policy.ruleData != null){
- if (many == true){
- document.getElementById(labelLevel +attributeName).options[0].selected = false;
- for (i=0; i < listemunerateValues.length; i += 1) {
- var testValue = $scope.temp.policy.ruleData[labelLevel +attributeName+'@' + i];
- if (testValue === undefined){
- testValue = $scope.temp.policy.ruleData[labelLevel +attributeName];
- }
- var location = listemunerateValues.indexOf(testValue);
- if (location!=-1){
- document.getElementById(labelLevel +attributeName).options[location].selected = true;
- }
- }
- }else {
- if($scope.temp.policy.ruleData[labelLevel + attributeName] != undefined && $scope.temp.policy.ruleData[labelLevel + attributeName] != "undefined"){
- document.getElementById(labelLevel + attributeName).value = $scope.temp.policy.ruleData[labelLevel + attributeName];
- }
- }
- }
- };
+ }
+
+ var listField = document.createElement("SELECT");
+ listField.setAttribute("class" , "form-control");
+ listField.setAttribute("style" , "width:300px;");
+ listField.setAttribute("ng-disabled" , "temp.policy.readOnly");
+
+ if(isRequired){
+ if(document.getElementById(divID).hasAttribute('data-conditional')){
+ listField.setAttribute("data-conditional", divID);
+ listField.setAttribute("ng-blur", "validContionalRequired('"+divID+"')");
+ }else{
+ listField.setAttribute("required", true);
+ }
+ }
+ if( many != true || isRequired != true){ // add an empty option for not required or not multiple select element
+ var optionFirst = document.createElement('option');
+ optionFirst.setAttribute('value', "");
+ listField.appendChild(optionFirst);
+ }
+
+ for (var i=0; i < listemunerateValues.length; i += 1) {
+ if(typeof listemunerateValues[i] == "string" && listemunerateValues[i].includes("equal-sign")){
+ listemunerateValues[i] = listemunerateValues[i].replace('equal-sign','=');
+ }
+ var option = document.createElement('option');
+ option.setAttribute('value', listemunerateValues[i]);
+ option.appendChild(document.createTextNode(listemunerateValues[i]));
+ option.setAttribute('value', listemunerateValues[i]);
+ listField.appendChild(option);
+ }
+ listField.setAttribute("id" , ''+ labelLevel + attributeName + '');
+
+ enumKeyList.push(attributeName);
+
+ document.getElementById(divID).appendChild(label);
+ document.getElementById(divID).appendChild(br);
+
+ if(many == true){
+ document.getElementById(divID).appendChild(listField).multiple = true;
+ plainAttributeKeys.push(labelLevel + attributeName+'*'+true);
+ }else {
+ document.getElementById(divID).appendChild(listField).multiple = false;
+ plainAttributeKeys.push(labelLevel + attributeName+'*'+false);
+ }
+
+ if($scope.temp.policy.ruleData != null){
+ if (many == true){
+ document.getElementById(labelLevel +attributeName).options[0].selected = false;
+ for (i=0; i < listemunerateValues.length; i += 1) {
+ var testValue = $scope.temp.policy.ruleData[labelLevel +attributeName+'@' + i];
+ if (testValue === undefined){
+ testValue = $scope.temp.policy.ruleData[labelLevel +attributeName];
+ }
+ var location = listemunerateValues.indexOf(testValue);
+ if (location!=-1){
+ document.getElementById(labelLevel +attributeName).options[location].selected = true;
+ }
+ }
+ }else {
+ if($scope.temp.policy.ruleData[labelLevel + attributeName] != undefined && $scope.temp.policy.ruleData[labelLevel + attributeName] != "undefined"){
+ document.getElementById(labelLevel + attributeName).value = $scope.temp.policy.ruleData[labelLevel + attributeName];
+ }
+ }
+ }
+ };
function onlyUnique(value, index, self) {
return self.indexOf(value) === index;
};
$scope.savePolicy = function(policy){
- if(policy.itemContent != undefined){
- $scope.refreshCheck = true;
- $scope.policyNavigator = policy.itemContent;
- policy.itemContent = "";
- }
- $scope.savebutton = false;
- var splitAt = '*';
- var dot ='.';
- var jsonPolicy = {};
- if(plainAttributeKeys != null){
- for(a = 0; a < plainAttributeKeys.length; a++){
- var splitPlainAttributeKey = plainAttributeKeys[a].split(splitAt);
- console.log("splitPlainAttributeKey: " + splitPlainAttributeKey);
- var searchElement = document.getElementById(splitPlainAttributeKey[0]);
- var key = splitPlainAttributeKey[0];
-
+ if(policy.itemContent != undefined){
+ $scope.refreshCheck = true;
+ $scope.policyNavigator = policy.itemContent;
+ policy.itemContent = "";
+ }
+ $scope.savebutton = false;
+ var splitAt = '*';
+ var dot ='.';
+ var jsonPolicy = {};
+ if(plainAttributeKeys != null){
+ for(a = 0; a < plainAttributeKeys.length; a++){
+ var splitPlainAttributeKey = plainAttributeKeys[a].split(splitAt);
+ var searchElement = document.getElementById(splitPlainAttributeKey[0]);
+ var key = splitPlainAttributeKey[0];
+
if(searchElement == null || searchElement.nodeName == 'BUTTON'){
searchElement = document.getElementById(splitPlainAttributeKey[0]+'@0');
key = splitPlainAttributeKey[0]+'@0';
}
- if(searchElement != null){
- var keySplit = key.split(dot);
- var elumentLocation = keySplit.length;
- var enumKey = key;
- if (elumentLocation > 1){
- enumKey = keySplit[keySplit.length - 1];
- }
- //check it is undefined or not
- if (enumKeyList != undefined && enumKeyList.indexOf(enumKey) != -1){
- if (splitPlainAttributeKey[1]!= undefined && splitPlainAttributeKey[1].indexOf("true") !== -1){
- var multiSlect = [];
- for ( var i = 0; i < searchElement.selectedOptions.length; i++) {
- multiSlect.push(searchElement.selectedOptions[i].value);
- }
- jsonPolicy[key]= multiSlect;
- }else{
- console.log(" searchElement.value = > " + searchElement.value);
- jsonPolicy[key]= searchElement.value;
- }
- } else {
- if(searchElement.value != null){
- console.log(" searchElement.value = > " + searchElement.value);
- jsonPolicy[key]= searchElement.value;
- }
- }
- }
- }
- }
+ if(searchElement != null){
+ var keySplit = key.split(dot);
+ var elumentLocation = keySplit.length;
+ var enumKey = key;
+ if (elumentLocation > 1){
+ enumKey = keySplit[keySplit.length - 1];
+ }
+ //check it is undefined or not
+ if (enumKeyList != undefined && enumKeyList.indexOf(enumKey) != -1){
+ if (splitPlainAttributeKey[1]!= undefined && splitPlainAttributeKey[1].indexOf("true") !== -1){
+ var multiSlect = [];
+ for ( var i = 0; i < searchElement.selectedOptions.length; i++) {
+ multiSlect.push(searchElement.selectedOptions[i].value);
+ }
+ jsonPolicy[key]= multiSlect;
+ }else{
+ jsonPolicy[key]= searchElement.value;
+ }
+ } else {
+ if(searchElement.value != null){
+ jsonPolicy[key]= searchElement.value;
+ }
+ }
+ }
+ }
+ }
var uuu = "policycreation/save_policy";
var postData={policyData: policy, policyJSON : jsonPolicy};
$.ajax({
@@ -1269,113 +1214,110 @@ angular.module('abs').controller('optimizationController', ['$scope', '$window',
data: JSON.stringify(postData),
success : function(data){
$scope.$apply(function(){
- $scope.data=data.policyData;
- if($scope.data == 'success'){
- $scope.temp.policy.readOnly = 'true';
- $scope.safetyChecker = data.policyData.split("#")[2];
- if ($scope.safetyChecker!=undefined) {
- Notification.success($scope.safetyChecker);
- }
- $scope.pushStatus=data.policyData.split("&")[1];
- if($scope.pushStatus=="successPush"){
- Notification.success("Policy pushed successfully");
- }
- Notification.success("Policy Saved Successfully.");
- }else if ($scope.data == 'PolicyExists'){
- $scope.savebutton = true;
- Notification.error("Policy Already Exists with Same Name in Scope.");
- }
+ $scope.data=data.policyData;
+ if($scope.data == 'success'){
+ $scope.temp.policy.readOnly = 'true';
+ $scope.safetyChecker = data.policyData.split("#")[2];
+ if ($scope.safetyChecker!=undefined) {
+ Notification.success($scope.safetyChecker);
+ }
+ $scope.pushStatus=data.policyData.split("&")[1];
+ if($scope.pushStatus=="successPush"){
+ Notification.success("Policy pushed successfully");
+ }
+ Notification.success("Policy Saved Successfully.");
+ }else if ($scope.data == 'PolicyExists'){
+ $scope.savebutton = true;
+ Notification.error("Policy Already Exists with Same Name in Scope.");
+ }
});
- console.log($scope.data);
},
error : function(data){
- Notification.error("Error Occured while saving Policy.");
+ Notification.error("Error Occured while saving Policy.");
}
});
};
$scope.validatePolicy = function(policy){
- document.getElementById("validate").innerHTML = "";
- var splitAt = '*';
- var dot ='.';
- var jsonPolicy = {};
- if(plainAttributeKeys != null){
- for(a = 0; a < plainAttributeKeys.length; a++){
- var splitPlainAttributeKey = plainAttributeKeys[a].split(splitAt);
- console.log(splitPlainAttributeKey[1]);
- var searchElement = document.getElementById(splitPlainAttributeKey[0]);
- var key = splitPlainAttributeKey[0];
- if(searchElement == null || searchElement.nodeName == 'BUTTON'){
- searchElement = document.getElementById(splitPlainAttributeKey[0]+'@0');
- key = splitPlainAttributeKey[0]+'@0';
- }
- if(searchElement != null){
- if (enumKeyList.indexOf(key) != -1){
- if (splitPlainAttributeKey[1].indexOf("true") !== -1){
- var multiSlect = [];
- for ( var i = 0; i < searchElement.selectedOptions.length; i++) {
- multiSlect.push(searchElement.selectedOptions[i].value);
- }
- jsonPolicy[key]= multiSlect;
- }else{
- jsonPolicy[key]= searchElement.value;
- }
- if(searchElement.getAttribute("required")){
- if(!searchElement.value){
- return;
- }
- }
- } else {
- if(searchElement.value != null){
- jsonPolicy[key]= searchElement.value;
- if(searchElement.getAttribute("required")){
- if(!searchElement.value){
- return;
- }
- }
- }
- }
- }
- }
- }
+ document.getElementById("validate").innerHTML = "";
+ var splitAt = '*';
+ var dot ='.';
+ var jsonPolicy = {};
+ if(plainAttributeKeys != null){
+ for(a = 0; a < plainAttributeKeys.length; a++){
+ var splitPlainAttributeKey = plainAttributeKeys[a].split(splitAt);
+ var searchElement = document.getElementById(splitPlainAttributeKey[0]);
+ var key = splitPlainAttributeKey[0];
+ if(searchElement == null || searchElement.nodeName == 'BUTTON'){
+ searchElement = document.getElementById(splitPlainAttributeKey[0]+'@0');
+ key = splitPlainAttributeKey[0]+'@0';
+ }
+ if(searchElement != null){
+ if (enumKeyList.indexOf(key) != -1){
+ if (splitPlainAttributeKey[1].indexOf("true") !== -1){
+ var multiSlect = [];
+ for ( var i = 0; i < searchElement.selectedOptions.length; i++) {
+ multiSlect.push(searchElement.selectedOptions[i].value);
+ }
+ jsonPolicy[key]= multiSlect;
+ }else{
+ jsonPolicy[key]= searchElement.value;
+ }
+ if(searchElement.getAttribute("required")){
+ if(!searchElement.value){
+ return;
+ }
+ }
+ } else {
+ if(searchElement.value != null){
+ jsonPolicy[key]= searchElement.value;
+ if(searchElement.getAttribute("required")){
+ if(!searchElement.value){
+ return;
+ }
+ }
+ }
+ }
+ }
+ }
+ }
var uuu = "policyController/validate_policy.htm";
var postData={policyData: policy, policyJSON : jsonPolicy};
- $.ajax({
- type : 'POST',
- url : uuu,
- dataType: 'json',
- contentType: 'application/json',
- data: JSON.stringify(postData),
- success : function(data){
- $scope.$apply(function(){
- $scope.validateData = data.data.replace(/\"/g, "");
- $scope.data=data.data.substring(1,8);
- var size = data.data.length;
- if($scope.data == 'success'){
- Notification.success("Validation Success.");
- $scope.savebutton = false;
- if (size > 18){
- var displayWarning = data.data.substring(19,size - 1);
- document.getElementById("validate").innerHTML = "Safe Policy Warning Message : "+displayWarning;
- document.getElementById("validate").style.color = "white";
- document.getElementById("validate").style.backgroundColor = "skyblue";
- }
- }else{
- Notification.error("Validation Failed.");
- document.getElementById("validate").innerHTML = $scope.validateData;
- document.getElementById("validate").style.color = "white";
- document.getElementById("validate").style.backgroundColor = "red";
- $scope.savebutton = true;
- }
-
- });
- console.log($scope.data);
- },
- error : function(data){
- Notification.error("Validation Failed.");
- $scope.savebutton = true;
- }
- });
+ $.ajax({
+ type : 'POST',
+ url : uuu,
+ dataType: 'json',
+ contentType: 'application/json',
+ data: JSON.stringify(postData),
+ success : function(data){
+ $scope.$apply(function(){
+ $scope.validateData = data.data.replace(/\"/g, "");
+ $scope.data=data.data.substring(1,8);
+ var size = data.data.length;
+ if($scope.data == 'success'){
+ Notification.success("Validation Success.");
+ $scope.savebutton = false;
+ if (size > 18){
+ var displayWarning = data.data.substring(19,size - 1);
+ document.getElementById("validate").innerHTML = "Safe Policy Warning Message : "+displayWarning;
+ document.getElementById("validate").style.color = "white";
+ document.getElementById("validate").style.backgroundColor = "skyblue";
+ }
+ }else{
+ Notification.error("Validation Failed.");
+ document.getElementById("validate").innerHTML = $scope.validateData;
+ document.getElementById("validate").style.color = "white";
+ document.getElementById("validate").style.backgroundColor = "red";
+ $scope.savebutton = true;
+ }
+
+ });
+ },
+ error : function(data){
+ Notification.error("Validation Failed.");
+ $scope.savebutton = true;
+ }
+ });
};
function extend(obj, src) {
@@ -1386,4 +1328,4 @@ angular.module('abs').controller('optimizationController', ['$scope', '$window',
}
}]);/**
*
- */ \ No newline at end of file
+ */
diff --git a/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/js/controllers/policyManager.js b/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/js/controllers/policyManager.js
index 0aec30c1d..0cf655398 100644
--- a/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/js/controllers/policyManager.js
+++ b/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/js/controllers/policyManager.js
@@ -2,13 +2,13 @@
* ============LICENSE_START=======================================================
* ONAP Policy Engine
* ================================================================================
- * Copyright (C) 2017, 2019 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017, 2019-2020 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
@@ -18,326 +18,308 @@
* ============LICENSE_END=========================================================
*/
app.controller('PolicyManagerController', [
- '$scope', '$q', '$window', '$cookies', 'policyManagerConfig', 'item', 'policyNavigator', 'policyUploader', 'Notification','PolicyAppService',
- function($scope, $q, $Window, $cookies, policyManagerConfig, Item, PolicyNavigator, PolicyUploader, Notification, PolicyAppService ) {
+ '$scope', '$q', '$window', '$cookies', 'policyManagerConfig', 'item', 'policyNavigator', 'policyUploader', 'Notification','PolicyAppService',
+ function($scope, $q, $Window, $cookies, policyManagerConfig, Item, PolicyNavigator, PolicyUploader, Notification, PolicyAppService ) {
- $scope.isDisabled = true;
- $scope.superAdminId = false;
- $scope.exportPolicyId = false;
- $scope.importPolicyId = false;
- $scope.createScopeId = false;
- $scope.deleteScopeId = false;
- $scope.renameId = false;
- $scope.createPolicyId = false;
- $scope.cloneId = false;
- $scope.editPolicyId = false;
- $scope.switchVersionId = false;
- $scope.describePolicyId = false;
- $scope.viewPolicyId = false;
- $scope.deletePolicyId = false;
- PolicyAppService.getData('get_LockDownData').then(function(data) {
- var j = data;
- $scope.data = JSON.parse(j.data);
- $scope.lockdowndata = JSON.parse($scope.data.lockdowndata);
- if ($scope.lockdowndata[0].lockdown == true) {
- $scope.isDisabled = true;
- } else {
- $scope.isDisabled = false;
- }
- console.log($scope.data);
- }, function(error) {
- console.log("failed");
- });
+ $scope.isDisabled = true;
+ $scope.superAdminId = false;
+ $scope.exportPolicyId = false;
+ $scope.importPolicyId = false;
+ $scope.createScopeId = false;
+ $scope.deleteScopeId = false;
+ $scope.renameId = false;
+ $scope.createPolicyId = false;
+ $scope.cloneId = false;
+ $scope.editPolicyId = false;
+ $scope.switchVersionId = false;
+ $scope.describePolicyId = false;
+ $scope.viewPolicyId = false;
+ $scope.deletePolicyId = false;
+ PolicyAppService.getData('get_LockDownData').then(function(data) {
+ var j = data;
+ $scope.data = JSON.parse(j.data);
+ $scope.lockdowndata = JSON.parse($scope.data.lockdowndata);
+ if ($scope.lockdowndata[0].lockdown == true) {
+ $scope.isDisabled = true;
+ } else {
+ $scope.isDisabled = false;
+ }
+ }, function(error) {
+ });
- PolicyAppService.getData('getDictionary/get_DescriptiveScopeByName').then(function(data) {
- var j = data;
- $scope.data = JSON.parse(j.data);
- console.log($scope.data);
- $scope.descriptiveScopeDictionaryDatas = JSON.parse($scope.data.descriptiveScopeDictionaryDatas);
- }, function (error) {
- console.log("failed");
- });
+ PolicyAppService.getData('getDictionary/get_DescriptiveScopeByName').then(function(data) {
+ var j = data;
+ $scope.data = JSON.parse(j.data);
+ $scope.descriptiveScopeDictionaryDatas = JSON.parse($scope.data.descriptiveScopeDictionaryDatas);
+ });
- PolicyAppService.getData('getDictionary/get_OnapNameDataByName').then(function(data) {
- var j = data;
- $scope.data = JSON.parse(j.data);
- console.log($scope.data);
- $scope.onapNameDictionaryDatas = JSON.parse($scope.data.onapNameDictionaryDatas);
- }, function (error) {
- console.log("failed");
- });
+ PolicyAppService.getData('getDictionary/get_OnapNameDataByName').then(function(data) {
+ var j = data;
+ $scope.data = JSON.parse(j.data);
+ $scope.onapNameDictionaryDatas = JSON.parse($scope.data.onapNameDictionaryDatas);
+ });
- PolicyAppService.getData('getDictionary/get_VSCLActionDataByName').then(function(data) {
- var j = data;
- $scope.data = JSON.parse(j.data);
- console.log($scope.data);
- $scope.vsclActionDictionaryDatas = JSON.parse($scope.data.vsclActionDictionaryDatas);
- }, function (error) {
- console.log("failed");
- });
-
- PolicyAppService.getData('getDictionary/get_VNFTypeDataByName').then(function(data) {
- var j = data;
- $scope.data = JSON.parse(j.data);
- console.log($scope.data);
- $scope.vnfTypeDictionaryDatas = JSON.parse($scope.data.vnfTypeDictionaryDatas);
- }, function (error) {
- console.log("failed");
- });
+ PolicyAppService.getData('getDictionary/get_VSCLActionDataByName').then(function(data) {
+ var j = data;
+ $scope.data = JSON.parse(j.data);
+ $scope.vsclActionDictionaryDatas = JSON.parse($scope.data.vsclActionDictionaryDatas);
+ });
+ PolicyAppService.getData('getDictionary/get_VNFTypeDataByName').then(function(data) {
+ var j = data;
+ $scope.data = JSON.parse(j.data);
+ $scope.vnfTypeDictionaryDatas = JSON.parse($scope.data.vnfTypeDictionaryDatas);
+ });
- PolicyAppService.getData('get_UserRolesData').then(function (data) {
- var j = data;
- $scope.data = JSON.parse(j.data);
- console.log($scope.data);
- $scope.userRolesDatas = JSON.parse($scope.data.userRolesDatas);
- console.log($scope.userRolesDatas);
- if ($scope.userRolesDatas[0] == 'super-admin') {
- $scope.superAdminId = true;
- $scope.exportPolicyId = true;
- $scope.importPolicyId = true;
- } else if ($scope.userRolesDatas[0] == 'super-editor' || $scope.userRolesDatas[0] == 'editor' || $scope.userRolesDatas[0] == 'admin') {
- $scope.exportPolicyId = true;
- $scope.importPolicyId = true;
- }
- }, function (error) {
- console.log("failed");
- });
- $scope.config = policyManagerConfig;
- $scope.reverse = false;
- $scope.predicate = ['model.type', 'model.name'];
- $scope.order = function(predicate) {
- $scope.reverse = ($scope.predicate[1] === predicate) ? !$scope.reverse : false;
- $scope.predicate[1] = predicate;
- };
+ PolicyAppService.getData('get_UserRolesData').then(function (data) {
+ var j = data;
+ $scope.data = JSON.parse(j.data);
+ $scope.userRolesDatas = JSON.parse($scope.data.userRolesDatas);
+ if ($scope.userRolesDatas[0] == 'super-admin') {
+ $scope.superAdminId = true;
+ $scope.exportPolicyId = true;
+ $scope.importPolicyId = true;
+ } else if ($scope.userRolesDatas[0] == 'super-editor' || $scope.userRolesDatas[0] == 'editor' || $scope.userRolesDatas[0] == 'admin') {
+ $scope.exportPolicyId = true;
+ $scope.importPolicyId = true;
+ }
+ });
- $scope.query = '';
- $scope.temp = new Item();
- $scope.policyNavigator = new PolicyNavigator();
- $scope.policyUploader = PolicyUploader;
- $scope.uploadFileList = [];
+ $scope.config = policyManagerConfig;
+ $scope.reverse = false;
+ $scope.predicate = ['model.type', 'model.name'];
+ $scope.order = function(predicate) {
+ $scope.reverse = ($scope.predicate[1] === predicate) ? !$scope.reverse : false;
+ $scope.predicate[1] = predicate;
+ };
- $scope.setTemplate = function(name) {
- $scope.viewTemplate = $cookies.viewTemplate = name;
- };
+ $scope.query = '';
+ $scope.temp = new Item();
+ $scope.policyNavigator = new PolicyNavigator();
+ $scope.policyUploader = PolicyUploader;
+ $scope.uploadFileList = [];
- $scope.touch = function(item) {
- item = item instanceof Item ? item : new Item();
- item.revert();
- $scope.temp = item;
- $scope.createScopeId = false;
- $scope.deleteScopeId = false;
- $scope.renameId = false;
- $scope.createPolicyId = false;
- $scope.cloneId = false;
- $scope.editPolicyId = false;
- $scope.switchVersionId = false;
- $scope.describePolicyId = false;
- $scope.viewPolicyId = false;
- $scope.deletePolicyId = false;
- if ($scope.temp.model.roleType == 'super-admin') {
- $scope.createScopeId = true;
- $scope.deleteScopeId = true;
- $scope.renameId = true;
- $scope.createPolicyId = true;
- $scope.cloneId = true;
- $scope.editPolicyId = true;
- $scope.switchVersionId = true;
- $scope.describePolicyId = true;
- $scope.viewPolicyId = true;
- $scope.deletePolicyId = true;
- } else if ($scope.temp.model.roleType == 'super-editor' || $scope.temp.model.roleType == 'editor') {
- $scope.cloneId = true;
- $scope.editPolicyId = true;
- $scope.createPolicyId = true;
- $scope.switchVersionId = true;
- $scope.describePolicyId = true;
- $scope.viewPolicyId = true;
- $scope.deletePolicyId = true;
- } else if ($scope.temp.model.roleType == 'super-guest' || $scope.temp.model.roleType == 'guest') {
- $scope.describePolicyId = true;
- $scope.viewPolicyId = true;
- } else if ($scope.temp.model.roleType == 'admin') {
- $scope.createScopeId = true;
- $scope.renameId = true;
- $scope.createPolicyId = true;
- $scope.cloneId = true;
- $scope.editPolicyId = true;
- $scope.switchVersionId = true;
- $scope.describePolicyId = true;
- $scope.viewPolicyId = true;
- $scope.deletePolicyId = true;
- }
- };
+ $scope.setTemplate = function(name) {
+ $scope.viewTemplate = $cookies.viewTemplate = name;
+ };
- $scope.smartClick = function(item) {
- if (item.isFolder()) {
- return $scope.policyNavigator.folderClick(item);
- }
- if (item.isEditable()) {
- return $scope.openEditItem(item);
- }
- };
+ $scope.touch = function(item) {
+ item = item instanceof Item ? item : new Item();
+ item.revert();
+ $scope.temp = item;
+ $scope.createScopeId = false;
+ $scope.deleteScopeId = false;
+ $scope.renameId = false;
+ $scope.createPolicyId = false;
+ $scope.cloneId = false;
+ $scope.editPolicyId = false;
+ $scope.switchVersionId = false;
+ $scope.describePolicyId = false;
+ $scope.viewPolicyId = false;
+ $scope.deletePolicyId = false;
+ if ($scope.temp.model.roleType == 'super-admin') {
+ $scope.createScopeId = true;
+ $scope.deleteScopeId = true;
+ $scope.renameId = true;
+ $scope.createPolicyId = true;
+ $scope.cloneId = true;
+ $scope.editPolicyId = true;
+ $scope.switchVersionId = true;
+ $scope.describePolicyId = true;
+ $scope.viewPolicyId = true;
+ $scope.deletePolicyId = true;
+ } else if ($scope.temp.model.roleType == 'super-editor' || $scope.temp.model.roleType == 'editor') {
+ $scope.cloneId = true;
+ $scope.editPolicyId = true;
+ $scope.createPolicyId = true;
+ $scope.switchVersionId = true;
+ $scope.describePolicyId = true;
+ $scope.viewPolicyId = true;
+ $scope.deletePolicyId = true;
+ } else if ($scope.temp.model.roleType == 'super-guest' || $scope.temp.model.roleType == 'guest') {
+ $scope.describePolicyId = true;
+ $scope.viewPolicyId = true;
+ } else if ($scope.temp.model.roleType == 'admin') {
+ $scope.createScopeId = true;
+ $scope.renameId = true;
+ $scope.createPolicyId = true;
+ $scope.cloneId = true;
+ $scope.editPolicyId = true;
+ $scope.switchVersionId = true;
+ $scope.describePolicyId = true;
+ $scope.viewPolicyId = true;
+ $scope.deletePolicyId = true;
+ }
+ };
- $scope.openEditItem = function(item) {
- item.getContent();
- $scope.modal('createNewPolicy');
- return $scope.touch(item);
- };
+ $scope.smartClick = function(item) {
+ if (item.isFolder()) {
+ return $scope.policyNavigator.folderClick(item);
+ }
+ if (item.isEditable()) {
+ return $scope.openEditItem(item);
+ }
+ };
- $scope.modal = function(id, hide) {
- return $('#' + id).modal(hide ? 'hide' : 'show');
- };
+ $scope.openEditItem = function(item) {
+ item.getContent();
+ $scope.modal('createNewPolicy');
+ return $scope.touch(item);
+ };
- $scope.isInThisPath = function(path) {
- var currentPath = $scope.policyNavigator.currentPath.join('/');
- return currentPath.indexOf(path) !== -1;
- };
-
- $scope.watchPolicy = function(item) {
- var uuu = "watchPolicy";
- var data = {name : item.model.name,
- path : item.model.path};
- var postData={watchData: data};
- $.ajax({
- type : 'POST',
- url : uuu,
- dataType: 'json',
- contentType: 'application/json',
- data: JSON.stringify(postData),
- success : function(data) {
- $scope.$apply(function() {
- $scope.watchData=data.watchData;});
- Notification.success($scope.watchData);
- console.log($scope.watchData);
- },
- error : function(data) {
- alert("Error while saving.");
- }
- });
- };
+ $scope.modal = function(id, hide) {
+ return $('#' + id).modal(hide ? 'hide' : 'show');
+ };
- $scope.refresh = function() {
- $scope.policyNavigator.refresh();
- };
+ $scope.isInThisPath = function(path) {
+ var currentPath = $scope.policyNavigator.currentPath.join('/');
+ return currentPath.indexOf(path) !== -1;
+ };
+
+ $scope.watchPolicy = function(item) {
+ var uuu = "watchPolicy";
+ var data = {name : item.model.name,
+ path : item.model.path};
+ var postData={watchData: data};
+ $.ajax({
+ type : 'POST',
+ url : uuu,
+ dataType: 'json',
+ contentType: 'application/json',
+ data: JSON.stringify(postData),
+ success : function(data) {
+ $scope.$apply(function() {
+ $scope.watchData=data.watchData;});
+ Notification.success($scope.watchData);
+ },
+ error : function(data) {
+ Notification.error("Error while saving.");
+ }
+ });
+ };
- $scope.switchVersion = function(item) {
- if ($scope.policyNavigator.fileNameExists(item.tempModel.content.activeVersion)) {
- item.error = 'Invalid filename or already exists, specify another name';
- return false;
- }
- item.getSwitchVersionContent().then(function(){
- $scope.policyNavigator.refresh();
- $scope.modal('switchVersion', true);
- });
+ $scope.refresh = function() {
+ $scope.policyNavigator.refresh();
};
- $scope.copy = function(item) {
- var samePath = item.tempModel.path.join() === item.model.path.join();
- if (samePath && $scope.policyNavigator.fileNameExists(item.tempModel.name)) {
- item.error = 'Invalid filename or already exists, specify another name';
- return false;
- }
- item.copy().then(function() {
- $scope.policyNavigator.refresh();
- $scope.modal('copy', true);
- });
- };
+ $scope.switchVersion = function(item) {
+ if ($scope.policyNavigator.fileNameExists(item.tempModel.content.activeVersion)) {
+ item.error = 'Invalid filename or already exists, specify another name';
+ return false;
+ }
+ item.getSwitchVersionContent().then(function(){
+ $scope.policyNavigator.refresh();
+ $scope.modal('switchVersion', true);
+ });
+ };
- $scope.remove = function(item) {
- item.remove().then(function() {
- $scope.policyNavigator.refresh();
- $scope.modal('delete', true);
- });
- };
+ $scope.copy = function(item) {
+ var samePath = item.tempModel.path.join() === item.model.path.join();
+ if (samePath && $scope.policyNavigator.fileNameExists(item.tempModel.name)) {
+ item.error = 'Invalid filename or already exists, specify another name';
+ return false;
+ }
+ item.copy().then(function() {
+ $scope.policyNavigator.refresh();
+ $scope.modal('copy', true);
+ });
+ };
- $scope.removePolicy = function(item) {
- item.removePolicy().then(function() {
- $scope.policyNavigator.refresh();
- $scope.modal('deletePolicy', true);
- });
- };
+ $scope.remove = function(item) {
+ item.remove().then(function() {
+ $scope.policyNavigator.refresh();
+ $scope.modal('delete', true);
+ });
+ };
- $scope.rename = function(item) {
- var samePath = item.tempModel.path.join() === item.model.path.join();
- if (samePath && $scope.policyNavigator.fileNameExists(item.tempModel.name)) {
- item.error = 'Invalid filename or already exists, specify another name';
- return false;
- }
- item.rename().then(function() {
- $scope.policyNavigator.refresh();
- $scope.modal('rename', true);
- });
- };
+ $scope.removePolicy = function(item) {
+ item.removePolicy().then(function() {
+ $scope.policyNavigator.refresh();
+ $scope.modal('deletePolicy', true);
+ });
+ };
- $scope.move = function(item) {
- var samePath = item.tempModel.path.join() === item.model.path.join();
- if (samePath && $scope.policyNavigator.fileNameExists(item.tempModel.name)) {
- item.error = 'Invalid filename or already exists, specify another name';
- return false;
- }
- item.move().then(function() {
- $scope.policyNavigator.refresh();
- $scope.modal('move', true);
- });
- };
+ $scope.rename = function(item) {
+ var samePath = item.tempModel.path.join() === item.model.path.join();
+ if (samePath && $scope.policyNavigator.fileNameExists(item.tempModel.name)) {
+ item.error = 'Invalid filename or already exists, specify another name';
+ return false;
+ }
+ item.rename().then(function() {
+ $scope.policyNavigator.refresh();
+ $scope.modal('rename', true);
+ });
+ };
- $scope.createFolder = function(item) {
- var name = item.tempModel.name && item.tempModel.name.trim();
- item.tempModel.type = 'dir';
- item.tempModel.path = $scope.policyNavigator.currentPath;
- if (name && !$scope.policyNavigator.fileNameExists(name)) {
- item.createFolder().then(function() {
- $scope.policyNavigator.refresh();
- $scope.modal('newfolder', true);
- });
- } else {
- item.error = 'Invalid filename or already exists, specify another name';
- return false;
- }
- };
+ $scope.move = function(item) {
+ var samePath = item.tempModel.path.join() === item.model.path.join();
+ if (samePath && $scope.policyNavigator.fileNameExists(item.tempModel.name)) {
+ item.error = 'Invalid filename or already exists, specify another name';
+ return false;
+ }
+ item.move().then(function() {
+ $scope.policyNavigator.refresh();
+ $scope.modal('move', true);
+ });
+ };
- $scope.subScopeFolder = function(item) {
- var name = item.tempModel.name +"\\" + item.tempModel.subScopename && item.tempModel.name.trim() + "\\"+item.tempModel.subScopename.trim() ;
- item.tempModel.type = 'dir';
- item.tempModel.path = $scope.policyNavigator.currentPath;
- if (name && !$scope.policyNavigator.fileNameExists(name)) {
- item.getScopeContent().then(function() {
- $scope.policyNavigator.refresh();
- $scope.modal('addSubScope', true);
- });
- } else {
- item.error = 'Invalid filename or already exists, specify another name';
- return false;
- }
- };
+ $scope.createFolder = function(item) {
+ var name = item.tempModel.name && item.tempModel.name.trim();
+ item.tempModel.type = 'dir';
+ item.tempModel.path = $scope.policyNavigator.currentPath;
+ if (name && !$scope.policyNavigator.fileNameExists(name)) {
+ item.createFolder().then(function() {
+ $scope.policyNavigator.refresh();
+ $scope.modal('newfolder', true);
+ });
+ } else {
+ item.error = 'Invalid filename or already exists, specify another name';
+ return false;
+ }
+ };
- $scope.closefunction = function(fianlPath) {
- $scope.policyNavigator.policyrefresh(fianlPath);
- };
+ $scope.subScopeFolder = function(item) {
+ var name = item.tempModel.name +"\\" + item.tempModel.subScopename && item.tempModel.name.trim() + "\\"+item.tempModel.subScopename.trim() ;
+ item.tempModel.type = 'dir';
+ item.tempModel.path = $scope.policyNavigator.currentPath;
+ if (name && !$scope.policyNavigator.fileNameExists(name)) {
+ item.getScopeContent().then(function() {
+ $scope.policyNavigator.refresh();
+ $scope.modal('addSubScope', true);
+ });
+ } else {
+ item.error = 'Invalid filename or already exists, specify another name';
+ return false;
+ }
+ };
- $scope.uploadFiles = function() {
- $scope.policyUploader.upload($scope.uploadFileList, $scope.policyNavigator.currentPath).then(function() {
- $scope.policyNavigator.refresh();
- $scope.modal('uploadfile', true);
- }, function(data) {
- var errorMsg = data.result && data.result.error || 'Error Occured while Uploading....';
- $scope.temp.error = errorMsg;
- });
- };
+ $scope.closefunction = function(fianlPath) {
+ $scope.policyNavigator.policyrefresh(fianlPath);
+ };
- $scope.getQueryParam = function(param) {
- var found;
- window.location.search.substr(1).split('&').forEach(function(item) {
- if (param === item.split('=')[0]) {
- found = item.split('=')[1];
- return false;
- }
- });
- return found;
- };
+ $scope.uploadFiles = function() {
+ $scope.policyUploader.upload($scope.uploadFileList, $scope.policyNavigator.currentPath).then(function() {
+ $scope.policyNavigator.refresh();
+ Notification.success('Policy Import Complete');
+ $scope.modal('uploadfile', true);
+ }, function(data) {
+ var errorMsg = data.result && data.result.error || 'Error Occured while Uploading....';
+ $scope.temp.error = errorMsg;
+ });
+ };
- $scope.isWindows = $scope.getQueryParam('server') === 'Windows';
- $scope.policyNavigator.refresh();
- }]);
+ $scope.getQueryParam = function(param) {
+ var found;
+ window.location.search.substr(1).split('&').forEach(function(item) {
+ if (param === item.split('=')[0]) {
+ found = item.split('=')[1];
+ return false;
+ }
+ });
+ return found;
+ };
+
+ $scope.isWindows = $scope.getQueryParam('server') === 'Windows';
+ $scope.policyNavigator.refresh();
+ }]);
diff --git a/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/js/controllers/policySearchManager.js b/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/js/controllers/policySearchManager.js
index 42e6796cd..edca7e47c 100644
--- a/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/js/controllers/policySearchManager.js
+++ b/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/js/controllers/policySearchManager.js
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP Policy Engine
* ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017, 2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -18,194 +18,176 @@
* ============LICENSE_END=========================================================
*/
app.controller('PolicySearchController', [
- '$scope', '$q', '$window', '$cookies', 'policyManagerConfig', 'item', 'policyNavigator', 'policyUploader', 'Notification','PolicyAppService',
- function($scope, $q, $Window, $cookies, policyManagerConfig, Item, PolicyNavigator, PolicyUploader, Notification, PolicyAppService ) {
-
- $scope.isDisabled = true;
- $scope.superAdminId = false;
- $scope.exportPolicyId = false;
- $scope.importPolicyId = false;
- $scope.createScopeId = false;
- $scope.deleteScopeId = false;
- $scope.renameId = false;
- $scope.createPolicyId = false;
- $scope.cloneId = false;
- $scope.editPolicyId = false;
- $scope.switchVersionId = false;
- $scope.describePolicyId = false;
- $scope.viewPolicyId = false;
- $scope.deletePolicyId = false;
- PolicyAppService.getData('get_LockDownData').then(function(data){
- var j = data;
- $scope.data = JSON.parse(j.data);
- $scope.lockdowndata = JSON.parse($scope.data.lockdowndata);
- if($scope.lockdowndata[0].lockdown == true){
- $scope.isDisabled = true;
- }else{
- $scope.isDisabled = false;
- }
- console.log($scope.data);
- },function(error){
- console.log("failed");
- });
+ '$scope', '$q', '$window', '$cookies', 'policyManagerConfig', 'item', 'policyNavigator', 'policyUploader', 'Notification','PolicyAppService',
+ function($scope, $q, $Window, $cookies, policyManagerConfig, Item, PolicyNavigator, PolicyUploader, Notification, PolicyAppService ) {
- PolicyAppService.getData('getDictionary/get_DescriptiveScopeByName').then(function(data){
- var j = data;
- $scope.data = JSON.parse(j.data);
- console.log($scope.data);
- $scope.descriptiveScopeDictionaryDatas = JSON.parse($scope.data.descriptiveScopeDictionaryDatas);
- }, function (error) {
- console.log("failed");
- });
+ $scope.isDisabled = true;
+ $scope.superAdminId = false;
+ $scope.exportPolicyId = false;
+ $scope.importPolicyId = false;
+ $scope.createScopeId = false;
+ $scope.deleteScopeId = false;
+ $scope.renameId = false;
+ $scope.createPolicyId = false;
+ $scope.cloneId = false;
+ $scope.editPolicyId = false;
+ $scope.switchVersionId = false;
+ $scope.describePolicyId = false;
+ $scope.viewPolicyId = false;
+ $scope.deletePolicyId = false;
+ PolicyAppService.getData('get_LockDownData').then(function(data){
+ var j = data;
+ $scope.data = JSON.parse(j.data);
+ $scope.lockdowndata = JSON.parse($scope.data.lockdowndata);
+ if($scope.lockdowndata[0].lockdown == true){
+ $scope.isDisabled = true;
+ }else{
+ $scope.isDisabled = false;
+ }
+ },function(error){
+ });
+
+ PolicyAppService.getData('getDictionary/get_DescriptiveScopeByName').then(function(data){
+ var j = data;
+ $scope.data = JSON.parse(j.data);
+ $scope.descriptiveScopeDictionaryDatas = JSON.parse($scope.data.descriptiveScopeDictionaryDatas);
+ });
- PolicyAppService.getData('getDictionary/get_OnapNameDataByName').then(function(data){
- var j = data;
- $scope.data = JSON.parse(j.data);
- console.log($scope.data);
- $scope.onapNameDictionaryDatas = JSON.parse($scope.data.onapNameDictionaryDatas);
- }, function (error) {
- console.log("failed");
- });
+ PolicyAppService.getData('getDictionary/get_OnapNameDataByName').then(function(data){
+ var j = data;
+ $scope.data = JSON.parse(j.data);
+ $scope.onapNameDictionaryDatas = JSON.parse($scope.data.onapNameDictionaryDatas);
+ });
- PolicyAppService.getData('getDictionary/get_VSCLActionDataByName').then(function(data){
- var j = data;
- $scope.data = JSON.parse(j.data);
- console.log($scope.data);
- $scope.vsclActionDictionaryDatas = JSON.parse($scope.data.vsclActionDictionaryDatas);
- }, function (error) {
- console.log("failed");
- });
+ PolicyAppService.getData('getDictionary/get_VSCLActionDataByName').then(function(data){
+ var j = data;
+ $scope.data = JSON.parse(j.data);
+ $scope.vsclActionDictionaryDatas = JSON.parse($scope.data.vsclActionDictionaryDatas);
+ });
- PolicyAppService.getData('getDictionary/get_VNFTypeDataByName').then(function(data){
- var j = data;
- $scope.data = JSON.parse(j.data);
- console.log($scope.data);
- $scope.vnfTypeDictionaryDatas = JSON.parse($scope.data.vnfTypeDictionaryDatas);
- }, function (error) {
- console.log("failed");
- });
+ PolicyAppService.getData('getDictionary/get_VNFTypeDataByName').then(function(data){
+ var j = data;
+ $scope.data = JSON.parse(j.data);
+ $scope.vnfTypeDictionaryDatas = JSON.parse($scope.data.vnfTypeDictionaryDatas);
+ });
-
- PolicyAppService.getData('get_UserRolesData').then(function (data) {
- var j = data;
- $scope.data = JSON.parse(j.data);
- console.log($scope.data);
- $scope.userRolesDatas = JSON.parse($scope.data.userRolesDatas);
- console.log($scope.userRolesDatas);
- if($scope.userRolesDatas[0] == 'super-admin'){
- $scope.superAdminId = true;
- $scope.createPolicyId = true;
- $scope.editPolicyId = true;
- $scope.describePolicyId = true;
- $scope.viewPolicyId = true;
- }else if($scope.userRolesDatas[0] == 'super-editor' || $scope.userRolesDatas[0] == 'editor' || $scope.userRolesDatas[0] == 'admin'){
- $scope.editPolicyId = true;
- $scope.createPolicyId = true;
- $scope.describePolicyId = true;
- $scope.viewPolicyId = true;
- }else if($scope.userRolesDatas[0] == 'super-guest' || $scope.userRolesDatas[0] == 'guest'){
- $scope.describePolicyId = true;
- $scope.viewPolicyId = true;
- }
- }, function (error) {
- console.log("failed");
- });
-
- $scope.config = policyManagerConfig;
- $scope.reverse = false;
- $scope.predicate = ['model.type', 'model.name'];
- $scope.order = function(predicate) {
- $scope.reverse = ($scope.predicate[1] === predicate) ? !$scope.reverse : false;
- $scope.predicate[1] = predicate;
- };
+
+ PolicyAppService.getData('get_UserRolesData').then(function (data) {
+ var j = data;
+ $scope.data = JSON.parse(j.data);
+ $scope.userRolesDatas = JSON.parse($scope.data.userRolesDatas);
+ if($scope.userRolesDatas[0] == 'super-admin'){
+ $scope.superAdminId = true;
+ $scope.createPolicyId = true;
+ $scope.editPolicyId = true;
+ $scope.describePolicyId = true;
+ $scope.viewPolicyId = true;
+ }else if($scope.userRolesDatas[0] == 'super-editor' || $scope.userRolesDatas[0] == 'editor' || $scope.userRolesDatas[0] == 'admin'){
+ $scope.editPolicyId = true;
+ $scope.createPolicyId = true;
+ $scope.describePolicyId = true;
+ $scope.viewPolicyId = true;
+ }else if($scope.userRolesDatas[0] == 'super-guest' || $scope.userRolesDatas[0] == 'guest'){
+ $scope.describePolicyId = true;
+ $scope.viewPolicyId = true;
+ }
+ });
+
+ $scope.config = policyManagerConfig;
+ $scope.reverse = false;
+ $scope.predicate = ['model.type', 'model.name'];
+ $scope.order = function(predicate) {
+ $scope.reverse = ($scope.predicate[1] === predicate) ? !$scope.reverse : false;
+ $scope.predicate[1] = predicate;
+ };
- $scope.query = '';
- $scope.temp = new Item();
- $scope.policyNavigator = new PolicyNavigator();
+ $scope.query = '';
+ $scope.temp = new Item();
+ $scope.policyNavigator = new PolicyNavigator();
- $scope.setTemplate = function(name) {
- $scope.viewTemplate = $cookies.viewTemplate = name;
- };
+ $scope.setTemplate = function(name) {
+ $scope.viewTemplate = $cookies.viewTemplate = name;
+ };
- $scope.touch = function(item) {
- item = item instanceof Item ? item : new Item();
- item.revert();
- $scope.temp = item;
- };
+ $scope.touch = function(item) {
+ item = item instanceof Item ? item : new Item();
+ item.revert();
+ $scope.temp = item;
+ };
- $scope.smartClick = function(item) {
- if (item.isFolder()) {
- return $scope.policyNavigator.folderClick(item);
- }
- if (item.isEditable()) {
- return $scope.openEditItem(item);
- }
- };
+ $scope.smartClick = function(item) {
+ if (item.isFolder()) {
+ return $scope.policyNavigator.folderClick(item);
+ }
+ if (item.isEditable()) {
+ return $scope.openEditItem(item);
+ }
+ };
- $scope.openEditItem = function(item) {
- item.getContent();
- $scope.modal('createNewPolicy');
- return $scope.touch(item);
- };
+ $scope.openEditItem = function(item) {
+ item.getContent();
+ $scope.modal('createNewPolicy');
+ return $scope.touch(item);
+ };
- $scope.modal = function(id, hide) {
- return $('#' + id).modal(hide ? 'hide' : 'show');
- };
+ $scope.modal = function(id, hide) {
+ return $('#' + id).modal(hide ? 'hide' : 'show');
+ };
- $scope.isInThisPath = function(path) {
- var currentPath = $scope.policyNavigator.currentPath.join('/');
- return currentPath.indexOf(path) !== -1;
- };
+ $scope.isInThisPath = function(path) {
+ var currentPath = $scope.policyNavigator.currentPath.join('/');
+ return currentPath.indexOf(path) !== -1;
+ };
- $scope.searchPolicy = function(searchContent){
- if(searchContent != undefined){
- var uuu = "searchPolicy";
- var postData = {searchdata : searchContent};
- $.ajax({
- type : 'POST',
- url : uuu,
- dataType: 'json',
- contentType: 'application/json',
- data: JSON.stringify(postData),
- success : function(data){
- $scope.$apply(function(){
- var searchdata = data.result;
- if(searchdata.length > 0){
- if(searchdata[0] == "Exception"){
- Notification.error(searchdata[1]);
- }else{
- $scope.policyNavigator.searchrefresh(searchdata);
- }
- }else{
- Notification.info("No Matches Found with your Search");
- }
- });
- },
- error : function(data){
- Notification.error("Error while Searching.");
- }
- });
- }else{
- Notification.error("No data has been entered or selected to search");
- }
- };
+ $scope.searchPolicy = function(searchContent){
+ if(searchContent != undefined){
+ var uuu = "searchPolicy";
+ var postData = {searchdata : searchContent};
+ $.ajax({
+ type : 'POST',
+ url : uuu,
+ dataType: 'json',
+ contentType: 'application/json',
+ data: JSON.stringify(postData),
+ success : function(data){
+ $scope.$apply(function(){
+ var searchdata = data.result;
+ if(searchdata.length > 0){
+ if(searchdata[0] == "Exception"){
+ Notification.error(searchdata[1]);
+ }else{
+ $scope.policyNavigator.searchrefresh(searchdata);
+ }
+ }else{
+ Notification.info("No Matches Found with your Search");
+ }
+ });
+ },
+ error : function(data){
+ Notification.error("Error while Searching.");
+ }
+ });
+ }else{
+ Notification.error("No data has been entered or selected to search");
+ }
+ };
$scope.refresh = function(searchData){
- $scope.policyNavigator.searchrefresh(null);
+ $scope.policyNavigator.searchrefresh(null);
};
-
- $scope.getQueryParam = function(param) {
- var found;
- window.location.search.substr(1).split('&').forEach(function(item) {
- if (param === item.split('=')[0]) {
- found = item.split('=')[1];
- return false;
- }
- });
- return found;
- };
+
+ $scope.getQueryParam = function(param) {
+ var found;
+ window.location.search.substr(1).split('&').forEach(function(item) {
+ if (param === item.split('=')[0]) {
+ found = item.split('=')[1];
+ return false;
+ }
+ });
+ return found;
+ };
- $scope.isWindows = $scope.getQueryParam('server') === 'Windows';
- $scope.policyNavigator.searchrefresh(null);
- $scope.policyNavigator.setSearchModalActiveStatus();
+ $scope.isWindows = $scope.getQueryParam('server') === 'Windows';
+ $scope.policyNavigator.searchrefresh(null);
+ $scope.policyNavigator.setSearchModalActiveStatus();
}]);
diff --git a/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/js/entities/item.js b/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/js/entities/item.js
index 26cdf67c3..017f49ddc 100644
--- a/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/js/entities/item.js
+++ b/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/js/entities/item.js
@@ -51,10 +51,6 @@ angular.module('abs').factory('item', ['$http', '$q', 'policyManagerConfig', fun
this.model = angular.copy(rawModel);
this.tempModel = angular.copy(rawModel);
- function parseMySQLDate(mysqlDate) {
- var d = (mysqlDate || '').toString().split(/[- :]/);
- return new Date(d[0], d[1] - 1, d[2], d[3], d[4], d[5]);
- }
};
Item.prototype.update = function() {
@@ -263,7 +259,6 @@ angular.module('abs').factory('item', ['$http', '$q', 'policyManagerConfig', fun
self.error = '';
$http.post(policyManagerConfig.describePolicyUrl, data).success(function(data) {
self.tempModel.content = self.model.content = data.html;
- var describeTemplate = self.tempModel.content;
self.deferredHandler(data, deferred);
}).error(function(data) {
diff --git a/POLICY-SDK-APP/src/main/webapp/app/policyApp/service/modalService.js b/POLICY-SDK-APP/src/main/webapp/app/policyApp/service/modalService.js
index 381db7f9a..ceb2ec39f 100644
--- a/POLICY-SDK-APP/src/main/webapp/app/policyApp/service/modalService.js
+++ b/POLICY-SDK-APP/src/main/webapp/app/policyApp/service/modalService.js
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP Policy Engine
* ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017, 2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -21,7 +21,7 @@ angular.module("modalServices",[]).service('modalService', ['$modal', function (
this.showSuccess = function(heading, messageBody){
- var modalInstance = $modal.open({
+ $modal.open({
templateUrl: 'modal_informative.html',
controller: 'modalpopupController',
resolve: {
@@ -38,7 +38,7 @@ angular.module("modalServices",[]).service('modalService', ['$modal', function (
});
};
this.showFailure = function(heading, messageBody){
- var modalInstance = $modal.open({
+ $modal.open({
templateUrl: 'modal_warning.html',
controller: 'modalpopupController',
resolve: {
@@ -54,7 +54,7 @@ angular.module("modalServices",[]).service('modalService', ['$modal', function (
};
this.showMessage = function(heading, messageBody){
- var modalInstance = $modal.open({
+ $modal.open({
templateUrl: 'modal_message.html',
controller: 'modalpopupController',
resolve: {
@@ -70,7 +70,7 @@ angular.module("modalServices",[]).service('modalService', ['$modal', function (
};
this.showWarning = function(heading, messageBody){
- var modalInstance = $modal.open({
+ $modal.open({
templateUrl: 'modal_warning_message.html',
controller: 'modalpopupController',
resolve: {
@@ -201,4 +201,4 @@ angular.module("modalServices",[]).service('modalService', ['$modal', function (
modalInstance = undefined;
});
};
- }]); \ No newline at end of file
+ }]);
diff --git a/POLICY-SDK-APP/src/test/java/org/onap/policy/admin/CheckPDPTest.java b/POLICY-SDK-APP/src/test/java/org/onap/policy/admin/CheckPDPTest.java
deleted file mode 100644
index a06afc997..000000000
--- a/POLICY-SDK-APP/src/test/java/org/onap/policy/admin/CheckPDPTest.java
+++ /dev/null
@@ -1,95 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * ONAP Policy Engine
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Modifications Copyright (C) 2019 Samsung
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 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.io.File;
-import org.junit.FixMethodOrder;
-import org.junit.Test;
-import org.junit.runners.MethodSorters;
-
-@FixMethodOrder(MethodSorters.NAME_ASCENDING)
-public class CheckPDPTest {
-
- @Test
- public final void test1NoPropertySet() {
- try {
- System.clearProperty("xacml.rest.pdp.idfile");
- assertFalse(CheckPDP.validateID("http://localhost:8082/pdp/"));
-
- System.setProperty("xacml.rest.pdp.idfile",
- new File(".").getCanonicalPath() + File.separator + "src" + File.separator
- + "test" + File.separator + "resources" + File.separator
- + "idonotexist.properties");
- assertFalse(CheckPDP.validateID("http://localhost:8082/pdp/"));
-
- System.setProperty("xacml.rest.pdp.idfile",
- new File(".").getCanonicalPath() + File.separator + "src" + File.separator
- + "test" + File.separator + "resources" + File.separator
- + "doesnothaveproperties.atall");
- assertFalse(CheckPDP.validateID("http://localhost:8082/pdp/"));
-
- System.setProperty("xacml.rest.pdp.idfile",
- new File(".").getCanonicalPath() + File.separator + "src" + File.separator
- + "test" + File.separator + "resources" + File.separator
- + "testbad.properties");
- assertFalse(CheckPDP.validateID("http://localhost:8082/pdp/"));
-
- System.setProperty("xacml.rest.pdp.idfile",
- new File(".").getCanonicalPath() + File.separator + "src" + File.separator
- + "test" + File.separator + "resources" + File.separator
- + "empty.properties");
- assertFalse(CheckPDP.validateID("http://localhost:8082/pdp/"));
-
- System.setProperty("xacml.rest.pdp.idfile",
- new File(".").getCanonicalPath() + File.separator + "src" + File.separator
- + "test" + File.separator + "resources" + File.separator
- + "testnotenoughvalues.properties");
- assertFalse(CheckPDP.validateID("http://localhost:8082/pdp/"));
-
- assertNull(CheckPDP.getPdpMap());
- assertNull(CheckPDP.getEncoding("http://localhost:8082/pdp/"));
-
- } catch (Exception e) {
- fail("Error occured in CheckPDP test");
- }
- }
-
- @Test
- public final void test2CheckPDP() {
- try {
- System.setProperty("xacml.rest.pdp.idfile",
- new File(".").getCanonicalPath() + File.separator + "src" + File.separator
- + "test" + File.separator + "resources" + File.separator
- + "test.properties");
- assertTrue(CheckPDP.validateID("http://localhost:8082/pdp/"));
- assertTrue(CheckPDP.getPdpMap().containsKey("http://localhost:8082/pdp/"));
- assertTrue(CheckPDP.getEncoding("http://localhost:8082/pdp/")
- .equals("dGVzdHBkcDphbHBoYTQ1Ng=="));
- } catch (Exception e) {
- fail("Error occured in CheckPDP test");
- }
- }
-}
diff --git a/POLICY-SDK-APP/src/test/java/org/onap/policy/admin/CheckPdpPropertiesTest.java b/POLICY-SDK-APP/src/test/java/org/onap/policy/admin/CheckPdpPropertiesTest.java
new file mode 100644
index 000000000..afb6fc8b0
--- /dev/null
+++ b/POLICY-SDK-APP/src/test/java/org/onap/policy/admin/CheckPdpPropertiesTest.java
@@ -0,0 +1,82 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP Policy Engine
+ * ================================================================================
+ * Copyright (C) 2017, 2019 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Modifications Copyright (C) 2019 Samsung
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertTrue;
+
+import com.att.research.xacml.util.XACMLProperties;
+import java.io.File;
+import java.io.IOException;
+import org.junit.FixMethodOrder;
+import org.junit.Test;
+import org.junit.runners.MethodSorters;
+
+@FixMethodOrder(MethodSorters.NAME_ASCENDING)
+public class CheckPdpPropertiesTest {
+
+ @Test
+ public final void test1NoPropertySet() throws IOException {
+ System.setProperty(XACMLProperties.XACML_PROPERTIES_NAME, "noexistenfile.properties");
+ assertFalse(CheckPdpProperties.validateId("http://localhost:8082/pdp/"));
+
+ System.clearProperty(XACMLProperties.XACML_PROPERTIES_NAME);
+ System.clearProperty("xacml.rest.pdp.idfile");
+ assertFalse(CheckPdpProperties.validateId("http://localhost:8082/pdp/"));
+
+ System.setProperty("xacml.rest.pdp.idfile", new File(".").getCanonicalPath() + File.separator + "src"
+ + File.separator + "test" + File.separator + "resources" + File.separator + "idonotexist.properties");
+ assertFalse(CheckPdpProperties.validateId("http://localhost:8082/pdp/"));
+
+ System.setProperty("xacml.rest.pdp.idfile",
+ new File(".").getCanonicalPath() + File.separator + "src" + File.separator + "test" + File.separator
+ + "resources" + File.separator + "doesnothaveproperties.atall");
+ assertFalse(CheckPdpProperties.validateId("http://localhost:8082/pdp/"));
+
+ System.setProperty("xacml.rest.pdp.idfile", new File(".").getCanonicalPath() + File.separator + "src"
+ + File.separator + "test" + File.separator + "resources" + File.separator + "testbad.properties");
+ assertFalse(CheckPdpProperties.validateId("http://localhost:8082/pdp/"));
+
+ System.setProperty("xacml.rest.pdp.idfile", new File(".").getCanonicalPath() + File.separator + "src"
+ + File.separator + "test" + File.separator + "resources" + File.separator + "empty.properties");
+ assertFalse(CheckPdpProperties.validateId("http://localhost:8082/pdp/"));
+
+ System.setProperty("xacml.rest.pdp.idfile",
+ new File(".").getCanonicalPath() + File.separator + "src" + File.separator + "test" + File.separator
+ + "resources" + File.separator + "testnotenoughvalues.properties");
+ assertFalse(CheckPdpProperties.validateId("http://localhost:8082/pdp/"));
+
+ assertNull(CheckPdpProperties.getPdpMap());
+ assertNull(CheckPdpProperties.getEncoding("http://localhost:8082/pdp/"));
+ }
+
+ @Test
+ public final void test2CheckPdp() throws IOException {
+ System.setProperty("xacml.rest.pdp.idfile", new File(".").getCanonicalPath() + File.separator + "src"
+ + File.separator + "test" + File.separator + "resources" + File.separator + "test.properties");
+ assertTrue(CheckPdpProperties.validateId("http://localhost:8082/pdp/"));
+ assertTrue(CheckPdpProperties.getPdpMap().containsKey("http://localhost:8082/pdp/"));
+ assertTrue(CheckPdpProperties.getEncoding("http://localhost:8082/pdp/").equals("dGVzdHBkcDphbHBoYTQ1Ng=="));
+ }
+}
diff --git a/POLICY-SDK-APP/src/test/java/org/onap/policy/admin/PolicyManagerServletTest.java b/POLICY-SDK-APP/src/test/java/org/onap/policy/admin/PolicyManagerServletTest.java
index 7bd3be440..c3b98f525 100644
--- a/POLICY-SDK-APP/src/test/java/org/onap/policy/admin/PolicyManagerServletTest.java
+++ b/POLICY-SDK-APP/src/test/java/org/onap/policy/admin/PolicyManagerServletTest.java
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP Policy Engine
* ================================================================================
- * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2020 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Modifications Copyright (C) 2019 Samsung
* ================================================================================
@@ -19,22 +19,42 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.policy.admin;
+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.io.BufferedReader;
import java.io.File;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.io.PrintWriter;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.Collections;
+import java.util.Date;
+import java.util.HashSet;
import java.util.List;
+import java.util.Set;
+import javax.json.JsonArray;
+import javax.script.SimpleBindings;
import javax.servlet.ServletConfig;
import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
+import org.apache.commons.fileupload.FileItem;
import org.apache.commons.io.IOUtils;
+import org.json.JSONArray;
+import org.json.JSONObject;
+import org.junit.AfterClass;
import org.junit.Before;
+import org.junit.FixMethodOrder;
import org.junit.Test;
+import org.junit.runners.MethodSorters;
import org.mockito.Mockito;
import org.onap.policy.common.logging.flexlogger.FlexLogger;
import org.onap.policy.common.logging.flexlogger.Logger;
@@ -49,10 +69,13 @@ 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.UserUtils.Pair;
import org.onap.portalsdk.core.domain.User;
import org.onap.portalsdk.core.util.SystemProperties;
+import org.powermock.reflect.Whitebox;
import org.springframework.mock.web.MockHttpServletResponse;
+@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class PolicyManagerServletTest extends Mockito {
private static Logger logger = FlexLogger.getLogger(PolicyManagerServletTest.class);
@@ -67,6 +90,21 @@ public class PolicyManagerServletTest extends Mockito {
private HttpServletRequest request;
private MockHttpServletResponse response;
+ /**
+ * Delete test File.
+ *
+ */
+ @AfterClass
+ public static void tearDown() {
+ File destroyFile = new File("testFileName.xls");
+ destroyFile.deleteOnExit();
+ }
+
+ /**
+ * setUp.
+ *
+ * @throws Exception should not get one
+ */
@Before
public void setUp() throws Exception {
logger.info("setUp: Entering");
@@ -98,8 +136,7 @@ public class PolicyManagerServletTest extends Mockito {
String policyContent = "";
try {
ClassLoader classLoader = getClass().getClassLoader();
- policyContent = IOUtils
- .toString(classLoader.getResourceAsStream("Config_SampleTest1206.1.xml"));
+ policyContent = IOUtils.toString(classLoader.getResourceAsStream("Config_SampleTest1206.1.xml"));
} catch (Exception e1) {
logger.error("Exception Occured" + e1);
}
@@ -141,26 +178,22 @@ public class PolicyManagerServletTest extends Mockito {
HttpSession mockSession = mock(HttpSession.class);
User user = new User();
user.setOrgUserId("Test");
- Mockito.when(mockSession.getAttribute(SystemProperties.getProperty("user_attribute_name")))
- .thenReturn(user);
+ Mockito.when(mockSession.getAttribute(SystemProperties.getProperty("user_attribute_name"))).thenReturn(user);
Mockito.when(request.getSession(false)).thenReturn(mockSession);
commonClassDao = mock(CommonClassDao.class);
}
@Test
- public void testInit() {
+ public void test01Init() {
PolicyManagerServlet servlet = new PolicyManagerServlet();
ServletConfig servletConfig = mock(ServletConfig.class);
try {
- when(servletConfig.getInitParameterNames())
- .thenReturn(Collections.enumeration(headers));
- when(servletConfig.getInitParameter("XACML_PROPERTIES_NAME"))
- .thenReturn("xacml.admin.properties");
+ when(servletConfig.getInitParameterNames()).thenReturn(Collections.enumeration(headers));
+ when(servletConfig.getInitParameter("XACML_PROPERTIES_NAME")).thenReturn("xacml.admin.properties");
System.setProperty("xacml.rest.admin.closedLoopJSON",
- new File(".").getCanonicalPath() + File.separator + "src" + File.separator
- + "test" + File.separator + "resources" + File.separator
- + "JSONConfig.json");
+ new File(".").getCanonicalPath() + File.separator + "src" + File.separator + "test" + File.separator
+ + "resources" + File.separator + "JSONConfig.json");
servlet.init(servletConfig);
assertTrue(PolicyManagerServlet.getServiceTypeNamesList().size() > 0);
@@ -173,18 +206,15 @@ public class PolicyManagerServletTest extends Mockito {
}
@Test
- public void testBadInitJson() {
+ public void test02BadInitJson() {
PolicyManagerServlet servlet = new PolicyManagerServlet();
ServletConfig servletConfig = mock(ServletConfig.class);
try {
- when(servletConfig.getInitParameterNames())
- .thenReturn(Collections.enumeration(headers));
- when(servletConfig.getInitParameter("XACML_PROPERTIES_NAME"))
- .thenReturn("xacml.admin.properties");
+ when(servletConfig.getInitParameterNames()).thenReturn(Collections.enumeration(headers));
+ when(servletConfig.getInitParameter("XACML_PROPERTIES_NAME")).thenReturn("xacml.admin.properties");
System.setProperty("xacml.rest.admin.closedLoopJSON",
- new File(".").getCanonicalPath() + File.separator + "src" + File.separator
- + "test" + File.separator + "resources" + File.separator
- + "JSONConfig.foo");
+ new File(".").getCanonicalPath() + File.separator + "src" + File.separator + "test" + File.separator
+ + "resources" + File.separator + "JSONConfig.foo");
servlet.init(servletConfig);
} catch (Exception e1) {
logger.error("Exception Occured" + e1);
@@ -193,18 +223,15 @@ public class PolicyManagerServletTest extends Mockito {
}
@Test
- public void testBadInitJsonInvalidFile() {
+ public void test03BadInitJsonInvalidFile() {
PolicyManagerServlet servlet = new PolicyManagerServlet();
ServletConfig servletConfig = mock(ServletConfig.class);
try {
- when(servletConfig.getInitParameterNames())
- .thenReturn(Collections.enumeration(headers));
- when(servletConfig.getInitParameter("XACML_PROPERTIES_NAME"))
- .thenReturn("xacml.admin.properties");
+ when(servletConfig.getInitParameterNames()).thenReturn(Collections.enumeration(headers));
+ when(servletConfig.getInitParameter("XACML_PROPERTIES_NAME")).thenReturn("xacml.admin.properties");
System.setProperty("xacml.rest.admin.closedLoopJSON",
- new File(".").getCanonicalPath() + File.separator + "src" + File.separator
- + "test" + File.separator + "resources" + File.separator
- + "IDonotExist.json");
+ new File(".").getCanonicalPath() + File.separator + "src" + File.separator + "test" + File.separator
+ + "resources" + File.separator + "IDonotExist.json");
servlet.init(servletConfig);
} catch (Exception e1) {
logger.error("Exception Occured" + e1);
@@ -214,11 +241,11 @@ public class PolicyManagerServletTest extends Mockito {
@SuppressWarnings("static-access")
@Test
- public void testDescribePolicy() {
+ public void test04DescribePolicy() {
PolicyManagerServlet servlet = new PolicyManagerServlet();
PolicyController controller = mock(PolicyController.class);
- BufferedReader reader = new BufferedReader(new StringReader(
- "{params: { mode: 'DESCRIBEPOLICYFILE', path: 'com.Config_SampleTest1206.1.xml'}}"));
+ BufferedReader reader = new BufferedReader(
+ new StringReader("{params: { mode: 'DESCRIBEPOLICYFILE', path: 'com.Config_SampleTest1206.1.xml'}}"));
try {
when(request.getReader()).thenReturn(reader);
String query = "FROM PolicyEntity where policyName = :split_1 and scope = :split_0";
@@ -231,10 +258,9 @@ public class PolicyManagerServletTest extends Mockito {
}
}
-
@SuppressWarnings("static-access")
@Test
- public void testPolicyScopeList() {
+ public void test05PolicyScopeList() {
PolicyManagerServlet servlet = new PolicyManagerServlet();
PolicyController controller = mock(PolicyController.class);
List<String> list = new ArrayList<>();
@@ -245,14 +271,11 @@ public class PolicyManagerServletTest extends Mockito {
try {
when(request.getReader()).thenReturn(reader);
when(controller.getRoles("Test")).thenReturn(rolesdata);
- when(controller.getDataByQuery("from PolicyEditorScopes", null))
+ when(controller.getDataByQuery("from PolicyEditorScopes", null)).thenReturn(policyEditorScopes);
+ when(controller.getDataByQuery("from PolicyEditorScopes where SCOPENAME like :scopeName", null))
.thenReturn(policyEditorScopes);
- when(controller.getDataByQuery(
- "from PolicyEditorScopes where SCOPENAME like :scopeName", null))
- .thenReturn(policyEditorScopes);
- when(controller.getDataByQuery(
- "from PolicyVersion where POLICY_NAME like :scopeName", null))
- .thenReturn(policyVersion);
+ when(controller.getDataByQuery("from PolicyVersion where POLICY_NAME like :scopeName", null))
+ .thenReturn(policyVersion);
servlet.setPolicyController(controller);
servlet.setTestUserId("Test");
servlet.doPost(request, response);
@@ -265,20 +288,18 @@ public class PolicyManagerServletTest extends Mockito {
@SuppressWarnings("static-access")
@Test
- public void editBasePolicyTest() {
+ public void test06editBasePolicyTest() {
PolicyManagerServlet servlet = new PolicyManagerServlet();
PolicyController controller = mock(PolicyController.class);
List<String> list = new ArrayList<>();
- list.add(
- "{params: { mode: 'EDITFILE', path: '/com/Config_SampleTest1206.1.xml', onlyFolders: false}}");
+ list.add("{params: { mode: 'EDITFILE', path: '/com/Config_SampleTest1206.1.xml', onlyFolders: false}}");
for (int i = 0; i < list.size(); i++) {
BufferedReader reader = new BufferedReader(new StringReader(list.get(i)));
try {
when(request.getReader()).thenReturn(reader);
when(controller.getRoles("Test")).thenReturn(rolesdata);
- when(controller.getDataByQuery(
- "FROM PolicyEntity where policyName = :split_1 and scope = :split_0", null))
- .thenReturn(basePolicyData);
+ when(controller.getDataByQuery("FROM PolicyEntity where policyName = :split_1 and scope = :split_0",
+ null)).thenReturn(basePolicyData);
servlet.setPolicyController(controller);
servlet.setTestUserId("Test");
servlet.doPost(request, response);
@@ -291,16 +312,16 @@ public class PolicyManagerServletTest extends Mockito {
@SuppressWarnings("static-access")
@Test
- public void editBRMSParamPolicyTest() {
+ public void test07editBRMSParamPolicyTest() {
List<Object> policyData = new ArrayList<>();
String policyContent = "";
String configData = "";
try {
ClassLoader classLoader = getClass().getClassLoader();
- policyContent = IOUtils.toString(classLoader
- .getResourceAsStream("Config_BRMS_Param_BRMSParamvFWDemoPolicy.1.xml"));
- configData = IOUtils.toString(classLoader
- .getResourceAsStream("com.Config_BRMS_Param_BRMSParamvFWDemoPolicy.1.txt"));
+ policyContent =
+ IOUtils.toString(classLoader.getResourceAsStream("Config_BRMS_Param_BRMSParamvFWDemoPolicy.1.xml"));
+ configData = IOUtils
+ .toString(classLoader.getResourceAsStream("com.Config_BRMS_Param_BRMSParamvFWDemoPolicy.1.txt"));
} catch (Exception e1) {
logger.error("Exception Occured" + e1);
}
@@ -311,25 +332,22 @@ public class PolicyManagerServletTest extends Mockito {
ConfigurationDataEntity configurationEntity = new ConfigurationDataEntity();
configurationEntity.setConfigBody(configData);
configurationEntity.setConfigType("OTHER");
- configurationEntity
- .setConfigurationName("com.Config_BRMS_Param_BRMSParamvFWDemoPolicy.1.txt");
+ configurationEntity.setConfigurationName("com.Config_BRMS_Param_BRMSParamvFWDemoPolicy.1.txt");
configurationEntity.setDescription("test");
entity.setConfigurationData(configurationEntity);
policyData.add(entity);
PolicyManagerServlet servlet = new PolicyManagerServlet();
PolicyController controller = mock(PolicyController.class);
List<String> list = new ArrayList<>();
- list.add(
- "{params: { mode: 'EDITFILE', path: '/com/Config_BRMS_Param_BRMSParamvFWDemoPolicy.1.xml',"
- + " onlyFolders: false}}");
+ list.add("{params: { mode: 'EDITFILE', path: '/com/Config_BRMS_Param_BRMSParamvFWDemoPolicy.1.xml',"
+ + " onlyFolders: false}}");
for (int i = 0; i < list.size(); i++) {
BufferedReader reader = new BufferedReader(new StringReader(list.get(i)));
try {
when(request.getReader()).thenReturn(reader);
when(controller.getRoles("Test")).thenReturn(rolesdata);
- when(controller.getDataByQuery(
- "FROM PolicyEntity where policyName = :split_1 and scope = :split_0", null))
- .thenReturn(policyData);
+ when(controller.getDataByQuery("FROM PolicyEntity where policyName = :split_1 and scope = :split_0",
+ null)).thenReturn(policyData);
servlet.setPolicyController(controller);
servlet.setTestUserId("Test");
servlet.doPost(request, response);
@@ -342,16 +360,16 @@ public class PolicyManagerServletTest extends Mockito {
@SuppressWarnings("static-access")
@Test
- public void editBRMSRawPolicyTest() {
+ public void test08editBRMSRawPolicyTest() {
List<Object> policyData = new ArrayList<>();
String policyContent = "";
String configData = "";
try {
ClassLoader classLoader = getClass().getClassLoader();
- policyContent = IOUtils.toString(
- classLoader.getResourceAsStream("Config_BRMS_Raw_TestBRMSRawPolicy.1.xml"));
- configData = IOUtils.toString(
- classLoader.getResourceAsStream("com.Config_BRMS_Raw_TestBRMSRawPolicy.1.txt"));
+ policyContent =
+ IOUtils.toString(classLoader.getResourceAsStream("Config_BRMS_Raw_TestBRMSRawPolicy.1.xml"));
+ configData =
+ IOUtils.toString(classLoader.getResourceAsStream("com.Config_BRMS_Raw_TestBRMSRawPolicy.1.txt"));
} catch (Exception e1) {
logger.error("Exception Occured" + e1);
}
@@ -369,17 +387,15 @@ public class PolicyManagerServletTest extends Mockito {
PolicyManagerServlet servlet = new PolicyManagerServlet();
PolicyController controller = mock(PolicyController.class);
List<String> list = new ArrayList<>();
- list.add(
- "{params: { mode: 'EDITFILE', path: '/com/Config_BRMS_Raw_TestBRMSRawPolicy.1.xml',"
- + " onlyFolders: false}}");
+ list.add("{params: { mode: 'EDITFILE', path: '/com/Config_BRMS_Raw_TestBRMSRawPolicy.1.xml',"
+ + " onlyFolders: false}}");
for (int i = 0; i < list.size(); i++) {
BufferedReader reader = new BufferedReader(new StringReader(list.get(i)));
try {
when(request.getReader()).thenReturn(reader);
when(controller.getRoles("Test")).thenReturn(rolesdata);
- when(controller.getDataByQuery(
- "FROM PolicyEntity where policyName = :split_1 and scope = :split_0", null))
- .thenReturn(policyData);
+ when(controller.getDataByQuery("FROM PolicyEntity where policyName = :split_1 and scope = :split_0",
+ null)).thenReturn(policyData);
servlet.setPolicyController(controller);
servlet.setTestUserId("Test");
servlet.doPost(request, response);
@@ -392,16 +408,16 @@ public class PolicyManagerServletTest extends Mockito {
@SuppressWarnings("static-access")
@Test
- public void editClosedLoopFaultPolicyTest() {
+ public void test09editClosedLoopFaultPolicyTest() {
List<Object> policyData = new ArrayList<>();
String policyContent = "";
String configData = "";
try {
ClassLoader classLoader = getClass().getClassLoader();
- policyContent = IOUtils.toString(
- classLoader.getResourceAsStream("Config_Fault_TestClosedLoopPolicy.1.xml"));
- configData = IOUtils.toString(classLoader
- .getResourceAsStream("com.Config_Fault_TestClosedLoopPolicy.1.json"));
+ policyContent =
+ IOUtils.toString(classLoader.getResourceAsStream("Config_Fault_TestClosedLoopPolicy.1.xml"));
+ configData =
+ IOUtils.toString(classLoader.getResourceAsStream("com.Config_Fault_TestClosedLoopPolicy.1.json"));
} catch (Exception e1) {
logger.error("Exception Occured" + e1);
}
@@ -419,17 +435,15 @@ public class PolicyManagerServletTest extends Mockito {
PolicyManagerServlet servlet = new PolicyManagerServlet();
PolicyController controller = mock(PolicyController.class);
List<String> list = new ArrayList<>();
- list.add(
- "{params: { mode: 'EDITFILE', path: '/com/Config_Fault_TestClosedLoopPolicy.1.xml',"
- + " onlyFolders: false}}");
+ list.add("{params: { mode: 'EDITFILE', path: '/com/Config_Fault_TestClosedLoopPolicy.1.xml',"
+ + " onlyFolders: false}}");
for (int i = 0; i < list.size(); i++) {
BufferedReader reader = new BufferedReader(new StringReader(list.get(i)));
try {
when(request.getReader()).thenReturn(reader);
when(controller.getRoles("Test")).thenReturn(rolesdata);
- when(controller.getDataByQuery(
- "FROM PolicyEntity where policyName = :split_1 and scope = :split_0", null))
- .thenReturn(policyData);
+ when(controller.getDataByQuery("FROM PolicyEntity where policyName = :split_1 and scope = :split_0",
+ null)).thenReturn(policyData);
servlet.setPolicyController(controller);
servlet.setTestUserId("Test");
servlet.doPost(request, response);
@@ -442,16 +456,15 @@ public class PolicyManagerServletTest extends Mockito {
@SuppressWarnings("static-access")
@Test
- public void editClosedLoopPMPolicyTest() {
+ public void test10editClosedLoopPMPolicyTest() {
List<Object> policyData = new ArrayList<>();
String policyContent = "";
String configData = "";
try {
ClassLoader classLoader = getClass().getClassLoader();
- policyContent = IOUtils.toString(
- classLoader.getResourceAsStream("Config_PM_TestClosedLoopPMPolicy.1.xml"));
- configData = IOUtils.toString(
- classLoader.getResourceAsStream("com.Config_PM_TestClosedLoopPMPolicy.1.json"));
+ policyContent = IOUtils.toString(classLoader.getResourceAsStream("Config_PM_TestClosedLoopPMPolicy.1.xml"));
+ configData =
+ IOUtils.toString(classLoader.getResourceAsStream("com.Config_PM_TestClosedLoopPMPolicy.1.json"));
} catch (Exception e1) {
logger.error("Exception Occured" + e1);
}
@@ -476,9 +489,8 @@ public class PolicyManagerServletTest extends Mockito {
try {
when(request.getReader()).thenReturn(reader);
when(controller.getRoles("Test")).thenReturn(rolesdata);
- when(controller.getDataByQuery(
- "FROM PolicyEntity where policyName = :split_1 and scope = :split_0", null))
- .thenReturn(policyData);
+ when(controller.getDataByQuery("FROM PolicyEntity where policyName = :split_1 and scope = :split_0",
+ null)).thenReturn(policyData);
servlet.setPolicyController(controller);
servlet.setTestUserId("Test");
servlet.doPost(request, response);
@@ -491,7 +503,7 @@ public class PolicyManagerServletTest extends Mockito {
@SuppressWarnings("static-access")
@Test
- public void editMicroServicePolicyTest() {
+ public void test11editMicroServicePolicyTest() {
GroupPolicyScopeList groupData = new GroupPolicyScopeList();
groupData.setGroupName("Test");
groupData.setGroupList("resource=SampleResource,service=SampleService,type=SampleType,"
@@ -505,10 +517,8 @@ public class PolicyManagerServletTest extends Mockito {
String configData = "";
try {
ClassLoader classLoader = getClass().getClassLoader();
- policyContent =
- IOUtils.toString(classLoader.getResourceAsStream("Config_MS_vFirewall.1.xml"));
- configData = IOUtils
- .toString(classLoader.getResourceAsStream("com.Config_MS_vFirewall.1.json"));
+ policyContent = IOUtils.toString(classLoader.getResourceAsStream("Config_MS_vFirewall.1.xml"));
+ configData = IOUtils.toString(classLoader.getResourceAsStream("com.Config_MS_vFirewall.1.json"));
} catch (Exception e1) {
logger.error("Exception Occured" + e1);
}
@@ -526,20 +536,17 @@ public class PolicyManagerServletTest extends Mockito {
PolicyManagerServlet servlet = new PolicyManagerServlet();
PolicyController controller = mock(PolicyController.class);
List<String> list = new ArrayList<>();
- list.add(
- "{params: { mode: 'EDITFILE', path: '/com/Config_MS_vFirewall.1.xml', onlyFolders: false}}");
+ list.add("{params: { mode: 'EDITFILE', path: '/com/Config_MS_vFirewall.1.xml', onlyFolders: false}}");
for (int i = 0; i < list.size(); i++) {
BufferedReader reader = new BufferedReader(new StringReader(list.get(i)));
try {
when(request.getReader()).thenReturn(reader);
when(commonClassDao.getDataById(GroupPolicyScopeList.class, "groupList",
"resource=SampleResource,service=SampleService,type=SampleType,"
- + "closedLoopControlName=SampleClosedLoop"))
- .thenReturn(groupListData);
+ + "closedLoopControlName=SampleClosedLoop")).thenReturn(groupListData);
when(controller.getRoles("Test")).thenReturn(rolesdata);
- when(controller.getDataByQuery(
- "FROM PolicyEntity where policyName = :split_1 and scope = :split_0", null))
- .thenReturn(policyData);
+ when(controller.getDataByQuery("FROM PolicyEntity where policyName = :split_1 and scope = :split_0",
+ null)).thenReturn(policyData);
servlet.setPolicyController(controller);
servlet.setTestUserId("Test");
servlet.doPost(request, response);
@@ -552,16 +559,14 @@ public class PolicyManagerServletTest extends Mockito {
@SuppressWarnings("static-access")
@Test
- public void editFirewallPolicyTest() {
+ public void test12editFirewallPolicyTest() {
List<Object> policyData = new ArrayList<>();
String policyContent = "";
String configData = "";
try {
ClassLoader classLoader = getClass().getClassLoader();
- policyContent = IOUtils.toString(
- classLoader.getResourceAsStream("Config_FW_TestFireWallPolicy.1.xml"));
- configData = IOUtils.toString(
- classLoader.getResourceAsStream("com.Config_FW_TestFireWallPolicy.1.json"));
+ policyContent = IOUtils.toString(classLoader.getResourceAsStream("Config_FW_TestFireWallPolicy.1.xml"));
+ configData = IOUtils.toString(classLoader.getResourceAsStream("com.Config_FW_TestFireWallPolicy.1.json"));
} catch (Exception e1) {
logger.error("Exception Occured" + e1);
}
@@ -586,9 +591,8 @@ public class PolicyManagerServletTest extends Mockito {
try {
when(request.getReader()).thenReturn(reader);
when(controller.getRoles("Test")).thenReturn(rolesdata);
- when(controller.getDataByQuery(
- "FROM PolicyEntity where policyName = :split_1 and scope = :split_0", null))
- .thenReturn(policyData);
+ when(controller.getDataByQuery("FROM PolicyEntity where policyName = :split_1 and scope = :split_0",
+ null)).thenReturn(policyData);
servlet.setPolicyController(controller);
servlet.setTestUserId("Test");
servlet.doPost(request, response);
@@ -601,16 +605,14 @@ public class PolicyManagerServletTest extends Mockito {
@SuppressWarnings("static-access")
@Test
- public void editActionPolicyTest() {
+ public void test13editActionPolicyTest() {
List<Object> policyData = new ArrayList<>();
String policyContent = "";
String configData = "";
try {
ClassLoader classLoader = getClass().getClassLoader();
- policyContent = IOUtils
- .toString(classLoader.getResourceAsStream("Action_TestActionPolicy.1.xml"));
- configData = IOUtils.toString(
- classLoader.getResourceAsStream("com.Action_TestActionPolicy.1.json"));
+ policyContent = IOUtils.toString(classLoader.getResourceAsStream("Action_TestActionPolicy.1.xml"));
+ configData = IOUtils.toString(classLoader.getResourceAsStream("com.Action_TestActionPolicy.1.json"));
} catch (Exception e1) {
logger.error("Exception Occured" + e1);
}
@@ -626,16 +628,14 @@ public class PolicyManagerServletTest extends Mockito {
PolicyManagerServlet servlet = new PolicyManagerServlet();
PolicyController controller = mock(PolicyController.class);
List<String> list = new ArrayList<>();
- list.add("{params: { mode: 'EDITFILE', path: '/com/Action_TestActionPolicy.1.xml',"
- + " onlyFolders: false}}");
+ list.add("{params: { mode: 'EDITFILE', path: '/com/Action_TestActionPolicy.1.xml'," + " onlyFolders: false}}");
for (int i = 0; i < list.size(); i++) {
BufferedReader reader = new BufferedReader(new StringReader(list.get(i)));
try {
when(request.getReader()).thenReturn(reader);
when(controller.getRoles("Test")).thenReturn(rolesdata);
- when(controller.getDataByQuery(
- "FROM PolicyEntity where policyName = :split_1 and scope = :split_0", null))
- .thenReturn(policyData);
+ when(controller.getDataByQuery("FROM PolicyEntity where policyName = :split_1 and scope = :split_0",
+ null)).thenReturn(policyData);
servlet.setPolicyController(controller);
servlet.setTestUserId("Test");
servlet.doPost(request, response);
@@ -648,13 +648,13 @@ public class PolicyManagerServletTest extends Mockito {
@SuppressWarnings("static-access")
@Test
- public void editDecisionPolicyTest() {
+ public void test14editDecisionPolicyTest() {
List<Object> policyData = new ArrayList<>();
String policyContent = "";
try {
ClassLoader classLoader = getClass().getClassLoader();
- policyContent = IOUtils.toString(classLoader
- .getResourceAsStream("Decision_TestDecisionPolicyWithRuleAlgorithms.1.xml"));
+ policyContent = IOUtils
+ .toString(classLoader.getResourceAsStream("Decision_TestDecisionPolicyWithRuleAlgorithms.1.xml"));
} catch (Exception e1) {
logger.error("Exception Occured" + e1);
}
@@ -666,17 +666,15 @@ public class PolicyManagerServletTest extends Mockito {
PolicyManagerServlet servlet = new PolicyManagerServlet();
PolicyController controller = mock(PolicyController.class);
List<String> list = new ArrayList<>();
- list.add(
- "{params: { mode: 'EDITFILE', path: '/com/Decision_TestDecisionPolicyWithRuleAlgorithms.1.xml',"
- + " onlyFolders: false}}");
+ list.add("{params: { mode: 'EDITFILE', path: '/com/Decision_TestDecisionPolicyWithRuleAlgorithms.1.xml',"
+ + " onlyFolders: false}}");
for (int i = 0; i < list.size(); i++) {
BufferedReader reader = new BufferedReader(new StringReader(list.get(i)));
try {
when(request.getReader()).thenReturn(reader);
when(controller.getRoles("Test")).thenReturn(rolesdata);
- when(controller.getDataByQuery(
- "FROM PolicyEntity where policyName = :split_1 and scope = :split_0", null))
- .thenReturn(policyData);
+ when(controller.getDataByQuery("FROM PolicyEntity where policyName = :split_1 and scope = :split_0",
+ null)).thenReturn(policyData);
servlet.setPolicyController(controller);
servlet.setTestUserId("Test");
servlet.doPost(request, response);
@@ -688,23 +686,20 @@ public class PolicyManagerServletTest extends Mockito {
}
@Test
- public void testAddScope() {
+ public void test15AddScope() {
PolicyManagerServlet servlet = new PolicyManagerServlet();
PolicyController controller = mock(PolicyController.class);
List<BufferedReader> readers = new ArrayList<>();
+ readers.add(new BufferedReader(new StringReader("{params: { mode: 'ADDFOLDER', path: '/', name: 'Test'}}")));
+ readers.add(new BufferedReader(new StringReader("{params: { mode: 'ADDFOLDER', path: '/', name: 'Test*&'}}")));
readers.add(new BufferedReader(
- new StringReader("{params: { mode: 'ADDFOLDER', path: '/', name: 'Test'}}")));
- readers.add(new BufferedReader(
- new StringReader("{params: { mode: 'ADDFOLDER', path: '/', name: 'Test*&'}}")));
- readers.add(new BufferedReader(new StringReader(
- "{params: { mode: 'ADDFOLDER', path: '/Test', subScopename: 'Test1'}}")));
+ new StringReader("{params: { mode: 'ADDFOLDER', path: '/Test', subScopename: 'Test1'}}")));
for (int i = 0; i < readers.size(); i++) {
try {
when(request.getReader()).thenReturn(readers.get(i));
PolicyManagerServlet.setPolicyController(controller);
servlet.doPost(request, response);
- assertTrue(response.getContentAsString() != null
- && response.getContentAsString().contains("success"));
+ assertTrue(response.getContentAsString() != null && response.getContentAsString().contains("success"));
} catch (Exception e1) {
logger.error("Exception Occured" + e1);
fail();
@@ -713,25 +708,23 @@ public class PolicyManagerServletTest extends Mockito {
}
@Test
- public void testClone() {
+ public void test16Clone() {
PolicyManagerServlet servlet = new PolicyManagerServlet();
PolicyController controller = mock(PolicyController.class);
List<BufferedReader> readers = new ArrayList<>();
when(controller.getEntityItem(ConfigurationDataEntity.class, "configurationName",
"com.Config_SampleTest1206.1.txt")).thenReturn(configurationEntity);
when(controller.getDataByQuery(
- "FROM PolicyEntity where policyName = :oldPolicySplit_1 and scope = :oldPolicySplit_0",
- null)).thenReturn(basePolicyData);
- readers.add(new BufferedReader(
- new StringReader("{params: { mode: 'COPY', path: 'com.Config_test.1.xml',"
- + " newPath: 'com.Config_testClone.1.xml'}}")));
+ "FROM PolicyEntity where policyName = :oldPolicySplit_1 and scope = :oldPolicySplit_0", null))
+ .thenReturn(basePolicyData);
+ readers.add(new BufferedReader(new StringReader("{params: { mode: 'COPY', path: 'com.Config_test.1.xml',"
+ + " newPath: 'com.Config_testClone.1.xml'}}")));
for (int i = 0; i < readers.size(); i++) {
try {
when(request.getReader()).thenReturn(readers.get(i));
PolicyManagerServlet.setPolicyController(controller);
servlet.doPost(request, response);
- assertTrue(response.getContentAsString() != null
- && response.getContentAsString().contains("success"));
+ assertTrue(response.getContentAsString() != null && response.getContentAsString().contains("success"));
} catch (Exception e1) {
logger.error("Exception Occured" + e1);
fail();
@@ -740,25 +733,23 @@ public class PolicyManagerServletTest extends Mockito {
}
@Test
- public void testRename() {
+ public void test17Rename() {
PolicyManagerServlet servlet = new PolicyManagerServlet();
PolicyController controller = mock(PolicyController.class);
List<BufferedReader> readers = new ArrayList<>();
when(controller.getEntityItem(ConfigurationDataEntity.class, "configurationName",
"com.Config_SampleTest1206.1.txt")).thenReturn(configurationEntity);
when(controller.getDataByQuery(
- "FROM PolicyEntity where policyName = :oldPolicySplit_1 and scope = :oldPolicySplit_0",
- null)).thenReturn(basePolicyData);
- readers.add(new BufferedReader(
- new StringReader("{params: { mode: 'RENAME', path: 'com.Config_test.1.xml',"
- + " newPath: 'com.Config_testClone.1.xml'}}")));
+ "FROM PolicyEntity where policyName = :oldPolicySplit_1 and scope = :oldPolicySplit_0", null))
+ .thenReturn(basePolicyData);
+ readers.add(new BufferedReader(new StringReader("{params: { mode: 'RENAME', path: 'com.Config_test.1.xml',"
+ + " newPath: 'com.Config_testClone.1.xml'}}")));
for (int i = 0; i < readers.size(); i++) {
try {
when(request.getReader()).thenReturn(readers.get(i));
PolicyManagerServlet.setPolicyController(controller);
servlet.doPost(request, response);
- assertTrue(response.getContentAsString() != null
- && response.getContentAsString().contains("success"));
+ assertTrue(response.getContentAsString() != null && response.getContentAsString().contains("success"));
} catch (Exception e1) {
logger.error("Exception Occured" + e1);
fail();
@@ -767,23 +758,402 @@ public class PolicyManagerServletTest extends Mockito {
}
@Test
- public void testRenameScope() {
+ public void test18RenameScope() throws Exception {
PolicyManagerServlet servlet = new PolicyManagerServlet();
PolicyController controller = mock(PolicyController.class);
List<BufferedReader> readers = new ArrayList<>();
- readers.add(new BufferedReader(
- new StringReader("{params: { mode: 'RENAME', path: 'com', newPath: 'Test'}}")));
+ readers.add(new BufferedReader(new StringReader("{params: { mode: 'RENAME', path: 'com', newPath: 'Test'}}")));
for (int i = 0; i < readers.size(); i++) {
try {
when(request.getReader()).thenReturn(readers.get(i));
PolicyManagerServlet.setPolicyController(controller);
servlet.doPost(request, response);
- assertTrue(response.getContentAsString() != null
- && response.getContentAsString().contains("success"));
+ assertTrue(response.getContentAsString() != null && response.getContentAsString().contains("success"));
} catch (Exception e1) {
logger.error("Exception Occured" + e1);
fail();
}
}
+
+ String inScopeName = "\\\\\\\\inScopeName";
+ String newScopeName = "\\\\\\\\newScopeName";
+ List<Object> scopesList = new ArrayList<Object>();
+ PolicyEditorScopes mockPolicyEditorScope = Mockito.mock(PolicyEditorScopes.class);
+ scopesList.add(mockPolicyEditorScope);
+ when(mockPolicyEditorScope.getScopeName()).thenReturn("inScopeName");
+ Whitebox.invokeMethod(servlet, "renameScope", scopesList, inScopeName, newScopeName, controller);
+ verify(mockPolicyEditorScope, atLeast(1)).getScopeName();
+ }
+
+ @Test
+ public void test19SetPolicyNames() {
+ JsonArray mockJsonArray = Mockito.mock(JsonArray.class);
+ PolicyManagerServlet.setPolicyNames(mockJsonArray);
+ assertEquals(mockJsonArray, PolicyManagerServlet.getPolicyNames());
+ }
+
+ @Test
+ public void test20DoPostSetErrorException() throws IOException {
+ PolicyManagerServlet servlet = new PolicyManagerServlet();
+ HttpServletRequest mockRequest = Mockito.mock(HttpServletRequest.class);
+ HttpServletResponse mockResponse = Mockito.mock(HttpServletResponse.class);
+ doThrow(IOException.class).when(mockRequest).getReader();
+ doThrow(IOException.class).when(mockResponse).sendError(any(Integer.class), any(String.class));
+ servlet.doPost(mockRequest, mockResponse);
+ verify(mockRequest).getReader();
+ }
+
+ @Test
+ public void test21DoPostException() throws IOException {
+ PolicyManagerServlet servlet = new PolicyManagerServlet();
+ HttpServletRequest mockRequest = Mockito.mock(HttpServletRequest.class);
+ HttpServletResponse mockResponse = Mockito.mock(HttpServletResponse.class);
+
+ doThrow(IOException.class).when(mockRequest).getReader();
+ doThrow(IOException.class).when(mockResponse).sendError(any(Integer.class), any(String.class));
+ doThrow(IOException.class).when(mockResponse).getWriter();
+
+ servlet.doPost(mockRequest, mockResponse);
+ verify(mockRequest).getReader();
+ verify(mockResponse).getWriter();
+ }
+
+ @Test
+ public void test22DoPostSuccess() throws IOException {
+ PolicyManagerServlet servlet = new PolicyManagerServlet();
+ HttpServletRequest mockRequest = Mockito.mock(HttpServletRequest.class);
+ HttpServletResponse mockResponse = Mockito.mock(HttpServletResponse.class);
+ PrintWriter mockPrintWriter = Mockito.mock(PrintWriter.class);
+
+ doThrow(IOException.class).when(mockRequest).getReader();
+ when(mockResponse.getWriter()).thenReturn(mockPrintWriter);
+
+ servlet.doPost(null, mockResponse);
+ verify(mockResponse).getWriter();
+ }
+
+ @Test
+ public void test23DoPostUploadFileException() {
+ PolicyManagerServlet servlet = new PolicyManagerServlet() {
+ private static final long serialVersionUID = 1L;
+ @Override
+ protected boolean isMultipartContent(HttpServletRequest request) {
+ return true;
+ }
+ };
+ HttpServletRequest mockRequest = Mockito.mock(HttpServletRequest.class);
+ HttpServletResponse mockResponse = Mockito.mock(HttpServletResponse.class);
+ servlet.doPost(mockRequest, mockResponse);
+ }
+
+ @Test
+ public void test24ProcessFormFile() throws Exception {
+ long fileSizeLimit = 10;
+
+ PolicyManagerServlet servlet = new PolicyManagerServlet() {
+ private static final long serialVersionUID = 1L;
+
+ @Override
+ protected long getFileSizeLimit() {
+ return fileSizeLimit;
+ }
+
+ @Override
+ protected long copyStream(InputStream inputStream, OutputStream outputStream) throws IOException {
+ // don't really copy the file
+ return 0;
+ }
+ };
+ HttpServletRequest mockRequest = Mockito.mock(HttpServletRequest.class);
+ HttpServletResponse mockResp = Mockito.mock(HttpServletResponse.class);
+ FileItem mockFileItem = Mockito.mock(FileItem.class);
+ InputStream mockInputStream = Mockito.mock(InputStream.class);
+
+ when(mockFileItem.getName()).thenReturn("testFileName.xls");
+ when(mockFileItem.getInputStream()).thenReturn(mockInputStream);
+ when(mockFileItem.getSize()).thenReturn(fileSizeLimit + 1);
+
+ Whitebox.invokeMethod(servlet, "processFormFile", mockRequest, mockFileItem, mockResp);
+ verify(mockFileItem, atLeast(1)).getName();
+ verify(mockFileItem, atLeast(1)).getSize();
+
+ when(mockFileItem.getName()).thenReturn("testFileName.txt");
+ Whitebox.invokeMethod(servlet, "processFormFile", mockRequest, mockFileItem, mockResp);
+ verify(mockFileItem, atLeast(1)).getName();
+
+ when(mockFileItem.getSize()).thenReturn(fileSizeLimit);
+ when(mockFileItem.getName()).thenReturn("testFileName.xls");
+ when(mockFileItem.getInputStream()).thenThrow(IOException.class);
+ Whitebox.invokeMethod(servlet, "processFormFile", mockRequest, mockFileItem, mockResp);
+ verify(mockFileItem, atLeast(1)).getName();
+ verify(mockFileItem, atLeast(1)).getInputStream();
+ verify(mockFileItem, atLeast(1)).getSize();
+ }
+
+ @Test
+ public void test25SearchPolicyList() throws Exception {
+ PolicyManagerServlet servlet = new PolicyManagerServlet();
+ HttpServletRequest mockRequest = Mockito.mock(HttpServletRequest.class);
+ JSONObject mockJSONObject = Mockito.mock(JSONObject.class);
+
+ mockJSONObject.append("policyList", "sampleValue");
+
+ Object res = Whitebox.invokeMethod(servlet, "searchPolicyList", mockJSONObject, mockRequest);
+ assert (res instanceof JSONObject);
+ assertNotNull(((JSONObject) res).get("result"));
+ }
+
+ @Test
+ public void test26LookupPolicyData() throws Exception {
+ HttpServletRequest mockRequest = Mockito.mock(HttpServletRequest.class);
+ User mockUser = Mockito.mock(User.class);
+ UserInfo mockUserInfo = Mockito.mock(UserInfo.class);
+ PolicyController mockPolicyController = Mockito.mock(PolicyController.class);
+ List<JSONObject> resultList = new ArrayList<>();
+ JSONObject mockJSONObject = Mockito.mock(JSONObject.class);
+ resultList.add(mockJSONObject);
+
+ Date mockDate = Mockito.mock(Date.class);
+ List<Object> policyDataList = new ArrayList<>();
+ PolicyVersion mockPolicyVersion = Mockito.mock(PolicyVersion.class);
+ policyDataList.add(mockPolicyVersion);
+ JSONArray mockJSONArray = Mockito.mock(JSONArray.class);
+
+ List<Object> rolesList = new ArrayList<>();
+ Roles adminRole = Mockito.mock(Roles.class);
+ Roles editorRole = Mockito.mock(Roles.class);
+ Roles guestRole = Mockito.mock(Roles.class);
+ adminRole.setRole("admin");
+ editorRole.setRole("editor");
+ guestRole.setRole("guest");
+
+ List<Object> filterDataList = new ArrayList<>();
+ PolicyVersion mockPolicyVersionFilter = Mockito.mock(PolicyVersion.class);
+ filterDataList.add(mockPolicyVersionFilter);
+ List<String> listOfRoles = new ArrayList<String>();
+ Set<String> setOfScopes = new HashSet<String>();
+ Pair<Set<String>, List<String>> pairList = new Pair<Set<String>, List<String>>(setOfScopes, listOfRoles);
+
+ PolicyManagerServlet servlet = new PolicyManagerServlet() {
+ private static final long serialVersionUID = 1L;
+
+ @Override
+ protected User getUserSession(HttpServletRequest request) {
+ return mockUser;
+ }
+
+ @Override
+ protected Pair<Set<String>, List<String>> checkRoleAndScope(List<Object> userRoles) {
+ return pairList;
+ }
+ };
+
+ PolicyManagerServlet.setPolicyController(mockPolicyController);
+ when(mockPolicyController.getRoles(any(String.class))).thenReturn(rolesList);
+ when(mockPolicyController.getData(any(Class.class))).thenReturn(filterDataList);
+ when(mockPolicyVersion.getPolicyName()).thenReturn("sampleName");
+ when(mockPolicyVersion.getModifiedDate()).thenReturn(mockDate);
+ when(mockPolicyVersion.getActiveVersion()).thenReturn(1);
+ when(mockPolicyVersion.getCreatedBy()).thenReturn("sampleUserName");
+ when(mockPolicyVersion.getModifiedBy()).thenReturn("sampleUserName");
+ when(mockPolicyController.getEntityItem(UserInfo.class, "userLoginId", "sampleUserName"))
+ .thenReturn(mockUserInfo);
+ when(mockUserInfo.getUserName()).thenReturn("testUserName");
+
+ Whitebox.invokeMethod(servlet, "getPolicyControllerInstance");
+
+ boolean result = Whitebox.invokeMethod(servlet, "lookupPolicyData", mockRequest, policyDataList, null,
+ mockPolicyController, resultList);
+
+ assertTrue(result);
+ verify(mockPolicyController, atLeast(1)).getRoles(any());
+ verify(mockPolicyController, atLeast(1)).getRoles(any());
+ verify(mockPolicyController, atLeast(1)).getData(any());
+ verify(mockPolicyController, atLeast(1)).getEntityItem(UserInfo.class, "userLoginId", "sampleUserName");
+ verify(mockPolicyVersion, atLeast(1)).getPolicyName();
+ verify(mockPolicyVersion, atLeast(1)).getModifiedDate();
+ verify(mockPolicyVersion, atLeast(1)).getActiveVersion();
+ verify(mockPolicyVersion, atLeast(1)).getCreatedBy();
+ verify(mockPolicyVersion, atLeast(1)).getModifiedBy();
+ verify(mockUserInfo, atLeast(1)).getUserName();
+
+ when(mockPolicyVersionFilter.getPolicyName()).thenReturn("testAdminScope" + File.separator);
+ result = Whitebox.invokeMethod(servlet, "lookupPolicyData", mockRequest, policyDataList, null,
+ mockPolicyController, resultList);
+ assertTrue(result);
+ verify(mockPolicyVersionFilter, atLeast(1)).getPolicyName();
+
+ setOfScopes.add("testAdminScope");
+ result = Whitebox.invokeMethod(servlet, "lookupPolicyData", mockRequest, policyDataList, null,
+ mockPolicyController, resultList);
+ assertTrue(result);
+ verify(mockPolicyVersionFilter, atLeast(1)).getPolicyName();
+
+ listOfRoles.add("super-admin");
+ listOfRoles.add("super-editor");
+ listOfRoles.add("super-guest");
+ filterDataList.clear();
+
+ result = Whitebox.invokeMethod(servlet, "lookupPolicyData", mockRequest, policyDataList, null,
+ mockPolicyController, resultList);
+ assertTrue(result);
+ verify(mockPolicyController, atLeast(1)).getData(any(Class.class));
+
+ listOfRoles.clear();
+ listOfRoles.add("admin");
+ listOfRoles.add("editor");
+ listOfRoles.add("guest");
+ setOfScopes.clear();
+ result = Whitebox.invokeMethod(servlet, "lookupPolicyData", mockRequest, policyDataList, null,
+ mockPolicyController, resultList);
+ assertFalse(result);
+
+ setOfScopes.add("testScope");
+ result = Whitebox.invokeMethod(servlet, "lookupPolicyData", mockRequest, policyDataList, mockJSONArray,
+ mockPolicyController, resultList);
+ assertTrue(result);
+ }
+
+ @Test
+ public void test27DeleteEntityFromEsAndPolicyEntityTable() throws Exception {
+ PolicyManagerServlet servlet = new PolicyManagerServlet();
+ PolicyController mockPolicyController = Mockito.mock(PolicyController.class);
+ PolicyRestController mockPolicyRestController = Mockito.mock(PolicyRestController.class);
+ PolicyEntity mockPolicyEntity = Mockito.mock(PolicyEntity.class);
+ ConfigurationDataEntity mockConfigDataEntity = Mockito.mock(ConfigurationDataEntity.class);
+ ActionBodyEntity mockActionBodyEntity = Mockito.mock(ActionBodyEntity.class);
+
+ String policyNamewithoutExtension = "Config_";
+ String configName = "";
+ String actionBodyName = "";
+
+ when(mockPolicyEntity.getScope()).thenReturn("");
+ when(mockPolicyEntity.getPolicyName()).thenReturn("");
+ Mockito.doNothing().when(mockPolicyRestController).deleteElasticData(any(String.class));
+ Mockito.doNothing().when(mockPolicyController).deleteData(mockPolicyEntity);
+ when(mockPolicyEntity.getConfigurationData()).thenReturn(mockConfigDataEntity);
+ when(mockPolicyEntity.getActionBodyEntity()).thenReturn(mockActionBodyEntity);
+ when(mockConfigDataEntity.getConfigurationName()).thenReturn(configName);
+ when(mockActionBodyEntity.getActionBodyName()).thenReturn(actionBodyName);
+ when(mockPolicyRestController.notifyOtherPapsToUpdateConfigurations("delete", null, configName)).thenReturn("");
+
+ Whitebox.invokeMethod(servlet, "deleteEntityFromEsAndPolicyEntityTable", mockPolicyController,
+ mockPolicyRestController, mockPolicyEntity, policyNamewithoutExtension);
+
+ verify(mockPolicyEntity, atLeast(1)).getScope();
+ verify(mockPolicyEntity, atLeast(1)).getPolicyName();
+ verify(mockPolicyEntity, atLeast(1)).getConfigurationData();
+ verify(mockConfigDataEntity, atLeast(1)).getConfigurationName();
+
+ policyNamewithoutExtension = "Action_";
+ when(mockPolicyRestController.notifyOtherPapsToUpdateConfigurations("delete", null, actionBodyName))
+ .thenReturn("");
+
+ Whitebox.invokeMethod(servlet, "deleteEntityFromEsAndPolicyEntityTable", mockPolicyController,
+ mockPolicyRestController, mockPolicyEntity, policyNamewithoutExtension);
+
+ verify(mockPolicyEntity, atLeast(1)).getScope();
+ verify(mockPolicyEntity, atLeast(1)).getPolicyName();
+ verify(mockPolicyEntity, atLeast(1)).getActionBodyEntity();
+ verify(mockActionBodyEntity, atLeast(1)).getActionBodyName();
+
+ policyNamewithoutExtension = "Other_";
+ Whitebox.invokeMethod(servlet, "deleteEntityFromEsAndPolicyEntityTable", mockPolicyController,
+ mockPolicyRestController, mockPolicyEntity, policyNamewithoutExtension);
+
+ verify(mockPolicyEntity, atLeast(1)).getScope();
+ verify(mockPolicyEntity, atLeast(1)).getPolicyName();
+ verify(mockPolicyRestController, atLeast(1)).deleteElasticData(any(String.class));
+ verify(mockPolicyController, atLeast(1)).deleteData(mockPolicyEntity);
+ }
+
+ @Test
+ public void test28Delete() throws Exception {
+ JSONObject mockJSONObject = Mockito.mock(JSONObject.class);
+ HttpServletRequest mockRequest = Mockito.mock(HttpServletRequest.class);
+ User mockUser = Mockito.mock(User.class);
+ PolicyController mockPolicyController = Mockito.mock(PolicyController.class);
+ List<Object> policyEntityList = new ArrayList<Object>();
+ PolicyEntity mockPolicyEntity = Mockito.mock(PolicyEntity.class);
+ policyEntityList.add(mockPolicyEntity);
+ long policyId = 1;
+
+ PolicyManagerServlet servlet = new PolicyManagerServlet() {
+ private static final long serialVersionUID = 1L;
+
+ @Override
+ protected User getUserSession(HttpServletRequest request) {
+ return mockUser;
+ }
+ };
+
+ PolicyManagerServlet.setPolicyController(mockPolicyController);
+ when(mockUser.getOrgUserId()).thenReturn("sampleUserId");
+ when(mockJSONObject.getString("path")).thenReturn("/sampleScope:samplePolicyName.1.xml");
+ when(mockJSONObject.has("deleteVersion")).thenReturn(true);
+ when(mockJSONObject.getString("deleteVersion")).thenReturn("ALL");
+ when(mockPolicyController.getDataByQuery(any(String.class), any(SimpleBindings.class)))
+ .thenReturn(policyEntityList);
+ when(mockPolicyEntity.getPolicyId()).thenReturn(policyId);
+ when(mockPolicyEntity.getScope()).thenReturn("sampleScope");
+ when(mockPolicyEntity.getPolicyName()).thenReturn("samplePolicyName");
+
+ JSONObject returnObj = Whitebox.invokeMethod(servlet, "delete", mockJSONObject, mockRequest);
+ assertTrue(returnObj.has("result"));
+ verify(mockUser, atLeast(1)).getOrgUserId();
+ verify(mockJSONObject, atLeast(1)).getString(any(String.class));
+ verify(mockJSONObject, atLeast(1)).has(any(String.class));
+ verify(mockPolicyController, atLeast(1)).getDataByQuery(any(String.class), any(SimpleBindings.class));
+ verify(mockPolicyEntity, atLeast(1)).getPolicyId();
+ verify(mockPolicyEntity, atLeast(1)).getScope();
+ verify(mockPolicyEntity, atLeast(1)).getPolicyName();
+
+ when(mockJSONObject.getString("path")).thenReturn("/sampleScope\\:samplePolicyName.1.xml");
+ when(mockJSONObject.getString("deleteVersion")).thenReturn("CURRENT");
+ returnObj = Whitebox.invokeMethod(servlet, "delete", mockJSONObject, mockRequest);
+ assertTrue(returnObj.has("result"));
+ verify(mockJSONObject, atLeast(1)).getString(any(String.class));
+
+ when(mockJSONObject.getString("path")).thenReturn("/sampleScope:samplePolicyName.2.txt");
+ when(mockJSONObject.has("deleteVersion")).thenReturn(false);
+ returnObj = Whitebox.invokeMethod(servlet, "delete", mockJSONObject, mockRequest);
+ assertTrue(returnObj.has("result"));
+ verify(mockJSONObject, atLeast(1)).getString("path");
+ verify(mockJSONObject, atLeast(1)).has("deleteVersion");
+ }
+
+ @Test
+ public void test29ParsePolicyList() throws Exception {
+ PolicyManagerServlet servlet = new PolicyManagerServlet();
+ List<JSONObject> resultList = new ArrayList<JSONObject>();
+ PolicyController mockPolicyController = Mockito.mock(PolicyController.class);
+ UserInfo mockUserInfo = Mockito.mock(UserInfo.class);
+ String policyName = "sampleName\\";
+ String policyVersion = "sampleVersion";
+ List<Object> activeDataList = new ArrayList<Object>();
+ PolicyVersion mockPolicyVersion = Mockito.mock(PolicyVersion.class);
+ activeDataList.add(mockPolicyVersion);
+ Date mockDate = Mockito.mock(Date.class);
+
+ when(mockPolicyController.getDataByQuery(any(String.class), any(SimpleBindings.class)))
+ .thenReturn(activeDataList);
+ when(mockPolicyVersion.getPolicyName()).thenReturn("testPolicyName");
+ when(mockPolicyVersion.getModifiedDate()).thenReturn(mockDate);
+ when(mockPolicyVersion.getActiveVersion()).thenReturn(1);
+ when(mockPolicyVersion.getCreatedBy()).thenReturn("sampleUserName");
+ when(mockPolicyVersion.getModifiedBy()).thenReturn("sampleUserName");
+ //
+ // This intermittently throws an NPE, even when fixing the method order
+ //
+ when(mockPolicyController.getEntityItem(UserInfo.class, "userLoginId", "sampleUserName"))
+ .thenReturn(mockUserInfo);
+ when(mockUserInfo.getUserName()).thenReturn("testUserName");
+ Whitebox.invokeMethod(servlet, "parsePolicyList", resultList, mockPolicyController, policyName, policyVersion);
+ verify(mockPolicyController, atLeast(1)).getDataByQuery(any(String.class), any(SimpleBindings.class));
+ verify(mockPolicyVersion, atLeast(1)).getPolicyName();
+ verify(mockPolicyVersion, atLeast(1)).getModifiedDate();
+ verify(mockPolicyVersion, atLeast(1)).getActiveVersion();
+ verify(mockPolicyVersion, atLeast(1)).getCreatedBy();
+ verify(mockPolicyVersion, atLeast(1)).getModifiedBy();
}
}
diff --git a/POLICY-SDK-APP/src/test/java/org/onap/policy/admin/PolicyNotificationMailTest.java b/POLICY-SDK-APP/src/test/java/org/onap/policy/admin/PolicyNotificationMailTest.java
index 95296f4b0..5111ef2a8 100644
--- a/POLICY-SDK-APP/src/test/java/org/onap/policy/admin/PolicyNotificationMailTest.java
+++ b/POLICY-SDK-APP/src/test/java/org/onap/policy/admin/PolicyNotificationMailTest.java
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP Policy Engine
* ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017, 2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Modifications Copyright (C) 2019 Samsung
* ================================================================================
@@ -19,16 +19,20 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.policy.admin;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
import java.util.ArrayList;
import java.util.List;
+
import org.junit.Before;
import org.junit.Test;
-import static org.mockito.Mockito.when;
+import org.onap.policy.common.utils.network.NetworkUtil;
import org.onap.policy.controller.PolicyController;
import org.onap.policy.rest.dao.CommonClassDao;
import org.onap.policy.rest.jpa.PolicyVersion;
@@ -41,16 +45,27 @@ public class PolicyNotificationMailTest {
private CommonClassDao commonClassDao;
private List<Object> data = null;
+ /**
+ * setUp.
+ *
+ * @throws Exception should not throw one
+ */
@Before
public void setUp() throws Exception {
PolicyController.setjUnit(true);
PolicyController.setSmtpApplicationName("Test");
PolicyController.setSmtpEmailExtension("test.com");
- PolicyController.setSmtpHost("test");
- PolicyController.setSmtpPort("23");
+ PolicyController.setSmtpHost("localhost");
PolicyController.setSmtpPassword("test");
PolicyController.setSmtpUsername("test");
+ /*
+ * Allocate a port to which the mail sender should connect, but don't actually
+ * start a listener on the port so that connection attempts will be immediately
+ * rejected.
+ */
+ PolicyController.setSmtpPort(String.valueOf(NetworkUtil.allocPort()));
+
version = new PolicyVersion();
version.setPolicyName("com/Config_Test");
version.setModifiedBy("xyz");
@@ -62,9 +77,8 @@ public class PolicyNotificationMailTest {
commonClassDao = mock(CommonClassDao.class);
PolicyController.setCommonClassDao(commonClassDao);
- when(commonClassDao.getDataByQuery(
- "from WatchPolicyNotificationTable where policyName like:policyFileName", null))
- .thenReturn(data);
+ when(commonClassDao.getDataByQuery("from WatchPolicyNotificationTable where policyName like:policyFileName",
+ null)).thenReturn(data);
}
@Test
diff --git a/POLICY-SDK-APP/src/test/java/org/onap/policy/admin/PolicyRestControllerTest.java b/POLICY-SDK-APP/src/test/java/org/onap/policy/admin/PolicyRestControllerTest.java
index ce38f236f..6c47b3955 100644
--- a/POLICY-SDK-APP/src/test/java/org/onap/policy/admin/PolicyRestControllerTest.java
+++ b/POLICY-SDK-APP/src/test/java/org/onap/policy/admin/PolicyRestControllerTest.java
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP Policy Engine
* ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017, 2019-2020 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Modifications Copyright (C) 2019 Samsung
* ================================================================================
@@ -19,26 +19,40 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.policy.admin;
+import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertNull;
import static org.junit.Assert.fail;
+import static org.mockito.Mockito.atLeast;
import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.reset;
+import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
+
import java.io.BufferedReader;
import java.io.IOException;
+import java.io.InputStream;
+import java.io.PrintWriter;
import java.io.StringReader;
+import java.net.HttpURLConnection;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.junit.Before;
import org.junit.Test;
+import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.onap.policy.controller.CreateFirewallController;
+import org.onap.policy.controller.PolicyController;
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.FWTagPicker;
+import org.onap.policy.rest.jpa.FwTagPicker;
import org.onap.policy.rest.jpa.GroupServiceList;
import org.onap.policy.rest.jpa.PrefixList;
import org.onap.policy.rest.jpa.SecurityZone;
@@ -46,8 +60,16 @@ import org.onap.policy.rest.jpa.ServiceList;
import org.onap.policy.rest.jpa.TermList;
import org.onap.portalsdk.core.domain.User;
import org.onap.portalsdk.core.util.SystemProperties;
+import org.onap.portalsdk.core.web.support.UserUtils;
+import org.powermock.api.mockito.PowerMockito;
+import org.powermock.core.classloader.annotations.PowerMockIgnore;
+import org.powermock.core.classloader.annotations.PrepareForTest;
+import org.powermock.modules.junit4.PowerMockRunner;
+import org.powermock.reflect.Whitebox;
import org.springframework.mock.web.MockHttpServletResponse;
+@RunWith(PowerMockRunner.class)
+@PowerMockIgnore({"com.sun.org.apache.xerces.*", "javax.xml.*", "org.xml.*", "com.sun.org.apache.xalan.*"})
public class PolicyRestControllerTest {
private String clRequestString;
@@ -65,77 +87,78 @@ public class PolicyRestControllerTest {
private List<Object> tagListData;
private List<Object> termListData;
+ /**
+ * Before.
+ *
+ * @throws Exception exception
+ */
@Before
public void setUp() throws Exception {
commonClassDao = mock(CommonClassDao.class);
- HttpSession mockSession = mock(HttpSession.class);
+ final HttpSession mockSession = mock(HttpSession.class);
request = mock(HttpServletRequest.class);
response = new MockHttpServletResponse();
User user = new User();
user.setOrgUserId("Test");
- Mockito.when(mockSession.getAttribute(SystemProperties.getProperty("user_attribute_name")))
- .thenReturn(user);
+ Mockito.when(mockSession.getAttribute(SystemProperties.getProperty("user_attribute_name"))).thenReturn(user);
Mockito.when(request.getSession(false)).thenReturn(mockSession);
- clRequestString =
- "{\"policyData\":{\"error\":\"\",\"inprocess\":false,\"model\":{\"name\":\"com\","
- + "\"subScopename\":\"\",\"path\":[],\"type\":\"dir\",\"size\":0,"
- + "\"date\":\"2017-06-01T15:45:36.000Z\",\"version\":\"\",\"createdBy\":\"Demo\","
- + "\"modifiedBy\":\"Demo\",\"content\":\"\",\"recursive\":false},"
- + "\"tempModel\":{\"name\":\"com\",\"subScopename\":\"\",\"path\":[],\"type\":\"dir\","
- + "\"size\":0,\"date\":\"2017-06-01T15:45:36.000Z\",\"version\":\"\",\"createdBy\":\"Demo\","
- + "\"modifiedBy\":\"Demo\",\"content\":\"\",\"recursive\":false},"
- + "\"$$hashKey\":\"object:1439\",\"policy\":{\"policyType\":\"Config\","
- + "\"configPolicyType\":\"ClosedLoop_Fault\",\"triggerTrapSignatures\":[1,1,2,3],"
- + "\"triggerfaultSignatures\":[1,1,2,3],\"traptriggerSignatures\":[{\"id\":\"Trap1\","
- + "\"$$hashKey\":\"object:1526\"},{\"id\":\"Trap2\",\"$$hashKey\":\"object:1534\"}],"
- + "\"connecttriggerSignatures\":[{\"id\":\"C1\",\"$$hashKey\":\"object:1554\","
- + "\"notBox\":\"NOT\",\"connectTrap1\":\"Trap1\",\"trapCount1\":\"12\","
- + "\"operatorBox\":\"AND\",\"connectTrap2\":\"Trap2\",\"trapCount2\":\"14\"}],"
- + "\"faulttriggerSignatures\":[{\"id\":\"Fault1\",\"$$hashKey\":\"object:1566\"},"
- + "{\"id\":\"Fault2\",\"$$hashKey\":\"object:1575\"}],\"connectVerificationSignatures\":"
- + "[{\"id\":\"C1\",\"$$hashKey\":\"object:1595\",\"notBox\":\"NOT\","
- + "\"connectTrap1\":\"Fault1\",\"trapCount1\":\"11\",\"operatorBox\":\"AND\","
- + "\"connectTrap2\":\"Fault2\",\"trapCount2\":\"12\"}],\"jsonBodyData\":"
- + "{\"trapMaxAge\":\"300\",\"vnfType\":\"Test\",\"closedLoopPolicyStatus\":\"Active\","
- + "\"vUSP\":true,\"trinity\":true,\"vDNS\":true,\"mcr\":true,\"gamma\":true,"
- + "\"actions\":\"Test\",\"timeInterval\":\"11\",\"timeOutvPRO\":\"11\",\"timeOutRuby\":\"11\","
- + "\"retrys\":\"1\",\"agingWindow\":\"12\",\"geoLink\":\"test\","
- + "\"emailAddress\":\"aa@test.com\",\"pepName\":\"Test\",\"pepAction\":\"test\","
- + "\"conditions\":\"SEND\"},\"policyName\":\"SampleTest\","
- + "\"policyDescription\":\"SampleTest\",\"riskType\":\"SampleRiskType\",\"riskLevel\":\"1\","
- + "\"guard\":\"True\",\"onapName\":\"SampleDemo\",\"ttlDate\":\"14/09/2017\","
- + "\"clearTimeOut\":\"123\",\"trapMaxAge\":\"11\",\"verificationclearTimeOut\":\"13\"}},"
- + "\"trapData\":{\"trap1\":[{\"id\":\"A1\",\"$$hashKey\":\"object:1528\","
- + "\"notBox\":\"NOT\",\"trigger1\":\"Test\",\"operatorBox\":\"AND\",\"trigger2\":\"Test\"}],"
- + "\"trap2\":[{\"id\":\"A1\",\"$$hashKey\":\"object:1536\",\"notBox\":\"NOT\","
- + "\"trigger1\":\"Test\",\"operatorBox\":\"AND\",\"trigger2\":\"Test\"},{\"id\":\"A2\","
- + "\"$$hashKey\":\"object:1542\",\"notBox\":\"NOT\",\"trigger1\":\"A1\","
- + "\"operatorBox\":\"AND\",\"trigger2\":\"Test\"},{\"id\":\"A3\","
- + "\"$$hashKey\":\"object:1548\",\"notBox\":\"NOT\",\"trigger1\":\"A1\","
- + "\"operatorBox\":\"OR\",\"trigger2\":\"A2\"}]},\"faultData\":{\"trap1\":[{\"id\":\"A1\","
- + "\"$$hashKey\":\"object:1568\",\"notBox\":\"NOT\",\"trigger1\":\"Test\","
- + "\"operatorBox\":\"AND\",\"trigger2\":\"Test\"}],\"trap2\":[{\"id\":\"A1\","
- + "\"$$hashKey\":\"object:1577\",\"notBox\":\"NOT\",\"trigger1\":\"Test\","
- + "\"operatorBox\":\"AND\",\"trigger2\":\"Test\"},{\"id\":\"A2\",\"$$hashKey\":"
- + "\"object:1583\",\"notBox\":\"NOT\",\"trigger1\":\"Test\",\"operatorBox\":\"OR\","
- + "\"trigger2\":\"Test\"},{\"id\":\"A3\",\"$$hashKey\":\"object:1589\",\"notBox\":\"NOT\","
- + "\"trigger1\":\"A1\",\"operatorBox\":\"AND\",\"trigger2\":\"A2\"}]}}";
-
-
- fwRequestString =
- "{\"policyData\":{\"error\":\"\",\"inprocess\":false,\"model\":{\"name\":\"com\","
- + "\"subScopename\":\"\",\"path\":[],\"type\":\"dir\",\"size\":0,"
- + "\"date\":\"2017-06-01T15:45:36.000Z\",\"version\":\"\",\"createdBy\":\"Demo\","
- + "\"modifiedBy\":\"Demo\",\"content\":\"\",\"recursive\":false},\"tempModel\":"
- + "{\"name\":\"com\",\"subScopename\":\"\",\"path\":[],\"type\":\"dir\",\"size\":0,"
- + "\"date\":\"2017-06-01T15:45:36.000Z\",\"version\":\"\",\"createdBy\":\"Demo\","
- + "\"modifiedBy\":\"Demo\",\"content\":\"\",\"recursive\":false},\"$$hashKey\":\"object:260\","
- + "\"policy\":{\"policyType\":\"Config\",\"configPolicyType\":\"Firewall Config\","
- + "\"attributes\":[{\"id\":\"choice1\",\"$$hashKey\":\"object:338\",\"key\":\"Test\","
- + "\"value\":\"Test\"}],\"fwattributes\":[],\"policyName\":\"SampleTest\","
- + "\"policyDescription\":\"SampleTest\",\"riskType\":\"SampleRiskType\",\"riskLevel\":\"1\","
- + "\"guard\":\"True\",\"configName\":\"SampleTest\",\"ttlDate\":\"14/09/2017\","
- + "\"securityZone\":\"Test\"}}}";
+ clRequestString = "{\"policyData\":{\"error\":\"\",\"inprocess\":false,\"model\":{\"name\":\"com\","
+ + "\"subScopename\":\"\",\"path\":[],\"type\":\"dir\",\"size\":0,"
+ + "\"date\":\"2017-06-01T15:45:36.000Z\",\"version\":\"\",\"createdBy\":\"Demo\","
+ + "\"modifiedBy\":\"Demo\",\"content\":\"\",\"recursive\":false},"
+ + "\"tempModel\":{\"name\":\"com\",\"subScopename\":\"\",\"path\":[],\"type\":\"dir\","
+ + "\"size\":0,\"date\":\"2017-06-01T15:45:36.000Z\",\"version\":\"\",\"createdBy\":\"Demo\","
+ + "\"modifiedBy\":\"Demo\",\"content\":\"\",\"recursive\":false},"
+ + "\"$$hashKey\":\"object:1439\",\"policy\":{\"policyType\":\"Config\","
+ + "\"configPolicyType\":\"ClosedLoop_Fault\",\"triggerTrapSignatures\":[1,1,2,3],"
+ + "\"triggerfaultSignatures\":[1,1,2,3],\"traptriggerSignatures\":[{\"id\":\"Trap1\","
+ + "\"$$hashKey\":\"object:1526\"},{\"id\":\"Trap2\",\"$$hashKey\":\"object:1534\"}],"
+ + "\"connecttriggerSignatures\":[{\"id\":\"C1\",\"$$hashKey\":\"object:1554\","
+ + "\"notBox\":\"NOT\",\"connectTrap1\":\"Trap1\",\"trapCount1\":\"12\","
+ + "\"operatorBox\":\"AND\",\"connectTrap2\":\"Trap2\",\"trapCount2\":\"14\"}],"
+ + "\"faulttriggerSignatures\":[{\"id\":\"Fault1\",\"$$hashKey\":\"object:1566\"},"
+ + "{\"id\":\"Fault2\",\"$$hashKey\":\"object:1575\"}],\"connectVerificationSignatures\":"
+ + "[{\"id\":\"C1\",\"$$hashKey\":\"object:1595\",\"notBox\":\"NOT\","
+ + "\"connectTrap1\":\"Fault1\",\"trapCount1\":\"11\",\"operatorBox\":\"AND\","
+ + "\"connectTrap2\":\"Fault2\",\"trapCount2\":\"12\"}],\"jsonBodyData\":"
+ + "{\"trapMaxAge\":\"300\",\"vnfType\":\"Test\",\"closedLoopPolicyStatus\":\"Active\","
+ + "\"vUSP\":true,\"trinity\":true,\"vDNS\":true,\"mcr\":true,\"gamma\":true,"
+ + "\"actions\":\"Test\",\"timeInterval\":\"11\",\"timeOutvPRO\":\"11\",\"timeOutRuby\":\"11\","
+ + "\"retrys\":\"1\",\"agingWindow\":\"12\",\"geoLink\":\"test\","
+ + "\"emailAddress\":\"aa@test.com\",\"pepName\":\"Test\",\"pepAction\":\"test\","
+ + "\"conditions\":\"SEND\"},\"policyName\":\"SampleTest\","
+ + "\"policyDescription\":\"SampleTest\",\"riskType\":\"SampleRiskType\",\"riskLevel\":\"1\","
+ + "\"guard\":\"True\",\"onapName\":\"SampleDemo\",\"ttlDate\":\"14/09/2017\","
+ + "\"clearTimeOut\":\"123\",\"trapMaxAge\":\"11\",\"verificationclearTimeOut\":\"13\"}},"
+ + "\"trapData\":{\"trap1\":[{\"id\":\"A1\",\"$$hashKey\":\"object:1528\","
+ + "\"notBox\":\"NOT\",\"trigger1\":\"Test\",\"operatorBox\":\"AND\",\"trigger2\":\"Test\"}],"
+ + "\"trap2\":[{\"id\":\"A1\",\"$$hashKey\":\"object:1536\",\"notBox\":\"NOT\","
+ + "\"trigger1\":\"Test\",\"operatorBox\":\"AND\",\"trigger2\":\"Test\"},{\"id\":\"A2\","
+ + "\"$$hashKey\":\"object:1542\",\"notBox\":\"NOT\",\"trigger1\":\"A1\","
+ + "\"operatorBox\":\"AND\",\"trigger2\":\"Test\"},{\"id\":\"A3\","
+ + "\"$$hashKey\":\"object:1548\",\"notBox\":\"NOT\",\"trigger1\":\"A1\","
+ + "\"operatorBox\":\"OR\",\"trigger2\":\"A2\"}]},\"faultData\":{\"trap1\":[{\"id\":\"A1\","
+ + "\"$$hashKey\":\"object:1568\",\"notBox\":\"NOT\",\"trigger1\":\"Test\","
+ + "\"operatorBox\":\"AND\",\"trigger2\":\"Test\"}],\"trap2\":[{\"id\":\"A1\","
+ + "\"$$hashKey\":\"object:1577\",\"notBox\":\"NOT\",\"trigger1\":\"Test\","
+ + "\"operatorBox\":\"AND\",\"trigger2\":\"Test\"},{\"id\":\"A2\",\"$$hashKey\":"
+ + "\"object:1583\",\"notBox\":\"NOT\",\"trigger1\":\"Test\",\"operatorBox\":\"OR\","
+ + "\"trigger2\":\"Test\"},{\"id\":\"A3\",\"$$hashKey\":\"object:1589\",\"notBox\":\"NOT\","
+ + "\"trigger1\":\"A1\",\"operatorBox\":\"AND\",\"trigger2\":\"A2\"}]}}";
+
+ fwRequestString = "{\"policyData\":{\"error\":\"\",\"inprocess\":false,\"model\":{\"name\":\"com\","
+ + "\"subScopename\":\"\",\"path\":[],\"type\":\"dir\",\"size\":0,"
+ + "\"date\":\"2017-06-01T15:45:36.000Z\",\"version\":\"\",\"createdBy\":\"Demo\","
+ + "\"modifiedBy\":\"Demo\",\"content\":\"\",\"recursive\":false},\"tempModel\":"
+ + "{\"name\":\"com\",\"subScopename\":\"\",\"path\":[],\"type\":\"dir\",\"size\":0,"
+ + "\"date\":\"2017-06-01T15:45:36.000Z\",\"version\":\"\",\"createdBy\":\"Demo\","
+ + "\"modifiedBy\":\"Demo\",\"content\":\"\",\"recursive\":false},\"$$hashKey\":\"object:260\","
+ + "\"policy\":{\"policyType\":\"Config\",\"configPolicyType\":\"Firewall Config\","
+ + "\"attributes\":[{\"id\":\"choice1\",\"$$hashKey\":\"object:338\",\"key\":\"Test\","
+ + "\"value\":\"Test\"}],\"fwattributes\":[],\"policyName\":\"SampleTest\","
+ + "\"policyDescription\":\"SampleTest\",\"riskType\":\"SampleRiskType\",\"riskLevel\":\"1\","
+ + "\"guard\":\"True\",\"configName\":\"SampleTest\",\"ttlDate\":\"14/09/2017\","
+ + "\"securityZone\":\"Test\"}}}";
fwViewRequestString =
"{\"policyData\":{\"policyType\":\"Config\",\"configPolicyType\":\"Firewall Config\",\"attributes\":"
@@ -144,8 +167,6 @@ public class PolicyRestControllerTest {
+ "\"riskType\":\"SampleRiskType\",\"riskLevel\":\"1\",\"guard\":\"True\","
+ "\"configName\":\"SampleTest\",\"ttlDate\":\"14/09/2017\",\"securityZone\":\"Test\"}}";
-
-
prefixListData = new ArrayList<>();
PrefixList prefixList = new PrefixList();
prefixList.setPrefixListName("Test");
@@ -163,7 +184,7 @@ public class PolicyRestControllerTest {
ServiceList serviceList = new ServiceList();
serviceList.setServiceName("Test");
serviceList.setServiceType("SERVICE");
- serviceList.setServiceTransProtocol("Test");
+ serviceList.setServiceTransportProtocol("Test");
serviceList.setServiceAppProtocol("Test");
serviceList.setServicePorts("8080");
serviceListData.add(serviceList);
@@ -191,30 +212,33 @@ public class PolicyRestControllerTest {
when(commonClassDao.getData(GroupServiceList.class)).thenReturn(serviceGroupData);
tagListData = new ArrayList<>();
- FWTagPicker fwPicker = new FWTagPicker();
+ FwTagPicker fwPicker = new FwTagPicker();
fwPicker.setTagPickerName("Test");
fwPicker.setTagValues("Test:8080");
tagListData.add(fwPicker);
- when(commonClassDao.getData(FWTagPicker.class)).thenReturn(tagListData);
+ when(commonClassDao.getData(FwTagPicker.class)).thenReturn(tagListData);
termListData = new ArrayList<>();
TermList termList = new TermList();
termList.setTermName("Test");
- termList.setFromZones("Test");
- termList.setToZones("Test");
- termList.setSrcIPList("Test");
- termList.setDestIPList("Test");
+ termList.setFromZone("Test");
+ termList.setToZone("Test");
+ termList.setSrcIpList("Test");
+ termList.setDestIpList("Test");
termList.setSrcPortList("Test");
termList.setDestPortList("Test");
termList.setAction("Test");
termListData.add(termList);
when(commonClassDao.getData(TermList.class)).thenReturn(termListData);
- when(commonClassDao.getDataById(TermList.class, "termName", "Test"))
- .thenReturn(termListData);
+ when(commonClassDao.getDataById(TermList.class, "termName", "Test")).thenReturn(termListData);
}
@Test
public final void testPolicyCreationController() {
+ assertNull(PolicyRestController.getCommonClassDao());
+ PolicyRestController.setCommonClassDao(commonClassDao);
+ assertNotNull(PolicyRestController.getCommonClassDao());
+
PolicyRestController controller = new PolicyRestController();
BufferedReader reader = new BufferedReader(new StringReader(clRequestString));
try {
@@ -225,6 +249,7 @@ public class PolicyRestControllerTest {
}
PolicyRestController controller1 = new PolicyRestController();
CreateFirewallController.setCommonClassDao(commonClassDao);
+ assertNotNull(CreateFirewallController.getCommonClassDao());
BufferedReader reader1 = new BufferedReader(new StringReader(fwRequestString));
try {
Mockito.when(request.getReader()).thenReturn(reader1);
@@ -245,6 +270,27 @@ public class PolicyRestControllerTest {
}
@Test
+ public final void testSearchPolicy() throws IOException {
+ PolicyController.setjUnit(true);
+ PolicyController.setPapUrl("http://localhost:8070/pap/");
+ PolicyRestController controller = new PolicyRestController();
+ BufferedReader reader = new BufferedReader(new StringReader("{\"foo\":\"bar\"}"));
+ Mockito.when(request.getReader()).thenReturn(reader);
+ Mockito.when(request.getRequestURI()).thenReturn("/pap/foo/");
+ assertThatExceptionOfType(NullPointerException.class)
+ .isThrownBy(() -> controller.searchPolicy(request, response));
+ }
+
+ @Test
+ public final void testSearchDictionaryController() throws IOException {
+ PolicyRestController controller = new PolicyRestController();
+ BufferedReader reader = new BufferedReader(new StringReader("{\"foo\":\"bar\"}"));
+ Mockito.when(request.getReader()).thenReturn(reader);
+ Mockito.when(request.getRequestURI()).thenReturn("/pap/foo/");
+ assertNull(controller.searchDictionaryController(request, response));
+ }
+
+ @Test
public final void testDeleteElasticData() {
PolicyRestController controller = new PolicyRestController();
try {
@@ -253,4 +299,101 @@ public class PolicyRestControllerTest {
fail();
}
}
+
+ @Test
+ public final void testNotifyOtherPaps() {
+ PolicyRestController controller = new PolicyRestController();
+ String strReturn = controller.notifyOtherPapsToUpdateConfigurations("mode", "newName", "oldName");
+ assertNull(strReturn);
+ }
+
+ @SuppressWarnings("unchecked")
+ @Test
+ public void testGetDictionaryController() throws IOException {
+ PolicyRestController controller = new PolicyRestController();
+ HttpServletRequest mockRequest = Mockito.mock(HttpServletRequest.class);
+ HttpServletResponse mockResponse = Mockito.mock(HttpServletResponse.class);
+ PrintWriter mockPrintWriter = Mockito.mock(PrintWriter.class);
+
+ when(mockRequest.getRequestURI()).thenReturn("//testRequestURI///getDictionary");
+ when(mockResponse.getWriter()).thenThrow(IOException.class);
+ controller.getDictionaryController(mockRequest, mockResponse);
+ verify(mockRequest, atLeast(1)).getRequestURI();
+ verify(mockResponse, atLeast(1)).getWriter();
+
+ reset(mockResponse);
+ when(mockRequest.getRequestURI()).thenReturn("testRequestURI///getDictionary");
+ when(mockResponse.getWriter()).thenReturn(mockPrintWriter);
+ controller.getDictionaryController(mockRequest, mockResponse);
+ verify(mockRequest, atLeast(1)).getRequestURI();
+ verify(mockResponse, atLeast(1)).getWriter();
+ }
+
+ @PrepareForTest(UserUtils.class)
+ @Test
+ public void testdeletetDictionaryController() throws IOException {
+ HttpServletRequest mockRequest = Mockito.mock(HttpServletRequest.class);
+ HttpServletResponse mockResponse = Mockito.mock(HttpServletResponse.class);
+ PolicyRestController controller = new PolicyRestController();
+ User mockUser = Mockito.mock(User.class);
+ PowerMockito.mockStatic(UserUtils.class);
+ PrintWriter mockPrintWriter = Mockito.mock(PrintWriter.class);
+
+ when(mockRequest.getRequestURI()).thenReturn("//testRequestURI///deleteDictionary");
+ when(mockResponse.getWriter()).thenReturn(mockPrintWriter);
+ when(UserUtils.getUserSession(mockRequest)).thenReturn(mockUser);
+ when(mockUser.getOrgUserId()).thenReturn("testUserId");
+
+ controller.deletetDictionaryController(mockRequest, mockResponse);
+ verify(mockRequest).getRequestURI();
+ verify(mockResponse).getWriter();
+ verify(mockUser).getOrgUserId();
+
+ when(mockRequest.getRequestURI()).thenReturn("testRequestURI///deleteDictionary");
+ controller.deletetDictionaryController(mockRequest, mockResponse);
+ verify(mockRequest, atLeast(1)).getRequestURI();
+ }
+
+ @PrepareForTest(UserUtils.class)
+ @Test
+ public void testSaveDictionaryController() throws IOException {
+ HttpServletRequest mockRequest = Mockito.mock(HttpServletRequest.class);
+ HttpServletResponse mockResponse = Mockito.mock(HttpServletResponse.class);
+ PolicyRestController controller = new PolicyRestController();
+ User mockUser = Mockito.mock(User.class);
+ PowerMockito.mockStatic(UserUtils.class);
+ PrintWriter mockPrintWriter = Mockito.mock(PrintWriter.class);
+
+ when(mockRequest.getRequestURI()).thenReturn("//testRequestURI///saveDictionary//import_dictionary");
+ when(mockResponse.getWriter()).thenReturn(mockPrintWriter);
+ when(UserUtils.getUserSession(mockRequest)).thenReturn(mockUser);
+ when(mockUser.getOrgUserId()).thenReturn("testUserId");
+
+ controller.saveDictionaryController(mockRequest, mockResponse);
+ verify(mockRequest).getRequestURI();
+ verify(mockResponse).getWriter();
+ verify(mockUser).getOrgUserId();
+
+ when(mockRequest.getRequestURI()).thenReturn("testRequestURI///saveDictionary");
+ controller.saveDictionaryController(mockRequest, mockResponse);
+ verify(mockRequest, atLeast(1)).getRequestURI();
+ }
+
+ @Test
+ public void testDoConnect() throws Exception {
+ HttpURLConnection mockConnection = Mockito.mock(HttpURLConnection.class);
+ PolicyRestController controller = new PolicyRestController();
+ Mockito.doNothing().when(mockConnection).connect();
+ InputStream mockInputStream = Mockito.mock(InputStream.class);
+
+ when(mockConnection.getResponseCode()).thenReturn(200);
+ when(mockConnection.getInputStream()).thenReturn(mockInputStream);
+
+ Whitebox.invokeMethod(controller, "doConnect", mockConnection);
+ verify(mockConnection).getResponseCode();
+ verify(mockConnection).getInputStream();
+
+ when(mockConnection.getResponseCode()).thenReturn(201);
+ assertNull(Whitebox.invokeMethod(controller, "doConnect", mockConnection));
+ }
}
diff --git a/POLICY-SDK-APP/src/test/java/org/onap/policy/admin/PolicyUserInfoControllerTest.java b/POLICY-SDK-APP/src/test/java/org/onap/policy/admin/PolicyUserInfoControllerTest.java
index d05b7933d..55e4b5a93 100644
--- a/POLICY-SDK-APP/src/test/java/org/onap/policy/admin/PolicyUserInfoControllerTest.java
+++ b/POLICY-SDK-APP/src/test/java/org/onap/policy/admin/PolicyUserInfoControllerTest.java
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP Policy Engine
* ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017, 2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Modifications Copyright (C) 2019 Samsung
* ================================================================================
@@ -19,12 +19,19 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.policy.admin;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
+import static org.mockito.Mockito.atLeast;
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.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.junit.Before;
import org.junit.Test;
@@ -45,8 +52,7 @@ public class PolicyUserInfoControllerTest {
response = new MockHttpServletResponse();
User user = new User();
user.setOrgUserId("Test");
- Mockito.when(mockSession.getAttribute(SystemProperties.getProperty("user_attribute_name")))
- .thenReturn(user);
+ Mockito.when(mockSession.getAttribute(SystemProperties.getProperty("user_attribute_name"))).thenReturn(user);
Mockito.when(request.getSession(false)).thenReturn(mockSession);
}
@@ -60,4 +66,14 @@ public class PolicyUserInfoControllerTest {
fail();
}
}
+
+ @SuppressWarnings("unchecked")
+ @Test
+ public void testGetPolicyUserInfoException() throws IOException {
+ HttpServletResponse mockResponse = Mockito.mock(HttpServletResponse.class);
+ when(mockResponse.getWriter()).thenThrow(IOException.class);
+ PolicyUserInfoController controller = new PolicyUserInfoController();
+ controller.getPolicyUserInfo(request, mockResponse);
+ verify(mockResponse, atLeast(1)).getWriter();
+ }
}
diff --git a/POLICY-SDK-APP/src/test/java/org/onap/policy/admin/RESTfulPAPEngineTest.java b/POLICY-SDK-APP/src/test/java/org/onap/policy/admin/RESTfulPAPEngineTest.java
index 4b307f594..0deb3d6fc 100644
--- a/POLICY-SDK-APP/src/test/java/org/onap/policy/admin/RESTfulPAPEngineTest.java
+++ b/POLICY-SDK-APP/src/test/java/org/onap/policy/admin/RESTfulPAPEngineTest.java
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP Policy Engine
* ================================================================================
- * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2018-2020 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Modifications Copyright (C) 2019 Samsung
* ================================================================================
@@ -19,35 +19,30 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.policy.admin;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.fail;
+import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
+import static org.junit.Assert.assertNull;
+
+import com.att.research.xacml.api.pap.PAPException;
+import com.att.research.xacml.api.pap.PDPPolicy;
+import com.att.research.xacml.util.XACMLProperties;
import java.io.ByteArrayInputStream;
+import java.io.IOException;
import java.io.InputStream;
-import java.net.URL;
-import javax.servlet.http.HttpServletResponse;
import java.net.HttpURLConnection;
-import org.junit.Before;
-import org.junit.Rule;
+import java.net.URLConnection;
+import javax.servlet.http.HttpServletResponse;
+import org.junit.AfterClass;
+import org.junit.BeforeClass;
import org.junit.Test;
-import org.junit.rules.ExpectedException;
-import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.onap.policy.rest.adapter.PolicyRestAdapter;
import org.onap.policy.xacml.api.pap.OnapPDP;
import org.onap.policy.xacml.api.pap.OnapPDPGroup;
-import org.powermock.api.mockito.PowerMockito;
-import org.powermock.core.classloader.annotations.PrepareForTest;
-import org.powermock.modules.junit4.PowerMockRunner;
-import com.att.research.xacml.api.pap.PAPException;
-import com.att.research.xacml.api.pap.PDPPolicy;
-@RunWith(PowerMockRunner.class)
-@PrepareForTest({URL.class, RESTfulPAPEngine.class})
public class RESTfulPAPEngineTest {
- @Rule
- public ExpectedException thrown = ExpectedException.none();
private RESTfulPAPEngine engine = null;
private String name = "testName";
@@ -56,28 +51,55 @@ public class RESTfulPAPEngineTest {
private String policyType = "testType";
private String policyContent = "testContent";
private int jmxport = 0;
+ private String userId = "testId";
OnapPDPGroup group = Mockito.mock(OnapPDPGroup.class);
OnapPDPGroup newGroup = Mockito.mock(OnapPDPGroup.class);
OnapPDP pdp = Mockito.mock(OnapPDP.class);
InputStream policy;
- @Before
- public void runConstructor() throws Exception {
- // Mock url and connection
- URL url = PowerMockito.mock(URL.class);
- PowerMockito.whenNew(URL.class).withArguments(Mockito.any()).thenReturn(url);
+ /**
+ * BeforeClass does some simple code coverage and sets up the
+ * XACML properties.
+ */
+ @BeforeClass
+ public static void setUpBeforeClass() {
+ //
+ // Test constructor with bad URL
+ //
+ assertThatExceptionOfType(PAPException.class).isThrownBy(() ->
+ new RESTfulPAPEngine(null));
+
+ XACMLProperties.reloadProperties();
+ }
+
+ @AfterClass
+ public static void tearDownAfterClass() {
+ XACMLProperties.reloadProperties();
+ }
+
+ private void setupConnection(int responseCode, String location) throws Exception {
+ // Mock connection
HttpURLConnection connection = Mockito.mock(HttpURLConnection.class);
- Mockito.when(url.openConnection()).thenReturn(connection);
- Mockito.when(connection.getResponseCode()).thenReturn(HttpServletResponse.SC_NO_CONTENT);
+
+ Mockito.when(connection.getResponseCode()).thenReturn(responseCode);
+ Mockito.when(connection.getHeaderField("Location")).thenReturn(location);
+
+ InputStream mockInputStream = Mockito.mock(InputStream.class);
+ Mockito.when(connection.getInputStream()).thenReturn(mockInputStream);
// Set the system property temporarily
String systemKey = "xacml.properties";
- String oldProperty = System.getProperty(systemKey);
+ final String oldProperty = System.getProperty(systemKey);
System.setProperty(systemKey, "src/test/resources/xacml.admin.properties");
// Test constructor
String urlName = "localhost:1234";
- engine = new RESTfulPAPEngine(urlName);
+ engine = new RESTfulPAPEngine(urlName) {
+ @Override
+ protected URLConnection makeConnection(String fullUrl) throws IOException {
+ return connection;
+ }
+ };
// Initialize policy
policy = new ByteArrayInputStream(policyContent.getBytes("UTF-8"));
@@ -91,75 +113,89 @@ public class RESTfulPAPEngineTest {
}
@Test
- public void testGroups() throws Exception {
+ public void testAllTheExceptions() throws Exception {
+ setupConnection(HttpServletResponse.SC_NO_CONTENT, "localhost:5678");
+
engine.setDefaultGroup(group);
- assertEquals(engine.getDefaultGroup(), null);
+ assertNull(engine.getDefaultGroup());
engine.newGroup(name, description);
engine.removeGroup(group, newGroup);
- assertEquals(engine.getPDPGroup(pdp), null);
- assertEquals(engine.getPDPGroup(id), null);
- assertEquals(engine.getPDP(id), null);
- assertEquals(engine.getStatus(pdp), null);
-
- thrown.expect(NullPointerException.class);
- engine.getOnapPDPGroups();
- fail("Expecting an exception.");
- }
+ assertNull(engine.getPDPGroup(pdp));
+ assertNull(engine.getPDPGroup(id));
+ assertNull(engine.getPDP(id));
+ assertNull(engine.getStatus(pdp));
- @Test
- public void testUpdateGroup() throws PAPException {
- thrown.expect(PAPException.class);
- engine.updateGroup(group);
- fail("Expecting an exception.");
- }
+ assertThatExceptionOfType(NullPointerException.class).isThrownBy(() ->
+ engine.getOnapPDPGroups()
+ );
- @Test
- public void testPDP() throws PAPException {
- assertEquals(engine.getGroup(name), null);
- engine.movePDP(pdp, newGroup);
+ assertThatExceptionOfType(PAPException.class).isThrownBy(() ->
+ engine.updateGroup(group)
+ );
- thrown.expect(PAPException.class);
- engine.newPDP(id, newGroup, name, description, jmxport);
- fail("Expecting an exception.");
- }
+ assertThatExceptionOfType(PAPException.class).isThrownBy(() ->
+ engine.updateGroup(group, "testUserName")
+ );
- @Test
- public void testUpdatePDP() throws PAPException {
- thrown.expect(NullPointerException.class);
- engine.updatePDP(pdp);
- fail("Expecting an exception.");
- }
+ assertNull(engine.getGroup(name));
+ engine.movePDP(pdp, newGroup);
- @Test
- public void testRemovePDP() throws PAPException {
- thrown.expect(NullPointerException.class);
- engine.removePDP(pdp);
- fail("Expecting an exception.");
- }
+ assertThatExceptionOfType(PAPException.class).isThrownBy(() ->
+ engine.newPDP(id, newGroup, name, description, jmxport)
+ );
- @Test
- public void testValidatePolicy() throws PAPException {
- PolicyRestAdapter policyAdapter = new PolicyRestAdapter();
+ assertThatExceptionOfType(NullPointerException.class).isThrownBy(() ->
+ engine.updatePDP(pdp)
+ );
- thrown.expect(PAPException.class);
- engine.validatePolicyRequest(policyAdapter, policyType);
- fail("Expecting an exception.");
- }
+ assertThatExceptionOfType(NullPointerException.class).isThrownBy(() ->
+ engine.removePDP(pdp)
+ );
- @Test
- public void testPublishPolicy() throws PAPException {
- thrown.expect(PAPException.class);
- engine.publishPolicy(id, name, false, policy, newGroup);
- fail("Expecting an exception.");
- }
+ assertThatExceptionOfType(PAPException.class).isThrownBy(() ->
+ engine.validatePolicyRequest(new PolicyRestAdapter(), policyType)
+ );
- @Test
- public void testCopy() throws PAPException {
- engine.copyFile(id, newGroup, policy);
- PDPPolicy pdpPolicy = Mockito.mock(PDPPolicy.class);
+ assertThatExceptionOfType(PAPException.class).isThrownBy(() ->
+ engine.publishPolicy(id, name, false, policy, newGroup)
+ );
- thrown.expect(PAPException.class);
- engine.copyPolicy(pdpPolicy, newGroup);
- fail("Expecting an exception.");
+ engine.copyFile(id, newGroup, policy, userId);
+ PDPPolicy pdpPolicy = Mockito.mock(PDPPolicy.class);
+ assertThatExceptionOfType(PAPException.class).isThrownBy(() ->
+ engine.copyPolicy(pdpPolicy, newGroup, userId)
+ );
+
+ assertThatExceptionOfType(PAPException.class).isThrownBy(() ->
+ engine.removePolicy(null, group)
+ );
+
+ assertThatExceptionOfType(PAPException.class).isThrownBy(() ->
+ engine.copyPolicy(null, null, null)
+ );
+
+ //
+ // Change the mockito to take a different path
+ //
+ assertThatExceptionOfType(PAPException.class).isThrownBy(() ->
+ setupConnection(HttpServletResponse.SC_FOUND, "localhost:5678")
+ );
+
+ assertThatExceptionOfType(PAPException.class).isThrownBy(() ->
+ setupConnection(200, "localhost:5678")
+ );
+
+ assertThatExceptionOfType(PAPException.class).isThrownBy(() ->
+ setupConnection(350, "localhost:5678")
+ );
+
+ assertThatExceptionOfType(PAPException.class).isThrownBy(() ->
+ setupConnection(500, "localhost:5678")
+ );
+
+ assertThatExceptionOfType(PAPException.class).isThrownBy(() ->
+ setupConnection(350, null)
+ );
}
+
}
diff --git a/POLICY-SDK-APP/src/test/java/org/onap/policy/components/HumanPolicyComponentTest.java b/POLICY-SDK-APP/src/test/java/org/onap/policy/components/HumanPolicyComponentTest.java
new file mode 100644
index 000000000..b56d3fd94
--- /dev/null
+++ b/POLICY-SDK-APP/src/test/java/org/onap/policy/components/HumanPolicyComponentTest.java
@@ -0,0 +1,839 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP Policy Engine
+ * ================================================================================
+ * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.fail;
+import static org.mockito.Mockito.atLeast;
+import static org.mockito.Mockito.doReturn;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+import com.att.research.xacml.api.XACML1;
+import com.att.research.xacml.util.XACMLPolicyScanner.CallbackResult;
+import java.io.File;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+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.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.EffectType;
+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.VariableReferenceType;
+import org.junit.BeforeClass;
+import org.junit.Test;
+import org.mockito.Mockito;
+
+public class HumanPolicyComponentTest {
+
+ private AttributeIdentifiers attrIds;
+ private HtmlProcessor processor;
+ private static File temp;
+ private static File tempAction;
+ private static File tempConfig;
+
+ @BeforeClass
+ public static void setup() throws IOException {
+ temp = File.createTempFile("tmpFile", ".tmp");
+ tempAction = File.createTempFile("Action_test", ".tmp");
+ tempConfig = File.createTempFile("Config_test", ".tmp");
+ temp.deleteOnExit();
+ tempAction.deleteOnExit();
+ tempConfig.deleteOnExit();
+ }
+
+ @Test
+ public void testAttributeIdentifiers() {
+ String testCategory = "testCategory";
+ String testID = "testId";
+ String testType = "testType";
+ String newTestType = "testNewType";
+
+ attrIds = new AttributeIdentifiers(testCategory, testType, testID);
+ assertEquals(testCategory, attrIds.category);
+ assertEquals(testID, attrIds.id);
+ assertEquals(testType, attrIds.getType());
+
+ attrIds.setType(newTestType);
+ assertEquals(newTestType, attrIds.getType());
+ }
+
+ @SuppressWarnings("unchecked")
+ @Test
+ public void testHumanPolicyComponentException() {
+ JAXBElement<PolicySetType> mockRoot = Mockito.mock(JAXBElement.class);
+ when(mockRoot.getValue()).thenReturn(null);
+ assertNull(HumanPolicyComponent.DescribePolicy(temp));
+ }
+
+ @Test(expected = IllegalArgumentException.class)
+ public void testHtmlProcessorNull() throws IOException {
+ processor = new HtmlProcessor(null, null);
+ }
+
+ @Test(expected = IllegalArgumentException.class)
+ public void testHtmlProcessor() throws IOException {
+ File tempFile = File.createTempFile("testFile", ".tmp");
+ tempFile.delete();
+ processor = new HtmlProcessor(tempFile, null);
+ }
+
+ @Test(expected = IllegalArgumentException.class)
+ public void testHtmlProcessorInvalidObject() throws IOException {
+ processor = new HtmlProcessor(temp, null);
+ }
+
+ @Test
+ public void testHtmlProcessorConfigPolicySetType() {
+ PolicySetType mockPolicySetType = Mockito.mock(PolicySetType.class);
+ processor = new HtmlProcessor(tempConfig, mockPolicySetType);
+ processor.onFinishScan(mockPolicySetType);
+ verify(mockPolicySetType).getVersion();
+ }
+
+ @Test
+ public void testHtmlProcessorActionPolicySetType() {
+ PolicySetType mockPolicySetType = Mockito.mock(PolicySetType.class);
+ processor = new HtmlProcessor(tempAction, mockPolicySetType);
+ processor.onFinishScan(mockPolicySetType);
+ verify(mockPolicySetType).getVersion();
+ }
+
+ @Test
+ public void testHtmlProcessorConfigPolicyType() {
+ PolicyType mockPolicyType = Mockito.mock(PolicyType.class);
+ processor = new HtmlProcessor(tempConfig, mockPolicyType);
+ verify(mockPolicyType).getVersion();
+ }
+
+ @Test
+ public void testHtmlProcessorActionPolicyType() {
+ PolicyType mockPolicyType = Mockito.mock(PolicyType.class);
+ processor = new HtmlProcessor(tempAction, mockPolicyType);
+ assertNotNull(processor.getAttributeIdentifiersMap());
+ verify(mockPolicyType).getVersion();
+ }
+
+ @Test
+ public void testHtmlProcessorOnPreVisitPolicySet() {
+ PolicySetType mockPolicySetType = Mockito.mock(PolicySetType.class);
+ PolicySetType mockPolicyParent = Mockito.mock(PolicySetType.class);
+
+ processor = new HtmlProcessor(temp, mockPolicySetType);
+
+ when(mockPolicySetType.getPolicySetOrPolicyOrPolicySetIdReference()).thenReturn(Collections.emptyList());
+ when(mockPolicySetType.getDescription()).thenReturn(null);
+
+ CallbackResult preResult = processor.onPreVisitPolicySet(mockPolicyParent, mockPolicySetType);
+ assertEquals("CONTINUE", preResult.name());
+ verify(mockPolicySetType, atLeast(1)).getPolicySetOrPolicyOrPolicySetIdReference();
+ verify(mockPolicySetType, atLeast(1)).getDescription();
+ }
+
+ @Test
+ public void testHtmlProcessorOnPreVisitPolicySetNullParent() {
+ PolicySetType mockPolicySetType = Mockito.mock(PolicySetType.class);
+ PolicySetType mockPolicyParent = null;
+ JAXBElement<?> mockElement = Mockito.mock(JAXBElement.class);
+
+ List<JAXBElement<?>> testList = new ArrayList<JAXBElement<?>>();
+ testList.add(mockElement);
+
+ processor = new HtmlProcessor(temp, mockPolicySetType);
+
+ when(mockPolicySetType.getPolicySetOrPolicyOrPolicySetIdReference()).thenReturn(testList);
+ when(mockPolicySetType.getDescription()).thenReturn("");
+
+ CallbackResult preResult = processor.onPreVisitPolicySet(mockPolicyParent, mockPolicySetType);
+ assertEquals("CONTINUE", preResult.name());
+ verify(mockPolicySetType, atLeast(1)).getPolicySetOrPolicyOrPolicySetIdReference();
+ verify(mockPolicySetType, atLeast(1)).getDescription();
+ }
+
+ @Test
+ public void testHtmlProcessorOnPostVisitPolicySet() {
+ PolicySetType mockPolicySetType = Mockito.mock(PolicySetType.class);
+ PolicySetType mockPolicyParent = Mockito.mock(PolicySetType.class);
+
+ processor = new HtmlProcessor(temp, mockPolicySetType);
+
+ when(mockPolicySetType.getPolicySetOrPolicyOrPolicySetIdReference()).thenReturn(Collections.emptyList());
+ when(mockPolicySetType.getDescription()).thenReturn(null);
+
+ CallbackResult postResult = processor.onPostVisitPolicySet(mockPolicyParent, mockPolicySetType);
+ assertEquals("CONTINUE", postResult.name());
+ verify(mockPolicySetType, atLeast(1)).getPolicySetOrPolicyOrPolicySetIdReference();
+ verify(mockPolicySetType, atLeast(1)).getDescription();
+ }
+
+ @Test
+ public void testHtmlProcessorOnPostVisitPolicySetNullParent() {
+ PolicySetType mockPolicySetType = Mockito.mock(PolicySetType.class);
+ PolicySetType mockPolicyParent = null;
+ JAXBElement<?> mockElement = Mockito.mock(JAXBElement.class);
+
+ List<JAXBElement<?>> testList = new ArrayList<JAXBElement<?>>();
+ testList.add(mockElement);
+
+ processor = new HtmlProcessor(temp, mockPolicySetType);
+
+ when(mockPolicySetType.getPolicySetOrPolicyOrPolicySetIdReference()).thenReturn(testList);
+ when(mockPolicySetType.getDescription()).thenReturn("");
+
+ CallbackResult postResult = processor.onPostVisitPolicySet(mockPolicyParent, mockPolicySetType);
+ assertEquals("CONTINUE", postResult.name());
+ verify(mockPolicySetType, atLeast(1)).getPolicySetOrPolicyOrPolicySetIdReference();
+ verify(mockPolicySetType, atLeast(1)).getDescription();
+ }
+
+ @Test
+ public void testHtmlProcessorOnPreVisitPolicy() {
+ PolicySetType mockPolicySetType = Mockito.mock(PolicySetType.class);
+ PolicyType mockPolicyType = Mockito.mock(PolicyType.class);
+ List<Object> testList = new ArrayList<Object>();
+ processor = new HtmlProcessor(temp, mockPolicySetType);
+
+ when(mockPolicyType.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition()).thenReturn(testList);
+ when(mockPolicySetType.getDescription()).thenReturn(null);
+
+ CallbackResult preResult = processor.onPreVisitPolicy(mockPolicySetType, mockPolicyType);
+ assertEquals("CONTINUE", preResult.name());
+ verify(mockPolicyType, atLeast(1)).getCombinerParametersOrRuleCombinerParametersOrVariableDefinition();
+ verify(mockPolicyType, atLeast(1)).getDescription();
+ }
+
+ @Test
+ public void testHtmlProcessorOnPreVisitPolicyNullParent() {
+ PolicyType mockPolicyType = Mockito.mock(PolicyType.class);
+ PolicySetType mockPolicyParent = null;
+ List<Object> testList = new ArrayList<Object>();
+ testList.add(new Object());
+ processor = new HtmlProcessor(temp, mockPolicyType);
+
+ when(mockPolicyType.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition()).thenReturn(testList);
+ when(mockPolicyType.getDescription()).thenReturn("");
+
+ CallbackResult preResult = processor.onPreVisitPolicy(mockPolicyParent, mockPolicyType);
+ assertEquals("CONTINUE", preResult.name());
+ verify(mockPolicyType, atLeast(1)).getCombinerParametersOrRuleCombinerParametersOrVariableDefinition();
+ verify(mockPolicyType, atLeast(1)).getDescription();
+
+ }
+
+ @Test
+ public void testHtmlProcessorOnPostVisitPolicy() {
+ PolicySetType mockPolicySetType = Mockito.mock(PolicySetType.class);
+ PolicyType mockPolicyType = Mockito.mock(PolicyType.class);
+ List<Object> testList = new ArrayList<Object>();
+ processor = new HtmlProcessor(temp, mockPolicySetType);
+
+ when(mockPolicyType.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition()).thenReturn(testList);
+
+ CallbackResult postResult = processor.onPostVisitPolicy(mockPolicySetType, mockPolicyType);
+ assertEquals("CONTINUE", postResult.name());
+ verify(mockPolicyType, atLeast(1)).getCombinerParametersOrRuleCombinerParametersOrVariableDefinition();
+ }
+
+ @Test
+ public void testHtmlProcessorOnPostVisitPolicyNullParent() {
+ PolicyType mockPolicyType = Mockito.mock(PolicyType.class);
+ PolicySetType mockPolicyParent = null;
+ List<Object> testList = new ArrayList<Object>();
+ testList.add(new Object());
+ processor = new HtmlProcessor(temp, mockPolicyType);
+
+ when(mockPolicyType.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition()).thenReturn(testList);
+
+ CallbackResult postResult = processor.onPostVisitPolicy(mockPolicyParent, mockPolicyType);
+ assertEquals("CONTINUE", postResult.name());
+ verify(mockPolicyType, atLeast(1)).getCombinerParametersOrRuleCombinerParametersOrVariableDefinition();
+ }
+
+ @Test
+ public void testHtmlProcessorPolicy() {
+ PolicySetType mockPolicySetType = Mockito.mock(PolicySetType.class);
+ PolicyType mockPolicyType = Mockito.mock(PolicyType.class);
+ processor = new HtmlProcessor(temp, mockPolicySetType);
+
+ when(mockPolicyType.getRuleCombiningAlgId()).thenReturn(null);
+ when(mockPolicyType.getPolicyId()).thenReturn(null);
+ when(mockPolicyType.getVersion()).thenReturn(null);
+ when(mockPolicyType.getTarget()).thenReturn(null);
+
+ processor.policy(mockPolicyType);
+ verify(mockPolicyType).getRuleCombiningAlgId();
+ verify(mockPolicyType).getPolicyId();
+ verify(mockPolicyType).getVersion();
+ verify(mockPolicyType).getTarget();
+ }
+
+ @Test
+ public void testHtmlProcessorPolicyListEmpty() {
+ PolicySetType mockPolicySetType = Mockito.mock(PolicySetType.class);
+ PolicyType mockPolicyType = Mockito.mock(PolicyType.class);
+ TargetType mockTargetType = Mockito.mock(TargetType.class);
+ List<AnyOfType> anyOfList = new ArrayList<AnyOfType>();
+ processor = new HtmlProcessor(temp, mockPolicySetType);
+
+ when(mockPolicyType.getRuleCombiningAlgId()).thenReturn(null);
+ when(mockPolicyType.getPolicyId()).thenReturn(null);
+ when(mockPolicyType.getVersion()).thenReturn(null);
+ when(mockPolicyType.getTarget()).thenReturn(mockTargetType);
+ when(mockTargetType.getAnyOf()).thenReturn(anyOfList);
+
+ processor.policy(mockPolicyType);
+
+ verify(mockPolicyType, atLeast(1)).getRuleCombiningAlgId();
+ verify(mockPolicyType, atLeast(1)).getPolicyId();
+ verify(mockPolicyType, atLeast(1)).getVersion();
+ verify(mockPolicyType, atLeast(1)).getTarget();
+ verify(mockTargetType, atLeast(1)).getAnyOf();
+ }
+
+ @Test
+ public void testHtmlProcessorPolicyListNotEmpty() {
+ PolicySetType mockPolicySetType = Mockito.mock(PolicySetType.class);
+ PolicyType mockPolicyType = Mockito.mock(PolicyType.class);
+ TargetType mockTargetType = Mockito.mock(TargetType.class);
+ List<AnyOfType> anyOfList = new ArrayList<AnyOfType>();
+ anyOfList.add(new AnyOfType());
+ processor = new HtmlProcessor(temp, mockPolicySetType);
+
+ when(mockPolicyType.getRuleCombiningAlgId()).thenReturn(null);
+ when(mockPolicyType.getPolicyId()).thenReturn(null);
+ when(mockPolicyType.getVersion()).thenReturn(null);
+ when(mockPolicyType.getTarget()).thenReturn(mockTargetType);
+ when(mockTargetType.getAnyOf()).thenReturn(anyOfList);
+
+ processor.policy(mockPolicyType);
+ verify(mockPolicyType, atLeast(1)).getRuleCombiningAlgId();
+ verify(mockPolicyType, atLeast(1)).getPolicyId();
+ verify(mockPolicyType, atLeast(1)).getVersion();
+ verify(mockPolicyType, atLeast(1)).getTarget();
+ verify(mockTargetType, atLeast(1)).getAnyOf();
+ }
+
+ @Test
+ public void testHtmlProcessorPolicyNull() {
+ PolicySetType mockPolicySetType = Mockito.mock(PolicySetType.class);
+ PolicyType mockPolicyType = Mockito.mock(PolicyType.class);
+ TargetType mockTargetType = Mockito.mock(TargetType.class);
+ processor = new HtmlProcessor(temp, mockPolicySetType);
+
+ when(mockPolicyType.getRuleCombiningAlgId()).thenReturn(null);
+ when(mockPolicyType.getPolicyId()).thenReturn(null);
+ when(mockPolicyType.getVersion()).thenReturn(null);
+ when(mockPolicyType.getTarget()).thenReturn(mockTargetType);
+ when(mockPolicyType.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition()).thenReturn(null);
+ when(mockTargetType.getAnyOf()).thenReturn(null);
+
+ processor.policy(mockPolicyType);
+ verify(mockPolicyType, atLeast(1)).getRuleCombiningAlgId();
+ verify(mockPolicyType, atLeast(1)).getPolicyId();
+ verify(mockPolicyType, atLeast(1)).getVersion();
+ verify(mockPolicyType, atLeast(1)).getTarget();
+ verify(mockPolicyType, atLeast(1)).getCombinerParametersOrRuleCombinerParametersOrVariableDefinition();
+ verify(mockTargetType, atLeast(1)).getAnyOf();
+ }
+
+ @Test
+ public void testHtmlProcessorPolicySet() {
+ PolicySetType mockPolicySetType = Mockito.mock(PolicySetType.class);
+ processor = new HtmlProcessor(temp, mockPolicySetType);
+
+ when(mockPolicySetType.getPolicyCombiningAlgId()).thenReturn("");
+ when(mockPolicySetType.getPolicySetId()).thenReturn("");
+ when(mockPolicySetType.getVersion()).thenReturn("");
+
+ processor.policySet(mockPolicySetType, "");
+ verify(mockPolicySetType, atLeast(1)).getPolicyCombiningAlgId();
+ verify(mockPolicySetType, atLeast(1)).getPolicySetId();
+ verify(mockPolicySetType, atLeast(1)).getVersion();
+ }
+
+ @Test
+ public void testHtmlProcessorPolicySetNull() {
+ PolicySetType mockPolicySetType = Mockito.mock(PolicySetType.class);
+ TargetType mockTargetType = Mockito.mock(TargetType.class);
+ processor = new HtmlProcessor(temp, mockPolicySetType);
+
+ when(mockPolicySetType.getTarget()).thenReturn(mockTargetType);
+ when(mockTargetType.getAnyOf()).thenReturn(null);
+ when(mockPolicySetType.getPolicySetOrPolicyOrPolicySetIdReference()).thenReturn(null);
+
+ processor.policySet(mockPolicySetType, "");
+ verify(mockPolicySetType, atLeast(1)).getTarget();
+ verify(mockTargetType, atLeast(1)).getAnyOf();
+ verify(mockPolicySetType, atLeast(1)).getPolicySetOrPolicyOrPolicySetIdReference();
+ }
+
+ @Test
+ public void testHtmlProcessorPolicySetEmpty() {
+ PolicySetType mockPolicySetType = Mockito.mock(PolicySetType.class);
+ TargetType mockTargetType = Mockito.mock(TargetType.class);
+ List<AnyOfType> anyOfList = new ArrayList<AnyOfType>();
+ processor = new HtmlProcessor(temp, mockPolicySetType);
+
+ when(mockPolicySetType.getTarget()).thenReturn(mockTargetType);
+ when(mockTargetType.getAnyOf()).thenReturn(anyOfList);
+ when(mockPolicySetType.getPolicySetOrPolicyOrPolicySetIdReference()).thenReturn(null);
+
+ processor.policySet(mockPolicySetType, "");
+ verify(mockPolicySetType, atLeast(1)).getTarget();
+ verify(mockTargetType, atLeast(1)).getAnyOf();
+ verify(mockPolicySetType, atLeast(1)).getPolicySetOrPolicyOrPolicySetIdReference();
+ }
+
+ @Test
+ public void testHtmlProcessorPolicySetNotEmpty() {
+ PolicySetType mockPolicySetType = Mockito.mock(PolicySetType.class);
+ TargetType mockTargetType = Mockito.mock(TargetType.class);
+ List<AnyOfType> anyOfList = new ArrayList<AnyOfType>();
+ anyOfList.add(new AnyOfType());
+
+ when(mockPolicySetType.getTarget()).thenReturn(mockTargetType);
+ when(mockTargetType.getAnyOf()).thenReturn(anyOfList);
+ when(mockPolicySetType.getPolicySetOrPolicyOrPolicySetIdReference()).thenReturn(null);
+
+ processor = new HtmlProcessor(temp, mockPolicySetType);
+ processor.policySet(mockPolicySetType, "");
+ verify(mockPolicySetType, atLeast(1)).getTarget();
+ verify(mockTargetType, atLeast(1)).getAnyOf();
+ verify(mockPolicySetType, atLeast(1)).getPolicySetOrPolicyOrPolicySetIdReference();
+ }
+
+ @Test
+ public void testHtmlProcessorRule() {
+ PolicySetType mockPolicySetType = Mockito.mock(PolicySetType.class);
+ RuleType mockRuleType = Mockito.mock(RuleType.class);
+ ConditionType mockConditionType = Mockito.mock(ConditionType.class);
+ ObligationExpressionsType mockOESType = Mockito.mock(ObligationExpressionsType.class);
+ ObligationExpressionType mockOEType = Mockito.mock(ObligationExpressionType.class);
+ EffectType effectTypePermit = EffectType.PERMIT;
+ processor = new HtmlProcessor(temp, mockPolicySetType);
+
+ List<ObligationExpressionType> oblList = new ArrayList<ObligationExpressionType>();
+ oblList.add(mockOEType);
+
+ when(mockRuleType.getEffect()).thenReturn(effectTypePermit);
+ when(mockRuleType.getRuleId()).thenReturn(null);
+ when(mockRuleType.getTarget()).thenReturn(null);
+ when(mockRuleType.getCondition()).thenReturn(mockConditionType);
+ when(mockRuleType.getObligationExpressions()).thenReturn(mockOESType);
+ when(mockOESType.getObligationExpression()).thenReturn(oblList);
+ when(mockOEType.getFulfillOn()).thenReturn(effectTypePermit);
+
+ processor.rule(mockRuleType);
+
+ verify(mockRuleType, atLeast(1)).getRuleId();
+ verify(mockRuleType, atLeast(1)).getTarget();
+ verify(mockRuleType, atLeast(1)).getCondition();
+ verify(mockRuleType, atLeast(1)).getObligationExpressions();
+ verify(mockOESType, atLeast(1)).getObligationExpression();
+ verify(mockOEType, atLeast(1)).getFulfillOn();
+
+ JAXBElement<?> mockJaxBElement = Mockito.mock(JAXBElement.class);
+ Object mockValueObject = Mockito.mock(Object.class);
+
+ doReturn(mockJaxBElement).when(mockConditionType).getExpression();
+ doReturn(mockValueObject).when(mockJaxBElement).getValue();
+
+ try {
+ processor.rule(mockRuleType);
+ fail();
+ } catch (IllegalArgumentException e) {
+ verify(mockConditionType, atLeast(1)).getExpression();
+ verify(mockJaxBElement, atLeast(1)).getValue();
+ }
+ }
+
+ @Test
+ public void testHtmlProcessorRuleNullEmptyList() {
+ PolicySetType mockPolicySetType = Mockito.mock(PolicySetType.class);
+ RuleType mockRuleType = Mockito.mock(RuleType.class);
+ TargetType mockTargetType = Mockito.mock(TargetType.class);
+ EffectType effectTypePermit = EffectType.PERMIT;
+ AdviceExpressionsType mockAdviceExsType = Mockito.mock(AdviceExpressionsType.class);
+ AdviceExpressionType mockAdviceEx = Mockito.mock(AdviceExpressionType.class);
+ processor = new HtmlProcessor(temp, mockPolicySetType);
+
+ List<AnyOfType> anyOfList = new ArrayList<AnyOfType>();
+ List<AdviceExpressionType> adviceExList = new ArrayList<AdviceExpressionType>();
+ adviceExList.add(mockAdviceEx);
+
+ when(mockRuleType.getEffect()).thenReturn(effectTypePermit);
+ when(mockRuleType.getRuleId()).thenReturn(null);
+ when(mockRuleType.getTarget()).thenReturn(mockTargetType);
+ when(mockRuleType.getObligationExpressions()).thenReturn(null);
+ when(mockRuleType.getAdviceExpressions()).thenReturn(mockAdviceExsType);
+ when(mockTargetType.getAnyOf()).thenReturn(null);
+ when(mockAdviceExsType.getAdviceExpression()).thenReturn(adviceExList);
+ when(mockAdviceEx.getAttributeAssignmentExpression()).thenReturn(null);
+ when(mockAdviceEx.getAppliesTo()).thenReturn(effectTypePermit);
+
+ processor.rule(mockRuleType);
+
+ verify(mockRuleType, atLeast(1)).getEffect();
+ verify(mockRuleType, atLeast(1)).getRuleId();
+ verify(mockRuleType, atLeast(1)).getTarget();
+ verify(mockRuleType, atLeast(1)).getCondition();
+ verify(mockRuleType, atLeast(1)).getObligationExpressions();
+ verify(mockRuleType, atLeast(1)).getAdviceExpressions();
+ verify(mockTargetType, atLeast(1)).getAnyOf();
+ verify(mockAdviceExsType, atLeast(1)).getAdviceExpression();
+ verify(mockAdviceEx, atLeast(1)).getAttributeAssignmentExpression();
+ verify(mockAdviceEx, atLeast(1)).getAppliesTo();
+
+ when(mockTargetType.getAnyOf()).thenReturn(anyOfList);
+ processor.rule(mockRuleType);
+ verify(mockTargetType, atLeast(1)).getAnyOf();
+ }
+
+ @Test
+ public void testHtmlProcessorRuleNonNullObjects() {
+ PolicySetType mockPolicySetType = Mockito.mock(PolicySetType.class);
+ RuleType mockRuleType = Mockito.mock(RuleType.class);
+ TargetType mockTargetType = Mockito.mock(TargetType.class);
+ AdviceExpressionsType mockAdvice = Mockito.mock(AdviceExpressionsType.class);
+ ObligationExpressionsType mockObEx = Mockito.mock(ObligationExpressionsType.class);
+ AdviceExpressionType adviceExpTypeMock = Mockito.mock(AdviceExpressionType.class);
+ ObligationExpressionType mockObExType = Mockito.mock(ObligationExpressionType.class);
+ EffectType effectTypePermit = EffectType.PERMIT;
+ processor = new HtmlProcessor(temp, mockPolicySetType);
+
+ List<AnyOfType> anyOfList = new ArrayList<AnyOfType>();
+ anyOfList.add(new AnyOfType());
+
+ List<AdviceExpressionType> adviceList = new ArrayList<AdviceExpressionType>();
+ adviceList.add(adviceExpTypeMock);
+
+ List<AttributeAssignmentExpressionType> attrList = new ArrayList<AttributeAssignmentExpressionType>();
+
+ List<ObligationExpressionType> obExList = new ArrayList<ObligationExpressionType>();
+ obExList.add(mockObExType);
+
+ List<Object> contentList = new ArrayList<>();
+ contentList.add(new Object());
+
+ when(mockRuleType.getRuleId()).thenReturn("");
+ when(mockRuleType.getTarget()).thenReturn(mockTargetType);
+ when(mockRuleType.getEffect()).thenReturn(effectTypePermit);
+ when(mockTargetType.getAnyOf()).thenReturn(anyOfList);
+ when(mockRuleType.getAdviceExpressions()).thenReturn(mockAdvice);
+ when(mockAdvice.getAdviceExpression()).thenReturn(adviceList);
+ when(mockRuleType.getObligationExpressions()).thenReturn(mockObEx);
+ when(mockObEx.getObligationExpression()).thenReturn(obExList);
+ when(mockObExType.getAttributeAssignmentExpression()).thenReturn(null);
+ when(mockObExType.getFulfillOn()).thenReturn(effectTypePermit);
+ when(adviceExpTypeMock.getAdviceId()).thenReturn("");
+ when(adviceExpTypeMock.getAppliesTo()).thenReturn(effectTypePermit);
+ when(adviceExpTypeMock.getAttributeAssignmentExpression()).thenReturn(attrList);
+
+ processor.rule(mockRuleType);
+
+ verify(mockRuleType, atLeast(1)).getRuleId();
+ verify(mockRuleType, atLeast(1)).getTarget();
+ verify(mockRuleType, atLeast(1)).getEffect();
+ verify(mockRuleType, atLeast(1)).getAdviceExpressions();
+ verify(mockRuleType, atLeast(1)).getObligationExpressions();
+ verify(mockTargetType, atLeast(1)).getAnyOf();
+ verify(mockObEx, atLeast(1)).getObligationExpression();
+ verify(mockObExType, atLeast(1)).getAttributeAssignmentExpression();
+ verify(mockObExType, atLeast(1)).getFulfillOn();
+ verify(mockAdvice, atLeast(1)).getAdviceExpression();
+ verify(adviceExpTypeMock, atLeast(1)).getAdviceId();
+ verify(adviceExpTypeMock, atLeast(1)).getAppliesTo();
+ verify(adviceExpTypeMock, atLeast(1)).getAttributeAssignmentExpression();
+ }
+
+ @Test
+ public void testHtmlProcessorOnPreVisitRule() {
+ PolicySetType mockPolicySetType = Mockito.mock(PolicySetType.class);
+ PolicyType mockPolicyType = null;
+ RuleType mockRuleType = Mockito.mock(RuleType.class);
+ EffectType effectTypePermit = EffectType.PERMIT;
+ TargetType mockTargetType = Mockito.mock(TargetType.class);
+ processor = new HtmlProcessor(temp, mockPolicySetType);
+
+ List<AnyOfType> anyOfList = new ArrayList<AnyOfType>();
+ anyOfList.add(new AnyOfType());
+
+ when(mockRuleType.getCondition()).thenReturn(null);
+ when(mockRuleType.getDescription()).thenReturn(null);
+ when(mockRuleType.getEffect()).thenReturn(effectTypePermit);
+ when(mockRuleType.getTarget()).thenReturn(mockTargetType);
+ when(mockTargetType.getAnyOf()).thenReturn(anyOfList);
+
+ CallbackResult callbackResult = processor.onPreVisitRule(mockPolicyType, mockRuleType);
+ assertNotNull(callbackResult);
+
+ verify(mockRuleType, atLeast(1)).getCondition();
+ verify(mockRuleType, atLeast(1)).getDescription();
+ verify(mockRuleType, atLeast(1)).getEffect();
+ verify(mockRuleType, atLeast(1)).getTarget();
+ verify(mockRuleType, atLeast(1)).getAdviceExpressions();
+ verify(mockTargetType, atLeast(1)).getAnyOf();
+
+ mockPolicyType = Mockito.mock(PolicyType.class);
+ when(mockRuleType.getDescription()).thenReturn("");
+
+ callbackResult = processor.onPreVisitRule(mockPolicyType, mockRuleType);
+ assertNotNull(callbackResult);
+ }
+
+ @Test
+ public void testHtmlProcessorOnPostVisitRule() {
+ PolicySetType mockPolicySetType = Mockito.mock(PolicySetType.class);
+ PolicyType mockPolicyType = null;
+ RuleType mockRuleType = Mockito.mock(RuleType.class);
+
+ processor = new HtmlProcessor(temp, mockPolicySetType);
+ CallbackResult callbackResult = processor.onPostVisitRule(mockPolicyType, mockRuleType);
+ assertNotNull(callbackResult);
+
+ mockPolicyType = Mockito.mock(PolicyType.class);
+ callbackResult = processor.onPostVisitRule(mockPolicyType, mockRuleType);
+ assertNotNull(callbackResult);
+ }
+
+ @Test
+ public void testHtmlProcessorProcessAttributeAssignments() {
+ PolicySetType mockPolicySetType = Mockito.mock(PolicySetType.class);
+ processor = new HtmlProcessor(temp, mockPolicySetType);
+
+ RuleType mockRuleType = Mockito.mock(RuleType.class);
+ EffectType effectTypePermit = EffectType.PERMIT;
+ ObligationExpressionsType mockOblExsType = Mockito.mock(ObligationExpressionsType.class);
+
+ ObligationExpressionType mockOblExTypeListObj = Mockito.mock(ObligationExpressionType.class);
+ List<ObligationExpressionType> oblExTypeList = new ArrayList<ObligationExpressionType>();
+ oblExTypeList.add(mockOblExTypeListObj);
+
+ AttributeAssignmentExpressionType mockattrAssignListObj = Mockito.mock(AttributeAssignmentExpressionType.class);
+ List<AttributeAssignmentExpressionType> attrAssignList = new ArrayList<AttributeAssignmentExpressionType>();
+ attrAssignList.add(mockattrAssignListObj);
+
+ JAXBElement<?> jaxbElementMock = Mockito.mock(JAXBElement.class);
+ AttributeValueType attrValTypeMock = Mockito.mock(AttributeValueType.class);
+ AttributeDesignatorType attrDesignTypeMock = Mockito.mock(AttributeDesignatorType.class);
+ AttributeSelectorType attrSelTypeMock = Mockito.mock(AttributeSelectorType.class);
+ ApplyType applyTypeMock = Mockito.mock(ApplyType.class);
+ Object genericObjectMock = Mockito.mock(Object.class);
+
+ Object mockContentListObject = Mockito.mock(Object.class);
+ List<Object> contentList = new ArrayList<Object>();
+ contentList.add(mockContentListObject);
+ contentList.add(mockContentListObject);
+
+ when(mockRuleType.getEffect()).thenReturn(effectTypePermit);
+ when(mockRuleType.getObligationExpressions()).thenReturn(mockOblExsType);
+ when(mockOblExsType.getObligationExpression()).thenReturn(oblExTypeList);
+ when(mockOblExTypeListObj.getAttributeAssignmentExpression()).thenReturn(attrAssignList);
+ when(mockOblExTypeListObj.getFulfillOn()).thenReturn(effectTypePermit);
+ when(mockattrAssignListObj.getCategory()).thenReturn("");
+ when(mockattrAssignListObj.getAttributeId()).thenReturn("");
+ doReturn(jaxbElementMock).when(mockattrAssignListObj).getExpression();
+ doReturn(attrValTypeMock).when(jaxbElementMock).getValue();
+ when(attrValTypeMock.getContent()).thenReturn(contentList);
+
+ processor.rule(mockRuleType);
+
+ verify(mockRuleType, atLeast(1)).getEffect();
+ verify(mockRuleType, atLeast(1)).getObligationExpressions();
+ verify(mockOblExsType, atLeast(1)).getObligationExpression();
+ verify(mockOblExTypeListObj, atLeast(1)).getAttributeAssignmentExpression();
+ verify(mockOblExTypeListObj, atLeast(1)).getFulfillOn();
+ verify(mockattrAssignListObj, atLeast(1)).getExpression();
+ verify(jaxbElementMock, atLeast(1)).getValue();
+ verify(attrValTypeMock, atLeast(1)).getContent();
+
+ doReturn(attrDesignTypeMock).when(jaxbElementMock).getValue();
+ processor.rule(mockRuleType);
+ verify(jaxbElementMock, atLeast(1)).getValue();
+
+ doReturn(attrSelTypeMock).when(jaxbElementMock).getValue();
+ processor.rule(mockRuleType);
+ verify(jaxbElementMock, atLeast(1)).getValue();
+
+ doReturn(applyTypeMock).when(jaxbElementMock).getValue();
+ processor.rule(mockRuleType);
+ verify(jaxbElementMock, atLeast(1)).getValue();
+
+ doReturn(genericObjectMock).when(jaxbElementMock).getValue();
+ processor.rule(mockRuleType);
+ verify(jaxbElementMock, atLeast(1)).getValue();
+ }
+
+ @Test
+ public void testHtmlProcessorTarget() {
+ PolicySetType mockPolicySetType = Mockito.mock(PolicySetType.class);
+ processor = new HtmlProcessor(temp, mockPolicySetType);
+
+ processor.target(null);
+
+ AnyOfType mockAnyOfType = Mockito.mock(AnyOfType.class);
+ List<AnyOfType> anyOfList = new ArrayList<AnyOfType>();
+ anyOfList.add(mockAnyOfType);
+ anyOfList.add(mockAnyOfType); // adding duplicate element
+
+ AllOfType mockAllOfType = Mockito.mock(AllOfType.class);
+ List<AllOfType> allOfTypeList = new ArrayList<AllOfType>();
+ allOfTypeList.add(mockAllOfType);
+ allOfTypeList.add(mockAllOfType); // adding duplicate element
+
+ MatchType mockMatchType = Mockito.mock(MatchType.class);
+ List<MatchType> matchTypeList = new ArrayList<MatchType>();
+ matchTypeList.add(mockMatchType);
+ matchTypeList.add(mockMatchType); // adding duplicate element
+
+ AttributeValueType mockAttrValType = Mockito.mock(AttributeValueType.class);
+ AttributeDesignatorType mockAttrDesType = Mockito.mock(AttributeDesignatorType.class);
+ AttributeSelectorType mockAttrSelType = Mockito.mock(AttributeSelectorType.class);
+
+ List<Object> contentList = new ArrayList<Object>();
+
+ when(mockAnyOfType.getAllOf()).thenReturn(allOfTypeList);
+ when(mockAllOfType.getMatch()).thenReturn(matchTypeList);
+ when(mockMatchType.getAttributeValue()).thenReturn(mockAttrValType);
+ when(mockMatchType.getMatchId()).thenReturn(XACML1.ID_FUNCTION_STRING_EQUAL.stringValue());
+ when(mockMatchType.getAttributeDesignator()).thenReturn(mockAttrDesType);
+ when(mockAttrValType.getDataType()).thenReturn("");
+ when(mockAttrValType.getContent()).thenReturn(contentList);
+ when(mockAttrDesType.getCategory()).thenReturn("");
+ when(mockAttrDesType.getAttributeId()).thenReturn("");
+ when(mockAttrDesType.getIssuer()).thenReturn("");
+ when(mockAttrDesType.getDataType()).thenReturn("");
+ processor.target(anyOfList);
+ verify(mockAnyOfType, atLeast(1)).getAllOf();
+ verify(mockAllOfType, atLeast(1)).getMatch();
+ verify(mockMatchType, atLeast(1)).getAttributeValue();
+ verify(mockMatchType, atLeast(1)).getMatchId();
+ verify(mockMatchType, atLeast(1)).getAttributeDesignator();
+ verify(mockAttrValType, atLeast(1)).getDataType();
+ verify(mockAttrValType, atLeast(1)).getContent();
+ verify(mockAttrDesType, atLeast(1)).getCategory();
+ verify(mockAttrDesType, atLeast(1)).getAttributeId();
+ verify(mockAttrDesType, atLeast(1)).getIssuer();
+ verify(mockAttrDesType, atLeast(1)).getDataType();
+
+ when(mockMatchType.getAttributeDesignator()).thenReturn(null);
+ when(mockMatchType.getAttributeSelector()).thenReturn(mockAttrSelType);
+ when(mockAttrSelType.getCategory()).thenReturn("");
+ when(mockAttrSelType.getContextSelectorId()).thenReturn("");
+ when(mockAttrSelType.getDataType()).thenReturn("");
+ processor.target(anyOfList);
+ verify(mockMatchType, atLeast(1)).getAttributeDesignator();
+ verify(mockMatchType, atLeast(1)).getAttributeSelector();
+ verify(mockAttrSelType, atLeast(1)).getCategory();
+ verify(mockAttrSelType, atLeast(1)).getContextSelectorId();
+ verify(mockAttrSelType, atLeast(1)).getDataType();
+
+ when(mockMatchType.getAttributeDesignator()).thenReturn(null);
+ when(mockMatchType.getAttributeSelector()).thenReturn(null);
+ processor.target(anyOfList);
+ verify(mockMatchType, atLeast(1)).getAttributeDesignator();
+ verify(mockMatchType, atLeast(1)).getAttributeSelector();
+ }
+
+ @Test
+ public void testHtmlProcessorStringifyExpression() {
+ PolicySetType mockPolicySetType = Mockito.mock(PolicySetType.class);
+ processor = new HtmlProcessor(temp, mockPolicySetType);
+
+ RuleType mockRuleType = Mockito.mock(RuleType.class);
+ ConditionType mockConditionType = Mockito.mock(ConditionType.class);
+ JAXBElement<?> mockJAXBElement = Mockito.mock(JAXBElement.class);
+ EffectType effectTypePermit = EffectType.PERMIT;
+ Object mockExpressObject = Mockito.mock(Object.class);
+ AttributeDesignatorType mockAttrDesType = Mockito.mock(AttributeDesignatorType.class);
+ AttributeSelectorType mockAttrSelType = Mockito.mock(AttributeSelectorType.class);
+ AttributeValueType mockAttrValType = Mockito.mock(AttributeValueType.class);
+ VariableReferenceType mockVarRefType = Mockito.mock(VariableReferenceType.class);
+
+ Object mockContentObject = Mockito.mock(Object.class);
+ List<Object> contentList = new ArrayList<Object>();
+ contentList.add(mockContentObject);
+
+ when(mockRuleType.getEffect()).thenReturn(effectTypePermit);
+ when(mockRuleType.getCondition()).thenReturn(mockConditionType);
+ doReturn(mockJAXBElement).when(mockConditionType).getExpression();
+ doReturn(mockExpressObject).when(mockJAXBElement).getValue();
+
+ try {
+ processor.rule(mockRuleType);
+ fail();
+ } catch (IllegalArgumentException e) {
+ verify(mockRuleType, atLeast(1)).getEffect();
+ verify(mockRuleType, atLeast(1)).getCondition();
+ verify(mockConditionType, atLeast(1)).getExpression();
+ verify(mockJAXBElement, atLeast(1)).getValue();
+ }
+
+ doReturn(mockAttrDesType).when(mockJAXBElement).getValue();
+ when(mockAttrDesType.getCategory()).thenReturn("");
+ when(mockAttrDesType.getAttributeId()).thenReturn("");
+ when(mockAttrDesType.getDataType()).thenReturn("");
+ processor.rule(mockRuleType);
+ verify(mockJAXBElement, atLeast(1)).getValue();
+ verify(mockAttrDesType, atLeast(1)).getCategory();
+ verify(mockAttrDesType, atLeast(1)).getAttributeId();
+ verify(mockAttrDesType, atLeast(1)).getDataType();
+
+ doReturn(mockAttrSelType).when(mockJAXBElement).getValue();
+ when(mockAttrSelType.getPath()).thenReturn("SamplePath/text()");
+ processor.rule(mockRuleType);
+ verify(mockJAXBElement, atLeast(1)).getValue();
+ verify(mockAttrSelType, atLeast(1)).getPath();
+
+ when(mockAttrSelType.getPath()).thenReturn("");
+ processor.rule(mockRuleType);
+ verify(mockJAXBElement, atLeast(1)).getValue();
+ verify(mockAttrSelType, atLeast(1)).getPath();
+
+ doReturn(mockAttrValType).when(mockJAXBElement).getValue();
+ when(mockAttrValType.getContent()).thenReturn(contentList);
+ processor.rule(mockRuleType);
+ verify(mockJAXBElement, atLeast(1)).getValue();
+ verify(mockAttrValType, atLeast(1)).getContent();
+
+ doReturn(mockVarRefType).when(mockJAXBElement).getValue();
+ processor.rule(mockRuleType);
+ verify(mockJAXBElement, atLeast(1)).getValue();
+ }
+}
diff --git a/POLICY-SDK-APP/src/test/java/org/onap/policy/conf/HibernateSessionTest.java b/POLICY-SDK-APP/src/test/java/org/onap/policy/conf/HibernateSessionTest.java
index dab2cba53..2f079f139 100644
--- a/POLICY-SDK-APP/src/test/java/org/onap/policy/conf/HibernateSessionTest.java
+++ b/POLICY-SDK-APP/src/test/java/org/onap/policy/conf/HibernateSessionTest.java
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP Policy Engine
* ================================================================================
- * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2018-2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Modifications Copyright (C) 2019 Samsung
* ================================================================================
@@ -23,6 +23,7 @@
package org.onap.policy.conf;
import static org.junit.Assert.assertNull;
+
import org.hibernate.SessionFactory;
import org.junit.Before;
import org.junit.Test;
@@ -30,6 +31,10 @@ import org.mockito.Mockito;
import org.onap.policy.controller.PolicyController;
public class HibernateSessionTest {
+
+ /**
+ * setup.
+ */
@Before
public void setup() {
PolicyController.setLogdbUrl("testURL");
diff --git a/POLICY-SDK-APP/src/test/java/org/onap/policy/controller/ActionPolicyControllerTest.java b/POLICY-SDK-APP/src/test/java/org/onap/policy/controller/ActionPolicyControllerTest.java
new file mode 100644
index 000000000..e34cab45e
--- /dev/null
+++ b/POLICY-SDK-APP/src/test/java/org/onap/policy/controller/ActionPolicyControllerTest.java
@@ -0,0 +1,205 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP Policy Engine
+ * ================================================================================
+ * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 static org.assertj.core.api.Assertions.assertThatCode;
+
+import com.att.research.xacml.api.XACML3;
+import java.io.IOException;
+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 oasis.names.tc.xacml._3_0.core.schema.wd_17.VariableDefinitionType;
+import org.junit.Test;
+import org.onap.policy.rest.adapter.PolicyRestAdapter;
+
+public class ActionPolicyControllerTest {
+
+ @Test
+ public void testBasicConstructor() throws IOException {
+ ActionPolicyController controller = new ActionPolicyController();
+ final PolicyRestAdapter adapter = new PolicyRestAdapter();
+ //
+ // Cover the simple if instance branch
+ //
+ assertThatCode(() -> controller.prePopulateActionPolicyData(adapter)).doesNotThrowAnyException();
+ }
+
+ @Test
+ public void testNoDescriptionNoTargetType() throws IOException {
+ //
+ // Do the test - with no description and
+ // no TargetType to cover those branches.
+ //
+ PolicyRestAdapter adapter = new PolicyRestAdapter();
+ adapter.setPolicyData(new PolicyType());
+ adapter.setPolicyName("name");
+ ActionPolicyController controller = new ActionPolicyController();
+ assertThatCode(() -> controller.prePopulateActionPolicyData(adapter)).doesNotThrowAnyException();
+ }
+
+ @Test
+ public void testWithDescriptionEmptyTargetType() throws IOException {
+ //
+ // Create a simple PolicyType
+ //
+ PolicyType policy = new PolicyType();
+ policy.setTarget(new TargetType());
+ policy.setDescription("i am a description. @CreatedBy: policy designer");
+ //
+ // Now do the test - description and
+ // TargetType but its empty
+ //
+ PolicyRestAdapter adapter = new PolicyRestAdapter();
+ adapter.setPolicyData(policy);
+ adapter.setPolicyName("name");
+ ActionPolicyController controller = new ActionPolicyController();
+ assertThatCode(() -> controller.prePopulateActionPolicyData(adapter)).doesNotThrowAnyException();
+ }
+
+
+ @Test
+ public void testWithTargetTypeWithAnyOf() throws IOException {
+ //
+ // Create TargetType with empty AnyOf
+ //
+ AttributeValueType value = new AttributeValueType();
+ value.setDataType(XACML3.ID_DATATYPE_STRING.stringValue());
+ value.getContent().add(new String("value"));
+ AttributeDesignatorType designator = new AttributeDesignatorType();
+ designator.setAttributeId("foo:bar");
+ designator.setDataType(XACML3.ID_DATATYPE_STRING.stringValue());
+ designator.setCategory(XACML3.ID_ATTRIBUTE_CATEGORY_ACTION.stringValue());
+
+ MatchType match = new MatchType();
+ match.setMatchId(XACML3.ID_FUNCTION_STRING_EQUAL.stringValue());
+ match.setAttributeValue(value);
+ match.setAttributeDesignator(designator);
+ AllOfType allOf = new AllOfType();
+ allOf.getMatch().add(match);
+ AnyOfType anyOf = new AnyOfType();
+ anyOf.getAllOf().add(allOf);
+ TargetType target = new TargetType();
+ target.getAnyOf().add(anyOf);
+ //
+ // Create a simple Rule with NO obligations but a Condition
+ //
+ RuleType rule = new RuleType();
+ rule.setRuleId("id:rule");
+ rule.setEffect(EffectType.PERMIT);
+
+ AttributeValueType expressionValue = new AttributeValueType();
+ expressionValue.setDataType(XACML3.ID_DATATYPE_STRING.stringValue());
+ expressionValue.getContent().add(new String("a string value"));
+
+ designator = new AttributeDesignatorType();
+ designator.setAttributeId("foo:bar");
+ designator.setDataType(XACML3.ID_DATATYPE_STRING.stringValue());
+ designator.setCategory(XACML3.ID_ATTRIBUTE_CATEGORY_ACTION.stringValue());
+
+ ApplyType applyOneAndOnly = new ApplyType();
+ applyOneAndOnly.setDescription("apply this");
+ applyOneAndOnly.setFunctionId(XACML3.ID_FUNCTION_STRING_ONE_AND_ONLY.stringValue());
+ applyOneAndOnly.getExpression().add(new ObjectFactory().createAttributeDesignator(designator));
+
+ ApplyType applyOneAndOnly2 = new ApplyType();
+ applyOneAndOnly2.setDescription("apply this");
+ applyOneAndOnly2.setFunctionId(XACML3.ID_FUNCTION_STRING_ONE_AND_ONLY.stringValue());
+ applyOneAndOnly2.getExpression().add(new ObjectFactory().createAttributeValue(expressionValue));
+
+ ApplyType apply = new ApplyType();
+ apply.setDescription("apply this");
+ apply.setFunctionId(XACML3.ID_FUNCTION_STRING_EQUAL.stringValue());
+ apply.getExpression().add(new ObjectFactory().createApply(applyOneAndOnly));
+ apply.getExpression().add(new ObjectFactory().createApply(applyOneAndOnly2));
+
+
+ ConditionType condition = new ConditionType();
+ condition.setExpression(new ObjectFactory().createApply(apply));
+ rule.setCondition(condition);
+ //
+ // Create a simple Rule WITH obligations
+ //
+ AttributeValueType val = new AttributeValueType();
+ val.setDataType(XACML3.ID_DATATYPE_STRING.stringValue());
+ val.getContent().add(new String("obligation data"));
+
+ AttributeAssignmentExpressionType assignment = new AttributeAssignmentExpressionType();
+ assignment.setAttributeId("ob:id:1");
+ assignment.setCategory(XACML3.ID_SUBJECT_CATEGORY_ACCESS_SUBJECT.stringValue());
+ assignment.setExpression(new ObjectFactory().createAttributeValue(val));
+
+ AttributeValueType val2 = new AttributeValueType();
+ val2.setDataType(XACML3.ID_DATATYPE_STRING.stringValue());
+ val2.getContent().add(new String("iamperformer"));
+
+ AttributeAssignmentExpressionType assignment2 = new AttributeAssignmentExpressionType();
+ assignment2.setAttributeId("performer");
+ assignment2.setCategory(XACML3.ID_SUBJECT_CATEGORY_ACCESS_SUBJECT.stringValue());
+ assignment2.setExpression(new ObjectFactory().createAttributeValue(val2));
+
+ ObligationExpressionType ob = new ObligationExpressionType();
+ ob.setFulfillOn(EffectType.PERMIT);
+ ob.setObligationId("id:obligation");
+ ob.getAttributeAssignmentExpression().add(assignment);
+ ob.getAttributeAssignmentExpression().add(assignment2);
+ ObligationExpressionsType obs = new ObligationExpressionsType();
+ obs.getObligationExpression().add(ob);
+ RuleType obligationRule = new RuleType();
+ obligationRule.setRuleId("id:rule:obligations");
+ obligationRule.setEffect(EffectType.DENY);
+ obligationRule.setObligationExpressions(obs);
+ //
+ // Create a PolicyType
+ //
+ PolicyType policy = new PolicyType();
+ policy.setDescription("i am a description. @CreatedBy: policy designer");
+ policy.setTarget(target);
+ policy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition().add(rule);
+ policy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition().add(obligationRule);
+ //
+ // Add something the ActionPolicyController will skip over
+ // to catch that branch
+ //
+ policy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition().add(new VariableDefinitionType());
+ //
+ // Now do the test - description and
+ // TargetType but its empty
+ //
+ PolicyRestAdapter adapter = new PolicyRestAdapter();
+ adapter.setPolicyData(policy);
+ adapter.setPolicyName("name");
+ ActionPolicyController controller = new ActionPolicyController();
+ assertThatCode(() -> controller.prePopulateActionPolicyData(adapter)).doesNotThrowAnyException();
+ }
+}
diff --git a/POLICY-SDK-APP/src/test/java/org/onap/policy/controller/AdminTabControllerTest.java b/POLICY-SDK-APP/src/test/java/org/onap/policy/controller/AdminTabControllerTest.java
index a4999ff42..eccab040c 100644
--- a/POLICY-SDK-APP/src/test/java/org/onap/policy/controller/AdminTabControllerTest.java
+++ b/POLICY-SDK-APP/src/test/java/org/onap/policy/controller/AdminTabControllerTest.java
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP Policy Engine
* ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017, 2019-2020 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Modifications Copyright (C) 2019 Samsung
* ================================================================================
@@ -19,18 +19,25 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.policy.controller;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
+
import java.io.BufferedReader;
+import java.io.IOException;
import java.io.StringReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.junit.Before;
import org.junit.Test;
@@ -49,25 +56,26 @@ public class AdminTabControllerTest {
private static CommonClassDao commonClassDao;
private HttpServletRequest request;
private MockHttpServletResponse response;
+ private AdminTabController admin;
+ /**
+ * Before.
+ *
+ * @throws Exception Exception
+ */
@Before
public void setUp() throws Exception {
-
+ admin = new AdminTabController();
logger.info("setUp: Entering");
commonClassDao = mock(CommonClassDao.class);
-
request = mock(HttpServletRequest.class);
response = new MockHttpServletResponse();
-
HttpSession mockSession = mock(HttpSession.class);
User user = new User();
user.setOrgUserId("Test");
- Mockito.when(mockSession.getAttribute(SystemProperties.getProperty("user_attribute_name")))
- .thenReturn(user);
+ Mockito.when(mockSession.getAttribute(SystemProperties.getProperty("user_attribute_name"))).thenReturn(user);
Mockito.when(request.getSession(false)).thenReturn(mockSession);
-
AdminTabController.setCommonClassDao(commonClassDao);
-
GlobalRoleSettings globalRole = new GlobalRoleSettings();
globalRole.setLockdown(true);
globalRole.setRole("super-admin");
@@ -78,11 +86,10 @@ public class AdminTabControllerTest {
@Test
public void testGetAdminRole() {
- AdminTabController admin = new AdminTabController();
+ assertNotNull(AdminTabController.getCommonClassDao());
try {
admin.getAdminTabEntityData(request, response);
- assertTrue(response.getContentAsString() != null
- && response.getContentAsString().contains("lockdowndata"));
+ assertTrue(response.getContentAsString() != null && response.getContentAsString().contains("lockdowndata"));
} catch (UnsupportedEncodingException e) {
logger.error("Exception Occured" + e);
fail();
@@ -91,7 +98,6 @@ public class AdminTabControllerTest {
@Test
public void testSaveAdminRole() throws Exception {
- AdminTabController admin = new AdminTabController();
String data = "{\"lockdowndata\":{\"lockdown\":true}}";
BufferedReader reader = new BufferedReader(new StringReader(data));
try {
@@ -104,4 +110,18 @@ public class AdminTabControllerTest {
fail();
}
}
+
+ @SuppressWarnings("unchecked")
+ @Test
+ public void testGetAdminTabEntityDataException() throws IOException {
+ HttpServletResponse mockResponse = Mockito.mock(HttpServletResponse.class);
+ when(mockResponse.getWriter()).thenThrow(IOException.class);
+ admin.getAdminTabEntityData(request, mockResponse);
+ verify(mockResponse).getWriter();
+ }
+
+ @Test
+ public void testSaveAdminTabLockdownValueException() throws IOException {
+ assertNull(admin.saveAdminTabLockdownValue(request, response));
+ }
}
diff --git a/POLICY-SDK-APP/src/test/java/org/onap/policy/controller/AutoPushControllerTest.java b/POLICY-SDK-APP/src/test/java/org/onap/policy/controller/AutoPushControllerTest.java
index 5dd5d7ee3..95d566278 100644
--- a/POLICY-SDK-APP/src/test/java/org/onap/policy/controller/AutoPushControllerTest.java
+++ b/POLICY-SDK-APP/src/test/java/org/onap/policy/controller/AutoPushControllerTest.java
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP Policy Engine
* ================================================================================
- * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2018-2020 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Modifications Copyright (C) 2019 Samsung
* ================================================================================
@@ -19,36 +19,71 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.policy.controller;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.atLeast;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+import com.att.research.xacml.api.pap.PAPException;
+import com.mockrunner.mock.web.MockHttpServletRequest;
+import com.mockrunner.mock.web.MockHttpServletResponse;
import java.io.IOException;
+import java.util.ArrayList;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
+import javax.servlet.http.HttpSession;
+import org.junit.BeforeClass;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
+import org.onap.policy.model.Roles;
+import org.onap.policy.xacml.api.pap.OnapPDPGroup;
+import org.onap.policy.xacml.api.pap.PAPPolicyEngine;
import org.onap.portalsdk.core.domain.User;
+import org.onap.portalsdk.core.web.support.AppUtils;
import org.onap.portalsdk.core.web.support.UserUtils;
import org.powermock.api.mockito.PowerMockito;
+import org.powermock.core.classloader.annotations.PowerMockIgnore;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
-import com.mockrunner.mock.web.MockHttpServletRequest;
-import com.mockrunner.mock.web.MockHttpServletResponse;
@RunWith(PowerMockRunner.class)
+@PowerMockIgnore({"com.sun.org.apache.xerces.*", "jdk.internal.reflect.*", "javax.xml.*", "org.xml.*", "org.w3c.*"})
public class AutoPushControllerTest {
- private PolicyController controller = new PolicyController();;
+ private PolicyController controller = new PolicyController();
private AutoPushController apController = new AutoPushController();
+ private static HttpServletRequest mockRequest = Mockito.mock(HttpServletRequest.class);
+ private static HttpServletResponse mockResponse = Mockito.mock(HttpServletResponse.class);
+ private static PolicyController mockPolicyController = Mockito.mock(PolicyController.class);
+ private static HttpSession mockSession = Mockito.mock(HttpSession.class);
+ private static User mockUser = Mockito.mock(User.class);
+ private static List<Object> rolesList = new ArrayList<>();
+
@Rule
public ExpectedException thrown = ExpectedException.none();
+ @BeforeClass
+ public static void setupMocks() {
+ when(mockRequest.getSession(false)).thenReturn(mockSession);
+ when(AppUtils.getSession(mockRequest)).thenReturn(mockSession);
+ when(UserUtils.getUserSession(mockRequest)).thenReturn(mockUser);
+ when(mockUser.getOrgUserId()).thenReturn("");
+ when(mockPolicyController.getRoles(any(String.class))).thenReturn(rolesList);
+ }
+
@Test
public void testAutoPushSetGet() throws IOException {
- // Get and set tests
apController.setPolicyController(controller);
assertEquals(apController.getPolicyController(), controller);
}
@@ -75,7 +110,7 @@ public class AutoPushControllerTest {
}
@Test(expected = NullPointerException.class)
- public void testRefresh() throws IOException {
+ public void testRefreshGroupsNull() throws IOException {
apController.refreshGroups();
}
@@ -88,22 +123,105 @@ public class AutoPushControllerTest {
Mockito.when(UserUtils.getUserSession(Mockito.any())).thenReturn(user);
// Mock policy controller
- PolicyController pController = Mockito.mock(PolicyController.class);
- PowerMockito.whenNew(PolicyController.class).withNoArguments().thenReturn(pController);
- Mockito.when(pController.getRoles(Mockito.any())).thenReturn(null);
+ PolicyController policyController = Mockito.mock(PolicyController.class);
+ PowerMockito.whenNew(PolicyController.class).withNoArguments().thenReturn(policyController);
+ Mockito.when(policyController.getRoles(Mockito.any())).thenReturn(null);
// Test group container
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
apController.getPolicyGroupContainerData(request, response);
- assertEquals(response.getStatusCode(), HttpServletResponse.SC_OK);
+ assertEquals(HttpServletResponse.SC_OK, response.getStatusCode());
// Test push
apController.pushPolicyToPDPGroup(request, response);
- assertEquals(response.getStatusCode(), HttpServletResponse.SC_OK);
+ assertEquals(HttpServletResponse.SC_OK, response.getStatusCode());
// Test remove
apController.removePDPGroup(request, response);
- assertEquals(response.getStatusCode(), HttpServletResponse.SC_OK);
+ assertEquals(HttpServletResponse.SC_OK, response.getStatusCode());
+ }
+
+ @Test
+ public void testRefreshGroupsSuccess() throws PAPException {
+ PolicyController mockPolicyController = Mockito.mock(PolicyController.class);
+ PAPPolicyEngine mockPAPPolicyEngine = Mockito.mock(PAPPolicyEngine.class);
+ Set<OnapPDPGroup> onapPDPGroups = new HashSet<>();
+ when(mockPolicyController.getPapEngine()).thenReturn(mockPAPPolicyEngine);
+ when(mockPAPPolicyEngine.getOnapPDPGroups()).thenReturn(onapPDPGroups);
+ apController.setPolicyController(mockPolicyController);
+ apController.refreshGroups();
+ verify(mockPolicyController).getPapEngine();
+ verify(mockPAPPolicyEngine).getOnapPDPGroups();
+ }
+
+ @SuppressWarnings("unchecked")
+ @Test
+ public void testRefreshGroups() throws PAPException {
+ PolicyController mockPolicyController = Mockito.mock(PolicyController.class);
+ PAPPolicyEngine mockPAPPolicyEngine = Mockito.mock(PAPPolicyEngine.class);
+ when(mockPolicyController.getPapEngine()).thenReturn(mockPAPPolicyEngine);
+ when(mockPAPPolicyEngine.getOnapPDPGroups()).thenThrow(PAPException.class);
+ apController.setPolicyController(mockPolicyController);
+ apController.refreshGroups();
+ verify(mockPolicyController).getPapEngine();
+ verify(mockPAPPolicyEngine).getOnapPDPGroups();
+ }
+
+ @Test
+ public void testGetPolicyGroupContainerData() throws Exception {
+ Roles superAdmin = new Roles();
+ Roles superEditor = new Roles();
+ Roles superGuest = new Roles();
+ rolesList.add(superAdmin);
+ rolesList.add(superEditor);
+ rolesList.add(superGuest);
+
+ apController.setPolicyController(mockPolicyController);
+ apController.getPolicyGroupContainerData(mockRequest, mockResponse);
+
+ verify(mockRequest, atLeast(1)).getSession(false);
+ verify(mockUser, atLeast(1)).getOrgUserId();
+ verify(mockPolicyController, atLeast(1)).getRoles(any(String.class));
+ }
+
+ @Test
+ public void testGetPolicyGroupContainerDataWithScope() throws Exception {
+ Roles superAdmin = new Roles();
+ superAdmin.setScope("super-admin-scope");
+ Roles superEditor = new Roles();
+ superEditor.setScope("super-editor-scope");
+ Roles superGuest = new Roles();
+ superGuest.setScope("super-guest-scope");
+ rolesList.add(superAdmin);
+ rolesList.add(superEditor);
+ rolesList.add(superGuest);
+
+ apController.setPolicyController(mockPolicyController);
+ apController.getPolicyGroupContainerData(mockRequest, mockResponse);
+
+ verify(mockRequest, atLeast(1)).getSession(false);
+ verify(mockUser, atLeast(1)).getOrgUserId();
+ verify(mockPolicyController, atLeast(1)).getRoles(any(String.class));
+ }
+
+ @Test
+ public void testGetPolicyGroupContainerDataWithRole() throws Exception {
+ Roles superAdmin = new Roles();
+ superAdmin.setRole("super-admin");
+ Roles superEditor = new Roles();
+ superEditor.setRole("super-editor");
+ Roles superGuest = new Roles();
+ superGuest.setRole("super-guest");
+ rolesList.add(superAdmin);
+ rolesList.add(superEditor);
+ rolesList.add(superGuest);
+
+ apController.setPolicyController(mockPolicyController);
+ apController.getPolicyGroupContainerData(mockRequest, mockResponse);
+
+ verify(mockRequest, atLeast(1)).getSession(false);
+ verify(mockUser, atLeast(1)).getOrgUserId();
+ verify(mockPolicyController, atLeast(1)).getRoles(any(String.class));
}
}
diff --git a/POLICY-SDK-APP/src/test/java/org/onap/policy/controller/CreateDcaeMicroServiceControllerTest.java b/POLICY-SDK-APP/src/test/java/org/onap/policy/controller/CreateDcaeMicroServiceControllerTest.java
index e4ededa1f..8966f47a9 100644
--- a/POLICY-SDK-APP/src/test/java/org/onap/policy/controller/CreateDcaeMicroServiceControllerTest.java
+++ b/POLICY-SDK-APP/src/test/java/org/onap/policy/controller/CreateDcaeMicroServiceControllerTest.java
@@ -22,7 +22,6 @@
package org.onap.policy.controller;
-
import static org.easymock.EasyMock.createMock;
import static org.easymock.EasyMock.expect;
import static org.easymock.EasyMock.replay;
@@ -70,10 +69,9 @@ import org.springframework.mock.web.MockHttpServletResponse;
/**
* The class <code>CreateDcaeMicroServiceControllerTest</code> contains tests for the class
- * {@link <code>CreateDcaeMicroServiceController</code>}*
*
- * All JUnits are designed to run in the local development environment where they have write privileges and can execute
- * time-sensitive tasks.
+ * <p/>All JUnits are designed to run in the local development environment where they have write privileges
+ * and can execute time-sensitive tasks.
*
*/
@@ -85,11 +83,15 @@ public class CreateDcaeMicroServiceControllerTest {
private String configBodyString = null;
private HttpServletRequest request = null;
+ /**
+ * setUp.
+ *
+ * @throws Exception should not throw one
+ */
@Before
public void setUp() throws Exception {
logger.info("setUp: Entering");
commonClassDao = mock(CommonClassDao.class);
- List<Object> microServiceModelsData = new ArrayList<Object>();
MicroServiceModels testData = new MicroServiceModels();
testData.setVersion("OpenOnap-Junit");
testData.setModelName("modelName");
@@ -101,11 +103,11 @@ public class CreateDcaeMicroServiceControllerTest {
+ "CorrelationWindow=String:defaultValue-null:required-true:MANY-false:description-null,"
+ "EmailNotification=String:defaultValue-null:required-true:MANY-false:description-null,"
+ "CorrelationPriority=string:defaultValue-null:required-true:MANY-false:description-null,");
- testData.setRef_attributes("SymptomTriggerSignature=resource-model-symptomEntity:MANY-true:description-null,"
+ testData.setRefAttributes("SymptomTriggerSignature=resource-model-symptomEntity:MANY-true:description-null,"
+ "triggerSignature=resource-model-entity:MANY-true:description-null,"
+ "SelectServerScope=SELECTSERVERSCOPE:MANY-false,logicalConnector=LOGICALCONNECTOR:MANY-false,"
+ "ParentCorrelationTraversal=PARENTCORRELATIONTRAVERSAL:MANY-false,");
- testData.setSub_attributes(
+ testData.setSubAttributes(
"{\"symptomAlarms\":{\"symptomContains\":\"SYMPTOMCONTAINS:defaultValue-null:required-true:MANY-false:"
+ "description-null\",\"symptomFilterValue\":\"string:defaultValue-null:"
+ "required-true:MANY-false:"
@@ -136,6 +138,7 @@ public class CreateDcaeMicroServiceControllerTest {
testData.setDataOrderInfo("triggerSignature.signaturesAlarm.alarmSignatures.alarmSignature[VnfType, Contains, "
+ "FilterValue]@SymptomTriggerSignature.signaturesSymptom.symptomSignatures."
+ "symptomSignature[symptomVnfType, symptomContains, symptomFilterValue]");
+ List<Object> microServiceModelsData = new ArrayList<Object>();
microServiceModelsData.add(testData);
// mock the getDataById() call
@@ -159,15 +162,8 @@ public class CreateDcaeMicroServiceControllerTest {
+ "\"asdafadf\",\"guard\":\"True\",\"riskType\":\"sfsgs\",\"riskLevel\":\"1\","
+ "\"priority\":\"1\",\"configName\":\"Search\",\"location\":\"Search\","
+ "\"uuid\":\"Search\",\"policyScope\":\"PolicyScope_ssaaa123\"}},"
- + "\"policyJSON\":{\"Correlation Priority\":\"testttt\",\"Correlation Window\":"
- + "\"testttt\",\"Email Notification for failures\":\"sds@l.com\","
- + "\"Select Server Scope\":\"testttt\",\"Parent Correlation Name\":"
- + "\"testttt\",\"Parent Correlation Traversal\":\"testttt\",\"logicalConnector\":"
- + "\"OR\",\"triggerSignature@0.signaturesAlarm.alarmSignatures@0.traversal\":\"testttt\","
- + "\"triggerSignature@0.signaturesAlarm.alarmSignatures@0.alarmSignature@0.VnfType\":"
- + "\" testttt\",\"triggerSignature@0.signaturesAlarm.alarmSignatures@0."
- + "alarmSignature@0.Contains\":\"AND\",\"triggerSignature@0.signaturesAlarm."
- + "alarmSignatures@0.alarmSignature@0.FilterValue\":\"testttt\"}}";
+ + "\"policyJSON\":{\"DCAEProcessingRules@0.processingRules_json\":"
+ + "\"eyJuYW1lIjogIkpvaG4iLCAiYWdlIjogIjI4IiwgImNpdHkiOiAiTmV3IFlvcmsifQ==\"}}";
configBodyString = "{\"service\":\"SniroPolicyEntityTest\",\"policyName\":\"someone\",\"description\":\"test\","
+ "\"templateVersion\":\"1607\",\"version\":\"HD\",\"priority\":\"2\","
@@ -349,11 +345,8 @@ public class CreateDcaeMicroServiceControllerTest {
try {
root = JsonLoader.fromString(jsonString);
restAdapter = mapper.readValue(root.get("policyData").get("policy").toString(), PolicyRestAdapter.class);
- TargetType target = new TargetType();
// create guard attribute
- AnyOfType anyOfType = new AnyOfType();
- AllOfType alltype = new AllOfType();
MatchType matchType = new MatchType();
// set value
AttributeValueType attributeValue1 = new AttributeValueType();
@@ -363,6 +356,7 @@ public class CreateDcaeMicroServiceControllerTest {
AttributeDesignatorType designator = new AttributeDesignatorType();
designator.setAttributeId("guard");
matchType.setAttributeDesignator(designator);
+ AllOfType alltype = new AllOfType();
alltype.getMatch().add(matchType);
// add a dummy MatchType object since while (matchList.size()>1 ...)
@@ -377,8 +371,10 @@ public class CreateDcaeMicroServiceControllerTest {
matchDummy.setAttributeDesignator(designatorDummy);
alltype.getMatch().add(matchDummy);
+ AnyOfType anyOfType = new AnyOfType();
anyOfType.getAllOf().add(alltype);
+ TargetType target = new TargetType();
target.getAnyOf().add(anyOfType);
// create RiskType attribute
diff --git a/POLICY-SDK-APP/src/test/java/org/onap/policy/controller/CreateOptimizationControllerTest.java b/POLICY-SDK-APP/src/test/java/org/onap/policy/controller/CreateOptimizationControllerTest.java
index 6747e9669..8e1b8be87 100644
--- a/POLICY-SDK-APP/src/test/java/org/onap/policy/controller/CreateOptimizationControllerTest.java
+++ b/POLICY-SDK-APP/src/test/java/org/onap/policy/controller/CreateOptimizationControllerTest.java
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP Policy Engine
* ================================================================================
- * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2018-2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Modifications Copyright (C) 2019 Samsung
* ================================================================================
@@ -22,7 +22,6 @@
package org.onap.policy.controller;
-
import static org.easymock.EasyMock.createMock;
import static org.easymock.EasyMock.expect;
import static org.easymock.EasyMock.replay;
@@ -31,6 +30,12 @@ import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
+
+import com.fasterxml.jackson.databind.DeserializationFeature;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.github.fge.jackson.JsonLoader;
+
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
@@ -39,9 +44,19 @@ import java.io.InputStream;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.List;
+
import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
+
+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;
+
import org.junit.Before;
import org.junit.Test;
import org.onap.policy.common.logging.flexlogger.FlexLogger;
@@ -51,25 +66,12 @@ import org.onap.policy.rest.dao.CommonClassDao;
import org.onap.policy.rest.jpa.ConfigurationDataEntity;
import org.onap.policy.rest.jpa.OptimizationModels;
import org.onap.policy.rest.jpa.PolicyEntity;
-import org.springframework.mock.web.MockHttpServletRequest;
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;
-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;
/**
* The class <code>CreateOptimizationControllerTest</code> contains tests for the class
- * {@link <code>CreateOptimizationController</code>}*
*
- * All JUnits are designed to run in the local development environment where they have write
+ * <p/>All JUnits are designed to run in the local development environment where they have write
* privileges and can execute time-sensitive tasks.
*/
public class CreateOptimizationControllerTest {
@@ -94,26 +96,24 @@ public class CreateOptimizationControllerTest {
when(commonClassDao.getDataById(OptimizationModels.class, "modelName", "test"))
.thenReturn(optimizationModelsData);
- jsonString =
- "{\"policyData\": {\"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\": \"OOF\","
- + "\"policyName\": \"testPolicy\",\"policyDescription\": \"testing input\","
- + "\"onapName\": \"test\",\"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\":\"PolicyEntityTest\",\"policyName\":\"someone\",\"description\":\"test\","
- + "\"templateVersion\":\"1607\",\"version\":\"HD\",\"priority\":\"2\","
- + "\"content\":{\"lastPolled\":\"1\",\"boolen-test\":\"true\",\"created\":\"test\","
- + "\"retiredDate\":\"test\",\"scope\":\"TEST_PLACEMENT_VDHV\",\"name\":\"test\","
- + "\"lastModified\":\"test\",\"state\":\"CREATED\",\"type\":\"CONFIG\",\"intent\":\"test\","
- + "\"target\":\"TEST\"}}";
+ jsonString = "{\"policyData\": {\"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\": \"OOF\","
+ + "\"policyName\": \"testPolicy\",\"policyDescription\": \"testing input\","
+ + "\"onapName\": \"test\",\"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\":\"PolicyEntityTest\",\"policyName\":\"someone\",\"description\":\"test\","
+ + "\"templateVersion\":\"1607\",\"version\":\"HD\",\"priority\":\"2\","
+ + "\"content\":{\"lastPolled\":\"1\",\"boolen-test\":\"true\",\"created\":\"test\","
+ + "\"retiredDate\":\"test\",\"scope\":\"TEST_PLACEMENT_VDHV\",\"name\":\"test\","
+ + "\"lastModified\":\"test\",\"state\":\"CREATED\",\"type\":\"CONFIG\",\"intent\":\"test\","
+ + "\"target\":\"TEST\"}}";
request = mock(HttpServletRequest.class);
BufferedReader br = new BufferedReader(new StringReader(jsonString));
@@ -124,7 +124,7 @@ public class CreateOptimizationControllerTest {
}
/**
- * Run the PolicyRestAdapter setDataToPolicyRestAdapter(PolicyRestAdapter, JsonNode) method test
+ * Run the PolicyRestAdapter setDataToPolicyRestAdapter(PolicyRestAdapter, JsonNode) method test.
*/
@Test
@@ -141,15 +141,14 @@ public class CreateOptimizationControllerTest {
PolicyRestAdapter policyData = null;
try {
root = JsonLoader.fromString(jsonString);
- policyData = (PolicyRestAdapter) mapper.readValue(
- root.get("policyData").get("policy").toString(), PolicyRestAdapter.class);
+ policyData = mapper.readValue(root.get("policyData").get("policy").toString(),
+ PolicyRestAdapter.class);
} catch (Exception e) {
logger.error("testSetDataToPolicyRestAdapter", e);
}
PolicyRestAdapter result = controller.setDataToPolicyRestAdapter(policyData, root);
- assertTrue(
- result != null && result.getJsonBody() != null && !result.getJsonBody().isEmpty());
+ assertTrue(result != null && result.getJsonBody() != null && !result.getJsonBody().isEmpty());
logger.debug("result.getJsonBody() : " + result.getJsonBody());
logger.debug("testSetDataToPolicyRestAdapter: exit");
@@ -157,7 +156,7 @@ public class CreateOptimizationControllerTest {
/**
* Run the ModelAndView getOptimizationTemplateData(HttpServletRequest, HttpServletResponse)
- * method test
+ * method test.
*/
@Test
@@ -181,8 +180,8 @@ public class CreateOptimizationControllerTest {
testData.setVersion("1707.4.1.2-Junit");
optimizationModelsData.add(testData);
// mock the getDataById() call with the same MS model name
- when(commonClassDao.getDataById(OptimizationModels.class, "modelName",
- "testPolicyBody")).thenReturn(optimizationModelsData);
+ when(commonClassDao.getDataById(OptimizationModels.class, "modelName", "testPolicyBody"))
+ .thenReturn(optimizationModelsData);
controller.getOptimizationTemplateData(request, response);
@@ -200,7 +199,7 @@ public class CreateOptimizationControllerTest {
/**
* Run the ModelAndView getModelServiceVersionData(HttpServletRequest, HttpServletResponse)
- * method test
+ * method test.
*/
@Test
@@ -225,8 +224,8 @@ public class CreateOptimizationControllerTest {
optimizationModelsData.add(testData);
// mock the getDataById() call with the same MS model name
- when(commonClassDao.getDataById(OptimizationModels.class, "modelName",
- "TestPolicyBody")).thenReturn(optimizationModelsData);
+ when(commonClassDao.getDataById(OptimizationModels.class, "modelName", "TestPolicyBody"))
+ .thenReturn(optimizationModelsData);
controller.getModelServiceVersionData(request, response);
assertTrue(response.getContentAsString() != null
@@ -243,7 +242,7 @@ public class CreateOptimizationControllerTest {
}
/**
- * Run the void prePopulateDCAEMSPolicyData(PolicyRestAdapter, PolicyEntity) method test
+ * Run the void prePopulateDCAEMSPolicyData(PolicyRestAdapter, PolicyEntity) method test.
*/
@Test
@@ -266,8 +265,8 @@ public class CreateOptimizationControllerTest {
try {
root = JsonLoader.fromString(jsonString);
- restAdapter = (PolicyRestAdapter) mapper.readValue(
- root.get("policyData").get("policy").toString(), PolicyRestAdapter.class);
+ restAdapter = mapper.readValue(root.get("policyData").get("policy").toString(),
+ PolicyRestAdapter.class);
PolicyType policyType = new PolicyType();
TargetType target = new TargetType();
@@ -386,7 +385,7 @@ public class CreateOptimizationControllerTest {
}
/**
- * Run the void SetMSModelData(HttpServletRequest, HttpServletResponse) method test
+ * Run the void SetMSModelData(HttpServletRequest, HttpServletResponse) method test.
*/
@Test
@@ -409,9 +408,7 @@ public class CreateOptimizationControllerTest {
String fileName = "";
try {
ClassLoader classLoader = getClass().getClassLoader();
- fileName =
- new File(classLoader.getResource("schedulerPolicies-v1707.xmi").getFile())
- .getAbsolutePath();
+ fileName = new File(classLoader.getResource("schedulerPolicies-v1707.xmi").getFile()).getAbsolutePath();
} catch (Exception e1) {
logger.error("Exception Occured while loading file" + e1);
}
@@ -430,9 +427,7 @@ public class CreateOptimizationControllerTest {
}
/**
- *
- * @ Get File Stream
- *
+ * @ Get File Stream.
*/
private class MockServletInputStream extends ServletInputStream {
diff --git a/POLICY-SDK-APP/src/test/java/org/onap/policy/controller/CreatePolicyControllerTest.java b/POLICY-SDK-APP/src/test/java/org/onap/policy/controller/CreatePolicyControllerTest.java
new file mode 100644
index 000000000..79277d81d
--- /dev/null
+++ b/POLICY-SDK-APP/src/test/java/org/onap/policy/controller/CreatePolicyControllerTest.java
@@ -0,0 +1,139 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP Policy Engine
+ * ================================================================================
+ * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+import com.att.research.xacml.api.XACML3;
+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;
+import oasis.names.tc.xacml._3_0.core.schema.wd_17.VariableDefinitionType;
+import org.junit.Before;
+import org.junit.Test;
+import org.onap.policy.rest.adapter.PolicyRestAdapter;
+import org.onap.policy.rest.jpa.ConfigurationDataEntity;
+import org.onap.policy.rest.jpa.PolicyEntity;
+
+public class CreatePolicyControllerTest {
+
+ private PolicyEntity entity;
+
+ /**
+ * before - sets up the mocked PolicyEntity.
+ */
+ @Before
+ public void before() {
+ //
+ // PolicyEntity
+ //
+ ConfigurationDataEntity dataEntity = mock(ConfigurationDataEntity.class);
+ when(dataEntity.getConfigType()).thenReturn("configtype");
+ entity = mock(PolicyEntity.class);
+ when(entity.getConfigurationData()).thenReturn(dataEntity);
+ }
+
+ @Test
+ public void testEasyStuff() {
+ CreatePolicyController controller = new CreatePolicyController();
+ PolicyRestAdapter adapter = new PolicyRestAdapter();
+ controller.prePopulateBaseConfigPolicyData(adapter, null);
+ //
+ // Create a simple PolicyType
+ //
+ VariableDefinitionType var = new VariableDefinitionType();
+ PolicyType policy = new PolicyType();
+ policy.setDescription("i am a description. @CreatedBy: policy designer");
+ policy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition().add(var);
+ adapter.setPolicyData(policy);
+ adapter.setPolicyName("name");
+ controller.prePopulateBaseConfigPolicyData(adapter, entity);
+ }
+
+ @Test
+ public void testBadDescription() {
+ PolicyRestAdapter adapter = new PolicyRestAdapter();
+ //
+ // Create a simple PolicyType
+ //
+ VariableDefinitionType var = new VariableDefinitionType();
+ PolicyType policy = new PolicyType();
+ policy.setDescription("i am a description");
+ policy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition().add(var);
+ adapter.setPolicyData(policy);
+ adapter.setPolicyName("name");
+ CreatePolicyController controller = new CreatePolicyController();
+ controller.prePopulateBaseConfigPolicyData(adapter, entity);
+ }
+
+ @Test
+ public void testExpectedPolicyContents() {
+ AllOfType allOf = new AllOfType();
+ allOf.getMatch().add(createMatchType("ONAPName", "ONAPName"));
+ allOf.getMatch().add(createMatchType("RiskType", "RiskType"));
+ allOf.getMatch().add(createMatchType("RiskLevel", "RiskLevel"));
+ allOf.getMatch().add(createMatchType("guard", "guard"));
+ allOf.getMatch().add(createMatchType("TTLDate", "TTLDate"));
+ allOf.getMatch().add(createMatchType("ConfigName", "ConfigName"));
+ allOf.getMatch().add(createMatchType("NA", "TTLDate"));
+ allOf.getMatch().add(createMatchType("custom", "custom"));
+ allOf.getMatch().add(createMatchType("custom", "custom"));
+ allOf.getMatch().add(createMatchType("custom", "custom"));
+
+ AnyOfType anyOf = new AnyOfType();
+ anyOf.getAllOf().add(allOf);
+
+ TargetType target = new TargetType();
+ target.getAnyOf().add(anyOf);
+
+ RuleType rule = new RuleType();
+ PolicyType policy = new PolicyType();
+ policy.setDescription("i am a description. @CreatedBy: policy designer");
+ policy.setTarget(target);
+ policy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition().add(rule);
+ PolicyRestAdapter adapter = new PolicyRestAdapter();
+ adapter.setPolicyData(policy);
+ adapter.setPolicyName("name");
+ CreatePolicyController controller = new CreatePolicyController();
+ controller.prePopulateBaseConfigPolicyData(adapter, entity);
+ }
+
+ private MatchType createMatchType(String strValue, String id) {
+ AttributeValueType value = new AttributeValueType();
+ value.setDataType(XACML3.ID_DATATYPE_STRING.stringValue());
+ value.getContent().add(new String(strValue));
+ AttributeDesignatorType designator = new AttributeDesignatorType();
+ designator.setAttributeId(id);
+
+ MatchType match = new MatchType();
+ match.setAttributeValue(value);
+ match.setAttributeDesignator(designator);
+
+ return match;
+ }
+
+}
diff --git a/POLICY-SDK-APP/src/test/java/org/onap/policy/controller/DashboardControllerTest.java b/POLICY-SDK-APP/src/test/java/org/onap/policy/controller/DashboardControllerTest.java
index f2ecea504..413849cd3 100644
--- a/POLICY-SDK-APP/src/test/java/org/onap/policy/controller/DashboardControllerTest.java
+++ b/POLICY-SDK-APP/src/test/java/org/onap/policy/controller/DashboardControllerTest.java
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* POLICY-SDK-APP
* ================================================================================
- * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2018-2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Modifications Copyright (C) 2019 Samsung
* ================================================================================
@@ -19,15 +19,19 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.policy.controller;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.mockito.Mockito.mock;
+
import java.io.UnsupportedEncodingException;
import java.nio.file.Path;
import java.nio.file.Paths;
+
import javax.servlet.http.HttpServletRequest;
+
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mockito;
@@ -50,6 +54,11 @@ public class DashboardControllerTest {
private Path repo;
StdEngine engine = null;
+ /**
+ * setUp.
+ *
+ * @throws Exception should not get one
+ */
@Before
public void setUp() throws Exception {
logger.info("setUp: Entering");
@@ -84,8 +93,8 @@ public class DashboardControllerTest {
public void testGetPAPStatusData() {
try {
controller.getPAPStatusData(request, response);
- assertTrue(response.getContentAsString() != null
- && response.getContentAsString().contains("papTableDatas"));
+ assertTrue(
+ response.getContentAsString() != null && response.getContentAsString().contains("papTableDatas"));
} catch (UnsupportedEncodingException e) {
logger.error("Exception Occured" + e);
fail();
@@ -96,8 +105,8 @@ public class DashboardControllerTest {
public void testGetPDPStatusData() {
try {
controller.getPDPStatusData(request, response);
- assertTrue(response.getContentAsString() != null
- && response.getContentAsString().contains("pdpTableDatas"));
+ assertTrue(
+ response.getContentAsString() != null && response.getContentAsString().contains("pdpTableDatas"));
} catch (UnsupportedEncodingException e) {
logger.error("Exception Occured" + e);
fail();
diff --git a/POLICY-SDK-APP/src/test/java/org/onap/policy/controller/ExportAndImportDecisionBlackListEntriesTest.java b/POLICY-SDK-APP/src/test/java/org/onap/policy/controller/ExportAndImportDecisionBlackListEntriesTest.java
index e9f953b87..1c744278a 100644
--- a/POLICY-SDK-APP/src/test/java/org/onap/policy/controller/ExportAndImportDecisionBlackListEntriesTest.java
+++ b/POLICY-SDK-APP/src/test/java/org/onap/policy/controller/ExportAndImportDecisionBlackListEntriesTest.java
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP Policy Engine
* ================================================================================
- * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2018-2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -27,7 +27,9 @@ import static org.mockito.Mockito.mock;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.StringReader;
+
import javax.servlet.http.HttpServletRequest;
+
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.junit.Before;
diff --git a/POLICY-SDK-APP/src/test/java/org/onap/policy/controller/PDPControllerTest.java b/POLICY-SDK-APP/src/test/java/org/onap/policy/controller/PDPControllerTest.java
index 1c1c0fbbd..372090fdf 100644
--- a/POLICY-SDK-APP/src/test/java/org/onap/policy/controller/PDPControllerTest.java
+++ b/POLICY-SDK-APP/src/test/java/org/onap/policy/controller/PDPControllerTest.java
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP Policy Engine
* ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017, 2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Modifications Copyright (C) 2019 Samsung
* ================================================================================
@@ -19,15 +19,20 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.policy.controller;
+import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
+
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
+
import javax.servlet.http.HttpServletRequest;
+
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mockito;
@@ -46,6 +51,11 @@ public class PDPControllerTest extends Mockito {
private Set<StdPDPGroup> groups;
private static List<Object> rolesdata;
+ /**
+ * Before.
+ *
+ * @throws Exception Exception
+ */
@Before
public void setUp() throws Exception {
logger.info("setUp: Entering");
@@ -75,9 +85,9 @@ public class PDPControllerTest extends Mockito {
}
@Test
- public void testPDPGroupData() {
- HttpServletRequest request = mock(HttpServletRequest.class);
- MockHttpServletResponse response = new MockHttpServletResponse();
+ public void testPdpGroupData() {
+ final HttpServletRequest request = mock(HttpServletRequest.class);
+ final MockHttpServletResponse response = new MockHttpServletResponse();
PolicyController controller = mock(PolicyController.class);
PDPController pdpController = new PDPController();
pdpController.setJunit(true);;
@@ -86,10 +96,22 @@ public class PDPControllerTest extends Mockito {
when(controller.getRoles("Test")).thenReturn(rolesdata);
pdpController.getPDPGroupEntityData(request, response);
try {
- assertTrue(response.getContentAsString() != null
- && response.getContentAsString().contains("data"));
+ assertTrue(response.getContentAsString() != null && response.getContentAsString().contains("data"));
} catch (UnsupportedEncodingException e) {
logger.error("Exception Occured" + e);
}
}
+
+ @Test
+ public void testPdpData() {
+ PdpData data = new PdpData();
+ data.setId("id");
+ assertEquals("id", data.getId());
+ data.setDescription("foo");
+ assertEquals("foo", data.getDescription());
+ data.setJmxPort(0);
+ assertEquals(0, data.getJmxPort());
+ data.setName("name");
+ assertEquals("name", data.getName());
+ }
}
diff --git a/POLICY-SDK-APP/src/test/java/org/onap/policy/controller/PolicyControllerTest.java b/POLICY-SDK-APP/src/test/java/org/onap/policy/controller/PolicyControllerTest.java
index 65077ae01..554c40f90 100644
--- a/POLICY-SDK-APP/src/test/java/org/onap/policy/controller/PolicyControllerTest.java
+++ b/POLICY-SDK-APP/src/test/java/org/onap/policy/controller/PolicyControllerTest.java
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP Policy Engine
* ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017, 2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Modifications Copyright (C) 2019 Samsung
* ================================================================================
@@ -19,15 +19,19 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.policy.controller;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
+
import java.util.ArrayList;
import java.util.List;
+
import javax.script.SimpleBindings;
+
import org.apache.commons.io.IOUtils;
import org.junit.Before;
import org.junit.Test;
@@ -43,17 +47,20 @@ public class PolicyControllerTest {
private static Logger logger = FlexLogger.getLogger(PolicyControllerTest.class);
private static CommonClassDao commonClassDao;
+ /**
+ * setUp.
+ *
+ * @throws Exception Should not throw one
+ */
@Before
public void setUp() throws Exception {
logger.info("setUp: Entering");
commonClassDao = mock(CommonClassDao.class);
PolicyController.setCommonClassDao(commonClassDao);
- List<Object> data = new ArrayList<>();
String policyData = "";
try {
ClassLoader classLoader = getClass().getClassLoader();
- policyData = IOUtils
- .toString(classLoader.getResourceAsStream("Config_SampleTest1206.1.xml"));
+ policyData = IOUtils.toString(classLoader.getResourceAsStream("Config_SampleTest1206.1.xml"));
} catch (Exception e1) {
e1.printStackTrace();
}
@@ -61,6 +68,7 @@ public class PolicyControllerTest {
entity.setPolicyName("Config_SampleTest.1.xml");
entity.setPolicyData(policyData);
entity.setScope("com");
+ List<Object> data = new ArrayList<>();
data.add(entity);
when(commonClassDao.getDataByQuery(
diff --git a/POLICY-SDK-APP/src/test/java/org/onap/policy/controller/PolicyExportAndImportControllerTest.java b/POLICY-SDK-APP/src/test/java/org/onap/policy/controller/PolicyExportAndImportControllerTest.java
index 1e4e62da1..37145655c 100644
--- a/POLICY-SDK-APP/src/test/java/org/onap/policy/controller/PolicyExportAndImportControllerTest.java
+++ b/POLICY-SDK-APP/src/test/java/org/onap/policy/controller/PolicyExportAndImportControllerTest.java
@@ -2,14 +2,14 @@
* ============LICENSE_START=======================================================
* ONAP Policy Engine
* ================================================================================
- * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2018-2020 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -17,20 +17,22 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.policy.controller;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.when;
-import static org.mockito.Matchers.any;
-import static org.mockito.Matchers.eq;
+import com.mockrunner.mock.web.MockHttpServletRequest;
+import com.mockrunner.mock.web.MockHttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.Collections;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
-import org.json.JSONObject;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
@@ -41,12 +43,12 @@ import org.onap.policy.rest.jpa.UserInfo;
import org.onap.portalsdk.core.domain.User;
import org.onap.portalsdk.core.web.support.UserUtils;
import org.powermock.api.mockito.PowerMockito;
+import org.powermock.core.classloader.annotations.PowerMockIgnore;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
-import com.mockrunner.mock.web.MockHttpServletRequest;
-import com.mockrunner.mock.web.MockHttpServletResponse;
@RunWith(PowerMockRunner.class)
+@PowerMockIgnore({"com.sun.org.apache.xerces.*", "jdk.internal.reflect.*", "javax.xml.*", "org.xml.*", "org.w3c.*"})
public class PolicyExportAndImportControllerTest {
@Test
public void testSetAndGet() {
@@ -97,10 +99,9 @@ public class PolicyExportAndImportControllerTest {
ClassLoader classLoader = getClass().getClassLoader();
// Test negative case
- String file =
- new File(classLoader.getResource("Config_BRMS_Raw_TestBRMSRawPolicy.1.xml").getFile())
- .getAbsolutePath();
- JSONObject json = controller.importRepositoryFile(file, request);
+ String file = new File(classLoader.getResource("Config_BRMS_Raw_TestBRMSRawPolicy.1.xml").getFile())
+ .getAbsolutePath();
+ String json = controller.importRepositoryFile(file, request);
assertNull(json);
// Another negative case
diff --git a/POLICY-SDK-APP/src/test/java/org/onap/policy/controller/PolicyNotificationControllerTest.java b/POLICY-SDK-APP/src/test/java/org/onap/policy/controller/PolicyNotificationControllerTest.java
index 476eb6728..31b2dffb3 100644
--- a/POLICY-SDK-APP/src/test/java/org/onap/policy/controller/PolicyNotificationControllerTest.java
+++ b/POLICY-SDK-APP/src/test/java/org/onap/policy/controller/PolicyNotificationControllerTest.java
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP Policy Engine
* ================================================================================
- * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2018-2020 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Modifications Copyright (C) 2019 Samsung
* ================================================================================
@@ -19,15 +19,22 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.policy.controller;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
-import static org.mockito.Matchers.any;
+import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.when;
+
+import com.mockrunner.mock.web.MockHttpServletRequest;
+import com.mockrunner.mock.web.MockHttpServletResponse;
+
import java.io.IOException;
import java.util.Collections;
+
import javax.servlet.http.HttpServletResponse;
+
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
@@ -35,15 +42,15 @@ import org.onap.policy.rest.dao.CommonClassDao;
import org.onap.portalsdk.core.domain.User;
import org.onap.portalsdk.core.web.support.UserUtils;
import org.powermock.api.mockito.PowerMockito;
+import org.powermock.core.classloader.annotations.PowerMockIgnore;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import org.springframework.web.servlet.ModelAndView;
-import com.mockrunner.mock.web.MockHttpServletRequest;
-import com.mockrunner.mock.web.MockHttpServletResponse;
@RunWith(PowerMockRunner.class)
+@PowerMockIgnore({"com.sun.org.apache.xerces.*", "jdk.internal.reflect.*", "javax.xml.*", "org.xml.*", "org.w3c.*"})
+@PrepareForTest({UserUtils.class})
public class PolicyNotificationControllerTest {
- @PrepareForTest({UserUtils.class})
@Test
public void testWatch() throws IOException {
// Mock user utilities
@@ -60,16 +67,14 @@ public class PolicyNotificationControllerTest {
PolicyNotificationController controller = new PolicyNotificationController();
controller.commonClassDao = dao;
MockHttpServletRequest request = new MockHttpServletRequest();
- request.setBodyContent(
- "{\n\"watchData\": {\"name\": \"testVal\",\"path\": \"testPath\"\n}}\n");
+ request.setBodyContent("{\n\"watchData\": {\"name\": \"testVal\",\"path\": \"testPath\"\n}}\n");
MockHttpServletResponse response = new MockHttpServletResponse();
ModelAndView model = controller.watchPolicy(request, response);
assertNull(model);
assertEquals(response.getStatusCode(), HttpServletResponse.SC_OK);
// Negative test watch
- request.setBodyContent(
- "{\n\"watchData\": {\"name\": \"testVal\",\"nopath\": \"testPath\"\n}}\n");
+ request.setBodyContent("{\n\"watchData\": {\"name\": \"testVal\",\"nopath\": \"testPath\"\n}}\n");
response = new MockHttpServletResponse();
model = controller.watchPolicy(request, response);
assertNull(model);
diff --git a/POLICY-SDK-APP/src/test/java/org/onap/policy/controller/PolicyRolesControllerTest.java b/POLICY-SDK-APP/src/test/java/org/onap/policy/controller/PolicyRolesControllerTest.java
index d665aae5e..e24525619 100644
--- a/POLICY-SDK-APP/src/test/java/org/onap/policy/controller/PolicyRolesControllerTest.java
+++ b/POLICY-SDK-APP/src/test/java/org/onap/policy/controller/PolicyRolesControllerTest.java
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* POLICY-SDK-APP
* ================================================================================
- * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2018-2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Modifications Copyright (C) 2019 Samsung
* ================================================================================
@@ -19,17 +19,21 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.policy.controller;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
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 javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
+
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mockito;
@@ -47,6 +51,11 @@ public class PolicyRolesControllerTest {
private PolicyRolesController controller = null;
private static CommonClassDao commonClassDao;
+ /**
+ * Before.
+ *
+ * @throws Exception exception
+ */
@Before
public void setUp() throws Exception {
logger.info("setUp: Entering");
@@ -59,8 +68,7 @@ public class PolicyRolesControllerTest {
HttpSession mockSession = mock(HttpSession.class);
User user = new User();
user.setOrgUserId("Test");
- Mockito.when(mockSession.getAttribute(SystemProperties.getProperty("user_attribute_name")))
- .thenReturn(user);
+ Mockito.when(mockSession.getAttribute(SystemProperties.getProperty("user_attribute_name"))).thenReturn(user);
Mockito.when(request.getSession(false)).thenReturn(mockSession);
logger.info("setUp: exit");
@@ -70,8 +78,7 @@ public class PolicyRolesControllerTest {
public void testGetPolicyRolesEntityData() {
try {
controller.getPolicyRolesEntityData(request, response);
- assertTrue(response.getContentAsString() != null
- && response.getContentAsString().contains("rolesDatas"));
+ assertTrue(response.getContentAsString() != null && response.getContentAsString().contains("rolesDatas"));
} catch (UnsupportedEncodingException e) {
logger.error("Exception Occured" + e);
fail();
@@ -82,8 +89,7 @@ public class PolicyRolesControllerTest {
public void testGetPolicyScopesEntityData() {
try {
controller.getPolicyScopesEntityData(request, response);
- assertTrue(response.getContentAsString() != null
- && response.getContentAsString().contains("scopeDatas"));
+ assertTrue(response.getContentAsString() != null && response.getContentAsString().contains("scopeDatas"));
} catch (UnsupportedEncodingException e) {
logger.error("Exception Occured" + e);
fail();
@@ -100,8 +106,7 @@ public class PolicyRolesControllerTest {
when(request.getReader()).thenReturn(br);
controller.SaveRolesEntityData(request, response);
logger.info("response.getContentAsString(): " + response.getContentAsString());
- assertTrue(response.getContentAsString() != null
- && response.getContentAsString().contains("rolesDatas"));
+ assertTrue(response.getContentAsString() != null && response.getContentAsString().contains("rolesDatas"));
} catch (Exception e) {
fail("Exception: " + e);
}
diff --git a/POLICY-SDK-APP/src/test/java/org/onap/policy/controller/PolicyValidationControllerTest.java b/POLICY-SDK-APP/src/test/java/org/onap/policy/controller/PolicyValidationControllerTest.java
index 2ad6d6a7e..56b2d1030 100644
--- a/POLICY-SDK-APP/src/test/java/org/onap/policy/controller/PolicyValidationControllerTest.java
+++ b/POLICY-SDK-APP/src/test/java/org/onap/policy/controller/PolicyValidationControllerTest.java
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP Policy Engine
* ================================================================================
- * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2018-2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Modifications Copyright (C) 2019 Samsung
* ================================================================================
@@ -19,16 +19,21 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.policy.controller;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
+
+import com.mockrunner.mock.web.MockHttpServletRequest;
+import com.mockrunner.mock.web.MockHttpServletResponse;
+
import java.io.IOException;
+
import javax.servlet.http.HttpServletResponse;
+
import org.junit.Test;
import org.springframework.web.servlet.ModelAndView;
-import com.mockrunner.mock.web.MockHttpServletRequest;
-import com.mockrunner.mock.web.MockHttpServletResponse;
public class PolicyValidationControllerTest {
@Test
diff --git a/POLICY-SDK-APP/src/test/java/org/onap/policy/daoImp/CommonClassDaoImplTest.java b/POLICY-SDK-APP/src/test/java/org/onap/policy/daoImp/CommonClassDaoImplTest.java
index e7212f109..2b1052044 100644
--- a/POLICY-SDK-APP/src/test/java/org/onap/policy/daoImp/CommonClassDaoImplTest.java
+++ b/POLICY-SDK-APP/src/test/java/org/onap/policy/daoImp/CommonClassDaoImplTest.java
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP Policy Engine
* ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017, 2019-2020 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Modifications Copyright (C) 2019 Samsung
* ================================================================================
@@ -24,8 +24,13 @@ package org.onap.policy.daoImp;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
+import static org.mockito.Mockito.doThrow;
+import static org.mockito.Mockito.when;
+
import java.io.File;
import java.util.ArrayList;
import java.util.Date;
@@ -34,10 +39,15 @@ import java.util.Properties;
import javax.script.SimpleBindings;
import org.apache.tomcat.dbcp.dbcp2.BasicDataSource;
import org.h2.tools.Server;
+import org.hibernate.Criteria;
+import org.hibernate.HibernateException;
+import org.hibernate.Session;
import org.hibernate.SessionFactory;
+import org.hibernate.Transaction;
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.conf.HibernateSession;
@@ -46,7 +56,7 @@ import org.onap.policy.rest.jpa.OnapName;
import org.onap.policy.rest.jpa.PolicyEntity;
import org.onap.policy.rest.jpa.PolicyRoles;
import org.onap.policy.rest.jpa.PolicyVersion;
-import org.onap.policy.rest.jpa.SystemLogDB;
+import org.onap.policy.rest.jpa.SystemLogDb;
import org.onap.policy.rest.jpa.UserInfo;
import org.onap.policy.rest.jpa.WatchPolicyNotificationTable;
import org.springframework.orm.hibernate4.LocalSessionFactoryBuilder;
@@ -61,6 +71,11 @@ public class CommonClassDaoImplTest {
Server server;
CommonClassDaoImpl commonClassDao;
+ /**
+ * setUp.
+ *
+ * @throws Exception Exception
+ */
@Before
public void setUp() throws Exception {
try {
@@ -87,13 +102,13 @@ public class CommonClassDaoImplTest {
CommonClassDaoImpl.setSessionfactory(sessionFactory);
PolicyController.setLogTableLimit("1");
HibernateSession.setSession(sessionFactory);
- SystemLogDB data1 = new SystemLogDB();
+ SystemLogDb data1 = new SystemLogDb();
data1.setDate(new Date());
data1.setLogtype("INFO");
data1.setRemote("Test");
data1.setSystem("Test");
data1.setType("Test");
- SystemLogDB data2 = new SystemLogDB();
+ SystemLogDb data2 = new SystemLogDb();
data2.setDate(new Date());
data2.setLogtype("error");
data2.setRemote("Test");
@@ -122,13 +137,13 @@ public class CommonClassDaoImplTest {
userinfo.setUserName("Test");
commonClassDao.save(userinfo);
OnapName onapName = new OnapName();
- onapName.setOnapName("Test");
+ onapName.setName("Test");
onapName.setUserCreatedBy(userinfo);
onapName.setUserModifiedBy(userinfo);
onapName.setModifiedDate(new Date());
commonClassDao.save(onapName);
- List<Object> list = commonClassDao.getData(OnapName.class);
+ List<?> list = commonClassDao.getData(OnapName.class);
assertTrue(list.size() == 1);
logger.debug(list.size());
logger.debug(list.get(0));
@@ -145,18 +160,17 @@ public class CommonClassDaoImplTest {
try {
// Add data
UserInfo userinfo = new UserInfo();
- String loginId_userName = "Test";
- userinfo.setUserLoginId(loginId_userName);
- userinfo.setUserName(loginId_userName);
+ String loginIdUserName = "Test";
+ userinfo.setUserLoginId(loginIdUserName);
+ userinfo.setUserName(loginIdUserName);
commonClassDao.save(userinfo);
- List<Object> dataCur =
- commonClassDao.getDataByQuery("from UserInfo", new SimpleBindings());
+ List<?> dataCur = commonClassDao.getDataByQuery("from UserInfo", new SimpleBindings());
assertEquals(1, dataCur.size());
UserInfo cur = (UserInfo) dataCur.get(0);
- assertEquals(loginId_userName, cur.getUserLoginId());
- assertEquals(loginId_userName, cur.getUserName());
+ assertEquals(loginIdUserName, cur.getUserLoginId());
+ assertEquals(loginIdUserName, cur.getUserName());
assertFalse(dataCur.isEmpty());
@@ -183,13 +197,12 @@ public class CommonClassDaoImplTest {
pe.setCreatedBy("Test");
commonClassDao.save(pe);
- List<Object> dataCur =
- commonClassDao.getDataByQuery("from PolicyEntity", new SimpleBindings());
+ List<?> dataCur = commonClassDao.getDataByQuery("from PolicyEntity", new SimpleBindings());
assertTrue(1 == dataCur.size());
assertTrue(dataCur.get(0) instanceof PolicyEntity);
assertEquals(name, ((PolicyEntity) dataCur.get(0)).getPolicyName());
- assertEquals(pe, ((PolicyEntity) dataCur.get(0)));
+ assertEquals(pe, (dataCur.get(0)));
} catch (Exception e) {
logger.debug("Exception Occured" + e);
@@ -225,10 +238,10 @@ public class CommonClassDaoImplTest {
String query = "From PolicyVersion where policy_name like :scope and id > 0";
SimpleBindings params = new SimpleBindings();
params.put("scope", scope);
- List<Object> dataCur = commonClassDao.getDataByQuery(query, params);
+ List<?> dataCur = commonClassDao.getDataByQuery(query, params);
assertTrue(1 == dataCur.size());
- assertEquals(pv, (PolicyVersion) dataCur.get(0));
+ assertEquals(pv, dataCur.get(0));
} catch (Exception e) {
logger.debug("Exception Occured" + e);
@@ -243,11 +256,11 @@ public class CommonClassDaoImplTest {
try {
// Add data
WatchPolicyNotificationTable watch = new WatchPolicyNotificationTable();
- String policyFileName = "banana";
watch.setLoginIds("Test");
watch.setPolicyName("bananaWatch");
commonClassDao.save(watch);
+ String policyFileName = "banana";
if (policyFileName.contains("/")) {
policyFileName = policyFileName.substring(0, policyFileName.indexOf("/"));
policyFileName = policyFileName.replace("/", File.separator);
@@ -262,12 +275,12 @@ public class CommonClassDaoImplTest {
String query = "from WatchPolicyNotificationTable where policyName like:policyFileName";
SimpleBindings params = new SimpleBindings();
params.put("policyFileName", policyFileName);
- List<Object> dataCur = commonClassDao.getDataByQuery(query, params);
+ List<?> dataCur = commonClassDao.getDataByQuery(query, params);
// Assertions
assertTrue(dataCur.size() == 1);
assertTrue(dataCur.get(0) instanceof WatchPolicyNotificationTable);
- assertEquals(watch, (WatchPolicyNotificationTable) dataCur.get(0));
+ assertEquals(watch, dataCur.get(0));
} catch (Exception e) {
logger.debug("Exception Occured" + e);
@@ -293,20 +306,19 @@ public class CommonClassDaoImplTest {
commonClassDao.save(pe);
String dbCheckName = "dummyScope:action";
- String[] splitDBCheckName = dbCheckName.split(":");
// Current Implementation
- String query =
- "FROM PolicyEntity where policyName like :splitDBCheckName1 and scope = :splitDBCheckName0";
+ String query = "FROM PolicyEntity where policyName like :splitDBCheckName1 and scope = :splitDBCheckName0";
SimpleBindings params = new SimpleBindings();
- params.put("splitDBCheckName1", splitDBCheckName[1] + "%");
- params.put("splitDBCheckName0", splitDBCheckName[0]);
- List<Object> dataCur = commonClassDao.getDataByQuery(query, params);
+ String[] splitDbCheckName = dbCheckName.split(":");
+ params.put("splitDBCheckName1", splitDbCheckName[1] + "%");
+ params.put("splitDBCheckName0", splitDbCheckName[0]);
+ List<?> dataCur = commonClassDao.getDataByQuery(query, params);
// Assertions
assertTrue(dataCur.size() == 1);
assertTrue(dataCur.get(0) instanceof PolicyEntity);
- assertEquals(pe, (PolicyEntity) dataCur.get(0));
+ assertEquals(pe, dataCur.get(0));
} catch (Exception e) {
logger.debug("Exception Occured" + e);
@@ -328,17 +340,16 @@ public class CommonClassDaoImplTest {
commonClassDao.save(watch);
// Current Implementation
- String query =
- "from WatchPolicyNotificationTable where POLICYNAME = :finalName and LOGINIDS = :userId";
+ String query = "from WatchPolicyNotificationTable where POLICYNAME = :finalName and LOGINIDS = :userId";
SimpleBindings params = new SimpleBindings();
params.put("finalName", finalName);
params.put("userId", userId);
- List<Object> dataCur = commonClassDao.getDataByQuery(query, params);
+ List<?> dataCur = commonClassDao.getDataByQuery(query, params);
// Assertions
assertTrue(dataCur.size() == 1);
assertTrue(dataCur.get(0) instanceof WatchPolicyNotificationTable);
- assertEquals(watch, (WatchPolicyNotificationTable) dataCur.get(0));
+ assertEquals(watch, dataCur.get(0));
} catch (Exception e) {
logger.debug("Exception Occured" + e);
@@ -371,20 +382,19 @@ public class CommonClassDaoImplTest {
String finalName = "banana' OR '1'='1";
// Current Implementation
- String query =
- "from WatchPolicyNotificationTable where POLICYNAME = :finalName and LOGINIDS = :userId";
+ String query = "from WatchPolicyNotificationTable where POLICYNAME = :finalName and LOGINIDS = :userId";
SimpleBindings params = new SimpleBindings();
params.put("finalName", finalName);
params.put("userId", userId);
- List<Object> dataCur = commonClassDao.getDataByQuery(query, params);
+ List<?> dataCur = commonClassDao.getDataByQuery(query, params);
// Assertions
assertTrue(dataCur.size() <= 1);
if (dataCur.size() >= 1) {
assertTrue(dataCur.get(0) instanceof WatchPolicyNotificationTable);
- assertFalse(watch.equals((WatchPolicyNotificationTable) dataCur.get(0)));
- assertFalse(watch.equals((WatchPolicyNotificationTable) dataCur.get(0)));
+ assertFalse(watch.equals(dataCur.get(0)));
+ assertFalse(watch.equals(dataCur.get(0)));
}
} catch (Exception e) {
logger.debug("Exception Occured" + e);
@@ -399,19 +409,17 @@ public class CommonClassDaoImplTest {
userInfo.setUserLoginId("TestID");
userInfo.setUserName("Test");
commonClassDao.save(userInfo);
- List<Object> data = commonClassDao.getDataById(UserInfo.class, "userLoginId:userName",
- "TestID:Test");
+ List<?> data = commonClassDao.getDataById(UserInfo.class, "userLoginId:userName", "TestID:Test");
assertTrue(data.size() == 1);
UserInfo userInfoUpdate = (UserInfo) data.get(0);
userInfoUpdate.setUserName("Test1");
commonClassDao.update(userInfoUpdate);
List<String> data1 = commonClassDao.getDataByColumn(UserInfo.class, "userLoginId");
assertTrue(data1.size() == 1);
- UserInfo data2 = (UserInfo) commonClassDao.getEntityItem(UserInfo.class,
- "userLoginId:userName", "TestID:Test1");
+ UserInfo data2 =
+ (UserInfo) commonClassDao.getEntityItem(UserInfo.class, "userLoginId:userName", "TestID:Test1");
assertTrue("TestID".equals(data2.getUserLoginId()));
- List<Object> data3 = commonClassDao.checkDuplicateEntry("TestID:Test1",
- "userLoginId:userName", UserInfo.class);
+ List<?> data3 = commonClassDao.checkDuplicateEntry("TestID:Test1", "userLoginId:userName", UserInfo.class);
assertTrue(data3.size() == 1);
PolicyRoles roles = new PolicyRoles();
roles.setRole("admin");
@@ -422,8 +430,8 @@ public class CommonClassDaoImplTest {
assertTrue(roles1.size() == 1);
List<String> multipleData = new ArrayList<>();
multipleData.add("TestID:Test1");
- List<Object> data4 = commonClassDao.getMultipleDataOnAddingConjunction(UserInfo.class,
- "userLoginId:userName", multipleData);
+ List<?> data4 = commonClassDao.getMultipleDataOnAddingConjunction(UserInfo.class, "userLoginId:userName",
+ multipleData);
assertTrue(data4.size() == 1);
commonClassDao.delete(data2);
} catch (Exception e) {
@@ -454,6 +462,70 @@ public class CommonClassDaoImplTest {
}
}
+ @SuppressWarnings("unchecked")
+ @Test
+ public void testExceptions() throws HibernateException {
+ SessionFactory sfMock = Mockito.mock(SessionFactory.class);
+ Session mockSession = Mockito.mock(Session.class);
+ Criteria crMock = Mockito.mock(Criteria.class);
+ Transaction mockTransaction = Mockito.mock(Transaction.class);
+
+ CommonClassDaoImpl.setSessionfactory(sfMock);
+
+ when(sfMock.openSession()).thenReturn(mockSession);
+ when(mockSession.createCriteria(OnapName.class)).thenReturn(crMock);
+
+ when(crMock.list()).thenThrow(HibernateException.class);
+ when(mockSession.close()).thenThrow(HibernateException.class);
+
+ when(mockSession.beginTransaction()).thenReturn(mockTransaction);
+ doThrow(HibernateException.class).when(mockTransaction).commit();
+
+ List<?> dataList = commonClassDao.getData(OnapName.class);
+ assertNull(dataList);
+
+ List<?> dataByIdList = commonClassDao.getDataById(UserInfo.class, "userLoginId:userName", "TestID:Test");
+ assertNull(dataByIdList);
+
+ commonClassDao.save(null);
+ commonClassDao.delete(null);
+ commonClassDao.update(null);
+
+ List<?> dupEntryList =
+ commonClassDao.checkDuplicateEntry("TestID:Test", "userLoginId:userName", UserInfo.class);
+ assertNull(dupEntryList);
+
+ List<PolicyRoles> userRoles = commonClassDao.getUserRoles();
+ assertNull(userRoles);
+
+ Object entityItem = commonClassDao.getEntityItem(UserInfo.class, "testColName", "testKey");
+ assertNull(entityItem);
+
+ commonClassDao.updateQuery("testQueryString");
+
+ List<String> dataByColumn = commonClassDao.getDataByColumn(UserInfo.class, "testColName");
+ assertNull(dataByColumn);
+
+ List<?> entityData = commonClassDao.getMultipleDataOnAddingConjunction(UserInfo.class, "", null);
+ assertNull(entityData);
+ }
+
+ @Test
+ public void testCheckExistingGroupListforUpdate() {
+ Object retObj = commonClassDao.checkExistingGroupListforUpdate("testString1", "testString2");
+ assertNotNull(retObj);
+ assertTrue(retObj instanceof List);
+ List<?> retList = (List<?>) retObj;
+ assertTrue(retList.isEmpty());
+ }
+
+ @Test
+ public void testEmptyMethods() {
+ commonClassDao.deleteAll();
+ commonClassDao.updateClAlarms("TestString1", "TestString2");
+ commonClassDao.updateClYaml("TestString1", "TestString2");
+ }
+
@After
public void deleteDB() {
sessionFactory.close();
diff --git a/POLICY-SDK-APP/src/test/java/org/onap/policy/daoImp/SystemLogDbDaoImplTest.java b/POLICY-SDK-APP/src/test/java/org/onap/policy/daoImp/SystemLogDbDaoImplTest.java
new file mode 100644
index 000000000..44f034c20
--- /dev/null
+++ b/POLICY-SDK-APP/src/test/java/org/onap/policy/daoImp/SystemLogDbDaoImplTest.java
@@ -0,0 +1,77 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP Policy Engine
+ * ================================================================================
+ * Copyright (C) 2019-2020 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 static org.junit.Assert.assertNull;
+import static org.mockito.Mockito.doThrow;
+import static org.mockito.Mockito.when;
+
+import java.util.List;
+
+import org.hibernate.HibernateException;
+import org.hibernate.Session;
+import org.hibernate.SessionFactory;
+import org.hibernate.Transaction;
+import org.junit.AfterClass;
+import org.junit.BeforeClass;
+import org.junit.Test;
+import org.mockito.Mockito;
+import org.onap.policy.conf.HibernateSession;
+import org.onap.policy.controller.PolicyController;
+import org.onap.policy.rest.jpa.SystemLogDb;
+
+public class SystemLogDbDaoImplTest {
+ private static Session mockSession = Mockito.mock(Session.class);
+ private static SessionFactory sfMock = Mockito.mock(SessionFactory.class);
+ private static Transaction mockTransaction = Mockito.mock(Transaction.class);
+ private SystemLogDbDaoImpl sysLogImpl = new SystemLogDbDaoImpl();
+
+ @SuppressWarnings("unchecked")
+ @BeforeClass
+ public static void setup() {
+ HibernateSession.setSession(sfMock);
+
+ when(sfMock.openSession()).thenReturn(mockSession);
+ when(mockSession.beginTransaction()).thenReturn(mockTransaction);
+
+ doThrow(HibernateException.class).when(mockTransaction).commit();
+ when(mockSession.close()).thenThrow(HibernateException.class);
+
+ PolicyController.setjUnit(true);
+ }
+
+ @Test
+ public void testGettingLoggingData() {
+ List<SystemLogDb> loggingData = sysLogImpl.getLoggingData();
+ assertNull(loggingData);
+ }
+
+ @Test
+ public void testGetSystemAlertData() {
+ List<SystemLogDb> systemAlertData = sysLogImpl.getSystemAlertData();
+ assertNull(systemAlertData);
+ }
+
+ @AfterClass
+ public static void resetjUnit() {
+ PolicyController.setjUnit(false);
+ }
+}
diff --git a/POLICY-SDK-APP/src/test/java/org/onap/policy/model/PDPGroupContainerTest.java b/POLICY-SDK-APP/src/test/java/org/onap/policy/model/PDPGroupContainerTest.java
index 5117a05da..5204fc414 100644
--- a/POLICY-SDK-APP/src/test/java/org/onap/policy/model/PDPGroupContainerTest.java
+++ b/POLICY-SDK-APP/src/test/java/org/onap/policy/model/PDPGroupContainerTest.java
@@ -2,10 +2,8 @@
* ============LICENSE_START=======================================================
* ONAP Policy Engine
* ================================================================================
- * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Modifications Copyright (C) 2019 Samsung
- * ================================================================================
+ * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
+ ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
@@ -23,16 +21,27 @@
package org.onap.policy.model;
import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertTrue;
+import static org.mockito.Mockito.doThrow;
+import static org.mockito.Mockito.when;
+
+import com.att.research.xacml.api.pap.PAPException;
+import java.awt.Checkbox;
+import java.util.Set;
import org.junit.Test;
import org.mockito.Mockito;
import org.onap.policy.rest.util.PolicyContainer.ItemSetChangeListener;
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;
public class PDPGroupContainerTest {
+ private OnapPDPGroup group = Mockito.mock(OnapPDPGroup.class);
+ private OnapPDPGroup newGroup = Mockito.mock(OnapPDPGroup.class);
+ private OnapPDP pdp = Mockito.mock(OnapPDP.class);
private PAPPolicyEngine engine = Mockito.mock(PAPPolicyEngine.class);
private PDPGroupContainer container = new PDPGroupContainer(engine);
@@ -44,13 +53,11 @@ public class PDPGroupContainerTest {
container.refreshGroups();
assertEquals(container.getGroups().size(), 0);
- OnapPDPGroup group = Mockito.mock(OnapPDPGroup.class);
container.makeDefault(group);
- OnapPDPGroup newGroup = Mockito.mock(OnapPDPGroup.class);
container.removeGroup(group, newGroup);
- OnapPDP pdp = Mockito.mock(OnapPDP.class);
container.updatePDP(pdp);
container.updateGroup(group);
+ container.updateGroup(group, "testUserName");
assertNull(container.getContainerPropertyIds());
assertEquals(container.getItemIds().size(), 0);
assertEquals(container.getType(itemId), null);
@@ -103,7 +110,7 @@ public class PDPGroupContainerTest {
}
@Test(expected = IndexOutOfBoundsException.class)
- public void testGetIdByIndex() {
+ public void testGetIdByIndexException() {
container.getIdByIndex(0);
}
@@ -113,7 +120,145 @@ public class PDPGroupContainerTest {
}
@Test(expected = IllegalArgumentException.class)
- public void testGetItemIds() {
+ public void testGetItemIdsException() {
container.getItemIds(0, 1);
}
+
+ @Test
+ public void testGetType() {
+ assertEquals(Boolean.class, container.getType("Default"));
+ assertEquals(Checkbox.class, container.getType("Selected"));
+ assertEquals(Set.class, container.getType("PDPs"));
+ assertEquals(Set.class, container.getType("Policies"));
+ assertEquals(Set.class, container.getType("PIP Configurations"));
+ assertEquals(String.class, container.getType("Id"));
+ assertEquals(String.class, container.getType("Name"));
+ assertEquals(String.class, container.getType("Description"));
+ assertEquals(String.class, container.getType("Status"));
+ }
+
+ @Test
+ public void testContainerPAPExceptions() throws PAPException {
+ doThrow(PAPException.class).when(engine).getOnapPDPGroups();
+ container.refreshGroups();
+
+ doThrow(PAPException.class).when(engine).setDefaultGroup(group);
+ container.makeDefault(group);
+
+ doThrow(PAPException.class).when(engine).updatePDP(pdp);
+ container.updatePDP(pdp);
+
+ doThrow(PAPException.class).when(engine).updateGroup(group);
+ container.updateGroup(group);
+
+ doThrow(PAPException.class).when(engine).updateGroup(group, "testUserName");
+ container.updateGroup(group, "testUserName");
+
+ doThrow(PAPException.class).when(engine).movePDP(pdp, group);
+ container.movePDP(pdp, group);
+ }
+
+ @Test(expected = PAPException.class)
+ public void testContainerRemoveGroup() throws PAPException {
+ doThrow(PAPException.class).when(engine).removeGroup(group, newGroup);
+ container.removeGroup(group, newGroup);
+ }
+
+ @Test(expected = PAPException.class)
+ public void testContainerRemovePDP() throws PAPException {
+ doThrow(PAPException.class).when(engine).removePDP(pdp);
+ container.removePDP(pdp, group);
+ }
+
+ @Test(expected = UnsupportedOperationException.class)
+ public void testRemoveDefaultGroup() throws PAPException {
+ when(group.isDefaultGroup()).thenReturn(true);
+ container.removeGroup(group, newGroup);
+ }
+
+ @Test
+ public void testGetItemIds() {
+ assertNotNull(container.getItemIds(0, 0));
+ }
+
+ @Test
+ public void testContainsId() {
+ assertFalse(container.containsId(group));
+ }
+
+ @Test
+ public void testGroupMethods() {
+ container.groups.add(group);
+
+ Object retObj = container.getIdByIndex(0);
+ assertTrue(retObj instanceof OnapPDPGroup);
+ assertNotNull(retObj);
+
+ Object retFirstItemId = container.firstItemId();
+ assertTrue(retFirstItemId instanceof OnapPDPGroup);
+ assertNotNull(retFirstItemId);
+
+ Object retLastItemId = container.lastItemId();
+ assertTrue(retLastItemId instanceof OnapPDPGroup);
+ assertNotNull(retLastItemId);
+
+ assertTrue(container.isFirstId(group));
+
+ assertTrue(container.isLastId(group));
+ }
+
+ @Test
+ public void testNextItemId() {
+ OnapPDPGroup groupNotInList = Mockito.mock(OnapPDPGroup.class);
+ Object retObj = null;
+
+ container.groups.add(group);
+ container.groups.add(newGroup);
+
+ assertNull(container.nextItemId(groupNotInList));
+ assertNull(container.nextItemId(newGroup));
+
+ retObj = container.nextItemId(group);
+ assertNotNull(retObj);
+ assertTrue(retObj instanceof OnapPDPGroup);
+ }
+
+ @Test
+ public void testPrevItemId() {
+ OnapPDPGroup groupNotInList = Mockito.mock(OnapPDPGroup.class);
+ Object retObj = null;
+
+ container.groups.add(group);
+ container.groups.add(newGroup);
+
+ assertNull(container.prevItemId(groupNotInList));
+ assertNull(container.prevItemId(group));
+
+ retObj = container.prevItemId(newGroup);
+ assertNotNull(retObj);
+ assertTrue(retObj instanceof OnapPDPGroup);
+ }
+
+ @Test
+ public void testRemoveNullItem() {
+ OnapPDPGroup nullGroup = null;
+ assertFalse(container.removeItem(nullGroup));
+ }
+
+ @Test(expected = UnsupportedOperationException.class)
+ public void testRemoveDefaultItem() {
+ when(group.getId()).thenReturn("Default");
+ container.removeItem(group);
+ }
+
+ @SuppressWarnings("unchecked")
+ @Test
+ public void testRemoveItem() throws PAPException {
+ assertTrue(container.removeItem(group));
+
+ PAPPolicyEngine mockPAPPolicyEngine = Mockito.mock(PAPPolicyEngine.class);
+ PDPGroupContainer groupContainer = new PDPGroupContainer(mockPAPPolicyEngine);
+ when(mockPAPPolicyEngine.getDefaultGroup()).thenThrow(PAPException.class);
+ assertFalse(groupContainer.removeItem(group));
+ }
}
diff --git a/POLICY-SDK-APP/src/test/java/org/onap/policy/model/RolesTest.java b/POLICY-SDK-APP/src/test/java/org/onap/policy/model/RolesTest.java
new file mode 100644
index 000000000..745579af9
--- /dev/null
+++ b/POLICY-SDK-APP/src/test/java/org/onap/policy/model/RolesTest.java
@@ -0,0 +1,38 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP Policy Engine
+ * ================================================================================
+ * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 com.openpojo.reflection.filters.FilterPackageInfo;
+import com.openpojo.validation.Validator;
+import com.openpojo.validation.ValidatorBuilder;
+import com.openpojo.validation.test.impl.GetterTester;
+import com.openpojo.validation.test.impl.SetterTester;
+
+import org.junit.Test;
+
+public class RolesTest {
+
+ @Test
+ public void testRolesSettersAndGetters() {
+ final Validator validator = ValidatorBuilder.create().with(new SetterTester()).with(new GetterTester()).build();
+ validator.validate(RolesTest.class.getPackage().getName(), new FilterPackageInfo());
+ }
+}
diff --git a/POLICY-SDK-APP/src/test/resources/logback.xml b/POLICY-SDK-APP/src/test/resources/logback.xml
index fc73b6af2..ea9a7b491 100644
--- a/POLICY-SDK-APP/src/test/resources/logback.xml
+++ b/POLICY-SDK-APP/src/test/resources/logback.xml
@@ -2,14 +2,14 @@
============LICENSE_START=======================================================
ONAP-PAP-REST
================================================================================
- Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
================================================================================
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
-
+
http://www.apache.org/licenses/LICENSE-2.0
-
+
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -22,74 +22,74 @@
<!--<jmxConfigurator /> -->
<!-- directory path for all other type logs -->
<property name="logDir" value="logs" />
-
+
<!-- directory path for debugging type logs -->
<property name="debugDir" value="logs" />
-
- <!-- specify the component name
+
+ <!-- specify the component name
<ONAP-component-name>::= "MSO" | "DCAE" | "ASDC " | "AAI" |"Policy" | "SDNC" | "AC" -->
<property name="componentName" value="Policy"></property>
<property name="subComponentName" value="XACML-PAP-REST"></property>
-
+
<!-- log file names -->
<property name="errorLogName" value="error" />
<property name="metricsLogName" value="metrics" />
<property name="auditLogName" value="audit" />
<property name="debugLogName" value="debug" />
-
-
+
+
<!-- modified time stamp format -->
-
- <!-- A U D I T
- <property name="defaultAuditPattern" value="%X{BeginTimestamp}|%X{EndTimestamp}|%X{RequestId}|%X{ServiceInstanceId}|%thread|%X{ServerName}|%X{ServiceName}|%X{PartnerName}|%X{StatusCode}|%X{ResponseCode}|%X{ResponseDescription}|%X{InstanceUUID}|%.-5level|%X{AlertSeverity}|%X{ServerIPAddress}|%X{ElapsedTime}|%X{ServerFQDN}|%X{RemoteHost}|%X{ClassName}||%X{ProcessKey}|%X{TargetVirtualEntity}|%X{CustomField1}|%X{CustomField2}|%X{CustomField3}|%X{CustomField4}|%msg%n" />
+
+ <!-- A U D I T
+ <property name="defaultAuditPattern" value="%X{BeginTimestamp}|%X{EndTimestamp}|%X{RequestId}|%X{ServiceInstanceId}|%thread|%X{ServerName}|%X{ServiceName}|%X{PartnerName}|%X{StatusCode}|%X{ResponseCode}|%X{ResponseDescription}|%X{InstanceUUID}|%.-5level|%X{Severity}|%X{ServerIPAddress}|%X{ElapsedTime}|%X{ServerFQDN}|%X{RemoteHost}|%X{ClassName}||%X{ProcessKey}|%X{TargetVirtualEntity}|%X{CustomField1}|%X{CustomField2}|%X{CustomField3}|%X{CustomField4}|%msg%n" />
<property name="defaultAuditPattern" value="%X{BeginTimestamp}|%X{EndTimestamp}|%X{requestId}|%X{serviceInstanceId}|%t|%X{serverName}|%X{serviceName}|%X{PartnerName}|%X{StatusCode}|%X{ResponseCode}|%X{ResponseDescription}|%X{instanceUuid}|%p|%X{severity}|%X{serverIpAddress}|%X{ElapsedTime}|%X{server}|%X{clientIpAddress}|%c||%X{ProcessKey}|%X{TargetVirtualEntity}|%X{CustomField1}|%X{CustomField2}|%X{CustomField3}|%X{CustomField4}|%msg%n" />
-->
<property name="defaultAuditPattern" value="%X{TransactionBeginTimestamp}|%X{TransactionEndTimestamp}|%X{requestId}|%X{serviceInstanceId}|%t|%X{serverName}|%X{serviceName}|%X{partnerName}|%X{statusCode}|%X{ResponseCode}|%X{ResponseDescription}|%X{instanceUuid}|%p|%X{severity}|%X{serverIpAddress}|%X{TransactionElapsedTime}|%X{server}|%X{clientIpAddress}|%c||%X{ProcessKey}|%X{CustomField1}|%X{CustomField2}|%X{CustomField3}|%X{CustomField4}|%msg%n" />
-
-
-
- <!-- M E T R I C
- <property name="defaultMetricPattern" value="%X{BeginTimestamp}|%X{EndTimestamp}|%X{RequestId}|%X{ServiceInstanceId}|%thread|%X{ServerName}|%X{ServiceName}|%X{PartnerName}|%X{TargetEntity}|%X{TargetServiceName}|%X{StatusCode}|%X{ResponseCode}|%X{ResponseDescription}|%X{InstanceUUID}|%.-5level|%X{AlertSeverity}|%X{ServerIPAddress}|%X{ElapsedTime}|%X{ServerFQDN}|%X{RemoteHost}|%X{ClassName}||%X{ProcessKey}|%X{TargetVirtualEntity}|%X{CustomField1}|%X{CustomField2}|%X{CustomField3}|%X{CustomField4}|%msg%n" />
+
+
+
+ <!-- M E T R I C
+ <property name="defaultMetricPattern" value="%X{BeginTimestamp}|%X{EndTimestamp}|%X{RequestId}|%X{ServiceInstanceId}|%thread|%X{ServerName}|%X{ServiceName}|%X{PartnerName}|%X{TargetEntity}|%X{TargetServiceName}|%X{StatusCode}|%X{ResponseCode}|%X{ResponseDescription}|%X{InstanceUUID}|%.-5level|%X{Severity}|%X{ServerIPAddress}|%X{ElapsedTime}|%X{ServerFQDN}|%X{RemoteHost}|%X{ClassName}||%X{ProcessKey}|%X{TargetVirtualEntity}|%X{CustomField1}|%X{CustomField2}|%X{CustomField3}|%X{CustomField4}|%msg%n" />
-->
<property name="defaultMetricPattern" value="%X{MetricBeginTimestamp}|%X{MetricEndTimestamp}|%X{requestId}|%X{serviceInstanceId}|%t|%X{serverName}|%X{serviceName}|%X{partnerName}|%X{targetEntity}|%X{targetServiceName}|%X{statusCode}|%X{ResponseCode}|%X{ResponseDescription}|%X{InstanceUUID}|%p|%X{severity}|%X{serverIpAddress}|%X{MetricElapsedTime}|%X{server}|%X{clientIpAddress}|%c||%X{ProcessKey}|%X{TargetVirtualEntity}|%X{CustomField1}|%X{CustomField2}|%X{CustomField3}|%X{CustomField4}|%msg%n" />
-
-
-
-
+
+
+
+
<!-- E R R O R
<property name="defaultErrorPattern" value="%d{yyyy-MM-dd'T'HH:mm:ss.SSS+00:00, UTC}|%X{RequestId}|%thread|%X{ServiceName}|%X{PartnerName}|%X{TargetEntity}|%X{TargetServiceName}|%X{ErrorCategory}|%X{ErrorCode}|%X{ErrorDesciption}|%msg%n" />
-->
<property name="defaultErrorPattern" value="%d{yyyy-MM-dd'T'HH:mm:ss.SSS+00:00, UTC}|%X{requestId}|%t|%X{serviceName}|%X{PartnerName}|%X{TargetEntity}|%X{TargetServiceName}|%X{ErrorCategory}|%X{ErrorCode}|%X{ErrorDesciption}|%msg%n" />
-
-
-
+
+
+
<!-- D E B U G
- <property name="debugLoggerPatternOld" value="%d{MM/dd-HH:mm:ss.SSS}|%X{RequestId}|%X{ServiceInstanceId}|%thread|%X{ServiceName}|%X{InstanceUUID}|%.-5level|%X{AlertSeverity}|%X{ServerIPAddress}|%X{ServerFQDN}|%X{RemoteHost}|%X{Timer}|[%caller{3}]|%msg%n" />
- <property name="debugLoggerPattern" value="%X{BeginTimestamp}|%X{EndTimestamp}|%X{RequestId}|%X{ServiceInstanceId}|%thread|%X{ServerName}|%X{ServiceName}|%X{PartnerName}|%X{StatusCode}|%X{ResponseCode}|%X{ResponseDescription}|%X{ServiceName}|%X{InstanceUUID}|%.-5level|%X{AlertSeverity}|%X{ServerIPAddress}|%X{ElapsedTime}|%X{ServerFQDN}|%X{RemoteHost}|%X{ClassName}||%X{ProcessKey}|%X{CustomField1}|%X{CustomField2}|%X{CustomField3}|%X{CustomField4}|%msg%n" /> -->
+ <property name="debugLoggerPatternOld" value="%d{MM/dd-HH:mm:ss.SSS}|%X{RequestId}|%X{ServiceInstanceId}|%thread|%X{ServiceName}|%X{InstanceUUID}|%.-5level|%X{Severity}|%X{ServerIPAddress}|%X{ServerFQDN}|%X{RemoteHost}|%X{Timer}|[%caller{3}]|%msg%n" />
+ <property name="debugLoggerPattern" value="%X{BeginTimestamp}|%X{EndTimestamp}|%X{RequestId}|%X{ServiceInstanceId}|%thread|%X{ServerName}|%X{ServiceName}|%X{PartnerName}|%X{StatusCode}|%X{ResponseCode}|%X{ResponseDescription}|%X{ServiceName}|%X{InstanceUUID}|%.-5level|%X{Severity}|%X{ServerIPAddress}|%X{ElapsedTime}|%X{ServerFQDN}|%X{RemoteHost}|%X{ClassName}||%X{ProcessKey}|%X{CustomField1}|%X{CustomField2}|%X{CustomField3}|%X{CustomField4}|%msg%n" /> -->
-->
- <property name="debugLoggerPattern" value="%d{yyyy-MM-dd'T'HH:mm:ss.SSS+00:00, UTC}|%X{RequestId}|%msg%n" />
-
-
-
- <!-- D E F A U L T
- <property name="defaultPatternOld" value="%d{MM/dd-HH:mm:ss.SSS}|%logger|%X{RequestId}|%X{ServiceInstanceId}|%thread|%X{ServiceName}|%X{InstanceUUID}|%.-5level|%X{AlertSeverity}|%X{ServerIPAddress}|%X{ServerFQDN}|%X{RemoteHost}|%X{ClassName}|%X{Timer}|%msg%n" />
- <property name="defaultPattern" value="%X{BeginTimestamp}|%X{EndTimestamp}|%X{RequestId}|%X{ServiceInstanceId}|%thread|%X{ServerName}|%X{ServiceName}|%X{PartnerName}|%X{TargetEntity}|%X{TargetServiceName}|%X{StatusCode}|%X{ResponseCode}|%X{ResponseDescription}|%X{InstanceUUID}|%.-5level|%X{AlertSeverity}|%X{ServerIPAddress}|%X{ElapsedTime}|%X{ServerFQDN}|%X{RemoteHost}|%X{ClassName}||%X{ProcessKey}|%X{TargetVirtualEntity}|%X{CustomField1}|%X{CustomField2}|%X{CustomField3}|%X{CustomField4}|%msg%n" />
+ <property name="debugLoggerPattern" value="%d{yyyy-MM-dd'T'HH:mm:ss.SSS+00:00, UTC}|%X{RequestId}|%msg%n" />
+
+
+
+ <!-- D E F A U L T
+ <property name="defaultPatternOld" value="%d{MM/dd-HH:mm:ss.SSS}|%logger|%X{RequestId}|%X{ServiceInstanceId}|%thread|%X{ServiceName}|%X{InstanceUUID}|%.-5level|%X{Severity}|%X{ServerIPAddress}|%X{ServerFQDN}|%X{RemoteHost}|%X{ClassName}|%X{Timer}|%msg%n" />
+ <property name="defaultPattern" value="%X{BeginTimestamp}|%X{EndTimestamp}|%X{RequestId}|%X{ServiceInstanceId}|%thread|%X{ServerName}|%X{ServiceName}|%X{PartnerName}|%X{TargetEntity}|%X{TargetServiceName}|%X{StatusCode}|%X{ResponseCode}|%X{ResponseDescription}|%X{InstanceUUID}|%.-5level|%X{Severity}|%X{ServerIPAddress}|%X{ElapsedTime}|%X{ServerFQDN}|%X{RemoteHost}|%X{ClassName}||%X{ProcessKey}|%X{TargetVirtualEntity}|%X{CustomField1}|%X{CustomField2}|%X{CustomField3}|%X{CustomField4}|%msg%n" />
-->
<property name="defaultPattern" value="%d{yyyy-MM-dd'T'HH:mm:ss.SSSXXX, UTC}|%X{requestId}|%X{serviceInstanceId}|%t|%X{serverName}|%X{serviceName}|%X{instanceUuid}|%p|%X{severity}|%X{serverIpAddress}|%X{server}|%X{clientIpAddress}|%c||%msg%n" />
-
-
-
+
+
+
<!-- P A T H
<property name="logDirectory" value="${logDir}/${componentName}/${subComponentName}" />
<property name="debugLogDirectory" value="${debugDir}/${componentName}/${subComponentName}" />
- -->
+ -->
<property name="logDirectory" value="${catalina.base}/${logDir}/${componentName}/${subComponentName}" />
<property name="debugLogDirectory" value="${catalina.base}/${debugDir}/${componentName}/${subComponentName}" />
-
-
-
+
+
+
<!-- Example evaluator filter applied against console appender -->
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
@@ -101,15 +101,15 @@
<!-- EELF Appenders -->
<!-- ============================================================================ -->
- <!-- The EELFAppender is used to record events to the general application
+ <!-- The EELFAppender is used to record events to the general application
log -->
-
- <!-- EELF Audit Appender. This appender is used to record audit engine
- related logging events. The audit logger and appender are specializations
- of the EELF application root logger and appender. This can be used to segregate
- Policy engine events from other components, or it can be eliminated to record
+
+ <!-- EELF Audit Appender. This appender is used to record audit engine
+ related logging events. The audit logger and appender are specializations
+ of the EELF application root logger and appender. This can be used to segregate
+ Policy engine events from other components, or it can be eliminated to record
these events as part of the application root log. -->
-
+
<appender name="EELFAudit"
class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>${logDirectory}/${auditLogName}.log</file>
@@ -152,12 +152,12 @@
<maxFileSize>5MB</maxFileSize>
</triggeringPolicy>
<encoder>
- <!-- <pattern>"%d{HH:mm:ss.SSS} [%thread] %-5level %logger{1024} -
+ <!-- <pattern>"%d{HH:mm:ss.SSS} [%thread] %-5level %logger{1024} -
%msg%n"</pattern> -->
<pattern>${defaultMetricPattern}</pattern>
</encoder>
</appender>
-
+
<appender name="asyncEELFMetrics" class="ch.qos.logback.classic.AsyncAppender">
<queueSize>256</queueSize>
<appender-ref ref="EELFMetrics"/>
@@ -165,7 +165,7 @@
-
+
<appender name="EELFError"
class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>${logDirectory}/${errorLogName}.log</file>
@@ -187,14 +187,14 @@
<pattern>${defaultErrorPattern}</pattern>
</encoder>
</appender>
-
+
<appender name="asyncEELFError" class="ch.qos.logback.classic.AsyncAppender">
<queueSize>256</queueSize>
<appender-ref ref="EELFError"/>
</appender>
-
+
<appender name="EELFDebug"
class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>${debugLogDirectory}/${debugLogName}.log</file>
@@ -216,36 +216,36 @@
<pattern>${debugLoggerPattern}</pattern>
</encoder>
</appender>
-
+
<appender name="asyncEELFDebug" class="ch.qos.logback.classic.AsyncAppender">
<queueSize>256</queueSize>
<appender-ref ref="EELFDebug" />
<includeCallerData>true</includeCallerData>
</appender>
-
-
+
+
<!-- ============================================================================ -->
<!-- EELF loggers -->
<!-- ============================================================================ -->
-
+
<logger name="com.att.eelf.audit" level="info" additivity="false">
<appender-ref ref="asyncEELFAudit" />
</logger>
-
+
<logger name="com.att.eelf.metrics" level="info" additivity="false">
<appender-ref ref="asyncEELFMetrics" />
</logger>
-
+
<logger name="com.att.eelf.error" level="error" additivity="false">
<appender-ref ref="asyncEELFError" />
</logger>
-
+
<logger name="com.att.eelf.debug" level="info" additivity="false">
<appender-ref ref="asyncEELFDebug" />
</logger>
-
-
-
+
+
+
<root level="INFO">
<appender-ref ref="asyncEELFDebug" />
<appender-ref ref="asyncEELFError" />
diff --git a/POLICY-SDK-APP/src/test/resources/xacml.admin.properties b/POLICY-SDK-APP/src/test/resources/xacml.admin.properties
index 363ab621f..1147ce6eb 100644
--- a/POLICY-SDK-APP/src/test/resources/xacml.admin.properties
+++ b/POLICY-SDK-APP/src/test/resources/xacml.admin.properties
@@ -2,7 +2,7 @@
# ============LICENSE_START=======================================================
# ONAP Policy Engine
# ================================================================================
-# Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+# Copyright (C) 2017, 2019 AT&T Intellectual Property. All rights reserved.
# ================================================================================
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
@@ -111,9 +111,9 @@ xacml.max.priority.count=10
#
# 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
+# 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.
#
diff --git a/PolicyEngineAPI/pom.xml b/PolicyEngineAPI/pom.xml
index 1eecf1cf5..830acc786 100644
--- a/PolicyEngineAPI/pom.xml
+++ b/PolicyEngineAPI/pom.xml
@@ -3,14 +3,14 @@
============LICENSE_START=======================================================
ONAP Policy Engine
================================================================================
- Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ Copyright (C) 2017-2020 AT&T Intellectual Property. All rights reserved.
================================================================================
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
-
+
http://www.apache.org/licenses/LICENSE-2.0
-
+
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -24,14 +24,29 @@
<parent>
<groupId>org.onap.policy.engine</groupId>
<artifactId>PolicyEngineSuite</artifactId>
- <version>1.4.1-SNAPSHOT</version>
+ <version>1.6.4-SNAPSHOT</version>
</parent>
<artifactId>PolicyEngineAPI</artifactId>
<dependencies>
<dependency>
<groupId>org.glassfish</groupId>
<artifactId>javax.json</artifactId>
- <version>1.0.4</version>
+ <version>1.1.4</version>
+ </dependency>
+ <dependency>
+ <groupId>javax.xml.bind</groupId>
+ <artifactId>jaxb-api</artifactId>
+ <version>${version.javax.bind}</version>
+ </dependency>
+ <dependency>
+ <groupId>org.glassfish.jaxb</groupId>
+ <artifactId>jaxb-runtime</artifactId>
+ <version>2.3.2</version>
+ </dependency>
+ <dependency>
+ <groupId>javax.activation</groupId>
+ <artifactId>javax.activation-api</artifactId>
+ <version>1.2.0</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
@@ -79,15 +94,23 @@
</exclusions>
</dependency>
<dependency>
- <groupId>org.projectlombok</groupId>
- <artifactId>lombok</artifactId>
- <version>1.18.6</version>
- <scope>provided</scope>
- </dependency>
- <dependency>
<groupId>org.onap.policy.engine</groupId>
<artifactId>ONAP-XACML</artifactId>
<version>${project.version}</version>
+ <exclusions>
+ <exclusion>
+ <groupId>javax.xml.parsers</groupId>
+ <artifactId>jaxp-api</artifactId>
+ </exclusion>
+ <exclusion>
+ <groupId>xml-apis</groupId>
+ <artifactId>xml-apis</artifactId>
+ </exclusion>
+ <exclusion>
+ <groupId>javax.xml</groupId>
+ <artifactId>jaxp-api</artifactId>
+ </exclusion>
+ </exclusions>
</dependency>
</dependencies>
<build>
@@ -96,8 +119,7 @@
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
- <source>1.8</source>
- <target>1.8</target>
+ <release>${java.version}</release>
</configuration>
</plugin>
<plugin>
diff --git a/PolicyEngineAPI/src/main/java/org/onap/policy/api/ImportParameters.java b/PolicyEngineAPI/src/main/java/org/onap/policy/api/ImportParameters.java
index 51398f32d..8cf57e1a1 100644
--- a/PolicyEngineAPI/src/main/java/org/onap/policy/api/ImportParameters.java
+++ b/PolicyEngineAPI/src/main/java/org/onap/policy/api/ImportParameters.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -25,152 +25,153 @@ import java.util.UUID;
/**
* <code>ImportParameters</code> defines the Policy Engine Import Parameters
- * which are required to import a new Policy Service or Value.
- *
+ * which are required to import a new Policy Service or Value.
+ *
* @version 0.1
*/
public class ImportParameters {
- private String serviceName;
- private String description;
- private UUID requestID;
- private String filePath;
- private String version;
- private IMPORT_TYPE importType;
-
- public enum IMPORT_TYPE {
- MICROSERVICE,
- BRMSPARAM,
- OPTIMIZATION
- }
-
- /**
- * Sets Import Policy Parameters.
- *
- * @param serviceName the <code>String</code> format of the Service Name
- * @param description the <code>String</code> format of the i Description
- * @param requestID unique request ID which will be passed throughout the ONAP components to correlate logging messages.
- * @param filePath the <code>List</code> format of the file paths for the service files
- * @param importType the {@link IMPORT_TYPE} format of the Policy Service List
- * @param version the <code>String</code> format of the Policy Import Version
- * A different request ID should be passed for each request.
- */
- public void setImportParameters(String serviceName, String description, UUID requestID, String filePath, IMPORT_TYPE importType, String version){
-
- this.setServiceName(serviceName);
- this.setDescription(description);
- this.setRequestID(requestID);
- this.setFilePath(filePath);
- this.setServiceType(importType);
- this.setVersion(version);
-
- }
-
- /**
- * Gets the Policy Service of the Policy Service Import Parameters.
- *
- * @return serviceName the <code>String</code> format of the Policy Service Name
- */
- public String getServiceName() {
- return serviceName;
- }
-
- /**
- * Sets the serviceName of the Policy Service Parameters.
- *
- * @param serviceName the <code>String</code> format of the Policy Service Name
- */
- public void setServiceName(String serviceName) {
- this.serviceName = serviceName;
- }
-
- /**
- * Gets the Policy Import Description.
- *
- * @return description the <code>String</code> format of the Policy Import Description
- */
- public String getDescription() {
- return description;
- }
-
- /**
- * Sets the Description of the new Policy Import Description.
- *
- * @param description the <code>String</code> format of the Policy Import Description
- */
- public void setDescription(String description) {
- this.description = description;
- }
-
- /**
- * Gets the requestID of the Policy Parameters.
- *
- * @return unique request ID which will be passed throughout the ONAP components to correlate logging messages.
- */
- public UUID getRequestID() {
- return requestID;
- }
-
- /**
- * Sets the requestID of the Policy Parameters.
- *
- * @param requestID unique request ID which will be passed throughout the ONAP components to correlate logging messages.
- */
- public void setRequestID(UUID requestID) {
- this.requestID = requestID;
- }
-
- /**
- * Gets the List of File Paths of the new import.
- *
- * @return filePath the <code>List</code> format of the Policy Import File
- */
- public String getFilePath() {
- return filePath;
- }
-
- /**
- * Sets the policy Import File List of the new Policy Import.
- *
- * @param filePath the <code>List</code> format of the Policy Import File
- */
- public void setFilePath(String filePath) {
- this.filePath = filePath;
- }
-
- /**
- * Gets the Service Type of the new policy import.
- *
- * @return ImportType {@link IMPORT_TYPE} format of the Policy Service List
- */
- public IMPORT_TYPE getServiceType() {
- return importType;
- }
-
- /**
- * Sets the policy Service Type of the new Policy Service.
- *
- * @param enumImportType the <code>enumServiceType</code> format of the Policy Service List
- */
- public void setServiceType(IMPORT_TYPE enumImportType) {
- this.importType = enumImportType;
- }
-
- /**
- *
- * Gets the Import Version of the new policy import.
- *
- * @return version the <code>String</code> format of the Policy Import Version
- */
- public String getVersion() {
- return version;
- }
-
- /**
- * Sets the policy Import Version of the new Policy Import.
- *
- * @param version the <code>String</code> format of the Policy Import Version
- */
- public void setVersion(String version) {
- this.version = version;
- }
+
+ private String serviceName;
+ private String description;
+ private UUID requestID;
+ private String filePath;
+ private String version;
+ private IMPORT_TYPE importType;
+
+ public enum IMPORT_TYPE {
+ MICROSERVICE, BRMSPARAM, OPTIMIZATION
+ }
+
+ /**
+ * Sets Import Policy Parameters.
+ *
+ * @param serviceName the <code>String</code> format of the Service Name
+ * @param description the <code>String</code> format of the i Description
+ * @param requestID unique request ID which will be passed throughout the ONAP components to correlate logging
+ * messages.
+ * @param filePath the <code>List</code> format of the file paths for the service files
+ * @param importType the {@link IMPORT_TYPE} format of the Policy Service List
+ * @param version the <code>String</code> format of the Policy Import Version
+ * A different request ID should be passed for each request.
+ */
+ public void setImportParameters(String serviceName, String description, UUID requestID, String filePath,
+ IMPORT_TYPE importType, String version) {
+
+ this.setServiceName(serviceName);
+ this.setDescription(description);
+ this.setRequestID(requestID);
+ this.setFilePath(filePath);
+ this.setServiceType(importType);
+ this.setVersion(version);
+
+ }
+
+ /**
+ * Gets the Policy Service of the Policy Service Import Parameters.
+ *
+ * @return serviceName the <code>String</code> format of the Policy Service Name
+ */
+ public String getServiceName() {
+ return serviceName;
+ }
+
+ /**
+ * Sets the serviceName of the Policy Service Parameters.
+ *
+ * @param serviceName the <code>String</code> format of the Policy Service Name
+ */
+ public void setServiceName(String serviceName) {
+ this.serviceName = serviceName;
+ }
+
+ /**
+ * Gets the Policy Import Description.
+ *
+ * @return description the <code>String</code> format of the Policy Import Description
+ */
+ public String getDescription() {
+ return description;
+ }
+
+ /**
+ * Sets the Description of the new Policy Import Description.
+ *
+ * @param description the <code>String</code> format of the Policy Import Description
+ */
+ public void setDescription(String description) {
+ this.description = description;
+ }
+
+ /**
+ * Gets the requestID of the Policy Parameters.
+ *
+ * @return unique request ID which will be passed throughout the ONAP components to correlate logging messages.
+ */
+ public UUID getRequestID() {
+ return requestID;
+ }
+
+ /**
+ * Sets the requestID of the Policy Parameters.
+ *
+ * @param requestID unique request ID which will be passed throughout the ONAP components to correlate logging
+ * messages.
+ */
+ public void setRequestID(UUID requestID) {
+ this.requestID = requestID;
+ }
+
+ /**
+ * Gets the List of File Paths of the new import.
+ *
+ * @return filePath the <code>List</code> format of the Policy Import File
+ */
+ public String getFilePath() {
+ return filePath;
+ }
+
+ /**
+ * Sets the policy Import File List of the new Policy Import.
+ *
+ * @param filePath the <code>List</code> format of the Policy Import File
+ */
+ public void setFilePath(String filePath) {
+ this.filePath = filePath;
+ }
+
+ /**
+ * Gets the Service Type of the new policy import.
+ *
+ * @return ImportType {@link IMPORT_TYPE} format of the Policy Service List
+ */
+ public IMPORT_TYPE getServiceType() {
+ return importType;
+ }
+
+ /**
+ * Sets the policy Service Type of the new Policy Service.
+ *
+ * @param enumImportType the <code>enumServiceType</code> format of the Policy Service List
+ */
+ public void setServiceType(IMPORT_TYPE enumImportType) {
+ this.importType = enumImportType;
+ }
+
+ /**
+ * Gets the Import Version of the new policy import.
+ *
+ * @return version the <code>String</code> format of the Policy Import Version
+ */
+ public String getVersion() {
+ return version;
+ }
+
+ /**
+ * Sets the policy Import Version of the new Policy Import.
+ *
+ * @param version the <code>String</code> format of the Policy Import Version
+ */
+ public void setVersion(String version) {
+ this.version = version;
+ }
}
diff --git a/PolicyEngineAPI/src/main/resources/logback.xml b/PolicyEngineAPI/src/main/resources/logback.xml
index 88e062cd8..c3eec49b5 100644
--- a/PolicyEngineAPI/src/main/resources/logback.xml
+++ b/PolicyEngineAPI/src/main/resources/logback.xml
@@ -2,14 +2,14 @@
============LICENSE_START=======================================================
PolicyEngineAPI
================================================================================
- Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
================================================================================
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
-
+
http://www.apache.org/licenses/LICENSE-2.0
-
+
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -22,73 +22,73 @@
<!--<jmxConfigurator /> -->
<!-- directory path for all other type logs -->
<property name="logDir" value="${POLICY_LOGS}" />
-
+
<!-- directory path for debugging type logs -->
<property name="debugDir" value="${POLICY_LOGS}" />
-
- <!-- specify the component name
+
+ <!-- specify the component name
<ONAP-component-name>::= "MSO" | "DCAE" | "ASDC " | "AAI" |"Policy" | "SDNC" | "AC" -->
<property name="componentName" value="policy"></property>
<property name="subComponentName" value="policyapi"></property>
-
+
<!-- log file names -->
<property name="errorLogName" value="error" />
<property name="metricsLogName" value="metrics" />
<property name="auditLogName" value="audit" />
<property name="debugLogName" value="debug" />
-
-
+
+
<!-- modified time stamp format -->
-
- <!-- A U D I T
- <property name="defaultAuditPattern" value="%X{BeginTimestamp}|%X{EndTimestamp}|%X{RequestId}|%X{ServiceInstanceId}|%thread|%X{ServerName}|%X{ServiceName}|%X{PartnerName}|%X{StatusCode}|%X{ResponseCode}|%X{ResponseDescription}|%X{InstanceUUID}|%.-5level|%X{AlertSeverity}|%X{ServerIPAddress}|%X{ElapsedTime}|%X{ServerFQDN}|%X{RemoteHost}|%X{ClassName}||%X{ProcessKey}|%X{TargetVirtualEntity}|%X{CustomField1}|%X{CustomField2}|%X{CustomField3}|%X{CustomField4}|%msg%n" />
+
+ <!-- A U D I T
+ <property name="defaultAuditPattern" value="%X{BeginTimestamp}|%X{EndTimestamp}|%X{RequestId}|%X{ServiceInstanceId}|%thread|%X{ServerName}|%X{ServiceName}|%X{PartnerName}|%X{StatusCode}|%X{ResponseCode}|%X{ResponseDescription}|%X{InstanceUUID}|%.-5level|%X{Severity}|%X{ServerIPAddress}|%X{ElapsedTime}|%X{ServerFQDN}|%X{RemoteHost}|%X{ClassName}||%X{ProcessKey}|%X{TargetVirtualEntity}|%X{CustomField1}|%X{CustomField2}|%X{CustomField3}|%X{CustomField4}|%msg%n" />
<property name="defaultAuditPattern" value="%X{BeginTimestamp}|%X{EndTimestamp}|%X{requestId}|%X{serviceInstanceId}|%t|%X{serverName}|%X{serviceName}|%X{PartnerName}|%X{StatusCode}|%X{ResponseCode}|%X{ResponseDescription}|%X{instanceUuid}|%p|%X{severity}|%X{serverIpAddress}|%X{ElapsedTime}|%X{server}|%X{clientIpAddress}|%c||%X{ProcessKey}|%X{TargetVirtualEntity}|%X{CustomField1}|%X{CustomField2}|%X{CustomField3}|%X{CustomField4}|%msg%n" />
-->
<property name="defaultAuditPattern" value="%X{TransactionBeginTimestamp}|%X{TransactionEndTimestamp}|%X{requestId}|%X{serviceInstanceId}|%t|%X{serverName}|%X{serviceName}|%X{partnerName}|%X{statusCode}|%X{ResponseCode}|%X{ResponseDescription}|%X{instanceUuid}|%p|%X{severity}|%X{serverIpAddress}|%X{TransactionElapsedTime}|%X{server}|%X{clientIpAddress}|%c||%X{ProcessKey}|%X{CustomField1}|%X{CustomField2}|%X{CustomField3}|%X{CustomField4}|%msg%n" />
-
-
-
- <!-- M E T R I C
- <property name="defaultMetricPattern" value="%X{BeginTimestamp}|%X{EndTimestamp}|%X{RequestId}|%X{ServiceInstanceId}|%thread|%X{ServerName}|%X{ServiceName}|%X{PartnerName}|%X{TargetEntity}|%X{TargetServiceName}|%X{StatusCode}|%X{ResponseCode}|%X{ResponseDescription}|%X{InstanceUUID}|%.-5level|%X{AlertSeverity}|%X{ServerIPAddress}|%X{ElapsedTime}|%X{ServerFQDN}|%X{RemoteHost}|%X{ClassName}||%X{ProcessKey}|%X{TargetVirtualEntity}|%X{CustomField1}|%X{CustomField2}|%X{CustomField3}|%X{CustomField4}|%msg%n" />
+
+
+
+ <!-- M E T R I C
+ <property name="defaultMetricPattern" value="%X{BeginTimestamp}|%X{EndTimestamp}|%X{RequestId}|%X{ServiceInstanceId}|%thread|%X{ServerName}|%X{ServiceName}|%X{PartnerName}|%X{TargetEntity}|%X{TargetServiceName}|%X{StatusCode}|%X{ResponseCode}|%X{ResponseDescription}|%X{InstanceUUID}|%.-5level|%X{Severity}|%X{ServerIPAddress}|%X{ElapsedTime}|%X{ServerFQDN}|%X{RemoteHost}|%X{ClassName}||%X{ProcessKey}|%X{TargetVirtualEntity}|%X{CustomField1}|%X{CustomField2}|%X{CustomField3}|%X{CustomField4}|%msg%n" />
-->
<property name="defaultMetricPattern" value="%X{MetricBeginTimestamp}|%X{MetricEndTimestamp}|%X{requestId}|%X{serviceInstanceId}|%t|%X{serverName}|%X{serviceName}|%X{partnerName}|%X{targetEntity}|%X{targetServiceName}|%X{statusCode}|%X{ResponseCode}|%X{ResponseDescription}|%X{InstanceUUID}|%p|%X{severity}|%X{serverIpAddress}|%X{MetricElapsedTime}|%X{server}|%X{clientIpAddress}|%c||%X{ProcessKey}|%X{TargetVirtualEntity}|%X{CustomField1}|%X{CustomField2}|%X{CustomField3}|%X{CustomField4}|%msg%n" />
-
-
-
-
+
+
+
+
<!-- E R R O R
<property name="defaultErrorPattern" value="%d{yyyy-MM-dd'T'HH:mm:ss.SSS+00:00, UTC}|%X{RequestId}|%thread|%X{ServiceName}|%X{PartnerName}|%X{TargetEntity}|%X{TargetServiceName}|%X{ErrorCategory}|%X{ErrorCode}|%X{ErrorDesciption}|%msg%n" />
-->
<property name="defaultErrorPattern" value="%d{yyyy-MM-dd'T'HH:mm:ss.SSS+00:00, UTC}|%X{requestId}|%t|%X{serviceName}|%X{PartnerName}|%X{TargetEntity}|%X{TargetServiceName}|%X{ErrorCategory}|%X{ErrorCode}|%X{ErrorDesciption}|%msg%n" />
-
-
-
+
+
+
<!-- D E B U G
- <property name="debugLoggerPatternOld" value="%d{MM/dd-HH:mm:ss.SSS}|%X{RequestId}|%X{ServiceInstanceId}|%thread|%X{ServiceName}|%X{InstanceUUID}|%.-5level|%X{AlertSeverity}|%X{ServerIPAddress}|%X{ServerFQDN}|%X{RemoteHost}|%X{Timer}|[%caller{3}]|%msg%n" />
- <property name="debugLoggerPattern" value="%X{BeginTimestamp}|%X{EndTimestamp}|%X{RequestId}|%X{ServiceInstanceId}|%thread|%X{ServerName}|%X{ServiceName}|%X{PartnerName}|%X{StatusCode}|%X{ResponseCode}|%X{ResponseDescription}|%X{ServiceName}|%X{InstanceUUID}|%.-5level|%X{AlertSeverity}|%X{ServerIPAddress}|%X{ElapsedTime}|%X{ServerFQDN}|%X{RemoteHost}|%X{ClassName}||%X{ProcessKey}|%X{CustomField1}|%X{CustomField2}|%X{CustomField3}|%X{CustomField4}|%msg%n" /> -->
+ <property name="debugLoggerPatternOld" value="%d{MM/dd-HH:mm:ss.SSS}|%X{RequestId}|%X{ServiceInstanceId}|%thread|%X{ServiceName}|%X{InstanceUUID}|%.-5level|%X{Severity}|%X{ServerIPAddress}|%X{ServerFQDN}|%X{RemoteHost}|%X{Timer}|[%caller{3}]|%msg%n" />
+ <property name="debugLoggerPattern" value="%X{BeginTimestamp}|%X{EndTimestamp}|%X{RequestId}|%X{ServiceInstanceId}|%thread|%X{ServerName}|%X{ServiceName}|%X{PartnerName}|%X{StatusCode}|%X{ResponseCode}|%X{ResponseDescription}|%X{ServiceName}|%X{InstanceUUID}|%.-5level|%X{Severity}|%X{ServerIPAddress}|%X{ElapsedTime}|%X{ServerFQDN}|%X{RemoteHost}|%X{ClassName}||%X{ProcessKey}|%X{CustomField1}|%X{CustomField2}|%X{CustomField3}|%X{CustomField4}|%msg%n" /> -->
-->
- <property name="debugLoggerPattern" value="%d{yyyy-MM-dd'T'HH:mm:ss.SSS+00:00, UTC}|%X{RequestId}|%msg%n" />
-
-
-
- <!-- D E F A U L T
- <property name="defaultPatternOld" value="%d{MM/dd-HH:mm:ss.SSS}|%logger|%X{RequestId}|%X{ServiceInstanceId}|%thread|%X{ServiceName}|%X{InstanceUUID}|%.-5level|%X{AlertSeverity}|%X{ServerIPAddress}|%X{ServerFQDN}|%X{RemoteHost}|%X{ClassName}|%X{Timer}|%msg%n" />
- <property name="defaultPattern" value="%X{BeginTimestamp}|%X{EndTimestamp}|%X{RequestId}|%X{ServiceInstanceId}|%thread|%X{ServerName}|%X{ServiceName}|%X{PartnerName}|%X{TargetEntity}|%X{TargetServiceName}|%X{StatusCode}|%X{ResponseCode}|%X{ResponseDescription}|%X{InstanceUUID}|%.-5level|%X{AlertSeverity}|%X{ServerIPAddress}|%X{ElapsedTime}|%X{ServerFQDN}|%X{RemoteHost}|%X{ClassName}||%X{ProcessKey}|%X{TargetVirtualEntity}|%X{CustomField1}|%X{CustomField2}|%X{CustomField3}|%X{CustomField4}|%msg%n" />
+ <property name="debugLoggerPattern" value="%d{yyyy-MM-dd'T'HH:mm:ss.SSS+00:00, UTC}|%X{RequestId}|%msg%n" />
+
+
+
+ <!-- D E F A U L T
+ <property name="defaultPatternOld" value="%d{MM/dd-HH:mm:ss.SSS}|%logger|%X{RequestId}|%X{ServiceInstanceId}|%thread|%X{ServiceName}|%X{InstanceUUID}|%.-5level|%X{Severity}|%X{ServerIPAddress}|%X{ServerFQDN}|%X{RemoteHost}|%X{ClassName}|%X{Timer}|%msg%n" />
+ <property name="defaultPattern" value="%X{BeginTimestamp}|%X{EndTimestamp}|%X{RequestId}|%X{ServiceInstanceId}|%thread|%X{ServerName}|%X{ServiceName}|%X{PartnerName}|%X{TargetEntity}|%X{TargetServiceName}|%X{StatusCode}|%X{ResponseCode}|%X{ResponseDescription}|%X{InstanceUUID}|%.-5level|%X{Severity}|%X{ServerIPAddress}|%X{ElapsedTime}|%X{ServerFQDN}|%X{RemoteHost}|%X{ClassName}||%X{ProcessKey}|%X{TargetVirtualEntity}|%X{CustomField1}|%X{CustomField2}|%X{CustomField3}|%X{CustomField4}|%msg%n" />
-->
<property name="defaultPattern" value="%d{yyyy-MM-dd'T'HH:mm:ss.SSSXXX, UTC}|%X{requestId}|%X{serviceInstanceId}|%t|%X{serverName}|%X{serviceName}|%X{instanceUuid}|%p|%X{severity}|%X{serverIpAddress}|%X{server}|%X{clientIpAddress}|%c||%msg%n" />
-
-
-
+
+
+
<!-- P A T H
<property name="logDirectory" value="${catalina.base}/${logDir}/${componentName}/${subComponentName}" />
- <property name="debugLogDirectory" value="${catalina.base}/${debugDir}/${componentName}/${subComponentName}" />
- -->
+ <property name="debugLogDirectory" value="${catalina.base}/${debugDir}/${componentName}/${subComponentName}" />
+ -->
<property name="logDirectory" value="${logDir}/${componentName}/${subComponentName}" />
<property name="debugLogDirectory" value="${debugDir}/${componentName}/${subComponentName}" />
-
-
-
+
+
+
<!-- Example evaluator filter applied against console appender -->
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
@@ -100,28 +100,28 @@
<!-- EELF Appenders -->
<!-- ============================================================================ -->
- <!-- The EELFAppender is used to record events to the general application
+ <!-- The EELFAppender is used to record events to the general application
log -->
-
- <!-- EELF Audit Appender. This appender is used to record audit engine
- related logging events. The audit logger and appender are specializations
- of the EELF application root logger and appender. This can be used to segregate
- Policy engine events from other components, or it can be eliminated to record
+
+ <!-- EELF Audit Appender. This appender is used to record audit engine
+ related logging events. The audit logger and appender are specializations
+ of the EELF application root logger and appender. This can be used to segregate
+ Policy engine events from other components, or it can be eliminated to record
these events as part of the application root log. -->
-
+
<appender name="EELFAudit"
class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>${logDirectory}/${auditLogName}.log</file>
<rollingPolicy
class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
<fileNamePattern>${logDirectory}/${auditLogName}.%d{yyyy-MM-dd}.%i.log.zip</fileNamePattern>
-
- <!-- keep 30 days' worth of history capped at 3GB total size -->
+
+ <!-- keep 30 days' worth of history capped at 3GB total size -->
<maxFileSize>50MB</maxFileSize>
<maxHistory>30</maxHistory>
<totalSizeCap>10GB</totalSizeCap>
</rollingPolicy>
-
+
<encoder>
<pattern>${defaultAuditPattern}</pattern>
</encoder>
@@ -141,18 +141,18 @@
<rollingPolicy
class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
<fileNamePattern>${logDirectory}/${metricsLogName}.%d{yyyy-MM-dd}.%i.log.zip</fileNamePattern>
-
- <!-- keep 30 days' worth of history capped at 3GB total size -->
+
+ <!-- keep 30 days' worth of history capped at 3GB total size -->
<maxFileSize>50MB</maxFileSize>
<maxHistory>30</maxHistory>
<totalSizeCap>10GB</totalSizeCap>
</rollingPolicy>
-
+
<encoder>
<pattern>${defaultMetricPattern}</pattern>
</encoder>
</appender>
-
+
<appender name="asyncEELFMetrics" class="ch.qos.logback.classic.AsyncAppender">
<queueSize>256</queueSize>
<appender-ref ref="EELFMetrics"/>
@@ -160,15 +160,15 @@
-
+
<appender name="EELFError"
class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>${logDirectory}/${errorLogName}.log</file>
<rollingPolicy
class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
<fileNamePattern>${logDirectory}/${errorLogName}.%d{yyyy-MM-dd}.%i.log.zip</fileNamePattern>
-
- <!-- keep 30 days' worth of history capped at 3GB total size -->
+
+ <!-- keep 30 days' worth of history capped at 3GB total size -->
<maxFileSize>50MB</maxFileSize>
<maxHistory>30</maxHistory>
<totalSizeCap>10GB</totalSizeCap>
@@ -176,27 +176,27 @@
<filter class="ch.qos.logback.classic.filter.ThresholdFilter">
<level>ERROR</level>
</filter>
-
+
<encoder>
<pattern>${defaultErrorPattern}</pattern>
</encoder>
</appender>
-
+
<appender name="asyncEELFError" class="ch.qos.logback.classic.AsyncAppender">
<queueSize>256</queueSize>
<appender-ref ref="EELFError"/>
</appender>
-
+
<appender name="EELFDebug"
class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>${debugLogDirectory}/${debugLogName}.log</file>
<rollingPolicy
class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
<fileNamePattern>${debugLogDirectory}/${debugLogName}.%d{yyyy-MM-dd}.%i.log.zip</fileNamePattern>
-
- <!-- keep 30 days' worth of history capped at 3GB total size -->
+
+ <!-- keep 30 days' worth of history capped at 3GB total size -->
<maxFileSize>50MB</maxFileSize>
<maxHistory>30</maxHistory>
<totalSizeCap>10GB</totalSizeCap>
@@ -204,41 +204,41 @@
<filter class="ch.qos.logback.classic.filter.ThresholdFilter">
<level>DEBUG</level>
</filter>
-
+
<encoder>
<pattern>${debugLoggerPattern}</pattern>
</encoder>
</appender>
-
+
<appender name="asyncEELFDebug" class="ch.qos.logback.classic.AsyncAppender">
<queueSize>256</queueSize>
<appender-ref ref="EELFDebug" />
<includeCallerData>true</includeCallerData>
</appender>
-
-
+
+
<!-- ============================================================================ -->
<!-- EELF loggers -->
<!-- ============================================================================ -->
-
+
<logger name="com.att.eelf.audit" level="info" additivity="false">
<appender-ref ref="asyncEELFAudit" />
</logger>
-
+
<logger name="com.att.eelf.metrics" level="info" additivity="false">
<appender-ref ref="asyncEELFMetrics" />
</logger>
-
+
<logger name="com.att.eelf.error" level="error" additivity="false">
<appender-ref ref="asyncEELFError" />
</logger>
-
+
<logger name="com.att.eelf.debug" level="info" additivity="false">
<appender-ref ref="asyncEELFDebug" />
</logger>
-
-
-
+
+
+
<root level="INFO">
<appender-ref ref="asyncEELFDebug" />
<appender-ref ref="asyncEELFError" />
diff --git a/PolicyEngineAPI/src/test/java/org/onap/policy/std/StdPolicyEngineTest.java b/PolicyEngineAPI/src/test/java/org/onap/policy/std/StdPolicyEngineTest.java
index 90e00c2c3..a7f609904 100644
--- a/PolicyEngineAPI/src/test/java/org/onap/policy/std/StdPolicyEngineTest.java
+++ b/PolicyEngineAPI/src/test/java/org/onap/policy/std/StdPolicyEngineTest.java
@@ -5,6 +5,7 @@
* Copyright (C) 2018 Ericsson. All rights reserved.
* ================================================================================
* Modifications Copyright (C) 2019 Samsung
+ * Modifications Copyright (C) 2020 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -24,8 +25,8 @@ package org.onap.policy.std;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
-import static org.mockito.Matchers.any;
-import static org.mockito.Matchers.eq;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.spy;
@@ -103,6 +104,8 @@ import org.onap.policy.api.PushPolicyParameters;
import org.onap.policy.models.APIDictionaryResponse;
import org.onap.policy.models.APIPolicyConfigResponse;
import org.onap.policy.std.utils.PolicyConfigConstants;
+import org.powermock.core.classloader.annotations.PowerMockIgnore;
+import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
@@ -111,6 +114,8 @@ import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.RestClientException;
@RunWith(PowerMockRunner.class)
+@PowerMockIgnore({"com.sun.org.apache.xerces.*", "jdk.internal.reflect.*", "javax.xml.*", "org.xml.*", "org.w3c.*"})
+@PrepareForTest(StdPolicyEngine.class)
public class StdPolicyEngineTest {
private static final String ONAP_NAME_VAL = "ONAP_NAME";
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
index f8af9c4f2..1b55fef91 100644
--- a/PolicyEngineAPI/src/test/java/org/onap/policy/std/test/ManualClientEndUEBTest.java
+++ b/PolicyEngineAPI/src/test/java/org/onap/policy/std/test/ManualClientEndUEBTest.java
@@ -22,7 +22,6 @@
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;
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
index cb5c40c60..ce1794450 100644
--- a/PolicyEngineAPI/src/test/java/org/onap/policy/std/test/NotificationStoreTest.java
+++ b/PolicyEngineAPI/src/test/java/org/onap/policy/std/test/NotificationStoreTest.java
@@ -25,7 +25,6 @@ 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 <code>NotificationStoreTest</code> contains tests for the 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
index e7d82499f..a5c4e85fa 100644
--- a/PolicyEngineAPI/src/test/java/org/onap/policy/test/PolicyConfigStatusTest.java
+++ b/PolicyEngineAPI/src/test/java/org/onap/policy/test/PolicyConfigStatusTest.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -23,8 +23,6 @@ package org.onap.policy.test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
-import org.junit.After;
-import org.junit.Before;
import org.junit.Test;
import org.onap.policy.api.PolicyConfigStatus;
diff --git a/PolicyEngineClient/pom.xml b/PolicyEngineClient/pom.xml
index 54ca652f5..89c5c8974 100644
--- a/PolicyEngineClient/pom.xml
+++ b/PolicyEngineClient/pom.xml
@@ -24,7 +24,7 @@
<parent>
<groupId>org.onap.policy.engine</groupId>
<artifactId>PolicyEngineSuite</artifactId>
- <version>1.4.1-SNAPSHOT</version>
+ <version>1.6.4-SNAPSHOT</version>
</parent>
<artifactId>PolicyEngineClient</artifactId>
<dependencies>
diff --git a/PolicyEngineClient/src/test/java/org/onap/policyengine/ActionPolicyClient.java b/PolicyEngineClient/src/test/java/org/onap/policyengine/ActionPolicyClient.java
index 94c6043c5..a3c29fb8e 100644
--- a/PolicyEngineClient/src/test/java/org/onap/policyengine/ActionPolicyClient.java
+++ b/PolicyEngineClient/src/test/java/org/onap/policyengine/ActionPolicyClient.java
@@ -2,14 +2,14 @@
* ============LICENSE_START=======================================================
* PolicyEngineClient
* ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017, 2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -34,78 +34,84 @@ import org.onap.policy.api.PolicyEngine;
import org.onap.policy.api.PolicyParameters;
public class ActionPolicyClient {
- static Boolean isEdit = true;
- public static void main(String[] args) {
- try {
- PolicyEngine policyEngine = new PolicyEngine("config.properties");
- PolicyParameters policyParameters = new PolicyParameters();
- // Set Policy Type
- policyParameters.setPolicyClass(PolicyClass.Action); //required
- policyParameters.setPolicyName("MikeAPItesting.testActionAPI5"); //required
- policyParameters.setPolicyDescription("This is a sample Action policy update example with no Action Body"); //optional
- //policyParameters.setPolicyScope("MikeAPItesting"); //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<String, String> configAttributes = new HashMap<>();
- configAttributes.put("Template", "UpdateTemplate");
- configAttributes.put("controller", "default");
- configAttributes.put("SamPoll", "30");
- configAttributes.put("value", "abcd");
-
- Map<AttributeType, Map<String,String>> attributes = new HashMap<>();
- attributes.put(AttributeType.MATCHING, configAttributes);
- policyParameters.setAttributes(attributes);
+ static Boolean isEdit = true;
-
- List<String> dynamicRuleAlgorithmLabels = new LinkedList<>();
- List<String> dynamicRuleAlgorithmFunctions = new LinkedList<>();
- List<String> dynamicRuleAlgorithmField1 = new LinkedList<>();
- List<String> dynamicRuleAlgorithmField2 = new LinkedList<>();
-
- //Example of a complex Rule algorithm
- /* label field1 function field2
- * *****************************************************
- * A1 cobal integer-equal 90
- * A2 cap string-contains ca
- * A3 cobal integer-equal 90
- * A4 A2 and A3
- * A5 Config integer-greater-than 45
- * A6 A4 ` or A5
- * A7 A1 and A6
- */
- dynamicRuleAlgorithmLabels = Arrays.asList("A1","A2","A3","A4","A5","A6","A7");
- dynamicRuleAlgorithmField1 = Arrays.asList("cobal","cap","cobal","A2","Config","A4","A1");
- dynamicRuleAlgorithmFunctions = Arrays.asList("integer-equal","string-contains","integer-equal","and","integer-greater-than","or","and");
- dynamicRuleAlgorithmField2 = Arrays.asList("90","ca","90","A3","45","A5","A6");
-
- policyParameters.setDynamicRuleAlgorithmLabels(dynamicRuleAlgorithmLabels);
- policyParameters.setDynamicRuleAlgorithmField1(dynamicRuleAlgorithmField1);
- policyParameters.setDynamicRuleAlgorithmFunctions(dynamicRuleAlgorithmFunctions);
- policyParameters.setDynamicRuleAlgorithmField2(dynamicRuleAlgorithmField2);
-
- policyParameters.setActionPerformer("PEP");
- policyParameters.setActionAttribute("mikeTest2");
- policyParameters.setRequestID(UUID.randomUUID());
-
- // API method to create Policy or update policy
- PolicyChangeResponse response = null;
- if (!isEdit) {
- response = policyEngine.createPolicy(policyParameters);
- } else {
- response = policyEngine.updatePolicy(policyParameters);
- }
-
- if(response.getResponseCode()==200){
- System.out.println(response.getResponseMessage());
- System.out.println("Policy Created Successfully!");
- }else{
- System.out.println("Error! " + response.getResponseMessage());
- }
- } catch (Exception e) {
- System.err.println(e.getMessage() + e);
- }
- }
-
-}
+ /**
+ * main.
+ *
+ * @param args String[] args
+ */
+ public static void main(String[] args) {
+ try {
+ PolicyEngine policyEngine = new PolicyEngine("config.properties");
+ PolicyParameters policyParameters = new PolicyParameters();
+ // Set Policy Type
+ policyParameters.setPolicyClass(PolicyClass.Action); // required
+ policyParameters.setPolicyName("MikeAPItesting.testActionAPI5"); // required
+ policyParameters.setPolicyDescription(
+ "This is a sample Action policy update example with no Action Body"); // optional
+ // saved... this displays a a subscope on the GUI
+
+ // Set the Component Attributes... These are Optional
+ Map<String, String> configAttributes = new HashMap<>();
+ configAttributes.put("Template", "UpdateTemplate");
+ configAttributes.put("controller", "default");
+ configAttributes.put("SamPoll", "30");
+ configAttributes.put("value", "abcd");
+
+ Map<AttributeType, Map<String, String>> attributes = new HashMap<>();
+ attributes.put(AttributeType.MATCHING, configAttributes);
+ policyParameters.setAttributes(attributes);
+
+ List<String> dynamicRuleAlgorithmLabels = new LinkedList<>();
+ List<String> dynamicRuleAlgorithmFunctions = new LinkedList<>();
+ List<String> dynamicRuleAlgorithmField1 = new LinkedList<>();
+
+ // Example of a complex Rule algorithm
+ /*
+ * label field1 function field2
+ * *****************************************************
+ * A1 cobal integer-equal 90
+ * A2 cap string-contains ca
+ * A3 cobal integer-equal 90
+ * A4 A2 and A3
+ * A5 Config integer-greater-than 45
+ * A6 A4 ` or A5
+ * A7 A1 and A6
+ */
+ dynamicRuleAlgorithmLabels = Arrays.asList("A1", "A2", "A3", "A4", "A5", "A6", "A7");
+ dynamicRuleAlgorithmField1 = Arrays.asList("cobal", "cap", "cobal", "A2", "Config", "A4", "A1");
+ dynamicRuleAlgorithmFunctions = Arrays.asList("integer-equal", "string-contains", "integer-equal", "and",
+ "integer-greater-than", "or", "and");
+ List<String> dynamicRuleAlgorithmField2 = new LinkedList<>();
+ dynamicRuleAlgorithmField2 = Arrays.asList("90", "ca", "90", "A3", "45", "A5", "A6");
+ policyParameters.setDynamicRuleAlgorithmLabels(dynamicRuleAlgorithmLabels);
+ policyParameters.setDynamicRuleAlgorithmField1(dynamicRuleAlgorithmField1);
+ policyParameters.setDynamicRuleAlgorithmFunctions(dynamicRuleAlgorithmFunctions);
+ policyParameters.setDynamicRuleAlgorithmField2(dynamicRuleAlgorithmField2);
+ policyParameters.setActionPerformer("PEP");
+ policyParameters.setActionAttribute("mikeTest2");
+ policyParameters.setRequestID(UUID.randomUUID());
+
+ // API method to create Policy or update policy
+ PolicyChangeResponse response = null;
+ if (!isEdit) {
+ response = policyEngine.createPolicy(policyParameters);
+ } else {
+ response = policyEngine.updatePolicy(policyParameters);
+ }
+
+ if (response.getResponseCode() == 200) {
+ System.out.println(response.getResponseMessage());
+ System.out.println("Policy Created Successfully!");
+ } else {
+ System.out.println("Error! " + response.getResponseMessage());
+ }
+ } catch (Exception e) {
+ System.err.println(e.getMessage() + e);
+ }
+ }
+
+}
diff --git a/PolicyEngineClient/src/test/java/org/onap/policyengine/BrmsParamPolicyClient.java b/PolicyEngineClient/src/test/java/org/onap/policyengine/BrmsParamPolicyClient.java
index 33ceedf7f..60022d526 100644
--- a/PolicyEngineClient/src/test/java/org/onap/policyengine/BrmsParamPolicyClient.java
+++ b/PolicyEngineClient/src/test/java/org/onap/policyengine/BrmsParamPolicyClient.java
@@ -2,14 +2,14 @@
* ============LICENSE_START=======================================================
* PolicyEngineClient
* ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017, 2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -32,65 +32,68 @@ import org.onap.policy.api.PolicyConfigType;
import org.onap.policy.api.PolicyEngine;
import org.onap.policy.api.PolicyParameters;
-
public class BrmsParamPolicyClient {
-
- public static void main(String[] args) {
- try {
- PolicyEngine policyEngine = new PolicyEngine("config.properties");
+ /**
+ * main.
+ *
+ * @param args String[] of arguments
+ */
+ public static void main(String[] args) {
+ try {
PolicyParameters policyParameters = new PolicyParameters();
- // Set Policy Type(Mandatory)
+ // Set Policy Type(Mandatory)
policyParameters.setPolicyConfigType(PolicyConfigType.BRMS_PARAM);
-
- // Set Policy Name(Mandatory)
+
+ // Set Policy Name(Mandatory)
policyParameters.setPolicyName("Lakshman.testParamPolicyThree");
-
+
+ // Set Safe Policy value for Risk Type
+ SimpleDateFormat dateformat3 = new SimpleDateFormat("dd/MM/yyyy");
+ Date date = dateformat3.parse("15/10/2016");
+ policyParameters.setTtlDate(date);
+ // Set Safe Policy value for Guard
+ policyParameters.setGuard(true);
+ // Set Safe Policy value for Risk Level
+ policyParameters.setRiskLevel("5");
// Set Safe Policy value for Risk Type
- SimpleDateFormat dateformat3 = new SimpleDateFormat("dd/MM/yyyy");
- Date date = dateformat3.parse("15/10/2016");
- policyParameters.setTtlDate(date);
- // Set Safe Policy value for Guard
- policyParameters.setGuard(true);
- // Set Safe Policy value for Risk Level
- policyParameters.setRiskLevel("5");
- // Set Safe Policy value for Risk Type
- policyParameters.setRiskType("PROD");
-
+ policyParameters.setRiskType("PROD");
+
// Set description of the policy(Optional)
policyParameters.setPolicyDescription("This is a sample BRMS Param policy creation example");
-
- // Set BRMS Param Template Attributes(Mandatory)
+
+ // Set BRMS Param Template Attributes(Mandatory)
Map<String, String> ruleAttributes = new HashMap<>();
- ruleAttributes.put("templateName", "Sample"); // This sampleTemplate is the Template name from dictionary.
- ruleAttributes.put("controller", "default"); // Set Rule to a PDP Controller, default is the controller name.
- ruleAttributes.put("SamPoll", "300"); // Template specific key and value set by us.
- ruleAttributes.put("value", "abcd"); // Template specific key and value set by us.
+ ruleAttributes.put("templateName", "Sample"); // This sampleTemplate is the Template name from dictionary.
+ // Set Rule to a PDP Controller, default is the controller
+ // name.
+ ruleAttributes.put("controller", "default");
+ ruleAttributes.put("SamPoll", "300"); // Template specific key and value set by us.
+ ruleAttributes.put("value", "abcd"); // Template specific key and value set by us.
Map<AttributeType, Map<String, String>> attributes = new HashMap<>();
attributes.put(AttributeType.RULE, ruleAttributes);
policyParameters.setAttributes(attributes);
-
- //Set a random UUID(Mandatory)
+
+ // Set a random UUID(Mandatory)
policyParameters.setRequestID(UUID.randomUUID());
- // CreatePolicy method to create Policy.
+ // CreatePolicy method to create Policy.
+ PolicyEngine policyEngine = new PolicyEngine("config.properties");
PolicyChangeResponse response = policyEngine.updatePolicy(policyParameters);
- if(response.getResponseCode()==200){
+ if (response.getResponseCode() == 200) {
System.out.println(response.getResponseMessage());
System.out.println("Policy Created Successfully!");
- }else{
+ } else {
System.out.println("Error! " + response.getResponseMessage());
}
} catch (Exception e) {
System.err.println(e.getMessage() + e);
}
-
- }
-
-}
+ }
+}
diff --git a/PolicyEngineClient/src/test/java/org/onap/policyengine/BrmsRawPolicyClient.java b/PolicyEngineClient/src/test/java/org/onap/policyengine/BrmsRawPolicyClient.java
index 60e2c5df7..41bb6c556 100644
--- a/PolicyEngineClient/src/test/java/org/onap/policyengine/BrmsRawPolicyClient.java
+++ b/PolicyEngineClient/src/test/java/org/onap/policyengine/BrmsRawPolicyClient.java
@@ -2,14 +2,14 @@
* ============LICENSE_START=======================================================
* PolicyEngineClient
* ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017, 2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -42,39 +42,44 @@ import org.onap.policy.api.PolicyType;
public class BrmsRawPolicyClient {
static Boolean isEdit = true;
- //Reads a File and converts into a String.
- private static String readFile( String file ) throws IOException {
+ // Reads a File and converts into a String.
+ private static String readFile(String file) throws IOException {
- String line = null;
- StringBuilder stringBuilder = new StringBuilder();
- String ls = System.getProperty("line.separator");
+ String line = null;
+ StringBuilder stringBuilder = new StringBuilder();
+ String ls = System.getProperty("line.separator");
- try (BufferedReader reader = new BufferedReader( new FileReader (file))) {
- while( ( line = reader.readLine() ) != null ) {
- stringBuilder.append( line );
- stringBuilder.append( ls );
+ try (BufferedReader reader = new BufferedReader(new FileReader(file))) {
+ while ((line = reader.readLine()) != null) {
+ stringBuilder.append(line);
+ stringBuilder.append(ls);
}
return stringBuilder.toString();
}
}
-
+ /**
+ * main.
+ *
+ * @param args String[] of arguments
+ */
public static void main(String[] args) {
try {
PolicyEngine policyEngine = new PolicyEngine("config.properties");
- PolicyParameters policyParameters = new PolicyParameters();
- Map<String, String> attrib= new HashMap<>();
- attrib.put("cpu","80");
+ Map<String, String> attrib = new HashMap<>();
+ attrib.put("cpu", "80");
attrib.put("memory", "50");
Map<AttributeType, Map<String, String>> attributes = new HashMap<>();
attributes.put(AttributeType.RULE, attrib);
+ PolicyParameters policyParameters = new PolicyParameters();
// Set Policy Type
- policyParameters.setPolicyConfigType(PolicyConfigType.BRMS_RAW); //required
- policyParameters.setPolicyName("Lakshman.testBRMSRawAPITwo"); //required
- policyParameters.setPolicyDescription("This is a sample BRMS Raw policy body"); //optional
+ policyParameters.setPolicyConfigType(PolicyConfigType.BRMS_RAW); // required
+ policyParameters.setPolicyName("Lakshman.testBRMSRawAPITwo"); // required
+ policyParameters.setPolicyDescription("This is a sample BRMS Raw policy body"); // optional
policyParameters.setAttributes(attributes);
- //policyParameters.setPolicyScope("Lakshman"); //Directory will be created where the Policies are saved... this displays a a subscope on the GUI
+ // policyParameters.setPolicyScope("Lakshman"); //Directory will be created where the Policies are saved...
+ // this displays a a subscope on the GUI
policyParameters.setRequestID(UUID.randomUUID());
// Set Safe Policy value for Risk Type
@@ -104,10 +109,10 @@ public class BrmsRawPolicyClient {
response = policyEngine.updatePolicy(policyParameters);
}
- if(response.getResponseCode()==200){
+ if (response.getResponseCode() == 200) {
System.out.println(response.getResponseMessage());
System.out.println("Policy Created Successfully!");
- }else{
+ } else {
System.out.println("Error! " + response.getResponseMessage());
}
} catch (Exception e) {
@@ -116,5 +121,3 @@ public class BrmsRawPolicyClient {
}
}
-
-
diff --git a/PolicyEngineClient/src/test/java/org/onap/policyengine/ClosedLoopPolicyClient.java b/PolicyEngineClient/src/test/java/org/onap/policyengine/ClosedLoopPolicyClient.java
index 29a0f4363..13b9f4794 100644
--- a/PolicyEngineClient/src/test/java/org/onap/policyengine/ClosedLoopPolicyClient.java
+++ b/PolicyEngineClient/src/test/java/org/onap/policyengine/ClosedLoopPolicyClient.java
@@ -2,14 +2,14 @@
* ============LICENSE_START=======================================================
* PolicyEngineClient
* ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017, 2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -43,83 +43,88 @@ import org.onap.policy.api.PolicyParameters;
import org.onap.policy.api.PolicyType;
public class ClosedLoopPolicyClient {
- //For updating a ClosedLoop_Fault policy set the "isEdit" flag to true.
- //For creating a ClosedLoop_Fault policy set the "isEdit" flag to false.
- static Boolean isEdit = false;
-
- //Builds JSONObject from File
- private static JsonObject buildJSON(File jsonInput, String jsonString) throws FileNotFoundException {
- JsonObject json = null;;
- JsonReader jsonReader = null;
- if (jsonString != null && jsonInput == null) {
- StringReader in = null;
- in = new StringReader(jsonString);
- jsonReader = Json.createReader(in);
- json = jsonReader.readObject();
- in.close();
- }else {
- InputStream in = null;
- in = new FileInputStream(jsonInput);
- jsonReader = Json.createReader(in);
- json = jsonReader.readObject();
- try {
- in.close();
- } catch (IOException e) {
- System.err.println("Exception Occured while closing input stream"+e);
- }
- }
- jsonReader.close();
-
- return json;
- }
- public static void main(String[] args) {
- try {
- PolicyEngine policyEngine = new PolicyEngine("config.properties");
- PolicyParameters policyParameters = new PolicyParameters();
- // Set Policy Type
- policyParameters.setPolicyConfigType(PolicyConfigType.ClosedLoop_Fault);
- policyParameters.setPolicyName("MikeAPItests.ClosedLoopFaultApiTest45");
- policyParameters.setPolicyDescription("This is a sample ClosedLoop_Fault policy CREATE example");
- //policyParameters.setPolicyScope("MikeAPItests");
-
- // Set up Micro Services Attributes
- File jsonFile = null;
- String MSjsonString= null;
- Path file = Paths.get("C:\\policyAPI\\ClosedLoopJSON\\faultTestJson.json");
- jsonFile = file.toFile();
-
- policyParameters.setConfigBody(buildJSON(jsonFile, MSjsonString).toString());
- policyParameters.setConfigBodyType(PolicyType.JSON);
+ // For updating a ClosedLoop_Fault policy set the "isEdit" flag to true.
+ // For creating a ClosedLoop_Fault policy set the "isEdit" flag to false.
+ static Boolean isEdit = false;
- policyParameters.setRequestID(UUID.randomUUID());
- // Set Safe Policy value for Risk Type
- SimpleDateFormat dateformat3 = new SimpleDateFormat("dd/MM/yyyy");
- Date date = dateformat3.parse("15/10/2016");
- policyParameters.setTtlDate(date);
- // Set Safe Policy value for Guard
- policyParameters.setGuard(true);
- // Set Safe Policy value for Risk Level
- policyParameters.setRiskLevel("5");
- // Set Safe Policy value for Risk Type
- policyParameters.setRiskType("PROD");
-
- // API method to create or update Policy.
- PolicyChangeResponse response = null;
- if (!isEdit) {
- response = policyEngine.createPolicy(policyParameters);
- }
- else {
- response = policyEngine.updatePolicy(policyParameters);
- }
-
- if(response.getResponseCode()==200){
- System.out.println(response.getResponseMessage());
- System.out.println("Policy Created Successfully!");
- }else{
- System.out.println("Error! " + response.getResponseMessage());
- }
- } catch (Exception e) {
- System.err.println(e.getMessage());
- }
- }
+ // Builds JSONObject from File
+ private static JsonObject buildJson(File jsonInput, String jsonString) throws FileNotFoundException {
+ JsonObject json = null;;
+ JsonReader jsonReader = null;
+ if (jsonString != null && jsonInput == null) {
+ StringReader in = null;
+ in = new StringReader(jsonString);
+ jsonReader = Json.createReader(in);
+ json = jsonReader.readObject();
+ in.close();
+ } else {
+ InputStream in = null;
+ in = new FileInputStream(jsonInput);
+ jsonReader = Json.createReader(in);
+ json = jsonReader.readObject();
+ try {
+ in.close();
+ } catch (IOException e) {
+ System.err.println("Exception Occured while closing input stream" + e);
+ }
+ }
+ jsonReader.close();
+
+ return json;
+ }
+
+ /**
+ * main.
+ *
+ * @param args String[] args
+ */
+ public static void main(String[] args) {
+ try {
+ PolicyEngine policyEngine = new PolicyEngine("config.properties");
+ PolicyParameters policyParameters = new PolicyParameters();
+ // Set Policy Type
+ policyParameters.setPolicyConfigType(PolicyConfigType.ClosedLoop_Fault);
+ policyParameters.setPolicyName("MikeAPItests.ClosedLoopFaultApiTest45");
+ policyParameters.setPolicyDescription("This is a sample ClosedLoop_Fault policy CREATE example");
+ // policyParameters.setPolicyScope("MikeAPItests");
+
+ // Set up Micro Services Attributes
+ File jsonFile = null;
+ String msJsonString = null;
+ Path file = Paths.get("C:\\policyAPI\\ClosedLoopJSON\\faultTestJson.json");
+ jsonFile = file.toFile();
+
+ policyParameters.setConfigBody(buildJson(jsonFile, msJsonString).toString());
+ policyParameters.setConfigBodyType(PolicyType.JSON);
+
+ policyParameters.setRequestID(UUID.randomUUID());
+ // Set Safe Policy value for Risk Type
+ SimpleDateFormat dateformat3 = new SimpleDateFormat("dd/MM/yyyy");
+ Date date = dateformat3.parse("15/10/2016");
+ policyParameters.setTtlDate(date);
+ // Set Safe Policy value for Guard
+ policyParameters.setGuard(true);
+ // Set Safe Policy value for Risk Level
+ policyParameters.setRiskLevel("5");
+ // Set Safe Policy value for Risk Type
+ policyParameters.setRiskType("PROD");
+
+ // API method to create or update Policy.
+ PolicyChangeResponse response = null;
+ if (!isEdit) {
+ response = policyEngine.createPolicy(policyParameters);
+ } else {
+ response = policyEngine.updatePolicy(policyParameters);
+ }
+
+ if (response.getResponseCode() == 200) {
+ System.out.println(response.getResponseMessage());
+ System.out.println("Policy Created Successfully!");
+ } else {
+ System.out.println("Error! " + response.getResponseMessage());
+ }
+ } catch (Exception e) {
+ System.err.println(e.getMessage());
+ }
+ }
}
diff --git a/PolicyEngineClient/src/test/java/org/onap/policyengine/ClosedLoopPolicyPerformanceMetricClient.java b/PolicyEngineClient/src/test/java/org/onap/policyengine/ClosedLoopPolicyPerformanceMetricClient.java
index eaee2a325..bcdeaabd1 100644
--- a/PolicyEngineClient/src/test/java/org/onap/policyengine/ClosedLoopPolicyPerformanceMetricClient.java
+++ b/PolicyEngineClient/src/test/java/org/onap/policyengine/ClosedLoopPolicyPerformanceMetricClient.java
@@ -2,14 +2,14 @@
* ============LICENSE_START=======================================================
* PolicyEngineClient
* ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017, 2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -43,85 +43,88 @@ import org.onap.policy.api.PolicyParameters;
import org.onap.policy.api.PolicyType;
public class ClosedLoopPolicyPerformanceMetricClient {
-
- //For updating a ClosedLoop_Fault policy set the "isEdit" flag to true.
- //For creating a ClosedLoop_Fault policy set the "isEdit" flag to false.
- static Boolean isEdit = true;
-
- //Builds JSONObject from File
- private static JsonObject buildJSON(File jsonInput, String jsonString) throws FileNotFoundException {
- JsonObject json = null;;
- JsonReader jsonReader = null;
- if (jsonString != null && jsonInput == null) {
- StringReader in = null;
- in = new StringReader(jsonString);
- jsonReader = Json.createReader(in);
- json = jsonReader.readObject();
- in.close();
- }
- else {
- InputStream in = null;
- in = new FileInputStream(jsonInput);
- jsonReader = Json.createReader(in);
- json = jsonReader.readObject();
- try {
- in.close();
- } catch (IOException e) {
- System.err.println("Exception Occured while closing input stream"+e);
- }
- }
- jsonReader.close();
- return json;
- }
-
- public static void main(String[] args) {
- try {
- PolicyEngine policyEngine = new PolicyEngine("config.properties");
- PolicyParameters policyParameters = new PolicyParameters();
- // Set Policy Type
- policyParameters.setPolicyConfigType(PolicyConfigType.ClosedLoop_PM);
- policyParameters.setPolicyName("MikeAPItests.ClosedLoopPmApiTest");
- policyParameters.setPolicyDescription("This is a sample ClosedLoop_PM policy CREATE example");
- //policyParameters.setPolicyScope("MikeAPItests");
-
- // Set up Micro Services Attributes
- File jsonFile = null;
- String MSjsonString= null;
- Path file = Paths.get("C:\\policyAPI\\ClosedLoopJSON\\pmTestJson.json");
- jsonFile = file.toFile();
-
- policyParameters.setConfigBody(buildJSON(jsonFile, MSjsonString).toString());
- policyParameters.setConfigBodyType(PolicyType.JSON);
- policyParameters.setRequestID(UUID.randomUUID());
- // Set Safe Policy value for Risk Type
- SimpleDateFormat dateformat3 = new SimpleDateFormat("dd/MM/yyyy");
- Date date = dateformat3.parse("15/10/2016");
- policyParameters.setTtlDate(date);
- // Set Safe Policy value for Guard
- policyParameters.setGuard(true);
- // Set Safe Policy value for Risk Level
- policyParameters.setRiskLevel("5");
- // Set Safe Policy value for Risk Type
- policyParameters.setRiskType("PROD");
-
- // API method to create or update Policy.
- PolicyChangeResponse response = null;
- if (!isEdit) {
- response = policyEngine.createPolicy(policyParameters);
- }
- else {
- response = policyEngine.updatePolicy(policyParameters);
- }
-
- if(response.getResponseCode()==200){
- System.out.println(response.getResponseMessage());
- System.out.println("Policy Created Successfully!");
- }else{
- System.out.println("Error! " + response.getResponseMessage());
- }
- } catch (Exception e) {
- System.err.println(e.getMessage());
- }
- }
+ // For updating a ClosedLoop_Fault policy set the "isEdit" flag to true.
+ // For creating a ClosedLoop_Fault policy set the "isEdit" flag to false.
+ static Boolean isEdit = true;
+
+ // Builds JSONObject from File
+ private static JsonObject buildJson(File jsonInput, String jsonString) throws FileNotFoundException {
+ JsonObject json = null;;
+ JsonReader jsonReader = null;
+ if (jsonString != null && jsonInput == null) {
+ StringReader in = null;
+ in = new StringReader(jsonString);
+ jsonReader = Json.createReader(in);
+ json = jsonReader.readObject();
+ in.close();
+ } else {
+ InputStream in = null;
+ in = new FileInputStream(jsonInput);
+ jsonReader = Json.createReader(in);
+ json = jsonReader.readObject();
+ try {
+ in.close();
+ } catch (IOException e) {
+ System.err.println("Exception Occured while closing input stream" + e);
+ }
+ }
+ jsonReader.close();
+ return json;
+ }
+
+ /**
+ * main.
+ *
+ * @param args String[] args
+ */
+ public static void main(String[] args) {
+ try {
+ PolicyEngine policyEngine = new PolicyEngine("config.properties");
+ PolicyParameters policyParameters = new PolicyParameters();
+ // Set Policy Type
+ policyParameters.setPolicyConfigType(PolicyConfigType.ClosedLoop_PM);
+ policyParameters.setPolicyName("MikeAPItests.ClosedLoopPmApiTest");
+ policyParameters.setPolicyDescription("This is a sample ClosedLoop_PM policy CREATE example");
+ // policyParameters.setPolicyScope("MikeAPItests");
+
+ // Set up Micro Services Attributes
+ File jsonFile = null;
+ String msJsonString = null;
+ Path file = Paths.get("C:\\policyAPI\\ClosedLoopJSON\\pmTestJson.json");
+ jsonFile = file.toFile();
+
+ policyParameters.setConfigBody(buildJson(jsonFile, msJsonString).toString());
+ policyParameters.setConfigBodyType(PolicyType.JSON);
+
+ policyParameters.setRequestID(UUID.randomUUID());
+ // Set Safe Policy value for Risk Type
+ SimpleDateFormat dateformat3 = new SimpleDateFormat("dd/MM/yyyy");
+ Date date = dateformat3.parse("15/10/2016");
+ policyParameters.setTtlDate(date);
+ // Set Safe Policy value for Guard
+ policyParameters.setGuard(true);
+ // Set Safe Policy value for Risk Level
+ policyParameters.setRiskLevel("5");
+ // Set Safe Policy value for Risk Type
+ policyParameters.setRiskType("PROD");
+
+ // API method to create or update Policy.
+ PolicyChangeResponse response = null;
+ if (!isEdit) {
+ response = policyEngine.createPolicy(policyParameters);
+ } else {
+ response = policyEngine.updatePolicy(policyParameters);
+ }
+
+ if (response.getResponseCode() == 200) {
+ System.out.println(response.getResponseMessage());
+ System.out.println("Policy Created Successfully!");
+ } else {
+ System.out.println("Error! " + response.getResponseMessage());
+ }
+ } catch (Exception e) {
+ System.err.println(e.getMessage());
+ }
+ }
}
diff --git a/PolicyEngineClient/src/test/java/org/onap/policyengine/ConfigBasePolicyClient.java b/PolicyEngineClient/src/test/java/org/onap/policyengine/ConfigBasePolicyClient.java
index cfcc1460b..cfc47cc1e 100644
--- a/PolicyEngineClient/src/test/java/org/onap/policyengine/ConfigBasePolicyClient.java
+++ b/PolicyEngineClient/src/test/java/org/onap/policyengine/ConfigBasePolicyClient.java
@@ -1,22 +1,22 @@
- /*-
- * ============LICENSE_START=======================================================
- * PolicyEngineClient
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
+/*-
+* ============LICENSE_START=======================================================
+* PolicyEngineClient
+* ================================================================================
+* Copyright (C) 2017, 2019 AT&T Intellectual Property. All rights reserved.
+* ================================================================================
+* Licensed under the Apache License, Version 2.0 (the "License");
+* you may not use this file except in compliance with the License.
+* You may obtain a copy of the License at
+*
+* http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License.
+* ============LICENSE_END=========================================================
+*/
package org.onap.policyengine;
@@ -33,59 +33,65 @@ import org.onap.policy.api.PolicyEngine;
import org.onap.policy.api.PolicyParameters;
import org.onap.policy.api.PolicyType;
-public class ConfigBasePolicyClient{
- static Boolean isEdit = false;
- public static void main(String[] args) {
+public class ConfigBasePolicyClient {
+ static Boolean isEdit = false;
+
+ /**
+ * main.
+ *
+ * @param args String[] args
+ */
+ public static void main(String[] args) {
try {
PolicyEngine policyEngine = new PolicyEngine("config.properties");
PolicyParameters policyParameters = new PolicyParameters();
// Set Policy Type
- policyParameters.setPolicyConfigType(PolicyConfigType.Base); //required
- policyParameters.setPolicyName("MikeConsole.testDeleteAPI6"); //required
- policyParameters.setPolicyDescription("This is a sample Config Base policy creation example"); //optional
- policyParameters.setOnapName("DCAE"); //required
- policyParameters.setConfigName("testBase"); //required
- policyParameters.setConfigBodyType(PolicyType.OTHER); //required
- policyParameters.setConfigBody("testing"); //required
-
- //Set the Config Attributes... These are Optional
- Map<String, String> configAttributes = new HashMap<>();
+ policyParameters.setPolicyConfigType(PolicyConfigType.Base); // required
+ policyParameters.setPolicyName("MikeConsole.testDeleteAPI6"); // required
+ policyParameters.setPolicyDescription("This is a sample Config Base policy creation example"); // optional
+ policyParameters.setOnapName("DCAE"); // required
+ policyParameters.setConfigName("testBase"); // required
+ policyParameters.setConfigBodyType(PolicyType.OTHER); // required
+ policyParameters.setConfigBody("testing"); // required
+
+ // Set the Config Attributes... These are Optional
+ Map<String, String> configAttributes = new HashMap<>();
configAttributes.put("Template", "SampleTemplate");
- configAttributes.put("controller", "default");
+ configAttributes.put("controller", "default");
configAttributes.put("SamPoll", "30");
- configAttributes.put("value", "abcd");
- Map<AttributeType, Map<String,String>> attributes = new HashMap<>();
+ configAttributes.put("value", "abcd");
+ Map<AttributeType, Map<String, String>> attributes = new HashMap<>();
attributes.put(AttributeType.MATCHING, configAttributes);
policyParameters.setAttributes(attributes);
policyParameters.setRequestID(UUID.randomUUID());
// Set Safe Policy value for Risk Type
- SimpleDateFormat dateformat3 = new SimpleDateFormat("dd/MM/yyyy");
- Date date = dateformat3.parse("15/10/2016");
- policyParameters.setTtlDate(date);
- // Set Safe Policy value for Guard
- policyParameters.setGuard(true);
- // Set Safe Policy value for Risk Level
- policyParameters.setRiskLevel("5");
- // Set Safe Policy value for Risk Type
- policyParameters.setRiskType("PROD");
-
+ SimpleDateFormat dateformat3 = new SimpleDateFormat("dd/MM/yyyy");
+ Date date = dateformat3.parse("15/10/2016");
+ policyParameters.setTtlDate(date);
+ // Set Safe Policy value for Guard
+ policyParameters.setGuard(true);
+ // Set Safe Policy value for Risk Level
+ policyParameters.setRiskLevel("5");
+ // Set Safe Policy value for Risk Type
+ policyParameters.setRiskType("PROD");
+
// API method to create Policy or update policy
PolicyChangeResponse response = null;
if (!isEdit) {
response = policyEngine.createPolicy(policyParameters);
} else {
- response = policyEngine.updatePolicy(policyParameters);
+ response = policyEngine.updatePolicy(policyParameters);
}
-
- if(response.getResponseCode()==200){
+
+ if (response.getResponseCode() == 200) {
System.out.println(response.getResponseMessage());
System.out.println("Policy Created Successfully!");
- }else{
+ } else {
System.out.println("Error! " + response.getResponseMessage());
}
} catch (Exception e) {
System.err.println(e.getMessage());
}
- }
-
+ }
+
}
diff --git a/PolicyEngineClient/src/test/java/org/onap/policyengine/ConfigFirewallPolicyClient.java b/PolicyEngineClient/src/test/java/org/onap/policyengine/ConfigFirewallPolicyClient.java
index 37ec9fabd..f7665f9ac 100644
--- a/PolicyEngineClient/src/test/java/org/onap/policyengine/ConfigFirewallPolicyClient.java
+++ b/PolicyEngineClient/src/test/java/org/onap/policyengine/ConfigFirewallPolicyClient.java
@@ -2,14 +2,14 @@
* ============LICENSE_START=======================================================
* PolicyEngineClient
* ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017, 2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -43,77 +43,84 @@ import org.onap.policy.api.PolicyParameters;
import org.onap.policy.api.PolicyType;
public class ConfigFirewallPolicyClient {
- static Boolean isEdit = false;
- public static void main(String[] args) {
- try{
- PolicyEngine policyEngine = new PolicyEngine("config.properties");
- PolicyParameters policyParameters = new PolicyParameters();
- // Set Policy Type
- policyParameters.setPolicyConfigType(PolicyConfigType.Firewall); //required
- policyParameters.setPolicyName("MikeAPItesting.testConfigFirewallPolicy1607_1"); //required
- //policyParameters.setPolicyScope("MikeAPItesting"); //Directory will be created where the Policies are saved... this displays a a subscope on the GUI
- policyParameters.setRequestID(UUID.randomUUID());
-
+ static Boolean isEdit = false;
+
+ /**
+ * main.
+ *
+ * @param args String[] args
+ */
+ public static void main(String[] args) {
+ try {
+ PolicyEngine policyEngine = new PolicyEngine("config.properties");
+ PolicyParameters policyParameters = new PolicyParameters();
+ // Set Policy Type
+ policyParameters.setPolicyConfigType(PolicyConfigType.Firewall); // required
+ policyParameters.setPolicyName("MikeAPItesting.testConfigFirewallPolicy1607_1"); // required
+ // policyParameters.setPolicyScope("MikeAPItesting"); //Directory will be created where the Policies are
+ // saved... this displays a a subscope on the GUI
+ policyParameters.setRequestID(UUID.randomUUID());
+
+ // Set Safe Policy value for Risk Type
+ SimpleDateFormat dateformat3 = new SimpleDateFormat("dd/MM/yyyy");
+ Date date = dateformat3.parse("15/10/2016");
+ policyParameters.setTtlDate(date);
+ // Set Safe Policy value for Guard
+ policyParameters.setGuard(true);
+ // Set Safe Policy value for Risk Level
+ policyParameters.setRiskLevel("5");
// Set Safe Policy value for Risk Type
- SimpleDateFormat dateformat3 = new SimpleDateFormat("dd/MM/yyyy");
- Date date = dateformat3.parse("15/10/2016");
- policyParameters.setTtlDate(date);
- // Set Safe Policy value for Guard
- policyParameters.setGuard(true);
- // Set Safe Policy value for Risk Level
- policyParameters.setRiskLevel("5");
- // Set Safe Policy value for Risk Type
- policyParameters.setRiskType("PROD");
- File jsonFile = null;
- String jsonRuleList = null;
- Path file = Paths.get("C:\\policyAPI\\firewallRulesJSON\\Config_FW_1607Rule.json");
- jsonFile = file.toFile();
-
- //buildJSON(jsonFile, jsonRuleList);
- policyParameters.setConfigBody(buildJSON(jsonFile, jsonRuleList).toString());
- policyParameters.setConfigBodyType(PolicyType.JSON);
+ policyParameters.setRiskType("PROD");
+ File jsonFile = null;
+ String jsonRuleList = null;
+ Path file = Paths.get("C:\\policyAPI\\firewallRulesJSON\\Config_FW_1607Rule.json");
+ jsonFile = file.toFile();
+
+ // buildJSON(jsonFile, jsonRuleList);
+ policyParameters.setConfigBody(buildJson(jsonFile, jsonRuleList).toString());
+ policyParameters.setConfigBodyType(PolicyType.JSON);
// API method to create Policy or update policy
PolicyChangeResponse response = null;
if (!isEdit) {
response = policyEngine.createPolicy(policyParameters);
} else {
- response = policyEngine.updatePolicy(policyParameters);
+ response = policyEngine.updatePolicy(policyParameters);
}
-
- if(response.getResponseCode()==200){
- System.out.println(response.getResponseMessage());
- System.out.println("Policy Created Successfully!");
- }else{
- System.out.println("Error! " + response.getResponseMessage());
- }
- } catch (Exception e) {
- System.err.println(e.getMessage());
- }
-
-}
-
- private static JsonObject buildJSON(File jsonInput, String jsonString) throws FileNotFoundException {
- JsonObject json = null;
- JsonReader jsonReader = null;
- if (jsonString != null && jsonInput == null) {
- StringReader in = null;
- in = new StringReader(jsonString);
- jsonReader = Json.createReader(in);
- json = jsonReader.readObject();
- in.close();
- } else {
- InputStream in = null;
- in = new FileInputStream(jsonInput);
- jsonReader = Json.createReader(in);
- json = jsonReader.readObject();
- try {
- in.close();
- } catch (IOException e) {
- System.err.println("Exception Occured while closing input stream"+e);
- }
- }
- jsonReader.close();
- return json;
- }
+
+ if (response.getResponseCode() == 200) {
+ System.out.println(response.getResponseMessage());
+ System.out.println("Policy Created Successfully!");
+ } else {
+ System.out.println("Error! " + response.getResponseMessage());
+ }
+ } catch (Exception e) {
+ System.err.println(e.getMessage());
+ }
+
+ }
+
+ private static JsonObject buildJson(File jsonInput, String jsonString) throws FileNotFoundException {
+ JsonObject json = null;
+ JsonReader jsonReader = null;
+ if (jsonString != null && jsonInput == null) {
+ StringReader in = null;
+ in = new StringReader(jsonString);
+ jsonReader = Json.createReader(in);
+ json = jsonReader.readObject();
+ in.close();
+ } else {
+ InputStream in = null;
+ in = new FileInputStream(jsonInput);
+ jsonReader = Json.createReader(in);
+ json = jsonReader.readObject();
+ try {
+ in.close();
+ } catch (IOException e) {
+ System.err.println("Exception Occured while closing input stream" + e);
+ }
+ }
+ jsonReader.close();
+ return json;
+ }
}
diff --git a/PolicyEngineClient/src/test/java/org/onap/policyengine/DecisionPolicyClient.java b/PolicyEngineClient/src/test/java/org/onap/policyengine/DecisionPolicyClient.java
index 2ef2d3b1a..44fb455af 100644
--- a/PolicyEngineClient/src/test/java/org/onap/policyengine/DecisionPolicyClient.java
+++ b/PolicyEngineClient/src/test/java/org/onap/policyengine/DecisionPolicyClient.java
@@ -2,14 +2,14 @@
* ============LICENSE_START=======================================================
* PolicyEngineClient
* ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017, 2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -34,81 +34,90 @@ import org.onap.policy.api.PolicyEngine;
import org.onap.policy.api.PolicyParameters;
public class DecisionPolicyClient {
- static Boolean isEdit = true;
- public static void main(String[] args) {
- try {
- PolicyEngine policyEngine = new PolicyEngine("config.properties");
- PolicyParameters policyParameters = new PolicyParameters();
- // Set Policy Type
- policyParameters.setPolicyClass(PolicyClass.Decision); //required
- policyParameters.setPolicyName("MikeAPItests.testDecisionAPI"); //required
- policyParameters.setOnapName("java"); //required
- policyParameters.setPolicyDescription("This is a sample Decision policy UPDATE example with Settings"); //optional
- //policyParameters.setPolicyScope("MikeAPItests"); //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<String, String> configAttributes = new HashMap<>();
- configAttributes.put("Template", "UpdateTemplate");
- configAttributes.put("controller", "default");
- configAttributes.put("SamPoll", "30");
- configAttributes.put("value", "abcd");
-
- Map<AttributeType, Map<String,String>> attributes = new HashMap<>();
- attributes.put(AttributeType.MATCHING, configAttributes);
-
- //Set the settings... These are Optional
- Map<String, String> settingsMap = new HashMap<>();
- settingsMap.put("server", "5");
-
- attributes.put(AttributeType.SETTINGS, settingsMap);
- policyParameters.setAttributes(attributes);
-
-
- List<String> dynamicRuleAlgorithmLabels = new LinkedList<>();
- List<String> dynamicRuleAlgorithmFunctions = new LinkedList<>();
- List<String> dynamicRuleAlgorithmField1 = new LinkedList<>();
- List<String> dynamicRuleAlgorithmField2 = new LinkedList<>();
-
- //Example of a complex Rule algorithm using the settings in the Field1
- /* label field1 function field2
- * *****************************************************
- * A1 S_server integer-equal 90
- * A2 cap string-contains ca
- * A3 cobal integer-equal 90
- * A4 A2 and A3
- * A5 Config integer-greater-than 45
- * A6 A4 ` or A5
- * A7 A1 and A6
- */
- dynamicRuleAlgorithmLabels = Arrays.asList("A1","A2","A3","A4","A5","A6","A7");
- dynamicRuleAlgorithmField1 = Arrays.asList("S_server","cap","cobal","A2","Config","A4","A1");
- dynamicRuleAlgorithmFunctions = Arrays.asList("integer-equal","string-contains","integer-equal","and","integer-greater-than","or","and");
- dynamicRuleAlgorithmField2 = Arrays.asList("90","ca","90","A3","45","A5","A6");
-
- policyParameters.setDynamicRuleAlgorithmLabels(dynamicRuleAlgorithmLabels);
- policyParameters.setDynamicRuleAlgorithmField1(dynamicRuleAlgorithmField1);
- policyParameters.setDynamicRuleAlgorithmFunctions(dynamicRuleAlgorithmFunctions);
- policyParameters.setDynamicRuleAlgorithmField2(dynamicRuleAlgorithmField2);
-
- policyParameters.setRequestID(UUID.randomUUID());
-
- // API method to create Policy or update policy
- PolicyChangeResponse response = null;
- if (!isEdit) {
- response = policyEngine.createPolicy(policyParameters);
- } else {
- response = policyEngine.updatePolicy(policyParameters);
- }
-
- if(response.getResponseCode()==200){
- System.out.println(response.getResponseMessage());
- System.out.println("Policy Created Successfully!");
- }else{
- System.out.println("Error! " + response.getResponseMessage());
- }
- } catch (Exception e) {
- System.err.println(e.getMessage());
- }
- }
+ static Boolean isEdit = true;
+
+ /**
+ * main.
+ *
+ * @param args String[] args
+ */
+ public static void main(String[] args) {
+ try {
+ PolicyEngine policyEngine = new PolicyEngine("config.properties");
+ PolicyParameters policyParameters = new PolicyParameters();
+ // Set Policy Type
+ policyParameters.setPolicyClass(PolicyClass.Decision); // required
+ policyParameters.setPolicyName("MikeAPItests.testDecisionAPI"); // required
+ policyParameters.setOnapName("java"); // required
+ policyParameters.setPolicyDescription(
+ "This is a sample Decision policy UPDATE example with Settings"); // optional
+ // policyParameters.setPolicyScope("MikeAPItests"); //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<String, String> configAttributes = new HashMap<>();
+ configAttributes.put("Template", "UpdateTemplate");
+ configAttributes.put("controller", "default");
+ configAttributes.put("SamPoll", "30");
+ configAttributes.put("value", "abcd");
+
+ Map<AttributeType, Map<String, String>> attributes = new HashMap<>();
+ attributes.put(AttributeType.MATCHING, configAttributes);
+
+ // Set the settings... These are Optional
+ Map<String, String> settingsMap = new HashMap<>();
+ settingsMap.put("server", "5");
+
+ attributes.put(AttributeType.SETTINGS, settingsMap);
+ policyParameters.setAttributes(attributes);
+
+ List<String> dynamicRuleAlgorithmLabels = new LinkedList<>();
+ List<String> dynamicRuleAlgorithmFunctions = new LinkedList<>();
+ List<String> dynamicRuleAlgorithmField1 = new LinkedList<>();
+
+ // Example of a complex Rule algorithm using the settings in the Field1
+ /*
+ * label field1 function field2
+ * *****************************************************
+ * A1 S_server integer-equal 90
+ * A2 cap string-contains ca
+ * A3 cobal integer-equal 90
+ * A4 A2 and A3
+ * A5 Config integer-greater-than 45
+ * A6 A4 ` or A5
+ * A7 A1 and A6
+ */
+ dynamicRuleAlgorithmLabels = Arrays.asList("A1", "A2", "A3", "A4", "A5", "A6", "A7");
+ dynamicRuleAlgorithmField1 = Arrays.asList("S_server", "cap", "cobal", "A2", "Config", "A4", "A1");
+ dynamicRuleAlgorithmFunctions = Arrays.asList("integer-equal", "string-contains", "integer-equal", "and",
+ "integer-greater-than", "or", "and");
+ List<String> dynamicRuleAlgorithmField2 = new LinkedList<>();
+ dynamicRuleAlgorithmField2 = Arrays.asList("90", "ca", "90", "A3", "45", "A5", "A6");
+
+ policyParameters.setDynamicRuleAlgorithmLabels(dynamicRuleAlgorithmLabels);
+ policyParameters.setDynamicRuleAlgorithmField1(dynamicRuleAlgorithmField1);
+ policyParameters.setDynamicRuleAlgorithmFunctions(dynamicRuleAlgorithmFunctions);
+ policyParameters.setDynamicRuleAlgorithmField2(dynamicRuleAlgorithmField2);
+
+ policyParameters.setRequestID(UUID.randomUUID());
+
+ // API method to create Policy or update policy
+ PolicyChangeResponse response = null;
+ if (!isEdit) {
+ response = policyEngine.createPolicy(policyParameters);
+ } else {
+ response = policyEngine.updatePolicy(policyParameters);
+ }
+
+ if (response.getResponseCode() == 200) {
+ System.out.println(response.getResponseMessage());
+ System.out.println("Policy Created Successfully!");
+ } else {
+ System.out.println("Error! " + response.getResponseMessage());
+ }
+ } catch (Exception e) {
+ System.err.println(e.getMessage());
+ }
+ }
}
diff --git a/PolicyEngineClient/src/test/java/org/onap/policyengine/DeletePolicyClient.java b/PolicyEngineClient/src/test/java/org/onap/policyengine/DeletePolicyClient.java
index c66067942..e411a4c6f 100644
--- a/PolicyEngineClient/src/test/java/org/onap/policyengine/DeletePolicyClient.java
+++ b/PolicyEngineClient/src/test/java/org/onap/policyengine/DeletePolicyClient.java
@@ -2,14 +2,14 @@
* ============LICENSE_START=======================================================
* PolicyEngineClient
* ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017, 2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -27,36 +27,39 @@ import org.onap.policy.api.PolicyEngine;
public class DeletePolicyClient {
- public static void main(String[] args) {
- try {
-
- PolicyEngine policyEngine = new PolicyEngine("config.properties");
- DeletePolicyParameters policyParameters = new DeletePolicyParameters();
-
- //Parameter arguments
- policyParameters.setPolicyName("MikeConsole.Config_testDeleteAPI6.1.xml");
- policyParameters.setPolicyComponent("PDP");
- policyParameters.setPdpGroup("default");
- policyParameters.setDeleteCondition(DeletePolicyCondition.ALL);
- policyParameters.setRequestID(null);
-
+ /**
+ * main.
+ *
+ * @param args String[] args
+ */
+ public static void main(String[] args) {
+ try {
+ DeletePolicyParameters policyParameters = new DeletePolicyParameters();
+
+ // Parameter arguments
+ policyParameters.setPolicyName("MikeConsole.Config_testDeleteAPI6.1.xml");
+ policyParameters.setPolicyComponent("PDP");
+ policyParameters.setPdpGroup("default");
+ policyParameters.setDeleteCondition(DeletePolicyCondition.ALL);
+ policyParameters.setRequestID(null);
+
// API method to Push Policy to PDP
PolicyChangeResponse response = null;
+ PolicyEngine policyEngine = new PolicyEngine("config.properties");
response = policyEngine.deletePolicy(policyParameters);
- if(response.getResponseCode()==200){
+ if (response.getResponseCode() == 200) {
System.out.println(response.getResponseMessage());
System.out.println("Policy Deleted Successfully!");
- }else{
+ } else {
System.out.println("Error! " + response.getResponseMessage());
}
- } catch (Exception e) {
- System.err.println(e.getMessage());
-
- }
-
- }
-
+ } catch (Exception e) {
+ System.err.println(e.getMessage());
+
+ }
+
+ }
}
diff --git a/PolicyEngineClient/src/test/java/org/onap/policyengine/GeneralTestClient.java b/PolicyEngineClient/src/test/java/org/onap/policyengine/GeneralTestClient.java
index 4c5a262df..77a12279a 100644
--- a/PolicyEngineClient/src/test/java/org/onap/policyengine/GeneralTestClient.java
+++ b/PolicyEngineClient/src/test/java/org/onap/policyengine/GeneralTestClient.java
@@ -2,14 +2,14 @@
* ============LICENSE_START=======================================================
* PolicyEngineClient
* ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017, 2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -17,6 +17,7 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.policyengine;
import java.io.FileNotFoundException;
@@ -43,347 +44,315 @@ import org.onap.policy.common.logging.flexlogger.Logger;
* Class reads from .testCases file and run the test cases available in the file
* and generates output for each test cases specifing whether is passed or fail
* and reason why it fails.
- *
- *
+ *
+ *
* @version 1.0
*
*/
public class GeneralTestClient {
-
- private static final Logger LOGGER = FlexLogger.getLogger(GeneralTestClient.class);
-
- static int totalTC = 0, passTC = 0, failTC = 0;
-
- public static void main(String[] args) {
- Path file;
- /* command line arguments */
- if (args.length != 0) {
- for (int index = 0; index < args.length; index++) {
- // System.out.println(args[index]);
- file = Paths.get(args[index]);
- runTestClientOnConfigFile(file);
- }
- } else {
- /* default file */
- file = Paths.get("input.testCases");
- runTestClientOnConfigFile(file);
- }
- System.out
- .println("###############################################################################################");
- System.out.println("\n\t SUMMARY: TOTAL: " + totalTC + ",\tPASS: "
- + passTC + ",\tFAIL: " + failTC + "\n");
- System.out
- .println("###############################################################################################");
-
- System.out.println("Enter a any key to exit");
- try {
- System.in.read();
- } catch (IOException e) {
- //
- }
-
- }
-
- /**
- * This function reads the files passed as arguments and runs the test cases
- * in the file
- *
- * @param file
- */
- private static void runTestClientOnConfigFile(Path file) {
- String resultReturned, onapComponentName;
- int totalTCforFile = 0, passTCforFile = 0, failTCforFile = 0;
- System.out
- .println("\n###############################################################################################");
- System.out.println("\tRuning test Client on Config file: " + file);
- System.out
- .println("###############################################################################################\n");
-
- if (Files.notExists(file)) {
- System.out.println("file doesnot exist");
- // throw new
- // PolicyEngineException("File doesn't exist in the specified Path "
- // + file.toString());
- } else if (file.toString().endsWith(".testCases")) {
- try {
- // read the json file
- FileReader reader = new FileReader(file.toString());
-
- JSONParser jsonParser = new JSONParser();
- JSONArray jsonObjectArray = (JSONArray) jsonParser
- .parse(reader);
- for (Object jsonObject : jsonObjectArray) {
- totalTC++;
- totalTCforFile++;
- ArrayList<String> expectedResult = new ArrayList<>();
- ArrayList<String> resultReceived = new ArrayList<>();
- JSONObject testCase = (JSONObject) jsonObject;
- // get a String from the JSON object
- long id = (long) testCase.get("id");
- String testFor = (String) testCase.get("testFor");
- String testCaseDescription = (String) testCase
- .get("testCaseDescription");
- JSONArray expectedResultJson = (JSONArray) testCase
- .get("expectedResult");
- @SuppressWarnings("rawtypes")
- Iterator i = expectedResultJson.iterator();
- while (i.hasNext()) {
- expectedResult.add((String) i.next());
- }
- String pdp_urlConfigFile = (String) testCase
- .get("PDP_URLConfigFile");
- // System.out.println(pdp_urlConfigFile);
- PolicyEngine policyEngine;
- try {
- policyEngine = new PolicyEngine(pdp_urlConfigFile);
-
- switch (testFor) {
-
- case "getConfig":
- onapComponentName = (String) testCase
- .get("ONAPName");
- String configName = (String) testCase
- .get("ConfigName");
- Map<String, String> configAttributes = new HashMap<>();
- configAttributes.put("key", "value");
- JSONArray configAttributesJSON = (JSONArray) testCase
- .get("configAttributes");
- if(configAttributesJSON!=null){
- i = configAttributesJSON.iterator();
- while (i.hasNext()) {
- JSONObject innerObj = (JSONObject) i.next();
- configAttributes.put(
- (String) innerObj.get("key"),
- (String) innerObj.get("value"));
-
- }
- }else{
- configAttributes = null;
- }
- resultReceived = PolicyEngineTestClient.getConfig(
- policyEngine, onapComponentName,
- configName, configAttributes);
- Collections.sort(expectedResult);
- Collections.sort(resultReceived);
- resultReturned = compareResults(expectedResult,resultReceived);
- if (resultReturned.equals("PASSED")) {
- printResult(id, testFor, testCaseDescription,
- "PASSED");
- passTCforFile++;
- passTC++;
- } else {
- printResult(id, testFor, testCaseDescription,
- "FAILED", resultReturned);
- failTCforFile++;
- failTC++;
- }
- break;
-
- case "getAction":
- Map<String, String> eventAttributes = new HashMap<>();
- eventAttributes.put("Key", "Value");
- JSONArray eventAttributesJSON = (JSONArray) testCase
- .get("eventAttributes");
- if(eventAttributesJSON != null){
- i = eventAttributesJSON.iterator();
- while (i.hasNext()) {
- JSONObject innerObj = (JSONObject) i.next();
- eventAttributes.put(
- (String) innerObj.get("key"),
- (String) innerObj.get("value"));
- }
- }else{
- eventAttributes=null;
- }
- resultReceived = PolicyEngineTestClient.getAction(
- policyEngine, eventAttributes);
- Collections.sort(expectedResult);
- Collections.sort(resultReceived);
- resultReturned = compareResults(expectedResult,
- resultReceived);
- if (resultReturned.equals("PASSED")) {
- printResult(id, testFor, testCaseDescription,
- "PASSED");
- passTCforFile++;
- passTC++;
- } else {
- printResult(id, testFor, testCaseDescription,
- "FAILED", resultReturned);
- failTCforFile++;
- failTC++;
- }
- break;
-
- case "getDecision":
- onapComponentName = (String) testCase
- .get("ONAPName");
- Map<String, String> decisionAttributes = new HashMap<>();
- decisionAttributes.put("Key", "Value");
- JSONArray decisionAttributesJSON = (JSONArray) testCase
- .get("decisionAttributes");
- i = decisionAttributesJSON.iterator();
- while (i.hasNext()) {
- JSONObject innerObj = (JSONObject) i.next();
- decisionAttributes.put(
- (String) innerObj.get("key"),
- (String) innerObj.get("value"));
-
- }
-
- resultReceived = PolicyEngineTestClient
- .getDecision(policyEngine,
- onapComponentName,
- decisionAttributes);
- Collections.sort(expectedResult);
- Collections.sort(resultReceived);
- resultReturned = compareResults(expectedResult,
- resultReceived);
- if (resultReturned.equals("PASSED")) {
- printResult(id, testFor, testCaseDescription,
- "PASSED");
- passTCforFile++;
- passTC++;
- } else {
- printResult(id, testFor, testCaseDescription,
- "FAILED", resultReturned);
- failTCforFile++;
- failTC++;
- }
- break;
-
- // case "getManualNotification":
- // PolicyEngineTestClient
- // .getManualNotifications(org.onap.policyEngine);
- // break;
- // case "getAutoNotification":
- // PolicyEngineTestClient
- // .getAutoNotifications(org.onap.policyEngine);
- // break;
-
- default:
- printResult(id, testFor, testCaseDescription,
- "FAILED", "\tINVAILD TEST CASE.");
- failTCforFile++;
- failTC++;
- break;
-
- }
- } catch (PolicyEngineException e) {
- printResult(id, testFor, testCaseDescription, "FAILED");
- failTCforFile++;
- failTC++;
- LOGGER.error("Exception Occured"+e);
- } catch (Exception e) {
- printResult(id, testFor, testCaseDescription, "FAILED");
- failTCforFile++;
- failTC++;
- LOGGER.error("Exception Occured"+e);
- }
- }
-
- } catch (FileNotFoundException ex) {
- LOGGER.error("Exception Occured due to File not found"+ex);
- } catch (IOException ex) {
- LOGGER.error("Exception Occured"+ex);
- } catch (NullPointerException ex) {
- LOGGER.error("Exception Occured due to Null Pointer"+ex);
- } catch (org.json.simple.parser.ParseException e) {
- LOGGER.error("Exception Occured while Parsing"+e);
- }
- }
- System.out.println("\n\n\t Summary for the file: TOTAL: "
- + totalTCforFile + ",\tPASS: " + passTCforFile + ",\tFAIL: "
- + failTCforFile + "\n");
- }
-
- /**
- * This function prints the reason if test fails.
- *
- * @param id
- * @param testFor
- * @param testCaseDescription
- * @param passFail
- * @param resultReturned
- */
- private static void printResult(long id, String testFor,
- String testCaseDescription, String passFail, String resultReturned) {
- // TODO Auto-generated method stub
- printResult(id, testFor, testCaseDescription, passFail);
- System.out.println(resultReturned);
-
- }
-
- /**
- * This function prints in output in required format.
- *
- * @param id
- * @param testFor
- * @param testCaseDescription
- * @param result
- */
- private static void printResult(long id, String testFor,
- String testCaseDescription, String result) {
- System.out.println(result + " - Test Case " + id + " - Test type: "
- + testFor + " - " + testCaseDescription);
- }
-
- /**
- * This function compares the required expected output and received output
- * and returns PASS if expected output and received output matches
- *
- * @param expectedResult
- * @param resultReceived
- * @return
- */
- private static String compareResults(ArrayList<String> expectedResult,
- ArrayList<String> resultReceived) {
- // TODO Auto-generated method stub
- String returnString = "";
- int index;
-// System.out.println(expectedResult.size());
-// System.out.println(resultReceived.size());
- for (index = 0; index < expectedResult.size()
- || index < resultReceived.size(); index++) {
- if (index < expectedResult.size() && index < resultReceived.size()) {
- if (!expectedResult.get(index)
- .equals(resultReceived.get(index))) {
- //returnString = "FAILED";
- returnString += "\tExpected Output: "
- + expectedResult.get(index)
- + ",\n\tOutput Received: "
- + resultReceived.get(index)+"\n";
-//
- //System.out.println(resultReceived.get(index));
- }
-
- } else {
- if (index >= expectedResult.size()) {
- returnString += "\tExpected Size of output: "
- + expectedResult.size()
- + ", Size of output received: "
- + resultReceived.size()
- + "\n\tExpected Output: none,\n\tOutput Received: "
- + resultReceived.get(index)+"\n";
-
- } else {
- if (index >= resultReceived.size()) {
- returnString += "\tExpected Size of output: "
- + expectedResult.size()
- + ", Size of output received: "
- + resultReceived.size()
- + "\n\tExpected Output: "
- + expectedResult.get(index)
- + ",\n\tOutput Received: none\n";
-
- }
- }
- }
-
- }
- if(index==expectedResult.size() && index==resultReceived.size() && returnString.equals("")){
- returnString="PASSED";
- }
- return returnString;
-
- }
+
+ private static final Logger LOGGER = FlexLogger.getLogger(GeneralTestClient.class);
+
+ static int totalTC = 0;
+ static int passTC = 0;
+ static int failTC = 0;
+
+ /**
+ * main.
+ *
+ * @param args String[] args
+ */
+ public static void main(String[] args) {
+ Path file;
+ /* command line arguments */
+ if (args.length != 0) {
+ for (int index = 0; index < args.length; index++) {
+ // System.out.println(args[index]);
+ file = Paths.get(args[index]);
+ runTestClientOnConfigFile(file);
+ }
+ } else {
+ /* default file */
+ file = Paths.get("input.testCases");
+ runTestClientOnConfigFile(file);
+ }
+ System.out.println(
+ "###############################################################################################");
+ System.out.println("\n\t SUMMARY: TOTAL: " + totalTC + ",\tPASS: " + passTC + ",\tFAIL: " + failTC + "\n");
+ System.out.println(
+ "###############################################################################################");
+
+ System.out.println("Enter a any key to exit");
+ try {
+ System.in.read();
+ } catch (IOException e) {
+ //
+ }
+
+ }
+
+ /**
+ * This function reads the files passed as arguments and runs the test cases
+ * in the file.
+ *
+ * @param file Path
+ */
+ private static void runTestClientOnConfigFile(Path file) {
+ String resultReturned;
+ String onapComponentName;
+ int totalTCforFile = 0;
+ int passTCforFile = 0;
+ int failTCforFile = 0;
+ System.out.println(
+ "\n###############################################################################################");
+ System.out.println("\tRuning test Client on Config file: " + file);
+ System.out.println(
+ "###############################################################################################\n");
+
+ if (Files.notExists(file)) {
+ System.out.println("file doesnot exist");
+ // throw new
+ // PolicyEngineException("File doesn't exist in the specified Path "
+ // + file.toString());
+ } else if (file.toString().endsWith(".testCases")) {
+ try {
+ // read the json file
+ FileReader reader = new FileReader(file.toString());
+
+ JSONParser jsonParser = new JSONParser();
+ JSONArray jsonObjectArray = (JSONArray) jsonParser.parse(reader);
+ for (Object jsonObject : jsonObjectArray) {
+ totalTC++;
+ totalTCforFile++;
+ ArrayList<String> expectedResult = new ArrayList<>();
+ ArrayList<String> resultReceived = new ArrayList<>();
+ JSONObject testCase = (JSONObject) jsonObject;
+ // get a String from the JSON object
+ long id = (long) testCase.get("id");
+ String testFor = (String) testCase.get("testFor");
+ String testCaseDescription = (String) testCase.get("testCaseDescription");
+ JSONArray expectedResultJson = (JSONArray) testCase.get("expectedResult");
+ @SuppressWarnings("rawtypes")
+ Iterator iter = expectedResultJson.iterator();
+ while (iter.hasNext()) {
+ expectedResult.add((String) iter.next());
+ }
+ String pdpUrlConfigFile = (String) testCase.get("PDP_URLConfigFile");
+ // System.out.println(pdp_urlConfigFile);
+ PolicyEngine policyEngine;
+ try {
+ policyEngine = new PolicyEngine(pdpUrlConfigFile);
+
+ switch (testFor) {
+
+ case "getConfig":
+ onapComponentName = (String) testCase.get("ONAPName");
+ String configName = (String) testCase.get("ConfigName");
+ Map<String, String> configAttributes = new HashMap<>();
+ configAttributes.put("key", "value");
+ JSONArray configAttributesJson = (JSONArray) testCase.get("configAttributes");
+ if (configAttributesJson != null) {
+ iter = configAttributesJson.iterator();
+ while (iter.hasNext()) {
+ JSONObject innerObj = (JSONObject) iter.next();
+ configAttributes.put((String) innerObj.get("key"),
+ (String) innerObj.get("value"));
+
+ }
+ } else {
+ configAttributes = null;
+ }
+ resultReceived = PolicyEngineTestClient.getConfig(policyEngine, onapComponentName,
+ configName, configAttributes);
+ Collections.sort(expectedResult);
+ Collections.sort(resultReceived);
+ resultReturned = compareResults(expectedResult, resultReceived);
+ if (resultReturned.equals("PASSED")) {
+ printResult(id, testFor, testCaseDescription, "PASSED");
+ passTCforFile++;
+ passTC++;
+ } else {
+ printResult(id, testFor, testCaseDescription, "FAILED", resultReturned);
+ failTCforFile++;
+ failTC++;
+ }
+ break;
+
+ case "getAction":
+ Map<String, String> eventAttributes = new HashMap<>();
+ eventAttributes.put("Key", "Value");
+ JSONArray eventAttributesJson = (JSONArray) testCase.get("eventAttributes");
+ if (eventAttributesJson != null) {
+ iter = eventAttributesJson.iterator();
+ while (iter.hasNext()) {
+ JSONObject innerObj = (JSONObject) iter.next();
+ eventAttributes.put((String) innerObj.get("key"),
+ (String) innerObj.get("value"));
+ }
+ } else {
+ eventAttributes = null;
+ }
+ resultReceived = PolicyEngineTestClient.getAction(policyEngine, eventAttributes);
+ Collections.sort(expectedResult);
+ Collections.sort(resultReceived);
+ resultReturned = compareResults(expectedResult, resultReceived);
+ if (resultReturned.equals("PASSED")) {
+ printResult(id, testFor, testCaseDescription, "PASSED");
+ passTCforFile++;
+ passTC++;
+ } else {
+ printResult(id, testFor, testCaseDescription, "FAILED", resultReturned);
+ failTCforFile++;
+ failTC++;
+ }
+ break;
+
+ case "getDecision":
+ onapComponentName = (String) testCase.get("ONAPName");
+ Map<String, String> decisionAttributes = new HashMap<>();
+ decisionAttributes.put("Key", "Value");
+ JSONArray decisionAttributesJson = (JSONArray) testCase.get("decisionAttributes");
+ iter = decisionAttributesJson.iterator();
+ while (iter.hasNext()) {
+ JSONObject innerObj = (JSONObject) iter.next();
+ decisionAttributes.put((String) innerObj.get("key"),
+ (String) innerObj.get("value"));
+
+ }
+
+ resultReceived = PolicyEngineTestClient.getDecision(policyEngine, onapComponentName,
+ decisionAttributes);
+ Collections.sort(expectedResult);
+ Collections.sort(resultReceived);
+ resultReturned = compareResults(expectedResult, resultReceived);
+ if (resultReturned.equals("PASSED")) {
+ printResult(id, testFor, testCaseDescription, "PASSED");
+ passTCforFile++;
+ passTC++;
+ } else {
+ printResult(id, testFor, testCaseDescription, "FAILED", resultReturned);
+ failTCforFile++;
+ failTC++;
+ }
+ break;
+
+ // case "getManualNotification":
+ // PolicyEngineTestClient
+ // .getManualNotifications(org.onap.policyEngine);
+ // break;
+ // case "getAutoNotification":
+ // PolicyEngineTestClient
+ // .getAutoNotifications(org.onap.policyEngine);
+ // break;
+
+ default:
+ printResult(id, testFor, testCaseDescription, "FAILED", "\tINVAILD TEST CASE.");
+ failTCforFile++;
+ failTC++;
+ break;
+
+ }
+ } catch (PolicyEngineException e) {
+ printResult(id, testFor, testCaseDescription, "FAILED");
+ failTCforFile++;
+ failTC++;
+ LOGGER.error("Exception Occured" + e);
+ } catch (Exception e) {
+ printResult(id, testFor, testCaseDescription, "FAILED");
+ failTCforFile++;
+ failTC++;
+ LOGGER.error("Exception Occured" + e);
+ }
+ }
+
+ } catch (FileNotFoundException ex) {
+ LOGGER.error("Exception Occured due to File not found" + ex);
+ } catch (IOException ex) {
+ LOGGER.error("Exception Occured" + ex);
+ } catch (NullPointerException ex) {
+ LOGGER.error("Exception Occured due to Null Pointer" + ex);
+ } catch (org.json.simple.parser.ParseException e) {
+ LOGGER.error("Exception Occured while Parsing" + e);
+ }
+ }
+ System.out.println("\n\n\t Summary for the file: TOTAL: " + totalTCforFile + ",\tPASS: " + passTCforFile
+ + ",\tFAIL: " + failTCforFile + "\n");
+ }
+
+ /**
+ * This function prints the reason if test fails.
+ *
+ * @param id long
+ * @param testFor String
+ * @param testCaseDescription String
+ * @param passFail String
+ * @param resultReturned String
+ */
+ private static void printResult(long id, String testFor, String testCaseDescription, String passFail,
+ String resultReturned) {
+ // TODO Auto-generated method stub
+ printResult(id, testFor, testCaseDescription, passFail);
+ System.out.println(resultReturned);
+
+ }
+
+ /**
+ * This function prints in output in required format.
+ *
+ * @param id long
+ * @param testFor String
+ * @param testCaseDescription String
+ * @param result String
+ */
+ private static void printResult(long id, String testFor, String testCaseDescription, String result) {
+ System.out.println(result + " - Test Case " + id + " - Test type: " + testFor + " - " + testCaseDescription);
+ }
+
+ /**
+ * This function compares the required expected output and received output
+ * and returns PASS if expected output and received output matches.
+ *
+ * @param expectedResult ArrayList of Strings
+ * @param resultReceived ArrayList of Strings
+ * @return String
+ */
+ private static String compareResults(ArrayList<String> expectedResult, ArrayList<String> resultReceived) {
+ // TODO Auto-generated method stub
+ String returnString = "";
+ int index;
+ // System.out.println(expectedResult.size());
+ // System.out.println(resultReceived.size());
+ for (index = 0; index < expectedResult.size() || index < resultReceived.size(); index++) {
+ if (index < expectedResult.size() && index < resultReceived.size()) {
+ if (!expectedResult.get(index).equals(resultReceived.get(index))) {
+ // returnString = "FAILED";
+ returnString += "\tExpected Output: " + expectedResult.get(index) + ",\n\tOutput Received: "
+ + resultReceived.get(index) + "\n";
+ //
+ // System.out.println(resultReceived.get(index));
+ }
+
+ } else {
+ if (index >= expectedResult.size()) {
+ returnString += "\tExpected Size of output: " + expectedResult.size()
+ + ", Size of output received: " + resultReceived.size()
+ + "\n\tExpected Output: none,\n\tOutput Received: " + resultReceived.get(index) + "\n";
+
+ } else {
+ if (index >= resultReceived.size()) {
+ returnString += "\tExpected Size of output: " + expectedResult.size()
+ + ", Size of output received: " + resultReceived.size() + "\n\tExpected Output: "
+ + expectedResult.get(index) + ",\n\tOutput Received: none\n";
+
+ }
+ }
+ }
+
+ }
+ if (index == expectedResult.size() && index == resultReceived.size() && returnString.equals("")) {
+ returnString = "PASSED";
+ }
+ return returnString;
+
+ }
}
diff --git a/PolicyEngineClient/src/test/java/org/onap/policyengine/GetConfigSample.java b/PolicyEngineClient/src/test/java/org/onap/policyengine/GetConfigSample.java
index 94cc69fd7..033eccaad 100644
--- a/PolicyEngineClient/src/test/java/org/onap/policyengine/GetConfigSample.java
+++ b/PolicyEngineClient/src/test/java/org/onap/policyengine/GetConfigSample.java
@@ -2,14 +2,14 @@
* ============LICENSE_START=======================================================
* PolicyEngineClient
* ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017, 2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -28,14 +28,19 @@ import org.onap.policy.api.PolicyEngine;
public class GetConfigSample {
- public static void main(String[] args) throws Exception {
- PolicyEngine pe = new PolicyEngine("config.properties");
- ConfigRequestParameters configRequestParams = new ConfigRequestParameters();
- configRequestParams.setPolicyName(".*");
- Collection<PolicyConfig> configs = pe.getConfig(configRequestParams);
- for (PolicyConfig config: configs){
- System.out.println(config.getPolicyConfigMessage());
- System.out.println(config.getPolicyConfigStatus());
- }
- }
+ /**
+ * main.
+ *
+ * @param args String[] args
+ */
+ public static void main(String[] args) throws Exception {
+ PolicyEngine pe = new PolicyEngine("config.properties");
+ ConfigRequestParameters configRequestParams = new ConfigRequestParameters();
+ configRequestParams.setPolicyName(".*");
+ Collection<PolicyConfig> configs = pe.getConfig(configRequestParams);
+ for (PolicyConfig config : configs) {
+ System.out.println(config.getPolicyConfigMessage());
+ System.out.println(config.getPolicyConfigStatus());
+ }
+ }
}
diff --git a/PolicyEngineClient/src/test/java/org/onap/policyengine/Handler.java b/PolicyEngineClient/src/test/java/org/onap/policyengine/Handler.java
index 12fca6e93..243c86021 100644
--- a/PolicyEngineClient/src/test/java/org/onap/policyengine/Handler.java
+++ b/PolicyEngineClient/src/test/java/org/onap/policyengine/Handler.java
@@ -2,14 +2,14 @@
* ============LICENSE_START=======================================================
* PolicyEngineClient
* ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017, 2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -35,93 +35,93 @@ 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{
+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<PolicyConfig> 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<PolicyConfig> 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);
- }
- }
- }
- }
+ 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<PolicyConfig> 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<PolicyConfig> 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/PolicyEngineClient/src/test/java/org/onap/policyengine/ImportBRMSTemplate.java b/PolicyEngineClient/src/test/java/org/onap/policyengine/ImportBRMSTemplate.java
index 20175b28d..9f132d36b 100644
--- a/PolicyEngineClient/src/test/java/org/onap/policyengine/ImportBRMSTemplate.java
+++ b/PolicyEngineClient/src/test/java/org/onap/policyengine/ImportBRMSTemplate.java
@@ -2,14 +2,14 @@
* ============LICENSE_START=======================================================
* PolicyEngineClient
* ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017, 2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -24,27 +24,32 @@ import java.io.File;
import java.util.UUID;
import org.onap.policy.api.ImportParameters;
+import org.onap.policy.api.ImportParameters.IMPORT_TYPE;
import org.onap.policy.api.PolicyChangeResponse;
import org.onap.policy.api.PolicyEngine;
-import org.onap.policy.api.ImportParameters.IMPORT_TYPE;
public class ImportBRMSTemplate {
- public static void main(String[] args) {
- try{
- PolicyEngine policyEngine = new PolicyEngine("config.properties");
- ImportParameters importParameters = new ImportParameters();
- importParameters.setFilePath("testResources"+File.separator+"test.drl");
- importParameters.setServiceName("testTemplate");
- importParameters.setRequestID(UUID.randomUUID());
- importParameters.setServiceType(IMPORT_TYPE.BRMSPARAM);
+
+ /**
+ * main.
+ *
+ * @param args String[] args
+ */
+ public static void main(String[] args) {
+ try {
+ ImportParameters importParameters = new ImportParameters();
+ importParameters.setFilePath("resources" + File.separator + "test.drl");
+ importParameters.setServiceName("testTemplate");
+ importParameters.setRequestID(UUID.randomUUID());
+ importParameters.setServiceType(IMPORT_TYPE.BRMSPARAM);
// API method to create Policy or update policy
- PolicyChangeResponse response = null;
- response = policyEngine.policyEngineImport(importParameters);
+ PolicyEngine policyEngine = new PolicyEngine("config.properties");
+ PolicyChangeResponse response = policyEngine.policyEngineImport(importParameters);
System.out.println(response.getResponseMessage());
- } catch (Exception e) {
- System.err.println(e.getMessage());
- }
- }
+ } catch (Exception e) {
+ System.err.println(e.getMessage());
+ }
+ }
}
diff --git a/PolicyEngineClient/src/test/java/org/onap/policyengine/ImportMicroServiceClient.java b/PolicyEngineClient/src/test/java/org/onap/policyengine/ImportMicroServiceClient.java
index 86439583a..377dfcbb5 100644
--- a/PolicyEngineClient/src/test/java/org/onap/policyengine/ImportMicroServiceClient.java
+++ b/PolicyEngineClient/src/test/java/org/onap/policyengine/ImportMicroServiceClient.java
@@ -2,14 +2,14 @@
* ============LICENSE_START=======================================================
* PolicyEngineClient
* ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017, 2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -28,26 +28,33 @@ import org.onap.policy.api.PolicyChangeResponse;
import org.onap.policy.api.PolicyEngine;
public class ImportMicroServiceClient {
- static Boolean isEdit = false;
- public static void main(String[] args) {
- try{
- PolicyEngine policyEngine = new PolicyEngine("config.properties");
- ImportParameters importParameters = new ImportParameters();
- 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");
+ static Boolean isEdit = false;
+
+ /**
+ * main.
+ *
+ * @param args String[] args
+ */
+ public static void main(String[] args) {
+ try {
+ ImportParameters importParameters = new ImportParameters();
+ 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");
// API method to create Policy or update policy
- PolicyChangeResponse response = null;
+ PolicyChangeResponse response = null;
+ PolicyEngine policyEngine = new PolicyEngine("config.properties");
response = policyEngine.policyEngineImport(importParameters);
System.out.println(response.getResponseMessage());
- } catch (Exception e) {
- System.err.println(e.getMessage());
- }
- }
-
+ } catch (Exception e) {
+ System.err.println(e.getMessage());
+ }
+ }
+
}
diff --git a/PolicyEngineClient/src/test/java/org/onap/policyengine/ListConfigPoliciesClient.java b/PolicyEngineClient/src/test/java/org/onap/policyengine/ListConfigPoliciesClient.java
index 9973ce70c..c56a234ca 100644
--- a/PolicyEngineClient/src/test/java/org/onap/policyengine/ListConfigPoliciesClient.java
+++ b/PolicyEngineClient/src/test/java/org/onap/policyengine/ListConfigPoliciesClient.java
@@ -2,14 +2,14 @@
* ============LICENSE_START=======================================================
* PolicyEngineClient
* ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017, 2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -33,44 +33,49 @@ import org.onap.policy.common.logging.flexlogger.FlexLogger;
import org.onap.policy.common.logging.flexlogger.Logger;
public class ListConfigPoliciesClient {
-
- private static final Logger LOGGER = FlexLogger.getLogger(ListConfigPoliciesClient.class);
-
- public static void main(String[] args) {
- PolicyEngine policyEngine;
- // List Config Policies Example
- try {
- policyEngine = new PolicyEngine("config.properties");
- ConfigRequestParameters parameters = new ConfigRequestParameters();
-
- parameters.setPolicyName(".*");
- parameters.setOnapName(".*");
- parameters.setConfigName(".*");
-
- Map<String, String> configAttributes = new HashMap<>();
- configAttributes.put("java", "java");
- configAttributes.put("peach", "Tar");
- configAttributes.put("true", "false");
- configAttributes.put("small", "testPass");
- parameters.setConfigAttributes(configAttributes);
-
- parameters.setRequestID(UUID.randomUUID());
-
- Collection<String> response = policyEngine.listConfig(parameters);
- if(response!=null && !response.contains("PE300")){
- for(String configList : response){
- System.out.println(configList.toString()+"\n");
- }
- }else{
- System.out.println("Error! " +response);
- }
+ private static final Logger LOGGER = FlexLogger.getLogger(ListConfigPoliciesClient.class);
+
+ /**
+ * main.
+ *
+ * @param args String[] args
+ */
+ public static void main(String[] args) {
+ PolicyEngine policyEngine;
+
+ // List Config Policies Example
+ try {
+ policyEngine = new PolicyEngine("config.properties");
+ ConfigRequestParameters parameters = new ConfigRequestParameters();
+
+ parameters.setPolicyName(".*");
+ parameters.setOnapName(".*");
+ parameters.setConfigName(".*");
+
+ Map<String, String> configAttributes = new HashMap<>();
+ configAttributes.put("java", "java");
+ configAttributes.put("peach", "Tar");
+ configAttributes.put("true", "false");
+ configAttributes.put("small", "testPass");
+ parameters.setConfigAttributes(configAttributes);
+
+ parameters.setRequestID(UUID.randomUUID());
+
+ Collection<String> response = policyEngine.listConfig(parameters);
+ if (response != null && !response.contains("PE300")) {
+ for (String configList : response) {
+ System.out.println(configList.toString() + "\n");
+ }
+ } else {
+ System.out.println("Error! " + response);
+ }
+
+ } catch (PolicyConfigException e) {
+ LOGGER.error("Exception Occured" + e);
+ } catch (PolicyEngineException e) {
+ LOGGER.error("Exception Occured" + e);
+ }
+ }
- } catch (PolicyConfigException e) {
- LOGGER.error("Exception Occured"+e);
- } catch (PolicyEngineException e) {
- LOGGER.error("Exception Occured"+e);
- }
- }
-
}
diff --git a/PolicyEngineClient/src/test/java/org/onap/policyengine/ListPolicyClient.java b/PolicyEngineClient/src/test/java/org/onap/policyengine/ListPolicyClient.java
index 785c44d11..d2e6d706b 100644
--- a/PolicyEngineClient/src/test/java/org/onap/policyengine/ListPolicyClient.java
+++ b/PolicyEngineClient/src/test/java/org/onap/policyengine/ListPolicyClient.java
@@ -21,6 +21,7 @@
package org.onap.policyengine;
import java.util.Collection;
+
import org.onap.policy.api.ConfigNameRequest;
import org.onap.policy.api.PolicyEngine;
@@ -30,6 +31,12 @@ import org.onap.policy.api.PolicyEngine;
* (active version)
*/
public class ListPolicyClient {
+
+ /**
+ * main.
+ *
+ * @param args String[] args
+ */
public static void main(String[] args) throws Exception {
PolicyEngine pe = new PolicyEngine("config.properties");
ConfigNameRequest listPolicyParams = new ConfigNameRequest();
diff --git a/PolicyEngineClient/src/test/java/org/onap/policyengine/MainClient.java b/PolicyEngineClient/src/test/java/org/onap/policyengine/MainClient.java
index 210499ca1..dfd06e51e 100644
--- a/PolicyEngineClient/src/test/java/org/onap/policyengine/MainClient.java
+++ b/PolicyEngineClient/src/test/java/org/onap/policyengine/MainClient.java
@@ -2,14 +2,14 @@
* ============LICENSE_START=======================================================
* PolicyEngineClient
* ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017, 2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -46,80 +46,93 @@ import org.onap.policy.common.logging.flexlogger.Logger;
import org.w3c.dom.Document;
public class MainClient {
-
- private static final Logger LOGGER = FlexLogger.getLogger(MainClient.class);
-
- public static void main(String[] args) {
- PolicyEngine policyEngine;
- try {
- policyEngine = new PolicyEngine("config.properties");
- Map<String, String> configAttributes = new HashMap<>();
- configAttributes.put("java", "java");
- configAttributes.put("peach", "Tar");
- configAttributes.put("true", "false");
- configAttributes.put("small", "testPass");
- Map<String, String> eventAttributes = new HashMap<>();
- eventAttributes.put("true", "true");
- eventAttributes.put("cpu", "91");
- Map<String, String> decisionAttributes = new HashMap<>();
- decisionAttributes.put("Key", "Value");
-
- // Config Example
- try {
- @SuppressWarnings("deprecation")
- Collection<PolicyConfig> policyConfigs = policyEngine.getConfigByPolicyName(".*");//(onapComponentName, configName, configAttributes);
- if(policyConfigs!=null && !policyConfigs.isEmpty()){
- for(PolicyConfig policyConfig: policyConfigs){
- System.out.println("\nConfig Message: "+ policyConfig.getPolicyConfigMessage());
- System.out.println("Config Status: " + policyConfig.getPolicyConfigStatus());
- System.out.println("Policy Name: "+ policyConfig.getPolicyName());
- System.out.println("policy Version: " + policyConfig.getPolicyVersion());
- }
- }
- } catch (PolicyConfigException e) {
- LOGGER.error("Exception Occured"+e);
- }
-
- // Manual Notifications..
- policyEngine.setScheme(NotificationScheme.MANUAL_ALL_NOTIFICATIONS);
- if(policyEngine.getNotification()!=null){
- System.out.println(policyEngine.getNotification().getNotificationType());
- for(LoadedPolicy updated: policyEngine.getNotification().getLoadedPolicies()){
- System.out.println(updated.getPolicyName());
- System.out.println(updated.getVersionNo());
- System.out.println(updated.getMatches());
- }
- for(RemovedPolicy removed: policyEngine.getNotification().getRemovedPolicies()){
- System.out.println(removed.getPolicyName());
- System.out.println(removed.getVersionNo());
- }
- }
- // Auto Notifications..
- Handler handler = new Handler();
- policyEngine.setNotification(NotificationScheme.AUTO_ALL_NOTIFICATIONS, handler);
- //
- System.out.println("Enter a any key to exit");
- try {
- System.in.read();
- } catch (IOException e) {
- System.err.println("Exception Occured"+e);
- }
-
- } catch (PolicyEngineException e1) {
- System.err.println("Exception Occured"+e1);
- }
- }
-
- public static void printDocument(Document doc, OutputStream out) throws IOException, TransformerException {
- TransformerFactory tf = TransformerFactory.newInstance();
- Transformer transformer = tf.newTransformer();
- transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
- transformer.setOutputProperty(OutputKeys.METHOD, "xml");
- transformer.setOutputProperty(OutputKeys.INDENT, "yes");
- transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
- transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
- transformer.transform(new DOMSource(doc),
- new StreamResult(new OutputStreamWriter(out, "UTF-8")));
- }
+ private static final Logger LOGGER = FlexLogger.getLogger(MainClient.class);
+
+ /**
+ * main.
+ *
+ * @param args String[] args
+ */
+ public static void main(String[] args) {
+ PolicyEngine policyEngine;
+ try {
+ policyEngine = new PolicyEngine("config.properties");
+ Map<String, String> configAttributes = new HashMap<>();
+ configAttributes.put("java", "java");
+ configAttributes.put("peach", "Tar");
+ configAttributes.put("true", "false");
+ configAttributes.put("small", "testPass");
+ Map<String, String> eventAttributes = new HashMap<>();
+ eventAttributes.put("true", "true");
+ eventAttributes.put("cpu", "91");
+ Map<String, String> decisionAttributes = new HashMap<>();
+ decisionAttributes.put("Key", "Value");
+
+ // Config Example
+ try {
+ @SuppressWarnings("deprecation")
+ Collection<PolicyConfig> policyConfigs = policyEngine.getConfigByPolicyName(".*");
+ if (policyConfigs != null && !policyConfigs.isEmpty()) {
+ for (PolicyConfig policyConfig : policyConfigs) {
+ System.out.println("\nConfig Message: " + policyConfig.getPolicyConfigMessage());
+ System.out.println("Config Status: " + policyConfig.getPolicyConfigStatus());
+ System.out.println("Policy Name: " + policyConfig.getPolicyName());
+ System.out.println("policy Version: " + policyConfig.getPolicyVersion());
+ }
+ }
+ } catch (PolicyConfigException e) {
+ LOGGER.error("Exception Occured" + e);
+ }
+
+ // Manual Notifications..
+ policyEngine.setScheme(NotificationScheme.MANUAL_ALL_NOTIFICATIONS);
+ if (policyEngine.getNotification() != null) {
+ System.out.println(policyEngine.getNotification().getNotificationType());
+ for (LoadedPolicy updated : policyEngine.getNotification().getLoadedPolicies()) {
+ System.out.println(updated.getPolicyName());
+ System.out.println(updated.getVersionNo());
+ System.out.println(updated.getMatches());
+ }
+ for (RemovedPolicy removed : policyEngine.getNotification().getRemovedPolicies()) {
+ System.out.println(removed.getPolicyName());
+ System.out.println(removed.getVersionNo());
+ }
+ }
+ // Auto Notifications..
+ Handler handler = new Handler();
+ policyEngine.setNotification(NotificationScheme.AUTO_ALL_NOTIFICATIONS, handler);
+ //
+ System.out.println("Enter a any key to exit");
+ try {
+ System.in.read();
+ } catch (IOException e) {
+ System.err.println("Exception Occured" + e);
+ }
+
+ } catch (PolicyEngineException e1) {
+ System.err.println("Exception Occured" + e1);
+ }
+ }
+
+ /**
+ * printDocument.
+ *
+ * @param doc Document
+ * @param out OutputStream
+ * @throws IOException IOException
+ * @throws TransformerException TransformerException
+ */
+ public static void printDocument(Document doc, OutputStream out)
+ throws IOException, TransformerException {
+ TransformerFactory tf = TransformerFactory.newInstance();
+ Transformer transformer = tf.newTransformer();
+ transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
+ transformer.setOutputProperty(OutputKeys.METHOD, "xml");
+ transformer.setOutputProperty(OutputKeys.INDENT, "yes");
+ transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
+ transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
+
+ transformer.transform(new DOMSource(doc), new StreamResult(new OutputStreamWriter(out, "UTF-8")));
+ }
}
diff --git a/PolicyEngineClient/src/test/java/org/onap/policyengine/MicroServicesPolicyClient.java b/PolicyEngineClient/src/test/java/org/onap/policyengine/MicroServicesPolicyClient.java
index b05e44726..d592e7c5a 100644
--- a/PolicyEngineClient/src/test/java/org/onap/policyengine/MicroServicesPolicyClient.java
+++ b/PolicyEngineClient/src/test/java/org/onap/policyengine/MicroServicesPolicyClient.java
@@ -2,14 +2,14 @@
* ============LICENSE_START=======================================================
* PolicyEngineClient
* ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017, 2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -31,6 +31,7 @@ import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;
+
import javax.json.Json;
import javax.json.JsonObject;
import javax.json.JsonReader;
@@ -40,88 +41,89 @@ import org.onap.policy.api.PolicyConfigType;
import org.onap.policy.api.PolicyEngine;
import org.onap.policy.api.PolicyParameters;
import org.onap.policy.api.PolicyType;
+
public class MicroServicesPolicyClient {
-
-//For updating a Micro Services policy set the "isEdit" flag to true.
-//For creating a Micro Services policy set the "isEdit" flag to false.
-static Boolean isEdit = false;
-
-//Builds JSONObject from File
-private static JsonObject buildJSON(File jsonInput, String jsonString) throws FileNotFoundException {
- JsonObject json = null;;
- JsonReader jsonReader = null;
- if (jsonString != null && jsonInput == null) {
- StringReader in = null;
+
+ // For updating a Micro Services policy set the "isEdit" flag to true.
+ // For creating a Micro Services policy set the "isEdit" flag to false.
+ static Boolean isEdit = false;
+
+ // Builds JSONObject from File
+ private static JsonObject buildJson(File jsonInput, String jsonString) throws FileNotFoundException {
+ JsonObject json = null;;
+ JsonReader jsonReader = null;
+ if (jsonString != null && jsonInput == null) {
+ StringReader in = null;
in = new StringReader(jsonString);
jsonReader = Json.createReader(in);
json = jsonReader.readObject();
in.close();
+ } else {
+ InputStream in = null;
+ in = new FileInputStream(jsonInput);
+ jsonReader = Json.createReader(in);
+ json = jsonReader.readObject();
+ try {
+ in.close();
+ } catch (IOException e) {
+ System.err.println("Exception Occured while closing input stream" + e);
+ }
+ }
+ jsonReader.close();
+ return json;
}
- else {
- InputStream in = null;
- in = new FileInputStream(jsonInput);
- jsonReader = Json.createReader(in);
- json = jsonReader.readObject();
+
+ /**
+ * main.
+ *
+ * @param args String[] args
+ */
+ public static void main(String[] args) {
try {
- in.close();
- } catch (IOException e) {
- System.err.println("Exception Occured while closing input stream"+e);
- }
- }
- jsonReader.close();
- return json;
-}
-public static void main(String[] args) {
- try {
- PolicyEngine policyEngine = new PolicyEngine("config.properties");
- PolicyParameters policyParameters = new PolicyParameters();
- // Set Policy Type
- policyParameters.setPolicyConfigType(PolicyConfigType.MicroService);
- policyParameters.setPolicyName("Katrina.configuration_dcae_microservice_stringmatcher");
- //policyParameters.setPolicyDescription("This is a sample Micro Service policy Create example");
- policyParameters.setOnapName("DCAE");
- //policyParameters.setConfigName("Collector");
- //policyParameters.setPriority("1");
- //policyParameters.setPolicyScope("service=vSCP;resource=F5;type=configuration;closedLoopControlName=vSCP_F5_Firewall_d925ed73-8231-4d02-9545-db4e113213abab322");
-
- // Set up Micro Services Attributes
- File jsonFile = null;
- String MSjsonString= null;
- Path file = Paths.get("C:\\policyAPI\\MicroServicesJSON\\testStringMatching.json");
- jsonFile = file.toFile();
-
- policyParameters.setConfigBody(buildJSON(jsonFile, MSjsonString).toString());
- policyParameters.setConfigBodyType(PolicyType.JSON);
+ PolicyEngine policyEngine = new PolicyEngine("config.properties");
+ PolicyParameters policyParameters = new PolicyParameters();
+ // Set Policy Type
+ policyParameters.setPolicyConfigType(PolicyConfigType.MicroService);
+ policyParameters.setPolicyName("Katrina.configuration_dcae_microservice_stringmatcher");
+ policyParameters.setOnapName("DCAE");
+
+ // Set up Micro Services Attributes
+ File jsonFile = null;
+ String msJsonString = null;
+ Path file = Paths.get("C:\\policyAPI\\MicroServicesJSON\\testStringMatching.json");
+ jsonFile = file.toFile();
- policyParameters.setRequestID(UUID.randomUUID());
+ policyParameters.setConfigBody(buildJson(jsonFile, msJsonString).toString());
+ policyParameters.setConfigBodyType(PolicyType.JSON);
+
+ policyParameters.setRequestID(UUID.randomUUID());
+ // Set Safe Policy value for Risk Type
+ SimpleDateFormat dateformat3 = new SimpleDateFormat("dd/MM/yyyy");
+ Date date = dateformat3.parse("15/10/2016");
+ policyParameters.setTtlDate(date);
+ // Set Safe Policy value for Guard
+ policyParameters.setGuard(true);
+ // Set Safe Policy value for Risk Level
+ policyParameters.setRiskLevel("5");
// Set Safe Policy value for Risk Type
- SimpleDateFormat dateformat3 = new SimpleDateFormat("dd/MM/yyyy");
- Date date = dateformat3.parse("15/10/2016");
- policyParameters.setTtlDate(date);
- // Set Safe Policy value for Guard
- policyParameters.setGuard(true);
- // Set Safe Policy value for Risk Level
- policyParameters.setRiskLevel("5");
- // Set Safe Policy value for Risk Type
- policyParameters.setRiskType("PROD");
-
- // API method to create or update Policy.
- PolicyChangeResponse response = null;
- if (!isEdit) {
- response = policyEngine.createPolicy(policyParameters);
- }
- else {
- response = policyEngine.updatePolicy(policyParameters);
- }
-
- if(response.getResponseCode()==200){
- System.out.println(response.getResponseMessage());
- System.out.println("Policy Created Successfully!");
- }else{
- System.out.println("Error! " + response.getResponseMessage());
- }
- } catch (Exception e) {
- System.err.println(e.getMessage());
- }
- }
+ policyParameters.setRiskType("PROD");
+
+ // API method to create or update Policy.
+ PolicyChangeResponse response = null;
+ if (!isEdit) {
+ response = policyEngine.createPolicy(policyParameters);
+ } else {
+ response = policyEngine.updatePolicy(policyParameters);
+ }
+
+ if (response.getResponseCode() == 200) {
+ System.out.println(response.getResponseMessage());
+ System.out.println("Policy Created Successfully!");
+ } else {
+ System.out.println("Error! " + response.getResponseMessage());
+ }
+ } catch (Exception e) {
+ System.err.println(e.getMessage());
+ }
+ }
}
diff --git a/PolicyEngineClient/src/test/java/org/onap/policyengine/OptimizationPolicyJavaAPIClient.java b/PolicyEngineClient/src/test/java/org/onap/policyengine/OptimizationPolicyJavaAPIClient.java
index 090ec39de..1d765c3c9 100644
--- a/PolicyEngineClient/src/test/java/org/onap/policyengine/OptimizationPolicyJavaAPIClient.java
+++ b/PolicyEngineClient/src/test/java/org/onap/policyengine/OptimizationPolicyJavaAPIClient.java
@@ -2,14 +2,14 @@
* ============LICENSE_START=======================================================
* PolicyEngineClient
* ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017, 2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -31,6 +31,7 @@ import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;
+
import javax.json.Json;
import javax.json.JsonObject;
import javax.json.JsonReader;
@@ -40,89 +41,94 @@ import org.onap.policy.api.PolicyConfigType;
import org.onap.policy.api.PolicyEngine;
import org.onap.policy.api.PolicyParameters;
import org.onap.policy.api.PolicyType;
+
public class OptimizationPolicyJavaAPIClient {
-
-/*
- * THIS IS AN EXAMPLE JAVA CLIENT API FOR CREATE/UPDATE Optimization Policies
- */
-//For updating a Optmization policy set the "isEdit" flag to true.
-//For creating a Optmization policy set the "isEdit" flag to false.
-static Boolean isEdit = false;
-
-//Builds JSONObject from File
-private static JsonObject buildJSON(File jsonInput, String jsonString) throws FileNotFoundException {
- JsonObject json = null;;
- JsonReader jsonReader = null;
- if (jsonString != null && jsonInput == null) {
- StringReader in = null;
+
+ /*
+ * THIS IS AN EXAMPLE JAVA CLIENT API FOR CREATE/UPDATE Optimization Policies
+ */
+ // For updating a Optmization policy set the "isEdit" flag to true.
+ // For creating a Optmization policy set the "isEdit" flag to false.
+ static Boolean isEdit = false;
+
+ // Builds JSONObject from File
+ private static JsonObject buildJson(File jsonInput, String jsonString) throws FileNotFoundException {
+ JsonObject json = null;;
+ JsonReader jsonReader = null;
+ if (jsonString != null && jsonInput == null) {
+ StringReader in = null;
in = new StringReader(jsonString);
jsonReader = Json.createReader(in);
json = jsonReader.readObject();
in.close();
+ } else {
+ InputStream in = null;
+ in = new FileInputStream(jsonInput);
+ jsonReader = Json.createReader(in);
+ json = jsonReader.readObject();
+ try {
+ in.close();
+ } catch (IOException e) {
+ System.err.println("Exception Occured while closing input stream" + e);
+ }
+ }
+ jsonReader.close();
+ return json;
}
- else {
- InputStream in = null;
- in = new FileInputStream(jsonInput);
- jsonReader = Json.createReader(in);
- json = jsonReader.readObject();
+
+ /**
+ * main.
+ *
+ * @param args String[] args
+ */
+ public static void main(String[] args) {
try {
- in.close();
- } catch (IOException e) {
- System.err.println("Exception Occured while closing input stream"+e);
- }
- }
- jsonReader.close();
- return json;
-}
-public static void main(String[] args) {
- try {
- PolicyEngine policyEngine = new PolicyEngine("config.properties");
- PolicyParameters policyParameters = new PolicyParameters();
- // Set Policy Type
- policyParameters.setPolicyConfigType(PolicyConfigType.Optimization);
- policyParameters.setPolicyName("Mike.testOOFPolicyFromJavaClient");
- policyParameters.setPolicyDescription("This is a sample Optimization policy");
- policyParameters.setOnapName("OOF");
+ PolicyEngine policyEngine = new PolicyEngine("config.properties");
+ PolicyParameters policyParameters = new PolicyParameters();
+ // Set Policy Type
+ policyParameters.setPolicyConfigType(PolicyConfigType.Optimization);
+ policyParameters.setPolicyName("Mike.testOOFPolicyFromJavaClient");
+ policyParameters.setPolicyDescription("This is a sample Optimization policy");
+ policyParameters.setOnapName("OOF");
+
+ File jsonFile = null;
+ String oofJsonString = null;
+
+ // path where you store the json payload
+ Path file = Paths.get("/home/users/PolicyEngine/json/optimizationPolicy.json");
+ jsonFile = file.toFile();
- File jsonFile = null;
- String OOFjsonString= null;
-
- //path where you store the json payload
- Path file = Paths.get("/home/users/PolicyEngine/json/optimizationPolicy.json");
- jsonFile = file.toFile();
-
- policyParameters.setConfigBody(buildJSON(jsonFile, OOFjsonString).toString());
- policyParameters.setConfigBodyType(PolicyType.JSON);
+ policyParameters.setConfigBody(buildJson(jsonFile, oofJsonString).toString());
+ policyParameters.setConfigBodyType(PolicyType.JSON);
- policyParameters.setRequestID(UUID.randomUUID());
+ policyParameters.setRequestID(UUID.randomUUID());
// Set Safe Policy value for Risk Type
- SimpleDateFormat dateformat3 = new SimpleDateFormat("dd/MM/yyyy");
- Date date = dateformat3.parse("15/10/2016");
- policyParameters.setTtlDate(date);
- // Set Safe Policy value for Guard
- policyParameters.setGuard(false);
- // Set Safe Policy value for Risk Level
- policyParameters.setRiskLevel("5");
- // Set Safe Policy value for Risk Type
- policyParameters.setRiskType("TEST");
-
- // API method to create or update Policy.
- PolicyChangeResponse response = null;
- if (!isEdit) {
- response = policyEngine.createPolicy(policyParameters);
- }
- else {
- response = policyEngine.updatePolicy(policyParameters);
- }
-
- if(response.getResponseCode()==200){
- System.out.println(response.getResponseMessage());
- System.out.println("Policy Created Successfully!");
- }else{
- System.out.println("Error! " + response.getResponseMessage());
- }
- } catch (Exception e) {
- System.err.println(e.getMessage());
- }
- }
+ SimpleDateFormat dateformat3 = new SimpleDateFormat("dd/MM/yyyy");
+ Date date = dateformat3.parse("15/10/2016");
+ policyParameters.setTtlDate(date);
+ // Set Safe Policy value for Guard
+ policyParameters.setGuard(false);
+ // Set Safe Policy value for Risk Level
+ policyParameters.setRiskLevel("5");
+ // Set Safe Policy value for Risk Type
+ policyParameters.setRiskType("TEST");
+
+ // API method to create or update Policy.
+ PolicyChangeResponse response = null;
+ if (!isEdit) {
+ response = policyEngine.createPolicy(policyParameters);
+ } else {
+ response = policyEngine.updatePolicy(policyParameters);
+ }
+
+ if (response.getResponseCode() == 200) {
+ System.out.println(response.getResponseMessage());
+ System.out.println("Policy Created Successfully!");
+ } else {
+ System.out.println("Error! " + response.getResponseMessage());
+ }
+ } catch (Exception e) {
+ System.err.println(e.getMessage());
+ }
+ }
}
diff --git a/PolicyEngineClient/src/test/java/org/onap/policyengine/PolicyEngineTestClient.java b/PolicyEngineClient/src/test/java/org/onap/policyengine/PolicyEngineTestClient.java
index 9ce4a2a22..9e055ebb1 100644
--- a/PolicyEngineClient/src/test/java/org/onap/policyengine/PolicyEngineTestClient.java
+++ b/PolicyEngineClient/src/test/java/org/onap/policyengine/PolicyEngineTestClient.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -17,6 +17,7 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.policyengine;
import java.io.IOException;
@@ -39,155 +40,143 @@ import org.onap.policy.api.RemovedPolicy;
/**
* Class contains static functions which make call to policy engine using API.
* This class is used by generalTestClient.java
- *
- *
+ *
+ *
* @version 1.0
*
*/
public class PolicyEngineTestClient {
- /**
- * This fuction make API call to policy engine to get config. And returns
- * policy name, policy version and policy configStatus
- *
- * @param org.onap.policyEngine
- * @param onapComponentName
- * @param configName
- * @param configAttributes
- * @return
- */
+ /**
+ * This function make API call to policy engine to get config. And returns
+ * policy name, policy version and policy configStatus
+ *
+ * @param policyEngine Policy Engine object
+ * @param onapComponentName String
+ * @param configName String
+ * @param configAttributes Map of String to String
+ * @return ArrayList of String
+ */
+
+ @SuppressWarnings("deprecation")
+ public static ArrayList<String> getConfig(PolicyEngine policyEngine, String onapComponentName, String configName,
+ Map<String, String> configAttributes) {
+ ArrayList<String> resultReceived = new ArrayList<>();
+ try {
+ UUID requestID = UUID.randomUUID();
+ Collection<PolicyConfig> policyConfigs;
+ if (configName == null) {
+ policyConfigs = policyEngine.getConfig(onapComponentName, requestID);
+ } else {
+ if (configAttributes == null) {
+ policyConfigs = policyEngine.getConfig(onapComponentName, configName, requestID);
+ } else {
- @SuppressWarnings("deprecation")
- public static ArrayList<String> getConfig(PolicyEngine policyEngine,
- String onapComponentName, String configName,
- Map<String, String> configAttributes) {
- ArrayList<String> resultReceived = new ArrayList<>();
- try {
- UUID requestID = UUID.randomUUID();
- Collection<PolicyConfig> policyConfigs;
- if (configName == null) {
- policyConfigs = policyEngine.getConfig(onapComponentName, requestID);
- } else {
- if (configAttributes == null) {
- policyConfigs = policyEngine.getConfig(onapComponentName,
- configName, requestID);
- } else {
-
- policyConfigs = policyEngine.getConfig(onapComponentName,
- configName, configAttributes, requestID);
- }
- }
- if (policyConfigs != null && !policyConfigs.isEmpty()) {
- for (PolicyConfig policyConfig : policyConfigs) {
- resultReceived.add("Policy Name: "
- + policyConfig.getPolicyName()
- + " Policy version: "
- + policyConfig.getPolicyVersion() + " - "
- + policyConfig.getPolicyConfigStatus());
- }
- }
- } catch (PolicyConfigException e) {
-// logger.error("Exception Occured"+e);
- resultReceived.add(""+e);
- }
- return resultReceived;
- }
+ policyConfigs = policyEngine.getConfig(onapComponentName, configName, configAttributes, requestID);
+ }
+ }
+ if (policyConfigs != null && !policyConfigs.isEmpty()) {
+ for (PolicyConfig policyConfig : policyConfigs) {
+ resultReceived.add("Policy Name: " + policyConfig.getPolicyName() + " Policy version: "
+ + policyConfig.getPolicyVersion() + " - " + policyConfig.getPolicyConfigStatus());
+ }
+ }
+ } catch (PolicyConfigException e) {
+ // logger.error("Exception Occured"+e);
+ resultReceived.add("" + e);
+ }
+ return resultReceived;
+ }
- /**
- * This functions make API call to policy engine to get decision. And
- * returns policy Decision
- *
- * @param org.onap.policyEngine
- * @param onapComponentName
- * @param decisionAttributes
- * @return
- */
- public static ArrayList<String> getDecision(PolicyEngine policyEngine,
- String onapComponentName, Map<String, String> decisionAttributes) {
- ArrayList<String> resultReceived = new ArrayList<>();
- // Decision example
- try {
- UUID requestID = UUID.randomUUID();
- @SuppressWarnings("deprecation")
- DecisionResponse policyDecision = policyEngine.getDecision(
- onapComponentName, decisionAttributes, requestID);
- resultReceived.add(policyDecision.getDecision().toString());
- } catch (PolicyDecisionException e) {
-// logger.error("Exception Occured"+e);
- resultReceived.add(""+e);
- }
- return resultReceived;
- }
+ /**
+ * This functions make API call to policy engine to get decision. And
+ * returns policy Decision
+ *
+ * @param policyEngine Policy Engine
+ * @param onapComponentName String
+ * @param decisionAttributes Map of String
+ * @return List of String
+ */
+ public static ArrayList<String> getDecision(PolicyEngine policyEngine, String onapComponentName,
+ Map<String, String> decisionAttributes) {
+ ArrayList<String> resultReceived = new ArrayList<>();
+ // Decision example
+ try {
+ UUID requestID = UUID.randomUUID();
+ @SuppressWarnings("deprecation")
+ DecisionResponse policyDecision =
+ policyEngine.getDecision(onapComponentName, decisionAttributes, requestID);
+ resultReceived.add(policyDecision.getDecision().toString());
+ } catch (PolicyDecisionException e) {
+ // logger.error("Exception Occured"+e);
+ resultReceived.add("" + e);
+ }
+ return resultReceived;
+ }
- /**
- * This function makes API call to policy engine to get action. And returns
- * responseMessage and responseStatus
- *
- * @param org.onap.policyEngine
- * @param eventAttributes
- * @return
- */
- public static ArrayList<String> getAction(PolicyEngine policyEngine,
- Map<String, String> eventAttributes) {
- ArrayList<String> resultReceived = new ArrayList<>();
- try {
- UUID requestID = UUID.randomUUID();
- @SuppressWarnings("deprecation")
- Collection<PolicyResponse> policyResponses = policyEngine
- .sendEvent(eventAttributes, requestID);
- if (policyResponses != null && !policyResponses.isEmpty()) {
- for (PolicyResponse policyResponse : policyResponses) {
- resultReceived.add(policyResponse
- .getPolicyResponseMessage()
- + " : "
- + policyResponse.getPolicyResponseStatus());
- }
- }
- } catch (PolicyEventException e) {
-// logger.error("Exception Occured"+e);
- resultReceived.add(""+e);
- }
- return resultReceived;
- }
+ /**
+ * This function makes API call to policy engine to get action. And returns
+ * responseMessage and responseStatus
+ *
+ * @param policyEngine Policy Engine object
+ * @param eventAttributes Map of String
+ * @return List of String
+ */
+ public static ArrayList<String> getAction(PolicyEngine policyEngine, Map<String, String> eventAttributes) {
+ ArrayList<String> resultReceived = new ArrayList<>();
+ try {
+ UUID requestID = UUID.randomUUID();
+ @SuppressWarnings("deprecation")
+ Collection<PolicyResponse> policyResponses = policyEngine.sendEvent(eventAttributes, requestID);
+ if (policyResponses != null && !policyResponses.isEmpty()) {
+ for (PolicyResponse policyResponse : policyResponses) {
+ resultReceived.add(policyResponse.getPolicyResponseMessage() + " : "
+ + policyResponse.getPolicyResponseStatus());
+ }
+ }
+ } catch (PolicyEventException e) {
+ // logger.error("Exception Occured"+e);
+ resultReceived.add("" + e);
+ }
+ return resultReceived;
+ }
- /**
- * This function makes API call to policy engine to get manual
- * notifications.
- *
- * @param org.onap.policyEngine
- */
+ /**
+ * This function makes API call to policy engine to get manual
+ * notifications.
+ *
+ * @param policyEngine Policy Engine object
+ */
- public static void getManualNotifications(PolicyEngine policyEngine) {
- policyEngine.setScheme(NotificationScheme.MANUAL_ALL_NOTIFICATIONS);
- System.out.println(policyEngine.getNotification().getNotificationType());
- for (LoadedPolicy updated : policyEngine.getNotification().getLoadedPolicies()) {
- System.out.println(updated.getPolicyName());
- System.out.println(updated.getVersionNo());
- System.out.println(updated.getMatches());
- }
- for (RemovedPolicy removed : policyEngine.getNotification()
- .getRemovedPolicies()) {
- System.out.println(removed.getPolicyName());
- System.out.println(removed.getVersionNo());
- }
- }
+ public static void getManualNotifications(PolicyEngine policyEngine) {
+ policyEngine.setScheme(NotificationScheme.MANUAL_ALL_NOTIFICATIONS);
+ System.out.println(policyEngine.getNotification().getNotificationType());
+ for (LoadedPolicy updated : policyEngine.getNotification().getLoadedPolicies()) {
+ System.out.println(updated.getPolicyName());
+ System.out.println(updated.getVersionNo());
+ System.out.println(updated.getMatches());
+ }
+ for (RemovedPolicy removed : policyEngine.getNotification().getRemovedPolicies()) {
+ System.out.println(removed.getPolicyName());
+ System.out.println(removed.getVersionNo());
+ }
+ }
- /**
- * This function makes API call to policy engine to get automatic
- * notifications.
- *
- * @param org.onap.policyEngine
- */
- public static void getAutoNotifications(PolicyEngine policyEngine) {
- Handler handler = new Handler();
- policyEngine.setNotification(NotificationScheme.AUTO_ALL_NOTIFICATIONS,
- handler);
- //
- System.out.println("Enter a any key to exit");
- try {
- System.in.read();
- } catch (IOException e) {
- //
- }
- }
+ /**
+ * This function makes API call to policy engine to get automatic
+ * notifications.
+ *
+ * @param policyEngine Policy Engine object
+ */
+ public static void getAutoNotifications(PolicyEngine policyEngine) {
+ Handler handler = new Handler();
+ policyEngine.setNotification(NotificationScheme.AUTO_ALL_NOTIFICATIONS, handler);
+ //
+ System.out.println("Enter a any key to exit");
+ try {
+ System.in.read();
+ } catch (IOException e) {
+ //
+ }
+ }
}
diff --git a/PolicyEngineClient/src/test/java/org/onap/policyengine/PushPoliciesToPDP.java b/PolicyEngineClient/src/test/java/org/onap/policyengine/PushPoliciesToPDP.java
index 880af0610..3a3b9e704 100644
--- a/PolicyEngineClient/src/test/java/org/onap/policyengine/PushPoliciesToPDP.java
+++ b/PolicyEngineClient/src/test/java/org/onap/policyengine/PushPoliciesToPDP.java
@@ -2,14 +2,14 @@
* ============LICENSE_START=======================================================
* PolicyEngineClient
* ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017, 2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -25,35 +25,39 @@ import org.onap.policy.api.PolicyEngine;
import org.onap.policy.api.PushPolicyParameters;
public class PushPoliciesToPDP {
- public static void main(String[] args) {
- try {
-
- PolicyEngine policyEngine = new PolicyEngine("config.properties");
- PushPolicyParameters policyParameters = new PushPolicyParameters();
-
- //Parameter arguments
- policyParameters.setPolicyName("Mike.testCase1");
- policyParameters.setPolicyType("Base");
- //policyParameters.setPolicyScope("MikeAPItesting");
- policyParameters.setPdpGroup("default");
- policyParameters.setRequestID(null);
-
+
+ /**
+ * main.
+ *
+ * @param args String[] args
+ */
+ public static void main(String[] args) {
+ try {
+ PushPolicyParameters policyParameters = new PushPolicyParameters();
+
+ // Parameter arguments
+ policyParameters.setPolicyName("Mike.testCase1");
+ policyParameters.setPolicyType("Base");
+ // policyParameters.setPolicyScope("MikeAPItesting");
+ policyParameters.setPdpGroup("default");
+ policyParameters.setRequestID(null);
+
// API method to Push Policy to PDP
PolicyChangeResponse response = null;
- response = policyEngine.pushPolicy(policyParameters);
+ response = new PolicyEngine("config.properties").pushPolicy(policyParameters);
- if(response.getResponseCode()==204){
+ if (response.getResponseCode() == 204) {
System.out.println(response.getResponseMessage());
System.out.println("Policy Pushed Successfully!");
- }else{
+ } else {
System.out.println("Error! " + response.getResponseMessage());
}
- } catch (Exception e) {
- System.err.println(e.getMessage());
-
- }
-
- }
+ } catch (Exception e) {
+ System.err.println(e.getMessage());
+
+ }
+
+ }
}
diff --git a/PolicyEngineClient/src/test/java/org/onap/policyengine/RawDecisionPolicyClient.java b/PolicyEngineClient/src/test/java/org/onap/policyengine/RawDecisionPolicyClient.java
index 5f0e74fc6..de28ae8e9 100644
--- a/PolicyEngineClient/src/test/java/org/onap/policyengine/RawDecisionPolicyClient.java
+++ b/PolicyEngineClient/src/test/java/org/onap/policyengine/RawDecisionPolicyClient.java
@@ -2,14 +2,14 @@
* ============LICENSE_START=======================================================
* PolicyEngineClient
* ================================================================================
- * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2018-2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -21,6 +21,7 @@
package org.onap.policyengine;
import java.util.UUID;
+
import org.onap.policy.api.PolicyChangeResponse;
import org.onap.policy.api.PolicyClass;
import org.onap.policy.api.PolicyEngine;
@@ -29,15 +30,16 @@ import org.onap.policy.api.RuleProvider;
public class RawDecisionPolicyClient {
/*
- *
+ *
* To Create a Decision Policy Use case. User need provide valid PolicySet or Policy Type xacml. On Setting below
* required attributes the Decision Raw policy will be created successfully.
- *
+ *
*/
static Boolean isEdit = true;
/**
* Sample code to create Decison Raw Policy.
+ *
* @param args with policy parameters
*/
public static void main(String[] args) {
diff --git a/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/package-info.java b/PolicyEngineClient/src/test/resources/test.drl
index 72a36f4f4..f46a7fe50 100644
--- a/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/package-info.java
+++ b/PolicyEngineClient/src/test/resources/test.drl
@@ -1,15 +1,14 @@
/*-
* ============LICENSE_START=======================================================
- * ONAP-REST
- * ================================================================================
* Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2019 Bell Canada.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -18,4 +17,18 @@
* ============LICENSE_END=========================================================
*/
-package org.onap.policy.rest.jpa;
+package org.onap.policyengine;
+
+rule "INIT"
+when
+then
+ insert("This is a test");
+end
+
+rule "PRINT_MSG"
+when
+ $o : Object();
+then
+ System.out.println("MSG: " + $o);
+ retract($o);
+end
diff --git a/PolicyEngineClient/testResources/test.drl b/PolicyEngineClient/testResources/test.drl
deleted file mode 100644
index 5253cf8fb..000000000
--- a/PolicyEngineClient/testResources/test.drl
+++ /dev/null
@@ -1,1121 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * archetype-closed-loop-demo-rules
- * ================================================================================
- * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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<String, Object>();
- //
- // 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<AAINQF199InventoryResponseItem> 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<String, Object>();
- //
- // 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/PolicyEngineUtils/pom.xml b/PolicyEngineUtils/pom.xml
index 349311e72..ba16c7236 100644
--- a/PolicyEngineUtils/pom.xml
+++ b/PolicyEngineUtils/pom.xml
@@ -2,7 +2,7 @@
============LICENSE_START=======================================================
ONAP Policy Engine
================================================================================
- Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
================================================================================
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
@@ -24,7 +24,7 @@
<parent>
<groupId>org.onap.policy.engine</groupId>
<artifactId>PolicyEngineSuite</artifactId>
- <version>1.4.1-SNAPSHOT</version>
+ <version>1.6.4-SNAPSHOT</version>
</parent>
<artifactId>PolicyEngineUtils</artifactId>
<dependencies>
@@ -65,32 +65,14 @@
<artifactId>maven-model</artifactId>
<version>3.5.3</version>
</dependency>
- <!--
- CLM security fix - force use of xstream
- Remove this if a new version of drools-verifier is upgraded
- that upgrades to xstream.
- -->
- <dependency>
- <groupId>com.thoughtworks.xstream</groupId>
- <artifactId>xstream</artifactId>
- </dependency>
<dependency>
<groupId>org.drools</groupId>
- <artifactId>drools-verifier</artifactId>
- <version>6.5.0.Final</version>
+ <artifactId>drools-verifier-drl</artifactId>
<exclusions>
<exclusion>
- <groupId>com.google.guava</groupId>
- <artifactId>guava</artifactId>
- </exclusion>
- <exclusion>
<groupId>com.lowagie</groupId>
<artifactId>itext</artifactId>
</exclusion>
- <exclusion>
- <groupId>com.thoughtworks.xstream</groupId>
- <artifactId>xstream</artifactId>
- </exclusion>
</exclusions>
</dependency>
<dependency>
diff --git a/PolicyEngineUtils/src/main/java/org/onap/policy/api/LoadedPolicy.java b/PolicyEngineUtils/src/main/java/org/onap/policy/api/LoadedPolicy.java
index 862b654b8..95ef694d8 100644
--- a/PolicyEngineUtils/src/main/java/org/onap/policy/api/LoadedPolicy.java
+++ b/PolicyEngineUtils/src/main/java/org/onap/policy/api/LoadedPolicy.java
@@ -2,14 +2,14 @@
* ============LICENSE_START=======================================================
* PolicyEngineUtils
* ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017, 2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -23,7 +23,7 @@ package org.onap.policy.api;
import java.util.Map;
/**
- * <code>LoadedPolicy</code> defines the Policy that has been Loaded into the PDP.
+ * <code>LoadedPolicy</code> defines the Policy that has been Loaded into the PDP.
*
* @version 0.2
*/
@@ -44,7 +44,8 @@ public interface LoadedPolicy {
String getVersionNo();
/**
- * Gets the <code>Map</code> of <code>String,String</code> format of the Matches if the policy Loaded is of Config Type.
+ * Gets the <code>Map</code> of <code>String,String</code> format of the Matches if the policy Loaded is of Config
+ * Type.
*
* @return the <code>Map</code> of <code>String,String</code> format of the matches in the policy.
*/
diff --git a/PolicyEngineUtils/src/main/java/org/onap/policy/api/NotificationHandler.java b/PolicyEngineUtils/src/main/java/org/onap/policy/api/NotificationHandler.java
index 78b79a08f..fe30241dd 100644
--- a/PolicyEngineUtils/src/main/java/org/onap/policy/api/NotificationHandler.java
+++ b/PolicyEngineUtils/src/main/java/org/onap/policy/api/NotificationHandler.java
@@ -2,14 +2,14 @@
* ============LICENSE_START=======================================================
* PolicyEngineUtils
* ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017, 2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -29,10 +29,11 @@ package org.onap.policy.api;
public interface NotificationHandler {
/**
- * <code>notificationReceived</code> method will be triggered automatically whenever a Notification is received by the PEP.
+ * <code>notificationReceived</code> method will be triggered automatically whenever a Notification is received by
+ * the PEP.
*
* @param notification <code>PDPNotification</code> of {@link org.onap.policy.api.PDPNotification}
- * is the object that has information of the notification.
+ * is the object that has information of the notification.
*/
void notificationReceived(PDPNotification notification);
}
diff --git a/PolicyEngineUtils/src/main/java/org/onap/policy/api/NotificationType.java b/PolicyEngineUtils/src/main/java/org/onap/policy/api/NotificationType.java
index 8b65a420d..a86e997b8 100644
--- a/PolicyEngineUtils/src/main/java/org/onap/policy/api/NotificationType.java
+++ b/PolicyEngineUtils/src/main/java/org/onap/policy/api/NotificationType.java
@@ -2,14 +2,14 @@
* ============LICENSE_START=======================================================
* PolicyEngineUtils
* ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017, 2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -21,18 +21,18 @@
package org.onap.policy.api;
/**
- * Enumeration of the Update Type that has occurred in the <code>PDPNotification</code> of
- * {@link org.onap.policy.api.PDPNotification}
+ * Enumeration of the Update Type that has occurred in the <code>PDPNotification</code> of
+ * {@link org.onap.policy.api.PDPNotification}.
*
* @version 0.1
*/
public enum NotificationType {
/**
- * Indicates that a policy has been updated
+ * Indicates that a policy has been updated.
*/
UPDATE("update"),
/**
- * Indicates that a policy has been removed
+ * Indicates that a policy has been removed.
*/
REMOVE("remove"),
/**
@@ -47,7 +47,8 @@ public enum NotificationType {
}
/**
- * Returns the <code>String</code> format of the Type for this <code>UpdateType</code>
+ * Returns the <code>String</code> format of the Type for this <code>UpdateType</code>.
+ *
* @return the <code>String</code> Type of <code>UpdateType</code>
*/
@Override
diff --git a/PolicyEngineUtils/src/main/java/org/onap/policy/api/PDPNotification.java b/PolicyEngineUtils/src/main/java/org/onap/policy/api/PDPNotification.java
index 9ab508281..caee7e301 100644
--- a/PolicyEngineUtils/src/main/java/org/onap/policy/api/PDPNotification.java
+++ b/PolicyEngineUtils/src/main/java/org/onap/policy/api/PDPNotification.java
@@ -2,14 +2,14 @@
* ============LICENSE_START=======================================================
* PolicyEngineUtils
* ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017, 2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -23,7 +23,7 @@ package org.onap.policy.api;
import java.util.Collection;
/**
- * Defines the <code>Notification</code> event sent from PDP to Client PEP.
+ * Defines the <code>Notification</code> event sent from PDP to Client PEP.
*
* @version 0.2
*/
diff --git a/PolicyEngineUtils/src/main/java/org/onap/policy/api/PEDependency.java b/PolicyEngineUtils/src/main/java/org/onap/policy/api/PEDependency.java
index d722f1696..b94872785 100644
--- a/PolicyEngineUtils/src/main/java/org/onap/policy/api/PEDependency.java
+++ b/PolicyEngineUtils/src/main/java/org/onap/policy/api/PEDependency.java
@@ -2,14 +2,14 @@
* ============LICENSE_START=======================================================
* PolicyEngineUtils
* ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017, 2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -20,63 +20,29 @@
package org.onap.policy.api;
+import lombok.Getter;
+import lombok.Setter;
import org.apache.maven.model.Dependency;
import org.apache.maven.model.Exclusion;
-public class PEDependency{
-
+@Setter
+@Getter
+public class PEDependency {
+
private String groupId;
private String artifactId;
private String version;
private String classifier;
- private String type;
+ private String type;
private String scope;
private java.util.List<Exclusion> exclusions;
-
- public String getGroupId() {
- return groupId;
- }
- public void setGroupId(String groupId) {
- this.groupId = groupId;
- }
- public String getArtifactId() {
- return artifactId;
- }
- public void setArtifactId(String artifactId) {
- this.artifactId = artifactId;
- }
- public String getVersion() {
- return version;
- }
- public void setVersion(String version) {
- this.version = version;
- }
- public java.util.List<Exclusion> getExclusions() {
- return exclusions;
- }
- public void setExclusions(java.util.List<Exclusion> exclusions) {
- this.exclusions = exclusions;
- }
- public String getClassifier() {
- return classifier;
- }
- public void setClassifier(String classifier) {
- this.classifier = classifier;
- }
- public String getType() {
- return type;
- }
- public void setType(String type) {
- this.type = type;
- }
- public String getScope() {
- return scope;
- }
- public void setScope(String scope) {
- this.scope = scope;
- }
-
- public Dependency getDependency(){
+
+ /**
+ * getDependency.
+ *
+ * @return Dependency
+ */
+ public Dependency getDependency() {
Dependency dependency = new Dependency();
dependency.setArtifactId(artifactId);
dependency.setGroupId(groupId);
diff --git a/PolicyEngineUtils/src/main/java/org/onap/policy/api/RemovedPolicy.java b/PolicyEngineUtils/src/main/java/org/onap/policy/api/RemovedPolicy.java
index e8125a1dc..db7183ed7 100644
--- a/PolicyEngineUtils/src/main/java/org/onap/policy/api/RemovedPolicy.java
+++ b/PolicyEngineUtils/src/main/java/org/onap/policy/api/RemovedPolicy.java
@@ -2,14 +2,14 @@
* ============LICENSE_START=======================================================
* PolicyEngineUtils
* ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017, 2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -21,7 +21,7 @@
package org.onap.policy.api;
/**
- * <code>RemovedPolicy</code> defines the Policy that has been removed
+ * <code>RemovedPolicy</code> defines the Policy that has been removed.
*
* @version 0.1
*/
diff --git a/PolicyEngineUtils/src/main/java/org/onap/policy/api/UpdateType.java b/PolicyEngineUtils/src/main/java/org/onap/policy/api/UpdateType.java
index 7f401fec0..6219928bc 100644
--- a/PolicyEngineUtils/src/main/java/org/onap/policy/api/UpdateType.java
+++ b/PolicyEngineUtils/src/main/java/org/onap/policy/api/UpdateType.java
@@ -2,14 +2,14 @@
* ============LICENSE_START=======================================================
* PolicyEngineUtils
* ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017, 2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -21,18 +21,18 @@
package org.onap.policy.api;
/**
- * Enumeration of the Update Type that has occurred in the <code>UpdatedPolicy</code> of
- * {@link org.onap.policy.api.LoadedPolicy}
+ * Enumeration of the Update Type that has occurred in the <code>UpdatedPolicy</code> of
+ * {@link org.onap.policy.api.LoadedPolicy}.
*
* @version 0.1
*/
public enum UpdateType {
/**
- * Indicates that a policy has been updated
+ * Indicates that a policy has been updated.
*/
UPDATE("update"),
/**
- * Indicates that a policy is new
+ * Indicates that a policy is new.
*/
NEW("new");
@@ -43,7 +43,8 @@ public enum UpdateType {
}
/**
- * Returns the <code>String</code> format of the Type for this <code>UpdateType</code>
+ * Returns the <code>String</code> format of the Type for this <code>UpdateType</code>.
+ *
* @return the <code>String</code> Type of <code>UpdateType</code>
*/
@Override
diff --git a/PolicyEngineUtils/src/main/java/org/onap/policy/jpa/BackUpMonitorEntity.java b/PolicyEngineUtils/src/main/java/org/onap/policy/jpa/BackUpMonitorEntity.java
index 1bfffce6c..55daf1e83 100644
--- a/PolicyEngineUtils/src/main/java/org/onap/policy/jpa/BackUpMonitorEntity.java
+++ b/PolicyEngineUtils/src/main/java/org/onap/policy/jpa/BackUpMonitorEntity.java
@@ -2,14 +2,14 @@
* ============LICENSE_START=======================================================
* PolicyEngineUtils
* ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017, 2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -22,6 +22,7 @@ package org.onap.policy.jpa;
import java.io.Serializable;
import java.util.Date;
+
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
@@ -35,7 +36,6 @@ import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
-
@Entity
@Table(name = "BackUpMonitorEntity")
@NamedQuery(name = "BackUpMonitorEntity.findAll", query = "SELECT b FROM BackUpMonitorEntity b ")
diff --git a/PolicyEngineUtils/src/main/java/org/onap/policy/std/NotificationStore.java b/PolicyEngineUtils/src/main/java/org/onap/policy/std/NotificationStore.java
index 6164418d9..40c640f9a 100644
--- a/PolicyEngineUtils/src/main/java/org/onap/policy/std/NotificationStore.java
+++ b/PolicyEngineUtils/src/main/java/org/onap/policy/std/NotificationStore.java
@@ -2,15 +2,15 @@
* ============LICENSE_START=======================================================
* PolicyEngineUtils
* ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017, 2019 AT&T Intellectual Property. All rights reserved.
* Modified Copyright (C) 2018 Samsung Electronics Co., Ltd.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -25,27 +25,33 @@ import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
+
import org.onap.policy.api.LoadedPolicy;
import org.onap.policy.api.NotificationType;
import org.onap.policy.api.PDPNotification;
import org.onap.policy.api.RemovedPolicy;
-
/*
- * This Should Compare and save the Notifications from the beginning of Time.
- * If there is something new (missed) We notify the client.
- * Works for PDP failures.
- *
+ * This Should Compare and save the Notifications from the beginning of Time.
+ * If there is something new (missed) We notify the client.
+ * Works for PDP failures.
+ *
*/
public class NotificationStore {
private static StdPDPNotification notificationRecord = new StdPDPNotification();
- private NotificationStore () {
+ private NotificationStore() {
// Sonar prefers that we have an empty public constructor
// as opposed to an implicit public constructor.
}
-
+
+ /**
+ * getDeltaNotification.
+ *
+ * @param newNotification StdPDPNotification
+ * @return StdPDPNotification
+ */
public static StdPDPNotification getDeltaNotification(StdPDPNotification newNotification) {
StdPDPNotification notificationDelta = new StdPDPNotification();
ArrayList<StdRemovedPolicy> removedDelta = new ArrayList<>();
@@ -72,13 +78,15 @@ public class NotificationStore {
// check for old removed policies.
if (!newNotification.getRemovedPolicies().isEmpty()) {
for (RemovedPolicy newRemovedPolicy : newNotification.getRemovedPolicies()) {
- remove = updateRemovedPolicies(removedDelta, oldUpdatedLostPolicies, oldRemovedPolicies, oldUpdatedPolicies, remove, newRemovedPolicy);
+ remove = updateRemovedPolicies(removedDelta, oldUpdatedLostPolicies, oldRemovedPolicies,
+ oldUpdatedPolicies, remove, newRemovedPolicy);
}
}
// Check for old Updated Policies.
if (!newNotification.getLoadedPolicies().isEmpty()) {
for (LoadedPolicy newUpdatedPolicy : newNotification.getLoadedPolicies()) {
- update = modifyUpdatedPolicies(updatedDelta, oldUpdatedLostPolicies, oldRemovedPolicies, oldUpdatedPolicies, update, newUpdatedPolicy);
+ update = modifyUpdatedPolicies(updatedDelta, oldUpdatedLostPolicies, oldRemovedPolicies,
+ oldUpdatedPolicies, update, newUpdatedPolicy);
}
// Conversion of Update to Remove if that occurred.
if (!oldUpdatedLostPolicies.isEmpty()) {
@@ -118,14 +126,15 @@ public class NotificationStore {
return notificationDelta;
}
- private static Boolean modifyUpdatedPolicies(ArrayList<StdLoadedPolicy> updatedDelta, Collection<LoadedPolicy> oldUpdatedLostPolicies, Collection<RemovedPolicy> oldRemovedPolicies, Collection<LoadedPolicy> oldUpdatedPolicies, Boolean update, LoadedPolicy newUpdatedPolicy) {
+ private static Boolean modifyUpdatedPolicies(ArrayList<StdLoadedPolicy> updatedDelta,
+ Collection<LoadedPolicy> oldUpdatedLostPolicies, Collection<RemovedPolicy> oldRemovedPolicies,
+ Collection<LoadedPolicy> oldUpdatedPolicies, Boolean update, LoadedPolicy newUpdatedPolicy) {
// Look for policies which are not in Update
Boolean updated = true;
String policyName = newUpdatedPolicy.getPolicyName();
String ver = newUpdatedPolicy.getVersionNo();
for (LoadedPolicy oldUpdatedPolicy : notificationRecord.getLoadedPolicies()) {
- if (policyName.equals(oldUpdatedPolicy.getPolicyName())
- && ver.equals(oldUpdatedPolicy.getVersionNo())) {
+ if (policyName.equals(oldUpdatedPolicy.getPolicyName()) && ver.equals(oldUpdatedPolicy.getVersionNo())) {
updated = false;
// Remove the policy from copy.
oldUpdatedLostPolicies.remove(oldUpdatedPolicy);
@@ -135,8 +144,7 @@ public class NotificationStore {
}
// Change the record if the policy has been Removed earlier.
for (RemovedPolicy oldRemovedPolicy : notificationRecord.getRemovedPolicies()) {
- if (oldRemovedPolicy.getPolicyName().equals(policyName)
- && oldRemovedPolicy.getVersionNo().equals(ver)) {
+ if (oldRemovedPolicy.getPolicyName().equals(policyName) && oldRemovedPolicy.getVersionNo().equals(ver)) {
oldRemovedPolicies.remove(oldRemovedPolicy);
}
}
@@ -149,23 +157,23 @@ public class NotificationStore {
return update;
}
- private static Boolean updateRemovedPolicies(ArrayList<StdRemovedPolicy> removedDelta, Collection<LoadedPolicy> oldUpdatedLostPolicies, Collection<RemovedPolicy> oldRemovedPolicies, Collection<LoadedPolicy> oldUpdatedPolicies, Boolean remove, RemovedPolicy newRemovedPolicy) {
- //Look for policy Not in Remove
+ private static Boolean updateRemovedPolicies(ArrayList<StdRemovedPolicy> removedDelta,
+ Collection<LoadedPolicy> oldUpdatedLostPolicies, Collection<RemovedPolicy> oldRemovedPolicies,
+ Collection<LoadedPolicy> oldUpdatedPolicies, Boolean remove, RemovedPolicy newRemovedPolicy) {
+ // Look for policy Not in Remove
Boolean removed = true;
String policyName = newRemovedPolicy.getPolicyName();
String ver = newRemovedPolicy.getVersionNo();
for (RemovedPolicy oldRemovedPolicy : notificationRecord.getRemovedPolicies()) {
- if (policyName.equals(oldRemovedPolicy.getPolicyName())
- && ver.equals(oldRemovedPolicy.getVersionNo())) {
+ if (policyName.equals(oldRemovedPolicy.getPolicyName()) && ver.equals(oldRemovedPolicy.getVersionNo())) {
removed = false;
// Don't want a duplicate.
oldRemovedPolicies.remove(oldRemovedPolicy);
}
}
- //We need to change our record we have an Update record of this remove.
+ // We need to change our record we have an Update record of this remove.
for (LoadedPolicy oldUpdatedPolicy : notificationRecord.getLoadedPolicies()) {
- if (policyName.equals(oldUpdatedPolicy.getPolicyName())
- && ver.equals(oldUpdatedPolicy.getVersionNo())) {
+ if (policyName.equals(oldUpdatedPolicy.getPolicyName()) && ver.equals(oldUpdatedPolicy.getVersionNo())) {
oldUpdatedPolicies.remove(oldUpdatedPolicy);
oldUpdatedLostPolicies.remove(oldUpdatedPolicy);
}
@@ -180,6 +188,11 @@ public class NotificationStore {
return remove;
}
+ /**
+ * recordNotification.
+ *
+ * @param notification StdPDPNotification
+ */
public static void recordNotification(StdPDPNotification notification) {
if (notification == null) {
return;
@@ -187,49 +200,50 @@ public class NotificationStore {
if (notificationRecord.getRemovedPolicies() == null || notificationRecord.getLoadedPolicies() == null) {
notificationRecord = notification;
- } else {
- // Check if there is anything new and update the record.
- if (notificationRecord.getLoadedPolicies() != null || notificationRecord.getRemovedPolicies() != null) {
- HashSet<StdRemovedPolicy> removedPolicies = new HashSet<>();
- for (RemovedPolicy rPolicy : notificationRecord.getRemovedPolicies()) {
- StdRemovedPolicy sRPolicy = new StdRemovedPolicy();
- sRPolicy.setPolicyName(rPolicy.getPolicyName());
- sRPolicy.setVersionNo(rPolicy.getVersionNo());
- removedPolicies.add(sRPolicy);
- }
- HashSet<StdLoadedPolicy> updatedPolicies = new HashSet<>();
- for (LoadedPolicy uPolicy : notificationRecord.getLoadedPolicies()) {
- StdLoadedPolicy sUPolicy = new StdLoadedPolicy();
- sUPolicy.setMatches(uPolicy.getMatches());
- sUPolicy.setPolicyName(uPolicy.getPolicyName());
- sUPolicy.setVersionNo(uPolicy.getVersionNo());
- sUPolicy.setUpdateType(uPolicy.getUpdateType());
- updatedPolicies.add(sUPolicy);
- }
+ return;
+ }
+ // Check if there is anything new and update the record.
+ if (notificationRecord.getLoadedPolicies() != null || notificationRecord.getRemovedPolicies() != null) {
+ HashSet<StdRemovedPolicy> removedPolicies = new HashSet<>();
+ for (RemovedPolicy removedPolicy : notificationRecord.getRemovedPolicies()) {
+ StdRemovedPolicy stdRemovedPolicy = new StdRemovedPolicy();
+ stdRemovedPolicy.setPolicyName(removedPolicy.getPolicyName());
+ stdRemovedPolicy.setVersionNo(removedPolicy.getVersionNo());
+ removedPolicies.add(stdRemovedPolicy);
+ }
+ HashSet<StdLoadedPolicy> updatedPolicies = new HashSet<>();
+ for (LoadedPolicy loadedPolicy : notificationRecord.getLoadedPolicies()) {
+ StdLoadedPolicy stdLoadedPolicy = new StdLoadedPolicy();
+ stdLoadedPolicy.setMatches(loadedPolicy.getMatches());
+ stdLoadedPolicy.setPolicyName(loadedPolicy.getPolicyName());
+ stdLoadedPolicy.setVersionNo(loadedPolicy.getVersionNo());
+ stdLoadedPolicy.setUpdateType(loadedPolicy.getUpdateType());
+ updatedPolicies.add(stdLoadedPolicy);
+ }
- // Checking with the new updated policies.
- if (notification.getLoadedPolicies() != null && !notification.getLoadedPolicies().isEmpty()) {
- checkNewUpdatedPolicies(notification, removedPolicies, updatedPolicies);
- }
- // Checking with New Removed Policies.
- if (notification.getRemovedPolicies() != null && !notification.getRemovedPolicies().isEmpty()) {
- checkNewRemovedPolicies(notification, removedPolicies, updatedPolicies);
- }
- notificationRecord.setRemovedPolicies(removedPolicies);
- notificationRecord.setLoadedPolicies(updatedPolicies);
+ // Checking with the new updated policies.
+ if (notification.getLoadedPolicies() != null && !notification.getLoadedPolicies().isEmpty()) {
+ checkNewUpdatedPolicies(notification, removedPolicies, updatedPolicies);
}
- if (!notificationRecord.getLoadedPolicies().isEmpty() && !notificationRecord.getRemovedPolicies()
- .isEmpty()) {
- notificationRecord.setNotificationType(NotificationType.BOTH);
- } else if (!notificationRecord.getLoadedPolicies().isEmpty()) {
- notificationRecord.setNotificationType(NotificationType.UPDATE);
- } else if (!notificationRecord.getRemovedPolicies().isEmpty()) {
- notificationRecord.setNotificationType(NotificationType.REMOVE);
+ // Checking with New Removed Policies.
+ if (notification.getRemovedPolicies() != null && !notification.getRemovedPolicies().isEmpty()) {
+ checkNewRemovedPolicies(notification, removedPolicies, updatedPolicies);
}
+ notificationRecord.setRemovedPolicies(removedPolicies);
+ notificationRecord.setLoadedPolicies(updatedPolicies);
+ }
+ if (!notificationRecord.getLoadedPolicies().isEmpty()
+ && !notificationRecord.getRemovedPolicies().isEmpty()) {
+ notificationRecord.setNotificationType(NotificationType.BOTH);
+ } else if (!notificationRecord.getLoadedPolicies().isEmpty()) {
+ notificationRecord.setNotificationType(NotificationType.UPDATE);
+ } else if (!notificationRecord.getRemovedPolicies().isEmpty()) {
+ notificationRecord.setNotificationType(NotificationType.REMOVE);
}
}
- private static void checkNewUpdatedPolicies(StdPDPNotification notification, HashSet<StdRemovedPolicy> removedPolicies, HashSet<StdLoadedPolicy> updatedPolicies) {
+ private static void checkNewUpdatedPolicies(StdPDPNotification notification,
+ HashSet<StdRemovedPolicy> removedPolicies, HashSet<StdLoadedPolicy> updatedPolicies) {
for (LoadedPolicy newUpdatedPolicy : notification.getLoadedPolicies()) {
// If it was removed earlier then we need to remove from our record
Iterator<StdRemovedPolicy> oldRemovedPolicy = removedPolicies.iterator();
@@ -237,25 +251,25 @@ public class NotificationStore {
String ver = newUpdatedPolicy.getVersionNo();
while (oldRemovedPolicy.hasNext()) {
RemovedPolicy policy = oldRemovedPolicy.next();
- if (policyName.equals(policy.getPolicyName())
- && ver.equals(policy.getVersionNo())) {
+ if (policyName.equals(policy.getPolicyName()) && ver.equals(policy.getVersionNo())) {
oldRemovedPolicy.remove();
}
}
// If it was previously updated need to Overwrite it to the record.
- updatedPolicies.removeIf(policy -> policyName.equals(policy.getPolicyName())
- && ver.equals(policy.getVersionNo()));
+ updatedPolicies
+ .removeIf(policy -> policyName.equals(policy.getPolicyName()) && ver.equals(policy.getVersionNo()));
- StdLoadedPolicy sUPolicy = new StdLoadedPolicy();
- sUPolicy.setMatches(newUpdatedPolicy.getMatches());
- sUPolicy.setPolicyName(newUpdatedPolicy.getPolicyName());
- sUPolicy.setVersionNo(newUpdatedPolicy.getVersionNo());
- sUPolicy.setUpdateType(newUpdatedPolicy.getUpdateType());
- updatedPolicies.add(sUPolicy);
+ StdLoadedPolicy stdLoadedPolicy = new StdLoadedPolicy();
+ stdLoadedPolicy.setMatches(newUpdatedPolicy.getMatches());
+ stdLoadedPolicy.setPolicyName(newUpdatedPolicy.getPolicyName());
+ stdLoadedPolicy.setVersionNo(newUpdatedPolicy.getVersionNo());
+ stdLoadedPolicy.setUpdateType(newUpdatedPolicy.getUpdateType());
+ updatedPolicies.add(stdLoadedPolicy);
}
}
- private static void checkNewRemovedPolicies(StdPDPNotification notification, HashSet<StdRemovedPolicy> removedPolicies, HashSet<StdLoadedPolicy> updatedPolicies) {
+ private static void checkNewRemovedPolicies(StdPDPNotification notification,
+ HashSet<StdRemovedPolicy> removedPolicies, HashSet<StdLoadedPolicy> updatedPolicies) {
for (RemovedPolicy newRemovedPolicy : notification.getRemovedPolicies()) {
// If it was previously removed Overwrite it to the record.
Iterator<StdRemovedPolicy> oldRemovedPolicy = removedPolicies.iterator();
@@ -263,19 +277,18 @@ public class NotificationStore {
String ver = newRemovedPolicy.getVersionNo();
while (oldRemovedPolicy.hasNext()) {
RemovedPolicy policy = oldRemovedPolicy.next();
- if (policyName.equals(policy.getPolicyName())
- && ver.equals(policy.getVersionNo())) {
+ if (policyName.equals(policy.getPolicyName()) && ver.equals(policy.getVersionNo())) {
oldRemovedPolicy.remove();
}
}
// If it was added earlier then we need to remove from our record.
- updatedPolicies.removeIf(policy -> policyName.equals(policy.getPolicyName())
- && ver.equals(policy.getVersionNo()));
+ updatedPolicies
+ .removeIf(policy -> policyName.equals(policy.getPolicyName()) && ver.equals(policy.getVersionNo()));
- StdRemovedPolicy sRPolicy = new StdRemovedPolicy();
- sRPolicy.setPolicyName(policyName);
- sRPolicy.setVersionNo(ver);
- removedPolicies.add(sRPolicy);
+ StdRemovedPolicy stdRemovedPolicy = new StdRemovedPolicy();
+ stdRemovedPolicy.setPolicyName(policyName);
+ stdRemovedPolicy.setVersionNo(ver);
+ removedPolicies.add(stdRemovedPolicy);
}
}
diff --git a/PolicyEngineUtils/src/main/java/org/onap/policy/std/StdLoadedPolicy.java b/PolicyEngineUtils/src/main/java/org/onap/policy/std/StdLoadedPolicy.java
index ebbed2100..4d45ebe4e 100644
--- a/PolicyEngineUtils/src/main/java/org/onap/policy/std/StdLoadedPolicy.java
+++ b/PolicyEngineUtils/src/main/java/org/onap/policy/std/StdLoadedPolicy.java
@@ -2,14 +2,14 @@
* ============LICENSE_START=======================================================
* PolicyEngineUtils
* ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017, 2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -25,48 +25,48 @@ import java.util.Map;
import org.onap.policy.api.LoadedPolicy;
import org.onap.policy.api.UpdateType;
-public class StdLoadedPolicy implements LoadedPolicy{
- private String policyName = null;
- private String versionNo = null;
- private Map<String,String> matches = null;
- private UpdateType updateType = null;
-
- @Override
- public String getPolicyName() {
- if(policyName!=null && policyName.contains(".xml")){
- return policyName.substring(0, policyName.substring(0, policyName.lastIndexOf('.')).lastIndexOf('.'));
- }
- return this.policyName;
- }
-
- public void setPolicyName(String policyName) {
- this.policyName = policyName;
- }
-
- @Override
- public String getVersionNo() {
- return this.versionNo;
- }
-
- public void setVersionNo(String versionNo) {
- this.versionNo = versionNo;
- }
-
- @Override
- public Map<String,String> getMatches() {
- return this.matches;
- }
-
- public void setMatches(Map<String,String> matches) {
- this.matches = matches;
- }
+public class StdLoadedPolicy implements LoadedPolicy {
+ private String policyName = null;
+ private String versionNo = null;
+ private Map<String, String> matches = null;
+ private UpdateType updateType = null;
- @Override
- public UpdateType getUpdateType() {
- return this.updateType;
- }
-
- public void setUpdateType(UpdateType updateType){
- this.updateType = updateType;
- }
+ @Override
+ public String getPolicyName() {
+ if (policyName != null && policyName.contains(".xml")) {
+ return policyName.substring(0, policyName.substring(0, policyName.lastIndexOf('.')).lastIndexOf('.'));
+ }
+ return this.policyName;
+ }
+
+ public void setPolicyName(String policyName) {
+ this.policyName = policyName;
+ }
+
+ @Override
+ public String getVersionNo() {
+ return this.versionNo;
+ }
+
+ public void setVersionNo(String versionNo) {
+ this.versionNo = versionNo;
+ }
+
+ @Override
+ public Map<String, String> getMatches() {
+ return this.matches;
+ }
+
+ public void setMatches(Map<String, String> matches) {
+ this.matches = matches;
+ }
+
+ @Override
+ public UpdateType getUpdateType() {
+ return this.updateType;
+ }
+
+ public void setUpdateType(UpdateType updateType) {
+ this.updateType = updateType;
+ }
}
diff --git a/PolicyEngineUtils/src/main/java/org/onap/policy/std/StdPDPNotification.java b/PolicyEngineUtils/src/main/java/org/onap/policy/std/StdPDPNotification.java
index 54b9bb0f6..b863fbba5 100644
--- a/PolicyEngineUtils/src/main/java/org/onap/policy/std/StdPDPNotification.java
+++ b/PolicyEngineUtils/src/main/java/org/onap/policy/std/StdPDPNotification.java
@@ -2,14 +2,14 @@
* ============LICENSE_START=======================================================
* PolicyEngineUtils
* ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017, 2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -23,6 +23,7 @@ package org.onap.policy.std;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
+
import org.onap.policy.api.LoadedPolicy;
import org.onap.policy.api.NotificationType;
import org.onap.policy.api.PDPNotification;
diff --git a/PolicyEngineUtils/src/main/java/org/onap/policy/std/StdRemovedPolicy.java b/PolicyEngineUtils/src/main/java/org/onap/policy/std/StdRemovedPolicy.java
index 04ec6981b..1a7be3d3c 100644
--- a/PolicyEngineUtils/src/main/java/org/onap/policy/std/StdRemovedPolicy.java
+++ b/PolicyEngineUtils/src/main/java/org/onap/policy/std/StdRemovedPolicy.java
@@ -2,14 +2,14 @@
* ============LICENSE_START=======================================================
* PolicyEngineUtils
* ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017, 2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -22,28 +22,28 @@ package org.onap.policy.std;
import org.onap.policy.api.RemovedPolicy;
-public class StdRemovedPolicy implements RemovedPolicy{
- private String policyName = null;
- private String versionNo = null;
-
- @Override
- public String getVersionNo() {
- return this.versionNo;
- }
-
- public void setVersionNo(String versionNo) {
- this.versionNo = versionNo;
- }
-
- @Override
- public String getPolicyName() {
- if(policyName!=null && policyName.contains(".xml")){
- return policyName.substring(0, policyName.substring(0, policyName.lastIndexOf('.')).lastIndexOf('.'));
- }
- return this.policyName;
- }
-
- public void setPolicyName(String policyName) {
- this.policyName = policyName;
- }
-}
+public class StdRemovedPolicy implements RemovedPolicy {
+ private String policyName = null;
+ private String versionNo = null;
+
+ @Override
+ public String getVersionNo() {
+ return this.versionNo;
+ }
+
+ public void setVersionNo(String versionNo) {
+ this.versionNo = versionNo;
+ }
+
+ @Override
+ public String getPolicyName() {
+ if (policyName != null && policyName.contains(".xml")) {
+ return policyName.substring(0, policyName.substring(0, policyName.lastIndexOf('.')).lastIndexOf('.'));
+ }
+ return this.policyName;
+ }
+
+ public void setPolicyName(String policyName) {
+ this.policyName = policyName;
+ }
+}
diff --git a/PolicyEngineUtils/src/main/java/org/onap/policy/utils/AAFEnvironment.java b/PolicyEngineUtils/src/main/java/org/onap/policy/utils/AAFEnvironment.java
index 1fccabcbd..e1849f06b 100644
--- a/PolicyEngineUtils/src/main/java/org/onap/policy/utils/AAFEnvironment.java
+++ b/PolicyEngineUtils/src/main/java/org/onap/policy/utils/AAFEnvironment.java
@@ -2,14 +2,14 @@
* ============LICENSE_START=======================================================
* PolicyEngineUtils
* ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017, 2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -17,13 +17,12 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.policy.utils;
public enum AAFEnvironment {
- /*
- * Enumeration for the Resource Node Naming. Add here if required.
- */
- DEVL,
- TEST,
- PROD
+ /*
+ * Enumeration for the Resource Node Naming. Add here if required.
+ */
+ DEVL, TEST, PROD
}
diff --git a/PolicyEngineUtils/src/main/java/org/onap/policy/utils/AAFPolicyClient.java b/PolicyEngineUtils/src/main/java/org/onap/policy/utils/AAFPolicyClient.java
index e560d0ecc..236f01eff 100644
--- a/PolicyEngineUtils/src/main/java/org/onap/policy/utils/AAFPolicyClient.java
+++ b/PolicyEngineUtils/src/main/java/org/onap/policy/utils/AAFPolicyClient.java
@@ -2,14 +2,14 @@
* ============LICENSE_START=======================================================
* PolicyEngineUtils
* ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017, 2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -17,6 +17,7 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.policy.utils;
import java.lang.reflect.Method;
@@ -24,17 +25,29 @@ import java.util.Properties;
public interface AAFPolicyClient {
- public boolean checkAuth(String userName, String pass);
- public void updateProperties(Properties properties) throws AAFPolicyException;
- public boolean checkAuthPerm(String mechID, String pass, String type, String instance, String action);
- public boolean checkPerm(String userName, String pass, String type, String instance, String action);
- public static AAFPolicyClient getInstance(Properties properties) throws AAFPolicyException{
- try {
- Class<?> aafPolicyClient = Class.forName(properties.getProperty("aafClient.impl.className", AAFPolicyClientImpl.class.getName()));
- Method method = aafPolicyClient.getMethod("getInstance", Properties.class);
- return (AAFPolicyClient) method.invoke(null, properties);
- } catch (Exception e) {
- throw new AAFPolicyException(e);
- }
- }
+ public boolean checkAuth(String userName, String pass);
+
+ public void updateProperties(Properties properties) throws AAFPolicyException;
+
+ public boolean checkAuthPerm(String mechID, String pass, String type, String instance, String action);
+
+ public boolean checkPerm(String userName, String pass, String type, String instance, String action);
+
+ /**
+ * getInstance.
+ *
+ * @param properties Properties
+ * @return AAFPolicyClient
+ * @throws AAFPolicyException AAFPolicyException
+ */
+ public static AAFPolicyClient getInstance(Properties properties) throws AAFPolicyException {
+ try {
+ Class<?> aafPolicyClient = Class
+ .forName(properties.getProperty("aafClient.impl.className", AAFPolicyClientImpl.class.getName()));
+ Method method = aafPolicyClient.getMethod("getInstance", Properties.class);
+ return (AAFPolicyClient) method.invoke(null, properties);
+ } catch (Exception e) {
+ throw new AAFPolicyException(e);
+ }
+ }
}
diff --git a/PolicyEngineUtils/src/main/java/org/onap/policy/utils/AAFPolicyClientImpl.java b/PolicyEngineUtils/src/main/java/org/onap/policy/utils/AAFPolicyClientImpl.java
index 1513507ca..fcdc7e9f8 100644
--- a/PolicyEngineUtils/src/main/java/org/onap/policy/utils/AAFPolicyClientImpl.java
+++ b/PolicyEngineUtils/src/main/java/org/onap/policy/utils/AAFPolicyClientImpl.java
@@ -2,15 +2,15 @@
* ============LICENSE_START=======================================================
* PolicyEngineUtils
* ================================================================================
- * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
* Modified Copyright (C) 2018 Samsung Electronics Co., Ltd.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -18,6 +18,7 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.policy.utils;
import java.security.Principal;
@@ -38,7 +39,7 @@ import org.onap.aaf.cadi.principal.UnAuthPrincipal;
/**
* AAF Client: Generic AAF Client implementation to connect to AAF Resources to
* validate permissions and authorization.
- *
+ *
*/
public class AAFPolicyClientImpl implements AAFPolicyClient {
private static Logger logger = Logger.getLogger(AAFPolicyClientImpl.class.getName());
@@ -60,10 +61,10 @@ public class AAFPolicyClientImpl implements AAFPolicyClient {
* CLIENT_ID, CLIENT_KEY and ENVIRONMENT
*
* @param properties
- * Properties with CLIENT_ID, CLIENT_KEY and ENVIRONMENT
+ * Properties with CLIENT_ID, CLIENT_KEY and ENVIRONMENT
* @return AAFClient instance.
* @throws AAFPolicyException
- * Exceptions.
+ * Exceptions.
*/
public static synchronized AAFPolicyClientImpl getInstance(Properties properties) throws AAFPolicyException {
if (instance == null) {
@@ -83,16 +84,16 @@ public class AAFPolicyClientImpl implements AAFPolicyClient {
logger.error("Required Property value is missing : " + ENVIRONMENT);
throw new AAFPolicyException("Required Property value is missing : " + ENVIRONMENT);
}
- setUpAAF();
+ setUpAaf();
}
/**
* Updates the Properties file in case if required.
*
* @param properties
- * Properties with CLIENT_ID, CLIENT_KEY and ENVIRONMENT
+ * Properties with CLIENT_ID, CLIENT_KEY and ENVIRONMENT
* @throws AAFPolicyException
- * exceptions if any.
+ * exceptions if any.
*/
@Override
public void updateProperties(Properties properties) throws AAFPolicyException {
@@ -103,15 +104,15 @@ public class AAFPolicyClientImpl implements AAFPolicyClient {
* Checks the Authentication and Permissions for the given values.
*
* @param userName
- * Username must be registered under the Name space.
+ * Username must be registered under the Name space.
* @param pass
- * Password pertaining to the Username.
+ * Password pertaining to the Username.
* @param type
- * Permissions Type.
+ * Permissions Type.
* @param instance
- * Permissions Instance.
+ * Permissions Instance.
* @param action
- * Permissions Action.
+ * Permissions Action.
* @return
*/
@Override
@@ -123,9 +124,9 @@ public class AAFPolicyClientImpl implements AAFPolicyClient {
* Checks the Authentication of the UserName and Password Given.
*
* @param userName
- * UserName
+ * UserName
* @param pass
- * Password.
+ * Password.
* @return True or False.
*/
@Override
@@ -134,17 +135,18 @@ public class AAFPolicyClientImpl implements AAFPolicyClient {
return false;
}
try {
- int i = 0;
+ int index = 0;
do {
String aafAuthResponse = aafAuthn.validate(userName, pass);
- if (aafAuthResponse==null) {
+ if (aafAuthResponse == null) {
return true;
} else {
- logger.warn("User, " + userName + ", failed to authenticate with AAF. \n"
- + "AAF Response is " + aafAuthResponse);
+ logger.warn("User, " + userName + ", failed to authenticate with AAF. \n" + "AAF Response is "
+ + aafAuthResponse);
}
- i++;
- } while (i < 2);
+ index++;
+ }
+ while (index < 2);
} catch (Exception e) {
logger.error(e.getMessage() + e);
}
@@ -157,27 +159,27 @@ public class AAFPolicyClientImpl implements AAFPolicyClient {
* Action.
*
* @param userName
- * UserName
+ * UserName
* @param pass
- * Password.
+ * Password.
* @param type
- * Permissions Type.
+ * Permissions Type.
* @param instance
- * Permissions Instance.
+ * Permissions Instance.
* @param action
- * Permissions Action.
+ * Permissions Action.
* @return True or False.
*/
@Override
public boolean checkPerm(String userName, String pass, String type, String instance, String action) {
- int i = 0;
+ int index = 0;
Boolean result = false;
do {
if (aafCon != null && aafLurPerm != null) {
try {
aafCon.basicAuth(userName, pass);
- AAFPermission perm = new AAFPermission(cadiprops.getProperty("policy.aaf.namespace"), type,
- instance, action);
+ AAFPermission perm =
+ new AAFPermission(cadiprops.getProperty("policy.aaf.namespace"), type, instance, action);
final Principal p = new UnAuthPrincipal(userName);
result = aafLurPerm.fish(p, perm);
} catch (CadiException e) {
@@ -185,12 +187,13 @@ public class AAFPolicyClientImpl implements AAFPolicyClient {
aafLurPerm.destroy();
}
}
- i++;
- } while (i < 2 && !result); // Try once more to check if this can be passed. AAF has some issues.
+ index++;
+ }
+ while (index < 2 && !result); // Try once more to check if this can be passed. AAF has some issues.
return result;
}
- private static boolean setUpAAF() {
+ private static boolean setUpAaf() {
try {
aafCon = new AAFConHttp(access,
new PropertyLocator("https://" + cadiprops.getProperty("aaf_fqdn") + ":8100"));
diff --git a/PolicyEngineUtils/src/main/java/org/onap/policy/utils/AAFPolicyException.java b/PolicyEngineUtils/src/main/java/org/onap/policy/utils/AAFPolicyException.java
index b67b02243..c64c3c4d2 100644
--- a/PolicyEngineUtils/src/main/java/org/onap/policy/utils/AAFPolicyException.java
+++ b/PolicyEngineUtils/src/main/java/org/onap/policy/utils/AAFPolicyException.java
@@ -2,14 +2,14 @@
* ============LICENSE_START=======================================================
* PolicyEngineUtils
* ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017, 2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -21,30 +21,30 @@
package org.onap.policy.utils;
/**
- * AAFPolicyException to show exception messages.
- *
+ * AAFPolicyException to show exception messages.
+ *
*/
public class AAFPolicyException extends Exception {
- private static final long serialVersionUID = 1910606668038621L;
-
- public AAFPolicyException() {
- // Empty constructor.
- // Nothing needs to be initialized in this exception class.
- }
-
- public AAFPolicyException(String message) {
- super(message);
- }
-
- public AAFPolicyException(Throwable cause){
- super(cause);
- }
-
- public AAFPolicyException(String message, Throwable cause) {
- super(message, cause);
- }
-
- public AAFPolicyException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
- super(message, cause, enableSuppression, writableStackTrace);
- }
+ private static final long serialVersionUID = 1910606668038621L;
+
+ public AAFPolicyException() {
+ // Empty constructor.
+ // Nothing needs to be initialized in this exception class.
+ }
+
+ public AAFPolicyException(String message) {
+ super(message);
+ }
+
+ public AAFPolicyException(Throwable cause) {
+ super(cause);
+ }
+
+ public AAFPolicyException(String message, Throwable cause) {
+ super(message, cause);
+ }
+
+ public AAFPolicyException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
+ super(message, cause, enableSuppression, writableStackTrace);
+ }
}
diff --git a/PolicyEngineUtils/src/main/java/org/onap/policy/utils/BackUpHandler.java b/PolicyEngineUtils/src/main/java/org/onap/policy/utils/BackUpHandler.java
index 4dfc64c39..09cfe7832 100644
--- a/PolicyEngineUtils/src/main/java/org/onap/policy/utils/BackUpHandler.java
+++ b/PolicyEngineUtils/src/main/java/org/onap/policy/utils/BackUpHandler.java
@@ -2,14 +2,14 @@
* ============LICENSE_START=======================================================
* PolicyEngineUtils
* ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017, 2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -23,20 +23,24 @@ package org.onap.policy.utils;
import org.onap.policy.api.NotificationHandler;
import org.onap.policy.api.PDPNotification;
-public interface BackUpHandler extends NotificationHandler{
-
- /**
- * <code>notificationReceived</code> method will be triggered automatically whenever a Notification is received by the PEP.
- *
- * @param notification <code>PDPNotification</code> of {@link org.onap.policy.api.PDPNotification} is the object that has information of the notification.
- */
- @Override
- public void notificationReceived(PDPNotification notification);
-
- /**
- * <code>runOnNotification</code> method will be triggered automatically whenever a Notification is received by the PEP This needs to be the main implementation.
- *
- * @param notification <code>PDPNotification</code> of {@link org.onap.policy.api.PDPNotification} is the object that has information of the notification.
- */
- public void runOnNotification(PDPNotification notification);
+public interface BackUpHandler extends NotificationHandler {
+
+ /**
+ * <code>notificationReceived</code> method will be triggered automatically whenever a Notification is received by
+ * the PEP.
+ *
+ * @param notification <code>PDPNotification</code> of {@link org.onap.policy.api.PDPNotification} is the object
+ * that has information of the notification.
+ */
+ @Override
+ public void notificationReceived(PDPNotification notification);
+
+ /**
+ * <code>runOnNotification</code> method will be triggered automatically whenever a Notification is received by the
+ * PEP This needs to be the main implementation.
+ *
+ * @param notification <code>PDPNotification</code> of {@link org.onap.policy.api.PDPNotification} is the object
+ * that has information of the notification.
+ */
+ public void runOnNotification(PDPNotification notification);
}
diff --git a/PolicyEngineUtils/src/main/java/org/onap/policy/utils/BackUpMonitor.java b/PolicyEngineUtils/src/main/java/org/onap/policy/utils/BackUpMonitor.java
index 4f8a82100..c82e6968f 100644
--- a/PolicyEngineUtils/src/main/java/org/onap/policy/utils/BackUpMonitor.java
+++ b/PolicyEngineUtils/src/main/java/org/onap/policy/utils/BackUpMonitor.java
@@ -2,15 +2,15 @@
* ============LICENSE_START=======================================================
* PolicyEngineUtils
* ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017, 2019 AT&T Intellectual Property. All rights reserved.
* Modified Copyright (C) 2018 Samsung Electronics Co., Ltd.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -21,6 +21,13 @@
package org.onap.policy.utils;
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.github.fge.jackson.JsonLoader;
+import com.github.fge.jsonpatch.JsonPatch;
+import com.github.fge.jsonpatch.JsonPatchException;
+import com.github.fge.jsonpatch.diff.JsonDiff;
+
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
@@ -41,16 +48,9 @@ import org.onap.policy.jpa.BackUpMonitorEntity;
import org.onap.policy.std.NotificationStore;
import org.onap.policy.std.StdPDPNotification;
-import com.fasterxml.jackson.core.JsonProcessingException;
-import com.fasterxml.jackson.databind.JsonNode;
-import com.github.fge.jackson.JsonLoader;
-import com.github.fge.jsonpatch.JsonPatch;
-import com.github.fge.jsonpatch.JsonPatchException;
-import com.github.fge.jsonpatch.diff.JsonDiff;
-
/**
* BackUp Monitor checks Backup Status with the Database and maintains Redundancy for Gateway Applications.
- *
+ *
*/
public class BackUpMonitor {
private static final Logger LOGGER = Logger.getLogger(BackUpMonitor.class.getName());
@@ -58,7 +58,7 @@ public class BackUpMonitor {
private static final String PING_INTERVAL = "ping_interval";
private static final String MASTER = "MASTER";
private static final String SLAVE = "SLAVE";
-
+
private static BackUpMonitor instance = null;
private static String resourceName = null;
private static String resourceNodeName = null;
@@ -85,7 +85,7 @@ public class BackUpMonitor {
throws BackUpMonitorException {
init(resourceName, resourceNodeName, handler);
// Create Persistence Entity
- if(!properties.containsKey(PersistenceUnitProperties.ECLIPSELINK_PERSISTENCE_XML)){
+ if (!properties.containsKey(PersistenceUnitProperties.ECLIPSELINK_PERSISTENCE_XML)) {
properties.setProperty(PersistenceUnitProperties.ECLIPSELINK_PERSISTENCE_XML, "META-INF/persistencePU.xml");
}
emf = Persistence.createEntityManagerFactory("PolicyEngineUtils", properties);
@@ -100,15 +100,20 @@ public class BackUpMonitor {
// Start thread.
startThread(new BMonitor());
}
-
- private static void startThread(BMonitor bMonitor) {
- t = new Thread(bMonitor);
+
+ private static void startThread(BMonitor monitor) {
+ t = new Thread(monitor);
t.start();
}
- public static void stop() throws InterruptedException{
+ /**
+ * Stop.
+ *
+ * @throws InterruptedException InterruptedException
+ */
+ public static void stop() throws InterruptedException {
stopFlag = true;
- if(t!=null){
+ if (t != null) {
t.interrupt();
t.join();
}
@@ -124,13 +129,13 @@ public class BackUpMonitor {
/**
* Gets the BackUpMonitor Instance if given proper resourceName and properties. Else returns null.
- *
+ *
* @param resourceNodeName
- * String format of the Resource Node to which the resource Belongs to.
+ * String format of the Resource Node to which the resource Belongs to.
* @param resourceName
- * String format of the ResourceName. This needs to be Unique.
+ * String format of the ResourceName. This needs to be Unique.
* @param properties
- * Properties format of the properties file.
+ * Properties format of the properties file.
* @return BackUpMonitor instance.
*/
public static synchronized BackUpMonitor getInstance(String resourceNodeName, String resourceName,
@@ -164,8 +169,7 @@ public class BackUpMonitor {
LOGGER.error("javax.persistence.jdbc.user property is empty");
return false;
}
- if (properties.getProperty(PING_INTERVAL) == null
- || "".equals(properties.getProperty(PING_INTERVAL).trim())) {
+ if (properties.getProperty(PING_INTERVAL) == null || "".equals(properties.getProperty(PING_INTERVAL).trim())) {
LOGGER.info("ping_interval property not specified. Taking default value");
} else {
try {
@@ -186,8 +190,8 @@ public class BackUpMonitor {
}
/**
- * Gets the Boolean value of Master(True) or Slave mode (False)
- *
+ * Gets the Boolean value of Master(True) or Slave mode (False).
+ *
* @return Boolean flag which if True means that the operation needs to be performed(Master mode) or if false the
* operation is in slave mode.
*/
@@ -214,17 +218,17 @@ public class BackUpMonitor {
}
// Set Master
- private static BackUpMonitorEntity setMaster(BackUpMonitorEntity bMEntity) {
- bMEntity.setFlag(MASTER);
+ private static BackUpMonitorEntity setMaster(BackUpMonitorEntity entity) {
+ entity.setFlag(MASTER);
setFlag(true);
- return bMEntity;
+ return entity;
}
// Set Slave
- private static BackUpMonitorEntity setSlave(BackUpMonitorEntity bMEntity) {
- bMEntity.setFlag(SLAVE);
+ private static BackUpMonitorEntity setSlave(BackUpMonitorEntity entity) {
+ entity.setFlag(SLAVE);
setFlag(false);
- return bMEntity;
+ return entity;
}
// Check Database and set the Flag.
@@ -244,45 +248,45 @@ public class BackUpMonitor {
} else if (resourceNodeName.equals(ResourceNode.BRMS.toString())) {
query.setParameter("nn", ResourceNode.BRMS.toString());
}
- List<?> bMList = query.getResultList();
- if (bMList.isEmpty()) {
+ List<?> entityList = query.getResultList();
+ if (entityList.isEmpty()) {
// This is New. create an entry as Master.
LOGGER.info("Adding resource " + resourceName + " to Database");
- BackUpMonitorEntity bMEntity = new BackUpMonitorEntity();
- bMEntity.setResourceNodeName(resourceNodeName);
- bMEntity.setResourceName(resourceName);
- bMEntity = setMaster(bMEntity);
- bMEntity.setTimeStamp(new Date());
- em.persist(bMEntity);
+ BackUpMonitorEntity entity = new BackUpMonitorEntity();
+ entity.setResourceNodeName(resourceNodeName);
+ entity.setResourceName(resourceName);
+ entity = setMaster(entity);
+ entity.setTimeStamp(new Date());
+ em.persist(entity);
em.flush();
} else {
- checkOtherMaster(bMList);
+ checkOtherMaster(entityList);
}
et.commit();
} catch (Exception e) {
LOGGER.error("failed Database Operation " + e.getMessage(), e);
- if (et!=null && et.isActive()) {
+ if (et != null && et.isActive()) {
et.rollback();
}
throw new BackUpMonitorException(e);
}
}
- private void checkOtherMaster(List<?> bMList) {
+ private void checkOtherMaster(List<?> entityList) {
// Check for other Master(s)
ArrayList<BackUpMonitorEntity> masterEntities = new ArrayList<>();
// Check for self.
BackUpMonitorEntity selfEntity = null;
// Check backup monitor entities.
- for (int i = 0; i < bMList.size(); i++) {
- BackUpMonitorEntity bMEntity = (BackUpMonitorEntity) bMList.get(i);
+ for (Object entity : entityList) {
+ BackUpMonitorEntity backupEntity = (BackUpMonitorEntity) entity;
LOGGER.info("Refreshing Entity. ");
- em.refresh(bMEntity);
- if (bMEntity.getFlag().equalsIgnoreCase(MASTER)) {
- masterEntities.add(bMEntity);
+ em.refresh(backupEntity);
+ if (backupEntity.getFlag().equalsIgnoreCase(MASTER)) {
+ masterEntities.add(backupEntity);
}
- if (bMEntity.getResourceName().equals(resourceName)) {
- selfEntity = bMEntity;
+ if (backupEntity.getResourceName().equals(resourceName)) {
+ selfEntity = backupEntity;
}
}
if (selfEntity != null) {
@@ -338,8 +342,7 @@ public class BackUpMonitor {
if (masterEntities.size() == 1) {
singleMasterEntity(masterEntities, selfEntity);
} else {
- LOGGER.error(
- "Backup Monitor Issue, Masters out of sync, This will be fixed in next interval.");
+ LOGGER.error("Backup Monitor Issue, Masters out of sync, This will be fixed in next interval.");
}
}
}
@@ -365,7 +368,6 @@ public class BackUpMonitor {
em.persist(masterEntity);
em.flush();
// Lets Become Master.
- selfEntity = setMaster(selfEntity);
LOGGER.info("Changing " + resourceName + " from slave to Master Mode");
selfEntity.setTimeStamp(new Date());
selfEntity.setNotificationRecord(notificationRecord);
@@ -383,8 +385,7 @@ public class BackUpMonitor {
if (currentEntity.getFlag().equalsIgnoreCase(MASTER)) {
if (masterEntity == null) {
masterEntity = currentEntity;
- } else if (currentEntity.getTimeStamp().getTime() > masterEntity.getTimeStamp()
- .getTime()) {
+ } else if (currentEntity.getTimeStamp().getTime() > masterEntity.getTimeStamp().getTime()) {
// False Master, Update master to slave and take currentMaster as Master.
masterEntity.setFlag(SLAVE);
masterEntity.setTimeStamp(new Date());
@@ -441,10 +442,8 @@ public class BackUpMonitor {
/**
* Updates Notification in the Database while Performing the health check.
- *
- * @param notification
- * String format of notification record to store in the Database.
- * @throws Exception
+ *
+ * @throws BackUpMonitorException BackUpMonitorException
*/
public synchronized void updateNotification() throws BackUpMonitorException {
checkDataBase();
@@ -454,8 +453,8 @@ public class BackUpMonitor {
private static void callHandler(String notification) {
if (handler != null) {
try {
- PDPNotification notificationObject = PolicyUtils.jsonStringToObject(notification,
- StdPDPNotification.class);
+ PDPNotification notificationObject =
+ PolicyUtils.jsonStringToObject(notification, StdPDPNotification.class);
if (notificationObject.getNotificationType() != null) {
LOGGER.info("Performing Patched notification ");
performPatchNotification(notificationObject);
diff --git a/PolicyEngineUtils/src/main/java/org/onap/policy/utils/BackUpMonitorException.java b/PolicyEngineUtils/src/main/java/org/onap/policy/utils/BackUpMonitorException.java
index 4f7883800..60dd5e569 100644
--- a/PolicyEngineUtils/src/main/java/org/onap/policy/utils/BackUpMonitorException.java
+++ b/PolicyEngineUtils/src/main/java/org/onap/policy/utils/BackUpMonitorException.java
@@ -2,14 +2,14 @@
* ============LICENSE_START=======================================================
* PolicyEngineUtils
* ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017, 2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -20,27 +20,28 @@
package org.onap.policy.utils;
-public class BackUpMonitorException extends Exception{
+public class BackUpMonitorException extends Exception {
private static final long serialVersionUID = 6778134503685443473L;
-
+
public BackUpMonitorException() {
- // Nothing for this constructor to initialize
- // in an exception class.
+ // Nothing for this constructor to initialize
+ // in an exception class.
}
-
+
public BackUpMonitorException(String message) {
super(message);
}
-
- public BackUpMonitorException(Throwable cause){
+
+ public BackUpMonitorException(Throwable cause) {
super(cause);
}
-
+
public BackUpMonitorException(String message, Throwable cause) {
super(message, cause);
}
-
- public BackUpMonitorException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
+
+ public BackUpMonitorException(String message, Throwable cause, boolean enableSuppression,
+ boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
}
}
diff --git a/PolicyEngineUtils/src/main/java/org/onap/policy/utils/BusConsumer.java b/PolicyEngineUtils/src/main/java/org/onap/policy/utils/BusConsumer.java
index 0d4c86b3d..b64d6143e 100644
--- a/PolicyEngineUtils/src/main/java/org/onap/policy/utils/BusConsumer.java
+++ b/PolicyEngineUtils/src/main/java/org/onap/policy/utils/BusConsumer.java
@@ -2,14 +2,15 @@
* ============LICENSE_START=======================================================
* PolicyEngineUtils
* ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017, 2019 AT&T Intellectual Property. All rights reserved.
+ * Modifications copyright (c) 2019 Nokia
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -23,103 +24,100 @@ package org.onap.policy.utils;
import java.net.MalformedURLException;
import java.util.List;
import java.util.Properties;
+
import org.onap.dmaap.mr.client.MRClient.MRApiException;
import org.onap.dmaap.mr.client.impl.MRConsumerImpl;
import org.onap.dmaap.mr.test.clients.ProtocolTypeConstants;
public interface BusConsumer {
-
- /**
- * fetch messages
- *
- * @return list of messages
- * @throws MRApiException when error encountered by underlying libraries
- */
- public Iterable<String> fetch() throws MRApiException;
-
- /**
- * close underlying library consumer
- */
- public void close();
-
- /**
- * MR based consumer
- */
- public static class DmaapConsumerWrapper implements BusConsumer {
-
- /**
- * MR Consumer
- */
- protected MRConsumerImpl consumer;
-
- /**
- * MR Consumer Wrapper
- *
- * @param servers messaging bus hosts
- * @param topic topic
- * @param apiKey API Key
- * @param apiSecret API Secret
- * @param aafLogin AAF Login
- * @param aafPassword AAF Password
- * @param consumerGroup Consumer Group
- * @param consumerInstance Consumer Instance
- * @param fetchTimeout Fetch Timeout
- * @param fetchLimit Fetch Limit
- */
- public DmaapConsumerWrapper(List<String> servers, String topic,
- String aafLogin, String aafPassword,
- String consumerGroup, String consumerInstance,
- int fetchTimeout, int fetchLimit) throws MalformedURLException{
-
- this.consumer = new MRConsumerImpl(servers, topic,
- consumerGroup, consumerInstance,
- fetchTimeout, fetchLimit,
- null, aafLogin, aafPassword);
-
- this.consumer.setUsername(aafLogin);
- this.consumer.setPassword(aafPassword);
-
- this.consumer.setProtocolFlag(ProtocolTypeConstants.AAF_AUTH.getValue());
-
- Properties props = new Properties();
- props.setProperty("Protocol", "http");
- this.consumer.setProps(props);
- this.consumer.setHost(servers.get(0) + ":3904");
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- public Iterable<String> fetch() throws MRApiException {
- try {
- return this.consumer.fetch();
+
+ /**
+ * fetch messages.
+ *
+ * @return list of messages
+ * @throws MRApiException when error encountered by underlying libraries
+ */
+ Iterable<String> fetch() throws MRApiException;
+
+ /**
+ * close underlying library consumer.
+ */
+ void close();
+
+ /**
+ * MR based consumer.
+ */
+ class DmaapConsumerWrapper implements BusConsumer {
+
+ /**
+ * MR Consumer.
+ */
+ protected MRConsumerImpl consumer;
+
+ /**
+ * MR Consumer Wrapper.
+ *
+ * @param servers messaging bus hosts
+ * @param topic topic
+ * @param apiKey API Key
+ * @param apiSecret API Secret
+ * @param aafLogin AAF Login
+ * @param aafPassword AAF Password
+ * @param consumerGroup Consumer Group
+ * @param consumerInstance Consumer Instance
+ * @param fetchTimeout Fetch Timeout
+ * @param fetchLimit Fetch Limit
+ */
+ public DmaapConsumerWrapper(List<String> servers, String topic, String aafLogin, String aafPassword,
+ String consumerGroup, String consumerInstance, int fetchTimeout, int fetchLimit)
+ throws MalformedURLException {
+
+ this(new MRConsumerImpl(servers, topic, consumerGroup, consumerInstance, fetchTimeout, fetchLimit, null,
+ aafLogin, aafPassword), aafLogin, aafPassword, servers.get(0));
+
+ }
+
+ DmaapConsumerWrapper(MRConsumerImpl consumer, String aafLogin, String aafPassword, String host) {
+ this.consumer = consumer;
+ this.consumer.setUsername(aafLogin);
+ this.consumer.setPassword(aafPassword);
+ this.consumer.setProtocolFlag(ProtocolTypeConstants.AAF_AUTH.getValue());
+ this.consumer.setHost(host + ":3904");
+
+ Properties props = new Properties();
+ props.setProperty("Protocol", "http");
+ this.consumer.setProps(props);
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ public Iterable<String> fetch() throws MRApiException {
+ try {
+ return consumer.fetch();
} catch (Exception e) {
- throw new MRApiException("Error during MR consumer Fetch ",e);
+ throw new MRApiException("Error during MR consumer Fetch ", e);
}
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- public void close() {
- this.consumer.close();
- }
-
- @Override
- public String toString() {
- StringBuilder builder = new StringBuilder();
- builder.
- append("DmaapConsumerWrapper [").
- append("consumer.getAuthDate()=").append(consumer.getAuthDate()).
- append(", consumer.getAuthKey()=").append(consumer.getAuthKey()).
- append(", consumer.getHost()=").append(consumer.getHost()).
- append(", consumer.getProtocolFlag()=").append(consumer.getProtocolFlag()).
- append(", consumer.getUsername()=").append(consumer.getUsername()).
- append("]");
- return builder.toString();
- }
- }
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ public void close() {
+ this.consumer.close();
+ }
+ @Override
+ public String toString() {
+ StringBuilder builder = new StringBuilder();
+ builder.append("DmaapConsumerWrapper [").append("consumer.getAuthDate()=").append(consumer.getAuthDate())
+ .append(", consumer.getAuthKey()=").append(consumer.getAuthKey()).append(", consumer.getHost()=")
+ .append(consumer.getHost()).append(", consumer.getProtocolFlag()=")
+ .append(consumer.getProtocolFlag()).append(", consumer.getUsername()=")
+ .append(consumer.getUsername()).append("]");
+ return builder.toString();
+ }
+ }
}
diff --git a/PolicyEngineUtils/src/main/java/org/onap/policy/utils/BusPublisher.java b/PolicyEngineUtils/src/main/java/org/onap/policy/utils/BusPublisher.java
index 745213529..f5c792caf 100644
--- a/PolicyEngineUtils/src/main/java/org/onap/policy/utils/BusPublisher.java
+++ b/PolicyEngineUtils/src/main/java/org/onap/policy/utils/BusPublisher.java
@@ -2,14 +2,14 @@
* ============LICENSE_START=======================================================
* PolicyEngineUtils
* ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017, 2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -24,6 +24,7 @@ import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.concurrent.TimeUnit;
+
import org.onap.dmaap.mr.client.impl.MRSimplerBatchPublisher;
import org.onap.dmaap.mr.test.clients.ProtocolTypeConstants;
import org.onap.policy.common.logging.eelf.PolicyLogger;
@@ -31,109 +32,109 @@ import org.onap.policy.common.logging.flexlogger.FlexLogger;
import org.onap.policy.common.logging.flexlogger.Logger;
public interface BusPublisher {
-
- /**
- * sends a message
- *
- * @param partition id
- * @param message the message
- * @return true if success, false otherwise
- * @throws IllegalArgumentException if no message provided
- */
- public boolean send(String partitionId, String message);
-
- /**
- * closes the publisher
- */
- public void close();
-
- /**
- * DmaapClient library wrapper
- */
- public static class DmaapPublisherWrapper implements BusPublisher {
- private static Logger logger = FlexLogger.getLogger(DmaapPublisherWrapper.class);
- /**
- * MR based Publisher
- */
- protected MRSimplerBatchPublisher publisher;
-
- public DmaapPublisherWrapper(List<String> servers, String topic,
- String aafLogin,
- String aafPassword) {
-
- ArrayList<String> dmaapServers = new ArrayList<>();
- for (String server: servers) {
- dmaapServers.add(server + ":3904");
- }
-
- this.publisher =
- new MRSimplerBatchPublisher.Builder().
- againstUrls(dmaapServers).
- onTopic(topic).
- build();
-
- this.publisher.setProtocolFlag(ProtocolTypeConstants.AAF_AUTH.getValue());
-
- this.publisher.setUsername(aafLogin);
- this.publisher.setPassword(aafPassword);
-
- Properties props = new Properties();
- props.setProperty("Protocol", "http");
- props.setProperty("contenttype", "application/json");
-
- this.publisher.setProps(props);
-
- this.publisher.setHost(servers.get(0));
-
- if (PolicyLogger.isInfoEnabled())
- PolicyLogger.info(DmaapPublisherWrapper.class.getName(),
- "CREATION: " + this);
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- public void close() {
- if (logger.isInfoEnabled())
- logger.info(DmaapPublisherWrapper.class.getName()+
- "CREATION: " + this);
-
- try {
- this.publisher.close(1, TimeUnit.SECONDS);
- } catch (Exception e) {
- logger.warn(DmaapPublisherWrapper.class.getName()+
- "CLOSE: " + this + " because of " +
- e.getMessage(), e);
- }
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- public boolean send(String partitionId, String message){
- if (message == null)
- throw new IllegalArgumentException("No message provided");
-
- this.publisher.send(partitionId, message);
- return true;
-
- }
-
- @Override
- public String toString() {
- StringBuilder builder = new StringBuilder();
- builder.append("DmaapPublisherWrapper [").
- append("publisher.getAuthDate()=").append(publisher.getAuthDate()).
- append(", publisher.getAuthKey()=").append(publisher.getAuthKey()).
- append(", publisher.getHost()=").append(publisher.getHost()).
- append(", publisher.getProtocolFlag()=").append(publisher.getProtocolFlag()).
- append(", publisher.getUsername()=").append(publisher.getUsername()).
- append(", publisher.getPendingMessageCount()=").append(publisher.getPendingMessageCount()).
- append("]");
- return builder.toString();
- }
- }
+
+ /**
+ * sends a message
+ * .
+ * @param partitionId id
+ * @param message the message
+ * @return true if success, false otherwise
+ * @throws IllegalArgumentException if no message provided
+ */
+ public boolean send(String partitionId, String message);
+
+ /**
+ * closes the publisher.
+ */
+ public void close();
+
+ /**
+ * DmaapClient library wrapper.
+ */
+ public static class DmaapPublisherWrapper implements BusPublisher {
+ private static Logger logger = FlexLogger.getLogger(DmaapPublisherWrapper.class);
+ /**
+ * MR based Publisher.
+ */
+ protected MRSimplerBatchPublisher publisher;
+
+ /**
+ * DmaapPublisherWrapper constructor.
+ *
+ * @param servers list of servers
+ * @param topic topic
+ * @param aafLogin login
+ * @param aafPassword password
+ */
+ public DmaapPublisherWrapper(List<String> servers, String topic, String aafLogin, String aafPassword) {
+
+ ArrayList<String> dmaapServers = new ArrayList<>();
+ for (String server : servers) {
+ dmaapServers.add(server + ":3904");
+ }
+
+ this.publisher = new MRSimplerBatchPublisher.Builder().againstUrls(dmaapServers).onTopic(topic).build();
+
+ this.publisher.setProtocolFlag(ProtocolTypeConstants.AAF_AUTH.getValue());
+
+ this.publisher.setUsername(aafLogin);
+ this.publisher.setPassword(aafPassword);
+
+ Properties props = new Properties();
+ props.setProperty("Protocol", "http");
+ props.setProperty("contenttype", "application/json");
+
+ this.publisher.setProps(props);
+
+ this.publisher.setHost(servers.get(0));
+
+ if (PolicyLogger.isInfoEnabled()) {
+ PolicyLogger.info(DmaapPublisherWrapper.class.getName(), "CREATION: " + this);
+ }
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ public void close() {
+ if (logger.isInfoEnabled()) {
+ logger.info(DmaapPublisherWrapper.class.getName() + "CREATION: " + this);
+ }
+
+ try {
+ this.publisher.close(1, TimeUnit.SECONDS);
+ } catch (Exception e) {
+ logger.warn(DmaapPublisherWrapper.class.getName() + "CLOSE: " + this + " because of " + e.getMessage(),
+ e);
+ }
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ public boolean send(String partitionId, String message) {
+ if (message == null) {
+ throw new IllegalArgumentException("No message provided");
+ }
+
+ this.publisher.send(partitionId, message);
+ return true;
+
+ }
+
+ @Override
+ public String toString() {
+ StringBuilder builder = new StringBuilder();
+ builder.append("DmaapPublisherWrapper [").append("publisher.getAuthDate()=").append(publisher.getAuthDate())
+ .append(", publisher.getAuthKey()=").append(publisher.getAuthKey()).append(", publisher.getHost()=")
+ .append(publisher.getHost()).append(", publisher.getProtocolFlag()=")
+ .append(publisher.getProtocolFlag()).append(", publisher.getUsername()=")
+ .append(publisher.getUsername()).append(", publisher.getPendingMessageCount()=")
+ .append(publisher.getPendingMessageCount()).append("]");
+ return builder.toString();
+ }
+ }
}
diff --git a/PolicyEngineUtils/src/main/java/org/onap/policy/utils/PeCryptoUtils.java b/PolicyEngineUtils/src/main/java/org/onap/policy/utils/PeCryptoUtils.java
index 9863f03ad..2ffdae159 100644
--- a/PolicyEngineUtils/src/main/java/org/onap/policy/utils/PeCryptoUtils.java
+++ b/PolicyEngineUtils/src/main/java/org/onap/policy/utils/PeCryptoUtils.java
@@ -20,25 +20,22 @@
package org.onap.policy.utils;
-import java.security.GeneralSecurityException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
+
import org.apache.commons.lang3.StringUtils;
-import org.onap.policy.common.logging.flexlogger.FlexLogger;
-import org.onap.policy.common.logging.flexlogger.Logger;
import org.onap.policy.common.utils.security.CryptoUtils;
public class PeCryptoUtils {
- private static Logger logger = FlexLogger.getLogger(PeCryptoUtils.class);
private static final String PROP_AES_KEY = "org.onap.policy.encryption.aes.key";
private static CryptoUtils cryptoUtils = null;
private static String secretKey = System.getenv("AES_ENCRYPTION_KEY");
private static final Map<String, String> decryptCache = new ConcurrentHashMap<>();
private static final Map<String, String> encryptCache = new ConcurrentHashMap<>();
-
- private PeCryptoUtils() {}
+ private PeCryptoUtils() {
+ }
/**
* Inits the aes key.
@@ -65,19 +62,10 @@ public class PeCryptoUtils {
* @return The encrypted String
*/
public static String encrypt(String value) {
-
if (cryptoUtils == null || StringUtils.isBlank(value)) {
return value;
}
-
- return encryptCache.computeIfAbsent(value, k -> {
- try {
- return cryptoUtils.encrypt(k);
- } catch (GeneralSecurityException e) {
- logger.error("Could not decrypt value - exception: ", e);
- return value;
- }
- });
+ return encryptCache.computeIfAbsent(value, cryptoUtils::encrypt);
}
/**
@@ -90,13 +78,6 @@ public class PeCryptoUtils {
if (cryptoUtils == null || StringUtils.isBlank(value)) {
return value;
}
- return decryptCache.computeIfAbsent(value, k -> {
- try {
- return cryptoUtils.decrypt(k);
- } catch (GeneralSecurityException e) {
- logger.error("Could not decrypt value - exception: ", e);
- return value;
- }
- });
+ return decryptCache.computeIfAbsent(value, cryptoUtils::decrypt);
}
}
diff --git a/PolicyEngineUtils/src/main/java/org/onap/policy/utils/PolicyAccess.java b/PolicyEngineUtils/src/main/java/org/onap/policy/utils/PolicyAccess.java
index 1994578e6..950103c86 100644
--- a/PolicyEngineUtils/src/main/java/org/onap/policy/utils/PolicyAccess.java
+++ b/PolicyEngineUtils/src/main/java/org/onap/policy/utils/PolicyAccess.java
@@ -2,14 +2,14 @@
* ============LICENSE_START=======================================================
* PolicyEngineUtils
* ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017, 2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -24,14 +24,13 @@ import java.util.Properties;
import org.onap.aaf.cadi.PropAccess;
-
/**
- * PolicyAccess used by AAF for logging purposes.
- *
+ * PolicyAccess used by AAF for logging purposes.
+ *
*/
public class PolicyAccess extends PropAccess {
- public PolicyAccess (Properties props, Level level) {
- super(props);
- this.setLogLevel(level);
- }
+ public PolicyAccess(Properties props, Level level) {
+ super(props);
+ this.setLogLevel(level);
+ }
}
diff --git a/PolicyEngineUtils/src/main/java/org/onap/policy/utils/PolicyUtils.java b/PolicyEngineUtils/src/main/java/org/onap/policy/utils/PolicyUtils.java
index 67210c814..7d70da2f7 100644
--- a/PolicyEngineUtils/src/main/java/org/onap/policy/utils/PolicyUtils.java
+++ b/PolicyEngineUtils/src/main/java/org/onap/policy/utils/PolicyUtils.java
@@ -2,14 +2,14 @@
* ============LICENSE_START=======================================================
* PolicyEngineUtils
* ================================================================================
- * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -20,6 +20,12 @@
package org.onap.policy.utils;
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.google.common.base.CharMatcher;
+import com.google.gson.JsonParser;
+import com.google.gson.JsonSyntaxException;
+
import java.io.IOException;
import java.io.StringReader;
import java.io.UnsupportedEncodingException;
@@ -38,7 +44,6 @@ import javax.xml.parsers.SAXParserFactory;
import org.drools.core.io.impl.ReaderResource;
import org.drools.verifier.Verifier;
import org.drools.verifier.VerifierError;
-import org.drools.verifier.builder.VerifierBuilder;
import org.drools.verifier.builder.VerifierBuilderFactory;
import org.kie.api.io.ResourceType;
import org.onap.policy.common.logging.flexlogger.FlexLogger;
@@ -46,295 +51,291 @@ import org.onap.policy.common.logging.flexlogger.Logger;
import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;
-import com.fasterxml.jackson.core.JsonProcessingException;
-import com.fasterxml.jackson.databind.ObjectMapper;
-import com.google.common.base.CharMatcher;
-import com.google.gson.JsonParser;
-import com.google.gson.JsonSyntaxException;
-
public class PolicyUtils {
private static final Logger LOGGER = FlexLogger.getLogger(PolicyUtils.class);
- public static final String CATCH_EXCEPTION = "PE500: An exception was caught.";
- public 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,})$";
private static final String PACKAGE_ERROR = "mismatched input '{' expecting one of the following tokens: '[package";
+
+ public static final String CATCH_EXCEPTION = "PE500: An exception was caught.";
+ public 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,})$";
public static final String SUCCESS = "success";
-
- private PolicyUtils(){
+ public static final String CHARACTER_ENCODING = "UTF-8";
+ public static final String APPLICATION_JSON = "application/json";
+
+ private PolicyUtils() {
// Private Constructor
}
-
+
/**
- * Converts an Object to JSON String
- *
- * @param o Object
- * @return String format of Object JSON.
- * @throws JsonProcessingException
+ * Converts an Object to JSON String.
+ *
+ * @param object Object
+ * @return String format of Object JSON.
+ * @throws JsonProcessingException JsonProcessingException
*/
- public static String objectToJsonString(Object o) throws JsonProcessingException{
- ObjectMapper mapper = new ObjectMapper();
- return mapper.writeValueAsString(o);
+ public static String objectToJsonString(Object object) throws JsonProcessingException {
+ return new ObjectMapper().writeValueAsString(object);
}
-
+
/**
- * Converts JSON string into Object
- *
- * @param jsonString
- * @param className equivalent Class of the given JSON string
- * @return T instance of the class given.
- * @throws IOException
+ * Converts JSON string into Object.
+ *
+ * @param jsonString Input JSON String
+ * @param className equivalent Class of the given JSON string
+ * @return T instance of the class given.
+ * @throws IOException IOException
*/
- public static <T> T jsonStringToObject(String jsonString, Class<T> className) throws IOException{
+ public static <T> T jsonStringToObject(String jsonString, Class<T> className) throws IOException {
ObjectMapper mapper = new ObjectMapper();
return mapper.readValue(jsonString, className);
}
-
+
/**
- * Decode a base64 string
- *
- * @param encodedString
+ * Decode a base64 string.
+ *
+ * @param encodedString String to encode
* @return String
- * @throws UnsupportedEncodingException
+ * @throws UnsupportedEncodingException UnsupportedEncodingException
*/
- public static String decode(String encodedString) throws UnsupportedEncodingException {
- if(encodedString!=null && !encodedString.isEmpty()){
- return new String(Base64.getDecoder().decode(encodedString) ,"UTF-8");
- }else{
- return null;
- }
+ public static String decode(String encodedString) throws UnsupportedEncodingException {
+ if (encodedString != null && !encodedString.isEmpty()) {
+ return new String(Base64.getDecoder().decode(encodedString), "UTF-8");
+ } else {
+ return null;
+ }
}
-
+
/**
- * Decodes Basic Authentication
- *
- * @param encodedValue
- * @return
- * @throws UnsupportedEncodingException
+ * Decodes Basic Authentication.
+ *
+ * @param encodedValue value to encode
+ * @return list of String
+ * @throws UnsupportedEncodingException UnsupportedEncodingException
*/
public static String[] decodeBasicEncoding(String encodedValue) throws UnsupportedEncodingException {
- if(encodedValue!=null && encodedValue.contains("Basic ")){
- String encodedUserPassword = encodedValue.replaceFirst("Basic" + " ", "");
+ if (encodedValue != null && encodedValue.contains("Basic ")) {
+ String encodedUserPassword = encodedValue.replaceFirst("Basic" + " ", "");
String usernameAndPassword;
byte[] decodedBytes = Base64.getDecoder().decode(encodedUserPassword);
usernameAndPassword = new String(decodedBytes, "UTF-8");
StringTokenizer tokenizer = new StringTokenizer(usernameAndPassword, ":");
String username = tokenizer.nextToken();
String password = tokenizer.nextToken();
- return new String[]{username, password};
- }else{
- return new String[]{};
+ return new String[] {username, password};
+ } else {
+ return new String[] {};
}
}
-
+
/**
- * Validate a field if contains space or unacceptable policy input and return "success" if good.
- *
- * @param field
- * @return
+ * Validate a field if contains space or unacceptable policy input and return "success" if good.
+ *
+ * @param field String
+ * @return String
*/
- public static String policySpecialCharValidator(String field){
+ public static String policySpecialCharValidator(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;
+ error = "The Value in Required Field will allow only"
+ + " '{0-9}, {a-z}, {A-Z}, _' following set of Combinations";
+ return error;
}
- return SUCCESS;
- }
-
+ return SUCCESS;
+ }
+
/**
- * Validate a field (accepts space) if it contains unacceptable policy input and return "success" if good.
- *
- * @param field
+ * Validate a field (accepts space) if it contains unacceptable policy input and return "success" if good.
+ *
+ * @param field Input field String
* @return
*/
- public static String policySpecialCharWithSpaceValidator(String field){
+ public static String policySpecialCharWithSpaceValidator(String field) {
String error;
if ("".equals(field) || !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";
+ error = "The Value in Required Field will allow only "
+ + "'{0-9}, {a-z}, {A-Z}, _' following set of Combinations";
return error;
}
- return SUCCESS;
- }
-
+ return SUCCESS;
+ }
+
/**
- * Validate a field (accepts Dash) if it contains unacceptable policy input and return "success" if good.
- *
- * @param field
- * @return
+ * Validate a field (accepts Dash) if it contains unacceptable policy input and return "success" if good.
+ *
+ * @param field String
+ * @return String
*/
- public static String policySpecialCharWithDashValidator(String field){
+ public static String policySpecialCharWithDashValidator(String field) {
String error;
if ("".equals(field) || !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";
+ error = "The Value in Required Field will allow only "
+ + "'{0-9}, {a-z}, {A-Z}, _, -' following set of Combinations";
return error;
}
- return SUCCESS;
- }
-
+ return SUCCESS;
+ }
+
/**
- * Validate the XACML description tag and return "success" if good.
- *
- * @param field
- * @return
+ * Validate the XACML description tag and return "success" if good.
+ *
+ * @param field String
+ * @return String
*/
public static 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;
+ error = "The value in the description shouldn't contain @CreatedBy: or @ModifiedBy:";
+ return error;
} else {
error = SUCCESS;
}
- return error;
+ return error;
}
-
+
/**
- * Validate if string contains non ASCII characters
- *
- * @param value
- * @return
+ * Validate if string contains non ASCII characters.
+ *
+ * @param value String
+ * @return true if contains non ASCII characters
*/
public static boolean containsNonAsciiEmptyChars(String value) {
- return (value == null || value.contains(" ") || "".equals(value.trim()) || !CharMatcher.ascii().matchesAllOf((CharSequence) value)) ? true : false;
+ return (value == null || value.contains(" ") || "".equals(value.trim())
+ || !CharMatcher.ascii().matchesAllOf(value)) ? true : false;
}
-
+
/**
- * Validate if given string is an integer.
- *
- * @param number
- * @return
+ * Validate if given string is an integer.
+ *
+ * @param number String representing a number
+ * @return true if integer
*/
- public static Boolean isInteger(String number){
- if(number==null) {
+ public static Boolean isInteger(String number) {
+ if (number == null) {
return false;
}
- for (char c : number.toCharArray()){
+ for (char c : number.toCharArray()) {
if (!Character.isDigit(c)) {
- return false;
+ return false;
}
}
return true;
}
-
+
/**
- * Validate Email Address and return "success" if good.
- *
- * @param emailAddressValue
- * @return
+ * Validate Email Address and return "success" if good.
+ *
+ * @param emailAddressValue String email address
+ * @return SUCCESS String if valid
*/
public static String validateEmailAddress(String emailAddressValue) {
String error = SUCCESS;
List<String> emailList = Arrays.asList(emailAddressValue.split(","));
- for(int i =0 ; i < emailList.size() ; i++){
+ for (int i = 0; i < emailList.size(); i++) {
Pattern pattern = Pattern.compile(EMAIL_PATTERN);
Matcher matcher = pattern.matcher(emailList.get(i).trim());
- if(!matcher.matches()){
- error = "Please check the Following Email Address is not Valid .... " +emailList.get(i);
+ if (!matcher.matches()) {
+ error = "Please check the Following Email Address is not Valid .... " + emailList.get(i);
return error;
- }else{
+ } else {
error = SUCCESS;
}
}
- return error;
+ return error;
}
-
+
/**
* Validates BRMS rule as per Policy Platform and return string contains "[ERR" if there are any errors.
- *
- * @param rule
+ *
+ * @param rule BRMS Rule
* @return String error message
*/
- public static String brmsRawValidate(String rule){
- VerifierBuilder vBuilder = VerifierBuilderFactory.newVerifierBuilder();
- Verifier verifier = vBuilder.newVerifier();
+ public static String brmsRawValidate(String rule) {
+ Verifier verifier = VerifierBuilderFactory.newVerifierBuilder().newVerifier();
verifier.addResourcesToVerify(new ReaderResource(new StringReader(rule)), ResourceType.DRL);
- // Check if there are any Errors in Verification.
- if(!verifier.getErrors().isEmpty()){
+ // Check if there are any Errors in Verification.
+ if (!verifier.getErrors().isEmpty()) {
boolean ignore = false;
- StringBuilder message = new StringBuilder("Not a Valid DRL rule");
- for(VerifierError error: verifier.getErrors()){
+ StringBuilder message = new StringBuilder("Not a Valid DRL rule");
+ for (VerifierError error : verifier.getErrors()) {
// Ignore annotations Error Messages
- if(!error.getMessage().contains("'@'") && !error.getMessage().contains(PACKAGE_ERROR)){
- ignore= true;
+ if (!error.getMessage().contains("'@'") && !error.getMessage().contains(PACKAGE_ERROR)) {
+ ignore = true;
message.append("\n" + error.getMessage());
}
}
// Ignore new package names with '{'
// More checks for message to check if its a package error.
- if(ignore && !message.toString().contains("Parser returned a null Package")){
+ if (ignore && !message.toString().contains("Parser returned a null Package")) {
message.append("[ERR 107]");
}
return message.toString();
}
return "";
}
-
+
/**
- * Validates if the given string is proper JSON format.
- *
- * @param data
- * @return
+ * Validates if the given string is proper JSON format.
+ *
+ * @param data JSON data
+ * @return true if it is JSON
*/
public static boolean isJSONValid(String data) {
- try{
+ try {
JsonParser parser = new JsonParser();
parser.parse(data);
- }catch(JsonSyntaxException e){
- LOGGER.error("Exception Occurred While Validating"+e);
+ } catch (JsonSyntaxException e) {
+ LOGGER.error("Exception Occurred While Validating" + e);
return false;
}
return true;
}
/**
- * Validates if the given string is proper XML format.
- *
- * @param data
- * @return
+ * Validates if the given string is proper XML format.
+ *
+ * @param data XML data
+ * @return true if it is XML
*/
public static boolean isXMLValid(String data) {
- if(data == null || data.isEmpty()){
- return false;
+ if (data == null || data.isEmpty()) {
+ return false;
}
SAXParserFactory factory = SAXParserFactory.newInstance();
factory.setValidating(false);
factory.setNamespaceAware(true);
-
- try {
- factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
+
+ try {
+ factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
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);
+ LOGGER.error("Exception Occured While Validating" + e);
return false;
}
return true;
}
/**
- * Validates if given string is valid Properties format.
- *
- * @param prop
- * @return
+ * Validates if given string is valid Properties format.
+ *
+ * @param prop String of properties
+ * @return is valid property format
*/
public static 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.startsWith("#")) {
if (line.contains("=")) {
String[] parts = line.split("=");
if (parts.length < 2) {
scanner.close();
return false;
}
- } else if(!line.trim().isEmpty()){
+ } else if (!line.trim().isEmpty()) {
scanner.close();
return false;
}
@@ -343,15 +344,15 @@ public class PolicyUtils {
scanner.close();
return true;
}
-
+
/**
* Given a version string consisting of integers with dots between them, convert it into an array of integers.
- *
- * @param version
- * @return
- * @throws NumberFormatException
+ *
+ * @param version String representing the version
+ * @return array of int
+ * @throws NumberFormatException NumberFormatException
*/
- public static int[] versionStringToArray(String version){
+ public static int[] versionStringToArray(String version) {
if (version == null || version.length() == 0) {
return new int[0];
}
@@ -362,4 +363,4 @@ public class PolicyUtils {
}
return resultArray;
}
-} \ No newline at end of file
+}
diff --git a/PolicyEngineUtils/src/main/java/org/onap/policy/utils/XMLErrorHandler.java b/PolicyEngineUtils/src/main/java/org/onap/policy/utils/XMLErrorHandler.java
index 3037a423c..00251ee2d 100644
--- a/PolicyEngineUtils/src/main/java/org/onap/policy/utils/XMLErrorHandler.java
+++ b/PolicyEngineUtils/src/main/java/org/onap/policy/utils/XMLErrorHandler.java
@@ -2,14 +2,14 @@
* ============LICENSE_START=======================================================
* PolicyEngineUtils
* ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017, 2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -28,7 +28,7 @@ import org.xml.sax.SAXParseException;
public class XMLErrorHandler implements ErrorHandler {
private static final Logger LOGGER = FlexLogger.getLogger(XMLErrorHandler.class);
-
+
@Override
public void warning(SAXParseException exception) throws SAXException {
LOGGER.debug(exception);
diff --git a/PolicyEngineUtils/src/main/resources/META-INF/persistencePU.xml b/PolicyEngineUtils/src/main/resources/META-INF/persistencePU.xml
index 6cd88bf28..93a2acf05 100644
--- a/PolicyEngineUtils/src/main/resources/META-INF/persistencePU.xml
+++ b/PolicyEngineUtils/src/main/resources/META-INF/persistencePU.xml
@@ -3,14 +3,14 @@
============LICENSE_START=======================================================
PolicyEngineUtils
================================================================================
- Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ Copyright (C) 2017, 2019 AT&T Intellectual Property. All rights reserved.
================================================================================
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
-
+
http://www.apache.org/licenses/LICENSE-2.0
-
+
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -20,10 +20,12 @@
-->
<persistence version="2.1"
- xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
- <persistence-unit name="PolicyEngineUtils" transaction-type="RESOURCE_LOCAL">
- <provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
- <class>org.onap.policy.jpa.BackUpMonitorEntity</class>
- </persistence-unit>
+ xmlns="http://xmlns.jcp.org/xml/ns/persistence"
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
+ <persistence-unit name="PolicyEngineUtils"
+ transaction-type="RESOURCE_LOCAL">
+ <provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
+ <class>org.onap.policy.jpa.BackUpMonitorEntity</class>
+ </persistence-unit>
</persistence>
diff --git a/PolicyEngineUtils/src/test/java/org/onap/policy/utils/AAFEnvironmentTest.java b/PolicyEngineUtils/src/test/java/org/onap/policy/utils/AAFEnvironmentTest.java
new file mode 100644
index 000000000..cf997251c
--- /dev/null
+++ b/PolicyEngineUtils/src/test/java/org/onap/policy/utils/AAFEnvironmentTest.java
@@ -0,0 +1,39 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * PolicyEngineUtils
+ * ================================================================================
+ * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 static org.junit.Assert.assertEquals;
+
+import org.junit.Test;
+
+public class AAFEnvironmentTest {
+
+ @Test
+ public void test() {
+ AAFEnvironment env = AAFEnvironment.DEVL;
+ assertEquals(AAFEnvironment.DEVL, env);
+ env = AAFEnvironment.PROD;
+ assertEquals(AAFEnvironment.PROD, env);
+ env = AAFEnvironment.TEST;
+ assertEquals(AAFEnvironment.TEST, env);
+ }
+
+}
diff --git a/PolicyEngineUtils/src/test/java/org/onap/policy/utils/test/BusTest.java b/PolicyEngineUtils/src/test/java/org/onap/policy/utils/BusTest.java
index 37f0bb016..50d91c6fc 100644
--- a/PolicyEngineUtils/src/test/java/org/onap/policy/utils/test/BusTest.java
+++ b/PolicyEngineUtils/src/test/java/org/onap/policy/utils/BusTest.java
@@ -2,14 +2,15 @@
* ============LICENSE_START=======================================================
* PolicyEngineUtils
* ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017, 2019 AT&T Intellectual Property. All rights reserved.
+ * Modifications copyright (c) 2019 Nokia
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -18,38 +19,50 @@
* ============LICENSE_END=========================================================
*/
-package org.onap.policy.utils.test;
+package org.onap.policy.utils;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
import java.net.MalformedURLException;
import java.util.Arrays;
import org.junit.Test;
import org.onap.dmaap.mr.client.MRClient.MRApiException;
-import org.onap.policy.utils.BusConsumer;
-import org.onap.policy.utils.BusPublisher;
+import org.onap.dmaap.mr.client.impl.MRConsumerImpl;
+import org.onap.policy.utils.BusConsumer.DmaapConsumerWrapper;
public class BusTest {
-
- @Test
- public void busPublisherTest(){
+
+ @Test
+ public void busPublisherTest() {
BusPublisher bus = new BusPublisher.DmaapPublisherWrapper(Arrays.asList("test"), "test", "test", "test");
assertTrue(bus.send("test123", "Hello World!"));
- assertEquals("DmaapPublisherWrapper [publisher.getAuthDate()=null, publisher.getAuthKey()=null, publisher.getHost()=test, publisher.getProtocolFlag()=HTTPAAF, publisher.getUsername()=test, publisher.getPendingMessageCount()=1]",bus.toString());
+ assertEquals(
+ "DmaapPublisherWrapper [publisher.getAuthDate()=null, publisher.getAuthKey()=null, publisher.getHost()=test, publisher.getProtocolFlag()=HTTPAAF, publisher.getUsername()=test, publisher.getPendingMessageCount()=1]",
+ bus.toString());
bus.close();
}
-
- @Test (expected = MRApiException.class)
- public void busConsumerFailTest() throws MalformedURLException, MRApiException{
- new BusConsumer.DmaapConsumerWrapper(Arrays.asList("test"), "test", "test", "test", "test", "test", 1, 1).fetch();
+
+ @Test(expected = MRApiException.class)
+ public void busConsumerFailTest() throws Exception {
+ // given
+ MRConsumerImpl mrConsumer = mock(MRConsumerImpl.class);
+ when(mrConsumer.fetch()).thenThrow(new Exception());
+ DmaapConsumerWrapper dmaapConsumerWrapper = new DmaapConsumerWrapper(mrConsumer, "", "", "");
+
+ // when
+ dmaapConsumerWrapper.fetch();
}
-
+
@Test
- public void busConsumerTest() throws MalformedURLException, MRApiException{
- BusConsumer bus = new BusConsumer.DmaapConsumerWrapper(Arrays.asList("test"), "test", "test", "test", "test", "test", 1, 1);
- assertEquals(bus.toString(),"DmaapConsumerWrapper [consumer.getAuthDate()=null, consumer.getAuthKey()=null, consumer.getHost()=test:3904, consumer.getProtocolFlag()=HTTPAAF, consumer.getUsername()=test]");
+ public void busConsumerTest() throws MalformedURLException, MRApiException {
+ BusConsumer bus = new BusConsumer.DmaapConsumerWrapper(Arrays.asList("test"), "test", "test", "test", "test",
+ "test", 1, 1);
+ assertEquals(bus.toString(),
+ "DmaapConsumerWrapper [consumer.getAuthDate()=null, consumer.getAuthKey()=null, consumer.getHost()=test:3904, consumer.getProtocolFlag()=HTTPAAF, consumer.getUsername()=test]");
bus.close();
}
diff --git a/PolicyEngineUtils/src/test/java/org/onap/policy/utils/PeCryptoUtilsTest.java b/PolicyEngineUtils/src/test/java/org/onap/policy/utils/PeCryptoUtilsTest.java
index 3765ff2e3..28b1fb4e8 100644
--- a/PolicyEngineUtils/src/test/java/org/onap/policy/utils/PeCryptoUtilsTest.java
+++ b/PolicyEngineUtils/src/test/java/org/onap/policy/utils/PeCryptoUtilsTest.java
@@ -22,12 +22,13 @@ package org.onap.policy.utils;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
+
import java.security.GeneralSecurityException;
+
import org.junit.Before;
import org.junit.Test;
import org.powermock.reflect.Whitebox;
-
public class PeCryptoUtilsTest {
private final String pass = "policy_user";
private final String secretKey = "bmpybWJrbGN4dG9wbGF3Zg==";
@@ -36,7 +37,7 @@ public class PeCryptoUtilsTest {
@Before
public void reset() {
- Whitebox.setInternalState( PeCryptoUtils.class, "cryptoUtils", (PeCryptoUtils)null);
+ Whitebox.setInternalState(PeCryptoUtils.class, "cryptoUtils", (PeCryptoUtils) null);
}
@@ -55,8 +56,8 @@ public class PeCryptoUtilsTest {
PeCryptoUtils.initAesKey(null);
System.clearProperty(PROP_AES_KEY);
assertEquals(pass, PeCryptoUtils.decrypt(encryptedPass));
- Whitebox.setInternalState( PeCryptoUtils.class, "cryptoUtils", (PeCryptoUtils)null);
- Whitebox.setInternalState( PeCryptoUtils.class, "secretKey", secretKey);
+ Whitebox.setInternalState(PeCryptoUtils.class, "cryptoUtils", (PeCryptoUtils) null);
+ Whitebox.setInternalState(PeCryptoUtils.class, "secretKey", secretKey);
PeCryptoUtils.initAesKey(" ");
assertEquals(pass, PeCryptoUtils.decrypt(pass));
}
diff --git a/PolicyEngineUtils/src/test/java/org/onap/policy/utils/test/AAFClientTest.java b/PolicyEngineUtils/src/test/java/org/onap/policy/utils/test/AAFClientTest.java
index 2fa822a33..23060688d 100644
--- a/PolicyEngineUtils/src/test/java/org/onap/policy/utils/test/AAFClientTest.java
+++ b/PolicyEngineUtils/src/test/java/org/onap/policy/utils/test/AAFClientTest.java
@@ -2,14 +2,14 @@
* ============LICENSE_START=======================================================
* PolicyEngineUtils
* ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017, 2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -33,23 +33,33 @@ import org.onap.policy.utils.AAFPolicyException;
public class AAFClientTest {
AAFPolicyClient afClient;
String pass = "test";
-
+ String user = "test";
+
+ /**
+ * setUp.
+ *
+ * @throws AAFPolicyException AAFPolicyException
+ */
@Before
- public void setUp() throws AAFPolicyException{
+ public void setUp() throws AAFPolicyException {
Properties props = new Properties();
props.setProperty("ENVIRONMENT", "TEST");
props.setProperty("aafClient.impl.className", AAFPolicyClientImpl.class.getName());
- afClient = AAFPolicyClient.getInstance(props);
+ afClient = AAFPolicyClient.getInstance(props);
}
-
+
@Test
- public void invalidClientTest() throws AAFPolicyException{
- assertFalse(afClient.checkAuth("test", pass));
- assertFalse(afClient.checkPerm("test", pass, "policy-engine.config", "*", "*"));
+ public void invalidClientTest() throws AAFPolicyException {
+ assertFalse(afClient.checkPerm(null, null, null, null, null));
+ assertFalse(afClient.checkPerm(user, null, null, null, null));
+ assertFalse(afClient.checkAuth(user, pass));
+ assertFalse(afClient.checkAuth(null, pass));
+ assertFalse(afClient.checkAuth(user, null));
+ assertFalse(afClient.checkPerm(user, pass, "policy-engine.config", "*", "*"));
Properties props = new Properties();
props.setProperty("aafClient.impl.className", AAFPolicyClientImpl.class.getName());
- afClient = AAFPolicyClient.getInstance(props);
- assertFalse(afClient.checkAuth("test", pass));
+ afClient = AAFPolicyClient.getInstance(props);
+ assertFalse(afClient.checkAuth(user, pass));
props.setProperty("ENVIRONMENT", "PROD");
props.setProperty("aafClient.impl.className", AAFPolicyClientImpl.class.getName());
afClient.updateProperties(props);
@@ -63,14 +73,14 @@ public class AAFClientTest {
assertFalse(afClient.checkAuth("test", pass));
assertFalse(afClient.checkAuthPerm("test", pass, "decision", "*", "read"));
}
-
+
@Test(expected = AAFPolicyException.class)
- public void invalidAAFInstance() throws AAFPolicyException{
+ public void invalidAafInstance() throws AAFPolicyException {
Properties props = new Properties();
props.setProperty("aafClient.impl.className", "errorClass");
- afClient = AAFPolicyClient.getInstance(props);
+ afClient = AAFPolicyClient.getInstance(props);
}
-
+
@Test(expected = AAFPolicyException.class)
public void testPropNullException() throws AAFPolicyException {
afClient.updateProperties(null);
@@ -80,9 +90,9 @@ public class AAFClientTest {
public void testPropEmptyException() throws AAFPolicyException {
afClient.updateProperties(new Properties());
}
-
+
@Test(expected = AAFPolicyException.class)
- public void testAAFException() throws AAFPolicyException{
+ public void testAafException() throws AAFPolicyException {
new AAFPolicyException();
new AAFPolicyException("error", new Exception());
throw new AAFPolicyException("error", new Exception(), false, false);
diff --git a/PolicyEngineUtils/src/test/java/org/onap/policy/utils/test/BackUpMonitorEntityTest.java b/PolicyEngineUtils/src/test/java/org/onap/policy/utils/test/BackUpMonitorEntityTest.java
index f77fe72c9..4bbe008e3 100644
--- a/PolicyEngineUtils/src/test/java/org/onap/policy/utils/test/BackUpMonitorEntityTest.java
+++ b/PolicyEngineUtils/src/test/java/org/onap/policy/utils/test/BackUpMonitorEntityTest.java
@@ -2,14 +2,14 @@
* ============LICENSE_START=======================================================
* PolicyEngineUtils
* ================================================================================
- * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2018-2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -22,31 +22,33 @@ package org.onap.policy.utils.test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
+
import java.util.Date;
+
import org.junit.Test;
import org.onap.policy.jpa.BackUpMonitorEntity;
public class BackUpMonitorEntityTest {
- @Test
- public void testEntity() {
- String value = "testVal";
- Date date = new Date();
-
- BackUpMonitorEntity entity = new BackUpMonitorEntity();
- assertNotNull(entity);
-
- entity.setResourceName(value);
- entity.setResourceNodeName(value);
- entity.setFlag(value);
- entity.setNotificationRecord(value);
- entity.prePersist();
- entity.preUpdate();
- entity.setTimeStamp(date);
-
- assertEquals(value, entity.getResourceName());
- assertEquals(value, entity.getResourceNodeName());
- assertEquals(value, entity.getFlag());
- assertEquals(value, entity.getNotificationRecord());
- assertEquals(date, entity.getTimeStamp());
- }
+ @Test
+ public void testEntity() {
+ String value = "testVal";
+
+ BackUpMonitorEntity entity = new BackUpMonitorEntity();
+ assertNotNull(entity);
+
+ entity.setResourceName(value);
+ entity.setResourceNodeName(value);
+ entity.setFlag(value);
+ entity.setNotificationRecord(value);
+ entity.prePersist();
+ entity.preUpdate();
+ Date date = new Date();
+ entity.setTimeStamp(date);
+
+ assertEquals(value, entity.getResourceName());
+ assertEquals(value, entity.getResourceNodeName());
+ assertEquals(value, entity.getFlag());
+ assertEquals(value, entity.getNotificationRecord());
+ assertEquals(date, entity.getTimeStamp());
+ }
}
diff --git a/PolicyEngineUtils/src/test/java/org/onap/policy/utils/test/BackUpMonitorExceptionTest.java b/PolicyEngineUtils/src/test/java/org/onap/policy/utils/test/BackUpMonitorExceptionTest.java
index b9700124d..eb56c6f24 100644
--- a/PolicyEngineUtils/src/test/java/org/onap/policy/utils/test/BackUpMonitorExceptionTest.java
+++ b/PolicyEngineUtils/src/test/java/org/onap/policy/utils/test/BackUpMonitorExceptionTest.java
@@ -2,14 +2,14 @@
* ============LICENSE_START=======================================================
* PolicyEngineUtils
* ================================================================================
- * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2018-2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -21,35 +21,36 @@
package org.onap.policy.utils.test;
import java.io.IOException;
+
import org.junit.Test;
import org.onap.policy.utils.BackUpMonitorException;
public class BackUpMonitorExceptionTest {
- @Test(expected = BackUpMonitorException.class)
- public void testException1() throws BackUpMonitorException {
- throw new BackUpMonitorException();
- }
-
- @Test(expected = BackUpMonitorException.class)
- public void testException2() throws BackUpMonitorException {
- throw new BackUpMonitorException("test");
- }
-
- @Test(expected = BackUpMonitorException.class)
- public void testException3() throws BackUpMonitorException {
- Throwable cause = new IOException();
- throw new BackUpMonitorException(cause);
- }
-
- @Test(expected = BackUpMonitorException.class)
- public void testException4() throws BackUpMonitorException {
- Throwable cause = new IOException();
- throw new BackUpMonitorException("test", cause);
- }
-
- @Test(expected = BackUpMonitorException.class)
- public void testException5() throws BackUpMonitorException {
- Throwable cause = new IOException();
- throw new BackUpMonitorException("test", cause, true, true);
- }
+ @Test(expected = BackUpMonitorException.class)
+ public void testException1() throws BackUpMonitorException {
+ throw new BackUpMonitorException();
+ }
+
+ @Test(expected = BackUpMonitorException.class)
+ public void testException2() throws BackUpMonitorException {
+ throw new BackUpMonitorException("test");
+ }
+
+ @Test(expected = BackUpMonitorException.class)
+ public void testException3() throws BackUpMonitorException {
+ Throwable cause = new IOException();
+ throw new BackUpMonitorException(cause);
+ }
+
+ @Test(expected = BackUpMonitorException.class)
+ public void testException4() throws BackUpMonitorException {
+ Throwable cause = new IOException();
+ throw new BackUpMonitorException("test", cause);
+ }
+
+ @Test(expected = BackUpMonitorException.class)
+ public void testException5() throws BackUpMonitorException {
+ Throwable cause = new IOException();
+ throw new BackUpMonitorException("test", cause, true, true);
+ }
}
diff --git a/PolicyEngineUtils/src/test/java/org/onap/policy/utils/test/BackUpMonitorTest.java b/PolicyEngineUtils/src/test/java/org/onap/policy/utils/test/BackUpMonitorTest.java
index 5182c5329..c692ab8c4 100644
--- a/PolicyEngineUtils/src/test/java/org/onap/policy/utils/test/BackUpMonitorTest.java
+++ b/PolicyEngineUtils/src/test/java/org/onap/policy/utils/test/BackUpMonitorTest.java
@@ -25,6 +25,7 @@ import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import com.fasterxml.jackson.core.JsonProcessingException;
+
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
@@ -34,11 +35,13 @@ import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.TimeUnit;
+
import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;
import javax.persistence.PersistenceException;
import javax.persistence.Query;
+
import org.apache.commons.io.FileUtils;
import org.eclipse.persistence.config.PersistenceUnitProperties;
import org.junit.After;
@@ -56,7 +59,6 @@ import org.onap.policy.utils.BackUpMonitor.ResourceNode;
import org.onap.policy.utils.BackUpMonitorException;
import org.onap.policy.utils.PolicyUtils;
-
public class BackUpMonitorTest {
@Test(expected = PersistenceException.class)
public void backUpMonitorTestFail() throws Exception {
diff --git a/PolicyEngineUtils/src/test/java/org/onap/policy/utils/test/DummyBackUpHandler.java b/PolicyEngineUtils/src/test/java/org/onap/policy/utils/test/DummyBackUpHandler.java
index 15fb33944..232652fa5 100644
--- a/PolicyEngineUtils/src/test/java/org/onap/policy/utils/test/DummyBackUpHandler.java
+++ b/PolicyEngineUtils/src/test/java/org/onap/policy/utils/test/DummyBackUpHandler.java
@@ -2,14 +2,14 @@
* ============LICENSE_START=======================================================
* PolicyEngineUtils
* ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017, 2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -23,16 +23,16 @@ package org.onap.policy.utils.test;
import org.onap.policy.api.PDPNotification;
import org.onap.policy.utils.BackUpHandler;
-public class DummyBackUpHandler implements BackUpHandler{
+public class DummyBackUpHandler implements BackUpHandler {
- @Override
- public void notificationReceived(PDPNotification notification) {
- System.out.println("Received Notification from PDP. ");
- }
+ @Override
+ public void notificationReceived(PDPNotification notification) {
+ System.out.println("Received Notification from PDP. ");
+ }
+
+ @Override
+ public void runOnNotification(PDPNotification notification) {
+ System.out.println("Running main Notification Function. ");
+ }
- @Override
- public void runOnNotification(PDPNotification notification) {
- System.out.println("Running main Notification Function. ");
- }
-
}
diff --git a/PolicyEngineUtils/src/test/java/org/onap/policy/utils/test/NotificationStoreTest.java b/PolicyEngineUtils/src/test/java/org/onap/policy/utils/test/NotificationStoreTest.java
index 774bf8a7e..a7e3a9478 100644
--- a/PolicyEngineUtils/src/test/java/org/onap/policy/utils/test/NotificationStoreTest.java
+++ b/PolicyEngineUtils/src/test/java/org/onap/policy/utils/test/NotificationStoreTest.java
@@ -2,14 +2,14 @@
* ============LICENSE_START=======================================================
* PolicyEngineUtils
* ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017, 2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -38,16 +38,16 @@ import org.onap.policy.std.StdRemovedPolicy;
import org.onap.policy.utils.PolicyUtils;
public class NotificationStoreTest {
-
+
@Test
- public void notificationTest() throws IOException{
- // Notification Delta test first.
+ public void notificationTest() throws IOException {
+ // Notification Delta test first.
NotificationStore.recordNotification(new StdPDPNotification());
- assertEquals("{\"removedPolicies\":[],\"loadedPolicies\":[],\"notificationType\":null}", PolicyUtils.objectToJsonString(NotificationStore.getDeltaNotification(new StdPDPNotification())));
- // Initialize test
+ assertEquals("{\"removedPolicies\":[],\"loadedPolicies\":[],\"notificationType\":null}",
+ PolicyUtils.objectToJsonString(NotificationStore.getDeltaNotification(new StdPDPNotification())));
+ // Initialize test
StdPDPNotification notification = new StdPDPNotification();
notification.setNotificationType(NotificationType.BOTH);
- List<StdLoadedPolicy> loadedPolicies = new ArrayList<>();
StdLoadedPolicy loadedPolicy = new StdLoadedPolicy();
loadedPolicy.setPolicyName("com.testing");
loadedPolicy.setUpdateType(UpdateType.UPDATE);
@@ -55,6 +55,7 @@ public class NotificationStoreTest {
Map<String, String> matches = new HashMap<>();
matches.put("test", "test");
loadedPolicy.setMatches(matches);
+ List<StdLoadedPolicy> loadedPolicies = new ArrayList<>();
loadedPolicies.add(loadedPolicy);
notification.setLoadedPolicies(loadedPolicies);
List<StdRemovedPolicy> removedPolicies = new ArrayList<>();
@@ -64,8 +65,10 @@ public class NotificationStoreTest {
removedPolicies.add(removedPolicy);
notification.setRemovedPolicies(removedPolicies);
NotificationStore.recordNotification(notification);
- assertEquals("{\"removedPolicies\":[{\"policyName\":\"com.testing\",\"versionNo\":\"1\"}],\"loadedPolicies\":[{\"policyName\":\"com.testing\",\"versionNo\":\"2\",\"matches\":{\"test\":\"test\"},\"updateType\":\"UPDATE\"}],\"notificationType\":\"BOTH\"}", PolicyUtils.objectToJsonString(NotificationStore.getNotificationRecord()));
- // Add new Notifications.
+ assertEquals(
+ "{\"removedPolicies\":[{\"policyName\":\"com.testing\",\"versionNo\":\"1\"}],\"loadedPolicies\":[{\"policyName\":\"com.testing\",\"versionNo\":\"2\",\"matches\":{\"test\":\"test\"},\"updateType\":\"UPDATE\"}],\"notificationType\":\"BOTH\"}",
+ PolicyUtils.objectToJsonString(NotificationStore.getNotificationRecord()));
+ // Add new Notifications.
notification = new StdPDPNotification();
notification.setNotificationType(NotificationType.BOTH);
loadedPolicies = new ArrayList<>();
@@ -85,9 +88,12 @@ public class NotificationStoreTest {
removedPolicies.add(removedPolicy);
notification.setRemovedPolicies(removedPolicies);
NotificationStore.recordNotification(notification);
- StdPDPNotification check = NotificationStore.getDeltaNotification(PolicyUtils.jsonStringToObject("{\"removedPolicies\":[{\"policyName\":\"com.testing\",\"versionNo\":\"1\"},{\"policyName\":\"com.testing\",\"versionNo\":\"2\"}],\"loadedPolicies\":[{\"policyName\":\"com.test\",\"versionNo\":\"3\",\"matches\":{\"test\":\"test\"},\"updateType\":\"NEW\"}],\"notificationType\":\"BOTH\"}", StdPDPNotification.class));
- assertEquals("{\"removedPolicies\":[],\"loadedPolicies\":[],\"notificationType\":null}", PolicyUtils.objectToJsonString(check));
- // Remove Notifications.
+ StdPDPNotification check = NotificationStore.getDeltaNotification(PolicyUtils.jsonStringToObject(
+ "{\"removedPolicies\":[{\"policyName\":\"com.testing\",\"versionNo\":\"1\"},{\"policyName\":\"com.testing\",\"versionNo\":\"2\"}],\"loadedPolicies\":[{\"policyName\":\"com.test\",\"versionNo\":\"3\",\"matches\":{\"test\":\"test\"},\"updateType\":\"NEW\"}],\"notificationType\":\"BOTH\"}",
+ StdPDPNotification.class));
+ assertEquals("{\"removedPolicies\":[],\"loadedPolicies\":[],\"notificationType\":null}",
+ PolicyUtils.objectToJsonString(check));
+ // Remove Notifications.
notification = new StdPDPNotification();
notification.setNotificationType(NotificationType.REMOVE);
removedPolicies = new ArrayList<>();
@@ -97,9 +103,12 @@ public class NotificationStoreTest {
removedPolicies.add(removedPolicy);
notification.setRemovedPolicies(removedPolicies);
NotificationStore.recordNotification(notification);
- check = NotificationStore.getDeltaNotification(PolicyUtils.jsonStringToObject("{\"removedPolicies\":[{\"policyName\":\"com.test\",\"versionNo\":\"3\"},{\"policyName\":\"com.testing\",\"versionNo\":\"1\"},{\"policyName\":\"com.testing\",\"versionNo\":\"2\"}],\"loadedPolicies\":[],\"notificationType\":\"REMOVE\"}", StdPDPNotification.class));
- assertEquals("{\"removedPolicies\":[],\"loadedPolicies\":[],\"notificationType\":null}", PolicyUtils.objectToJsonString(check));
- // Remove on remove duplicate Notifications.
+ check = NotificationStore.getDeltaNotification(PolicyUtils.jsonStringToObject(
+ "{\"removedPolicies\":[{\"policyName\":\"com.test\",\"versionNo\":\"3\"},{\"policyName\":\"com.testing\",\"versionNo\":\"1\"},{\"policyName\":\"com.testing\",\"versionNo\":\"2\"}],\"loadedPolicies\":[],\"notificationType\":\"REMOVE\"}",
+ StdPDPNotification.class));
+ assertEquals("{\"removedPolicies\":[],\"loadedPolicies\":[],\"notificationType\":null}",
+ PolicyUtils.objectToJsonString(check));
+ // Remove on remove duplicate Notifications.
notification = new StdPDPNotification();
notification.setNotificationType(NotificationType.REMOVE);
removedPolicies = new ArrayList<>();
@@ -109,9 +118,12 @@ public class NotificationStoreTest {
removedPolicies.add(removedPolicy);
notification.setRemovedPolicies(removedPolicies);
NotificationStore.recordNotification(notification);
- check = NotificationStore.getDeltaNotification(PolicyUtils.jsonStringToObject("{\"removedPolicies\":[{\"policyName\":\"com.test\",\"versionNo\":\"3\"},{\"policyName\":\"com.testing\",\"versionNo\":\"1\"},{\"policyName\":\"com.testing\",\"versionNo\":\"2\"}],\"loadedPolicies\":[],\"notificationType\":\"REMOVE\"}", StdPDPNotification.class));
- assertEquals("{\"removedPolicies\":[],\"loadedPolicies\":[],\"notificationType\":null}", PolicyUtils.objectToJsonString(check));
- // Update Notification
+ check = NotificationStore.getDeltaNotification(PolicyUtils.jsonStringToObject(
+ "{\"removedPolicies\":[{\"policyName\":\"com.test\",\"versionNo\":\"3\"},{\"policyName\":\"com.testing\",\"versionNo\":\"1\"},{\"policyName\":\"com.testing\",\"versionNo\":\"2\"}],\"loadedPolicies\":[],\"notificationType\":\"REMOVE\"}",
+ StdPDPNotification.class));
+ assertEquals("{\"removedPolicies\":[],\"loadedPolicies\":[],\"notificationType\":null}",
+ PolicyUtils.objectToJsonString(check));
+ // Update Notification
notification = new StdPDPNotification();
notification.setNotificationType(NotificationType.UPDATE);
loadedPolicies = new ArrayList<>();
@@ -125,9 +137,12 @@ public class NotificationStoreTest {
loadedPolicies.add(loadedPolicy);
notification.setLoadedPolicies(loadedPolicies);
NotificationStore.recordNotification(notification);
- check = NotificationStore.getDeltaNotification(PolicyUtils.jsonStringToObject("{\"removedPolicies\":[{\"policyName\":\"com.testing\",\"versionNo\":\"1\"},{\"policyName\":\"com.testing\",\"versionNo\":\"2\"}],\"loadedPolicies\":[{\"policyName\":\"com.test\",\"versionNo\":\"3\",\"matches\":{\"test\":\"test\"},\"updateType\":\"NEW\"}],\"notificationType\":\"BOTH\"}", StdPDPNotification.class));
- assertEquals("{\"removedPolicies\":[],\"loadedPolicies\":[],\"notificationType\":null}", PolicyUtils.objectToJsonString(check));
- // Update on update duplicate Notification
+ check = NotificationStore.getDeltaNotification(PolicyUtils.jsonStringToObject(
+ "{\"removedPolicies\":[{\"policyName\":\"com.testing\",\"versionNo\":\"1\"},{\"policyName\":\"com.testing\",\"versionNo\":\"2\"}],\"loadedPolicies\":[{\"policyName\":\"com.test\",\"versionNo\":\"3\",\"matches\":{\"test\":\"test\"},\"updateType\":\"NEW\"}],\"notificationType\":\"BOTH\"}",
+ StdPDPNotification.class));
+ assertEquals("{\"removedPolicies\":[],\"loadedPolicies\":[],\"notificationType\":null}",
+ PolicyUtils.objectToJsonString(check));
+ // Update on update duplicate Notification
notification = new StdPDPNotification();
notification.setNotificationType(NotificationType.UPDATE);
loadedPolicies = new ArrayList<>();
@@ -141,9 +156,12 @@ public class NotificationStoreTest {
loadedPolicies.add(loadedPolicy);
notification.setLoadedPolicies(loadedPolicies);
NotificationStore.recordNotification(notification);
- check = NotificationStore.getDeltaNotification(PolicyUtils.jsonStringToObject("{\"removedPolicies\":[{\"policyName\":\"com.testing\",\"versionNo\":\"1\"},{\"policyName\":\"com.testing\",\"versionNo\":\"2\"}],\"loadedPolicies\":[{\"policyName\":\"com.test\",\"versionNo\":\"3\",\"matches\":{\"test\":\"test\"},\"updateType\":\"NEW\"}],\"notificationType\":\"BOTH\"}", StdPDPNotification.class));
- assertEquals("{\"removedPolicies\":[],\"loadedPolicies\":[],\"notificationType\":null}", PolicyUtils.objectToJsonString(check));
- //
+ check = NotificationStore.getDeltaNotification(PolicyUtils.jsonStringToObject(
+ "{\"removedPolicies\":[{\"policyName\":\"com.testing\",\"versionNo\":\"1\"},{\"policyName\":\"com.testing\",\"versionNo\":\"2\"}],\"loadedPolicies\":[{\"policyName\":\"com.test\",\"versionNo\":\"3\",\"matches\":{\"test\":\"test\"},\"updateType\":\"NEW\"}],\"notificationType\":\"BOTH\"}",
+ StdPDPNotification.class));
+ assertEquals("{\"removedPolicies\":[],\"loadedPolicies\":[],\"notificationType\":null}",
+ PolicyUtils.objectToJsonString(check));
+ //
// Notification Delta Tests
//
notification = new StdPDPNotification();
@@ -165,7 +183,9 @@ public class NotificationStoreTest {
removedPolicies.add(removedPolicy);
notification.setRemovedPolicies(removedPolicies);
check = NotificationStore.getDeltaNotification(notification);
- assertEquals("{\"removedPolicies\":[{\"policyName\":\"com.test\",\"versionNo\":\"3\"}],\"loadedPolicies\":[{\"policyName\":\"com.testing\",\"versionNo\":\"3\",\"matches\":{\"test\":\"test\"},\"updateType\":\"NEW\"}],\"notificationType\":\"BOTH\"}", PolicyUtils.objectToJsonString(check));
+ assertEquals(
+ "{\"removedPolicies\":[{\"policyName\":\"com.test\",\"versionNo\":\"3\"}],\"loadedPolicies\":[{\"policyName\":\"com.testing\",\"versionNo\":\"3\",\"matches\":{\"test\":\"test\"},\"updateType\":\"NEW\"}],\"notificationType\":\"BOTH\"}",
+ PolicyUtils.objectToJsonString(check));
}
}
diff --git a/PolicyEngineUtils/src/test/java/org/onap/policy/utils/test/PEDependencyTest.java b/PolicyEngineUtils/src/test/java/org/onap/policy/utils/test/PEDependencyTest.java
index 4cc6c90f2..e3cf67f30 100644
--- a/PolicyEngineUtils/src/test/java/org/onap/policy/utils/test/PEDependencyTest.java
+++ b/PolicyEngineUtils/src/test/java/org/onap/policy/utils/test/PEDependencyTest.java
@@ -2,14 +2,14 @@
* ============LICENSE_START=======================================================
* PolicyEngineUtils
* ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017, 2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -30,9 +30,9 @@ import org.junit.Test;
import org.onap.policy.api.PEDependency;
public class PEDependencyTest {
-
+
@Test
- public void pojoTests(){
+ public void pojoTests() {
PEDependency pe = new PEDependency();
pe.setArtifactId("test");
pe.setGroupId("test");
@@ -41,10 +41,10 @@ public class PEDependencyTest {
pe.setScope("test");
pe.setClassifier("pom");
List<Exclusion> exclusions = new ArrayList<>();
- Exclusion e = new Exclusion();
- e.setArtifactId("ex1");
- e.setGroupId("eG");
- exclusions.add(e);
+ Exclusion exclusion = new Exclusion();
+ exclusion.setArtifactId("ex1");
+ exclusion.setGroupId("eG");
+ exclusions.add(exclusion);
pe.setExclusions(exclusions);
pe.getDependency();
assertEquals(exclusions, pe.getExclusions());
diff --git a/PolicyEngineUtils/src/test/java/org/onap/policy/utils/test/PolicyUtilsTest.java b/PolicyEngineUtils/src/test/java/org/onap/policy/utils/test/PolicyUtilsTest.java
index 8445ad7c8..8d9116d32 100644
--- a/PolicyEngineUtils/src/test/java/org/onap/policy/utils/test/PolicyUtilsTest.java
+++ b/PolicyEngineUtils/src/test/java/org/onap/policy/utils/test/PolicyUtilsTest.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -45,165 +45,162 @@ import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
public class PolicyUtilsTest {
-
- private static final String ERROR = "The Value in Required Field will allow only '{0-9}, {a-z}, {A-Z}, _' following set of Combinations";
- private static final String SUCCESS = "success";
-
- @Test
- public void testJsonConversions() throws Exception{
- StdPDPNotification notification = new StdPDPNotification();
- notification.setNotificationType(NotificationType.BOTH);
- Collection<StdRemovedPolicy> removedPolicies = new ArrayList<>();
- Collection<StdLoadedPolicy> loadedPolicies = new ArrayList<>();
- StdRemovedPolicy removedPolicy = new StdRemovedPolicy();
- StdLoadedPolicy updatedPolicy = new StdLoadedPolicy();
- removedPolicy.setPolicyName("Test");
- removedPolicy.setVersionNo("1");
- removedPolicies.add(removedPolicy);
- updatedPolicy.setPolicyName("Testing");
- updatedPolicy.setVersionNo("1");
- updatedPolicy.setUpdateType(UpdateType.NEW);
- Map<String, String> matches = new HashMap<>();
- matches.put("key", "value");
- updatedPolicy.setMatches(matches);
- loadedPolicies.add(updatedPolicy);
- notification.setRemovedPolicies(removedPolicies);
- notification.setLoadedPolicies(loadedPolicies);
-
- String json = PolicyUtils.objectToJsonString(notification);
- PDPNotification getBackObject = PolicyUtils.jsonStringToObject(json, StdPDPNotification.class);
- assertEquals(0,getBackObject.getNotificationType().compareTo(notification.getNotificationType()));
-
- }
-
- private String encodedValue(String input){
- return new String(Base64.getEncoder().encode(input.getBytes()));
- }
-
- @Test
- public void testDecode() throws Exception{
- String value = "test";
- assertEquals(value, PolicyUtils.decode(encodedValue(value)));
- assertNull(PolicyUtils.decode(null));
- assertNull(PolicyUtils.decode(""));
- }
-
- @Test
- public void testBasicEncoding() throws Exception{
- String userName = "test";
- String key = "pass";
- String[] decodedValue = PolicyUtils.decodeBasicEncoding("Basic "+encodedValue(userName+":"+key));
- assertEquals(userName,decodedValue[0]);
- assertEquals(key,decodedValue[1]);
- assertEquals(0, PolicyUtils.decodeBasicEncoding(encodedValue(userName+":"+key)).length);
- assertEquals(0, PolicyUtils.decodeBasicEncoding(null).length);
- }
-
- @Test
- public void testSpecialCharValidator(){
- assertEquals(ERROR, PolicyUtils.policySpecialCharValidator("$TEST_"));
- assertEquals(ERROR, PolicyUtils.policySpecialCharValidator("$TEST _"));
- assertEquals(ERROR, PolicyUtils.policySpecialCharValidator(""));
- assertEquals(ERROR, PolicyUtils.policySpecialCharValidator("TæST"));
- assertEquals(SUCCESS, PolicyUtils.policySpecialCharValidator("TEST"));
- }
-
- @Test
- public void testSpecialCharWithSpaceValidator(){
- assertEquals(ERROR, PolicyUtils.policySpecialCharWithSpaceValidator(""));
- assertEquals(ERROR, PolicyUtils.policySpecialCharWithSpaceValidator("$TEST _"));
- assertEquals(SUCCESS, PolicyUtils.policySpecialCharWithSpaceValidator("TE ST"));
- }
-
- @Test
- public void testDescription() {
- assertEquals(SUCCESS, PolicyUtils.descriptionValidator("Test"));
- assertNotEquals(SUCCESS, PolicyUtils.descriptionValidator("@ModifiedBy:TesterB"));
- assertNotEquals(SUCCESS, PolicyUtils.descriptionValidator("@CreatedBy:TesterA"));
- }
-
- @Test
- public void testNonAscii(){
- assertTrue(PolicyUtils.containsNonAsciiEmptyChars(null));
- assertTrue(PolicyUtils.containsNonAsciiEmptyChars(""));
- assertTrue(PolicyUtils.containsNonAsciiEmptyChars("T æST"));
- assertTrue(PolicyUtils.containsNonAsciiEmptyChars("TæST"));
- assertFalse(PolicyUtils.containsNonAsciiEmptyChars("TEST"));
- }
-
- @Test
- public void testInteger(){
- assertFalse(PolicyUtils.isInteger(null));
- assertTrue(PolicyUtils.isInteger("123"));
- assertFalse(PolicyUtils.isInteger("1a23"));
- }
-
- @Test
- public void testEmailAddress(){
- assertEquals(SUCCESS, PolicyUtils.validateEmailAddress("test@onap.org"));
- assertNotEquals(SUCCESS, PolicyUtils.validateEmailAddress("test@onap"));
- }
-
- @Test
- public void testBRMSValidate(){
- String rule = "package com.sample;\n"
- + "import com.sample.DroolsTest.Message;\n"
- + "declare Params\n"
- + "samPoll : int\n"
- + "value : String\n"
- + "end\n"
- + "///This Rule will be generated by the UI.\n"
- + "rule \"Create parameters structure\"\n"
- + "salience 1000 \n"
- + "when\n"
- + "then\n"
- + "Params params = new Params();\n"
- + "params.setSamPoll(76);\n"
- + "params.setValue(\"test\");\n"
- + "insertLogical(params);\n"
- + "end\n"
- + "rule \"Rule 1: Check parameter structure access from when/then\"\n"
- + "when\n"
- + "$param: Params()\n"
- + "Params($param.samPoll > 50)\n"
- + "then\n"
- + "System.out.println(\"Firing rule 1\");\n"
- + "System.out.println($param);\n"
- + "end\n";
- assertEquals(PolicyUtils.brmsRawValidate(rule),"");
- assertTrue(PolicyUtils.brmsRawValidate("error").contains("[ERR"));
- assertFalse(PolicyUtils.brmsRawValidate("package com.att.ecomp.policy.controlloop.p_${unique};").contains("[ERR"));
- }
-
- @Test
- public void testiIsJsonValid(){
- assertTrue(PolicyUtils.isJSONValid("{\"test\":\"test\"}"));
- String value = "{\"test\":\"test\", \"t1\": {\"test\": 12 , \"t2\":\"34\"},\"t2\":[{\"test\":\"val\"}]}";
- assertTrue(PolicyUtils.isJSONValid(value));
- assertFalse(PolicyUtils.isJSONValid("{\"test\":\"test"));
- }
-
- @Test
- public void testIsXMLValid() throws SAXException{
- XMLErrorHandler error = new XMLErrorHandler();
+
+ private static final String ERROR =
+ "The Value in Required Field will allow only '{0-9}, {a-z}, {A-Z}, _' following set of Combinations";
+ private static final String SUCCESS = "success";
+
+ @Test
+ public void testJsonConversions() throws Exception {
+ StdPDPNotification notification = new StdPDPNotification();
+ notification.setNotificationType(NotificationType.BOTH);
+ Collection<StdRemovedPolicy> removedPolicies = new ArrayList<>();
+ StdRemovedPolicy removedPolicy = new StdRemovedPolicy();
+ removedPolicy.setPolicyName("Test");
+ removedPolicy.setVersionNo("1");
+ removedPolicies.add(removedPolicy);
+ StdLoadedPolicy updatedPolicy = new StdLoadedPolicy();
+ updatedPolicy.setPolicyName("Testing");
+ updatedPolicy.setVersionNo("1");
+ updatedPolicy.setUpdateType(UpdateType.NEW);
+ Map<String, String> matches = new HashMap<>();
+ matches.put("key", "value");
+ updatedPolicy.setMatches(matches);
+ Collection<StdLoadedPolicy> loadedPolicies = new ArrayList<>();
+ loadedPolicies.add(updatedPolicy);
+ notification.setRemovedPolicies(removedPolicies);
+ notification.setLoadedPolicies(loadedPolicies);
+
+ String json = PolicyUtils.objectToJsonString(notification);
+ PDPNotification getBackObject = PolicyUtils.jsonStringToObject(json, StdPDPNotification.class);
+ assertEquals(0, getBackObject.getNotificationType().compareTo(notification.getNotificationType()));
+
+ }
+
+ private String encodedValue(String input) {
+ return new String(Base64.getEncoder().encode(input.getBytes()));
+ }
+
+ @Test
+ public void testDecode() throws Exception {
+ String value = "test";
+ assertEquals(value, PolicyUtils.decode(encodedValue(value)));
+ assertNull(PolicyUtils.decode(null));
+ assertNull(PolicyUtils.decode(""));
+ }
+
+ @Test
+ public void testBasicEncoding() throws Exception {
+ String userName = "test";
+ String key = "pass";
+ String[] decodedValue = PolicyUtils.decodeBasicEncoding("Basic " + encodedValue(userName + ":" + key));
+ assertEquals(userName, decodedValue[0]);
+ assertEquals(key, decodedValue[1]);
+ assertEquals(0, PolicyUtils.decodeBasicEncoding(encodedValue(userName + ":" + key)).length);
+ assertEquals(0, PolicyUtils.decodeBasicEncoding(null).length);
+ }
+
+ @Test
+ public void testSpecialCharValidator() {
+ assertEquals(ERROR, PolicyUtils.policySpecialCharValidator("$TEST_"));
+ assertEquals(ERROR, PolicyUtils.policySpecialCharValidator("$TEST _"));
+ assertEquals(ERROR, PolicyUtils.policySpecialCharValidator(""));
+ assertEquals(ERROR, PolicyUtils.policySpecialCharValidator("TæST"));
+ assertEquals(SUCCESS, PolicyUtils.policySpecialCharValidator("TEST"));
+ }
+
+ @Test
+ public void testSpecialCharWithSpaceValidator() {
+ assertEquals(ERROR, PolicyUtils.policySpecialCharWithSpaceValidator(""));
+ assertEquals(ERROR, PolicyUtils.policySpecialCharWithSpaceValidator("$TEST _"));
+ assertEquals(SUCCESS, PolicyUtils.policySpecialCharWithSpaceValidator("TE ST"));
+ }
+
+ @Test
+ public void testDescription() {
+ assertEquals(SUCCESS, PolicyUtils.descriptionValidator("Test"));
+ assertNotEquals(SUCCESS, PolicyUtils.descriptionValidator("@ModifiedBy:TesterB"));
+ assertNotEquals(SUCCESS, PolicyUtils.descriptionValidator("@CreatedBy:TesterA"));
+ }
+
+ @Test
+ public void testNonAscii() {
+ assertTrue(PolicyUtils.containsNonAsciiEmptyChars(null));
+ assertTrue(PolicyUtils.containsNonAsciiEmptyChars(""));
+ assertTrue(PolicyUtils.containsNonAsciiEmptyChars("T æST"));
+ assertTrue(PolicyUtils.containsNonAsciiEmptyChars("TæST"));
+ assertFalse(PolicyUtils.containsNonAsciiEmptyChars("TEST"));
+ }
+
+ @Test
+ public void testInteger() {
+ assertFalse(PolicyUtils.isInteger(null));
+ assertTrue(PolicyUtils.isInteger("123"));
+ assertFalse(PolicyUtils.isInteger("1a23"));
+ }
+
+ @Test
+ public void testEmailAddress() {
+ assertEquals(SUCCESS, PolicyUtils.validateEmailAddress("test@onap.org"));
+ assertNotEquals(SUCCESS, PolicyUtils.validateEmailAddress("test@onap"));
+ }
+
+ @Test
+ public void testBrmsValidate() {
+ String rule = "package com.sample;\n" + "import com.sample.DroolsTest.Message;\n" + "declare Params\n"
+ + "samPoll : int\n" + "value : String\n" + "end\n" + "///This Rule will be generated by the UI.\n"
+ + "rule \"Create parameters structure\"\n" + "salience 1000 \n" + "when\n" + "then\n"
+ + "Params params = new Params();\n" + "params.setSamPoll(76);\n" + "params.setValue(\"test\");\n"
+ + "insertLogical(params);\n" + "end\n"
+ + "rule \"Rule 1: Check parameter structure access from when/then\"\n" + "when\n" + "$param: Params()\n"
+ + "Params($param.samPoll > 50)\n" + "then\n" + "System.out.println(\"Firing rule 1\");\n"
+ + "System.out.println($param);\n" + "end\n";
+ assertEquals(PolicyUtils.brmsRawValidate(rule), "");
+ assertTrue(PolicyUtils.brmsRawValidate("error").contains("[ERR"));
+ assertFalse(
+ PolicyUtils.brmsRawValidate("package com.att.ecomp.policy.controlloop.p_${unique};").contains("[ERR"));
+ }
+
+ @Test
+ public void testiIsJsonValid() {
+ assertTrue(PolicyUtils.isJSONValid("{\"test\":\"test\"}"));
+ String value = "{\"test\":\"test\", \"t1\": {\"test\": 12 , \"t2\":\"34\"},\"t2\":[{\"test\":\"val\"}]}";
+ assertTrue(PolicyUtils.isJSONValid(value));
+ assertFalse(PolicyUtils.isJSONValid("{\"test\":\"test"));
+ }
+
+ @Test
+ public void testIsXmlValid() throws SAXException {
+ assertFalse(PolicyUtils.isXMLValid(null));
+ assertFalse(PolicyUtils.isXMLValid(""));
+ XMLErrorHandler error = new XMLErrorHandler();
error.error(new SAXParseException(null, null));
error.warning(new SAXParseException(null, null));
- assertTrue(PolicyUtils.isXMLValid("<test>123</test>"));
- assertFalse(PolicyUtils.isXMLValid("<test>123</test"));
- }
-
- @Test
- public void testIsPropValid(){
+ assertTrue(PolicyUtils.isXMLValid("<test>123</test>"));
+ assertFalse(PolicyUtils.isXMLValid("<test>123</test"));
+ }
+
+ @Test
+ public void testIsPropValid() {
assertTrue(PolicyUtils.isPropValid("test=123\n\tval=123"));
assertFalse(PolicyUtils.isPropValid("test"));
assertFalse(PolicyUtils.isPropValid("test="));
assertTrue(PolicyUtils.isPropValid("#test\n\nval=123"));
- }
-
- @Test
- public void testVersionStringToArray(){
- assertTrue(PolicyUtils.versionStringToArray(null).length==0);
- assertTrue(PolicyUtils.versionStringToArray("").length==0);
- assertTrue(PolicyUtils.versionStringToArray("1.2.3").length==3);
- }
-} \ No newline at end of file
+ }
+
+ @Test
+ public void testVersionStringToArray() {
+ assertTrue(PolicyUtils.versionStringToArray(null).length == 0);
+ assertTrue(PolicyUtils.versionStringToArray("").length == 0);
+ assertTrue(PolicyUtils.versionStringToArray("1.2.3").length == 3);
+ }
+
+ @Test
+ public void testSpecialChar() {
+ assertEquals(PolicyUtils.SUCCESS, PolicyUtils.policySpecialCharWithDashValidator("test"));
+ assertEquals(PolicyUtils.SUCCESS, PolicyUtils.policySpecialCharWithDashValidator("test-"));
+ assertEquals(PolicyUtils.SUCCESS, PolicyUtils.policySpecialCharWithDashValidator("test_"));
+ assertNotEquals(PolicyUtils.SUCCESS, PolicyUtils.policySpecialCharWithDashValidator(""));
+ assertNotEquals(PolicyUtils.SUCCESS, PolicyUtils.policySpecialCharWithDashValidator("test*"));
+ }
+}
diff --git a/PolicyEngineUtils/src/test/resources/META-INF/persistencePUtest.xml b/PolicyEngineUtils/src/test/resources/META-INF/persistencePUtest.xml
index a73e6b3c5..17cdce68d 100644
--- a/PolicyEngineUtils/src/test/resources/META-INF/persistencePUtest.xml
+++ b/PolicyEngineUtils/src/test/resources/META-INF/persistencePUtest.xml
@@ -1,35 +1,52 @@
<?xml version="1.0" encoding="UTF-8"?>
-<!-- ============LICENSE_START=======================================================
- PolicyEngineUtils ================================================================================
- Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. ================================================================================
- Licensed under the Apache License, Version 2.0 (the "License"); you may not
- use this file except in compliance with the License. You may obtain a copy
- of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required
- by applicable law or agreed to in writing, software distributed under the
- License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS
- OF ANY KIND, either express or implied. See the License for the specific
- language governing permissions and limitations under the License. ============LICENSE_END========================================================= -->
+<!--
+ ============LICENSE_START=======================================================
+ PolicyEngineUtils
+ ================================================================================
+ Copyright (C) 2017, 2019 AT&T Intellectual Property. All rights reserved.
+ ================================================================================
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+ ============LICENSE_END=========================================================
+ -->
<persistence version="2.1"
- xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
- <persistence-unit name="PolicyEngineUtils"
- transaction-type="RESOURCE_LOCAL">
- <provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
- <class>org.onap.policy.jpa.BackUpMonitorEntity</class>
- <property name="javax.persistence.schema-generation.scripts.action"
- value="drop-and-create" />
- <property name="javax.persistence.schema-generation.scripts.create-target"
- value="./src/test/resources/META-INF/generatedCreate.ddl" />
- <property name="javax.persistence.schema-generation.scripts.drop-target"
- value="./src/test/resources/META-INF/generatedDrop.ddl" />
- <property name="javax.persistence.schema-generation.database.action"
- value="drop-and-create" />
- <property name="javax.persistence.schema-generation.create-source"
- value="metadata-then-script" />
- <property name="javax.persistence.schema-generation.drop-source"
- value="script" />
- <property name="javax.persistence.schema-generation.drop-script-source"
- value="META-INF/drop.ddl" />
- </persistence-unit>
+ xmlns="http://xmlns.jcp.org/xml/ns/persistence"
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
+ <persistence-unit name="PolicyEngineUtils"
+ transaction-type="RESOURCE_LOCAL">
+ <provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
+ <class>org.onap.policy.jpa.BackUpMonitorEntity</class>
+ <property
+ name="javax.persistence.schema-generation.scripts.action"
+ value="drop-and-create" />
+ <property
+ name="javax.persistence.schema-generation.scripts.create-target"
+ value="./src/test/resources/META-INF/generatedCreate.ddl" />
+ <property
+ name="javax.persistence.schema-generation.scripts.drop-target"
+ value="./src/test/resources/META-INF/generatedDrop.ddl" />
+ <property
+ name="javax.persistence.schema-generation.database.action"
+ value="drop-and-create" />
+ <property
+ name="javax.persistence.schema-generation.create-source"
+ value="metadata-then-script" />
+ <property
+ name="javax.persistence.schema-generation.drop-source"
+ value="script" />
+ <property
+ name="javax.persistence.schema-generation.drop-script-source"
+ value="META-INF/drop.ddl" />
+ </persistence-unit>
</persistence>
diff --git a/TestSuite/Performance/pom.xml b/TestSuite/Performance/pom.xml
index 386c6bc67..151ef5202 100644
--- a/TestSuite/Performance/pom.xml
+++ b/TestSuite/Performance/pom.xml
@@ -23,7 +23,7 @@
<parent>
<groupId>org.onap.policy.engine</groupId>
<artifactId>TestSuite</artifactId>
- <version>1.4.1-SNAPSHOT</version>
+ <version>1.6.4-SNAPSHOT</version>
</parent>
<artifactId>Performance</artifactId>
<properties>
diff --git a/TestSuite/Stability/pom.xml b/TestSuite/Stability/pom.xml
index 70ae11e7f..aee373caa 100644
--- a/TestSuite/Stability/pom.xml
+++ b/TestSuite/Stability/pom.xml
@@ -23,7 +23,7 @@
<parent>
<groupId>org.onap.policy.engine</groupId>
<artifactId>TestSuite</artifactId>
- <version>1.4.1-SNAPSHOT</version>
+ <version>1.6.4-SNAPSHOT</version>
</parent>
<artifactId>Stability</artifactId>
<properties>
diff --git a/TestSuite/pom.xml b/TestSuite/pom.xml
index b8b6ed48c..22efd4dbe 100644
--- a/TestSuite/pom.xml
+++ b/TestSuite/pom.xml
@@ -23,7 +23,7 @@
<parent>
<groupId>org.onap.policy.engine</groupId>
<artifactId>PolicyEngineSuite</artifactId>
- <version>1.4.1-SNAPSHOT</version>
+ <version>1.6.4-SNAPSHOT</version>
</parent>
<artifactId>TestSuite</artifactId>
<packaging>pom</packaging>
@@ -31,4 +31,4 @@
<module>Performance</module>
<module>Stability</module>
</modules>
-</project> \ No newline at end of file
+</project>
diff --git a/docker_build.sh b/docker_build.sh
deleted file mode 100644
index 2f11b0ba4..000000000
--- a/docker_build.sh
+++ /dev/null
@@ -1,126 +0,0 @@
-#!/bin/bash
-#
-#============LICENSE_START==================================================
-# ONAP Policy Engine
-#===========================================================================
-# Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
-#===========================================================================
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-#============LICENSE_END==================================================
-#
-
-#
-echo '============== STARTING SCRIPT TO BUILD DOCKER IMAGES ================='
-DOCKER_REPOSITORY=nexus3.onap.org:10003
-MVN_VERSION=$(cat packages/docker/target/version)
-MVN_MAJMIN_VERSION=$(cut -f 1,2 -d . packages/docker/target/version)
-TIMESTAMP=$(date -u +%Y%m%dT%H%M%S)
-BUILD_ARGS="--build-arg BUILD_VERSION_ENGINE=${MVN_VERSION}"
-IMAGE=policy-pe
-
-if [ $HTTP_PROXY ]; then
- BUILD_ARGS+=" --build-arg HTTP_PROXY=${HTTP_PROXY}"
-fi
-if [ $HTTPS_PROXY ]; then
- BUILD_ARGS+=" --build-arg HTTPS_PROXY=${HTTPS_PROXY}"
-fi
-
-echo $DOCKER_REPOSITORY
-echo $MVN_VERSION
-echo $MVN_MAJMIN_VERSION
-echo $TIMESTAMP
-
-if [[ -z $MVN_VERSION ]]
-then
- echo "MVN_VERSION is empty"
- exit 1
-fi
-
-if [[ -z $MVN_MAJMIN_VERSION ]]
-then
- echo "MVN_MAJMIN_VERSION is empty"
- exit 1
-fi
-
-if [[ $MVN_VERSION == *"SNAPSHOT"* ]]
-then
- MVN_MAJMIN_VERSION="${MVN_MAJMIN_VERSION}-SNAPSHOT"
-else
- MVN_MAJMIN_VERSION="${MVN_MAJMIN_VERSION}-STAGING"
-fi
-
-echo $MVN_MAJMIN_VERSION
-
-docker login -u docker -p docker nexus3.onap.org:10001
-docker pull nexus3.onap.org:10001/onap/policy-common-alpine:1.4.0
-docker tag nexus3.onap.org:10001/onap/policy-common-alpine:1.4.0 onap/policy-common-alpine:1.4.0
-
-echo "Building $IMAGE"
-
-#
-# This is the local latest tagged image. The Dockerfile's need this to build images
-#
-TAGS="--tag onap/${IMAGE}:latest"
-#
-# This is the nexus repo prepended for latest tagged image.
-#
-TAGS="${TAGS} --tag ${DOCKER_REPOSITORY}/onap/${IMAGE}:latest"
-#
-# This has the nexus repo prepended and only major/minor version with latest
-#
-TAGS="${TAGS} --tag ${DOCKER_REPOSITORY}/onap/${IMAGE}:${MVN_MAJMIN_VERSION}-latest"
-#
-# This has the nexus repo prepended and major/minor/patch version with timestamp
-#
-TAGS="${TAGS} --tag ${DOCKER_REPOSITORY}/onap/${IMAGE}:${MVN_VERSION}-STAGING-${TIMESTAMP}Z"
-
-echo $TAGS
-
-docker build --quiet ${BUILD_ARGS} $TAGS packages/docker/target/$IMAGE
-
-if [ $? -ne 0 ]
-then
- echo "Docker build failed"
- docker images
- exit 1
-fi
-
-docker images
-
-echo "Pushing $IMAGE"
-
-docker push ${DOCKER_REPOSITORY}/onap/${IMAGE}:latest
-
-if [ $? -ne 0 ]
-then
- echo "Docker push failed"
- exit 1
-
-fi
-
-docker push ${DOCKER_REPOSITORY}/onap/${IMAGE}:${MVN_MAJMIN_VERSION}-latest
-
-if [ $? -ne 0 ]
-then
- echo "Docker push failed"
- exit 1
-
-fi
-docker push ${DOCKER_REPOSITORY}/onap/${IMAGE}:${MVN_VERSION}-STAGING-${TIMESTAMP}Z
-
-if [ $? -ne 0 ]
-then
- echo "Docker push failed"
- exit 1
-
-fi
diff --git a/docker_merge.sh b/docker_merge.sh
deleted file mode 100644
index c624662b9..000000000
--- a/docker_merge.sh
+++ /dev/null
@@ -1,114 +0,0 @@
-#!/bin/bash
-#
-#============LICENSE_START==================================================
-# ONAP Policy Engine
-#===========================================================================
-# Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
-#===========================================================================
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-#============LICENSE_END==================================================
-#
-
-#
-echo '============== STARTING SCRIPT TO BUILD DOCKER IMAGES ================='
-DOCKER_REPOSITORY=nexus3.onap.org:10003
-MVN_VERSION=$(cat packages/docker/target/version)
-MVN_MAJMIN_VERSION=$(cut -f 1,2 -d . packages/docker/target/version)
-TIMESTAMP=$(date -u +%Y%m%dT%H%M%S)
-BUILD_ARGS="--build-arg BUILD_VERSION_ENGINE=${MVN_VERSION}"
-IMAGE=policy-pe
-
-if [ $HTTP_PROXY ]; then
- BUILD_ARGS+=" --build-arg HTTP_PROXY=${HTTP_PROXY}"
-fi
-if [ $HTTPS_PROXY ]; then
- BUILD_ARGS+=" --build-arg HTTPS_PROXY=${HTTPS_PROXY}"
-fi
-
-echo $DOCKER_REPOSITORY
-echo $MVN_VERSION
-echo $MVN_MAJMIN_VERSION
-echo $TIMESTAMP
-
-if [[ -z $MVN_VERSION ]]
-then
- echo "MVN_VERSION is empty"
- exit 1
-fi
-
-if [[ -z $MVN_MAJMIN_VERSION ]]
-then
- echo "MVN_MAJMIN_VERSION is empty"
- exit 1
-fi
-
-if [[ $MVN_VERSION == *"SNAPSHOT"* ]]
-then
- MVN_MAJMIN_VERSION="${MVN_MAJMIN_VERSION}-SNAPSHOT"
-else
- MVN_MAJMIN_VERSION="${MVN_MAJMIN_VERSION}-STAGING"
-fi
-
-echo $MVN_MAJMIN_VERSION
-
-echo "Building $IMAGE"
-
-docker login -u docker -p docker nexus3.onap.org:10001
-docker pull nexus3.onap.org:10001/onap/policy-common-alpine:1.4.0
-docker tag nexus3.onap.org:10001/onap/policy-common-alpine:1.4.0 onap/policy-common-alpine:1.4.0
-
-#
-# This is the local latest tagged image. The Dockerfile's need this to build images
-#
-TAGS="--tag onap/${IMAGE}:latest"
-#
-# This has the nexus repo prepended and only major/minor version with latest
-#
-TAGS="${TAGS} --tag ${DOCKER_REPOSITORY}/onap/${IMAGE}:${MVN_MAJMIN_VERSION}-latest"
-#
-# This has the nexus repo prepended and major/minor/patch version with timestamp
-#
-TAGS="${TAGS} --tag ${DOCKER_REPOSITORY}/onap/${IMAGE}:${MVN_VERSION}-${TIMESTAMP}Z"
-
-echo $TAGS
-
-docker build --quiet ${BUILD_ARGS} $TAGS packages/docker/target/$IMAGE
-
-if [ $? -ne 0 ]
-then
- echo "Docker build failed"
- docker images
- exit 1
-fi
-
-docker images
-
-#
-# Push image
-#
-echo "Pushing $IMAGE"
-docker push ${DOCKER_REPOSITORY}/onap/$IMAGE:${MVN_MAJMIN_VERSION}-latest
-
-if [ $? -ne 0 ]
-then
- echo "Docker push failed"
- exit 1
-fi
-
-docker push ${DOCKER_REPOSITORY}/onap/$IMAGE:${MVN_VERSION}-${TIMESTAMP}Z
-
-if [ $? -ne 0 ]
-then
- echo "Docker push failed"
- exit 1
-fi
diff --git a/docker_verify.sh b/docker_verify.sh
deleted file mode 100644
index d97a87f1a..000000000
--- a/docker_verify.sh
+++ /dev/null
@@ -1,98 +0,0 @@
-#!/bin/bash
-#
-#============LICENSE_START==================================================
-# ONAP Policy Engine
-#===========================================================================
-# Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
-#===========================================================================
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-#============LICENSE_END==================================================
-#
-
-#
-echo '============== STARTING SCRIPT TO BUILD DOCKER IMAGES ================='
-#
-# JUST VERIFY ONLY - NO PUSHING
-#
-DOCKER_REPOSITORY=nexus3.onap.org:10003
-MVN_VERSION=$(cat packages/docker/target/version)
-MVN_MAJMIN_VERSION=$(cut -f 1,2 -d . packages/docker/target/version)
-TIMESTAMP=$(date -u +%Y%m%dT%H%M%S)
-BUILD_ARGS="--build-arg BUILD_VERSION_ENGINE=${MVN_VERSION}"
-IMAGE=policy-pe
-
-if [ $HTTP_PROXY ]; then
- BUILD_ARGS+=" --build-arg HTTP_PROXY=${HTTP_PROXY}"
-fi
-if [ $HTTPS_PROXY ]; then
- BUILD_ARGS+=" --build-arg HTTPS_PROXY=${HTTPS_PROXY}"
-fi
-
-echo $DOCKER_REPOSITORY
-echo $MVN_VERSION
-echo $MVN_MAJMIN_VERSION
-echo $TIMESTAMP
-
-if [[ -z $MVN_VERSION ]]
-then
- echo "MVN_VERSION is empty"
- exit 1
-fi
-
-if [[ -z $MVN_MAJMIN_VERSION ]]
-then
- echo "MVN_MAJMIN_VERSION is empty"
- exit 1
-fi
-
-if [[ $MVN_VERSION == *"SNAPSHOT"* ]]
-then
- MVN_MAJMIN_VERSION="${MVN_MAJMIN_VERSION}-SNAPSHOT"
-else
- MVN_MAJMIN_VERSION="${MVN_MAJMIN_VERSION}-STAGING"
-fi
-
-echo $MVN_MAJMIN_VERSION
-
-echo "Building $IMAGE"
-
-docker login -u docker -p docker nexus3.onap.org:10001
-docker pull nexus3.onap.org:10001/onap/policy-common-alpine:1.4.0
-docker tag nexus3.onap.org:10001/onap/policy-common-alpine:1.4.0 onap/policy-common-alpine:1.4.0
-
-#
-# This is the local latest tagged image. The Dockerfile's need this to build images
-#
-TAGS="--tag onap/${IMAGE}:latest"
-#
-# This has the nexus repo prepended and only major/minor version with latest
-#
-TAGS="${TAGS} --tag ${DOCKER_REPOSITORY}/onap/${IMAGE}:${MVN_MAJMIN_VERSION}-latest"
-#
-# This has the nexus repo prepended and major/minor/patch version with timestamp
-#
-TAGS="${TAGS} --tag ${DOCKER_REPOSITORY}/onap/${IMAGE}:${MVN_VERSION}-${TIMESTAMP}Z"
-
-echo $TAGS
-
-docker build --quiet ${BUILD_ARGS} $TAGS packages/docker/target/$IMAGE
-
-if [ $? -ne 0 ]
-then
- echo "Docker build failed"
- docker images
- exit 1
-fi
-
-docker images
-
diff --git a/docs/.gitignore b/docs/.gitignore
new file mode 100644
index 000000000..43ca5b671
--- /dev/null
+++ b/docs/.gitignore
@@ -0,0 +1,3 @@
+/.tox
+/_build/*
+/__pycache__/*
diff --git a/docs/_static/css/ribbon.css b/docs/_static/css/ribbon.css
new file mode 100644
index 000000000..6008cb1a0
--- /dev/null
+++ b/docs/_static/css/ribbon.css
@@ -0,0 +1,63 @@
+.ribbon {
+ z-index: 1000;
+ background-color: #a00;
+ overflow: hidden;
+ white-space: nowrap;
+ position: fixed;
+ top: 25px;
+ right: -50px;
+ -webkit-transform: rotate(45deg);
+ -moz-transform: rotate(45deg);
+ -ms-transform: rotate(45deg);
+ -o-transform: rotate(45deg);
+ transform: rotate(45deg);
+ -webkit-box-shadow: 0 0 10px #888;
+ -moz-box-shadow: 0 0 10px #888;
+ box-shadow: 0 0 10px #888;
+
+}
+
+.ribbon a {
+ border: 1px solid #faa;
+ color: #fff;
+ display: block;
+ font: bold 81.25% 'Helvetica Neue', Helvetica, Arial, sans-serif;
+ margin: 1px 0;
+ padding: 10px 50px;
+ text-align: center;
+ text-decoration: none;
+ text-shadow: 0 0 5px #444;
+ transition: 0.5s;
+}
+
+.ribbon a:hover {
+ background: #c11;
+ color: #fff;
+}
+
+
+/* override table width restrictions */
+@media screen and (min-width: 767px) {
+
+ .wy-table-responsive table td, .wy-table-responsive table th {
+ /* !important prevents the common CSS stylesheets from overriding
+ this as on RTD they are loaded after this stylesheet */
+ white-space: normal !important;
+ }
+
+ .wy-table-responsive {
+ overflow: visible !important;
+ }
+}
+
+@media screen and (max-width: 767px) {
+ .wy-table-responsive table td {
+ white-space: nowrap;
+ }
+}
+
+/* fix width of the screen */
+
+.wy-nav-content {
+ max-width: none;
+}
diff --git a/docs/_static/favicon.ico b/docs/_static/favicon.ico
new file mode 100755
index 000000000..cb712ebd2
--- /dev/null
+++ b/docs/_static/favicon.ico
Binary files differ
diff --git a/docs/_static/logo_onap_2017.png b/docs/_static/logo_onap_2017.png
new file mode 100644
index 000000000..5d064f431
--- /dev/null
+++ b/docs/_static/logo_onap_2017.png
Binary files differ
diff --git a/docs/conf.py b/docs/conf.py
new file mode 100644
index 000000000..5371015c6
--- /dev/null
+++ b/docs/conf.py
@@ -0,0 +1,15 @@
+from docs_conf.conf import *
+
+branch = 'latest'
+master_doc = 'index'
+
+linkcheck_ignore = [
+ 'http://localhost',
+]
+
+intersphinx_mapping = {}
+
+html_last_updated_fmt = '%d-%b-%y %H:%M'
+
+def setup(app):
+ app.add_stylesheet("css/ribbon.css")
diff --git a/docs/conf.yaml b/docs/conf.yaml
new file mode 100644
index 000000000..ab5928131
--- /dev/null
+++ b/docs/conf.yaml
@@ -0,0 +1,7 @@
+---
+project_cfg: onap
+project: onap
+
+# Change this to ReleaseBranchName to modify the header
+default-version: latest
+#
diff --git a/docs/index.rst b/docs/index.rst
index ece0fd903..b25b12305 100644
--- a/docs/index.rst
+++ b/docs/index.rst
@@ -1,7 +1,8 @@
.. This work is licensed under a Creative Commons Attribution 4.0 International License.
+.. _master_index:
-Policy Engine
--------------
+Policy Engine (Legacy)
+----------------------
.. toctree::
:maxdepth: 1
diff --git a/docs/platform/architecture.rst b/docs/platform/architecture.rst
index 19f774c65..2eb3e88f0 100644
--- a/docs/platform/architecture.rst
+++ b/docs/platform/architecture.rst
@@ -1,6 +1,7 @@
.. This work is licensed under a
.. Creative Commons Attribution 4.0 International License.
.. http://creativecommons.org/licenses/by/4.0
+.. _architecture:
Architecture
@@ -10,7 +11,7 @@ Architecture
:depth: 3
POLICY is a subsystem of ONAP that maintains, distributes, and operates on the
-set of rules that underlie ONAP’s control, orchestration, and management
+set of rules that underlie ONAP's control, orchestration, and management
functions.
POLICY provides a logically centralized environment for the creation and
@@ -136,14 +137,14 @@ selected conditions in effect at that time.
Some examples of types of policies are:
-* VNF placement — rules governing where VNFs should be placed, including
+* VNF placement - rules governing where VNFs should be placed, including
affinity rules
-* Data and feed management — what data to collect and when, retention periods,
+* Data and feed management - what data to collect and when, retention periods,
and when to send alarms about issues
-* Access control — who (or what) can have access to which data
-* Trigger conditions and actions — what conditions are actionable, and what to
+* Access control - who (or what) can have access to which data
+* Trigger conditions and actions - what conditions are actionable, and what to
do under those conditions
-* Interactions — how interactions between change management and
+* Interactions - how interactions between change management and
fault/performance management are handled (for example, should closed loops be
disabled during maintenance?)
@@ -190,7 +191,7 @@ correct component in a control loop such as the MSO, a Controller, or DCAE.
Policy engines such as XACML and Drools also enforce policies and can trigger
other components as a result (for example, causing a controller to take
specific actions specified by the policy). Additionally, some policies
-(“Guard Policies”) may enforce checks against decided actions.
+("Guard Policies") may enforce checks against decided actions.
Policy Unification and Organization
diff --git a/docs/platform/cookbook.rst b/docs/platform/cookbook.rst
index e79b4a9c8..0a834b40a 100644
--- a/docs/platform/cookbook.rst
+++ b/docs/platform/cookbook.rst
@@ -94,7 +94,7 @@ OOM Installation - Policy Kubernetes Recipes
:caption: Access the PAP container
:linenos:
- kubectl exec -it <pap-pod> -c pap -n onap bash
+ kubectl exec -it <pap-pod> -c pap -n onap -- bash --login
.. code-block:: bash
@@ -112,7 +112,7 @@ OOM Installation - Policy Kubernetes Recipes
# <policy-deployment-prefix> depends on the deployment configuration
- kubectl exec -it <policy-deployment-prefix>-pdp-0 -c drools -n onap bash
+ kubectl exec -it <policy-deployment-prefix>-pdp-0 -c pdp -n onap -- bash --login
.. code-block:: bash
@@ -193,15 +193,17 @@ PAP Recipes (inside the "pap" container)
:caption: Bypass Portal Authentication with the Policy Web UI
:linenos:
- sed -i "s/^role_access_centralized.*$/#role_access_centralized=remote/g" /opt/app/policy/servers/console/webapps/onap/WEB-INF/classes/portal.properties; policy.sh stop; policy.sh start;
+ sed -i "s/^role_access_centralized.*$/#role_access_centralized=remote/g" /opt/app/policy/servers/console/webapps/onap/WEB-INF/classes/portal.properties
+ cd /opt/app/policy/servers/pap
+ /opt/app/policy/etc/init.d/pap stop; /opt/app/policy/etc/init.d/pap start
+ policy.sh status
.. code-block:: bash
:caption: Access the Policy Web UI without going through the Portal UI
:linenos:
- https://<pap-vm>:8443/onap/login.htm (Heat)
- https://<pap-vm>:30219/onap/login.htm (Kubernetes)
+ https://policy.api.simpledemo.onap.org:30219/onap/policy (Kubernetes)
End of Document
diff --git a/docs/platform/index.rst b/docs/platform/index.rst
index 6257e56ee..69ef1da64 100644
--- a/docs/platform/index.rst
+++ b/docs/platform/index.rst
@@ -3,6 +3,10 @@
Policy Engine Platform
----------------------
+Please note that the Policy Engine code contained in the policy/engine repository will be deprecated in Frankfurt.
+
+Please refer to :ref:`policy-framework-doc` for the new Policy Framework Architecture that supports the new Policy Lifecycle API.
+
.. toctree::
:maxdepth: 1
@@ -16,7 +20,6 @@ Policy Installation and Deployment
.. toctree::
:maxdepth: 1
- installation.rst
installationVM.rst
installAmsterController.rst
swarch_srm.rst
diff --git a/docs/platform/offeredapis.rst b/docs/platform/offeredapis.rst
index 516260941..7c6309c17 100644
--- a/docs/platform/offeredapis.rst
+++ b/docs/platform/offeredapis.rst
@@ -1,9 +1,12 @@
.. This work is licensed under a Creative Commons Attribution 4.0 International License.
.. http://creativecommons.org/licenses/by/4.0
+.. _legacyapis-label:
-Offered APIs
-============
+Legacy Offered APIs
+===================
+
+.. warning:: These Legacy APIs are scheduled to be deprecated after the Frankfurt release!
.. contents::
:depth: 2
diff --git a/docs/release-notes.rst b/docs/release-notes.rst
deleted file mode 100644
index 1f8f078a4..000000000
--- a/docs/release-notes.rst
+++ /dev/null
@@ -1,529 +0,0 @@
-.. This work is licensed under a Creative Commons Attribution 4.0 International License.
-
-Policy Release Notes
-====================
-
-.. note
-.. * This Release Notes must be updated each time the team decides to Release new artifacts.
-.. * The scope of these Release Notes are for ONAP POLICY. In other words, each ONAP component has its Release Notes.
-.. * This Release Notes is cumulative, the most recently Released artifact is made visible in the top of
-.. * this Release Notes.
-.. * Except the date and the version number, all the other sections are optional but there must be at least
-.. * one section describing the purpose of this new release.
-.. * This note must be removed after content has been added.
-
-
-.. ==========================
-.. * * * DUBLIN * * *
-.. ==========================
-
-Version: 4.0.0
---------------
-
-:Release Date: 2019-06-06 (Dublin Release)
-
-**New Features**
-
-The Dublin release for POLICY delivered the following Epics. For a full list of stories and tasks delivered in the Dublin release, refer to `JiraPolicyDublin`_.
-
- * [POLICY-1068] - This epic covers the work to cleanup, enhance, fix, etc. any Control Loop based code base.
- - POLICY-1459 PDP-D [Control Loop] : Create a Control Loop flavored PDP-D image
- - POLICY-1397 PDP-D: NOOP Endpoints Support to test Operational Policies.
- - POLICY-1195 Separate model code from drools-applications into other repositories
- - POLICY-1367 Spike - Experimentation for management of Drools templates and Operational Policies
-
- * [POLICY-1069] - This epic covers the work to harden the codebase for the Policy Framework project.
- - POLICY-1250 Fix issues reported by sonar in policy modules
- - POLICY-1202 policy-engine & apex-pdp are using different version of eclipselink
- - POLICY-1368 Remove hibernate from policy repos
- - POLICY-1007 Remove Jackson from policy framework components
- - POLICY-1457 Use Alpine in base docker images
-
- * [POLICY-1072] - This epic covers the work to support S3P Performance criteria.
-
- * [POLICY-1171] - Enhance CLC Facility
- - POLICY-1173 High-level specification of coordination directives
-
- * [POLICY-1220] - This epic covers the work to support S3P Security criteria
- - Task POLICY-1538 Upgrade Elasticsearch to 6.4.x to clear security issue
-
- * [POLICY-1269] - R4 Dublin - ReBuild Policy Infrastructure
- - POLICY-1453 Apex PDP Dmaap Deploy/UnDeploy Functionality
- - POLICY-1452 Apex PDP Dmaap Register/UnRegister Functionality
- - POLICY-1460 Create S3P JMeter Tests for PAP
- - POLICY-1458 Create S3P JMeter Tests for Policy API
- - POLICY-1462 Create S3P JMeter Tests for Policy SDC Distribution
- - POLICY-1461 Create S3P JMeter Tests for Policy XACML Engine (2nd Generation)
- - POLICY-1272 Create the S3P JMeter tests for API, PAP, XACML (2nd Gen)
- - POLICY-1455 Drools PDP Dmaap Deploy/UnDeploy Functionality
- - POLICY-1454 Drools PDP Dmaap Register/UnRegister Functionality
- - POLICY-1474 Modifications of Control Loop Operational Policy to support new Policy Lifecycle API
- - POLICY-1443 PAP Dmaap PDP Register/UnRegister Main Entry Point
- - POLICY-1444 PAP Dmaap Policy Deploy/Undeploy Policies Main Entry Point
- - POLICY-1542 PAP REST API for PDPGroup Deployment, State Management & Health Check
- - POLICY-1541 PAP REST API for PDPGroup Query, Statistics & Delete
- - POLICY-1271 PAP RESTful HealthCheck/Statistics Main Entry Point
- - POLICY-1471 Policy Application Designer - Develop Guard and Control Loop Coordination Policy Type application
- - POLICY-1456 Policy Architecture and Roadmap Documentation
- - POLICY-1442 Policy Lifecycle API RESTful Create/Read Main Entry Point for Concrete Policies
- - POLICY-1441 Policy Lifecycle API RESTful Create/Read Main Entry Point for Policy Types
- - POLICY-1447 Policy Lifecycle API RESTful Delete Main Entry Point for Concrete Policies
- - POLICY-1446 Policy Lifecycle API RESTful Delete Main Entry Point for Policy Types
- - POLICY-1270 Policy Lifecycle API RESTful HealthCheck/Statistics Main Entry Point
- - POLICY-1273 Policy Type Application Design Requirements
- - POLICY-1515 Prototype Policy Lifecycle API Swagger Entry Points
- - POLICY-1516 Prototype the Policy Decision API
- - POLICY-1451 XACML PDP Dmaap Deploy/UnDeploy Functionality
- - POLICY-1449 XACML PDP Dmaap Register/UnRegister Functionality
- - POLICY-1440 XACML PDP RESTful Decision API Main Entry Point
- - POLICY-1436 XACML PDP RESTful HealthCheck/Statistics Main Entry Point
- - POLICY-1445 XACML PDP upgrade to xacml 2.0.0
-
- * [POLICY-1399] - This epic covers the work to support model drive control loop design as defined by the Control Loop Subcommittee
-
- * [POLICY-1404] - This epic covers the work to support the CCVPN Use Case for Dublin
- - POLICY-1405 Develop SDNC API for trigger bandwidth
-
- * [POLICY-1408] - This epic covers the work done with the Casablanca release
- - POLICY-1419 Better multi-role support
- - POLICY-1427 Controller Logging Feature
- - POLICY-1413 Dashboard enhancements
- - POLICY-1422 Enhanced encryption
- - POLICY-1420 Model enhancement to support embedded JSON
- - POLICY-1416 Model enhancements to support CLAMP
- - POLICY-1421 New audit data for push/delete
- - POLICY-1418 PDP APIs - make ClientAuth optional
- - POLICY-1414 Push Policy and DeletePolicy API enhancement
- - POLICY-1417 Resiliency improvements
- - POLICY-1423 Save original model file
- - POLICY-1410 List Policy API
- - POLICY-1499 Mdc Filter Feature
- - POLICY-1489 PDP-D: Nested JSON Event Filtering support with JsonPath
-
- * [POLICY-1438] - This epic covers the work to support 5G OOF PCI Use Case
- - POLICY-1464 Config related aspects for OOF SON use case
- - POLICY-1463 Functional code changes in Policy for OOF SON use case
-
- * [POLICY-1450] - This epic covers the work to support the Scale Out Use Case.
- - POLICY-1278 AAI named-queries are being deprecated and should be replaced with custom-queries
- - POLICY-1545 E2E Automation - Parse the newly added model ids from operation policy
-
- * Additional items delivered with the release.
- - POLICY-1266 A&AI Modularity
- - POLICY-1274 further improvement in PSSD S3P test
- - POLICY-1159 Move expectException to policy-common/utils-test
- - POLICY-1465 Support configurable Heap Memory Settings for JVM processes
- - POLICY-1176 Work on technical debt introduced by CLC POC
-
-
-**Bug Fixes**
-
-The following bug fixes have been deployed with this release:
-
- * `[POLICY-1627] <https://jira.onap.org/browse/POLICY-1627>`_ - APEX does not support specification of a partitioner class for Kafka
- * `[POLICY-1289] <https://jira.onap.org/browse/POLICY-1289>`_ - Apex only considers 200 response codes as successful result codes
- * `[POLICY-1437] <https://jira.onap.org/browse/POLICY-1437>`_ - Fix issues in FileSystemReceptionHandler of policy-distribution component
- * `[POLICY-1501] <https://jira.onap.org/browse/POLICY-1501>`_ - policy-engine JUnit tests are not independent
- * `[POLICY-1241] <https://jira.onap.org/browse/POLICY-1241>`_ - Test failure in drools-pdp if JAVA_HOME is not set
-
-**Security Notes**
-
-POLICY code has been formally scanned during build time using NexusIQ and all Critical vulnerabilities have been addressed, items that remain open have been assessed for risk and determined to be false positive. The POLICY open Critical security vulnerabilities and their risk assessment have been documented as part of the `project (Dublin Release) <https://wiki.onap.org/pages/viewpage.action?pageId=54723253>`_.
-
-Quick Links:
- - `POLICY project page`_
- - `Passing Badge information for POLICY`_
- - `Project Vulnerability Review Table for POLICY (Dublin Release) <https://wiki.onap.org/pages/viewpage.action?pageId=54723253>`_
-
-
-**Known Issues**
-
-The following known issues will be addressed in a future release:
-
- * `[POLICY-1291] - <https://jira.onap.org/browse/POLICY-1291>`_ Maven Error when building Apex documentation in Windows
- * `[POLICY-1650] - <https://jira.onap.org/browse/POLICY-1650>`_ Policy UI doesn't show left menu or any content
- * `[POLICY-1725] - <https://jira.onap.org/browse/POLICY-1725>`_ XACML PDP returns 500 vs 400 for bad syntax JSON
-
-
-
-.. ==========================
-.. * * * CASABLANCA * * *
-.. ==========================
-
-Version: 3.0.2
---------------
-
-:Release Date: 2019-03-31 (Casablanca Maintenance Release #2)
-
-The following items were deployed with the Casablanca Maintenance Release:
-
-**Bug Fixes**
-
- * [POLICY-1522] - Policy doesn't send "payload" field to APPC
-
-**Security Fixes**
-
- * [POLICY-1538] - Upgrade Elasticsearch to 6.4.x to clear security issue
-
-**License Issues**
-
- * [POLICY-1433] - Remove proprietary licenses in PSSD test CSAR
-
-**Known Issues**
-
-The following known issue will be addressed in a future release.
-
- * `[POLICY-1650] <https://jira.onap.org/browse/POLICY-1277>`_ - Policy UI doesn't show left menu or any content
-
-A workaround for this issue consists in bypassing the Portal UI when accessing the Policy UI. See `PAP recipes <https://docs.onap.org/en/casablanca/submodules/policy/engine.git/docs/platform/cookbook.html?highlight=policy%20cookbook#id23>`_ for the specific procedure.
-
-
-Version: 3.0.1
---------------
-
-:Release Date: 2019-01-31 (Casablanca Maintenance Release)
-
-The following items were deployed with the Casablanca Maintenance Release:
-
-**New Features**
-
- * [POLICY-1221] - Policy distribution application to support HTTPS communication
- * [POLICY-1222] - Apex policy PDP to support HTTPS Communication
-
-**Bug Fixes**
-
- * `[POLICY-1282] <https://jira.onap.org/browse/POLICY-1282>`_ - Policy format with some problems
- * `[POLICY-1395] <https://jira.onap.org/browse/POLICY-1395>`_ - Apex PDP does not preserve context on model upgrade
-
-
-Version: 3.0.0
---------------
-
-:Release Date: 2018-11-30 (Casablanca Release)
-
-**New Features**
-
-The Casablanca release for POLICY delivered the following Epics. For a full list of stories and tasks delivered in the Casablanca release, refer to `JiraPolicyCasablanca`_ (Note: Jira details can also be viewed from this link).
-
- * [POLICY-701] - This epic covers the work to integrate Policy into the SDC Service Distribution
-
- The policy team introduced a new application into the framework that provides integration of the Service Distribution Notifications from SDC to Policy.
-
- * [POLICY-719] - This epic covers the work to build the Policy Lifecycle API
- * [POLICY-726] - This epic covers the work to distribute policy from the PAP to the PDPs into the ONAP platform
- * [POLICY-876] - This epics covers the work to re-build how the PAP organizes the PDP's into groups.
-
- The policy team did some forward looking spike work towards re-building the Software Architecture.
-
- * [POLICY-809] - Maintain and implement performance
- * [POLICY-814] - 72 hour stability testing (component and platform)
-
- The policy team made enhancements to the Drools PDP to further support S3P Performance.
- For the new Policy SDC Distribution application and the newly ingested Apex PDP the team established S3P
- performance standard and performed 72 hour stability tests.
-
- * [POLICY-824] - maintain and implement security
-
- The policy team established AAF Root Certificate for HTTPS communication and CADI/AAF integration into the
- MVP applications. In addition, many java dependencies were upgraded to clear CLM security issues.
-
- * [POLICY-840] - Flexible control loop coordination facility.
-
- Work towards a POC for control loop coordination policies were implemented.
-
- * [POLICY-841] - Covers the work required to support HPA
-
- Enhancements were made to support the HPA use case through the use of the new Policy SDC Service Distribution application.
-
- * [POLICY-842] - This epic covers the work to support the Auto Scale Out functional requirements
-
- Enhancements were made to support Scale Out Use Case to enforce new guard policies and updated SO and A&AI APIs.
-
- * [POLICY-851] - This epic covers the work to bring in the Apex PDP code
-
- A new Apex PDP engine was ingested into the platform and work was done to ensure code cleared CLM security issues,
- sonar issues, and checkstyle.
-
- * [POLICY-1081] - This epic covers the contribution for the 5G OOF PCI Optimization use case.
-
- Policy templates changes were submitted that supported the 5G OOF PCI optimization use case.
-
- * [POLICY-1182] - Covers the work to support CCVPN use case
-
- Policy templates changes were submitted that supported the CCVPN use case.
-
-**Bug Fixes**
-
-The following bug fixes have been deployed with this release:
-
- * `[POLICY-799] <https://jira.onap.org/browse/POLICY-799>`_ - Policy API Validation Does Not Validate Required Parent Attributes in the Model
- * `[POLICY-869] <https://jira.onap.org/browse/POLICY-869>`_ - Control Loop Drools Rules should not have exceptions as well as die upon an exception
- * `[POLICY-872] <https://jira.onap.org/browse/POLICY-872>`_ - investigate potential race conditions during rules version upgrades during call loads
- * `[POLICY-878] <https://jira.onap.org/browse/POLICY-878>`_ - pdp-d: feature-pooling disables policy-controllers preventing processing of onset events
- * `[POLICY-909] <https://jira.onap.org/browse/POLICY-909>`_ - get_ZoneDictionaryDataByName class type error
- * `[POLICY-920] <https://jira.onap.org/browse/POLICY-920>`_ - Hard-coded path in junit test
- * `[POLICY-921] <https://jira.onap.org/browse/POLICY-921>`_ - XACML Junit test cannot find property file
- * `[POLICY-1083] <https://jira.onap.org/browse/POLICY-1083>`_ - Mismatch in action cases between Policy and APPC
-
-
-**Security Notes**
-
-POLICY code has been formally scanned during build time using NexusIQ and all Critical vulnerabilities have been addressed, items that remain open have been assessed for risk and determined to be false positive. The POLICY open Critical security vulnerabilities and their risk assessment have been documented as part of the `project (Casablanca Release) <https://wiki.onap.org/pages/viewpage.action?pageId=45300864>`_.
-
-Quick Links:
- - `POLICY project page`_
- - `Passing Badge information for POLICY`_
- - `Project Vulnerability Review Table for POLICY (Casablanca Release) <https://wiki.onap.org/pages/viewpage.action?pageId=45300864>`_
-
-**Known Issues**
-
- * `[POLICY-1277] <https://jira.onap.org/browse/POLICY-1277>`_ - policy config takes too long time to become retrievable in PDP
- * `[POLICY-1282] <https://jira.onap.org/browse/POLICY-1282>`_ - Policy format with some problems
-
-
-
-.. =======================
-.. * * * BEIJING * * *
-.. =======================
-
-Version: 2.0.0
---------------
-
-:Release Date: 2018-06-07 (Beijing Release)
-
-**New Features**
-
-The Beijing release for POLICY delivered the following Epics. For a full list of stories and tasks delivered in the Beijing release, refer to `JiraPolicyBeijing`_.
-
- * [POLICY-390] - This epic covers the work to harden the Policy platform software base (incl 50% JUnit coverage)
- - POLICY-238 policy/drools-applications: clean up maven structure
- - POLICY-336 Address Technical Debt
- - POLICY-338 Address JUnit Code Coverage
- - POLICY-377 Policy Create API should validate input matches DCAE microservice template
- - POLICY-389 Cleanup Jenkin's CI/CD process's
- - POLICY-449 Policy API + Console : Common Policy Validation
- - POLICY-568 Integration with org.onap AAF project
- - POLICY-610 Support vDNS scale out for multiple times in Beijing release
-
- * [POLICY-391] - This epic covers the work to support Release Planning activities
- - POLICY-552 ONAP Licensing Scan - Use Restrictions
-
- * [POLICY-392] - Platform Maturity Requirements - Performance Level 1
- - POLICY-529 Platform Maturity Performance - Drools PDP
- - POLICY-567 Platform Maturity Performance - PDP-X
-
- * [POLICY-394] - This epic covers the work required to support a Policy developer environment in which Policy Developers can create, update policy templates/rules separate from the policy Platform runtime platform.
- - POLICY-488 pap should not add rules to official template provided in drools applications
-
- * [POLICY-398] - This epic covers the body of work involved in supporting policy that is platform specific.
- - POLICY-434 need PDP /getConfig to return an indicator of where to find the config data - in config.content versus config field
-
- * [POLICY-399] - This epic covers the work required to policy enable Hardware Platform Enablement
- - POLICY-622 Integrate OOF Policy Model into Policy Platform
-
- * [POLICY-512] - This epic covers the work to support Platform Maturity Requirements - Stability Level 1
- - POLICY-525 Platform Maturity Stability - Drools PDP
- - POLICY-526 Platform Maturity Stability - XACML PDP
-
- * [POLICY-513] - Platform Maturity Requirements - Resiliency Level 2
- - POLICY-527 Platform Maturity Resiliency - Policy Engine GUI and PAP
- - POLICY-528 Platform Maturity Resiliency - Drools PDP
- - POLICY-569 Platform Maturity Resiliency - BRMS Gateway
- - POLICY-585 Platform Maturity Resiliency - XACML PDP
- - POLICY-586 Platform Maturity Resiliency - Planning
- - POLICY-681 Regression Test Use Cases
-
- * [POLICY-514] - This epic covers the work to support Platform Maturity Requirements - Security Level 1
- - POLICY-523 Platform Maturity Security - CII Badging - Project Website
-
- * [POLICY-515] - This epic covers the work to support Platform Maturity Requirements - Escalability Level 1
- - POLICY-531 Platform Maturity Scalability - XACML PDP
- - POLICY-532 Platform Maturity Scalability - Drools PDP
- - POLICY-623 Docker image re-design
-
- * [POLICY-516] - This epic covers the work to support Platform Maturity Requirements - Manageability Level 1
- - POLICY-533 Platform Maturity Manageability L1 - Logging
- - POLICY-534 Platform Maturity Manageability - Instantiation < 1 hour
-
- * [POLICY-517] - This epic covers the work to support Platform Maturity Requirements - Usability Level 1
- - POLICY-535 Platform Maturity Usability - User Guide
- - POLICY-536 Platform Maturity Usability - Deployment Documentation
- - POLICY-537 Platform Maturity Usability - API Documentation
-
- * [POLICY-546] - R2 Beijing - Various enhancements requested by clients to the way we handle TOSCA models.
-
-
-**Bug Fixes**
-
-The following bug fixes have been deployed with this release:
-
- * `[POLICY-484] <https://jira.onap.org/browse/POLICY-484>`_ - Extend election handler run window and clean up error messages
- * `[POLICY-494] <https://jira.onap.org/browse/POLICY-494>`_ - POLICY EELF Audit.log not in ECOMP Standards Compliance
- * `[POLICY-501] <https://jira.onap.org/browse/POLICY-501>`_ - Fix issues blocking election handler and add directed interface for opstate
- * `[POLICY-509] <https://jira.onap.org/browse/POLICY-509>`_ - Add IntelliJ file to .gitingore
- * `[POLICY-510] <https://jira.onap.org/browse/POLICY-510>`_ - Do not enforce hostname validation
- * `[POLICY-518] <https://jira.onap.org/browse/POLICY-518>`_ - StateManagement creation of EntityManagers.
- * `[POLICY-519] <https://jira.onap.org/browse/POLICY-519>`_ - Correctly initialize the value of allSeemsWell in DroolsPdpsElectionHandler
- * `[POLICY-629] <https://jira.onap.org/browse/POLICY-629>`_ - Fixed a bug on editor screen
- * `[POLICY-684] <https://jira.onap.org/browse/POLICY-684>`_ - Fix regex for brmsgw dependency handling
- * `[POLICY-707] <https://jira.onap.org/browse/POLICY-707>`_ - ONAO-PAP-REST unit tests fail on first build on clean checkout
- * `[POLICY-717] <https://jira.onap.org/browse/POLICY-717>`_ - Fix a bug in checking required fields if the object has include function
- * `[POLICY-734] <https://jira.onap.org/browse/POLICY-734>`_ - Fix Fortify Header Manipulation Issue
- * `[POLICY-743] <https://jira.onap.org/browse/POLICY-743>`_ - Fixed data name since its name was changed on server side
- * `[POLICY-753] <https://jira.onap.org/browse/POLICY-753>`_ - Policy Health Check failed with multi-node cluster
- * `[POLICY-765] <https://jira.onap.org/browse/POLICY-765>`_ - junit test for guard fails intermittently
-
-
-**Security Notes**
-
-POLICY code has been formally scanned during build time using NexusIQ and all Critical vulnerabilities have been addressed, items that remain open have been assessed for risk and determined to be false positive. The POLICY open Critical security vulnerabilities and their risk assessment have been documented as part of the `project <https://wiki.onap.org/pages/viewpage.action?pageId=25437092>`_.
-
-Quick Links:
- - `POLICY project page`_
- - `Passing Badge information for POLICY`_
- - `Project Vulnerability Review Table for POLICY <https://wiki.onap.org/pages/viewpage.action?pageId=25437092>`_
-
-**Known Issues**
-
-The following known issues will be addressed in a future release:
-
- * `[POLICY-522] <https://jira.onap.org/browse/POLICY-522>`_ - PAP REST APIs undesired HTTP response body for 500 responses
- * `[POLICY-608] <https://jira.onap.org/browse/POLICY-608>`_ - xacml components : remove hardcoded secret key from source code
- * `[POLICY-764] <https://jira.onap.org/browse/POLICY-764>`_ - Policy Engine PIP Configuration JUnit Test fails intermittently
- * `[POLICY-776] <https://jira.onap.org/browse/POLICY-776>`_ - OOF Policy TOSCA models are not correctly rendered
- * `[POLICY-799] <https://jira.onap.org/browse/POLICY-799>`_ - Policy API Validation Does Not Validate Required Parent Attributes in the Model
- * `[POLICY-801] <https://jira.onap.org/browse/POLICY-801>`_ - fields mismatch for OOF flavorFeatures between implementation and wiki
- * `[POLICY-869] <https://jira.onap.org/browse/POLICY-869>`_ - Control Loop Drools Rules should not have exceptions as well as die upon an exception
- * `[POLICY-872] <https://jira.onap.org/browse/POLICY-872>`_ - investigate potential race conditions during rules version upgrades during call loads
-
-
-
-
-Version: 1.0.2
---------------
-
-:Release Date: 2018-01-18 (Amsterdam Maintenance Release)
-
-**Bug Fixes**
-
-The following fixes were deployed with the Amsterdam Maintenance Release:
-
- * `[POLICY-486] <https://jira.onap.org/browse/POLICY-486>`_ - pdp-x api pushPolicy fails to push latest version
-
-
-Version: 1.0.1
---------------
-
-:Release Date: 2017-11-16 (Amsterdam Release)
-
-**New Features**
-
-The Amsterdam release continued evolving the design driven architecture of and functionality for POLICY. The following is a list of Epics delivered with the release. For a full list of stories and tasks delivered in the Amsterdam release, refer to `JiraPolicyAmsterdam`_.
-
- * [POLICY-31] - Stabilization of Seed Code
- - POLICY-25 Replace any remaining openecomp reference by onap
- - POLICY-32 JUnit test code coverage
- - POLICY-66 PDP-D Feature mechanism enhancements
- - POLICY-67 Rainy Day Decision Policy
- - POLICY-93 Notification API
- - POLICY-158 policy/engine: SQL injection Mitigation
- - POLICY-269 Policy API Support for Rainy Day Decision Policy and Dictionaries
-
- * [POLICY-33] - This epic covers the body of work involved in deploying the Policy Platform components
- - POLICY-40 MSB Integration
- - POLICY-124 Integration with oparent
- - POLICY-41 OOM Integration
- - POLICY-119 PDP-D: noop sinks
-
- * [POLICY-34] - This epic covers the work required to support a Policy developer environment in which Policy Developers can create, update policy templates/rules separate from the policy Platform runtime platform.
- - POLICY-57 VF-C Actor code development
- - POLICY-43 Amsterdam Use Case Template
- - POLICY-173 Deployment of Operational Policies Documentation
-
- * [POLICY-35] - This epic covers the body of work involved in supporting policy that is platform specific.
- - POLICY-68 TOSCA Parsing for nested objects for Microservice Policies
-
- * [POLICY-36] - This epic covers the work required to capture policy during VNF on-boarding.
-
- * [POLICY-37] - This epic covers the work required to capture, update, extend Policy(s) during Service Design.
- - POLICY-64 CLAMP Configuration and Operation Policies for vFW Use Case
- - POLICY-65 CLAMP Configuration and Operation Policies for vDNS Use Case
- - POLICY-48 CLAMP Configuration and Operation Policies for vCPE Use Case
- - POLICY-63 CLAMP Configuration and Operation Policies for VOLTE Use Case
-
- * [POLICY-38] - This epic covers the work required to support service distribution by SDC.
-
- * [POLICY-39] - This epic covers the work required to support the Policy Platform during runtime.
- - POLICY-61 vFW Use Case - Runtime
- - POLICY-62 vDNS Use Case - Runtime
- - POLICY-59 vCPE Use Case - Runtime
- - POLICY-60 VOLTE Use Case - Runtime
- - POLICY-51 Runtime Policy Update Support
- - POLICY-328 vDNS Use Case - Runtime Testing
- - POLICY-324 vFW Use Case - Runtime Testing
- - POLICY-320 VOLTE Use Case - Runtime Testing
- - POLICY-316 vCPE Use Case - Runtime Testing
-
- * [POLICY-76] - This epic covers the body of work involved in supporting R1 Amsterdam Milestone Release Planning Milestone Tasks.
- - POLICY-77 Functional Test case definition for Control Loops
- - POLICY-387 Deliver the released policy artifacts
-
-
-**Bug Fixes**
- - This is technically the first release of POLICY, previous release was the seed code contribution. As such, the defects fixed in this release were raised during the course of the release. Anything not closed is captured below under Known Issues. For a list of defects fixed in the Amsterdam release, refer to `JiraPolicyAmsterdam`_.
-
-
-**Known Issues**
- - The operational policy template has been tested with the vFW, vCPE, vDNS and VOLTE use cases. Additional development may/may not be required for other scenarios.
-
- - For vLBS Use Case, the following steps are required to setup the service instance:
- - Create a Service Instance via VID.
- - Create a VNF Instance via VID.
- - Preload SDNC with topology data used for the actual VNF instantiation (both base and DNS scaling modules). NOTE: you may want to set “vlb_name_0” in the base VF module data to something unique. This is the vLB server name that DCAE will pass to Policy during closed loop. If the same name is used multiple times, the Policy name-query to AAI will show multiple entries, one for each occurrence of that vLB VM name in the OpenStack zone. Note that this is not a limitation, typically server names in a domain are supposed to be unique.
- - Instantiate the base VF module (vLB, vPacketGen, and one vDNS) via VID. NOTE: The name of the VF module MUST start with ``Vfmodule_``. The same name MUST appear in the SDNC preload of the base VF module topology. We’ll relax this naming requirement for Beijing Release.
- - Run heatbridge from the Robot VM using ``Vfmodule_`` … as stack name (it is the actual stack name in OpenStack)
- - Populate AAI with a dummy VF module for vDNS scaling.
-
-**Security Issues**
- - None at this time
-
-**Other**
- - None at this time
-
-
-.. Links to jira release notes
-
-.. _JiraPolicyDublin: https://jira.onap.org/secure/ReleaseNote.jspa?projectId=10106&version=10464
-.. _JiraPolicyCasablanca: https://jira.onap.org/secure/ReleaseNote.jspa?projectId=10106&version=10446
-.. _JiraPolicyBeijing: https://jira.onap.org/secure/ReleaseNote.jspa?projectId=10106&version=10349
-.. _JiraPolicyAmsterdam: https://jira.onap.org/secure/ReleaseNote.jspa?projectId=10106&version=10300
-
-.. Links to Project related pages
-
-.. _POLICY project page: https://wiki.onap.org/display/DW/Policy+Framework+Project
-.. _Passing Badge information for POLICY: https://bestpractices.coreinfrastructure.org/en/projects/1614
-
-
-.. note
-.. CHANGE HISTORY
-.. 05/16/2019 - Updated for Dublin Release.
-.. 01/17/2019 - Updated for Casablanca Maintenance Release.
-.. 11/19/2018 - Updated for Casablanca. Also, fixed bugs is a list of bugs where the "Affected Version" is Beijing.
-.. Changed version number to use ONAP versions.
-.. 10/08/2018 - Initial document for Casablanca release.
-.. Per Jorge, POLICY-785 did not get done in Casablanca (removed).
-.. 05/29/2018 - Information for Beijing release.
-.. 03/22/2018 - Initial document for Beijing release.
-.. 01/15/2018 - Added change for version 1.1.3 to the Amsterdam branch. Also corrected prior version (1.2.0) to (1.1.1)
-.. Also, Set up initial information for Beijing.
-.. Excluded POLICY-454 from bug list since it doesn't apply to Beijing per Jorge.
-
-
-End of Release Notes
-
-.. How to notes for SS
-.. For initial document: list epic and user stories for each, list user stories with no epics.
-.. For Bugs section, list bugs where Affected Version is a prior release (Casablanca, Beijing etc), Fixed Version is the current release (Dublin), Resolution is done.
-.. For Known issues, list bugs that are slotted for a future release.
-
-
diff --git a/docs/requirements-docs.txt b/docs/requirements-docs.txt
new file mode 100644
index 000000000..b3188ddd3
--- /dev/null
+++ b/docs/requirements-docs.txt
@@ -0,0 +1,15 @@
+tox
+Sphinx
+doc8
+docutils
+setuptools
+six
+sphinx_rtd_theme>=0.4.3
+sphinxcontrib-blockdiag
+sphinxcontrib-needs>=0.2.3
+sphinxcontrib-nwdiag
+sphinxcontrib-seqdiag
+sphinxcontrib-swaggerdoc
+sphinxcontrib-plantuml
+sphinx_bootstrap_theme
+lfdocs-conf
diff --git a/docs/tox.ini b/docs/tox.ini
new file mode 100644
index 000000000..edac8c35f
--- /dev/null
+++ b/docs/tox.ini
@@ -0,0 +1,22 @@
+[tox]
+minversion = 1.6
+envlist = docs,
+skipsdist = true
+
+[testenv:docs]
+basepython = python3
+deps = -r{toxinidir}/requirements-docs.txt
+commands =
+ sphinx-build -b html -n -d {envtmpdir}/doctrees ./ {toxinidir}/_build/html
+ echo "Generated docs available in {toxinidir}/_build/html"
+whitelist_externals =
+ echo
+ git
+ sh
+
+[testenv:docs-linkcheck]
+basepython = python3
+#deps = -r{toxinidir}/requirements-docs.txt
+commands = echo "Link Checking not enforced"
+#commands = sphinx-build -b linkcheck -d {envtmpdir}/doctrees ./ {toxinidir}/_build/linkcheck
+whitelist_externals = echo
diff --git a/lombok.config b/lombok.config
new file mode 100644
index 000000000..d458699b9
--- /dev/null
+++ b/lombok.config
@@ -0,0 +1,2 @@
+config.stopBubbling = true
+#lombok.addLombokGeneratedAnnotation = true
diff --git a/packages/base/pom.xml b/packages/base/pom.xml
index afdf44068..47ae6df3f 100755
--- a/packages/base/pom.xml
+++ b/packages/base/pom.xml
@@ -25,7 +25,7 @@
<parent>
<groupId>org.onap.policy.engine</groupId>
<artifactId>packages</artifactId>
- <version>1.4.1-SNAPSHOT</version>
+ <version>1.6.4-SNAPSHOT</version>
</parent>
<artifactId>base</artifactId>
diff --git a/packages/base/src/files/etc/ssl/policy-keystore b/packages/base/src/files/etc/ssl/policy-keystore
index 3809f7d69..389df5fe5 100644
--- a/packages/base/src/files/etc/ssl/policy-keystore
+++ b/packages/base/src/files/etc/ssl/policy-keystore
Binary files differ
diff --git a/packages/base/src/files/install/mysql/data/161000_upgrade_script.sql b/packages/base/src/files/install/mysql/data/161000_upgrade_script.sql
index dbab6ac30..b3589b053 100755
--- a/packages/base/src/files/install/mysql/data/161000_upgrade_script.sql
+++ b/packages/base/src/files/install/mysql/data/161000_upgrade_script.sql
@@ -6320,7 +6320,7 @@ INSERT INTO FunctionArguments (id, is_bag, function_id, arg_index, datatype_id)
INSERT INTO FunctionArguments (id, is_bag, function_id, arg_index, datatype_id) VALUES (452,0,254,2,28);
INSERT INTO FunctionArguments (id, is_bag, function_id, arg_index, datatype_id) VALUES (453,0,92,3,16);
-INSERT INTO PIPType VALUES (500,'SQL'), (501,'LDAP'), (502,'CSV'), (503,'Hyper-CSV'), (504,'Custom');
+INSERT INTO PipType VALUES (500,'SQL'), (501,'LDAP'), (502,'CSV'), (503,'Hyper-CSV'), (504,'Custom');
INSERT INTO GlobalRoleSettings (role, lockdown) values ('super-admin', '0');
diff --git a/packages/base/src/files/install/mysql/data/170701_downgrade_script.sql b/packages/base/src/files/install/mysql/data/170701_downgrade_script.sql
index 8271f27ce..58f92a6cd 100644
--- a/packages/base/src/files/install/mysql/data/170701_downgrade_script.sql
+++ b/packages/base/src/files/install/mysql/data/170701_downgrade_script.sql
@@ -18,9 +18,9 @@
use onap_sdk;
ALTER TABLE fwtagpicker drop networkRole;
-alter table microservicemodels drop column enumValues, drop column annotation;
-drop table if exists FWTag;
-drop table if exists FWTagPicker;
+alter table microservicemodels drop column enumValues, drop column annotation;
+drop table if exists FwTag;
+drop table if exists FwTagPicker;
drop table if exists brmsdependency;
drop table if exists brmscontroller;
-drop table if exists microserviceattribute;
+drop table if exists microserviceattribute;
diff --git a/packages/base/src/files/install/mysql/data/170701_upgrade_script.sql b/packages/base/src/files/install/mysql/data/170701_upgrade_script.sql
index f8ed77182..c2343b720 100644
--- a/packages/base/src/files/install/mysql/data/170701_upgrade_script.sql
+++ b/packages/base/src/files/install/mysql/data/170701_upgrade_script.sql
@@ -20,14 +20,14 @@ use onap_sdk;
INSERT INTO policyeditorscopes (`id`, `scopename`, `created_date`, `created_by`, `modified_date`, `modified_by`) VALUES ('1', 'com', '2017-06-01 11:45:36', 'demo', '2017-06-01 11:45:36', 'demo');
-alter table IntegrityAuditEntity modify jdbcUrl varchar(200) not null;
+alter table IntegrityAuditEntity modify jdbcUrl varchar(200) not null;
-alter table `onap_sdk`.`microservicemodels`
-add column `enumValues` longtext null default null after `version`,
+alter table `onap_sdk`.`microservicemodels`
+add column `enumValues` longtext null default null after `version`,
add column `annotation` longtext null after `enumValues`;
-drop table if exists FWTag;
-CREATE TABLE FWTag(
+drop table if exists FwTag;
+CREATE TABLE FwTag(
Id int NOT NULL AUTO_INCREMENT,
tagName VARCHAR(45) NOT NULL,
description VARCHAR(1024),
@@ -39,8 +39,8 @@ MODIFIED_BY VARCHAR(45) NOT NULL,
PRIMARY KEY(ID)
);
-drop table if exists FWTagPicker;
-CREATE TABLE FWTagPicker(
+drop table if exists FwTagPicker;
+CREATE TABLE FwTagPicker(
ID INT NOT NULL AUTO_INCREMENT,
tagPickerName VARCHAR(45) NOT NULL,
DESCRIPTION VARCHAR(1024),
@@ -79,7 +79,7 @@ controller longtext not null,
primary key(id)
);
-drop table if exists microserviceattribute;
+drop table if exists microserviceattribute;
CREATE TABLE microserviceattribute(
ID INT NOT NULL AUTO_INCREMENT,
name VARCHAR(255) NOT NULL,
diff --git a/packages/base/src/files/install/mysql/data/191000_upgrade_script.sql b/packages/base/src/files/install/mysql/data/191000_upgrade_script.sql
new file mode 100644
index 000000000..6fefe6bf0
--- /dev/null
+++ b/packages/base/src/files/install/mysql/data/191000_upgrade_script.sql
@@ -0,0 +1,42 @@
+-- ============LICENSE_START=======================================================
+-- ONAP Policy Engine
+-- ================================================================================
+-- Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
+-- ================================================================================
+-- Licensed under the Apache License, Version 2.0 (the "License");
+-- you may not use this file except in compliance with the License.
+-- You may obtain a copy of the License at
+--
+-- http://www.apache.org/licenses/LICENSE-2.0
+--
+-- Unless required by applicable law or agreed to in writing, software
+-- distributed under the License is distributed on an "AS IS" BASIS,
+-- WITHOUT WARRANTIES OR 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 onap_sdk;
+
+SET FOREIGN_KEY_CHECKS=0;
+
+-- Changes for epsdk 2.5.0 version
+update fn_menu set action = 'welcome' where action = 'welcome.htm';
+
+-- Changes for epsdk 2.6.0 version upgrade
+INSERT INTO fn_restricted_url (restricted_url, function_cd) VALUES ('report/wizard/add_formfield_tab_data/*','menu_reports');
+INSERT INTO fn_restricted_url (restricted_url, function_cd) VALUES ('report/wizard/save_formfield_tab_data/*','menu_reports');
+INSERT INTO fn_restricted_url (restricted_url, function_cd) VALUES ('report/wizard/retrieve_form_tab_wise_data/*/delete','menu_reports');
+INSERT INTO fn_restricted_url (restricted_url, function_cd) VALUES ('report/wizard/list_child_report_col/*','menu_reports');
+INSERT INTO fn_restricted_url (restricted_url, function_cd) VALUES ('report/wizard/list_child_report_ff/*','menu_reports');
+INSERT INTO fn_restricted_url VALUES('serviceModels','serviceModels ');
+INSERT INTO fn_restricted_url VALUES('serviceModels','menu_admin');
+INSERT INTO fn_restricted_url VALUES('report/wizard/list_columns','menu_reports');
+INSERT INTO fn_restricted_url VALUES('report/wizard/list_formfields','menu_reports');
+INSERT INTO fn_restricted_url VALUES('report/wizard/retrieve_data/*','menu_reports');
+INSERT INTO fn_restricted_url VALUES('report/wizard/retrieve_col_tab_wise_data/*','menu_reports');
+INSERT INTO fn_restricted_url VALUES('welcome','menu_reports');
+INSERT INTO fn_restricted_url VALUES('report/security/addReportUser','menu_reports');
+INSERT INTO fn_restricted_url VALUES('report/security/addReportRole','menu_reports');
+INSERT INTO fn_restricted_url VALUES('report/security/*','menu_reports');
+INSERT INTO fn_restricted_url VALUES('report/wizard/get_report_log/*','menu_reports');
+
diff --git a/packages/base/src/files/install/servers/brmsgw/config.properties b/packages/base/src/files/install/servers/brmsgw/config.properties
index 1080f4636..d54f56d77 100644
--- a/packages/base/src/files/install/servers/brmsgw/config.properties
+++ b/packages/base/src/files/install/servers/brmsgw/config.properties
@@ -84,7 +84,7 @@ test_via_jmx=${{test_via_jmx}}
ping_interval=30000
-brms.dependency.version=1.4.1-SNAPSHOT
+brms.dependency.version=1.6.3-SNAPSHOT
CLIENT_FILE=client.properties
diff --git a/packages/base/src/files/install/servers/brmsgw/dependency.json b/packages/base/src/files/install/servers/brmsgw/dependency.json
index c2a365ba8..b77e39795 100644
--- a/packages/base/src/files/install/servers/brmsgw/dependency.json
+++ b/packages/base/src/files/install/servers/brmsgw/dependency.json
@@ -24,10 +24,6 @@
"groupId": "org.onap.policy.models.policy-models-interactions.model-impl",
"artifactId": "so",
"version": "${{BRMS_MODELS_DEPENDENCY_VERSION}}"
- }, {
- "groupId": "org.onap.policy.models.policy-models-interactions.model-impl",
- "artifactId": "trafficgenerator",
- "version": "${{BRMS_MODELS_DEPENDENCY_VERSION}}"
}],
"amsterdam": [{
"groupId": "org.onap.policy.models.policy-models-interactions.model-impl",
@@ -66,10 +62,6 @@
"artifactId": "sdnc",
"version": "${{BRMS_MODELS_DEPENDENCY_VERSION}}"
}, {
- "groupId": "org.onap.policy.models.policy-models-interactions.model-impl",
- "artifactId": "trafficgenerator",
- "version": "${{BRMS_MODELS_DEPENDENCY_VERSION}}"
- }, {
"groupId": "org.onap.policy.drools-applications.controlloop.common",
"artifactId": "eventmanager",
"version": "${{BRMS_DEPENDENCY_VERSION}}"
diff --git a/packages/base/src/files/install/servers/onap/WEB-INF/classes/portal.properties b/packages/base/src/files/install/servers/onap/WEB-INF/classes/portal.properties
index 6473cc963..7b534358c 100644
--- a/packages/base/src/files/install/servers/onap/WEB-INF/classes/portal.properties
+++ b/packages/base/src/files/install/servers/onap/WEB-INF/classes/portal.properties
@@ -68,7 +68,7 @@ ueb_app_consumer_group_name = {UUID}
decryption_key = AGLDdG4D04BKm2IxIWEr8o==
# Use this tag if the app is centralized
-role_access_centralized = remote
+#role_access_centralized = remote
# Connection and Read timeout values
ext_req_connection_timeout = 15000
diff --git a/packages/base/src/files/install/servers/pdp/bin/xacml.pdp.properties b/packages/base/src/files/install/servers/pdp/bin/xacml.pdp.properties
index e8e28793a..d90b6f075 100644
--- a/packages/base/src/files/install/servers/pdp/bin/xacml.pdp.properties
+++ b/packages/base/src/files/install/servers/pdp/bin/xacml.pdp.properties
@@ -140,7 +140,7 @@ xacml.rest.pep.idfile = client.properties
enable_aaf=false
policy.aaf.namespace = ${{AAF_NAMESPACE}}
policy.aaf.root.permission=${{AAF_NAMESPACE}}.pdpx
-cm_url=https://${{AAF_HOST}}:8095/AAF_NS.cm:2.1
+cm_url=https://${{AAF_HOST}}:8095/onap.org.osaaf.aaf.cm:2.1
cadi_latitude=38.000
cadi.longitude=72.000
cadi_alias=policy@policy.onap.org
@@ -154,12 +154,12 @@ cadi_key_password=${{KEYSTORE_PASSWD}}
cadi_truststore=${{POLICY_HOME}}/etc/ssl/policy-truststore
cadi_truststore_password=${{TRUSTSTORE_PASSWD}}
aaf_env=DEV
-aaf_url=https://${{AAF_HOST}}:8095/AAF_NS.service:2.1
+aaf_url=https://${{AAF_HOST}}:8095/onap.org.osaaf.aaf.service:2.1
aaf_fqdn=${{AAF_HOST}}
-aaf_oauth2_introspect_url=https://${{AAF_HOST}}:8095/AAF_NS.introspect:2.1/introspect
-aaf_oauth2_token_url=https://${{AAF_HOST}}:8095/AAF_NS.token:2.1/token
-fs_url=https://${{AAF_HOST}}:8095/AAF_NS.fs.2.1
-gui_url=https://${{AAF_HOST}}:8095/AAF_NS.gui.2.1
+aaf_oauth2_introspect_url=https://${{AAF_HOST}}:8095/onap.org.osaaf.aaf.introspect:2.1/introspect
+aaf_oauth2_token_url=https://${{AAF_HOST}}:8095/onap.org.osaaf.aaf.token:2.1/token
+fs_url=https://${{AAF_HOST}}:8095/onap.org.osaaf.aaf.fs.2.1
+gui_url=https://${{AAF_HOST}}:8095/onap.org.osaaf.aaf.gui.2.1
# Decision Response settings.
# can be either PERMIT or DENY.
diff --git a/packages/docker/pom.xml b/packages/docker/pom.xml
index 0cc321233..38f8ab4a1 100644
--- a/packages/docker/pom.xml
+++ b/packages/docker/pom.xml
@@ -3,6 +3,7 @@
ONAP Policy Engine - Docker files
================================================================================
Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ Modifications Copyright (C) 2019 Bell Canada.
================================================================================
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
@@ -18,99 +19,150 @@
============LICENSE_END=========================================================
-->
-<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://maven.apache.org/POM/4.0.0"
+ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
- <modelVersion>4.0.0</modelVersion>
+ <modelVersion>4.0.0</modelVersion>
- <parent>
- <groupId>org.onap.policy.engine</groupId>
- <artifactId>packages</artifactId>
- <version>1.4.1-SNAPSHOT</version>
- </parent>
+ <parent>
+ <groupId>org.onap.policy.engine</groupId>
+ <artifactId>packages</artifactId>
+ <version>1.6.4-SNAPSHOT</version>
+ </parent>
- <artifactId>docker</artifactId>
- <packaging>pom</packaging>
- <name>Policy Engine - Docker build</name>
- <description>ONAP Policy Docker Build</description>
+ <artifactId>docker</artifactId>
+ <packaging>pom</packaging>
+ <name>Policy Engine - Docker build</name>
+ <description>ONAP Policy Docker Build</description>
- <properties>
- <nexusproxy>https://nexus.onap.org</nexusproxy>
- </properties>
-
- <build>
- <plugins>
- <plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-dependency-plugin</artifactId>
- <executions>
- <execution>
- <id>copy-pe-zip</id>
- <phase>prepare-package</phase>
- <goals>
- <goal>copy</goal>
- </goals>
- <configuration>
- <outputDirectory>${project.build.directory}/policy-pe</outputDirectory>
- <overWriteReleases>false</overWriteReleases>
- <overWriteSnapshots>true</overWriteSnapshots>
- <artifactItems>
- <artifactItem>
- <groupId>org.onap.policy.engine</groupId>
- <artifactId>install</artifactId>
- <version>${project.version}</version>
- <type>zip</type>
- <destFileName>install.zip</destFileName>
- </artifactItem>
- </artifactItems>
- </configuration>
- </execution>
- </executions>
- </plugin>
- <plugin>
- <artifactId>maven-resources-plugin</artifactId>
- <version>3.0.2</version>
- <executions>
- <execution>
- <id>copy-resources</id>
- <phase>prepare-package</phase>
- <goals>
- <goal>copy-resources</goal>
- </goals>
- <configuration>
- <outputDirectory>${project.build.directory}/policy-pe</outputDirectory>
- <resources>
- <resource>
- <directory>src/main/docker</directory>
- </resource>
- </resources>
- </configuration>
- </execution>
- </executions>
- </plugin>
- <plugin>
- <groupId>org.codehaus.mojo</groupId>
- <artifactId>exec-maven-plugin</artifactId>
- <version>1.6.0</version>
- <executions>
- <execution>
- <id>get-target-version</id>
- <phase>prepare-package</phase>
- <goals>
- <goal>exec</goal>
- </goals>
- </execution>
- </executions>
- <configuration>
- <executable>echo</executable>
- <workingDirectory>${project.build.directory}</workingDirectory>
- <arguments>
- <argument>${project.version}</argument>
- </arguments>
- <outputFile>${project.build.directory}/version</outputFile>
- </configuration>
- </plugin>
-
- </plugins>
- </build>
+ <properties>
+ <nexusproxy>https://nexus.onap.org</nexusproxy>
+ <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
+ <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
+ <dist.project.version>${project.version}</dist.project.version>
+ <docker.skip>false</docker.skip>
+ <docker.skip.build>false</docker.skip.build>
+ <docker.skip.push>false</docker.skip.push>
+ <docker.pull.registry>nexus3.onap.org:10001</docker.pull.registry>
+ <docker.push.registry>nexus3.onap.org:10003</docker.push.registry>
+ <maven.build.timestamp.format>yyyyMMdd'T'HHmm</maven.build.timestamp.format>
+ </properties>
+ <build>
+ <finalName>${project.artifactId}-${project.version}</finalName>
+ <plugins>
+ <plugin>
+ <groupId>org.codehaus.groovy.maven</groupId>
+ <artifactId>gmaven-plugin</artifactId>
+ <version>1.0</version>
+ <executions>
+ <execution>
+ <phase>validate</phase>
+ <goals>
+ <goal>execute</goal>
+ </goals>
+ <configuration>
+ <source>
+ println 'Project version: ' + project.properties['dist.project.version']
+ if (project.properties['dist.project.version'] != null) {
+ def versionArray = project.properties['dist.project.version'].split('-')
+ def minMaxVersionArray = versionArray[0].tokenize('.')
+ if (project.properties['dist.project.version'].endsWith("-SNAPSHOT")) {
+ project.properties['project.docker.latest.minmax.tag.version'] =
+ minMaxVersionArray[0] + "." + minMaxVersionArray[1] + "-SNAPSHOT-latest"
+ } else {
+ project.properties['project.docker.latest.minmax.tag.version'] =
+ minMaxVersionArray[0] + "." + minMaxVersionArray[1] + "-STAGING-latest"
+ }
+ println 'New tag for docker: ' + project.properties['project.docker.latest.minmax.tag.version']
+ }
+ </source>
+ </configuration>
+ </execution>
+ </executions>
+ </plugin>
+ <plugin>
+ <groupId>io.fabric8</groupId>
+ <artifactId>docker-maven-plugin</artifactId>
+ <configuration>
+ <verbose>true</verbose>
+ <apiVersion>1.23</apiVersion>
+ <pullRegistry>${docker.pull.registry}</pullRegistry>
+ <pushRegistry>${docker.push.registry}</pushRegistry>
+ <images>
+ <image>
+ <name>onap/policy-pe</name>
+ <build>
+ <cleanup>try</cleanup>
+ <dockerFile>Dockerfile</dockerFile>
+ <tags>
+ <tag>${project.version}</tag>
+ <tag>${project.version}-${maven.build.timestamp}</tag>
+ <tag>${project.docker.latest.minmax.tag.version}</tag>
+ </tags>
+ <assembly>
+ <inline>
+ <dependencySets>
+ <dependencySet>
+ <includes>
+ <include>org.onap.policy.engine:install</include>
+ </includes>
+ <outputDirectory>.</outputDirectory>
+ <outputFileNameMapping>install.zip</outputFileNameMapping>
+ </dependencySet>
+ </dependencySets>
+ </inline>
+ </assembly>
+ </build>
+ </image>
+ </images>
+ </configuration>
+ <executions>
+ <execution>
+ <id>clean-images</id>
+ <phase>pre-clean</phase>
+ <goals>
+ <goal>remove</goal>
+ </goals>
+ <configuration>
+ <removeAll>true</removeAll>
+ </configuration>
+ </execution>
+ <execution>
+ <id>generate-images</id>
+ <phase>generate-sources</phase>
+ <goals>
+ <goal>build</goal>
+ </goals>
+ </execution>
+ <execution>
+ <id>push-images</id>
+ <phase>deploy</phase>
+ <goals>
+ <goal>build</goal>
+ <goal>push</goal>
+ </goals>
+ <configuration>
+ <image>onap/policy-pe</image>
+ </configuration>
+ </execution>
+ </executions>
+ </plugin>
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-deploy-plugin</artifactId>
+ <configuration>
+ <skip>true</skip>
+ </configuration>
+ </plugin>
+ </plugins>
+ </build>
+ <dependencies>
+ <dependency>
+ <groupId>${project.groupId}</groupId>
+ <artifactId>install</artifactId>
+ <version>${project.version}</version>
+ <type>zip</type>
+ </dependency>
+ </dependencies>
</project>
diff --git a/packages/docker/src/main/docker/Dockerfile b/packages/docker/src/main/docker/Dockerfile
index 6b04b631f..ce7c95482 100644
--- a/packages/docker/src/main/docker/Dockerfile
+++ b/packages/docker/src/main/docker/Dockerfile
@@ -1,4 +1,4 @@
-FROM onap/policy-common-alpine:1.4.0
+FROM onap/policy-jdk-debian:2.0.1
LABEL maintainer="Policy Team"
@@ -8,16 +8,16 @@ ARG POLICY_LOGS=/var/log/onap
ENV BUILD_VERSION_ENGINE ${BUILD_VERSION_ENGINE}
ENV POLICY_LOGS ${POLICY_LOGS}
-RUN apk add --no-cache mariadb-client
-
-RUN mkdir -p /tmp/policy-install ${POLICY_LOGS} && \
- chown policy:policy /tmp/policy-install ${POLICY_LOGS} && \
- rmdir ${POLICY_HOME}/etc/ssl && \
- rmdir ${POLICY_HOME}/etc
+RUN apt update && \
+ apt-get install -y mariadb-client && \
+ apt-get install -y netcat && \
+ apt-get install -y cron && \
+ mkdir -p /tmp/policy-install ${POLICY_LOGS} && \
+ chown policy:policy /tmp/policy-install ${POLICY_LOGS}
WORKDIR /tmp/policy-install
-COPY install.zip docker-install.sh do-start.sh wait-for-port.sh ./
+COPY /maven/install.zip docker-install.sh do-start.sh wait-for-port.sh ./
RUN unzip install.zip && rm install.zip && chown policy * && chmod +x *.sh
USER policy
diff --git a/packages/docker/src/main/docker/do-start.sh b/packages/docker/src/main/docker/do-start.sh
index c655ce90a..63bac6ea2 100644
--- a/packages/docker/src/main/docker/do-start.sh
+++ b/packages/docker/src/main/docker/do-start.sh
@@ -3,7 +3,7 @@
#============LICENSE_START==================================================
# ONAP Policy Engine
#===========================================================================
-# Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+# Copyright (C) 2017-2020 AT&T Intellectual Property. All rights reserved.
#===========================================================================
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
@@ -112,9 +112,6 @@ if [[ $container == pap ]]; then
./wait-for-port.sh brmsgw 9989
./wait-for-port.sh nexus 8081
./wait-for-port.sh drools 6969
- # wait addional 1 minute for all processes to get fully initialized and synched up
- sleep 60
- bash -xv config/push-policies.sh
fi
-sleep 1000d
+sleep infinity
diff --git a/packages/install/pom.xml b/packages/install/pom.xml
index d72a78aaf..50ffa1c25 100644
--- a/packages/install/pom.xml
+++ b/packages/install/pom.xml
@@ -25,7 +25,7 @@
<parent>
<groupId>org.onap.policy.engine</groupId>
<artifactId>packages</artifactId>
- <version>1.4.1-SNAPSHOT</version>
+ <version>1.6.4-SNAPSHOT</version>
</parent>
<artifactId>install</artifactId>
diff --git a/packages/install/src/files/brmsgw.conf b/packages/install/src/files/brmsgw.conf
index 6d0f7d1af..09cf69d67 100644
--- a/packages/install/src/files/brmsgw.conf
+++ b/packages/install/src/files/brmsgw.conf
@@ -59,5 +59,5 @@ CLIENT_ID=PDPServer
CLIENT_KEY=test
ENVIRONMENT=DEVL
-BRMS_DEPENDENCY_VERSION=1.4.1-SNAPSHOT
-BRMS_MODELS_DEPENDENCY_VERSION=2.0.1-SNAPSHOT
+BRMS_DEPENDENCY_VERSION=1.6.3-SNAPSHOT
+BRMS_MODELS_DEPENDENCY_VERSION=2.2.6-SNAPSHOT
diff --git a/packages/pom.xml b/packages/pom.xml
index a97debf55..17f596f7a 100644
--- a/packages/pom.xml
+++ b/packages/pom.xml
@@ -2,7 +2,8 @@
============LICENSE_START=======================================================
ONAP Policy Engine
================================================================================
- Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ Copyright (C) 2017-2018, 2020 AT&T Intellectual Property. All rights reserved.
+ Modifications Copyright (C) 2019 Bell Canada.
================================================================================
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
@@ -18,41 +19,53 @@
============LICENSE_END=========================================================
-->
-<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
- <modelVersion>4.0.0</modelVersion>
- <parent>
- <groupId>org.onap.policy.engine</groupId>
- <artifactId>PolicyEngineSuite</artifactId>
- <version>1.4.1-SNAPSHOT</version>
- </parent>
- <artifactId>packages</artifactId>
- <packaging>pom</packaging>
- <name>Policy Packages</name>
- <description>D2 ONAP Policy Installation Packages</description>
- <profiles>
- <!-- DO NOT CHANGE THE *ORDER* IN WHICH THESE PROFILES ARE DEFINED! -->
- <profile>
- <id>default</id>
- <activation>
- <activeByDefault>true</activeByDefault>
- </activation>
- <modules>
- <module>base</module>
- <module>install</module>
- <module>docker</module>
- </modules>
- </profile>
- <profile>
- <id>with-integration-tests</id>
- <modules>
- <module>base</module>
- <module>install</module>
- </modules>
- </profile>
- </profiles>
- <modules>
- <module>base</module>
- <module>install</module>
- <module>docker</module>
- </modules>
+<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://maven.apache.org/POM/4.0.0"
+ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+ <modelVersion>4.0.0</modelVersion>
+ <parent>
+ <groupId>org.onap.policy.engine</groupId>
+ <artifactId>PolicyEngineSuite</artifactId>
+ <version>1.6.4-SNAPSHOT</version>
+ </parent>
+ <artifactId>packages</artifactId>
+ <packaging>pom</packaging>
+ <name>Policy Packages</name>
+ <description>D2 ONAP Policy Installation Packages</description>
+
+ <properties>
+ <!-- There is no code in this sub-module, only holds interfaces. So skip sonar. -->
+ <sonar.skip>true</sonar.skip>
+ </properties>
+
+ <profiles>
+ <!-- DO NOT CHANGE THE *ORDER* IN WHICH THESE PROFILES ARE DEFINED! -->
+ <profile>
+ <id>default</id>
+ <activation>
+ <activeByDefault>true</activeByDefault>
+ </activation>
+ <modules>
+ <module>base</module>
+ <module>install</module>
+ </modules>
+ </profile>
+ <profile>
+ <id>docker</id>
+ <modules>
+ <module>base</module>
+ <module>install</module>
+ <module>docker</module>
+ </modules>
+ <properties>
+ <docker.skip.push>false</docker.skip.push>
+ </properties>
+ </profile>
+ <profile>
+ <id>with-integration-tests</id>
+ <modules>
+ <module>base</module>
+ <module>install</module>
+ </modules>
+ </profile>
+ </profiles>
</project>
diff --git a/pom.xml b/pom.xml
index 21b7218c7..876d74f05 100644
--- a/pom.xml
+++ b/pom.xml
@@ -2,15 +2,15 @@
============LICENSE_START=======================================================
ONAP Policy Engine
================================================================================
- Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
+ Copyright (C) 2017-2020 AT&T Intellectual Property. All rights reserved.
Modifications Copyright (C) 2019 Nordix Foundation.
================================================================================
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
-
+
http://www.apache.org/licenses/LICENSE-2.0
-
+
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -18,24 +18,23 @@
limitations under the License.
============LICENSE_END=========================================================
-->
-<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.onap.policy.parent</groupId>
<artifactId>integration</artifactId>
- <version>2.1.0</version>
+ <version>3.1.3-SNAPSHOT</version>
<relativePath />
</parent>
<groupId>org.onap.policy.engine</groupId>
<artifactId>PolicyEngineSuite</artifactId>
- <version>1.4.1-SNAPSHOT</version>
+ <version>1.6.4-SNAPSHOT</version>
<packaging>pom</packaging>
<name>policy-engine</name>
<description>The ONAP Policy Engine main pom</description>
<properties>
<!-- Project common build settings -->
- <project.source.version>1.8</project.source.version>
- <project.target.version>1.8</project.target.version>
<project.encoding>UTF-8</project.encoding>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<!-- Project path properties -->
@@ -45,22 +44,18 @@
<snapshots.path>content/repositories/snapshots/</snapshots.path>
<staging.path>content/repositories/staging/</staging.path>
- <!-- sonar/jacoco overrides -->
- <!-- Overriding oparent default sonar/jacoco settings Combine all our reports
- into one file shared across sub-modules -->
- <sonar.jacoco.reportPath>${project.basedir}/../target/code-coverage/jacoco-ut.exec</sonar.jacoco.reportPath>
- <sonar.jacoco.itReportPath>${project.basedir}/../target/code-coverage/jacoco-it.exec</sonar.jacoco.itReportPath>
- <sonar.dynamicAnalysis>reuseReports</sonar.dynamicAnalysis>
+ <!-- Default Sonar configuration -->
+ <sonar.coverage.jacoco.xmlReportPaths>${project.reporting.outputDirectory}/jacoco-ut/jacoco.xml</sonar.coverage.jacoco.xmlReportPaths>
<!-- Project common dependency versions -->
- <springframework.version>4.3.18.RELEASE</springframework.version>
+ <springframework.version>4.3.24.RELEASE</springframework.version>
<jetty.plugin.version>9.2.3.v20140905</jetty.plugin.version>
<jackson.version>2.9.4</jackson.version>
<commons.fileupload.version>1.3.3</commons.fileupload.version>
<commons.compress.version>1.18</commons.compress.version>
- <elasticsearch.version>6.4.3</elasticsearch.version>
- <version.policy.common>1.4.0</version.policy.common>
- <version.policy.models>2.0.0</version.policy.models>
+ <elasticsearch.version>6.8.2</elasticsearch.version>
+ <version.policy.common>1.6.5-SNAPSHOT</version.policy.common>
+ <version.policy.models>2.2.6-SNAPSHOT</version.policy.models>
</properties>
<modules>
<module>PolicyEngineUtils</module>
@@ -100,14 +95,13 @@
</reporting>
<dependencies>
<dependency>
- <groupId>javax.servlet</groupId>
- <artifactId>javax.servlet-api</artifactId>
+ <groupId>org.projectlombok</groupId>
+ <artifactId>lombok</artifactId>
+ <scope>provided</scope>
</dependency>
<dependency>
- <!-- org.w3c.dom dependencies -->
- <groupId>xml-apis</groupId>
- <artifactId>xml-apis</artifactId>
- <version>1.3.03</version>
+ <groupId>javax.servlet</groupId>
+ <artifactId>javax.servlet-api</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
<dependency>
@@ -121,6 +115,11 @@
<scope>test</scope>
</dependency>
<dependency>
+ <groupId>org.assertj</groupId>
+ <artifactId>assertj-core</artifactId>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-mock</artifactId>
<version>2.0.8</version>
@@ -135,7 +134,7 @@
<!-- https://mvnrepository.com/artifact/org.powermock/powermock-api-mockito -->
<dependency>
<groupId>org.powermock</groupId>
- <artifactId>powermock-api-mockito</artifactId>
+ <artifactId>powermock-api-mockito2</artifactId>
<scope>test</scope>
</dependency>
<dependency>
@@ -152,49 +151,18 @@
<dependency>
<groupId>org.easymock</groupId>
<artifactId>easymock</artifactId>
- <version>3.1</version>
+ <version>4.1</version>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.glassfish.jersey.inject</groupId>
+ <artifactId>jersey-hk2</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
- <groupId>org.jacoco</groupId>
- <artifactId>jacoco-maven-plugin</artifactId>
- <executions>
- <execution>
- <id>pre-unit-test</id>
- <goals>
- <goal>prepare-agent</goal>
- </goals>
- <configuration>
- <destFile>${sonar.jacoco.reportPath}</destFile>
- <append>true</append>
- </configuration>
- </execution>
- <execution>
- <id>post-unit-test</id>
- <phase>test</phase>
- <goals>
- <goal>report</goal>
- </goals>
- <configuration>
- <dataFile>${sonar.jacoco.reportPath}</dataFile>
- </configuration>
- </execution>
- </executions>
- </plugin>
- <plugin>
- <groupId>org.sonatype.plugins</groupId>
- <artifactId>nexus-staging-maven-plugin</artifactId>
- <extensions>true</extensions>
- <configuration>
- <nexusUrl>${nexusproxy}</nexusUrl>
- <stagingProfileId>176c31dfe190a</stagingProfileId>
- <serverId>ecomp-staging</serverId>
- </configuration>
- </plugin>
- <plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-deploy-plugin</artifactId>
<configuration>
@@ -215,8 +183,7 @@
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<encoding>${project.encoding}</encoding>
- <source>${project.source.version}</source>
- <target>${project.target.version}</target>
+ <release>${java.version}</release>
</configuration>
</plugin>
<plugin>
@@ -263,46 +230,6 @@
<pluginManagement>
<plugins>
<plugin>
- <groupId>org.jacoco</groupId>
- <artifactId>jacoco-maven-plugin</artifactId>
- <version>${jacoco.version}</version>
- <configuration>
- <!-- Note: This exclusion list should match <sonar.exclusions> property
- above -->
- <excludes>
- <exclude>**/gen/**</exclude>
- <exclude>**/generated-sources/**</exclude>
- <exclude>**/yang-gen/**</exclude>
- <exclude>**/pax/**</exclude>
- </excludes>
- </configuration>
- <executions>
- <!-- Prepares the property pointing to the JaCoCo runtime agent which
- is passed as VM argument when Maven the Surefire plugin is executed. -->
- <execution>
- <id>pre-unit-test</id>
- <goals>
- <goal>prepare-agent</goal>
- </goals>
- <configuration>
- <destFile>${sonar.jacoco.reportPath}</destFile>
- </configuration>
- </execution>
- <!-- Ensures that the code coverage report for unit tests is created
- after unit tests have been run. -->
- <execution>
- <id>post-unit-test</id>
- <phase>test</phase>
- <goals>
- <goal>report</goal>
- </goals>
- <configuration>
- <dataFile>${sonar.jacoco.reportPath}</dataFile>
- </configuration>
- </execution>
- </executions>
- </plugin>
- <plugin>
<groupId>org.eclipse.m2e</groupId>
<artifactId>lifecycle-mapping</artifactId>
<version>1.0.0</version>
diff --git a/releases/1.5.1.yaml b/releases/1.5.1.yaml
new file mode 100644
index 000000000..54902c9ac
--- /dev/null
+++ b/releases/1.5.1.yaml
@@ -0,0 +1,4 @@
+distribution_type: 'maven'
+version: '1.5.1'
+project: 'policy-engine'
+log_dir: 'policy-engine-maven-stage-master/46/'
diff --git a/releases/1.5.2.yaml b/releases/1.5.2.yaml
new file mode 100644
index 000000000..20a8420e1
--- /dev/null
+++ b/releases/1.5.2.yaml
@@ -0,0 +1,4 @@
+distribution_type: 'maven'
+version: '1.5.2'
+project: 'policy-engine'
+log_dir: 'policy-engine-maven-stage-master/86/'
diff --git a/releases/1.6.0.yaml b/releases/1.6.0.yaml
new file mode 100644
index 000000000..c59dffbd0
--- /dev/null
+++ b/releases/1.6.0.yaml
@@ -0,0 +1,4 @@
+distribution_type: 'maven'
+version: '1.6.0'
+project: 'policy-engine'
+log_dir: 'policy-engine-maven-stage-master/280/'
diff --git a/releases/1.6.1-container.yaml b/releases/1.6.1-container.yaml
new file mode 100644
index 000000000..98a5e364f
--- /dev/null
+++ b/releases/1.6.1-container.yaml
@@ -0,0 +1,8 @@
+distribution_type: 'container'
+container_release_tag: '1.6.1'
+project: 'policy-engine'
+log_dir: 'policy-engine-maven-docker-stage-master/282'
+ref: 9af888cc263c9f30ce7a2af49fe3dcda1899f3ab
+containers:
+ - name: 'policy-pe'
+ version: '1.6.1-20200325T2242'
diff --git a/releases/1.6.1.yaml b/releases/1.6.1.yaml
new file mode 100644
index 000000000..724b4b734
--- /dev/null
+++ b/releases/1.6.1.yaml
@@ -0,0 +1,4 @@
+distribution_type: 'maven'
+version: '1.6.1'
+project: 'policy-engine'
+log_dir: 'policy-engine-maven-stage-master/283/'
diff --git a/releases/1.6.2-container.yaml b/releases/1.6.2-container.yaml
new file mode 100644
index 000000000..88566e08f
--- /dev/null
+++ b/releases/1.6.2-container.yaml
@@ -0,0 +1,8 @@
+distribution_type: 'container'
+container_release_tag: '1.6.2'
+project: 'policy-engine'
+log_dir: 'policy-engine-maven-docker-stage-master/304'
+ref: 99fad3e83f8282299e59077d8826362990c695a9
+containers:
+ - name: 'policy-pe'
+ version: '1.6.2-20200415T1303'
diff --git a/releases/1.6.2.yaml b/releases/1.6.2.yaml
new file mode 100644
index 000000000..c268e5a0d
--- /dev/null
+++ b/releases/1.6.2.yaml
@@ -0,0 +1,4 @@
+distribution_type: 'maven'
+version: '1.6.2'
+project: 'policy-engine'
+log_dir: 'policy-engine-maven-stage-master/305/'
diff --git a/releases/1.6.3-container.yaml b/releases/1.6.3-container.yaml
new file mode 100644
index 000000000..495d33bef
--- /dev/null
+++ b/releases/1.6.3-container.yaml
@@ -0,0 +1,8 @@
+distribution_type: 'container'
+container_release_tag: '1.6.3'
+project: 'policy-engine'
+log_dir: 'policy-engine-maven-docker-stage-master/321/'
+ref: fdd97327b8b3c646825c055de65d20c87261decb
+containers:
+ - name: 'policy-pe'
+ version: '1.6.3-20200430T1443'
diff --git a/releases/1.6.3.yaml b/releases/1.6.3.yaml
new file mode 100644
index 000000000..2836de910
--- /dev/null
+++ b/releases/1.6.3.yaml
@@ -0,0 +1,5 @@
+distribution_type: 'maven'
+version: '1.6.3'
+project: 'policy-engine'
+tag_release: false
+log_dir: 'policy-engine-maven-stage-master/322/'
diff --git a/version.properties b/version.properties
index e0ab8ddb9..cf52995b4 100644
--- a/version.properties
+++ b/version.properties
@@ -23,8 +23,8 @@
# because they are used in Jenkins, whose plug-in doesn't support
major=1
-minor=4
-patch=1
+minor=6
+patch=4
base_version=${major}.${minor}.${patch}