17e34ed0196ed271520a65053d2aba625062794e
[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     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      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 Boolean isExtendedURINotNull(URI extendedURI) {
79         return extendedURI != null;
80     }
81
82     private Optional<StringEntity> createStringEntity(Optional<String> jsonBody) {
83         return Optional.of(parseJson(jsonBody).get());
84     }
85
86     private Optional<StringEntity> parseJson(Optional<String> jsonBody) {
87         Optional<StringEntity> stringEntity = Optional.empty();
88
89         try {
90             stringEntity = Optional.of(new StringEntity(jsonBody.get()));
91         } catch (UnsupportedEncodingException e) {
92             logger.error("Exception while parsing JSON: {}", e);
93         }
94
95         return stringEntity;
96     }
97
98     private Optional<HttpRequestBase> createRequest (DmaapPublisherRequestDetails requestDetails) {
99
100         Optional<HttpRequestBase> request = Optional.empty();
101         final URI extendedURI = createDmaapPublisherExtendedURI(requestDetails);
102
103         if ("application/json".equals(dmaapContentType)) {
104             request = Optional.ofNullable(createRequest(extendedURI, requestDetails));
105             request.get().addHeader("Content-type", dmaapContentType);
106         }
107
108         return request;
109     }
110
111     private URI createDmaapPublisherExtendedURI(DmaapPublisherRequestDetails requestDetails) {
112         URI extendedURI = null;
113
114         final URIBuilder uriBuilder = new URIBuilder()
115                 .setScheme(dmaapProtocol)
116                 .setHost(dmaapHostName)
117                 .setPort(dmaapPortNumber)
118                 .setPath(requestDetails.dmaapAPIPath() + "/" + dmaapTopicName);
119
120         try {
121             extendedURI = uriBuilder.build();
122             logger.info("Building extended URI: {}",extendedURI);
123         } catch (URISyntaxException e) {
124             logger.error("Exception while building extended URI: {}", e);
125         }
126
127         return extendedURI;
128     }
129
130     private HttpRequestBase createRequest(URI extendedURI, DmaapPublisherRequestDetails requestDetails) {
131         if (isExtendedURINotNull(extendedURI) && requestDetails.jsonBody().isPresent()) {
132             return createHttpPost(extendedURI, requestDetails.jsonBody());
133         } else {
134             return null;
135         }
136     }
137
138     private HttpPost createHttpPost(URI extendedURI, Optional<String> jsonBody) {
139         HttpPost post = new HttpPost(extendedURI);
140         Optional<StringEntity> stringEntity = createStringEntity(jsonBody);
141         post.setEntity(stringEntity.get());
142         return post;
143     }
144
145     private ResponseHandler<Optional<String>> dmaapProducerResponseHandler() {
146         return httpResponse ->  {
147             final int responseCode = httpResponse.getStatusLine().getStatusCode();
148             final HttpEntity responseEntity = httpResponse.getEntity();
149
150             if (HttpUtils.isSuccessfulResponseCode(responseCode)) {
151                 logger.info("HTTP response successful.");
152                 return Optional.of("" + responseCode);
153             } else {
154                 String response = responseEntity != null ? EntityUtils.toString(responseEntity) : "";
155                 logger.error("HTTP response not successful : {}", response);
156                 return Optional.of("" + responseCode);
157             }
158         };
159     }
160 }