1 19 package com.mysql.jdbc; 20 21 import java.io.IOException ; 22 23 import java.lang.reflect.Constructor ; 24 import java.lang.reflect.Method ; 25 26 import java.net.Socket ; 27 import java.net.SocketException ; 28 29 import java.util.Properties ; 30 31 32 37 public class StandardSocketFactory implements SocketFactory { 38 39 protected Socket rawSocket = null; 40 41 42 protected String host = null; 43 44 45 protected int port = 3306; 46 47 56 public Socket afterHandshake() throws SocketException , IOException { 57 return rawSocket; 58 } 59 60 70 public Socket beforeHandshake() throws SocketException , IOException { 71 return rawSocket; 72 } 73 74 77 public Socket connect(String host, Properties props) 78 throws SocketException , IOException { 79 if (props != null) { 80 this.host = host; 81 82 String portStr = props.getProperty("PORT"); 83 84 if (portStr != null) { 85 port = Integer.parseInt(portStr); 86 } 87 88 boolean hasConnectTimeoutMethod = false; 89 90 Method connectWithTimeoutMethod = null; 91 92 try { 93 Class socketAddressClass = Class.forName( 95 "java.net.SocketAddress"); 96 97 connectWithTimeoutMethod = Socket .class.getMethod("connect", 98 new Class [] { socketAddressClass, Integer.TYPE }); 99 100 hasConnectTimeoutMethod = true; 101 } catch (NoClassDefFoundError noClassDefFound) { 102 hasConnectTimeoutMethod = false; 103 } catch (NoSuchMethodException noSuchMethodEx) { 104 hasConnectTimeoutMethod = false; 105 } catch (Throwable catchAll) { 106 hasConnectTimeoutMethod = false; 107 } 108 109 int connectTimeout = 0; 110 111 String connectTimeoutStr = props.getProperty("connectTimeout"); 112 113 if (connectTimeoutStr != null) { 114 try { 115 connectTimeout = Integer.parseInt(connectTimeoutStr); 116 } catch (NumberFormatException nfe) { 117 throw new SocketException ("Illegal value '" 118 + connectTimeoutStr + "' for connectTimeout"); 119 } 120 } 121 122 if (this.host != null) { 123 if (!hasConnectTimeoutMethod || (connectTimeout == 0)) { 124 rawSocket = new Socket (this.host, port); 125 } else { 126 try { 129 Class inetSocketAddressClass = Class.forName( 130 "java.net.InetSocketAddress"); 131 Constructor addrConstructor = inetSocketAddressClass 132 .getConstructor(new Class [] { 133 String .class, Integer.TYPE 134 }); 135 136 Object sockAddr = addrConstructor.newInstance(new Object [] { 137 this.host, new Integer (port) 138 }); 139 140 rawSocket = new Socket (); 141 connectWithTimeoutMethod.invoke(rawSocket, 142 new Object [] { sockAddr, new Integer (connectTimeout) }); 143 } catch (Throwable t) { 144 throw new SocketException (t.toString()); 145 } 146 } 147 148 try { 149 rawSocket.setTcpNoDelay(true); 150 } catch (Exception ex) { 151 152 } 153 154 return rawSocket; 155 } 156 } 157 158 throw new SocketException ("Unable to create socket"); 159 } 160 } 161 | Popular Tags |