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