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