9522c904c5a0bf6d06065f90a9a8fc4d459de807
[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.util.Collection;
31 import java.util.Set;
32 import java.util.TreeSet;
33 import java.util.concurrent.TimeUnit;
34 import javax.ws.rs.client.WebTarget;
35 import javax.ws.rs.core.Response;
36
37 import org.apache.http.HttpException;
38 import org.apache.http.HttpStatus;
39 import org.glassfish.jersey.client.ClientConfig;
40 import org.glassfish.jersey.internal.util.Base64;
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             String encoding = Base64.encodeAsString(username + ":" + password);
124
125             response = DmaapClientUtil.postResponsewtBasicAuth(target, encoding, data, contentType);
126
127             return getResponseDataInJson(response);
128         } else {
129             throw new HttpException(AUTH_FAILED);
130         }
131     }
132
133     public JSONObject postNoAuth(final String path, final byte[] data, String contentType)
134             throws HttpException, JSONException {
135         WebTarget target = null;
136         Response response = null;
137         if (contentType == null) {
138             contentType = "text/pain";
139         }
140         target = DmaapClientUtil.getTarget(clientConfig, path);
141
142         response = DmaapClientUtil.postResponsewtNoAuth(target, data, contentType);
143
144         return getResponseDataInJson(response);
145     }
146
147     public String postWithResponse(final String path, final byte[] data, final String contentType,
148                                    final String username, final String password, final String protocolFlag)
149             throws HttpException, JSONException {
150         String responseData = null;
151         if ((null != username && null != password)) {
152             WebTarget target = null;
153             Response response = null;
154             target = DmaapClientUtil.getTarget(clientConfig, path, username, password);
155             String encoding = Base64.encodeAsString(username + ":" + password);
156
157             response = DmaapClientUtil.postResponsewtBasicAuth(target, encoding, data, contentType);
158
159             responseData = response.readEntity(String.class);
160             return responseData;
161         } else {
162             throw new HttpException(AUTH_FAILED);
163         }
164     }
165
166     public String postNoAuthWithResponse(final String path, final byte[] data, String contentType)
167             throws HttpException, JSONException {
168
169         String responseData = null;
170         WebTarget target = null;
171         Response response = null;
172         if (contentType == null) {
173             contentType = "text/pain";
174         }
175         target = DmaapClientUtil.getTarget(clientConfig, path);
176
177         response = DmaapClientUtil.postResponsewtNoAuth(target, data, contentType);
178         responseData = response.readEntity(String.class);
179         return responseData;
180     }
181
182     public JSONObject postAuth(PostAuthDataObject postAuthDO) throws HttpException, JSONException {
183         if ((null != postAuthDO.getUsername() && null != postAuthDO.getPassword())) {
184             WebTarget target = null;
185             Response response = null;
186             target = DmaapClientUtil.getTarget(clientConfig, postAuthDO.getPath(), postAuthDO.getUsername(),
187                     postAuthDO.getPassword());
188             response = DmaapClientUtil.postResponsewtCambriaAuth(target, postAuthDO.getAuthKey(),
189                     postAuthDO.getAuthDate(), postAuthDO.getData(), postAuthDO.getContentType());
190             return getResponseDataInJson(response);
191         } else {
192             throw new HttpException(AUTH_FAILED);
193         }
194     }
195
196     public String postAuthwithResponse(final String path, final byte[] data, final String contentType,
197                                        final String authKey, final String authDate, final String username, final String password,
198                                        final String protocolFlag) throws HttpException, JSONException {
199         String responseData = null;
200         if ((null != username && null != password)) {
201             WebTarget target = null;
202             Response response = null;
203             target = DmaapClientUtil.getTarget(clientConfig, path, username, password);
204             response = DmaapClientUtil.postResponsewtCambriaAuth(target, authKey, authDate, data, contentType);
205             responseData = response.readEntity(String.class);
206             return responseData;
207
208         } else {
209             throw new HttpException(AUTH_FAILED);
210         }
211     }
212
213     public JSONObject get(final String path, final String username, final String password, final String protocolFlag)
214             throws HttpException, JSONException {
215         if (null != username && null != password) {
216
217             WebTarget target = null;
218             Response response = null;
219
220             if (ProtocolType.AUTH_KEY.getValue().equalsIgnoreCase(protocolFlag)) {
221                 target = DmaapClientUtil.getTarget(clientConfig, path);
222                 response = DmaapClientUtil.getResponsewtCambriaAuth(target, username, password);
223             } else {
224                 target = DmaapClientUtil.getTarget(clientConfig, path, username, password);
225                 String encoding = Base64.encodeAsString(username + ":" + password);
226
227                 response = DmaapClientUtil.getResponsewtBasicAuth(target, encoding);
228
229             }
230             return getResponseDataInJson(response);
231         } else {
232             throw new HttpException(AUTH_FAILED);
233         }
234     }
235
236     public String getResponse(final String path, final String username, final String password,
237                               final String protocolFlag) throws HttpException, JSONException {
238         String responseData = null;
239         if (null != username && null != password) {
240             WebTarget target = null;
241             Response response = null;
242             if (ProtocolType.AUTH_KEY.getValue().equalsIgnoreCase(protocolFlag)) {
243                 target = DmaapClientUtil.getTarget(clientConfig, path);
244                 response = DmaapClientUtil.getResponsewtCambriaAuth(target, username, password);
245             } else {
246                 target = DmaapClientUtil.getTarget(clientConfig, path, username, password);
247                 String encoding = Base64.encodeAsString(username + ":" + password);
248                 response = DmaapClientUtil.getResponsewtBasicAuth(target, encoding);
249             }
250             MRClientFactory.setHTTPHeadersMap(response.getHeaders());
251
252             String transactionid = response.getHeaderString(HEADER_TRANSACTION_ID);
253             if (transactionid != null && !transactionid.equalsIgnoreCase("")) {
254                 logger.info(LOG_TRANSACTION_ID, transactionid);
255             }
256
257             responseData = response.readEntity(String.class);
258             return responseData;
259         } else {
260             throw new HttpException(AUTH_FAILED);
261         }
262     }
263
264     public JSONObject getAuth(final String path, final String authKey, final String authDate, final String username,
265                               final String password, final String protocolFlag) throws HttpException, JSONException {
266         if (null != username && null != password) {
267             WebTarget target = null;
268             Response response = null;
269             target = DmaapClientUtil.getTarget(clientConfig, path, username, password);
270             response = DmaapClientUtil.getResponsewtCambriaAuth(target, authKey, authDate);
271
272             return getResponseDataInJson(response);
273         } else {
274             throw new HttpException(AUTH_FAILED);
275         }
276     }
277
278     public JSONObject getNoAuth(final String path) throws HttpException, JSONException {
279
280         WebTarget target = null;
281         Response response = null;
282         target = DmaapClientUtil.getTarget(clientConfig, path);
283         response = DmaapClientUtil.getResponsewtNoAuth(target);
284
285         return getResponseDataInJson(response);
286     }
287
288     public String getAuthResponse(final String path, final String authKey, final String authDate, final String username,
289                                   final String password, final String protocolFlag) throws HttpException, JSONException {
290         String responseData = null;
291         if (null != username && null != password) {
292             WebTarget target = null;
293             Response response = null;
294             target = DmaapClientUtil.getTarget(clientConfig, path, username, password);
295             response = DmaapClientUtil.getResponsewtCambriaAuth(target, authKey, authDate);
296
297             MRClientFactory.setHTTPHeadersMap(response.getHeaders());
298
299             String transactionid = response.getHeaderString(HEADER_TRANSACTION_ID);
300             if (transactionid != null && !transactionid.equalsIgnoreCase("")) {
301                 logger.info(LOG_TRANSACTION_ID, transactionid);
302             }
303
304             responseData = response.readEntity(String.class);
305             return responseData;
306         } else {
307             throw new HttpException(AUTH_FAILED);
308         }
309     }
310
311     public String getNoAuthResponse(String path, final String username, final String password,
312                                     final String protocolFlag) throws HttpException, JSONException {
313         String responseData = null;
314         WebTarget target = null;
315         Response response = null;
316         target = DmaapClientUtil.getTarget(clientConfig, path, username, password);
317         response = DmaapClientUtil.getResponsewtNoAuth(target);
318
319         MRClientFactory.setHTTPHeadersMap(response.getHeaders());
320
321         String transactionid = response.getHeaderString(HEADER_TRANSACTION_ID);
322         if (transactionid != null && !transactionid.equalsIgnoreCase("")) {
323             logger.info(LOG_TRANSACTION_ID, transactionid);
324         }
325
326         responseData = response.readEntity(String.class);
327         return responseData;
328
329     }
330
331     private JSONObject getResponseDataInJson(Response response) throws JSONException {
332         try {
333             MRClientFactory.setHTTPHeadersMap(response.getHeaders());
334
335             // MultivaluedMap<String, Object> headersMap =
336             // for(String key : headersMap.keySet()) {
337             String transactionid = response.getHeaderString(HEADER_TRANSACTION_ID);
338             if (transactionid != null && !transactionid.equalsIgnoreCase("")) {
339                 logger.info(LOG_TRANSACTION_ID, transactionid);
340             }
341
342             if (response.getStatus() == HttpStatus.SC_FORBIDDEN) {
343                 JSONObject jsonObject = null;
344                 jsonObject = new JSONObject();
345                 JSONArray jsonArray = new JSONArray();
346                 jsonArray.put(response.getEntity());
347                 jsonObject.put(JSON_RESULT, jsonArray);
348                 jsonObject.put(JSON_STATUS, response.getStatus());
349                 return jsonObject;
350             }
351             String responseData = response.readEntity(String.class);
352
353             JSONTokener jsonTokener = new JSONTokener(responseData);
354             JSONObject jsonObject = null;
355             final char firstChar = jsonTokener.next();
356             jsonTokener.back();
357             if ('[' == firstChar) {
358                 JSONArray jsonArray = new JSONArray(jsonTokener);
359                 jsonObject = new JSONObject();
360                 jsonObject.put(JSON_RESULT, jsonArray);
361                 jsonObject.put(JSON_STATUS, response.getStatus());
362             } else {
363                 jsonObject = new JSONObject(jsonTokener);
364                 jsonObject.put(JSON_STATUS, response.getStatus());
365             }
366
367             return jsonObject;
368         } catch (JSONException excp) {
369             logger.error("DMAAP - Error reading response data.", excp);
370             return null;
371         }
372
373     }
374
375     public String getHTTPErrorResponseMessage(String responseString) {
376
377         String response = null;
378         int beginIndex = 0;
379         int endIndex = 0;
380         if (responseString.contains("<body>")) {
381
382             beginIndex = responseString.indexOf("body>") + 5;
383             endIndex = responseString.indexOf("</body");
384             response = responseString.substring(beginIndex, endIndex);
385         }
386
387         return response;
388
389     }
390
391     public String getHTTPErrorResponseCode(String responseString) {
392
393         String response = null;
394         int beginIndex = 0;
395         int endIndex = 0;
396         if (responseString.contains("<title>")) {
397             beginIndex = responseString.indexOf("title>") + 6;
398             endIndex = responseString.indexOf("</title");
399             response = responseString.substring(beginIndex, endIndex);
400         }
401
402         return response;
403     }
404
405 }