View Javadoc

1   /*
2    * ====================================================================
3    *
4    *  Licensed to the Apache Software Foundation (ASF) under one or more
5    *  contributor license agreements.  See the NOTICE file distributed with
6    *  this work for additional information regarding copyright ownership.
7    *  The ASF licenses this file to You under the Apache License, Version 2.0
8    *  (the "License"); you may not use this file except in compliance with
9    *  the License.  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   * ====================================================================
19   *
20   * This software consists of voluntary contributions made by many
21   * individuals on behalf of the Apache Software Foundation.  For more
22   * information on the Apache Software Foundation, please see
23   * <http://www.apache.org/>.
24   *
25   */
26  
27  package org.apache.http.client.fluent;
28  
29  import java.io.IOException;
30  import java.security.KeyManagementException;
31  import java.security.NoSuchAlgorithmException;
32  
33  import javax.net.ssl.SSLContext;
34  
35  import org.apache.http.HttpHost;
36  import org.apache.http.auth.AuthScope;
37  import org.apache.http.auth.ChallengeState;
38  import org.apache.http.auth.Credentials;
39  import org.apache.http.auth.NTCredentials;
40  import org.apache.http.auth.UsernamePasswordCredentials;
41  import org.apache.http.client.AuthCache;
42  import org.apache.http.client.ClientProtocolException;
43  import org.apache.http.client.CookieStore;
44  import org.apache.http.client.CredentialsProvider;
45  import org.apache.http.client.HttpClient;
46  import org.apache.http.client.methods.HttpRequestBase;
47  import org.apache.http.client.protocol.ClientContext;
48  import org.apache.http.conn.scheme.PlainSocketFactory;
49  import org.apache.http.conn.scheme.Scheme;
50  import org.apache.http.conn.scheme.SchemeRegistry;
51  import org.apache.http.conn.scheme.SchemeSocketFactory;
52  import org.apache.http.conn.ssl.SSLInitializationException;
53  import org.apache.http.conn.ssl.SSLSocketFactory;
54  import org.apache.http.impl.auth.BasicScheme;
55  import org.apache.http.impl.client.BasicAuthCache;
56  import org.apache.http.impl.client.BasicCredentialsProvider;
57  import org.apache.http.impl.client.DefaultHttpClient;
58  import org.apache.http.impl.conn.PoolingClientConnectionManager;
59  import org.apache.http.protocol.BasicHttpContext;
60  
61  /**
62   * An Executor for fluent requests
63   * <p/>
64   * A {@link PoolingClientConnectionManager} with maximum 100 connections per route and
65   * a total maximum of 200 connections is used internally.
66   */
67  public class Executor {
68  
69      final static PoolingClientConnectionManager CONNMGR;
70      final static DefaultHttpClient CLIENT;
71  
72      static {
73          SchemeRegistry schemeRegistry = new SchemeRegistry();
74          SchemeSocketFactory plain = PlainSocketFactory.getSocketFactory();
75          schemeRegistry.register(new Scheme("http", 80, plain));
76          SchemeSocketFactory ssl = null;
77          try {
78              ssl = SSLSocketFactory.getSystemSocketFactory();
79          } catch (SSLInitializationException ex) {
80              SSLContext sslcontext;
81              try {
82                  sslcontext = SSLContext.getInstance(SSLSocketFactory.TLS);
83                  sslcontext.init(null, null, null);
84                  ssl = new SSLSocketFactory(sslcontext);
85              } catch (SecurityException ignore) {
86              } catch (KeyManagementException ignore) {
87              } catch (NoSuchAlgorithmException ignore) {
88              }
89          }
90          if (ssl != null) {
91              schemeRegistry.register(new Scheme("https", 443, ssl));
92          }
93          CONNMGR = new PoolingClientConnectionManager(schemeRegistry);
94          CONNMGR.setDefaultMaxPerRoute(100);
95          CONNMGR.setMaxTotal(200);
96          CLIENT = new DefaultHttpClient(CONNMGR);
97      }
98  
99      public static Executor newInstance() {
100         return new Executor(CLIENT);
101     }
102 
103     public static Executor newInstance(final HttpClient httpclient) {
104         return new Executor(httpclient != null ? httpclient : CLIENT);
105     }
106 
107     private final HttpClient httpclient;
108     private final BasicHttpContext localContext;
109     private final AuthCache authCache;
110 
111     private CredentialsProvider credentialsProvider;
112     private CookieStore cookieStore;
113 
114     Executor(final HttpClient httpclient) {
115         super();
116         this.httpclient = httpclient;
117         this.localContext = new BasicHttpContext();
118         this.authCache = new BasicAuthCache();
119     }
120 
121     public Executor auth(final AuthScope authScope, final Credentials creds) {
122         if (this.credentialsProvider == null) {
123             this.credentialsProvider = new BasicCredentialsProvider();
124         }
125         this.credentialsProvider.setCredentials(authScope, creds);
126         return this;
127     }
128 
129     public Executor auth(final HttpHost host, final Credentials creds) {
130         AuthScope authScope = host != null ? new AuthScope(host) : AuthScope.ANY;
131         return auth(authScope, creds);
132     }
133 
134     public Executor authPreemptive(final HttpHost host) {
135         this.authCache.put(host, new BasicScheme(ChallengeState.TARGET));
136         return this;
137     }
138 
139     public Executor authPreemptiveProxy(final HttpHost host) {
140         this.authCache.put(host, new BasicScheme(ChallengeState.PROXY));
141         return this;
142     }
143 
144     public Executor auth(final Credentials cred) {
145         return auth(AuthScope.ANY, cred);
146     }
147 
148     public Executor auth(final String username, final String password) {
149         return auth(new UsernamePasswordCredentials(username, password));
150     }
151 
152     public Executor auth(final String username, final String password,
153             final String workstation, final String domain) {
154         return auth(new NTCredentials(username, password, workstation, domain));
155     }
156 
157     public Executor auth(final HttpHost host,
158             final String username, final String password) {
159         return auth(host, new UsernamePasswordCredentials(username, password));
160     }
161 
162     public Executor auth(final HttpHost host,
163             final String username, final String password,
164             final String workstation, final String domain) {
165         return auth(host, new NTCredentials(username, password, workstation, domain));
166     }
167 
168     public Executor clearAuth() {
169         if (this.credentialsProvider != null) {
170             this.credentialsProvider.clear();
171         }
172         return this;
173     }
174 
175     public Executor cookieStore(final CookieStore cookieStore) {
176         this.cookieStore = cookieStore;
177         return this;
178     }
179 
180     public Executor clearCookies() {
181         if (this.cookieStore != null) {
182             this.cookieStore.clear();
183         }
184         return this;
185     }
186 
187     /**
188      * Executes the request. Please Note that response content must be processed 
189      * or discarded using {@link Response#discardContent()}, otherwise the
190      * connection used for the request might not be released to the pool.
191      * 
192      * @see Response#handleResponse(org.apache.http.client.ResponseHandler)
193      * @see Response#discardContent()
194      */
195     public Response execute(
196             final Request request) throws ClientProtocolException, IOException {
197         this.localContext.setAttribute(ClientContext.CREDS_PROVIDER, this.credentialsProvider);
198         this.localContext.setAttribute(ClientContext.AUTH_CACHE, this.authCache);
199         this.localContext.setAttribute(ClientContext.COOKIE_STORE, this.cookieStore);
200         HttpRequestBase httprequest = request.getHttpRequest();
201         httprequest.reset();
202         return new Response(this.httpclient.execute(httprequest, this.localContext));
203     }
204 
205     public static void registerScheme(final Scheme scheme) {
206         CONNMGR.getSchemeRegistry().register(scheme);
207     }
208 
209     public static void unregisterScheme(final String name) {
210         CONNMGR.getSchemeRegistry().unregister(name);
211     }
212 
213 }