summaryrefslogtreecommitdiffstats
path: root/client/src/main/java/com/att/cadi/http/HClient.java
blob: 6704bf4f2564c9e6bdee99ba1dc33b3211d552f7 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
/*******************************************************************************
 * ============LICENSE_START====================================================
 * * org.onap.aaf
 * * ===========================================================================
 * * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
 * * ===========================================================================
 * * Licensed under the Apache License, Version 2.0 (the "License");
 * * you may not use this file except in compliance with the License.
 * * You may obtain a copy of the License at
 * * 
 *  *      http://www.apache.org/licenses/LICENSE-2.0
 * * 
 *  * Unless required by applicable law or agreed to in writing, software
 * * distributed under the License is distributed on an "AS IS" BASIS,
 * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * * See the License for the specific language governing permissions and
 * * limitations under the License.
 * * ============LICENSE_END====================================================
 * *
 * * ECOMP is a trademark and service mark of AT&T Intellectual Property.
 * *
 ******************************************************************************/
package com.att.cadi.http;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.Reader;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URL;
import java.util.ArrayList;

import javax.servlet.http.HttpServletResponse;

import com.att.cadi.CadiException;
import com.att.cadi.LocatorException;
import com.att.cadi.SecuritySetter;
import com.att.cadi.client.EClient;
import com.att.cadi.client.Future;
import com.att.cadi.client.Rcli;
import com.att.inno.env.APIException;
import com.att.inno.env.Data;
import com.att.inno.env.Data.TYPE;
import com.att.inno.env.util.Pool.Pooled;
import com.att.rosetta.env.RosettaDF;

/**
 * Low Level Http Client Mechanism. Chances are, you want the high level "HRcli"
 * for Rosetta Object Translation
 * 
 *
 */
public class HClient implements EClient<HttpURLConnection> {
	private URI uri;
	private ArrayList<Header> headers;
	private String meth;
	private String pathinfo;
	private String query;
	private String fragment;
	private Transfer transfer;
	private SecuritySetter<HttpURLConnection> ss;
	private HttpURLConnection huc;
	private int connectTimeout;

	public HClient(SecuritySetter<HttpURLConnection> ss, URI uri,int connectTimeout) throws LocatorException {
		if (uri == null) {
			throw new LocatorException("No Service available to call");
		}
		this.uri = uri;
		this.ss = ss;
		this.connectTimeout = connectTimeout;
		pathinfo = query = fragment = ""; 
	}

	@Override
	public void setMethod(String meth) {
		this.meth = meth;
	}

	@Override
	public void setPathInfo(String pathinfo) {
		this.pathinfo = pathinfo;
	}

	@Override
	public void setPayload(Transfer transfer) {
		this.transfer = transfer;
	}
	
	@Override
	public void addHeader(String tag, String value) {
		if (headers == null)
			headers = new ArrayList<Header>();
		headers.add(new Header(tag, value));
	}

	@Override
	public void setQueryParams(String q) {
		query = q;
	}

	@Override
	public void setFragment(String f) {
		fragment = f;
	}

	@Override
	public void send() throws APIException {
		try {
			// Build URL from given URI plus current Settings
			if(uri.getPath()==null) {
				throw new APIException("Invalid URL entered for HClient");
			}
			StringBuilder pi = new StringBuilder(uri.getPath());
			if(!pathinfo.startsWith("/")) {
				pi.append('/');
			}
			pi.append(pathinfo);
			URL url = new URI(
					uri.getScheme(), 
					uri.getUserInfo(),
					uri.getHost(), 
					uri.getPort(), 
					pi.toString(), 
					query,
					fragment).toURL();
			pathinfo=null;
			query=null;
			fragment=null;
			huc = (HttpURLConnection) url.openConnection();
			if(ss!=null) {
				ss.setSecurity(huc); 
			}
			huc.setRequestMethod(meth);
			if (headers != null)
				for (Header d : headers) {
					huc.addRequestProperty(d.tag, d.value);
				}
			huc.setDoInput(true);
			huc.setDoOutput(true);
			huc.setUseCaches(false);
			huc.setConnectTimeout(connectTimeout);
			huc.connect();
			if (transfer != null) {
				transfer.transfer(huc.getOutputStream());
			}
			// TODO other settings? There's a bunch here.
		} catch (Exception e) {
			throw new APIException(e);
		} finally { // ensure all these are reset after sends
			meth=pathinfo=null;
			if(headers!=null) {
				headers.clear();
			}
			pathinfo = query = fragment = "";
		}
	}

	public abstract class HFuture<T> extends Future<T> {
		protected HttpURLConnection huc;
		protected int respCode;
		protected String respMessage;
		protected IOException exception;
		protected StringBuilder errContent;
	
		public HFuture(final HttpURLConnection huc) {
			this.huc = huc;
		}
	
		protected boolean evalInfo(HttpURLConnection huc) throws APIException, IOException{
			return respCode == 200;
		};
	
		@Override
		public final boolean get(int timeout) throws CadiException {
			try {
				huc.setReadTimeout(timeout);
				respCode = huc.getResponseCode();
				ss.setLastResponse(respCode);
				if(evalInfo(huc)) {
					return true;
				} else {
					extractError();
					return false;
				}
			} catch (IOException | APIException e) {
				throw new CadiException(e);
			} finally {
				close();
			}
		}
	
		private void extractError() {
			InputStream is = huc.getErrorStream();
			try {
				if(is==null) {
					is = huc.getInputStream();
				}
				if(is!=null) {
				errContent = new StringBuilder();
				int c;
					while((c=is.read())>=0) {
						errContent.append((char)c);
					}
				}
			} catch (IOException e) {
				exception = e;
			}
		}
	
		// Typically only used by Read
		public StringBuilder inputStreamToString(InputStream is) {
			// Avoids Carriage returns, and is reasonably efficient, given
			// the buffer reads.
			try {
				StringBuilder sb = new StringBuilder();
				Reader rdr = new InputStreamReader(is);
				try {
					char[] buf = new char[256];
					int read;
					while ((read = rdr.read(buf)) >= 0) {
						sb.append(buf, 0, read);
					}
				} finally {
					rdr.close();
				}
				return sb;
			} catch (IOException e) {
				exception = e;
				return null;
			}
		}
	
	
		@Override
		public int code() {
			return respCode;
		}
	
		public HttpURLConnection huc() {
			return huc;
		}
	
		public IOException exception() {
			return exception;
		}
	
		public String respMessage() {
			return respMessage;
		}
	
		@Override
		public String header(String tag) {
			return huc.getHeaderField(tag);
		}
	
		public void close() {
			if(huc!=null) {
				huc.disconnect();
			}
		}
	}

	@Override
	public <T> Future<T> futureCreate(Class<T> t) {
		return new HFuture<T>(huc) {
			public boolean evalInfo(HttpURLConnection huc) {
				return respCode==201;
			}

			@Override
			public String body() {
				if (errContent != null) {
					return errContent.toString();
	
				} else if (respMessage != null) {
					return respMessage;
				}
				return "";
			}
		};
	}

	@Override
	public Future<String> futureReadString() {
		return new HFuture<String>(huc) {
			public boolean evalInfo(HttpURLConnection huc) throws IOException {
				if (respCode == 200) {
					StringBuilder sb = inputStreamToString(huc.getInputStream());
					if (sb != null) {
						value = sb.toString();
					}
					return true;
				}
				return false;
			}

			@Override
			public String body() {
				if (value != null) {
					return value;
				} else if (errContent != null) {
					return errContent.toString();
				} else if (respMessage != null) {
					return respMessage;
				}
				return "";
			}

		};
	}

	@Override
	public <T> Future<T> futureRead(final RosettaDF<T> df, final TYPE type) {
		return new HFuture<T>(huc) {
			private Data<T> data;

			public boolean evalInfo(HttpURLConnection huc) throws APIException, IOException {
				if (respCode == 200) {
					data = df.newData().in(type).load(huc.getInputStream());
					value = data.asObject();
					return true;
				}
				return false;
			}

			@Override
			public String body() {
				if (data != null) {
					try {
						return data.asString();
					} catch (APIException e) {
					}
				} else if (errContent != null) {
					return errContent.toString();
				} else if (respMessage != null) {
					return respMessage;
				}
				return "";
			}
		};
	}

	@Override
	public <T> Future<T> future(final T t) {
		return new HFuture<T>(huc) {
			public boolean evalInfo(HttpURLConnection huc) {
				if (respCode == 200) {
					value = t;
					return true;
				}
				return false;
			}

			@Override
			public String body() {
				if (errContent != null) {
					return errContent.toString();
				} else if (respMessage != null) {
					return respMessage;
				}
				return Integer.toString(respCode);
			}
		};
	}

	@Override
	public Future<Void> future(final HttpServletResponse resp, final int expected) throws APIException {
		return new HFuture<Void>(huc) {
			public boolean evalInfo(HttpURLConnection huc) throws IOException, APIException {
				resp.setStatus(respCode);
				int read;
				InputStream is;
				OutputStream os = resp.getOutputStream();
				if(respCode==expected) {
					is = huc.getInputStream();
					// reuse Buffers
					Pooled<byte[]> pbuff = Rcli.buffPool.get();
					try { 
						while((read=is.read(pbuff.content))>=0) {
							os.write(pbuff.content,0,read);
						}
					} finally {
						pbuff.done();
					}
					return true;
				} else {
					is = huc.getErrorStream();
					if(is==null) {
						is = huc.getInputStream();
					}
					if(is!=null) {
						errContent = new StringBuilder();
						Pooled<byte[]> pbuff = Rcli.buffPool.get();
						try { 
							while((read=is.read(pbuff.content))>=0) {
								os.write(pbuff.content,0,read);
							}
						} finally {
							pbuff.done();
						}
					}
				}
				return false;
			}

			@Override
			public String body() {
				return errContent==null?respMessage:errContent.toString();
			}
		};
	}

	private static class Header {
		public final String tag;
		public final String value;

		public Header(String t, String v) {
			this.tag = t;
			this.value = v;
		}
		
		public String toString() {
			return tag + '=' + value;
		}
	}
	
	public String toString() {
		return "HttpURLConnection Client configured to " + uri.toString();
	}
}