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