a99833dcc11e62474448b522f607ffc06bf02f20
[dcaegen2/services/prh.git] /
1 /*
2  * ============LICENSE_START=======================================================
3  * PNF-REGISTRATION-HANDLER
4  * ================================================================================
5  * Copyright (C) 2018 NOKIA Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  *
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.onap.dcaegen2.services.prh.service.consumer;
22
23 import static org.springframework.web.reactive.function.client.ExchangeFilterFunctions.basicAuthentication;
24
25 import java.net.URI;
26 import java.net.URISyntaxException;
27 import java.util.Optional;
28 import org.apache.http.client.utils.URIBuilder;
29 import org.onap.dcaegen2.services.prh.config.DmaapConsumerConfiguration;
30 import org.slf4j.Logger;
31 import org.slf4j.LoggerFactory;
32 import org.springframework.http.HttpHeaders;
33 import org.springframework.http.HttpStatus;
34 import org.springframework.web.reactive.function.client.ExchangeFilterFunction;
35 import org.springframework.web.reactive.function.client.WebClient;
36 import reactor.core.publisher.Mono;
37
38 /**
39  * @author <a href="mailto:przemyslaw.wasala@nokia.com">Przemysław Wąsala</a> on 6/26/18
40  */
41 public class DmaapConsumerReactiveHttpClient {
42
43     private final Logger logger = LoggerFactory.getLogger(this.getClass());
44
45     private WebClient webClient;
46     private final String dmaapHostName;
47     private final String dmaapProtocol;
48     private final Integer dmaapPortNumber;
49     private final String dmaapTopicName;
50     private final String consumerGroup;
51     private final String consumerId;
52
53     public DmaapConsumerReactiveHttpClient(DmaapConsumerConfiguration consumerConfiguration) {
54         this.dmaapHostName = consumerConfiguration.dmaapHostName();
55         this.dmaapProtocol = consumerConfiguration.dmaapProtocol();
56         this.dmaapPortNumber = consumerConfiguration.dmaapPortNumber();
57         this.dmaapTopicName = consumerConfiguration.dmaapTopicName();
58         this.consumerGroup = consumerConfiguration.consumerGroup();
59         this.consumerId = consumerConfiguration.consumerId();
60         String dmaapContentType = consumerConfiguration.dmaapContentType();
61         this.webClient = WebClient.builder()
62             .defaultHeader(HttpHeaders.CONTENT_TYPE, dmaapContentType)
63             .filter(
64                 basicAuthentication(consumerConfiguration.dmaapUserName(), consumerConfiguration.dmaapUserPassword()))
65             .filter(logRequest())
66             .filter(logResponse())
67             .build();
68     }
69
70     public Mono<Optional<String>> getDmaaPConsumerResponse() {
71         try {
72             return webClient
73                 .get()
74                 .uri(getUri())
75                 .retrieve()
76                 .onStatus(HttpStatus::is4xxClientError, clientResponse ->
77                     Mono.error(new Exception("HTTP 400"))
78                 )
79                 .onStatus(HttpStatus::is5xxServerError, clientResponse ->
80                     Mono.error(new Exception("HTTP 500")))
81                 .bodyToMono(String.class)
82                 .map(Optional::of);
83         } catch (URISyntaxException e) {
84             logger.warn("Exception while executing HTTP request: ", e);
85             return Mono.error(e);
86         }
87     }
88
89     private URI getUri() throws URISyntaxException {
90         return new URIBuilder().setScheme(dmaapProtocol).setHost(dmaapHostName).setPort(dmaapPortNumber)
91             .setPath(createRequestPath()).build();
92     }
93
94     private String createRequestPath() {
95         return dmaapTopicName + "/" + consumerGroup + "/" + consumerId;
96     }
97
98     private ExchangeFilterFunction logResponse() {
99         return ExchangeFilterFunction.ofResponseProcessor(clientResponse -> {
100             logger.info("Response Status {}", clientResponse.statusCode());
101             return Mono.just(clientResponse);
102         });
103     }
104
105     private ExchangeFilterFunction logRequest() {
106         return ExchangeFilterFunction.ofRequestProcessor(clientRequest -> {
107             logger.info("Request: {} {}", clientRequest.method(), clientRequest.url());
108             clientRequest.headers()
109                 .forEach((name, values) -> values.forEach(value -> logger.info("{}={}", name, value)));
110             return Mono.just(clientRequest);
111         });
112     }
113 }