012e95e78306a7bef4cb886827345910845f55ca
[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                 fLog = LoggerFactory.getLogger ( this.getClass().getName () );
64         }
65
66         protected MRBaseClient ( Collection<String> hosts, int stdSvcPort ) throws MalformedURLException {
67                 super ( ConnectionType.HTTP,hosts, stdSvcPort);
68
69                 fLog = LoggerFactory.getLogger ( this.getClass().getName () );
70         }
71
72         protected MRBaseClient ( Collection<String> hosts, String clientSignature ) throws MalformedURLException
73         {
74                 super(ConnectionType.HTTP, hosts, MRConstants.kStdMRServicePort, clientSignature, CacheUse.NONE, 1, 1L, TimeUnit.MILLISECONDS, 32, 32, 600000);
75
76                 fLog = LoggerFactory.getLogger ( this.getClass().getName () );
77         }
78
79
80         @Override
81         public void close ()
82         {
83         }
84
85         protected Set<String> jsonArrayToSet ( JSONArray a )
86         {
87                 if ( a == null ) return null;
88
89                 final TreeSet<String> set = new TreeSet<String> ();
90                 for ( int i=0; i<a.length (); i++ )
91                 {
92                         set.add ( a.getString ( i ));
93                 }
94                 return set;
95         }
96
97         public void logTo ( Logger log )
98         {
99                 fLog = log;
100                 replaceLogger ( log );
101         }
102
103         protected Logger getLog ()
104         {
105                 return fLog;
106         }
107
108         private Logger fLog;
109         
110         public JSONObject post(final String path, final byte[] data, final String contentType, final String username, final String password, final String protocolFlag) throws HttpException, JSONException{
111                 if ((null != username && null != password)) {
112                         WebTarget target = null;
113
114                         Response response = null;
115                         
116                         target = getTarget(path, username, password);
117                         String encoding = Base64.encodeAsString(username+":"+password);
118                         
119                         
120                         response = target.request().header("Authorization", "Basic " + encoding).post(Entity.entity(data, contentType));
121                         
122                         return getResponseDataInJson(response);
123                 } else {
124                         throw new HttpException("Authentication Failed: Username/password/AuthKey/AuthDate parameter(s) cannot be null or empty.");
125                 }
126         }
127         public String postWithResponse(final String path, final byte[] data, final String contentType, final String username, final String password, final String protocolFlag) throws HttpException, JSONException{
128                 String responseData = null;
129                 if ((null != username && null != password)) {
130                         WebTarget target = null;
131
132                         Response response = null;
133                         
134                         target = getTarget(path, username, password);
135                         String encoding = Base64.encodeAsString(username+":"+password);
136                         
137                         
138                         response = target.request().header("Authorization", "Basic " + encoding).post(Entity.entity(data, contentType));
139                         
140                         responseData = response.readEntity(String.class);
141                         return responseData;
142                 } else {
143                         throw new HttpException("Authentication Failed: Username/password/AuthKey/AuthDate parameter(s) cannot be null or empty.");
144                 }
145         }
146         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{
147                 if ((null != username && null != password)) {
148                         WebTarget target = null;
149
150                         Response response = null;
151                                 target= getTarget(path,username, password);
152                                 response = target.request()
153                                                 .header(MR_AUTH_CONSTANT, authKey)
154                                                 .header(MR_DATE_CONSTANT, authDate)
155                                                 .post(Entity.entity(data, contentType));
156                                 
157                         return getResponseDataInJson(response);
158                 } else {
159                         throw new HttpException("Authentication Failed: Username/password/AuthKey/AuthDate parameter(s) cannot be null or empty.");
160                 }
161         }
162         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{
163                 String responseData = null;
164                 if ((null != username && null != password)) {
165                         WebTarget target = null;
166
167                         Response response = null;
168                                 target= getTarget(path,username, password);
169                                 response = target.request()
170                                                 .header(MR_AUTH_CONSTANT, authKey)
171                                                 .header(MR_DATE_CONSTANT, authDate)
172                                                 .post(Entity.entity(data, contentType));
173                                 responseData = response.readEntity(String.class);
174                                 return responseData;
175                         
176                 } else {
177                         throw new HttpException("Authentication Failed: Username/password/AuthKey/AuthDate parameter(s) cannot be null or empty.");
178                 }
179         }
180
181
182         public JSONObject get(final String path, final String username, final String password, final String protocolFlag) throws HttpException, JSONException {
183                 if (null != username && null != password) {
184                         
185                         WebTarget target = null;
186
187                         Response response = null;
188                         if (ProtocolTypeConstants.AUTH_KEY.getValue().equalsIgnoreCase(protocolFlag)) {
189                                 target=getTarget(path);
190                                 response = target.request()
191                                                 .header(MR_AUTH_CONSTANT, username)
192                                                 .header(MR_DATE_CONSTANT, password)
193                                                 .get();
194                         } else {
195                                 target = getTarget(path, username, password);
196                                 String encoding = Base64.encodeAsString(username+":"+password);
197                                 
198                                 response = target.request().header("Authorization", "Basic " + encoding).get(); 
199                                                 
200                         }
201                         return getResponseDataInJson(response);
202                 } else {
203                         throw new HttpException("Authentication Failed: Username/password/AuthKey/Authdate parameter(s) cannot be null or empty.");
204                 }
205         }
206         
207         
208         public String getResponse(final String path, final String username, final String password, final String protocolFlag) throws HttpException, JSONException {
209                 String responseData = null;
210                 if (null != username && null != password) {
211                         
212                         WebTarget target = null;
213
214                         Response response = null;
215                         if (ProtocolTypeConstants.AUTH_KEY.getValue().equalsIgnoreCase(protocolFlag)) {
216                                 target=getTarget(path);
217                                 response = target.request()
218                                                 .header(MR_AUTH_CONSTANT, username)
219                                                 .header(MR_DATE_CONSTANT, password)
220                                                 .get();
221                         } else {
222                                 target = getTarget(path, username, password);
223                                 String encoding = Base64.encodeAsString(username+":"+password);                         
224                                 response = target.request().header("Authorization", "Basic " + encoding).get();                                                 
225                         }
226                         MRClientFactory.HTTPHeadersMap=response.getHeaders();
227                 
228                         String transactionid=response.getHeaderString("transactionid");
229                                 if (transactionid!=null && !transactionid.equalsIgnoreCase("")) {
230                                         fLog.info("TransactionId : " + transactionid);
231                         }
232                         
233                         responseData = response.readEntity(String.class);
234                         return responseData;
235                 } else {
236                         throw new HttpException("Authentication Failed: Username/password/AuthKey/Authdate parameter(s) cannot be null or empty.");
237                 }
238         }
239         
240         public JSONObject getAuth(final String path, final String authKey, final String authDate,final String username, final String password, final String protocolFlag) throws HttpException, JSONException {
241                 if (null != username && null != password) {
242                         
243                         WebTarget target = null;
244
245                         Response response = null;
246                                 target=getTarget(path, username, password);
247                                 response = target.request()
248                                                 .header(MR_AUTH_CONSTANT, authKey)
249                                                 .header(MR_DATE_CONSTANT, authDate)
250                                                 .get();
251                                                 
252                         return getResponseDataInJson(response);
253                 } else {
254                         throw new HttpException("Authentication Failed: Username/password/AuthKey/Authdate parameter(s) cannot be null or empty.");
255                 }
256         }
257         
258         public String getAuthResponse(final String path, final String authKey, final String authDate,final String username, final String password, final String protocolFlag) throws HttpException, JSONException {
259                 String responseData = null;
260                 if (null != username && null != password) {
261                         
262                         WebTarget target = null;
263
264                         Response response = null;
265                                 target=getTarget(path, username, password);
266                                 response = target.request()
267                                                 .header(MR_AUTH_CONSTANT, authKey)
268                                                 .header(MR_DATE_CONSTANT, authDate)
269                                                 .get();
270                                 
271                                 MRClientFactory.HTTPHeadersMap=response.getHeaders();
272                                 
273                                 String transactionid=response.getHeaderString("transactionid");
274                                         if (transactionid!=null && !transactionid.equalsIgnoreCase("")) {
275                                                 fLog.info("TransactionId : " + transactionid);
276                                 }
277                                                 
278                                 responseData = response.readEntity(String.class);
279                                 return responseData;
280                 } else {
281                         throw new HttpException("Authentication Failed: Username/password/AuthKey/Authdate parameter(s) cannot be null or empty.");
282                 }
283         }
284
285         private WebTarget getTarget(final String path, final String username, final String password) {
286
287                 Client client = ClientBuilder.newClient();
288
289                 
290                         // Using UNIVERSAL as it supports both BASIC and DIGEST authentication types.
291                         HttpAuthenticationFeature feature = HttpAuthenticationFeature.universal(username, password);
292                         client.register(feature);
293                 
294                 return client.target(path);
295         }
296
297
298         private WebTarget getTarget(final String path) {
299
300                 Client client = ClientBuilder.newClient();
301                 return client.target(path);
302         }
303         private JSONObject getResponseDataInJson(Response response) throws JSONException {
304                 try {
305                         MRClientFactory.HTTPHeadersMap=response.getHeaders();
306                 //      fLog.info("DMAAP response status: " + response.getStatus());
307                         
308                                                 
309                         //MultivaluedMap<String, Object> headersMap = response.getHeaders();
310                         //for(String key : headersMap.keySet()) {
311                         String transactionid=response.getHeaderString("transactionid");
312                         if (transactionid!=null && !transactionid.equalsIgnoreCase("")) {
313                                 fLog.info("TransactionId : " + transactionid);
314                         }
315
316                         /*final String responseData = response.readEntity(String.class);
317                         JSONTokener jsonTokener = new JSONTokener(responseData);
318                         JSONObject jsonObject = null;
319                         final char firstChar = jsonTokener.next();
320                         jsonTokener.back();
321                         if ('[' == firstChar) {
322                                 JSONArray jsonArray = new JSONArray(jsonTokener);
323                                 jsonObject = new JSONObject();
324                                 jsonObject.put("result", jsonArray);
325                         } else {
326                                 jsonObject = new JSONObject(jsonTokener);
327                         }
328
329                         return jsonObject;*/
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 = 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 }