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.net.ssl.SSLException;
36 import javax.net.ssl.SSLHandshakeException;
37 import javax.servlet.http.HttpServletResponse;
39 import org.onap.aaf.cadi.CadiException;
40 import org.onap.aaf.cadi.LocatorException;
41 import org.onap.aaf.cadi.SecuritySetter;
42 import org.onap.aaf.cadi.client.EClient;
43 import org.onap.aaf.cadi.client.Future;
44 import org.onap.aaf.cadi.client.Rcli;
45 import org.onap.aaf.misc.env.APIException;
46 import org.onap.aaf.misc.env.Data;
47 import org.onap.aaf.misc.env.Data.TYPE;
48 import org.onap.aaf.misc.env.util.Pool.Pooled;
49 import org.onap.aaf.misc.rosetta.env.RosettaDF;
51 * Low Level Http Client Mechanism. Chances are, you want the high level "HRcli"
52 * for Rosetta Object Translation
57 public class HClient implements EClient<HttpURLConnection> {
59 private ArrayList<Header> headers;
61 private String pathinfo;
63 private String fragment;
64 private Transfer transfer;
65 private SecuritySetter<HttpURLConnection> ss;
66 private HttpURLConnection huc;
67 private int connectTimeout;
69 public HClient(SecuritySetter<HttpURLConnection> ss, URI uri,int connectTimeout) throws LocatorException {
71 throw new LocatorException("No Service available to call");
75 this.connectTimeout = connectTimeout;
76 pathinfo = query = fragment = null;
80 public void setMethod(String meth) {
85 public void setPathInfo(String pathinfo) {
86 this.pathinfo = pathinfo;
90 public void setPayload(Transfer transfer) {
91 this.transfer = transfer;
95 public void addHeader(String tag, String value) {
97 headers = new ArrayList<>();
98 headers.add(new Header(tag, value));
102 public void setQueryParams(String q) {
107 public void setFragment(String f) {
112 public void send() throws APIException {
113 // Build URL from given URI plus current Settings
114 if (uri.getPath()==null) {
115 throw new APIException("Invalid URL entered for HClient");
117 StringBuilder pi=null;
118 if (pathinfo!=null) { // additional pathinfo
119 pi = new StringBuilder(uri.getPath());
120 if (!pathinfo.startsWith("/")) {
130 pi==null?uri.getPath():pi.toString(),
131 query==null?uri.getQuery():query,
132 fragment==null?uri.getFragment():fragment
134 huc = getConnection(sendURI, pi);
135 huc.setRequestMethod(meth);
140 for (Header d : headers) {
141 huc.addRequestProperty(d.tag, d.value);
143 huc.setDoInput(true);
144 huc.setDoOutput(true);
145 huc.setUseCaches(false);
146 huc.setConnectTimeout(connectTimeout);
148 if (transfer != null) {
149 transfer.transfer(huc.getOutputStream());
151 // TODO other settings? There's a bunch here.
152 } catch (APIException e) {
154 } catch (Exception e) {
156 throw new APIException("Cannot connect to Root URI: '" + uri.toString() + '\'',e);
158 throw new APIException("Cannot connect to '" + sendURI.toString() + "' (Root URI: '" + uri.toString() + "')",e);
160 } finally { // ensure all these are reset after sends
165 pathinfo = query = fragment = "";
169 public URI getURI() {
173 public void setURI(URI uri) {
177 public int timeout() {
178 return connectTimeout;
181 protected HttpURLConnection getConnection(URI uri, StringBuilder pi) throws IOException, URISyntaxException {
185 pi==null?uri.getPath():pi.toString(),
188 return (HttpURLConnection) url.openConnection();
191 public abstract class HFuture<T> extends Future<T> {
192 protected HttpURLConnection huc;
193 protected int respCode;
194 protected IOException exception;
195 protected StringBuilder errContent;
197 public HFuture(final HttpURLConnection huc) {
201 protected boolean evalInfo(HttpURLConnection huc) throws APIException, IOException{
202 return respCode == 200;
206 public final boolean get(int timeout) throws CadiException {
208 huc.setReadTimeout(timeout);
209 respCode = huc.getResponseCode();
210 ss.setLastResponse(respCode);
217 } catch (IOException | APIException e) {
218 throw new CadiException(e);
224 private void extractError() {
225 InputStream is = huc.getErrorStream();
228 is = huc.getInputStream();
231 errContent = new StringBuilder();
233 while ((c=is.read())>=0) {
234 errContent.append((char)c);
237 } catch (IOException e) {
242 // Typically only used by Read
243 public StringBuilder inputStreamToString(InputStream is) {
244 // Avoids Carriage returns, and is reasonably efficient, given
247 StringBuilder sb = new StringBuilder();
248 Reader rdr = new InputStreamReader(is);
250 char[] buf = new char[256];
252 while ((read = rdr.read(buf)) >= 0) {
253 sb.append(buf, 0, read);
259 } catch (IOException e) {
271 public HttpURLConnection huc() {
275 public IOException exception() {
280 public String header(String tag) {
281 return huc.getHeaderField(tag);
284 public void close() {
292 public <T> Future<T> futureCreate(Class<T> t) {
293 return new HFuture<T>(huc) {
294 public boolean evalInfo(HttpURLConnection huc) {
295 return respCode==201;
299 public String body() {
300 if (errContent != null) {
301 return errContent.toString();
309 public Future<String> futureReadString() {
310 return new HFuture<String>(huc) {
311 public boolean evalInfo(HttpURLConnection huc) throws IOException {
312 if (respCode == 200) {
313 StringBuilder sb = inputStreamToString(huc.getInputStream());
315 value = sb.toString();
323 public String body() {
326 } else if (errContent != null) {
327 return errContent.toString();
336 public <T> Future<T> futureRead(final RosettaDF<T> df, final TYPE type) {
337 return new HFuture<T>(huc) {
338 private Data<T> data;
340 public boolean evalInfo(HttpURLConnection huc) throws APIException, IOException {
341 if (respCode == 200) {
342 data = df.newData().in(type).load(huc.getInputStream());
343 value = data.asObject();
350 public String body() {
353 return data.asString();
354 } catch (APIException e) {
356 } else if (errContent != null) {
357 return errContent.toString();
365 public <T> Future<T> future(final T t) {
366 return new HFuture<T>(huc) {
367 public boolean evalInfo(HttpURLConnection huc) {
368 if (respCode == 200) {
376 public String body() {
377 if (errContent != null) {
378 return errContent.toString();
380 return Integer.toString(respCode);
386 public Future<Void> future(final HttpServletResponse resp, final int expected) throws APIException {
387 return new HFuture<Void>(huc) {
388 public boolean evalInfo(HttpURLConnection huc) throws IOException, APIException {
389 resp.setStatus(respCode);
392 OutputStream os = resp.getOutputStream();
393 if (respCode==expected) {
394 is = huc.getInputStream();
396 Pooled<byte[]> pbuff = Rcli.buffPool.get();
398 while ((read=is.read(pbuff.content))>=0) {
399 os.write(pbuff.content,0,read);
406 is = huc.getErrorStream();
408 is = huc.getInputStream();
411 errContent = new StringBuilder();
412 Pooled<byte[]> pbuff = Rcli.buffPool.get();
414 while ((read=is.read(pbuff.content))>=0) {
415 os.write(pbuff.content,0,read);
426 public String body() {
427 return errContent==null?null:errContent.toString();
432 private static class Header {
433 public final String tag;
434 public final String value;
436 public Header(String t, String v) {
441 public String toString() {
442 return tag + '=' + value;
446 public String toString() {
447 return "HttpURLConnection Client configured to " + uri.toString();