release 1.1.11
[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.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 org.onap.dmaap.mr.client.MRClient;
45 import org.onap.dmaap.mr.client.MRClientFactory;
46 import org.onap.dmaap.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<>();
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 protocalFlag) 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(PostAuthDataObject postAuthDO)
164                         throws HttpException, JSONException {
165         if ((null != postAuthDO.getUsername() && null != postAuthDO.getPassword())) {
166             WebTarget target = null;
167             Response response = null;
168             target = DmaapClientUtil.getTarget(postAuthDO.getPath(), postAuthDO.getUsername(),
169                     postAuthDO.getPassword());
170             response = DmaapClientUtil.postResponsewtCambriaAuth(target, postAuthDO.getAuthKey(),
171                     postAuthDO.getAuthDate(), postAuthDO.getData(), postAuthDO.getContentType());
172             return getResponseDataInJson(response);
173         } else {
174                         throw new HttpException(
175                                         "Authentication Failed: Username/password/AuthKey/AuthDate parameter(s) cannot be null or empty.");
176                 }
177         }
178
179         public String postAuthwithResponse(final String path, final byte[] data, final String contentType,
180                         final String authKey, final String authDate, final String username, final String password,
181                         final String protocolFlag) throws HttpException, JSONException {
182                 String responseData = null;
183                 if ((null != username && null != password)) {
184                         WebTarget target=null;
185                         Response response=null;
186                         target = DmaapClientUtil.getTarget(path, username, password);
187                         response = DmaapClientUtil.postResponsewtCambriaAuth(target, authKey, authDate, data, contentType);
188                         responseData = (String)response.readEntity(String.class);
189                         return responseData;
190
191                 } else {
192                         throw new HttpException(
193                                         "Authentication Failed: Username/password/AuthKey/AuthDate parameter(s) cannot be null or empty.");
194                 }
195         }
196
197         public JSONObject get(final String path, final String username, final String password, final String protocolFlag)
198                         throws HttpException, JSONException {
199                 if (null != username && null != password) {
200
201                          WebTarget target=null;
202                          Response response=null;
203                          
204                         if (ProtocolTypeConstants.AUTH_KEY.getValue().equalsIgnoreCase(protocolFlag)) {
205                                 target = DmaapClientUtil.getTarget(path);
206                                 response = DmaapClientUtil.getResponsewtCambriaAuth(target, username, password);
207                         } else {
208                                 target = DmaapClientUtil.getTarget(path, username, password);
209                                 String encoding = Base64.encodeAsString(username + ":" + password);
210
211                                 response = DmaapClientUtil.getResponsewtBasicAuth(target, encoding);
212
213                         }
214                         return getResponseDataInJson(response);
215                 } else {
216                         throw new HttpException(
217                                         "Authentication Failed: Username/password/AuthKey/Authdate parameter(s) cannot be null or empty.");
218                 }
219         }
220
221         public String getResponse(final String path, final String username, final String password,
222                         final String protocolFlag) throws HttpException, JSONException {
223                 String responseData = null;
224                 if (null != username && null != password) {
225                         WebTarget target=null;
226                         Response response=null;
227                         if (ProtocolTypeConstants.AUTH_KEY.getValue().equalsIgnoreCase(protocolFlag)) {
228                                 target = DmaapClientUtil.getTarget(path);
229                                 response = DmaapClientUtil.getResponsewtCambriaAuth(target, username, password);
230                         } else {
231                                 target = DmaapClientUtil.getTarget(path, username, password);
232                                 String encoding = Base64.encodeAsString(username + ":" + password);
233                                 response = DmaapClientUtil.getResponsewtBasicAuth(target, encoding);
234                         }
235                         MRClientFactory.HTTPHeadersMap = response.getHeaders();
236
237                         String transactionid = response.getHeaderString("transactionid");
238                         if (transactionid != null && !transactionid.equalsIgnoreCase("")) {
239                                 fLog.info("TransactionId : " + transactionid);
240                         }
241
242                         responseData = (String)response.readEntity(String.class);
243                         return responseData;
244                 } else {
245                         throw new HttpException(
246                                         "Authentication Failed: Username/password/AuthKey/Authdate parameter(s) cannot be null or empty.");
247                 }
248         }
249
250         public JSONObject getAuth(final String path, final String authKey, final String authDate, final String username,
251                         final String password, final String protocolFlag) throws HttpException, JSONException {
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                         return getResponseDataInJson(response);
259                 } else {
260                         throw new HttpException(
261                                         "Authentication Failed: Username/password/AuthKey/Authdate parameter(s) cannot be null or empty.");
262                 }
263         }
264
265         public JSONObject getNoAuth(final String path) throws HttpException, JSONException {
266
267                 WebTarget target = null;
268                 Response response = null;
269                 target = DmaapClientUtil.getTarget(path);
270                 response = DmaapClientUtil.getResponsewtNoAuth(target);
271
272                 return getResponseDataInJson(response);
273         }
274
275         public String getAuthResponse(final String path, final String authKey, final String authDate, final String username,
276                         final String password, final String protocolFlag) throws HttpException, JSONException {
277                 String responseData = null;
278                 if (null != username && null != password) {
279                         WebTarget target=null;
280                         Response response=null;
281                         target = DmaapClientUtil.getTarget(path, username, password);
282                         response = DmaapClientUtil.getResponsewtCambriaAuth(target, authKey, authDate);
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 = (String)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                 WebTarget target=null;
303                 Response response=null;
304                 target = DmaapClientUtil.getTarget(path, username, password);
305                 response = DmaapClientUtil.getResponsewtNoAuth(target);
306
307                 MRClientFactory.HTTPHeadersMap = response.getHeaders();
308
309                 String transactionid = response.getHeaderString("transactionid");
310                 if (transactionid != null && !transactionid.equalsIgnoreCase("")) {
311                         fLog.info("TransactionId : " + transactionid);
312                 }
313
314                 responseData = (String)response.readEntity(String.class);
315                 return responseData;
316
317         }
318
319
320         private JSONObject getResponseDataInJson(Response response) throws JSONException {
321                 try {
322                         MRClientFactory.HTTPHeadersMap = response.getHeaders();
323                         
324
325                         // MultivaluedMap<String, Object> headersMap =
326                         // for(String key : headersMap.keySet()) {
327                         String transactionid = response.getHeaderString("transactionid");
328                         if (transactionid != null && !transactionid.equalsIgnoreCase("")) {
329                                 fLog.info("TransactionId : " + transactionid);
330                         }
331
332
333                         if (response.getStatus() == 403) {
334                                 JSONObject jsonObject = null;
335                                 jsonObject = new JSONObject();
336                                 JSONArray jsonArray = new JSONArray();
337                                 jsonArray.put(response.getEntity());
338                                 jsonObject.put("result", jsonArray);
339                                 jsonObject.put("status", response.getStatus());
340                                 return jsonObject;
341                         }
342                         String responseData = (String)response.readEntity(String.class);
343
344                         JSONTokener jsonTokener = new JSONTokener(responseData);
345                         JSONObject jsonObject = null;
346                         final char firstChar = jsonTokener.next();
347                         jsonTokener.back();
348                         if ('[' == firstChar) {
349                                 JSONArray jsonArray = new JSONArray(jsonTokener);
350                                 jsonObject = new JSONObject();
351                                 jsonObject.put("result", jsonArray);
352                                 jsonObject.put("status", response.getStatus());
353                         } else {
354                                 jsonObject = new JSONObject(jsonTokener);
355                                 jsonObject.put("status", response.getStatus());
356                         }
357
358                         return jsonObject;
359                 } catch (JSONException excp) {
360                         fLog.error("DMAAP - Error reading response data.", excp);
361                         return null;
362                 }
363
364         }
365
366         public String getHTTPErrorResponseMessage(String responseString) {
367
368                 String response = null;
369                 int beginIndex = 0;
370                 int endIndex = 0;
371                 if (responseString.contains("<body>")) {
372
373                         beginIndex = responseString.indexOf("body>") + 5;
374                         endIndex = responseString.indexOf("</body");
375                         response = responseString.substring(beginIndex, endIndex);
376                 }
377
378                 return response;
379
380         }
381
382         public String getHTTPErrorResponseCode(String responseString) {
383
384                 String response = null;
385                 int beginIndex = 0;
386                 int endIndex = 0;
387                 if (responseString.contains("<title>")) {
388                         beginIndex = responseString.indexOf("title>") + 6;
389                         endIndex = responseString.indexOf("</title");
390                         response = responseString.substring(beginIndex, endIndex);
391                 }
392
393                 return response;
394         }
395
396 }