View Javadoc

1   /*
2    *  XNap - A P2P framework and client.
3    *
4    *  See the file AUTHORS for copyright information.
5    *
6    *  This program is free software; you can redistribute it and/or modify
7    *  it under the terms of the GNU General Public License as published by
8    *  the Free Software Foundation.
9    *
10   *  This program is distributed in the hope that it will be useful,
11   *  but WITHOUT ANY WARRANTY; without even the implied warranty of
12   *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13   *  GNU General Public License for more details.
14   *
15   *  You should have received a copy of the GNU General Public License
16   *  along with this program; if not, write to the Free Software
17   *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
18   */
19  
20  package org.xnap.net;
21  
22  import java.io.IOException;
23  import java.net.ConnectException;
24  import java.net.Socket;
25  import java.net.UnknownHostException;
26  
27  import org.apache.log4j.Logger;
28  import org.xnap.XNap;
29  
30  /***
31   * Provides a set of static methods for common network tasks.
32   */
33  public class NetHelper {
34  
35      //--- Data field(s) ---
36  
37      private static Logger logger = Logger.getLogger(NetHelper.class);
38  
39      //--- Method(s) ---
40  
41      /***
42       * Enables the use of a socks proxy at <code>host:port</code>. 
43       *
44       * @param host hostname of the proxy
45       * @param host port of the proxy
46       */
47      public static void enableSocksProxy(String host, int port) {
48  		logger.debug("enabling socks proxy: " + host + ":" + port);
49  
50          System.getProperties().put("socksProxySet", "true");
51          System.getProperties().put("socksProxyHost", host);
52          System.getProperties().put("socksProxyPort", port + "");
53      }
54  
55      /***
56       * Disables the use of a socks proxy.
57       */ 
58      public static void disableSocksProxy() {
59  		logger.debug("disabling socks proxy");
60  
61          System.getProperties().remove("socksProxySet");
62          System.getProperties().remove("socksProxyHost");
63          System.getProperties().remove("socksProxyPort");
64      }
65  
66      /***
67       * Enables the use of a http proxy at <code>host:port</code>. 
68       *
69       * @param host hostname of the proxy
70       * @param host port of the proxy
71       */
72      public static void enableHttpProxy(String host, int port) {
73  		logger.debug("enabling http proxy: " + host + ":" + port);
74  
75          System.getProperties().put("proxySet", "true");
76          System.getProperties().put("proxyHost", host);
77          System.getProperties().put("proxyPort", port + "");
78      }
79  
80      /***
81       * Disables the use of a http proxy.
82       */ 
83      public static void disableHttpProxy() {
84  		logger.debug("disabling http proxy");
85  
86          System.getProperties().remove("proxySet");
87          System.getProperties().remove("proxyHost");
88          System.getProperties().remove("proxyPort");
89      }
90  
91      /***
92       * Returns a sensible error message.
93       */
94      public static String getErrorMessage(IOException e)
95      {
96  		String message = e.getLocalizedMessage();
97  		if (e instanceof ConnectException) {
98  			return XNap.tr("Connection refused");
99  		}
100 		else if (e instanceof UnknownHostException) {
101 			return XNap.tr("Unknown host {0}", 
102 						   (message != null) ? message : "");
103 		}
104 		else {
105 			return XNap.tr("Error ({0})", 
106 						   (message != null) ? message : e.toString());
107 		}
108     }
109 
110 	public static long ipToLongHiFirst(byte[] address)
111 	{
112         if (address.length != 4) {
113             throw new IllegalArgumentException("byte array must be of length 4");
114         }
115 
116         long ipNum = 0;
117         long multiplier = 1;
118         for (int i = 3; i >= 0; i--) {
119             int byteVal = (address[i] + 256) % 256;
120             ipNum += byteVal * multiplier;
121             multiplier *= 256;
122         }
123         return ipNum;
124 	}
125 
126     /***
127      * Converts <code>ip</code> from an integer value to a dotted string
128      * representation.
129      *
130      * @see #toIP(long)
131      */
132     public static String toIP(String ip)
133     {
134 		// int would do (it's 32-bit) but the range is too small
135 		return toIP(Long.parseLong(ip));
136     }
137 
138     /***
139      * Converts <code>ip</code> from an integer value to a dotted string
140      * representation.
141      */
142     public static String toIP(long ip)
143     {
144 		StringBuffer sb = new StringBuffer(4 * 3 + 3);
145 	
146 		sb.append(ip & 0xFF);
147 		sb.append(".");
148 		sb.append((ip >> 8) & 0xFF);
149 		sb.append(".");
150 		sb.append((ip >> 16) & 0xFF);
151 		sb.append(".");
152 		sb.append((ip >> 24) & 0xFF);
153 
154 		return sb.toString();
155     }
156 
157     /***
158      * Converts <code>ip</code> from an integer value to a dotted string
159      * representation.
160      */
161     public static String toIPHiFirst(long ip)
162     {
163 		StringBuffer sb = new StringBuffer(4 * 3 + 3);
164 	
165 		sb.append((ip >> 24) & 0xFF);
166 		sb.append(".");
167 		sb.append((ip >> 16) & 0xFF);
168 		sb.append(".");
169 		sb.append((ip >> 8) & 0xFF);
170 		sb.append(".");
171 		sb.append(ip & 0xFF);
172 
173 		return sb.toString();
174     }
175 
176     public static Socket connect(String host, int port, long timeout)
177 		throws IOException
178     {
179 		SocketConnector runner = new SocketConnector(host, port);
180 		Thread t = new Thread(runner, "SocketRunner " + host + ":" + port);
181 		t.start();
182 
183 		return runner.getSocket(timeout);
184     }
185 
186     //--- Inner Class(es) ---
187 
188     public static class SocketConnector implements Runnable
189     {
190 
191 		String host;
192 		int port;
193 		Socket socket;
194 		boolean done = false;
195 		IOException exception;
196 	
197 		public SocketConnector(String host, int port)
198 		{
199 			this.host = host;
200 			this.port = port;
201 
202 			this.socket = null;
203 		}
204 
205 		public synchronized Socket getSocket(long timeout) throws IOException
206 		{
207 			if (!done) {
208 				try {
209 					this.wait(timeout);
210 				}
211 				catch (InterruptedException e) {
212 				}
213 			}
214 
215 			if (exception != null) {
216 				throw (exception);
217 			}
218 			else if (socket == null) {
219 				throw new IOException(XNap.tr("Socket timeout"));
220 			}
221 			else {
222 				return socket;
223 			}
224 		}
225 
226 		public void run()
227 		{
228 			try {
229 				socket = new Socket(host, port);
230 			}
231 			catch (IOException e) {
232 				this.exception = e;
233 			}
234 
235 			synchronized (this) {
236 				done = true;
237 				this.notify();
238 			}
239 		}
240 
241     }
242 
243 }