Changes to the DMaap Client
[dmaap/messagerouter/dmaapclient.git] / src / main / java / com / att / nsa / 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 com.att.nsa.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.Client;
31 import javax.ws.rs.client.ClientBuilder;
32 import javax.ws.rs.client.Entity;
33 import javax.ws.rs.client.WebTarget;
34 import javax.ws.rs.core.Response;
35
36 import org.apache.http.HttpException;
37 import org.glassfish.jersey.client.authentication.HttpAuthenticationFeature;
38 import org.glassfish.jersey.internal.util.Base64;
39 import org.json.JSONArray;
40 import org.json.JSONException;
41 import org.json.JSONObject;
42 import org.json.JSONTokener;
43 import org.slf4j.Logger;
44 import org.slf4j.LoggerFactory;
45
46 import com.att.nsa.apiClient.http.CacheUse;
47 import com.att.nsa.apiClient.http.HttpClient;
48 import com.att.nsa.mr.client.MRClient;
49 import com.att.nsa.mr.client.MRClientFactory;
50 import com.att.nsa.mr.test.clients.ProtocolTypeConstants;
51 //import com.fasterxml.jackson.core.JsonProcessingException;
52
53 public class MRBaseClient extends HttpClient implements MRClient {
54
55         private static final String MR_AUTH_CONSTANT = "X-CambriaAuth";
56         private static final String MR_DATE_CONSTANT = "X-CambriaDate";
57
58         protected MRBaseClient(Collection<String> hosts) throws MalformedURLException {
59                 super(ConnectionType.HTTP, hosts, MRConstants.kStdMRServicePort);
60
61                 fLog = LoggerFactory.getLogger(this.getClass().getName());
62         }
63
64         protected MRBaseClient(Collection<String> hosts, int stdSvcPort) throws MalformedURLException {
65                 super(ConnectionType.HTTP, hosts, stdSvcPort);
66
67                 fLog = LoggerFactory.getLogger(this.getClass().getName());
68         }
69
70         protected MRBaseClient(Collection<String> hosts, String clientSignature) throws MalformedURLException {
71                 super(ConnectionType.HTTP, hosts, MRConstants.kStdMRServicePort, clientSignature, CacheUse.NONE, 1, 1L,
72                                 TimeUnit.MILLISECONDS, 32, 32, 600000);
73
74                 fLog = LoggerFactory.getLogger(this.getClass().getName());
75         }
76
77         @Override
78         public void close() {
79         }
80
81         protected Set<String> jsonArrayToSet(JSONArray a) {
82                 if (a == null)
83                         return null;
84
85                 final TreeSet<String> set = new TreeSet<String>();
86                 for (int i = 0; i < a.length(); i++) {
87                         set.add(a.getString(i));
88                 }
89                 return set;
90         }
91
92         public void logTo(Logger log) {
93                 fLog = log;
94                 replaceLogger(log);
95         }
96
97         protected Logger getLog() {
98                 return fLog;
99         }
100
101         private Logger fLog;
102
103         public JSONObject post(final String path, final byte[] data, final String contentType, final String username,
104                         final String password, final String protocolFlag) throws HttpException, JSONException {
105                 if ((null != username && null != password)) {
106                         WebTarget target = null;
107
108                         Response response = null;
109
110                         target = getTarget(path, username, password);
111                         String encoding = Base64.encodeAsString(username + ":" + password);
112
113                         response = target.request().header("Authorization", "Basic " + encoding)
114                                         .post(Entity.entity(data, contentType));
115
116                         return getResponseDataInJson(response);
117                 } else {
118                         throw new HttpException(
119                                         "Authentication Failed: Username/password/AuthKey/AuthDate parameter(s) cannot be null or empty.");
120                 }
121         }
122
123         public String postWithResponse(final String path, final byte[] data, final String contentType,
124                         final String username, final String password, final String protocolFlag)
125                         throws HttpException, JSONException {
126                 String responseData = null;
127                 if ((null != username && null != password)) {
128                         WebTarget target = null;
129
130                         Response response = null;
131
132                         target = getTarget(path, username, password);
133                         String encoding = Base64.encodeAsString(username + ":" + password);
134
135                         response = target.request().header("Authorization", "Basic " + encoding)
136                                         .post(Entity.entity(data, contentType));
137
138                         responseData = response.readEntity(String.class);
139                         return responseData;
140                 } else {
141                         throw new HttpException(
142                                         "Authentication Failed: Username/password/AuthKey/AuthDate parameter(s) cannot be null or empty.");
143                 }
144         }
145
146         public JSONObject postAuth(final String path, final byte[] data, final String contentType, final String authKey,
147                         final String authDate, final String username, final String password, final String protocolFlag)
148                         throws HttpException, JSONException {
149                 if ((null != username && null != password)) {
150                         WebTarget target = null;
151
152                         Response response = null;
153                         target = getTarget(path, username, password);
154                         response = target.request().header(MR_AUTH_CONSTANT, authKey).header(MR_DATE_CONSTANT, authDate)
155                                         .post(Entity.entity(data, contentType));
156
157                         return getResponseDataInJson(response);
158                 } else {
159                         throw new HttpException(
160                                         "Authentication Failed: Username/password/AuthKey/AuthDate parameter(s) cannot be null or empty.");
161                 }
162         }
163
164         public String postAuthwithResponse(final String path, final byte[] data, final String contentType,
165                         final String authKey, final String authDate, final String username, final String password,
166                         final String protocolFlag) throws HttpException, JSONException {
167                 String responseData = null;
168                 if ((null != username && null != password)) {
169                         WebTarget target = null;
170
171                         Response response = null;
172                         target = getTarget(path, username, password);
173                         response = target.request().header(MR_AUTH_CONSTANT, authKey).header(MR_DATE_CONSTANT, authDate)
174                                         .post(Entity.entity(data, contentType));
175                         responseData = response.readEntity(String.class);
176                         return responseData;
177
178                 } else {
179                         throw new HttpException(
180                                         "Authentication Failed: Username/password/AuthKey/AuthDate parameter(s) cannot be null or empty.");
181                 }
182         }
183
184         public JSONObject get(final String path, final String username, final String password, final String protocolFlag)
185                         throws HttpException, JSONException {
186                 if (null != username && null != password) {
187
188                         WebTarget target = null;
189
190                         Response response = null;
191                         if (ProtocolTypeConstants.AUTH_KEY.getValue().equalsIgnoreCase(protocolFlag)) {
192                                 target = getTarget(path);
193                                 response = target.request().header(MR_AUTH_CONSTANT, username).header(MR_DATE_CONSTANT, password).get();
194                         } else {
195                                 target = getTarget(path, username, password);
196                                 String encoding = Base64.encodeAsString(username + ":" + password);
197
198                                 response = target.request().header("Authorization", "Basic " + encoding).get();
199
200                         }
201                         return getResponseDataInJson(response);
202                 } else {
203                         throw new HttpException(
204                                         "Authentication Failed: Username/password/AuthKey/Authdate parameter(s) cannot be null or empty.");
205                 }
206         }
207
208         public String getResponse(final String path, final String username, final String password,
209                         final String protocolFlag) throws HttpException, JSONException {
210                 String responseData = null;
211                 if (null != username && null != password) {
212
213                         WebTarget target = null;
214
215                         Response response = null;
216                         if (ProtocolTypeConstants.AUTH_KEY.getValue().equalsIgnoreCase(protocolFlag)) {
217                                 target = getTarget(path);
218                                 response = target.request().header(MR_AUTH_CONSTANT, username).header(MR_DATE_CONSTANT, password).get();
219                         } else {
220                                 target = getTarget(path, username, password);
221                                 String encoding = Base64.encodeAsString(username + ":" + password);
222                                 response = target.request().header("Authorization", "Basic " + encoding).get();
223                         }
224                         MRClientFactory.HTTPHeadersMap = response.getHeaders();
225
226                         String transactionid = response.getHeaderString("transactionid");
227                         if (transactionid != null && !transactionid.equalsIgnoreCase("")) {
228                                 fLog.info("TransactionId : " + transactionid);
229                         }
230
231                         responseData = response.readEntity(String.class);
232                         return responseData;
233                 } else {
234                         throw new HttpException(
235                                         "Authentication Failed: Username/password/AuthKey/Authdate parameter(s) cannot be null or empty.");
236                 }
237         }
238
239         public JSONObject getAuth(final String path, final String authKey, final String authDate, final String username,
240                         final String password, final String protocolFlag) throws HttpException, JSONException {
241                 if (null != username && null != password) {
242
243                         WebTarget target = null;
244
245                         Response response = null;
246                         target = getTarget(path, username, password);
247                         response = target.request().header(MR_AUTH_CONSTANT, authKey).header(MR_DATE_CONSTANT, authDate).get();
248
249                         return getResponseDataInJson(response);
250                 } else {
251                         throw new HttpException(
252                                         "Authentication Failed: Username/password/AuthKey/Authdate parameter(s) cannot be null or empty.");
253                 }
254         }
255
256         public JSONObject getNoAuth(final String path, final String username, final String password,
257                         final String protocolFlag) throws HttpException, JSONException {
258                 if (null != username && null != password) {
259
260                         WebTarget target = null;
261
262                         Response response = null;
263                         target = getTarget(path, username, password);
264                         response = target.request().get();
265
266                         return getResponseDataInJson(response);
267                 } else {
268                         throw new HttpException(
269                                         "Authentication Failed: Username/password/AuthKey/Authdate parameter(s) cannot be null or empty.");
270                 }
271         }
272
273         public String getAuthResponse(final String path, final String authKey, final String authDate, final String username,
274                         final String password, final String protocolFlag) throws HttpException, JSONException {
275                 String responseData = null;
276                 if (null != username && null != password) {
277
278                         WebTarget target = null;
279
280                         Response response = null;
281                         target = getTarget(path, username, password);
282                         response = target.request().header(MR_AUTH_CONSTANT, authKey).header(MR_DATE_CONSTANT, authDate).get();
283
284                         MRClientFactory.HTTPHeadersMap = response.getHeaders();
285
286                         String transactionid = response.getHeaderString("transactionid");
287                         if (transactionid != null && !transactionid.equalsIgnoreCase("")) {
288                                 fLog.info("TransactionId : " + transactionid);
289                         }
290
291                         responseData = response.readEntity(String.class);
292                         return responseData;
293                 } else {
294                         throw new HttpException(
295                                         "Authentication Failed: Username/password/AuthKey/Authdate parameter(s) cannot be null or empty.");
296                 }
297         }
298
299         public String getNoAuthResponse(String path, final String username, final String password,
300                         final String protocolFlag) throws HttpException, JSONException {
301                 String responseData = null;
302
303                 WebTarget target = null;
304
305                 Response response = null;
306                 target = getTarget(path, username, password);
307                 response = target.request().get();
308
309                 MRClientFactory.HTTPHeadersMap = response.getHeaders();
310
311                 String transactionid = response.getHeaderString("transactionid");
312                 if (transactionid != null && !transactionid.equalsIgnoreCase("")) {
313                         fLog.info("TransactionId : " + transactionid);
314                 }
315
316                 responseData = response.readEntity(String.class);
317                 return responseData;
318
319         }
320
321         private WebTarget getTarget(final String path, final String username, final String password) {
322
323                 Client client = ClientBuilder.newClient();
324
325                 // Using UNIVERSAL as it supports both BASIC and DIGEST authentication
326                 // types.
327                 HttpAuthenticationFeature feature = HttpAuthenticationFeature.universal(username, password);
328                 client.register(feature);
329
330                 return client.target(path);
331         }
332
333         private WebTarget getTarget(final String path) {
334
335                 Client client = ClientBuilder.newClient();
336                 return client.target(path);
337         }
338
339         private JSONObject getResponseDataInJson(Response response) throws JSONException {
340                 try {
341                         MRClientFactory.HTTPHeadersMap = response.getHeaders();
342                         // fLog.info("DMAAP response status: " + response.getStatus());
343
344                         // MultivaluedMap<String, Object> headersMap =
345                         // response.getHeaders();
346                         // for(String key : headersMap.keySet()) {
347                         String transactionid = response.getHeaderString("transactionid");
348                         if (transactionid != null && !transactionid.equalsIgnoreCase("")) {
349                                 fLog.info("TransactionId : " + transactionid);
350                         }
351
352                         /*
353                          * final String responseData = response.readEntity(String.class);
354                          * JSONTokener jsonTokener = new JSONTokener(responseData);
355                          * JSONObject jsonObject = null; final char firstChar =
356                          * jsonTokener.next(); jsonTokener.back(); if ('[' == firstChar) {
357                          * JSONArray jsonArray = new JSONArray(jsonTokener); jsonObject =
358                          * new JSONObject(); jsonObject.put("result", jsonArray); } else {
359                          * jsonObject = new JSONObject(jsonTokener); }
360                          * 
361                          * return jsonObject;
362                          */
363
364                         if (response.getStatus() == 403) {
365                                 JSONObject jsonObject = null;
366                                 jsonObject = new JSONObject();
367                                 JSONArray jsonArray = new JSONArray();
368                                 jsonArray.put(response.getEntity());
369                                 jsonObject.put("result", jsonArray);
370                                 jsonObject.put("status", response.getStatus());
371                                 return jsonObject;
372                         }
373                         String responseData = response.readEntity(String.class);
374
375                         JSONTokener jsonTokener = new JSONTokener(responseData);
376                         JSONObject jsonObject = null;
377                         final char firstChar = jsonTokener.next();
378                         jsonTokener.back();
379                         if ('[' == firstChar) {
380                                 JSONArray jsonArray = new JSONArray(jsonTokener);
381                                 jsonObject = new JSONObject();
382                                 jsonObject.put("result", jsonArray);
383                                 jsonObject.put("status", response.getStatus());
384                         } else {
385                                 jsonObject = new JSONObject(jsonTokener);
386                                 jsonObject.put("status", response.getStatus());
387                         }
388
389                         return jsonObject;
390                 } catch (JSONException excp) {
391                         fLog.error("DMAAP - Error reading response data.", excp);
392                         return null;
393                 }
394
395         }
396
397         public String getHTTPErrorResponseMessage(String responseString) {
398
399                 String response = null;
400                 int beginIndex = 0;
401                 int endIndex = 0;
402                 if (responseString.contains("<body>")) {
403
404                         beginIndex = responseString.indexOf("body>") + 5;
405                         endIndex = responseString.indexOf("</body");
406                         response = responseString.substring(beginIndex, endIndex);
407                 }
408
409                 return response;
410
411         }
412
413         public String getHTTPErrorResponseCode(String responseString) {
414
415                 String response = null;
416                 int beginIndex = 0;
417                 int endIndex = 0;
418                 if (responseString.contains("<title>")) {
419                         beginIndex = responseString.indexOf("title>") + 6;
420                         endIndex = responseString.indexOf("</title");
421                         response = responseString.substring(beginIndex, endIndex);
422                 }
423
424                 return response;
425         }
426
427 }