KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > servicemix > components > http > HttpsInvoker


1 /*
2  * Licensed to the Apache Software Foundation (ASF) under one or more
3  * contributor license agreements. See the NOTICE file distributed with
4  * this work for additional information regarding copyright ownership.
5  * The ASF licenses this file to You under the Apache License, Version 2.0
6  * (the "License"); you may not use this file except in compliance with
7  * the License. You may obtain a copy of the License at
8  *
9  * http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  */

17 package org.apache.servicemix.components.http;
18
19 import java.io.IOException JavaDoc;
20 import java.net.InetAddress JavaDoc;
21 import java.net.InetSocketAddress JavaDoc;
22 import java.net.Socket JavaDoc;
23 import java.net.SocketAddress JavaDoc;
24 import java.net.URI JavaDoc;
25 import java.net.URL JavaDoc;
26 import java.net.UnknownHostException JavaDoc;
27 import java.security.KeyStore JavaDoc;
28
29 import javax.jbi.JBIException;
30 import javax.jbi.messaging.MessageExchange;
31 import javax.jbi.messaging.MessagingException;
32 import javax.jbi.messaging.NormalizedMessage;
33 import javax.net.ssl.KeyManagerFactory;
34 import javax.net.ssl.SSLContext;
35 import javax.net.ssl.SSLSocketFactory;
36 import javax.net.ssl.TrustManagerFactory;
37
38 import org.apache.commons.httpclient.ConnectTimeoutException;
39 import org.apache.commons.httpclient.HostConfiguration;
40 import org.apache.commons.httpclient.HttpClient;
41 import org.apache.commons.httpclient.HttpHost;
42 import org.apache.commons.httpclient.HttpStatus;
43 import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager;
44 import org.apache.commons.httpclient.methods.PostMethod;
45 import org.apache.commons.httpclient.params.HttpConnectionParams;
46 import org.apache.commons.httpclient.protocol.Protocol;
47 import org.apache.commons.httpclient.protocol.ProtocolSocketFactory;
48 import org.apache.commons.httpclient.protocol.SecureProtocolSocketFactory;
49 import org.apache.servicemix.MessageExchangeListener;
50 import org.apache.servicemix.components.util.TransformComponentSupport;
51 import org.mortbay.resource.Resource;
52 import org.springframework.core.io.ClassPathResource;
53
54 /**
55  * Performs HTTP client invocations on a remote HTTP site.
56  *
57  * @version $Revision: 373823 $
58  */

59 public class HttpsInvoker extends TransformComponentSupport implements MessageExchangeListener {
60
61     protected HttpClientMarshaler marshaler = new HttpClientMarshaler();
62     protected MultiThreadedHttpConnectionManager connectionManager = new MultiThreadedHttpConnectionManager();
63     protected HttpClient httpClient = new HttpClient(connectionManager);
64     protected HostConfiguration hostConfiguration = new HostConfiguration();
65     protected String JavaDoc url;
66     protected boolean defaultInOut = true;
67
68     private String JavaDoc keyPassword;
69     private String JavaDoc keyStore;
70     private String JavaDoc keyStorePassword;
71     private String JavaDoc keyStoreType = "JKS"; // type of the key store
72
private String JavaDoc trustStore;
73     private String JavaDoc trustStorePassword;
74     private String JavaDoc trustStoreType = "JKS";
75     private String JavaDoc protocol = "TLS";
76     private String JavaDoc algorithm = "SunX509"; // cert algorithm
77

78     private class CommonsHttpSSLSocketFactory implements SecureProtocolSocketFactory {
79
80         private SSLSocketFactory factory;
81         
82         public CommonsHttpSSLSocketFactory() throws Exception JavaDoc {
83             SSLContext context = SSLContext.getInstance(protocol);
84             KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(algorithm);
85             if (keyStore == null) {
86                 keyStore = System.getProperty("javax.net.ssl.keyStore");
87                 if (keyStore == null) {
88                     throw new IllegalArgumentException JavaDoc("keyStore or system property javax.net.ssl.keyStore must be set");
89                 }
90             }
91             if (keyStore.startsWith("classpath:")) {
92                 try {
93                     String JavaDoc res = keyStore.substring(10);
94                     URL JavaDoc url = new ClassPathResource(res).getURL();
95                     keyStore = url.toString();
96                 } catch (IOException JavaDoc e) {
97                     throw new JBIException("Unable to find keyStore " + keyStore, e);
98                 }
99             }
100             if (keyStorePassword == null) {
101                 keyStorePassword = System.getProperty("javax.net.ssl.keyStorePassword");
102                 if (keyStorePassword == null) {
103                     throw new IllegalArgumentException JavaDoc("keyStorePassword or system property javax.net.ssl.keyStorePassword must be set");
104                 }
105             }
106             if (trustStore == null) {
107                 trustStore = System.getProperty("javax.net.ssl.trustStore");
108             }
109             if (trustStore != null && trustStore.startsWith("classpath:")) {
110                 try {
111                     String JavaDoc res = trustStore.substring(10);
112                     URL JavaDoc url = new ClassPathResource(res).getURL();
113                     trustStore = url.toString();
114                 } catch (IOException JavaDoc e) {
115                     throw new JBIException("Unable to find trustStore " + trustStore, e);
116                 }
117             }
118             if (trustStorePassword == null) {
119                 trustStorePassword = System.getProperty("javax.net.ssl.trustStorePassword");
120                 if (keyStorePassword == null) {
121                     throw new IllegalArgumentException JavaDoc("trustStorePassword or system property javax.net.ssl.trustStorePassword must be set");
122                 }
123             }
124             KeyStore JavaDoc ks = KeyStore.getInstance(keyStoreType);
125             ks.load(Resource.newResource(keyStore).getInputStream(), keyStorePassword.toCharArray());
126             keyManagerFactory.init(ks, keyPassword != null ? keyPassword.toCharArray() : keyStorePassword.toCharArray());
127             if (trustStore != null) {
128                 KeyStore JavaDoc ts = KeyStore.getInstance(trustStoreType);
129                 ts.load(Resource.newResource(trustStore).getInputStream(), trustStorePassword.toCharArray());
130                 TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(algorithm);
131                 trustManagerFactory.init(ts);
132                 context.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), new java.security.SecureRandom JavaDoc());
133             } else {
134                 context.init(keyManagerFactory.getKeyManagers(), null, new java.security.SecureRandom JavaDoc());
135             }
136             factory = context.getSocketFactory();
137         }
138         
139         public Socket JavaDoc createSocket(Socket JavaDoc socket, String JavaDoc host, int port, boolean autoClose) throws IOException JavaDoc, UnknownHostException JavaDoc {
140             return factory.createSocket(socket, host, port, autoClose);
141         }
142
143         public Socket JavaDoc createSocket(String JavaDoc host, int port, InetAddress JavaDoc localAddress, int localPort) throws IOException JavaDoc, UnknownHostException JavaDoc {
144             return factory.createSocket(host, port, localAddress, localPort);
145         }
146
147         public Socket JavaDoc createSocket(String JavaDoc host, int port, InetAddress JavaDoc localAddress, int localPort, HttpConnectionParams params) throws IOException JavaDoc, UnknownHostException JavaDoc, ConnectTimeoutException {
148             if (params == null) {
149                 throw new IllegalArgumentException JavaDoc("Parameters may not be null");
150             }
151             int timeout = params.getConnectionTimeout();
152             if (timeout == 0) {
153                 return createSocket(host, port, localAddress, localPort);
154             } else {
155                 Socket JavaDoc socket = factory.createSocket();
156                 SocketAddress JavaDoc localaddr = new InetSocketAddress JavaDoc(localAddress, localPort);
157                 SocketAddress JavaDoc remoteaddr = new InetSocketAddress JavaDoc(host, port);
158                 socket.bind(localaddr);
159                 socket.connect(remoteaddr, timeout);
160                 return socket;
161             }
162         }
163
164         public Socket JavaDoc createSocket(String JavaDoc host, int port) throws IOException JavaDoc, UnknownHostException JavaDoc {
165             return factory.createSocket(host, port);
166         }
167         
168     }
169     
170     protected void init() throws JBIException {
171         super.init();
172         try {
173             URI JavaDoc uri = new URI JavaDoc(url);
174             ProtocolSocketFactory sf = new CommonsHttpSSLSocketFactory();
175             Protocol protocol = new Protocol("https", sf, 443);
176             HttpHost host = new HttpHost(uri.getHost(), uri.getPort(), protocol);
177             hostConfiguration.setHost(host);
178         } catch (Exception JavaDoc e) {
179             throw new JBIException("Unable to initialize HttpsInvoker", e);
180         }
181     }
182     
183     public void stop() throws JBIException {
184         super.stop();
185         connectionManager.shutdown();
186     }
187
188     protected boolean transform(MessageExchange exchange, NormalizedMessage in, NormalizedMessage out) throws MessagingException {
189         String JavaDoc url;
190         // We need to relativize the method url to the host config
191
// so that the hostConfiguration is not overriden by the executeMethod call
192
try {
193             java.net.URI JavaDoc uri = new URI JavaDoc(this.url);
194             uri = uri.relativize(new URI JavaDoc(hostConfiguration.getHostURL()));
195             url = uri.toString();
196         } catch (Exception JavaDoc e1) {
197             url = this.url;
198         }
199         PostMethod method = new PostMethod(url);
200         try {
201             marshaler.fromNMS(method, exchange, in);
202             if (method.getRequestHeader("Content-Type") == null) {
203                 method.setRequestHeader("Content-Type", "text/html; charset=UTF-8");
204             }
205             int response = httpClient.executeMethod(hostConfiguration, method);
206
207             if (response != HttpStatus.SC_OK && response != HttpStatus.SC_ACCEPTED) {
208                 throw new InvalidStatusResponseException(response);
209             }
210
211             // now lets grab the output and set it on the out message
212
if (defaultInOut) {
213                 marshaler.toNMS(out, method);
214             }
215             return defaultInOut;
216         }
217         catch (Exception JavaDoc e) {
218             throw new MessagingException("Error executing http request", e);
219         }
220         finally {
221             method.releaseConnection();
222         }
223     }
224
225     public HttpClient getHttpClient() {
226         return httpClient;
227     }
228
229     public void setHttpClient(HttpClient httpClient) {
230         this.httpClient = httpClient;
231     }
232
233     public String JavaDoc getUrl() {
234         return url;
235     }
236
237     public void setUrl(String JavaDoc url) {
238         this.url = url;
239     }
240
241     public boolean isDefaultInOut() {
242         return defaultInOut;
243     }
244
245     public void setDefaultInOut(boolean defaultInOut) {
246         this.defaultInOut = defaultInOut;
247     }
248
249     public HttpClientMarshaler getMarshaler() {
250         return marshaler;
251     }
252
253     public void setMarshaler(HttpClientMarshaler marshaler) {
254         this.marshaler = marshaler;
255     }
256
257     /**
258      * @return Returns the algorithm.
259      */

260     public String JavaDoc getAlgorithm() {
261         return algorithm;
262     }
263
264     /**
265      * @param algorithm The algorithm to set.
266      */

267     public void setAlgorithm(String JavaDoc algorithm) {
268         this.algorithm = algorithm;
269     }
270
271     /**
272      * @return Returns the keyPassword.
273      */

274     public String JavaDoc getKeyPassword() {
275         return keyPassword;
276     }
277
278     /**
279      * @param keyPassword The keyPassword to set.
280      */

281     public void setKeyPassword(String JavaDoc keyPassword) {
282         this.keyPassword = keyPassword;
283     }
284
285     /**
286      * @return Returns the keyStore.
287      */

288     public String JavaDoc getKeyStore() {
289         return keyStore;
290     }
291
292     /**
293      * @param keyStore The keyStore to set.
294      */

295     public void setKeyStore(String JavaDoc keyStore) {
296         this.keyStore = keyStore;
297     }
298
299     /**
300      * @return Returns the keyStorePassword.
301      */

302     public String JavaDoc getKeyStorePassword() {
303         return keyStorePassword;
304     }
305
306     /**
307      * @param keyStorePassword The keyStorePassword to set.
308      */

309     public void setKeyStorePassword(String JavaDoc keyStorePassword) {
310         this.keyStorePassword = keyStorePassword;
311     }
312
313     /**
314      * @return Returns the keyStoreType.
315      */

316     public String JavaDoc getKeyStoreType() {
317         return keyStoreType;
318     }
319
320     /**
321      * @param keyStoreType The keyStoreType to set.
322      */

323     public void setKeyStoreType(String JavaDoc keyStoreType) {
324         this.keyStoreType = keyStoreType;
325     }
326
327     /**
328      * @return Returns the protocol.
329      */

330     public String JavaDoc getProtocol() {
331         return protocol;
332     }
333
334     /**
335      * @param protocol The protocol to set.
336      */

337     public void setProtocol(String JavaDoc protocol) {
338         this.protocol = protocol;
339     }
340
341     /**
342      * @return Returns the trustStore.
343      */

344     public String JavaDoc getTrustStore() {
345         return trustStore;
346     }
347
348     /**
349      * @param trustStore The trustStore to set.
350      */

351     public void setTrustStore(String JavaDoc trustStore) {
352         this.trustStore = trustStore;
353     }
354
355     /**
356      * @return Returns the trustStorePassword.
357      */

358     public String JavaDoc getTrustStorePassword() {
359         return trustStorePassword;
360     }
361
362     /**
363      * @param trustStorePassword The trustStorePassword to set.
364      */

365     public void setTrustStorePassword(String JavaDoc trustStorePassword) {
366         this.trustStorePassword = trustStorePassword;
367     }
368
369     /**
370      * @return Returns the trustStoreType.
371      */

372     public String JavaDoc getTrustStoreType() {
373         return trustStoreType;
374     }
375
376     /**
377      * @param trustStoreType The trustStoreType to set.
378      */

379     public void setTrustStoreType(String JavaDoc trustStoreType) {
380         this.trustStoreType = trustStoreType;
381     }
382
383 }
384
Popular Tags