Migrate policy api startup & config, controller to springboot 75/126975/7
authorRashmi Pujar <rashmi.pujar1@bell.ca>
Sat, 5 Feb 2022 02:49:30 +0000 (21:49 -0500)
committerRashmi Pujar <rashmi.pujar1@bell.ca>
Thu, 10 Feb 2022 06:33:25 +0000 (01:33 -0500)
Issue-ID: POLICY-3753
Signed-off-by: Rashmi Pujar <rashmi.pujar1@bell.ca>
Change-Id: I4537ed49b7fc57683bfc487f0d212642b7e69f17

58 files changed:
main/pom.xml
main/src/main/java/org/onap/policy/api/main/PolicyApiApplication.java [new file with mode: 0644]
main/src/main/java/org/onap/policy/api/main/config/PolicyApiAafConfig.java [new file with mode: 0644]
main/src/main/java/org/onap/policy/api/main/config/PolicyApiConfig.java [new file with mode: 0644]
main/src/main/java/org/onap/policy/api/main/config/PolicyPreloadConfig.java [new file with mode: 0644]
main/src/main/java/org/onap/policy/api/main/config/SecurityConfig.java [new file with mode: 0644]
main/src/main/java/org/onap/policy/api/main/config/SwaggerConfig.java [new file with mode: 0644]
main/src/main/java/org/onap/policy/api/main/config/WebConfig.java [new file with mode: 0644]
main/src/main/java/org/onap/policy/api/main/config/converter/StringToEnumConverter.java [new file with mode: 0644]
main/src/main/java/org/onap/policy/api/main/config/converter/YamlHttpMessageConverter.java [new file with mode: 0644]
main/src/main/java/org/onap/policy/api/main/exception/PolicyApiRuntimeException.java
main/src/main/java/org/onap/policy/api/main/parameters/ApiParameterGroup.java [deleted file]
main/src/main/java/org/onap/policy/api/main/parameters/ApiParameterHandler.java [deleted file]
main/src/main/java/org/onap/policy/api/main/rest/ApiRestController.java
main/src/main/java/org/onap/policy/api/main/rest/ApiStatisticsManager.java
main/src/main/java/org/onap/policy/api/main/rest/CommonRestController.java
main/src/main/java/org/onap/policy/api/main/rest/provider/CommonModelProvider.java
main/src/main/java/org/onap/policy/api/main/rest/provider/HealthCheckProvider.java
main/src/main/java/org/onap/policy/api/main/rest/provider/PolicyProvider.java
main/src/main/java/org/onap/policy/api/main/rest/provider/PolicyTypeProvider.java
main/src/main/java/org/onap/policy/api/main/rest/provider/StatisticsProvider.java
main/src/main/java/org/onap/policy/api/main/startstop/ApiActivator.java [deleted file]
main/src/main/java/org/onap/policy/api/main/startstop/ApiCommandLineArguments.java [deleted file]
main/src/main/java/org/onap/policy/api/main/startstop/ApiDatabaseInitializer.java
main/src/main/java/org/onap/policy/api/main/startstop/Main.java [deleted file]
main/src/main/resources/application.yaml [new file with mode: 0644]
main/src/test/java/org/onap/policy/api/main/parameters/CommonTestData.java [deleted file]
main/src/test/java/org/onap/policy/api/main/parameters/TestApiParameterGroup.java [deleted file]
main/src/test/java/org/onap/policy/api/main/parameters/TestApiParameterHandler.java [deleted file]
main/src/test/java/org/onap/policy/api/main/rest/TestApiRestServer.java
main/src/test/java/org/onap/policy/api/main/rest/TestApiStatisticsManager.java
main/src/test/java/org/onap/policy/api/main/rest/TestCommonRestController.java
main/src/test/java/org/onap/policy/api/main/rest/provider/TestPolicyProvider.java
main/src/test/java/org/onap/policy/api/main/rest/provider/TestPolicyTypeProvider.java
main/src/test/java/org/onap/policy/api/main/startstop/ApiDatabaseInitializerTest.java
main/src/test/java/org/onap/policy/api/main/startstop/TestApiActivator.java [deleted file]
main/src/test/java/org/onap/policy/api/main/startstop/TestApiCommandLineArguments.java [deleted file]
main/src/test/java/org/onap/policy/api/main/startstop/TestMain.java [deleted file]
main/src/test/resources/application-test.yaml [new file with mode: 0644]
main/src/test/resources/logback-test.xml [deleted file]
main/src/test/resources/parameters/ApiConfigParameters_Https.json [deleted file]
main/src/test/resources/parameters/ApiConfigParameters_InvalidName.json [deleted file]
main/src/test/resources/parameters/ApiConfigParameters_InvalidRestServerParameters.json [deleted file]
main/src/test/resources/parameters/ApiConfigParameters_Postgres.json [deleted file]
main/src/test/resources/parameters/BadParameters.json [deleted file]
main/src/test/resources/parameters/EmptyParameters.json [deleted file]
main/src/test/resources/parameters/InvalidParameters.json [deleted file]
main/src/test/resources/parameters/MinimumParameters.json [deleted file]
main/src/test/resources/parameters/NoParameters.json [deleted file]
main/src/test/resources/parameters/RestServerParameters.json [deleted file]
main/src/test/resources/parameters/RestServerParametersEmpty.json [deleted file]
packages/policy-api-docker/pom.xml
packages/policy-api-docker/src/main/docker/Dockerfile
packages/policy-api-docker/src/main/docker/policy-api.sh
packages/policy-api-tarball/src/main/package/tarball/assembly.xml
packages/policy-api-tarball/src/main/resources/etc/apiParameters.yaml [new file with mode: 0644]
packages/policy-api-tarball/src/main/resources/etc/defaultConfig.json [deleted file]
packages/policy-api-tarball/src/main/resources/etc/s3pConfig.json [deleted file]

index 5e54f2d..c89eafd 100644 (file)
@@ -3,7 +3,7 @@
    Copyright (C) 2018 Ericsson. All rights reserved.
    Modified Copyright (C) 2018 Samsung Electronics Co., Ltd.
    Copyright (C) 2019,2021 AT&T Intellectual Property. All rights reserved.
-   Modifications Copyright (C) 2020 Bell Canada.
+   Modifications Copyright (C) 2020-2022 Bell Canada.
    Modifications Copyright (C) 2022 Nordix Foundation.
   ================================================================================
   Licensed under the Apache License, Version 2.0 (the "License");
 
     <dependencies>
         <dependency>
-            <groupId>org.onap.policy.common</groupId>
-            <artifactId>capabilities</artifactId>
-            <version>${policy.common.version}</version>
+            <groupId>org.onap.policy.models</groupId>
+            <artifactId>policy-models-provider</artifactId>
+            <version>${policy.models.version}</version>
         </dependency>
         <dependency>
-            <groupId>commons-cli</groupId>
-            <artifactId>commons-cli</artifactId>
+            <groupId>com.h2database</groupId>
+            <artifactId>h2</artifactId>
         </dependency>
         <dependency>
-            <groupId>com.google.code.gson</groupId>
-            <artifactId>gson</artifactId>
+            <groupId>org.assertj</groupId>
+            <artifactId>assertj-core</artifactId>
+            <scope>test</scope>
         </dependency>
         <dependency>
             <groupId>org.onap.policy.common</groupId>
-            <artifactId>common-parameters</artifactId>
+            <artifactId>utils-test</artifactId>
             <version>${policy.common.version}</version>
+            <scope>test</scope>
         </dependency>
         <dependency>
-            <groupId>org.onap.policy.models</groupId>
-            <artifactId>policy-models-tosca</artifactId>
-            <version>${policy.models.version}</version>
-        </dependency>
-        <dependency>
-            <groupId>org.onap.policy.models</groupId>
-            <artifactId>policy-models-provider</artifactId>
-            <version>${policy.models.version}</version>
+            <groupId>org.junit.vintage</groupId>
+            <artifactId>junit-vintage-engine</artifactId>
+            <scope>test</scope>
         </dependency>
         <dependency>
-            <groupId>org.onap.policy.models</groupId>
-            <artifactId>policy-models-examples</artifactId>
-            <version>${policy.models.version}</version>
+            <groupId>org.springframework.boot</groupId>
+            <artifactId>spring-boot-starter-test</artifactId>
+            <scope>test</scope>
         </dependency>
         <dependency>
-            <groupId>org.onap.policy.common</groupId>
-            <artifactId>utils</artifactId>
-            <version>${policy.common.version}</version>
+            <groupId>com.google.code.gson</groupId>
+            <artifactId>gson</artifactId>
         </dependency>
         <dependency>
-            <groupId>org.projectlombok</groupId>
-            <artifactId>lombok</artifactId>
-            <scope>provided</scope>
+            <groupId>org.springframework.boot</groupId>
+            <artifactId>spring-boot-starter-web</artifactId>
+            <!-- Exclude the default Jackson dependency -->
+            <exclusions>
+                <exclusion>
+                    <groupId>org.springframework.boot</groupId>
+                    <artifactId>spring-boot-starter-json</artifactId>
+                </exclusion>
+            </exclusions>
         </dependency>
         <dependency>
-            <groupId>com.h2database</groupId>
-            <artifactId>h2</artifactId>
-            <scope>test</scope>
+            <groupId>org.springframework.boot</groupId>
+            <artifactId>spring-boot-starter-security</artifactId>
         </dependency>
         <dependency>
-            <groupId>org.mariadb.jdbc</groupId>
-            <artifactId>mariadb-java-client</artifactId>
+            <groupId>org.springframework.boot</groupId>
+            <artifactId>spring-boot-starter-actuator</artifactId>
+            <version>${version.springboot.actuator}</version>
         </dependency>
         <dependency>
-            <groupId>org.postgresql</groupId>
-            <artifactId>postgresql</artifactId>
+            <groupId>io.micrometer</groupId>
+            <artifactId>micrometer-registry-prometheus</artifactId>
+            <version>${version.io.micrometer}</version>
+            <scope>runtime</scope>
         </dependency>
         <dependency>
-            <groupId>org.assertj</groupId>
-            <artifactId>assertj-core</artifactId>
-            <scope>test</scope>
+            <groupId>io.springfox</groupId>
+            <artifactId>springfox-boot-starter</artifactId>
+            <version>${version.springfox}</version>
         </dependency>
         <dependency>
-            <groupId>org.onap.policy.common</groupId>
-            <artifactId>utils-test</artifactId>
-            <version>${policy.common.version}</version>
-            <scope>test</scope>
+            <groupId>io.springfox</groupId>
+            <artifactId>springfox-swagger-ui</artifactId>
+            <version>${version.springfox}</version>
+            <scope>runtime</scope>
         </dependency>
     </dependencies>
 
                 </excludes>
             </resource>
         </resources>
+        <plugins>
+            <plugin>
+                <groupId>org.springframework.boot</groupId>
+                <artifactId>spring-boot-maven-plugin</artifactId>
+                <executions>
+                    <execution>
+                        <goals>
+                            <goal>repackage</goal>
+                        </goals>
+                        <phase>package</phase>
+                    </execution>
+                </executions>
+            </plugin>
+        </plugins>
     </build>
-
-</project>
+</project>
\ No newline at end of file
diff --git a/main/src/main/java/org/onap/policy/api/main/PolicyApiApplication.java b/main/src/main/java/org/onap/policy/api/main/PolicyApiApplication.java
new file mode 100644 (file)
index 0000000..25c4d93
--- /dev/null
@@ -0,0 +1,31 @@
+/*-
+ * ============LICENSE_START=======================================================
+ *  Copyright (C) 2022 Bell Canada. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ * SPDX-License-Identifier: Apache-2.0
+ * ============LICENSE_END=========================================================
+ */
+
+package org.onap.policy.api.main;
+
+import org.springframework.boot.SpringApplication;
+import org.springframework.boot.autoconfigure.SpringBootApplication;
+
+@SpringBootApplication
+public class PolicyApiApplication {
+    public static void main(String[] args) {
+        SpringApplication.run(PolicyApiApplication.class, args);
+    }
+}
\ No newline at end of file
diff --git a/main/src/main/java/org/onap/policy/api/main/config/PolicyApiAafConfig.java b/main/src/main/java/org/onap/policy/api/main/config/PolicyApiAafConfig.java
new file mode 100644 (file)
index 0000000..bd55344
--- /dev/null
@@ -0,0 +1,37 @@
+/*-
+ * ============LICENSE_START=======================================================
+ *  Copyright (C) 2022 Bell Canada. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ * SPDX-License-Identifier: Apache-2.0
+ * ============LICENSE_END=========================================================
+ */
+
+package org.onap.policy.api.main.config;
+
+import javax.servlet.Filter;
+import org.onap.policy.api.main.rest.aaf.AafApiFilter;
+import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+
+@Configuration
+@ConditionalOnProperty(value = "policy-api.aaf", havingValue = "true")
+public class PolicyApiAafConfig {
+
+    @Bean
+    public Filter aafFilter() {
+        return new AafApiFilter();
+    }
+}
\ No newline at end of file
diff --git a/main/src/main/java/org/onap/policy/api/main/config/PolicyApiConfig.java b/main/src/main/java/org/onap/policy/api/main/config/PolicyApiConfig.java
new file mode 100644 (file)
index 0000000..3e4f11a
--- /dev/null
@@ -0,0 +1,76 @@
+/*-
+ * ============LICENSE_START=======================================================
+ *  Copyright (C) 2022 Bell Canada. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ * SPDX-License-Identifier: Apache-2.0
+ * ============LICENSE_END=========================================================
+ */
+
+package org.onap.policy.api.main.config;
+
+import org.onap.policy.api.main.rest.StatisticsReport;
+import org.onap.policy.models.base.PfModelException;
+import org.onap.policy.models.provider.PolicyModelsProvider;
+import org.onap.policy.models.provider.PolicyModelsProviderFactory;
+import org.onap.policy.models.provider.PolicyModelsProviderParameters;
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+
+@Configuration
+public class PolicyApiConfig {
+
+    @Value("${policy-api.name}")
+    private String groupName;
+    @Value("${database.name}")
+    private String databaseName;
+    @Value("${database.implementation}")
+    private String databaseImplementation;
+    @Value("${database.driver}")
+    private String databaseDriver;
+    @Value("${database.url}")
+    private String databaseUrl;
+    @Value("${database.user}")
+    private String databaseUser;
+    @Value("${database.password}")
+    private String databasePassword;
+    @Value("${database.persistenceUnit}")
+    private String databasePersistenceUnit;
+
+    /**
+     * Initialize database configuration.
+     *
+     * @return PolicyModelsProvider
+     * @throws PfModelException Policy exception
+     */
+    @Bean(destroyMethod = "close")
+    public PolicyModelsProvider policyModelsProvider() throws PfModelException {
+        PolicyModelsProviderParameters modelsProviderParameters = new PolicyModelsProviderParameters();
+        modelsProviderParameters.setName(databaseName);
+        modelsProviderParameters.setImplementation(databaseImplementation);
+        modelsProviderParameters.setDatabaseDriver(databaseDriver);
+        modelsProviderParameters.setDatabaseUrl(databaseUrl);
+        modelsProviderParameters.setDatabaseUser(databaseUser);
+        modelsProviderParameters.setDatabasePassword(databasePassword);
+        modelsProviderParameters.setPersistenceUnit(databasePersistenceUnit);
+        modelsProviderParameters.setDatabaseDriver(databaseDriver);
+        return new PolicyModelsProviderFactory().createPolicyModelsProvider(modelsProviderParameters);
+    }
+
+    @Bean
+    public StatisticsReport createStatisticsReport() {
+        return new StatisticsReport();
+    }
+}
\ No newline at end of file
diff --git a/main/src/main/java/org/onap/policy/api/main/config/PolicyPreloadConfig.java b/main/src/main/java/org/onap/policy/api/main/config/PolicyPreloadConfig.java
new file mode 100644 (file)
index 0000000..c2c40ff
--- /dev/null
@@ -0,0 +1,40 @@
+/*-
+ * ============LICENSE_START=======================================================
+ *  Copyright (C) 2022 Bell Canada. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ * SPDX-License-Identifier: Apache-2.0
+ * ============LICENSE_END=========================================================
+ */
+
+package org.onap.policy.api.main.config;
+
+import java.util.List;
+import lombok.Getter;
+import lombok.Setter;
+import org.springframework.boot.context.properties.ConfigurationProperties;
+import org.springframework.stereotype.Component;
+
+@Component
+@ConfigurationProperties("policy-preload")
+public class PolicyPreloadConfig {
+
+    @Getter
+    @Setter
+    List<String> policyTypes;
+
+    @Getter
+    @Setter
+    List<String> policies;
+}
\ No newline at end of file
diff --git a/main/src/main/java/org/onap/policy/api/main/config/SecurityConfig.java b/main/src/main/java/org/onap/policy/api/main/config/SecurityConfig.java
new file mode 100644 (file)
index 0000000..367f92a
--- /dev/null
@@ -0,0 +1,36 @@
+/*-
+ * ============LICENSE_START=======================================================
+ *  Copyright (C) 2022 Bell Canada. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ * SPDX-License-Identifier: Apache-2.0
+ * ============LICENSE_END=========================================================
+ */
+
+package org.onap.policy.api.main.config;
+
+import org.springframework.context.annotation.Configuration;
+import org.springframework.security.config.annotation.web.builders.HttpSecurity;
+import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
+
+@Configuration
+public class SecurityConfig extends WebSecurityConfigurerAdapter {
+
+    @Override
+    public void configure(HttpSecurity http) throws Exception {
+        http.httpBasic().and()  // use Basic authentication
+            .authorizeRequests().anyRequest().authenticated() // allow authenticated access to all rest endpoints
+            .and().csrf().disable(); // CSRF filter is relevant when serving browser clients, hence disable
+    }
+}
\ No newline at end of file
diff --git a/main/src/main/java/org/onap/policy/api/main/config/SwaggerConfig.java b/main/src/main/java/org/onap/policy/api/main/config/SwaggerConfig.java
new file mode 100644 (file)
index 0000000..052ae5c
--- /dev/null
@@ -0,0 +1,47 @@
+/*-
+ * ============LICENSE_START=======================================================
+ *  Copyright (C) 2022 Bell Canada. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ * SPDX-License-Identifier: Apache-2.0
+ * ============LICENSE_END=========================================================
+ */
+
+package org.onap.policy.api.main.config;
+
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+import springfox.documentation.builders.PathSelectors;
+import springfox.documentation.builders.RequestHandlerSelectors;
+import springfox.documentation.spi.DocumentationType;
+import springfox.documentation.spring.web.plugins.Docket;
+import springfox.documentation.swagger2.annotations.EnableSwagger2;
+
+@Configuration
+@EnableSwagger2
+public class SwaggerConfig {
+
+    /**
+     * Create a bean of type Docket to determine the swagger configuration.
+     * @return docket bean with swagger configuration.
+     */
+    @Bean
+    public Docket api() {
+        return new Docket(DocumentationType.SWAGGER_2)
+            .select()
+            .apis(RequestHandlerSelectors.basePackage("org.onap.policy.api.main.rest"))
+            .paths(PathSelectors.any())
+            .build();
+    }
+}
\ No newline at end of file
diff --git a/main/src/main/java/org/onap/policy/api/main/config/WebConfig.java b/main/src/main/java/org/onap/policy/api/main/config/WebConfig.java
new file mode 100644 (file)
index 0000000..a50dd18
--- /dev/null
@@ -0,0 +1,72 @@
+/*-
+ * ============LICENSE_START=======================================================
+ *  Copyright (C) 2022 Bell Canada. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ * SPDX-License-Identifier: Apache-2.0
+ * ============LICENSE_END=========================================================
+ */
+
+package org.onap.policy.api.main.config;
+
+import com.google.gson.Gson;
+import com.google.gson.GsonBuilder;
+import com.google.gson.JsonParser;
+import com.google.gson.JsonSerializer;
+import java.util.Arrays;
+import java.util.List;
+import org.onap.policy.api.main.config.converter.StringToEnumConverter;
+import org.onap.policy.api.main.config.converter.YamlHttpMessageConverter;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.format.FormatterRegistry;
+import org.springframework.http.MediaType;
+import org.springframework.http.converter.HttpMessageConverter;
+import org.springframework.http.converter.json.GsonHttpMessageConverter;
+import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
+import springfox.documentation.spring.web.json.Json;
+
+/**
+ * Register custom converters to Spring configuration.
+ */
+@Configuration
+public class WebConfig implements WebMvcConfigurer {
+    @Override
+    public void addFormatters(FormatterRegistry registry) {
+        registry.addConverter(new StringToEnumConverter());
+    }
+
+    @Override
+    public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
+        YamlHttpMessageConverter yamlConverter = new YamlHttpMessageConverter();
+        yamlConverter.setSupportedMediaTypes(Arrays.asList(MediaType.parseMediaType("application/yaml")));
+        converters.add(yamlConverter);
+
+        GsonHttpMessageConverter converter = buildGsonConverter();
+        converters.removeIf(c -> c instanceof GsonHttpMessageConverter);
+        converters.add(0, converter);
+    }
+
+    /**
+     * Swagger uses {{@link springfox.documentation.spring.web.json.Json}} which leads to Gson serialization errors.
+     * Hence, we customize a typeAdapter on the Gson bean in the Gson http message converter.
+     *
+     * @return customised GSON HttpMessageConverter instance.
+     */
+    private GsonHttpMessageConverter buildGsonConverter() {
+        JsonSerializer<Json> serializer = (json, type, jsonSerializationContext) ->
+            JsonParser.parseString(json.value());
+        Gson gson = new GsonBuilder().registerTypeAdapter(Json.class, serializer).create();
+        return new GsonHttpMessageConverter(gson);
+    }
+}
\ No newline at end of file
diff --git a/main/src/main/java/org/onap/policy/api/main/config/converter/StringToEnumConverter.java b/main/src/main/java/org/onap/policy/api/main/config/converter/StringToEnumConverter.java
new file mode 100644 (file)
index 0000000..a6e8c4a
--- /dev/null
@@ -0,0 +1,39 @@
+/*-
+ * ============LICENSE_START=======================================================
+ *  Copyright (C) 2022 Bell Canada. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ * SPDX-License-Identifier: Apache-2.0
+ * ============LICENSE_END=========================================================
+ */
+
+package org.onap.policy.api.main.config.converter;
+
+import org.onap.policy.api.main.rest.PolicyFetchMode;
+import org.springframework.core.convert.converter.Converter;
+
+/**
+ * Custom converter to support lowercase request parameters for policy fetch mode enumeration.
+ */
+public class StringToEnumConverter implements Converter<String, PolicyFetchMode> {
+
+    @Override
+    public PolicyFetchMode convert(String source) {
+        try {
+            return PolicyFetchMode.valueOf(source.toUpperCase());
+        } catch (IllegalArgumentException e) {
+            return null;
+        }
+    }
+}
\ No newline at end of file
diff --git a/main/src/main/java/org/onap/policy/api/main/config/converter/YamlHttpMessageConverter.java b/main/src/main/java/org/onap/policy/api/main/config/converter/YamlHttpMessageConverter.java
new file mode 100644 (file)
index 0000000..9fe9b03
--- /dev/null
@@ -0,0 +1,109 @@
+/*-
+ * ============LICENSE_START=======================================================
+ *  Copyright (C) 2022 Bell Canada. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ * SPDX-License-Identifier: Apache-2.0
+ * ============LICENSE_END=========================================================
+ */
+
+package org.onap.policy.api.main.config.converter;
+
+import java.io.IOException;
+import java.io.InputStreamReader;
+import java.io.OutputStreamWriter;
+import java.io.Reader;
+import java.io.Writer;
+import java.lang.reflect.Type;
+import java.nio.charset.Charset;
+import java.nio.charset.StandardCharsets;
+import org.onap.policy.common.utils.coder.YamlJsonTranslator;
+import org.springframework.core.GenericTypeResolver;
+import org.springframework.http.HttpHeaders;
+import org.springframework.http.HttpInputMessage;
+import org.springframework.http.HttpOutputMessage;
+import org.springframework.http.MediaType;
+import org.springframework.http.converter.AbstractGenericHttpMessageConverter;
+import org.springframework.http.converter.HttpMessageNotReadableException;
+import org.springframework.http.converter.HttpMessageNotWritableException;
+import org.springframework.lang.Nullable;
+
+/**
+ * Custom converter to marshal/unmarshall data structured with YAML media type.
+ */
+public class YamlHttpMessageConverter extends AbstractGenericHttpMessageConverter<Object> {
+
+    public static final Charset DEFAULT_CHARSET = StandardCharsets.UTF_8;
+
+    private static final YamlJsonTranslator TRANSLATOR = new YamlJsonTranslator();
+
+    public YamlHttpMessageConverter() {
+        super(new MediaType("application", "yaml"));
+        setDefaultCharset(DEFAULT_CHARSET);
+    }
+
+    @Override
+    public final Object read(Type type, @Nullable Class<?> contextClass, HttpInputMessage inputMessage)
+        throws IOException {
+        return readResolved(GenericTypeResolver.resolveType(type, contextClass), inputMessage);
+    }
+
+    @Override
+    protected final Object readInternal(Class<?> clazz, HttpInputMessage inputMessage) throws IOException {
+        return readResolved(clazz, inputMessage);
+    }
+
+    private Object readInternal(Type resolvedType, Reader reader) {
+        Class<?> clazz = (Class<?>) resolvedType;
+        return TRANSLATOR.fromYaml(reader, clazz);
+    }
+
+    @Override
+    protected final void writeInternal(Object object, @Nullable Type type, HttpOutputMessage outputMessage)
+        throws IOException {
+        Writer writer = getWriter(outputMessage);
+        try {
+            writeInternal(object, type, writer);
+        } catch (Exception ex) {
+            throw new HttpMessageNotWritableException("Could not write YAML: " + ex.getMessage(), ex);
+        }
+        writer.flush();
+    }
+
+    private void writeInternal(Object object, @Nullable Type type, Writer writer) {
+        TRANSLATOR.toYaml(writer, object);
+    }
+
+    private Object readResolved(Type resolvedType, HttpInputMessage inputMessage) throws IOException {
+        Reader reader = getReader(inputMessage);
+        try {
+            return readInternal(resolvedType, reader);
+        } catch (Exception ex) {
+            throw new HttpMessageNotReadableException("Could not read YAML: " + ex.getMessage(), ex, inputMessage);
+        }
+    }
+
+    private static Reader getReader(HttpInputMessage inputMessage) throws IOException {
+        return new InputStreamReader(inputMessage.getBody(), getCharset(inputMessage.getHeaders()));
+    }
+
+    private static Writer getWriter(HttpOutputMessage outputMessage) throws IOException {
+        return new OutputStreamWriter(outputMessage.getBody(), getCharset(outputMessage.getHeaders()));
+    }
+
+    private static Charset getCharset(HttpHeaders headers) {
+        Charset charset = (headers.getContentType() == null ? null : headers.getContentType().getCharset());
+        return (charset != null ? charset : DEFAULT_CHARSET);
+    }
+}
\ No newline at end of file
index ea6b55f..19bf5e1 100644 (file)
@@ -1,6 +1,7 @@
 /*-
  * ============LICENSE_START=======================================================
  *  Copyright (C) 2018 Samsung Electronics Co., Ltd. All rights reserved.
+ *  Modifications Copyright (C) 2022 Bell Canada. All rights reserved.
  * ================================================================================
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
 
 package org.onap.policy.api.main.exception;
 
+import java.util.UUID;
+import lombok.Getter;
+import org.onap.policy.models.errors.concepts.ErrorResponse;
+
 /**
  * This runtime exception will be called if a runtime error occurs when using policy api.
  */
 public class PolicyApiRuntimeException extends RuntimeException {
+
     private static final long serialVersionUID = -8507246953751956974L;
 
+    @Getter
+    private final UUID requestId;
+    @Getter
+    private final ErrorResponse errorResponse;
+
     /**
      * Instantiates a new policy api runtime exception with a message.
      *
@@ -33,6 +44,8 @@ public class PolicyApiRuntimeException extends RuntimeException {
      */
     public PolicyApiRuntimeException(final String message) {
         super(message);
+        this.requestId = null;
+        this.errorResponse = null;
     }
 
     /**
@@ -43,5 +56,23 @@ public class PolicyApiRuntimeException extends RuntimeException {
      */
     public PolicyApiRuntimeException(final String message, final Exception exp) {
         super(message, exp);
+        this.requestId = null;
+        this.errorResponse = null;
+    }
+
+    /**
+     * Instantiates a new policy api runtime exception with requestId, errorResponse object
+     * along with message and a caused by exception.
+     *
+     * @param message the message
+     * @param cause the exception that caused this exception to be thrown
+     * @param requestId request identifier
+     * @param errorResponse error response object
+     */
+    public PolicyApiRuntimeException(final String message, final Throwable cause,
+                                     final ErrorResponse errorResponse, final UUID requestId) {
+        super(message, cause);
+        this.requestId = requestId;
+        this.errorResponse = errorResponse;
     }
-}
+}
\ No newline at end of file
diff --git a/main/src/main/java/org/onap/policy/api/main/parameters/ApiParameterGroup.java b/main/src/main/java/org/onap/policy/api/main/parameters/ApiParameterGroup.java
deleted file mode 100644 (file)
index c9b96e3..0000000
+++ /dev/null
@@ -1,65 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- *  Copyright (C) 2018 Samsung Electronics Co., Ltd. All rights reserved.
- *  Modifications Copyright (C) 2021 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- * SPDX-License-Identifier: Apache-2.0
- * ============LICENSE_END=========================================================
- */
-
-package org.onap.policy.api.main.parameters;
-
-import java.util.List;
-import lombok.Getter;
-import org.onap.policy.common.endpoints.parameters.RestServerParameters;
-import org.onap.policy.common.parameters.ParameterGroupImpl;
-import org.onap.policy.common.parameters.annotations.NotBlank;
-import org.onap.policy.common.parameters.annotations.NotNull;
-import org.onap.policy.common.parameters.annotations.Valid;
-import org.onap.policy.models.provider.PolicyModelsProviderParameters;
-
-/**
- * Class to hold all parameters needed for Api component.
- *
- */
-@Getter
-public class ApiParameterGroup extends ParameterGroupImpl {
-
-    @NotNull @Valid
-    private final RestServerParameters restServerParameters;
-    @NotNull @Valid
-    private final PolicyModelsProviderParameters databaseProviderParameters;
-    private final List<@NotNull @NotBlank String> preloadPolicyTypes;
-    private final List<@NotNull @NotBlank String> preloadPolicies;
-
-    /**
-     * Create the api parameter group.
-     *
-     * @param name the parameter group name
-     * @param restServerParameters the parameters for instantiating API rest server
-     * @param databaseProviderParameters the parameters for instantiating database provider
-     * @param preloadPolicyTypes the list of preloaded policy types
-     * @param preloadPolicies the list of preloaded policies
-     */
-    public ApiParameterGroup(final String name, final RestServerParameters restServerParameters,
-            final PolicyModelsProviderParameters databaseProviderParameters, final List<String> preloadPolicyTypes,
-            final List<String> preloadPolicies) {
-        super(name);
-        this.restServerParameters = restServerParameters;
-        this.databaseProviderParameters = databaseProviderParameters;
-        this.preloadPolicyTypes = preloadPolicyTypes;
-        this.preloadPolicies = preloadPolicies;
-    }
-}
diff --git a/main/src/main/java/org/onap/policy/api/main/parameters/ApiParameterHandler.java b/main/src/main/java/org/onap/policy/api/main/parameters/ApiParameterHandler.java
deleted file mode 100644 (file)
index 019a012..0000000
+++ /dev/null
@@ -1,84 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * ONAP Policy API
- * ================================================================================
- * Copyright (C) 2018 Samsung Electronics Co., Ltd. All rights reserved.
- * Copyright (C) 2019, 2021 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- * SPDX-License-Identifier: Apache-2.0
- * ============LICENSE_END=========================================================
- */
-
-package org.onap.policy.api.main.parameters;
-
-import com.google.gson.GsonBuilder;
-import java.io.FileReader;
-import org.onap.policy.api.main.exception.PolicyApiException;
-import org.onap.policy.api.main.startstop.ApiCommandLineArguments;
-import org.onap.policy.common.parameters.ValidationResult;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-/**
- * This class handles reading, parsing and validating of policy api parameters from JSON files.
- */
-public class ApiParameterHandler {
-
-    private static final Logger LOGGER = LoggerFactory.getLogger(ApiParameterHandler.class);
-
-    /**
-     * Read the parameters from the parameter file.
-     *
-     * @param arguments the arguments passed to policy api
-     * @return the parameters read from the configuration file
-     * @throws PolicyApiException on parameter exceptions
-     */
-    public ApiParameterGroup getParameters(final ApiCommandLineArguments arguments)
-            throws PolicyApiException {
-        ApiParameterGroup apiParameterGroup = null;
-
-        // Read the parameters
-        try {
-            // Read the parameters from JSON using Gson
-            final var gson = new GsonBuilder().create();
-            apiParameterGroup = gson.fromJson(new FileReader(arguments.getFullConfigurationFilePath()),
-                    ApiParameterGroup.class);
-        } catch (final Exception e) {
-            final String errorMessage = "error reading parameters from \"" + arguments.getConfigurationFilePath()
-                    + "\"\n" + "(" + e.getClass().getSimpleName() + "):" + e.getMessage();
-            throw new PolicyApiException(errorMessage, e);
-        }
-
-        // The JSON processing returns null if there is an empty file
-        if (apiParameterGroup == null) {
-            final String errorMessage = "no parameters found in \"" + arguments.getConfigurationFilePath() + "\"";
-            LOGGER.error(errorMessage);
-            throw new PolicyApiException(errorMessage);
-        }
-
-        // validate the parameters
-        final ValidationResult validationResult = apiParameterGroup.validate();
-        if (!validationResult.isValid()) {
-            String returnMessage =
-                    "validation error(s) on parameters from \"" + arguments.getConfigurationFilePath() + "\"\n";
-            returnMessage += validationResult.getResult();
-
-            LOGGER.error(returnMessage);
-            throw new PolicyApiException(returnMessage);
-        }
-
-        return apiParameterGroup;
-    }
-}
index eb60c5e..263345a 100644 (file)
@@ -5,7 +5,7 @@
  * Copyright (C) 2018 Samsung Electronics Co., Ltd. All rights reserved.\r
  * Modifications Copyright (C) 2019-2021 AT&T Intellectual Property. All rights reserved.\r
  * Modifications Copyright (C) 2020 Nordix Foundation.\r
- * Modifications Copyright (C) 2020 Bell Canada.\r
+ * Modifications Copyright (C) 2020-2022 Bell Canada. All rights reserved.\r
  * ================================================================================\r
  * Licensed under the Apache License, Version 2.0 (the "License");\r
  * you may not use this file except in compliance with the License.\r
@@ -41,18 +41,8 @@ import io.swagger.annotations.SwaggerDefinition;
 import java.net.HttpURLConnection;\r
 import java.util.List;\r
 import java.util.UUID;\r
-import javax.ws.rs.Consumes;\r
-import javax.ws.rs.DELETE;\r
-import javax.ws.rs.DefaultValue;\r
-import javax.ws.rs.GET;\r
-import javax.ws.rs.HeaderParam;\r
-import javax.ws.rs.POST;\r
-import javax.ws.rs.Path;\r
-import javax.ws.rs.PathParam;\r
-import javax.ws.rs.Produces;\r
-import javax.ws.rs.QueryParam;\r
-import javax.ws.rs.core.Response;\r
 import javax.ws.rs.core.Response.Status;\r
+import org.onap.policy.api.main.exception.PolicyApiRuntimeException;\r
 import org.onap.policy.api.main.rest.provider.HealthCheckProvider;\r
 import org.onap.policy.api.main.rest.provider.PolicyProvider;\r
 import org.onap.policy.api.main.rest.provider.PolicyTypeProvider;\r
@@ -66,16 +56,29 @@ import org.onap.policy.models.base.PfModelRuntimeException;
 import org.onap.policy.models.tosca.authorative.concepts.ToscaServiceTemplate;\r
 import org.slf4j.Logger;\r
 import org.slf4j.LoggerFactory;\r
+import org.springframework.beans.factory.annotation.Autowired;\r
+import org.springframework.http.HttpMethod;\r
+import org.springframework.http.HttpStatus;\r
+import org.springframework.http.ResponseEntity;\r
+import org.springframework.web.bind.annotation.DeleteMapping;\r
+import org.springframework.web.bind.annotation.ExceptionHandler;\r
+import org.springframework.web.bind.annotation.GetMapping;\r
+import org.springframework.web.bind.annotation.PathVariable;\r
+import org.springframework.web.bind.annotation.PostMapping;\r
+import org.springframework.web.bind.annotation.RequestBody;\r
+import org.springframework.web.bind.annotation.RequestHeader;\r
+import org.springframework.web.bind.annotation.RequestMapping;\r
+import org.springframework.web.bind.annotation.RequestParam;\r
+import org.springframework.web.bind.annotation.RestController;\r
 \r
 /**\r
  * Class to provide REST API services.\r
  *\r
  * @author Chenfei Gao (cgao@research.att.com)\r
  */\r
-@Path("/policy/api/v1")\r
+@RestController\r
+@RequestMapping(path = "/policy/api/v1", produces = { "application/json", "application/yaml" })\r
 @Api(value = "Policy Design API")\r
-@Produces({"application/json", "application/yaml"})\r
-@Consumes({"application/json", "application/yaml"})\r
 @SwaggerDefinition(\r
     info = @Info(\r
         description = "Policy Design API is publicly exposed for clients to Create/Read/Update/Delete"\r
@@ -129,14 +132,33 @@ public class ApiRestController extends CommonRestController {
     private static final String INVALID_PAYLOAD_MESSAGE = "Not Acceptable Payload";\r
     private static final String HTTP_CONFLICT_MESSAGE = "Delete Conflict, Rule Violation";\r
 \r
+    private enum Target {\r
+        POLICY,\r
+        POLICY_TYPE,\r
+        OTHER\r
+    }\r
+\r
+    @Autowired\r
+    private PolicyProvider policyProvider;\r
+\r
+    @Autowired\r
+    private HealthCheckProvider healthCheckProvider;\r
+\r
+    @Autowired\r
+    private PolicyTypeProvider policyTypeProvider;\r
+\r
+    @Autowired\r
+    private ApiStatisticsManager mgr;\r
+\r
+    @Autowired\r
+    private StatisticsProvider statisticsProvider;\r
 \r
     /**\r
      * Retrieves the healthcheck status of the API component.\r
      *\r
      * @return the Response object containing the results of the API operation\r
      */\r
-    @GET\r
-    @Path("/healthcheck")\r
+    @GetMapping("/healthcheck")\r
     @ApiOperation(value = "Perform a system healthcheck", notes = "Returns healthy status of the Policy API component",\r
         response = HealthCheckReport.class,\r
         responseHeaders = {\r
@@ -159,11 +181,11 @@ public class ApiRestController extends CommonRestController {
         @ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = AUTHENTICATION_ERROR_MESSAGE),\r
         @ApiResponse(code = HttpURLConnection.HTTP_FORBIDDEN, message = AUTHORIZATION_ERROR_MESSAGE),\r
         @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = SERVER_ERROR_MESSAGE)})\r
-    public Response\r
-        getHealthCheck(@HeaderParam(REQUEST_ID_NAME) @ApiParam(REQUEST_ID_PARAM_DESCRIPTION) UUID requestId) {\r
-\r
-        updateApiStatisticsCounter(Target.OTHER, Result.SUCCESS, HttpMethod.GET);\r
-        return makeOkResponse(requestId, new HealthCheckProvider().performHealthCheck());\r
+    public ResponseEntity<HealthCheckReport> getHealthCheck(\r
+        @RequestHeader(name = REQUEST_ID_NAME, required = false)\r
+        @ApiParam(REQUEST_ID_PARAM_DESCRIPTION) UUID requestId) {\r
+        updateApiStatisticsCounter(Target.OTHER, HttpStatus.OK, HttpMethod.GET);\r
+        return makeOkResponse(requestId, healthCheckProvider.performHealthCheck());\r
     }\r
 \r
     /**\r
@@ -171,8 +193,7 @@ public class ApiRestController extends CommonRestController {
      *\r
      * @return the Response object containing the results of the API operation\r
      */\r
-    @GET\r
-    @Path("/statistics")\r
+    @GetMapping("/statistics")\r
     @ApiOperation(value = "Retrieve current statistics",\r
         notes = "Returns current statistics including the counters of API invocation",\r
         response = StatisticsReport.class,\r
@@ -196,12 +217,11 @@ public class ApiRestController extends CommonRestController {
         @ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = AUTHENTICATION_ERROR_MESSAGE),\r
         @ApiResponse(code = HttpURLConnection.HTTP_FORBIDDEN, message = AUTHORIZATION_ERROR_MESSAGE),\r
         @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = SERVER_ERROR_MESSAGE)})\r
-    public Response\r
-        getStatistics(@HeaderParam(REQUEST_ID_NAME) @ApiParam(REQUEST_ID_PARAM_DESCRIPTION) UUID requestId) {\r
-\r
-        updateApiStatisticsCounter(Target.OTHER, Result.SUCCESS, HttpMethod.GET);\r
-\r
-        return makeOkResponse(requestId, new StatisticsProvider().fetchCurrentStatistics());\r
+    public ResponseEntity<StatisticsReport> getStatistics(\r
+        @RequestHeader(name = REQUEST_ID_NAME, required = false)\r
+        @ApiParam(REQUEST_ID_PARAM_DESCRIPTION) UUID requestId) {\r
+        updateApiStatisticsCounter(Target.OTHER, HttpStatus.OK, HttpMethod.GET);\r
+        return makeOkResponse(requestId, statisticsProvider.fetchCurrentStatistics());\r
     }\r
 \r
     /**\r
@@ -209,8 +229,7 @@ public class ApiRestController extends CommonRestController {
      *\r
      * @return the Response object containing the results of the API operation\r
      */\r
-    @GET\r
-    @Path("/policytypes")\r
+    @GetMapping("/policytypes")\r
     @ApiOperation(value = "Retrieve existing policy types",\r
         notes = "Returns a list of existing policy types stored in Policy Framework",\r
         response = ToscaServiceTemplate.class,\r
@@ -234,17 +253,18 @@ public class ApiRestController extends CommonRestController {
         @ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = AUTHENTICATION_ERROR_MESSAGE),\r
         @ApiResponse(code = HttpURLConnection.HTTP_FORBIDDEN, message = AUTHORIZATION_ERROR_MESSAGE),\r
         @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = SERVER_ERROR_MESSAGE)})\r
-    public Response\r
-        getAllPolicyTypes(@HeaderParam(REQUEST_ID_NAME) @ApiParam(REQUEST_ID_PARAM_DESCRIPTION) UUID requestId) {\r
-\r
-        try (var policyTypeProvider = new PolicyTypeProvider()) {\r
+    public ResponseEntity<ToscaServiceTemplate> getAllPolicyTypes(\r
+        @RequestHeader(name = REQUEST_ID_NAME, required = false)\r
+        @ApiParam(REQUEST_ID_PARAM_DESCRIPTION) UUID requestId) {\r
+        try {\r
             ToscaServiceTemplate serviceTemplate = policyTypeProvider.fetchPolicyTypes(null, null);\r
-            updateApiStatisticsCounter(Target.POLICY_TYPE, Result.SUCCESS, HttpMethod.GET);\r
+            updateApiStatisticsCounter(Target.POLICY_TYPE, HttpStatus.OK, HttpMethod.GET);\r
             return makeOkResponse(requestId, serviceTemplate);\r
         } catch (PfModelException | PfModelRuntimeException pfme) {\r
-            LOGGER.warn("GET /policytypes", pfme);\r
-            updateApiStatisticsCounter(Target.POLICY_TYPE, Result.FAILURE, HttpMethod.GET);\r
-            return makeErrorResponse(requestId, pfme);\r
+            final var msg = "GET /policytypes";\r
+            updateApiStatisticsCounter(Target.POLICY_TYPE, HttpStatus.resolve(pfme.getErrorResponse().getResponseCode()\r
+                .getStatusCode()), HttpMethod.GET);\r
+            throw new PolicyApiRuntimeException(msg, pfme.getCause(), pfme.getErrorResponse(), requestId);\r
         }\r
     }\r
 \r
@@ -255,8 +275,7 @@ public class ApiRestController extends CommonRestController {
      *\r
      * @return the Response object containing the results of the API operation\r
      */\r
-    @GET\r
-    @Path("/policytypes/{policyTypeId}")\r
+    @GetMapping("/policytypes/{policyTypeId}")\r
     @ApiOperation(value = "Retrieve all available versions of a policy type",\r
         notes = "Returns a list of all available versions for the specified policy type",\r
         response = ToscaServiceTemplate.class,\r
@@ -281,18 +300,19 @@ public class ApiRestController extends CommonRestController {
         @ApiResponse(code = HttpURLConnection.HTTP_FORBIDDEN, message = AUTHORIZATION_ERROR_MESSAGE),\r
         @ApiResponse(code = HttpURLConnection.HTTP_NOT_FOUND, message = NOT_FOUND_MESSAGE),\r
         @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = SERVER_ERROR_MESSAGE)})\r
-    public Response getAllVersionsOfPolicyType(\r
-        @PathParam("policyTypeId") @ApiParam(value = "ID of policy type", required = true) String policyTypeId,\r
-        @HeaderParam(REQUEST_ID_NAME) @ApiParam(REQUEST_ID_PARAM_DESCRIPTION) UUID requestId) {\r
-\r
-        try (var policyTypeProvider = new PolicyTypeProvider()) {\r
+    public ResponseEntity<ToscaServiceTemplate> getAllVersionsOfPolicyType(\r
+        @PathVariable("policyTypeId") @ApiParam(value = "ID of policy type", required = true) String policyTypeId,\r
+        @RequestHeader(name = REQUEST_ID_NAME, required = false)\r
+        @ApiParam(REQUEST_ID_PARAM_DESCRIPTION) UUID requestId) {\r
+        try {\r
             ToscaServiceTemplate serviceTemplate = policyTypeProvider.fetchPolicyTypes(policyTypeId, null);\r
-            updateApiStatisticsCounter(Target.POLICY_TYPE, Result.SUCCESS, HttpMethod.GET);\r
+            updateApiStatisticsCounter(Target.POLICY_TYPE, HttpStatus.OK, HttpMethod.GET);\r
             return makeOkResponse(requestId, serviceTemplate);\r
         } catch (PfModelException | PfModelRuntimeException pfme) {\r
-            LOGGER.warn("GET /policytypes/{}", policyTypeId, pfme);\r
-            updateApiStatisticsCounter(Target.POLICY_TYPE, Result.FAILURE, HttpMethod.GET);\r
-            return makeErrorResponse(requestId, pfme);\r
+            var msg = String.format("GET /policytypes/%s", policyTypeId);\r
+            updateApiStatisticsCounter(Target.POLICY_TYPE, HttpStatus.resolve(pfme.getErrorResponse().getResponseCode()\r
+                .getStatusCode()), HttpMethod.GET);\r
+            throw new PolicyApiRuntimeException(msg, pfme.getCause(), pfme.getErrorResponse(), requestId);\r
         }\r
     }\r
 \r
@@ -304,8 +324,7 @@ public class ApiRestController extends CommonRestController {
      *\r
      * @return the Response object containing the results of the API operation\r
      */\r
-    @GET\r
-    @Path("/policytypes/{policyTypeId}/versions/{versionId}")\r
+    @GetMapping("/policytypes/{policyTypeId}/versions/{versionId}")\r
     @ApiOperation(value = "Retrieve one particular version of a policy type",\r
         notes = "Returns a particular version for the specified policy type", response = ToscaServiceTemplate.class,\r
         responseHeaders = {\r
@@ -329,19 +348,20 @@ public class ApiRestController extends CommonRestController {
         @ApiResponse(code = HttpURLConnection.HTTP_FORBIDDEN, message = AUTHORIZATION_ERROR_MESSAGE),\r
         @ApiResponse(code = HttpURLConnection.HTTP_NOT_FOUND, message = NOT_FOUND_MESSAGE),\r
         @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = SERVER_ERROR_MESSAGE)})\r
-    public Response getSpecificVersionOfPolicyType(\r
-        @PathParam("policyTypeId") @ApiParam(value = "ID of policy type", required = true) String policyTypeId,\r
-        @PathParam("versionId") @ApiParam(value = "Version of policy type", required = true) String versionId,\r
-        @HeaderParam(REQUEST_ID_NAME) @ApiParam(REQUEST_ID_PARAM_DESCRIPTION) UUID requestId) {\r
-\r
-        try (var policyTypeProvider = new PolicyTypeProvider()) {\r
+    public ResponseEntity<ToscaServiceTemplate> getSpecificVersionOfPolicyType(\r
+        @PathVariable("policyTypeId") @ApiParam(value = "ID of policy type", required = true) String policyTypeId,\r
+        @PathVariable("versionId") @ApiParam(value = "Version of policy type", required = true) String versionId,\r
+        @RequestHeader(name = REQUEST_ID_NAME, required = false)\r
+        @ApiParam(REQUEST_ID_PARAM_DESCRIPTION) UUID requestId) {\r
+        try {\r
             ToscaServiceTemplate serviceTemplate = policyTypeProvider.fetchPolicyTypes(policyTypeId, versionId);\r
-            updateApiStatisticsCounter(Target.POLICY_TYPE, Result.SUCCESS, HttpMethod.GET);\r
+            updateApiStatisticsCounter(Target.POLICY_TYPE, HttpStatus.OK, HttpMethod.GET);\r
             return makeOkResponse(requestId, serviceTemplate);\r
         } catch (PfModelException | PfModelRuntimeException pfme) {\r
-            LOGGER.warn("GET /policytypes/{}/versions/{}", policyTypeId, versionId, pfme);\r
-            updateApiStatisticsCounter(Target.POLICY_TYPE, Result.FAILURE, HttpMethod.GET);\r
-            return makeErrorResponse(requestId, pfme);\r
+            var msg = String.format("GET /policytypes/%s/versions/%s", policyTypeId, versionId);\r
+            updateApiStatisticsCounter(Target.POLICY_TYPE, HttpStatus.resolve(pfme.getErrorResponse().getResponseCode()\r
+                .getStatusCode()), HttpMethod.GET);\r
+            throw new PolicyApiRuntimeException(msg, pfme.getCause(), pfme.getErrorResponse(), requestId);\r
         }\r
     }\r
 \r
@@ -352,8 +372,7 @@ public class ApiRestController extends CommonRestController {
      *\r
      * @return the Response object containing the results of the API operation\r
      */\r
-    @GET\r
-    @Path("/policytypes/{policyTypeId}/versions/latest")\r
+    @GetMapping("/policytypes/{policyTypeId}/versions/latest")\r
     @ApiOperation(value = "Retrieve latest version of a policy type",\r
         notes = "Returns latest version for the specified policy type", response = ToscaServiceTemplate.class,\r
         responseHeaders = {\r
@@ -377,18 +396,19 @@ public class ApiRestController extends CommonRestController {
         @ApiResponse(code = HttpURLConnection.HTTP_FORBIDDEN, message = AUTHORIZATION_ERROR_MESSAGE),\r
         @ApiResponse(code = HttpURLConnection.HTTP_NOT_FOUND, message = NOT_FOUND_MESSAGE),\r
         @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = SERVER_ERROR_MESSAGE)})\r
-    public Response getLatestVersionOfPolicyType(\r
-        @PathParam("policyTypeId") @ApiParam(value = "ID of policy type", required = true) String policyTypeId,\r
-        @HeaderParam(REQUEST_ID_NAME) @ApiParam(REQUEST_ID_PARAM_DESCRIPTION) UUID requestId) {\r
-\r
-        try (var policyTypeProvider = new PolicyTypeProvider()) {\r
+    public ResponseEntity<ToscaServiceTemplate> getLatestVersionOfPolicyType(\r
+        @PathVariable("policyTypeId") @ApiParam(value = "ID of policy type", required = true) String policyTypeId,\r
+        @RequestHeader(name = REQUEST_ID_NAME, required = false)\r
+        @ApiParam(REQUEST_ID_PARAM_DESCRIPTION) UUID requestId) {\r
+        try {\r
             ToscaServiceTemplate serviceTemplate = policyTypeProvider.fetchLatestPolicyTypes(policyTypeId);\r
-            updateApiStatisticsCounter(Target.POLICY_TYPE, Result.SUCCESS, HttpMethod.GET);\r
+            updateApiStatisticsCounter(Target.POLICY_TYPE, HttpStatus.OK, HttpMethod.GET);\r
             return makeOkResponse(requestId, serviceTemplate);\r
         } catch (PfModelException | PfModelRuntimeException pfme) {\r
-            LOGGER.warn("GET /policytypes/{}/versions/latest", policyTypeId, pfme);\r
-            updateApiStatisticsCounter(Target.POLICY_TYPE, Result.FAILURE, HttpMethod.GET);\r
-            return makeErrorResponse(requestId, pfme);\r
+            var msg = String.format("GET /policytypes/%s/versions/latest", policyTypeId);\r
+            updateApiStatisticsCounter(Target.POLICY_TYPE, HttpStatus.resolve(pfme.getErrorResponse().getResponseCode()\r
+                .getStatusCode()), HttpMethod.GET);\r
+            throw new PolicyApiRuntimeException(msg, pfme.getCause(), pfme.getErrorResponse(), requestId);\r
         }\r
     }\r
 \r
@@ -399,8 +419,7 @@ public class ApiRestController extends CommonRestController {
      *\r
      * @return the Response object containing the results of the API operation\r
      */\r
-    @POST\r
-    @Path("/policytypes")\r
+    @PostMapping("/policytypes")\r
     @ApiOperation(value = "Create a new policy type", notes = "Client should provide TOSCA body of the new policy type",\r
         authorizations = @Authorization(value = AUTHORIZATION_TYPE), tags = {"PolicyType", },\r
         response = ToscaServiceTemplate.class,\r
@@ -425,22 +444,22 @@ public class ApiRestController extends CommonRestController {
         @ApiResponse(code = HttpURLConnection.HTTP_FORBIDDEN, message = AUTHORIZATION_ERROR_MESSAGE),\r
         @ApiResponse(code = HttpURLConnection.HTTP_NOT_ACCEPTABLE, message = INVALID_PAYLOAD_MESSAGE),\r
         @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = SERVER_ERROR_MESSAGE)})\r
-    public Response createPolicyType(\r
-        @ApiParam(value = "Entity body of policy type", required = true) ToscaServiceTemplate body,\r
-        @HeaderParam(REQUEST_ID_NAME) @ApiParam(REQUEST_ID_PARAM_DESCRIPTION) UUID requestId) {\r
-\r
+    public ResponseEntity<ToscaServiceTemplate> createPolicyType(\r
+        @RequestBody @ApiParam(value = "Entity body of policy type", required = true) ToscaServiceTemplate body,\r
+        @RequestHeader(name = REQUEST_ID_NAME, required = false)\r
+        @ApiParam(REQUEST_ID_PARAM_DESCRIPTION) UUID requestId) {\r
         if (NetLoggerUtil.getNetworkLogger().isInfoEnabled()) {\r
             NetLoggerUtil.log(EventType.IN, CommInfrastructure.REST, "/policytypes", toJson(body));\r
         }\r
-\r
-        try (var policyTypeProvider = new PolicyTypeProvider()) {\r
+        try {\r
             ToscaServiceTemplate serviceTemplate = policyTypeProvider.createPolicyType(body);\r
-            updateApiStatisticsCounter(Target.POLICY_TYPE, Result.SUCCESS, HttpMethod.POST);\r
+            updateApiStatisticsCounter(Target.POLICY_TYPE, HttpStatus.OK, HttpMethod.POST);\r
             return makeOkResponse(requestId, serviceTemplate);\r
         } catch (PfModelException | PfModelRuntimeException pfme) {\r
-            LOGGER.warn("POST /policytypes", pfme);\r
-            updateApiStatisticsCounter(Target.POLICY_TYPE, Result.FAILURE, HttpMethod.POST);\r
-            return makeErrorResponse(requestId, pfme);\r
+            final var msg = "POST /policytypes";\r
+            updateApiStatisticsCounter(Target.POLICY_TYPE, HttpStatus.resolve(pfme.getErrorResponse().getResponseCode()\r
+                .getStatusCode()), HttpMethod.POST);\r
+            throw new PolicyApiRuntimeException(msg, pfme.getCause(), pfme.getErrorResponse(), requestId);\r
         }\r
     }\r
 \r
@@ -452,8 +471,7 @@ public class ApiRestController extends CommonRestController {
      *\r
      * @return the Response object containing the results of the API operation\r
      */\r
-    @DELETE\r
-    @Path("/policytypes/{policyTypeId}/versions/{versionId}")\r
+    @DeleteMapping("/policytypes/{policyTypeId}/versions/{versionId}")\r
     @ApiOperation(value = "Delete one version of a policy type",\r
         notes = "Rule 1: pre-defined policy types cannot be deleted;"\r
             + "Rule 2: policy types that are in use (parameterized by a TOSCA policy) cannot be deleted."\r
@@ -481,19 +499,20 @@ public class ApiRestController extends CommonRestController {
         @ApiResponse(code = HttpURLConnection.HTTP_NOT_FOUND, message = NOT_FOUND_MESSAGE),\r
         @ApiResponse(code = HttpURLConnection.HTTP_CONFLICT, message = HTTP_CONFLICT_MESSAGE),\r
         @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = SERVER_ERROR_MESSAGE)})\r
-    public Response deleteSpecificVersionOfPolicyType(\r
-        @PathParam("policyTypeId") @ApiParam(value = "ID of policy type", required = true) String policyTypeId,\r
-        @PathParam("versionId") @ApiParam(value = "Version of policy type", required = true) String versionId,\r
-        @HeaderParam(REQUEST_ID_NAME) @ApiParam(REQUEST_ID_PARAM_DESCRIPTION) UUID requestId) {\r
-\r
-        try (var policyTypeProvider = new PolicyTypeProvider()) {\r
+    public ResponseEntity<ToscaServiceTemplate> deleteSpecificVersionOfPolicyType(\r
+        @PathVariable("policyTypeId") @ApiParam(value = "ID of policy type", required = true) String policyTypeId,\r
+        @PathVariable("versionId") @ApiParam(value = "Version of policy type", required = true) String versionId,\r
+        @RequestHeader(name = REQUEST_ID_NAME, required = false)\r
+        @ApiParam(REQUEST_ID_PARAM_DESCRIPTION) UUID requestId) {\r
+        try {\r
             ToscaServiceTemplate serviceTemplate = policyTypeProvider.deletePolicyType(policyTypeId, versionId);\r
-            updateApiStatisticsCounter(Target.POLICY_TYPE, Result.SUCCESS, HttpMethod.DELETE);\r
+            updateApiStatisticsCounter(Target.POLICY_TYPE, HttpStatus.OK, HttpMethod.DELETE);\r
             return makeOkResponse(requestId, serviceTemplate);\r
         } catch (PfModelException | PfModelRuntimeException pfme) {\r
-            LOGGER.warn("DELETE /policytypes/{}/versions/{}", policyTypeId, versionId, pfme);\r
-            updateApiStatisticsCounter(Target.POLICY_TYPE, Result.FAILURE, HttpMethod.DELETE);\r
-            return makeErrorResponse(requestId, pfme);\r
+            var msg = String.format("DELETE /policytypes/%s/versions/%s", policyTypeId, versionId);\r
+            updateApiStatisticsCounter(Target.POLICY_TYPE, HttpStatus.resolve(pfme.getErrorResponse().getResponseCode()\r
+                .getStatusCode()), HttpMethod.DELETE);\r
+            throw new PolicyApiRuntimeException(msg, pfme.getCause(), pfme.getErrorResponse(), requestId);\r
         }\r
     }\r
 \r
@@ -505,8 +524,7 @@ public class ApiRestController extends CommonRestController {
      *\r
      * @return the Response object containing the results of the API operation\r
      */\r
-    @GET\r
-    @Path("/policytypes/{policyTypeId}/versions/{policyTypeVersion}/policies")\r
+    @GetMapping("/policytypes/{policyTypeId}/versions/{policyTypeVersion}/policies")\r
     @ApiOperation(\r
         value = "Retrieve all versions of a policy created for a particular policy type version",\r
         notes = "Returns a list of all versions of specified policy created for the specified policy type version",\r
@@ -536,24 +554,24 @@ public class ApiRestController extends CommonRestController {
         @ApiResponse(code = HttpURLConnection.HTTP_NOT_FOUND, message = NOT_FOUND_MESSAGE),\r
         @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = SERVER_ERROR_MESSAGE)\r
     })\r
-    public Response getAllPolicies(\r
-        @PathParam("policyTypeId") @ApiParam(value = "ID of policy type", required = true) String policyTypeId,\r
-        @PathParam("policyTypeVersion") @ApiParam(value = "Version of policy type",\r
+    public ResponseEntity<ToscaServiceTemplate> getAllPolicies(\r
+        @PathVariable("policyTypeId") @ApiParam(value = "ID of policy type", required = true) String policyTypeId,\r
+        @PathVariable("policyTypeVersion") @ApiParam(value = "Version of policy type",\r
             required = true) String policyTypeVersion,\r
-        @HeaderParam(REQUEST_ID_NAME) @ApiParam(REQUEST_ID_PARAM_DESCRIPTION) UUID requestId,\r
-        @QueryParam("mode") @DefaultValue("bare") @ApiParam("Fetch mode for policies, BARE for bare policies (default),"\r
-            + " REFERENCED for fully referenced policies") PolicyFetchMode mode\r
-    ) {\r
-\r
-        try (var policyProvider = new PolicyProvider()) {\r
+        @RequestHeader(name = REQUEST_ID_NAME, required = false)\r
+        @ApiParam(REQUEST_ID_PARAM_DESCRIPTION) UUID requestId,\r
+        @RequestParam(name = "mode", defaultValue = "bare") @ApiParam("Fetch mode for policies, BARE for bare"\r
+            + " policies (default), REFERENCED for fully referenced policies") PolicyFetchMode mode) {\r
+        try {\r
             ToscaServiceTemplate serviceTemplate =\r
                 policyProvider.fetchPolicies(policyTypeId, policyTypeVersion, null, null, mode);\r
-            updateApiStatisticsCounter(Target.POLICY, Result.SUCCESS, HttpMethod.GET);\r
+            updateApiStatisticsCounter(Target.POLICY, HttpStatus.OK, HttpMethod.GET);\r
             return makeOkResponse(requestId, serviceTemplate);\r
         } catch (PfModelException | PfModelRuntimeException pfme) {\r
-            LOGGER.warn("GET /policytypes/{}/versions/{}/policies", policyTypeId, policyTypeVersion, pfme);\r
-            updateApiStatisticsCounter(Target.POLICY, Result.FAILURE, HttpMethod.GET);\r
-            return makeErrorResponse(requestId, pfme);\r
+            var msg = String.format("GET /policytypes/%s/versions/%s/policies", policyTypeId, policyTypeVersion);\r
+            updateApiStatisticsCounter(Target.POLICY, HttpStatus.resolve(pfme.getErrorResponse().getResponseCode()\r
+                .getStatusCode()), HttpMethod.GET);\r
+            throw new PolicyApiRuntimeException(msg, pfme.getCause(), pfme.getErrorResponse(), requestId);\r
         }\r
     }\r
 \r
@@ -566,8 +584,7 @@ public class ApiRestController extends CommonRestController {
      *\r
      * @return the Response object containing the results of the API operation\r
      */\r
-    @GET\r
-    @Path("/policytypes/{policyTypeId}/versions/{policyTypeVersion}/policies/{policyId}")\r
+    @GetMapping("/policytypes/{policyTypeId}/versions/{policyTypeVersion}/policies/{policyId}")\r
     @ApiOperation(value = "Retrieve all version details of a policy created for a particular policy type version",\r
         notes = "Returns a list of all version details of the specified policy", response = ToscaServiceTemplate.class,\r
         responseHeaders = {\r
@@ -595,24 +612,26 @@ public class ApiRestController extends CommonRestController {
         @ApiResponse(code = HttpURLConnection.HTTP_NOT_FOUND, message = NOT_FOUND_MESSAGE),\r
         @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = SERVER_ERROR_MESSAGE)\r
     })\r
-    public Response getAllVersionsOfPolicy(\r
-        @PathParam("policyTypeId") @ApiParam(value = "ID of policy type", required = true) String policyTypeId,\r
-        @PathParam("policyTypeVersion") @ApiParam(value = "Version of policy type",\r
+    public ResponseEntity<ToscaServiceTemplate> getAllVersionsOfPolicy(\r
+        @PathVariable("policyTypeId") @ApiParam(value = "ID of policy type", required = true) String policyTypeId,\r
+        @PathVariable("policyTypeVersion") @ApiParam(value = "Version of policy type",\r
             required = true) String policyTypeVersion,\r
-        @PathParam("policyId") @ApiParam(value = "ID of policy", required = true) String policyId,\r
-        @HeaderParam(REQUEST_ID_NAME) @ApiParam(REQUEST_ID_PARAM_DESCRIPTION) UUID requestId,\r
-        @QueryParam("mode") @DefaultValue("bare") @ApiParam("Fetch mode for policies, BARE for bare policies (default),"\r
-            + " REFERENCED for fully referenced policies") PolicyFetchMode mode\r
-    ) {\r
-        try (var policyProvider = new PolicyProvider()) {\r
+        @PathVariable("policyId") @ApiParam(value = "ID of policy", required = true) String policyId,\r
+        @RequestHeader(name = REQUEST_ID_NAME, required = false) @ApiParam(REQUEST_ID_PARAM_DESCRIPTION) UUID requestId,\r
+        @RequestParam(name = "mode", defaultValue = "bare")\r
+        @ApiParam("Fetch mode for policies, BARE for bare policies (default),"\r
+            + " REFERENCED for fully referenced policies") PolicyFetchMode mode) {\r
+        try {\r
             ToscaServiceTemplate serviceTemplate =\r
                 policyProvider.fetchPolicies(policyTypeId, policyTypeVersion, policyId, null, mode);\r
-            updateApiStatisticsCounter(Target.POLICY, Result.SUCCESS, HttpMethod.GET);\r
+            updateApiStatisticsCounter(Target.POLICY, HttpStatus.OK, HttpMethod.GET);\r
             return makeOkResponse(requestId, serviceTemplate);\r
         } catch (PfModelException | PfModelRuntimeException pfme) {\r
-            LOGGER.warn("/policytypes/{}/versions/{}/policies/{}", policyTypeId, policyTypeVersion, policyId, pfme);\r
-            updateApiStatisticsCounter(Target.POLICY, Result.FAILURE, HttpMethod.GET);\r
-            return makeErrorResponse(requestId, pfme);\r
+            var msg = String.format("/policytypes/%s/versions/$s/policies/%s",\r
+                policyTypeId, policyTypeVersion, policyId);\r
+            updateApiStatisticsCounter(Target.POLICY, HttpStatus.resolve(pfme.getErrorResponse().getResponseCode()\r
+                .getStatusCode()), HttpMethod.GET);\r
+            throw new PolicyApiRuntimeException(msg, pfme.getCause(), pfme.getErrorResponse(), requestId);\r
         }\r
     }\r
 \r
@@ -626,8 +645,7 @@ public class ApiRestController extends CommonRestController {
      *\r
      * @return the Response object containing the results of the API operation\r
      */\r
-    @GET\r
-    @Path("/policytypes/{policyTypeId}/versions/{policyTypeVersion}/policies/{policyId}/versions/{policyVersion}")\r
+    @GetMapping("/policytypes/{policyTypeId}/versions/{policyTypeVersion}/policies/{policyId}/versions/{policyVersion}")\r
     @ApiOperation(value = "Retrieve one version of a policy created for a particular policy type version",\r
         notes = "Returns a particular version of specified policy created for the specified policy type version",\r
         response = ToscaServiceTemplate.class,\r
@@ -656,26 +674,27 @@ public class ApiRestController extends CommonRestController {
         @ApiResponse(code = HttpURLConnection.HTTP_NOT_FOUND, message = NOT_FOUND_MESSAGE),\r
         @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = SERVER_ERROR_MESSAGE)\r
     })\r
-    public Response getSpecificVersionOfPolicy(\r
-        @PathParam("policyTypeId") @ApiParam(value = "ID of policy type", required = true) String policyTypeId,\r
-        @PathParam("policyTypeVersion") @ApiParam(value = "Version of policy type",\r
+    public ResponseEntity<ToscaServiceTemplate> getSpecificVersionOfPolicy(\r
+        @PathVariable("policyTypeId") @ApiParam(value = "ID of policy type", required = true) String policyTypeId,\r
+        @PathVariable("policyTypeVersion") @ApiParam(value = "Version of policy type",\r
             required = true) String policyTypeVersion,\r
-        @PathParam("policyId") @ApiParam(value = "ID of policy", required = true) String policyId,\r
-        @PathParam("policyVersion") @ApiParam(value = "Version of policy", required = true) String policyVersion,\r
-        @HeaderParam(REQUEST_ID_NAME) @ApiParam(REQUEST_ID_PARAM_DESCRIPTION) UUID requestId,\r
-        @QueryParam("mode") @DefaultValue("bare") @ApiParam("Fetch mode for policies, BARE for bare policies (default),"\r
-            + " REFERENCED for fully referenced policies") PolicyFetchMode mode\r
-    ) {\r
-        try (var policyProvider = new PolicyProvider()) {\r
+        @PathVariable("policyId") @ApiParam(value = "ID of policy", required = true) String policyId,\r
+        @PathVariable("policyVersion") @ApiParam(value = "Version of policy", required = true) String policyVersion,\r
+        @RequestHeader(name = REQUEST_ID_NAME, required = false)\r
+        @ApiParam(REQUEST_ID_PARAM_DESCRIPTION) UUID requestId,\r
+        @RequestParam(name = "mode", defaultValue = "bare") @ApiParam("Fetch mode for policies, BARE for bare policies"\r
+            + "  (default), REFERENCED for fully referenced policies") PolicyFetchMode mode) {\r
+        try {\r
             ToscaServiceTemplate serviceTemplate =\r
                 policyProvider.fetchPolicies(policyTypeId, policyTypeVersion, policyId, policyVersion, mode);\r
-            updateApiStatisticsCounter(Target.POLICY, Result.SUCCESS, HttpMethod.GET);\r
+            updateApiStatisticsCounter(Target.POLICY, HttpStatus.OK, HttpMethod.GET);\r
             return makeOkResponse(requestId, serviceTemplate);\r
         } catch (PfModelException | PfModelRuntimeException pfme) {\r
-            LOGGER.warn("GET /policytypes/{}/versions/{}/policies/{}/versions/{}", policyTypeId, policyTypeVersion,\r
-                policyId, policyVersion, pfme);\r
-            updateApiStatisticsCounter(Target.POLICY, Result.FAILURE, HttpMethod.GET);\r
-            return makeErrorResponse(requestId, pfme);\r
+            var msg = String.format("GET /policytypes/%s/versions/%s/policies/%s/versions/%s",\r
+                policyTypeId, policyTypeVersion, policyId, policyVersion);\r
+            updateApiStatisticsCounter(Target.POLICY, HttpStatus.resolve(pfme.getErrorResponse().getResponseCode()\r
+                .getStatusCode()), HttpMethod.GET);\r
+            throw new PolicyApiRuntimeException(msg, pfme.getCause(), pfme.getErrorResponse(), requestId);\r
         }\r
     }\r
 \r
@@ -688,8 +707,7 @@ public class ApiRestController extends CommonRestController {
      *\r
      * @return the Response object containing the results of the API operation\r
      */\r
-    @GET\r
-    @Path("/policytypes/{policyTypeId}/versions/{policyTypeVersion}/policies/{policyId}/versions/latest")\r
+    @GetMapping("/policytypes/{policyTypeId}/versions/{policyTypeVersion}/policies/{policyId}/versions/latest")\r
     @ApiOperation(value = "Retrieve the latest version of a particular policy",\r
         notes = "Returns the latest version of specified policy", response = ToscaServiceTemplate.class,\r
         responseHeaders = {\r
@@ -713,25 +731,26 @@ public class ApiRestController extends CommonRestController {
         @ApiResponse(code = HttpURLConnection.HTTP_FORBIDDEN, message = AUTHORIZATION_ERROR_MESSAGE),\r
         @ApiResponse(code = HttpURLConnection.HTTP_NOT_FOUND, message = NOT_FOUND_MESSAGE),\r
         @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = SERVER_ERROR_MESSAGE)})\r
-    public Response getLatestVersionOfPolicy(\r
-        @PathParam("policyTypeId") @ApiParam(value = "ID of policy type", required = true) String policyTypeId,\r
-        @PathParam("policyTypeVersion") @ApiParam(value = "Version of policy type",\r
+    public ResponseEntity<ToscaServiceTemplate> getLatestVersionOfPolicy(\r
+        @PathVariable("policyTypeId") @ApiParam(value = "ID of policy type", required = true) String policyTypeId,\r
+        @PathVariable("policyTypeVersion") @ApiParam(value = "Version of policy type",\r
             required = true) String policyTypeVersion,\r
-        @PathParam("policyId") @ApiParam(value = "ID of policy", required = true) String policyId,\r
-        @HeaderParam(REQUEST_ID_NAME) @ApiParam(REQUEST_ID_PARAM_DESCRIPTION) UUID requestId,\r
-        @QueryParam("mode") @ApiParam("Fetch mode for policies, TERSE for bare policies (default), "\r
-            + "REFERENCED for fully referenced policies") PolicyFetchMode mode) {\r
-\r
-        try (var policyProvider = new PolicyProvider()) {\r
+        @PathVariable("policyId") @ApiParam(value = "ID of policy", required = true) String policyId,\r
+        @RequestHeader(name = REQUEST_ID_NAME, required = false)\r
+        @ApiParam(REQUEST_ID_PARAM_DESCRIPTION) UUID requestId,\r
+        @RequestParam(name = "mode", defaultValue = "bare") @ApiParam("Fetch mode for policies, TERSE for bare "\r
+            + "policies (default), REFERENCED for fully referenced policies") PolicyFetchMode mode) {\r
+        try {\r
             ToscaServiceTemplate serviceTemplate =\r
                 policyProvider.fetchLatestPolicies(policyTypeId, policyTypeVersion, policyId, mode);\r
-            updateApiStatisticsCounter(Target.POLICY, Result.SUCCESS, HttpMethod.GET);\r
+            updateApiStatisticsCounter(Target.POLICY, HttpStatus.OK, HttpMethod.GET);\r
             return makeOkResponse(requestId, serviceTemplate);\r
         } catch (PfModelException | PfModelRuntimeException pfme) {\r
-            LOGGER.warn("GET /policytypes/{}/versions/{}/policies/{}/versions/latest", policyTypeId, policyTypeVersion,\r
-                policyId, pfme);\r
-            updateApiStatisticsCounter(Target.POLICY, Result.FAILURE, HttpMethod.GET);\r
-            return makeErrorResponse(requestId, pfme);\r
+            var msg = String.format("GET /policytypes/%s/versions/%s/policies/%s/versions/latest",\r
+                policyTypeId, policyTypeVersion, policyId);\r
+            updateApiStatisticsCounter(Target.POLICY, HttpStatus.resolve(pfme.getErrorResponse().getResponseCode()\r
+                .getStatusCode()), HttpMethod.GET);\r
+            throw new PolicyApiRuntimeException(msg, pfme.getCause(), pfme.getErrorResponse(), requestId);\r
         }\r
     }\r
 \r
@@ -744,8 +763,7 @@ public class ApiRestController extends CommonRestController {
      *\r
      * @return the Response object containing the results of the API operation\r
      */\r
-    @POST\r
-    @Path("/policytypes/{policyTypeId}/versions/{policyTypeVersion}/policies")\r
+    @PostMapping("/policytypes/{policyTypeId}/versions/{policyTypeVersion}/policies")\r
     @ApiOperation(value = "Create a new policy for a policy type version",\r
         notes = "Client should provide TOSCA body of the new policy",\r
         authorizations = @Authorization(value = AUTHORIZATION_TYPE), tags = {"Policy", },\r
@@ -772,26 +790,26 @@ public class ApiRestController extends CommonRestController {
         @ApiResponse(code = HttpURLConnection.HTTP_NOT_FOUND, message = NOT_FOUND_MESSAGE),\r
         @ApiResponse(code = HttpURLConnection.HTTP_NOT_ACCEPTABLE, message = INVALID_PAYLOAD_MESSAGE),\r
         @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = SERVER_ERROR_MESSAGE)})\r
-    public Response createPolicy(\r
-        @PathParam("policyTypeId") @ApiParam(value = "ID of policy type", required = true) String policyTypeId,\r
-        @PathParam("policyTypeVersion") @ApiParam(value = "Version of policy type",\r
+    public ResponseEntity<ToscaServiceTemplate> createPolicy(\r
+        @PathVariable("policyTypeId") @ApiParam(value = "ID of policy type", required = true) String policyTypeId,\r
+        @PathVariable("policyTypeVersion") @ApiParam(value = "Version of policy type",\r
             required = true) String policyTypeVersion,\r
-        @HeaderParam(REQUEST_ID_NAME) @ApiParam(REQUEST_ID_PARAM_DESCRIPTION) UUID requestId,\r
-        @ApiParam(value = "Entity body of policy", required = true) ToscaServiceTemplate body) {\r
-\r
+        @RequestHeader(name = REQUEST_ID_NAME, required = false)\r
+        @ApiParam(REQUEST_ID_PARAM_DESCRIPTION) UUID requestId,\r
+        @RequestBody @ApiParam(value = "Entity body of policy", required = true) ToscaServiceTemplate body) {\r
         if (NetLoggerUtil.getNetworkLogger().isInfoEnabled()) {\r
             NetLoggerUtil.log(EventType.IN, CommInfrastructure.REST,\r
                 "/policytypes/" + policyTypeId + "/versions/" + policyTypeVersion + "/policies", toJson(body));\r
         }\r
-\r
-        try (var policyProvider = new PolicyProvider()) {\r
+        try {\r
             ToscaServiceTemplate serviceTemplate = policyProvider.createPolicy(policyTypeId, policyTypeVersion, body);\r
-            updateApiStatisticsCounter(Target.POLICY, Result.SUCCESS, HttpMethod.POST);\r
+            updateApiStatisticsCounter(Target.POLICY, HttpStatus.OK, HttpMethod.POST);\r
             return makeOkResponse(requestId, serviceTemplate);\r
         } catch (PfModelException | PfModelRuntimeException pfme) {\r
-            LOGGER.warn("POST /policytypes/{}/versions/{}/policies", policyTypeId, policyTypeVersion, pfme);\r
-            updateApiStatisticsCounter(Target.POLICY, Result.FAILURE, HttpMethod.POST);\r
-            return makeErrorResponse(requestId, pfme);\r
+            var msg = String.format("POST /policytypes/%s/versions/%s/policies", policyTypeId, policyTypeVersion);\r
+            updateApiStatisticsCounter(Target.POLICY, HttpStatus.resolve(pfme.getErrorResponse().getResponseCode()\r
+                .getStatusCode()), HttpMethod.POST);\r
+            throw new PolicyApiRuntimeException(msg, pfme.getCause(), pfme.getErrorResponse(), requestId);\r
         }\r
     }\r
 \r
@@ -805,8 +823,8 @@ public class ApiRestController extends CommonRestController {
      *\r
      * @return the Response object containing the results of the API operation\r
      */\r
-    @DELETE\r
-    @Path("/policytypes/{policyTypeId}/versions/{policyTypeVersion}/policies/{policyId}/versions/{policyVersion}")\r
+    @DeleteMapping("/policytypes/{policyTypeId}/versions/{policyTypeVersion}/policies/{policyId}/"\r
+        + "versions/{policyVersion}")\r
     @ApiOperation(value = "Delete a particular version of a policy",\r
         notes = "Rule: the version that has been deployed in PDP group(s) cannot be deleted",\r
         authorizations = @Authorization(value = AUTHORIZATION_TYPE), tags = {"Policy", },\r
@@ -832,24 +850,25 @@ public class ApiRestController extends CommonRestController {
         @ApiResponse(code = HttpURLConnection.HTTP_NOT_FOUND, message = NOT_FOUND_MESSAGE),\r
         @ApiResponse(code = HttpURLConnection.HTTP_CONFLICT, message = HTTP_CONFLICT_MESSAGE),\r
         @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = SERVER_ERROR_MESSAGE)})\r
-    public Response deleteSpecificVersionOfPolicy(\r
-        @PathParam("policyTypeId") @ApiParam(value = "PolicyType ID", required = true) String policyTypeId,\r
-        @PathParam("policyTypeVersion") @ApiParam(value = "Version of policy type",\r
+    public ResponseEntity<ToscaServiceTemplate> deleteSpecificVersionOfPolicy(\r
+        @PathVariable("policyTypeId") @ApiParam(value = "PolicyType ID", required = true) String policyTypeId,\r
+        @PathVariable("policyTypeVersion") @ApiParam(value = "Version of policy type",\r
             required = true) String policyTypeVersion,\r
-        @PathParam("policyId") @ApiParam(value = "ID of policy", required = true) String policyId,\r
-        @PathParam("policyVersion") @ApiParam(value = "Version of policy", required = true) String policyVersion,\r
-        @HeaderParam(REQUEST_ID_NAME) @ApiParam(REQUEST_ID_PARAM_DESCRIPTION) UUID requestId) {\r
-\r
-        try (var policyProvider = new PolicyProvider()) {\r
+        @PathVariable("policyId") @ApiParam(value = "ID of policy", required = true) String policyId,\r
+        @PathVariable("policyVersion") @ApiParam(value = "Version of policy", required = true) String policyVersion,\r
+        @RequestHeader(name = REQUEST_ID_NAME, required = false)\r
+        @ApiParam(REQUEST_ID_PARAM_DESCRIPTION) UUID requestId) {\r
+        try {\r
             ToscaServiceTemplate serviceTemplate =\r
                 policyProvider.deletePolicy(policyTypeId, policyTypeVersion, policyId, policyVersion);\r
-            updateApiStatisticsCounter(Target.POLICY, Result.SUCCESS, HttpMethod.DELETE);\r
+            updateApiStatisticsCounter(Target.POLICY, HttpStatus.OK, HttpMethod.DELETE);\r
             return makeOkResponse(requestId, serviceTemplate);\r
         } catch (PfModelException | PfModelRuntimeException pfme) {\r
-            LOGGER.warn("DELETE /policytypes/{}/versions/{}/policies/{}/versions/{}", policyTypeId, policyTypeVersion,\r
-                policyId, policyVersion, pfme);\r
-            updateApiStatisticsCounter(Target.POLICY, Result.FAILURE, HttpMethod.DELETE);\r
-            return makeErrorResponse(requestId, pfme);\r
+            var msg = String.format("DELETE /policytypes/%s/versions/%s/policies/%s/versions/%s",\r
+                policyTypeId, policyTypeVersion, policyId, policyVersion);\r
+            updateApiStatisticsCounter(Target.POLICY, HttpStatus.resolve(pfme.getErrorResponse().getResponseCode()\r
+                .getStatusCode()), HttpMethod.DELETE);\r
+            throw new PolicyApiRuntimeException(msg, pfme.getCause(), pfme.getErrorResponse(), requestId);\r
         }\r
     }\r
 \r
@@ -858,8 +877,7 @@ public class ApiRestController extends CommonRestController {
      *\r
      * @return the Response object containing the results of the API operation\r
      */\r
-    @GET\r
-    @Path("/policies")\r
+    @GetMapping("/policies")\r
     @ApiOperation(value = "Retrieve all versions of available policies",\r
         notes = "Returns all version of available policies",\r
         response = ToscaServiceTemplate.class,\r
@@ -888,24 +906,25 @@ public class ApiRestController extends CommonRestController {
         @ApiResponse(code = HttpURLConnection.HTTP_NOT_FOUND, message = NOT_FOUND_MESSAGE),\r
         @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = SERVER_ERROR_MESSAGE)\r
     })\r
-    public Response getPolicies(\r
-        @HeaderParam(REQUEST_ID_NAME) @ApiParam(REQUEST_ID_PARAM_DESCRIPTION) UUID requestId,\r
-        @QueryParam("mode") @DefaultValue("bare") @ApiParam("Fetch mode for policies, BARE for bare policies (default),"\r
-            + " REFERENCED for fully referenced policies") PolicyFetchMode mode\r
-    ) {\r
-        try (var policyProvider = new PolicyProvider()) {\r
+    public ResponseEntity<ToscaServiceTemplate> getPolicies(\r
+        @RequestHeader(name = REQUEST_ID_NAME, required = false)\r
+        @ApiParam(REQUEST_ID_PARAM_DESCRIPTION) UUID requestId,\r
+        @RequestParam(name = "mode", defaultValue = "bare") @ApiParam("Fetch mode for policies, BARE for bare"\r
+            + "  policies (default), REFERENCED for fully referenced policies") PolicyFetchMode mode) {\r
+        try {\r
             ToscaServiceTemplate serviceTemplate =\r
                 policyProvider.fetchPolicies(null, null, null, null, mode);\r
-            updateApiStatisticsCounter(Target.POLICY, Result.SUCCESS, HttpMethod.GET);\r
+            updateApiStatisticsCounter(Target.POLICY, HttpStatus.OK, HttpMethod.GET);\r
             return makeOkResponse(requestId, serviceTemplate);\r
         } catch (PfModelException | PfModelRuntimeException pfme) {\r
-            LOGGER.warn("GET /policies/ --", pfme);\r
-            updateApiStatisticsCounter(Target.POLICY, Result.FAILURE, HttpMethod.GET);\r
+            final var msg = "GET /policies/ --";\r
+            updateApiStatisticsCounter(Target.POLICY, HttpStatus.resolve(pfme.getErrorResponse().getResponseCode()\r
+                .getStatusCode()), HttpMethod.GET);\r
             if (pfme.getErrorResponse().getResponseCode().equals(Status.NOT_FOUND)) {\r
                 pfme.getErrorResponse().setErrorMessage(ERROR_MESSAGE_NO_POLICIES_FOUND);\r
                 pfme.getErrorResponse().setErrorDetails(List.of(ERROR_MESSAGE_NO_POLICIES_FOUND));\r
             }\r
-            return makeErrorResponse(requestId, pfme);\r
+            throw new PolicyApiRuntimeException(msg, pfme.getCause(), pfme.getErrorResponse(), requestId);\r
         }\r
     }\r
 \r
@@ -917,8 +936,7 @@ public class ApiRestController extends CommonRestController {
      *\r
      * @return the Response object containing the results of the API operation\r
      */\r
-    @GET\r
-    @Path("/policies/{policyId}/versions/{policyVersion}")\r
+    @GetMapping("/policies/{policyId}/versions/{policyVersion}")\r
     @ApiOperation(value = "Retrieve specific version of a specified policy",\r
         notes = "Returns a particular version of specified policy",\r
         response = ToscaServiceTemplate.class,\r
@@ -947,22 +965,23 @@ public class ApiRestController extends CommonRestController {
         @ApiResponse(code = HttpURLConnection.HTTP_NOT_FOUND, message = NOT_FOUND_MESSAGE),\r
         @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = SERVER_ERROR_MESSAGE)\r
     })\r
-    public Response getSpecificPolicy(\r
-        @PathParam("policyId") @ApiParam(value = "Name of policy", required = true) String policyId,\r
-        @PathParam("policyVersion") @ApiParam(value = "Version of policy", required = true) String policyVersion,\r
-        @HeaderParam(REQUEST_ID_NAME) @ApiParam(REQUEST_ID_PARAM_DESCRIPTION) UUID requestId,\r
-        @QueryParam("mode") @DefaultValue("bare") @ApiParam("Fetch mode for policies, BARE for bare policies (default),"\r
-            + " REFERENCED for fully referenced policies") PolicyFetchMode mode\r
-    ) {\r
-        try (var policyProvider = new PolicyProvider()) {\r
+    public ResponseEntity<ToscaServiceTemplate> getSpecificPolicy(\r
+        @PathVariable("policyId") @ApiParam(value = "Name of policy", required = true) String policyId,\r
+        @PathVariable("policyVersion") @ApiParam(value = "Version of policy", required = true) String policyVersion,\r
+        @RequestHeader(name = REQUEST_ID_NAME, required = false)\r
+        @ApiParam(REQUEST_ID_PARAM_DESCRIPTION) UUID requestId,\r
+        @RequestParam(name = "mode", defaultValue = "bare") @ApiParam("Fetch mode for policies, BARE for bare"\r
+            + "  policies (default), REFERENCED for fully referenced policies") PolicyFetchMode mode) {\r
+        try {\r
             ToscaServiceTemplate serviceTemplate =\r
                 policyProvider.fetchPolicies(null, null, policyId, policyVersion, mode);\r
-            updateApiStatisticsCounter(Target.POLICY, Result.SUCCESS, HttpMethod.GET);\r
+            updateApiStatisticsCounter(Target.POLICY, HttpStatus.OK, HttpMethod.GET);\r
             return makeOkResponse(requestId, serviceTemplate);\r
         } catch (PfModelException | PfModelRuntimeException pfme) {\r
-            LOGGER.warn("GET /policies/{}/versions/{}", policyId, policyVersion, pfme);\r
-            updateApiStatisticsCounter(Target.POLICY, Result.FAILURE, HttpMethod.GET);\r
-            return makeErrorResponse(requestId, pfme);\r
+            var msg = String.format("GET /policies/%s/versions/%s", policyId, policyVersion);\r
+            updateApiStatisticsCounter(Target.POLICY, HttpStatus.resolve(pfme.getErrorResponse().getResponseCode()\r
+                .getStatusCode()), HttpMethod.GET);\r
+            throw new PolicyApiRuntimeException(msg, pfme.getCause(), pfme.getErrorResponse(), requestId);\r
         }\r
     }\r
 \r
@@ -973,8 +992,7 @@ public class ApiRestController extends CommonRestController {
      *\r
      * @return the Response object containing the results of the API operation\r
      */\r
-    @POST\r
-    @Path("/policies")\r
+    @PostMapping("/policies")\r
     @ApiOperation(value = "Create one or more new policies",\r
         notes = "Client should provide TOSCA body of the new polic(ies)",\r
         authorizations = @Authorization(value = AUTHORIZATION_TYPE), tags = {"Policy", },\r
@@ -1001,22 +1019,22 @@ public class ApiRestController extends CommonRestController {
         @ApiResponse(code = HttpURLConnection.HTTP_NOT_FOUND, message = NOT_FOUND_MESSAGE),\r
         @ApiResponse(code = HttpURLConnection.HTTP_NOT_ACCEPTABLE, message = INVALID_PAYLOAD_MESSAGE),\r
         @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = SERVER_ERROR_MESSAGE)})\r
-    public Response createPolicies(\r
-        @HeaderParam(REQUEST_ID_NAME) @ApiParam(REQUEST_ID_PARAM_DESCRIPTION) UUID requestId,\r
-        @ApiParam(value = "Entity body of policy", required = true) ToscaServiceTemplate body) {\r
-\r
+    public ResponseEntity<ToscaServiceTemplate> createPolicies(\r
+        @RequestHeader(name = REQUEST_ID_NAME, required = false)\r
+        @ApiParam(REQUEST_ID_PARAM_DESCRIPTION) UUID requestId,\r
+        @RequestBody @ApiParam(value = "Entity body of policy", required = true) ToscaServiceTemplate body) {\r
         if (NetLoggerUtil.getNetworkLogger().isInfoEnabled()) {\r
             NetLoggerUtil.log(EventType.IN, CommInfrastructure.REST, "/policies", toJson(body));\r
         }\r
-\r
-        try (var policyProvider = new PolicyProvider()) {\r
+        try {\r
             ToscaServiceTemplate serviceTemplate = policyProvider.createPolicies(body);\r
-            updateApiStatisticsCounter(Target.POLICY, Result.SUCCESS, HttpMethod.POST);\r
+            updateApiStatisticsCounter(Target.POLICY, HttpStatus.OK, HttpMethod.POST);\r
             return makeOkResponse(requestId, serviceTemplate);\r
         } catch (PfModelException | PfModelRuntimeException pfme) {\r
-            LOGGER.warn("POST /policies", pfme);\r
-            updateApiStatisticsCounter(Target.POLICY, Result.FAILURE, HttpMethod.POST);\r
-            return makeErrorResponse(requestId, pfme);\r
+            final var msg = "POST /policies";\r
+            updateApiStatisticsCounter(Target.POLICY, HttpStatus.resolve(pfme.getErrorResponse().getResponseCode()\r
+                .getStatusCode()), HttpMethod.POST);\r
+            throw new PolicyApiRuntimeException(msg, pfme.getCause(), pfme.getErrorResponse(), requestId);\r
         }\r
     }\r
 \r
@@ -1028,8 +1046,7 @@ public class ApiRestController extends CommonRestController {
      *\r
      * @return the Response object containing the results of the API operation\r
      */\r
-    @DELETE\r
-    @Path("/policies/{policyId}/versions/{policyVersion}")\r
+    @DeleteMapping("/policies/{policyId}/versions/{policyVersion}")\r
     @ApiOperation(value = "Delete a particular version of a policy",\r
         notes = "Rule: the version that has been deployed in PDP group(s) cannot be deleted",\r
         authorizations = @Authorization(value = AUTHORIZATION_TYPE), tags = {"Policy", },\r
@@ -1055,47 +1072,33 @@ public class ApiRestController extends CommonRestController {
         @ApiResponse(code = HttpURLConnection.HTTP_NOT_FOUND, message = NOT_FOUND_MESSAGE),\r
         @ApiResponse(code = HttpURLConnection.HTTP_CONFLICT, message = HTTP_CONFLICT_MESSAGE),\r
         @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = SERVER_ERROR_MESSAGE)})\r
-    public Response deleteSpecificPolicy(\r
-        @PathParam("policyId") @ApiParam(value = "ID of policy", required = true) String policyId,\r
-        @PathParam("policyVersion") @ApiParam(value = "Version of policy", required = true) String policyVersion,\r
-        @HeaderParam(REQUEST_ID_NAME) @ApiParam(REQUEST_ID_PARAM_DESCRIPTION) UUID requestId) {\r
-\r
-        try (var policyProvider = new PolicyProvider()) {\r
+    public ResponseEntity<ToscaServiceTemplate> deleteSpecificPolicy(\r
+        @PathVariable("policyId") @ApiParam(value = "ID of policy", required = true) String policyId,\r
+        @PathVariable("policyVersion") @ApiParam(value = "Version of policy", required = true) String policyVersion,\r
+        @RequestHeader(name = REQUEST_ID_NAME, required = false)\r
+        @ApiParam(REQUEST_ID_PARAM_DESCRIPTION) UUID requestId) {\r
+        try {\r
             ToscaServiceTemplate serviceTemplate =\r
                 policyProvider.deletePolicy(null, null, policyId, policyVersion);\r
-            updateApiStatisticsCounter(Target.POLICY, Result.SUCCESS, HttpMethod.DELETE);\r
+            updateApiStatisticsCounter(Target.POLICY, HttpStatus.OK, HttpMethod.DELETE);\r
             return makeOkResponse(requestId, serviceTemplate);\r
         } catch (PfModelException | PfModelRuntimeException pfme) {\r
-            LOGGER.warn("DELETE /policies/{}/versions/{}", policyId, policyVersion, pfme);\r
-            updateApiStatisticsCounter(Target.POLICY, Result.FAILURE, HttpMethod.DELETE);\r
-            return makeErrorResponse(requestId, pfme);\r
+            var msg = String.format("DELETE /policies/%s/versions/%s", policyId, policyVersion);\r
+            updateApiStatisticsCounter(Target.POLICY, HttpStatus.resolve(pfme.getErrorResponse().getResponseCode()\r
+                .getStatusCode()), HttpMethod.DELETE);\r
+            throw new PolicyApiRuntimeException(msg, pfme.getCause(), pfme.getErrorResponse(), requestId);\r
         }\r
     }\r
 \r
-\r
-\r
-    private enum Target {\r
-        POLICY,\r
-        POLICY_TYPE,\r
-        OTHER\r
-    }\r
-\r
-    private enum Result {\r
-        SUCCESS,\r
-        FAILURE\r
-    }\r
-\r
-    private enum HttpMethod {\r
-        POST,\r
-        GET,\r
-        DELETE\r
+    @ExceptionHandler(value = {PolicyApiRuntimeException.class})\r
+    protected ResponseEntity<Object> handleException(PolicyApiRuntimeException ex) {\r
+        LOGGER.warn(ex.getMessage(), ex.getCause());\r
+        return makeErrorResponse(ex.getRequestId(), ex.getErrorResponse(),\r
+            ex.getErrorResponse().getResponseCode().getStatusCode());\r
     }\r
 \r
-    private void updateApiStatisticsCounter(Target target, Result result, HttpMethod http) {\r
-\r
-        var mgr = ApiStatisticsManager.getInstance();\r
+    private void updateApiStatisticsCounter(Target target, HttpStatus result, HttpMethod http) {\r
         mgr.updateTotalApiCallCount();\r
-\r
         switch (target) {\r
             case POLICY:\r
                 updatePolicyStats(result, http);\r
@@ -1109,10 +1112,8 @@ public class ApiRestController extends CommonRestController {
         }\r
     }\r
 \r
-    private void updatePolicyStats(Result result, HttpMethod http) {\r
-        var mgr = ApiStatisticsManager.getInstance();\r
-\r
-        if (result == Result.SUCCESS) {\r
+    private void updatePolicyStats(HttpStatus result, HttpMethod http) {\r
+        if (result.equals(HttpStatus.OK)) {\r
             switch (http) {\r
                 case GET:\r
                     mgr.updateApiCallSuccessCount();\r
@@ -1157,10 +1158,8 @@ public class ApiRestController extends CommonRestController {
         }\r
     }\r
 \r
-    private void updatePolicyTypeStats(Result result, HttpMethod http) {\r
-        var mgr = ApiStatisticsManager.getInstance();\r
-\r
-        if (result == Result.SUCCESS) {\r
+    private void updatePolicyTypeStats(HttpStatus result, HttpMethod http) {\r
+        if (result.equals(HttpStatus.OK)) {\r
             switch (http) {\r
                 case GET:\r
                     mgr.updateApiCallSuccessCount();\r
@@ -1204,4 +1203,4 @@ public class ApiRestController extends CommonRestController {
             }\r
         }\r
     }\r
-}\r
+}
\ No newline at end of file
index 2a4a46a..b497c7f 100644 (file)
@@ -3,7 +3,7 @@
  * ONAP Policy API
  * ================================================================================
  * Copyright (C) 2019, 2021 AT&T Intellectual Property. All rights reserved.
- * Modifications Copyright (C) 2020-2021 Bell Canada.
+ * Modifications Copyright (C) 2020-2022 Bell Canada. All rights reserved.
  * ================================================================================
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
 
 package org.onap.policy.api.main.rest;
 
-import lombok.Getter;
-import lombok.NoArgsConstructor;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Component;
 
 /**
  * Class to hold statistical data for API access.
  *
  * @author Chenfei Gao (cgao@research.att.com)
  */
-@Getter
-@NoArgsConstructor
+@Component
 public class ApiStatisticsManager {
-    @Getter
-    private static ApiStatisticsManager instance = new ApiStatisticsManager();
 
-    private StatisticsReport report = new StatisticsReport();
+    @Autowired
+    private StatisticsReport report;
+
     private long totalPolicyDeleteCount;
     private long totalPolicyTypeDeleteCount;
     private long policyDeleteSuccessCount;
@@ -233,11 +232,4 @@ public class ApiStatisticsManager {
     public long updatePolicyTypeDeleteFailureCount() {
         return ++policyTypeDeleteFailureCount;
     }
-
-    /**
-     * Resets the statistics.
-     */
-    protected static void resetAllStatistics() {
-        instance = new ApiStatisticsManager();
-    }
-}
+}
\ No newline at end of file
index b059490..0389e0f 100644 (file)
@@ -3,6 +3,7 @@
  * ONAP Policy API\r
  * ================================================================================\r
  * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.\r
+ * Modifications Copyright (C) 2022 Bell Canada. All rights reserved.\r
  * ================================================================================\r
  * Licensed under the Apache License, Version 2.0 (the "License");\r
  * you may not use this file except in compliance with the License.\r
 package org.onap.policy.api.main.rest;\r
 \r
 import java.util.UUID;\r
-import javax.ws.rs.core.Response;\r
-import javax.ws.rs.core.Response.ResponseBuilder;\r
 import org.onap.policy.common.utils.coder.Coder;\r
 import org.onap.policy.common.utils.coder.CoderException;\r
 import org.onap.policy.common.utils.coder.StandardCoder;\r
-import org.onap.policy.models.errors.concepts.ErrorResponseInfo;\r
 import org.slf4j.Logger;\r
 import org.slf4j.LoggerFactory;\r
+import org.springframework.http.HttpHeaders;\r
+import org.springframework.http.ResponseEntity;\r
 \r
 /**\r
  * Super class from which REST controllers are derived.\r
@@ -41,27 +41,33 @@ public class CommonRestController {
 \r
     private final Coder coder = new StandardCoder();\r
 \r
-\r
-    protected Response makeOkResponse(UUID requestId, Object respEntity) {\r
-        return addLoggingHeaders(addVersionControlHeaders(Response.status(Response.Status.OK)), requestId)\r
-                        .entity(respEntity).build();\r
+    protected <T> ResponseEntity<T> makeOkResponse(UUID requestId, T respEntity) {\r
+        HttpHeaders headers = new HttpHeaders();\r
+        addVersionControlHeaders(headers);\r
+        addLoggingHeaders(headers, requestId);\r
+        return ResponseEntity.ok().headers(headers).body(respEntity);\r
     }\r
 \r
-    protected <T extends ErrorResponseInfo> Response makeErrorResponse(UUID requestId, T pfme) {\r
-        return addLoggingHeaders(addVersionControlHeaders(Response.status(pfme.getErrorResponse().getResponseCode())),\r
-                        requestId).entity(pfme.getErrorResponse()).build();\r
+    protected <T> ResponseEntity<T> makeErrorResponse(UUID requestId, T respEntity, int status) {\r
+        HttpHeaders headers = new HttpHeaders();\r
+        addVersionControlHeaders(headers);\r
+        addLoggingHeaders(headers, requestId);\r
+        return ResponseEntity.status(status).headers(headers).body(respEntity);\r
     }\r
 \r
-    protected ResponseBuilder addVersionControlHeaders(ResponseBuilder rb) {\r
-        return rb.header("X-MinorVersion", "0").header("X-PatchVersion", "0").header("X-LatestVersion", "1.0.0");\r
+    private void addVersionControlHeaders(HttpHeaders headers) {\r
+        headers.add("X-MinorVersion", "0");\r
+        headers.add("X-PatchVersion", "0");\r
+        headers.add("X-LatestVersion", "1.0.0");\r
     }\r
 \r
-    protected ResponseBuilder addLoggingHeaders(ResponseBuilder rb, UUID requestId) {\r
+    private void addLoggingHeaders(HttpHeaders headers, UUID requestId) {\r
         if (requestId == null) {\r
             // Generate a random uuid if client does not embed requestId in rest request\r
-            return rb.header("X-ONAP-RequestID", UUID.randomUUID());\r
+            headers.add("X-ONAP-RequestID", UUID.randomUUID().toString());\r
+        } else {\r
+            headers.add("X-ONAP-RequestID", requestId.toString());\r
         }\r
-        return rb.header("X-ONAP-RequestID", requestId);\r
     }\r
 \r
     /**\r
@@ -83,4 +89,4 @@ public class CommonRestController {
             return null;\r
         }\r
     }\r
-}\r
+}
\ No newline at end of file
index e555cd8..287c0b2 100644 (file)
@@ -4,6 +4,7 @@
  * ================================================================================\r
  * Copyright (C) 2019-2021 AT&T Intellectual Property. All rights reserved.\r
  * Modifications Copyright (C) 2019-2021 Nordix Foundation.\r
+ * Modifications Copyright (C) 2022 Bell Canada. All rights reserved.\r
  * ================================================================================\r
  * Licensed under the Apache License, Version 2.0 (the "License");\r
  * you may not use this file except in compliance with the License.\r
@@ -30,8 +31,6 @@ import java.util.Map;
 import java.util.function.BiConsumer;\r
 import javax.ws.rs.core.Response;\r
 import org.apache.commons.lang3.tuple.Pair;\r
-import org.onap.policy.api.main.parameters.ApiParameterGroup;\r
-import org.onap.policy.common.parameters.ParameterService;\r
 import org.onap.policy.models.base.PfConceptKey;\r
 import org.onap.policy.models.base.PfModelException;\r
 import org.onap.policy.models.pdp.concepts.PdpGroup;\r
@@ -39,38 +38,21 @@ import org.onap.policy.models.pdp.concepts.PdpGroupFilter;
 import org.onap.policy.models.pdp.concepts.PdpSubGroup;\r
 import org.onap.policy.models.pdp.enums.PdpState;\r
 import org.onap.policy.models.provider.PolicyModelsProvider;\r
-import org.onap.policy.models.provider.PolicyModelsProviderFactory;\r
-import org.onap.policy.models.provider.PolicyModelsProviderParameters;\r
 import org.onap.policy.models.tosca.authorative.concepts.ToscaConceptIdentifier;\r
 \r
 /**\r
  * Super class for providers that use a model provider.\r
  */\r
-public class CommonModelProvider implements AutoCloseable {\r
+public class CommonModelProvider {\r
 \r
     protected final PolicyModelsProvider modelsProvider;\r
 \r
     /**\r
      * Constructs the object, populating {@link #modelsProvider}.\r
      *\r
-     * @throws PfModelException if an error occurs\r
      */\r
-    public CommonModelProvider() throws PfModelException {\r
-\r
-        ApiParameterGroup parameterGroup = ParameterService.get("ApiGroup");\r
-        PolicyModelsProviderParameters providerParameters = parameterGroup.getDatabaseProviderParameters();\r
-        modelsProvider = new PolicyModelsProviderFactory().createPolicyModelsProvider(providerParameters);\r
-    }\r
-\r
-    /**\r
-     * Closes the connection to database.\r
-     *\r
-     * @throws PfModelException the PfModel parsing exception\r
-     */\r
-    @Override\r
-    public void close() throws PfModelException {\r
-\r
-        modelsProvider.close();\r
+    public CommonModelProvider(PolicyModelsProvider modelsProvider) {\r
+        this.modelsProvider = modelsProvider;\r
     }\r
 \r
     /**\r
@@ -243,4 +225,4 @@ public class CommonModelProvider implements AutoCloseable {
         return "could not find policy with ID " + policyId + " and type " + policyType.getName() + ":"\r
                 + policyType.getVersion() + " deployed in any pdp group";\r
     }\r
-}\r
+}
\ No newline at end of file
index b5a198a..40b841e 100644 (file)
@@ -5,6 +5,7 @@
  * Copyright (C) 2018 Samsung Electronics Co., Ltd. All rights reserved.
  * Modifications Copyright (C) 2019, 2021 AT&T Intellectual Property. All rights reserved.
  * Modifications Copyright (C) 2019 Nordix Foundation.
+ * Modifications Copyright (C) 2022 Bell Canada. All rights reserved.
  * ================================================================================
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
 package org.onap.policy.api.main.rest.provider;
 
 import org.onap.policy.api.main.rest.PolicyFetchMode;
-import org.onap.policy.api.main.startstop.ApiActivator;
 import org.onap.policy.common.endpoints.report.HealthCheckReport;
 import org.onap.policy.common.utils.network.NetworkUtil;
 import org.onap.policy.models.base.PfModelException;
 import org.onap.policy.models.base.PfModelRuntimeException;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Service;
 
 /**
  * Class to fetch health check of api service.
  *
  */
+@Service
 public class HealthCheckProvider {
 
     private static final Logger LOGGER = LoggerFactory.getLogger(HealthCheckProvider.class);
 
-    private static final String NOT_ALIVE = "not alive";
     private static final String ALIVE = "alive";
     private static final String URL = NetworkUtil.getHostname();
     private static final String NAME = "Policy API";
     private static final String DB_CONN_FAILURE = "unable to connect with database";
 
+    @Autowired
+    private PolicyProvider policyProvider;
+
     /**
      * Performs the health check of api service.
      *
@@ -54,19 +59,12 @@ public class HealthCheckProvider {
      */
     public HealthCheckReport performHealthCheck() {
         final var report = new HealthCheckReport();
+        final var dbConnectionStatus = verifyApiDatabase();
         report.setName(NAME);
         report.setUrl(URL);
-        boolean heathStatus = ApiActivator.isAlive();
-        if (heathStatus) {
-            boolean dbConnectionStatus = verifyApiDatabase();
-            report.setHealthy(dbConnectionStatus);
-            report.setCode(dbConnectionStatus ? 200 : 503);
-            report.setMessage(dbConnectionStatus ? ALIVE : DB_CONN_FAILURE);
-        } else {
-            report.setHealthy(heathStatus);
-            report.setCode(500);
-            report.setMessage(NOT_ALIVE);
-        }
+        report.setHealthy(dbConnectionStatus);
+        report.setCode(dbConnectionStatus ? 200 : 503);
+        report.setMessage(dbConnectionStatus ? ALIVE : DB_CONN_FAILURE);
         return report;
     }
 
@@ -76,7 +74,7 @@ public class HealthCheckProvider {
      * @return boolean signaling the verification result
      */
     private boolean verifyApiDatabase() {
-        try (var policyProvider = new PolicyProvider()) {
+        try {
             policyProvider.fetchPolicies(null, null, null, null, PolicyFetchMode.BARE);
             return true;
         } catch (PfModelException | PfModelRuntimeException pfme) {
@@ -84,4 +82,4 @@ public class HealthCheckProvider {
             return false;
         }
     }
-}
+}
\ No newline at end of file
index 33df1cc..1e5ed47 100644 (file)
@@ -4,6 +4,7 @@
  * ================================================================================\r
  * Copyright (C) 2019-2020 AT&T Intellectual Property. All rights reserved.\r
  * Modifications Copyright (C) 2020-2021 Nordix Foundation.\r
+ * Modifications Copyright (C) 2022 Bell Canada. All rights reserved.\r
  * ================================================================================\r
  * Licensed under the Apache License, Version 2.0 (the "License");\r
  * you may not use this file except in compliance with the License.\r
@@ -25,22 +26,27 @@ package org.onap.policy.api.main.rest.provider;
 \r
 import org.onap.policy.api.main.rest.PolicyFetchMode;\r
 import org.onap.policy.models.base.PfModelException;\r
+import org.onap.policy.models.provider.PolicyModelsProvider;\r
 import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicy;\r
 import org.onap.policy.models.tosca.authorative.concepts.ToscaServiceTemplate;\r
 import org.onap.policy.models.tosca.authorative.concepts.ToscaTypedEntityFilter;\r
+import org.springframework.beans.factory.annotation.Autowired;\r
+import org.springframework.stereotype.Service;\r
 \r
 /**\r
  * Class to provide all kinds of policy operations.\r
  *\r
  * @author Chenfei Gao (cgao@research.att.com)\r
  */\r
+@Service\r
 public class PolicyProvider extends CommonModelProvider {\r
 \r
     /**\r
      * Default constructor.\r
      */\r
-    public PolicyProvider() throws PfModelException {\r
-        super();\r
+    @Autowired\r
+    public PolicyProvider(PolicyModelsProvider modelsProvider) throws PfModelException {\r
+        super(modelsProvider);\r
     }\r
 \r
     /**\r
@@ -156,4 +162,4 @@ public class PolicyProvider extends CommonModelProvider {
 \r
         return serviceTemplate;\r
     }\r
-}\r
+}
\ No newline at end of file
index e56b536..4db1698 100644 (file)
@@ -4,6 +4,7 @@
  * ================================================================================\r
  * Copyright (C) 2019-2020 AT&T Intellectual Property. All rights reserved.\r
  * Modifications Copyright (C) 2020-2021 Nordix Foundation.\r
+ * Modifications Copyright (C) 2022 Bell Canada. All rights reserved.\r
  * ================================================================================\r
  * Licensed under the Apache License, Version 2.0 (the "License");\r
  * you may not use this file except in compliance with the License.\r
 package org.onap.policy.api.main.rest.provider;\r
 \r
 import org.onap.policy.models.base.PfModelException;\r
+import org.onap.policy.models.provider.PolicyModelsProvider;\r
 import org.onap.policy.models.tosca.authorative.concepts.ToscaEntityFilter;\r
 import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicyType;\r
 import org.onap.policy.models.tosca.authorative.concepts.ToscaServiceTemplate;\r
+import org.springframework.beans.factory.annotation.Autowired;\r
+import org.springframework.stereotype.Service;\r
 \r
 /**\r
  * Class to provide all kinds of policy type operations.\r
  *\r
  * @author Chenfei Gao (cgao@research.att.com)\r
  */\r
+@Service\r
 public class PolicyTypeProvider extends CommonModelProvider {\r
 \r
     /**\r
      * Default constructor.\r
      */\r
-    public PolicyTypeProvider() throws PfModelException {\r
-        super();\r
+    @Autowired\r
+    public PolicyTypeProvider(PolicyModelsProvider modelsProvider) throws PfModelException {\r
+        super(modelsProvider);\r
     }\r
 \r
     /**\r
@@ -118,4 +124,4 @@ public class PolicyTypeProvider extends CommonModelProvider {
                 ToscaEntityFilter.<ToscaPolicyType>builder().name(policyTypeName).version(policyTypeVersion).build();\r
         return modelsProvider.getFilteredPolicyTypes(policyTypeFilter);\r
     }\r
-}\r
+}
\ No newline at end of file
index 9df0047..9dfc0dd 100644 (file)
@@ -1,10 +1,11 @@
-/*-
 /*-
  * ============LICENSE_START=======================================================
  * ONAP Policy API
  * ================================================================================
  * Copyright (C) 2019, 2021 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2022 Bell Canada. All rights reserved.
  * ================================================================================
+ *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
  * You may obtain a copy of the License at
 
 package org.onap.policy.api.main.rest.provider;
 
-import org.onap.policy.api.main.rest.ApiStatisticsManager;
 import org.onap.policy.api.main.rest.StatisticsReport;
-import org.onap.policy.api.main.startstop.ApiActivator;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Service;
 
 /**
  * Class to fetch API statistics.
  *
  * @author Chenfei Gao (cgao@research.att.com)
  */
+@Service
 public class StatisticsProvider {
 
+    @Autowired
+    private StatisticsReport report;
+
     /**
      * Return the current API statistics.
      *
      * @return Report containing API statistics
      */
     public StatisticsReport fetchCurrentStatistics() {
-        final var report = ApiStatisticsManager.getInstance().getReport();
-        report.setCode(ApiActivator.isAlive() ? 200 : 500);
+        report.setCode(200);
         return report;
     }
-}
-
+}
\ No newline at end of file
diff --git a/main/src/main/java/org/onap/policy/api/main/startstop/ApiActivator.java b/main/src/main/java/org/onap/policy/api/main/startstop/ApiActivator.java
deleted file mode 100644 (file)
index 156837d..0000000
+++ /dev/null
@@ -1,125 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * ONAP Policy API
- * ================================================================================
- * Copyright (C) 2018 Samsung Electronics Co., Ltd. All rights reserved.
- * Modifications Copyright (C) 2019, 2021 AT&T Intellectual Property. All rights reserved.
- * Modifications Copyright (C) 2021 Bell Canada. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- * SPDX-License-Identifier: Apache-2.0
- * ============LICENSE_END=========================================================
- */
-
-package org.onap.policy.api.main.startstop;
-
-import lombok.Getter;
-import lombok.RequiredArgsConstructor;
-import lombok.Setter;
-import org.onap.policy.api.main.exception.PolicyApiException;
-import org.onap.policy.api.main.parameters.ApiParameterGroup;
-import org.onap.policy.api.main.rest.ApiRestController;
-import org.onap.policy.api.main.rest.aaf.AafApiFilter;
-import org.onap.policy.common.endpoints.http.server.RestServer;
-import org.onap.policy.common.parameters.ParameterService;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-/**
- * This class wraps a distributor so that it can be activated as a complete service together with all its api and
- * forwarding handlers.
- */
-@RequiredArgsConstructor
-public class ApiActivator {
-
-    private static final Logger LOGGER = LoggerFactory.getLogger(ApiActivator.class);
-
-    @Getter
-    @Setter
-    private static boolean alive = false;
-
-    @Getter
-    private final ApiParameterGroup parameterGroup;
-
-    private RestServer restServer;
-
-    /**
-     * Initialize api as a complete service.
-     *
-     * @throws PolicyApiException on errors in initializing the service
-     */
-    public void initialize() throws PolicyApiException {
-        LOGGER.debug("Policy api starting as a service . . .");
-        startApiRestServer();
-        registerToParameterService(parameterGroup);
-        ApiActivator.setAlive(true);
-        LOGGER.debug("Policy api started as a service");
-    }
-
-    /**
-     * Starts the api rest server using configuration parameters.
-     *
-     * @throws PolicyApiException if server start fails
-     */
-    private void startApiRestServer() throws PolicyApiException {
-        parameterGroup.getRestServerParameters().setName(parameterGroup.getName());
-        restServer = new RestServer(parameterGroup.getRestServerParameters(), AafApiFilter.class,
-                        ApiRestController.class);
-        if (!restServer.start()) {
-            throw new PolicyApiException("Failed to start api rest server. Check log for more details...");
-        }
-    }
-
-    /**
-     * Terminate policy api.
-     *
-     * @throws PolicyApiException on termination errors
-     */
-    public void terminate() throws PolicyApiException {
-        try {
-            deregisterToParameterService(parameterGroup);
-
-            if (ApiActivator.isAlive()) {
-                ApiActivator.setAlive(false);
-            }
-
-            // Stop the api rest server
-            if (restServer.isAlive()) {
-                restServer.stop();
-            }
-        } catch (final Exception exp) {
-            throw new PolicyApiException("Policy api service termination failed", exp);
-        }
-    }
-
-    /**
-     * Method to register the parameters to Common Parameter Service.
-     *
-     * @param apiParameterGroup the api parameter group
-     */
-    public void registerToParameterService(final ApiParameterGroup apiParameterGroup) {
-        ParameterService.register(apiParameterGroup, true);
-    }
-
-    /**
-     * Method to deregister the parameters from Common Parameter Service.
-     *
-     * @param apiParameterGroup the api parameter group
-     */
-    public void deregisterToParameterService(final ApiParameterGroup apiParameterGroup) {
-        if (ParameterService.contains(apiParameterGroup.getName())) {
-            ParameterService.deregister(apiParameterGroup.getName());
-        }
-    }
-}
diff --git a/main/src/main/java/org/onap/policy/api/main/startstop/ApiCommandLineArguments.java b/main/src/main/java/org/onap/policy/api/main/startstop/ApiCommandLineArguments.java
deleted file mode 100644 (file)
index 47f004e..0000000
+++ /dev/null
@@ -1,55 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- *  Copyright (C) 2018 Samsung Electronics Co., Ltd. All rights reserved.
- *  Modifications Copyright (C) 2021 Nordix Foundation.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- * SPDX-License-Identifier: Apache-2.0
- * ============LICENSE_END=========================================================
- */
-
-package org.onap.policy.api.main.startstop;
-
-import org.onap.policy.api.main.exception.PolicyApiRuntimeException;
-import org.onap.policy.common.utils.cmd.CommandLineArgumentsHandler;
-import org.onap.policy.common.utils.cmd.CommandLineException;
-import org.onap.policy.common.utils.resources.MessageConstants;
-
-/**
- * This class reads and handles command line parameters for the policy api main program.
- */
-public class ApiCommandLineArguments extends CommandLineArgumentsHandler {
-
-    /**
-     * Construct the options for the CLI editor from super.
-     */
-    public ApiCommandLineArguments() {
-        super(Main.class.getName(), MessageConstants.POLICY_API);
-    }
-
-    /**
-     * Construct the options for the CLI editor and parse in the given arguments.
-     *
-     * @param args The command line arguments
-     */
-    public ApiCommandLineArguments(final String[] args) {
-        this();
-
-        try {
-            parse(args);
-        } catch (final CommandLineException e) {
-            throw new PolicyApiRuntimeException("parse error on policy api parameters", e);
-        }
-    }
-}
index 76ffd9f..4aa2516 100644 (file)
@@ -4,6 +4,7 @@
  * ================================================================================
  * Copyright (C) 2019-2021 AT&T Intellectual Property. All rights reserved.
  * Modifications Copyright (C) 2019-2021 Nordix Foundation.
+ * Modifications Copyright (C) 2022 Bell Canada. All rights reserved.
  * ================================================================================
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -26,53 +27,60 @@ package org.onap.policy.api.main.startstop;
 import java.util.LinkedHashMap;
 import java.util.LinkedList;
 import java.util.List;
+import javax.annotation.PostConstruct;
+import org.onap.policy.api.main.config.PolicyPreloadConfig;
 import org.onap.policy.api.main.exception.PolicyApiException;
-import org.onap.policy.api.main.parameters.ApiParameterGroup;
 import org.onap.policy.common.utils.coder.CoderException;
 import org.onap.policy.common.utils.coder.StandardYamlCoder;
 import org.onap.policy.common.utils.resources.ResourceUtils;
 import org.onap.policy.models.base.PfModelException;
 import org.onap.policy.models.base.PfModelRuntimeException;
 import org.onap.policy.models.provider.PolicyModelsProvider;
-import org.onap.policy.models.provider.PolicyModelsProviderFactory;
 import org.onap.policy.models.tosca.authorative.concepts.ToscaEntityFilter;
 import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicyType;
 import org.onap.policy.models.tosca.authorative.concepts.ToscaServiceTemplate;
 import org.onap.policy.models.tosca.authorative.concepts.ToscaTopologyTemplate;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
+import org.springframework.stereotype.Component;
 
 /**
  * This class creates initial policy types in the database.
  *
  * @author Chenfei Gao (cgao@research.att.com)
  */
+@Component
+@ConditionalOnProperty(value = "database.initialize", havingValue = "true", matchIfMissing = true)
 public class ApiDatabaseInitializer {
 
     private static final Logger LOGGER = LoggerFactory.getLogger(ApiDatabaseInitializer.class);
 
     private static final StandardYamlCoder coder = new StandardYamlCoder();
-    private PolicyModelsProviderFactory factory;
 
-    /**
-     * Constructs the object.
-     */
-    public ApiDatabaseInitializer() {
-        factory = new PolicyModelsProviderFactory();
+    @Autowired
+    PolicyModelsProvider policyModelsProvider;
+
+    @Autowired
+    PolicyPreloadConfig policyPreloadConfig;
+
+    @PostConstruct
+    public void loadData() throws PolicyApiException {
+        initializeApiDatabase(policyPreloadConfig.getPolicyTypes(), policyPreloadConfig.getPolicies());
     }
 
     /**
      * Initializes database by preloading policy types and policies.
      *
-     * @param apiParameterGroup the apiParameterGroup parameters
+     * @param policyTypes List of policy types to preload.
+     * @param policies List of policies to preload.
      * @throws PolicyApiException in case of errors.
      */
-    public void initializeApiDatabase(final ApiParameterGroup apiParameterGroup) throws PolicyApiException {
-
-        try (var databaseProvider =
-                factory.createPolicyModelsProvider(apiParameterGroup.getDatabaseProviderParameters())) {
-
-            if (alreadyExists(databaseProvider)) {
+    public void initializeApiDatabase(final List<String> policyTypes, final List<String> policies)
+        throws PolicyApiException {
+        try {
+            if (alreadyExists()) {
                 LOGGER.warn("DB already contains policy data - skipping preload");
                 return;
             }
@@ -82,27 +90,24 @@ public class ApiDatabaseInitializer {
             serviceTemplate.setPolicyTypes(new LinkedHashMap<>());
             serviceTemplate.setToscaDefinitionsVersion("tosca_simple_yaml_1_1_0");
 
-            ToscaServiceTemplate createdPolicyTypes = preloadServiceTemplate(serviceTemplate,
-                    apiParameterGroup.getPreloadPolicyTypes(), databaseProvider::createPolicyTypes);
-            preloadServiceTemplate(createdPolicyTypes, apiParameterGroup.getPreloadPolicies(),
-                    databaseProvider::createPolicies);
+            ToscaServiceTemplate createdPolicyTypes =
+                    preloadServiceTemplate(serviceTemplate, policyTypes, policyModelsProvider::createPolicyTypes);
+            preloadServiceTemplate(createdPolicyTypes, policies, policyModelsProvider::createPolicies);
         } catch (final PolicyApiException | PfModelException | CoderException exp) {
             throw new PolicyApiException(exp);
         }
     }
 
-    private boolean alreadyExists(PolicyModelsProvider databaseProvider) throws PfModelException {
+    private boolean alreadyExists() throws PfModelException {
         try {
             ToscaServiceTemplate serviceTemplate =
-                    databaseProvider.getFilteredPolicyTypes(ToscaEntityFilter.<ToscaPolicyType>builder().build());
+                    policyModelsProvider.getFilteredPolicyTypes(ToscaEntityFilter.<ToscaPolicyType>builder().build());
             if (!serviceTemplate.getPolicyTypes().isEmpty()) {
                 return true;
             }
-
         } catch (PfModelRuntimeException e) {
             LOGGER.trace("DB does not yet contain policy types", e);
         }
-
         return false;
     }
 
@@ -119,7 +124,7 @@ public class ApiDatabaseInitializer {
 
             ToscaServiceTemplate singleEntity = coder.decode(entityAsStringYaml, ToscaServiceTemplate.class);
             if (singleEntity == null) {
-                throw new PolicyApiException("Error deserializaing entity from file: " + entity);
+                throw new PolicyApiException("Error deserializing entity from file: " + entity);
             }
 
             // Consolidate data types and policy types
@@ -149,4 +154,4 @@ public class ApiDatabaseInitializer {
     protected interface FunctionWithEx<T, R> {
         public R apply(T value) throws PfModelException;
     }
-}
+}
\ No newline at end of file
diff --git a/main/src/main/java/org/onap/policy/api/main/startstop/Main.java b/main/src/main/java/org/onap/policy/api/main/startstop/Main.java
deleted file mode 100644 (file)
index 21bd5c4..0000000
+++ /dev/null
@@ -1,141 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * ONAP Policy API
- * ================================================================================
- * Copyright (C) 2018 Samsung Electronics Co., Ltd. All rights reserved.
- * Modifications Copyright (C) 2019, 2021 AT&T Intellectual Property. All rights reserved.
- * Modifications Copyright (C) 2020-2021 Bell Canada. All rights reserved.
- * Modifications Copyright (C) 2021 Nordix Foundation.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- * SPDX-License-Identifier: Apache-2.0
- * ============LICENSE_END=========================================================
- */
-
-package org.onap.policy.api.main.startstop;
-
-import java.util.Arrays;
-import lombok.Getter;
-import org.onap.policy.api.main.exception.PolicyApiException;
-import org.onap.policy.api.main.exception.PolicyApiRuntimeException;
-import org.onap.policy.api.main.parameters.ApiParameterGroup;
-import org.onap.policy.api.main.parameters.ApiParameterHandler;
-import org.onap.policy.common.utils.cmd.CommandLineException;
-import org.onap.policy.common.utils.resources.MessageConstants;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-/**
- * This class initiates ONAP Policy Framework policy api.
- *
- */
-public class Main {
-
-    private static final Logger LOGGER = LoggerFactory.getLogger(Main.class);
-
-    // The policy api Activator that activates the policy api service
-    private ApiActivator activator;
-
-    // The parameters read in from JSON
-    @Getter
-    private ApiParameterGroup parameterGroup;
-
-    /**
-     * Instantiates the policy api service.
-     *
-     * @param args the command line arguments
-     */
-    public Main(final String[] args) {
-        final var argumentString = Arrays.toString(args);
-        LOGGER.info("Starting policy api service with arguments - {}", argumentString);
-
-        // Check the arguments
-        final var arguments = new ApiCommandLineArguments();
-        try {
-            // The arguments return a string if there is a message to print and we should exit
-            final String argumentMessage = arguments.parse(args);
-            if (argumentMessage != null) {
-                LOGGER.info(argumentMessage);
-                return;
-            }
-
-            // Validate that the arguments are sane
-            arguments.validate();
-
-            // Read the parameters
-            parameterGroup = new ApiParameterHandler().getParameters(arguments);
-            // Initialize database
-            new ApiDatabaseInitializer().initializeApiDatabase(parameterGroup);
-
-            // Now, create the activator for the policy api service
-            activator = new ApiActivator(parameterGroup);
-
-            // Start the activator
-            activator.initialize();
-        } catch (final PolicyApiException | CommandLineException e) {
-            throw new PolicyApiRuntimeException(
-                String.format(MessageConstants.START_FAILURE_MSG, MessageConstants.POLICY_API), e);
-        }
-
-        // Add a shutdown hook to shut everything down in an orderly manner
-        Runtime.getRuntime().addShutdownHook(new PolicyApiShutdownHookClass());
-        var successMsg = String.format(MessageConstants.START_SUCCESS_MSG, MessageConstants.POLICY_API);
-        LOGGER.info(successMsg);
-    }
-
-    /**
-     * Shut down Execution.
-     *
-     * @throws PolicyApiException on shutdown errors
-     */
-    public void shutdown() throws PolicyApiException {
-        // clear the parameterGroup variable
-        parameterGroup = null;
-
-        // clear the api activator
-        if (activator != null) {
-            activator.terminate();
-        }
-    }
-
-    /**
-     * The Class PolicyApiShutdownHookClass terminates the policy api service when its run method is
-     * called.
-     */
-    private class PolicyApiShutdownHookClass extends Thread {
-        /*
-         * (non-Javadoc)
-         *
-         * @see java.lang.Runnable#run()
-         */
-        @Override
-        public void run() {
-            try {
-                // Shutdown the policy api service and wait for everything to stop
-                activator.terminate();
-            } catch (final PolicyApiException e) {
-                LOGGER.warn("error occured during shut down of the policy api service", e);
-            }
-        }
-    }
-
-    /**
-     * The main method.
-     *
-     * @param args the arguments
-     */
-    public static void main(final String[] args) {
-        new Main(args);
-    }
-}
diff --git a/main/src/main/resources/application.yaml b/main/src/main/resources/application.yaml
new file mode 100644 (file)
index 0000000..96b7982
--- /dev/null
@@ -0,0 +1,65 @@
+server:
+  port: 6969
+
+spring:
+  security.user:
+    name: policyadmin
+    password: zb!XztG34
+  mvc.converters.preferred-json-mapper: gson
+
+policy-api:
+  name: ApiGroup
+  aaf: false
+
+database:
+  name: PolicyProviderParameterGroup
+  implementation: org.onap.policy.models.provider.impl.DatabasePolicyModelsProviderImpl
+  driver: org.mariadb.jdbc.Driver
+  url: jdbc:mariadb://mariadb:3306/policyadmin
+  user: policy_user
+  password: policy_user
+  persistenceUnit: PolicyDb
+
+policy-preload:
+  policyTypes:
+    - policytypes/onap.policies.monitoring.tcagen2.yaml
+    - policytypes/onap.policies.monitoring.dcaegen2.collectors.datafile.datafile-app-server.yaml
+    - policytypes/onap.policies.monitoring.dcae-restconfcollector.yaml
+    - policytypes/onap.policies.monitoring.dcae-pm-subscription-handler.yaml
+    - policytypes/onap.policies.monitoring.dcae-pm-mapper.yaml
+    - policytypes/onap.policies.Optimization.yaml
+    - policytypes/onap.policies.optimization.Resource.yaml
+    - policytypes/onap.policies.optimization.Service.yaml
+    - policytypes/onap.policies.optimization.resource.AffinityPolicy.yaml
+    - policytypes/onap.policies.optimization.resource.DistancePolicy.yaml
+    - policytypes/onap.policies.optimization.resource.HpaPolicy.yaml
+    - policytypes/onap.policies.optimization.resource.OptimizationPolicy.yaml
+    - policytypes/onap.policies.optimization.resource.PciPolicy.yaml
+    - policytypes/onap.policies.optimization.service.QueryPolicy.yaml
+    - policytypes/onap.policies.optimization.service.SubscriberPolicy.yaml
+    - policytypes/onap.policies.optimization.resource.Vim_fit.yaml
+    - policytypes/onap.policies.optimization.resource.VnfPolicy.yaml
+    - policytypes/onap.policies.controlloop.guard.Common.yaml
+    - policytypes/onap.policies.controlloop.guard.common.Blacklist.yaml
+    - policytypes/onap.policies.controlloop.guard.common.FrequencyLimiter.yaml
+    - policytypes/onap.policies.controlloop.guard.common.MinMax.yaml
+    - policytypes/onap.policies.controlloop.guard.common.Filter.yaml
+    - policytypes/onap.policies.controlloop.guard.coordination.FirstBlocksSecond.yaml
+    - policytypes/onap.policies.Naming.yaml
+    - policytypes/onap.policies.Match.yaml
+    - policytypes/onap.policies.native.Drools.yaml
+    - policytypes/onap.policies.native.Xacml.yaml
+    - policytypes/onap.policies.native.Apex.yaml
+    - policytypes/onap.policies.controlloop.operational.Common.yaml
+    - policytypes/onap.policies.controlloop.operational.common.Apex.yaml
+    - policytypes/onap.policies.controlloop.operational.common.Drools.yaml
+  policies:
+    - policies/sdnc.policy.naming.input.tosca.yaml
+
+management:
+  endpoints:
+    web:
+      base-path: /
+      exposure:
+        include: health,metrics,prometheus
+      path-mapping.prometheus: metrics
\ No newline at end of file
diff --git a/main/src/test/java/org/onap/policy/api/main/parameters/CommonTestData.java b/main/src/test/java/org/onap/policy/api/main/parameters/CommonTestData.java
deleted file mode 100644 (file)
index 32c4460..0000000
+++ /dev/null
@@ -1,119 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * ONAP Policy API
- * ================================================================================
- * Copyright (C) 2018 Samsung Electronics Co., Ltd. All rights reserved.
- * 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.
- *
- * SPDX-License-Identifier: Apache-2.0
- * ============LICENSE_END=========================================================
- */
-
-package org.onap.policy.api.main.parameters;
-
-import java.io.File;
-import java.io.IOException;
-import java.nio.charset.StandardCharsets;
-import java.nio.file.Files;
-import org.onap.policy.common.endpoints.parameters.RestServerParameters;
-import org.onap.policy.common.utils.coder.Coder;
-import org.onap.policy.common.utils.coder.CoderException;
-import org.onap.policy.common.utils.coder.StandardCoder;
-import org.onap.policy.common.utils.resources.TextFileUtils;
-import org.onap.policy.models.provider.PolicyModelsProviderParameters;
-
-/**
- * Class to hold/create all parameters for test cases.
- *
- */
-public class CommonTestData {
-
-    public static final String API_GROUP_NAME = "ApiGroup";
-
-    /**
-     * Server port, as it appears within the config files.
-     */
-    private static final String REST_SERVER_PORT = "6969";
-
-    private static final String PROVIDER_GROUP_NAME = "PolicyProviderParameterGroup";
-    private static final String PROVIDER_IMPL = "org.onap.policy.models.provider.impl.DatabasePolicyModelsProviderImpl";
-    private static final String DATABASE_DRIVER = "org.h2.Driver";
-    private static final String DATABASE_URL = "jdbc:h2:mem:testdb";
-    private static final String DATABASE_USER = "policy";
-    private static final String DATABASE_PASSWORD = "P01icY";
-    private static final String PERSISTENCE_UNIT = "ToscaConceptTest";
-
-    private Coder coder = new StandardCoder();
-
-    /**
-     * Returns an instance of RestServerParameters for test cases.
-     *
-     * @param isEmpty boolean value to represent that object created should be empty or not
-     * @param port server port
-     * @return the RestServerParameters object
-     */
-    public RestServerParameters getRestServerParameters(final boolean isEmpty, int port) {
-        String fileName = "src/test/resources/parameters/"
-                        + (isEmpty ? "RestServerParametersEmpty" : "RestServerParameters") + ".json";
-        try {
-            String text = new String(Files.readAllBytes(new File(fileName).toPath()), StandardCharsets.UTF_8);
-            text = text.replace("6969", String.valueOf(port));
-            return coder.decode(text, RestServerParameters.class);
-        } catch (CoderException | IOException e) {
-            throw new RuntimeException("cannot read/decode " + fileName, e);
-        }
-    }
-
-    /**
-     * Returns an instance of PolicyModelsProviderParameters for test cases.
-     *
-     * @param isEmpty boolean value to represent that object created should be empty or not
-     * @return the PolicyModelsProviderParameters object
-     */
-    public PolicyModelsProviderParameters getDatabaseProviderParameters(final boolean isEmpty) {
-        final PolicyModelsProviderParameters databaseProviderParameters;
-        if (!isEmpty) {
-            databaseProviderParameters = new PolicyModelsProviderParameters();
-            databaseProviderParameters.setName(PROVIDER_GROUP_NAME);
-            databaseProviderParameters.setImplementation(PROVIDER_IMPL);
-            databaseProviderParameters.setDatabaseDriver(DATABASE_DRIVER);
-            databaseProviderParameters.setDatabaseUrl(DATABASE_URL);
-            databaseProviderParameters.setDatabaseUser(DATABASE_USER);
-            databaseProviderParameters.setDatabasePassword(DATABASE_PASSWORD);
-            databaseProviderParameters.setPersistenceUnit(PERSISTENCE_UNIT);
-        } else {
-            databaseProviderParameters = new PolicyModelsProviderParameters();
-        }
-        return databaseProviderParameters;
-    }
-
-    /**
-     * Copies a source file to a target file, replacing occurrances of
-     * {@link #REST_SERVER_PORT} with the given port number.
-     *
-     * @param source source file name
-     * @param target target file name
-     * @param port port to be substituted
-     * @throws IOException if an error occurs
-     */
-    public void makeParameters(String source, String target, int port) throws IOException {
-        String text = TextFileUtils.getTextFileAsString(source);
-        text = text.replace(REST_SERVER_PORT, String.valueOf(port));
-
-        File file = new File(target);
-        file.deleteOnExit();
-        TextFileUtils.putStringAsFile(text, file);
-    }
-}
diff --git a/main/src/test/java/org/onap/policy/api/main/parameters/TestApiParameterGroup.java b/main/src/test/java/org/onap/policy/api/main/parameters/TestApiParameterGroup.java
deleted file mode 100644 (file)
index 2898248..0000000
+++ /dev/null
@@ -1,152 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * ONAP Policy API
- * ================================================================================
- * Copyright (C) 2018 Samsung Electronics Co., Ltd. All rights reserved.
- * Copyright (C) 2019, 2021 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- * SPDX-License-Identifier: Apache-2.0
- * ============LICENSE_END=========================================================
- */
-
-package org.onap.policy.api.main.parameters;
-
-import static org.assertj.core.api.Assertions.assertThat;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
-
-import java.util.Collections;
-import org.junit.Test;
-import org.onap.policy.common.endpoints.parameters.RestServerParameters;
-import org.onap.policy.common.parameters.ValidationResult;
-import org.onap.policy.models.provider.PolicyModelsProviderParameters;
-
-/**
- * Class to perform unit test of ApiParameterGroup.
- *
- */
-public class TestApiParameterGroup {
-    private static final int PORT = 6969;
-    private CommonTestData commonTestData = new CommonTestData();
-
-    @Test
-    public void testApiParameterGroup() {
-        final RestServerParameters restServerParameters = commonTestData.getRestServerParameters(false, PORT);
-        final PolicyModelsProviderParameters databaseProviderParameters =
-                commonTestData.getDatabaseProviderParameters(false);
-        final ApiParameterGroup apiParameters = new ApiParameterGroup(CommonTestData.API_GROUP_NAME,
-                restServerParameters, databaseProviderParameters, Collections.emptyList(), Collections.emptyList());
-        final ValidationResult validationResult = apiParameters.validate();
-        assertTrue(validationResult.isValid());
-        assertEquals(restServerParameters.getHost(), apiParameters.getRestServerParameters().getHost());
-        assertEquals(restServerParameters.getPort(), apiParameters.getRestServerParameters().getPort());
-        assertEquals(restServerParameters.getUserName(),
-                apiParameters.getRestServerParameters().getUserName());
-        assertEquals(restServerParameters.getPassword(),
-                apiParameters.getRestServerParameters().getPassword());
-        assertEquals(restServerParameters.isHttps(), apiParameters.getRestServerParameters().isHttps());
-        assertEquals(restServerParameters.isAaf(), apiParameters.getRestServerParameters().isAaf());
-        assertEquals(CommonTestData.API_GROUP_NAME, apiParameters.getName());
-        assertTrue(apiParameters.getPreloadPolicyTypes().isEmpty());
-    }
-
-    @Test
-    public void testApiParameterGroup_NullName() {
-        final RestServerParameters restServerParameters = commonTestData.getRestServerParameters(false, PORT);
-        final PolicyModelsProviderParameters databaseProviderParameters =
-                commonTestData.getDatabaseProviderParameters(false);
-        final ApiParameterGroup apiParameters = new ApiParameterGroup(null, restServerParameters,
-                databaseProviderParameters, Collections.emptyList(), Collections.emptyList());
-        final ValidationResult validationResult = apiParameters.validate();
-        assertFalse(validationResult.isValid());
-        assertEquals(null, apiParameters.getName());
-        assertThat(validationResult.getResult()).contains("\"name\" value \"null\" INVALID, is null");
-    }
-
-    @Test
-    public void testApiParameterGroup_EmptyName() {
-        final RestServerParameters restServerParameters = commonTestData.getRestServerParameters(false, PORT);
-        final PolicyModelsProviderParameters databaseProviderParameters =
-                commonTestData.getDatabaseProviderParameters(false);
-        final ApiParameterGroup apiParameters = new ApiParameterGroup("", restServerParameters,
-                databaseProviderParameters, Collections.emptyList(), Collections.emptyList());
-        final ValidationResult validationResult = apiParameters.validate();
-        assertFalse(validationResult.isValid());
-        assertEquals("", apiParameters.getName());
-        assertThat(validationResult.getResult()).contains("\"name\" value \"\" INVALID, is blank");
-    }
-
-    @Test
-    public void testApiParameterGroup_EmptyRestServerParameters() {
-        final RestServerParameters restServerParameters = commonTestData.getRestServerParameters(true, PORT);
-        final PolicyModelsProviderParameters databaseProviderParameters =
-                commonTestData.getDatabaseProviderParameters(false);
-        final ApiParameterGroup apiParameters = new ApiParameterGroup(CommonTestData.API_GROUP_NAME,
-                restServerParameters, databaseProviderParameters, Collections.emptyList(), Collections.emptyList());
-        final ValidationResult validationResult = apiParameters.validate();
-        assertFalse(validationResult.isValid());
-        assertThat(validationResult.getResult())
-                        .contains("\"RestServerParameters\" INVALID, item has status INVALID");
-    }
-
-    @Test
-    public void testApiParameterGroup_NullRestServerParameters() {
-        final RestServerParameters restServerParameters = null;
-        final PolicyModelsProviderParameters databaseProviderParameters =
-                commonTestData.getDatabaseProviderParameters(false);
-        final ApiParameterGroup apiParameters = new ApiParameterGroup(CommonTestData.API_GROUP_NAME,
-                restServerParameters, databaseProviderParameters, Collections.emptyList(), Collections.emptyList());
-        final ValidationResult validationResult = apiParameters.validate();
-        assertFalse(validationResult.isValid());
-        assertThat(validationResult.getResult())
-                        .contains("item \"restServerParameters\" value \"null\" INVALID, is null");
-    }
-
-
-    @Test
-    public void testApiParameterGroup_EmptyDatabaseProviderParameters() {
-        final RestServerParameters restServerParameters = commonTestData.getRestServerParameters(false, PORT);
-        final PolicyModelsProviderParameters databaseProviderParameters =
-                commonTestData.getDatabaseProviderParameters(true);
-        final ApiParameterGroup apiParameters = new ApiParameterGroup(CommonTestData.API_GROUP_NAME,
-                restServerParameters, databaseProviderParameters, Collections.emptyList(), Collections.emptyList());
-        final ValidationResult validationResult = apiParameters.validate();
-        assertFalse(validationResult.isValid());
-        assertThat(validationResult.getResult())
-                        .contains("\"PolicyModelsProviderParameters\" INVALID, item has status INVALID");
-    }
-
-    @Test
-    public void testApiParameterGroup_NullDatabaseProviderParameters() {
-        final RestServerParameters restServerParameters = commonTestData.getRestServerParameters(false, PORT);
-        final PolicyModelsProviderParameters databaseProviderParameters = null;
-        final ApiParameterGroup apiParameters = new ApiParameterGroup(CommonTestData.API_GROUP_NAME,
-                restServerParameters, databaseProviderParameters, Collections.emptyList(), Collections.emptyList());
-        final ValidationResult validationResult = apiParameters.validate();
-        assertFalse(validationResult.isValid());
-        assertThat(validationResult.getResult())
-            .contains("item \"databaseProviderParameters\" value \"null\" INVALID, is null");
-    }
-
-    @Test
-    public void testApiParameterGroup_SetName() {
-        final ApiParameterGroup apiParameters = new ApiParameterGroup(CommonTestData.API_GROUP_NAME,
-                null, null, Collections.emptyList(), Collections.emptyList());
-        assertEquals(CommonTestData.API_GROUP_NAME, apiParameters.getName());
-        apiParameters.setName("SampleName");
-        assertEquals("SampleName", apiParameters.getName());
-    }
-}
diff --git a/main/src/test/java/org/onap/policy/api/main/parameters/TestApiParameterHandler.java b/main/src/test/java/org/onap/policy/api/main/parameters/TestApiParameterHandler.java
deleted file mode 100644 (file)
index 26ecd02..0000000
+++ /dev/null
@@ -1,175 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- *  Copyright (C) 2018 Samsung Electronics Co., Ltd. All rights reserved.
- *  Copyright (C) 2019, 2021 AT&T Intellectual Property. All rights reserved.
- *  Modifications Copyright (C) 2022 Nordix Foundation.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- * SPDX-License-Identifier: Apache-2.0
- * ============LICENSE_END=========================================================
- */
-
-package org.onap.policy.api.main.parameters;
-
-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 org.junit.Test;
-import org.onap.policy.api.main.exception.PolicyApiException;
-import org.onap.policy.api.main.startstop.ApiCommandLineArguments;
-import org.onap.policy.common.utils.cmd.CommandLineException;
-
-/**
- * Class to perform unit test of ApiParameterHandler.
- *
- */
-public class TestApiParameterHandler {
-    @Test
-    public void testParameterHandlerNoParameterFile() throws PolicyApiException, CommandLineException {
-        final String[] noArgumentString = {"-c", "parameters/NoParameterFile.json"};
-        final ApiCommandLineArguments noArguments = new ApiCommandLineArguments();
-        noArguments.parse(noArgumentString);
-
-        try {
-            new ApiParameterHandler().getParameters(noArguments);
-            fail("test should throw an exception here");
-        } catch (final Exception e) {
-            assertTrue(e.getMessage().contains("FileNotFoundException"));
-        }
-    }
-
-    @Test
-    public void testParameterHandlerEmptyParameters() throws PolicyApiException, CommandLineException {
-        final String[] emptyArgumentString = {"-c", "parameters/EmptyParameters.json"};
-        final ApiCommandLineArguments emptyArguments = new ApiCommandLineArguments();
-        emptyArguments.parse(emptyArgumentString);
-
-        try {
-            new ApiParameterHandler().getParameters(emptyArguments);
-            fail("test should throw an exception here");
-        } catch (final Exception e) {
-            assertEquals("no parameters found in \"parameters/EmptyParameters.json\"", e.getMessage());
-        }
-    }
-
-    @Test
-    public void testParameterHandlerBadParameters() throws PolicyApiException, CommandLineException {
-        final String[] badArgumentString = {"-c", "parameters/BadParameters.json"};
-        final ApiCommandLineArguments badArguments = new ApiCommandLineArguments();
-        badArguments.parse(badArgumentString);
-
-        try {
-            new ApiParameterHandler().getParameters(badArguments);
-            fail("test should throw an exception here");
-        } catch (final Exception e) {
-            assertEquals("error reading parameters from \"parameters/BadParameters.json\"\n"
-                    + "(JsonSyntaxException):java.lang.IllegalStateException: "
-                    + "Expected a string but was BEGIN_ARRAY at line 2 column 15 path $.name", e.getMessage());
-        }
-    }
-
-    @Test
-    public void testParameterHandlerInvalidParameters() throws PolicyApiException, CommandLineException {
-        final String[] invalidArgumentString = {"-c", "parameters/InvalidParameters.json"};
-        final ApiCommandLineArguments invalidArguments = new ApiCommandLineArguments();
-        invalidArguments.parse(invalidArgumentString);
-
-        try {
-            new ApiParameterHandler().getParameters(invalidArguments);
-            fail("test should throw an exception here");
-        } catch (final Exception e) {
-            assertEquals("error reading parameters from \"parameters/InvalidParameters.json\"\n"
-                    + "(JsonSyntaxException):java.lang.IllegalStateException: "
-                    + "Expected a string but was BEGIN_ARRAY at line 2 column 15 path $.name", e.getMessage());
-        }
-    }
-
-    @Test
-    public void testParameterHandlerNoParameters() throws PolicyApiException, CommandLineException {
-        final String[] noArgumentString = {"-c", "parameters/NoParameters.json"};
-        final ApiCommandLineArguments noArguments = new ApiCommandLineArguments();
-        noArguments.parse(noArgumentString);
-
-        assertThatThrownBy(() -> new ApiParameterHandler().getParameters(noArguments))
-            .hasMessageContaining("\"name\"", "is null");
-    }
-
-    @Test
-    public void testParameterHandlerMinumumParameters() throws PolicyApiException, CommandLineException {
-        final String[] minArgumentString = {"-c", "parameters/MinimumParameters.json"};
-        final ApiCommandLineArguments minArguments = new ApiCommandLineArguments();
-        minArguments.parse(minArgumentString);
-        final ApiParameterGroup parGroup = new ApiParameterHandler().getParameters(minArguments);
-        assertEquals(CommonTestData.API_GROUP_NAME, parGroup.getName());
-    }
-
-    @Test
-    public void testApiParameterGroup() throws PolicyApiException, CommandLineException {
-        final String[] apiConfigParameters = {"-c", "parameters/ApiConfigParameters_Https.json"};
-        final ApiCommandLineArguments arguments = new ApiCommandLineArguments();
-        arguments.parse(apiConfigParameters);
-        final ApiParameterGroup parGroup = new ApiParameterHandler().getParameters(arguments);
-        assertTrue(arguments.checkSetConfigurationFilePath());
-        assertEquals(CommonTestData.API_GROUP_NAME, parGroup.getName());
-    }
-
-    @Test
-    public void testApiParameterGroup_Postgres() throws PolicyApiException, CommandLineException {
-        final String[] apiConfigParameters = {"-c", "parameters/ApiConfigParameters_Postgres.json"};
-        final ApiCommandLineArguments arguments = new ApiCommandLineArguments();
-        arguments.parse(apiConfigParameters);
-        final ApiParameterGroup parGroup = new ApiParameterHandler().getParameters(arguments);
-        assertTrue(arguments.checkSetConfigurationFilePath());
-        assertEquals(CommonTestData.API_GROUP_NAME, parGroup.getName());
-    }
-
-    @Test
-    public void testApiParameterGroup_Invalid() throws PolicyApiException, CommandLineException {
-        final String[] apiConfigParameters = {"-c", "parameters/ApiConfigParameters_InvalidName.json"};
-        final ApiCommandLineArguments arguments = new ApiCommandLineArguments();
-        arguments.parse(apiConfigParameters);
-
-        assertThatThrownBy(() -> new ApiParameterHandler().getParameters(arguments)).hasMessageContaining("\"name\"",
-                        "is null");
-    }
-
-    @Test
-    public void testApiVersion() throws PolicyApiException, CommandLineException {
-        final String[] apiConfigParameters = {"-v"};
-        final ApiCommandLineArguments arguments = new ApiCommandLineArguments();
-        final String version = arguments.parse(apiConfigParameters);
-        assertTrue(version.startsWith("ONAP Policy Framework Api Service"));
-    }
-
-    @Test
-    public void testApiHelp() throws PolicyApiException, CommandLineException {
-        final String[] apiConfigParameters = {"-h"};
-        final ApiCommandLineArguments arguments = new ApiCommandLineArguments();
-        final String help = arguments.parse(apiConfigParameters);
-        assertTrue(help.startsWith("usage:"));
-    }
-
-    @Test
-    public void testApiInvalidOption() throws PolicyApiException {
-        final String[] apiConfigParameters = {"-d"};
-        final ApiCommandLineArguments arguments = new ApiCommandLineArguments();
-        try {
-            arguments.parse(apiConfigParameters);
-        } catch (final Exception exp) {
-            assertTrue(exp.getMessage().startsWith("invalid command line arguments specified"));
-        }
-    }
-}
index 9f22ff2..ae654c6 100644 (file)
@@ -3,7 +3,7 @@
  *  Copyright (C) 2018 Samsung Electronics Co., Ltd. All rights reserved.
  *  Copyright (C) 2019-2021 AT&T Intellectual Property. All rights reserved.
  *  Modifications Copyright (C) 2019-2020 Nordix Foundation.
- *  Modifications Copyright (C) 2020 Bell Canada.
+ *  Modifications Copyright (C) 2020-2022 Bell Canada. All rights reserved.
  * ================================================================================
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -32,10 +32,8 @@ import static org.junit.Assert.assertNull;
 import java.io.File;
 import java.io.IOException;
 import java.security.SecureRandom;
-import java.util.Collections;
 import java.util.List;
 import java.util.Map;
-import java.util.Properties;
 import javax.net.ssl.SSLContext;
 import javax.net.ssl.TrustManager;
 import javax.ws.rs.client.Client;
@@ -47,34 +45,40 @@ import javax.ws.rs.core.Response;
 import javax.ws.rs.core.Response.Status;
 import org.glassfish.jersey.client.ClientProperties;
 import org.glassfish.jersey.client.authentication.HttpAuthenticationFeature;
-import org.junit.AfterClass;
 import org.junit.BeforeClass;
 import org.junit.Test;
-import org.onap.policy.api.main.parameters.ApiParameterGroup;
-import org.onap.policy.api.main.parameters.CommonTestData;
-import org.onap.policy.api.main.rest.provider.PolicyProvider;
-import org.onap.policy.api.main.rest.provider.PolicyTypeProvider;
-import org.onap.policy.api.main.startstop.Main;
+import org.junit.runner.RunWith;
+import org.onap.policy.api.main.PolicyApiApplication;
 import org.onap.policy.common.endpoints.http.server.YamlMessageBodyHandler;
 import org.onap.policy.common.endpoints.report.HealthCheckReport;
 import org.onap.policy.common.gson.GsonMessageBodyHandler;
-import org.onap.policy.common.parameters.ParameterService;
 import org.onap.policy.common.utils.coder.StandardCoder;
 import org.onap.policy.common.utils.coder.StandardYamlCoder;
 import org.onap.policy.common.utils.network.NetworkUtil;
 import org.onap.policy.common.utils.resources.ResourceUtils;
 import org.onap.policy.common.utils.resources.TextFileUtils;
 import org.onap.policy.common.utils.security.SelfSignedKeyStore;
-import org.onap.policy.models.base.PfModelException;
 import org.onap.policy.models.errors.concepts.ErrorResponse;
-import org.onap.policy.models.provider.PolicyModelsProviderParameters;
 import org.onap.policy.models.tosca.authorative.concepts.ToscaServiceTemplate;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.test.context.SpringBootTest;
+import org.springframework.boot.web.server.LocalServerPort;
+import org.springframework.test.annotation.DirtiesContext;
+import org.springframework.test.annotation.DirtiesContext.ClassMode;
+import org.springframework.test.context.ActiveProfiles;
+import org.springframework.test.context.DynamicPropertyRegistry;
+import org.springframework.test.context.DynamicPropertySource;
+import org.springframework.test.context.junit4.SpringRunner;
 
 /**
  * Class to perform unit test of {@link ApiRestController}.
  *
  * @author Chenfei Gao (cgao@research.att.com)
  */
+@RunWith(SpringRunner.class)
+@SpringBootTest(classes = PolicyApiApplication.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
+@ActiveProfiles("test")
+@DirtiesContext(classMode = ClassMode.AFTER_CLASS)
 public class TestApiRestServer {
 
     private static final String ALIVE = "alive";
@@ -156,70 +160,37 @@ public class TestApiRestServer {
         "policies/vCPE.policy.operational.input.tosca.yaml";
 
     private static final String POLICIES_VCPE_VERSION1 = "policies/onap.restart.tca/versions/1.0.0";
-
-    private static PolicyModelsProviderParameters providerParams;
-    private static ApiParameterGroup apiParamGroup;
-    private static PolicyProvider policyProvider;
-    private static PolicyTypeProvider policyTypeProvider;
-
     // @formatter:on
 
     private static final StandardCoder standardCoder = new StandardCoder();
+    private static StandardYamlCoder standardYamlCoder = new StandardYamlCoder();
+    private static SelfSignedKeyStore keystore;
 
-    private static int apiPort;
-    private static Main apiMain;
+    @LocalServerPort
+    private int apiPort;
 
-    private static StandardYamlCoder standardYamlCoder = new StandardYamlCoder();
+    @Autowired
+    private ApiStatisticsManager mgr;
 
     /**
      * Initializes parameters and set up test environment.
      *
-     * @throws PfModelException the PfModel parsing exception
      * @throws IOException on I/O exceptions
      * @throws InterruptedException if interrupted
      */
     @BeforeClass
-    public static void setupParameters() throws PfModelException, IOException, InterruptedException {
-        providerParams = new PolicyModelsProviderParameters();
-        // H2, use "org.mariadb.jdbc.Driver" and "jdbc:mariadb://localhost:3306/policy" for locally installed MariaDB
-        providerParams.setDatabaseDriver("org.h2.Driver");
-        providerParams.setDatabaseUrl("jdbc:h2:mem:testdb");
-        providerParams.setDatabaseUser("policy");
-        providerParams.setDatabasePassword("P01icY");
-        providerParams.setPersistenceUnit("ToscaConceptTest");
-        apiParamGroup = new ApiParameterGroup("ApiGroup", null, providerParams, Collections.emptyList(),
-                Collections.emptyList());
-        ParameterService.register(apiParamGroup, true);
-
-        policyTypeProvider = new PolicyTypeProvider();
-        policyProvider = new PolicyProvider();
-
-        apiPort = NetworkUtil.allocPort();
-
-        final String[] apiConfigParameters = new String[2];
-        final Properties systemProps = System.getProperties();
-        systemProps.put("javax.net.ssl.keyStore", new SelfSignedKeyStore().getKeystoreName());
-        systemProps.put("javax.net.ssl.keyStorePassword", SelfSignedKeyStore.KEYSTORE_PASSWORD);
-        System.setProperties(systemProps);
-        new CommonTestData().makeParameters("src/test/resources/parameters/ApiConfigParameters_Https.json",
-                "src/test/resources/parameters/ApiConfigParameters_HttpsXXX.json", apiPort);
-        apiConfigParameters[0] = "-c";
-        apiConfigParameters[1] = "src/test/resources/parameters/ApiConfigParameters_HttpsXXX.json";
-
-        apiMain = new Main(apiConfigParameters);
+    public static void setupParameters() throws IOException, InterruptedException {
+        keystore = new SelfSignedKeyStore();
     }
 
-    /**
-     * Method for cleanup after each test.
-     */
-    @AfterClass
-    public static void teardown() throws Exception {
-        policyTypeProvider.close();
-        policyProvider.close();
-
-        if (apiMain != null) {
-            apiMain.shutdown();
-        }
+    @DynamicPropertySource
+    static void registerPgProperties(DynamicPropertyRegistry registry) {
+        registry.add("server.ssl.enabled", () -> "true");
+        registry.add("server.ssl.key-store", () -> keystore.getKeystoreName());
+        registry.add("server.ssl.key-store-password", () -> SelfSignedKeyStore.KEYSTORE_PASSWORD);
+        registry.add("server.ssl.key-store-type", () -> "PKCS12");
+        registry.add("server.ssl.key-alias", () -> "policy@policy.onap.org");
+        registry.add("server.ssl.key-password", () -> SelfSignedKeyStore.PRIVATE_KEY_PASSWORD);
     }
 
     @Test
@@ -378,7 +349,7 @@ public class TestApiRestServer {
         invocationBuilder = sendHttpsRequest(STATISTICS_ENDPOINT, mediaType);
         report = invocationBuilder.get(StatisticsReport.class);
         validateStatisticsReport(report, 200);
-        ApiStatisticsManager.resetAllStatistics();
+        // ApiStatisticsManager.resetAllStatistics();
     }
 
     @Test
@@ -798,8 +769,6 @@ public class TestApiRestServer {
     }
 
     private void updateApiStatistics() {
-        var mgr = ApiStatisticsManager.getInstance();
-
         mgr.updateTotalApiCallCount();
         mgr.updateApiCallSuccessCount();
         mgr.updateApiCallFailureCount();
@@ -831,4 +800,4 @@ public class TestApiRestServer {
         assertEquals(code, report.getCode());
         assertEquals(message, report.getMessage());
     }
-}
+}
\ No newline at end of file
index 5f5c586..bc67d21 100644 (file)
@@ -3,7 +3,7 @@
  * ONAP Policy API
  * ================================================================================
  * Copyright (C) 2019 IBM.
- * Modifications Copyright (C) 2020 Bell Canada.
+ * Modifications Copyright (C) 2020-2022 Bell Canada.
  * Modifications Copyright (C) 2021 AT&T Intellectual Property. All rights reserved.
  * ================================================================================
  * Licensed under the Apache License, Version 2.0 (the "License");
@@ -27,13 +27,23 @@ package org.onap.policy.api.main.rest;
 import static org.junit.Assert.assertEquals;
 
 import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.onap.policy.api.main.PolicyApiApplication;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.test.context.SpringBootTest;
+import org.springframework.test.context.ActiveProfiles;
+import org.springframework.test.context.junit4.SpringRunner;
 
+@RunWith(SpringRunner.class)
+@SpringBootTest(classes = PolicyApiApplication.class)
+@ActiveProfiles("test")
 public class TestApiStatisticsManager {
 
+    @Autowired
+    private ApiStatisticsManager mgr = new ApiStatisticsManager();
+
     @Test
     public void testUpdateMethods() {
-        var mgr = new ApiStatisticsManager();
-
         assertEquals(1, mgr.updateTotalApiCallCount());
         assertEquals(1, mgr.updateApiCallSuccessCount());
         assertEquals(1, mgr.updateApiCallFailureCount());
@@ -56,4 +66,4 @@ public class TestApiStatisticsManager {
         assertEquals(1, mgr.updatePolicyTypeDeleteSuccessCount());
         assertEquals(1, mgr.updatePolicyTypeDeleteFailureCount());
     }
-}
+}
\ No newline at end of file
index dc92148..2213bbf 100644 (file)
@@ -4,6 +4,7 @@
  * ================================================================================
  * Copyright (C) 2019-2020 AT&T Intellectual Property. All rights reserved.
  * Modifications Copyright (C) 2019 Nordix Foundation.
+ * Modifications Copyright (C) 2022 Bell Canada. All rights reserved.
  * ================================================================================
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
 
 package org.onap.policy.api.main.rest;
 
+import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertSame;
 
 import java.util.UUID;
-import javax.ws.rs.core.Response;
-import javax.ws.rs.core.Response.ResponseBuilder;
 import org.junit.Test;
+import org.springframework.http.ResponseEntity;
 
 /**
  * Class to perform unit testing of CommonRestController.
@@ -40,9 +40,8 @@ public class TestCommonRestController {
     @Test
     public void testAddLoggingHeaders() {
         UUID requestId = UUID.randomUUID();
-        ResponseBuilder rb =
-                crc.addLoggingHeaders(crc.addVersionControlHeaders(Response.status(Response.Status.OK)), requestId);
-        assertSame(rb, rb.header("X-ONAP-RequestID", requestId));
+        ResponseEntity<Void> rb = crc.makeOkResponse(requestId, null);
+        assertEquals(requestId.toString(), rb.getHeaders().getFirst("X-ONAP-RequestID"));
     }
 
     /*
@@ -52,4 +51,4 @@ public class TestCommonRestController {
     public void testToJsonNull() {
         assertNull(crc.toJson(null));
     }
-}
+}
\ No newline at end of file
index e47a4ce..ad394e3 100644 (file)
@@ -4,7 +4,7 @@
  * ================================================================================
  * Copyright (C) 2019-2021 AT&T Intellectual Property. All rights reserved.
  * Modifications Copyright (C) 2019-2021 Nordix Foundation.
- * Modifications Copyright (C) 2020 Bell Canada.
+ * Modifications Copyright (C) 2020,2022 Bell Canada.
  * ================================================================================
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -33,13 +33,11 @@ import static org.junit.Assert.assertNotNull;
 import static org.junit.Assert.fail;
 
 import java.util.ArrayList;
-import java.util.Collections;
 import java.util.List;
-import org.junit.After;
-import org.junit.Before;
+import org.junit.Ignore;
 import org.junit.Test;
-import org.onap.policy.api.main.parameters.ApiParameterGroup;
-import org.onap.policy.common.parameters.ParameterService;
+import org.junit.runner.RunWith;
+import org.onap.policy.api.main.PolicyApiApplication;
 import org.onap.policy.common.utils.coder.CoderException;
 import org.onap.policy.common.utils.coder.StandardCoder;
 import org.onap.policy.common.utils.coder.StandardYamlCoder;
@@ -52,24 +50,30 @@ import org.onap.policy.models.pdp.concepts.PdpSubGroup;
 import org.onap.policy.models.pdp.enums.PdpHealthStatus;
 import org.onap.policy.models.pdp.enums.PdpState;
 import org.onap.policy.models.provider.PolicyModelsProvider;
-import org.onap.policy.models.provider.PolicyModelsProviderFactory;
-import org.onap.policy.models.provider.PolicyModelsProviderParameters;
 import org.onap.policy.models.tosca.authorative.concepts.ToscaConceptIdentifier;
 import org.onap.policy.models.tosca.authorative.concepts.ToscaServiceTemplate;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.test.context.SpringBootTest;
+import org.springframework.test.annotation.DirtiesContext;
+import org.springframework.test.annotation.DirtiesContext.ClassMode;
+import org.springframework.test.context.ActiveProfiles;
+import org.springframework.test.context.junit4.SpringRunner;
 
 /**
  * This class performs unit test of {@link PolicyProvider}.
  *
  * @author Chenfei Gao (cgao@research.att.com)
  */
+// Provider classes will be obsolete upon migration to Hibernate
+@Ignore
+@RunWith(SpringRunner.class)
+@SpringBootTest(classes = PolicyApiApplication.class, properties = {"database.initialize=false"})
+@ActiveProfiles("test")
+@DirtiesContext(classMode = ClassMode.AFTER_EACH_TEST_METHOD)
 public class TestPolicyProvider {
 
-    private static PolicyProvider policyProvider;
-    private static PolicyTypeProvider policyTypeProvider;
-    private static PolicyModelsProviderParameters providerParams;
-    private static ApiParameterGroup apiParamGroup;
-    private static StandardCoder standardCoder;
-    private static StandardYamlCoder standardYamlCoder;
+    private static StandardCoder standardCoder = new StandardCoder();
+    private static StandardYamlCoder standardYamlCoder = new StandardYamlCoder();
 
     private static final String POLICY_RESOURCE = "policies/vCPE.policy.monitoring.input.tosca.json";
     private static final String POLICY_TYPE_RESOURCE = "policytypes/onap.policies.monitoring.tcagen2.yaml";
@@ -88,41 +92,12 @@ public class TestPolicyProvider {
     private static final String POLICY_RESOURCE_OPERATIONAL = "policies/vCPE.policy.operational.input.tosca.json";
     private static final String POLICY_TYPE_OPERATIONAL_DROOLS = "onap.policies.controlloop.operational.common.Drools";
 
-    /**
-     * Initializes parameters.
-     *
-     * @throws PfModelException the PfModel parsing exception
-     */
-    @Before
-    public void setupParameters() throws PfModelException {
-
-        standardCoder = new StandardCoder();
-        standardYamlCoder = new StandardYamlCoder();
-        providerParams = new PolicyModelsProviderParameters();
-        providerParams.setDatabaseDriver("org.h2.Driver");
-        providerParams.setDatabaseUrl("jdbc:h2:mem:testdb");
-        providerParams.setDatabaseUser("policy");
-        providerParams.setDatabasePassword("P01icY");
-        providerParams.setPersistenceUnit("ToscaConceptTest");
-        apiParamGroup = new ApiParameterGroup("ApiGroup", null, providerParams, Collections.emptyList(),
-                Collections.emptyList());
-        ParameterService.register(apiParamGroup, true);
-        policyTypeProvider = new PolicyTypeProvider();
-        policyProvider = new PolicyProvider();
-    }
-
-    /**
-     * Closes up DB connections and deregisters API parameter group.
-     *
-     * @throws PfModelException the PfModel parsing exception
-     */
-    @After
-    public void tearDown() throws PfModelException {
-
-        policyTypeProvider.close();
-        policyProvider.close();
-        ParameterService.deregister(apiParamGroup);
-    }
+    @Autowired
+    private PolicyProvider policyProvider;
+    @Autowired
+    private PolicyTypeProvider policyTypeProvider;
+    @Autowired
+    private PolicyModelsProvider databaseProvider;
 
     @Test
     public void testFetchPolicies() {
@@ -159,8 +134,7 @@ public class TestPolicyProvider {
         String policyTypeVersion = "1.0.0";
         String policyTypeId = "onap.policies.monitoring.cdap.tca.hi.lo.app";
 
-        try (PolicyModelsProvider databaseProvider =
-                new PolicyModelsProviderFactory().createPolicyModelsProvider(providerParams)) {
+        try {
             assertEquals(0, databaseProvider.getPdpGroups("name").size());
             assertEquals(0, databaseProvider.getFilteredPdpGroups(PdpGroupFilter.builder().build()).size());
 
@@ -511,4 +485,4 @@ public class TestPolicyProvider {
         assertThatThrownBy(() -> policyProvider.deletePolicy(null, null, "onap.restart.tca.unavailable", "1.0.0"))
                 .hasMessageContaining("not found");
     }
-}
+}
\ No newline at end of file
index 355f3d4..6b7630c 100644 (file)
@@ -4,7 +4,7 @@
  * ================================================================================
  * Copyright (C) 2019-2021 AT&T Intellectual Property. All rights reserved.
  * Modifications Copyright (C) 2019-2021 Nordix Foundation.
- * Modifications Copyright (C) 2020 Bell Canada. All rights reserved.
+ * Modifications Copyright (C) 2020-2022 Bell Canada. All rights reserved.
  * ================================================================================
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -29,32 +29,43 @@ import static org.assertj.core.api.Assertions.assertThatThrownBy;
 import static org.junit.Assert.assertFalse;
 import static org.junit.Assert.assertNotNull;
 
-import java.util.Collections;
-import org.junit.AfterClass;
-import org.junit.BeforeClass;
+import org.junit.Ignore;
 import org.junit.Test;
-import org.onap.policy.api.main.parameters.ApiParameterGroup;
-import org.onap.policy.common.parameters.ParameterService;
+import org.junit.runner.RunWith;
+import org.onap.policy.api.main.PolicyApiApplication;
 import org.onap.policy.common.utils.coder.CoderException;
 import org.onap.policy.common.utils.coder.StandardYamlCoder;
 import org.onap.policy.common.utils.resources.ResourceUtils;
 import org.onap.policy.models.base.PfModelException;
-import org.onap.policy.models.provider.PolicyModelsProviderParameters;
 import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicyType;
 import org.onap.policy.models.tosca.authorative.concepts.ToscaServiceTemplate;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.test.context.SpringBootTest;
+import org.springframework.test.annotation.DirtiesContext;
+import org.springframework.test.annotation.DirtiesContext.ClassMode;
+import org.springframework.test.context.ActiveProfiles;
+import org.springframework.test.context.junit4.SpringRunner;
 
 /**
  * This class performs unit test of {@link PolicyTypeProvider}.
  *
  * @author Chenfei Gao (cgao@research.att.com)
  */
+// Provider classes will be obsolete upon migration to Hibernate
+@Ignore
+@RunWith(SpringRunner.class)
+@SpringBootTest(classes = PolicyApiApplication.class, properties = {"database.initialize=false"})
+@ActiveProfiles("test")
+@DirtiesContext(classMode = ClassMode.AFTER_CLASS)
 public class TestPolicyTypeProvider {
 
-    private static PolicyTypeProvider policyTypeProvider;
-    private static PolicyProvider policyProvider;
-    private static PolicyModelsProviderParameters providerParams;
-    private static ApiParameterGroup apiParamGroup;
-    private static StandardYamlCoder standardYamlCoder;
+    private static StandardYamlCoder standardYamlCoder = new StandardYamlCoder();
+
+    @Autowired
+    private PolicyProvider policyProvider;
+
+    @Autowired
+    private PolicyTypeProvider policyTypeProvider;
 
     private static final String POLICY_TYPE_VERSION = "1.0.0";
 
@@ -74,41 +85,6 @@ public class TestPolicyTypeProvider {
     private static final String POLICY_TYPE_OPERATIONAL_APEX = "onap.policies.controlloop.operational.common.Apex";
     private static final String POLICY_TYPE_OPERATIONAL_DROOLS = "onap.policies.controlloop.operational.common.Drools";
 
-    /**
-     * Initializes parameters.
-     *
-     * @throws PfModelException the PfModel parsing exception
-     */
-    @BeforeClass
-    public static void setupParameters() throws PfModelException {
-
-        standardYamlCoder = new StandardYamlCoder();
-        providerParams = new PolicyModelsProviderParameters();
-        providerParams.setDatabaseDriver("org.h2.Driver");
-        providerParams.setDatabaseUrl("jdbc:h2:mem:testdb");
-        providerParams.setDatabaseUser("policy");
-        providerParams.setDatabasePassword("P01icY");
-        providerParams.setPersistenceUnit("ToscaConceptTest");
-        apiParamGroup = new ApiParameterGroup("ApiGroup", null, providerParams, Collections.emptyList(),
-                Collections.emptyList());
-        ParameterService.register(apiParamGroup, true);
-        policyTypeProvider = new PolicyTypeProvider();
-        policyProvider = new PolicyProvider();
-    }
-
-    /**
-     * Closes up DB connections and deregisters API parameter group.
-     *
-     * @throws PfModelException the PfModel parsing exception
-     */
-    @AfterClass
-    public static void tearDown() throws PfModelException {
-
-        policyTypeProvider.close();
-        policyProvider.close();
-        ParameterService.deregister(apiParamGroup);
-    }
-
     @Test
     public void testFetchPolicyTypes() throws Exception {
 
@@ -220,4 +196,4 @@ public class TestPolicyTypeProvider {
             policyTypeProvider.deletePolicyType("onap.policies.monitoring.tcagen2", "1.0.0");
         }).hasMessage("policy type onap.policies.monitoring.tcagen2:1.0.0 not found");
     }
-}
+}
\ No newline at end of file
index f7e43b8..aa86d73 100644 (file)
@@ -3,6 +3,7 @@
  * ONAP
  * ================================================================================
  * Copyright (C) 2020-2021 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2022 Bell Canada. All rights reserved.
  * ================================================================================
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
 package org.onap.policy.api.main.startstop;
 
 import static org.assertj.core.api.Assertions.assertThatCode;
-import static org.junit.Assert.fail;
 
-import java.io.File;
-import org.junit.AfterClass;
-import org.junit.BeforeClass;
 import org.junit.Test;
-import org.onap.policy.api.main.exception.PolicyApiException;
-import org.onap.policy.api.main.parameters.ApiParameterGroup;
-import org.onap.policy.api.main.parameters.CommonTestData;
-import org.onap.policy.common.parameters.ValidationResult;
-import org.onap.policy.common.utils.coder.StandardCoder;
-import org.onap.policy.models.provider.PolicyModelsProvider;
-import org.onap.policy.models.provider.PolicyModelsProviderFactory;
-
+import org.junit.runner.RunWith;
+import org.onap.policy.api.main.PolicyApiApplication;
+import org.onap.policy.api.main.config.PolicyPreloadConfig;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.test.context.SpringBootTest;
+import org.springframework.test.annotation.DirtiesContext;
+import org.springframework.test.context.ActiveProfiles;
+import org.springframework.test.context.junit4.SpringRunner;
+
+@RunWith(SpringRunner.class)
+@SpringBootTest(classes = PolicyApiApplication.class)
+@ActiveProfiles("test")
+@DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_CLASS)
 public class ApiDatabaseInitializerTest {
-    private static final String PARAM_FILE = "src/test/resources/parameters/ApiConfigParameters_Https.json";
-    private static final CommonTestData COMMON_TEST_DATA = new CommonTestData();
-    private static ApiParameterGroup params;
-    private static PolicyModelsProvider provider;
-
-    /**
-     * Creates the DB and keeps it open.
-     */
-    @BeforeClass
-    public static void setUpBeforeClass() throws Exception {
-        COMMON_TEST_DATA.makeParameters(PARAM_FILE, "src/test/resources/parameters/ApiConfigParametersXXX.json", 6969);
 
-        params = new StandardCoder().decode(new File(PARAM_FILE), ApiParameterGroup.class);
-        ValidationResult result = params.validate();
-        if (!result.isValid()) {
-            fail(result.getResult());
-        }
+    @Autowired
+    private PolicyPreloadConfig params;
 
-        // keep the DB open until the test completes
-        provider = new PolicyModelsProviderFactory().createPolicyModelsProvider(params.getDatabaseProviderParameters());
-    }
-
-    @AfterClass
-    public static void tearDownAfterClass() throws Exception {
-        provider.close();
-    }
+    @Autowired
+    private ApiDatabaseInitializer adi;
 
     @Test
-    public void testInitializeApiDatabase() throws PolicyApiException {
-        ApiDatabaseInitializer adi = new ApiDatabaseInitializer();
-        assertThatCode(() -> adi.initializeApiDatabase(params)).doesNotThrowAnyException();
+    public void testInitializeApiDatabase() {
+        assertThatCode(() -> adi.initializeApiDatabase(params.getPolicyTypes(),
+                params.getPolicies())).doesNotThrowAnyException();
 
         // invoke it again - should still be OK
-        assertThatCode(() -> adi.initializeApiDatabase(params)).doesNotThrowAnyException();
+        assertThatCode(() -> adi.initializeApiDatabase(params.getPolicyTypes(),
+                params.getPolicies())).doesNotThrowAnyException();
     }
-}
+}
\ No newline at end of file
diff --git a/main/src/test/java/org/onap/policy/api/main/startstop/TestApiActivator.java b/main/src/test/java/org/onap/policy/api/main/startstop/TestApiActivator.java
deleted file mode 100644 (file)
index ccd0f14..0000000
+++ /dev/null
@@ -1,54 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- *  Copyright (C) 2018 Samsung Electronics Co., Ltd. All rights reserved.
- *  Modifications Copyright (C) 2019, 2021 AT&T Intellectual Property. All rights reserved.
- *  Modifications Copyright (C) 2021 Bell Canada. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- * SPDX-License-Identifier: Apache-2.0
- * ============LICENSE_END=========================================================
- */
-
-package org.onap.policy.api.main.startstop;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
-
-import org.junit.Test;
-import org.onap.policy.api.main.parameters.ApiParameterGroup;
-import org.onap.policy.api.main.parameters.ApiParameterHandler;
-import org.onap.policy.api.main.parameters.CommonTestData;
-import org.onap.policy.common.utils.network.NetworkUtil;
-
-/**
- * Class to perform unit test of ApiActivator.
- *
- */
-public class TestApiActivator {
-    private static final CommonTestData COMMON_TEST_DATA = new CommonTestData();
-
-    @Test
-    public void testApiActivator() throws Exception {
-        COMMON_TEST_DATA.makeParameters("src/test/resources/parameters/ApiConfigParameters_Https.json",
-                "src/test/resources/parameters/ApiConfigParametersXXX.json", NetworkUtil.allocPort());
-        final String[] apiConfigParameters = {"-c", "src/test/resources/parameters/ApiConfigParametersXXX.json"};
-        final ApiCommandLineArguments arguments = new ApiCommandLineArguments(apiConfigParameters);
-        final ApiParameterGroup parGroup = new ApiParameterHandler().getParameters(arguments);
-        final ApiActivator activator = new ApiActivator(parGroup);
-        activator.initialize();
-        assertTrue(activator.getParameterGroup().isValid());
-        assertEquals(CommonTestData.API_GROUP_NAME, activator.getParameterGroup().getName());
-        activator.terminate();
-    }
-}
diff --git a/main/src/test/java/org/onap/policy/api/main/startstop/TestApiCommandLineArguments.java b/main/src/test/java/org/onap/policy/api/main/startstop/TestApiCommandLineArguments.java
deleted file mode 100644 (file)
index 8d3c42c..0000000
+++ /dev/null
@@ -1,68 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * ONAP Policy API
- * ================================================================================
- * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
- * Modifications Copyright (C) 2021 Nordix Foundation.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- * SPDX-License-Identifier: Apache-2.0
- * ============LICENSE_END=========================================================
- */
-
-package org.onap.policy.api.main.startstop;
-
-import static org.assertj.core.api.Assertions.assertThat;
-import static org.assertj.core.api.Assertions.assertThatThrownBy;
-
-import org.junit.Test;
-import org.onap.policy.api.main.exception.PolicyApiRuntimeException;
-
-public class TestApiCommandLineArguments {
-    private ApiCommandLineArguments apiCmdArgs = new ApiCommandLineArguments();
-
-    @Test(expected = PolicyApiRuntimeException.class)
-    public void testApiCommandLineArgumentsStringArray() {
-        String[] args = {"---d"};
-        new ApiCommandLineArguments(args);
-    }
-
-    @Test
-    public void testNonExistentFileValidateReadableFile() {
-        apiCmdArgs.setConfigurationFilePath("src/test/resources/filetest/nonexist.json ");
-        assertThatThrownBy(apiCmdArgs::validate)
-                .hasMessageContaining("file \"src/test/resources/filetest/nonexist.json \" does not exist");
-    }
-
-    @Test
-    public void testEmptyFileNameValidateReadableFile() {
-        apiCmdArgs.setConfigurationFilePath("");
-        assertThatThrownBy(apiCmdArgs::validate)
-                .hasMessageContaining("policy-api configuration file was not specified as an argument");
-    }
-
-    @Test
-    public void testInvalidUrlValidateReadableFile() {
-        apiCmdArgs.setConfigurationFilePath("src/test\\resources/filetest\\n");
-        assertThatThrownBy(apiCmdArgs::validate).hasMessageContaining(
-                "policy-api configuration file \"src/test\\resources/filetest\\n\" does not exist");
-    }
-
-    @Test
-    public void testVersion() {
-        String[] testArgs = {"-v"};
-        ApiCommandLineArguments cmdArgs = new ApiCommandLineArguments(testArgs);
-        assertThat(cmdArgs.version()).startsWith("ONAP Policy Framework Api Service");
-    }
-}
diff --git a/main/src/test/java/org/onap/policy/api/main/startstop/TestMain.java b/main/src/test/java/org/onap/policy/api/main/startstop/TestMain.java
deleted file mode 100644 (file)
index 6c8c514..0000000
+++ /dev/null
@@ -1,80 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- *  Copyright (C) 2018 Samsung Electronics Co., Ltd. All rights reserved.
- *  Modifications Copyright (C) 2019-2020 AT&T Intellectual Property. All rights reserved.
- *  Modifications Copyright (C) 2020-2021 Bell Canada. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- * SPDX-License-Identifier: Apache-2.0
- * ============LICENSE_END=========================================================
- */
-
-package org.onap.policy.api.main.startstop;
-
-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 org.junit.Test;
-import org.onap.policy.api.main.exception.PolicyApiRuntimeException;
-import org.onap.policy.api.main.parameters.CommonTestData;
-import org.onap.policy.common.utils.network.NetworkUtil;
-import org.onap.policy.common.utils.resources.MessageConstants;
-
-/**
- * Class to perform unit test of Main.
- *
- */
-public class TestMain {
-    private static final CommonTestData COMMON_TEST_DATA = new CommonTestData();
-
-    @Test
-    public void testMain() throws Exception {
-        COMMON_TEST_DATA.makeParameters("src/test/resources/parameters/ApiConfigParameters_Https.json",
-                "src/test/resources/parameters/ApiConfigParametersXXX.json", NetworkUtil.allocPort());
-        final String[] apiConfigParameters = {"-c", "src/test/resources/parameters/ApiConfigParametersXXX.json"};
-        final Main main = new Main(apiConfigParameters);
-        assertTrue(main.getParameterGroup().isValid());
-        assertEquals(CommonTestData.API_GROUP_NAME, main.getParameterGroup().getName());
-        main.shutdown();
-    }
-
-    @Test
-    public void testMain_NoArguments() {
-        final String[] apiConfigParameters = {};
-        assertThatThrownBy(() -> new Main(apiConfigParameters)).isInstanceOf(PolicyApiRuntimeException.class)
-            .hasMessage(String.format(MessageConstants.START_FAILURE_MSG, MessageConstants.POLICY_API));
-    }
-
-    @Test
-    public void testMain_InvalidArguments() {
-        final String[] apiConfigParameters = {"parameters/ApiConfigParameters.json"};
-        assertThatThrownBy(() -> new Main(apiConfigParameters)).isInstanceOf(PolicyApiRuntimeException.class)
-            .hasMessage(String.format(MessageConstants.START_FAILURE_MSG, MessageConstants.POLICY_API));
-    }
-
-    @Test
-    public void testMain_Help() {
-        final String[] apiConfigParameters = {"-h"};
-        assertThatCode(() -> Main.main(apiConfigParameters)).doesNotThrowAnyException();
-    }
-
-    @Test
-    public void testMain_InvalidParameters() {
-        final String[] apiConfigParameters = {"-c", "parameters/ApiConfigParameters_InvalidName.json"};
-        assertThatThrownBy(() -> new Main(apiConfigParameters)).isInstanceOf(PolicyApiRuntimeException.class)
-            .hasMessage(String.format(MessageConstants.START_FAILURE_MSG, MessageConstants.POLICY_API));
-    }
-}
diff --git a/main/src/test/resources/application-test.yaml b/main/src/test/resources/application-test.yaml
new file mode 100644 (file)
index 0000000..240d364
--- /dev/null
@@ -0,0 +1,8 @@
+database:
+  name: PolicyProviderParameterGroup
+  implementation: org.onap.policy.models.provider.impl.DatabasePolicyModelsProviderImpl
+  driver: org.h2.Driver
+  url: jdbc:h2:mem:testdb
+  user: policy_user
+  password: policy_user
+  persistenceUnit: ToscaConceptTest
\ No newline at end of file
diff --git a/main/src/test/resources/logback-test.xml b/main/src/test/resources/logback-test.xml
deleted file mode 100644 (file)
index 8818737..0000000
+++ /dev/null
@@ -1,53 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
-  ============LICENSE_START=======================================================
-   Copyright (C) 2016-2018 Ericsson. All rights reserved.
-  ================================================================================
-  Licensed under the Apache License, Version 2.0 (the "License");
-  you may not use this file except in compliance with the License.
-  You may obtain a copy of the License at
-
-       http://www.apache.org/licenses/LICENSE-2.0
-
-  Unless required by applicable law or agreed to in writing, software
-  distributed under the License is distributed on an "AS IS" BASIS,
-  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-  See the License for the specific language governing permissions and
-  limitations under the License.
-
-  SPDX-License-Identifier: Apache-2.0
-  ============LICENSE_END=========================================================
--->
-
-<configuration>
-
-    <contextName>policy-api</contextName>
-    <statusListener class="ch.qos.logback.core.status.OnConsoleStatusListener" />
-
-    <!-- USE FOR STD OUT ONLY -->
-    <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
-        <encoder>
-            <Pattern>%d %contextName [%t] %level %logger{36} - %msg%n</Pattern>
-        </encoder>
-    </appender>
-
-    <root level="INFO">
-        <appender-ref ref="STDOUT" />
-    </root>
-
-    <logger name="org.onap.policy.api" level="INFO" additivity="false">
-        <appender-ref ref="STDOUT" />
-    </logger>
-
-    <logger name="org.onap.policy.common.gson.GsonMessageBodyHandler" level="WARN" additivity="false">
-        <appender-ref ref="STDOUT" />
-    </logger>
-
-    <logger name="org.onap.policy.common.endpoints.http.server.YamlMessageBodyHandler" level="WARN" additivity="false">
-        <appender-ref ref="STDOUT" />
-    </logger>
-
-    <logger name="org.eclipse.jetty.server.RequestLog" level="WARN" additivity="false">
-        <appender-ref ref="STDOUT" />
-    </logger>
-</configuration>
diff --git a/main/src/test/resources/parameters/ApiConfigParameters_Https.json b/main/src/test/resources/parameters/ApiConfigParameters_Https.json
deleted file mode 100644 (file)
index 1d33e2e..0000000
+++ /dev/null
@@ -1,56 +0,0 @@
-{
-    "name":"ApiGroup",
-    "restServerParameters":{
-        "host":"0.0.0.0",
-        "port":6969,
-        "userName":"policyadmin",
-        "password":"zb!XztG34",
-        "https":true
-    },
-    "databaseProviderParameters": {
-        "name": "PolicyProviderParameterGroup",
-        "implementation": "org.onap.policy.models.provider.impl.DatabasePolicyModelsProviderImpl",
-        "databaseDriver": "org.h2.Driver",
-        "databaseUrl": "jdbc:h2:mem:testdb",
-        "databaseUser": "policy",
-        "databasePassword": "UDAxaWNZ",
-        "persistenceUnit": "ToscaConceptTest"
-    },
-    "preloadPolicyTypes": [
-        "policytypes/onap.policies.monitoring.tcagen2.yaml",
-        "policytypes/onap.policies.monitoring.dcaegen2.collectors.datafile.datafile-app-server.yaml",
-        "policytypes/onap.policies.monitoring.dcae-restconfcollector.yaml",
-        "policytypes/onap.policies.monitoring.dcae-pm-subscription-handler.yaml",
-        "policytypes/onap.policies.monitoring.dcae-pm-mapper.yaml",
-        "policytypes/onap.policies.Optimization.yaml",
-        "policytypes/onap.policies.optimization.Resource.yaml",
-        "policytypes/onap.policies.optimization.Service.yaml",
-        "policytypes/onap.policies.optimization.resource.AffinityPolicy.yaml",
-        "policytypes/onap.policies.optimization.resource.DistancePolicy.yaml",
-        "policytypes/onap.policies.optimization.resource.HpaPolicy.yaml",
-        "policytypes/onap.policies.optimization.resource.OptimizationPolicy.yaml",
-        "policytypes/onap.policies.optimization.resource.PciPolicy.yaml",
-        "policytypes/onap.policies.optimization.service.QueryPolicy.yaml",
-        "policytypes/onap.policies.optimization.service.SubscriberPolicy.yaml",
-        "policytypes/onap.policies.optimization.resource.Vim_fit.yaml",
-        "policytypes/onap.policies.optimization.resource.VnfPolicy.yaml",
-        "policytypes/onap.policies.controlloop.guard.Common.yaml",
-        "policytypes/onap.policies.controlloop.guard.common.Blacklist.yaml",
-        "policytypes/onap.policies.controlloop.guard.common.FrequencyLimiter.yaml",
-        "policytypes/onap.policies.controlloop.guard.common.MinMax.yaml",
-        "policytypes/onap.policies.controlloop.guard.common.Filter.yaml",
-        "policytypes/onap.policies.controlloop.guard.coordination.FirstBlocksSecond.yaml",
-        "policytypes/onap.policies.controlloop.Operational.yaml",
-        "policytypes/onap.policies.Naming.yaml",
-        "policytypes/onap.policies.Match.yaml",
-        "policytypes/onap.policies.native.Drools.yaml",
-        "policytypes/onap.policies.native.Xacml.yaml",
-        "policytypes/onap.policies.native.Apex.yaml",
-        "policytypes/onap.policies.controlloop.operational.Common.yaml",
-        "policytypes/onap.policies.controlloop.operational.common.Apex.yaml",
-        "policytypes/onap.policies.controlloop.operational.common.Drools.yaml"
-    ],
-    "preloadPolicies" : [
-        "policies/sdnc.policy.naming.input.tosca.yaml"
-    ]
-}
diff --git a/main/src/test/resources/parameters/ApiConfigParameters_InvalidName.json b/main/src/test/resources/parameters/ApiConfigParameters_InvalidName.json
deleted file mode 100644 (file)
index 832035e..0000000
+++ /dev/null
@@ -1,19 +0,0 @@
-{
-    "name":" ",
-    "restServerParameters":{
-        "host":"0.0.0.0",
-        "port":6969,
-        "userName":"policyadmin",
-        "password":"zb!XztG34"
-    },
-    "databaseProviderParameters": {
-        "name": "PolicyProviderParameterGroup",
-        "implementation": "org.onap.policy.models.provider.impl.DatabasePolicyModelsProviderImpl",
-        "databaseUrl": "jdbc:h2:mem:testdb",
-        "databaseUser": "policy",
-        "databasePassword": "UDAxaWNZ",
-        "persistenceUnit": "ToscaConceptTest"
-    },
-    "preloadPolicyTypes": [],
-    "preloadPolicies": []
-}
diff --git a/main/src/test/resources/parameters/ApiConfigParameters_InvalidRestServerParameters.json b/main/src/test/resources/parameters/ApiConfigParameters_InvalidRestServerParameters.json
deleted file mode 100644 (file)
index 4e9083e..0000000
+++ /dev/null
@@ -1,20 +0,0 @@
-{
-    "name":"ApiGroup",
-    "restServerParameters":{
-        "host":"",
-        "port":-1,
-        "userName":"",
-        "password":""
-    },
-    "databaseProviderParameters": {
-        "name": "PolicyProviderParameterGroup",
-        "implementation": "org.onap.policy.models.provider.impl.DatabasePolicyModelsProviderImpl",
-        "databaseDriver": "org.h2.Driver",
-        "databaseUrl": "jdbc:h2:mem:testdb",
-        "databaseUser": "policy",
-        "databasePassword": "UDAxaWNZ",
-        "persistenceUnit": "ToscaConceptTest"
-    },
-    "preloadPolicyTypes": [],
-    "preloadPolicies": []
-}
diff --git a/main/src/test/resources/parameters/ApiConfigParameters_Postgres.json b/main/src/test/resources/parameters/ApiConfigParameters_Postgres.json
deleted file mode 100644 (file)
index e5c375a..0000000
+++ /dev/null
@@ -1,56 +0,0 @@
-{
-    "name":"ApiGroup",
-    "restServerParameters":{
-        "host":"0.0.0.0",
-        "port":6968,
-        "userName":"healthcheck",
-        "password":"zb!XztG34",
-        "https":false
-    },
-    "databaseProviderParameters": {
-        "name": "PolicyProviderParameterGroup",
-        "implementation": "org.onap.policy.models.provider.impl.DatabasePolicyModelsProviderImpl",
-        "databaseDriver": "org.postgresql.Driver",
-        "databaseUrl": "jdbc:postgresql://localhost:5432/policyadmin",
-        "databaseUser": "policy_user",
-        "databasePassword": "policy_user",
-        "persistenceUnit": "PolicyDb"
-    },
-    "preloadPolicyTypes": [
-        "policytypes/onap.policies.monitoring.tcagen2.yaml",
-        "policytypes/onap.policies.monitoring.dcaegen2.collectors.datafile.datafile-app-server.yaml",
-        "policytypes/onap.policies.monitoring.dcae-restconfcollector.yaml",
-        "policytypes/onap.policies.monitoring.dcae-pm-subscription-handler.yaml",
-        "policytypes/onap.policies.monitoring.dcae-pm-mapper.yaml",
-        "policytypes/onap.policies.Optimization.yaml",
-        "policytypes/onap.policies.optimization.Resource.yaml",
-        "policytypes/onap.policies.optimization.Service.yaml",
-        "policytypes/onap.policies.optimization.resource.AffinityPolicy.yaml",
-        "policytypes/onap.policies.optimization.resource.DistancePolicy.yaml",
-        "policytypes/onap.policies.optimization.resource.HpaPolicy.yaml",
-        "policytypes/onap.policies.optimization.resource.OptimizationPolicy.yaml",
-        "policytypes/onap.policies.optimization.resource.PciPolicy.yaml",
-        "policytypes/onap.policies.optimization.service.QueryPolicy.yaml",
-        "policytypes/onap.policies.optimization.service.SubscriberPolicy.yaml",
-        "policytypes/onap.policies.optimization.resource.Vim_fit.yaml",
-        "policytypes/onap.policies.optimization.resource.VnfPolicy.yaml",
-        "policytypes/onap.policies.controlloop.guard.Common.yaml",
-        "policytypes/onap.policies.controlloop.guard.common.Blacklist.yaml",
-        "policytypes/onap.policies.controlloop.guard.common.FrequencyLimiter.yaml",
-        "policytypes/onap.policies.controlloop.guard.common.MinMax.yaml",
-        "policytypes/onap.policies.controlloop.guard.common.Filter.yaml",
-        "policytypes/onap.policies.controlloop.guard.coordination.FirstBlocksSecond.yaml",
-        "policytypes/onap.policies.controlloop.Operational.yaml",
-        "policytypes/onap.policies.Naming.yaml",
-        "policytypes/onap.policies.Match.yaml",
-        "policytypes/onap.policies.native.Drools.yaml",
-        "policytypes/onap.policies.native.Xacml.yaml",
-        "policytypes/onap.policies.native.Apex.yaml",
-        "policytypes/onap.policies.controlloop.operational.Common.yaml",
-        "policytypes/onap.policies.controlloop.operational.common.Apex.yaml",
-        "policytypes/onap.policies.controlloop.operational.common.Drools.yaml"
-    ],
-    "preloadPolicies" : [
-        "policies/sdnc.policy.naming.input.tosca.yaml"
-    ]
-}
diff --git a/main/src/test/resources/parameters/BadParameters.json b/main/src/test/resources/parameters/BadParameters.json
deleted file mode 100644 (file)
index de2040c..0000000
+++ /dev/null
@@ -1,3 +0,0 @@
-{
-    "name" : []
-}
\ No newline at end of file
diff --git a/main/src/test/resources/parameters/EmptyParameters.json b/main/src/test/resources/parameters/EmptyParameters.json
deleted file mode 100644 (file)
index e69de29..0000000
diff --git a/main/src/test/resources/parameters/InvalidParameters.json b/main/src/test/resources/parameters/InvalidParameters.json
deleted file mode 100644 (file)
index de2040c..0000000
+++ /dev/null
@@ -1,3 +0,0 @@
-{
-    "name" : []
-}
\ No newline at end of file
diff --git a/main/src/test/resources/parameters/MinimumParameters.json b/main/src/test/resources/parameters/MinimumParameters.json
deleted file mode 100644 (file)
index 5d671d2..0000000
+++ /dev/null
@@ -1,20 +0,0 @@
-{
-    "name":"ApiGroup",
-    "restServerParameters":{
-        "host":"0.0.0.0",
-        "port":6969,
-        "userName":"policyadmin",
-        "password":"zb!XztG34"
-    },
-    "databaseProviderParameters": {
-        "name": "PolicyProviderParameterGroup",
-        "implementation": "org.onap.policy.models.provider.impl.DatabasePolicyModelsProviderImpl",
-        "databaseDriver": "org.h2.Driver",
-        "databaseUrl": "jdbc:h2:mem:testdb",
-        "databaseUser": "policy",
-        "databasePassword": "UDAxaWNZ",
-        "persistenceUnit": "ToscaConceptTest"
-    },
-    "preloadPolicyTypes": [],
-    "preloadPolicies": []
-}
\ No newline at end of file
diff --git a/main/src/test/resources/parameters/NoParameters.json b/main/src/test/resources/parameters/NoParameters.json
deleted file mode 100644 (file)
index 36e33af..0000000
+++ /dev/null
@@ -1,19 +0,0 @@
-{
-    "restServerParameters":{
-        "host":"0.0.0.0",
-        "port":6969,
-        "userName":"policyadmin",
-        "password":"zb!XztG34"
-    },
-    "databaseProviderParameters": {
-        "name": "PolicyProviderParameterGroup",
-        "implementation": "org.onap.policy.models.provider.impl.DatabasePolicyModelsProviderImpl",
-        "databaseDriver": "org.h2.Driver",
-        "databaseUrl": "jdbc:h2:mem:testdb",
-        "databaseUser": "policy",
-        "databasePassword": "UDAxaWNZ",
-        "persistenceUnit": "ToscaConceptTest"
-    },
-    "preloadPolicyTypes": [],
-    "preloadPolicies": []
-}
\ No newline at end of file
diff --git a/main/src/test/resources/parameters/RestServerParameters.json b/main/src/test/resources/parameters/RestServerParameters.json
deleted file mode 100644 (file)
index 8d3bc58..0000000
+++ /dev/null
@@ -1,6 +0,0 @@
-{
-    "host": "0.0.0.0",
-    "port": 6969,
-    "userName": "policyadmin",
-    "password": "zb!XztG34"
-}
diff --git a/main/src/test/resources/parameters/RestServerParametersEmpty.json b/main/src/test/resources/parameters/RestServerParametersEmpty.json
deleted file mode 100644 (file)
index e02aef2..0000000
+++ /dev/null
@@ -1,2 +0,0 @@
-{\r
-}
\ No newline at end of file
index 57078d5..e9c4587 100644 (file)
@@ -1,7 +1,7 @@
 <!--
   ============LICENSE_START=======================================================
    Copyright (C) 2019,2021 AT&T Intellectual Property. All rights reserved.
-   Modifications Copyright (C) 2020 Bell Canada.
+   Modifications Copyright (C) 2020-2022 Bell Canada.
   ================================================================================
   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
                                                 <outputDirectory>/lib</outputDirectory>
                                                 <outputFileNameMapping>policy-api.tar.gz</outputFileNameMapping>
                                             </dependencySet>
+                                            <dependencySet>
+                                                <includes>
+                                                    <include>org.onap.policy.api:api-main</include>
+                                                </includes>
+                                                <outputFileNameMapping>api.jar</outputFileNameMapping>
+                                            </dependencySet>
                                         </dependencySets>
                                     </inline>
                                 </assembly>
             <type>tar.gz</type>
         </dependency>
     </dependencies>
-</project>
+</project>
\ No newline at end of file
index aac535d..652d97d 100644 (file)
@@ -2,6 +2,7 @@
 # Dockerfile
 # ============LICENSE_START=======================================================
 #  Copyright (C) 2020-2021 AT&T Intellectual Property. All rights reserved.
+#  Modifications Copyright (C) 2022 Bell Canada. All rights reserved.
 # ================================================================================
 # Licensed under the Apache License, Version 2.0 (the "License");
 # you may not use this file except in compliance with the License.
@@ -30,15 +31,16 @@ ENV POLICY_HOME=$POLICY_HOME/api
 RUN mkdir -p $POLICY_LOGS $POLICY_HOME $POLICY_HOME/bin && \
     chown -R policy:policy $POLICY_HOME $POLICY_LOGS && \
     mkdir /packages
-COPY /maven/* /packages
+COPY /maven/lib/policy-api.tar.gz /packages
 RUN tar xvfz /packages/policy-api.tar.gz --directory $POLICY_HOME && \
     rm /packages/policy-api.tar.gz
 
 WORKDIR $POLICY_HOME
 COPY policy-api.sh  bin/.
+COPY /maven/api.jar /app
 
-RUN chown -R policy:policy * && chmod 755 bin/*.sh
+RUN chown -R policy:policy * && chmod 755 bin/*.sh && chown -R policy:policy /app
 
 USER policy
 WORKDIR $POLICY_HOME/bin
-ENTRYPOINT [ "./policy-api.sh" ]
+ENTRYPOINT [ "./policy-api.sh" ]
\ No newline at end of file
index d058d25..5d22c03 100644 (file)
@@ -3,6 +3,7 @@
 # ============LICENSE_START=======================================================
 #  Copyright (C) 2019-2021 AT&T Intellectual Property. All rights reserved.
 #  Modifications Copyright (C) 2019-2020 Nordix Foundation.
+#  Modifications Copyright (C) 2022 Bell Canada. All rights reserved.
 # ================================================================================
 # Licensed under the Apache License, Version 2.0 (the "License");
 # you may not use this file except in compliance with the License.
@@ -33,7 +34,7 @@ else
 fi
 
 if [ -z "$CONFIG_FILE" ]; then
-    CONFIG_FILE="${POLICY_HOME}/etc/defaultConfig.json"
+    CONFIG_FILE="${POLICY_HOME}/etc/apiParameters.yaml"
 fi
 
 echo "Policy api config file: $CONFIG_FILE"
@@ -53,4 +54,11 @@ if [ -f "${POLICY_HOME}/etc/mounted/logback.xml" ]; then
     cp -f "${POLICY_HOME}"/etc/mounted/logback.xml "${POLICY_HOME}"/etc/
 fi
 
-$JAVA_HOME/bin/java -cp "${POLICY_HOME}/etc:${POLICY_HOME}/lib/*" -Dlogback.configurationFile="${POLICY_HOME}/etc/logback.xml" -Djavax.net.ssl.keyStore="${KEYSTORE}" -Djavax.net.ssl.keyStorePassword="${KEYSTORE_PASSWD}" -Djavax.net.ssl.trustStore="${TRUSTSTORE}" -Djavax.net.ssl.trustStorePassword="${TRUSTSTORE_PASSWD}" org.onap.policy.api.main.startstop.Main -c "${CONFIG_FILE}"
+$JAVA_HOME/bin/java \
+    -Dlogback.configurationFile="${POLICY_HOME}/etc/logback.xml" \
+    -Dserver.ssl.key-store="${KEYSTORE}" \
+    -Dserver.ssl.key-store-password="${KEYSTORE_PASSWD}" \
+    -Djavax.net.ssl.trustStore="${TRUSTSTORE}" \
+    -Djavax.net.ssl.trustStorePassword="${TRUSTSTORE_PASSWD}" \
+    -jar /app/api.jar \
+    --spring.config.location="${CONFIG_FILE}"
\ No newline at end of file
index c19bd08..777ea85 100644 (file)
@@ -1,6 +1,7 @@
 <!--
   ============LICENSE_START=======================================================
    Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
+   Modifications Copyright (C) 2022 Bell Canada. All rights reserved.
   ================================================================================
   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
@@ -40,8 +41,8 @@
             <directory>${project.basedir}/src/main/resources/etc
             </directory>
             <includes>
-                <include>*.json</include>
                 <include>*.xml</include>
+                <include>*.yaml</include>
             </includes>
             <outputDirectory>${file.separator}etc</outputDirectory>
             <lineEnding>unix</lineEnding>
@@ -59,4 +60,4 @@
             <lineEnding>keep</lineEnding>
         </fileSet>
     </fileSets>
-</assembly>
+</assembly>
\ No newline at end of file
diff --git a/packages/policy-api-tarball/src/main/resources/etc/apiParameters.yaml b/packages/policy-api-tarball/src/main/resources/etc/apiParameters.yaml
new file mode 100644 (file)
index 0000000..96b7982
--- /dev/null
@@ -0,0 +1,65 @@
+server:
+  port: 6969
+
+spring:
+  security.user:
+    name: policyadmin
+    password: zb!XztG34
+  mvc.converters.preferred-json-mapper: gson
+
+policy-api:
+  name: ApiGroup
+  aaf: false
+
+database:
+  name: PolicyProviderParameterGroup
+  implementation: org.onap.policy.models.provider.impl.DatabasePolicyModelsProviderImpl
+  driver: org.mariadb.jdbc.Driver
+  url: jdbc:mariadb://mariadb:3306/policyadmin
+  user: policy_user
+  password: policy_user
+  persistenceUnit: PolicyDb
+
+policy-preload:
+  policyTypes:
+    - policytypes/onap.policies.monitoring.tcagen2.yaml
+    - policytypes/onap.policies.monitoring.dcaegen2.collectors.datafile.datafile-app-server.yaml
+    - policytypes/onap.policies.monitoring.dcae-restconfcollector.yaml
+    - policytypes/onap.policies.monitoring.dcae-pm-subscription-handler.yaml
+    - policytypes/onap.policies.monitoring.dcae-pm-mapper.yaml
+    - policytypes/onap.policies.Optimization.yaml
+    - policytypes/onap.policies.optimization.Resource.yaml
+    - policytypes/onap.policies.optimization.Service.yaml
+    - policytypes/onap.policies.optimization.resource.AffinityPolicy.yaml
+    - policytypes/onap.policies.optimization.resource.DistancePolicy.yaml
+    - policytypes/onap.policies.optimization.resource.HpaPolicy.yaml
+    - policytypes/onap.policies.optimization.resource.OptimizationPolicy.yaml
+    - policytypes/onap.policies.optimization.resource.PciPolicy.yaml
+    - policytypes/onap.policies.optimization.service.QueryPolicy.yaml
+    - policytypes/onap.policies.optimization.service.SubscriberPolicy.yaml
+    - policytypes/onap.policies.optimization.resource.Vim_fit.yaml
+    - policytypes/onap.policies.optimization.resource.VnfPolicy.yaml
+    - policytypes/onap.policies.controlloop.guard.Common.yaml
+    - policytypes/onap.policies.controlloop.guard.common.Blacklist.yaml
+    - policytypes/onap.policies.controlloop.guard.common.FrequencyLimiter.yaml
+    - policytypes/onap.policies.controlloop.guard.common.MinMax.yaml
+    - policytypes/onap.policies.controlloop.guard.common.Filter.yaml
+    - policytypes/onap.policies.controlloop.guard.coordination.FirstBlocksSecond.yaml
+    - policytypes/onap.policies.Naming.yaml
+    - policytypes/onap.policies.Match.yaml
+    - policytypes/onap.policies.native.Drools.yaml
+    - policytypes/onap.policies.native.Xacml.yaml
+    - policytypes/onap.policies.native.Apex.yaml
+    - policytypes/onap.policies.controlloop.operational.Common.yaml
+    - policytypes/onap.policies.controlloop.operational.common.Apex.yaml
+    - policytypes/onap.policies.controlloop.operational.common.Drools.yaml
+  policies:
+    - policies/sdnc.policy.naming.input.tosca.yaml
+
+management:
+  endpoints:
+    web:
+      base-path: /
+      exposure:
+        include: health,metrics,prometheus
+      path-mapping.prometheus: metrics
\ No newline at end of file
diff --git a/packages/policy-api-tarball/src/main/resources/etc/defaultConfig.json b/packages/policy-api-tarball/src/main/resources/etc/defaultConfig.json
deleted file mode 100644 (file)
index 555a113..0000000
+++ /dev/null
@@ -1,57 +0,0 @@
-{
-    "name": "ApiGroup",
-    "restServerParameters": {
-        "host": "0.0.0.0",
-        "port": 6969,
-        "userName": "policyadmin",
-        "password": "zb!XztG34",
-        "https": true,
-        "aaf": false,
-        "prometheus": true
-    },
-    "databaseProviderParameters": {
-        "name": "PolicyProviderParameterGroup",
-        "implementation": "org.onap.policy.models.provider.impl.DatabasePolicyModelsProviderImpl",
-        "databaseDriver": "org.mariadb.jdbc.Driver",
-        "databaseUrl": "jdbc:mariadb://mariadb:3306/policyadmin",
-        "databaseUser": "policy_user",
-        "databasePassword": "policy_user",
-        "persistenceUnit": "PolicyDb"
-    },
-    "preloadPolicyTypes": [
-        "policytypes/onap.policies.monitoring.tcagen2.yaml",
-        "policytypes/onap.policies.monitoring.dcaegen2.collectors.datafile.datafile-app-server.yaml",
-        "policytypes/onap.policies.monitoring.dcae-restconfcollector.yaml",
-        "policytypes/onap.policies.monitoring.dcae-pm-subscription-handler.yaml",
-        "policytypes/onap.policies.monitoring.dcae-pm-mapper.yaml",
-        "policytypes/onap.policies.Optimization.yaml",
-        "policytypes/onap.policies.optimization.Resource.yaml",
-        "policytypes/onap.policies.optimization.Service.yaml",
-        "policytypes/onap.policies.optimization.resource.AffinityPolicy.yaml",
-        "policytypes/onap.policies.optimization.resource.DistancePolicy.yaml",
-        "policytypes/onap.policies.optimization.resource.HpaPolicy.yaml",
-        "policytypes/onap.policies.optimization.resource.OptimizationPolicy.yaml",
-        "policytypes/onap.policies.optimization.resource.PciPolicy.yaml",
-        "policytypes/onap.policies.optimization.service.QueryPolicy.yaml",
-        "policytypes/onap.policies.optimization.service.SubscriberPolicy.yaml",
-        "policytypes/onap.policies.optimization.resource.Vim_fit.yaml",
-        "policytypes/onap.policies.optimization.resource.VnfPolicy.yaml",
-        "policytypes/onap.policies.controlloop.guard.Common.yaml",
-        "policytypes/onap.policies.controlloop.guard.common.Blacklist.yaml",
-        "policytypes/onap.policies.controlloop.guard.common.FrequencyLimiter.yaml",
-        "policytypes/onap.policies.controlloop.guard.common.MinMax.yaml",
-        "policytypes/onap.policies.controlloop.guard.common.Filter.yaml",
-        "policytypes/onap.policies.controlloop.guard.coordination.FirstBlocksSecond.yaml",
-        "policytypes/onap.policies.Naming.yaml",
-        "policytypes/onap.policies.Match.yaml",
-        "policytypes/onap.policies.native.Drools.yaml",
-        "policytypes/onap.policies.native.Xacml.yaml",
-        "policytypes/onap.policies.native.Apex.yaml",
-        "policytypes/onap.policies.controlloop.operational.Common.yaml",
-        "policytypes/onap.policies.controlloop.operational.common.Apex.yaml",
-        "policytypes/onap.policies.controlloop.operational.common.Drools.yaml"
-    ],
-    "preloadPolicies" : [
-        "policies/sdnc.policy.naming.input.tosca.yaml"
-    ]
-}
diff --git a/packages/policy-api-tarball/src/main/resources/etc/s3pConfig.json b/packages/policy-api-tarball/src/main/resources/etc/s3pConfig.json
deleted file mode 100644 (file)
index 5bd1797..0000000
+++ /dev/null
@@ -1,56 +0,0 @@
-{
-    "name": "ApiGroup",
-    "restServerParameters": {
-        "host": "0.0.0.0",
-        "port": 6969,
-        "userName": "policyadmin",
-        "password": "zb!XztG34",
-        "https": true,
-        "aaf": false
-    },
-    "databaseProviderParameters": {
-        "name": "PolicyProviderParameterGroup",
-        "implementation": "org.onap.policy.models.provider.impl.DatabasePolicyModelsProviderImpl",
-        "databaseDriver": "org.mariadb.jdbc.Driver",
-        "databaseUrl": "jdbc:mariadb://mariadb:3306/policyadmin",
-        "databaseUser": "policy_user",
-        "databasePassword": "policy_user",
-        "persistenceUnit": "PolicyDb"
-    },
-    "preloadPolicyTypes": [
-        "policytypes/onap.policies.monitoring.tcagen2.yaml",
-        "policytypes/onap.policies.monitoring.dcaegen2.collectors.datafile.datafile-app-server.yaml",
-        "policytypes/onap.policies.monitoring.dcae-restconfcollector.yaml",
-        "policytypes/onap.policies.monitoring.dcae-pm-subscription-handler.yaml",
-        "policytypes/onap.policies.monitoring.dcae-pm-mapper.yaml",
-        "policytypes/onap.policies.Optimization.yaml",
-        "policytypes/onap.policies.optimization.Resource.yaml",
-        "policytypes/onap.policies.optimization.Service.yaml",
-        "policytypes/onap.policies.optimization.resource.AffinityPolicy.yaml",
-        "policytypes/onap.policies.optimization.resource.DistancePolicy.yaml",
-        "policytypes/onap.policies.optimization.resource.HpaPolicy.yaml",
-        "policytypes/onap.policies.optimization.resource.OptimizationPolicy.yaml",
-        "policytypes/onap.policies.optimization.resource.PciPolicy.yaml",
-        "policytypes/onap.policies.optimization.service.QueryPolicy.yaml",
-        "policytypes/onap.policies.optimization.service.SubscriberPolicy.yaml",
-        "policytypes/onap.policies.optimization.resource.Vim_fit.yaml",
-        "policytypes/onap.policies.optimization.resource.VnfPolicy.yaml",
-        "policytypes/onap.policies.controlloop.guard.Common.yaml",
-        "policytypes/onap.policies.controlloop.guard.common.Blacklist.yaml",
-        "policytypes/onap.policies.controlloop.guard.common.FrequencyLimiter.yaml",
-        "policytypes/onap.policies.controlloop.guard.common.MinMax.yaml",
-        "policytypes/onap.policies.controlloop.guard.common.Filter.yaml",
-        "policytypes/onap.policies.controlloop.guard.coordination.FirstBlocksSecond.yaml",
-        "policytypes/onap.policies.Naming.yaml",
-        "policytypes/onap.policies.Match.yaml",
-        "policytypes/onap.policies.native.Drools.yaml",
-        "policytypes/onap.policies.native.Xacml.yaml",
-        "policytypes/onap.policies.native.Apex.yaml",
-        "policytypes/onap.policies.controlloop.operational.Common.yaml",
-        "policytypes/onap.policies.controlloop.operational.common.Apex.yaml",
-        "policytypes/onap.policies.controlloop.operational.common.Drools.yaml"
-    ],
-    "preloadPolicies" : [
-        "policies/sdnc.policy.naming.input.tosca.yaml"
-    ]
-}