Improve Batches
[aaf/authz.git] / cadi / client / src / main / java / org / onap / aaf / cadi / http / HClient.java
1 /**
2  * ============LICENSE_START====================================================
3  * org.onap.aaf
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
10  * 
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  * 
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====================================================
19  *
20  */
21
22 package org.onap.aaf.cadi.http;
23
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;
30 import java.net.URI;
31 import java.net.URISyntaxException;
32 import java.net.URL;
33 import java.util.ArrayList;
34
35 import javax.servlet.http.HttpServletResponse;
36
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;
48
49 /**
50  * Low Level Http Client Mechanism. Chances are, you want the high level "HRcli"
51  * for Rosetta Object Translation
52  * 
53  * @author Jonathan
54  *
55  */
56 public class HClient implements EClient<HttpURLConnection> {
57     private URI uri;
58     private ArrayList<Header> headers;
59     private String meth;
60     private String pathinfo;
61     private String query;
62     private String fragment;
63     private Transfer transfer;
64     private SecuritySetter<HttpURLConnection> ss;
65     private HttpURLConnection huc;
66     private int connectTimeout;
67
68     public HClient(SecuritySetter<HttpURLConnection> ss, URI uri,int connectTimeout) throws LocatorException {
69         if (uri == null) {
70             throw new LocatorException("No Service available to call");
71         }
72         this.uri = uri;
73         this.ss = ss;
74         this.connectTimeout = connectTimeout;
75         pathinfo = query = fragment = null; 
76     }
77
78     @Override
79     public void setMethod(String meth) {
80         this.meth = meth;
81     }
82
83     @Override
84     public void setPathInfo(String pathinfo) {
85         this.pathinfo = pathinfo;
86     }
87
88     @Override
89     public void setPayload(Transfer transfer) {
90         this.transfer = transfer;
91     }
92     
93     @Override
94     public void addHeader(String tag, String value) {
95         if (headers == null)
96             headers = new ArrayList<>();
97         headers.add(new Header(tag, value));
98     }
99
100     @Override
101     public void setQueryParams(String q) {
102         query = q;
103     }
104
105     @Override
106     public void setFragment(String f) {
107         fragment = f;
108     }
109
110     @Override
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");
115         }
116         StringBuilder pi=null;
117         if (pathinfo!=null) { // additional pathinfo
118             pi = new StringBuilder(uri.getPath());
119             if (!pathinfo.startsWith("/")) {
120                 pi.append('/');
121             }
122             pi.append(pathinfo);
123         }
124         URI sendURI = null;
125         try {
126             sendURI = new URI(
127                     uri.getScheme(),
128                     uri.getAuthority(),
129                     pi==null?uri.getPath():pi.toString(),
130                     query==null?uri.getQuery():query,
131                     fragment==null?uri.getFragment():fragment
132                     );
133             huc = getConnection(sendURI, pi);
134             huc.setRequestMethod(meth);
135             if (ss!=null) {
136                 ss.setSecurity(huc); 
137             }
138             if (headers != null)
139                 for (Header d : headers) {                    
140                     huc.addRequestProperty(d.tag, d.value);
141                 }
142             huc.setDoInput(true);
143             huc.setDoOutput(true);
144             huc.setUseCaches(false);
145             huc.setConnectTimeout(connectTimeout);
146             huc.connect();
147             if (transfer != null) {
148                 transfer.transfer(huc.getOutputStream());
149             }
150             // TODO other settings? There's a bunch here.
151         } catch (APIException e) {
152                 throw e;
153         } catch (Exception e) {
154                 if(sendURI==null) {
155                         throw new APIException("Cannot connect to Root URI: '" + uri.toString() + '\'',e);
156                 } else {
157                         throw new APIException("Cannot connect to '" + sendURI.toString() + "' (Root URI: '" + uri.toString() + "')",e);
158                 }
159         } finally { // ensure all these are reset after sends
160             meth=pathinfo=null;
161             if (headers!=null) {
162                 headers.clear();
163             }
164             pathinfo = query = fragment = "";
165         }
166     }
167     
168     public URI getURI() {
169         return uri;
170     }
171
172     public int timeout() {
173         return connectTimeout;
174     }
175     
176     protected HttpURLConnection getConnection(URI uri, StringBuilder pi) throws IOException, URISyntaxException {
177         URL url = new URI(
178                 uri.getScheme(), 
179                 uri.getAuthority(),
180                 pi==null?uri.getPath():pi.toString(), 
181                 query,
182                 fragment).toURL();
183         return (HttpURLConnection) url.openConnection();
184     }
185     
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;
191     
192         public HFuture(final HttpURLConnection huc) {
193             this.huc = huc;
194         }
195     
196         protected boolean evalInfo(HttpURLConnection huc) throws APIException, IOException{
197             return respCode == 200;
198         };
199     
200         @Override
201         public final boolean get(int timeout) throws CadiException {
202             try {
203                 huc.setReadTimeout(timeout);
204                 respCode = huc.getResponseCode();
205                 ss.setLastResponse(respCode);
206                 if (evalInfo(huc)) {
207                     return true;
208                 } else {
209                     extractError();
210                     return false;
211                 }
212             } catch (IOException | APIException e) {
213                 throw new CadiException(e);
214             } finally {
215                 close();
216             }
217         }
218     
219         private void extractError() {
220             InputStream is = huc.getErrorStream();
221             try {
222                 if (is==null) {
223                     is = huc.getInputStream();
224                 }
225                 if (is!=null) {
226                 errContent = new StringBuilder();
227                 int c;
228                     while ((c=is.read())>=0) {
229                         errContent.append((char)c);
230                     }
231                 }
232             } catch (IOException e) {
233                 exception = e;
234             }
235         }
236     
237         // Typically only used by Read
238         public StringBuilder inputStreamToString(InputStream is) {
239             // Avoids Carriage returns, and is reasonably efficient, given
240             // the buffer reads.
241             try {
242                 StringBuilder sb = new StringBuilder();
243                 Reader rdr = new InputStreamReader(is);
244                 try {
245                     char[] buf = new char[256];
246                     int read;
247                     while ((read = rdr.read(buf)) >= 0) {
248                         sb.append(buf, 0, read);
249                     }
250                 } finally {
251                     rdr.close();
252                 }
253                 return sb;
254             } catch (IOException e) {
255                 exception = e;
256                 return null;
257             }
258         }
259     
260     
261         @Override
262         public int code() {
263             return respCode;
264         }
265     
266         public HttpURLConnection huc() {
267             return huc;
268         }
269     
270         public IOException exception() {
271             return exception;
272         }
273     
274         @Override
275         public String header(String tag) {
276             return huc.getHeaderField(tag);
277         }
278     
279         public void close() {
280             if (huc!=null) {
281                 huc.disconnect();
282             }
283         }
284     }
285
286     @Override
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;
291             }
292
293             @Override
294             public String body() {
295                 if (errContent != null) {
296                     return errContent.toString();
297                 }
298                 return "";
299             }
300         };
301     }
302
303     @Override
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());
309                     if (sb != null) {
310                         value = sb.toString();
311                     }
312                     return true;
313                 }
314                 return false;
315             }
316
317             @Override
318             public String body() {
319                 if (value != null) {
320                     return value;
321                 } else if (errContent != null) {
322                     return errContent.toString();
323                 }
324                 return "";
325             }
326
327         };
328     }
329
330     @Override
331     public <T> Future<T> futureRead(final RosettaDF<T> df, final TYPE type) {
332         return new HFuture<T>(huc) {
333             private Data<T> data;
334
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();
339                     return true;
340                 }
341                 return false;
342             }
343
344             @Override
345             public String body() {
346                 if (data != null) {
347                     try {
348                         return data.asString();
349                     } catch (APIException e) {
350                     }
351                 } else if (errContent != null) {
352                     return errContent.toString();
353                 }
354                 return "";
355             }
356         };
357     }
358
359     @Override
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) {
364                     value = t;
365                     return true;
366                 }
367                 return false;
368             }
369
370             @Override
371             public String body() {
372                 if (errContent != null) {
373                     return errContent.toString();
374                 }
375                 return Integer.toString(respCode);
376             }
377         };
378     }
379
380     @Override
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);
385                 int read;
386                 InputStream is;
387                 OutputStream os = resp.getOutputStream();
388                 if (respCode==expected) {
389                     is = huc.getInputStream();
390                     // reuse Buffers
391                     Pooled<byte[]> pbuff = Rcli.buffPool.get();
392                     try { 
393                         while ((read=is.read(pbuff.content))>=0) {
394                             os.write(pbuff.content,0,read);
395                         }
396                     } finally {
397                         pbuff.done();
398                     }
399                     return true;
400                 } else {
401                     is = huc.getErrorStream();
402                     if (is==null) {
403                         is = huc.getInputStream();
404                     }
405                     if (is!=null) {
406                         errContent = new StringBuilder();
407                         Pooled<byte[]> pbuff = Rcli.buffPool.get();
408                         try { 
409                             while ((read=is.read(pbuff.content))>=0) {
410                                 os.write(pbuff.content,0,read);
411                             }
412                         } finally {
413                             pbuff.done();
414                         }
415                     }
416                 }
417                 return false;
418             }
419
420             @Override
421             public String body() {
422                 return errContent==null?null:errContent.toString();
423             }
424         };
425     }
426
427     private static class Header {
428         public final String tag;
429         public final String value;
430
431         public Header(String t, String v) {
432             this.tag = t;
433             this.value = v;
434         }
435         
436         public String toString() {
437             return tag + '=' + value;
438         }
439     }
440     
441     public String toString() {
442         return "HttpURLConnection Client configured to " + uri.toString();
443     }
444 }