Merge "Add INFO.yaml file"
[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<Header>();
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                 try {
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                         pathinfo=null;
126                         query=null;
127                         fragment=null;
128                         //huc = (HttpURLConnection) url.openConnection();
129                         huc = getConnection(uri, pi);
130                         huc.setRequestMethod(meth);
131                         if(ss!=null) {
132                                 ss.setSecurity(huc); 
133                         }
134                         if (headers != null)
135                                 for (Header d : headers) {                                      
136                                         huc.addRequestProperty(d.tag, d.value);
137                                 }
138                         huc.setDoInput(true);
139                         huc.setDoOutput(true);
140                         huc.setUseCaches(false);
141                         huc.setConnectTimeout(connectTimeout);
142                         huc.connect();
143                         if (transfer != null) {
144                                 transfer.transfer(huc.getOutputStream());
145                         }
146                         // TODO other settings? There's a bunch here.
147                 } catch (Exception e) {
148                         throw new APIException(e);
149                 } finally { // ensure all these are reset after sends
150                         meth=pathinfo=null;
151                         if(headers!=null) {
152                                 headers.clear();
153                         }
154                         pathinfo = query = fragment = "";
155                 }
156         }
157         
158         public URI getURI() {
159                 return uri;
160         }
161
162         public int timeout() {
163                 return connectTimeout;
164         }
165         
166         protected HttpURLConnection getConnection(URI uri, StringBuilder pi) throws IOException, URISyntaxException {
167                 URL url = new URI(
168                                 uri.getScheme(), 
169                                 uri.getUserInfo(),
170                                 uri.getHost(), 
171                                 uri.getPort(), 
172                                 pi==null?uri.getPath():pi.toString(), 
173                                 query,
174                                 fragment).toURL();
175                 return (HttpURLConnection) url.openConnection();
176         }
177         
178         public abstract class HFuture<T> extends Future<T> {
179                 protected HttpURLConnection huc;
180                 protected int respCode;
181                 protected IOException exception;
182                 protected StringBuilder errContent;
183         
184                 public HFuture(final HttpURLConnection huc) {
185                         this.huc = huc;
186                 }
187         
188                 protected boolean evalInfo(HttpURLConnection huc) throws APIException, IOException{
189                         return respCode == 200;
190                 };
191         
192                 @Override
193                 public final boolean get(int timeout) throws CadiException {
194                         try {
195                                 huc.setReadTimeout(timeout);
196                                 respCode = huc.getResponseCode();
197                                 ss.setLastResponse(respCode);
198                                 if(evalInfo(huc)) {
199                                         return true;
200                                 } else {
201                                         extractError();
202                                         return false;
203                                 }
204                         } catch (IOException | APIException e) {
205                                 throw new CadiException(e);
206                         } finally {
207                                 close();
208                         }
209                 }
210         
211                 private void extractError() {
212                         InputStream is = huc.getErrorStream();
213                         try {
214                                 if(is==null) {
215                                         is = huc.getInputStream();
216                                 }
217                                 if(is!=null) {
218                                 errContent = new StringBuilder();
219                                 int c;
220                                         while((c=is.read())>=0) {
221                                                 errContent.append((char)c);
222                                         }
223                                 }
224                         } catch (IOException e) {
225                                 exception = e;
226                         }
227                 }
228         
229                 // Typically only used by Read
230                 public StringBuilder inputStreamToString(InputStream is) {
231                         // Avoids Carriage returns, and is reasonably efficient, given
232                         // the buffer reads.
233                         try {
234                                 StringBuilder sb = new StringBuilder();
235                                 Reader rdr = new InputStreamReader(is);
236                                 try {
237                                         char[] buf = new char[256];
238                                         int read;
239                                         while ((read = rdr.read(buf)) >= 0) {
240                                                 sb.append(buf, 0, read);
241                                         }
242                                 } finally {
243                                         rdr.close();
244                                 }
245                                 return sb;
246                         } catch (IOException e) {
247                                 exception = e;
248                                 return null;
249                         }
250                 }
251         
252         
253                 @Override
254                 public int code() {
255                         return respCode;
256                 }
257         
258                 public HttpURLConnection huc() {
259                         return huc;
260                 }
261         
262                 public IOException exception() {
263                         return exception;
264                 }
265         
266                 @Override
267                 public String header(String tag) {
268                         return huc.getHeaderField(tag);
269                 }
270         
271                 public void close() {
272                         if(huc!=null) {
273                                 huc.disconnect();
274                         }
275                 }
276         }
277
278         @Override
279         public <T> Future<T> futureCreate(Class<T> t) {
280                 return new HFuture<T>(huc) {
281                         public boolean evalInfo(HttpURLConnection huc) {
282                                 return respCode==201;
283                         }
284
285                         @Override
286                         public String body() {
287                                 if (errContent != null) {
288                                         return errContent.toString();
289                                 }
290                                 return "";
291                         }
292                 };
293         }
294
295         @Override
296         public Future<String> futureReadString() {
297                 return new HFuture<String>(huc) {
298                         public boolean evalInfo(HttpURLConnection huc) throws IOException {
299                                 if (respCode == 200) {
300                                         StringBuilder sb = inputStreamToString(huc.getInputStream());
301                                         if (sb != null) {
302                                                 value = sb.toString();
303                                         }
304                                         return true;
305                                 }
306                                 return false;
307                         }
308
309                         @Override
310                         public String body() {
311                                 if (value != null) {
312                                         return value;
313                                 } else if (errContent != null) {
314                                         return errContent.toString();
315                                 }
316                                 return "";
317                         }
318
319                 };
320         }
321
322         @Override
323         public <T> Future<T> futureRead(final RosettaDF<T> df, final TYPE type) {
324                 return new HFuture<T>(huc) {
325                         private Data<T> data;
326
327                         public boolean evalInfo(HttpURLConnection huc) throws APIException, IOException {
328                                 if (respCode == 200) {
329                                         data = df.newData().in(type).load(huc.getInputStream());
330                                         value = data.asObject();
331                                         return true;
332                                 }
333                                 return false;
334                         }
335
336                         @Override
337                         public String body() {
338                                 if (data != null) {
339                                         try {
340                                                 return data.asString();
341                                         } catch (APIException e) {
342                                         }
343                                 } else if (errContent != null) {
344                                         return errContent.toString();
345                                 }
346                                 return "";
347                         }
348                 };
349         }
350
351         @Override
352         public <T> Future<T> future(final T t) {
353                 return new HFuture<T>(huc) {
354                         public boolean evalInfo(HttpURLConnection huc) {
355                                 if (respCode == 200) {
356                                         value = t;
357                                         return true;
358                                 }
359                                 return false;
360                         }
361
362                         @Override
363                         public String body() {
364                                 if (errContent != null) {
365                                         return errContent.toString();
366                                 }
367                                 return Integer.toString(respCode);
368                         }
369                 };
370         }
371
372         @Override
373         public Future<Void> future(final HttpServletResponse resp, final int expected) throws APIException {
374                 return new HFuture<Void>(huc) {
375                         public boolean evalInfo(HttpURLConnection huc) throws IOException, APIException {
376                                 resp.setStatus(respCode);
377                                 int read;
378                                 InputStream is;
379                                 OutputStream os = resp.getOutputStream();
380                                 if(respCode==expected) {
381                                         is = huc.getInputStream();
382                                         // reuse Buffers
383                                         Pooled<byte[]> pbuff = Rcli.buffPool.get();
384                                         try { 
385                                                 while((read=is.read(pbuff.content))>=0) {
386                                                         os.write(pbuff.content,0,read);
387                                                 }
388                                         } finally {
389                                                 pbuff.done();
390                                         }
391                                         return true;
392                                 } else {
393                                         is = huc.getErrorStream();
394                                         if(is==null) {
395                                                 is = huc.getInputStream();
396                                         }
397                                         if(is!=null) {
398                                                 errContent = new StringBuilder();
399                                                 Pooled<byte[]> pbuff = Rcli.buffPool.get();
400                                                 try { 
401                                                         while((read=is.read(pbuff.content))>=0) {
402                                                                 os.write(pbuff.content,0,read);
403                                                         }
404                                                 } finally {
405                                                         pbuff.done();
406                                                 }
407                                         }
408                                 }
409                                 return false;
410                         }
411
412                         @Override
413                         public String body() {
414                                 return errContent==null?null:errContent.toString();
415                         }
416                 };
417         }
418
419         private static class Header {
420                 public final String tag;
421                 public final String value;
422
423                 public Header(String t, String v) {
424                         this.tag = t;
425                         this.value = v;
426                 }
427                 
428                 public String toString() {
429                         return tag + '=' + value;
430                 }
431         }
432         
433         public String toString() {
434                 return "HttpURLConnection Client configured to " + uri.toString();
435         }
436 }