[DMAAP-CLIENT] Package upgrades for J
[dmaap/messagerouter/dmaapclient.git] / src / main / java / org / onap / dmaap / mr / client / impl / MRBaseClient.java
1 /*******************************************************************************
2  *  ============LICENSE_START=======================================================
3  *  org.onap.dmaap
4  *  ================================================================================
5  *  Copyright © 2017 AT&T Intellectual Property. All rights reserved.
6  *  ================================================================================
7  *  Modifications Copyright © 2021 Orange.
8  *  ================================================================================
9  *  Licensed under the Apache License, Version 2.0 (the "License");
10  *  you may not use this file except in compliance with the License.
11  *  You may obtain a copy of the License at
12  *        http://www.apache.org/licenses/LICENSE-2.0
13  *
14  *  Unless required by applicable law or agreed to in writing, software
15  *  distributed under the License is distributed on an "AS IS" BASIS,
16  *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17  *  See the License for the specific language governing permissions and
18  *  limitations under the License.
19  *  ============LICENSE_END=========================================================
20  *
21  *  ECOMP is a trademark and service mark of AT&T Intellectual Property.
22  *
23  *******************************************************************************/
24
25 package org.onap.dmaap.mr.client.impl;
26
27 import com.att.nsa.apiClient.http.CacheUse;
28 import com.att.nsa.apiClient.http.HttpClient;
29 import java.net.MalformedURLException;
30 import java.nio.charset.StandardCharsets;
31 import java.util.Collection;
32 import java.util.Set;
33 import java.util.TreeSet;
34 import java.util.concurrent.TimeUnit;
35 import javax.ws.rs.client.WebTarget;
36 import javax.ws.rs.core.Response;
37 import org.apache.commons.codec.binary.Base64;
38 import org.apache.http.HttpException;
39 import org.apache.http.HttpStatus;
40 import org.glassfish.jersey.client.ClientConfig;
41 import org.json.JSONArray;
42 import org.json.JSONException;
43 import org.json.JSONObject;
44 import org.json.JSONTokener;
45 import org.onap.dmaap.mr.client.MRClient;
46 import org.onap.dmaap.mr.client.MRClientFactory;
47 import org.onap.dmaap.mr.client.ProtocolType;
48 import org.slf4j.Logger;
49 import org.slf4j.LoggerFactory;
50
51 public class MRBaseClient extends HttpClient implements MRClient {
52
53     private static final String HEADER_TRANSACTION_ID = "transactionid";
54
55     private static final String JSON_RESULT = "result";
56     private static final String JSON_STATUS = "status";
57
58     private static final String AUTH_FAILED = "Authentication Failed: Username/password/AuthKey/AuthDate parameter(s) cannot be null or empty.";
59     private static final String LOG_TRANSACTION_ID = "TransactionId : {}";
60
61     private ClientConfig clientConfig = null;
62
63     protected MRBaseClient(Collection<String> hosts) throws MalformedURLException {
64         super(ConnectionType.HTTP, hosts, MRConstants.STD_MR_SERVICE_PORT);
65
66         logger = LoggerFactory.getLogger(this.getClass().getName());
67     }
68
69     protected MRBaseClient(Collection<String> hosts, int stdSvcPort) throws MalformedURLException {
70         super(ConnectionType.HTTP, hosts, stdSvcPort);
71
72         logger = LoggerFactory.getLogger(this.getClass().getName());
73     }
74
75     protected MRBaseClient(Collection<String> hosts, String clientSignature) throws MalformedURLException {
76         super(ConnectionType.HTTP, hosts, MRConstants.STD_MR_SERVICE_PORT, clientSignature, CacheUse.NONE, 1, 1L,
77                 TimeUnit.MILLISECONDS, 32, 32, 600000);
78
79         logger = LoggerFactory.getLogger(this.getClass().getName());
80     }
81
82     public ClientConfig getClientConfig1() {
83         return clientConfig;
84     }
85
86     public void setClientConfig(ClientConfig config) {
87         this.clientConfig = config;
88     }
89
90     @Override
91     public void close() {
92         // nothing to close
93     }
94
95     protected Set<String> jsonArrayToSet(JSONArray array) {
96         if (array == null) {
97             return null;
98         }
99         final TreeSet<String> set = new TreeSet<>();
100         for (int i = 0; i < array.length(); i++) {
101             set.add(array.getString(i));
102         }
103         return set;
104     }
105
106     public void logTo(Logger log) {
107         logger = log;
108         replaceLogger(log);
109     }
110
111     protected Logger getLog() {
112         return logger;
113     }
114
115     private Logger logger;
116
117     public JSONObject post(final String path, final byte[] data, final String contentType, final String username,
118                            final String password, final String protocalFlag) throws HttpException, JSONException {
119         if ((null != username && null != password)) {
120             WebTarget target = null;
121             Response response = null;
122             target = DmaapClientUtil.getTarget(clientConfig, path, username, password);
123             Base64 base64 = new Base64();
124             String encoding = base64.encodeAsString((username + ":" + password).getBytes(StandardCharsets.UTF_8));
125
126             response = DmaapClientUtil.postResponsewtBasicAuth(target, encoding, data, contentType);
127
128             return getResponseDataInJson(response);
129         } else {
130             throw new HttpException(AUTH_FAILED);
131         }
132     }
133
134     public JSONObject postNoAuth(final String path, final byte[] data, String contentType)
135             throws HttpException, JSONException {
136         WebTarget target = null;
137         Response response = null;
138         if (contentType == null) {
139             contentType = "text/pain";
140         }
141         target = DmaapClientUtil.getTarget(clientConfig, path);
142
143         response = DmaapClientUtil.postResponsewtNoAuth(target, data, contentType);
144
145         return getResponseDataInJson(response);
146     }
147
148     public String postWithResponse(final String path, final byte[] data, final String contentType,
149                                    final String username, final String password, final String protocolFlag)
150             throws HttpException, JSONException {
151         String responseData = null;
152         if ((null != username && null != password)) {
153             WebTarget target = null;
154             Response response = null;
155             target = DmaapClientUtil.getTarget(clientConfig, path, username, password);
156             Base64 base64 = new Base64();
157             String encoding = base64.encodeAsString((username + ":" + password).getBytes(StandardCharsets.UTF_8));
158
159             response = DmaapClientUtil.postResponsewtBasicAuth(target, encoding, data, contentType);
160
161             responseData = response.readEntity(String.class);
162             return responseData;
163         } else {
164             throw new HttpException(AUTH_FAILED);
165         }
166     }
167
168     public String postNoAuthWithResponse(final String path, final byte[] data, String contentType)
169             throws HttpException, JSONException {
170
171         String responseData = null;
172         WebTarget target = null;
173         Response response = null;
174         if (contentType == null) {
175             contentType = "text/pain";
176         }
177         target = DmaapClientUtil.getTarget(clientConfig, path);
178
179         response = DmaapClientUtil.postResponsewtNoAuth(target, data, contentType);
180         responseData = response.readEntity(String.class);
181         return responseData;
182     }
183
184     public JSONObject postAuth(PostAuthDataObject postAuthDO) throws HttpException, JSONException {
185         if ((null != postAuthDO.getUsername() && null != postAuthDO.getPassword())) {
186             WebTarget target = null;
187             Response response = null;
188             target = DmaapClientUtil.getTarget(clientConfig, postAuthDO.getPath(), postAuthDO.getUsername(),
189                     postAuthDO.getPassword());
190             response = DmaapClientUtil.postResponsewtCambriaAuth(target, postAuthDO.getAuthKey(),
191                     postAuthDO.getAuthDate(), postAuthDO.getData(), postAuthDO.getContentType());
192             return getResponseDataInJson(response);
193         } else {
194             throw new HttpException(AUTH_FAILED);
195         }
196     }
197
198     public String postAuthwithResponse(final String path, final byte[] data, final String contentType,
199                                        final String authKey, final String authDate, final String username, final String password,
200                                        final String protocolFlag) throws HttpException, JSONException {
201         String responseData = null;
202         if ((null != username && null != password)) {
203             WebTarget target = null;
204             Response response = null;
205             target = DmaapClientUtil.getTarget(clientConfig, path, username, password);
206             response = DmaapClientUtil.postResponsewtCambriaAuth(target, authKey, authDate, data, contentType);
207             responseData = response.readEntity(String.class);
208             return responseData;
209
210         } else {
211             throw new HttpException(AUTH_FAILED);
212         }
213     }
214
215     public JSONObject get(final String path, final String username, final String password, final String protocolFlag)
216             throws HttpException, JSONException {
217         if (null != username && null != password) {
218
219             WebTarget target = null;
220             Response response = null;
221
222             if (ProtocolType.AUTH_KEY.getValue().equalsIgnoreCase(protocolFlag)) {
223                 target = DmaapClientUtil.getTarget(clientConfig, path);
224                 response = DmaapClientUtil.getResponsewtCambriaAuth(target, username, password);
225             } else {
226                 target = DmaapClientUtil.getTarget(clientConfig, path, username, password);
227                 Base64 base64 = new Base64();
228                 String encoding = base64.encodeAsString((username + ":" + password).getBytes(StandardCharsets.UTF_8));
229
230                 response = DmaapClientUtil.getResponsewtBasicAuth(target, encoding);
231
232             }
233             return getResponseDataInJson(response);
234         } else {
235             throw new HttpException(AUTH_FAILED);
236         }
237     }
238
239     public String getResponse(final String path, final String username, final String password,
240                               final String protocolFlag) throws HttpException, JSONException {
241         String responseData = null;
242         if (null != username && null != password) {
243             WebTarget target = null;
244             Response response = null;
245             if (ProtocolType.AUTH_KEY.getValue().equalsIgnoreCase(protocolFlag)) {
246                 target = DmaapClientUtil.getTarget(clientConfig, path);
247                 response = DmaapClientUtil.getResponsewtCambriaAuth(target, username, password);
248             } else {
249                 target = DmaapClientUtil.getTarget(clientConfig, path, username, password);
250                 Base64 base64 = new Base64();
251                 String encoding = base64.encodeAsString((username + ":" + password).getBytes(StandardCharsets.UTF_8));
252                 response = DmaapClientUtil.getResponsewtBasicAuth(target, encoding);
253             }
254             MRClientFactory.setHTTPHeadersMap(response.getHeaders());
255
256             String transactionid = response.getHeaderString(HEADER_TRANSACTION_ID);
257             if (transactionid != null && !transactionid.equalsIgnoreCase("")) {
258                 logger.info(LOG_TRANSACTION_ID, transactionid);
259             }
260
261             responseData = response.readEntity(String.class);
262             return responseData;
263         } else {
264             throw new HttpException(AUTH_FAILED);
265         }
266     }
267
268     public JSONObject getAuth(final String path, final String authKey, final String authDate, final String username,
269                               final String password, final String protocolFlag) throws HttpException, JSONException {
270         if (null != username && null != password) {
271             WebTarget target = null;
272             Response response = null;
273             target = DmaapClientUtil.getTarget(clientConfig, path, username, password);
274             response = DmaapClientUtil.getResponsewtCambriaAuth(target, authKey, authDate);
275
276             return getResponseDataInJson(response);
277         } else {
278             throw new HttpException(AUTH_FAILED);
279         }
280     }
281
282     public JSONObject getNoAuth(final String path) throws HttpException, JSONException {
283
284         WebTarget target = null;
285         Response response = null;
286         target = DmaapClientUtil.getTarget(clientConfig, path);
287         response = DmaapClientUtil.getResponsewtNoAuth(target);
288
289         return getResponseDataInJson(response);
290     }
291
292     public String getAuthResponse(final String path, final String authKey, final String authDate, final String username,
293                                   final String password, final String protocolFlag) throws HttpException, JSONException {
294         String responseData = null;
295         if (null != username && null != password) {
296             WebTarget target = null;
297             Response response = null;
298             target = DmaapClientUtil.getTarget(clientConfig, path, username, password);
299             response = DmaapClientUtil.getResponsewtCambriaAuth(target, authKey, authDate);
300
301             MRClientFactory.setHTTPHeadersMap(response.getHeaders());
302
303             String transactionid = response.getHeaderString(HEADER_TRANSACTION_ID);
304             if (transactionid != null && !transactionid.equalsIgnoreCase("")) {
305                 logger.info(LOG_TRANSACTION_ID, transactionid);
306             }
307
308             responseData = response.readEntity(String.class);
309             return responseData;
310         } else {
311             throw new HttpException(AUTH_FAILED);
312         }
313     }
314
315     public String getNoAuthResponse(String path, final String username, final String password,
316                                     final String protocolFlag) throws HttpException, JSONException {
317         String responseData = null;
318         WebTarget target = null;
319         Response response = null;
320         target = DmaapClientUtil.getTarget(clientConfig, path, username, password);
321         response = DmaapClientUtil.getResponsewtNoAuth(target);
322
323         MRClientFactory.setHTTPHeadersMap(response.getHeaders());
324
325         String transactionid = response.getHeaderString(HEADER_TRANSACTION_ID);
326         if (transactionid != null && !transactionid.equalsIgnoreCase("")) {
327             logger.info(LOG_TRANSACTION_ID, transactionid);
328         }
329
330         responseData = response.readEntity(String.class);
331         return responseData;
332
333     }
334
335     private JSONObject getResponseDataInJson(Response response) throws JSONException {
336         try {
337             MRClientFactory.setHTTPHeadersMap(response.getHeaders());
338
339             // MultivaluedMap<String, Object> headersMap =
340             // for(String key : headersMap.keySet()) {
341             String transactionid = response.getHeaderString(HEADER_TRANSACTION_ID);
342             if (transactionid != null && !transactionid.equalsIgnoreCase("")) {
343                 logger.info(LOG_TRANSACTION_ID, transactionid);
344             }
345
346             if (response.getStatus() == HttpStatus.SC_FORBIDDEN) {
347                 JSONObject jsonObject = null;
348                 jsonObject = new JSONObject();
349                 JSONArray jsonArray = new JSONArray();
350                 jsonArray.put(response.getEntity());
351                 jsonObject.put(JSON_RESULT, jsonArray);
352                 jsonObject.put(JSON_STATUS, response.getStatus());
353                 return jsonObject;
354             }
355             String responseData = response.readEntity(String.class);
356
357             JSONTokener jsonTokener = new JSONTokener(responseData);
358             JSONObject jsonObject = null;
359             final char firstChar = jsonTokener.next();
360             jsonTokener.back();
361             if ('[' == firstChar) {
362                 JSONArray jsonArray = new JSONArray(jsonTokener);
363                 jsonObject = new JSONObject();
364                 jsonObject.put(JSON_RESULT, jsonArray);
365                 jsonObject.put(JSON_STATUS, response.getStatus());
366             } else {
367                 jsonObject = new JSONObject(jsonTokener);
368                 jsonObject.put(JSON_STATUS, response.getStatus());
369             }
370
371             return jsonObject;
372         } catch (JSONException excp) {
373             logger.error("DMAAP - Error reading response data.", excp);
374             return null;
375         }
376
377     }
378
379     public String getHTTPErrorResponseMessage(String responseString) {
380
381         String response = null;
382         int beginIndex = 0;
383         int endIndex = 0;
384         if (responseString.contains("<body>")) {
385
386             beginIndex = responseString.indexOf("body>") + 5;
387             endIndex = responseString.indexOf("</body");
388             response = responseString.substring(beginIndex, endIndex);
389         }
390
391         return response;
392
393     }
394
395     public String getHTTPErrorResponseCode(String responseString) {
396
397         String response = null;
398         int beginIndex = 0;
399         int endIndex = 0;
400         if (responseString.contains("<title>")) {
401             beginIndex = responseString.indexOf("title>") + 6;
402             endIndex = responseString.indexOf("</title");
403             response = responseString.substring(beginIndex, endIndex);
404         }
405
406         return response;
407     }
408
409 }