cb7d5af29d216dfb527c7746b50ceecd0835795a
[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 package org.onap.dcaegen2.services.prh.service.consumer;
21
22 import static org.springframework.web.reactive.function.client.ExchangeFilterFunctions.basicAuthentication;
23
24 import java.net.URI;
25 import java.net.URISyntaxException;
26 import org.apache.http.client.utils.URIBuilder;
27 import org.onap.dcaegen2.services.prh.config.DmaapConsumerConfiguration;
28 import org.slf4j.Logger;
29 import org.slf4j.LoggerFactory;
30 import org.springframework.http.HttpHeaders;
31 import org.springframework.http.HttpStatus;
32 import org.springframework.web.reactive.function.client.ExchangeFilterFunction;
33 import org.springframework.web.reactive.function.client.WebClient;
34 import reactor.core.publisher.Mono;
35
36 /**
37  * @author <a href="mailto:przemyslaw.wasala@nokia.com">Przemysław Wąsala</a> on 6/26/18
38  */
39 public class DmaapConsumerReactiveHttpClient {
40
41     private final Logger logger = LoggerFactory.getLogger(this.getClass());
42
43     private WebClient webClient;
44     private final String dmaapHostName;
45     private final String dmaapProtocol;
46     private final Integer dmaapPortNumber;
47     private final String dmaapTopicName;
48     private final String consumerGroup;
49     private final String consumerId;
50     private final String dmaapContentType;
51     private final String dmaapUserName;
52     private final String dmaapUserPassword;
53
54     public DmaapConsumerReactiveHttpClient(DmaapConsumerConfiguration consumerConfiguration) {
55         this.dmaapHostName = consumerConfiguration.dmaapHostName();
56         this.dmaapProtocol = consumerConfiguration.dmaapProtocol();
57         this.dmaapPortNumber = consumerConfiguration.dmaapPortNumber();
58         this.dmaapTopicName = consumerConfiguration.dmaapTopicName();
59         this.consumerGroup = consumerConfiguration.consumerGroup();
60         this.consumerId = consumerConfiguration.consumerId();
61         this.dmaapContentType = consumerConfiguration.dmaapContentType();
62         this.dmaapUserName = consumerConfiguration.dmaapUserName();
63         this.dmaapUserPassword = consumerConfiguration.dmaapUserPassword();
64     }
65
66     public void initWebClient() {
67         this.webClient = WebClient.builder()
68             .defaultHeader(HttpHeaders.CONTENT_TYPE, dmaapContentType)
69             .filter(basicAuthentication(dmaapUserName, dmaapUserPassword))
70             .filter(logRequest())
71             .filter(logResponse())
72             .build();
73     }
74
75     public Mono<String> getDmaaPConsumerResponse() {
76         try {
77             return webClient
78                 .get()
79                 .uri(getUri())
80                 .retrieve()
81                 .onStatus(HttpStatus::is4xxClientError, clientResponse ->
82                     Mono.error(new Exception("HTTP 400"))
83                 )
84                 .onStatus(HttpStatus::is5xxServerError, clientResponse ->
85                     Mono.error(new Exception("HTTP 500")))
86                 .bodyToMono(String.class);
87         } catch (URISyntaxException e) {
88             logger.warn("Exception while executing HTTP request: ", e);
89             return Mono.error(e);
90         }
91     }
92
93     private String createRequestPath() {
94         return dmaapTopicName + "/" + consumerGroup + "/" + consumerId;
95     }
96
97     void initWebClient(WebClient webClient) {
98         this.webClient = webClient;
99     }
100
101     ExchangeFilterFunction logResponse() {
102         return ExchangeFilterFunction.ofResponseProcessor(clientResponse -> {
103             logger.info("Response Status {}", clientResponse.statusCode());
104             return Mono.just(clientResponse);
105         });
106     }
107
108     URI getUri() throws URISyntaxException {
109         return new URIBuilder().setScheme(dmaapProtocol).setHost(dmaapHostName).setPort(dmaapPortNumber)
110             .setPath(createRequestPath()).build();
111     }
112
113     ExchangeFilterFunction logRequest() {
114         return ExchangeFilterFunction.ofRequestProcessor(clientRequest -> {
115             logger.info("Request: {} {}", clientRequest.method(), clientRequest.url());
116             clientRequest.headers()
117                 .forEach((name, values) -> values.forEach(value -> logger.info("{}={}", name, value)));
118             return Mono.just(clientRequest);
119         });
120     }
121 }