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 void setURI(URI uri) {
176 public int timeout() {
177 return connectTimeout;
180 protected HttpURLConnection getConnection(URI uri, StringBuilder pi) throws IOException, URISyntaxException {
184 pi==null?uri.getPath():pi.toString(),
187 return (HttpURLConnection) url.openConnection();
190 public abstract class HFuture<T> extends Future<T> {
191 protected HttpURLConnection huc;
192 protected int respCode;
193 protected IOException exception;
194 protected StringBuilder errContent;
196 public HFuture(final HttpURLConnection huc) {
200 protected boolean evalInfo(HttpURLConnection huc) throws APIException, IOException{
201 return respCode == 200;
205 public final boolean get(int timeout) throws CadiException {
207 huc.setReadTimeout(timeout);
208 respCode = huc.getResponseCode();
209 ss.setLastResponse(respCode);
216 } catch (IOException | APIException e) {
217 throw new CadiException(e);
223 private void extractError() {
224 InputStream is = huc.getErrorStream();
227 is = huc.getInputStream();
230 errContent = new StringBuilder();
232 while ((c=is.read())>=0) {
233 errContent.append((char)c);
236 } catch (IOException e) {
241 // Typically only used by Read
242 public StringBuilder inputStreamToString(InputStream is) {
243 // Avoids Carriage returns, and is reasonably efficient, given
246 StringBuilder sb = new StringBuilder();
247 Reader rdr = new InputStreamReader(is);
249 char[] buf = new char[256];
251 while ((read = rdr.read(buf)) >= 0) {
252 sb.append(buf, 0, read);
258 } catch (IOException e) {
270 public HttpURLConnection huc() {
274 public IOException exception() {
279 public String header(String tag) {
280 return huc.getHeaderField(tag);
283 public void close() {
291 public <T> Future<T> futureCreate(Class<T> t) {
292 return new HFuture<T>(huc) {
293 public boolean evalInfo(HttpURLConnection huc) {
294 return respCode==201;
298 public String body() {
299 if (errContent != null) {
300 return errContent.toString();
308 public Future<String> futureReadString() {
309 return new HFuture<String>(huc) {
310 public boolean evalInfo(HttpURLConnection huc) throws IOException {
311 if (respCode == 200) {
312 StringBuilder sb = inputStreamToString(huc.getInputStream());
314 value = sb.toString();
322 public String body() {
325 } else if (errContent != null) {
326 return errContent.toString();
335 public <T> Future<T> futureRead(final RosettaDF<T> df, final TYPE type) {
336 return new HFuture<T>(huc) {
337 private Data<T> data;
339 public boolean evalInfo(HttpURLConnection huc) throws APIException, IOException {
340 if (respCode == 200) {
341 data = df.newData().in(type).load(huc.getInputStream());
342 value = data.asObject();
349 public String body() {
352 return data.asString();
353 } catch (APIException e) {
355 } else if (errContent != null) {
356 return errContent.toString();
364 public <T> Future<T> future(final T t) {
365 return new HFuture<T>(huc) {
366 public boolean evalInfo(HttpURLConnection huc) {
367 if (respCode == 200) {
375 public String body() {
376 if (errContent != null) {
377 return errContent.toString();
379 return Integer.toString(respCode);
385 public Future<Void> future(final HttpServletResponse resp, final int expected) throws APIException {
386 return new HFuture<Void>(huc) {
387 public boolean evalInfo(HttpURLConnection huc) throws IOException, APIException {
388 resp.setStatus(respCode);
391 OutputStream os = resp.getOutputStream();
392 if (respCode==expected) {
393 is = huc.getInputStream();
395 Pooled<byte[]> pbuff = Rcli.buffPool.get();
397 while ((read=is.read(pbuff.content))>=0) {
398 os.write(pbuff.content,0,read);
405 is = huc.getErrorStream();
407 is = huc.getInputStream();
410 errContent = new StringBuilder();
411 Pooled<byte[]> pbuff = Rcli.buffPool.get();
413 while ((read=is.read(pbuff.content))>=0) {
414 os.write(pbuff.content,0,read);
425 public String body() {
426 return errContent==null?null:errContent.toString();
431 private static class Header {
432 public final String tag;
433 public final String value;
435 public Header(String t, String v) {
440 public String toString() {
441 return tag + '=' + value;
445 public String toString() {
446 return "HttpURLConnection Client configured to " + uri.toString();