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