1 /*******************************************************************************
2 * ============LICENSE_START=======================================================
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
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=========================================================
19 * ECOMP is a trademark and service mark of AT&T Intellectual Property.
21 *******************************************************************************/
22 package com.att.nsa.mr.client.impl;
24 import java.net.MalformedURLException;
25 import java.util.Collection;
27 import java.util.TreeSet;
28 import java.util.concurrent.TimeUnit;
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;
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;
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;
53 public class MRBaseClient extends HttpClient implements MRClient
56 private static final String MR_AUTH_CONSTANT = "X-CambriaAuth";
57 private static final String MR_DATE_CONSTANT = "X-CambriaDate";
59 protected MRBaseClient ( Collection<String> hosts ) throws MalformedURLException
61 super ( ConnectionType.HTTP, hosts, MRConstants.kStdMRServicePort );
63 fLog = LoggerFactory.getLogger ( this.getClass().getName () );
66 protected MRBaseClient ( Collection<String> hosts, int stdSvcPort ) throws MalformedURLException {
67 super ( ConnectionType.HTTP,hosts, stdSvcPort);
69 fLog = LoggerFactory.getLogger ( this.getClass().getName () );
72 protected MRBaseClient ( Collection<String> hosts, String clientSignature ) throws MalformedURLException
74 super(ConnectionType.HTTP, hosts, MRConstants.kStdMRServicePort, clientSignature, CacheUse.NONE, 1, 1L, TimeUnit.MILLISECONDS, 32, 32, 600000);
76 fLog = LoggerFactory.getLogger ( this.getClass().getName () );
85 protected Set<String> jsonArrayToSet ( JSONArray a )
87 if ( a == null ) return null;
89 final TreeSet<String> set = new TreeSet<String> ();
90 for ( int i=0; i<a.length (); i++ )
92 set.add ( a.getString ( i ));
97 public void logTo ( Logger log )
100 replaceLogger ( log );
103 protected Logger getLog ()
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;
114 Response response = null;
116 target = getTarget(path, username, password);
117 String encoding = Base64.encodeAsString(username+":"+password);
120 response = target.request().header("Authorization", "Basic " + encoding).post(Entity.entity(data, contentType));
122 return getResponseDataInJson(response);
124 throw new HttpException("Authentication Failed: Username/password/AuthKey/AuthDate parameter(s) cannot be null or empty.");
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;
132 Response response = null;
134 target = getTarget(path, username, password);
135 String encoding = Base64.encodeAsString(username+":"+password);
138 response = target.request().header("Authorization", "Basic " + encoding).post(Entity.entity(data, contentType));
140 responseData = response.readEntity(String.class);
143 throw new HttpException("Authentication Failed: Username/password/AuthKey/AuthDate parameter(s) cannot be null or empty.");
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;
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));
157 return getResponseDataInJson(response);
159 throw new HttpException("Authentication Failed: Username/password/AuthKey/AuthDate parameter(s) cannot be null or empty.");
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;
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);
177 throw new HttpException("Authentication Failed: Username/password/AuthKey/AuthDate parameter(s) cannot be null or empty.");
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) {
185 WebTarget target = null;
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)
195 target = getTarget(path, username, password);
196 String encoding = Base64.encodeAsString(username+":"+password);
198 response = target.request().header("Authorization", "Basic " + encoding).get();
201 return getResponseDataInJson(response);
203 throw new HttpException("Authentication Failed: Username/password/AuthKey/Authdate parameter(s) cannot be null or empty.");
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) {
212 WebTarget target = null;
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)
222 target = getTarget(path, username, password);
223 String encoding = Base64.encodeAsString(username+":"+password);
224 response = target.request().header("Authorization", "Basic " + encoding).get();
226 MRClientFactory.HTTPHeadersMap=response.getHeaders();
228 String transactionid=response.getHeaderString("transactionid");
229 if (transactionid!=null && !transactionid.equalsIgnoreCase("")) {
230 fLog.info("TransactionId : " + transactionid);
233 responseData = response.readEntity(String.class);
236 throw new HttpException("Authentication Failed: Username/password/AuthKey/Authdate parameter(s) cannot be null or empty.");
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) {
243 WebTarget target = null;
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)
252 return getResponseDataInJson(response);
254 throw new HttpException("Authentication Failed: Username/password/AuthKey/Authdate parameter(s) cannot be null or empty.");
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) {
262 WebTarget target = null;
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)
271 MRClientFactory.HTTPHeadersMap=response.getHeaders();
273 String transactionid=response.getHeaderString("transactionid");
274 if (transactionid!=null && !transactionid.equalsIgnoreCase("")) {
275 fLog.info("TransactionId : " + transactionid);
278 responseData = response.readEntity(String.class);
281 throw new HttpException("Authentication Failed: Username/password/AuthKey/Authdate parameter(s) cannot be null or empty.");
285 private WebTarget getTarget(final String path, final String username, final String password) {
287 Client client = ClientBuilder.newClient();
290 // Using UNIVERSAL as it supports both BASIC and DIGEST authentication types.
291 HttpAuthenticationFeature feature = HttpAuthenticationFeature.universal(username, password);
292 client.register(feature);
294 return client.target(path);
298 private WebTarget getTarget(final String path) {
300 Client client = ClientBuilder.newClient();
301 return client.target(path);
303 private JSONObject getResponseDataInJson(Response response) throws JSONException {
305 MRClientFactory.HTTPHeadersMap=response.getHeaders();
306 // fLog.info("DMAAP response status: " + response.getStatus());
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);
316 /*final String responseData = response.readEntity(String.class);
317 JSONTokener jsonTokener = new JSONTokener(responseData);
318 JSONObject jsonObject = null;
319 final char firstChar = jsonTokener.next();
321 if ('[' == firstChar) {
322 JSONArray jsonArray = new JSONArray(jsonTokener);
323 jsonObject = new JSONObject();
324 jsonObject.put("result", jsonArray);
326 jsonObject = new JSONObject(jsonTokener);
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());
341 String responseData = response.readEntity(String.class);
343 JSONTokener jsonTokener = new JSONTokener(responseData);
344 JSONObject jsonObject = null;
345 final char firstChar = jsonTokener.next();
347 if ('[' == firstChar) {
348 JSONArray jsonArray = new JSONArray(jsonTokener);
349 jsonObject = new JSONObject();
350 jsonObject.put("result", jsonArray);
351 jsonObject.put("status", response.getStatus());
353 jsonObject = new JSONObject(jsonTokener);
354 jsonObject.put("status", response.getStatus());
358 } catch (JSONException excp) {
359 fLog.error("DMAAP - Error reading response data.", excp);
365 public String getHTTPErrorResponseMessage(String responseString){
367 String response = null;
370 if(responseString.contains("<body>")){
372 beginIndex = responseString.indexOf("body>")+5;
373 endIndex = responseString.indexOf("</body");
374 response = responseString.substring(beginIndex,endIndex);
381 public String getHTTPErrorResponseCode(String responseString){
383 String response = null;
386 if(responseString.contains("<title>")){
387 beginIndex = responseString.indexOf("title>")+6;
388 endIndex = responseString.indexOf("</title");
389 response = responseString.substring(beginIndex,endIndex);