diff options
author | Rashmi Pujar <rashmi.pujar1@bell.ca> | 2022-02-04 21:49:30 -0500 |
---|---|---|
committer | Rashmi Pujar <rashmi.pujar1@bell.ca> | 2022-02-10 01:33:25 -0500 |
commit | 5f919673b13d8fd40a6a90b97f4e662ade068304 (patch) | |
tree | c24a727c3c60b228b28cd68df3d37ca56acd379e | |
parent | 2d4db3c6375ca761b25700226addea6060432b0d (diff) |
Migrate policy api startup & config, controller to springboot
Issue-ID: POLICY-3753
Signed-off-by: Rashmi Pujar <rashmi.pujar1@bell.ca>
Change-Id: I4537ed49b7fc57683bfc487f0d212642b7e69f17
58 files changed, 1245 insertions, 2135 deletions
diff --git a/main/pom.xml b/main/pom.xml index 5e54f2d9..c89eafd1 100644 --- a/main/pom.xml +++ b/main/pom.xml @@ -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"); @@ -37,71 +37,75 @@ <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> @@ -123,6 +127,19 @@ </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 index 00000000..25c4d937 --- /dev/null +++ b/main/src/main/java/org/onap/policy/api/main/PolicyApiApplication.java @@ -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 index 00000000..bd55344a --- /dev/null +++ b/main/src/main/java/org/onap/policy/api/main/config/PolicyApiAafConfig.java @@ -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 index 00000000..3e4f11ac --- /dev/null +++ b/main/src/main/java/org/onap/policy/api/main/config/PolicyApiConfig.java @@ -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 index 00000000..c2c40ff2 --- /dev/null +++ b/main/src/main/java/org/onap/policy/api/main/config/PolicyPreloadConfig.java @@ -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 index 00000000..367f92af --- /dev/null +++ b/main/src/main/java/org/onap/policy/api/main/config/SecurityConfig.java @@ -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 index 00000000..052ae5c6 --- /dev/null +++ b/main/src/main/java/org/onap/policy/api/main/config/SwaggerConfig.java @@ -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 index 00000000..a50dd187 --- /dev/null +++ b/main/src/main/java/org/onap/policy/api/main/config/WebConfig.java @@ -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 index 00000000..a6e8c4a3 --- /dev/null +++ b/main/src/main/java/org/onap/policy/api/main/config/converter/StringToEnumConverter.java @@ -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 index 00000000..9fe9b031 --- /dev/null +++ b/main/src/main/java/org/onap/policy/api/main/config/converter/YamlHttpMessageConverter.java @@ -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 diff --git a/main/src/main/java/org/onap/policy/api/main/exception/PolicyApiRuntimeException.java b/main/src/main/java/org/onap/policy/api/main/exception/PolicyApiRuntimeException.java index ea6b55f6..19bf5e12 100644 --- a/main/src/main/java/org/onap/policy/api/main/exception/PolicyApiRuntimeException.java +++ b/main/src/main/java/org/onap/policy/api/main/exception/PolicyApiRuntimeException.java @@ -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. @@ -20,12 +21,22 @@ 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 index c9b96e36..00000000 --- a/main/src/main/java/org/onap/policy/api/main/parameters/ApiParameterGroup.java +++ /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 index 019a0125..00000000 --- a/main/src/main/java/org/onap/policy/api/main/parameters/ApiParameterHandler.java +++ /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; - } -} diff --git a/main/src/main/java/org/onap/policy/api/main/rest/ApiRestController.java b/main/src/main/java/org/onap/policy/api/main/rest/ApiRestController.java index eb60c5e5..263345a3 100644 --- a/main/src/main/java/org/onap/policy/api/main/rest/ApiRestController.java +++ b/main/src/main/java/org/onap/policy/api/main/rest/ApiRestController.java @@ -5,7 +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) 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.
@@ -41,18 +41,8 @@ import io.swagger.annotations.SwaggerDefinition; import java.net.HttpURLConnection;
import java.util.List;
import java.util.UUID;
-import javax.ws.rs.Consumes;
-import javax.ws.rs.DELETE;
-import javax.ws.rs.DefaultValue;
-import javax.ws.rs.GET;
-import javax.ws.rs.HeaderParam;
-import javax.ws.rs.POST;
-import javax.ws.rs.Path;
-import javax.ws.rs.PathParam;
-import javax.ws.rs.Produces;
-import javax.ws.rs.QueryParam;
-import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
+import org.onap.policy.api.main.exception.PolicyApiRuntimeException;
import org.onap.policy.api.main.rest.provider.HealthCheckProvider;
import org.onap.policy.api.main.rest.provider.PolicyProvider;
import org.onap.policy.api.main.rest.provider.PolicyTypeProvider;
@@ -66,16 +56,29 @@ import org.onap.policy.models.base.PfModelRuntimeException; import org.onap.policy.models.tosca.authorative.concepts.ToscaServiceTemplate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.http.HttpMethod;
+import org.springframework.http.HttpStatus;
+import org.springframework.http.ResponseEntity;
+import org.springframework.web.bind.annotation.DeleteMapping;
+import org.springframework.web.bind.annotation.ExceptionHandler;
+import org.springframework.web.bind.annotation.GetMapping;
+import org.springframework.web.bind.annotation.PathVariable;
+import org.springframework.web.bind.annotation.PostMapping;
+import org.springframework.web.bind.annotation.RequestBody;
+import org.springframework.web.bind.annotation.RequestHeader;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RequestParam;
+import org.springframework.web.bind.annotation.RestController;
/**
* Class to provide REST API services.
*
* @author Chenfei Gao (cgao@research.att.com)
*/
-@Path("/policy/api/v1")
+@RestController
+@RequestMapping(path = "/policy/api/v1", produces = { "application/json", "application/yaml" })
@Api(value = "Policy Design API")
-@Produces({"application/json", "application/yaml"})
-@Consumes({"application/json", "application/yaml"})
@SwaggerDefinition(
info = @Info(
description = "Policy Design API is publicly exposed for clients to Create/Read/Update/Delete"
@@ -129,14 +132,33 @@ public class ApiRestController extends CommonRestController { private static final String INVALID_PAYLOAD_MESSAGE = "Not Acceptable Payload";
private static final String HTTP_CONFLICT_MESSAGE = "Delete Conflict, Rule Violation";
+ private enum Target {
+ POLICY,
+ POLICY_TYPE,
+ OTHER
+ }
+
+ @Autowired
+ private PolicyProvider policyProvider;
+
+ @Autowired
+ private HealthCheckProvider healthCheckProvider;
+
+ @Autowired
+ private PolicyTypeProvider policyTypeProvider;
+
+ @Autowired
+ private ApiStatisticsManager mgr;
+
+ @Autowired
+ private StatisticsProvider statisticsProvider;
/**
* Retrieves the healthcheck status of the API component.
*
* @return the Response object containing the results of the API operation
*/
- @GET
- @Path("/healthcheck")
+ @GetMapping("/healthcheck")
@ApiOperation(value = "Perform a system healthcheck", notes = "Returns healthy status of the Policy API component",
response = HealthCheckReport.class,
responseHeaders = {
@@ -159,11 +181,11 @@ public class ApiRestController extends CommonRestController { @ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = AUTHENTICATION_ERROR_MESSAGE),
@ApiResponse(code = HttpURLConnection.HTTP_FORBIDDEN, message = AUTHORIZATION_ERROR_MESSAGE),
@ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = SERVER_ERROR_MESSAGE)})
- public Response
- getHealthCheck(@HeaderParam(REQUEST_ID_NAME) @ApiParam(REQUEST_ID_PARAM_DESCRIPTION) UUID requestId) {
-
- updateApiStatisticsCounter(Target.OTHER, Result.SUCCESS, HttpMethod.GET);
- return makeOkResponse(requestId, new HealthCheckProvider().performHealthCheck());
+ public ResponseEntity<HealthCheckReport> getHealthCheck(
+ @RequestHeader(name = REQUEST_ID_NAME, required = false)
+ @ApiParam(REQUEST_ID_PARAM_DESCRIPTION) UUID requestId) {
+ updateApiStatisticsCounter(Target.OTHER, HttpStatus.OK, HttpMethod.GET);
+ return makeOkResponse(requestId, healthCheckProvider.performHealthCheck());
}
/**
@@ -171,8 +193,7 @@ public class ApiRestController extends CommonRestController { *
* @return the Response object containing the results of the API operation
*/
- @GET
- @Path("/statistics")
+ @GetMapping("/statistics")
@ApiOperation(value = "Retrieve current statistics",
notes = "Returns current statistics including the counters of API invocation",
response = StatisticsReport.class,
@@ -196,12 +217,11 @@ public class ApiRestController extends CommonRestController { @ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = AUTHENTICATION_ERROR_MESSAGE),
@ApiResponse(code = HttpURLConnection.HTTP_FORBIDDEN, message = AUTHORIZATION_ERROR_MESSAGE),
@ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = SERVER_ERROR_MESSAGE)})
- public Response
- getStatistics(@HeaderParam(REQUEST_ID_NAME) @ApiParam(REQUEST_ID_PARAM_DESCRIPTION) UUID requestId) {
-
- updateApiStatisticsCounter(Target.OTHER, Result.SUCCESS, HttpMethod.GET);
-
- return makeOkResponse(requestId, new StatisticsProvider().fetchCurrentStatistics());
+ public ResponseEntity<StatisticsReport> getStatistics(
+ @RequestHeader(name = REQUEST_ID_NAME, required = false)
+ @ApiParam(REQUEST_ID_PARAM_DESCRIPTION) UUID requestId) {
+ updateApiStatisticsCounter(Target.OTHER, HttpStatus.OK, HttpMethod.GET);
+ return makeOkResponse(requestId, statisticsProvider.fetchCurrentStatistics());
}
/**
@@ -209,8 +229,7 @@ public class ApiRestController extends CommonRestController { *
* @return the Response object containing the results of the API operation
*/
- @GET
- @Path("/policytypes")
+ @GetMapping("/policytypes")
@ApiOperation(value = "Retrieve existing policy types",
notes = "Returns a list of existing policy types stored in Policy Framework",
response = ToscaServiceTemplate.class,
@@ -234,17 +253,18 @@ public class ApiRestController extends CommonRestController { @ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = AUTHENTICATION_ERROR_MESSAGE),
@ApiResponse(code = HttpURLConnection.HTTP_FORBIDDEN, message = AUTHORIZATION_ERROR_MESSAGE),
@ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = SERVER_ERROR_MESSAGE)})
- public Response
- getAllPolicyTypes(@HeaderParam(REQUEST_ID_NAME) @ApiParam(REQUEST_ID_PARAM_DESCRIPTION) UUID requestId) {
-
- try (var policyTypeProvider = new PolicyTypeProvider()) {
+ public ResponseEntity<ToscaServiceTemplate> getAllPolicyTypes(
+ @RequestHeader(name = REQUEST_ID_NAME, required = false)
+ @ApiParam(REQUEST_ID_PARAM_DESCRIPTION) UUID requestId) {
+ try {
ToscaServiceTemplate serviceTemplate = policyTypeProvider.fetchPolicyTypes(null, null);
- updateApiStatisticsCounter(Target.POLICY_TYPE, Result.SUCCESS, HttpMethod.GET);
+ updateApiStatisticsCounter(Target.POLICY_TYPE, HttpStatus.OK, HttpMethod.GET);
return makeOkResponse(requestId, serviceTemplate);
} catch (PfModelException | PfModelRuntimeException pfme) {
- LOGGER.warn("GET /policytypes", pfme);
- updateApiStatisticsCounter(Target.POLICY_TYPE, Result.FAILURE, HttpMethod.GET);
- return makeErrorResponse(requestId, pfme);
+ final var msg = "GET /policytypes";
+ updateApiStatisticsCounter(Target.POLICY_TYPE, HttpStatus.resolve(pfme.getErrorResponse().getResponseCode()
+ .getStatusCode()), HttpMethod.GET);
+ throw new PolicyApiRuntimeException(msg, pfme.getCause(), pfme.getErrorResponse(), requestId);
}
}
@@ -255,8 +275,7 @@ public class ApiRestController extends CommonRestController { *
* @return the Response object containing the results of the API operation
*/
- @GET
- @Path("/policytypes/{policyTypeId}")
+ @GetMapping("/policytypes/{policyTypeId}")
@ApiOperation(value = "Retrieve all available versions of a policy type",
notes = "Returns a list of all available versions for the specified policy type",
response = ToscaServiceTemplate.class,
@@ -281,18 +300,19 @@ public class ApiRestController extends CommonRestController { @ApiResponse(code = HttpURLConnection.HTTP_FORBIDDEN, message = AUTHORIZATION_ERROR_MESSAGE),
@ApiResponse(code = HttpURLConnection.HTTP_NOT_FOUND, message = NOT_FOUND_MESSAGE),
@ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = SERVER_ERROR_MESSAGE)})
- public Response getAllVersionsOfPolicyType(
- @PathParam("policyTypeId") @ApiParam(value = "ID of policy type", required = true) String policyTypeId,
- @HeaderParam(REQUEST_ID_NAME) @ApiParam(REQUEST_ID_PARAM_DESCRIPTION) UUID requestId) {
-
- try (var policyTypeProvider = new PolicyTypeProvider()) {
+ public ResponseEntity<ToscaServiceTemplate> getAllVersionsOfPolicyType(
+ @PathVariable("policyTypeId") @ApiParam(value = "ID of policy type", required = true) String policyTypeId,
+ @RequestHeader(name = REQUEST_ID_NAME, required = false)
+ @ApiParam(REQUEST_ID_PARAM_DESCRIPTION) UUID requestId) {
+ try {
ToscaServiceTemplate serviceTemplate = policyTypeProvider.fetchPolicyTypes(policyTypeId, null);
- updateApiStatisticsCounter(Target.POLICY_TYPE, Result.SUCCESS, HttpMethod.GET);
+ updateApiStatisticsCounter(Target.POLICY_TYPE, HttpStatus.OK, HttpMethod.GET);
return makeOkResponse(requestId, serviceTemplate);
} catch (PfModelException | PfModelRuntimeException pfme) {
- LOGGER.warn("GET /policytypes/{}", policyTypeId, pfme);
- updateApiStatisticsCounter(Target.POLICY_TYPE, Result.FAILURE, HttpMethod.GET);
- return makeErrorResponse(requestId, pfme);
+ var msg = String.format("GET /policytypes/%s", policyTypeId);
+ updateApiStatisticsCounter(Target.POLICY_TYPE, HttpStatus.resolve(pfme.getErrorResponse().getResponseCode()
+ .getStatusCode()), HttpMethod.GET);
+ throw new PolicyApiRuntimeException(msg, pfme.getCause(), pfme.getErrorResponse(), requestId);
}
}
@@ -304,8 +324,7 @@ public class ApiRestController extends CommonRestController { *
* @return the Response object containing the results of the API operation
*/
- @GET
- @Path("/policytypes/{policyTypeId}/versions/{versionId}")
+ @GetMapping("/policytypes/{policyTypeId}/versions/{versionId}")
@ApiOperation(value = "Retrieve one particular version of a policy type",
notes = "Returns a particular version for the specified policy type", response = ToscaServiceTemplate.class,
responseHeaders = {
@@ -329,19 +348,20 @@ public class ApiRestController extends CommonRestController { @ApiResponse(code = HttpURLConnection.HTTP_FORBIDDEN, message = AUTHORIZATION_ERROR_MESSAGE),
@ApiResponse(code = HttpURLConnection.HTTP_NOT_FOUND, message = NOT_FOUND_MESSAGE),
@ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = SERVER_ERROR_MESSAGE)})
- public Response getSpecificVersionOfPolicyType(
- @PathParam("policyTypeId") @ApiParam(value = "ID of policy type", required = true) String policyTypeId,
- @PathParam("versionId") @ApiParam(value = "Version of policy type", required = true) String versionId,
- @HeaderParam(REQUEST_ID_NAME) @ApiParam(REQUEST_ID_PARAM_DESCRIPTION) UUID requestId) {
-
- try (var policyTypeProvider = new PolicyTypeProvider()) {
+ public ResponseEntity<ToscaServiceTemplate> getSpecificVersionOfPolicyType(
+ @PathVariable("policyTypeId") @ApiParam(value = "ID of policy type", required = true) String policyTypeId,
+ @PathVariable("versionId") @ApiParam(value = "Version of policy type", required = true) String versionId,
+ @RequestHeader(name = REQUEST_ID_NAME, required = false)
+ @ApiParam(REQUEST_ID_PARAM_DESCRIPTION) UUID requestId) {
+ try {
ToscaServiceTemplate serviceTemplate = policyTypeProvider.fetchPolicyTypes(policyTypeId, versionId);
- updateApiStatisticsCounter(Target.POLICY_TYPE, Result.SUCCESS, HttpMethod.GET);
+ updateApiStatisticsCounter(Target.POLICY_TYPE, HttpStatus.OK, HttpMethod.GET);
return makeOkResponse(requestId, serviceTemplate);
} catch (PfModelException | PfModelRuntimeException pfme) {
- LOGGER.warn("GET /policytypes/{}/versions/{}", policyTypeId, versionId, pfme);
- updateApiStatisticsCounter(Target.POLICY_TYPE, Result.FAILURE, HttpMethod.GET);
- return makeErrorResponse(requestId, pfme);
+ var msg = String.format("GET /policytypes/%s/versions/%s", policyTypeId, versionId);
+ updateApiStatisticsCounter(Target.POLICY_TYPE, HttpStatus.resolve(pfme.getErrorResponse().getResponseCode()
+ .getStatusCode()), HttpMethod.GET);
+ throw new PolicyApiRuntimeException(msg, pfme.getCause(), pfme.getErrorResponse(), requestId);
}
}
@@ -352,8 +372,7 @@ public class ApiRestController extends CommonRestController { *
* @return the Response object containing the results of the API operation
*/
- @GET
- @Path("/policytypes/{policyTypeId}/versions/latest")
+ @GetMapping("/policytypes/{policyTypeId}/versions/latest")
@ApiOperation(value = "Retrieve latest version of a policy type",
notes = "Returns latest version for the specified policy type", response = ToscaServiceTemplate.class,
responseHeaders = {
@@ -377,18 +396,19 @@ public class ApiRestController extends CommonRestController { @ApiResponse(code = HttpURLConnection.HTTP_FORBIDDEN, message = AUTHORIZATION_ERROR_MESSAGE),
@ApiResponse(code = HttpURLConnection.HTTP_NOT_FOUND, message = NOT_FOUND_MESSAGE),
@ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = SERVER_ERROR_MESSAGE)})
- public Response getLatestVersionOfPolicyType(
- @PathParam("policyTypeId") @ApiParam(value = "ID of policy type", required = true) String policyTypeId,
- @HeaderParam(REQUEST_ID_NAME) @ApiParam(REQUEST_ID_PARAM_DESCRIPTION) UUID requestId) {
-
- try (var policyTypeProvider = new PolicyTypeProvider()) {
+ public ResponseEntity<ToscaServiceTemplate> getLatestVersionOfPolicyType(
+ @PathVariable("policyTypeId") @ApiParam(value = "ID of policy type", required = true) String policyTypeId,
+ @RequestHeader(name = REQUEST_ID_NAME, required = false)
+ @ApiParam(REQUEST_ID_PARAM_DESCRIPTION) UUID requestId) {
+ try {
ToscaServiceTemplate serviceTemplate = policyTypeProvider.fetchLatestPolicyTypes(policyTypeId);
- updateApiStatisticsCounter(Target.POLICY_TYPE, Result.SUCCESS, HttpMethod.GET);
+ updateApiStatisticsCounter(Target.POLICY_TYPE, HttpStatus.OK, HttpMethod.GET);
return makeOkResponse(requestId, serviceTemplate);
} catch (PfModelException | PfModelRuntimeException pfme) {
- LOGGER.warn("GET /policytypes/{}/versions/latest", policyTypeId, pfme);
- updateApiStatisticsCounter(Target.POLICY_TYPE, Result.FAILURE, HttpMethod.GET);
- return makeErrorResponse(requestId, pfme);
+ var msg = String.format("GET /policytypes/%s/versions/latest", policyTypeId);
+ updateApiStatisticsCounter(Target.POLICY_TYPE, HttpStatus.resolve(pfme.getErrorResponse().getResponseCode()
+ .getStatusCode()), HttpMethod.GET);
+ throw new PolicyApiRuntimeException(msg, pfme.getCause(), pfme.getErrorResponse(), requestId);
}
}
@@ -399,8 +419,7 @@ public class ApiRestController extends CommonRestController { *
* @return the Response object containing the results of the API operation
*/
- @POST
- @Path("/policytypes")
+ @PostMapping("/policytypes")
@ApiOperation(value = "Create a new policy type", notes = "Client should provide TOSCA body of the new policy type",
authorizations = @Authorization(value = AUTHORIZATION_TYPE), tags = {"PolicyType", },
response = ToscaServiceTemplate.class,
@@ -425,22 +444,22 @@ public class ApiRestController extends CommonRestController { @ApiResponse(code = HttpURLConnection.HTTP_FORBIDDEN, message = AUTHORIZATION_ERROR_MESSAGE),
@ApiResponse(code = HttpURLConnection.HTTP_NOT_ACCEPTABLE, message = INVALID_PAYLOAD_MESSAGE),
@ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = SERVER_ERROR_MESSAGE)})
- public Response createPolicyType(
- @ApiParam(value = "Entity body of policy type", required = true) ToscaServiceTemplate body,
- @HeaderParam(REQUEST_ID_NAME) @ApiParam(REQUEST_ID_PARAM_DESCRIPTION) UUID requestId) {
-
+ public ResponseEntity<ToscaServiceTemplate> createPolicyType(
+ @RequestBody @ApiParam(value = "Entity body of policy type", required = true) ToscaServiceTemplate body,
+ @RequestHeader(name = REQUEST_ID_NAME, required = false)
+ @ApiParam(REQUEST_ID_PARAM_DESCRIPTION) UUID requestId) {
if (NetLoggerUtil.getNetworkLogger().isInfoEnabled()) {
NetLoggerUtil.log(EventType.IN, CommInfrastructure.REST, "/policytypes", toJson(body));
}
-
- try (var policyTypeProvider = new PolicyTypeProvider()) {
+ try {
ToscaServiceTemplate serviceTemplate = policyTypeProvider.createPolicyType(body);
- updateApiStatisticsCounter(Target.POLICY_TYPE, Result.SUCCESS, HttpMethod.POST);
+ updateApiStatisticsCounter(Target.POLICY_TYPE, HttpStatus.OK, HttpMethod.POST);
return makeOkResponse(requestId, serviceTemplate);
} catch (PfModelException | PfModelRuntimeException pfme) {
- LOGGER.warn("POST /policytypes", pfme);
- updateApiStatisticsCounter(Target.POLICY_TYPE, Result.FAILURE, HttpMethod.POST);
- return makeErrorResponse(requestId, pfme);
+ final var msg = "POST /policytypes";
+ updateApiStatisticsCounter(Target.POLICY_TYPE, HttpStatus.resolve(pfme.getErrorResponse().getResponseCode()
+ .getStatusCode()), HttpMethod.POST);
+ throw new PolicyApiRuntimeException(msg, pfme.getCause(), pfme.getErrorResponse(), requestId);
}
}
@@ -452,8 +471,7 @@ public class ApiRestController extends CommonRestController { *
* @return the Response object containing the results of the API operation
*/
- @DELETE
- @Path("/policytypes/{policyTypeId}/versions/{versionId}")
+ @DeleteMapping("/policytypes/{policyTypeId}/versions/{versionId}")
@ApiOperation(value = "Delete one version of a policy type",
notes = "Rule 1: pre-defined policy types cannot be deleted;"
+ "Rule 2: policy types that are in use (parameterized by a TOSCA policy) cannot be deleted."
@@ -481,19 +499,20 @@ public class ApiRestController extends CommonRestController { @ApiResponse(code = HttpURLConnection.HTTP_NOT_FOUND, message = NOT_FOUND_MESSAGE),
@ApiResponse(code = HttpURLConnection.HTTP_CONFLICT, message = HTTP_CONFLICT_MESSAGE),
@ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = SERVER_ERROR_MESSAGE)})
- public Response deleteSpecificVersionOfPolicyType(
- @PathParam("policyTypeId") @ApiParam(value = "ID of policy type", required = true) String policyTypeId,
- @PathParam("versionId") @ApiParam(value = "Version of policy type", required = true) String versionId,
- @HeaderParam(REQUEST_ID_NAME) @ApiParam(REQUEST_ID_PARAM_DESCRIPTION) UUID requestId) {
-
- try (var policyTypeProvider = new PolicyTypeProvider()) {
+ public ResponseEntity<ToscaServiceTemplate> deleteSpecificVersionOfPolicyType(
+ @PathVariable("policyTypeId") @ApiParam(value = "ID of policy type", required = true) String policyTypeId,
+ @PathVariable("versionId") @ApiParam(value = "Version of policy type", required = true) String versionId,
+ @RequestHeader(name = REQUEST_ID_NAME, required = false)
+ @ApiParam(REQUEST_ID_PARAM_DESCRIPTION) UUID requestId) {
+ try {
ToscaServiceTemplate serviceTemplate = policyTypeProvider.deletePolicyType(policyTypeId, versionId);
- updateApiStatisticsCounter(Target.POLICY_TYPE, Result.SUCCESS, HttpMethod.DELETE);
+ updateApiStatisticsCounter(Target.POLICY_TYPE, HttpStatus.OK, HttpMethod.DELETE);
return makeOkResponse(requestId, serviceTemplate);
} catch (PfModelException | PfModelRuntimeException pfme) {
- LOGGER.warn("DELETE /policytypes/{}/versions/{}", policyTypeId, versionId, pfme);
- updateApiStatisticsCounter(Target.POLICY_TYPE, Result.FAILURE, HttpMethod.DELETE);
- return makeErrorResponse(requestId, pfme);
+ var msg = String.format("DELETE /policytypes/%s/versions/%s", policyTypeId, versionId);
+ updateApiStatisticsCounter(Target.POLICY_TYPE, HttpStatus.resolve(pfme.getErrorResponse().getResponseCode()
+ .getStatusCode()), HttpMethod.DELETE);
+ throw new PolicyApiRuntimeException(msg, pfme.getCause(), pfme.getErrorResponse(), requestId);
}
}
@@ -505,8 +524,7 @@ public class ApiRestController extends CommonRestController { *
* @return the Response object containing the results of the API operation
*/
- @GET
- @Path("/policytypes/{policyTypeId}/versions/{policyTypeVersion}/policies")
+ @GetMapping("/policytypes/{policyTypeId}/versions/{policyTypeVersion}/policies")
@ApiOperation(
value = "Retrieve all versions of a policy created for a particular policy type version",
notes = "Returns a list of all versions of specified policy created for the specified policy type version",
@@ -536,24 +554,24 @@ public class ApiRestController extends CommonRestController { @ApiResponse(code = HttpURLConnection.HTTP_NOT_FOUND, message = NOT_FOUND_MESSAGE),
@ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = SERVER_ERROR_MESSAGE)
})
- public Response getAllPolicies(
- @PathParam("policyTypeId") @ApiParam(value = "ID of policy type", required = true) String policyTypeId,
- @PathParam("policyTypeVersion") @ApiParam(value = "Version of policy type",
+ public ResponseEntity<ToscaServiceTemplate> getAllPolicies(
+ @PathVariable("policyTypeId") @ApiParam(value = "ID of policy type", required = true) String policyTypeId,
+ @PathVariable("policyTypeVersion") @ApiParam(value = "Version of policy type",
required = true) String policyTypeVersion,
- @HeaderParam(REQUEST_ID_NAME) @ApiParam(REQUEST_ID_PARAM_DESCRIPTION) UUID requestId,
- @QueryParam("mode") @DefaultValue("bare") @ApiParam("Fetch mode for policies, BARE for bare policies (default),"
- + " REFERENCED for fully referenced policies") PolicyFetchMode mode
- ) {
-
- try (var policyProvider = new PolicyProvider()) {
+ @RequestHeader(name = REQUEST_ID_NAME, required = false)
+ @ApiParam(REQUEST_ID_PARAM_DESCRIPTION) UUID requestId,
+ @RequestParam(name = "mode", defaultValue = "bare") @ApiParam("Fetch mode for policies, BARE for bare"
+ + " policies (default), REFERENCED for fully referenced policies") PolicyFetchMode mode) {
+ try {
ToscaServiceTemplate serviceTemplate =
policyProvider.fetchPolicies(policyTypeId, policyTypeVersion, null, null, mode);
- updateApiStatisticsCounter(Target.POLICY, Result.SUCCESS, HttpMethod.GET);
+ updateApiStatisticsCounter(Target.POLICY, HttpStatus.OK, HttpMethod.GET);
return makeOkResponse(requestId, serviceTemplate);
} catch (PfModelException | PfModelRuntimeException pfme) {
- LOGGER.warn("GET /policytypes/{}/versions/{}/policies", policyTypeId, policyTypeVersion, pfme);
- updateApiStatisticsCounter(Target.POLICY, Result.FAILURE, HttpMethod.GET);
- return makeErrorResponse(requestId, pfme);
+ var msg = String.format("GET /policytypes/%s/versions/%s/policies", policyTypeId, policyTypeVersion);
+ updateApiStatisticsCounter(Target.POLICY, HttpStatus.resolve(pfme.getErrorResponse().getResponseCode()
+ .getStatusCode()), HttpMethod.GET);
+ throw new PolicyApiRuntimeException(msg, pfme.getCause(), pfme.getErrorResponse(), requestId);
}
}
@@ -566,8 +584,7 @@ public class ApiRestController extends CommonRestController { *
* @return the Response object containing the results of the API operation
*/
- @GET
- @Path("/policytypes/{policyTypeId}/versions/{policyTypeVersion}/policies/{policyId}")
+ @GetMapping("/policytypes/{policyTypeId}/versions/{policyTypeVersion}/policies/{policyId}")
@ApiOperation(value = "Retrieve all version details of a policy created for a particular policy type version",
notes = "Returns a list of all version details of the specified policy", response = ToscaServiceTemplate.class,
responseHeaders = {
@@ -595,24 +612,26 @@ public class ApiRestController extends CommonRestController { @ApiResponse(code = HttpURLConnection.HTTP_NOT_FOUND, message = NOT_FOUND_MESSAGE),
@ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = SERVER_ERROR_MESSAGE)
})
- public Response getAllVersionsOfPolicy(
- @PathParam("policyTypeId") @ApiParam(value = "ID of policy type", required = true) String policyTypeId,
- @PathParam("policyTypeVersion") @ApiParam(value = "Version of policy type",
+ public ResponseEntity<ToscaServiceTemplate> getAllVersionsOfPolicy(
+ @PathVariable("policyTypeId") @ApiParam(value = "ID of policy type", required = true) String policyTypeId,
+ @PathVariable("policyTypeVersion") @ApiParam(value = "Version of policy type",
required = true) String policyTypeVersion,
- @PathParam("policyId") @ApiParam(value = "ID of policy", required = true) String policyId,
- @HeaderParam(REQUEST_ID_NAME) @ApiParam(REQUEST_ID_PARAM_DESCRIPTION) UUID requestId,
- @QueryParam("mode") @DefaultValue("bare") @ApiParam("Fetch mode for policies, BARE for bare policies (default),"
- + " REFERENCED for fully referenced policies") PolicyFetchMode mode
- ) {
- try (var policyProvider = new PolicyProvider()) {
+ @PathVariable("policyId") @ApiParam(value = "ID of policy", required = true) String policyId,
+ @RequestHeader(name = REQUEST_ID_NAME, required = false) @ApiParam(REQUEST_ID_PARAM_DESCRIPTION) UUID requestId,
+ @RequestParam(name = "mode", defaultValue = "bare")
+ @ApiParam("Fetch mode for policies, BARE for bare policies (default),"
+ + " REFERENCED for fully referenced policies") PolicyFetchMode mode) {
+ try {
ToscaServiceTemplate serviceTemplate =
policyProvider.fetchPolicies(policyTypeId, policyTypeVersion, policyId, null, mode);
- updateApiStatisticsCounter(Target.POLICY, Result.SUCCESS, HttpMethod.GET);
+ updateApiStatisticsCounter(Target.POLICY, HttpStatus.OK, HttpMethod.GET);
return makeOkResponse(requestId, serviceTemplate);
} catch (PfModelException | PfModelRuntimeException pfme) {
- LOGGER.warn("/policytypes/{}/versions/{}/policies/{}", policyTypeId, policyTypeVersion, policyId, pfme);
- updateApiStatisticsCounter(Target.POLICY, Result.FAILURE, HttpMethod.GET);
- return makeErrorResponse(requestId, pfme);
+ var msg = String.format("/policytypes/%s/versions/$s/policies/%s",
+ policyTypeId, policyTypeVersion, policyId);
+ updateApiStatisticsCounter(Target.POLICY, HttpStatus.resolve(pfme.getErrorResponse().getResponseCode()
+ .getStatusCode()), HttpMethod.GET);
+ throw new PolicyApiRuntimeException(msg, pfme.getCause(), pfme.getErrorResponse(), requestId);
}
}
@@ -626,8 +645,7 @@ public class ApiRestController extends CommonRestController { *
* @return the Response object containing the results of the API operation
*/
- @GET
- @Path("/policytypes/{policyTypeId}/versions/{policyTypeVersion}/policies/{policyId}/versions/{policyVersion}")
+ @GetMapping("/policytypes/{policyTypeId}/versions/{policyTypeVersion}/policies/{policyId}/versions/{policyVersion}")
@ApiOperation(value = "Retrieve one version of a policy created for a particular policy type version",
notes = "Returns a particular version of specified policy created for the specified policy type version",
response = ToscaServiceTemplate.class,
@@ -656,26 +674,27 @@ public class ApiRestController extends CommonRestController { @ApiResponse(code = HttpURLConnection.HTTP_NOT_FOUND, message = NOT_FOUND_MESSAGE),
@ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = SERVER_ERROR_MESSAGE)
})
- public Response getSpecificVersionOfPolicy(
- @PathParam("policyTypeId") @ApiParam(value = "ID of policy type", required = true) String policyTypeId,
- @PathParam("policyTypeVersion") @ApiParam(value = "Version of policy type",
+ public ResponseEntity<ToscaServiceTemplate> getSpecificVersionOfPolicy(
+ @PathVariable("policyTypeId") @ApiParam(value = "ID of policy type", required = true) String policyTypeId,
+ @PathVariable("policyTypeVersion") @ApiParam(value = "Version of policy type",
required = true) String policyTypeVersion,
- @PathParam("policyId") @ApiParam(value = "ID of policy", required = true) String policyId,
- @PathParam("policyVersion") @ApiParam(value = "Version of policy", required = true) String policyVersion,
- @HeaderParam(REQUEST_ID_NAME) @ApiParam(REQUEST_ID_PARAM_DESCRIPTION) UUID requestId,
- @QueryParam("mode") @DefaultValue("bare") @ApiParam("Fetch mode for policies, BARE for bare policies (default),"
- + " REFERENCED for fully referenced policies") PolicyFetchMode mode
- ) {
- try (var policyProvider = new PolicyProvider()) {
+ @PathVariable("policyId") @ApiParam(value = "ID of policy", required = true) String policyId,
+ @PathVariable("policyVersion") @ApiParam(value = "Version of policy", required = true) String policyVersion,
+ @RequestHeader(name = REQUEST_ID_NAME, required = false)
+ @ApiParam(REQUEST_ID_PARAM_DESCRIPTION) UUID requestId,
+ @RequestParam(name = "mode", defaultValue = "bare") @ApiParam("Fetch mode for policies, BARE for bare policies"
+ + " (default), REFERENCED for fully referenced policies") PolicyFetchMode mode) {
+ try {
ToscaServiceTemplate serviceTemplate =
policyProvider.fetchPolicies(policyTypeId, policyTypeVersion, policyId, policyVersion, mode);
- updateApiStatisticsCounter(Target.POLICY, Result.SUCCESS, HttpMethod.GET);
+ updateApiStatisticsCounter(Target.POLICY, HttpStatus.OK, HttpMethod.GET);
return makeOkResponse(requestId, serviceTemplate);
} catch (PfModelException | PfModelRuntimeException pfme) {
- LOGGER.warn("GET /policytypes/{}/versions/{}/policies/{}/versions/{}", policyTypeId, policyTypeVersion,
- policyId, policyVersion, pfme);
- updateApiStatisticsCounter(Target.POLICY, Result.FAILURE, HttpMethod.GET);
- return makeErrorResponse(requestId, pfme);
+ var msg = String.format("GET /policytypes/%s/versions/%s/policies/%s/versions/%s",
+ policyTypeId, policyTypeVersion, policyId, policyVersion);
+ updateApiStatisticsCounter(Target.POLICY, HttpStatus.resolve(pfme.getErrorResponse().getResponseCode()
+ .getStatusCode()), HttpMethod.GET);
+ throw new PolicyApiRuntimeException(msg, pfme.getCause(), pfme.getErrorResponse(), requestId);
}
}
@@ -688,8 +707,7 @@ public class ApiRestController extends CommonRestController { *
* @return the Response object containing the results of the API operation
*/
- @GET
- @Path("/policytypes/{policyTypeId}/versions/{policyTypeVersion}/policies/{policyId}/versions/latest")
+ @GetMapping("/policytypes/{policyTypeId}/versions/{policyTypeVersion}/policies/{policyId}/versions/latest")
@ApiOperation(value = "Retrieve the latest version of a particular policy",
notes = "Returns the latest version of specified policy", response = ToscaServiceTemplate.class,
responseHeaders = {
@@ -713,25 +731,26 @@ public class ApiRestController extends CommonRestController { @ApiResponse(code = HttpURLConnection.HTTP_FORBIDDEN, message = AUTHORIZATION_ERROR_MESSAGE),
@ApiResponse(code = HttpURLConnection.HTTP_NOT_FOUND, message = NOT_FOUND_MESSAGE),
@ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = SERVER_ERROR_MESSAGE)})
- public Response getLatestVersionOfPolicy(
- @PathParam("policyTypeId") @ApiParam(value = "ID of policy type", required = true) String policyTypeId,
- @PathParam("policyTypeVersion") @ApiParam(value = "Version of policy type",
+ public ResponseEntity<ToscaServiceTemplate> getLatestVersionOfPolicy(
+ @PathVariable("policyTypeId") @ApiParam(value = "ID of policy type", required = true) String policyTypeId,
+ @PathVariable("policyTypeVersion") @ApiParam(value = "Version of policy type",
required = true) String policyTypeVersion,
- @PathParam("policyId") @ApiParam(value = "ID of policy", required = true) String policyId,
- @HeaderParam(REQUEST_ID_NAME) @ApiParam(REQUEST_ID_PARAM_DESCRIPTION) UUID requestId,
- @QueryParam("mode") @ApiParam("Fetch mode for policies, TERSE for bare policies (default), "
- + "REFERENCED for fully referenced policies") PolicyFetchMode mode) {
-
- try (var policyProvider = new PolicyProvider()) {
+ @PathVariable("policyId") @ApiParam(value = "ID of policy", required = true) String policyId,
+ @RequestHeader(name = REQUEST_ID_NAME, required = false)
+ @ApiParam(REQUEST_ID_PARAM_DESCRIPTION) UUID requestId,
+ @RequestParam(name = "mode", defaultValue = "bare") @ApiParam("Fetch mode for policies, TERSE for bare "
+ + "policies (default), REFERENCED for fully referenced policies") PolicyFetchMode mode) {
+ try {
ToscaServiceTemplate serviceTemplate =
policyProvider.fetchLatestPolicies(policyTypeId, policyTypeVersion, policyId, mode);
- updateApiStatisticsCounter(Target.POLICY, Result.SUCCESS, HttpMethod.GET);
+ updateApiStatisticsCounter(Target.POLICY, HttpStatus.OK, HttpMethod.GET);
return makeOkResponse(requestId, serviceTemplate);
} catch (PfModelException | PfModelRuntimeException pfme) {
- LOGGER.warn("GET /policytypes/{}/versions/{}/policies/{}/versions/latest", policyTypeId, policyTypeVersion,
- policyId, pfme);
- updateApiStatisticsCounter(Target.POLICY, Result.FAILURE, HttpMethod.GET);
- return makeErrorResponse(requestId, pfme);
+ var msg = String.format("GET /policytypes/%s/versions/%s/policies/%s/versions/latest",
+ policyTypeId, policyTypeVersion, policyId);
+ updateApiStatisticsCounter(Target.POLICY, HttpStatus.resolve(pfme.getErrorResponse().getResponseCode()
+ .getStatusCode()), HttpMethod.GET);
+ throw new PolicyApiRuntimeException(msg, pfme.getCause(), pfme.getErrorResponse(), requestId);
}
}
@@ -744,8 +763,7 @@ public class ApiRestController extends CommonRestController { *
* @return the Response object containing the results of the API operation
*/
- @POST
- @Path("/policytypes/{policyTypeId}/versions/{policyTypeVersion}/policies")
+ @PostMapping("/policytypes/{policyTypeId}/versions/{policyTypeVersion}/policies")
@ApiOperation(value = "Create a new policy for a policy type version",
notes = "Client should provide TOSCA body of the new policy",
authorizations = @Authorization(value = AUTHORIZATION_TYPE), tags = {"Policy", },
@@ -772,26 +790,26 @@ public class ApiRestController extends CommonRestController { @ApiResponse(code = HttpURLConnection.HTTP_NOT_FOUND, message = NOT_FOUND_MESSAGE),
@ApiResponse(code = HttpURLConnection.HTTP_NOT_ACCEPTABLE, message = INVALID_PAYLOAD_MESSAGE),
@ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = SERVER_ERROR_MESSAGE)})
- public Response createPolicy(
- @PathParam("policyTypeId") @ApiParam(value = "ID of policy type", required = true) String policyTypeId,
- @PathParam("policyTypeVersion") @ApiParam(value = "Version of policy type",
+ public ResponseEntity<ToscaServiceTemplate> createPolicy(
+ @PathVariable("policyTypeId") @ApiParam(value = "ID of policy type", required = true) String policyTypeId,
+ @PathVariable("policyTypeVersion") @ApiParam(value = "Version of policy type",
required = true) String policyTypeVersion,
- @HeaderParam(REQUEST_ID_NAME) @ApiParam(REQUEST_ID_PARAM_DESCRIPTION) UUID requestId,
- @ApiParam(value = "Entity body of policy", required = true) ToscaServiceTemplate body) {
-
+ @RequestHeader(name = REQUEST_ID_NAME, required = false)
+ @ApiParam(REQUEST_ID_PARAM_DESCRIPTION) UUID requestId,
+ @RequestBody @ApiParam(value = "Entity body of policy", required = true) ToscaServiceTemplate body) {
if (NetLoggerUtil.getNetworkLogger().isInfoEnabled()) {
NetLoggerUtil.log(EventType.IN, CommInfrastructure.REST,
"/policytypes/" + policyTypeId + "/versions/" + policyTypeVersion + "/policies", toJson(body));
}
-
- try (var policyProvider = new PolicyProvider()) {
+ try {
ToscaServiceTemplate serviceTemplate = policyProvider.createPolicy(policyTypeId, policyTypeVersion, body);
- updateApiStatisticsCounter(Target.POLICY, Result.SUCCESS, HttpMethod.POST);
+ updateApiStatisticsCounter(Target.POLICY, HttpStatus.OK, HttpMethod.POST);
return makeOkResponse(requestId, serviceTemplate);
} catch (PfModelException | PfModelRuntimeException pfme) {
- LOGGER.warn("POST /policytypes/{}/versions/{}/policies", policyTypeId, policyTypeVersion, pfme);
- updateApiStatisticsCounter(Target.POLICY, Result.FAILURE, HttpMethod.POST);
- return makeErrorResponse(requestId, pfme);
+ var msg = String.format("POST /policytypes/%s/versions/%s/policies", policyTypeId, policyTypeVersion);
+ updateApiStatisticsCounter(Target.POLICY, HttpStatus.resolve(pfme.getErrorResponse().getResponseCode()
+ .getStatusCode()), HttpMethod.POST);
+ throw new PolicyApiRuntimeException(msg, pfme.getCause(), pfme.getErrorResponse(), requestId);
}
}
@@ -805,8 +823,8 @@ public class ApiRestController extends CommonRestController { *
* @return the Response object containing the results of the API operation
*/
- @DELETE
- @Path("/policytypes/{policyTypeId}/versions/{policyTypeVersion}/policies/{policyId}/versions/{policyVersion}")
+ @DeleteMapping("/policytypes/{policyTypeId}/versions/{policyTypeVersion}/policies/{policyId}/"
+ + "versions/{policyVersion}")
@ApiOperation(value = "Delete a particular version of a policy",
notes = "Rule: the version that has been deployed in PDP group(s) cannot be deleted",
authorizations = @Authorization(value = AUTHORIZATION_TYPE), tags = {"Policy", },
@@ -832,24 +850,25 @@ public class ApiRestController extends CommonRestController { @ApiResponse(code = HttpURLConnection.HTTP_NOT_FOUND, message = NOT_FOUND_MESSAGE),
@ApiResponse(code = HttpURLConnection.HTTP_CONFLICT, message = HTTP_CONFLICT_MESSAGE),
@ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = SERVER_ERROR_MESSAGE)})
- public Response deleteSpecificVersionOfPolicy(
- @PathParam("policyTypeId") @ApiParam(value = "PolicyType ID", required = true) String policyTypeId,
- @PathParam("policyTypeVersion") @ApiParam(value = "Version of policy type",
+ public ResponseEntity<ToscaServiceTemplate> deleteSpecificVersionOfPolicy(
+ @PathVariable("policyTypeId") @ApiParam(value = "PolicyType ID", required = true) String policyTypeId,
+ @PathVariable("policyTypeVersion") @ApiParam(value = "Version of policy type",
required = true) String policyTypeVersion,
- @PathParam("policyId") @ApiParam(value = "ID of policy", required = true) String policyId,
- @PathParam("policyVersion") @ApiParam(value = "Version of policy", required = true) String policyVersion,
- @HeaderParam(REQUEST_ID_NAME) @ApiParam(REQUEST_ID_PARAM_DESCRIPTION) UUID requestId) {
-
- try (var policyProvider = new PolicyProvider()) {
+ @PathVariable("policyId") @ApiParam(value = "ID of policy", required = true) String policyId,
+ @PathVariable("policyVersion") @ApiParam(value = "Version of policy", required = true) String policyVersion,
+ @RequestHeader(name = REQUEST_ID_NAME, required = false)
+ @ApiParam(REQUEST_ID_PARAM_DESCRIPTION) UUID requestId) {
+ try {
ToscaServiceTemplate serviceTemplate =
policyProvider.deletePolicy(policyTypeId, policyTypeVersion, policyId, policyVersion);
- updateApiStatisticsCounter(Target.POLICY, Result.SUCCESS, HttpMethod.DELETE);
+ updateApiStatisticsCounter(Target.POLICY, HttpStatus.OK, HttpMethod.DELETE);
return makeOkResponse(requestId, serviceTemplate);
} catch (PfModelException | PfModelRuntimeException pfme) {
- LOGGER.warn("DELETE /policytypes/{}/versions/{}/policies/{}/versions/{}", policyTypeId, policyTypeVersion,
- policyId, policyVersion, pfme);
- updateApiStatisticsCounter(Target.POLICY, Result.FAILURE, HttpMethod.DELETE);
- return makeErrorResponse(requestId, pfme);
+ var msg = String.format("DELETE /policytypes/%s/versions/%s/policies/%s/versions/%s",
+ policyTypeId, policyTypeVersion, policyId, policyVersion);
+ updateApiStatisticsCounter(Target.POLICY, HttpStatus.resolve(pfme.getErrorResponse().getResponseCode()
+ .getStatusCode()), HttpMethod.DELETE);
+ throw new PolicyApiRuntimeException(msg, pfme.getCause(), pfme.getErrorResponse(), requestId);
}
}
@@ -858,8 +877,7 @@ public class ApiRestController extends CommonRestController { *
* @return the Response object containing the results of the API operation
*/
- @GET
- @Path("/policies")
+ @GetMapping("/policies")
@ApiOperation(value = "Retrieve all versions of available policies",
notes = "Returns all version of available policies",
response = ToscaServiceTemplate.class,
@@ -888,24 +906,25 @@ public class ApiRestController extends CommonRestController { @ApiResponse(code = HttpURLConnection.HTTP_NOT_FOUND, message = NOT_FOUND_MESSAGE),
@ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = SERVER_ERROR_MESSAGE)
})
- public Response getPolicies(
- @HeaderParam(REQUEST_ID_NAME) @ApiParam(REQUEST_ID_PARAM_DESCRIPTION) UUID requestId,
- @QueryParam("mode") @DefaultValue("bare") @ApiParam("Fetch mode for policies, BARE for bare policies (default),"
- + " REFERENCED for fully referenced policies") PolicyFetchMode mode
- ) {
- try (var policyProvider = new PolicyProvider()) {
+ public ResponseEntity<ToscaServiceTemplate> getPolicies(
+ @RequestHeader(name = REQUEST_ID_NAME, required = false)
+ @ApiParam(REQUEST_ID_PARAM_DESCRIPTION) UUID requestId,
+ @RequestParam(name = "mode", defaultValue = "bare") @ApiParam("Fetch mode for policies, BARE for bare"
+ + " policies (default), REFERENCED for fully referenced policies") PolicyFetchMode mode) {
+ try {
ToscaServiceTemplate serviceTemplate =
policyProvider.fetchPolicies(null, null, null, null, mode);
- updateApiStatisticsCounter(Target.POLICY, Result.SUCCESS, HttpMethod.GET);
+ updateApiStatisticsCounter(Target.POLICY, HttpStatus.OK, HttpMethod.GET);
return makeOkResponse(requestId, serviceTemplate);
} catch (PfModelException | PfModelRuntimeException pfme) {
- LOGGER.warn("GET /policies/ --", pfme);
- updateApiStatisticsCounter(Target.POLICY, Result.FAILURE, HttpMethod.GET);
+ final var msg = "GET /policies/ --";
+ updateApiStatisticsCounter(Target.POLICY, HttpStatus.resolve(pfme.getErrorResponse().getResponseCode()
+ .getStatusCode()), HttpMethod.GET);
if (pfme.getErrorResponse().getResponseCode().equals(Status.NOT_FOUND)) {
pfme.getErrorResponse().setErrorMessage(ERROR_MESSAGE_NO_POLICIES_FOUND);
pfme.getErrorResponse().setErrorDetails(List.of(ERROR_MESSAGE_NO_POLICIES_FOUND));
}
- return makeErrorResponse(requestId, pfme);
+ throw new PolicyApiRuntimeException(msg, pfme.getCause(), pfme.getErrorResponse(), requestId);
}
}
@@ -917,8 +936,7 @@ public class ApiRestController extends CommonRestController { *
* @return the Response object containing the results of the API operation
*/
- @GET
- @Path("/policies/{policyId}/versions/{policyVersion}")
+ @GetMapping("/policies/{policyId}/versions/{policyVersion}")
@ApiOperation(value = "Retrieve specific version of a specified policy",
notes = "Returns a particular version of specified policy",
response = ToscaServiceTemplate.class,
@@ -947,22 +965,23 @@ public class ApiRestController extends CommonRestController { @ApiResponse(code = HttpURLConnection.HTTP_NOT_FOUND, message = NOT_FOUND_MESSAGE),
@ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = SERVER_ERROR_MESSAGE)
})
- public Response getSpecificPolicy(
- @PathParam("policyId") @ApiParam(value = "Name of policy", required = true) String policyId,
- @PathParam("policyVersion") @ApiParam(value = "Version of policy", required = true) String policyVersion,
- @HeaderParam(REQUEST_ID_NAME) @ApiParam(REQUEST_ID_PARAM_DESCRIPTION) UUID requestId,
- @QueryParam("mode") @DefaultValue("bare") @ApiParam("Fetch mode for policies, BARE for bare policies (default),"
- + " REFERENCED for fully referenced policies") PolicyFetchMode mode
- ) {
- try (var policyProvider = new PolicyProvider()) {
+ public ResponseEntity<ToscaServiceTemplate> getSpecificPolicy(
+ @PathVariable("policyId") @ApiParam(value = "Name of policy", required = true) String policyId,
+ @PathVariable("policyVersion") @ApiParam(value = "Version of policy", required = true) String policyVersion,
+ @RequestHeader(name = REQUEST_ID_NAME, required = false)
+ @ApiParam(REQUEST_ID_PARAM_DESCRIPTION) UUID requestId,
+ @RequestParam(name = "mode", defaultValue = "bare") @ApiParam("Fetch mode for policies, BARE for bare"
+ + " policies (default), REFERENCED for fully referenced policies") PolicyFetchMode mode) {
+ try {
ToscaServiceTemplate serviceTemplate =
policyProvider.fetchPolicies(null, null, policyId, policyVersion, mode);
- updateApiStatisticsCounter(Target.POLICY, Result.SUCCESS, HttpMethod.GET);
+ updateApiStatisticsCounter(Target.POLICY, HttpStatus.OK, HttpMethod.GET);
return makeOkResponse(requestId, serviceTemplate);
} catch (PfModelException | PfModelRuntimeException pfme) {
- LOGGER.warn("GET /policies/{}/versions/{}", policyId, policyVersion, pfme);
- updateApiStatisticsCounter(Target.POLICY, Result.FAILURE, HttpMethod.GET);
- return makeErrorResponse(requestId, pfme);
+ var msg = String.format("GET /policies/%s/versions/%s", policyId, policyVersion);
+ updateApiStatisticsCounter(Target.POLICY, HttpStatus.resolve(pfme.getErrorResponse().getResponseCode()
+ .getStatusCode()), HttpMethod.GET);
+ throw new PolicyApiRuntimeException(msg, pfme.getCause(), pfme.getErrorResponse(), requestId);
}
}
@@ -973,8 +992,7 @@ public class ApiRestController extends CommonRestController { *
* @return the Response object containing the results of the API operation
*/
- @POST
- @Path("/policies")
+ @PostMapping("/policies")
@ApiOperation(value = "Create one or more new policies",
notes = "Client should provide TOSCA body of the new polic(ies)",
authorizations = @Authorization(value = AUTHORIZATION_TYPE), tags = {"Policy", },
@@ -1001,22 +1019,22 @@ public class ApiRestController extends CommonRestController { @ApiResponse(code = HttpURLConnection.HTTP_NOT_FOUND, message = NOT_FOUND_MESSAGE),
@ApiResponse(code = HttpURLConnection.HTTP_NOT_ACCEPTABLE, message = INVALID_PAYLOAD_MESSAGE),
@ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = SERVER_ERROR_MESSAGE)})
- public Response createPolicies(
- @HeaderParam(REQUEST_ID_NAME) @ApiParam(REQUEST_ID_PARAM_DESCRIPTION) UUID requestId,
- @ApiParam(value = "Entity body of policy", required = true) ToscaServiceTemplate body) {
-
+ public ResponseEntity<ToscaServiceTemplate> createPolicies(
+ @RequestHeader(name = REQUEST_ID_NAME, required = false)
+ @ApiParam(REQUEST_ID_PARAM_DESCRIPTION) UUID requestId,
+ @RequestBody @ApiParam(value = "Entity body of policy", required = true) ToscaServiceTemplate body) {
if (NetLoggerUtil.getNetworkLogger().isInfoEnabled()) {
NetLoggerUtil.log(EventType.IN, CommInfrastructure.REST, "/policies", toJson(body));
}
-
- try (var policyProvider = new PolicyProvider()) {
+ try {
ToscaServiceTemplate serviceTemplate = policyProvider.createPolicies(body);
- updateApiStatisticsCounter(Target.POLICY, Result.SUCCESS, HttpMethod.POST);
+ updateApiStatisticsCounter(Target.POLICY, HttpStatus.OK, HttpMethod.POST);
return makeOkResponse(requestId, serviceTemplate);
} catch (PfModelException | PfModelRuntimeException pfme) {
- LOGGER.warn("POST /policies", pfme);
- updateApiStatisticsCounter(Target.POLICY, Result.FAILURE, HttpMethod.POST);
- return makeErrorResponse(requestId, pfme);
+ final var msg = "POST /policies";
+ updateApiStatisticsCounter(Target.POLICY, HttpStatus.resolve(pfme.getErrorResponse().getResponseCode()
+ .getStatusCode()), HttpMethod.POST);
+ throw new PolicyApiRuntimeException(msg, pfme.getCause(), pfme.getErrorResponse(), requestId);
}
}
@@ -1028,8 +1046,7 @@ public class ApiRestController extends CommonRestController { *
* @return the Response object containing the results of the API operation
*/
- @DELETE
- @Path("/policies/{policyId}/versions/{policyVersion}")
+ @DeleteMapping("/policies/{policyId}/versions/{policyVersion}")
@ApiOperation(value = "Delete a particular version of a policy",
notes = "Rule: the version that has been deployed in PDP group(s) cannot be deleted",
authorizations = @Authorization(value = AUTHORIZATION_TYPE), tags = {"Policy", },
@@ -1055,47 +1072,33 @@ public class ApiRestController extends CommonRestController { @ApiResponse(code = HttpURLConnection.HTTP_NOT_FOUND, message = NOT_FOUND_MESSAGE),
@ApiResponse(code = HttpURLConnection.HTTP_CONFLICT, message = HTTP_CONFLICT_MESSAGE),
@ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = SERVER_ERROR_MESSAGE)})
- public Response deleteSpecificPolicy(
- @PathParam("policyId") @ApiParam(value = "ID of policy", required = true) String policyId,
- @PathParam("policyVersion") @ApiParam(value = "Version of policy", required = true) String policyVersion,
- @HeaderParam(REQUEST_ID_NAME) @ApiParam(REQUEST_ID_PARAM_DESCRIPTION) UUID requestId) {
-
- try (var policyProvider = new PolicyProvider()) {
+ public ResponseEntity<ToscaServiceTemplate> deleteSpecificPolicy(
+ @PathVariable("policyId") @ApiParam(value = "ID of policy", required = true) String policyId,
+ @PathVariable("policyVersion") @ApiParam(value = "Version of policy", required = true) String policyVersion,
+ @RequestHeader(name = REQUEST_ID_NAME, required = false)
+ @ApiParam(REQUEST_ID_PARAM_DESCRIPTION) UUID requestId) {
+ try {
ToscaServiceTemplate serviceTemplate =
policyProvider.deletePolicy(null, null, policyId, policyVersion);
- updateApiStatisticsCounter(Target.POLICY, Result.SUCCESS, HttpMethod.DELETE);
+ updateApiStatisticsCounter(Target.POLICY, HttpStatus.OK, HttpMethod.DELETE);
return makeOkResponse(requestId, serviceTemplate);
} catch (PfModelException | PfModelRuntimeException pfme) {
- LOGGER.warn("DELETE /policies/{}/versions/{}", policyId, policyVersion, pfme);
- updateApiStatisticsCounter(Target.POLICY, Result.FAILURE, HttpMethod.DELETE);
- return makeErrorResponse(requestId, pfme);
+ var msg = String.format("DELETE /policies/%s/versions/%s", policyId, policyVersion);
+ updateApiStatisticsCounter(Target.POLICY, HttpStatus.resolve(pfme.getErrorResponse().getResponseCode()
+ .getStatusCode()), HttpMethod.DELETE);
+ throw new PolicyApiRuntimeException(msg, pfme.getCause(), pfme.getErrorResponse(), requestId);
}
}
-
-
- private enum Target {
- POLICY,
- POLICY_TYPE,
- OTHER
- }
-
- private enum Result {
- SUCCESS,
- FAILURE
- }
-
- private enum HttpMethod {
- POST,
- GET,
- DELETE
+ @ExceptionHandler(value = {PolicyApiRuntimeException.class})
+ protected ResponseEntity<Object> handleException(PolicyApiRuntimeException ex) {
+ LOGGER.warn(ex.getMessage(), ex.getCause());
+ return makeErrorResponse(ex.getRequestId(), ex.getErrorResponse(),
+ ex.getErrorResponse().getResponseCode().getStatusCode());
}
- private void updateApiStatisticsCounter(Target target, Result result, HttpMethod http) {
-
- var mgr = ApiStatisticsManager.getInstance();
+ private void updateApiStatisticsCounter(Target target, HttpStatus result, HttpMethod http) {
mgr.updateTotalApiCallCount();
-
switch (target) {
case POLICY:
updatePolicyStats(result, http);
@@ -1109,10 +1112,8 @@ public class ApiRestController extends CommonRestController { }
}
- private void updatePolicyStats(Result result, HttpMethod http) {
- var mgr = ApiStatisticsManager.getInstance();
-
- if (result == Result.SUCCESS) {
+ private void updatePolicyStats(HttpStatus result, HttpMethod http) {
+ if (result.equals(HttpStatus.OK)) {
switch (http) {
case GET:
mgr.updateApiCallSuccessCount();
@@ -1157,10 +1158,8 @@ public class ApiRestController extends CommonRestController { }
}
- private void updatePolicyTypeStats(Result result, HttpMethod http) {
- var mgr = ApiStatisticsManager.getInstance();
-
- if (result == Result.SUCCESS) {
+ private void updatePolicyTypeStats(HttpStatus result, HttpMethod http) {
+ if (result.equals(HttpStatus.OK)) {
switch (http) {
case GET:
mgr.updateApiCallSuccessCount();
@@ -1204,4 +1203,4 @@ public class ApiRestController extends CommonRestController { }
}
}
-}
+}
\ No newline at end of file diff --git a/main/src/main/java/org/onap/policy/api/main/rest/ApiStatisticsManager.java b/main/src/main/java/org/onap/policy/api/main/rest/ApiStatisticsManager.java index 2a4a46ae..b497c7f0 100644 --- a/main/src/main/java/org/onap/policy/api/main/rest/ApiStatisticsManager.java +++ b/main/src/main/java/org/onap/policy/api/main/rest/ApiStatisticsManager.java @@ -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. @@ -23,21 +23,20 @@ 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 diff --git a/main/src/main/java/org/onap/policy/api/main/rest/CommonRestController.java b/main/src/main/java/org/onap/policy/api/main/rest/CommonRestController.java index b059490b..0389e0f6 100644 --- a/main/src/main/java/org/onap/policy/api/main/rest/CommonRestController.java +++ b/main/src/main/java/org/onap/policy/api/main/rest/CommonRestController.java @@ -3,6 +3,7 @@ * ONAP Policy API
* ================================================================================
* 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.
@@ -23,14 +24,13 @@ package org.onap.policy.api.main.rest;
import java.util.UUID;
-import javax.ws.rs.core.Response;
-import javax.ws.rs.core.Response.ResponseBuilder;
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.models.errors.concepts.ErrorResponseInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
+import org.springframework.http.HttpHeaders;
+import org.springframework.http.ResponseEntity;
/**
* Super class from which REST controllers are derived.
@@ -41,27 +41,33 @@ public class CommonRestController { private final Coder coder = new StandardCoder();
-
- protected Response makeOkResponse(UUID requestId, Object respEntity) {
- return addLoggingHeaders(addVersionControlHeaders(Response.status(Response.Status.OK)), requestId)
- .entity(respEntity).build();
+ protected <T> ResponseEntity<T> makeOkResponse(UUID requestId, T respEntity) {
+ HttpHeaders headers = new HttpHeaders();
+ addVersionControlHeaders(headers);
+ addLoggingHeaders(headers, requestId);
+ return ResponseEntity.ok().headers(headers).body(respEntity);
}
- protected <T extends ErrorResponseInfo> Response makeErrorResponse(UUID requestId, T pfme) {
- return addLoggingHeaders(addVersionControlHeaders(Response.status(pfme.getErrorResponse().getResponseCode())),
- requestId).entity(pfme.getErrorResponse()).build();
+ protected <T> ResponseEntity<T> makeErrorResponse(UUID requestId, T respEntity, int status) {
+ HttpHeaders headers = new HttpHeaders();
+ addVersionControlHeaders(headers);
+ addLoggingHeaders(headers, requestId);
+ return ResponseEntity.status(status).headers(headers).body(respEntity);
}
- protected ResponseBuilder addVersionControlHeaders(ResponseBuilder rb) {
- return rb.header("X-MinorVersion", "0").header("X-PatchVersion", "0").header("X-LatestVersion", "1.0.0");
+ private void addVersionControlHeaders(HttpHeaders headers) {
+ headers.add("X-MinorVersion", "0");
+ headers.add("X-PatchVersion", "0");
+ headers.add("X-LatestVersion", "1.0.0");
}
- protected ResponseBuilder addLoggingHeaders(ResponseBuilder rb, UUID requestId) {
+ private void addLoggingHeaders(HttpHeaders headers, UUID requestId) {
if (requestId == null) {
// Generate a random uuid if client does not embed requestId in rest request
- return rb.header("X-ONAP-RequestID", UUID.randomUUID());
+ headers.add("X-ONAP-RequestID", UUID.randomUUID().toString());
+ } else {
+ headers.add("X-ONAP-RequestID", requestId.toString());
}
- return rb.header("X-ONAP-RequestID", requestId);
}
/**
@@ -83,4 +89,4 @@ public class CommonRestController { return null;
}
}
-}
+}
\ No newline at end of file diff --git a/main/src/main/java/org/onap/policy/api/main/rest/provider/CommonModelProvider.java b/main/src/main/java/org/onap/policy/api/main/rest/provider/CommonModelProvider.java index e555cd86..287c0b2b 100644 --- a/main/src/main/java/org/onap/policy/api/main/rest/provider/CommonModelProvider.java +++ b/main/src/main/java/org/onap/policy/api/main/rest/provider/CommonModelProvider.java @@ -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.
@@ -30,8 +31,6 @@ import java.util.Map; import java.util.function.BiConsumer;
import javax.ws.rs.core.Response;
import org.apache.commons.lang3.tuple.Pair;
-import org.onap.policy.api.main.parameters.ApiParameterGroup;
-import org.onap.policy.common.parameters.ParameterService;
import org.onap.policy.models.base.PfConceptKey;
import org.onap.policy.models.base.PfModelException;
import org.onap.policy.models.pdp.concepts.PdpGroup;
@@ -39,38 +38,21 @@ import org.onap.policy.models.pdp.concepts.PdpGroupFilter; import org.onap.policy.models.pdp.concepts.PdpSubGroup;
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;
/**
* Super class for providers that use a model provider.
*/
-public class CommonModelProvider implements AutoCloseable {
+public class CommonModelProvider {
protected final PolicyModelsProvider modelsProvider;
/**
* Constructs the object, populating {@link #modelsProvider}.
*
- * @throws PfModelException if an error occurs
*/
- public CommonModelProvider() throws PfModelException {
-
- ApiParameterGroup parameterGroup = ParameterService.get("ApiGroup");
- PolicyModelsProviderParameters providerParameters = parameterGroup.getDatabaseProviderParameters();
- modelsProvider = new PolicyModelsProviderFactory().createPolicyModelsProvider(providerParameters);
- }
-
- /**
- * Closes the connection to database.
- *
- * @throws PfModelException the PfModel parsing exception
- */
- @Override
- public void close() throws PfModelException {
-
- modelsProvider.close();
+ public CommonModelProvider(PolicyModelsProvider modelsProvider) {
+ this.modelsProvider = modelsProvider;
}
/**
@@ -243,4 +225,4 @@ public class CommonModelProvider implements AutoCloseable { return "could not find policy with ID " + policyId + " and type " + policyType.getName() + ":"
+ policyType.getVersion() + " deployed in any pdp group";
}
-}
+}
\ No newline at end of file diff --git a/main/src/main/java/org/onap/policy/api/main/rest/provider/HealthCheckProvider.java b/main/src/main/java/org/onap/policy/api/main/rest/provider/HealthCheckProvider.java index b5a198a2..40b841ef 100644 --- a/main/src/main/java/org/onap/policy/api/main/rest/provider/HealthCheckProvider.java +++ b/main/src/main/java/org/onap/policy/api/main/rest/provider/HealthCheckProvider.java @@ -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. @@ -25,28 +26,32 @@ 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 diff --git a/main/src/main/java/org/onap/policy/api/main/rest/provider/PolicyProvider.java b/main/src/main/java/org/onap/policy/api/main/rest/provider/PolicyProvider.java index 33df1ccc..1e5ed477 100644 --- a/main/src/main/java/org/onap/policy/api/main/rest/provider/PolicyProvider.java +++ b/main/src/main/java/org/onap/policy/api/main/rest/provider/PolicyProvider.java @@ -4,6 +4,7 @@ * ================================================================================
* Copyright (C) 2019-2020 AT&T Intellectual Property. All rights reserved.
* Modifications Copyright (C) 2020-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.
@@ -25,22 +26,27 @@ package org.onap.policy.api.main.rest.provider; import org.onap.policy.api.main.rest.PolicyFetchMode;
import org.onap.policy.models.base.PfModelException;
+import org.onap.policy.models.provider.PolicyModelsProvider;
import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicy;
import org.onap.policy.models.tosca.authorative.concepts.ToscaServiceTemplate;
import org.onap.policy.models.tosca.authorative.concepts.ToscaTypedEntityFilter;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Service;
/**
* Class to provide all kinds of policy operations.
*
* @author Chenfei Gao (cgao@research.att.com)
*/
+@Service
public class PolicyProvider extends CommonModelProvider {
/**
* Default constructor.
*/
- public PolicyProvider() throws PfModelException {
- super();
+ @Autowired
+ public PolicyProvider(PolicyModelsProvider modelsProvider) throws PfModelException {
+ super(modelsProvider);
}
/**
@@ -156,4 +162,4 @@ public class PolicyProvider extends CommonModelProvider { return serviceTemplate;
}
-}
+}
\ No newline at end of file diff --git a/main/src/main/java/org/onap/policy/api/main/rest/provider/PolicyTypeProvider.java b/main/src/main/java/org/onap/policy/api/main/rest/provider/PolicyTypeProvider.java index e56b536c..4db16985 100644 --- a/main/src/main/java/org/onap/policy/api/main/rest/provider/PolicyTypeProvider.java +++ b/main/src/main/java/org/onap/policy/api/main/rest/provider/PolicyTypeProvider.java @@ -4,6 +4,7 @@ * ================================================================================
* Copyright (C) 2019-2020 AT&T Intellectual Property. All rights reserved.
* Modifications Copyright (C) 2020-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.
@@ -24,22 +25,27 @@ package org.onap.policy.api.main.rest.provider;
import org.onap.policy.models.base.PfModelException;
+import org.onap.policy.models.provider.PolicyModelsProvider;
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.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Service;
/**
* Class to provide all kinds of policy type operations.
*
* @author Chenfei Gao (cgao@research.att.com)
*/
+@Service
public class PolicyTypeProvider extends CommonModelProvider {
/**
* Default constructor.
*/
- public PolicyTypeProvider() throws PfModelException {
- super();
+ @Autowired
+ public PolicyTypeProvider(PolicyModelsProvider modelsProvider) throws PfModelException {
+ super(modelsProvider);
}
/**
@@ -118,4 +124,4 @@ public class PolicyTypeProvider extends CommonModelProvider { ToscaEntityFilter.<ToscaPolicyType>builder().name(policyTypeName).version(policyTypeVersion).build();
return modelsProvider.getFilteredPolicyTypes(policyTypeFilter);
}
-}
+}
\ No newline at end of file diff --git a/main/src/main/java/org/onap/policy/api/main/rest/provider/StatisticsProvider.java b/main/src/main/java/org/onap/policy/api/main/rest/provider/StatisticsProvider.java index 9df00470..9dfc0dd6 100644 --- a/main/src/main/java/org/onap/policy/api/main/rest/provider/StatisticsProvider.java +++ b/main/src/main/java/org/onap/policy/api/main/rest/provider/StatisticsProvider.java @@ -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 @@ -23,26 +24,28 @@ 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 index 156837d5..00000000 --- a/main/src/main/java/org/onap/policy/api/main/startstop/ApiActivator.java +++ /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 index 47f004ea..00000000 --- a/main/src/main/java/org/onap/policy/api/main/startstop/ApiCommandLineArguments.java +++ /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); - } - } -} diff --git a/main/src/main/java/org/onap/policy/api/main/startstop/ApiDatabaseInitializer.java b/main/src/main/java/org/onap/policy/api/main/startstop/ApiDatabaseInitializer.java index 76ffd9ff..4aa25168 100644 --- a/main/src/main/java/org/onap/policy/api/main/startstop/ApiDatabaseInitializer.java +++ b/main/src/main/java/org/onap/policy/api/main/startstop/ApiDatabaseInitializer.java @@ -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 index 21bd5c48..00000000 --- a/main/src/main/java/org/onap/policy/api/main/startstop/Main.java +++ /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 index 00000000..96b79823 --- /dev/null +++ b/main/src/main/resources/application.yaml @@ -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 index 32c44602..00000000 --- a/main/src/test/java/org/onap/policy/api/main/parameters/CommonTestData.java +++ /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 index 28982489..00000000 --- a/main/src/test/java/org/onap/policy/api/main/parameters/TestApiParameterGroup.java +++ /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 index 26ecd026..00000000 --- a/main/src/test/java/org/onap/policy/api/main/parameters/TestApiParameterHandler.java +++ /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")); - } - } -} diff --git a/main/src/test/java/org/onap/policy/api/main/rest/TestApiRestServer.java b/main/src/test/java/org/onap/policy/api/main/rest/TestApiRestServer.java index 9f22ff23..ae654c6c 100644 --- a/main/src/test/java/org/onap/policy/api/main/rest/TestApiRestServer.java +++ b/main/src/test/java/org/onap/policy/api/main/rest/TestApiRestServer.java @@ -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 diff --git a/main/src/test/java/org/onap/policy/api/main/rest/TestApiStatisticsManager.java b/main/src/test/java/org/onap/policy/api/main/rest/TestApiStatisticsManager.java index 5f5c586d..bc67d21c 100644 --- a/main/src/test/java/org/onap/policy/api/main/rest/TestApiStatisticsManager.java +++ b/main/src/test/java/org/onap/policy/api/main/rest/TestApiStatisticsManager.java @@ -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 diff --git a/main/src/test/java/org/onap/policy/api/main/rest/TestCommonRestController.java b/main/src/test/java/org/onap/policy/api/main/rest/TestCommonRestController.java index dc921488..2213bbf9 100644 --- a/main/src/test/java/org/onap/policy/api/main/rest/TestCommonRestController.java +++ b/main/src/test/java/org/onap/policy/api/main/rest/TestCommonRestController.java @@ -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. @@ -23,13 +24,12 @@ 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 diff --git a/main/src/test/java/org/onap/policy/api/main/rest/provider/TestPolicyProvider.java b/main/src/test/java/org/onap/policy/api/main/rest/provider/TestPolicyProvider.java index e47a4ce6..ad394e33 100644 --- a/main/src/test/java/org/onap/policy/api/main/rest/provider/TestPolicyProvider.java +++ b/main/src/test/java/org/onap/policy/api/main/rest/provider/TestPolicyProvider.java @@ -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 diff --git a/main/src/test/java/org/onap/policy/api/main/rest/provider/TestPolicyTypeProvider.java b/main/src/test/java/org/onap/policy/api/main/rest/provider/TestPolicyTypeProvider.java index 355f3d45..6b7630c7 100644 --- a/main/src/test/java/org/onap/policy/api/main/rest/provider/TestPolicyTypeProvider.java +++ b/main/src/test/java/org/onap/policy/api/main/rest/provider/TestPolicyTypeProvider.java @@ -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 diff --git a/main/src/test/java/org/onap/policy/api/main/startstop/ApiDatabaseInitializerTest.java b/main/src/test/java/org/onap/policy/api/main/startstop/ApiDatabaseInitializerTest.java index f7e43b8d..aa86d739 100644 --- a/main/src/test/java/org/onap/policy/api/main/startstop/ApiDatabaseInitializerTest.java +++ b/main/src/test/java/org/onap/policy/api/main/startstop/ApiDatabaseInitializerTest.java @@ -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. @@ -21,54 +22,36 @@ 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 index ccd0f14d..00000000 --- a/main/src/test/java/org/onap/policy/api/main/startstop/TestApiActivator.java +++ /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 index 8d3c42c9..00000000 --- a/main/src/test/java/org/onap/policy/api/main/startstop/TestApiCommandLineArguments.java +++ /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 index 6c8c514d..00000000 --- a/main/src/test/java/org/onap/policy/api/main/startstop/TestMain.java +++ /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 index 00000000..240d3640 --- /dev/null +++ b/main/src/test/resources/application-test.yaml @@ -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 index 88187371..00000000 --- a/main/src/test/resources/logback-test.xml +++ /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 index 1d33e2ec..00000000 --- a/main/src/test/resources/parameters/ApiConfigParameters_Https.json +++ /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 index 832035ec..00000000 --- a/main/src/test/resources/parameters/ApiConfigParameters_InvalidName.json +++ /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 index 4e9083ec..00000000 --- a/main/src/test/resources/parameters/ApiConfigParameters_InvalidRestServerParameters.json +++ /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 index e5c375a0..00000000 --- a/main/src/test/resources/parameters/ApiConfigParameters_Postgres.json +++ /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 index de2040cc..00000000 --- a/main/src/test/resources/parameters/BadParameters.json +++ /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 index e69de29b..00000000 --- a/main/src/test/resources/parameters/EmptyParameters.json +++ /dev/null diff --git a/main/src/test/resources/parameters/InvalidParameters.json b/main/src/test/resources/parameters/InvalidParameters.json deleted file mode 100644 index de2040cc..00000000 --- a/main/src/test/resources/parameters/InvalidParameters.json +++ /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 index 5d671d2f..00000000 --- a/main/src/test/resources/parameters/MinimumParameters.json +++ /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 index 36e33afb..00000000 --- a/main/src/test/resources/parameters/NoParameters.json +++ /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 index 8d3bc580..00000000 --- a/main/src/test/resources/parameters/RestServerParameters.json +++ /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 index e02aef27..00000000 --- a/main/src/test/resources/parameters/RestServerParametersEmpty.json +++ /dev/null @@ -1,2 +0,0 @@ -{
-}
\ No newline at end of file diff --git a/packages/policy-api-docker/pom.xml b/packages/policy-api-docker/pom.xml index 57078d52..e9c45879 100644 --- a/packages/policy-api-docker/pom.xml +++ b/packages/policy-api-docker/pom.xml @@ -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. @@ -96,6 +96,12 @@ <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> @@ -157,4 +163,4 @@ <type>tar.gz</type> </dependency> </dependencies> -</project> +</project>
\ No newline at end of file diff --git a/packages/policy-api-docker/src/main/docker/Dockerfile b/packages/policy-api-docker/src/main/docker/Dockerfile index aac535d6..652d97d8 100644 --- a/packages/policy-api-docker/src/main/docker/Dockerfile +++ b/packages/policy-api-docker/src/main/docker/Dockerfile @@ -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 diff --git a/packages/policy-api-docker/src/main/docker/policy-api.sh b/packages/policy-api-docker/src/main/docker/policy-api.sh index d058d256..5d22c03d 100644 --- a/packages/policy-api-docker/src/main/docker/policy-api.sh +++ b/packages/policy-api-docker/src/main/docker/policy-api.sh @@ -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 diff --git a/packages/policy-api-tarball/src/main/package/tarball/assembly.xml b/packages/policy-api-tarball/src/main/package/tarball/assembly.xml index c19bd082..777ea85c 100644 --- a/packages/policy-api-tarball/src/main/package/tarball/assembly.xml +++ b/packages/policy-api-tarball/src/main/package/tarball/assembly.xml @@ -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 index 00000000..96b79823 --- /dev/null +++ b/packages/policy-api-tarball/src/main/resources/etc/apiParameters.yaml @@ -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 index 555a1137..00000000 --- a/packages/policy-api-tarball/src/main/resources/etc/defaultConfig.json +++ /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 index 5bd17970..00000000 --- a/packages/policy-api-tarball/src/main/resources/etc/s3pConfig.json +++ /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" - ] -} |