Sonar majior issues
[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(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) throws HttpException, JSONException {
265
266                 WebTarget target = null;
267                 Response response = null;
268                 target = DmaapClientUtil.getTarget(path);
269                 response = DmaapClientUtil.getResponsewtNoAuth(target);
270
271                 return getResponseDataInJson(response);
272         }
273
274         public String getAuthResponse(final String path, final String authKey, final String authDate, final String username,
275                         final String password, final String protocolFlag) throws HttpException, JSONException {
276                 String responseData = null;
277                 if (null != username && null != password) {
278                         WebTarget target=null;
279                         Response response=null;
280                         target = DmaapClientUtil.getTarget(path, username, password);
281                         response = DmaapClientUtil.getResponsewtCambriaAuth(target, authKey, authDate);
282
283                         MRClientFactory.HTTPHeadersMap = response.getHeaders();
284
285                         String transactionid = response.getHeaderString("transactionid");
286                         if (transactionid != null && !transactionid.equalsIgnoreCase("")) {
287                                 fLog.info("TransactionId : " + transactionid);
288                         }
289
290                         responseData = (String)response.readEntity(String.class);
291                         return responseData;
292                 } else {
293                         throw new HttpException(
294                                         "Authentication Failed: Username/password/AuthKey/Authdate parameter(s) cannot be null or empty.");
295                 }
296         }
297
298         public String getNoAuthResponse(String path, final String username, final String password,
299                         final String protocolFlag) throws HttpException, JSONException {
300                 String responseData = null;
301                 WebTarget target=null;
302                 Response response=null;
303                 target = DmaapClientUtil.getTarget(path, username, password);
304                 response = DmaapClientUtil.getResponsewtNoAuth(target);
305
306                 MRClientFactory.HTTPHeadersMap = response.getHeaders();
307
308                 String transactionid = response.getHeaderString("transactionid");
309                 if (transactionid != null && !transactionid.equalsIgnoreCase("")) {
310                         fLog.info("TransactionId : " + transactionid);
311                 }
312
313                 responseData = (String)response.readEntity(String.class);
314                 return responseData;
315
316         }
317
318
319         private JSONObject getResponseDataInJson(Response response) throws JSONException {
320                 try {
321                         MRClientFactory.HTTPHeadersMap = response.getHeaders();
322                         
323
324                         // MultivaluedMap<String, Object> headersMap =
325                         // for(String key : headersMap.keySet()) {
326                         String transactionid = response.getHeaderString("transactionid");
327                         if (transactionid != null && !transactionid.equalsIgnoreCase("")) {
328                                 fLog.info("TransactionId : " + transactionid);
329                         }
330
331
332                         if (response.getStatus() == 403) {
333                                 JSONObject jsonObject = null;
334                                 jsonObject = new JSONObject();
335                                 JSONArray jsonArray = new JSONArray();
336                                 jsonArray.put(response.getEntity());
337                                 jsonObject.put("result", jsonArray);
338                                 jsonObject.put("status", response.getStatus());
339                                 return jsonObject;
340                         }
341                         String responseData = (String)response.readEntity(String.class);
342
343                         JSONTokener jsonTokener = new JSONTokener(responseData);
344                         JSONObject jsonObject = null;
345                         final char firstChar = jsonTokener.next();
346                         jsonTokener.back();
347                         if ('[' == firstChar) {
348                                 JSONArray jsonArray = new JSONArray(jsonTokener);
349                                 jsonObject = new JSONObject();
350                                 jsonObject.put("result", jsonArray);
351                                 jsonObject.put("status", response.getStatus());
352                         } else {
353                                 jsonObject = new JSONObject(jsonTokener);
354                                 jsonObject.put("status", response.getStatus());
355                         }
356
357                         return jsonObject;
358                 } catch (JSONException excp) {
359                         fLog.error("DMAAP - Error reading response data.", excp);
360                         return null;
361                 }
362
363         }
364
365         public String getHTTPErrorResponseMessage(String responseString) {
366
367                 String response = null;
368                 int beginIndex = 0;
369                 int endIndex = 0;
370                 if (responseString.contains("<body>")) {
371
372                         beginIndex = responseString.indexOf("body>") + 5;
373                         endIndex = responseString.indexOf("</body");
374                         response = responseString.substring(beginIndex, endIndex);
375                 }
376
377                 return response;
378
379         }
380
381         public String getHTTPErrorResponseCode(String responseString) {
382
383                 String response = null;
384                 int beginIndex = 0;
385                 int endIndex = 0;
386                 if (responseString.contains("<title>")) {
387                         beginIndex = responseString.indexOf("title>") + 6;
388                         endIndex = responseString.indexOf("</title");
389                         response = responseString.substring(beginIndex, endIndex);
390                 }
391
392                 return response;
393         }
394
395 }