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 );
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
72 super(ConnectionType.HTTP, hosts, MRConstants.kStdMRServicePort, clientSignature, CacheUse.NONE, 1, 1L, TimeUnit.MILLISECONDS, 32, 32, 600000);
74 fLog = LoggerFactory.getLogger ( this.getClass().getName () );
83 protected Set<String> jsonArrayToSet ( JSONArray a )
85 if ( a == null ) return null;
87 final TreeSet<String> set = new TreeSet<String> ();
88 for ( int i=0; i<a.length (); i++ )
90 set.add ( a.getString ( i ));
95 public void logTo ( Logger log )
98 replaceLogger ( log );
101 protected Logger getLog ()
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;
112 Response response = null;
114 target = getTarget(path, username, password);
115 String encoding = Base64.encodeAsString(username+":"+password);
118 response = target.request().header("Authorization", "Basic " + encoding).post(Entity.entity(data, contentType));
120 return getResponseDataInJson(response);
122 throw new HttpException("Authentication Failed: Username/password/AuthKey/AuthDate parameter(s) cannot be null or empty.");
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;
130 Response response = null;
132 target = getTarget(path, username, password);
133 String encoding = Base64.encodeAsString(username+":"+password);
136 response = target.request().header("Authorization", "Basic " + encoding).post(Entity.entity(data, contentType));
138 responseData = response.readEntity(String.class);
141 throw new HttpException("Authentication Failed: Username/password/AuthKey/AuthDate parameter(s) cannot be null or empty.");
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;
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));
155 return getResponseDataInJson(response);
157 throw new HttpException("Authentication Failed: Username/password/AuthKey/AuthDate parameter(s) cannot be null or empty.");
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;
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);
175 throw new HttpException("Authentication Failed: Username/password/AuthKey/AuthDate parameter(s) cannot be null or empty.");
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) {
183 WebTarget target = null;
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)
193 target = getTarget(path, username, password);
194 String encoding = Base64.encodeAsString(username+":"+password);
196 response = target.request().header("Authorization", "Basic " + encoding).get();
199 return getResponseDataInJson(response);
201 throw new HttpException("Authentication Failed: Username/password/AuthKey/Authdate parameter(s) cannot be null or empty.");
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) {
210 WebTarget target = null;
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)
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("Authentication Failed: Username/password/AuthKey/Authdate parameter(s) cannot be null or empty.");
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) {
241 WebTarget target = null;
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)
250 return getResponseDataInJson(response);
252 throw new HttpException("Authentication Failed: Username/password/AuthKey/Authdate parameter(s) cannot be null or empty.");
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) {
260 WebTarget target = null;
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)
269 MRClientFactory.HTTPHeadersMap=response.getHeaders();
271 String transactionid=response.getHeaderString("transactionid");
272 if (transactionid!=null && !transactionid.equalsIgnoreCase("")) {
273 fLog.info("TransactionId : " + transactionid);
276 responseData = response.readEntity(String.class);
279 throw new HttpException("Authentication Failed: Username/password/AuthKey/Authdate parameter(s) cannot be null or empty.");
283 private WebTarget getTarget(final String path, final String username, final String password) {
285 Client client = ClientBuilder.newClient();
288 // Using UNIVERSAL as it supports both BASIC and DIGEST authentication types.
289 HttpAuthenticationFeature feature = HttpAuthenticationFeature.universal(username, password);
290 client.register(feature);
292 return client.target(path);
296 private WebTarget getTarget(final String path) {
298 Client client = ClientBuilder.newClient();
299 return client.target(path);
301 private JSONObject getResponseDataInJson(Response response) throws JSONException {
303 MRClientFactory.HTTPHeadersMap=response.getHeaders();
304 // fLog.info("DMAAP response status: " + response.getStatus());
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);
314 /*final String responseData = response.readEntity(String.class);
315 JSONTokener jsonTokener = new JSONTokener(responseData);
316 JSONObject jsonObject = null;
317 final char firstChar = jsonTokener.next();
319 if ('[' == firstChar) {
320 JSONArray jsonArray = new JSONArray(jsonTokener);
321 jsonObject = new JSONObject();
322 jsonObject.put("result", jsonArray);
324 jsonObject = new JSONObject(jsonTokener);
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());
339 String responseData = response.readEntity(String.class);
341 JSONTokener jsonTokener = new JSONTokener(responseData);
342 JSONObject jsonObject = null;
343 final char firstChar = jsonTokener.next();
345 if ('[' == firstChar) {
346 JSONArray jsonArray = new JSONArray(jsonTokener);
347 jsonObject = new JSONObject();
348 jsonObject.put("result", jsonArray);
349 jsonObject.put("status", response.getStatus());
351 jsonObject = new JSONObject(jsonTokener);
352 jsonObject.put("status", response.getStatus());
356 } catch (JSONException excp) {
357 fLog.error("DMAAP - Error reading response data.", excp);
363 public String getHTTPErrorResponseMessage(String responseString){
365 String response = null;
368 if(responseString.contains("<body>")){
370 beginIndex = responseString.indexOf("body>")+5;
371 endIndex = responseString.indexOf("</body");
372 response = responseString.substring(beginIndex,endIndex);
379 public String getHTTPErrorResponseCode(String responseString){
381 String response = null;
384 if(responseString.contains("<title>")){
385 beginIndex = responseString.indexOf("title>")+6;
386 endIndex = responseString.indexOf("</title");
387 response = responseString.substring(beginIndex,endIndex);