KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > h2 > util > NetUtils


1 /*
2  * Copyright 2004-2006 H2 Group. Licensed under the H2 License, Version 1.0 (http://h2database.com/html/license.html).
3  * Initial Developer: H2 Group
4  */

5 package org.h2.util;
6
7 import java.io.IOException JavaDoc;
8 import java.net.BindException JavaDoc;
9 import java.net.InetAddress JavaDoc;
10 import java.net.ServerSocket JavaDoc;
11 import java.net.Socket JavaDoc;
12 import java.sql.SQLException JavaDoc;
13
14 import org.h2.message.Message;
15 import org.h2.security.SecureSocketFactory;
16
17 public class NetUtils {
18     
19     public static Socket JavaDoc createLoopbackSocket(int port, boolean ssl) throws IOException JavaDoc, SQLException JavaDoc {
20         InetAddress JavaDoc address = InetAddress.getByName("127.0.0.1");
21         return createSocket(address, port, ssl);
22     }
23     
24     public static Socket JavaDoc createSocket(InetAddress JavaDoc address, int port, boolean ssl) throws IOException JavaDoc, SQLException JavaDoc {
25         if (ssl) {
26             SecureSocketFactory f = SecureSocketFactory.getInstance();
27             return f.createSocket(address, port);
28         } else {
29             return new Socket JavaDoc(address, port);
30         }
31     }
32     
33     public static ServerSocket JavaDoc createServerSocket(int port, boolean ssl) throws SQLException JavaDoc {
34         try {
35             return createServerSocketTry(port, ssl);
36         } catch(SQLException JavaDoc e) {
37             // try again
38
return createServerSocketTry(port, ssl);
39         }
40     }
41     
42     private static ServerSocket JavaDoc createServerSocketTry(int port, boolean ssl) throws SQLException JavaDoc {
43         // TODO server sockets: maybe automatically open the next port if this is in use?
44
// TODO server sockets: maybe a parameter to allow anonymous ssl?
45
try {
46             if(ssl) {
47                 SecureSocketFactory f = SecureSocketFactory.getInstance();
48                 return f.createServerSocket(port);
49             } else {
50                 return new ServerSocket JavaDoc(port);
51             }
52         } catch(BindException JavaDoc be) {
53             throw Message.getSQLException(Message.EXCEPTION_OPENING_PORT_1, new String JavaDoc[]{""+port}, be);
54         } catch(IOException JavaDoc e) {
55             throw Message.convert(e);
56         }
57     }
58
59     public static boolean isLoopbackAddress(Socket JavaDoc socket) {
60         boolean result = true;
61 //#ifdef JDK14
62
result = socket.getInetAddress().isLoopbackAddress();
63 //#endif
64
return result;
65     }
66
67 }
68
Popular Tags