2 * ============LICENSE_START====================================================
4 * ===========================================================================
5 * Copyright (c) 2018 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
11 * http://www.apache.org/licenses/LICENSE-2.0
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ============LICENSE_END====================================================
22 package org.onap.aaf.cadi.http;
24 import java.io.IOException;
25 import java.io.InputStream;
26 import java.io.InputStreamReader;
27 import java.io.OutputStream;
28 import java.io.Reader;
29 import java.net.HttpURLConnection;
31 import java.net.URISyntaxException;
33 import java.util.ArrayList;
35 import javax.servlet.http.HttpServletResponse;
37 import org.onap.aaf.cadi.CadiException;
38 import org.onap.aaf.cadi.LocatorException;
39 import org.onap.aaf.cadi.SecuritySetter;
40 import org.onap.aaf.cadi.client.EClient;
41 import org.onap.aaf.cadi.client.Future;
42 import org.onap.aaf.cadi.client.Rcli;
43 import org.onap.aaf.misc.env.APIException;
44 import org.onap.aaf.misc.env.Data;
45 import org.onap.aaf.misc.env.Data.TYPE;
46 import org.onap.aaf.misc.env.util.Pool.Pooled;
47 import org.onap.aaf.misc.rosetta.env.RosettaDF;
50 * Low Level Http Client Mechanism. Chances are, you want the high level "HRcli"
51 * for Rosetta Object Translation
56 public class HClient implements EClient<HttpURLConnection> {
58 private ArrayList<Header> headers;
60 private String pathinfo;
62 private String fragment;
63 private Transfer transfer;
64 private SecuritySetter<HttpURLConnection> ss;
65 private HttpURLConnection huc;
66 private int connectTimeout;
68 public HClient(SecuritySetter<HttpURLConnection> ss, URI uri,int connectTimeout) throws LocatorException {
70 throw new LocatorException("No Service available to call");
74 this.connectTimeout = connectTimeout;
75 pathinfo = query = fragment = null;
79 public void setMethod(String meth) {
84 public void setPathInfo(String pathinfo) {
85 this.pathinfo = pathinfo;
89 public void setPayload(Transfer transfer) {
90 this.transfer = transfer;
94 public void addHeader(String tag, String value) {
96 headers = new ArrayList<>();
97 headers.add(new Header(tag, value));
101 public void setQueryParams(String q) {
106 public void setFragment(String f) {
111 public void send() throws APIException {
112 // Build URL from given URI plus current Settings
113 if (uri.getPath()==null) {
114 throw new APIException("Invalid URL entered for HClient");
116 StringBuilder pi=null;
117 if (pathinfo!=null) { // additional pathinfo
118 pi = new StringBuilder(uri.getPath());
119 if (!pathinfo.startsWith("/")) {
129 pi==null?uri.getPath():pi.toString(),
130 query==null?uri.getQuery():query,
131 fragment==null?uri.getFragment():fragment
133 huc = getConnection(sendURI, pi);
134 huc.setRequestMethod(meth);
139 for (Header d : headers) {
140 huc.addRequestProperty(d.tag, d.value);
142 huc.setDoInput(true);
143 huc.setDoOutput(true);
144 huc.setUseCaches(false);
145 huc.setConnectTimeout(connectTimeout);
147 if (transfer != null) {
148 transfer.transfer(huc.getOutputStream());
150 // TODO other settings? There's a bunch here.
151 } catch (APIException e) {
153 } catch (Exception e) {
155 throw new APIException("Cannot connect to Root URI: '" + uri.toString() + '\'',e);
157 throw new APIException("Cannot connect to '" + sendURI.toString() + "' (Root URI: '" + uri.toString() + "')",e);
159 } finally { // ensure all these are reset after sends
164 pathinfo = query = fragment = "";
168 public URI getURI() {
172 public int timeout() {
173 return connectTimeout;
176 protected HttpURLConnection getConnection(URI uri, StringBuilder pi) throws IOException, URISyntaxException {
180 pi==null?uri.getPath():pi.toString(),
183 return (HttpURLConnection) url.openConnection();
186 public abstract class HFuture<T> extends Future<T> {
187 protected HttpURLConnection huc;
188 protected int respCode;
189 protected IOException exception;
190 protected StringBuilder errContent;
192 public HFuture(final HttpURLConnection huc) {
196 protected boolean evalInfo(HttpURLConnection huc) throws APIException, IOException{
197 return respCode == 200;
201 public final boolean get(int timeout) throws CadiException {
203 huc.setReadTimeout(timeout);
204 respCode = huc.getResponseCode();
205 ss.setLastResponse(respCode);
212 } catch (IOException | APIException e) {
213 throw new CadiException(e);
219 private void extractError() {
220 InputStream is = huc.getErrorStream();
223 is = huc.getInputStream();
226 errContent = new StringBuilder();
228 while ((c=is.read())>=0) {
229 errContent.append((char)c);
232 } catch (IOException e) {
237 // Typically only used by Read
238 public StringBuilder inputStreamToString(InputStream is) {
239 // Avoids Carriage returns, and is reasonably efficient, given
242 StringBuilder sb = new StringBuilder();
243 Reader rdr = new InputStreamReader(is);
245 char[] buf = new char[256];
247 while ((read = rdr.read(buf)) >= 0) {
248 sb.append(buf, 0, read);
254 } catch (IOException e) {
266 public HttpURLConnection huc() {
270 public IOException exception() {
275 public String header(String tag) {
276 return huc.getHeaderField(tag);
279 public void close() {
287 public <T> Future<T> futureCreate(Class<T> t) {
288 return new HFuture<T>(huc) {
289 public boolean evalInfo(HttpURLConnection huc) {
290 return respCode==201;
294 public String body() {
295 if (errContent != null) {
296 return errContent.toString();
304 public Future<String> futureReadString() {
305 return new HFuture<String>(huc) {
306 public boolean evalInfo(HttpURLConnection huc) throws IOException {
307 if (respCode == 200) {
308 StringBuilder sb = inputStreamToString(huc.getInputStream());
310 value = sb.toString();
318 public String body() {
321 } else if (errContent != null) {
322 return errContent.toString();
331 public <T> Future<T> futureRead(final RosettaDF<T> df, final TYPE type) {
332 return new HFuture<T>(huc) {
333 private Data<T> data;
335 public boolean evalInfo(HttpURLConnection huc) throws APIException, IOException {
336 if (respCode == 200) {
337 data = df.newData().in(type).load(huc.getInputStream());
338 value = data.asObject();
345 public String body() {
348 return data.asString();
349 } catch (APIException e) {
351 } else if (errContent != null) {
352 return errContent.toString();
360 public <T> Future<T> future(final T t) {
361 return new HFuture<T>(huc) {
362 public boolean evalInfo(HttpURLConnection huc) {
363 if (respCode == 200) {
371 public String body() {
372 if (errContent != null) {
373 return errContent.toString();
375 return Integer.toString(respCode);
381 public Future<Void> future(final HttpServletResponse resp, final int expected) throws APIException {
382 return new HFuture<Void>(huc) {
383 public boolean evalInfo(HttpURLConnection huc) throws IOException, APIException {
384 resp.setStatus(respCode);
387 OutputStream os = resp.getOutputStream();
388 if (respCode==expected) {
389 is = huc.getInputStream();
391 Pooled<byte[]> pbuff = Rcli.buffPool.get();
393 while ((read=is.read(pbuff.content))>=0) {
394 os.write(pbuff.content,0,read);
401 is = huc.getErrorStream();
403 is = huc.getInputStream();
406 errContent = new StringBuilder();
407 Pooled<byte[]> pbuff = Rcli.buffPool.get();
409 while ((read=is.read(pbuff.content))>=0) {
410 os.write(pbuff.content,0,read);
421 public String body() {
422 return errContent==null?null:errContent.toString();
427 private static class Header {
428 public final String tag;
429 public final String value;
431 public Header(String t, String v) {
436 public String toString() {
437 return tag + '=' + value;
441 public String toString() {
442 return "HttpURLConnection Client configured to " + uri.toString();