aboutsummaryrefslogtreecommitdiffstats
path: root/ONAP-PAP-REST
diff options
context:
space:
mode:
Diffstat (limited to 'ONAP-PAP-REST')
-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
134 files changed, 6916 insertions, 5380 deletions
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