Top Banner
Wri$ng Powerful HTTP Apps Using the New Asynchronous HTTP Client Library Jeanfrancois Arcand h@p://[email protected]/jfarcand h@p://github.com/AsyncH@pClient/asynch@pclient Hubert Iwaniuk h@p://[email protected]/neotyk
35

Async Http Client for Java and Scripting Language

May 24, 2015

Download

Technology

jfarcand

JavaOne 2010 talk.
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Async Http Client for Java and Scripting Language

Wri$ng  Powerful  HTTP  Apps  Using  the  New  Asynchronous  HTTP  Client  

Library  

Jeanfrancois  Arcand  h@p://[email protected]/jfarcand  

h@p://github.com/AsyncH@pClient/async-­‐h@p-­‐client  

Hubert  Iwaniuk  h@p://[email protected]/neotyk  

Page 2: Async Http Client for Java and Scripting Language

Jeanfrancois  

Creator  of    the  Grizzly  Framework    

Creator  of  GlassFish  v3  Grizzly  Micro  

Kernel  Creator  and  Co-­‐

Leader  of    Atmosphere  

9  years  @  Sun  Microsystem  

Creator  Async  H@p  Client  

Major  contributor  to  GlassFish  

Page 3: Async Http Client for Java and Scripting Language

•  News  and  Update  • Why    

•  The  Async  H@p  Client  API  •  Conclusion    •  Q  &  A  

Page 4: Async Http Client for Java and Scripting Language

Since  released,  we’ve  got  an  impressive  amount  of  

contribu$ons  and  adop$ons.  Library  is  evolving  fast!  

Page 5: Async Http Client for Java and Scripting Language

Why  

JDK’s  UrlConnec$on  Totally  Broken  

Page 6: Async Http Client for Java and Scripting Language

Why  

JDK’s  UrlConnec$on  Totally  Broken  

Apache  H@pClient  high  on  steroid  

Page 7: Async Http Client for Java and Scripting Language

Why  

JDK’s  UrlConnec$on  Totally  Broken  

Apache  H@pClient  high  on  steroid  

Apache  H@p  is  blocking  

Page 8: Async Http Client for Java and Scripting Language

Why  

JDK’s  UrlConnec$on  Totally  Broken  

Apache  H@pClient  high  on  steroid  

Apache  H@p  is  blocking  

Apache  H@pClient  buffer  the  bytes  in  

memory  

Page 9: Async Http Client for Java and Scripting Language

Why  

JDK’s  UrlConnec$on  Totally  Broken  

Apache  H@pClient  high  on  steroid  

Apache  H@p  is  blocking  

Apache  H@pClient  buffer  the  bytes  in  

memory  

Apache  H@pClient  is  $ed  to  its  own    

I/O  layer.  

Page 10: Async Http Client for Java and Scripting Language

Why  

AsyncH@pClient  supports  the  “zero-­‐copy”    

Page 11: Async Http Client for Java and Scripting Language

Why  

AsyncH@pClient  supports  the  “zero-­‐copy”    

Large  Upload  using  na$ve  memory  

Small  memory    

Page 12: Async Http Client for Java and Scripting Language

Why  

AsyncH@pClient  supports  the  “zero-­‐copy”    

AsyncH@pClient  is  not  $ed  to  it’s  

I/O  layer    

Page 13: Async Http Client for Java and Scripting Language

Why  

AsyncH@pClient  supports  the  “zero-­‐copy”    

AsyncH@pClient  is  not  $ed  to  it’s  

I/O  layer    Ne@y    

Grizzly  

Apache  H@pClient  

JDK  UrlConnec

$on  

Page 14: Async Http Client for Java and Scripting Language

Why  

AsyncH@pClient  supports  the  “zero-­‐copy”    

AsyncH@pClient  is  not  $ed  to  it’s  

I/O  layer    

AsyncH@pClient  is  blocking  or  non  blocking  

Page 15: Async Http Client for Java and Scripting Language

Why  

AsyncH@pClient  supports  the  “zero-­‐copy”    

AsyncH@pClient  is  not  $ed  to  it’s  

I/O  layer    

AsyncH@pClient  is  blocking  or  non  blocking  

Allow  efficient  streaming  

Use  the  well  know    

Future<?>  API  

Page 16: Async Http Client for Java and Scripting Language

Why  

AsyncH@pClient  supports  the  “zero-­‐copy”    

AsyncH@pClient  is  not  $ed  to  it’s  

I/O  layer    

AsyncH@pClient  is  blocking  or  non  blocking  

AsyncH@pClient  doesn’t  buffer  the  bytes  in  memory  

Page 17: Async Http Client for Java and Scripting Language

Why  

AsyncH@pClient  supports  the  “zero-­‐copy”    

AsyncH@pClient  is  not  $ed  to  it’s  

I/O  layer    

AsyncH@pClient  is  blocking  or  non  blocking  

AsyncH@pClient  doesn’t  buffer  the  bytes  in  memory  

Your  applica$on  have  control  

Page 18: Async Http Client for Java and Scripting Language

Why  

AsyncH@pClient  supports  the  “zero-­‐copy”    

AsyncH@pClient  is  not  $ed  to  it’s  

I/O  layer    

AsyncH@pClient  is  blocking  or  non  blocking  

AsyncH@pClient  doesn’t  buffer  the  bytes  in  memory  

AsyncH@pClient  is  easy  to  use  

Page 19: Async Http Client for Java and Scripting Language

Fully  Asynchronous  

request  

callback  Response  chunk  

Calling  Thread  

callback  Response  chunk  

Server  Thread  Pool  (*)  

Page 20: Async Http Client for Java and Scripting Language

Comple$onHandler  

request  

Response  start  

Calling  Thread  

callback  Response  end  

Server  Thread  Pool  (*)  

Page 21: Async Http Client for Java and Scripting Language

Future  based  API  AsyncH@pClient  asyncH@pClient  =  new  AsyncH@pClient();  

 Future<Response>  f  =            [email protected]("h@p://www.sonatype.com/").execute();  

Response  r  =  f.get();    

Page 22: Async Http Client for Java and Scripting Language

Handler  based  API  AsyncH@pClient  asyncH@pClient  =  new  AsyncH@pClient();  Future<Response>  asyncH@pClient.     prepareGet("h@p://www.sonatype.com/").execute(  

              new  AsyncComple=onHandler<Response>(                           {                             @Override                             public  Response  onCompleted(Response  r){  

    return  response;                  }  

           @Override       public  void  onThrowable(Throwable  t){    

             }       });  

Page 23: Async Http Client for Java and Scripting Language

Typed  AsyncH@pClient  asyncH@pClient  =  new  AsyncH@pClient();  [email protected]("h@p://www.sonatype.com/").execute(            new  AsyncComple$onHandler<Integer>(                      {                        @Override                        public  Integer  onCompleted(Response  r){       return  response.getStatus();                        }  

                   @Override          public  void  onThrowable(Throwable  t){    

       }    }).get();  //  Return  Integer  

Page 24: Async Http Client for Java and Scripting Language

Request  Builder  

AsyncH@pClient  c=  new  AsyncH@pClient();  

c.preparePost(“h@ps://….”)                                  .setBody(body)          .setHeader(header)                                  .setProxy(proxy)                                  .execute();  

Page 25: Async Http Client for Java and Scripting Language

Streaming  Handler  AsyncH@pClient  c  =  new  AsyncH@pClient();    Future<String>  f  =  c.prepareGet("h@p://www.sonatype.com/").execute(  

         new  AsyncHandler<String>()  {  

        @Override       public  STATE  onStatusReceived(H@pResponseStatus<String>  status)         throws  Excep$on       {  //  return  STATE.ABORT  to  stop  }  

             @Override                  public  STATE  onHeadersReceived(H@pResponseHeaders<String>  headers)         throws  Excep$on                  {  …}  

  @Override       public  STATE  onBodyPartReceived(H@pResponseBodyPart<String>  bodyPart)         throws  Excep$on       {…}  }.get();  

Page 26: Async Http Client for Java and Scripting Language

Progress  Handler  Future<String>  f  =    [email protected](uri)                                                  .setRealm(createRealm())                                                  .setProxyServer(createProxyServer())                                                  .setFile(file)                                                  .execute(comple$onHandler);  ("….").setFile(.execute(  

         new  AsyncComple=onHandler<String>()  {  

        @Override         public  STATE  onHeaderWriteCompleted()  {                       return  STATE.CONTINUE;             }    

                 @Override                    public  STATE  onContentWriteCompleted()  {                                        return  STATE.CONTINUE;                    }  

               @Override                  public  STATE  onContentWriteProgess(long  amount,  long  current,  long  total)  {                                return  STATE.CONTINUE;                  }  )  

Page 27: Async Http Client for Java and Scripting Language

Configurable  AsyncH@pClientConfig  c  =       new  [email protected]().       setResponseTimeoutInMs(30000).build();  

AsyncH@pClient  asyncH@pClient  =  new  AsyncH@pClient(c);  

Realm  realm  =  new  Realm.RealmBuilder()                          .setPrincipal(“me”)                          .setPassword(“xxxx”).build();  c.setRealm(realm);  

AsyncH@pClient  asyncH@pClient  =  new  AsyncH@pClient(c);  

Page 28: Async Http Client for Java and Scripting Language

Zero  Copy  -­‐  Upload  

AsyncH@pClient  c=  new  AsyncH@pClient();  

c.preparePost(“h@ps://….”)                                  .setBody(body)            .setFile(header)                                  .setProxy(proxy).execute();  

Page 29: Async Http Client for Java and Scripting Language

Zero  Copy  -­‐  Download  AsyncH@pClient  c  =  new  AsyncH@pClient();    Future<String>  f  =  c.prepareGet("h@p://www.sonatype.com/").execute(  

         new  AsyncHandler<String>()  {  

  @Override       public  STATE  onBodyPartReceived(H@pResponseBodyPart<String>  bodyPart)         throws  Excep$on       {    

                                       bodyPart.write(OutputStream);     }  }.get();  

Page 30: Async Http Client for Java and Scripting Language

TLS  Support  

//  Op$onal  AsyncH@pClientConfig  c  =       new  [email protected]().       setSSLEngine(…).build();  

AsyncH@pClient  asyncH@pClient  =       new  AsyncH@pClient(c);  

Future<String>  f  =        c.prepareGet("hBps://….").get();  

Page 31: Async Http Client for Java and Scripting Language

Scrip$ng  Support  -­‐  Clojure  

•  (ns  twi@er-­‐stream      (:require  [[email protected]  :as  c]                          [org.danlarkin.json  :as  j]                          [clojure.contrib.logging  :as  l]))  

(doseq  [twit-­‐str  (c/string                                      (c/stream-­‐seq  :get  "h@p://[email protected]/1/statuses/sample.json"                                                                  :auth  {:user  "u"  :password  "p"}                                                                  :$meout  -­‐1))]      (try          (let  [twit  (j/decode-­‐from-­‐str  twit-­‐str)]              (l/info  (str  (get-­‐in  twit  [:user  :screen_name])  "=>"  (:text  twit))))          (catch  Excep$on  e              (l/warn  (str  "Failed  to  parse:  "  twit-­‐str)  e))))  

Page 32: Async Http Client for Java and Scripting Language

Scrip$ng  Support  -­‐  JRuby  

client  =  [email protected]    future  =  client.prepare_get("h@p://…")  

                 .set_header("X-­‐Trace",  "true").execute  

       response  =  future.get  

               response.headers.each  

         {  |pair|  puts  "#{pair.key}  =>    

                                     #{pair.value.join(",  ")}"  }  client.close    

Page 33: Async Http Client for Java and Scripting Language

Scrip$ng  Support  -­‐  Jython  

       client  =  AsyncH@pClient()  future  =  client.prepareGet("h@p://www.google.com/")  

                       .setHeaders({  "User-­‐Agent"  :  [  "Async  HTTP  Client/1.0.0"  ]})  

                       .execute()    

response  =  future.get()  for  entry  in  response.headers:  print  '%s  =>  %s'  %  (entry.key,  ",  ".join(entry.value))  client.close()    

Page 34: Async Http Client for Java and Scripting Language

What’s  Next  

•  NTLM  support  • Websocket  support  

•  New  Providers:  – Grizzly  2.0  – Apache  H@pClient  

•  H@p  Pipelining  •  Annota$on  based  support.  

Page 35: Async Http Client for Java and Scripting Language

Fancy  @BaseURL("h@p://localhost:12345")    public  interface  FooClient    {       @GET("/")       public  Future<Response>  getRoot();  

    @GET("/")       public  Future<String>  getRootAsString();  

  @GET("/")       public  Future<String>         getRootWithParam(@QueryParam("name")  String  name);    }    FancyClientBuilder  builder  =  new  FancyClientBuilder(asyncClient);  FooClient  client  =  builder.build(FooClient.class);