~ubuntu-branches/ubuntu/trusty/httpcomponents-core/trusty

« back to all changes in this revision

Viewing changes to httpcore-nio/src/examples/org/apache/http/examples/nio/NHttpSSLClient.java

  • Committer: Bazaar Package Importer
  • Author(s): David Paleino
  • Date: 2010-06-12 08:37:34 UTC
  • Revision ID: james.westby@ubuntu.com-20100612083734-1y8kp6qm4sjk60az
Tags: upstream-4.0.1
ImportĀ upstreamĀ versionĀ 4.0.1

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
/*
 
2
 * $HeadURL: https://svn.apache.org/repos/asf/httpcomponents/httpcore/tags/4.0.1/httpcore-nio/src/examples/org/apache/http/examples/nio/NHttpSSLClient.java $
 
3
 * $Revision: 744516 $
 
4
 * $Date: 2009-02-14 17:38:14 +0100 (Sat, 14 Feb 2009) $
 
5
 *
 
6
 * ====================================================================
 
7
 * Licensed to the Apache Software Foundation (ASF) under one
 
8
 * or more contributor license agreements.  See the NOTICE file
 
9
 * distributed with this work for additional information
 
10
 * regarding copyright ownership.  The ASF licenses this file
 
11
 * to you under the Apache License, Version 2.0 (the
 
12
 * "License"); you may not use this file except in compliance
 
13
 * with the License.  You may obtain a copy of the License at
 
14
 *
 
15
 *   http://www.apache.org/licenses/LICENSE-2.0
 
16
 *
 
17
 * Unless required by applicable law or agreed to in writing,
 
18
 * software distributed under the License is distributed on an
 
19
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 
20
 * KIND, either express or implied.  See the License for the
 
21
 * specific language governing permissions and limitations
 
22
 * under the License.
 
23
 * ====================================================================
 
24
 *
 
25
 * This software consists of voluntary contributions made by many
 
26
 * individuals on behalf of the Apache Software Foundation.  For more
 
27
 * information on the Apache Software Foundation, please see
 
28
 * <http://www.apache.org/>.
 
29
 *
 
30
 */
 
31
package org.apache.http.examples.nio;
 
32
 
 
33
import java.io.IOException;
 
34
import java.io.InterruptedIOException;
 
35
import java.net.InetSocketAddress;
 
36
import java.util.concurrent.CountDownLatch;
 
37
 
 
38
import javax.net.ssl.SSLContext;
 
39
 
 
40
import org.apache.http.HttpEntity;
 
41
import org.apache.http.HttpException;
 
42
import org.apache.http.HttpHost;
 
43
import org.apache.http.HttpRequest;
 
44
import org.apache.http.HttpResponse;
 
45
import org.apache.http.impl.DefaultConnectionReuseStrategy;
 
46
import org.apache.http.impl.nio.SSLClientIOEventDispatch;
 
47
import org.apache.http.impl.nio.reactor.DefaultConnectingIOReactor;
 
48
import org.apache.http.message.BasicHttpRequest;
 
49
import org.apache.http.nio.NHttpConnection;
 
50
import org.apache.http.nio.protocol.BufferingHttpClientHandler;
 
51
import org.apache.http.nio.protocol.EventListener;
 
52
import org.apache.http.nio.protocol.HttpRequestExecutionHandler;
 
53
import org.apache.http.nio.reactor.ConnectingIOReactor;
 
54
import org.apache.http.nio.reactor.IOEventDispatch;
 
55
import org.apache.http.nio.reactor.SessionRequest;
 
56
import org.apache.http.nio.reactor.SessionRequestCallback;
 
57
import org.apache.http.params.BasicHttpParams;
 
58
import org.apache.http.params.CoreConnectionPNames;
 
59
import org.apache.http.params.HttpParams;
 
60
import org.apache.http.params.CoreProtocolPNames;
 
61
import org.apache.http.protocol.BasicHttpProcessor;
 
62
import org.apache.http.protocol.ExecutionContext;
 
63
import org.apache.http.protocol.HttpContext;
 
64
import org.apache.http.protocol.RequestConnControl;
 
65
import org.apache.http.protocol.RequestContent;
 
66
import org.apache.http.protocol.RequestExpectContinue;
 
67
import org.apache.http.protocol.RequestTargetHost;
 
68
import org.apache.http.protocol.RequestUserAgent;
 
69
import org.apache.http.util.EntityUtils;
 
70
 
 
71
/**
 
72
 * Elemental example for executing HTTPS requests using the non-blocking I/O model.
 
73
 * <p>
 
74
 * Please note the purpose of this application is demonstrate the usage of HttpCore APIs.
 
75
 * It is NOT intended to demonstrate the most efficient way of building an HTTP client. 
 
76
 *
 
77
 * 
 
78
 * @version $Revision: 744516 $
 
79
 */
 
80
public class NHttpSSLClient {
 
81
 
 
82
    public static void main(String[] args) throws Exception {
 
83
        HttpParams params = new BasicHttpParams();
 
84
        params
 
85
            .setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 30000)
 
86
            .setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 30000)
 
87
            .setIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, 8 * 1024)
 
88
            .setBooleanParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK, false)
 
89
            .setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true)
 
90
            .setParameter(CoreProtocolPNames.USER_AGENT, "Jakarta-HttpComponents-NIO/1.1");
 
91
 
 
92
        final ConnectingIOReactor ioReactor = new DefaultConnectingIOReactor(2, params);
 
93
 
 
94
        BasicHttpProcessor httpproc = new BasicHttpProcessor();
 
95
        httpproc.addInterceptor(new RequestContent());
 
96
        httpproc.addInterceptor(new RequestTargetHost());
 
97
        httpproc.addInterceptor(new RequestConnControl());
 
98
        httpproc.addInterceptor(new RequestUserAgent());
 
99
        httpproc.addInterceptor(new RequestExpectContinue());
 
100
        
 
101
        // Initialize default SSL context
 
102
        SSLContext sslcontext = SSLContext.getInstance("SSL");
 
103
        sslcontext.init(null, null, null);
 
104
        
 
105
        // We are going to use this object to synchronize between the 
 
106
        // I/O event and main threads
 
107
        CountDownLatch requestCount = new CountDownLatch(3);
 
108
        
 
109
        BufferingHttpClientHandler handler = new BufferingHttpClientHandler(
 
110
                httpproc,
 
111
                new MyHttpRequestExecutionHandler(requestCount),
 
112
                new DefaultConnectionReuseStrategy(),
 
113
                params);
 
114
 
 
115
        handler.setEventListener(new EventLogger());
 
116
        
 
117
        final IOEventDispatch ioEventDispatch = new SSLClientIOEventDispatch(
 
118
                handler,
 
119
                sslcontext,
 
120
                params);
 
121
        
 
122
        Thread t = new Thread(new Runnable() {
 
123
         
 
124
            public void run() {
 
125
                try {
 
126
                    ioReactor.execute(ioEventDispatch);
 
127
                } catch (InterruptedIOException ex) {
 
128
                    System.err.println("Interrupted");
 
129
                } catch (IOException e) {
 
130
                    System.err.println("I/O error: " + e.getMessage());
 
131
                }
 
132
                System.out.println("Shutdown");
 
133
            }
 
134
            
 
135
        });
 
136
        t.start();
 
137
 
 
138
        SessionRequest[] reqs = new SessionRequest[3];
 
139
        reqs[0] = ioReactor.connect(
 
140
                new InetSocketAddress("www.netscape.com", 443), 
 
141
                null, 
 
142
                new HttpHost("www.netscape.com", 443),
 
143
                new MySessionRequestCallback(requestCount));
 
144
        reqs[1] = ioReactor.connect(
 
145
                new InetSocketAddress("www.verisign.com", 443), 
 
146
                null,
 
147
                new HttpHost("www.verisign.com", 443),
 
148
                new MySessionRequestCallback(requestCount));
 
149
        reqs[2] = ioReactor.connect(
 
150
                new InetSocketAddress("www.yahoo.com", 443), 
 
151
                null,
 
152
                new HttpHost("www.yahoo.com", 443),
 
153
                new MySessionRequestCallback(requestCount));
 
154
     
 
155
        // Block until all connections signal
 
156
        // completion of the request execution
 
157
        requestCount.await();
 
158
 
 
159
        System.out.println("Shutting down I/O reactor");
 
160
        
 
161
        ioReactor.shutdown();
 
162
        
 
163
        System.out.println("Done");
 
164
    }
 
165
    
 
166
    static class MyHttpRequestExecutionHandler implements HttpRequestExecutionHandler {
 
167
 
 
168
        private final static String REQUEST_SENT       = "request-sent";
 
169
        private final static String RESPONSE_RECEIVED  = "response-received";
 
170
        
 
171
        private final CountDownLatch requestCount;
 
172
        
 
173
        public MyHttpRequestExecutionHandler(final CountDownLatch requestCount) {
 
174
            super();
 
175
            this.requestCount = requestCount;
 
176
        }
 
177
        
 
178
        public void initalizeContext(final HttpContext context, final Object attachment) {
 
179
            HttpHost targetHost = (HttpHost) attachment;
 
180
            context.setAttribute(ExecutionContext.HTTP_TARGET_HOST, targetHost);
 
181
        }
 
182
 
 
183
        public void finalizeContext(final HttpContext context) {
 
184
            Object flag = context.getAttribute(RESPONSE_RECEIVED);
 
185
            if (flag == null) {
 
186
                // Signal completion of the request execution
 
187
                this.requestCount.countDown();
 
188
            }
 
189
        }
 
190
 
 
191
        public HttpRequest submitRequest(final HttpContext context) {
 
192
            HttpHost targetHost = (HttpHost) context.getAttribute(
 
193
                    ExecutionContext.HTTP_TARGET_HOST);
 
194
            Object token = context.getAttribute(REQUEST_SENT);
 
195
            if (token == null) {
 
196
                // Stick some object into the context
 
197
                context.setAttribute(REQUEST_SENT, Boolean.TRUE);
 
198
 
 
199
                System.out.println("--------------");
 
200
                System.out.println("Sending request to " + targetHost);
 
201
                System.out.println("--------------");
 
202
                
 
203
                return new BasicHttpRequest("GET", "/");
 
204
            } else {
 
205
                // No new request to submit
 
206
                return null;
 
207
            }
 
208
        }
 
209
        
 
210
        public void handleResponse(final HttpResponse response, final HttpContext context) {
 
211
            HttpEntity entity = response.getEntity();
 
212
            try {
 
213
                String content = EntityUtils.toString(entity);
 
214
                
 
215
                System.out.println("--------------");
 
216
                System.out.println(response.getStatusLine());
 
217
                System.out.println("--------------");
 
218
                System.out.println("Document length: " + content.length());
 
219
                System.out.println("--------------");
 
220
            } catch (IOException ex) {
 
221
                System.err.println("I/O error: " + ex.getMessage());
 
222
            }
 
223
 
 
224
            context.setAttribute(RESPONSE_RECEIVED, Boolean.TRUE);
 
225
            
 
226
            // Signal completion of the request execution
 
227
            this.requestCount.countDown();
 
228
        }
 
229
        
 
230
    }
 
231
    
 
232
    static class MySessionRequestCallback implements SessionRequestCallback {
 
233
 
 
234
        private final CountDownLatch requestCount;        
 
235
        
 
236
        public MySessionRequestCallback(final CountDownLatch requestCount) {
 
237
            super();
 
238
            this.requestCount = requestCount;
 
239
        }
 
240
        
 
241
        public void cancelled(final SessionRequest request) {
 
242
            System.out.println("Connect request cancelled: " + request.getRemoteAddress());
 
243
            this.requestCount.countDown();
 
244
        }
 
245
 
 
246
        public void completed(final SessionRequest request) {
 
247
        }
 
248
 
 
249
        public void failed(final SessionRequest request) {
 
250
            System.out.println("Connect request failed: " + request.getRemoteAddress());
 
251
            this.requestCount.countDown();
 
252
        }
 
253
 
 
254
        public void timeout(final SessionRequest request) {
 
255
            System.out.println("Connect request timed out: " + request.getRemoteAddress());
 
256
            this.requestCount.countDown();
 
257
        }
 
258
        
 
259
    }
 
260
    
 
261
    static class EventLogger implements EventListener {
 
262
 
 
263
        public void connectionOpen(final NHttpConnection conn) {
 
264
            System.out.println("Connection open: " + conn);
 
265
        }
 
266
 
 
267
        public void connectionTimeout(final NHttpConnection conn) {
 
268
            System.out.println("Connection timed out: " + conn);
 
269
        }
 
270
 
 
271
        public void connectionClosed(final NHttpConnection conn) {
 
272
            System.out.println("Connection closed: " + conn);
 
273
        }
 
274
 
 
275
        public void fatalIOException(final IOException ex, final NHttpConnection conn) {
 
276
            System.err.println("I/O error: " + ex.getMessage());
 
277
        }
 
278
 
 
279
        public void fatalProtocolException(final HttpException ex, final NHttpConnection conn) {
 
280
            System.err.println("HTTP error: " + ex.getMessage());
 
281
        }
 
282
        
 
283
    }
 
284
 
 
285
}