View Javadoc

1   /*
2    * ====================================================================
3    * Licensed to the Apache Software Foundation (ASF) under one
4    * or more contributor license agreements.  See the NOTICE file
5    * distributed with this work for additional information
6    * regarding copyright ownership.  The ASF licenses this file
7    * to you under the Apache License, Version 2.0 (the
8    * "License"); you may not use this file except in compliance
9    * with 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,
14   * software distributed under the License is distributed on an
15   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
16   * KIND, either express or implied.  See the License for the
17   * specific language governing permissions and limitations
18   * under the License.
19   * ====================================================================
20   *
21   * This software consists of voluntary contributions made by many
22   * individuals on behalf of the Apache Software Foundation.  For more
23   * information on the Apache Software Foundation, please see
24   * <http://www.apache.org/>.
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.AUTH;
37  import org.apache.http.auth.AuthScope;
38  import org.apache.http.auth.Credentials;
39  import org.apache.http.auth.MalformedChallengeException;
40  import org.apache.http.auth.NTCredentials;
41  import org.apache.http.auth.UsernamePasswordCredentials;
42  import org.apache.http.client.AuthCache;
43  import org.apache.http.client.ClientProtocolException;
44  import org.apache.http.client.CookieStore;
45  import org.apache.http.client.CredentialsProvider;
46  import org.apache.http.client.HttpClient;
47  import org.apache.http.client.methods.HttpRequestBase;
48  import org.apache.http.client.protocol.ClientContext;
49  import org.apache.http.config.Registry;
50  import org.apache.http.config.RegistryBuilder;
51  import org.apache.http.conn.socket.ConnectionSocketFactory;
52  import org.apache.http.conn.socket.LayeredConnectionSocketFactory;
53  import org.apache.http.conn.socket.PlainSocketFactory;
54  import org.apache.http.conn.ssl.SSLInitializationException;
55  import org.apache.http.conn.ssl.SSLSocketFactory;
56  import org.apache.http.impl.auth.BasicScheme;
57  import org.apache.http.impl.client.BasicAuthCache;
58  import org.apache.http.impl.client.BasicCredentialsProvider;
59  import org.apache.http.impl.client.HttpClientBuilder;
60  import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
61  import org.apache.http.message.BasicHeader;
62  import org.apache.http.protocol.BasicHttpContext;
63  
64  /**
65   * An Executor for fluent requests
66   * <p/>
67   * A {@link PoolingHttpClientConnectionManager} with maximum 100 connections per route and
68   * a total maximum of 200 connections is used internally.
69   */
70  public class Executor {
71  
72      final static PoolingHttpClientConnectionManager CONNMGR;
73      final static HttpClient CLIENT;
74  
75      static {
76          LayeredConnectionSocketFactory ssl = null;
77          try {
78              ssl = SSLSocketFactory.getSystemSocketFactory();
79          } catch (final 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 (final SecurityException ignore) {
86              } catch (final KeyManagementException ignore) {
87              } catch (final NoSuchAlgorithmException ignore) {
88              }
89          }
90  
91          final Registry<ConnectionSocketFactory> sfr = RegistryBuilder.<ConnectionSocketFactory>create()
92              .register("http", PlainSocketFactory.getSocketFactory())
93              .register("https", ssl != null ? ssl : SSLSocketFactory.getSocketFactory())
94              .build();
95  
96          CONNMGR = new PoolingHttpClientConnectionManager(sfr);
97          CONNMGR.setDefaultMaxPerRoute(100);
98          CONNMGR.setMaxTotal(200);
99          CLIENT = HttpClientBuilder.create().setConnectionManager(CONNMGR).build();
100     }
101 
102     public static Executor newInstance() {
103         return new Executor(CLIENT);
104     }
105 
106     public static Executor newInstance(final HttpClient httpclient) {
107         return new Executor(httpclient != null ? httpclient : CLIENT);
108     }
109 
110     private final HttpClient httpclient;
111     private final BasicHttpContext localContext;
112     private final AuthCache authCache;
113 
114     private CredentialsProvider credentialsProvider;
115     private CookieStore cookieStore;
116 
117     Executor(final HttpClient httpclient) {
118         super();
119         this.httpclient = httpclient;
120         this.localContext = new BasicHttpContext();
121         this.authCache = new BasicAuthCache();
122     }
123 
124     public Executor auth(final AuthScope authScope, final Credentials creds) {
125         if (this.credentialsProvider == null) {
126             this.credentialsProvider = new BasicCredentialsProvider();
127         }
128         this.credentialsProvider.setCredentials(authScope, creds);
129         return this;
130     }
131 
132     public Executor auth(final HttpHost host, final Credentials creds) {
133         final AuthScope authScope = host != null ? new AuthScope(host) : AuthScope.ANY;
134         return auth(authScope, creds);
135     }
136 
137     public Executor authPreemptive(final HttpHost host) {
138         final BasicScheme basicScheme = new BasicScheme();
139         try {
140             basicScheme.processChallenge(new BasicHeader(AUTH.WWW_AUTH, "BASIC "));
141         } catch (final MalformedChallengeException ingnore) {
142         }
143         this.authCache.put(host, basicScheme);
144         return this;
145     }
146 
147     public Executor authPreemptiveProxy(final HttpHost host) {
148         final BasicScheme basicScheme = new BasicScheme();
149         try {
150             basicScheme.processChallenge(new BasicHeader(AUTH.PROXY_AUTH, "BASIC "));
151         } catch (final MalformedChallengeException ingnore) {
152         }
153         this.authCache.put(host, basicScheme);
154         return this;
155     }
156 
157     public Executor auth(final Credentials cred) {
158         return auth(AuthScope.ANY, cred);
159     }
160 
161     public Executor auth(final String username, final String password) {
162         return auth(new UsernamePasswordCredentials(username, password));
163     }
164 
165     public Executor auth(final String username, final String password,
166             final String workstation, final String domain) {
167         return auth(new NTCredentials(username, password, workstation, domain));
168     }
169 
170     public Executor auth(final HttpHost host,
171             final String username, final String password) {
172         return auth(host, new UsernamePasswordCredentials(username, password));
173     }
174 
175     public Executor auth(final HttpHost host,
176             final String username, final String password,
177             final String workstation, final String domain) {
178         return auth(host, new NTCredentials(username, password, workstation, domain));
179     }
180 
181     public Executor clearAuth() {
182         if (this.credentialsProvider != null) {
183             this.credentialsProvider.clear();
184         }
185         return this;
186     }
187 
188     public Executor cookieStore(final CookieStore cookieStore) {
189         this.cookieStore = cookieStore;
190         return this;
191     }
192 
193     public Executor clearCookies() {
194         if (this.cookieStore != null) {
195             this.cookieStore.clear();
196         }
197         return this;
198     }
199 
200     /**
201      * Executes the request. Please Note that response content must be processed
202      * or discarded using {@link Response#discardContent()}, otherwise the
203      * connection used for the request might not be released to the pool.
204      *
205      * @see Response#handleResponse(org.apache.http.client.ResponseHandler)
206      * @see Response#discardContent()
207      */
208     public Response execute(
209             final Request request) throws ClientProtocolException, IOException {
210         this.localContext.setAttribute(ClientContext.CREDS_PROVIDER, this.credentialsProvider);
211         this.localContext.setAttribute(ClientContext.AUTH_CACHE, this.authCache);
212         this.localContext.setAttribute(ClientContext.COOKIE_STORE, this.cookieStore);
213         final HttpRequestBase httprequest = request.getHttpRequest();
214         httprequest.reset();
215         return new Response(this.httpclient.execute(httprequest, this.localContext));
216     }
217 
218     /**
219      * @deprecated (4.3) do not use.
220      */
221     @Deprecated
222     public static void registerScheme(final org.apache.http.conn.scheme.Scheme scheme) {
223     }
224 
225     /**
226      * @deprecated (4.3) do not use.
227      */
228     @Deprecated
229     public static void unregisterScheme(final String name) {
230     }
231 
232 }