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