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