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 {
55 private static final String MR_AUTH_CONSTANT = "X-CambriaAuth";
56 private static final String MR_DATE_CONSTANT = "X-CambriaDate";
58 protected MRBaseClient(Collection<String> hosts) throws MalformedURLException {
59 super(ConnectionType.HTTP, hosts, MRConstants.kStdMRServicePort);
61 fLog = LoggerFactory.getLogger(this.getClass().getName());
64 protected MRBaseClient(Collection<String> hosts, int stdSvcPort) throws MalformedURLException {
65 super(ConnectionType.HTTP, hosts, stdSvcPort);
67 fLog = LoggerFactory.getLogger(this.getClass().getName());
70 protected MRBaseClient(Collection<String> hosts, String clientSignature) throws MalformedURLException {
71 super(ConnectionType.HTTP, hosts, MRConstants.kStdMRServicePort, clientSignature, CacheUse.NONE, 1, 1L,
72 TimeUnit.MILLISECONDS, 32, 32, 600000);
74 fLog = LoggerFactory.getLogger(this.getClass().getName());
81 protected Set<String> jsonArrayToSet(JSONArray a) {
85 final TreeSet<String> set = new TreeSet<String>();
86 for (int i = 0; i < a.length(); i++) {
87 set.add(a.getString(i));
92 public void logTo(Logger log) {
97 protected Logger getLog() {
103 public JSONObject post(final String path, final byte[] data, final String contentType, final String username,
104 final String password, final String protocolFlag) throws HttpException, JSONException {
105 if ((null != username && null != password)) {
106 WebTarget target = null;
108 Response response = null;
110 target = getTarget(path, username, password);
111 String encoding = Base64.encodeAsString(username + ":" + password);
113 response = target.request().header("Authorization", "Basic " + encoding)
114 .post(Entity.entity(data, contentType));
116 return getResponseDataInJson(response);
118 throw new HttpException(
119 "Authentication Failed: Username/password/AuthKey/AuthDate parameter(s) cannot be null or empty.");
123 public String postWithResponse(final String path, final byte[] data, final String contentType,
124 final String username, final String password, final String protocolFlag)
125 throws HttpException, JSONException {
126 String responseData = null;
127 if ((null != username && null != password)) {
128 WebTarget target = null;
130 Response response = null;
132 target = getTarget(path, username, password);
133 String encoding = Base64.encodeAsString(username + ":" + password);
135 response = target.request().header("Authorization", "Basic " + encoding)
136 .post(Entity.entity(data, contentType));
138 responseData = response.readEntity(String.class);
141 throw new HttpException(
142 "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,
147 final String authDate, final String username, final String password, final String protocolFlag)
148 throws HttpException, JSONException {
149 if ((null != username && null != password)) {
150 WebTarget target = null;
152 Response response = null;
153 target = getTarget(path, username, password);
154 response = target.request().header(MR_AUTH_CONSTANT, authKey).header(MR_DATE_CONSTANT, authDate)
155 .post(Entity.entity(data, contentType));
157 return getResponseDataInJson(response);
159 throw new HttpException(
160 "Authentication Failed: Username/password/AuthKey/AuthDate parameter(s) cannot be null or empty.");
164 public String postAuthwithResponse(final String path, final byte[] data, final String contentType,
165 final String authKey, final String authDate, final String username, final String password,
166 final String protocolFlag) throws HttpException, JSONException {
167 String responseData = null;
168 if ((null != username && null != password)) {
169 WebTarget target = null;
171 Response response = null;
172 target = getTarget(path, username, password);
173 response = target.request().header(MR_AUTH_CONSTANT, authKey).header(MR_DATE_CONSTANT, authDate)
174 .post(Entity.entity(data, contentType));
175 responseData = response.readEntity(String.class);
179 throw new HttpException(
180 "Authentication Failed: Username/password/AuthKey/AuthDate parameter(s) cannot be null or empty.");
184 public JSONObject get(final String path, final String username, final String password, final String protocolFlag)
185 throws HttpException, JSONException {
186 if (null != username && null != password) {
188 WebTarget target = null;
190 Response response = null;
191 if (ProtocolTypeConstants.AUTH_KEY.getValue().equalsIgnoreCase(protocolFlag)) {
192 target = getTarget(path);
193 response = target.request().header(MR_AUTH_CONSTANT, username).header(MR_DATE_CONSTANT, password).get();
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(
204 "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,
209 final String protocolFlag) throws HttpException, JSONException {
210 String responseData = null;
211 if (null != username && null != password) {
213 WebTarget target = null;
215 Response response = null;
216 if (ProtocolTypeConstants.AUTH_KEY.getValue().equalsIgnoreCase(protocolFlag)) {
217 target = getTarget(path);
218 response = target.request().header(MR_AUTH_CONSTANT, username).header(MR_DATE_CONSTANT, password).get();
220 target = getTarget(path, username, password);
221 String encoding = Base64.encodeAsString(username + ":" + password);
222 response = target.request().header("Authorization", "Basic " + encoding).get();
224 MRClientFactory.HTTPHeadersMap = response.getHeaders();
226 String transactionid = response.getHeaderString("transactionid");
227 if (transactionid != null && !transactionid.equalsIgnoreCase("")) {
228 fLog.info("TransactionId : " + transactionid);
231 responseData = response.readEntity(String.class);
234 throw new HttpException(
235 "Authentication Failed: Username/password/AuthKey/Authdate parameter(s) cannot be null or empty.");
239 public JSONObject getAuth(final String path, final String authKey, final String authDate, final String username,
240 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().header(MR_AUTH_CONSTANT, authKey).header(MR_DATE_CONSTANT, authDate).get();
249 return getResponseDataInJson(response);
251 throw new HttpException(
252 "Authentication Failed: Username/password/AuthKey/Authdate parameter(s) cannot be null or empty.");
256 public JSONObject getNoAuth(final String path, final String username, final String password,
257 final String protocolFlag) throws HttpException, JSONException {
258 if (null != username && null != password) {
260 WebTarget target = null;
262 Response response = null;
263 target = getTarget(path, username, password);
264 response = target.request().get();
266 return getResponseDataInJson(response);
268 throw new HttpException(
269 "Authentication Failed: Username/password/AuthKey/Authdate parameter(s) cannot be null or empty.");
273 public String getAuthResponse(final String path, final String authKey, final String authDate, final String username,
274 final String password, final String protocolFlag) throws HttpException, JSONException {
275 String responseData = null;
276 if (null != username && null != password) {
278 WebTarget target = null;
280 Response response = null;
281 target = getTarget(path, username, password);
282 response = target.request().header(MR_AUTH_CONSTANT, authKey).header(MR_DATE_CONSTANT, authDate).get();
284 MRClientFactory.HTTPHeadersMap = response.getHeaders();
286 String transactionid = response.getHeaderString("transactionid");
287 if (transactionid != null && !transactionid.equalsIgnoreCase("")) {
288 fLog.info("TransactionId : " + transactionid);
291 responseData = response.readEntity(String.class);
294 throw new HttpException(
295 "Authentication Failed: Username/password/AuthKey/Authdate parameter(s) cannot be null or empty.");
299 public String getNoAuthResponse(String path, final String username, final String password,
300 final String protocolFlag) throws HttpException, JSONException {
301 String responseData = null;
303 WebTarget target = null;
305 Response response = null;
306 target = getTarget(path, username, password);
307 response = target.request().get();
309 MRClientFactory.HTTPHeadersMap = response.getHeaders();
311 String transactionid = response.getHeaderString("transactionid");
312 if (transactionid != null && !transactionid.equalsIgnoreCase("")) {
313 fLog.info("TransactionId : " + transactionid);
316 responseData = response.readEntity(String.class);
321 private WebTarget getTarget(final String path, final String username, final String password) {
323 Client client = ClientBuilder.newClient();
325 // Using UNIVERSAL as it supports both BASIC and DIGEST authentication
327 HttpAuthenticationFeature feature = HttpAuthenticationFeature.universal(username, password);
328 client.register(feature);
330 return client.target(path);
333 private WebTarget getTarget(final String path) {
335 Client client = ClientBuilder.newClient();
336 return client.target(path);
339 private JSONObject getResponseDataInJson(Response response) throws JSONException {
341 MRClientFactory.HTTPHeadersMap = response.getHeaders();
342 // fLog.info("DMAAP response status: " + response.getStatus());
344 // MultivaluedMap<String, Object> headersMap =
345 // response.getHeaders();
346 // for(String key : headersMap.keySet()) {
347 String transactionid = response.getHeaderString("transactionid");
348 if (transactionid != null && !transactionid.equalsIgnoreCase("")) {
349 fLog.info("TransactionId : " + transactionid);
353 * final String responseData = response.readEntity(String.class);
354 * JSONTokener jsonTokener = new JSONTokener(responseData);
355 * JSONObject jsonObject = null; final char firstChar =
356 * jsonTokener.next(); jsonTokener.back(); if ('[' == firstChar) {
357 * JSONArray jsonArray = new JSONArray(jsonTokener); jsonObject =
358 * new JSONObject(); jsonObject.put("result", jsonArray); } else {
359 * jsonObject = new JSONObject(jsonTokener); }
364 if (response.getStatus() == 403) {
365 JSONObject jsonObject = null;
366 jsonObject = new JSONObject();
367 JSONArray jsonArray = new JSONArray();
368 jsonArray.put(response.getEntity());
369 jsonObject.put("result", jsonArray);
370 jsonObject.put("status", response.getStatus());
373 String responseData = response.readEntity(String.class);
375 JSONTokener jsonTokener = new JSONTokener(responseData);
376 JSONObject jsonObject = null;
377 final char firstChar = jsonTokener.next();
379 if ('[' == firstChar) {
380 JSONArray jsonArray = new JSONArray(jsonTokener);
381 jsonObject = new JSONObject();
382 jsonObject.put("result", jsonArray);
383 jsonObject.put("status", response.getStatus());
385 jsonObject = new JSONObject(jsonTokener);
386 jsonObject.put("status", response.getStatus());
390 } catch (JSONException excp) {
391 fLog.error("DMAAP - Error reading response data.", excp);
397 public String getHTTPErrorResponseMessage(String responseString) {
399 String response = null;
402 if (responseString.contains("<body>")) {
404 beginIndex = responseString.indexOf("body>") + 5;
405 endIndex = responseString.indexOf("</body");
406 response = responseString.substring(beginIndex, endIndex);
413 public String getHTTPErrorResponseCode(String responseString) {
415 String response = null;
418 if (responseString.contains("<title>")) {
419 beginIndex = responseString.indexOf("title>") + 6;
420 endIndex = responseString.indexOf("</title");
421 response = responseString.substring(beginIndex, endIndex);