KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > sun > mail > util > SocketFetcher


1 /*
2  * The contents of this file are subject to the terms
3  * of the Common Development and Distribution License
4  * (the "License"). You may not use this file except
5  * in compliance with the License.
6  *
7  * You can obtain a copy of the license at
8  * glassfish/bootstrap/legal/CDDLv1.0.txt or
9  * https://glassfish.dev.java.net/public/CDDLv1.0.html.
10  * See the License for the specific language governing
11  * permissions and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL
14  * HEADER in each file and include the License file at
15  * glassfish/bootstrap/legal/CDDLv1.0.txt. If applicable,
16  * add the following below this CDDL HEADER, with the
17  * fields enclosed by brackets "[]" replaced with your
18  * own identifying information: Portions Copyright [yyyy]
19  * [name of copyright owner]
20  */

21
22 /*
23  * @(#)SocketFetcher.java 1.17 05/12/08
24  *
25  * Copyright 1998-2005 Sun Microsystems, Inc. All Rights Reserved.
26  */

27
28 package com.sun.mail.util;
29
30 import java.security.*;
31 import java.net.*;
32 import java.io.*;
33 import java.lang.reflect.*;
34 import java.util.Properties JavaDoc;
35 import javax.net.*;
36 import javax.net.ssl.*;
37
38 /**
39  * This class is used to get Sockets. Depending on the arguments passed
40  * it will either return a plain java.net.Socket or dynamically load
41  * the SocketFactory class specified in the classname param and return
42  * a socket created by that SocketFactory.
43  *
44  * @author Max Spivak
45  * @author Bill Shannon
46  */

47 public class SocketFetcher {
48
49     // No one should instantiate this class.
50
private SocketFetcher() {
51     }
52
53     /**
54      * This method returns a Socket. Properties control the use of
55      * socket factories and other socket characteristics. The properties
56      * used are: <p>
57      * <ul>
58      * <li> <i>prefix</i>.socketFactory.class
59      * <li> <i>prefix</i>.socketFactory.fallback
60      * <li> <i>prefix</i>.socketFactory.port
61      * <li> <i>prefix</i>.timeout
62      * <li> <i>prefix</i>.connectiontimeout
63      * <li> <i>prefix</i>.localaddress
64      * <li> <i>prefix</i>.localport
65      * </ul> <p>
66      * If the socketFactory.class property isn't set, the socket
67      * returned is an instance of java.net.Socket connected to the
68      * given host and port. If the socketFactory.class property is set,
69      * it is expected to contain a fully qualified classname of a
70      * javax.net.SocketFactory subclass. In this case, the class is
71      * dynamically instantiated and a socket created by that
72      * SocketFactory is returned. <p>
73      *
74      * If the socketFactory.fallback property is set to false, don't
75      * fall back to using regular sockets if the socket factory fails. <p>
76      *
77      * The socketFactory.port specifies a port to use when connecting
78      * through the socket factory. If unset, the port argument will be
79      * used. <p>
80      *
81      * If the connectiontimeout property is set, we use a separate thread
82      * to make the connection so that we can timeout that connection attempt.
83      * <p>
84      *
85      * If the timeout property is set, it is used to set the socket timeout.
86      * <p>
87      *
88      * If the localaddress property is set, it's used as the local address
89      * to bind to. If the localport property is also set, it's used as the
90      * local port number to bind to.
91      *
92      * @param host The host to connect to
93      * @param port The port to connect to at the host
94      * @param props Properties object containing socket properties
95      * @param prefix Property name prefix, e.g., "mail.imap"
96      * @param useSSL use the SSL socket factory as the default
97      */

98     public static Socket getSocket(String JavaDoc host, int port, Properties JavaDoc props,
99                 String JavaDoc prefix, boolean useSSL)
100                 throws IOException {
101
102     if (prefix == null)
103         prefix = "socket";
104     if (props == null)
105         props = new Properties JavaDoc(); // empty
106
String JavaDoc s = props.getProperty(prefix + ".connectiontimeout", null);
107     int cto = -1;
108     if (s != null) {
109         try {
110         cto = Integer.parseInt(s);
111         } catch (NumberFormatException JavaDoc nfex) { }
112     }
113
114     Socket socket = null;
115     String JavaDoc sfClass =
116         props.getProperty(prefix + ".socketFactory.class", null);
117     String JavaDoc timeout = props.getProperty(prefix + ".timeout", null);
118     String JavaDoc localaddrstr = props.getProperty(prefix + ".localaddress", null);
119     InetAddress localaddr = null;
120     if (localaddrstr != null)
121         localaddr = InetAddress.getByName(localaddrstr);
122     String JavaDoc localportstr = props.getProperty(prefix + ".localport", null);
123     int localport = 0;
124     if (localportstr != null) {
125         try {
126         localport = Integer.parseInt(localportstr);
127         } catch (NumberFormatException JavaDoc nfex) { }
128     }
129
130     if (sfClass != null && sfClass.length() > 0) {
131         // dynamically load the class
132
int sfPort = -1;
133         boolean fb = false;
134         String JavaDoc fallback =
135         props.getProperty(prefix + ".socketFactory.fallback", null);
136         fb = fallback == null || (!fallback.equalsIgnoreCase("false"));
137         String JavaDoc sfPortStr =
138         props.getProperty(prefix + ".socketFactory.port", null);
139         if (sfPortStr != null) {
140         try {
141             sfPort = Integer.parseInt(sfPortStr);
142         } catch (NumberFormatException JavaDoc nfex) { }
143         }
144
145         try {
146         ClassLoader JavaDoc cl = getContextClassLoader();
147         Class JavaDoc clsSockFact = null;
148         if (cl != null) {
149             try {
150             clsSockFact = cl.loadClass(sfClass);
151             } catch (ClassNotFoundException JavaDoc cex) { }
152         }
153         if (clsSockFact == null)
154             clsSockFact = Class.forName(sfClass);
155         // get & invoke the getDefault() method
156
Method mthGetDefault = clsSockFact.getMethod("getDefault",
157                                  new Class JavaDoc[]{});
158         SocketFactory sf = (SocketFactory)
159             mthGetDefault.invoke(new Object JavaDoc(), new Object JavaDoc[]{});
160         // if port passed in via property isn't valid, use param
161
if (sfPort == -1)
162             sfPort = port;
163         socket = createSocket(localaddr, localport,
164                     host, sfPort, cto, sf, useSSL);
165         } catch (SocketTimeoutException sex) {
166         throw sex;
167         } catch (Exception JavaDoc ex) {
168         if (!fb) {
169             if (ex instanceof InvocationTargetException) {
170             Throwable JavaDoc t =
171               ((InvocationTargetException)ex).getTargetException();
172             if (t instanceof Exception JavaDoc)
173                 ex = (Exception JavaDoc)t;
174             }
175             if (ex instanceof IOException)
176             throw (IOException)ex;
177             IOException ioex = new IOException(
178                     "Couldn't connect using \"" + sfClass +
179                     "\" socket factory to host, port: " +
180                     host + ", " + sfPort +
181                     "; Exception: " + ex);
182             ioex.initCause(ex);
183             throw ioex;
184         }
185         }
186     }
187
188     if (socket == null)
189         socket = createSocket(localaddr, localport,
190                 host, port, cto, null, useSSL);
191
192     int to = -1;
193     if (timeout != null) {
194         try {
195         to = Integer.parseInt(timeout);
196         } catch (NumberFormatException JavaDoc nfex) { }
197     }
198     if (to >= 0)
199         socket.setSoTimeout(to);
200
201     return socket;
202     }
203
204     public static Socket getSocket(String JavaDoc host, int port, Properties JavaDoc props,
205                 String JavaDoc prefix) throws IOException {
206     return getSocket(host, port, props, prefix, false);
207     }
208
209     /**
210      * Create a socket with the given local address and connected to
211      * the given host and port. Use the specified connection timeout.
212      * If a socket factory is specified, use it. Otherwise, use the
213      * SSLSocketFactory if useSSL is true.
214      */

215     private static Socket createSocket(InetAddress localaddr, int localport,
216                 String JavaDoc host, int port, int cto,
217                 SocketFactory sf, boolean useSSL)
218                 throws IOException {
219     Socket socket;
220
221     if (sf != null)
222         socket = sf.createSocket();
223     else if (useSSL)
224         socket = SSLSocketFactory.getDefault().createSocket();
225     else
226         socket = new Socket();
227     if (localaddr != null)
228         socket.bind(new InetSocketAddress(localaddr, localport));
229     if (cto >= 0)
230         socket.connect(new InetSocketAddress(host, port), cto);
231     else
232         socket.connect(new InetSocketAddress(host, port));
233     return socket;
234     }
235
236     /**
237      * Start TLS on an existing socket.
238      * Supports the "STARTTLS" command in many protocols.
239      */

240     public static Socket startTLS(Socket socket) throws IOException {
241     InetAddress a = socket.getInetAddress();
242     String JavaDoc host = a.getHostName();
243     int port = socket.getPort();
244 //System.out.println("SocketFetcher: startTLS host " + host + ", port " + port);
245

246     try {
247         SSLSocketFactory ssf =
248         (SSLSocketFactory)SSLSocketFactory.getDefault();
249         socket = ssf.createSocket(socket, host, port, true);
250
251         /*
252          * At least the UW IMAP server insists on only the TLSv1
253          * protocol for STARTTLS, and won't accept the old SSLv2
254          * or SSLv3 protocols. Here we enable only the TLSv1
255          * protocol. XXX - this should probably be parameterized.
256          */

257         ((SSLSocket)socket).setEnabledProtocols(new String JavaDoc[] {"TLSv1"});
258     } catch (Exception JavaDoc ex) {
259         if (ex instanceof InvocationTargetException) {
260         Throwable JavaDoc t =
261           ((InvocationTargetException)ex).getTargetException();
262         if (t instanceof Exception JavaDoc)
263             ex = (Exception JavaDoc)t;
264         }
265         if (ex instanceof IOException)
266         throw (IOException)ex;
267         // wrap anything else before sending it on
268
IOException ioex = new IOException("Exception in startTLS: host " +
269                 host + ", port " + port + "; Exception: " + ex);
270         ioex.initCause(ex);
271         throw ioex;
272     }
273     return socket;
274     }
275
276     /**
277      * Convenience method to get our context class loader.
278      * Assert any privileges we might have and then call the
279      * Thread.getContextClassLoader method.
280      */

281     private static ClassLoader JavaDoc getContextClassLoader() {
282     return (ClassLoader JavaDoc)
283         AccessController.doPrivileged(new PrivilegedAction() {
284         public Object JavaDoc run() {
285         ClassLoader JavaDoc cl = null;
286         try {
287             cl = Thread.currentThread().getContextClassLoader();
288         } catch (SecurityException JavaDoc ex) { }
289         return cl;
290         }
291     });
292     }
293 }
294
Popular Tags