diff options
author | Jakub Zieba <jakub.zieba@nokia.com> | 2018-08-28 14:07:56 +0200 |
---|---|---|
committer | Jakub Zieba <jakub.zieba@nokia.com> | 2018-08-29 13:09:46 +0200 |
commit | 4fbb9e8ad097c9ec3c3434ba257e887fb3a64699 (patch) | |
tree | b244acb1fd41b987afd514205636f16fe6d5e76e /prh-app-server/src | |
parent | 5b4e3b195960af161604eccb1c1c805bb91c6648 (diff) |
Revert web server to prh, fix configuration
Revert web server to prh, becaue it is used by health check
Fix cloud configuration fetching
Additional code refactoring
Change-Id: Ic3d6f4c266064436e2701ec3ef3a7534b2d5b8b4
Issue-ID: DCAEGEN2-696
Signed-off-by: Jakub Zieba <jakub.zieba@nokia.com>
Diffstat (limited to 'prh-app-server/src')
12 files changed, 418 insertions, 171 deletions
diff --git a/prh-app-server/src/main/java/org/onap/dcaegen2/services/prh/MainApp.java b/prh-app-server/src/main/java/org/onap/dcaegen2/services/prh/MainApp.java index 2357e1d2..fc485e15 100644 --- a/prh-app-server/src/main/java/org/onap/dcaegen2/services/prh/MainApp.java +++ b/prh-app-server/src/main/java/org/onap/dcaegen2/services/prh/MainApp.java @@ -34,10 +34,8 @@ import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler; /** * @author <a href="mailto:przemyslaw.wasala@nokia.com">Przemysław Wąsala</a> on 3/23/18 */ -@SpringBootApplication +@SpringBootApplication(exclude = {JacksonAutoConfiguration.class}) @Configuration -@ComponentScan -@EnableAutoConfiguration(exclude = {JacksonAutoConfiguration.class}) @EnableScheduling public class MainApp { diff --git a/prh-app-server/src/main/java/org/onap/dcaegen2/services/prh/configuration/CloudConfiguration.java b/prh-app-server/src/main/java/org/onap/dcaegen2/services/prh/configuration/CloudConfiguration.java index 82017a9d..b774f545 100644 --- a/prh-app-server/src/main/java/org/onap/dcaegen2/services/prh/configuration/CloudConfiguration.java +++ b/prh-app-server/src/main/java/org/onap/dcaegen2/services/prh/configuration/CloudConfiguration.java @@ -27,45 +27,42 @@ import org.onap.dcaegen2.services.prh.config.AaiClientConfiguration; import org.onap.dcaegen2.services.prh.config.DmaapConsumerConfiguration; import org.onap.dcaegen2.services.prh.config.DmaapPublisherConfiguration; import org.onap.dcaegen2.services.prh.model.EnvProperties; -import org.onap.dcaegen2.services.prh.service.HttpClientExecutorService; +import org.onap.dcaegen2.services.prh.service.PrhConfigurationProvider; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.annotation.Configuration; -import org.springframework.scheduling.TaskScheduler; +import org.springframework.context.annotation.Primary; import org.springframework.scheduling.annotation.EnableScheduling; -import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler; import reactor.core.publisher.Flux; import reactor.core.scheduler.Schedulers; + /** * @author <a href="mailto:przemyslaw.wasala@nokia.com">Przemysław Wąsala</a> on 8/9/18 */ @Configuration @EnableConfigurationProperties @EnableScheduling +@Primary public class CloudConfiguration extends AppConfig { private Logger logger = LoggerFactory.getLogger(this.getClass()); - private HttpClientExecutorService httpClientExecutorService; + private PrhConfigurationProvider prhConfigurationProvider; private AaiClientConfiguration aaiClientCloudConfiguration; private DmaapPublisherConfiguration dmaapPublisherCloudConfiguration; private DmaapConsumerConfiguration dmaapConsumerCloudConfiguration; - TaskScheduler cloudTaskScheduler; - @Value("#{systemEnvironment}") private Properties systemEnvironment; @Autowired - public void setThreadPoolTaskScheduler(ThreadPoolTaskScheduler threadPoolTaskScheduler, - HttpClientExecutorService httpClientExecutorService) { - this.cloudTaskScheduler = threadPoolTaskScheduler; - this.httpClientExecutorService = httpClientExecutorService; + public void setThreadPoolTaskScheduler(PrhConfigurationProvider prhConfigurationProvider) { + this.prhConfigurationProvider = prhConfigurationProvider; } protected void runTask() { @@ -84,10 +81,8 @@ public class CloudConfiguration extends AppConfig { private void parsingConfigSuccess(EnvProperties envProperties) { logger.info("Fetching PRH configuration from ConfigBindingService/Consul"); - Flux.just(httpClientExecutorService.callConsulForConfigBindingServiceEndpoint(envProperties)) - .flatMap(configBindingServiceUri -> httpClientExecutorService - .callConfigBindingServiceForPrhConfiguration(envProperties, - configBindingServiceUri)).subscribe(this::parseCloudConfig, this::cloudConfigError); + prhConfigurationProvider.callForPrhConfiguration(envProperties) + .subscribe(this::parseCloudConfig, this::cloudConfigError); } private void parseCloudConfig(JsonObject jsonObject) { diff --git a/prh-app-server/src/main/java/org/onap/dcaegen2/services/prh/configuration/SchedulerConfig.java b/prh-app-server/src/main/java/org/onap/dcaegen2/services/prh/configuration/SchedulerConfig.java index c53d3333..a27feefb 100644 --- a/prh-app-server/src/main/java/org/onap/dcaegen2/services/prh/configuration/SchedulerConfig.java +++ b/prh-app-server/src/main/java/org/onap/dcaegen2/services/prh/configuration/SchedulerConfig.java @@ -33,8 +33,10 @@ import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.context.annotation.Configuration; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; +import org.springframework.scheduling.TaskScheduler; import org.springframework.scheduling.annotation.EnableScheduling; import org.springframework.scheduling.concurrent.ConcurrentTaskScheduler; +import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler; import reactor.core.publisher.Mono; /** @@ -42,7 +44,7 @@ import reactor.core.publisher.Mono; */ @Configuration @EnableScheduling -public class SchedulerConfig extends CloudConfiguration { +public class SchedulerConfig { private static final int SCHEDULING_DELAY_FOR_PRH_TASKS = 5; private static final int SCHEDULING_REQUEST_FOR_CONFIGURATION_DELAY = 5; @@ -50,12 +52,17 @@ public class SchedulerConfig extends CloudConfiguration { private final ConcurrentTaskScheduler taskScheduler; private final ScheduledTasks scheduledTask; + private final TaskScheduler cloudTaskScheduler; + private final CloudConfiguration cloudConfiguration; @Autowired public SchedulerConfig(@Qualifier("concurrentTaskScheduler") ConcurrentTaskScheduler concurrentTaskScheduler, - ScheduledTasks scheduledTask) { + ScheduledTasks scheduledTask, ThreadPoolTaskScheduler cloudTaskScheduler, + CloudConfiguration cloudConfiguration) { this.taskScheduler = concurrentTaskScheduler; this.scheduledTask = scheduledTask; + this.cloudTaskScheduler = cloudTaskScheduler; + this.cloudConfiguration = cloudConfiguration; } /** @@ -83,7 +90,7 @@ public class SchedulerConfig extends CloudConfiguration { public synchronized boolean tryToStartTask() { if (scheduledPrhTaskFutureList.isEmpty()) { scheduledPrhTaskFutureList.add(cloudTaskScheduler - .scheduleAtFixedRate(super::runTask, Instant.now(), + .scheduleAtFixedRate(cloudConfiguration::runTask, Instant.now(), Duration.ofMinutes(SCHEDULING_REQUEST_FOR_CONFIGURATION_DELAY))); scheduledPrhTaskFutureList.add(taskScheduler .scheduleWithFixedDelay(scheduledTask::scheduleMainPrhEventTask, diff --git a/prh-app-server/src/main/java/org/onap/dcaegen2/services/prh/service/HttpClientExecutorService.java b/prh-app-server/src/main/java/org/onap/dcaegen2/services/prh/service/HttpClientExecutorService.java deleted file mode 100644 index 1b69f5fd..00000000 --- a/prh-app-server/src/main/java/org/onap/dcaegen2/services/prh/service/HttpClientExecutorService.java +++ /dev/null @@ -1,136 +0,0 @@ -/* - * ============LICENSE_START======================================================= - * PNF-REGISTRATION-HANDLER - * ================================================================================ - * Copyright (C) 2018 NOKIA Intellectual Property. All 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.dcaegen2.services.prh.service; - -import com.google.gson.Gson; -import com.google.gson.JsonArray; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import org.onap.dcaegen2.services.prh.model.EnvProperties; -import org.reactivestreams.Publisher; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.http.HttpStatus; -import org.springframework.stereotype.Service; -import org.springframework.web.reactive.function.client.ExchangeFilterFunction; -import org.springframework.web.reactive.function.client.WebClient; -import reactor.core.publisher.Mono; - -/** - * @author <a href="mailto:przemyslaw.wasala@nokia.com">Przemysław Wąsala</a> on 8/10/18 - */ - -@Service -public class HttpClientExecutorService { - - private final Logger logger = LoggerFactory.getLogger(this.getClass()); - - public Mono<String> callConsulForConfigBindingServiceEndpoint(EnvProperties envProperties) { - - return HttpGetClient.callHttpGet( - envProperties.consulHost() + ":" + envProperties.consulPort() + "/v1/catalog/service/" + envProperties - .cbsName()) - .flatMap(this::getJsonArrayFromRequest) - .flatMap(jsonArray -> Mono.just(jsonArray.get(0))) - .flatMap(this::createConfigBindingServiceURL); - - } - - public Publisher<JsonObject> callConfigBindingServiceForPrhConfiguration(EnvProperties envProperties, - Mono<String> configBindingServiceUri) { - return HttpGetClient.callHttpGet(configBindingServiceUri + "/service_component/" + envProperties.appName()) - .flatMap(this::getJsonConfiguration); - } - - private Mono<? extends JsonObject> getJsonConfiguration(String body) { - JsonElement jsonElement = new Gson().toJsonTree(body); - try { - return Mono.just(jsonElement.getAsJsonObject()); - } catch (IllegalStateException e) { - return Mono.error(e); - } - } - - private Mono<String> createConfigBindingServiceURL(JsonElement jsonElement) { - JsonObject jsonObject; - try { - jsonObject = jsonElement.getAsJsonObject(); - } catch (IllegalStateException e) { - return Mono.error(e); - } - return Mono.just(jsonObject.get("ServiceAddress").toString() + ":" + jsonObject.get("ServicePort").toString()); - } - - - private Mono<? extends JsonArray> getJsonArrayFromRequest(String body) { - JsonElement jsonElement = new Gson().toJsonTree(body); - try { - return Mono.just(jsonElement.getAsJsonArray()); - } catch (IllegalStateException e) { - logger.warn("Converting string to jsonArray threw error: " + e); - return Mono.error(e); - } - } - - private static class HttpGetClient { - - private static final Logger logger = LoggerFactory.getLogger(HttpGetClient.class); - - private static WebClient webClient; - - private HttpGetClient() { - } - - private static Mono<String> callHttpGet(String url) { - return webClient - .get() - .uri(url) - .retrieve() - .onStatus(HttpStatus::is4xxClientError, response -> - Mono.error(new Exception("Request for cloud config failed: HTTP 400"))) - .onStatus(HttpStatus::is5xxServerError, response -> - Mono.error(new Exception("Request for cloud config failed: HTTP 500"))) - .bodyToMono(String.class); - } - - private static ExchangeFilterFunction logResponse() { - return ExchangeFilterFunction.ofResponseProcessor(clientResponse -> { - logger.info("Response status {}", clientResponse.statusCode()); - return Mono.just(clientResponse); - }); - } - - private static ExchangeFilterFunction logRequest() { - return ExchangeFilterFunction.ofRequestProcessor(clientRequest -> { - logger.info("Request: {} {}", clientRequest.method(), clientRequest.url()); - clientRequest.headers() - .forEach((name, values) -> values.forEach(value -> logger.info("{}={}", name, value))); - return Mono.just(clientRequest); - }); - } - - static { - webClient = WebClient.builder().filter(logRequest()).filter(logResponse()).build(); - } - - - } -} diff --git a/prh-app-server/src/main/java/org/onap/dcaegen2/services/prh/service/HttpGetClient.java b/prh-app-server/src/main/java/org/onap/dcaegen2/services/prh/service/HttpGetClient.java new file mode 100644 index 00000000..56ab484b --- /dev/null +++ b/prh-app-server/src/main/java/org/onap/dcaegen2/services/prh/service/HttpGetClient.java @@ -0,0 +1,93 @@ +/* + * ============LICENSE_START======================================================= + * PNF-REGISTRATION-HANDLER + * ================================================================================ + * Copyright (C) 2018 NOKIA Intellectual Property. All 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.dcaegen2.services.prh.service; + +import com.google.gson.Gson; +import com.google.gson.JsonSyntaxException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.http.HttpStatus; +import org.springframework.web.reactive.function.client.ClientResponse; +import org.springframework.web.reactive.function.client.ExchangeFilterFunction; +import org.springframework.web.reactive.function.client.WebClient; +import reactor.core.publisher.Mono; + +public class HttpGetClient { + + private static final Logger logger = LoggerFactory.getLogger(HttpGetClient.class); + + private final WebClient webClient; + private final Gson gson; + + HttpGetClient() { + this(WebClient.builder().filter(logRequest()).filter(logResponse()).build()); + } + + HttpGetClient(WebClient webClient){ + this.webClient = webClient; + this.gson = new Gson(); + } + + public <T> Mono<T> callHttpGet(String url, Class<T> tClass) { + return webClient + .get() + .uri(url) + .retrieve() + .onStatus(HttpStatus::is4xxClientError, response -> Mono.error(getException(response))) + .onStatus(HttpStatus::is5xxServerError, response -> Mono.error(getException(response))) + .bodyToMono(String.class) + .flatMap(body->getJsonFromRequest(body,tClass)); + } + + private RuntimeException getException(ClientResponse response) { + return new RuntimeException(String.format("Request for cloud config failed: HTTP %d", + response.statusCode().value())); + } + + private <T> Mono<T> getJsonFromRequest(String body, Class<T> tClass) { + try { + return Mono.just(parseJson(body, tClass)); + } catch (JsonSyntaxException | IllegalStateException e) { + logger.warn("Converting string to json threw error ", e); + return Mono.error(e); + } + } + + private <T> T parseJson(String body, Class<T> tClass){ + return gson.fromJson(body, tClass); + } + + private static ExchangeFilterFunction logResponse() { + return ExchangeFilterFunction.ofResponseProcessor(clientResponse -> { + logger.info("Response status {}", clientResponse.statusCode()); + return Mono.just(clientResponse); + }); + } + + private static ExchangeFilterFunction logRequest() { + return ExchangeFilterFunction.ofRequestProcessor(clientRequest -> { + logger.info("Request: {} {}", clientRequest.method(), clientRequest.url()); + clientRequest.headers() + .forEach((name, values) -> values.forEach(value -> logger.info("{}={}", name, value))); + return Mono.just(clientRequest); + }); + } +} diff --git a/prh-app-server/src/main/java/org/onap/dcaegen2/services/prh/service/PrhConfigurationProvider.java b/prh-app-server/src/main/java/org/onap/dcaegen2/services/prh/service/PrhConfigurationProvider.java new file mode 100644 index 00000000..7af4a7c8 --- /dev/null +++ b/prh-app-server/src/main/java/org/onap/dcaegen2/services/prh/service/PrhConfigurationProvider.java @@ -0,0 +1,115 @@ +/* + * ============LICENSE_START======================================================= + * PNF-REGISTRATION-HANDLER + * ================================================================================ + * Copyright (C) 2018 NOKIA Intellectual Property. All 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.dcaegen2.services.prh.service; + +import com.google.gson.JsonArray; +import com.google.gson.JsonObject; +import org.apache.http.client.utils.URIBuilder; +import org.onap.dcaegen2.services.prh.model.EnvProperties; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Service; +import reactor.core.publisher.Mono; + +import java.net.URISyntaxException; + +/** + * @author <a href="mailto:przemyslaw.wasala@nokia.com">Przemysław Wąsala</a> on 8/10/18 + */ + +@Service +public class PrhConfigurationProvider { + + private final Logger logger = LoggerFactory.getLogger(this.getClass()); + + private final HttpGetClient httpGetClient; + + PrhConfigurationProvider() { + this(new HttpGetClient()); + } + + PrhConfigurationProvider(HttpGetClient httpGetClient) { + this.httpGetClient = httpGetClient; + } + + public Mono<JsonObject> callForPrhConfiguration(EnvProperties envProperties) { + return callConsulForConfigBindingServiceEndpoint(envProperties) + .flatMap(this::callConfigBindingServiceForPrhConfiguration); + } + + private Mono<String> callConsulForConfigBindingServiceEndpoint(EnvProperties envProperties) { + logger.info("Retrieving Config Binding Service endpoint from Consul"); + try { + return httpGetClient.callHttpGet(getConsulUrl(envProperties), JsonArray.class) + .flatMap(jsonArray -> this.createConfigBindingServiceURL(jsonArray, envProperties.appName())); + } catch (URISyntaxException e) { + logger.warn("Malformed Consul uri", e); + return Mono.error(e); + } + } + + private String getConsulUrl(EnvProperties envProperties) throws URISyntaxException { + return getUri(envProperties.consulHost(), envProperties.consulPort(), "/v1/catalog/service", + envProperties.cbsName()); + } + + private Mono<JsonObject> callConfigBindingServiceForPrhConfiguration(String configBindingServiceUri) { + logger.info("Retrieving PRH configuration"); + return httpGetClient.callHttpGet(configBindingServiceUri, JsonObject.class); + } + + + private Mono<String> createConfigBindingServiceURL(JsonArray jsonArray, String appName) { + return getConfigBindingObject(jsonArray).flatMap(jsonObject -> buildConfigBindingServiceURL(jsonObject, appName)); + } + + private Mono<String> buildConfigBindingServiceURL(JsonObject jsonObject, String appName) { + try { + return Mono.just(getUri(jsonObject.get("ServiceAddress").getAsString(), + jsonObject.get("ServicePort").getAsInt(), "/service_component", appName)); + } catch (URISyntaxException e) { + logger.warn("Malformed Config Binding Service uri", e); + return Mono.error(e); + } + } + + private Mono<JsonObject> getConfigBindingObject(JsonArray jsonArray) { + try { + if (jsonArray.size() > 0) { + return Mono.just(jsonArray.get(0).getAsJsonObject()); + } else { + throw new IllegalStateException("JSON Array was empty"); + } + } catch (IllegalStateException e) { + logger.warn("Failed to retrieve JSON Object from array", e); + return Mono.error(e); + } + } + + private String getUri(String host, Integer port, String... paths) throws URISyntaxException { + return new URIBuilder() + .setScheme("http") + .setHost(host) + .setPort(port) + .setPath(String.join("/", paths)) + .build().toString(); + } +} diff --git a/prh-app-server/src/main/java/org/onap/dcaegen2/services/prh/tasks/AaiProducerTaskImpl.java b/prh-app-server/src/main/java/org/onap/dcaegen2/services/prh/tasks/AaiProducerTaskImpl.java index 976547e2..379d10c6 100644 --- a/prh-app-server/src/main/java/org/onap/dcaegen2/services/prh/tasks/AaiProducerTaskImpl.java +++ b/prh-app-server/src/main/java/org/onap/dcaegen2/services/prh/tasks/AaiProducerTaskImpl.java @@ -31,7 +31,6 @@ import org.onap.dcaegen2.services.prh.service.producer.AaiProducerReactiveHttpCl import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Component; import reactor.core.publisher.Mono; @@ -48,7 +47,7 @@ public class AaiProducerTaskImpl extends private AaiProducerReactiveHttpClient aaiProducerReactiveHttpClient; @Autowired - public AaiProducerTaskImpl(@Qualifier("cloudConfiguration") Config config) { + public AaiProducerTaskImpl(Config config) { this.config = config; } @@ -67,8 +66,7 @@ public class AaiProducerTaskImpl extends @Override AaiProducerReactiveHttpClient resolveClient() { - return aaiProducerReactiveHttpClient == null ? new AaiProducerReactiveHttpClient(resolveConfiguration()) - .createAaiWebClient(buildWebClient()) : aaiProducerReactiveHttpClient; + return new AaiProducerReactiveHttpClient(resolveConfiguration()); } @Override diff --git a/prh-app-server/src/main/java/org/onap/dcaegen2/services/prh/tasks/DmaapConsumerTaskImpl.java b/prh-app-server/src/main/java/org/onap/dcaegen2/services/prh/tasks/DmaapConsumerTaskImpl.java index f8eccf11..bf3acccc 100644 --- a/prh-app-server/src/main/java/org/onap/dcaegen2/services/prh/tasks/DmaapConsumerTaskImpl.java +++ b/prh-app-server/src/main/java/org/onap/dcaegen2/services/prh/tasks/DmaapConsumerTaskImpl.java @@ -29,7 +29,6 @@ import org.onap.dcaegen2.services.prh.service.consumer.DMaaPConsumerReactiveHttp import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Component; import reactor.core.publisher.Mono; @@ -45,7 +44,7 @@ public class DmaapConsumerTaskImpl extends DmaapConsumerTask { private DMaaPConsumerReactiveHttpClient dmaaPConsumerReactiveHttpClient; @Autowired - public DmaapConsumerTaskImpl(@Qualifier("cloudConfiguration") Config config) { + public DmaapConsumerTaskImpl(Config config) { this.config = config; this.dmaapConsumerJsonParser = new DmaapConsumerJsonParser(); } @@ -79,8 +78,6 @@ public class DmaapConsumerTaskImpl extends DmaapConsumerTask { @Override DMaaPConsumerReactiveHttpClient resolveClient() { - return dmaaPConsumerReactiveHttpClient == null - ? new DMaaPConsumerReactiveHttpClient(resolveConfiguration()).createDMaaPWebClient(buildWebClient()) - : dmaaPConsumerReactiveHttpClient; + return new DMaaPConsumerReactiveHttpClient(resolveConfiguration()).createDMaaPWebClient(buildWebClient()); } } diff --git a/prh-app-server/src/main/java/org/onap/dcaegen2/services/prh/tasks/DmaapPublisherTaskImpl.java b/prh-app-server/src/main/java/org/onap/dcaegen2/services/prh/tasks/DmaapPublisherTaskImpl.java index 13f1b162..d4e1c1e3 100644 --- a/prh-app-server/src/main/java/org/onap/dcaegen2/services/prh/tasks/DmaapPublisherTaskImpl.java +++ b/prh-app-server/src/main/java/org/onap/dcaegen2/services/prh/tasks/DmaapPublisherTaskImpl.java @@ -28,7 +28,6 @@ import org.onap.dcaegen2.services.prh.service.producer.DMaaPProducerReactiveHttp import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Component; import reactor.core.publisher.Mono; @@ -43,7 +42,7 @@ public class DmaapPublisherTaskImpl extends DmaapPublisherTask { private DMaaPProducerReactiveHttpClient dmaapProducerReactiveHttpClient; @Autowired - public DmaapPublisherTaskImpl(@Qualifier("cloudConfiguration") Config config) { + public DmaapPublisherTaskImpl(Config config) { this.config = config; } @@ -73,8 +72,6 @@ public class DmaapPublisherTaskImpl extends DmaapPublisherTask { @Override DMaaPProducerReactiveHttpClient resolveClient() { - return dmaapProducerReactiveHttpClient == null - ? new DMaaPProducerReactiveHttpClient(resolveConfiguration()).createDMaaPWebClient(buildWebClient()) - : dmaapProducerReactiveHttpClient; + return new DMaaPProducerReactiveHttpClient(resolveConfiguration()).createDMaaPWebClient(buildWebClient()); } }
\ No newline at end of file diff --git a/prh-app-server/src/main/resources/application.properties b/prh-app-server/src/main/resources/application.properties index 7c6d988c..fa38d188 100644 --- a/prh-app-server/src/main/resources/application.properties +++ b/prh-app-server/src/main/resources/application.properties @@ -1,5 +1,4 @@ spring.profiles.active=prod -spring.main.web-application-type=none server.port=8433 server.ssl.key-store-type=PKCS12 server.ssl.key-store-password=nokiapnf diff --git a/prh-app-server/src/test/java/org/onap/dcaegen2/services/prh/service/HttpGetClientTest.java b/prh-app-server/src/test/java/org/onap/dcaegen2/services/prh/service/HttpGetClientTest.java new file mode 100644 index 00000000..5caed791 --- /dev/null +++ b/prh-app-server/src/test/java/org/onap/dcaegen2/services/prh/service/HttpGetClientTest.java @@ -0,0 +1,85 @@ +/* + * ============LICENSE_START======================================================= + * PROJECT + * ================================================================================ + * Copyright (C) 2018 NOKIA Intellectual Property. All 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.dcaegen2.services.prh.service; + +import com.google.gson.Gson; +import com.google.gson.JsonObject; +import com.google.gson.JsonParseException; +import com.google.gson.JsonSyntaxException; +import org.junit.jupiter.api.Test; +import org.springframework.web.reactive.function.client.WebClient; +import reactor.core.publisher.Mono; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.*; + +class HttpGetClientTest { + private static final String SOMEURL = "http://someurl"; + private static final String DATA = "{}"; + private Gson gson = new Gson(); + private WebClient webClient = mock(WebClient.class); + private WebClient.RequestHeadersUriSpec requestBodyUriSpec = mock(WebClient.RequestBodyUriSpec.class); + private WebClient.ResponseSpec responseSpec = mock(WebClient.ResponseSpec.class); + + @Test + void shouldReturnJsonObjectOnGetCall() { + //given + mockWebClientDependantObject(); + HttpGetClient httpGetClient = new HttpGetClient(webClient); + when(responseSpec.bodyToMono(String.class)).thenReturn(Mono.just(DATA)); + + //when + Mono<JsonObject> jsonObjectMono = httpGetClient.callHttpGet(SOMEURL, JsonObject.class); + + //then + assertThat(jsonObjectMono).isNotNull(); + assertThat(jsonObjectMono.block()).isEqualTo(gson.fromJson(DATA, JsonObject.class)); + } + + @Test + void shouldReturnMonoErrorOnGetCall() { + //given + mockWebClientDependantObject(); + HttpGetClient httpGetClient = new HttpGetClient(webClient); + when(responseSpec.bodyToMono(String.class)).thenReturn(Mono.just("some wrong data")); + + //when + Mono<JsonObject> jsonObjectMono = httpGetClient.callHttpGet(SOMEURL, JsonObject.class); + + //then + assertThat(jsonObjectMono).isNotNull(); + assertThrows(JsonSyntaxException.class, jsonObjectMono::block); + } + + + + private void mockWebClientDependantObject() { + doReturn(requestBodyUriSpec).when(webClient).get(); + when(requestBodyUriSpec.uri(SOMEURL)).thenReturn(requestBodyUriSpec); + doReturn(responseSpec).when(requestBodyUriSpec).retrieve(); + doReturn(responseSpec).when(responseSpec).onStatus(any(), any()); + doReturn(responseSpec).when(responseSpec).onStatus(any(), any()); + } + +}
\ No newline at end of file diff --git a/prh-app-server/src/test/java/org/onap/dcaegen2/services/prh/service/PrhConfigurationProviderTest.java b/prh-app-server/src/test/java/org/onap/dcaegen2/services/prh/service/PrhConfigurationProviderTest.java new file mode 100644 index 00000000..8b7ea3d0 --- /dev/null +++ b/prh-app-server/src/test/java/org/onap/dcaegen2/services/prh/service/PrhConfigurationProviderTest.java @@ -0,0 +1,99 @@ +/* + * ============LICENSE_START======================================================= + * PNF-REGISTRATION-HANDLER + * ================================================================================ + * Copyright (C) 2018 NOKIA Intellectual Property. All 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.dcaegen2.services.prh.service; + +import com.google.gson.Gson; +import com.google.gson.JsonArray; +import com.google.gson.JsonObject; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import org.onap.dcaegen2.services.prh.model.EnvProperties; +import org.onap.dcaegen2.services.prh.model.ImmutableEnvProperties; +import reactor.core.publisher.Mono; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +class PrhConfigurationProviderTest { + + private static final Gson gson = new Gson(); + private static final String configBindingService = "[{\"ID\":\"9c8dd674-34ce-7049-d318-e98d93a64303\",\"Node\"" + + ":\"dcae-bootstrap\",\"Address\":\"10.42.52.82\",\"Datacenter\":\"dc1\",\"TaggedAddresses\":" + + "{\"lan\":\"10.42.52.82\",\"wan\":\"10.42.52.82\"},\"NodeMeta\":{\"consul-network-segment\":\"\"}," + + "\"ServiceID\":\"dcae-cbs1\",\"ServiceName\":\"config-binding-service\",\"ServiceTags\":[]," + + "\"ServiceAddress\":\"config-binding-service\",\"ServicePort\":10000,\"ServiceEnableTagOverride\":false," + + "\"CreateIndex\":14352,\"ModifyIndex\":14352},{\"ID\":\"35c6f540-a29c-1a92-23b0-1305bd8c81f5\",\"Node\":" + + "\"dev-consul-server-1\",\"Address\":\"10.42.165.51\",\"Datacenter\":\"dc1\",\"TaggedAddresses\":" + + "{\"lan\":\"10.42.165.51\",\"wan\":\"10.42.165.51\"},\"NodeMeta\":{\"consul-network-segment\":\"\"}," + + "\"ServiceID\":\"dcae-cbs1\",\"ServiceName\":\"config-binding-service\",\"ServiceTags\":[]," + + "\"ServiceAddress\":\"config-binding-service\",\"ServicePort\":10000,\"ServiceEnableTagOverride\":false," + + "\"CreateIndex\":803,\"ModifyIndex\":803}]"; + private static final JsonArray configBindingServiceJson = gson.fromJson(configBindingService, JsonArray.class); + private static final JsonArray emptyConfigBindingServiceJson = gson.fromJson("[]", JsonArray.class); + private static final String prhMockConfiguration = "{\"test\":1}"; + private static final JsonObject prhMockConfigurationJson = gson.fromJson(prhMockConfiguration, JsonObject.class); + + private EnvProperties envProperties = ImmutableEnvProperties.builder() + .appName("dcae-prh") + .cbsName("config-binding-service") + .consulHost("consul") + .consulPort(8500) + .build(); + + @Test + void shouldReturnPrhConfiguration() { + // given + HttpGetClient webClient = mock(HttpGetClient.class); + when( + webClient.callHttpGet("http://consul:8500/v1/catalog/service/config-binding-service", JsonArray.class)) + .thenReturn(Mono.just(configBindingServiceJson)); + when(webClient.callHttpGet("http://config-binding-service:10000/service_component/dcae-prh", JsonObject.class)) + .thenReturn(Mono.just(prhMockConfigurationJson)); + + PrhConfigurationProvider provider = new PrhConfigurationProvider(webClient); + + // when + Mono<JsonObject> jsonObjectMono = provider.callForPrhConfiguration(envProperties); + + // then + assertThat(jsonObjectMono).isNotNull(); + assertThat(jsonObjectMono.block()).isEqualTo(prhMockConfigurationJson); + } + + @Test + void shouldReturnMonoErrorWhenConsuleDoesntHaveConfigBindingServiceEntry() { + // given + HttpGetClient webClient = mock(HttpGetClient.class); + when( + webClient.callHttpGet("http://consul:8500/v1/catalog/service/config-binding-service", JsonArray.class)) + .thenReturn(Mono.just(emptyConfigBindingServiceJson)); + + PrhConfigurationProvider provider = new PrhConfigurationProvider(webClient); + + // when + Mono<JsonObject> jsonObjectMono = provider.callForPrhConfiguration(envProperties); + + // then + assertThat(jsonObjectMono).isNotNull(); + Assertions.assertThrows(IllegalStateException.class, jsonObjectMono::block); + } +}
\ No newline at end of file |