diff options
author | FrancescoFioraEst <francesco.fiora@est.tech> | 2021-06-09 14:22:50 +0100 |
---|---|---|
committer | FrancescoFioraEst <francesco.fiora@est.tech> | 2021-06-14 09:22:46 +0100 |
commit | 1595ed794f395816b0bfb6296aecb4a18bbbdec1 (patch) | |
tree | 9b315c1f04a4c3ff67a44b0d8cdb0debbd4435c6 /participant/participant-impl/participant-impl-simulator/src/main/java | |
parent | 9deb780264c7d12aa932fbb3ff2d442fcb3e8d5a (diff) |
Convert Participant Simulator to SpringBoot Application
Issue-ID: POLICY-3246
Change-Id: I0e5220be826531cf0338d5cad7018d06bda3daf5
Signed-off-by: FrancescoFioraEst <francesco.fiora@est.tech>
Diffstat (limited to 'participant/participant-impl/participant-impl-simulator/src/main/java')
20 files changed, 683 insertions, 638 deletions
diff --git a/participant/participant-impl/participant-impl-simulator/src/main/java/org/onap/policy/clamp/controlloop/participant/simulator/ParticipantSimulatorApplication.java b/participant/participant-impl/participant-impl-simulator/src/main/java/org/onap/policy/clamp/controlloop/participant/simulator/ParticipantSimulatorApplication.java new file mode 100644 index 000000000..3aa1c36db --- /dev/null +++ b/participant/participant-impl/participant-impl-simulator/src/main/java/org/onap/policy/clamp/controlloop/participant/simulator/ParticipantSimulatorApplication.java @@ -0,0 +1,36 @@ +/*-
+ * ============LICENSE_START=======================================================
+ * 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.clamp.controlloop.participant.simulator;
+
+import org.springframework.boot.SpringApplication;
+import org.springframework.boot.autoconfigure.SpringBootApplication;
+
+/**
+ * Starter.
+ *
+ */
+@SpringBootApplication
+public class ParticipantSimulatorApplication {
+
+ public static void main(String[] args) {
+ SpringApplication.run(ParticipantSimulatorApplication.class, args);
+ }
+}
diff --git a/participant/participant-impl/participant-impl-simulator/src/main/java/org/onap/policy/clamp/controlloop/participant/simulator/config/AafConfiguration.java b/participant/participant-impl/participant-impl-simulator/src/main/java/org/onap/policy/clamp/controlloop/participant/simulator/config/AafConfiguration.java new file mode 100644 index 000000000..c8922a1f5 --- /dev/null +++ b/participant/participant-impl/participant-impl-simulator/src/main/java/org/onap/policy/clamp/controlloop/participant/simulator/config/AafConfiguration.java @@ -0,0 +1,46 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP CLAMP + * ================================================================================ + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights + * reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END============================================ + * =================================================================== + * + */ + +package org.onap.policy.clamp.controlloop.participant.simulator.config; + +import javax.servlet.Filter; +import org.onap.policy.clamp.controlloop.participant.simulator.main.rest.ParticipantSimulatorAafFilter; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Profile; + +@Configuration +@Profile("clamp-aaf-authentication") +public class AafConfiguration { + + /** + * Method to return Aaf filter. + * + * @return Filter + */ + @Bean + public Filter aafFilter() { + return new ParticipantSimulatorAafFilter(); + } + +} diff --git a/participant/participant-impl/participant-impl-simulator/src/main/java/org/onap/policy/clamp/controlloop/participant/simulator/config/ParametersConfig.java b/participant/participant-impl/participant-impl-simulator/src/main/java/org/onap/policy/clamp/controlloop/participant/simulator/config/ParametersConfig.java new file mode 100644 index 000000000..936df2c57 --- /dev/null +++ b/participant/participant-impl/participant-impl-simulator/src/main/java/org/onap/policy/clamp/controlloop/participant/simulator/config/ParametersConfig.java @@ -0,0 +1,40 @@ +/*- + * ============LICENSE_START======================================================= + * 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.clamp.controlloop.participant.simulator.config; + +import org.onap.policy.clamp.controlloop.common.exception.ControlLoopException; +import org.onap.policy.clamp.controlloop.participant.simulator.main.parameters.ParticipantSimulatorParameterHandler; +import org.onap.policy.clamp.controlloop.participant.simulator.main.parameters.ParticipantSimulatorParameters; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +@Configuration +public class ParametersConfig { + + @Value("${participant.file}") + private String file; + + @Bean + public ParticipantSimulatorParameters participantSimulatorParameters() throws ControlLoopException { + return new ParticipantSimulatorParameterHandler().toParticipantSimulatorParameters(file); + } +} diff --git a/participant/participant-impl/participant-impl-simulator/src/main/java/org/onap/policy/clamp/controlloop/participant/simulator/config/ParticipantConfig.java b/participant/participant-impl/participant-impl-simulator/src/main/java/org/onap/policy/clamp/controlloop/participant/simulator/config/ParticipantConfig.java new file mode 100644 index 000000000..f4e6791ec --- /dev/null +++ b/participant/participant-impl/participant-impl-simulator/src/main/java/org/onap/policy/clamp/controlloop/participant/simulator/config/ParticipantConfig.java @@ -0,0 +1,61 @@ +/*- + * ============LICENSE_START======================================================= + * 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.clamp.controlloop.participant.simulator.config; + +import org.onap.policy.clamp.controlloop.participant.intermediary.api.ParticipantIntermediaryApi; +import org.onap.policy.clamp.controlloop.participant.intermediary.api.ParticipantIntermediaryFactory; +import org.onap.policy.clamp.controlloop.participant.simulator.main.parameters.ParticipantSimulatorParameters; +import org.onap.policy.clamp.controlloop.participant.simulator.main.rest.RequestResponseLoggingFilter; +import org.springframework.boot.web.servlet.FilterRegistrationBean; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +@Configuration +public class ParticipantConfig { + + /** + * Create ParticipantIntermediaryApi. + * + * @param parameters the Participant Dcae Parameters + * @return ParticipantIntermediaryApi + */ + @Bean + public ParticipantIntermediaryApi participantIntermediaryApi(ParticipantSimulatorParameters parameters) { + ParticipantIntermediaryApi intermediaryApi = new ParticipantIntermediaryFactory().createApiImplementation(); + intermediaryApi.init(parameters.getIntermediaryParameters()); + return intermediaryApi; + } + + /** + * logging Filter configuration. + * + * @return FilterRegistrationBean + */ + @Bean + public FilterRegistrationBean<RequestResponseLoggingFilter> loggingFilter() { + FilterRegistrationBean<RequestResponseLoggingFilter> registrationBean = new FilterRegistrationBean<>(); + + registrationBean.setFilter(new RequestResponseLoggingFilter()); + registrationBean.addUrlPatterns("/onap/participantsim/v2/*"); + + return registrationBean; + } +} diff --git a/participant/participant-impl/participant-impl-simulator/src/main/java/org/onap/policy/clamp/controlloop/participant/simulator/config/SecurityConfig.java b/participant/participant-impl/participant-impl-simulator/src/main/java/org/onap/policy/clamp/controlloop/participant/simulator/config/SecurityConfig.java new file mode 100644 index 000000000..cdfd5eac3 --- /dev/null +++ b/participant/participant-impl/participant-impl-simulator/src/main/java/org/onap/policy/clamp/controlloop/participant/simulator/config/SecurityConfig.java @@ -0,0 +1,39 @@ +/*- + * ============LICENSE_START======================================================= + * 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.clamp.controlloop.participant.simulator.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 + protected void configure(HttpSecurity http) throws Exception { + // @formatter:off + http.authorizeRequests() + .antMatchers().authenticated() + .anyRequest().authenticated() + .and().httpBasic().and().csrf().disable(); + // @formatter:on + } +} diff --git a/participant/participant-impl/participant-impl-simulator/src/main/java/org/onap/policy/clamp/controlloop/participant/simulator/config/SpringFoxConfig.java b/participant/participant-impl/participant-impl-simulator/src/main/java/org/onap/policy/clamp/controlloop/participant/simulator/config/SpringFoxConfig.java new file mode 100644 index 000000000..bf776140b --- /dev/null +++ b/participant/participant-impl/participant-impl-simulator/src/main/java/org/onap/policy/clamp/controlloop/participant/simulator/config/SpringFoxConfig.java @@ -0,0 +1,45 @@ +/*- + * ============LICENSE_START======================================================= + * 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.clamp.controlloop.participant.simulator.config; + +import org.onap.policy.clamp.controlloop.participant.simulator.simulation.rest.SimulationElementController; +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; + +@Configuration +public class SpringFoxConfig { + + /** + * Docket Spring Fox Config. + * + * @return Docket + */ + @Bean + public Docket api() { + return new Docket(DocumentationType.SWAGGER_2).select() + .apis(RequestHandlerSelectors.basePackage(SimulationElementController.class.getPackageName())) + .paths(PathSelectors.any()).build(); + } +} diff --git a/participant/participant-impl/participant-impl-simulator/src/main/java/org/onap/policy/clamp/controlloop/participant/simulator/config/YamlConfiguration.java b/participant/participant-impl/participant-impl-simulator/src/main/java/org/onap/policy/clamp/controlloop/participant/simulator/config/YamlConfiguration.java new file mode 100644 index 000000000..e84a7fc0a --- /dev/null +++ b/participant/participant-impl/participant-impl-simulator/src/main/java/org/onap/policy/clamp/controlloop/participant/simulator/config/YamlConfiguration.java @@ -0,0 +1,35 @@ +/*- + * ============LICENSE_START======================================================= + * 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.clamp.controlloop.participant.simulator.config; + +import java.util.List; +import org.springframework.context.annotation.Configuration; +import org.springframework.http.converter.HttpMessageConverter; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; + +@Configuration +public class YamlConfiguration implements WebMvcConfigurer { + + @Override + public void extendMessageConverters(List<HttpMessageConverter<?>> converters) { + converters.add(new YamlHttpMessageConverter<>()); + } +} diff --git a/participant/participant-impl/participant-impl-simulator/src/main/java/org/onap/policy/clamp/controlloop/participant/simulator/config/YamlHttpMessageConverter.java b/participant/participant-impl/participant-impl-simulator/src/main/java/org/onap/policy/clamp/controlloop/participant/simulator/config/YamlHttpMessageConverter.java new file mode 100644 index 000000000..4c8d324c6 --- /dev/null +++ b/participant/participant-impl/participant-impl-simulator/src/main/java/org/onap/policy/clamp/controlloop/participant/simulator/config/YamlHttpMessageConverter.java @@ -0,0 +1,60 @@ +/*- + * ============LICENSE_START======================================================= + * 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.clamp.controlloop.participant.simulator.config; + +import java.io.IOException; +import java.io.OutputStreamWriter; +import java.nio.charset.StandardCharsets; +import org.springframework.http.HttpInputMessage; +import org.springframework.http.HttpOutputMessage; +import org.springframework.http.MediaType; +import org.springframework.http.converter.AbstractHttpMessageConverter; +import org.springframework.http.converter.HttpMessageNotReadableException; +import org.springframework.http.converter.HttpMessageNotWritableException; +import org.yaml.snakeyaml.Yaml; + +public class YamlHttpMessageConverter<T> extends AbstractHttpMessageConverter<T> { + + public YamlHttpMessageConverter() { + super(new MediaType("application", "yaml")); + } + + @Override + protected boolean supports(Class<?> clazz) { + return true; + } + + @Override + protected T readInternal(Class<? extends T> clazz, HttpInputMessage inputMessage) + throws IOException, HttpMessageNotReadableException { + Yaml yaml = new Yaml(); + return yaml.loadAs(inputMessage.getBody(), clazz); + } + + @Override + protected void writeInternal(T t, HttpOutputMessage outputMessage) + throws IOException, HttpMessageNotWritableException { + Yaml yaml = new Yaml(); + try (OutputStreamWriter writer = new OutputStreamWriter(outputMessage.getBody(), StandardCharsets.UTF_8)) { + yaml.dump(t, writer); + } + } +} diff --git a/participant/participant-impl/participant-impl-simulator/src/main/java/org/onap/policy/clamp/controlloop/participant/simulator/main/parameters/ParticipantSimulatorParameterHandler.java b/participant/participant-impl/participant-impl-simulator/src/main/java/org/onap/policy/clamp/controlloop/participant/simulator/main/parameters/ParticipantSimulatorParameterHandler.java index 42f458602..178d08794 100644 --- a/participant/participant-impl/participant-impl-simulator/src/main/java/org/onap/policy/clamp/controlloop/participant/simulator/main/parameters/ParticipantSimulatorParameterHandler.java +++ b/participant/participant-impl/participant-impl-simulator/src/main/java/org/onap/policy/clamp/controlloop/participant/simulator/main/parameters/ParticipantSimulatorParameterHandler.java @@ -23,8 +23,7 @@ package org.onap.policy.clamp.controlloop.participant.simulator.main.parameters; import java.io.File; import javax.ws.rs.core.Response; import org.onap.policy.clamp.controlloop.common.exception.ControlLoopException; -import org.onap.policy.clamp.controlloop.participant.simulator.main.startstop.ParticipantSimulatorCommandLineArguments; -import org.onap.policy.common.parameters.ValidationResult; +import org.onap.policy.common.parameters.BeanValidationResult; import org.onap.policy.common.utils.coder.Coder; import org.onap.policy.common.utils.coder.CoderException; import org.onap.policy.common.utils.coder.StandardCoder; @@ -37,42 +36,41 @@ public class ParticipantSimulatorParameterHandler { private static final Coder CODER = new StandardCoder(); /** - * Read the parameters from the parameter file. + * Read the parameters from the path of the file. * - * @param arguments the arguments passed to simulator + * @param path path of the config file. * @return the parameters read from the configuration file * @throws ControlLoopException on parameter exceptions */ - public ParticipantSimulatorParameters getParameters(final ParticipantSimulatorCommandLineArguments arguments) - throws ControlLoopException { + public ParticipantSimulatorParameters toParticipantSimulatorParameters(String path) throws ControlLoopException { ParticipantSimulatorParameters parameters = null; - // Read the parameters try { // Read the parameters from JSON - File file = new File(arguments.getFullConfigurationFilePath()); + File file = new File(path); parameters = CODER.decode(file, ParticipantSimulatorParameters.class); } catch (final CoderException e) { - final String errorMessage = "error reading parameters from \"" + arguments.getConfigurationFilePath() - + "\"\n" + "(" + e.getClass().getSimpleName() + ")"; + final String errorMessage = "error reading parameters from \"" + path + "\"" + System.lineSeparator() + "(" + + e.getClass().getSimpleName() + ")"; throw new ControlLoopException(Response.Status.NOT_ACCEPTABLE, errorMessage, e); } // The JSON processing returns null if there is an empty file if (parameters == null) { - final String errorMessage = "no parameters found in \"" + arguments.getConfigurationFilePath() + "\""; + final String errorMessage = "no parameters found in \"" + path + "\""; throw new ControlLoopException(Response.Status.NOT_ACCEPTABLE, errorMessage); } // validate the parameters - final ValidationResult validationResult = parameters.validate(); + final BeanValidationResult validationResult = parameters.validate(); if (!validationResult.isValid()) { - String returnMessage = - "validation error(s) on parameters from \"" + arguments.getConfigurationFilePath() + "\"\n"; - returnMessage += validationResult.getResult(); + final String returnMessage = "validation error(s) on parameters from \"" + path + "\"" + + System.lineSeparator() + validationResult.getResult(); + throw new ControlLoopException(Response.Status.NOT_ACCEPTABLE, returnMessage); } return parameters; } + } diff --git a/participant/participant-impl/participant-impl-simulator/src/main/java/org/onap/policy/clamp/controlloop/participant/simulator/main/rest/RestController.java b/participant/participant-impl/participant-impl-simulator/src/main/java/org/onap/policy/clamp/controlloop/participant/simulator/main/rest/AbstractRestController.java index 444f37889..b872ec0c6 100644 --- a/participant/participant-impl/participant-impl-simulator/src/main/java/org/onap/policy/clamp/controlloop/participant/simulator/main/rest/RestController.java +++ b/participant/participant-impl/participant-impl-simulator/src/main/java/org/onap/policy/clamp/controlloop/participant/simulator/main/rest/AbstractRestController.java @@ -27,34 +27,29 @@ import io.swagger.annotations.SecurityDefinition; import io.swagger.annotations.SwaggerDefinition; import io.swagger.annotations.Tag; import java.net.HttpURLConnection; -import java.util.UUID; -import javax.ws.rs.Path; -import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response.ResponseBuilder; import lombok.AccessLevel; import lombok.Getter; -import org.onap.policy.clamp.controlloop.participant.simulator.simulation.SimulationHandler; import org.onap.policy.clamp.controlloop.participant.simulator.simulation.SimulationProvider; +import org.springframework.web.bind.annotation.RequestMapping; /** * Common superclass to provide REST endpoints for the participant simulator. */ // @formatter:off -@Path("/onap/participantsim/v2") +@RequestMapping(value = "/v2", produces = {MediaType.APPLICATION_JSON, AbstractRestController.APPLICATION_YAML}) @Api(value = "Participant Simulator API") -@Produces({MediaType.APPLICATION_JSON, RestController.APPLICATION_YAML}) @SwaggerDefinition( info = @Info(description = "Participant Simulator", version = "v1.0", title = "Participant Simulator"), - consumes = {MediaType.APPLICATION_JSON, RestController.APPLICATION_YAML}, - produces = {MediaType.APPLICATION_JSON, RestController.APPLICATION_YAML}, + consumes = {MediaType.APPLICATION_JSON, AbstractRestController.APPLICATION_YAML}, + produces = {MediaType.APPLICATION_JSON, AbstractRestController.APPLICATION_YAML}, schemes = {SwaggerDefinition.Scheme.HTTP, SwaggerDefinition.Scheme.HTTPS}, tags = {@Tag(name = "participantsim", description = "Participant Simulator")}, securityDefinition = @SecurityDefinition(basicAuthDefinitions = {@BasicAuthDefinition(key = "basicAuth")})) // @formatter:on -public class RestController { +public abstract class AbstractRestController { public static final String APPLICATION_YAML = "application/yaml"; public static final String EXTENSION_NAME = "interface info"; @@ -90,41 +85,16 @@ public class RestController { public static final String AUTHENTICATION_ERROR_MESSAGE = "Authentication Error"; public static final String AUTHORIZATION_ERROR_MESSAGE = "Authorization Error"; public static final String SERVER_ERROR_MESSAGE = "Internal Server Error"; + @Getter(AccessLevel.PROTECTED) // The provider for simulation requests private SimulationProvider simulationProvider; - /** * create a Rest Controller. */ - public RestController() { - simulationProvider = SimulationHandler.getInstance().getSimulationProvider(); - } - - /** - * Adds version headers to the response. - * - * @param respBuilder response builder - * @return the response builder, with version headers - */ - public ResponseBuilder addVersionControlHeaders(ResponseBuilder respBuilder) { - return respBuilder.header(VERSION_MINOR_NAME, "0").header(VERSION_PATCH_NAME, "0").header(VERSION_LATEST_NAME, - API_VERSION); + protected AbstractRestController(SimulationProvider simulationProvider) { + this.simulationProvider = simulationProvider; } - /** - * Adds logging headers to the response. - * - * @param respBuilder response builder - * @return the response builder, with version logging - */ - public ResponseBuilder addLoggingHeaders(ResponseBuilder respBuilder, UUID requestId) { - if (requestId == null) { - // Generate a random uuid if client does not embed requestId in rest request - return respBuilder.header(REQUEST_ID_NAME, UUID.randomUUID()); - } - - return respBuilder.header(REQUEST_ID_NAME, requestId); - } } diff --git a/participant/participant-impl/participant-impl-simulator/src/main/java/org/onap/policy/clamp/controlloop/participant/simulator/main/rest/GlobalControllerExceptionHandler.java b/participant/participant-impl/participant-impl-simulator/src/main/java/org/onap/policy/clamp/controlloop/participant/simulator/main/rest/GlobalControllerExceptionHandler.java new file mode 100644 index 000000000..562bbd13e --- /dev/null +++ b/participant/participant-impl/participant-impl-simulator/src/main/java/org/onap/policy/clamp/controlloop/participant/simulator/main/rest/GlobalControllerExceptionHandler.java @@ -0,0 +1,49 @@ +/*- + * ============LICENSE_START======================================================= + * 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.clamp.controlloop.participant.simulator.main.rest; + +import org.onap.policy.clamp.controlloop.common.exception.ControlLoopException; +import org.onap.policy.clamp.controlloop.models.messages.rest.commissioning.CommissioningResponse; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.ExceptionHandler; +import org.springframework.web.bind.annotation.ResponseStatus; +import org.springframework.web.bind.annotation.RestControllerAdvice; + +@RestControllerAdvice +public class GlobalControllerExceptionHandler { + + /** + * Handle ControlLoopException. + * + * @param ex ControlLoopException + * @return ResponseEntity + */ + @ExceptionHandler(ControlLoopException.class) + @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR) + public ResponseEntity<CommissioningResponse> handleBadRequest(ControlLoopException ex) { + + CommissioningResponse resp = new CommissioningResponse(); + resp.setErrorDetails(ex.getErrorResponse().getErrorMessage()); + + return ResponseEntity.status(ex.getErrorResponse().getResponseCode().getStatusCode()).body(resp); + } +} diff --git a/participant/participant-impl/participant-impl-simulator/src/main/java/org/onap/policy/clamp/controlloop/participant/simulator/main/rest/ParticipantErrorController.java b/participant/participant-impl/participant-impl-simulator/src/main/java/org/onap/policy/clamp/controlloop/participant/simulator/main/rest/ParticipantErrorController.java new file mode 100644 index 000000000..6607377bb --- /dev/null +++ b/participant/participant-impl/participant-impl-simulator/src/main/java/org/onap/policy/clamp/controlloop/participant/simulator/main/rest/ParticipantErrorController.java @@ -0,0 +1,102 @@ +/*- + * ============LICENSE_START======================================================= + * 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.clamp.controlloop.participant.simulator.main.rest; + +import io.swagger.v3.oas.annotations.Hidden; +import java.util.Map; +import javax.servlet.RequestDispatcher; +import javax.servlet.http.HttpServletRequest; +import org.onap.policy.clamp.controlloop.models.messages.rest.SimpleResponse; +import org.onap.policy.clamp.controlloop.models.messages.rest.TypedSimpleResponse; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.web.error.ErrorAttributeOptions; +import org.springframework.boot.web.servlet.error.ErrorAttributes; +import org.springframework.boot.web.servlet.error.ErrorController; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.context.request.ServletWebRequest; + +@Controller +@Hidden +public class ParticipantErrorController implements ErrorController { + + private final ErrorAttributes errorAttributes; + + @Value("${server.error.path}") + private String path; + + /** + * Constructor. + * + * @param errorAttributes ErrorAttributes + */ + public ParticipantErrorController(ErrorAttributes errorAttributes) { + this.errorAttributes = errorAttributes; + } + + protected HttpStatus getStatus(HttpServletRequest request) { + Integer statusCode = (Integer) request.getAttribute(RequestDispatcher.ERROR_STATUS_CODE); + if (statusCode == null) { + return HttpStatus.INTERNAL_SERVER_ERROR; + } + try { + return HttpStatus.valueOf(statusCode); + } catch (Exception ex) { + return HttpStatus.INTERNAL_SERVER_ERROR; + } + } + + /** + * Handle Errors not handled to GlobalControllerExceptionHandler. + * + * @param request HttpServletRequest + * @return ResponseEntity + */ + @RequestMapping(value = "${server.error.path}", produces = MediaType.APPLICATION_JSON_VALUE) + public ResponseEntity<TypedSimpleResponse<SimpleResponse>> handleError(HttpServletRequest request) { + Map<String, Object> map = this.errorAttributes.getErrorAttributes(new ServletWebRequest(request), + ErrorAttributeOptions.defaults()); + + StringBuilder sb = new StringBuilder(); + final Object error = map.get("error"); + if (error != null) { + sb.append(error.toString() + " "); + } + final Object message = map.get("message"); + if (message != null) { + sb.append(message.toString()); + } + + TypedSimpleResponse<SimpleResponse> resp = new TypedSimpleResponse<>(); + resp.setErrorDetails(sb.toString()); + + return ResponseEntity.status(getStatus(request)).body(resp); + + } + + @Override + public String getErrorPath() { + return path; + } +} diff --git a/participant/participant-impl/participant-impl-simulator/src/main/java/org/onap/policy/clamp/controlloop/participant/simulator/main/rest/RequestResponseLoggingFilter.java b/participant/participant-impl/participant-impl-simulator/src/main/java/org/onap/policy/clamp/controlloop/participant/simulator/main/rest/RequestResponseLoggingFilter.java new file mode 100644 index 000000000..3aaeeaf72 --- /dev/null +++ b/participant/participant-impl/participant-impl-simulator/src/main/java/org/onap/policy/clamp/controlloop/participant/simulator/main/rest/RequestResponseLoggingFilter.java @@ -0,0 +1,63 @@ +/*- + * ============LICENSE_START======================================================= + * 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.clamp.controlloop.participant.simulator.main.rest; + +import java.io.IOException; +import java.util.UUID; +import javax.servlet.Filter; +import javax.servlet.FilterChain; +import javax.servlet.ServletException; +import javax.servlet.ServletRequest; +import javax.servlet.ServletResponse; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import org.springframework.core.annotation.Order; +import org.springframework.stereotype.Component; + +@Component +@Order(2) +public class RequestResponseLoggingFilter implements Filter { + + private static final String VERSION_MINOR_NAME = "X-MinorVersion"; + private static final String VERSION_PATCH_NAME = "X-PatchVersion"; + private static final String VERSION_LATEST_NAME = "X-LatestVersion"; + public static final String API_VERSION = "1.0.0"; + public static final String REQUEST_ID_NAME = "X-ONAP-RequestID"; + + @Override + public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) + throws IOException, ServletException { + + + HttpServletResponse res = (HttpServletResponse) response; + HttpServletRequest req = (HttpServletRequest) request; + + String requestId = req.getHeader(REQUEST_ID_NAME); + res.addHeader(REQUEST_ID_NAME, requestId != null ? requestId : UUID.randomUUID().toString()); + + res.addHeader(VERSION_MINOR_NAME, "0"); + res.addHeader(VERSION_PATCH_NAME, "0"); + res.addHeader(VERSION_LATEST_NAME, API_VERSION); + + chain.doFilter(request, response); + } + +} diff --git a/participant/participant-impl/participant-impl-simulator/src/main/java/org/onap/policy/clamp/controlloop/participant/simulator/main/startstop/Main.java b/participant/participant-impl/participant-impl-simulator/src/main/java/org/onap/policy/clamp/controlloop/participant/simulator/main/startstop/Main.java deleted file mode 100644 index e6c93d55d..000000000 --- a/participant/participant-impl/participant-impl-simulator/src/main/java/org/onap/policy/clamp/controlloop/participant/simulator/main/startstop/Main.java +++ /dev/null @@ -1,141 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * 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.clamp.controlloop.participant.simulator.main.startstop; - -import java.util.Arrays; -import javax.ws.rs.core.Response; -import lombok.Getter; -import org.onap.policy.clamp.controlloop.common.exception.ControlLoopException; -import org.onap.policy.clamp.controlloop.common.exception.ControlLoopRuntimeException; -import org.onap.policy.clamp.controlloop.participant.simulator.main.parameters.ParticipantSimulatorParameterHandler; -import org.onap.policy.clamp.controlloop.participant.simulator.main.parameters.ParticipantSimulatorParameters; -import org.onap.policy.common.utils.resources.MessageConstants; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * This class initiates participant simulator. - */ -public class Main { - - private static final Logger LOGGER = LoggerFactory.getLogger(Main.class); - - private ParticipantSimulatorActivator activator; - - @Getter - private ParticipantSimulatorParameters parameterGroup; - - /** - * Instantiates the control loop participant service. - * - * @param args the command line arguments - */ - public Main(final String[] args) { - final String argumentString = Arrays.toString(args); - LOGGER.info("Starting the participant service with arguments - {}", argumentString); - - // Check the arguments - final ParticipantSimulatorCommandLineArguments arguments = new ParticipantSimulatorCommandLineArguments(); - 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 ParticipantSimulatorParameterHandler().getParameters(arguments); - - // Now, create the activator for the service - activator = new ParticipantSimulatorActivator(parameterGroup); - - // Start the activator - activator.start(); - } catch (Exception exp) { - throw new ControlLoopRuntimeException(Response.Status.BAD_REQUEST, - String.format(MessageConstants.START_FAILURE_MSG, MessageConstants.POLICY_CLAMP), exp); - } - - // Add a shutdown hook to shut everything down in an orderly manner - Runtime.getRuntime().addShutdownHook(new ClParticipantSimulatorShutdownHookClass()); - String successMsg = String.format(MessageConstants.START_SUCCESS_MSG, MessageConstants.POLICY_CLAMP); - LOGGER.info(successMsg); - } - - /** - * Check if main is running. - */ - public boolean isRunning() { - return activator != null && activator.isAlive(); - } - - /** - * Shut down Execution. - * - * @throws ControlLoopException on shutdown errors - */ - public void shutdown() throws ControlLoopException { - // clear the parameterGroup variable - parameterGroup = null; - - // clear the cl participant activator - if (activator != null) { - activator.stop(); - } - } - - /** - * The Class ClParticipantSimulatorShutdownHookClass terminates the control loop participant service - * when its run method is called. - */ - private class ClParticipantSimulatorShutdownHookClass extends Thread { - /* - * (non-Javadoc) - * - * @see java.lang.Runnable#run() - */ - @Override - public void run() { - try { - // Shutdown the participant simulator and wait for everything to stop - shutdown(); - } catch (final RuntimeException | ControlLoopException e) { - LOGGER.warn("error occured during shut down of the participant simulator", e); - } - } - } - - /** - * The main method. - * - * @param args the arguments - */ - public static void main(final String[] args) { // NOSONAR - /* - * NOTE: arguments are validated by the constructor, thus sonar is disabled. - */ - - new Main(args); - } -} diff --git a/participant/participant-impl/participant-impl-simulator/src/main/java/org/onap/policy/clamp/controlloop/participant/simulator/main/startstop/ParticipantSimulatorActivator.java b/participant/participant-impl/participant-impl-simulator/src/main/java/org/onap/policy/clamp/controlloop/participant/simulator/main/startstop/ParticipantSimulatorActivator.java deleted file mode 100644 index 4daa0393f..000000000 --- a/participant/participant-impl/participant-impl-simulator/src/main/java/org/onap/policy/clamp/controlloop/participant/simulator/main/startstop/ParticipantSimulatorActivator.java +++ /dev/null @@ -1,75 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * 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.clamp.controlloop.participant.simulator.main.startstop; - -import java.util.Set; -import java.util.concurrent.atomic.AtomicReference; -import lombok.Getter; -import org.onap.policy.clamp.controlloop.participant.simulator.main.parameters.ParticipantSimulatorParameters; -import org.onap.policy.clamp.controlloop.participant.simulator.main.rest.ParticipantSimulatorAafFilter; -import org.onap.policy.clamp.controlloop.participant.simulator.simulation.SimulationHandler; -import org.onap.policy.common.endpoints.http.server.RestServer; -import org.onap.policy.common.utils.services.ServiceManagerContainer; - -/** - * This class activates the participant simulator component as a complete service together with all its controllers, - * listeners and handlers. - */ -public class ParticipantSimulatorActivator extends ServiceManagerContainer { - @Getter - private final ParticipantSimulatorParameters parameters; - - /** - * Instantiate the activator for the simulator as a complete service. - * - * @param parameters the parameters for the participant service - */ - public ParticipantSimulatorActivator(final ParticipantSimulatorParameters parameters) { - this.parameters = parameters; - - final AtomicReference<SimulationHandler> simulationHandler = new AtomicReference<>(); - final AtomicReference<RestServer> restServer = new AtomicReference<>(); - - // @formatter:off - addAction("Simulation Handler", - () -> simulationHandler.set(new SimulationHandler(parameters)), - () -> simulationHandler.get().close()); - - addAction("Simulation Providers", - () -> simulationHandler.get().startProviders(), - () -> simulationHandler.get().stopProviders()); - - parameters.getRestServerParameters().setName(parameters.getName()); - - addAction("REST server", - () -> { - Set<Class<?>> providerClasses = simulationHandler.get().getProviderClasses(); - - RestServer server = new RestServer(parameters.getRestServerParameters(), - ParticipantSimulatorAafFilter.class, - providerClasses.toArray(new Class<?>[providerClasses.size()])); - restServer.set(server); - restServer.get().start(); - }, - () -> restServer.get().stop()); - // @formatter:on - } -} diff --git a/participant/participant-impl/participant-impl-simulator/src/main/java/org/onap/policy/clamp/controlloop/participant/simulator/main/startstop/ParticipantSimulatorCommandLineArguments.java b/participant/participant-impl/participant-impl-simulator/src/main/java/org/onap/policy/clamp/controlloop/participant/simulator/main/startstop/ParticipantSimulatorCommandLineArguments.java deleted file mode 100644 index 51ac3a4d5..000000000 --- a/participant/participant-impl/participant-impl-simulator/src/main/java/org/onap/policy/clamp/controlloop/participant/simulator/main/startstop/ParticipantSimulatorCommandLineArguments.java +++ /dev/null @@ -1,151 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * 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.clamp.controlloop.participant.simulator.main.startstop; - -import java.io.File; -import java.io.PrintWriter; -import java.io.StringWriter; -import java.net.URL; -import java.util.Arrays; -import javax.ws.rs.core.Response; -import lombok.Getter; -import lombok.Setter; -import org.apache.commons.cli.CommandLine; -import org.apache.commons.cli.DefaultParser; -import org.apache.commons.cli.HelpFormatter; -import org.apache.commons.cli.Option; -import org.apache.commons.cli.Options; -import org.apache.commons.cli.ParseException; -import org.apache.commons.lang3.StringUtils; -import org.onap.policy.clamp.controlloop.common.exception.ControlLoopException; -import org.onap.policy.clamp.controlloop.common.exception.ControlLoopRuntimeException; -import org.onap.policy.clamp.controlloop.common.startstop.CommonCommandLineArguments; -import org.onap.policy.common.utils.resources.ResourceUtils; - -/** - * This class reads and handles command line parameters for the participant simulator service. - * - */ -public class ParticipantSimulatorCommandLineArguments { - private static final String FILE_MESSAGE_PREAMBLE = " file \""; - private static final int HELP_LINE_LENGTH = 120; - - private final Options options; - private final CommonCommandLineArguments commonCommandLineArguments; - - @Getter() - @Setter() - private String configurationFilePath = null; - - /** - * Construct the options for the participant component. - */ - public ParticipantSimulatorCommandLineArguments() { - options = new Options(); - commonCommandLineArguments = new CommonCommandLineArguments(options); - } - - /** - * Construct the options for the participant component and parse in the given arguments. - * - * @param args The command line arguments - */ - public ParticipantSimulatorCommandLineArguments(final String[] args) { - // Set up the options with the default constructor - this(); - - // Parse the arguments - try { - parse(args); - } catch (final ControlLoopException e) { - throw new ControlLoopRuntimeException(Response.Status.NOT_ACCEPTABLE, - "parse error on participant parameters", e); - } - } - - /** - * Parse the command line options. - * - * @param args The command line arguments - * @return a string with a message for help and version, or null if there is no message - * @throws ControlLoopException on command argument errors - */ - public String parse(final String[] args) throws ControlLoopException { - // Clear all our arguments - setConfigurationFilePath(null); - CommandLine commandLine = null; - try { - commandLine = new DefaultParser().parse(options, args); - } catch (final ParseException e) { - throw new ControlLoopException(Response.Status.NOT_ACCEPTABLE, - "invalid command line arguments specified : " + e.getMessage()); - } - - // Arguments left over after Commons CLI does its stuff - final String[] remainingArgs = commandLine.getArgs(); - - if (remainingArgs.length > 0) { - throw new ControlLoopException(Response.Status.NOT_ACCEPTABLE, - "too many command line arguments specified : " + Arrays.toString(args)); - } - - if (commandLine.hasOption('h')) { - return commonCommandLineArguments.help(Main.class.getName(), options); - } - - if (commandLine.hasOption('v')) { - return commonCommandLineArguments.version(); - } - - if (commandLine.hasOption('c')) { - setConfigurationFilePath(commandLine.getOptionValue('c')); - } - - return null; - } - - /** - * Validate the command line options. - * - * @throws ControlLoopException on command argument validation errors - */ - public void validate() throws ControlLoopException { - commonCommandLineArguments.validate(configurationFilePath); - } - - /** - * Gets the full expanded configuration file path. - * - * @return the configuration file path - */ - public String getFullConfigurationFilePath() { - return ResourceUtils.getFilePath4Resource(getConfigurationFilePath()); - } - - /** - * Check set configuration file path. - * - * @return true, if check set configuration file path - */ - public boolean checkSetConfigurationFilePath() { - return !StringUtils.isEmpty(configurationFilePath); - } -} diff --git a/participant/participant-impl/participant-impl-simulator/src/main/java/org/onap/policy/clamp/controlloop/participant/simulator/simulation/SimulationHandler.java b/participant/participant-impl/participant-impl-simulator/src/main/java/org/onap/policy/clamp/controlloop/participant/simulator/simulation/SimulationHandler.java deleted file mode 100644 index df7f2a611..000000000 --- a/participant/participant-impl/participant-impl-simulator/src/main/java/org/onap/policy/clamp/controlloop/participant/simulator/simulation/SimulationHandler.java +++ /dev/null @@ -1,81 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * 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.clamp.controlloop.participant.simulator.simulation; - -import java.io.IOException; -import java.util.List; -import java.util.Set; -import javax.ws.rs.core.Response; -import lombok.Getter; -import org.onap.policy.clamp.controlloop.common.handler.ControlLoopHandler; -import org.onap.policy.clamp.controlloop.participant.intermediary.parameters.ParticipantIntermediaryParameters; -import org.onap.policy.clamp.controlloop.participant.simulator.main.parameters.ParticipantSimulatorParameters; -import org.onap.policy.clamp.controlloop.participant.simulator.simulation.rest.SimulationElementController; -import org.onap.policy.clamp.controlloop.participant.simulator.simulation.rest.SimulationParticipantController; -import org.onap.policy.common.endpoints.event.comm.TopicSink; -import org.onap.policy.common.endpoints.listeners.MessageTypeDispatcher; -import org.onap.policy.common.utils.services.Registry; -import org.onap.policy.models.base.PfModelRuntimeException; - -/** - * This class handles simulation of participants and control loop elements. - * - * <p/>It is effectively a singleton that is started at system start. - */ -public class SimulationHandler extends ControlLoopHandler { - private final ParticipantIntermediaryParameters participantParameters; - - @Getter - private SimulationProvider simulationProvider; - - /** - * Create a handler. - * - * @param parameters the parameters for access to the database - */ - public SimulationHandler(ParticipantSimulatorParameters parameters) { - super(parameters.getDatabaseProviderParameters()); - participantParameters = parameters.getIntermediaryParameters(); - } - - public static SimulationHandler getInstance() { - return Registry.get(SimulationHandler.class.getName()); - } - - @Override - public Set<Class<?>> getProviderClasses() { - return Set.of(SimulationElementController.class, SimulationParticipantController.class); - } - - @Override - public void startProviders() { - simulationProvider = new SimulationProvider(participantParameters); - } - - @Override - public void stopProviders() { - try { - simulationProvider.close(); - } catch (IOException e) { - throw new PfModelRuntimeException(Response.Status.INTERNAL_SERVER_ERROR, "Stop providers failed ", e); - } - } -} diff --git a/participant/participant-impl/participant-impl-simulator/src/main/java/org/onap/policy/clamp/controlloop/participant/simulator/simulation/SimulationProvider.java b/participant/participant-impl/participant-impl-simulator/src/main/java/org/onap/policy/clamp/controlloop/participant/simulator/simulation/SimulationProvider.java index 1fcbba3af..6ee4eac3e 100644 --- a/participant/participant-impl/participant-impl-simulator/src/main/java/org/onap/policy/clamp/controlloop/participant/simulator/simulation/SimulationProvider.java +++ b/participant/participant-impl/participant-impl-simulator/src/main/java/org/onap/policy/clamp/controlloop/participant/simulator/simulation/SimulationProvider.java @@ -20,44 +20,30 @@ package org.onap.policy.clamp.controlloop.participant.simulator.simulation; -import java.io.Closeable; -import java.io.IOException; import java.util.List; import java.util.Map; import java.util.UUID; -import lombok.Getter; import org.onap.policy.clamp.controlloop.common.exception.ControlLoopException; -import org.onap.policy.clamp.controlloop.common.exception.ControlLoopRuntimeException; -import org.onap.policy.clamp.controlloop.models.controlloop.concepts.ControlLoop; import org.onap.policy.clamp.controlloop.models.controlloop.concepts.ControlLoopElement; import org.onap.policy.clamp.controlloop.models.controlloop.concepts.ControlLoops; import org.onap.policy.clamp.controlloop.models.controlloop.concepts.Participant; import org.onap.policy.clamp.controlloop.models.messages.rest.TypedSimpleResponse; import org.onap.policy.clamp.controlloop.participant.intermediary.api.ParticipantIntermediaryApi; -import org.onap.policy.clamp.controlloop.participant.intermediary.api.ParticipantIntermediaryFactory; -import org.onap.policy.clamp.controlloop.participant.intermediary.parameters.ParticipantIntermediaryParameters; +import org.springframework.stereotype.Service; /** * This provider class simulation of participants and control loop elements. */ -public class SimulationProvider implements Closeable { - @Getter +@Service +public class SimulationProvider { + private final ParticipantIntermediaryApi intermediaryApi; /** * Create a participant simulation provider. - * - * @throws ControlLoopRuntimeException on errors creating the provider */ - public SimulationProvider(ParticipantIntermediaryParameters participantParameters) - throws ControlLoopRuntimeException { - intermediaryApi = new ParticipantIntermediaryFactory().createApiImplementation(); - intermediaryApi.init(participantParameters); - } - - @Override - public void close() throws IOException { - intermediaryApi.close(); + public SimulationProvider(ParticipantIntermediaryApi intermediaryApi) { + this.intermediaryApi = intermediaryApi; } /** @@ -78,10 +64,8 @@ public class SimulationProvider implements Closeable { * @param name the controlLoopElement, null to get all * @param version the controlLoopElement, null to get all * @return the control loop elements - * @throws ControlLoopException on errors getting the control loop elements */ - public Map<UUID, ControlLoopElement> getControlLoopElements(String name, String version) - throws ControlLoopException { + public Map<UUID, ControlLoopElement> getControlLoopElements(String name, String version) { return intermediaryApi.getControlLoopElements(name, version); } @@ -90,13 +74,11 @@ public class SimulationProvider implements Closeable { * * @param element the control loop element to update * @return response simple response returned - * @throws ControlLoopException on errors updating the control loop element */ - public TypedSimpleResponse<ControlLoopElement> updateControlLoopElement(ControlLoopElement element) - throws ControlLoopException { + public TypedSimpleResponse<ControlLoopElement> updateControlLoopElement(ControlLoopElement element) { TypedSimpleResponse<ControlLoopElement> response = new TypedSimpleResponse<>(); - response.setResponse(intermediaryApi.updateControlLoopElementState( - element.getId(), element.getOrderedState(), element.getState())); + response.setResponse(intermediaryApi.updateControlLoopElementState(element.getId(), element.getOrderedState(), + element.getState())); return response; } @@ -106,9 +88,8 @@ public class SimulationProvider implements Closeable { * @param name the participant, null to get all * @param version the participant, null to get all * @return the list of participants - * @throws ControlLoopException on errors getting the participants */ - public List<Participant> getParticipants(String name, String version) throws ControlLoopException { + public List<Participant> getParticipants(String name, String version) { return intermediaryApi.getParticipants(name, version); } @@ -117,13 +98,11 @@ public class SimulationProvider implements Closeable { * * @param participant the participant to update * @return TypedSimpleResponse simple response - * @throws ControlLoopException on errors updating the participant */ - - public TypedSimpleResponse<Participant> updateParticipant(Participant participant) throws ControlLoopException { + public TypedSimpleResponse<Participant> updateParticipant(Participant participant) { TypedSimpleResponse<Participant> response = new TypedSimpleResponse<>(); - response.setResponse(intermediaryApi.updateParticipantState( - participant.getDefinition(), participant.getParticipantState())); + response.setResponse( + intermediaryApi.updateParticipantState(participant.getDefinition(), participant.getParticipantState())); return response; } } diff --git a/participant/participant-impl/participant-impl-simulator/src/main/java/org/onap/policy/clamp/controlloop/participant/simulator/simulation/rest/SimulationElementController.java b/participant/participant-impl/participant-impl-simulator/src/main/java/org/onap/policy/clamp/controlloop/participant/simulator/simulation/rest/SimulationElementController.java index 1869047c9..de2a06223 100644 --- a/participant/participant-impl/participant-impl-simulator/src/main/java/org/onap/policy/clamp/controlloop/participant/simulator/simulation/rest/SimulationElementController.java +++ b/participant/participant-impl/participant-impl-simulator/src/main/java/org/onap/policy/clamp/controlloop/participant/simulator/simulation/rest/SimulationElementController.java @@ -28,30 +28,35 @@ import io.swagger.annotations.Authorization; import io.swagger.annotations.Extension; import io.swagger.annotations.ExtensionProperty; import io.swagger.annotations.ResponseHeader; -import java.util.List; import java.util.Map; import java.util.UUID; -import javax.ws.rs.GET; -import javax.ws.rs.HeaderParam; -import javax.ws.rs.PUT; -import javax.ws.rs.Path; -import javax.ws.rs.PathParam; -import javax.ws.rs.core.Response; -import javax.ws.rs.core.Response.Status; -import org.onap.policy.clamp.controlloop.common.exception.ControlLoopException; import org.onap.policy.clamp.controlloop.models.controlloop.concepts.ControlLoopElement; import org.onap.policy.clamp.controlloop.models.controlloop.concepts.ControlLoops; -import org.onap.policy.clamp.controlloop.models.messages.rest.SimpleResponse; import org.onap.policy.clamp.controlloop.models.messages.rest.TypedSimpleResponse; -import org.onap.policy.clamp.controlloop.participant.simulator.main.rest.RestController; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import org.onap.policy.clamp.controlloop.participant.simulator.main.rest.AbstractRestController; +import org.onap.policy.clamp.controlloop.participant.simulator.simulation.SimulationProvider; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PutMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestHeader; +import org.springframework.web.bind.annotation.RestController; /** * Class to provide REST end points for participant simulator to query/update details of controlLoopElements. */ -public class SimulationElementController extends RestController { - private static final Logger LOGGER = LoggerFactory.getLogger(SimulationElementController.class); +@RestController +public class SimulationElementController extends AbstractRestController { + + /** + * Constructor. + * + * @param simulationProvider the Simulation Provider + */ + public SimulationElementController(SimulationProvider simulationProvider) { + super(simulationProvider); + } /** * Queries details of all control loop element within the simulator. @@ -62,8 +67,7 @@ public class SimulationElementController extends RestController { * @return the control loop elements */ // @formatter:off - @GET - @Path("/elements/{name}/{version}") + @GetMapping("/elements/{name}/{version}") @ApiOperation(value = "Query details of the requested simulated control loop elements", notes = "Queries details of the requested simulated control loop elements, " + "returning all control loop element details", @@ -100,24 +104,16 @@ public class SimulationElementController extends RestController { } ) // @formatter:on - public Response elements(@HeaderParam(REQUEST_ID_NAME) @ApiParam(REQUEST_ID_PARAM_DESCRIPTION) UUID requestId, - @ApiParam(value = "Control loop element name", required = true) @PathParam("name") String name, - @ApiParam(value = "Control loop element version", required = true) @PathParam("version") String version) { - - try { - Map<UUID, ControlLoopElement> response = getSimulationProvider().getControlLoopElements(name, version); - return addLoggingHeaders(addVersionControlHeaders(Response.status(Status.OK)), requestId).entity(response) - .build(); - - } catch (ControlLoopException cle) { - LOGGER.warn("get of control loop elements failed", cle); - SimpleResponse resp = new SimpleResponse(); - resp.setErrorDetails(cle.getErrorResponse().getErrorMessage()); - return addLoggingHeaders( - addVersionControlHeaders(Response.status(cle.getErrorResponse().getResponseCode())), requestId) - .entity(resp).build(); - } + public ResponseEntity<Map<UUID, ControlLoopElement>> elements( + @RequestHeader( + name = REQUEST_ID_NAME, + required = false) @ApiParam(REQUEST_ID_PARAM_DESCRIPTION) UUID requestId, + @ApiParam(value = "Control loop element name", required = true) @PathVariable("name") String name, + @ApiParam( + value = "Control loop element version", + required = true) @PathVariable("version") String version) { + return ResponseEntity.ok().body(getSimulationProvider().getControlLoopElements(name, version)); } /** @@ -128,8 +124,7 @@ public class SimulationElementController extends RestController { * @return a response */ // @formatter:off - @PUT - @Path("/elements") + @PutMapping("/elements") @ApiOperation( value = "Updates simulated control loop elements", notes = "Updates simulated control loop elements, returning the updated control loop definition IDs", @@ -174,22 +169,12 @@ public class SimulationElementController extends RestController { } ) // @formatter:on - public Response update(@HeaderParam(REQUEST_ID_NAME) @ApiParam(REQUEST_ID_PARAM_DESCRIPTION) UUID requestId, - @ApiParam(value = "Body of a control loop element", required = true) ControlLoopElement body) { - - try { - TypedSimpleResponse<ControlLoopElement> response = - getSimulationProvider().updateControlLoopElement(body); - return addLoggingHeaders(addVersionControlHeaders(Response.status(Status.OK)), requestId).entity(response) - .build(); + public ResponseEntity<TypedSimpleResponse<ControlLoopElement>> update( + @RequestHeader( + name = REQUEST_ID_NAME, + required = false) @ApiParam(REQUEST_ID_PARAM_DESCRIPTION) UUID requestId, + @ApiParam(value = "Body of a control loop element", required = true) @RequestBody ControlLoopElement body) { - } catch (ControlLoopException cle) { - LOGGER.warn("update of control loop element failed", cle); - TypedSimpleResponse<ControlLoopElement> resp = new TypedSimpleResponse<>(); - resp.setErrorDetails(cle.getErrorResponse().getErrorMessage()); - return addLoggingHeaders( - addVersionControlHeaders(Response.status(cle.getErrorResponse().getResponseCode())), requestId) - .entity(resp).build(); - } + return ResponseEntity.ok().body(getSimulationProvider().updateControlLoopElement(body)); } } diff --git a/participant/participant-impl/participant-impl-simulator/src/main/java/org/onap/policy/clamp/controlloop/participant/simulator/simulation/rest/SimulationParticipantController.java b/participant/participant-impl/participant-impl-simulator/src/main/java/org/onap/policy/clamp/controlloop/participant/simulator/simulation/rest/SimulationParticipantController.java index d6ca6d0d1..715ec3410 100644 --- a/participant/participant-impl/participant-impl-simulator/src/main/java/org/onap/policy/clamp/controlloop/participant/simulator/simulation/rest/SimulationParticipantController.java +++ b/participant/participant-impl/participant-impl-simulator/src/main/java/org/onap/policy/clamp/controlloop/participant/simulator/simulation/rest/SimulationParticipantController.java @@ -30,26 +30,32 @@ import io.swagger.annotations.ExtensionProperty; import io.swagger.annotations.ResponseHeader; import java.util.List; import java.util.UUID; -import javax.ws.rs.GET; -import javax.ws.rs.HeaderParam; -import javax.ws.rs.PUT; -import javax.ws.rs.Path; -import javax.ws.rs.PathParam; -import javax.ws.rs.core.Response; -import javax.ws.rs.core.Response.Status; -import org.onap.policy.clamp.controlloop.common.exception.ControlLoopException; import org.onap.policy.clamp.controlloop.models.controlloop.concepts.Participant; -import org.onap.policy.clamp.controlloop.models.messages.rest.SimpleResponse; import org.onap.policy.clamp.controlloop.models.messages.rest.TypedSimpleResponse; -import org.onap.policy.clamp.controlloop.participant.simulator.main.rest.RestController; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import org.onap.policy.clamp.controlloop.participant.simulator.main.rest.AbstractRestController; +import org.onap.policy.clamp.controlloop.participant.simulator.simulation.SimulationProvider; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PutMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestHeader; +import org.springframework.web.bind.annotation.RestController; /** * Class to provide REST end points for participant simulator to query/update details of all participants. */ -public class SimulationParticipantController extends RestController { - private static final Logger LOGGER = LoggerFactory.getLogger(SimulationParticipantController.class); +@RestController +public class SimulationParticipantController extends AbstractRestController { + + /** + * Constructor. + * + * @param simulationProvider the Simulation Provider + */ + public SimulationParticipantController(SimulationProvider simulationProvider) { + super(simulationProvider); + } /** * Queries details of all participants within the simulator. @@ -60,8 +66,7 @@ public class SimulationParticipantController extends RestController { * @return the participants */ // @formatter:off - @GET - @Path("/participants/{name}/{version}") + @GetMapping("/participants/{name}/{version}") @ApiOperation(value = "Query details of the requested simulated participants", notes = "Queries details of the requested simulated participants, " + "returning all participant details", @@ -98,24 +103,14 @@ public class SimulationParticipantController extends RestController { } ) // @formatter:on - public Response participants(@HeaderParam(REQUEST_ID_NAME) @ApiParam(REQUEST_ID_PARAM_DESCRIPTION) UUID requestId, - @ApiParam(value = "Participant name", required = true) @PathParam("name") String name, - @ApiParam(value = "Participant version", required = true) @PathParam("version") String version) { - - try { - List<Participant> response = getSimulationProvider().getParticipants(name, version); - return addLoggingHeaders(addVersionControlHeaders(Response.status(Status.OK)), requestId).entity(response) - .build(); - - } catch (ControlLoopException cle) { - LOGGER.warn("get of participants failed", cle); - SimpleResponse resp = new SimpleResponse(); - resp.setErrorDetails(cle.getErrorResponse().getErrorMessage()); - return addLoggingHeaders( - addVersionControlHeaders(Response.status(cle.getErrorResponse().getResponseCode())), requestId) - .entity(resp).build(); - } + public ResponseEntity<List<Participant>> participants( + @RequestHeader( + name = REQUEST_ID_NAME, + required = false) @ApiParam(REQUEST_ID_PARAM_DESCRIPTION) UUID requestId, + @ApiParam(value = "Participant name", required = true) @PathVariable("name") String name, + @ApiParam(value = "Participant version", required = true) @PathVariable("version") String version) { + return ResponseEntity.ok().body(getSimulationProvider().getParticipants(name, version)); } /** @@ -126,8 +121,7 @@ public class SimulationParticipantController extends RestController { * @return a response */ // @formatter:off - @PUT - @Path("/participants") + @PutMapping("/participants") @ApiOperation( value = "Updates simulated participants", notes = "Updates simulated participants, returning the updated control loop definition IDs", @@ -172,21 +166,12 @@ public class SimulationParticipantController extends RestController { } ) // @formatter:on - public Response update(@HeaderParam(REQUEST_ID_NAME) @ApiParam(REQUEST_ID_PARAM_DESCRIPTION) UUID requestId, - @ApiParam(value = "Body of a participant", required = true) Participant body) { - - try { - TypedSimpleResponse<Participant> response = getSimulationProvider().updateParticipant(body); - return addLoggingHeaders(addVersionControlHeaders(Response.status(Status.OK)), requestId).entity(response) - .build(); + public ResponseEntity<TypedSimpleResponse<Participant>> update( + @RequestHeader( + name = REQUEST_ID_NAME, + required = false) @ApiParam(REQUEST_ID_PARAM_DESCRIPTION) UUID requestId, + @ApiParam(value = "Body of a participant", required = true) @RequestBody Participant body) { - } catch (ControlLoopException cle) { - LOGGER.warn("update of participant failed", cle); - TypedSimpleResponse<Participant> resp = new TypedSimpleResponse<>(); - resp.setErrorDetails(cle.getErrorResponse().getErrorMessage()); - return addLoggingHeaders( - addVersionControlHeaders(Response.status(cle.getErrorResponse().getResponseCode())), requestId) - .entity(resp).build(); - } + return ResponseEntity.ok().body(getSimulationProvider().updateParticipant(body)); } } |