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 {
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("/")) {
125 URI sendURI = new URI(
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 (Exception e) {
153 throw new APIException(e);
154 } finally { // ensure all these are reset after sends
159 pathinfo = query = fragment = "";
163 public URI getURI() {
167 public int timeout() {
168 return connectTimeout;
171 protected HttpURLConnection getConnection(URI uri, StringBuilder pi) throws IOException, URISyntaxException {
177 pi==null?uri.getPath():pi.toString(),
180 return (HttpURLConnection) url.openConnection();
183 public abstract class HFuture<T> extends Future<T> {
184 protected HttpURLConnection huc;
185 protected int respCode;
186 protected IOException exception;
187 protected StringBuilder errContent;
189 public HFuture(final HttpURLConnection huc) {
193 protected boolean evalInfo(HttpURLConnection huc) throws APIException, IOException{
194 return respCode == 200;
198 public final boolean get(int timeout) throws CadiException {
200 huc.setReadTimeout(timeout);
201 respCode = huc.getResponseCode();
202 ss.setLastResponse(respCode);
209 } catch (IOException | APIException e) {
210 throw new CadiException(e);
216 private void extractError() {
217 InputStream is = huc.getErrorStream();
220 is = huc.getInputStream();
223 errContent = new StringBuilder();
225 while((c=is.read())>=0) {
226 errContent.append((char)c);
229 } catch (IOException e) {
234 // Typically only used by Read
235 public StringBuilder inputStreamToString(InputStream is) {
236 // Avoids Carriage returns, and is reasonably efficient, given
239 StringBuilder sb = new StringBuilder();
240 Reader rdr = new InputStreamReader(is);
242 char[] buf = new char[256];
244 while ((read = rdr.read(buf)) >= 0) {
245 sb.append(buf, 0, read);
251 } catch (IOException e) {
263 public HttpURLConnection huc() {
267 public IOException exception() {
272 public String header(String tag) {
273 return huc.getHeaderField(tag);
276 public void close() {
284 public <T> Future<T> futureCreate(Class<T> t) {
285 return new HFuture<T>(huc) {
286 public boolean evalInfo(HttpURLConnection huc) {
287 return respCode==201;
291 public String body() {
292 if (errContent != null) {
293 return errContent.toString();
301 public Future<String> futureReadString() {
302 return new HFuture<String>(huc) {
303 public boolean evalInfo(HttpURLConnection huc) throws IOException {
304 if (respCode == 200) {
305 StringBuilder sb = inputStreamToString(huc.getInputStream());
307 value = sb.toString();
315 public String body() {
318 } else if (errContent != null) {
319 return errContent.toString();
328 public <T> Future<T> futureRead(final RosettaDF<T> df, final TYPE type) {
329 return new HFuture<T>(huc) {
330 private Data<T> data;
332 public boolean evalInfo(HttpURLConnection huc) throws APIException, IOException {
333 if (respCode == 200) {
334 data = df.newData().in(type).load(huc.getInputStream());
335 value = data.asObject();
342 public String body() {
345 return data.asString();
346 } catch (APIException e) {
348 } else if (errContent != null) {
349 return errContent.toString();
357 public <T> Future<T> future(final T t) {
358 return new HFuture<T>(huc) {
359 public boolean evalInfo(HttpURLConnection huc) {
360 if (respCode == 200) {
368 public String body() {
369 if (errContent != null) {
370 return errContent.toString();
372 return Integer.toString(respCode);
378 public Future<Void> future(final HttpServletResponse resp, final int expected) throws APIException {
379 return new HFuture<Void>(huc) {
380 public boolean evalInfo(HttpURLConnection huc) throws IOException, APIException {
381 resp.setStatus(respCode);
384 OutputStream os = resp.getOutputStream();
385 if(respCode==expected) {
386 is = huc.getInputStream();
388 Pooled<byte[]> pbuff = Rcli.buffPool.get();
390 while((read=is.read(pbuff.content))>=0) {
391 os.write(pbuff.content,0,read);
398 is = huc.getErrorStream();
400 is = huc.getInputStream();
403 errContent = new StringBuilder();
404 Pooled<byte[]> pbuff = Rcli.buffPool.get();
406 while((read=is.read(pbuff.content))>=0) {
407 os.write(pbuff.content,0,read);
418 public String body() {
419 return errContent==null?null:errContent.toString();
424 private static class Header {
425 public final String tag;
426 public final String value;
428 public Header(String t, String v) {
433 public String toString() {
434 return tag + '=' + value;
438 public String toString() {
439 return "HttpURLConnection Client configured to " + uri.toString();