af7534c67c07b55d15da8de2e73b7aa0bb53fe38
[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.service.producer;
22
23 import org.apache.http.HttpEntity;
24 import org.apache.http.client.ResponseHandler;
25 import org.apache.http.client.methods.HttpPost;
26 import org.apache.http.client.methods.HttpRequestBase;
27 import org.apache.http.client.utils.URIBuilder;
28 import org.apache.http.entity.StringEntity;
29 import org.apache.http.impl.client.CloseableHttpClient;
30 import org.apache.http.util.EntityUtils;
31 import org.onap.dcaegen2.services.config.DmaapPublisherConfiguration;
32 import org.onap.dcaegen2.services.service.DmaapHttpClientImpl;
33 import org.onap.dcaegen2.services.service.HttpUtils;
34 import org.slf4j.Logger;
35 import org.slf4j.LoggerFactory;
36
37 import java.io.IOException;
38 import java.io.UnsupportedEncodingException;
39 import java.net.URI;
40 import java.net.URISyntaxException;
41 import java.util.Optional;
42
43 public class ExtendedDmaapProducerHttpClientImpl {
44
45     private static Logger logger = LoggerFactory.getLogger(ExtendedDmaapProducerHttpClientImpl.class);
46
47     private final CloseableHttpClient closeableHttpClient;
48     private final String dmaapHostName;
49     private final String dmaapProtocol;
50     private final Integer dmaapPortNumber;
51     private final String dmaapTopicName;
52     private final String dmaapContentType;
53
54
55     public ExtendedDmaapProducerHttpClientImpl(DmaapPublisherConfiguration configuration) {
56         this.closeableHttpClient = new DmaapHttpClientImpl(configuration).getHttpClient();
57         this.dmaapHostName = configuration.dmaapHostName();
58         this.dmaapProtocol = configuration.dmaapProtocol();
59         this.dmaapPortNumber = configuration.dmaapPortNumber();
60         this.dmaapTopicName = configuration.dmaapTopicName();
61         this.dmaapContentType = configuration.dmaapContentType();
62     }
63
64     public Optional<String> getHttpProducerResponse(DmaapPublisherRequestDetails requestDetails) {
65
66         Optional<String> extendedDetails = Optional.empty();
67         Optional<HttpRequestBase> request = createRequest(requestDetails);
68
69         try {
70             extendedDetails = closeableHttpClient.execute(request.get(), dmaapProducerResponseHandler());
71         } catch (IOException | NullPointerException e) {
72             logger.error("Exception while executing HTTP request: {}", e);
73         }
74
75         return extendedDetails;
76     }
77     
78     private Optional<StringEntity> createStringEntity(Optional<String> jsonBody) {
79         return Optional.of(parseJson(jsonBody).get());
80     }
81
82     private Optional<StringEntity> parseJson(Optional<String> jsonBody) {
83         Optional<StringEntity> stringEntity = Optional.empty();
84
85         try {
86             stringEntity = Optional.of(new StringEntity(jsonBody.get()));
87         } catch (UnsupportedEncodingException e) {
88             logger.error("Exception while parsing JSON: {}", e);
89         }
90
91         return stringEntity;
92     }
93
94     private Optional<HttpRequestBase> createRequest(DmaapPublisherRequestDetails requestDetails) {
95
96         Optional<HttpRequestBase> request = Optional.empty();
97         final URI extendedURI = createDmaapPublisherExtendedURI(requestDetails);
98
99         if ("application/json".equals(dmaapContentType)) {
100             request = Optional.ofNullable(createRequest(extendedURI, requestDetails));
101             request.get().addHeader("Content-type", dmaapContentType);
102         }
103
104         return request;
105     }
106
107     private URI createDmaapPublisherExtendedURI(DmaapPublisherRequestDetails requestDetails) {
108         URI extendedURI = null;
109
110         final URIBuilder uriBuilder = new URIBuilder()
111             .setScheme(dmaapProtocol)
112             .setHost(dmaapHostName)
113             .setPort(dmaapPortNumber)
114             .setPath(requestDetails.dmaapAPIPath() + "/" + dmaapTopicName);
115
116         try {
117             extendedURI = uriBuilder.build();
118             logger.info("Building extended URI: {}", extendedURI);
119         } catch (URISyntaxException e) {
120             logger.error("Exception while building extended URI: ", e);
121         }
122
123         return extendedURI;
124     }
125
126     private HttpRequestBase createRequest(URI extendedURI, DmaapPublisherRequestDetails requestDetails) {
127         if (extendedURI != null) {
128             return createHttpPost(extendedURI, Optional.ofNullable(requestDetails.jsonBody()));
129         } else {
130             return null;
131         }
132     }
133
134     private HttpPost createHttpPost(URI extendedURI, Optional<String> jsonBody) {
135         HttpPost post = new HttpPost(extendedURI);
136         Optional<StringEntity> stringEntity = createStringEntity(jsonBody);
137         post.setEntity(stringEntity.get());
138         return post;
139     }
140
141     private ResponseHandler<Optional<String>> dmaapProducerResponseHandler() {
142         return httpResponse -> {
143             final int responseCode = httpResponse.getStatusLine().getStatusCode();
144             final HttpEntity responseEntity = httpResponse.getEntity();
145
146             if (HttpUtils.isSuccessfulResponseCode(responseCode)) {
147                 logger.info("HTTP response successful.");
148                 return Optional.of("" + responseCode);
149             } else {
150                 String response = responseEntity != null ? EntityUtils.toString(responseEntity) : "";
151                 logger.error("HTTP response not successful : {}", response);
152                 return Optional.of("" + responseCode);
153             }
154         };
155     }
156 }