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