ecc9ed2c3762550784b775ef148ae2fa7426c800
[dcaegen2/collectors/datafile.git] /
1 /*
2  * ============LICENSE_START=======================================================
3  * Datafile Collector Service
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.collectors.datafile.service;
22
23 import java.io.IOException;
24 import java.net.URI;
25 import java.net.URISyntaxException;
26 import java.util.Map;
27 import java.util.Objects;
28 import java.util.Optional;
29
30 import org.apache.http.HttpEntity;
31 import org.apache.http.client.ResponseHandler;
32 import org.apache.http.client.methods.HttpGet;
33 import org.apache.http.client.methods.HttpRequestBase;
34 import org.apache.http.client.utils.URIBuilder;
35 import org.apache.http.impl.client.CloseableHttpClient;
36 import org.apache.http.util.EntityUtils;
37 import org.onap.dcaegen2.collectors.datafile.config.AaiClientConfiguration;
38 import org.onap.dcaegen2.collectors.datafile.model.ConsumerDmaapModel;
39 import org.onap.dcaegen2.collectors.datafile.model.utils.HttpUtils;
40 import org.onap.dcaegen2.collectors.datafile.service.AaiClientImpl;
41 import org.slf4j.Logger;
42 import org.slf4j.LoggerFactory;
43
44
45 public class AaiConsumerClient {
46
47     private final Logger logger = LoggerFactory.getLogger(this.getClass());
48
49     private final CloseableHttpClient closeableHttpClient;
50     private final String aaiHost;
51     private final String aaiProtocol;
52     private final Integer aaiHostPortNumber;
53     private final String aaiPath;
54     private final Map<String, String> aaiHeaders;
55
56     /**
57      * A{@literal &}AI client for consuming data from A{@literal &}AI.
58      *
59      * @param aaiClientConfiguration - A{@literal &}AI client config
60      */
61     public AaiConsumerClient(AaiClientConfiguration aaiClientConfiguration) {
62         closeableHttpClient = new AaiClientImpl(aaiClientConfiguration).getAaiHttpClient();
63         aaiHost = aaiClientConfiguration.aaiHost();
64         aaiProtocol = aaiClientConfiguration.aaiProtocol();
65         aaiHostPortNumber = aaiClientConfiguration.aaiPort();
66         aaiPath = aaiClientConfiguration.aaiBasePath() + aaiClientConfiguration.aaiPnfPath();
67         aaiHeaders = aaiClientConfiguration.aaiHeaders();
68     }
69
70     /**
71      * Function which call http client for getting object from A{@literal &}AI.
72      *
73      * @param consumerDmaapModel - helper object for uri generation
74      * @return - status code of operation
75      * @throws IOException - Apache HTTP client exception
76      */
77     public Optional<String> getHttpResponse(ConsumerDmaapModel consumerDmaapModel) throws IOException {
78         Optional<HttpRequestBase> request = createRequest(consumerDmaapModel);
79         try {
80             return closeableHttpClient.execute(request.get(), aaiResponseHandler());
81         } catch (IOException e) {
82             logger.warn("Exception while executing http client: ", e);
83             throw new IOException();
84         }
85     }
86
87     private URI createAaiExtendedUri(String pnfName) {
88
89         URI extendedUri = null;
90
91         final URIBuilder uriBuilder = new URIBuilder()
92             .setScheme(aaiProtocol)
93             .setHost(aaiHost)
94             .setPort(aaiHostPortNumber)
95             .setPath(aaiPath + "/" + pnfName);
96
97         try {
98             extendedUri = uriBuilder.build();
99             logger.trace("Building extended URI: {}", extendedUri);
100         } catch (URISyntaxException e) {
101             logger.warn("Exception while building extended URI: {}", e);
102         }
103
104         return extendedUri;
105     }
106
107     private ResponseHandler<Optional<String>> aaiResponseHandler() {
108         return httpResponse -> {
109             final int responseCode = httpResponse.getStatusLine().getStatusCode();
110             logger.info("Status code of operation: {}", responseCode);
111             final HttpEntity responseEntity = httpResponse.getEntity();
112
113             if (HttpUtils.isSuccessfulResponseCode(responseCode)) {
114                 logger.trace("HTTP response successful.");
115                 final String aaiResponse = EntityUtils.toString(responseEntity);
116                 return Optional.of(aaiResponse);
117             } else {
118                 String aaiResponse = responseEntity != null ? EntityUtils.toString(responseEntity) : "";
119                 logger.warn("HTTP response not successful : {}", aaiResponse);
120                 return Optional.of(String.valueOf(responseCode));
121             }
122         };
123     }
124
125     private HttpRequestBase createHttpRequest(URI extendedUri) {
126         return isExtendedUriNotNull(extendedUri) ? new HttpGet(extendedUri) : null;
127     }
128
129     private Boolean isExtendedUriNotNull(URI extendedUri) {
130         return extendedUri != null;
131     }
132
133     private Optional<HttpRequestBase> createRequest(ConsumerDmaapModel consumerDmaapModel) {
134         final URI extendedUri = createAaiExtendedUri(consumerDmaapModel.getPnfName());
135         HttpRequestBase request = createHttpRequest(extendedUri);
136         aaiHeaders.forEach(Objects.requireNonNull(request)::addHeader);
137         Objects.requireNonNull(request).addHeader("Content-Type", "application/json");
138         return Optional.of(request);
139     }
140 }