Initial revision

From-SVN: r102074
This commit is contained in:
Tom Tromey 2005-07-16 00:30:23 +00:00
parent 6f4434b39b
commit f911ba985a
4557 changed files with 1000262 additions and 0 deletions

View file

@ -0,0 +1,313 @@
/* Authenticator.java -- Abstract class for obtaining authentication info
Copyright (C) 1998, 2000, 2003 Free Software Foundation, Inc.
This file is part of GNU Classpath.
GNU Classpath is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2, or (at your option)
any later version.
GNU Classpath is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with GNU Classpath; see the file COPYING. If not, write to the
Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301 USA.
Linking this library statically or dynamically with other modules is
making a combined work based on this library. Thus, the terms and
conditions of the GNU General Public License cover the whole
combination.
As a special exception, the copyright holders of this library give you
permission to link this library with independent modules to produce an
executable, regardless of the license terms of these independent
modules, and to copy and distribute the resulting executable under
terms of your choice, provided that you also meet, for each linked
independent module, the terms and conditions of the license of that
module. An independent module is a module which is not derived from
or based on this library. If you modify this library, you may extend
this exception to your version of the library, but you are not
obligated to do so. If you do not wish to do so, delete this
exception statement from your version. */
package java.net;
/**
* This abstract class provides a model for obtaining authentication
* information (in the form of a username and password) required by
* some network operations (such as hitting a password protected
* web site).
* <p>
* To make use of this feature, a programmer must create a subclass
* that knows how to obtain the necessary info. An example
* would be a class that popped up a dialog box to prompt the user.
* After creating an instance of that subclass, the static
* <code>setDefault</code> method of this class is called to set up
* that instance as the object to use on subsequent calls to obtain
* authorization.
*
* @since 1.2
*
* @author Aaron M. Renn (arenn@urbanophile.com)
* @status Believed to be JDK 1.4 complete
*/
public abstract class Authenticator
{
/*
* Class Variables
*/
/**
* This is the default Authenticator object to use for password requests
*/
private static Authenticator defaultAuthenticator;
/*
* Instance Variables
*/
/**
* The hostname of the site requesting authentication
*/
private String host;
/**
* InternetAddress of the site requesting authentication
*/
private InetAddress addr;
/**
* The port number of the site requesting authentication
*/
private int port;
/**
* The protocol name of the site requesting authentication
*/
private String protocol;
/**
* The prompt to display to the user when requesting authentication info
*/
private String prompt;
/**
* The authentication scheme in use
*/
private String scheme;
/*
* Class Methods
*/
/**
* This method sets the default <code>Authenticator</code> object (an
* instance of a subclass of <code>Authenticator</code>) to use when
* prompting the user for
* information. Note that this method checks to see if the caller is
* allowed to set this value (the "setDefaultAuthenticator" permission)
* and throws a <code>SecurityException</code> if it is not.
*
* @param defAuth The new default <code>Authenticator</code> object to use
*
* @exception SecurityException If the caller does not have permission
* to perform this operation
*/
public static void setDefault(Authenticator defAuth)
{
SecurityManager sm = System.getSecurityManager();
if (sm != null)
sm.checkPermission(new NetPermission("setDefaultAuthenticator"));
defaultAuthenticator = defAuth;
}
/**
* This method is called whenever a username and password for a given
* network operation is required. First, a security check is made to see
* if the caller has the "requestPasswordAuthentication"
* permission. If not, the method thows an exception. If there is no
* default <code>Authenticator</code> object, the method then returns
* <code>null</code>. Otherwise, the default authenticators's instance
* variables are initialized and it's <code>getPasswordAuthentication</code>
* method is called to get the actual authentication information to return.
*
* @param addr The address requesting authentication
* @param port The port requesting authentication
* @param protocol The protocol requesting authentication
* @param prompt The prompt to display to the user when requesting
* authentication info
* @param scheme The authentication scheme in use
*
* @return A <code>PasswordAuthentication</code> object with the user's
* authentication info.
*
* @exception SecurityException If the caller does not have permission to
* perform this operation
*/
public static PasswordAuthentication requestPasswordAuthentication(InetAddress addr,
int port,
String protocol,
String prompt,
String scheme)
throws SecurityException
{
return requestPasswordAuthentication(null, addr, port, protocol, prompt,
scheme);
}
/**
* This method is called whenever a username and password for a given
* network operation is required. First, a security check is made to see
* if the caller has the "requestPasswordAuthentication"
* permission. If not, the method thows an exception. If there is no
* default <code>Authenticator</code> object, the method then returns
* <code>null</code>. Otherwise, the default authenticators's instance
* variables are initialized and it's <code>getPasswordAuthentication</code>
* method is called to get the actual authentication information to return.
* This method is the preferred one as it can be used with hostname
* when addr is unknown.
*
* @param host The hostname requesting authentication
* @param addr The address requesting authentication
* @param port The port requesting authentication
* @param protocol The protocol requesting authentication
* @param prompt The prompt to display to the user when requesting
* authentication info
* @param scheme The authentication scheme in use
*
* @return A <code>PasswordAuthentication</code> object with the user's
* authentication info.
*
* @exception SecurityException If the caller does not have permission to
* perform this operation
*
* @since 1.4
*/
public static PasswordAuthentication requestPasswordAuthentication(String host,
InetAddress addr,
int port,
String protocol,
String prompt,
String scheme)
throws SecurityException
{
SecurityManager sm = System.getSecurityManager();
if (sm != null)
sm.checkPermission(new NetPermission("requestPasswordAuthentication"));
if (defaultAuthenticator == null)
return null;
defaultAuthenticator.host = host;
defaultAuthenticator.addr = addr;
defaultAuthenticator.port = port;
defaultAuthenticator.protocol = protocol;
defaultAuthenticator.prompt = prompt;
defaultAuthenticator.scheme = scheme;
return defaultAuthenticator.getPasswordAuthentication();
}
/*
* Constructors
*/
/**
* Default, no-argument constructor for subclasses to call.
*/
public Authenticator()
{
}
/*
* Instance Methods
*/
/**
* This method returns the address of the site that is requesting
* authentication.
*
* @return The requesting site's address
*/
protected final InetAddress getRequestingSite()
{
return addr;
}
/**
* Returns the hostname of the host or proxy requesting authorization,
* or <code>null</code> if not available.
*
* @return The name of the host requesting authentication, or
* <code>null</code> if it is not available.
*
* @since 1.4
*/
protected final String getRequestingHost()
{
return host;
}
/**
* This method returns the port of the site that is requesting
* authentication.
*
* @return The requesting port
*/
protected final int getRequestingPort()
{
return port;
}
/**
* This method returns the requesting protocol of the operation that is
* requesting authentication
*
* @return The requesting protocol
*/
protected final String getRequestingProtocol()
{
return protocol;
}
/**
* Returns the prompt that should be used when requesting authentication
* information from the user
*
* @return The user prompt
*/
protected final String getRequestingPrompt()
{
return prompt;
}
/**
* This method returns the authentication scheme in use
*
* @return The authentication scheme
*/
protected final String getRequestingScheme()
{
return scheme;
}
/**
* This method is called whenever a request for authentication is made. It
* can call the other getXXX methods to determine the information relevant
* to this request. Subclasses should override this method, which returns
* <code>null</code> by default.
*
* @return The <code>PasswordAuthentication</code> information
*/
protected PasswordAuthentication getPasswordAuthentication()
{
return null;
}
} // class Authenticator

View file

@ -0,0 +1,74 @@
/* BindException.java -- An exception occurred while binding to a socket
Copyright (C) 1998, 1999, 2000, 2001, 2002 Free Software Foundation, Inc.
This file is part of GNU Classpath.
GNU Classpath is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2, or (at your option)
any later version.
GNU Classpath is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with GNU Classpath; see the file COPYING. If not, write to the
Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301 USA.
Linking this library statically or dynamically with other modules is
making a combined work based on this library. Thus, the terms and
conditions of the GNU General Public License cover the whole
combination.
As a special exception, the copyright holders of this library give you
permission to link this library with independent modules to produce an
executable, regardless of the license terms of these independent
modules, and to copy and distribute the resulting executable under
terms of your choice, provided that you also meet, for each linked
independent module, the terms and conditions of the license of that
module. An independent module is a module which is not derived from
or based on this library. If you modify this library, you may extend
this exception to your version of the library, but you are not
obligated to do so. If you do not wish to do so, delete this
exception statement from your version. */
package java.net;
/**
* This exception indicates that an error occurred while attempting to bind
* socket to a particular port.
*
* @author Aaron M. Renn (arenn@urbanophile.com)
* @author Warren Levy (warrenl@cygnus.com)
* @since 1.1
* @status updated to 1.4
*/
public class BindException extends SocketException
{
/**
* Compatible with JDK 1.1+.
*/
private static final long serialVersionUID = -5945005768251722951L;
/**
* Create a new instance without a descriptive error message.
*/
public BindException()
{
}
/**
* Create a new instance with a descriptive error message, such as the
* text from strerror(3).
*
* @param message a message describing the error that occurred
*/
public BindException(String message)
{
super(message);
}
} // class BindException

View file

@ -0,0 +1,75 @@
/* ConnectException.java -- An exception occurred while connecting to a host
Copyright (C) 1998, 1999, 2000, 2001, 2002 Free Software Foundation, Inc.
This file is part of GNU Classpath.
GNU Classpath is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2, or (at your option)
any later version.
GNU Classpath is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with GNU Classpath; see the file COPYING. If not, write to the
Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301 USA.
Linking this library statically or dynamically with other modules is
making a combined work based on this library. Thus, the terms and
conditions of the GNU General Public License cover the whole
combination.
As a special exception, the copyright holders of this library give you
permission to link this library with independent modules to produce an
executable, regardless of the license terms of these independent
modules, and to copy and distribute the resulting executable under
terms of your choice, provided that you also meet, for each linked
independent module, the terms and conditions of the license of that
module. An independent module is a module which is not derived from
or based on this library. If you modify this library, you may extend
this exception to your version of the library, but you are not
obligated to do so. If you do not wish to do so, delete this
exception statement from your version. */
package java.net;
/**
* This exception indicates that an error occurred while attempting to
* connect to a remote host. Often this indicates that the remote host
* refused the connection (ie, is not listening on the target socket).
*
* @author Aaron M. Renn (arenn@urbanophile.com)
* @author Warren Levy (warrenl@cygnus.com)
* @since 1.1
* @status updated to 1.4
*/
public class ConnectException extends SocketException
{
/**
* Compatible with JDK 1.1+.
*/
private static final long serialVersionUID = 3831404271622369215L;
/**
* Create a new instance without a descriptive error message.
*/
public ConnectException()
{
}
/**
* Create a new instance with a descriptive error message, such as the
* text from strerror(3).
*
* @param message a message describing the error that occurred
*/
public ConnectException(String message)
{
super(message);
}
} // class ConnectException

View file

@ -0,0 +1,126 @@
/* ContentHandler.java -- Abstract class for handling content from URL's
Copyright (C) 1998, 1999, 2000, 2001, 2003 Free Software Foundation, Inc.
This file is part of GNU Classpath.
GNU Classpath is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2, or (at your option)
any later version.
GNU Classpath is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with GNU Classpath; see the file COPYING. If not, write to the
Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301 USA.
Linking this library statically or dynamically with other modules is
making a combined work based on this library. Thus, the terms and
conditions of the GNU General Public License cover the whole
combination.
As a special exception, the copyright holders of this library give you
permission to link this library with independent modules to produce an
executable, regardless of the license terms of these independent
modules, and to copy and distribute the resulting executable under
terms of your choice, provided that you also meet, for each linked
independent module, the terms and conditions of the license of that
module. An independent module is a module which is not derived from
or based on this library. If you modify this library, you may extend
this exception to your version of the library, but you are not
obligated to do so. If you do not wish to do so, delete this
exception statement from your version. */
package java.net;
import java.io.IOException;
/**
* Written using on-line Java Platform 1.2 API Specification, as well
* as "The Java Class Libraries", 2nd edition (Addison-Wesley, 1998).
* Status: Believed complete and correct.
*/
/**
* This is an abstract class that is the superclass for classes that read
* objects from URL's. Calling the <code>getContent()</code> method in the
* <code>URL</code> class or the <code>URLConnection</code> class will cause
* an instance of a subclass of <code>ContentHandler</code> to be created for
* the MIME type of the object being downloaded from the URL. Thus, this
* class is seldom needed by applications/applets directly, but only
* indirectly through methods in other classes.
*
* @author Aaron M. Renn (arenn@urbanophile.com)
* @author Warren Levy (warrenl@cygnus.com)
*/
public abstract class ContentHandler
{
/*
* Constructors
*/
/**
* Default, no-argument constructor.
*/
public ContentHandler()
{
}
/*
* Instance Methods
*/
/**
* This method reads from the <code>InputStream</code> of the passed in URL
* connection and uses the data downloaded to create an <code>Object</code>
* represening the content. For example, if the URL is pointing to a GIF
* file, this method might return an <code>Image</code> object. This method
* must be implemented by subclasses.
*
* @param urlc A <code>URLConnection</code> object to read data from.
*
* @return An object representing the data read
*
* @exception IOException If an error occurs
*/
public abstract Object getContent(URLConnection urlc)
throws IOException;
/**
* This method reads from the <code>InputStream</code> of the passed in URL
* connection and uses the data downloaded to create an <code>Object</code>
* represening the content. For example, if the URL is pointing to a GIF
* file, this method might return an <code>Image</code> object. This method
* must be implemented by subclasses. This method uses the list of
* supplied classes as candidate types. If the data read doesn't match
* any of the supplied type, <code>null</code> is returned.
*
* @param urlc A <code>URLConnection</code> object to read data from.
* @param classes An array of types of objects that are candidate types
* for the data to be read.
*
* @return An object representing the data read, or <code>null</code>
* if the data does not match any of the candidate types.
*
* @exception IOException If an error occurs
*
* @since 1.3
*/
public Object getContent(URLConnection urlc, Class[] classes)
throws IOException
{
Object obj = getContent(urlc);
for (int i = 0; i < classes.length; i++)
{
if (classes[i].isInstance(obj))
return obj;
}
return null;
}
} // class ContentHandler

View file

@ -0,0 +1,65 @@
/* ContentHandlerFactory.java -- Interface for creating content handlers
Copyright (C) 1998, 1999, 2000, 2001, 2003 Free Software Foundation, Inc.
This file is part of GNU Classpath.
GNU Classpath is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2, or (at your option)
any later version.
GNU Classpath is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with GNU Classpath; see the file COPYING. If not, write to the
Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301 USA.
Linking this library statically or dynamically with other modules is
making a combined work based on this library. Thus, the terms and
conditions of the GNU General Public License cover the whole
combination.
As a special exception, the copyright holders of this library give you
permission to link this library with independent modules to produce an
executable, regardless of the license terms of these independent
modules, and to copy and distribute the resulting executable under
terms of your choice, provided that you also meet, for each linked
independent module, the terms and conditions of the license of that
module. An independent module is a module which is not derived from
or based on this library. If you modify this library, you may extend
this exception to your version of the library, but you are not
obligated to do so. If you do not wish to do so, delete this
exception statement from your version. */
package java.net;
/**
* Written using on-line Java Platform 1.2 API Specification, as well
* as "The Java Class Libraries", 2nd edition (Addison-Wesley, 1998).
* Status: Believed complete and correct.
*/
/**
* This interface maps MIME types to <code>ContentHandler</code> objects.
* It consists of one method that, when passed a MIME type, returns a
* handler for that type.
*
* @author Aaron M. Renn (arenn@urbanophile.com)
* @author Warren Levy (warrenl@cygnus.com)
*/
public interface ContentHandlerFactory
{
/**
* This method is passed a MIME type as a string and is responsible for
* returning the appropriate <code>ContentHandler</code> object.
*
* @param mimeType The MIME type to map to a <code>ContentHandler</code>
*
* @return The <code>ContentHandler</code> for the passed in MIME type
*/
ContentHandler createContentHandler(String mimeType);
} // interface ContentHandlerFactory

View file

@ -0,0 +1,391 @@
/* DatagramPacket.java -- Class to model a packet to be sent via UDP
Copyright (C) 1998, 1999, 2000, 2001 Free Software Foundation, Inc.
This file is part of GNU Classpath.
GNU Classpath is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2, or (at your option)
any later version.
GNU Classpath is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with GNU Classpath; see the file COPYING. If not, write to the
Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301 USA.
Linking this library statically or dynamically with other modules is
making a combined work based on this library. Thus, the terms and
conditions of the GNU General Public License cover the whole
combination.
As a special exception, the copyright holders of this library give you
permission to link this library with independent modules to produce an
executable, regardless of the license terms of these independent
modules, and to copy and distribute the resulting executable under
terms of your choice, provided that you also meet, for each linked
independent module, the terms and conditions of the license of that
module. An independent module is a module which is not derived from
or based on this library. If you modify this library, you may extend
this exception to your version of the library, but you are not
obligated to do so. If you do not wish to do so, delete this
exception statement from your version. */
package java.net;
/*
* Written using on-line Java Platform 1.2 API Specification, as well
* as "The Java Class Libraries", 2nd edition (Addison-Wesley, 1998).
* Status: Believed complete and correct.
*/
/**
* This class models a packet of data that is to be sent across the network
* using a connectionless protocol such as UDP. It contains the data
* to be send, as well as the destination address and port. Note that
* datagram packets can arrive in any order and are not guaranteed to be
* delivered at all.
* <p>
* This class can also be used for receiving data from the network.
* <p>
* Note that for all method below where the buffer length passed by the
* caller cannot exceed the actually length of the byte array passed as
* the buffer, if this condition is not true, then the method silently
* reduces the length value to maximum allowable value.
*
* Written using on-line Java Platform 1.2 API Specification, as well
* as "The Java Class Libraries", 2nd edition (Addison-Wesley, 1998).
* Status: Believed complete and correct.
*
* @author Warren Levy (warrenl@cygnus.com)
* @author Aarom M. Renn (arenn@urbanophile.com) (Documentation comments)
* @date April 28, 1999.
*/
public final class DatagramPacket
{
/**
* The data buffer to send
*/
private byte[] buffer;
/**
* This is the offset into the buffer to start sending from or receiving to.
*/
private int offset;
/**
* The length of the data buffer to send.
*/
int length;
/**
* The maximal length of the buffer.
*/
int maxlen;
/**
* The address to which the packet should be sent or from which it
* was received.
*/
private InetAddress address;
/**
* The port to which the packet should be sent or from which it was
* was received.
*/
private int port;
/**
* This method initializes a new instance of <code>DatagramPacket</code>
* which has the specified buffer, offset, and length.
*
* @param buf The buffer for holding the incoming datagram.
* @param offset The offset into the buffer to start writing.
* @param length The maximum number of bytes to read.
*
* @since 1.2
*/
public DatagramPacket(byte[] buf, int offset, int length)
{
setData(buf, offset, length);
address = null;
port = -1;
}
/**
* Initializes a new instance of <code>DatagramPacket</code> for
* receiving packets from the network.
*
* @param buf A buffer for storing the returned packet data
* @param length The length of the buffer (must be &lt;= buf.length)
*/
public DatagramPacket(byte[] buf, int length)
{
this(buf, 0, length);
}
/**
* Initializes a new instance of <code>DatagramPacket</code> for
* transmitting packets across the network.
*
* @param buf A buffer containing the data to send
* @param offset The offset into the buffer to start writing from.
* @param length The length of the buffer (must be &lt;= buf.length)
* @param address The address to send to
* @param port The port to send to
*
* @since 1.2
*/
public DatagramPacket(byte[] buf, int offset, int length,
InetAddress address, int port)
{
setData(buf, offset, length);
setAddress(address);
setPort(port);
}
/**
* Initializes a new instance of <code>DatagramPacket</code> for
* transmitting packets across the network.
*
* @param buf A buffer containing the data to send
* @param length The length of the buffer (must be &lt;= buf.length)
* @param address The address to send to
* @param port The port to send to
*/
public DatagramPacket(byte[] buf, int length, InetAddress address, int port)
{
this(buf, 0, length, address, port);
}
/**
* Initializes a new instance of <code>DatagramPacket</code> for
* transmitting packets across the network.
*
* @param buf A buffer containing the data to send
* @param offset The offset into the buffer to start writing from.
* @param length The length of the buffer (must be &lt;= buf.length)
* @param address The socket address to send to
*
* @exception SocketException If an error occurs
* @exception IllegalArgumentException If address type is not supported
*
* @since 1.4
*/
public DatagramPacket(byte[] buf, int offset, int length,
SocketAddress address) throws SocketException
{
if (! (address instanceof InetSocketAddress))
throw new IllegalArgumentException("unsupported address type");
InetSocketAddress tmp = (InetSocketAddress) address;
setData(buf, offset, length);
setAddress(tmp.getAddress());
setPort(tmp.getPort());
}
/**
* Initializes a new instance of <code>DatagramPacket</code> for
* transmitting packets across the network.
*
* @param buf A buffer containing the data to send
* @param length The length of the buffer (must be &lt;= buf.length)
* @param address The socket address to send to
*
* @exception SocketException If an error occurs
* @exception IllegalArgumentException If address type is not supported
*
* @since 1.4
*/
public DatagramPacket(byte[] buf, int length, SocketAddress address)
throws SocketException
{
this(buf, 0, length, address);
}
/**
* Returns the address that this packet is being sent to or, if it was used
* to receive a packet, the address that is was received from. If the
* constructor that doesn not take an address was used to create this object
* and no packet was actually read into this object, then this method
* returns <code>null</code>.
*
* @return The address for this packet.
*/
public synchronized InetAddress getAddress()
{
return address;
}
/**
* Returns the port number this packet is being sent to or, if it was used
* to receive a packet, the port that it was received from. If the
* constructor that doesn not take an address was used to create this object
* and no packet was actually read into this object, then this method
* will return 0.
*
* @return The port number for this packet
*/
public synchronized int getPort()
{
return port;
}
/**
* Returns the data buffer for this packet
*
* @return This packet's data buffer
*/
public synchronized byte[] getData()
{
return buffer;
}
/**
* This method returns the current offset value into the data buffer
* where data will be sent from.
*
* @return The buffer offset.
*
* @since 1.2
*/
public synchronized int getOffset()
{
return offset;
}
/**
* Returns the length of the data in the buffer
*
* @return The length of the data
*/
public synchronized int getLength()
{
return length;
}
/**
* This sets the address to which the data packet will be transmitted.
*
* @param address The destination address
*
* @since 1.1
*/
public synchronized void setAddress(InetAddress address)
{
this.address = address;
}
/**
* This sets the port to which the data packet will be transmitted.
*
* @param port The destination port
*
* @since 1.1
*/
public synchronized void setPort(int port)
{
if (port < 0 || port > 65535)
throw new IllegalArgumentException("Invalid port: " + port);
this.port = port;
}
/**
* Sets the address of the remote host this package will be sent
*
* @param address The socket address of the remove host
*
* @exception IllegalArgumentException If address type is not supported
*
* @since 1.4
*/
public void setSocketAddress(SocketAddress address)
throws IllegalArgumentException
{
if (address == null)
throw new IllegalArgumentException("address may not be null");
InetSocketAddress tmp = (InetSocketAddress) address;
this.address = tmp.getAddress();
this.port = tmp.getPort();
}
/**
* Gets the socket address of the host this packet
* will be sent to/is coming from
*
* @return The socket address of the remote host
*
* @since 1.4
*/
public SocketAddress getSocketAddress()
{
return new InetSocketAddress(address, port);
}
/**
* Sets the data buffer for this packet.
*
* @param buf The new buffer for this packet
*
* @exception NullPointerException If the argument is null
*
* @since 1.1
*/
public void setData(byte[] buf)
{
setData(buf, 0, buf.length);
}
/**
* This method sets the data buffer for the packet.
*
* @param buf The byte array containing the data for this packet.
* @param offset The offset into the buffer to start reading data from.
* @param length The number of bytes of data in the buffer.
*
* @exception NullPointerException If the argument is null
*
* @since 1.2
*/
public synchronized void setData(byte[] buf, int offset, int length)
{
// This form of setData must be used if offset is to be changed.
if (buf == null)
throw new NullPointerException("Null buffer");
if (offset < 0)
throw new IllegalArgumentException("Invalid offset: " + offset);
buffer = buf;
this.offset = offset;
setLength(length);
}
/**
* Sets the length of the data in the buffer.
*
* @param length The new length. (Where len &lt;= buf.length)
*
* @exception IllegalArgumentException If the length is negative or
* if the length is greater than the packet's data buffer length
*
* @since 1.1
*/
public synchronized void setLength(int length)
{
if (length < 0)
throw new IllegalArgumentException("Invalid length: " + length);
if (offset + length > buffer.length)
throw new IllegalArgumentException("Potential buffer overflow - offset: "
+ offset + " length: " + length);
this.length = length;
this.maxlen = length;
}
}

View file

@ -0,0 +1,933 @@
/* DatagramSocket.java -- A class to model UDP sockets
Copyright (C) 1998, 1999, 2000, 2002, 2003, 2004
Free Software Foundation, Inc.
This file is part of GNU Classpath.
GNU Classpath is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2, or (at your option)
any later version.
GNU Classpath is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with GNU Classpath; see the file COPYING. If not, write to the
Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301 USA.
Linking this library statically or dynamically with other modules is
making a combined work based on this library. Thus, the terms and
conditions of the GNU General Public License cover the whole
combination.
As a special exception, the copyright holders of this library give you
permission to link this library with independent modules to produce an
executable, regardless of the license terms of these independent
modules, and to copy and distribute the resulting executable under
terms of your choice, provided that you also meet, for each linked
independent module, the terms and conditions of the license of that
module. An independent module is a module which is not derived from
or based on this library. If you modify this library, you may extend
this exception to your version of the library, but you are not
obligated to do so. If you do not wish to do so, delete this
exception statement from your version. */
package java.net;
import gnu.java.net.PlainDatagramSocketImpl;
import gnu.java.nio.DatagramChannelImpl;
import java.io.IOException;
import java.nio.channels.DatagramChannel;
import java.nio.channels.IllegalBlockingModeException;
/**
* Written using on-line Java Platform 1.2 API Specification, as well
* as "The Java Class Libraries", 2nd edition (Addison-Wesley, 1998).
* Status: Believed complete and correct.
*/
/**
* This class models a connectionless datagram socket that sends
* individual packets of data across the network. In the TCP/IP world,
* this means UDP. Datagram packets do not have guaranteed delivery,
* or any guarantee about the order the data will be received on the
* remote host.
*
* @author Aaron M. Renn (arenn@urbanophile.com)
* @author Warren Levy (warrenl@cygnus.com)
* @date May 3, 1999.
*/
public class DatagramSocket
{
/**
* This is the user DatagramSocketImplFactory for this class. If this
* variable is null, a default factory is used.
*/
private static DatagramSocketImplFactory factory;
/**
* This is the implementation object used by this socket.
*/
private DatagramSocketImpl impl;
/**
* True if socket implementation was created.
*/
private boolean implCreated;
/**
* This is the address we are "connected" to
*/
private InetAddress remoteAddress;
/**
* This is the port we are "connected" to
*/
private int remotePort = -1;
/**
* True if socket is bound.
*/
private boolean bound;
/**
* Creates a <code>DatagramSocket</code> from a specified
* <code>DatagramSocketImpl</code> instance
*
* @param impl The <code>DatagramSocketImpl</code> the socket will be
* created from
*
* @since 1.4
*/
protected DatagramSocket(DatagramSocketImpl impl)
{
if (impl == null)
throw new NullPointerException("impl may not be null");
this.impl = impl;
this.remoteAddress = null;
this.remotePort = -1;
}
/**
* Initializes a new instance of <code>DatagramSocket</code> that binds to
* a random port and every address on the local machine.
*
* @exception SocketException If an error occurs.
* @exception SecurityException If a security manager exists and
* its <code>checkListen</code> method doesn't allow the operation.
*/
public DatagramSocket() throws SocketException
{
this(new InetSocketAddress(0));
}
/**
* Initializes a new instance of <code>DatagramSocket</code> that binds to
* the specified port and every address on the local machine.
*
* @param port The local port number to bind to.
*
* @exception SecurityException If a security manager exists and its
* <code>checkListen</code> method doesn't allow the operation.
* @exception SocketException If an error occurs.
*/
public DatagramSocket(int port) throws SocketException
{
this(new InetSocketAddress(port));
}
/**
* Initializes a new instance of <code>DatagramSocket</code> that binds to
* the specified local port and address.
*
* @param port The local port number to bind to.
* @param addr The local address to bind to.
*
* @exception SecurityException If a security manager exists and its
* checkListen method doesn't allow the operation.
* @exception SocketException If an error occurs.
*/
public DatagramSocket(int port, InetAddress addr) throws SocketException
{
this(new InetSocketAddress(addr, port));
}
/**
* Initializes a new instance of <code>DatagramSocket</code> that binds to
* the specified local port and address.
*
* @param address The local address and port number to bind to.
*
* @exception SecurityException If a security manager exists and its
* <code>checkListen</code> method doesn't allow the operation.
* @exception SocketException If an error occurs.
*
* @since 1.4
*/
public DatagramSocket(SocketAddress address) throws SocketException
{
String propVal = System.getProperty("impl.prefix");
if (propVal == null || propVal.equals(""))
impl = new PlainDatagramSocketImpl();
else
try
{
impl =
(DatagramSocketImpl) Class.forName("java.net." + propVal
+ "DatagramSocketImpl")
.newInstance();
}
catch (Exception e)
{
System.err.println("Could not instantiate class: java.net."
+ propVal + "DatagramSocketImpl");
impl = new PlainDatagramSocketImpl();
}
if (address != null)
bind(address);
}
// This needs to be accessible from java.net.MulticastSocket
DatagramSocketImpl getImpl() throws SocketException
{
try
{
if (! implCreated)
{
impl.create();
implCreated = true;
}
return impl;
}
catch (IOException e)
{
SocketException se = new SocketException();
se.initCause(e);
throw se;
}
}
/**
* Closes this datagram socket.
*/
public void close()
{
if (isClosed())
return;
try
{
getImpl().close();
}
catch (SocketException e)
{
// Ignore this case, just close the socket in finally clause.
}
finally
{
remoteAddress = null;
remotePort = -1;
impl = null;
}
try
{
if (getChannel() != null)
getChannel().close();
}
catch (IOException e)
{
// Do nothing.
}
}
/**
* This method returns the remote address to which this socket is
* connected. If this socket is not connected, then this method will
* return <code>null</code>.
*
* @return The remote address.
*
* @since 1.2
*/
public InetAddress getInetAddress()
{
return remoteAddress;
}
/**
* This method returns the remote port to which this socket is
* connected. If this socket is not connected, then this method will
* return -1.
*
* @return The remote port.
*
* @since 1.2
*/
public int getPort()
{
return remotePort;
}
/**
* Returns the local address this datagram socket is bound to.
*
* @return The local address is the socket is bound or null
*
* @since 1.1
*/
public InetAddress getLocalAddress()
{
if (! isBound())
return null;
InetAddress localAddr;
try
{
localAddr =
(InetAddress) getImpl().getOption(SocketOptions.SO_BINDADDR);
SecurityManager s = System.getSecurityManager();
if (s != null)
s.checkConnect(localAddr.getHostName(), -1);
}
catch (SecurityException e)
{
localAddr = InetAddress.ANY_IF;
}
catch (SocketException e)
{
// This cannot happen as we are bound.
return null;
}
return localAddr;
}
/**
* Returns the local port this socket is bound to.
*
* @return The local port number.
*/
public int getLocalPort()
{
if (isClosed())
return -1;
try
{
return getImpl().getLocalPort();
}
catch (SocketException e)
{
// This cannot happen as we are bound.
return 0;
}
}
/**
* Returns the value of the socket's SO_TIMEOUT setting. If this method
* returns 0 then SO_TIMEOUT is disabled.
*
* @return The current timeout in milliseconds.
*
* @exception SocketException If an error occurs.
*
* @since 1.1
*/
public synchronized int getSoTimeout() throws SocketException
{
if (isClosed())
throw new SocketException("socket is closed");
Object buf = getImpl().getOption(SocketOptions.SO_TIMEOUT);
if (buf instanceof Integer)
return ((Integer) buf).intValue();
throw new SocketException("unexpected type");
}
/**
* Sets the value of the socket's SO_TIMEOUT value. A value of 0 will
* disable SO_TIMEOUT. Any other value is the number of milliseconds
* a socket read/write will block before timing out.
*
* @param timeout The new SO_TIMEOUT value in milliseconds.
*
* @exception SocketException If an error occurs.
*
* @since 1.1
*/
public synchronized void setSoTimeout(int timeout) throws SocketException
{
if (isClosed())
throw new SocketException("socket is closed");
if (timeout < 0)
throw new IllegalArgumentException("Invalid timeout: " + timeout);
getImpl().setOption(SocketOptions.SO_TIMEOUT, new Integer(timeout));
}
/**
* This method returns the value of the system level socket option
* SO_SNDBUF, which is used by the operating system to tune buffer
* sizes for data transfers.
*
* @return The send buffer size.
*
* @exception SocketException If an error occurs.
*
* @since 1.2
*/
public int getSendBufferSize() throws SocketException
{
if (isClosed())
throw new SocketException("socket is closed");
Object buf = getImpl().getOption(SocketOptions.SO_SNDBUF);
if (buf instanceof Integer)
return ((Integer) buf).intValue();
throw new SocketException("unexpected type");
}
/**
* This method sets the value for the system level socket option
* SO_SNDBUF to the specified value. Note that valid values for this
* option are specific to a given operating system.
*
* @param size The new send buffer size.
*
* @exception SocketException If an error occurs.
* @exception IllegalArgumentException If size is 0 or negative.
*
* @since 1.2
*/
public void setSendBufferSize(int size) throws SocketException
{
if (isClosed())
throw new SocketException("socket is closed");
if (size < 0)
throw new IllegalArgumentException("Buffer size is less than 0");
getImpl().setOption(SocketOptions.SO_SNDBUF, new Integer(size));
}
/**
* This method returns the value of the system level socket option
* SO_RCVBUF, which is used by the operating system to tune buffer
* sizes for data transfers.
*
* @return The receive buffer size.
*
* @exception SocketException If an error occurs.
*
* @since 1.2
*/
public int getReceiveBufferSize() throws SocketException
{
if (isClosed())
throw new SocketException("socket is closed");
Object buf = getImpl().getOption(SocketOptions.SO_RCVBUF);
if (buf instanceof Integer)
return ((Integer) buf).intValue();
throw new SocketException("unexpected type");
}
/**
* This method sets the value for the system level socket option
* SO_RCVBUF to the specified value. Note that valid values for this
* option are specific to a given operating system.
*
* @param size The new receive buffer size.
*
* @exception SocketException If an error occurs.
* @exception IllegalArgumentException If size is 0 or negative.
*
* @since 1.2
*/
public void setReceiveBufferSize(int size) throws SocketException
{
if (isClosed())
throw new SocketException("socket is closed");
if (size < 0)
throw new IllegalArgumentException("Buffer size is less than 0");
getImpl().setOption(SocketOptions.SO_RCVBUF, new Integer(size));
}
/**
* This method connects this socket to the specified address and port.
* When a datagram socket is connected, it will only send or receive
* packets to and from the host to which it is connected. A multicast
* socket that is connected may only send and not receive packets.
*
* @param address The address to connect this socket to.
* @param port The port to connect this socket to.
*
* @exception SocketException If an error occurs.
* @exception IllegalArgumentException If address or port are invalid.
* @exception SecurityException If the caller is not allowed to send
* datagrams to or receive from this address and port.
*
* @since 1.2
*/
public void connect(InetAddress address, int port)
{
if (address == null)
throw new IllegalArgumentException("Connect address may not be null");
if ((port < 1) || (port > 65535))
throw new IllegalArgumentException("Port number is illegal: " + port);
SecurityManager sm = System.getSecurityManager();
if (sm != null)
sm.checkConnect(address.getHostName(), port);
try
{
getImpl().connect(address, port);
remoteAddress = address;
remotePort = port;
}
catch (SocketException e)
{
// This means simply not connected or connect not implemented.
}
}
/**
* This method disconnects this socket from the address/port it was
* connected to. If the socket was not connected in the first place,
* this method does nothing.
*
* @since 1.2
*/
public void disconnect()
{
if (! isConnected())
return;
try
{
getImpl().disconnect();
}
catch (SocketException e)
{
// This cannot happen as we are connected.
}
finally
{
remoteAddress = null;
remotePort = -1;
}
}
/**
* Reads a datagram packet from the socket. Note that this method
* will block until a packet is received from the network. On return,
* the passed in <code>DatagramPacket</code> is populated with the data
* received and all the other information about the packet.
*
* @param p A <code>DatagramPacket</code> for storing the data
*
* @exception IOException If an error occurs.
* @exception SocketTimeoutException If setSoTimeout was previously called
* and the timeout has expired.
* @exception PortUnreachableException If the socket is connected to a
* currently unreachable destination. Note, there is no guarantee that the
* exception will be thrown.
* @exception IllegalBlockingModeException If this socket has an associated
* channel, and the channel is in non-blocking mode.
* @exception SecurityException If a security manager exists and its
* checkAccept method doesn't allow the receive.
*/
public synchronized void receive(DatagramPacket p) throws IOException
{
if (isClosed())
throw new SocketException("socket is closed");
if (remoteAddress != null && remoteAddress.isMulticastAddress())
throw new IOException
("Socket connected to a multicast address my not receive");
if (getChannel() != null && ! getChannel().isBlocking()
&& ! ((DatagramChannelImpl) getChannel()).isInChannelOperation())
throw new IllegalBlockingModeException();
getImpl().receive(p);
SecurityManager s = System.getSecurityManager();
if (s != null && isConnected())
s.checkAccept(p.getAddress().getHostName(), p.getPort());
}
/**
* Sends the specified packet. The host and port to which the packet
* are to be sent should be set inside the packet.
*
* @param p The datagram packet to send.
*
* @exception IOException If an error occurs.
* @exception SecurityException If a security manager exists and its
* checkMulticast or checkConnect method doesn't allow the send.
* @exception PortUnreachableException If the socket is connected to a
* currently unreachable destination. Note, there is no guarantee that the
* exception will be thrown.
* @exception IllegalBlockingModeException If this socket has an associated
* channel, and the channel is in non-blocking mode.
*/
public void send(DatagramPacket p) throws IOException
{
if (isClosed())
throw new SocketException("socket is closed");
// JDK1.2: Don't do security checks if socket is connected; see jdk1.2 api.
SecurityManager s = System.getSecurityManager();
if (s != null && ! isConnected())
{
InetAddress addr = p.getAddress();
if (addr.isMulticastAddress())
s.checkMulticast(addr);
else
s.checkConnect(addr.getHostAddress(), p.getPort());
}
if (isConnected())
{
if (p.getAddress() != null
&& (remoteAddress != p.getAddress() || remotePort != p.getPort()))
throw new IllegalArgumentException
("DatagramPacket address does not match remote address");
}
// FIXME: if this is a subclass of MulticastSocket,
// use getTimeToLive for TTL val.
if (getChannel() != null && ! getChannel().isBlocking()
&& ! ((DatagramChannelImpl) getChannel()).isInChannelOperation())
throw new IllegalBlockingModeException();
getImpl().send(p);
}
/**
* Binds the socket to the given socket address.
*
* @param address The socket address to bind to.
*
* @exception SocketException If an error occurs.
* @exception SecurityException If a security manager exists and
* its checkListen method doesn't allow the operation.
* @exception IllegalArgumentException If address type is not supported.
*
* @since 1.4
*/
public void bind(SocketAddress address) throws SocketException
{
if (isClosed())
throw new SocketException("socket is closed");
if (! (address instanceof InetSocketAddress))
throw new IllegalArgumentException("unsupported address type");
InetAddress addr = ((InetSocketAddress) address).getAddress();
int port = ((InetSocketAddress) address).getPort();
if (port < 0 || port > 65535)
throw new IllegalArgumentException("Invalid port: " + port);
SecurityManager s = System.getSecurityManager();
if (s != null)
s.checkListen(port);
if (addr == null)
addr = InetAddress.ANY_IF;
try
{
getImpl().bind(port, addr);
bound = true;
}
catch (SocketException exception)
{
getImpl().close();
throw exception;
}
catch (RuntimeException exception)
{
getImpl().close();
throw exception;
}
catch (Error error)
{
getImpl().close();
throw error;
}
}
/**
* Checks if the datagram socket is closed.
*
* @return True if socket is closed, false otherwise.
*
* @since 1.4
*/
public boolean isClosed()
{
return impl == null;
}
/**
* Returns the datagram channel assoziated with this datagram socket.
*
* @return The associated <code>DatagramChannel</code> object or null
*
* @since 1.4
*/
public DatagramChannel getChannel()
{
return null;
}
/**
* Connects the datagram socket to a specified socket address.
*
* @param address The socket address to connect to.
*
* @exception SocketException If an error occurs.
* @exception IllegalArgumentException If address type is not supported.
*
* @since 1.4
*/
public void connect(SocketAddress address) throws SocketException
{
if (isClosed())
throw new SocketException("socket is closed");
if (! (address instanceof InetSocketAddress))
throw new IllegalArgumentException("unsupported address type");
InetSocketAddress tmp = (InetSocketAddress) address;
connect(tmp.getAddress(), tmp.getPort());
}
/**
* Returns the binding state of the socket.
*
* @return True if socket bound, false otherwise.
*
* @since 1.4
*/
public boolean isBound()
{
return bound;
}
/**
* Returns the connection state of the socket.
*
* @return True if socket is connected, false otherwise.
*
* @since 1.4
*/
public boolean isConnected()
{
return remoteAddress != null;
}
/**
* Returns the SocketAddress of the host this socket is conneted to
* or null if this socket is not connected.
*
* @return The socket address of the remote host if connected or null
*
* @since 1.4
*/
public SocketAddress getRemoteSocketAddress()
{
if (! isConnected())
return null;
return new InetSocketAddress(remoteAddress, remotePort);
}
/**
* Returns the local SocketAddress this socket is bound to.
*
* @return The local SocketAddress or null if the socket is not bound.
*
* @since 1.4
*/
public SocketAddress getLocalSocketAddress()
{
if (! isBound())
return null;
return new InetSocketAddress(getLocalAddress(), getLocalPort());
}
/**
* Enables/Disables SO_REUSEADDR.
*
* @param on Whether or not to have SO_REUSEADDR turned on.
*
* @exception SocketException If an error occurs.
*
* @since 1.4
*/
public void setReuseAddress(boolean on) throws SocketException
{
if (isClosed())
throw new SocketException("socket is closed");
getImpl().setOption(SocketOptions.SO_REUSEADDR, Boolean.valueOf(on));
}
/**
* Checks if SO_REUSEADDR is enabled.
*
* @return True if SO_REUSEADDR is set on the socket, false otherwise.
*
* @exception SocketException If an error occurs.
*
* @since 1.4
*/
public boolean getReuseAddress() throws SocketException
{
if (isClosed())
throw new SocketException("socket is closed");
Object buf = getImpl().getOption(SocketOptions.SO_REUSEADDR);
if (buf instanceof Boolean)
return ((Boolean) buf).booleanValue();
throw new SocketException("unexpected type");
}
/**
* Enables/Disables SO_BROADCAST
*
* @param enable True if SO_BROADCAST should be enabled, false otherwise.
*
* @exception SocketException If an error occurs
*
* @since 1.4
*/
public void setBroadcast(boolean enable) throws SocketException
{
if (isClosed())
throw new SocketException("socket is closed");
getImpl().setOption(SocketOptions.SO_BROADCAST, Boolean.valueOf(enable));
}
/**
* Checks if SO_BROADCAST is enabled
*
* @return Whether SO_BROADCAST is set
*
* @exception SocketException If an error occurs
*
* @since 1.4
*/
public boolean getBroadcast() throws SocketException
{
if (isClosed())
throw new SocketException("socket is closed");
Object buf = getImpl().getOption(SocketOptions.SO_BROADCAST);
if (buf instanceof Boolean)
return ((Boolean) buf).booleanValue();
throw new SocketException("unexpected type");
}
/**
* Sets the traffic class value
*
* @param tc The traffic class
*
* @exception SocketException If an error occurs
* @exception IllegalArgumentException If tc value is illegal
*
* @see DatagramSocket#getTrafficClass()
*
* @since 1.4
*/
public void setTrafficClass(int tc) throws SocketException
{
if (isClosed())
throw new SocketException("socket is closed");
if (tc < 0 || tc > 255)
throw new IllegalArgumentException();
getImpl().setOption(SocketOptions.IP_TOS, new Integer(tc));
}
/**
* Returns the current traffic class
*
* @return The current traffic class.
*
* @see DatagramSocket#setTrafficClass(int tc)
*
* @exception SocketException If an error occurs
*
* @since 1.4
*/
public int getTrafficClass() throws SocketException
{
if (isClosed())
throw new SocketException("socket is closed");
Object buf = getImpl().getOption(SocketOptions.IP_TOS);
if (buf instanceof Integer)
return ((Integer) buf).intValue();
throw new SocketException("unexpected type");
}
/**
* Sets the datagram socket implementation factory for the application
*
* @param fac The factory to set
*
* @exception IOException If an error occurs
* @exception SocketException If the factory is already defined
* @exception SecurityException If a security manager exists and its
* checkSetFactory method doesn't allow the operation
*/
public static void setDatagramSocketImplFactory(DatagramSocketImplFactory fac)
throws IOException
{
if (factory != null)
throw new SocketException("DatagramSocketImplFactory already defined");
SecurityManager sm = System.getSecurityManager();
if (sm != null)
sm.checkSetFactory();
factory = fac;
}
}

View file

@ -0,0 +1,296 @@
/* DatagramSocketImpl.java -- Abstract class for UDP socket implementations
Copyright (C) 1998, 1999 2000, 2001,
2002, 2003 Free Software Foundation, Inc.
This file is part of GNU Classpath.
GNU Classpath is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2, or (at your option)
any later version.
GNU Classpath is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with GNU Classpath; see the file COPYING. If not, write to the
Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301 USA.
Linking this library statically or dynamically with other modules is
making a combined work based on this library. Thus, the terms and
conditions of the GNU General Public License cover the whole
combination.
As a special exception, the copyright holders of this library give you
permission to link this library with independent modules to produce an
executable, regardless of the license terms of these independent
modules, and to copy and distribute the resulting executable under
terms of your choice, provided that you also meet, for each linked
independent module, the terms and conditions of the license of that
module. An independent module is a module which is not derived from
or based on this library. If you modify this library, you may extend
this exception to your version of the library, but you are not
obligated to do so. If you do not wish to do so, delete this
exception statement from your version. */
package java.net;
import java.io.FileDescriptor;
import java.io.IOException;
/**
* This abstract class models a datagram socket implementation. An
* actual implementation class would implement these methods, probably
* via redirecting them to native code.
* <p>
* Written using on-line Java Platform 1.2 API Specification, as well
* as "The Java Class Libraries", 2nd edition (Addison-Wesley, 1998).
* <p>
* Status: Believed complete and correct.
*
* @author Aaron M. Renn (arenn@urbanophile.com)
* @author Warren Levy (warrenl@cygnus.com)
* @since 1.1
*/
public abstract class DatagramSocketImpl implements SocketOptions
{
/**
* The local port to which this socket is bound
*/
protected int localPort;
/**
* The FileDescriptor object for this object.
*/
protected FileDescriptor fd;
/**
* Default, no-argument constructor for subclasses to call.
*/
public DatagramSocketImpl()
{
}
/**
* This method binds the socket to the specified local port and address.
*
* @param lport The port number to bind to
* @param laddr The address to bind to
*
* @exception SocketException If an error occurs
*/
protected abstract void bind(int lport, InetAddress laddr)
throws SocketException;
/**
* This methods closes the socket
*/
protected abstract void close();
/**
* Creates a new datagram socket.
*
* @exception SocketException If an error occurs
*/
protected abstract void create() throws SocketException;
/**
* Takes a peek at the next packet received in order to retrieve the
* address of the sender
*
* @param i The <code>InetAddress</code> to fill in with the information
* about the sender if the next packet
*
* @return The port number of the sender of the packet
*
* @exception IOException If an error occurs
* @exception PortUnreachableException May be thrown if the socket is
* connected to a currently unreachable destination. Note, there is no
* guarantee that the exception will be thrown.
*/
protected abstract int peek(InetAddress i) throws IOException;
/**
* Takes a peek at the next packet received. This packet is not consumed.
* With the next peekData/receive operation this packet will be read again.
*
* @param p The <code>DatagramPacket</code> to fill in with the data sent.
*
* @return The port number of the sender of the packet.
*
* @exception IOException If an error occurs
* @exception PortUnreachableException May be thrown if the socket is
* connected to a currently unreachable destination. Note, there is no
* guarantee that the exception will be thrown.
*
* @since 1.4
*/
protected abstract int peekData(DatagramPacket p) throws IOException;
/**
* Transmits the specified packet of data to the network. The destination
* host and port should be encoded in the packet.
*
* @param p The packet to send
*
* @exception IOException If an error occurs
* @exception PortUnreachableException May be thrown if the socket is
* connected to a currently unreachable destination. Note, there is no
* guarantee that the exception will be thrown.
*/
protected abstract void send(DatagramPacket p) throws IOException;
/**
* Receives a packet of data from the network Will block until a packet
* arrives. The packet info in populated into the passed in
* <code>DatagramPacket</code> object.
*
* @param p A place to store the incoming packet.
*
* @exception IOException If an error occurs
* @exception PortUnreachableException May be thrown if the socket is
* connected to a currently unreachable destination. Note, there is no
* guarantee that the exception will be thrown.
*/
protected abstract void receive(DatagramPacket p) throws IOException;
/**
* Connects the socket to a host specified by address and port.
*
* @param address The <code>InetAddress</code> of the host to connect to
* @param port The port number of the host to connect to
*
* @exception SocketException If an error occurs
*
* @since 1.4
*/
protected void connect(InetAddress address, int port)
throws SocketException
{
// This method has to be overwritten by real implementations
}
/**
* Disconnects the socket.
*
* @since 1.4
*/
protected void disconnect()
{
// This method has to be overwritten by real implementations
}
/**
* Sets the Time to Live (TTL) setting on this socket to the specified
* value. <b>Use <code>setTimeToLive(int)</code></b> instead.
*
* @param ttl The new Time to Live value
*
* @exception IOException If an error occurs
* @deprecated
*/
protected abstract void setTTL(byte ttl) throws IOException;
/**
* This method returns the current Time to Live (TTL) setting on this
* socket. <b>Use <code>getTimeToLive()</code></b> instead.
*
* @return the current time-to-live
*
* @exception IOException If an error occurs
*
* @deprecated // FIXME: when ?
*/
protected abstract byte getTTL() throws IOException;
/**
* Sets the Time to Live (TTL) setting on this socket to the specified
* value.
*
* @param ttl The new Time to Live value
*
* @exception IOException If an error occurs
*/
protected abstract void setTimeToLive(int ttl) throws IOException;
/**
* This method returns the current Time to Live (TTL) setting on this
* socket.
*
* @return the current time-to-live
*
* @exception IOException If an error occurs
*/
protected abstract int getTimeToLive() throws IOException;
/**
* Causes this socket to join the specified multicast group
*
* @param inetaddr The multicast address to join with
*
* @exception IOException If an error occurs
*/
protected abstract void join(InetAddress inetaddr) throws IOException;
/**
* Causes the socket to leave the specified multicast group.
*
* @param inetaddr The multicast address to leave
*
* @exception IOException If an error occurs
*/
protected abstract void leave(InetAddress inetaddr) throws IOException;
/**
* Causes this socket to join the specified multicast group on a specified
* device
*
* @param mcastaddr The address to leave
* @param netIf The specified network interface to join the group at
*
* @exception IOException If an error occurs
*
* @since 1.4
*/
protected abstract void joinGroup(SocketAddress mcastaddr,
NetworkInterface netIf)
throws IOException;
/**
* Leaves a multicast group
*
* @param mcastaddr The address to join
* @param netIf The specified network interface to leave the group at
*
* @exception IOException If an error occurs
*
* @since 1.4
*/
protected abstract void leaveGroup(SocketAddress mcastaddr,
NetworkInterface netIf)
throws IOException;
/**
* Returns the FileDescriptor for this socket
*
* @return the file descriptor associated with this socket
*/
protected FileDescriptor getFileDescriptor()
{
return fd;
}
/**
* Returns the local port this socket is bound to
*
* @return the local port
*/
protected int getLocalPort()
{
return localPort;
}
}

View file

@ -0,0 +1,60 @@
/* DatagramSocketImplFactory.java --
Copyright (C) 2002, 2003 Free Software Foundation, Inc.
This file is part of GNU Classpath.
GNU Classpath is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2, or (at your option)
any later version.
GNU Classpath is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with GNU Classpath; see the file COPYING. If not, write to the
Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301 USA.
Linking this library statically or dynamically with other modules is
making a combined work based on this library. Thus, the terms and
conditions of the GNU General Public License cover the whole
combination.
As a special exception, the copyright holders of this library give you
permission to link this library with independent modules to produce an
executable, regardless of the license terms of these independent
modules, and to copy and distribute the resulting executable under
terms of your choice, provided that you also meet, for each linked
independent module, the terms and conditions of the license of that
module. An independent module is a module which is not derived from
or based on this library. If you modify this library, you may extend
this exception to your version of the library, but you are not
obligated to do so. If you do not wish to do so, delete this
exception statement from your version. */
package java.net;
/** Written using on-line Java Platform 1.4 API Specification.
* Status: Believed complete and correct.
*/
/**
* This interface defines one method which returns a
* <code>DatagramSocketImpl</code> object.
* This should not be needed by ordinary applications.
*
* @author Michael Koch (konqueror@gmx.de)
* @since 1.3
*/
public interface DatagramSocketImplFactory
{
/**
* This method returns an instance of the DatagramSocketImpl object
*
* @return A DatagramSocketImpl object
*/
DatagramSocketImpl createDatagramSocketImpl();
} // interface DatagramSocketImplFactory

View file

@ -0,0 +1,65 @@
/* FileNameMap.java -- Maps filenames to MIME types
Copyright (C) 1998, 1999, 2000, 2001, 2003 Free Software Foundation, Inc.
This file is part of GNU Classpath.
GNU Classpath is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2, or (at your option)
any later version.
GNU Classpath is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with GNU Classpath; see the file COPYING. If not, write to the
Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301 USA.
Linking this library statically or dynamically with other modules is
making a combined work based on this library. Thus, the terms and
conditions of the GNU General Public License cover the whole
combination.
As a special exception, the copyright holders of this library give you
permission to link this library with independent modules to produce an
executable, regardless of the license terms of these independent
modules, and to copy and distribute the resulting executable under
terms of your choice, provided that you also meet, for each linked
independent module, the terms and conditions of the license of that
module. An independent module is a module which is not derived from
or based on this library. If you modify this library, you may extend
this exception to your version of the library, but you are not
obligated to do so. If you do not wish to do so, delete this
exception statement from your version. */
package java.net;
/**
* Written using on-line Java Platform 1.2 API Specification, as well
* as "The Java Class Libraries", 2nd edition (Addison-Wesley, 1998).
* Status: Believed complete and correct.
*/
/**
* This interface has one method which, when passed a filename, returns
* the MIME type associated with that filename.
*
* @author Aaron M. Renn (arenn@urbanophile.com)
* @author Warren Levy (warrenl@cygnus.com)
* @since 1.1
*/
public interface FileNameMap
{
/**
* This method is passed a filename and is responsible for determining
* the appropriate MIME type for that file.
*
* @param filename The name of the file to generate a MIME type for.
*
* @return The MIME type for the filename passed in.
*/
String getContentTypeFor(String filename);
} // interface FileNameMap

View file

@ -0,0 +1,589 @@
/* HttpURLConnection.java -- Subclass of communications links using
Hypertext Transfer Protocol.
Copyright (C) 1998, 1999, 2000, 2002, 2003 Free Software Foundation
This file is part of GNU Classpath.
GNU Classpath is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2, or (at your option)
any later version.
GNU Classpath is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with GNU Classpath; see the file COPYING. If not, write to the
Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301 USA.
Linking this library statically or dynamically with other modules is
making a combined work based on this library. Thus, the terms and
conditions of the GNU General Public License cover the whole
combination.
As a special exception, the copyright holders of this library give you
permission to link this library with independent modules to produce an
executable, regardless of the license terms of these independent
modules, and to copy and distribute the resulting executable under
terms of your choice, provided that you also meet, for each linked
independent module, the terms and conditions of the license of that
module. An independent module is a module which is not derived from
or based on this library. If you modify this library, you may extend
this exception to your version of the library, but you are not
obligated to do so. If you do not wish to do so, delete this
exception statement from your version. */
package java.net;
import java.io.IOException;
import java.io.InputStream;
import java.io.PushbackInputStream;
import java.security.Permission;
/*
* Written using on-line Java Platform 1.2 API Specification, as well
* as "The Java Class Libraries", 2nd edition (Addison-Wesley, 1998).
* Status: Believed complete and correct.
*/
/**
* This class provides a common abstract implementation for those
* URL connection classes that will connect using the HTTP protocol.
* In addition to the functionality provided by the URLConnection
* class, it defines constants for HTTP return code values and
* methods for setting the HTTP request method and determining whether
* or not to follow redirects.
*
* @since 1.1
*
* @author Warren Levy (warrenl@cygnus.com)
* @author Aaron M. Renn (arenn@urbanophile.com)
*/
public abstract class HttpURLConnection extends URLConnection
{
/* HTTP Success Response Codes */
/**
* Indicates that the client may continue with its request. This value
* is specified as part of RFC 2068 but was not included in Sun's JDK, so
* beware of using this value
*/
static final int HTTP_CONTINUE = 100;
/**
* Indicates the request succeeded.
*/
public static final int HTTP_OK = 200;
/**
* The requested resource has been created.
*/
public static final int HTTP_CREATED = 201;
/**
* The request has been accepted for processing but has not completed.
* There is no guarantee that the requested action will actually ever
* be completed succesfully, but everything is ok so far.
*/
public static final int HTTP_ACCEPTED = 202;
/**
* The meta-information returned in the header is not the actual data
* from the original server, but may be from a local or other copy.
* Normally this still indicates a successful completion.
*/
public static final int HTTP_NOT_AUTHORITATIVE = 203;
/**
* The server performed the request, but there is no data to send
* back. This indicates that the user's display should not be changed.
*/
public static final int HTTP_NO_CONTENT = 204;
/**
* The server performed the request, but there is no data to sent back,
* however, the user's display should be "reset" to clear out any form
* fields entered.
*/
public static final int HTTP_RESET = 205;
/**
* The server completed the partial GET request for the resource.
*/
public static final int HTTP_PARTIAL = 206;
/* HTTP Redirection Response Codes */
/**
* There is a list of choices available for the requested resource.
*/
public static final int HTTP_MULT_CHOICE = 300;
/**
* The resource has been permanently moved to a new location.
*/
public static final int HTTP_MOVED_PERM = 301;
/**
* The resource requested has been temporarily moved to a new location.
*/
public static final int HTTP_MOVED_TEMP = 302;
/**
* The response to the request issued is available at another location.
*/
public static final int HTTP_SEE_OTHER = 303;
/**
* The document has not been modified since the criteria specified in
* a conditional GET.
*/
public static final int HTTP_NOT_MODIFIED = 304;
/**
* The requested resource needs to be accessed through a proxy.
*/
public static final int HTTP_USE_PROXY = 305;
/* HTTP Client Error Response Codes */
/**
* The request was misformed or could not be understood.
*/
public static final int HTTP_BAD_REQUEST = 400;
/**
* The request made requires user authorization. Try again with
* a correct authentication header.
*/
public static final int HTTP_UNAUTHORIZED = 401;
/**
* Code reserved for future use - I hope way in the future.
*/
public static final int HTTP_PAYMENT_REQUIRED = 402;
/**
* There is no permission to access the requested resource.
*/
public static final int HTTP_FORBIDDEN = 403;
/**
* The requested resource was not found.
*/
public static final int HTTP_NOT_FOUND = 404;
/**
* The specified request method is not allowed for this resource.
*/
public static final int HTTP_BAD_METHOD = 405;
/**
* Based on the input headers sent, the resource returned in response
* to the request would not be acceptable to the client.
*/
public static final int HTTP_NOT_ACCEPTABLE = 406;
/**
* The client must authenticate with a proxy prior to attempting this
* request.
*/
public static final int HTTP_PROXY_AUTH = 407;
/**
* The request timed out.
*/
public static final int HTTP_CLIENT_TIMEOUT = 408;
/**
* There is a conflict between the current state of the resource and the
* requested action.
*/
public static final int HTTP_CONFLICT = 409;
/**
* The requested resource is no longer available. This ususally indicates
* a permanent condition.
*/
public static final int HTTP_GONE = 410;
/**
* A Content-Length header is required for this request, but was not
* supplied.
*/
public static final int HTTP_LENGTH_REQUIRED = 411;
/**
* A client specified pre-condition was not met on the server.
*/
public static final int HTTP_PRECON_FAILED = 412;
/**
* The request sent was too large for the server to handle.
*/
public static final int HTTP_ENTITY_TOO_LARGE = 413;
/**
* The name of the resource specified was too long.
*/
public static final int HTTP_REQ_TOO_LONG = 414;
/**
* The request is in a format not supported by the requested resource.
*/
public static final int HTTP_UNSUPPORTED_TYPE = 415;
/* HTTP Server Error Response Codes */
/**
* This error code indicates that some sort of server error occurred.
*
* @deprecated
*/
public static final int HTTP_SERVER_ERROR = 500;
/**
* The server encountered an unexpected error (such as a CGI script crash)
* that prevents the request from being fulfilled.
*/
public static final int HTTP_INTERNAL_ERROR = 500;
/**
* The server does not support the requested functionality.
* @since 1.3
*/
public static final int HTTP_NOT_IMPLEMENTED = 501;
/**
* The proxy encountered a bad response from the server it was proxy-ing for
*/
public static final int HTTP_BAD_GATEWAY = 502;
/**
* The HTTP service is not availalble, such as because it is overloaded
* and does not want additional requests.
*/
public static final int HTTP_UNAVAILABLE = 503;
/**
* The proxy timed out getting a reply from the remote server it was
* proxy-ing for.
*/
public static final int HTTP_GATEWAY_TIMEOUT = 504;
/**
* This server does not support the protocol version requested.
*/
public static final int HTTP_VERSION = 505;
// Non-HTTP response static variables
/**
* Flag to indicate whether or not redirects should be automatically
* followed by default.
*/
private static boolean followRedirects = true;
/**
* This is a list of valid request methods, separated by "|" characters.
*/
private static final String valid_methods =
"|GET|POST|HEAD|OPTIONS|PUT|DELETE|TRACE|";
// Instance Variables
/**
* The requested method in use for this connection. Default is GET.
*/
protected String method = "GET";
/**
* The response code received from the server
*/
protected int responseCode = -1;
/**
* The response message string received from the server.
*/
protected String responseMessage;
/**
* If this instance should follow redirect requests.
*/
protected boolean instanceFollowRedirects = followRedirects;
/**
* Whether we already got a valid response code for this connection.
* Used by <code>getResponseCode()</code> and
* <code>getResponseMessage()</code>.
*/
private boolean gotResponseVals;
/**
* Create an HttpURLConnection for the specified URL
*
* @param url The URL to create this connection for.
*/
protected HttpURLConnection(URL url)
{
super(url);
}
/**
* Closes the connection to the server.
*/
public abstract void disconnect();
/**
* Returns a boolean indicating whether or not this connection is going
* through a proxy
*
* @return true if through a proxy, false otherwise
*/
public abstract boolean usingProxy();
/**
* Sets whether HTTP redirects (requests with response code 3xx) should be
* automatically followed by this class. True by default
*
* @param set true if redirects should be followed, false otherwis.
*
* @exception SecurityException If a security manager exists and its
* checkSetFactory method doesn't allow the operation
*/
public static void setFollowRedirects(boolean set)
{
// Throw an exception if an extant security mgr precludes
// setting the factory.
SecurityManager s = System.getSecurityManager();
if (s != null)
s.checkSetFactory();
followRedirects = set;
}
/**
* Returns a boolean indicating whether or not HTTP redirects will
* automatically be followed or not.
*
* @return true if redirects will be followed, false otherwise
*/
public static boolean getFollowRedirects()
{
return followRedirects;
}
/**
* Returns the value of this HttpURLConnection's instanceFollowRedirects
* field
*
* @return true if following redirects is enabled, false otherwise
*/
public boolean getInstanceFollowRedirects()
{
return instanceFollowRedirects;
}
/**
* Sets the value of this HttpURLConnection's instanceFollowRedirects field
*
* @param follow true to enable following redirects, false otherwise
*/
public void setInstanceFollowRedirects(boolean follow)
{
instanceFollowRedirects = follow;
}
/**
* Set the method for the URL request, one of:
* GET POST HEAD OPTIONS PUT DELETE TRACE are legal
*
* @param method the method to use
*
* @exception ProtocolException If the method cannot be reset or if the
* requested method isn't valid for HTTP
*/
public void setRequestMethod(String method) throws ProtocolException
{
if (connected)
throw new ProtocolException("Already connected");
method = method.toUpperCase();
if (valid_methods.indexOf("|" + method + "|") != -1)
this.method = method;
else
throw new ProtocolException("Invalid HTTP request method: " + method);
}
/**
* The request method currently in use for this connection.
*
* @return The request method
*/
public String getRequestMethod()
{
return method;
}
/**
* Gets the status code from an HTTP response message, or -1 if
* the response code could not be determined.
* Note that all valid response codes have class variables
* defined for them in this class.
*
* @return The response code
*
* @exception IOException If an error occurs
*/
public int getResponseCode() throws IOException
{
if (! gotResponseVals)
getResponseVals();
return responseCode;
}
/**
* Gets the HTTP response message, if any, returned along with the
* response code from a server. Null if no response message was set
* or an error occured while connecting.
*
* @return The response message
*
* @exception IOException If an error occurs
*/
public String getResponseMessage() throws IOException
{
if (! gotResponseVals)
getResponseVals();
return responseMessage;
}
private void getResponseVals() throws IOException
{
// getHeaderField() will connect for us, but do it here first in
// order to pick up IOExceptions.
if (! connected)
connect();
gotResponseVals = true;
// If responseCode not yet explicitly set by subclass
if (responseCode == -1)
{
// Response is the first header received from the connection.
String respField = getHeaderField(0);
if (respField == null || ! respField.startsWith("HTTP/"))
{
// Set to default values on failure.
responseCode = -1;
responseMessage = null;
return;
}
int firstSpc;
int nextSpc;
firstSpc = respField.indexOf(' ');
nextSpc = respField.indexOf(' ', firstSpc + 1);
responseMessage = respField.substring(nextSpc + 1);
String codeStr = respField.substring(firstSpc + 1, nextSpc);
try
{
responseCode = Integer.parseInt(codeStr);
}
catch (NumberFormatException e)
{
// Set to default values on failure.
responseCode = -1;
responseMessage = null;
}
}
}
/**
* Returns a permission object representing the permission necessary to make
* the connection represented by this object
*
* @return the permission necessary for this connection
*
* @exception IOException If an error occurs
*/
public Permission getPermission() throws IOException
{
URL url = getURL();
String host = url.getHost();
int port = url.getPort();
if (port == -1)
port = 80;
host = host + ":" + port;
return new SocketPermission(host, "connect");
}
/**
* This method allows the caller to retrieve any data that might have
* been sent despite the fact that an error occurred. For example, the
* HTML page sent along with a 404 File Not Found error. If the socket
* is not connected, or if no error occurred or no data was returned,
* this method returns <code>null</code>.
*
* @return An <code>InputStream</code> for reading error data.
*/
public InputStream getErrorStream()
{
if (! connected)
return null;
int code;
try
{
code = getResponseCode();
}
catch (IOException e)
{
code = -1;
}
if (code == -1)
return null;
if (((code / 100) != 4) || ((code / 100) != 5))
return null;
try
{
PushbackInputStream pbis = new PushbackInputStream(getInputStream());
int i = pbis.read();
if (i == -1)
return null;
pbis.unread(i);
return pbis;
}
catch (IOException e)
{
return null;
}
}
/**
* Returns the value of the named field parsed as date
*
* @param key the key of the header field
* @param value the default value if the header field is not present
*
* @return the value of the header field
*/
public long getHeaderFieldDate(String key, long value)
{
// FIXME: implement this correctly
// http://www.w3.org/Protocols/HTTP-NG/ng-notes.txt
return super.getHeaderFieldDate(key, value);
}
}

View file

@ -0,0 +1,233 @@
/* Inet4Address.java --
Copyright (C) 2002, 2003, 2004, 2005 Free Software Foundation, Inc.
This file is part of GNU Classpath.
GNU Classpath is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2, or (at your option)
any later version.
GNU Classpath is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with GNU Classpath; see the file COPYING. If not, write to the
Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301 USA.
Linking this library statically or dynamically with other modules is
making a combined work based on this library. Thus, the terms and
conditions of the GNU General Public License cover the whole
combination.
As a special exception, the copyright holders of this library give you
permission to link this library with independent modules to produce an
executable, regardless of the license terms of these independent
modules, and to copy and distribute the resulting executable under
terms of your choice, provided that you also meet, for each linked
independent module, the terms and conditions of the license of that
module. An independent module is a module which is not derived from
or based on this library. If you modify this library, you may extend
this exception to your version of the library, but you are not
obligated to do so. If you do not wish to do so, delete this
exception statement from your version. */
package java.net;
import java.io.ObjectStreamException;
/*
* Written using on-line Java Platform 1.4 API Specification and
* RFC 1884 (http://www.ietf.org/rfc/rfc1884.txt),
* RFC 1918 (http://www.ietf.org/rfc/rfc1918.txt),
* RFC 2365 (http://www.ietf.org/rfc/rfc2365.txt)
*
* @author Michael Koch
* @status Believed complete and correct.
*/
public final class Inet4Address extends InetAddress
{
/**
* For compatability with Sun's JDK 1.4.2 rev. 5
*/
static final long serialVersionUID = 3286316764910316507L;
/**
* needed for serialization
*/
private Object writeReplace() throws ObjectStreamException
{
return new InetAddress(addr, hostName);
}
/**
* Initializes this object's addr instance variable from the passed in
* byte array. Note that this constructor is protected and is called
* only by static methods in this class.
*
* @param addr The IP number of this address as an array of bytes
* @param hostname The hostname of this IP address.
*/
Inet4Address(byte[] addr, String host)
{
super(addr, host);
}
/**
* Checks if the address is a multicast address
*
* @since 1.1
*/
public boolean isMulticastAddress()
{
return super.isMulticastAddress();
}
/**
* Checks if this address is a loopback address
*/
public boolean isLoopbackAddress()
{
return super.isLoopbackAddress();
}
/**
* Checks if this address is a wildcard address
*
* @since 1.4
*/
public boolean isAnyLocalAddress()
{
return super.isAnyLocalAddress();
}
/**
* Checks if this address is a link local address
*
* @since 1.4
*/
public boolean isLinkLocalAddress()
{
return super.isLinkLocalAddress();
}
/**
* Checks if this address is a site local address
*
* @since 1.4
*/
public boolean isSiteLocalAddress()
{
return super.isSiteLocalAddress();
}
/**
* Checks if this multicast address has global scope
*
* @since 1.4
*/
public boolean isMCGlobal()
{
return super.isMCGlobal();
}
/**
* Checks if this multicast address has node scope
*
* @since 1.4
*/
public boolean isMCNodeLocal()
{
return isMCNodeLocal();
}
/**
* Checks if this multicast address has link scope
*
* @since 1.4
*/
public boolean isMCLinkLocal()
{
return super.isMCLinkLocal();
}
/**
* Checks if this multicast address has site scope
*
* @since 1.4
*/
public boolean isMCSiteLocal()
{
return super.isMCSiteLocal();
}
/**
* Checks if this multicast address has organization scope
*
* @since 1.4
*/
public boolean isMCOrgLocal()
{
return isMCOrgLocal();
}
/**
* Returns the address of the current instance
*/
public byte[] getAddress()
{
return (byte[]) addr.clone();
}
/**
* Returns the address as string
*
* @since 1.0.2
*/
public String getHostAddress()
{
return super.getHostAddress();
}
/**
* Computes the hashcode of the instance
*/
public int hashCode()
{
int hash = 0;
int len = addr.length;
int i = len > 4 ? len - 4 : 0;
for (; i < len; i++)
hash = (hash << 8) | (addr[i] & 0xFF);
return hash;
}
/**
* Compare the current Inet4Address instance with obj
*
* @param obj Object to compare with
*/
public boolean equals(Object obj)
{
if (! (obj instanceof InetAddress))
return false;
byte[] addr1 = addr;
byte[] addr2 = ((InetAddress) obj).addr;
if (addr1.length != addr2.length)
return false;
for (int i = addr1.length; --i >= 0;)
if (addr1[i] != addr2[i])
return false;
return true;
}
}

View file

@ -0,0 +1,261 @@
/* Inet6Address.java --
Copyright (C) 2002, 2003, 2004 Free Software Foundation, Inc.
This file is part of GNU Classpath.
GNU Classpath is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2, or (at your option)
any later version.
GNU Classpath is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with GNU Classpath; see the file COPYING. If not, write to the
Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301 USA.
Linking this library statically or dynamically with other modules is
making a combined work based on this library. Thus, the terms and
conditions of the GNU General Public License cover the whole
combination.
As a special exception, the copyright holders of this library give you
permission to link this library with independent modules to produce an
executable, regardless of the license terms of these independent
modules, and to copy and distribute the resulting executable under
terms of your choice, provided that you also meet, for each linked
independent module, the terms and conditions of the license of that
module. An independent module is a module which is not derived from
or based on this library. If you modify this library, you may extend
this exception to your version of the library, but you are not
obligated to do so. If you do not wish to do so, delete this
exception statement from your version. */
package java.net;
import java.util.Arrays;
/*
* Written using on-line Java Platform 1.4 API Specification and
* RFC 1884 (http://www.ietf.org/rfc/rfc1884.txt)
*
* @author Michael Koch
* @status Believed complete and correct.
*/
public final class Inet6Address extends InetAddress
{
static final long serialVersionUID = 6880410070516793377L;
/**
* Needed for serialization
*/
byte[] ipaddress;
/**
* Create an Inet6Address object
*
* @param addr The IP address
* @param host The hostname
*/
Inet6Address(byte[] addr, String host)
{
super(addr, host);
// Super constructor clones the addr. Get a reference to the clone.
this.ipaddress = this.addr;
}
/**
* Utility routine to check if the InetAddress is an IP multicast address
*
* @since 1.1
*/
public boolean isMulticastAddress()
{
return ipaddress[0] == 0xFF;
}
/**
* Utility routine to check if the InetAddress in a wildcard address
*
* @since 1.4
*/
public boolean isAnyLocalAddress()
{
byte[] anylocal = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
return Arrays.equals(ipaddress, anylocal);
}
/**
* Utility routine to check if the InetAddress is a loopback address
*
* @since 1.4
*/
public boolean isLoopbackAddress()
{
byte[] loopback = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 };
return Arrays.equals(ipaddress, loopback);
}
/**
* Utility routine to check if the InetAddress is an link local address
*
* @since 1.4
*/
public boolean isLinkLocalAddress()
{
return ipaddress[0] == 0xFA;
}
/**
* Utility routine to check if the InetAddress is a site local address
*
* @since 1.4
*/
public boolean isSiteLocalAddress()
{
return ipaddress[0] == 0xFB;
}
/**
* Utility routine to check if the multicast address has global scope
*
* @since 1.4
*/
public boolean isMCGlobal()
{
if (! isMulticastAddress())
return false;
return (ipaddress[1] & 0x0F) == 0xE;
}
/**
* Utility routine to check if the multicast address has node scope
*
* @since 1.4
*/
public boolean isMCNodeLocal()
{
if (! isMulticastAddress())
return false;
return (ipaddress[1] & 0x0F) == 0x1;
}
/**
* Utility routine to check if the multicast address has link scope
*
* @since 1.4
*/
public boolean isMCLinkLocal()
{
if (! isMulticastAddress())
return false;
return (ipaddress[1] & 0x0F) == 0x2;
}
/**
* Utility routine to check if the multicast address has site scope
*
* @since 1.4
*/
public boolean isMCSiteLocal()
{
if (! isMulticastAddress())
return false;
return (ipaddress[1] & 0x0F) == 0x5;
}
/**
* Utility routine to check if the multicast address has organization scope
*
* @since 1.4
*/
public boolean isMCOrgLocal()
{
if (! isMulticastAddress())
return false;
return (ipaddress[1] & 0x0F) == 0x8;
}
/**
* Returns the raw IP address of this InetAddress object. The result is in
* network byte order: the highest order byte of the address is i
* n getAddress()[0]
*/
public byte[] getAddress()
{
return (byte[]) ipaddress.clone();
}
/**
* Returns the IP address string in textual presentation
*/
public String getHostAddress()
{
StringBuffer sbuf = new StringBuffer(40);
for (int i = 0; i < 16; i += 2)
{
int x = ((ipaddress[i] & 0xFF) << 8) | (ipaddress[i + 1] & 0xFF);
if (i > 0)
sbuf.append(':');
sbuf.append(Integer.toHexString(x));
}
return sbuf.toString();
}
/**
* Returns a hashcode for this IP address
*/
public int hashCode()
{
return super.hashCode();
}
/**
* Compares this object against the specified object
*/
public boolean equals(Object obj)
{
if (! (obj instanceof Inet6Address))
return false;
// this.ipaddress is never set in this class except to
// the value of the super class' addr. The super classes
// equals(Object) will do the compare.
return super.equals(obj);
}
/**
* Utility routine to check if the InetAddress is an
* IPv4 compatible IPv6 address
*
* @since 1.4
*/
public boolean isIPv4CompatibleAddress()
{
if (ipaddress[0] != 0x00 || ipaddress[1] != 0x00 || ipaddress[2] != 0x00
|| ipaddress[3] != 0x00 || ipaddress[4] != 0x00
|| ipaddress[5] != 0x00 || ipaddress[6] != 0x00
|| ipaddress[7] != 0x00 || ipaddress[8] != 0x00
|| ipaddress[9] != 0x00 || ipaddress[10] != 0x00
|| ipaddress[11] != 0x00)
return false;
return true;
}
}

View file

@ -0,0 +1,813 @@
/* InetAddress.java -- Class to model an Internet address
Copyright (C) 1998, 1999, 2002, 2004, 2005 Free Software Foundation, Inc.
This file is part of GNU Classpath.
GNU Classpath is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2, or (at your option)
any later version.
GNU Classpath is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with GNU Classpath; see the file COPYING. If not, write to the
Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301 USA.
Linking this library statically or dynamically with other modules is
making a combined work based on this library. Thus, the terms and
conditions of the GNU General Public License cover the whole
combination.
As a special exception, the copyright holders of this library give you
permission to link this library with independent modules to produce an
executable, regardless of the license terms of these independent
modules, and to copy and distribute the resulting executable under
terms of your choice, provided that you also meet, for each linked
independent module, the terms and conditions of the license of that
module. An independent module is a module which is not derived from
or based on this library. If you modify this library, you may extend
this exception to your version of the library, but you are not
obligated to do so. If you do not wish to do so, delete this
exception statement from your version. */
package java.net;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.ObjectStreamException;
import java.io.Serializable;
import java.util.HashMap;
import java.util.StringTokenizer;
/**
* This class models an Internet address. It does not have a public
* constructor. Instead, new instances of this objects are created
* using the static methods getLocalHost(), getByName(), and
* getAllByName().
*
* <p>This class fulfills the function of the C style functions gethostname(),
* gethostbyname(), and gethostbyaddr(). It resolves Internet DNS names
* into their corresponding numeric addresses and vice versa.</p>
*
* @author Aaron M. Renn (arenn@urbanophile.com)
* @author Per Bothner
*
* @specnote This class is not final since JK 1.4
*/
public class InetAddress implements Serializable
{
private static final long serialVersionUID = 3286316764910316507L;
/**
* The default DNS hash table size,
* Use a prime number happy with hash table.
*/
private static final int DEFAULT_CACHE_SIZE = 89;
/**
* The default caching period in minutes.
*/
private static final int DEFAULT_CACHE_PERIOD = 4 * 60;
/**
* Percentage of cache entries to purge when the table gets full.
*/
private static final int DEFAULT_CACHE_PURGE_PCT = 30;
/**
* The special IP address INADDR_ANY.
*/
private static InetAddress inaddr_any;
/**
* Dummy InetAddress, used to bind socket to any (all) network interfaces.
*/
static InetAddress ANY_IF;
/**
* Stores static localhost address object.
*/
static InetAddress LOCALHOST;
/**
* The size of the cache.
*/
private static int cache_size = 0;
/**
* The length of time we will continue to read the address from cache
* before forcing another lookup.
*/
private static int cache_period = 0;
/**
* What percentage of the cache we will purge if it gets full.
*/
private static int cache_purge_pct = 0;
/**
* HashMap to use as DNS lookup cache.
* Use HashMap because all accesses to cache are already synchronized.
*/
private static HashMap cache;
static
{
// Look for properties that override default caching behavior
cache_size =
Integer.getInteger("gnu.java.net.dns_cache_size", DEFAULT_CACHE_SIZE)
.intValue();
cache_period =
Integer.getInteger("gnu.java.net.dns_cache_period",
DEFAULT_CACHE_PERIOD * 60 * 1000).intValue();
cache_purge_pct =
Integer.getInteger("gnu.java.net.dns_cache_purge_pct",
DEFAULT_CACHE_PURGE_PCT).intValue();
// Fallback to defaults if necessary
if ((cache_purge_pct < 1) || (cache_purge_pct > 100))
cache_purge_pct = DEFAULT_CACHE_PURGE_PCT;
// Create the cache
if (cache_size != 0)
cache = new HashMap(cache_size);
// precompute the ANY_IF address
try
{
ANY_IF = getInaddrAny();
byte[] ip_localhost = { 127, 0, 0, 1 };
LOCALHOST = new Inet4Address(ip_localhost, "localhost");
}
catch (UnknownHostException uhe)
{
// Hmmm, make one up and hope that it works.
byte[] zeros = { 0, 0, 0, 0 };
ANY_IF = new Inet4Address(zeros, "0.0.0.0");
}
}
/**
* The Serialized Form specifies that an int 'address' is saved/restored.
* This class uses a byte array internally so we'll just do the conversion
* at serialization time and leave the rest of the algorithm as is.
*/
private int address;
/**
* An array of octets representing an IP address.
*/
transient byte[] addr;
/**
* The name of the host for this address.
*/
String hostName;
/**
* The time this address was looked up.
*/
transient long lookup_time;
/**
* The field 'family' seems to be the AF_ value.
* FIXME: Much of the code in the other java.net classes does not make
* use of this family field. A better implementation would be to make
* use of getaddrinfo() and have other methods just check the family
* field rather than examining the length of the address each time.
*/
int family;
/**
* Initializes this object's addr instance variable from the passed in
* byte array. Note that this constructor is protected and is called
* only by static methods in this class.
*
* @param ipaddr The IP number of this address as an array of bytes
* @param hostname The hostname of this IP address.
*/
InetAddress(byte[] ipaddr, String hostname)
{
addr = (null == ipaddr) ? null : (byte[]) ipaddr.clone();
hostName = hostname;
lookup_time = System.currentTimeMillis();
family = 2; /* AF_INET */
}
/**
* Returns true if this address is a multicast address, false otherwise.
* An address is multicast if the high four bits are "1110". These are
* also known as "Class D" addresses.
*
* @return true if mulitcast, false if not
*
* @since 1.1
*/
public boolean isMulticastAddress()
{
// Mask against high order bits of 1110
if (addr.length == 4)
return (addr[0] & 0xf0) == 0xe0;
return false;
}
/**
* Utility routine to check if the InetAddress in a wildcard address
*
* @since 1.4
*/
public boolean isAnyLocalAddress()
{
// This is the IPv4 implementation.
// Any class derived from InetAddress should override this.
return equals(ANY_IF);
}
/**
* Utility routine to check if the InetAddress is a loopback address
*
* @since 1.4
*/
public boolean isLoopbackAddress()
{
// This is the IPv4 implementation.
// Any class derived from InetAddress should override this.
return (addr[0] & 0xff) == 0x7f;
}
/**
* Utility routine to check if InetAddress is a link local address
*
* @since 1.4
*/
public boolean isLinkLocalAddress()
{
// This is the IPv4 implementation.
// Any class derived from InetAddress should override this.
// XXX: This seems to not exist with IPv4 addresses
return false;
}
/**
* Utility routine to check if InetAddress is a site local address
*
* @since 1.4
*/
public boolean isSiteLocalAddress()
{
// This is the IPv4 implementation.
// Any class derived from InetAddress should override this.
// 10.0.0.0/8
if ((addr[0] & 0xff) == 0x0a)
return true;
// 172.16.0.0/12
if ((addr[0] & 0xff) == 0xac && (addr[1] & 0xf0) == 0x10)
return true;
// 192.168.0.0/16
if ((addr[0] & 0xff) == 0xc0 && (addr[1] & 0xff) == 0xa8)
return true;
// XXX: Do we need to check more addresses here ?
return false;
}
/**
* Utility routine to check if InetAddress is a global multicast address
*
* @since 1.4
*/
public boolean isMCGlobal()
{
// This is the IPv4 implementation.
// Any class derived from InetAddress should override this.
// XXX: This seems to not exist with IPv4 addresses
return false;
}
/**
* Utility routine to check if InetAddress is a node local multicast address.
*
* @since 1.4
*/
public boolean isMCNodeLocal()
{
// This is the IPv4 implementation.
// Any class derived from InetAddress should override this.
// XXX: This seems to not exist with IPv4 addresses
return false;
}
/**
* Utility routine to check if InetAddress is a link local multicast address.
*
* @since 1.4
*/
public boolean isMCLinkLocal()
{
// This is the IPv4 implementation.
// Any class derived from InetAddress should override this.
if (! isMulticastAddress())
return false;
return ((addr[0] & 0xff) == 0xe0
&& (addr[1] & 0xff) == 0x00
&& (addr[2] & 0xff) == 0x00);
}
/**
* Utility routine to check if InetAddress is a site local multicast address.
*
* @since 1.4
*/
public boolean isMCSiteLocal()
{
// This is the IPv4 implementation.
// Any class derived from InetAddress should override this.
// XXX: This seems to not exist with IPv4 addresses
return false;
}
/**
* Utility routine to check if InetAddress is a organization local
* multicast address.
*
* @since 1.4
*/
public boolean isMCOrgLocal()
{
// This is the IPv4 implementation.
// Any class derived from InetAddress should override this.
// XXX: This seems to not exist with IPv4 addresses
return false;
}
/**
* Returns the hostname for this address. This will return the IP address
* as a String if there is no hostname available for this address
*
* @return The hostname for this address
*/
public String getHostName()
{
if (hostName != null)
return hostName;
try
{
hostName = VMInetAddress.getHostByAddr(addr);
return hostName;
}
catch (UnknownHostException e)
{
return getHostAddress();
}
}
/**
* Returns the canonical hostname represented by this InetAddress
*
* @since 1.4
*/
public String getCanonicalHostName()
{
SecurityManager sm = System.getSecurityManager();
if (sm != null)
{
try
{
sm.checkConnect(hostName, -1);
}
catch (SecurityException e)
{
return getHostAddress();
}
}
// Try to find the FDQN now
InetAddress address;
byte[] ipaddr = getAddress();
if (ipaddr.length == 16)
address = new Inet6Address(getAddress(), null);
else
address = new Inet4Address(getAddress(), null);
return address.getHostName();
}
/**
* Returns the IP address of this object as a byte array.
*
* @return IP address
*/
public byte[] getAddress()
{
// An experiment shows that JDK1.2 returns a different byte array each
// time. This makes sense, in terms of security.
return (byte[]) addr.clone();
}
/**
* Returns the IP address of this object as a String. The address is in
* the dotted octet notation, for example, "127.0.0.1".
*
* @return The IP address of this object in String form
*
* @since 1.0.2
*/
public String getHostAddress()
{
StringBuffer sb = new StringBuffer(40);
int len = addr.length;
int i = 0;
for ( ; ; )
{
sb.append(addr[i] & 0xff);
i++;
if (i == len)
break;
sb.append('.');
}
return sb.toString();
}
/**
* Returns a hash value for this address. Useful for creating hash
* tables. Overrides Object.hashCode()
*
* @return A hash value for this address.
*/
public int hashCode()
{
// There hashing algorithm is not specified, but a simple experiment
// shows that it is equal to the address, as a 32-bit big-endian integer.
int hash = 0;
int len = addr.length;
int i = len > 4 ? len - 4 : 0;
for (; i < len; i++)
hash = (hash << 8) | (addr[i] & 0xff);
return hash;
}
/**
* Tests this address for equality against another InetAddress. The two
* addresses are considered equal if they contain the exact same octets.
* This implementation overrides Object.equals()
*
* @param obj The address to test for equality
*
* @return true if the passed in object's address is equal to this one's,
* false otherwise
*/
public boolean equals(Object obj)
{
if (! (obj instanceof InetAddress))
return false;
// "The Java Class Libraries" 2nd edition says "If a machine has
// multiple names instances of InetAddress for different name of
// that same machine are not equal. This is because they have
// different host names." This violates the description in the
// JDK 1.2 API documentation. A little experimentation
// shows that the latter is correct.
byte[] addr2 = ((InetAddress) obj).addr;
if (addr.length != addr2.length)
return false;
for (int i = 0; i < addr.length; i++)
if (addr[i] != addr2[i])
return false;
return true;
}
/**
* Converts this address to a String. This string contains the IP in
* dotted decimal form. For example: "127.0.0.1" This method is equivalent
* to getHostAddress() and overrides Object.toString()
*
* @return This address in String form
*/
public String toString()
{
String addr = getHostAddress();
String host = (hostName != null) ? hostName : "";
return host + "/" + addr;
}
/**
* Returns an InetAddress object given the raw IP address.
*
* The argument is in network byte order: the highest order byte of the
* address is in getAddress()[0].
*
* @param addr The IP address to create the InetAddress object from
*
* @exception UnknownHostException If IP address has illegal length
*
* @since 1.4
*/
public static InetAddress getByAddress(byte[] addr)
throws UnknownHostException
{
return getByAddress(null, addr);
}
/**
* Creates an InetAddress based on the provided host name and IP address.
* No name service is checked for the validity of the address.
*
* @param host The hostname of the InetAddress object to create
* @param addr The IP address to create the InetAddress object from
*
* @exception UnknownHostException If IP address is of illegal length
*
* @since 1.4
*/
public static InetAddress getByAddress(String host, byte[] addr)
throws UnknownHostException
{
if (addr.length == 4)
return new Inet4Address(addr, host);
if (addr.length == 16)
return new Inet6Address(addr, host);
throw new UnknownHostException("IP address has illegal length");
}
/**
* If hostname is a valid numeric IP address, return the numeric address.
* Otherwise, return null.
*
* @param hostname the name of the host
*/
private static byte[] aton(String hostname)
{
StringTokenizer st = new StringTokenizer(hostname, ".");
if (st.countTokens() == 4)
{
int index;
byte[] address = new byte[4];
for (index = 0; index < 4; index++)
{
try
{
short n = Short.parseShort(st.nextToken());
if ((n < 0) || (n > 255))
break;
address[index] = (byte) n;
}
catch (NumberFormatException e)
{
break;
}
}
if (index == 4)
return address;
}
return null;
}
/**
* Returns an InetAddress object representing the IP address of the given
* hostname. This name can be either a hostname such as "www.urbanophile.com"
* or an IP address in dotted decimal format such as "127.0.0.1". If the
* hostname is null or "", the hostname of the local machine is supplied by
* default. This method is equivalent to returning the first element in
* the InetAddress array returned from GetAllByName.
*
* @param hostname The name of the desired host, or null for the local
* loopback address.
*
* @return The address of the host as an InetAddress object.
*
* @exception UnknownHostException If no IP address for the host could
* be found
* @exception SecurityException If a security manager exists and its
* checkConnect method doesn't allow the operation
*/
public static InetAddress getByName(String hostname)
throws UnknownHostException
{
InetAddress[] addresses = getAllByName(hostname);
return addresses[0];
}
/**
* Returns an array of InetAddress objects representing all the host/ip
* addresses of a given host, given the host's name. This name can be
* either a hostname such as "www.urbanophile.com" or an IP address in
* dotted decimal format such as "127.0.0.1". If the value is null, the
* hostname of the local machine is supplied by default.
*
* @param hostname The name of the desired host, or null for the
* local loopback address.
*
* @return All addresses of the host as an array of InetAddress objects.
*
* @exception UnknownHostException If no IP address for the host could
* be found
* @exception SecurityException If a security manager exists and its
* checkConnect method doesn't allow the operation
*/
public static InetAddress[] getAllByName(String hostname)
throws UnknownHostException
{
SecurityManager s = System.getSecurityManager();
if (s != null)
s.checkConnect(hostname, -1);
InetAddress[] addresses;
// Default to current host if necessary
if (hostname == null)
{
addresses = new InetAddress[1];
addresses[0] = LOCALHOST;
return addresses;
}
// Check the cache for this host before doing a lookup
addresses = checkCacheFor(hostname);
if (addresses != null)
return addresses;
// Not in cache, try the lookup
byte[][] iplist = VMInetAddress.getHostByName(hostname);
if (iplist.length == 0)
throw new UnknownHostException(hostname);
addresses = new InetAddress[iplist.length];
for (int i = 0; i < iplist.length; i++)
{
if (iplist[i].length != 4)
throw new UnknownHostException(hostname);
addresses[i] = new Inet4Address(iplist[i], hostname);
}
addToCache(hostname, addresses);
return addresses;
}
/**
* This method checks the DNS cache to see if we have looked this hostname
* up before. If so, we return the cached addresses unless it has been in the
* cache too long.
*
* @param hostname The hostname to check for
*
* @return The InetAddress for this hostname or null if not available
*/
private static synchronized InetAddress[] checkCacheFor(String hostname)
{
InetAddress[] addresses = null;
if (cache_size == 0)
return null;
Object obj = cache.get(hostname);
if (obj == null)
return null;
if (obj instanceof InetAddress[])
addresses = (InetAddress[]) obj;
if (addresses == null)
return null;
if (cache_period != -1)
if ((System.currentTimeMillis() - addresses[0].lookup_time) > cache_period)
{
cache.remove(hostname);
return null;
}
return addresses;
}
/**
* This method adds an InetAddress object to our DNS cache. Note that
* if the cache is full, then we run a purge to get rid of old entries.
* This will cause a performance hit, thus applications using lots of
* lookups should set the cache size to be very large.
*
* @param hostname The hostname to cache this address under
* @param obj The InetAddress or InetAddress array to store
*/
private static synchronized void addToCache(String hostname, Object obj)
{
if (cache_size == 0)
return;
// Check to see if hash table is full
if (cache_size != -1)
if (cache.size() == cache_size)
{
// FIXME Add code to purge later.
}
cache.put(hostname, obj);
}
/**
* Returns the special address INADDR_ANY used for binding to a local
* port on all IP addresses hosted by a the local host.
*
* @return An InetAddress object representing INDADDR_ANY
*
* @exception UnknownHostException If an error occurs
*/
static InetAddress getInaddrAny() throws UnknownHostException
{
if (inaddr_any == null)
{
byte[] tmp = VMInetAddress.lookupInaddrAny();
inaddr_any = new Inet4Address(tmp, null);
}
return inaddr_any;
}
/**
* Returns an InetAddress object representing the address of the current
* host.
*
* @return The local host's address
*
* @exception UnknownHostException If no IP address for the host could
* be found
*/
public static InetAddress getLocalHost() throws UnknownHostException
{
String hostname = VMInetAddress.getLocalHostname();
return getByName(hostname);
}
/*
* Needed for serialization
*/
private void readResolve() throws ObjectStreamException
{
// FIXME: implement this
}
private void readObject(ObjectInputStream ois)
throws IOException, ClassNotFoundException
{
ois.defaultReadObject();
addr = new byte[4];
addr[3] = (byte) address;
for (int i = 2; i >= 0; --i)
addr[i] = (byte) (address >>= 8);
family = 2; /* AF_INET */
}
private void writeObject(ObjectOutputStream oos) throws IOException
{
// Build a 32 bit address from the last 4 bytes of a 4 byte IPv4 address
// or a 16 byte IPv6 address.
int len = addr.length;
int i = len - 4;
for (; i < len; i++)
address = address << 8 | (addr[i] & 0xff);
oos.defaultWriteObject();
}
}

View file

@ -0,0 +1,221 @@
/* InetSocketAddress.java --
Copyright (C) 2002 Free Software Foundation, Inc.
This file is part of GNU Classpath.
GNU Classpath is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2, or (at your option)
any later version.
GNU Classpath is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with GNU Classpath; see the file COPYING. If not, write to the
Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301 USA.
Linking this library statically or dynamically with other modules is
making a combined work based on this library. Thus, the terms and
conditions of the GNU General Public License cover the whole
combination.
As a special exception, the copyright holders of this library give you
permission to link this library with independent modules to produce an
executable, regardless of the license terms of these independent
modules, and to copy and distribute the resulting executable under
terms of your choice, provided that you also meet, for each linked
independent module, the terms and conditions of the license of that
module. An independent module is a module which is not derived from
or based on this library. If you modify this library, you may extend
this exception to your version of the library, but you are not
obligated to do so. If you do not wish to do so, delete this
exception statement from your version. */
package java.net;
/**
* InetSocketAddress instances represent socket addresses
* in the java.nio package. They encapsulate a InetAddress and
* a port number.
*
* @since 1.4
*/
public class InetSocketAddress extends SocketAddress
{
/**
* Compatible with JDK 1.4+
*/
private static final long serialVersionUID = 5076001401234631237L;
/**
* Name of host.
*/
private String hostname;
/**
* Address of host.
*/
private InetAddress addr;
/**
* Port of host.
*/
private int port;
/**
* Constructs an InetSocketAddress instance.
*
* @param addr Address of the socket
* @param port Port if the socket
*
* @exception IllegalArgumentException If the port number is illegel
*/
public InetSocketAddress(InetAddress addr, int port)
throws IllegalArgumentException
{
if (port < 0 || port > 65535)
throw new IllegalArgumentException("Bad port number: " + port);
if (addr == null)
addr = InetAddress.ANY_IF;
this.addr = addr;
this.port = port;
this.hostname = addr.getHostName();
}
/**
* Constructs an InetSocketAddress instance.
*
* @param port Port if the socket
*
* @exception IllegalArgumentException If the port number is illegal
*/
public InetSocketAddress(int port) throws IllegalArgumentException
{
this((InetAddress) null, port);
}
/**
* Constructs an InetSocketAddress instance.
*
* @param hostname The hostname for the socket address
* @param port The port for the socket address
*
* @exception IllegalArgumentException If the port number is illegal
*/
public InetSocketAddress(String hostname, int port)
throws IllegalArgumentException
{
if (hostname == null)
throw new IllegalArgumentException("Null host name value");
if (port < 0 || port > 65535)
throw new IllegalArgumentException("Bad port number: " + port);
this.port = port;
this.hostname = hostname;
try
{
this.addr = InetAddress.getByName(hostname);
}
catch (Exception e) // UnknownHostException, SecurityException
{
this.addr = null;
}
}
/**
* Test if obj is a <code>InetSocketAddress</code> and
* has the same address and port
*
* @param obj The obj to compare this address with.
*
* @return True if obj is equal.
*/
public final boolean equals(Object obj)
{
// InetSocketAddress objects are equal when addr and port are equal.
// The hostname may differ.
if (obj instanceof InetSocketAddress)
{
InetSocketAddress sa = (InetSocketAddress) obj;
if (addr == null && sa.addr != null)
return false;
else if (addr == null && sa.addr == null)
return hostname.equals(sa.hostname) && sa.port == port;
else
return addr.equals(sa.addr) && sa.port == port;
}
return false;
}
/**
* Returns the <code>InetAddress</code> or
* <code>null</code> if its unresolved
*
* @return The IP address of this address.
*/
public final InetAddress getAddress()
{
return addr;
}
/**
* Returns <code>hostname</code>
*
* @return The hostname of this address.
*/
public final String getHostName()
{
return hostname;
}
/**
* Returns the <code>port</code>
*
* @return The port of this address.
*/
public final int getPort()
{
return port;
}
/**
* Returns the hashcode of the <code>InetSocketAddress</code>
*
* @return The hashcode for this address.
*/
public final int hashCode()
{
return port + addr.hashCode();
}
/**
* Checks wether the address has been resolved or not
*
* @return True if address is unresolved.
*/
public final boolean isUnresolved()
{
return addr == null;
}
/**
* Returns the <code>InetSocketAddress</code> as string
*
* @return A string represenation of this address.
*/
public String toString()
{
return (addr == null ? hostname : addr.getHostName()) + ":" + port;
}
}

View file

@ -0,0 +1,228 @@
/* JarURLConnection.java -- Class for manipulating remote jar files
Copyright (C) 1998, 2002, 2003 Free Software Foundation, Inc.
This file is part of GNU Classpath.
GNU Classpath is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2, or (at your option)
any later version.
GNU Classpath is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with GNU Classpath; see the file COPYING. If not, write to the
Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301 USA.
Linking this library statically or dynamically with other modules is
making a combined work based on this library. Thus, the terms and
conditions of the GNU General Public License cover the whole
combination.
As a special exception, the copyright holders of this library give you
permission to link this library with independent modules to produce an
executable, regardless of the license terms of these independent
modules, and to copy and distribute the resulting executable under
terms of your choice, provided that you also meet, for each linked
independent module, the terms and conditions of the license of that
module. An independent module is a module which is not derived from
or based on this library. If you modify this library, you may extend
this exception to your version of the library, but you are not
obligated to do so. If you do not wish to do so, delete this
exception statement from your version. */
package java.net;
import java.io.IOException;
import java.security.cert.Certificate;
import java.util.jar.Attributes;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import java.util.jar.Manifest;
/**
* This abstract class represents a common superclass for implementations
* of jar URL's. A jar URL is a special type of URL that allows JAR
* files on remote systems to be accessed. It has the form:
* <p>
* jar:&lt;standard URL pointing to jar filei&gt;!/file/within/jarfile
* <p> for example:
* <p>
* jar:http://www.urbanophile.com/java/foo.jar!/com/urbanophile/bar.class
* <p>
* That example URL points to the file /com/urbanophile/bar.class in the
* remote JAR file http://www.urbanophile.com/java/foo.jar. The HTTP
* protocol is used only as an example. Any supported remote protocol
* can be used.
* <p>
* This class currently works by retrieving the entire jar file into a
* local cache file, then performing standard jar operations on it.
* (At least this is true for the default protocol implementation).
*
* @author Aaron M. Renn (arenn@urbanophile.com)
* @author Kresten Krab Thorup (krab@gnu.org)
* @date Aug 10, 1999.
*
* @since 1.2
*/
public abstract class JarURLConnection extends URLConnection
{
/**
* This is the actual URL that points the remote jar file. This is parsed
* out of the jar URL by the constructor.
*/
private final URL jarFileURL;
/**
* The connection to the jar file itself. A JarURLConnection
* can represent an entry in a jar file or an entire jar file. In
* either case this describes just the jar file itself.
*/
protected URLConnection jarFileURLConnection;
/**
* This is the jar file "entry name" or portion after the "!/" in the
* URL which represents the pathname inside the actual jar file.
*/
private final String entryName;
/**
* Creates a JarURLConnection from an URL object
*
* @param url The URL object for this connection.
*
* @exception MalformedURLException If url is invalid
*
* @specnote This constructor is protected since JDK 1.4
*/
protected JarURLConnection(URL url) throws MalformedURLException
{
super(url);
if (! url.getProtocol().equals("jar"))
throw new MalformedURLException(url + ": Not jar protocol.");
String spec = url.getFile();
int bang = spec.indexOf("!/");
if (bang == -1)
throw new MalformedURLException(url + ": No `!/' in spec.");
// Extract the url for the jar itself.
jarFileURL = new URL(spec.substring(0, bang));
// Get the name of the entry, if any.
entryName = spec.length() == (bang + 2) ? null : spec.substring(bang + 2);
}
/**
* This method returns the "real" URL where the JarFile is located.
* //****Is this right?*****
*
* @return The remote URL
*/
public URL getJarFileURL()
{
return jarFileURL;
}
/**
* Returns the "entry name" portion of the jar URL. This is the portion
* after the "!/" in the jar URL that represents the pathname inside the
* actual jar file.
*
* @return The entry name.
*/
public String getEntryName()
{
return entryName;
}
/**
* Returns the entry in this jar file specified by the URL.
*
* @return The jar entry
*
* @exception IOException If an error occurs
*/
public JarEntry getJarEntry() throws IOException
{
JarFile jarFile = getJarFile();
return jarFile != null ? jarFile.getJarEntry(entryName) : null;
}
/**
* Returns a read-only JarFile object for the remote jar file
*
* @return The JarFile object
*
* @exception IOException If an error occurs
*/
public abstract JarFile getJarFile() throws IOException;
/**
* Returns an array of Certificate objects for the jar file entry specified
* by this URL or null if there are none
*
* @return A Certificate array
*
* @exception IOException If an error occurs
*/
public Certificate[] getCertificates() throws IOException
{
JarEntry entry = getJarEntry();
return entry != null ? entry.getCertificates() : null;
}
/**
* Returns the main Attributes for the jar file specified in the URL or
* null if there are none
*
* @return The main Attributes for the JAR file for this connection
*
* @exception IOException If an error occurs
*/
public Attributes getMainAttributes() throws IOException
{
Manifest manifest = getManifest();
return manifest != null ? manifest.getMainAttributes() : null;
}
/**
* Returns the Attributes for the Jar entry specified by the URL or null
* if none
*
* @return The Attributes object for this connection if the URL for it points
* to a JAR file entry, null otherwise
*
* @exception IOException If an error occurs
*/
public Attributes getAttributes() throws IOException
{
JarEntry entry = getJarEntry();
return entry != null ? entry.getAttributes() : null;
}
/**
* Returns a Manifest object for this jar file, or null if there is no
* manifest.
*
* @return The Manifest for this connection, or null if none
*
* @exception IOException If an error occurs
*/
public Manifest getManifest() throws IOException
{
JarFile file = getJarFile();
return file != null ? file.getManifest() : null;
}
}

View file

@ -0,0 +1,74 @@
/* MalformedURLException.java -- A URL was not in a valid format
Copyright (C) 1998, 1999, 2000, 2001, 2002 Free Software Foundation, Inc.
This file is part of GNU Classpath.
GNU Classpath is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2, or (at your option)
any later version.
GNU Classpath is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with GNU Classpath; see the file COPYING. If not, write to the
Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301 USA.
Linking this library statically or dynamically with other modules is
making a combined work based on this library. Thus, the terms and
conditions of the GNU General Public License cover the whole
combination.
As a special exception, the copyright holders of this library give you
permission to link this library with independent modules to produce an
executable, regardless of the license terms of these independent
modules, and to copy and distribute the resulting executable under
terms of your choice, provided that you also meet, for each linked
independent module, the terms and conditions of the license of that
module. An independent module is a module which is not derived from
or based on this library. If you modify this library, you may extend
this exception to your version of the library, but you are not
obligated to do so. If you do not wish to do so, delete this
exception statement from your version. */
package java.net;
import java.io.IOException;
/**
* This exception indicates that a URL passed to an object was not in a
* valid format.
*
* @author Aaron M. Renn (arenn@urbanophile.com)
* @author Warren Levy (warrenl@cygnus.com)
* @status updated to 1.4
*/
public class MalformedURLException extends IOException
{
/**
* Compatible with JDK 1.0+.
*/
private static final long serialVersionUID = -182787522200415866L;
/**
* Create a new instance without a descriptive error message.
*/
public MalformedURLException()
{
}
/**
* Create a new instance with a descriptive error message.
*
* @param message a message describing the error that occurred
*/
public MalformedURLException(String message)
{
super(message);
}
} // class MalformedURLException

View file

@ -0,0 +1,213 @@
/* MimeTypeMapper.java -- A class for mapping file names to MIME types
Copyright (C) 1998 Free Software Foundation, Inc.
This file is part of GNU Classpath.
GNU Classpath is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2, or (at your option)
any later version.
GNU Classpath is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with GNU Classpath; see the file COPYING. If not, write to the
Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301 USA.
Linking this library statically or dynamically with other modules is
making a combined work based on this library. Thus, the terms and
conditions of the GNU General Public License cover the whole
combination.
As a special exception, the copyright holders of this library give you
permission to link this library with independent modules to produce an
executable, regardless of the license terms of these independent
modules, and to copy and distribute the resulting executable under
terms of your choice, provided that you also meet, for each linked
independent module, the terms and conditions of the license of that
module. An independent module is a module which is not derived from
or based on this library. If you modify this library, you may extend
this exception to your version of the library, but you are not
obligated to do so. If you do not wish to do so, delete this
exception statement from your version. */
package java.net;
import java.util.Hashtable;
/**
* This non-public class is used to implement the FileNameMap interface
* which defines a mechanism for mapping filenames to MIME types.
*
* @version 0.5
*
* @author Aaron M. Renn (arenn@urbanophile.com)
*/
class MimeTypeMapper implements FileNameMap
{
/**
* This array of strings is used to identify a MIME type based on a file
* extension. This is list is based on the Apache mime.types file.
*/
protected static final String[][] mime_strings =
{
{ "application/mac-binhex40", "hqx" },
{ "application/mac-compactpro", "cpt" },
{ "application/msword", "doc" },
{ "application/octet-stream", "bin" },
{ "application/octet-stream", "dms" },
{ "application/octet-stream", "lha" },
{ "application/octet-stream", "lzh" },
{ "application/octet-stream", "exe" },
{ "application/octet-stream", "class" },
{ "application/oda", "oda" },
{ "application/pdf", "pdf" },
{ "application/postscript", "ai" },
{ "application/postscript", "eps" },
{ "application/postscript", "ps" },
{ "application/powerpoint", "ppt" },
{ "application/rtf", "rtf" },
{ "application/x-bcpio", "bcpio" },
{ "application/x-cdlink", "vcd" },
{ "application/x-compress", "Z" },
{ "application/x-cpio", "cpio" },
{ "application/x-csh", "csh" },
{ "application/x-director", "dcr" },
{ "application/x-director", "dir" },
{ "application/x-director", "dxr" },
{ "application/x-dvi", "dvi" },
{ "application/x-gtar", "gtar" },
{ "application/x-gzip", "gz" },
{ "application/x-hdf", "hdf" },
{ "application/x-httpd-cgi", "cgi" },
{ "application/x-koan", "skp" },
{ "application/x-koan", "skd" },
{ "application/x-koan", "skt" },
{ "application/x-koan", "skm" },
{ "application/x-latex", "latex" },
{ "application/x-mif", "mif" },
{ "application/x-netcdf", "nc" },
{ "application/x-netcdf", "cdf" },
{ "application/x-sh", "sh" },
{ "application/x-shar", "shar" },
{ "application/x-stuffit", "sit" },
{ "application/x-sv4cpio", "sv4cpio" },
{ "application/x-sv4crc", "sv4crc" },
{ "application/x-tar", "tar" },
{ "application/x-tcl", "tcl" },
{ "application/x-tex", "tex" },
{ "application/x-texinfo", "texinfo" },
{ "application/x-texinfo", "texi" },
{ "application/x-troff", "t" },
{ "application/x-troff", "tr" },
{ "application/x-troff", "roff" },
{ "application/x-troff-man", "man" },
{ "application/x-troff-me", "me" },
{ "application/x-troff-ms", "ms" },
{ "application/x-ustar", "ustar" },
{ "application/x-wais-source", "src" },
{ "application/zip", "zip" },
{ "audio/basic", "au" },
{ "audio/basic", "snd" },
{ "audio/mpeg", "mpga" },
{ "audio/mpeg", "mp2" },
{ "audio/mpeg", "mp3" },
{ "audio/x-aiff", "aif" },
{ "audio/x-aiff", "aiff" },
{ "audio/x-aiff", "aifc" },
{ "audio/x-pn-realaudio", "ram" },
{ "audio/x-pn-realaudio-plugin", "rpm" },
{ "audio/x-realaudio", "ra" },
{ "audio/x-wav", "wav" },
{ "chemical/x-pdb", "pdb" },
{ "chemical/x-pdb", "xyz" },
{ "image/gif", "gif" },
{ "image/ief", "ief" },
{ "image/jpeg", "jpeg" },
{ "image/jpeg", "jpg" },
{ "image/jpeg", "jpe" },
{ "image/png", "png" },
{ "image/tiff", "tiff" },
{ "image/tiff", "tif" },
{ "image/x-cmu-raster", "ras" },
{ "image/x-portable-anymap", "pnm" },
{ "image/x-portable-bitmap", "pbm" },
{ "image/x-portable-graymap", "pgm" },
{ "image/x-portable-pixmap", "ppm" },
{ "image/x-rgb", "rgb" },
{ "image/x-xbitmap", "xbm" },
{ "image/x-xpixmap", "xpm" },
{ "image/x-xwindowdump", "xwd" },
{ "text/html", "html" },
{ "text/html", "htm" },
{ "text/plain", "txt" },
{ "text/richtext", "rtx" },
{ "text/tab-separated-values", "tsv" },
{ "text/x-setext", "etx" },
{ "text/x-sgml", "sgml" },
{ "text/x-sgml", "sgm" },
{ "video/mpeg", "mpeg" },
{ "video/mpeg", "mpg" },
{ "video/mpeg", "mpe" },
{ "video/quicktime", "qt" },
{ "video/quicktime", "mov" },
{ "video/x-msvideo", "avi" },
{ "video/x-sgi-movie", "movie" },
{ "x-conference/x-cooltalk", "ice" },
{ "x-world/x-vrml", "wrl" },
{ "x-world/x-vrml", "vrml" }
};
/**
* The MIME types above are put into this Hashtable for faster lookup.
*/
private static Hashtable mime_types = new Hashtable(150);
// Static initializer to load MIME types into Hashtable
static
{
for (int i = 0; i < mime_strings.length; i++)
mime_types.put(mime_strings[i][1], mime_strings[i][0]);
}
/**
* Create a new <code>MimeTypeMapper</code> object.
*/
public MimeTypeMapper()
{
// Do nothing here.
}
/**
* The method returns the MIME type of the filename passed as an argument.
* The value returned is based on the extension of the filename. The
* default content type returned if this method cannot determine the
* actual content type is "application/octet-stream"
*
* @param filename The name of the file to return the MIME type for
*
* @return The MIME type
*/
public String getContentTypeFor(String filename)
{
int index = filename.lastIndexOf(".");
if (index != -1)
{
if (index == filename.length())
return "application/octet-stream";
else
filename = filename.substring(index + 1);
}
String type = (String) mime_types.get(filename);
if (type == null)
return "application/octet-stream";
else
return type;
}
}

View file

@ -0,0 +1,486 @@
/* MulticastSocket.java -- Class for using multicast sockets
Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003
Free Software Foundation, Inc.
This file is part of GNU Classpath.
GNU Classpath is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2, or (at your option)
any later version.
GNU Classpath is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with GNU Classpath; see the file COPYING. If not, write to the
Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301 USA.
Linking this library statically or dynamically with other modules is
making a combined work based on this library. Thus, the terms and
conditions of the GNU General Public License cover the whole
combination.
As a special exception, the copyright holders of this library give you
permission to link this library with independent modules to produce an
executable, regardless of the license terms of these independent
modules, and to copy and distribute the resulting executable under
terms of your choice, provided that you also meet, for each linked
independent module, the terms and conditions of the license of that
module. An independent module is a module which is not derived from
or based on this library. If you modify this library, you may extend
this exception to your version of the library, but you are not
obligated to do so. If you do not wish to do so, delete this
exception statement from your version. */
package java.net;
import java.io.IOException;
import java.util.Enumeration;
/**
* Written using on-line Java Platform 1.2 API Specification, as well
* as "The Java Class Libraries", 2nd edition (Addison-Wesley, 1998).
* Status: Believed complete and correct.
*/
/**
* This class models a multicast UDP socket. A multicast address is a
* class D internet address (one whose most significant bits are 1110).
* A multicast group consists of a multicast address and a well known
* port number. All members of the group listening on that address and
* port will receive all the broadcasts to the group.
* <p>
* Please note that applets are not allowed to use multicast sockets
*
* Written using on-line Java Platform 1.2 API Specification, as well
* as "The Java Class Libraries", 2nd edition (Addison-Wesley, 1998).
* Status: Believed complete and correct.
*
* @author Warren Levy (warrenl@cygnus.com)
* @author Aaron M. Renn (arenn@urbanophile.com) (Documentation comments)
* @since 1.1
* @date May 18, 1999.
*/
public class MulticastSocket extends DatagramSocket
{
/**
* Create a MulticastSocket that this not bound to any address
*
* @exception IOException If an error occurs
* @exception SecurityException If a security manager exists and its
* checkListen method doesn't allow the operation
*/
public MulticastSocket() throws IOException
{
this(new InetSocketAddress(0));
}
/**
* Create a multicast socket bound to the specified port
*
* @param port The port to bind to
*
* @exception IOException If an error occurs
* @exception SecurityException If a security manager exists and its
* checkListen method doesn't allow the operation
*/
public MulticastSocket(int port) throws IOException
{
this(new InetSocketAddress(port));
}
/**
* Create a multicast socket bound to the specified SocketAddress.
*
* @param address The SocketAddress the multicast socket will be bound to
*
* @exception IOException If an error occurs
* @exception SecurityException If a security manager exists and its
* checkListen method doesn't allow the operation
*
* @since 1.4
*/
public MulticastSocket(SocketAddress address) throws IOException
{
super((SocketAddress) null);
setReuseAddress(true);
if (address != null)
bind(address);
}
/**
* Returns the interface being used for multicast packets
*
* @return The multicast interface
*
* @exception SocketException If an error occurs
*/
public InetAddress getInterface() throws SocketException
{
if (isClosed())
throw new SocketException("socket is closed");
return (InetAddress) getImpl().getOption(SocketOptions.IP_MULTICAST_IF);
}
/**
* Returns the current value of the "Time to Live" option. This is the
* number of hops a packet can make before it "expires". This method id
* deprecated. Use <code>getTimeToLive</code> instead.
*
* @return The TTL value
*
* @exception IOException If an error occurs
*
* @deprecated 1.2 Replaced by getTimeToLive()
*
* @see MulticastSocket#getTimeToLive()
*/
public byte getTTL() throws IOException
{
if (isClosed())
throw new SocketException("socket is closed");
// Use getTTL here rather than getTimeToLive in case we're using an impl
// other than the default PlainDatagramSocketImpl and it doesn't have
// getTimeToLive yet.
return getImpl().getTTL();
}
/**
* Returns the current value of the "Time to Live" option. This is the
* number of hops a packet can make before it "expires".
*
* @return The TTL value
*
* @exception IOException If an error occurs
*
* @since 1.2
*/
public int getTimeToLive() throws IOException
{
if (isClosed())
throw new SocketException("socket is closed");
return getImpl().getTimeToLive();
}
/**
* Sets the interface to use for sending multicast packets.
*
* @param addr The new interface to use.
*
* @exception SocketException If an error occurs.
*
* @since 1.4
*/
public void setInterface(InetAddress addr) throws SocketException
{
if (isClosed())
throw new SocketException("socket is closed");
getImpl().setOption(SocketOptions.IP_MULTICAST_IF, addr);
}
/**
* Sets the local network interface used to send multicast messages
*
* @param netIf The local network interface used to send multicast messages
*
* @exception SocketException If an error occurs
*
* @see MulticastSocket#getNetworkInterface()
*
* @since 1.4
*/
public void setNetworkInterface(NetworkInterface netIf)
throws SocketException
{
if (isClosed())
throw new SocketException("socket is closed");
Enumeration e = netIf.getInetAddresses();
if (! e.hasMoreElements())
throw new SocketException("no network devices found");
InetAddress address = (InetAddress) e.nextElement();
getImpl().setOption(SocketOptions.IP_MULTICAST_IF, address);
}
/**
* Gets the local network interface which is used to send multicast messages
*
* @return The local network interface to send multicast messages
*
* @exception SocketException If an error occurs
*
* @see MulticastSocket#setNetworkInterface(NetworkInterface netIf)
*
* @since 1.4
*/
public NetworkInterface getNetworkInterface() throws SocketException
{
if (isClosed())
throw new SocketException("socket is closed");
InetAddress address =
(InetAddress) getImpl().getOption(SocketOptions.IP_MULTICAST_IF);
NetworkInterface netIf = NetworkInterface.getByInetAddress(address);
return netIf;
}
/**
* Disable/Enable local loopback of multicast packets. The option is used by
* the platform's networking code as a hint for setting whether multicast
* data will be looped back to the local socket.
*
* Because this option is a hint, applications that want to verify what
* loopback mode is set to should call #getLoopbackMode
*
* @param disable True to disable loopback mode
*
* @exception SocketException If an error occurs
*
* @since 1.4
*/
public void setLoopbackMode(boolean disable) throws SocketException
{
if (isClosed())
throw new SocketException("socket is closed");
getImpl().setOption(SocketOptions.IP_MULTICAST_LOOP,
Boolean.valueOf(disable));
}
/**
* Checks if local loopback mode is enabled
*
* @return true if loopback mode is enabled, false otherwise
*
* @exception SocketException If an error occurs
*
* @since 1.4
*/
public boolean getLoopbackMode() throws SocketException
{
if (isClosed())
throw new SocketException("socket is closed");
Object buf = getImpl().getOption(SocketOptions.IP_MULTICAST_LOOP);
if (buf instanceof Boolean)
return ((Boolean) buf).booleanValue();
throw new SocketException("unexpected type");
}
/**
* Sets the "Time to Live" value for a socket. The value must be between
* 1 and 255.
*
* @param ttl The new TTL value
*
* @exception IOException If an error occurs
*
* @deprecated 1.2 Replaced by <code>setTimeToLive</code>
*
* @see MulticastSocket#setTimeToLive(int ttl)
*/
public void setTTL(byte ttl) throws IOException
{
if (isClosed())
throw new SocketException("socket is closed");
// Use setTTL here rather than setTimeToLive in case we're using an impl
// other than the default PlainDatagramSocketImpl and it doesn't have
// setTimeToLive yet.
getImpl().setTTL(ttl);
}
/**
* Sets the "Time to Live" value for a socket. The value must be between
* 1 and 255.
*
* @param ttl The new TTL value
*
* @exception IOException If an error occurs
*
* @since 1.2
*/
public void setTimeToLive(int ttl) throws IOException
{
if (isClosed())
throw new SocketException("socket is closed");
if (ttl <= 0 || ttl > 255)
throw new IllegalArgumentException("Invalid ttl: " + ttl);
getImpl().setTimeToLive(ttl);
}
/**
* Joins the specified multicast group.
*
* @param mcastaddr The address of the group to join
*
* @exception IOException If an error occurs
* @exception SecurityException If a security manager exists and its
* checkMulticast method doesn't allow the operation
*/
public void joinGroup(InetAddress mcastaddr) throws IOException
{
if (isClosed())
throw new SocketException("socket is closed");
if (! mcastaddr.isMulticastAddress())
throw new IOException("Not a Multicast address");
SecurityManager s = System.getSecurityManager();
if (s != null)
s.checkMulticast(mcastaddr);
getImpl().join(mcastaddr);
}
/**
* Leaves the specified multicast group
*
* @param mcastaddr The address of the group to leave
*
* @exception IOException If an error occurs
* @exception SecurityException If a security manager exists and its
* checkMulticast method doesn't allow the operation
*/
public void leaveGroup(InetAddress mcastaddr) throws IOException
{
if (isClosed())
throw new SocketException("socket is closed");
if (! mcastaddr.isMulticastAddress())
throw new IOException("Not a Multicast address");
SecurityManager s = System.getSecurityManager();
if (s != null)
s.checkMulticast(mcastaddr);
getImpl().leave(mcastaddr);
}
/**
* Joins the specified mulitcast group on a specified interface.
*
* @param mcastaddr The multicast address to join
* @param netIf The local network interface to receive the multicast
* messages on or null to defer the interface set by #setInterface or
* #setNetworkInterface
*
* @exception IOException If an error occurs
* @exception IllegalArgumentException If address type is not supported
* @exception SecurityException If a security manager exists and its
* checkMulticast method doesn't allow the operation
*
* @see MulticastSocket#setInterface(InetAddress addr)
* @see MulticastSocket#setNetworkInterface(NetworkInterface netIf)
*
* @since 1.4
*/
public void joinGroup(SocketAddress mcastaddr, NetworkInterface netIf)
throws IOException
{
if (isClosed())
throw new SocketException("socket is closed");
if (! (mcastaddr instanceof InetSocketAddress))
throw new IllegalArgumentException("SocketAddress type not supported");
InetSocketAddress tmp = (InetSocketAddress) mcastaddr;
if (! tmp.getAddress().isMulticastAddress())
throw new IOException("Not a Multicast address");
SecurityManager s = System.getSecurityManager();
if (s != null)
s.checkMulticast(tmp.getAddress());
getImpl().joinGroup(mcastaddr, netIf);
}
/**
* Leaves the specified mulitcast group on a specified interface.
*
* @param mcastaddr The multicast address to leave
* @param netIf The local networki interface or null to defer to the
* interface set by setInterface or setNetworkInterface
*
* @exception IOException If an error occurs
* @exception IllegalArgumentException If address type is not supported
* @exception SecurityException If a security manager exists and its
* checkMulticast method doesn't allow the operation
*
* @see MulticastSocket#setInterface(InetAddress addr)
* @see MulticastSocket#setNetworkInterface(NetworkInterface netIf)
*
* @since 1.4
*/
public void leaveGroup(SocketAddress mcastaddr, NetworkInterface netIf)
throws IOException
{
if (isClosed())
throw new SocketException("socket is closed");
InetSocketAddress tmp = (InetSocketAddress) mcastaddr;
if (! tmp.getAddress().isMulticastAddress())
throw new IOException("Not a Multicast address");
SecurityManager s = System.getSecurityManager();
if (s != null)
s.checkMulticast(tmp.getAddress());
getImpl().leaveGroup(mcastaddr, netIf);
}
/**
* Sends a packet of data to a multicast address with a TTL that is
* different from the default TTL on this socket. The default TTL for
* the socket is not changed.
*
* @param packet The packet of data to send
* @param ttl The TTL for this packet
*
* @exception IOException If an error occurs
* @exception SecurityException If a security manager exists and its
* checkConnect or checkMulticast method doesn't allow the operation
*
* @deprecated
*/
public synchronized void send(DatagramPacket packet, byte ttl)
throws IOException
{
if (isClosed())
throw new SocketException("socket is closed");
SecurityManager s = System.getSecurityManager();
if (s != null)
{
InetAddress addr = packet.getAddress();
if (addr.isMulticastAddress())
s.checkPermission(new SocketPermission(addr.getHostName()
+ packet.getPort(),
"accept,connect"));
else
s.checkConnect(addr.getHostAddress(), packet.getPort());
}
int oldttl = getImpl().getTimeToLive();
getImpl().setTimeToLive(((int) ttl) & 0xFF);
getImpl().send(packet);
getImpl().setTimeToLive(oldttl);
}
}

View file

@ -0,0 +1,90 @@
/* NetPermission.java -- A class for basic miscellaneous network permission
Copyright (C) 1998, 2000, 2003 Free Software Foundation, Inc.
This file is part of GNU Classpath.
GNU Classpath is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2, or (at your option)
any later version.
GNU Classpath is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with GNU Classpath; see the file COPYING. If not, write to the
Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301 USA.
Linking this library statically or dynamically with other modules is
making a combined work based on this library. Thus, the terms and
conditions of the GNU General Public License cover the whole
combination.
As a special exception, the copyright holders of this library give you
permission to link this library with independent modules to produce an
executable, regardless of the license terms of these independent
modules, and to copy and distribute the resulting executable under
terms of your choice, provided that you also meet, for each linked
independent module, the terms and conditions of the license of that
module. An independent module is a module which is not derived from
or based on this library. If you modify this library, you may extend
this exception to your version of the library, but you are not
obligated to do so. If you do not wish to do so, delete this
exception statement from your version. */
package java.net;
import java.security.BasicPermission;
/**
* This class is used to model miscellaneous network permissions. It is
* a subclass of <code>BasicPermission</code>. This means that it models a
* "boolean" permission. One that you either have or do not have. Thus
* there is no permitted action list associated with this object.
*
* The following permission names are defined for this class:
*
* <ul>
* <li>setDefaultAuthenticator - Grants the ability to install a facility
* to collect username and password information when requested by a
* web site or proxy server.</li>
* <li>requestPasswordAuthentication - Grants the ability to ask the
* authentication facility for the user's password.</li>
* <li>specifyStreamHandler - Grants the permission to specify the
* stream handler class used when loading from a URL.</li>
* </ul>
*
* @author Aaron M. Renn (arenn@urbanophile.com)
*/
public final class NetPermission extends BasicPermission
{
static final long serialVersionUID = -8343910153355041693L;
/**
* Initializes a new instance of <code>NetPermission</code> with the
* specified name.
*
* @param name The name of this permission.
*/
public NetPermission(String name)
{
super(name);
}
/**
* Initializes a new instance of <code>NetPermission</code> with the
* specified name and perms. Note that the perms field is irrelevant and is
* ignored. This constructor should never need to be used.
*
* @param name The name of this permission
* @param perms The permitted actions of this permission (ignored)
*/
public NetPermission(String name, String perms)
{
super(name);
}
}

View file

@ -0,0 +1,259 @@
/* NetworkInterface.java --
Copyright (C) 2002, 2003, 2004, 2005 Free Software Foundation, Inc.
This file is part of GNU Classpath.
GNU Classpath is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2, or (at your option)
any later version.
GNU Classpath is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with GNU Classpath; see the file COPYING. If not, write to the
Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301 USA.
Linking this library statically or dynamically with other modules is
making a combined work based on this library. Thus, the terms and
conditions of the GNU General Public License cover the whole
combination.
As a special exception, the copyright holders of this library give you
permission to link this library with independent modules to produce an
executable, regardless of the license terms of these independent
modules, and to copy and distribute the resulting executable under
terms of your choice, provided that you also meet, for each linked
independent module, the terms and conditions of the license of that
module. An independent module is a module which is not derived from
or based on this library. If you modify this library, you may extend
this exception to your version of the library, but you are not
obligated to do so. If you do not wish to do so, delete this
exception statement from your version. */
package java.net;
import java.util.Enumeration;
import java.util.Vector;
/**
* This class models a network interface on the host computer. A network
* interface contains a name (typically associated with a specific
* hardware adapter) and a list of addresses that are bound to it.
* For example, an ethernet interface may be named "eth0" and have the
* address 192.168.1.101 assigned to it.
*
* @author Michael Koch (konqueror@gmx.de)
* @since 1.4
*/
public final class NetworkInterface
{
private String name;
private Vector inetAddresses;
NetworkInterface(String name, InetAddress address)
{
this.name = name;
this.inetAddresses = new Vector(1, 1);
this.inetAddresses.add(address);
}
NetworkInterface(String name, InetAddress[] addresses)
{
this.name = name;
this.inetAddresses = new Vector(addresses.length, 1);
for (int i = 0; i < addresses.length; i++)
this.inetAddresses.add(addresses[i]);
}
/**
* Returns the name of the network interface
*
* @return The name of the interface.
*/
public String getName()
{
return name;
}
/**
* Returns all available addresses of the network interface
*
* If a @see SecurityManager is available all addresses are checked
* with @see SecurityManager::checkConnect() if they are available.
* Only <code>InetAddresses</code> are returned where the security manager
* doesn't throw an exception.
*
* @return An enumeration of all addresses.
*/
public Enumeration getInetAddresses()
{
SecurityManager s = System.getSecurityManager();
if (s == null)
return inetAddresses.elements();
Vector tmpInetAddresses = new Vector(1, 1);
for (Enumeration addresses = inetAddresses.elements();
addresses.hasMoreElements();)
{
InetAddress addr = (InetAddress) addresses.nextElement();
try
{
s.checkConnect(addr.getHostAddress(), 58000);
tmpInetAddresses.add(addr);
}
catch (SecurityException e)
{
// Ignore.
}
}
return tmpInetAddresses.elements();
}
/**
* Returns the display name of the interface
*
* @return The display name of the interface
*/
public String getDisplayName()
{
return name;
}
/**
* Returns an network interface by name
*
* @param name The name of the interface to return
*
* @return a <code>NetworkInterface</code> object representing the interface,
* or null if there is no interface with that name.
*
* @exception SocketException If an error occurs
* @exception NullPointerException If the specified name is null
*/
public static NetworkInterface getByName(String name)
throws SocketException
{
Vector networkInterfaces = VMNetworkInterface.getInterfaces();
for (Enumeration e = networkInterfaces.elements(); e.hasMoreElements();)
{
NetworkInterface tmp = (NetworkInterface) e.nextElement();
if (name.equals(tmp.getName()))
return tmp;
}
// No interface with the given name found.
return null;
}
/**
* Return a network interface by its address
*
* @param addr The address of the interface to return
*
* @return the interface, or <code>null</code> if none found
*
* @exception SocketException If an error occurs
* @exception NullPointerException If the specified addess is null
*/
public static NetworkInterface getByInetAddress(InetAddress addr)
throws SocketException
{
Vector networkInterfaces = VMNetworkInterface.getInterfaces();
for (Enumeration interfaces = networkInterfaces.elements();
interfaces.hasMoreElements();)
{
NetworkInterface tmp = (NetworkInterface) interfaces.nextElement();
for (Enumeration addresses = tmp.inetAddresses.elements();
addresses.hasMoreElements();)
{
if (addr.equals((InetAddress) addresses.nextElement()))
return tmp;
}
}
throw new SocketException("no network interface is bound to such an IP address");
}
/**
* Return an <code>Enumeration</code> of all available network interfaces
*
* @return all interfaces
*
* @exception SocketException If an error occurs
*/
public static Enumeration getNetworkInterfaces() throws SocketException
{
Vector networkInterfaces = VMNetworkInterface.getInterfaces();
if (networkInterfaces.isEmpty())
return null;
return networkInterfaces.elements();
}
/**
* Checks if the current instance is equal to obj
*
* @param obj The object to compare with
*
* @return <code>true</code> if equal, <code>false</code> otherwise
*/
public boolean equals(Object obj)
{
if (! (obj instanceof NetworkInterface))
return false;
NetworkInterface tmp = (NetworkInterface) obj;
return (name.equals(tmp.name) && inetAddresses.equals(tmp.inetAddresses));
}
/**
* Returns the hashcode of the current instance
*
* @return the hashcode
*/
public int hashCode()
{
// FIXME: hash correctly
return name.hashCode() + inetAddresses.hashCode();
}
/**
* Returns a string representation of the interface
*
* @return the string
*/
public String toString()
{
// FIXME: check if this is correct
String result;
String separator = System.getProperty("line.separator");
result =
"name: " + getDisplayName() + " (" + getName() + ") addresses:"
+ separator;
for (Enumeration e = inetAddresses.elements(); e.hasMoreElements();)
{
InetAddress address = (InetAddress) e.nextElement();
result += address.toString() + ";" + separator;
}
return result;
}
}

View file

@ -0,0 +1,74 @@
/* NoRouteToHostException.java -- Cannot connect to a host
Copyright (C) 1998, 1999, 2000, 2001, 2002 Free Software Foundation, Inc.
This file is part of GNU Classpath.
GNU Classpath is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2, or (at your option)
any later version.
GNU Classpath is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with GNU Classpath; see the file COPYING. If not, write to the
Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301 USA.
Linking this library statically or dynamically with other modules is
making a combined work based on this library. Thus, the terms and
conditions of the GNU General Public License cover the whole
combination.
As a special exception, the copyright holders of this library give you
permission to link this library with independent modules to produce an
executable, regardless of the license terms of these independent
modules, and to copy and distribute the resulting executable under
terms of your choice, provided that you also meet, for each linked
independent module, the terms and conditions of the license of that
module. An independent module is a module which is not derived from
or based on this library. If you modify this library, you may extend
this exception to your version of the library, but you are not
obligated to do so. If you do not wish to do so, delete this
exception statement from your version. */
package java.net;
/**
* This exception indicates that there is no TCP/IP route to the requested
* host. This is often due to a misconfigured routing table.
*
* @author Aaron M. Renn (arenn@urbanophile.com)
* @author Warren Levy (warrenl@cygnus.com)
* @since 1.1
* @status updated to 1.4
*/
public class NoRouteToHostException extends SocketException
{
/**
* Compatible with JDK 1.1+.
*/
private static final long serialVersionUID = -1897550894873493790L;
/**
* Create an instance without a descriptive error message.
*/
public NoRouteToHostException()
{
}
/**
* Create an instance with a descriptive error message, such as the text
* from strerror(3).
*
* @param message a message describing the error that occurred
*/
public NoRouteToHostException(String message)
{
super(message);
}
} // class NoRouteToHostException

View file

@ -0,0 +1,92 @@
/* PasswordAuthentication.java -- Container class for username/password pairs
Copyright (C) 1998, 2000, 2003 Free Software Foundation, Inc.
This file is part of GNU Classpath.
GNU Classpath is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2, or (at your option)
any later version.
GNU Classpath is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with GNU Classpath; see the file COPYING. If not, write to the
Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301 USA.
Linking this library statically or dynamically with other modules is
making a combined work based on this library. Thus, the terms and
conditions of the GNU General Public License cover the whole
combination.
As a special exception, the copyright holders of this library give you
permission to link this library with independent modules to produce an
executable, regardless of the license terms of these independent
modules, and to copy and distribute the resulting executable under
terms of your choice, provided that you also meet, for each linked
independent module, the terms and conditions of the license of that
module. An independent module is a module which is not derived from
or based on this library. If you modify this library, you may extend
this exception to your version of the library, but you are not
obligated to do so. If you do not wish to do so, delete this
exception statement from your version. */
package java.net;
/**
* This class serves a container for username/password pairs.
*
* @author Aaron M. Renn (arenn@urbanophile.com)
*
* @since 1.2
*/
public final class PasswordAuthentication
{
/**
* The username
*/
private String username;
/**
* The password
*/
private char[] password;
/**
* Creates a new <code>PasswordAuthentication</code> object from the
* specified username and password.
*
* @param username The username for this object
* @param password The password for this object
*/
public PasswordAuthentication(String username, char[] password)
{
this.username = username;
this.password = password;
}
/**
* Returns the username associated with this object
*
* @return The username
*/
public String getUserName()
{
return username;
}
/**
* Returns the password associated with this object
*
* @return The password
*/
public char[] getPassword()
{
return password;
}
}

View file

@ -0,0 +1,72 @@
/* PortUnreachableException.java -- received an ICMP port unreachable datagram
Copyright (C) 2002 Free Software Foundation, Inc.
This file is part of GNU Classpath.
GNU Classpath is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2, or (at your option)
any later version.
GNU Classpath is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with GNU Classpath; see the file COPYING. If not, write to the
Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301 USA.
Linking this library statically or dynamically with other modules is
making a combined work based on this library. Thus, the terms and
conditions of the GNU General Public License cover the whole
combination.
As a special exception, the copyright holders of this library give you
permission to link this library with independent modules to produce an
executable, regardless of the license terms of these independent
modules, and to copy and distribute the resulting executable under
terms of your choice, provided that you also meet, for each linked
independent module, the terms and conditions of the license of that
module. An independent module is a module which is not derived from
or based on this library. If you modify this library, you may extend
this exception to your version of the library, but you are not
obligated to do so. If you do not wish to do so, delete this
exception statement from your version. */
package java.net;
/**
* This exception signals that an ICMP port unreachable datagram has been
* received.
*
* @author Eric Blake (ebb9@email.byu.edu)
* @since 1.4
* @status updated to 1.4
*/
public class PortUnreachableException extends SocketException
{
/**
* Compatible with JDK 1.0+.
*/
private static final long serialVersionUID = 8462541992376507323L;
/**
* Create a new instance without a descriptive error message.
*/
public PortUnreachableException()
{
}
/**
* Create a new instance with a descriptive error message.
*
* @param message a message describing the error that occurred
*/
public PortUnreachableException(String message)
{
super(message);
}
} // class PortUnreachableException

View file

@ -0,0 +1,75 @@
/* ProtocolException.java -- a low level protocol error occurred
Copyright (C) 1998, 1999, 2000, 2001, 2002 Free Software Foundation, Inc.
This file is part of GNU Classpath.
GNU Classpath is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2, or (at your option)
any later version.
GNU Classpath is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with GNU Classpath; see the file COPYING. If not, write to the
Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301 USA.
Linking this library statically or dynamically with other modules is
making a combined work based on this library. Thus, the terms and
conditions of the GNU General Public License cover the whole
combination.
As a special exception, the copyright holders of this library give you
permission to link this library with independent modules to produce an
executable, regardless of the license terms of these independent
modules, and to copy and distribute the resulting executable under
terms of your choice, provided that you also meet, for each linked
independent module, the terms and conditions of the license of that
module. An independent module is a module which is not derived from
or based on this library. If you modify this library, you may extend
this exception to your version of the library, but you are not
obligated to do so. If you do not wish to do so, delete this
exception statement from your version. */
package java.net;
import java.io.IOException;
/**
* This exception indicates that some sort of low level protocol
* exception occurred. Look in the descriptive message (if any) for
* details on what went wrong.
*
* @author Aaron M. Renn (arenn@urbanophile.com)
* @author Warren Levy (warrenl@cygnus.com)
* @status updated to 1.4
*/
public class ProtocolException extends IOException
{
/**
* Compatible with JDK 1.0+.
*/
private static final long serialVersionUID = -6098449442062388080L;
/**
* Create a new instance without a descriptive error message.
*/
public ProtocolException()
{
}
/**
* Create a new instance with a descriptive error message.
*
* @param message a message describing the error that occurred
*/
public ProtocolException(String message)
{
super(message);
}
} // class ProtocolException

View file

@ -0,0 +1,48 @@
X ContentHandlerFactory
X FileNameMap
X SocketImplFactory
X URLStreamHandlerFactory
* Authenticator
* ContentHandler
+ DatagramPacket
+ DatagramSocket
+ DatagramSocketImpl
+ HttpURLConnection
+ InetAddress
* JarURLConnection
+ MulticastSocket
* NetPermission
* PasswordAuthentication
+ PlainDatagramSocketImpl
+ PlainSocketImpl (internal)
+ ServerSocket
+ Socket
+ SocketImpl
+ SocketInputStream (internal)
+ SocketOptions (internal)
+ SocketOutputStream (internal)
* SocketPermission
+ URL
URLClassLoader
+ URLConnection
* URLEncoder
+ URLStreamHandler
X BindException
X ConnectException
X MalformedURLException
X NoRouteToHostException
X ProtocolException
X SocketException
X UnknownHostException
X UnknownServiceException
---------------
+ Native InetAddress
+ Native SocketImpl
+ Native DatagramSocketImpl
+ Protocol Handler for HTTP
Protocol Handler for FTP
+ ContentHandler for text
ContentHandler for gif
ContentHandler for jpeg

View file

@ -0,0 +1,599 @@
/* ServerSocket.java -- Class for implementing server side sockets
Copyright (C) 1998, 1999, 2000, 2002, 2003, 2004
Free Software Foundation, Inc.
This file is part of GNU Classpath.
GNU Classpath is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2, or (at your option)
any later version.
GNU Classpath is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with GNU Classpath; see the file COPYING. If not, write to the
Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301 USA.
Linking this library statically or dynamically with other modules is
making a combined work based on this library. Thus, the terms and
conditions of the GNU General Public License cover the whole
combination.
As a special exception, the copyright holders of this library give you
permission to link this library with independent modules to produce an
executable, regardless of the license terms of these independent
modules, and to copy and distribute the resulting executable under
terms of your choice, provided that you also meet, for each linked
independent module, the terms and conditions of the license of that
module. An independent module is a module which is not derived from
or based on this library. If you modify this library, you may extend
this exception to your version of the library, but you are not
obligated to do so. If you do not wish to do so, delete this
exception statement from your version. */
package java.net;
import gnu.java.net.PlainSocketImpl;
import java.io.IOException;
import java.nio.channels.IllegalBlockingModeException;
import java.nio.channels.ServerSocketChannel;
/* Written using on-line Java Platform 1.2 API Specification.
* Status: I believe all methods are implemented.
*/
/**
* This class models server side sockets. The basic model is that the
* server socket is created and bound to some well known port. It then
* listens for and accepts connections. At that point the client and
* server sockets are ready to communicate with one another utilizing
* whatever application layer protocol they desire.
*
* As with the <code>Socket</code> class, most instance methods of this class
* simply redirect their calls to an implementation class.
*
* @author Aaron M. Renn (arenn@urbanophile.com)
* @author Per Bothner (bothner@cygnus.com)
*/
public class ServerSocket
{
/**
* This is the user defined SocketImplFactory, if one is supplied
*/
private static SocketImplFactory factory;
/**
* This is the SocketImp object to which most instance methods in this
* class are redirected
*/
private SocketImpl impl;
/**
* We need to retain the local address even after the socket is closed.
*/
private InetSocketAddress local;
/*
* This constructor is only used by java.nio.
*/
// FIXME: Workaround a bug in gcj.
//ServerSocket (PlainSocketImpl impl) throws IOException
ServerSocket(SocketImpl impl) throws IOException
{
if (impl == null)
throw new NullPointerException("impl may not be null");
this.impl = impl;
this.impl.create(true);
}
/*
* This method is only used by java.nio.
*/
// FIXME: Workaround a bug in gcj.
//PlainSocketImpl getImpl()
SocketImpl getImpl()
{
return impl;
}
/**
* Constructor that simply sets the implementation.
*
* @exception IOException If an error occurs
*
* @specnote This constructor is public since JDK 1.4
*/
public ServerSocket() throws IOException
{
if (factory != null)
impl = factory.createSocketImpl();
else
impl = new PlainSocketImpl();
impl.create(true);
}
/**
* Creates a server socket and binds it to the specified port. If the
* port number is 0, a random free port will be chosen. The pending
* connection queue on this socket will be set to 50.
*
* @param port The port number to bind to
*
* @exception IOException If an error occurs
* @exception SecurityException If a security manager exists and its
* checkListen method doesn't allow the operation
*/
public ServerSocket(int port) throws IOException
{
this(port, 50);
}
/**
* Creates a server socket and binds it to the specified port. If the
* port number is 0, a random free port will be chosen. The pending
* connection queue on this socket will be set to the value passed as
* arg2.
*
* @param port The port number to bind to
* @param backlog The length of the pending connection queue
*
* @exception IOException If an error occurs
* @exception SecurityException If a security manager exists and its
* checkListen method doesn't allow the operation
*/
public ServerSocket(int port, int backlog) throws IOException
{
this(port, backlog, null);
}
/**
* Creates a server socket and binds it to the specified port. If the
* port number is 0, a random free port will be chosen. The pending
* connection queue on this socket will be set to the value passed as
* backlog. The third argument specifies a particular local address to
* bind t or null to bind to all local address.
*
* @param port The port number to bind to
* @param backlog The length of the pending connection queue
* @param bindAddr The address to bind to, or null to bind to all addresses
*
* @exception IOException If an error occurs
* @exception SecurityException If a security manager exists and its
* checkListen method doesn't allow the operation
*
* @since 1.1
*/
public ServerSocket(int port, int backlog, InetAddress bindAddr)
throws IOException
{
this();
// bind/listen socket
bind(new InetSocketAddress(bindAddr, port), backlog);
}
/**
* Binds the server socket to a specified socket address
*
* @param endpoint The socket address to bind to
*
* @exception IOException If an error occurs
* @exception IllegalArgumentException If address type is not supported
* @exception SecurityException If a security manager exists and its
* checkListen method doesn't allow the operation
*
* @since 1.4
*/
public void bind(SocketAddress endpoint) throws IOException
{
bind(endpoint, 50);
}
/**
* Binds the server socket to a specified socket address
*
* @param endpoint The socket address to bind to
* @param backlog The length of the pending connection queue
*
* @exception IOException If an error occurs
* @exception IllegalArgumentException If address type is not supported
* @exception SecurityException If a security manager exists and its
* checkListen method doesn't allow the operation
*
* @since 1.4
*/
public void bind(SocketAddress endpoint, int backlog)
throws IOException
{
if (isClosed())
throw new SocketException("ServerSocket is closed");
if (! (endpoint instanceof InetSocketAddress))
throw new IllegalArgumentException("Address type not supported");
InetSocketAddress tmp = (InetSocketAddress) endpoint;
SecurityManager s = System.getSecurityManager();
if (s != null)
s.checkListen(tmp.getPort());
InetAddress addr = tmp.getAddress();
// Initialize addr with 0.0.0.0.
if (addr == null)
addr = InetAddress.ANY_IF;
try
{
impl.bind(addr, tmp.getPort());
impl.listen(backlog);
local = new InetSocketAddress(
(InetAddress) impl.getOption(SocketOptions.SO_BINDADDR),
impl.getLocalPort());
}
catch (IOException exception)
{
close();
throw exception;
}
catch (RuntimeException exception)
{
close();
throw exception;
}
catch (Error error)
{
close();
throw error;
}
}
/**
* This method returns the local address to which this socket is bound
*
* @return The socket's local address
*/
public InetAddress getInetAddress()
{
if (local == null)
return null;
return local.getAddress();
}
/**
* This method returns the local port number to which this socket is bound
*
* @return The socket's port number
*/
public int getLocalPort()
{
if (local == null)
return -1;
return local.getPort();
}
/**
* Returns the local socket address
*
* @return the local socket address, null if not bound
*
* @since 1.4
*/
public SocketAddress getLocalSocketAddress()
{
return local;
}
/**
* Accepts a new connection and returns a connected <code>Socket</code>
* instance representing that connection. This method will block until a
* connection is available.
*
* @return socket object for the just accepted connection
*
* @exception IOException If an error occurs
* @exception SecurityException If a security manager exists and its
* checkListen method doesn't allow the operation
* @exception IllegalBlockingModeException If this socket has an associated
* channel, and the channel is in non-blocking mode
* @exception SocketTimeoutException If a timeout was previously set with
* setSoTimeout and the timeout has been reached
*/
public Socket accept() throws IOException
{
SecurityManager sm = System.getSecurityManager();
if (sm != null)
sm.checkListen(impl.getLocalPort());
Socket socket = new Socket();
try
{
implAccept(socket);
}
catch (IOException e)
{
try
{
socket.close();
}
catch (IOException e2)
{
// Ignore.
}
throw e;
}
return socket;
}
/**
* This protected method is used to help subclasses override
* <code>ServerSocket.accept()</code>. The passed in socket will be
* connected when this method returns.
*
* @param socket The socket that is used for the accepted connection
*
* @exception IOException If an error occurs
* @exception IllegalBlockingModeException If this socket has an associated
* channel, and the channel is in non-blocking mode
*
* @since 1.1
*/
protected final void implAccept(Socket socket) throws IOException
{
if (isClosed())
throw new SocketException("ServerSocket is closed");
// The Sun spec says that if we have an associated channel and
// it is in non-blocking mode, we throw an IllegalBlockingModeException.
// However, in our implementation if the channel itself initiated this
// operation, then we must honor it regardless of its blocking mode.
if (getChannel() != null && ! getChannel().isBlocking()
&& ! ((PlainSocketImpl) getImpl()).isInChannelOperation())
throw new IllegalBlockingModeException();
impl.accept(socket.impl);
socket.implCreated = true;
}
/**
* Closes this socket and stops listening for connections
*
* @exception IOException If an error occurs
*/
public void close() throws IOException
{
if (isClosed())
return;
impl.close();
impl = null;
if (getChannel() != null)
getChannel().close();
}
/**
* Returns the unique <code>ServerSocketChannel</code> object
* associated with this socket, if any.
*
* <p>The socket only has a <code>ServerSocketChannel</code> if its created
* by <code>ServerSocketChannel.open()</code>.</p>
*
* @return the associated socket channel, null if none exists
*
* @since 1.4
*/
public ServerSocketChannel getChannel()
{
return null;
}
/**
* Returns true when the socket is bound, otherwise false
*
* @return true if socket is bound, false otherwise
*
* @since 1.4
*/
public boolean isBound()
{
return local != null;
}
/**
* Returns true if the socket is closed, otherwise false
*
* @return true if socket is closed, false otherwise
*
* @since 1.4
*/
public boolean isClosed()
{
return impl == null;
}
/**
* Sets the value of SO_TIMEOUT. A value of 0 implies that SO_TIMEOUT is
* disabled (ie, operations never time out). This is the number of
* milliseconds a socket operation can block before an
* InterruptedIOException is thrown.
*
* @param timeout The new SO_TIMEOUT value
*
* @exception SocketException If an error occurs
*
* @since 1.1
*/
public void setSoTimeout(int timeout) throws SocketException
{
if (isClosed())
throw new SocketException("ServerSocket is closed");
if (timeout < 0)
throw new IllegalArgumentException("SO_TIMEOUT value must be >= 0");
impl.setOption(SocketOptions.SO_TIMEOUT, new Integer(timeout));
}
/**
* Retrieves the current value of the SO_TIMEOUT setting. A value of 0
* implies that SO_TIMEOUT is disabled (ie, operations never time out).
* This is the number of milliseconds a socket operation can block before
* an InterruptedIOException is thrown.
*
* @return The value of SO_TIMEOUT
*
* @exception IOException If an error occurs
*
* @since 1.1
*/
public int getSoTimeout() throws IOException
{
if (isClosed())
throw new SocketException("ServerSocket is closed");
Object timeout = impl.getOption(SocketOptions.SO_TIMEOUT);
if (! (timeout instanceof Integer))
throw new IOException("Internal Error");
return ((Integer) timeout).intValue();
}
/**
* Enables/Disables the SO_REUSEADDR option
*
* @param on true if SO_REUSEADDR should be enabled, false otherwise
*
* @exception SocketException If an error occurs
*
* @since 1.4
*/
public void setReuseAddress(boolean on) throws SocketException
{
if (isClosed())
throw new SocketException("ServerSocket is closed");
impl.setOption(SocketOptions.SO_REUSEADDR, Boolean.valueOf(on));
}
/**
* Checks if the SO_REUSEADDR option is enabled
*
* @return true if SO_REUSEADDR is set, false otherwise
*
* @exception SocketException If an error occurs
*
* @since 1.4
*/
public boolean getReuseAddress() throws SocketException
{
if (isClosed())
throw new SocketException("ServerSocket is closed");
Object reuseaddr = impl.getOption(SocketOptions.SO_REUSEADDR);
if (! (reuseaddr instanceof Boolean))
throw new SocketException("Internal Error");
return ((Boolean) reuseaddr).booleanValue();
}
/**
* This method sets the value for the system level socket option
* SO_RCVBUF to the specified value. Note that valid values for this
* option are specific to a given operating system.
*
* @param size The new receive buffer size.
*
* @exception SocketException If an error occurs or Socket is not connected
* @exception IllegalArgumentException If size is 0 or negative
*
* @since 1.4
*/
public void setReceiveBufferSize(int size) throws SocketException
{
if (isClosed())
throw new SocketException("ServerSocket is closed");
if (size <= 0)
throw new IllegalArgumentException("SO_RCVBUF value must be > 0");
impl.setOption(SocketOptions.SO_RCVBUF, new Integer(size));
}
/**
* This method returns the value of the system level socket option
* SO_RCVBUF, which is used by the operating system to tune buffer
* sizes for data transfers.
*
* @return The receive buffer size.
*
* @exception SocketException If an error occurs or Socket is not connected
*
* @since 1.4
*/
public int getReceiveBufferSize() throws SocketException
{
if (isClosed())
throw new SocketException("ServerSocket is closed");
Object buf = impl.getOption(SocketOptions.SO_RCVBUF);
if (! (buf instanceof Integer))
throw new SocketException("Internal Error: Unexpected type");
return ((Integer) buf).intValue();
}
/**
* Returns the value of this socket as a <code>String</code>.
*
* @return This socket represented as a <code>String</code>.
*/
public String toString()
{
if (! isBound())
return "ServerSocket[unbound]";
return ("ServerSocket[addr=" + getInetAddress() + ",port="
+ impl.getPort() + ",localport=" + impl.getLocalPort() + "]");
}
/**
* Sets the <code>SocketImplFactory</code> for all
* <code>ServerSocket</code>'s. This may only be done
* once per virtual machine. Subsequent attempts will generate an
* exception. Note that a <code>SecurityManager</code> check is made prior
* to setting the factory. If insufficient privileges exist to set the
* factory, an exception will be thrown
*
* @param fac the factory to set
*
* @exception SecurityException If this operation is not allowed by the
* <code>SecurityManager</code>.
* @exception SocketException If the factory object is already defined
* @exception IOException If any other error occurs
*/
public static synchronized void setSocketFactory(SocketImplFactory fac)
throws IOException
{
factory = fac;
}
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,63 @@
/* SocketAddress.java --
Copyright (C) 2002 Free Software Foundation, Inc.
This file is part of GNU Classpath.
GNU Classpath is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2, or (at your option)
any later version.
GNU Classpath is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with GNU Classpath; see the file COPYING. If not, write to the
Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301 USA.
Linking this library statically or dynamically with other modules is
making a combined work based on this library. Thus, the terms and
conditions of the GNU General Public License cover the whole
combination.
As a special exception, the copyright holders of this library give you
permission to link this library with independent modules to produce an
executable, regardless of the license terms of these independent
modules, and to copy and distribute the resulting executable under
terms of your choice, provided that you also meet, for each linked
independent module, the terms and conditions of the license of that
module. An independent module is a module which is not derived from
or based on this library. If you modify this library, you may extend
this exception to your version of the library, but you are not
obligated to do so. If you do not wish to do so, delete this
exception statement from your version. */
package java.net;
import java.io.Serializable;
/**
* Abstract base class for InetSocketAddress.
* InetSocketAddress is to my knowledge the only derived
* class. [Ronald]
*
* @since 1.4
*/
public abstract class SocketAddress implements Serializable
{
/**
* Compatible with JDK 1.4+
*/
static final long serialVersionUID = 5215720748342549866L;
/**
* Initializes the socket address.
*/
public SocketAddress()
{
}
}

View file

@ -0,0 +1,75 @@
/* SocketException.java -- An exception occurred while performing a socket op
Copyright (C) 1998, 1999, 2001, 2002 Free Software Foundation, Inc.
This file is part of GNU Classpath.
GNU Classpath is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2, or (at your option)
any later version.
GNU Classpath is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with GNU Classpath; see the file COPYING. If not, write to the
Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301 USA.
Linking this library statically or dynamically with other modules is
making a combined work based on this library. Thus, the terms and
conditions of the GNU General Public License cover the whole
combination.
As a special exception, the copyright holders of this library give you
permission to link this library with independent modules to produce an
executable, regardless of the license terms of these independent
modules, and to copy and distribute the resulting executable under
terms of your choice, provided that you also meet, for each linked
independent module, the terms and conditions of the license of that
module. An independent module is a module which is not derived from
or based on this library. If you modify this library, you may extend
this exception to your version of the library, but you are not
obligated to do so. If you do not wish to do so, delete this
exception statement from your version. */
package java.net;
import java.io.IOException;
/**
* This exception indicates that a generic error occurred related to an
* operation on a socket. Check the descriptive message (if any) for
* details on the nature of this error
*
* @author Aaron M. Renn (arenn@urbanophile.com)
* @author Per Bothner
* @status updated to 1.4
*/
public class SocketException extends IOException
{
/**
* Compatible with JDK 1.0+.
*/
private static final long serialVersionUID = -5935874303556886934L;
/**
* Create a new instance without a descriptive error message.
*/
public SocketException()
{
}
/**
* Create a new instance with a descriptive error message.
*
* @param message a message describing the error that occurred
*/
public SocketException(String message)
{
super(message);
}
} // class SocketException

View file

@ -0,0 +1,321 @@
/* SocketImpl.java -- Abstract socket implementation class
Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003
Free Software Foundation, Inc.
This file is part of GNU Classpath.
GNU Classpath is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2, or (at your option)
any later version.
GNU Classpath is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with GNU Classpath; see the file COPYING. If not, write to the
Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301 USA.
Linking this library statically or dynamically with other modules is
making a combined work based on this library. Thus, the terms and
conditions of the GNU General Public License cover the whole
combination.
As a special exception, the copyright holders of this library give you
permission to link this library with independent modules to produce an
executable, regardless of the license terms of these independent
modules, and to copy and distribute the resulting executable under
terms of your choice, provided that you also meet, for each linked
independent module, the terms and conditions of the license of that
module. An independent module is a module which is not derived from
or based on this library. If you modify this library, you may extend
this exception to your version of the library, but you are not
obligated to do so. If you do not wish to do so, delete this
exception statement from your version. */
package java.net;
import java.io.FileDescriptor;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
/* Written using on-line Java Platform 1.2 API Specification.
* Believed complete and correct.
*/
/**
* This abstract class serves as the parent class for socket implementations.
* The implementation class serves an intermediary to native routines that
* perform system specific socket operations.
* <p>
* A default implementation is provided by the system, but this can be
* changed via installing a <code>SocketImplFactory</code> (through a call
* to the static method <code>Socket.setSocketImplFactory</code>). A
* subclass of <code>Socket</code> can also pass in a <code>SocketImpl</code>
* to the <code>Socket(SocketImpl)</code> constructor to use an
* implementation different from the system default without installing
* a factory.
*
* @author Aaron M. Renn (arenn@urbanophile.com)
* @author Per Bothner (bothner@cygnus.com)
*/
public abstract class SocketImpl implements SocketOptions
{
/**
* The address of the remote end of the socket connection
*/
protected InetAddress address;
/**
* A FileDescriptor object representing this socket connection.
*/
protected FileDescriptor fd;
/**
* The port number the socket is bound to locally
*/
protected int localport = -1;
/**
* The port number of the remote end of the socket connection
*/
protected int port;
/**
* Default, no-argument constructor for use by subclasses.
*/
public SocketImpl()
{
}
/**
* Creates a new socket that is not bound to any local address/port and
* is not connected to any remote address/port. This will be created as
* a stream socket if the stream parameter is true, or a datagram socket
* if the stream parameter is false.
*
* @param stream true for a stream socket, false for a datagram socket
*
* @exception IOException If an error occurs
*/
protected abstract void create(boolean stream) throws IOException;
/**
* Connects to the remote hostname and port specified as arguments.
*
* @param host The remote hostname to connect to
* @param port The remote port to connect to
*
* @exception IOException If an error occurs
*/
protected abstract void connect(String host, int port)
throws IOException;
/**
* Connects to the remote address and port specified as arguments.
*
* @param host The remote address to connect to
* @param port The remote port to connect to
*
* @exception IOException If an error occurs
*/
protected abstract void connect(InetAddress host, int port)
throws IOException;
/**
* Connects to the socket to the host specified in address. This
* method blocks until successful connected or the timeout occurs.
* A timeout of zero means no timout.
*
* @param address Data of remote host
* @param timeout time to wait to stop connecting
*
* @exception IOException If an error occurs
*
* @since 1.4
*/
protected abstract void connect(SocketAddress address, int timeout)
throws IOException;
/**
* Binds to the specified port on the specified addr. Note that this addr
* must represent a local IP address.
* <p>
* Note that it is unspecified how to bind to all interfaces on the localhost
* (INADDR_ANY).
*
* @param host The address to bind to
* @param port The port number to bind to
*
* @exception IOException If an error occurs
*/
protected abstract void bind(InetAddress host, int port)
throws IOException;
/**
* Starts listening for connections on a socket. The backlog parameter
* is how many pending connections will queue up waiting to be serviced
* before being accept'ed. If the queue of pending requests exceeds this
* number, additional connections will be refused.
*
* @param backlog The length of the pending connection queue
*
* @exception IOException If an error occurs
*/
protected abstract void listen(int backlog) throws IOException;
/**
* Accepts a connection on this socket.
*
* @param s The implementation object for the accepted connection.
*
* @exception IOException If an error occurs
*/
protected abstract void accept(SocketImpl s) throws IOException;
/**
* Returns an <code>InputStream</code> object for reading from this socket.
*
* @return An <code>InputStream</code> for reading from this socket.
*
* @exception IOException If an error occurs
*/
protected abstract InputStream getInputStream() throws IOException;
/**
* Returns an <code>OutputStream</code> object for writing to this socket
*
* @return An <code>OutputStream</code> for writing to this socket.
*
* @exception IOException If an error occurs.
*/
protected abstract OutputStream getOutputStream() throws IOException;
/**
* Returns the number of bytes that the caller can read from this socket
* without blocking.
*
* @return The number of readable bytes before blocking
*
* @exception IOException If an error occurs
*/
protected abstract int available() throws IOException;
/**
* Closes the socket. This will normally cause any resources, such as the
* InputStream, OutputStream and associated file descriptors to be freed.
* <p>
* Note that if the SO_LINGER option is set on this socket, then the
* operation could block.
*
* @exception IOException If an error occurs
*/
protected abstract void close() throws IOException;
/**
* Returns the FileDescriptor objects for this socket.
*
* @return A FileDescriptor for this socket.
*/
protected FileDescriptor getFileDescriptor()
{
return fd;
}
/**
* Returns the remote address this socket is connected to
*
* @return The remote address
*/
protected InetAddress getInetAddress()
{
return address;
}
/**
* Returns the remote port this socket is connected to
*
* @return The remote port
*/
protected int getPort()
{
return port;
}
/**
* Returns true or false when this socket supports sending urgent data
* or not.
*
* @return true if the socket implementation supports sending urgent data,
* false otherwise
*
* @since 1.4
*/
protected boolean supportsUrgentData()
{
// This method has to be overwritten by socket classes that support
// sending urgend data.
return false;
}
/**
* Sends one byte of urgent data to the socket.
*
* @param data The byte to send, the low eight bits of it
*
* @exception IOException If an error occurs
*
* @since 1.4
*/
protected abstract void sendUrgentData(int data) throws IOException;
/**
* Returns the local port this socket is bound to
*
* @return The local port
*/
protected int getLocalPort()
{
return localport;
}
/**
* Returns a <code>String</code> representing the remote host and port of
* this socket.
*
* @return A <code>String</code> for this socket.
*/
public String toString()
{
return "[addr="
+ ((address == null) ? "0.0.0.0/0.0.0.0" : address.toString())
+ ",port=" + port + ",localport=" + localport + "]";
}
/**
* Shut down the input side of this socket. Subsequent reads will
* return end-of-file.
*
* @exception IOException if an error occurs
*/
protected void shutdownInput() throws IOException
{
throw new IOException("Not implemented in this socket class");
}
/**
* Shut down the output side of this socket. Subsequent writes will
* fail with an IOException.
*
* @exception IOException if an error occurs
*/
protected void shutdownOutput() throws IOException
{
throw new IOException("Not implemented in this socket class");
}
}

View file

@ -0,0 +1,59 @@
/* SocketImplFactory.java -- Interface to create a SocketImpl object
Copyright (C) 1998, 1999, 2000, 2001, 2003 Free Software Foundation, Inc.
This file is part of GNU Classpath.
GNU Classpath is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2, or (at your option)
any later version.
GNU Classpath is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with GNU Classpath; see the file COPYING. If not, write to the
Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301 USA.
Linking this library statically or dynamically with other modules is
making a combined work based on this library. Thus, the terms and
conditions of the GNU General Public License cover the whole
combination.
As a special exception, the copyright holders of this library give you
permission to link this library with independent modules to produce an
executable, regardless of the license terms of these independent
modules, and to copy and distribute the resulting executable under
terms of your choice, provided that you also meet, for each linked
independent module, the terms and conditions of the license of that
module. An independent module is a module which is not derived from
or based on this library. If you modify this library, you may extend
this exception to your version of the library, but you are not
obligated to do so. If you do not wish to do so, delete this
exception statement from your version. */
package java.net;
/** Written using on-line Java Platform 1.2 API Specification.
* Status: Believed complete and correct.
*/
/**
* This interface defines one method which returns a <code>SocketImpl</code>
* object. This should not be needed by ordinary applications.
*
* @author Aaron M. Renn (arenn@urbanophile.com)
* @author Per Bothner (bothner@cygnus.com)
*/
public interface SocketImplFactory
{
/**
* This method returns an instance of the <code>SocketImpl</code> object
*
* @return A <code>SocketImpl</code> object
*/
SocketImpl createSocketImpl();
} // interface SocketImplFactory

View file

@ -0,0 +1,166 @@
/* SocketOptions.java -- Implements options for sockets (duh!)
Copyright (C) 1998, 1999, 2000, 2001,
2002, 2003 Free Software Foundation, Inc.
This file is part of GNU Classpath.
GNU Classpath is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2, or (at your option)
any later version.
GNU Classpath is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with GNU Classpath; see the file COPYING. If not, write to the
Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301 USA.
Linking this library statically or dynamically with other modules is
making a combined work based on this library. Thus, the terms and
conditions of the GNU General Public License cover the whole
combination.
As a special exception, the copyright holders of this library give you
permission to link this library with independent modules to produce an
executable, regardless of the license terms of these independent
modules, and to copy and distribute the resulting executable under
terms of your choice, provided that you also meet, for each linked
independent module, the terms and conditions of the license of that
module. An independent module is a module which is not derived from
or based on this library. If you modify this library, you may extend
this exception to your version of the library, but you are not
obligated to do so. If you do not wish to do so, delete this
exception statement from your version. */
package java.net;
/**
* Written using on-line Java Platform 1.2 API Specification.
* Status: Believed complete and correct.
*/
/**
* This interface is used by <code>SocketImpl</code> and
* <code>DatagramSocketImpl</code> to implement options
* on sockets.
*
* @since 1.2
*
* @author Aaron M. Renn (arenn@urbanophile.com)
* @author Warren Levy (warrenl@cygnus.com)
* @status should be completely JDK 1.4 compatible
*/
public interface SocketOptions
{
/**
* Option id for the SO_KEEPALIVE value
* @since 1.3
*/
int SO_KEEPALIVE = 0x8;
/**
* Option id for the SO_LINGER value
*/
int SO_LINGER = 0x80; // 128
/**
* Option id for the SO_TIMEOUT value
*/
int SO_TIMEOUT = 0x1006; // 4102
/**
* Retrieve the local address to which the socket is bound.
*/
int SO_BINDADDR = 0x0F; // 15
/**
* Option id for the send buffer size
* @since 1.2
*/
int SO_SNDBUF = 0x1001; // 4097
/**
* Option id for the receive buffer size
* @since 1.2
*/
int SO_RCVBUF = 0x1002; // 4098
/**
* Sets the SO_REUSEADDR parameter on a socket
*/
int SO_REUSEADDR = 0x04; // 4
/**
* Sets SO_BROADCAST for a socket
* @since 1.4
*/
int SO_BROADCAST = 0x20; // 32
/**
* Sets SO_OOBINLINE for a socket
* @since 1.4
*/
int SO_OOBINLINE = 0x1003; // 4099
/**
* Option id for the TCP_NODELAY value
*/
int TCP_NODELAY = 0x01; // 1
/**
* Options id for the IP_MULTICAST_IF value
*/
int IP_MULTICAST_IF = 0x10; // 16
/**
* same as above
* @since 1.4
*/
int IP_MULTICAST_IF2 = 0x1F; // 31
/**
* This option enables or disables local loopback of multicast datagrams.
* @since 1.4
*/
int IP_MULTICAST_LOOP = 0x12; // 18
/**
* This option sets the type-of-service or traffic class field in the
* IP header for a TCP or UDP socket.
* @since 1.4
*/
int IP_TOS = 0x03; // 3
/**
* Sets the specified option on a socket to the passed in object. For
* options that take an integer argument, the passed in object is an
* <code>Integer</code>. For options that are set to on or off, the
* value passed will be a <code>Boolean</code>. The <code>optionId</code>
* parameter is one of the defined constants in this interface.
*
* @param optionId The identifier of the option
* @param val The value to set the option to
*
* @exception SocketException If an error occurs
*/
void setOption(int optionId, Object val) throws SocketException;
/**
* Returns the current setting of the specified option. The
* <code>Object</code> returned will be an <code>Integer</code> for options
* that have integer values. For options that are set to on or off, a
* <code>Boolean</code> will be returned. The <code>optionId</code>
* parameter is one of the defined constants in this interface.
*
* @param optionId The option identifier
*
* @return The current value of the option
*
* @exception SocketException If an error occurs
*/
Object getOption(int optionId) throws SocketException;
} // interface SocketOptions

View file

@ -0,0 +1,408 @@
/* SocketPermission.java -- Class modeling permissions for socket operations
Copyright (C) 1998, 2000, 2001, 2002, 2004 Free Software Foundation, Inc.
This file is part of GNU Classpath.
GNU Classpath is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2, or (at your option)
any later version.
GNU Classpath is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with GNU Classpath; see the file COPYING. If not, write to the
Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301 USA.
Linking this library statically or dynamically with other modules is
making a combined work based on this library. Thus, the terms and
conditions of the GNU General Public License cover the whole
combination.
As a special exception, the copyright holders of this library give you
permission to link this library with independent modules to produce an
executable, regardless of the license terms of these independent
modules, and to copy and distribute the resulting executable under
terms of your choice, provided that you also meet, for each linked
independent module, the terms and conditions of the license of that
module. An independent module is a module which is not derived from
or based on this library. If you modify this library, you may extend
this exception to your version of the library, but you are not
obligated to do so. If you do not wish to do so, delete this
exception statement from your version. */
package java.net;
import java.io.Serializable;
import java.security.Permission;
import java.security.PermissionCollection;
/**
* This class models a specific set of permssions for connecting to a
* host. There are two elements to this, the host/port combination and
* the permission list.
* <p>
* The host/port combination is specified as followed
* <p>
* <pre>
* hostname[:[-]port[-[port]]]
* </pre>
* <p>
* The hostname portion can be either a hostname or IP address. If it is
* a hostname, a wildcard is allowed in hostnames. This wildcard is a "*"
* and matches one or more characters. Only one "*" may appear in the
* host and it must be the leftmost character. For example,
* "*.urbanophile.com" matches all hosts in the "urbanophile.com" domain.
* <p>
* The port portion can be either a single value, or a range of values
* treated as inclusive. The first or the last port value in the range
* can be omitted in which case either the minimum or maximum legal
* value for a port (respectively) is used by default. Here are some
* examples:
* <p><ul>
* <li>8080 - Represents port 8080 only</li>
* <li>2000-3000 - Represents ports 2000 through 3000 inclusive</li>
* <li>-4000 - Represents ports 0 through 4000 inclusive</li>
* <li>1024- - Represents ports 1024 through 65535 inclusive</li>
* </ul><p>
* The permission list is a comma separated list of individual permissions.
* These individual permissions are:
* <p>
* <pre>
* accept
* connect
* listen
* resolve
* </pre>
* <p>
* The "listen" permission is only relevant if the host is localhost. If
* any permission at all is specified, then resolve permission is implied to
* exist.
* <p>
* Here are a variety of examples of how to create SocketPermission's
* <p><pre>
* SocketPermission("www.urbanophile.com", "connect");
* Can connect to any port on www.urbanophile.com
* SocketPermission("www.urbanophile.com:80", "connect,accept");
* Can connect to or accept connections from www.urbanophile.com on port 80
* SocketPermission("localhost:1024-", "listen,accept,connect");
* Can connect to, accept from, an listen on any local port number 1024
* and up.
* SocketPermission("*.edu", "connect");
* Can connect to any host in the edu domain
* SocketPermission("197.197.20.1", "accept");
* Can accept connections from 197.197.20.1
* </pre><p>
*
* This class also supports IPv6 addresses. These should be specified
* in either RFC 2732 format or in full uncompressed form.
*
* @since 1.2
*
* @author Aaron M. Renn (arenn@urbanophile.com)
*/
public final class SocketPermission extends Permission implements Serializable
{
static final long serialVersionUID = -7204263841984476862L;
// FIXME: Needs serialization work, including readObject/writeObject methods.
/**
* A hostname/port combination as described above
*/
private transient String hostport;
/**
* A comma separated list of actions for which we have permission
*/
private String actions;
/**
* Initializes a new instance of <code>SocketPermission</code> with the
* specified host/port combination and actions string.
*
* @param hostport The hostname/port number combination
* @param actions The actions string
*/
public SocketPermission(String hostport, String actions)
{
super(hostport);
this.hostport = hostport;
this.actions = actions;
}
/**
* Tests this object for equality against another. This will be true if
* and only if the passed object is an instance of
* <code>SocketPermission</code> and both its hostname/port combination
* and permissions string are identical.
*
* @param obj The object to test against for equality
*
* @return <code>true</code> if object is equal to this object,
* <code>false</code> otherwise.
*/
public boolean equals(Object obj)
{
if (! (obj instanceof SocketPermission))
return false;
if (((SocketPermission) obj).hostport.equals(hostport))
if (((SocketPermission) obj).actions.equals(actions))
return true;
return false;
}
/**
* Returns a hash code value for this object. Overrides the
* <code>Permission.hashCode()</code>.
*
* @return A hash code
*/
public int hashCode()
{
int hash = 100;
if (hostport != null)
hash += hostport.hashCode();
if (actions != null)
hash += actions.hashCode();
return hash;
}
/**
* Returns the list of permission actions in this object in canonical
* order. The canonical order is "connect,listen,accept,resolve"
*
* @return The permitted action string.
*/
public String getActions()
{
boolean found = false;
StringBuffer sb = new StringBuffer("");
if (actions.indexOf("connect") != -1)
{
sb.append("connect");
found = true;
}
if (actions.indexOf("listen") != -1)
if (found)
sb.append(",listen");
else
{
sb.append("listen");
found = true;
}
if (actions.indexOf("accept") != -1)
if (found)
sb.append(",accept");
else
{
sb.append("accept");
found = true;
}
if (found)
sb.append(",resolve");
else if (actions.indexOf("resolve") != -1)
sb.append("resolve");
return sb.toString();
}
/**
* Returns a new <code>PermissionCollection</code> object that can hold
* <code>SocketPermission</code>'s.
*
* @return A new <code>PermissionCollection</code>.
*/
public PermissionCollection newPermissionCollection()
{
// FIXME: Implement
return null;
}
/**
* Returns true if the permission object passed it is implied by the
* this permission. This will be true if:
*
* <ul>
* <li>The argument is of type <code>SocketPermission</code></li>
* <li>The actions list of the argument are in this object's actions</li>
* <li>The port range of the argument is within this objects port range</li>
* <li>The hostname is equal to or a subset of this objects hostname</li>
* </ul>
*
* <p>The argument's hostname will be a subset of this object's hostname if:</p>
*
* <ul>
* <li>The argument's hostname or IP address is equal to this object's.</li>
* <li>The argument's canonical hostname is equal to this object's.</li>
* <li>The argument's canonical name matches this domains hostname with
* wildcards</li>
* </ul>
*
* @param perm The <code>Permission</code> to check against
*
* @return <code>true</code> if the <code>Permission</code> is implied by
* this object, <code>false</code> otherwise.
*/
public boolean implies(Permission perm)
{
SocketPermission p;
// First make sure we are the right object type
if (perm instanceof SocketPermission)
p = (SocketPermission) perm;
else
return false;
// Next check the actions
String ourlist = getActions();
String theirlist = p.getActions();
if (! ourlist.startsWith(theirlist))
return false;
// Now check ports
int ourfirstport = 0;
// Now check ports
int ourlastport = 0;
// Now check ports
int theirfirstport = 0;
// Now check ports
int theirlastport = 0;
// Get ours
if (hostport.indexOf(":") == -1)
{
ourfirstport = 0;
ourlastport = 65535;
}
else
{
// FIXME: Needs bulletproofing.
// This will dump if hostport if all sorts of bad data was passed to
// the constructor
String range = hostport.substring(hostport.indexOf(":") + 1);
if (range.startsWith("-"))
ourfirstport = 0;
else if (range.indexOf("-") == -1)
ourfirstport = Integer.parseInt(range);
else
ourfirstport =
Integer.parseInt(range.substring(0, range.indexOf("-")));
if (range.endsWith("-"))
ourlastport = 65535;
else if (range.indexOf("-") == -1)
ourlastport = Integer.parseInt(range);
else
ourlastport =
Integer.parseInt(range.substring(range.indexOf("-") + 1,
range.length()));
}
// Get theirs
if (p.hostport.indexOf(":") == -1)
{
theirfirstport = 0;
ourlastport = 65535;
}
else
{
// This will dump if hostport if all sorts of bad data was passed to
// the constructor
String range = p.hostport.substring(hostport.indexOf(":") + 1);
if (range.startsWith("-"))
theirfirstport = 0;
else if (range.indexOf("-") == -1)
theirfirstport = Integer.parseInt(range);
else
theirfirstport =
Integer.parseInt(range.substring(0, range.indexOf("-")));
if (range.endsWith("-"))
theirlastport = 65535;
else if (range.indexOf("-") == -1)
theirlastport = Integer.parseInt(range);
else
theirlastport =
Integer.parseInt(range.substring(range.indexOf("-") + 1,
range.length()));
}
// Now check them
if ((theirfirstport < ourfirstport) || (theirlastport > ourlastport))
return false;
// Finally we can check the hosts
String ourhost;
// Finally we can check the hosts
String theirhost;
// Get ours
if (hostport.indexOf(":") == -1)
ourhost = hostport;
else
ourhost = hostport.substring(0, hostport.indexOf(":"));
// Get theirs
if (p.hostport.indexOf(":") == -1)
theirhost = p.hostport;
else
theirhost = p.hostport.substring(0, p.hostport.indexOf(":"));
// Are they equal?
if (ourhost.equals(theirhost))
return true;
// Try the canonical names
String ourcanonical = null;
// Try the canonical names
String theircanonical = null;
try
{
ourcanonical = InetAddress.getByName(ourhost).getHostName();
theircanonical = InetAddress.getByName(theirhost).getHostName();
}
catch (UnknownHostException e)
{
// Who didn't resolve? Just assume current address is canonical enough
// Is this ok to do?
if (ourcanonical == null)
ourcanonical = ourhost;
if (theircanonical == null)
theircanonical = theirhost;
}
if (ourcanonical.equals(theircanonical))
return true;
// Well, last chance. Try for a wildcard
if (ourhost.indexOf("*.") != -1)
{
String wild_domain = ourhost.substring(ourhost.indexOf("*" + 1));
if (theircanonical.endsWith(wild_domain))
return true;
}
// Didn't make it
return false;
}
}

View file

@ -0,0 +1,73 @@
/* SocketTimeoutException.java -- the socket timed out
Copyright (C) 2002 Free Software Foundation, Inc.
This file is part of GNU Classpath.
GNU Classpath is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2, or (at your option)
any later version.
GNU Classpath is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with GNU Classpath; see the file COPYING. If not, write to the
Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301 USA.
Linking this library statically or dynamically with other modules is
making a combined work based on this library. Thus, the terms and
conditions of the GNU General Public License cover the whole
combination.
As a special exception, the copyright holders of this library give you
permission to link this library with independent modules to produce an
executable, regardless of the license terms of these independent
modules, and to copy and distribute the resulting executable under
terms of your choice, provided that you also meet, for each linked
independent module, the terms and conditions of the license of that
module. An independent module is a module which is not derived from
or based on this library. If you modify this library, you may extend
this exception to your version of the library, but you are not
obligated to do so. If you do not wish to do so, delete this
exception statement from your version. */
package java.net;
import java.io.InterruptedIOException;
/**
* This exception signals that a socket read or accept timed out.
*
* @author Eric Blake (ebb9@email.byu.edu)
* @since 1.4
* @status updated to 1.4
*/
public class SocketTimeoutException extends InterruptedIOException
{
/**
* Compatible with JDK 1.4+.
*/
private static final long serialVersionUID = -8846654841826352300L;
/**
* Create a new instance without a descriptive error message.
*/
public SocketTimeoutException()
{
}
/**
* Create a new instance with a descriptive error message.
*
* @param message a message describing the error that occurred
*/
public SocketTimeoutException(String message)
{
super(message);
}
} // class SocketTimeoutException

View file

@ -0,0 +1,24 @@
-- DNS cache purging.
-- Implement ContentHandler chaining (non-JDK feature)
-- Implement MIME type by file determination chaining using external
disk files. (non-JDK feature)
-- Implement determining MIME type from an InputStream
-- Datagram peek()'s
-- Finalize methods for sockets
-- HTTP - caching (supported by JDK?)
-- HTTP - all protocol support beyond basic GET functionality
-- Fix call to Date(String) in URLConnection.getHeaderFieldDate() when
I figure out why DateFormat isn't working.
-- Finish off all JDK 1.2 permissions stuff
-- Write URLClassLoader

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,144 @@
/* URISyntaxException.java -- a string could not be parsed as a URI
Copyright (C) 2002 Free Software Foundation, Inc.
This file is part of GNU Classpath.
GNU Classpath is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2, or (at your option)
any later version.
GNU Classpath is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with GNU Classpath; see the file COPYING. If not, write to the
Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301 USA.
Linking this library statically or dynamically with other modules is
making a combined work based on this library. Thus, the terms and
conditions of the GNU General Public License cover the whole
combination.
As a special exception, the copyright holders of this library give you
permission to link this library with independent modules to produce an
executable, regardless of the license terms of these independent
modules, and to copy and distribute the resulting executable under
terms of your choice, provided that you also meet, for each linked
independent module, the terms and conditions of the license of that
module. An independent module is a module which is not derived from
or based on this library. If you modify this library, you may extend
this exception to your version of the library, but you are not
obligated to do so. If you do not wish to do so, delete this
exception statement from your version. */
package java.net;
/**
* This exception is thrown when a String cannot be parsed as a URI.
*
* @author Eric Blake (ebb9@email.byu.edu)
* @see URI
* @since 1.4
* @status updated to 1.4
*/
public class URISyntaxException extends Exception
{
/**
* Compatible with JDK 1.4+.
*/
private static final long serialVersionUID = 2137979680897488891L;
/**
* The failed input.
*
* @serial the bad URI
*/
private final String input;
/**
* The index of failure.
*
* @serial the location of the problem
*/
private final int index;
/**
* Create an exception from the invalid string, with the index set to -1.
*
* @param input the bad URI
* @param msg the descriptive error message
* @throws NullPointerException if input or msg are null
*/
public URISyntaxException(String input, String msg)
{
this(input, msg, -1);
}
/**
* Create an exception from the invalid string, with the index of the
* point of failure.
*
* @param input the bad URI
* @param msg the descriptive error message
* @param index the index of the parse error, or -1
* @throws NullPointerException if input or msg are null
* @throws IllegalArgumentException if index &lt; -1
*/
public URISyntaxException(String input, String msg, int index)
{
// The toString() hack checks for null.
super(msg.toString());
this.input = input.toString();
this.index = index;
if (index < -1)
throw new IllegalArgumentException();
}
/**
* Returns the bad input string.
*
* @return the bad URI, guaranteed non-null
*/
public String getInput()
{
return input;
}
/**
* Returns the reason for the failure.
*
* @return the message, guaranteed non-null
*/
public String getReason()
{
return super.getMessage();
}
/**
* Returns the index of the failure, or -1.
*
* @return the index of failure
*/
public int getIndex()
{
return index;
}
/**
* Returns a message describing the parse error, as if by
* <code>getReason() + (getIndex() &gt;= 0 ? " at index " + getIndex() : "")
* + ": " + getInput()</code>.
*
* @return the message string
*/
public String getMessage()
{
return (super.getMessage() + (index >= 0 ? " at index " + index : "")
+ ": " + input);
}
}

View file

@ -0,0 +1,956 @@
/* URL.java -- Uniform Resource Locator Class
Copyright (C) 1998, 1999, 2000, 2002, 2003, 2004, 2005
Free Software Foundation, Inc.
This file is part of GNU Classpath.
GNU Classpath is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2, or (at your option)
any later version.
GNU Classpath is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with GNU Classpath; see the file COPYING. If not, write to the
Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301 USA.
Linking this library statically or dynamically with other modules is
making a combined work based on this library. Thus, the terms and
conditions of the GNU General Public License cover the whole
combination.
As a special exception, the copyright holders of this library give you
permission to link this library with independent modules to produce an
executable, regardless of the license terms of these independent
modules, and to copy and distribute the resulting executable under
terms of your choice, provided that you also meet, for each linked
independent module, the terms and conditions of the license of that
module. An independent module is a module which is not derived from
or based on this library. If you modify this library, you may extend
this exception to your version of the library, but you are not
obligated to do so. If you do not wish to do so, delete this
exception statement from your version. */
package java.net;
import gnu.java.net.URLParseError;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.HashMap;
import java.util.StringTokenizer;
/*
* Written using on-line Java Platform 1.2 API Specification, as well
* as "The Java Class Libraries", 2nd edition (Addison-Wesley, 1998).
* Status: Believed complete and correct.
*/
/**
* This final class represents an Internet Uniform Resource Locator (URL).
* For details on the syntax of URL's and what they can be used for,
* refer to RFC 1738, available from <a
* href="http://ds.internic.net/rfcs/rfc1738.txt">
* http://ds.internic.net/rfcs/rfc1738.txt</a>
* <p>
* There are a great many protocols supported by URL's such as "http",
* "ftp", and "file". This object can handle any arbitrary URL for which
* a URLStreamHandler object can be written. Default protocol handlers
* are provided for the "http" and "ftp" protocols. Additional protocols
* handler implementations may be provided in the future. In any case,
* an application or applet can install its own protocol handlers that
* can be "chained" with other protocol hanlders in the system to extend
* the base functionality provided with this class. (Note, however, that
* unsigned applets cannot access properties by default or install their
* own protocol handlers).
* <p>
* This chaining is done via the system property java.protocol.handler.pkgs
* If this property is set, it is assumed to be a "|" separated list of
* package names in which to attempt locating protocol handlers. The
* protocol handler is searched for by appending the string
* ".&lt;protocol&gt;.Handler" to each packed in the list until a hander is
* found. If a protocol handler is not found in this list of packages, or if
* the property does not exist, then the default protocol handler of
* "gnu.java.net.&lt;protocol&gt;.Handler" is tried. If this is
* unsuccessful, a MalformedURLException is thrown.
* <p>
* All of the constructor methods of URL attempt to load a protocol
* handler and so any needed protocol handlers must be installed when
* the URL is constructed.
* <p>
* Here is an example of how URL searches for protocol handlers. Assume
* the value of java.protocol.handler.pkgs is "com.foo|com.bar" and the
* URL is "news://comp.lang.java.programmer". URL would looking the
* following places for protocol handlers:
* <p><pre>
* com.foo.news.Handler
* com.bar.news.Handler
* gnu.java.net.news.Handler
* </pre><p>
* If the protocol handler is not found in any of those locations, a
* MalformedURLException would be thrown.
* <p>
* Please note that a protocol handler must be a subclass of
* URLStreamHandler.
* <p>
* Normally, this class caches protocol handlers. Once it finds a handler
* for a particular protocol, it never tries to look up a new handler
* again. However, if the system property
* gnu.java.net.nocache_protocol_handlers is set, then this
* caching behavior is disabled. This property is specific to this
* implementation. Sun's JDK may or may not do protocol caching, but it
* almost certainly does not examine this property.
* <p>
* Please also note that an application can install its own factory for
* loading protocol handlers (see setURLStreamHandlerFactory). If this is
* done, then the above information is superseded and the behavior of this
* class in loading protocol handlers is dependent on that factory.
*
* @author Aaron M. Renn (arenn@urbanophile.com)
* @author Warren Levy (warrenl@cygnus.com)
*
* @see URLStreamHandler
*/
public final class URL implements Serializable
{
private static final String DEFAULT_SEARCH_PATH =
"gnu.java.net.protocol|gnu.inet";
// Cached System ClassLoader
private static ClassLoader systemClassLoader;
/**
* The name of the protocol for this URL.
* The protocol is always stored in lower case.
*/
private String protocol;
/**
* The "authority" portion of the URL.
*/
private String authority;
/**
* The hostname or IP address of this protocol.
* This includes a possible user. For example <code>joe@some.host.net</code>.
*/
private String host;
/**
* The user information necessary to establish the connection.
*/
private String userInfo;
/**
* The port number of this protocol or -1 if the port number used is
* the default for this protocol.
*/
private int port = -1; // Initialize for constructor using context.
/**
* The "file" portion of the URL. It is defined as <code>path[?query]</code>.
*/
private String file;
/**
* The anchor portion of the URL.
*/
private String ref;
/**
* This is the hashCode for this URL
*/
private int hashCode;
/**
* The protocol handler in use for this URL
*/
transient URLStreamHandler ph;
/**
* If an application installs its own protocol handler factory, this is
* where we keep track of it.
*/
private static URLStreamHandlerFactory factory;
private static final long serialVersionUID = -7627629688361524110L;
/**
* This a table where we cache protocol handlers to avoid the overhead
* of looking them up each time.
*/
private static HashMap ph_cache = new HashMap();
/**
* Whether or not to cache protocol handlers.
*/
private static boolean cache_handlers;
static
{
String s = System.getProperty("gnu.java.net.nocache_protocol_handlers");
if (s == null)
cache_handlers = true;
else
cache_handlers = false;
}
/**
* Constructs a URL and loads a protocol handler for the values passed as
* arguments.
*
* @param protocol The protocol for this URL ("http", "ftp", etc)
* @param host The hostname or IP address to connect to
* @param port The port number to use, or -1 to use the protocol's
* default port
* @param file The "file" portion of the URL.
*
* @exception MalformedURLException If a protocol handler cannot be loaded or
* a parse error occurs.
*/
public URL(String protocol, String host, int port, String file)
throws MalformedURLException
{
this(protocol, host, port, file, null);
}
/**
* Constructs a URL and loads a protocol handler for the values passed in
* as arugments. Uses the default port for the protocol.
*
* @param protocol The protocol for this URL ("http", "ftp", etc)
* @param host The hostname or IP address for this URL
* @param file The "file" portion of this URL.
*
* @exception MalformedURLException If a protocol handler cannot be loaded or
* a parse error occurs.
*/
public URL(String protocol, String host, String file)
throws MalformedURLException
{
this(protocol, host, -1, file, null);
}
/**
* This method initializes a new instance of <code>URL</code> with the
* specified protocol, host, port, and file. Additionally, this method
* allows the caller to specify a protocol handler to use instead of
* the default. If this handler is specified, the caller must have
* the "specifyStreamHandler" permission (see <code>NetPermission</code>)
* or a <code>SecurityException</code> will be thrown.
*
* @param protocol The protocol for this URL ("http", "ftp", etc)
* @param host The hostname or IP address to connect to
* @param port The port number to use, or -1 to use the protocol's default
* port
* @param file The "file" portion of the URL.
* @param ph The protocol handler to use with this URL.
*
* @exception MalformedURLException If no protocol handler can be loaded
* for the specified protocol.
* @exception SecurityException If the <code>SecurityManager</code> exists
* and does not allow the caller to specify its own protocol handler.
*
* @since 1.2
*/
public URL(String protocol, String host, int port, String file,
URLStreamHandler ph) throws MalformedURLException
{
if (protocol == null)
throw new MalformedURLException("null protocol");
protocol = protocol.toLowerCase();
this.protocol = protocol;
if (ph != null)
{
SecurityManager s = System.getSecurityManager();
if (s != null)
s.checkPermission(new NetPermission("specifyStreamHandler"));
this.ph = ph;
}
else
this.ph = getURLStreamHandler(protocol);
if (this.ph == null)
throw new MalformedURLException("Protocol handler not found: "
+ protocol);
this.host = host;
this.port = port;
this.authority = (host != null) ? host : "";
if (port >= 0 && host != null)
this.authority += ":" + port;
int hashAt = file.indexOf('#');
if (hashAt < 0)
{
this.file = file;
this.ref = null;
}
else
{
this.file = file.substring(0, hashAt);
this.ref = file.substring(hashAt + 1);
}
hashCode = hashCode(); // Used for serialization.
}
/**
* Initializes a URL from a complete string specification such as
* "http://www.urbanophile.com/arenn/". First the protocol name is parsed
* out of the string. Then a handler is located for that protocol and
* the parseURL() method of that protocol handler is used to parse the
* remaining fields.
*
* @param spec The complete String representation of a URL
*
* @exception MalformedURLException If a protocol handler cannot be found
* or the URL cannot be parsed
*/
public URL(String spec) throws MalformedURLException
{
this((URL) null, spec != null ? spec : "", (URLStreamHandler) null);
}
/**
* This method parses a String representation of a URL within the
* context of an existing URL. Principally this means that any
* fields not present the URL are inheritied from the context URL.
* This allows relative URL's to be easily constructed. If the
* context argument is null, then a complete URL must be specified
* in the URL string. If the protocol parsed out of the URL is
* different from the context URL's protocol, then then URL String
* is also expected to be a complete URL.
*
* @param context The context on which to parse the specification
* @param spec The string to parse an URL
*
* @exception MalformedURLException If a protocol handler cannot be found
* for the URL cannot be parsed
*/
public URL(URL context, String spec) throws MalformedURLException
{
this(context, spec, (URLStreamHandler) null);
}
/**
* Creates an URL from given arguments
* This method parses a String representation of a URL within the
* context of an existing URL. Principally this means that any fields
* not present the URL are inheritied from the context URL. This allows
* relative URL's to be easily constructed. If the context argument is
* null, then a complete URL must be specified in the URL string.
* If the protocol parsed out of the URL is different
* from the context URL's protocol, then then URL String is also
* expected to be a complete URL.
* <p>
* Additionally, this method allows the caller to specify a protocol handler
* to use instead of the default. If this handler is specified, the caller
* must have the "specifyStreamHandler" permission
* (see <code>NetPermission</code>) or a <code>SecurityException</code>
* will be thrown.
*
* @param context The context in which to parse the specification
* @param spec The string to parse as an URL
* @param ph The stream handler for the URL
*
* @exception MalformedURLException If a protocol handler cannot be found
* or the URL cannot be parsed
* @exception SecurityException If the <code>SecurityManager</code> exists
* and does not allow the caller to specify its own protocol handler.
*
* @since 1.2
*/
public URL(URL context, String spec, URLStreamHandler ph)
throws MalformedURLException
{
/* A protocol is defined by the doc as the substring before a ':'
* as long as the ':' occurs before any '/'.
*
* If context is null, then spec must be an absolute URL.
*
* The relative URL need not specify all the components of a URL.
* If the protocol, host name, or port number is missing, the value
* is inherited from the context. A bare file component is appended
* to the context's file. The optional anchor is not inherited.
*/
// If this is an absolute URL, then ignore context completely.
// An absolute URL must have chars prior to "://" but cannot have a colon
// right after the "://". The second colon is for an optional port value
// and implies that the host from the context is used if available.
int colon;
int slash = spec.indexOf('/');
if ((colon = spec.indexOf("://", 1)) > 0
&& ((colon < slash || slash < 0))
&& ! spec.regionMatches(colon, "://:", 0, 4))
context = null;
if ((colon = spec.indexOf(':')) > 0
&& (colon < slash || slash < 0))
{
// Protocol specified in spec string.
protocol = spec.substring(0, colon).toLowerCase();
if (context != null && context.protocol.equals(protocol))
{
// The 1.2 doc specifically says these are copied to the new URL.
host = context.host;
port = context.port;
file = context.file;
userInfo = context.userInfo;
if (file == null || file.length() == 0)
file = "/";
authority = context.authority;
}
}
else if (context != null)
{
// Protocol NOT specified in spec string.
// Use context fields (except ref) as a foundation for relative URLs.
colon = -1;
protocol = context.protocol;
host = context.host;
port = context.port;
file = context.file;
userInfo = context.userInfo;
if (file == null || file.length() == 0)
file = "/";
authority = context.authority;
}
else // Protocol NOT specified in spec. and no context available.
throw new MalformedURLException("Absolute URL required with null"
+ " context: " + spec);
protocol = protocol.trim();
if (ph != null)
{
SecurityManager s = System.getSecurityManager();
if (s != null)
s.checkPermission(new NetPermission("specifyStreamHandler"));
this.ph = ph;
}
else
this.ph = getURLStreamHandler(protocol);
if (this.ph == null)
throw new MalformedURLException("Protocol handler not found: "
+ protocol);
// JDK 1.2 doc for parseURL specifically states that any '#' ref
// is to be excluded by passing the 'limit' as the indexOf the '#'
// if one exists, otherwise pass the end of the string.
int hashAt = spec.indexOf('#', colon + 1);
try
{
this.ph.parseURL(this, spec, colon + 1,
hashAt < 0 ? spec.length() : hashAt);
}
catch (URLParseError e)
{
throw new MalformedURLException(e.getMessage());
}
if (hashAt >= 0)
ref = spec.substring(hashAt + 1);
hashCode = hashCode(); // Used for serialization.
}
/**
* Test another URL for equality with this one. This will be true only if
* the argument is non-null and all of the fields in the URL's match
* exactly (ie, protocol, host, port, file, and ref). Overrides
* Object.equals(), implemented by calling the equals method of the handler.
*
* @param obj The URL to compare with
*
* @return true if the URL is equal, false otherwise
*/
public boolean equals(Object obj)
{
if (! (obj instanceof URL))
return false;
return ph.equals(this, (URL) obj);
}
/**
* Returns the contents of this URL as an object by first opening a
* connection, then calling the getContent() method against the connection
*
* @return A content object for this URL
* @exception IOException If opening the connection or getting the
* content fails.
*
* @since 1.3
*/
public Object getContent() throws IOException
{
return openConnection().getContent();
}
/**
* Gets the contents of this URL
*
* @param classes The allow classes for the content object.
*
* @return a context object for this URL.
*
* @exception IOException If an error occurs
*/
public Object getContent(Class[] classes) throws IOException
{
// FIXME: implement this
return getContent();
}
/**
* Returns the file portion of the URL.
* Defined as <code>path[?query]</code>.
* Returns the empty string if there is no file portion.
*
* @return The filename specified in this URL, or an empty string if empty.
*/
public String getFile()
{
return file == null ? "" : file;
}
/**
* Returns the path of the URL. This is the part of the file before any '?'
* character.
*
* @return The path specified in this URL, or null if empty.
*
* @since 1.3
*/
public String getPath()
{
// The spec says we need to return an empty string, but some
// applications depends on receiving null when the path is empty.
if (file == null)
return null;
int quest = file.indexOf('?');
return quest < 0 ? getFile() : file.substring(0, quest);
}
/**
* Returns the authority of the URL
*
* @return The authority specified in this URL.
*
* @since 1.3
*/
public String getAuthority()
{
return authority;
}
/**
* Returns the host of the URL
*
* @return The host specified in this URL.
*/
public String getHost()
{
int at = (host == null) ? -1 : host.indexOf('@');
return at < 0 ? host : host.substring(at + 1, host.length());
}
/**
* Returns the port number of this URL or -1 if the default port number is
* being used.
*
* @return The port number
*
* @see #getDefaultPort()
*/
public int getPort()
{
return port;
}
/**
* Returns the default port of the URL. If the StreamHandler for the URL
* protocol does not define a default port it returns -1.
*
* @return The default port of the current protocol.
*/
public int getDefaultPort()
{
return ph.getDefaultPort();
}
/**
* Returns the protocol of the URL
*
* @return The specified protocol.
*/
public String getProtocol()
{
return protocol;
}
/**
* Returns the ref (sometimes called the "# reference" or "anchor") portion
* of the URL.
*
* @return The ref
*/
public String getRef()
{
return ref;
}
/**
* Returns the user information of the URL. This is the part of the host
* name before the '@'.
*
* @return the user at a particular host or null when no user defined.
*/
public String getUserInfo()
{
if (userInfo != null)
return userInfo;
int at = (host == null) ? -1 : host.indexOf('@');
return at < 0 ? null : host.substring(0, at);
}
/**
* Returns the query of the URL. This is the part of the file before the
* '?'.
*
* @return the query part of the file, or null when there is no query part.
*/
public String getQuery()
{
int quest = (file == null) ? -1 : file.indexOf('?');
return quest < 0 ? null : file.substring(quest + 1, file.length());
}
/**
* Returns a hashcode computed by the URLStreamHandler of this URL
*
* @return The hashcode for this URL.
*/
public int hashCode()
{
if (hashCode != 0)
return hashCode; // Use cached value if available.
else
return ph.hashCode(this);
}
/**
* Returns a URLConnection object that represents a connection to the remote
* object referred to by the URL. The URLConnection is created by calling the
* openConnection() method of the protocol handler
*
* @return A URLConnection for this URL
*
* @exception IOException If an error occurs
*/
public URLConnection openConnection() throws IOException
{
return ph.openConnection(this);
}
/**
* Opens a connection to this URL and returns an InputStream for reading
* from that connection
*
* @return An <code>InputStream</code> for this URL.
*
* @exception IOException If an error occurs
*/
public InputStream openStream() throws IOException
{
return openConnection().getInputStream();
}
/**
* Tests whether or not another URL refers to the same "file" as this one.
* This will be true if and only if the passed object is not null, is a
* URL, and matches all fields but the ref (ie, protocol, host, port,
* and file);
*
* @param url The URL object to test with
*
* @return true if URL matches this URL's file, false otherwise
*/
public boolean sameFile(URL url)
{
return ph.sameFile(this, url);
}
/**
* Sets the specified fields of the URL. This is not a public method so
* that only URLStreamHandlers can modify URL fields. This might be called
* by the <code>parseURL()</code> method in that class. URLs are otherwise
* constant. If the given protocol does not exist, it will keep the previously
* set protocol.
*
* @param protocol The protocol name for this URL
* @param host The hostname or IP address for this URL
* @param port The port number of this URL
* @param file The "file" portion of this URL.
* @param ref The anchor portion of this URL.
*/
protected void set(String protocol, String host, int port, String file,
String ref)
{
URLStreamHandler protocolHandler = null;
protocol = protocol.toLowerCase();
if (! this.protocol.equals(protocol))
protocolHandler = getURLStreamHandler(protocol);
// It is an hidden feature of the JDK. If the protocol does not exist,
// we keep the previously initialized protocol.
if (protocolHandler != null)
{
this.ph = protocolHandler;
this.protocol = protocol;
}
this.authority = "";
this.port = port;
this.host = host;
this.file = file;
this.ref = ref;
if (host != null)
this.authority += host;
if (port >= 0)
this.authority += ":" + port;
hashCode = hashCode(); // Used for serialization.
}
/**
* Sets the specified fields of the URL. This is not a public method so
* that only URLStreamHandlers can modify URL fields. URLs are otherwise
* constant. If the given protocol does not exist, it will keep the previously
* set protocol.
*
* @param protocol The protocol name for this URL.
* @param host The hostname or IP address for this URL.
* @param port The port number of this URL.
* @param authority The authority of this URL.
* @param userInfo The user and password (if needed) of this URL.
* @param path The "path" portion of this URL.
* @param query The query of this URL.
* @param ref The anchor portion of this URL.
*
* @since 1.3
*/
protected void set(String protocol, String host, int port, String authority,
String userInfo, String path, String query, String ref)
{
URLStreamHandler protocolHandler = null;
protocol = protocol.toLowerCase();
if (! this.protocol.equals(protocol))
protocolHandler = getURLStreamHandler(protocol);
// It is an hidden feature of the JDK. If the protocol does not exist,
// we keep the previously initialized protocol.
if (protocolHandler != null)
{
this.ph = protocolHandler;
this.protocol = protocol;
}
this.host = host;
this.userInfo = userInfo;
this.port = port;
this.authority = authority;
if (query == null)
this.file = path;
else
this.file = path + "?" + query;
this.ref = ref;
hashCode = hashCode(); // Used for serialization.
}
/**
* Sets the URLStreamHandlerFactory for this class. This factory is
* responsible for returning the appropriate protocol handler for
* a given URL.
*
* @param fac The URLStreamHandlerFactory class to use
*
* @exception Error If the factory is alread set.
* @exception SecurityException If a security manager exists and its
* checkSetFactory method doesn't allow the operation
*/
public static synchronized void setURLStreamHandlerFactory(URLStreamHandlerFactory fac)
{
if (factory != null)
throw new Error("URLStreamHandlerFactory already set");
// Throw an exception if an extant security mgr precludes
// setting the factory.
SecurityManager s = System.getSecurityManager();
if (s != null)
s.checkSetFactory();
factory = fac;
}
/**
* Returns a String representing this URL. The String returned is
* created by calling the protocol handler's toExternalForm() method.
*
* @return A string for this URL
*/
public String toExternalForm()
{
// Identical to toString().
return ph.toExternalForm(this);
}
/**
* Returns a String representing this URL. Identical to toExternalForm().
* The value returned is created by the protocol handler's
* toExternalForm method. Overrides Object.toString()
*
* @return A string for this URL
*/
public String toString()
{
// Identical to toExternalForm().
return ph.toExternalForm(this);
}
/**
* This internal method is used in two different constructors to load
* a protocol handler for this URL.
*
* @param protocol The protocol to load a handler for
*
* @return A URLStreamHandler for this protocol, or null when not found.
*/
private static synchronized URLStreamHandler getURLStreamHandler(String protocol)
{
URLStreamHandler ph = null;
// First, see if a protocol handler is in our cache.
if (cache_handlers)
{
if ((ph = (URLStreamHandler) ph_cache.get(protocol)) != null)
return ph;
}
// If a non-default factory has been set, use it to find the protocol.
if (factory != null)
{
ph = factory.createURLStreamHandler(protocol);
}
// Non-default factory may have returned null or a factory wasn't set.
// Use the default search algorithm to find a handler for this protocol.
if (ph == null)
{
// Get the list of packages to check and append our default handler
// to it, along with the JDK specified default as a last resort.
// Except in very unusual environments the JDK specified one shouldn't
// ever be needed (or available).
String ph_search_path =
System.getProperty("java.protocol.handler.pkgs");
// Tack our default package on at the ends.
if (ph_search_path != null)
ph_search_path += "|" + DEFAULT_SEARCH_PATH;
else
ph_search_path = DEFAULT_SEARCH_PATH;
// Finally loop through our search path looking for a match.
StringTokenizer pkgPrefix = new StringTokenizer(ph_search_path, "|");
// Cache the systemClassLoader
if (systemClassLoader == null)
{
systemClassLoader = (ClassLoader) AccessController.doPrivileged
(new PrivilegedAction() {
public Object run()
{
return ClassLoader.getSystemClassLoader();
}
});
}
do
{
try
{
// Try to get a class from the system/application
// classloader, initialize it, make an instance
// and try to cast it to a URLStreamHandler.
String clsName =
(pkgPrefix.nextToken() + "." + protocol + ".Handler");
Class c = Class.forName(clsName, true, systemClassLoader);
ph = (URLStreamHandler) c.newInstance();
}
catch (ThreadDeath death)
{
throw death;
}
catch (Throwable t)
{
// Ignored.
}
}
while (ph == null && pkgPrefix.hasMoreTokens());
}
// Update the hashtable with the new protocol handler.
if (ph != null && cache_handlers)
ph_cache.put(protocol, ph);
else
ph = null;
return ph;
}
private void readObject(ObjectInputStream ois)
throws IOException, ClassNotFoundException
{
ois.defaultReadObject();
this.ph = getURLStreamHandler(protocol);
if (this.ph == null)
throw new IOException("Handler for protocol " + protocol + " not found");
}
private void writeObject(ObjectOutputStream oos) throws IOException
{
oos.defaultWriteObject();
}
/**
* Returns the equivalent <code>URI</code> object for this <code>URL</code>.
* This is the same as calling <code>new URI(this.toString())</code>.
* RFC2396-compliant URLs are guaranteed a successful conversion to
* a <code>URI</code> instance. However, there are some values which
* form valid URLs, but which do not also form RFC2396-compliant URIs.
*
* @throws URISyntaxException if this URL is not RFC2396-compliant,
* and thus can not be successfully converted to a URI.
*/
public URI toURI()
throws URISyntaxException
{
return new URI(toString());
}
}

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,180 @@
/* URLDecoder.java -- Class to decode URL's from encoded form.
Copyright (C) 1998, 1999, 2000, 2001 Free Software Foundation, Inc.
This file is part of GNU Classpath.
GNU Classpath is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2, or (at your option)
any later version.
GNU Classpath is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with GNU Classpath; see the file COPYING. If not, write to the
Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301 USA.
Linking this library statically or dynamically with other modules is
making a combined work based on this library. Thus, the terms and
conditions of the GNU General Public License cover the whole
combination.
As a special exception, the copyright holders of this library give you
permission to link this library with independent modules to produce an
executable, regardless of the license terms of these independent
modules, and to copy and distribute the resulting executable under
terms of your choice, provided that you also meet, for each linked
independent module, the terms and conditions of the license of that
module. An independent module is a module which is not derived from
or based on this library. If you modify this library, you may extend
this exception to your version of the library, but you are not
obligated to do so. If you do not wish to do so, delete this
exception statement from your version. */
package java.net;
import java.io.UnsupportedEncodingException;
/**
* This utility class contains static methods that converts a
* string encoded in the x-www-form-urlencoded format to the original
* text. The x-www-form-urlencoded format replaces certain disallowed
* characters with encoded equivalents. All upper case and lower case
* letters in the US alphabet remain as is, the space character (' ')
* is replaced with '+' sign, and all other characters are converted to a
* "%XX" format where XX is the hexadecimal representation of that character
* in a given character encoding (default is "UTF-8").
* <p>
* This method is very useful for decoding strings sent to CGI scripts
*
* Written using on-line Java Platform 1.2/1.4 API Specification.
* Status: Believed complete and correct.
*
* @since 1.2
*
* @author Warren Levy (warrenl@cygnus.com)
* @author Aaron M. Renn (arenn@urbanophile.com) (documentation comments)
* @author Mark Wielaard (mark@klomp.org)
*/
public class URLDecoder
{
/**
* Public contructor. Note that this class has only static methods.
*/
public URLDecoder()
{
}
/**
* This method translates the passed in string from x-www-form-urlencoded
* format using the default encoding "UTF-8" to decode the hex encoded
* unsafe characters.
*
* @param s the String to convert
*
* @return the converted String
*
* @deprecated
*/
public static String decode(String s)
{
try
{
return decode(s, "UTF-8");
}
catch (UnsupportedEncodingException uee)
{
// Should never happen since UTF-8 encoding should always be supported
return s;
}
}
/**
* This method translates the passed in string from x-www-form-urlencoded
* format using the given character encoding to decode the hex encoded
* unsafe characters.
*
* This implementation will decode the string even if it contains
* unsafe characters (characters that should have been encoded) or if the
* two characters following a % do not represent a hex encoded byte.
* In those cases the unsafe character or the % character will be added
* verbatim to the decoded result.
*
* @param s the String to convert
* @param encoding the character encoding to use the decode the hex encoded
* unsafe characters
*
* @return the converted String
*
* @exception UnsupportedEncodingException If the named encoding is not
* supported
*
* @since 1.4
*/
public static String decode(String s, String encoding)
throws UnsupportedEncodingException
{
// First convert all '+' characters to spaces.
String str = s.replace('+', ' ');
// Then go through the whole string looking for byte encoded characters
int i;
int start = 0;
byte[] bytes = null;
int length = str.length();
StringBuffer result = new StringBuffer(length);
while ((i = str.indexOf('%', start)) >= 0)
{
// Add all non-encoded characters to the result buffer
result.append(str.substring(start, i));
start = i;
// Get all consecutive encoded bytes
while ((i + 2 < length) && (str.charAt(i) == '%'))
i += 3;
// Decode all these bytes
if ((bytes == null) || (bytes.length < ((i - start) / 3)))
bytes = new byte[((i - start) / 3)];
int index = 0;
try
{
while (start < i)
{
String sub = str.substring(start + 1, start + 3);
bytes[index] = (byte) Integer.parseInt(sub, 16);
index++;
start += 3;
}
}
catch (NumberFormatException nfe)
{
// One of the hex encoded strings was bad
}
// Add the bytes as characters according to the given encoding
result.append(new String(bytes, 0, index, encoding));
// Make sure we skip to just after a % sign
// There might not have been enough encoded characters after the %
// or the hex chars were not actually hex chars (NumberFormatException)
if (start < length && s.charAt(start) == '%')
{
result.append('%');
start++;
}
}
// Add any characters left
if (start < str.length())
result.append(str.substring(start));
return result.toString();
}
} // class URLDecoder

View file

@ -0,0 +1,184 @@
/* URLEncoder.java -- Class to convert strings to a properly encoded URL
Copyright (C) 1998, 1999, 2001, 2002, 2003 Free Software Foundation, Inc.
This file is part of GNU Classpath.
GNU Classpath is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2, or (at your option)
any later version.
GNU Classpath is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with GNU Classpath; see the file COPYING. If not, write to the
Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301 USA.
Linking this library statically or dynamically with other modules is
making a combined work based on this library. Thus, the terms and
conditions of the GNU General Public License cover the whole
combination.
As a special exception, the copyright holders of this library give you
permission to link this library with independent modules to produce an
executable, regardless of the license terms of these independent
modules, and to copy and distribute the resulting executable under
terms of your choice, provided that you also meet, for each linked
independent module, the terms and conditions of the license of that
module. An independent module is a module which is not derived from
or based on this library. If you modify this library, you may extend
this exception to your version of the library, but you are not
obligated to do so. If you do not wish to do so, delete this
exception statement from your version. */
package java.net;
import java.io.UnsupportedEncodingException;
/*
* Written using on-line Java Platform 1.2/1.4 API Specification, as well
* as "The Java Class Libraries", 2nd edition (Addison-Wesley, 1998).
* Status: Believed complete and correct.
*/
/**
* This utility class contains static methods that converts a
* string into a fully encoded URL string in x-www-form-urlencoded
* format. This format replaces certain disallowed characters with
* encoded equivalents. All upper case and lower case letters in the
* US alphabet remain as is, the space character (' ') is replaced with
* '+' sign, and all other characters are converted to a "%XX" format
* where XX is the hexadecimal representation of that character in a
* certain encoding (by default, the platform encoding, though the
* standard is "UTF-8").
* <p>
* This method is very useful for encoding strings to be sent to CGI scripts
*
* @author Aaron M. Renn (arenn@urbanophile.com)
* @author Warren Levy (warrenl@cygnus.com)
* @author Mark Wielaard (mark@klomp.org)
*/
public class URLEncoder
{
/**
* This method translates the passed in string into x-www-form-urlencoded
* format using the default encoding. The standard encoding is
* "UTF-8", and the two-argument form of this method should be used
* instead.
*
* @param s The String to convert
*
* @return The converted String
*
* @deprecated
*/
public static String encode(String s)
{
try
{
// We default to 8859_1 for compatibility with the same
// default elsewhere in the library.
return encode(s, System.getProperty("file.encoding", "8859_1"));
}
catch (UnsupportedEncodingException uee)
{
// Should never happen since default should always be supported
return s;
}
}
/**
* This method translates the passed in string into x-www-form-urlencoded
* format using the character encoding to hex-encode the unsafe characters.
*
* @param s The String to convert
* @param encoding The encoding to use for unsafe characters
*
* @return The converted String
*
* @exception UnsupportedEncodingException If the named encoding is not
* supported
*
* @since 1.4
*/
public static String encode(String s, String encoding)
throws UnsupportedEncodingException
{
int length = s.length();
int start = 0;
int i = 0;
StringBuffer result = new StringBuffer(length);
while (true)
{
while (i < length && isSafe(s.charAt(i)))
i++;
// Safe character can just be added
result.append(s.substring(start, i));
// Are we done?
if (i >= length)
return result.toString();
else if (s.charAt(i) == ' ')
{
result.append('+'); // Replace space char with plus symbol.
i++;
}
else
{
// Get all unsafe characters
start = i;
char c;
while (i < length && (c = s.charAt(i)) != ' ' && ! isSafe(c))
i++;
// Convert them to %XY encoded strings
String unsafe = s.substring(start, i);
byte[] bytes = unsafe.getBytes(encoding);
for (int j = 0; j < bytes.length; j++)
{
result.append('%');
int val = bytes[j];
result.append(hex.charAt((val & 0xf0) >> 4));
result.append(hex.charAt(val & 0x0f));
}
}
start = i;
}
}
/**
* Private static method that returns true if the given char is either
* a uppercase or lowercase letter from 'a' till 'z', or a digit froim
* '0' till '9', or one of the characters '-', '_', '.' or '*'. Such
* 'safe' character don't have to be url encoded.
*/
private static boolean isSafe(char c)
{
return ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')
|| (c >= '0' && c <= '9') || c == '-' || c == '_' || c == '.'
|| c == '*');
}
/**
* Private constructor that does nothing. Included to avoid a default
* public constructor being created by the compiler.
*/
private URLEncoder()
{
}
/**
* Used to convert to hex. We don't use Integer.toHexString, since
* it converts to lower case (and the Sun docs pretty clearly
* specify upper case here), and because it doesn't provide a
* leading 0.
*/
private static final String hex = "0123456789ABCDEF";
}

View file

@ -0,0 +1,532 @@
/* URLStreamHandler.java -- Abstract superclass for all protocol handlers
Copyright (C) 1998, 1999, 2002, 2003, 2004 Free Software Foundation, Inc.
This file is part of GNU Classpath.
GNU Classpath is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2, or (at your option)
any later version.
GNU Classpath is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with GNU Classpath; see the file COPYING. If not, write to the
Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301 USA.
Linking this library statically or dynamically with other modules is
making a combined work based on this library. Thus, the terms and
conditions of the GNU General Public License cover the whole
combination.
As a special exception, the copyright holders of this library give you
permission to link this library with independent modules to produce an
executable, regardless of the license terms of these independent
modules, and to copy and distribute the resulting executable under
terms of your choice, provided that you also meet, for each linked
independent module, the terms and conditions of the license of that
module. An independent module is a module which is not derived from
or based on this library. If you modify this library, you may extend
this exception to your version of the library, but you are not
obligated to do so. If you do not wish to do so, delete this
exception statement from your version. */
package java.net;
import java.io.File;
import java.io.IOException;
/*
* Written using on-line Java Platform 1.2 API Specification, as well
* as "The Java Class Libraries", 2nd edition (Addison-Wesley, 1998).
* Status: Believed complete and correct.
*/
/**
* This class is the superclass of all URL protocol handlers. The URL
* class loads the appropriate protocol handler to establish a connection
* to a (possibly) remote service (eg, "http", "ftp") and to do protocol
* specific parsing of URL's. Refer to the URL class documentation for
* details on how that class locates and loads protocol handlers.
* <p>
* A protocol handler implementation should override the openConnection()
* method, and optionally override the parseURL() and toExternalForm()
* methods if necessary. (The default implementations will parse/write all
* URL's in the same form as http URL's). A protocol specific subclass
* of URLConnection will most likely need to be created as well.
* <p>
* Note that the instance methods in this class are called as if they
* were static methods. That is, a URL object to act on is passed with
* every call rather than the caller assuming the URL is stored in an
* instance variable of the "this" object.
* <p>
* The methods in this class are protected and accessible only to subclasses.
* URLStreamConnection objects are intended for use by the URL class only,
* not by other classes (unless those classes are implementing protocols).
*
* @author Aaron M. Renn (arenn@urbanophile.com)
* @author Warren Levy (warrenl@cygnus.com)
*
* @see URL
*/
public abstract class URLStreamHandler
{
/**
* Creates a URLStreamHander
*/
public URLStreamHandler()
{
}
/**
* Returns a URLConnection for the passed in URL. Note that this should
* not actually create the connection to the (possibly) remote host, but
* rather simply return a URLConnection object. The connect() method of
* URL connection is used to establish the actual connection, possibly
* after the caller sets up various connection options.
*
* @param url The URL to get a connection object for
*
* @return A URLConnection object for the given URL
*
* @exception IOException If an error occurs
*/
protected abstract URLConnection openConnection(URL url)
throws IOException;
/**
* This method parses the string passed in as a URL and set's the
* instance data fields in the URL object passed in to the various values
* parsed out of the string. The start parameter is the position to start
* scanning the string. This is usually the position after the ":" which
* terminates the protocol name. The end parameter is the position to
* stop scanning. This will be either the end of the String, or the
* position of the "#" character, which separates the "file" portion of
* the URL from the "anchor" portion.
* <p>
* This method assumes URL's are formatted like http protocol URL's, so
* subclasses that implement protocols with URL's the follow a different
* syntax should override this method. The lone exception is that if
* the protocol name set in the URL is "file", this method will accept
* an empty hostname (i.e., "file:///"), which is legal for that protocol
*
* @param url The URL object in which to store the results
* @param spec The String-ized URL to parse
* @param start The position in the string to start scanning from
* @param end The position in the string to stop scanning
*/
protected void parseURL(URL url, String spec, int start, int end)
{
String host = url.getHost();
int port = url.getPort();
String file = url.getFile();
String ref = url.getRef();
String userInfo = url.getUserInfo();
String authority = url.getAuthority();
String query = null;
// On Windows we need to change \ to / for file URLs
char separator = File.separatorChar;
if (url.getProtocol().equals("file") && separator != '/')
{
file = file.replace(separator, '/');
spec = spec.replace(separator, '/');
}
if (spec.regionMatches(start, "//", 0, 2))
{
String genuineHost;
int hostEnd;
int colon;
int at_host;
start += 2;
int slash = spec.indexOf('/', start);
if (slash >= 0)
hostEnd = slash;
else
hostEnd = end;
authority = host = spec.substring(start, hostEnd);
// We first need a genuine host name (with userinfo).
// So we check for '@': if it's present check the port in the
// section after '@' in the other case check it in the full string.
// P.S.: We don't care having '@' at the beginning of the string.
if ((at_host = host.indexOf('@')) >= 0)
{
genuineHost = host.substring(at_host);
userInfo = host.substring(0, at_host);
}
else
genuineHost = host;
// Look for optional port number. It is valid for the non-port
// part of the host name to be null (e.g. a URL "http://:80").
// TBD: JDK 1.2 in this case sets host to null rather than "";
// this is undocumented and likely an unintended side effect in 1.2
// so we'll be simple here and stick with "". Note that
// "http://" or "http:///" produce a "" host in JDK 1.2.
if ((colon = genuineHost.indexOf(':')) >= 0)
{
try
{
port = Integer.parseInt(genuineHost.substring(colon + 1));
}
catch (NumberFormatException e)
{
// Ignore invalid port values; port is already set to u's
// port.
}
// Now we must cut the port number in the original string.
if (at_host >= 0)
host = host.substring(0, at_host + colon);
else
host = host.substring(0, colon);
}
file = null;
start = hostEnd;
}
else if (host == null)
host = "";
if (file == null || file.length() == 0
|| (start < end && spec.charAt(start) == '/'))
{
// No file context available; just spec for file.
// Or this is an absolute path name; ignore any file context.
file = spec.substring(start, end);
ref = null;
}
else if (start < end)
{
// Context is available, but only override it if there is a new file.
int lastSlash = file.lastIndexOf('/');
if (lastSlash < 0)
file = spec.substring(start, end);
else
file = (file.substring(0, lastSlash)
+ '/' + spec.substring(start, end));
// For URLs constructed relative to a context, we
// need to canonicalise the file path.
file = canonicalizeFilename(file);
ref = null;
}
if (ref == null)
{
// Normally there should be no '#' in the file part,
// but we are nice.
int hash = file.indexOf('#');
if (hash != -1)
{
ref = file.substring(hash + 1, file.length());
file = file.substring(0, hash);
}
}
// We care about the query tag only if there is no reference at all.
if (ref == null)
{
int queryTag = file.indexOf('?');
if (queryTag != -1)
{
query = file.substring(queryTag + 1);
file = file.substring(0, queryTag);
}
}
// XXX - Classpath used to call PlatformHelper.toCanonicalForm() on
// the file part. It seems like overhead, but supposedly there is some
// benefit in windows based systems (it also lowercased the string).
setURL(url, url.getProtocol(), host, port, authority, userInfo, file, query, ref);
}
/*
* Canonicalize a filename.
*/
private static String canonicalizeFilename(String file)
{
// XXX - GNU Classpath has an implementation that might be more appropriate
// for Windows based systems (gnu.java.io.PlatformHelper.toCanonicalForm)
int index;
// Replace "/./" with "/". This probably isn't very efficient in
// the general case, but it's probably not bad most of the time.
while ((index = file.indexOf("/./")) >= 0)
file = file.substring(0, index) + file.substring(index + 2);
// Process "/../" correctly. This probably isn't very efficient in
// the general case, but it's probably not bad most of the time.
while ((index = file.indexOf("/../")) >= 0)
{
// Strip of the previous directory - if it exists.
int previous = file.lastIndexOf('/', index - 1);
if (previous >= 0)
file = file.substring(0, previous) + file.substring(index + 3);
else
break;
}
return file;
}
/**
* Compares two URLs, excluding the fragment component
*
* @param url1 The first url
* @param url2 The second url to compare with the first
*
* @return True if both URLs point to the same file, false otherwise.
*
* @specnote Now protected
*/
protected boolean sameFile(URL url1, URL url2)
{
if (url1 == url2)
return true;
// This comparison is very conservative. It assumes that any
// field can be null.
if (url1 == null || url2 == null)
return false;
int p1 = url1.getPort();
if (p1 == -1)
p1 = url1.ph.getDefaultPort();
int p2 = url2.getPort();
if (p2 == -1)
p2 = url2.ph.getDefaultPort();
if (p1 != p2)
return false;
String s1;
String s2;
s1 = url1.getProtocol();
s2 = url2.getProtocol();
if (s1 != s2 && (s1 == null || ! s1.equals(s2)))
return false;
s1 = url1.getHost();
s2 = url2.getHost();
if (s1 != s2 && (s1 == null || ! s1.equals(s2)))
return false;
s1 = canonicalizeFilename(url1.getFile());
s2 = canonicalizeFilename(url2.getFile());
if (s1 != s2 && (s1 == null || ! s1.equals(s2)))
return false;
return true;
}
/**
* This methods sets the instance variables representing the various fields
* of the URL to the values passed in.
*
* @param u The URL to modify
* @param protocol The protocol to set
* @param host The host name to et
* @param port The port number to set
* @param file The filename to set
* @param ref The reference
*
* @exception SecurityException If the protocol handler of the URL is
* different from this one
*
* @deprecated 1.2 Please use
* #setURL(URL,String,String,int,String,String,String,String);
*/
protected void setURL(URL u, String protocol, String host, int port,
String file, String ref)
{
u.set(protocol, host, port, file, ref);
}
/**
* Sets the fields of the URL argument to the indicated values
*
* @param u The URL to modify
* @param protocol The protocol to set
* @param host The host name to set
* @param port The port number to set
* @param authority The authority to set
* @param userInfo The user information to set
* @param path The path/filename to set
* @param query The query part to set
* @param ref The reference
*
* @exception SecurityException If the protocol handler of the URL is
* different from this one
*/
protected void setURL(URL u, String protocol, String host, int port,
String authority, String userInfo, String path,
String query, String ref)
{
u.set(protocol, host, port, authority, userInfo, path, query, ref);
}
/**
* Provides the default equals calculation. May be overidden by handlers for
* other protocols that have different requirements for equals(). This method
* requires that none of its arguments is null. This is guaranteed by the
* fact that it is only called by java.net.URL class.
*
* @param url1 An URL object
* @param url2 An URL object
*
* @return True if both given URLs are equal, false otherwise.
*/
protected boolean equals(URL url1, URL url2)
{
// This comparison is very conservative. It assumes that any
// field can be null.
return (url1.getPort() == url2.getPort()
&& ((url1.getProtocol() == null && url2.getProtocol() == null)
|| (url1.getProtocol() != null
&& url1.getProtocol().equals(url2.getProtocol())))
&& ((url1.getUserInfo() == null && url2.getUserInfo() == null)
|| (url1.getUserInfo() != null
&& url1.getUserInfo().equals(url2.getUserInfo())))
&& ((url1.getAuthority() == null && url2.getAuthority() == null)
|| (url1.getAuthority() != null
&& url1.getAuthority().equals(url2.getAuthority())))
&& ((url1.getHost() == null && url2.getHost() == null)
|| (url1.getHost() != null && url1.getHost().equals(url2.getHost())))
&& ((url1.getPath() == null && url2.getPath() == null)
|| (url1.getPath() != null && url1.getPath().equals(url2.getPath())))
&& ((url1.getQuery() == null && url2.getQuery() == null)
|| (url1.getQuery() != null
&& url1.getQuery().equals(url2.getQuery())))
&& ((url1.getRef() == null && url2.getRef() == null)
|| (url1.getRef() != null && url1.getRef().equals(url2.getRef()))));
}
/**
* Compares the host components of two URLs.
*
* @param url1 The first URL.
* @param url2 The second URL.
*
* @return True if both URLs contain the same host.
*
* @exception UnknownHostException If an unknown host is found
*/
protected boolean hostsEqual(URL url1, URL url2)
{
InetAddress addr1 = getHostAddress(url1);
InetAddress addr2 = getHostAddress(url2);
if (addr1 != null && addr2 != null)
return addr1.equals(addr2);
String host1 = url1.getHost();
String host2 = url2.getHost();
if (host1 != null && host2 != null)
return host1.equalsIgnoreCase(host2);
return host1 == null && host2 == null;
}
/**
* Get the IP address of our host. An empty host field or a DNS failure will
* result in a null return.
*
* @param url The URL to return the host address for.
*
* @return The address of the hostname in url.
*/
protected InetAddress getHostAddress(URL url)
{
String hostname = url.getHost();
if (hostname.equals(""))
return null;
try
{
return InetAddress.getByName(hostname);
}
catch (UnknownHostException e)
{
return null;
}
}
/**
* Returns the default port for a URL parsed by this handler. This method is
* meant to be overidden by handlers with default port numbers.
*
* @return The default port number.
*/
protected int getDefaultPort()
{
return -1;
}
/**
* Provides the default hash calculation. May be overidden by handlers for
* other protocols that have different requirements for hashCode calculation.
*
* @param url The URL to calc the hashcode for.
*
* @return The hashcode for the given URL.
*/
protected int hashCode(URL url)
{
return url.getProtocol().hashCode()
+ ((url.getHost() == null) ? 0 : url.getHost().hashCode())
+ url.getFile().hashCode() + url.getPort();
}
/**
* This method converts a URL object into a String. This method creates
* Strings in the mold of http URL's, so protocol handlers which use URL's
* that have a different syntax should override this method
*
* @param url The URL object to convert
*
* @return A string representation of the url
*/
protected String toExternalForm(URL url)
{
String protocol;
String file;
String ref;
String authority;
protocol = url.getProtocol();
authority = url.getAuthority();
if (authority == null)
authority = "";
file = url.getFile();
ref = url.getRef();
// Guess a reasonable size for the string buffer so we have to resize
// at most once.
int size = protocol.length() + authority.length() + file.length() + 24;
StringBuffer sb = new StringBuffer(size);
if (protocol != null && protocol.length() > 0)
{
sb.append(protocol);
sb.append(":");
}
if (authority.length() != 0)
{
sb.append("//").append(authority);
}
sb.append(file);
if (ref != null)
sb.append('#').append(ref);
return sb.toString();
}
}

View file

@ -0,0 +1,65 @@
/* URLStreamHandlerFactory.java -- Maps protocols to URLStreamHandlers
Copyright (C) 1998, 1999, 2000, 2001, 2003 Free Software Foundation, Inc.
This file is part of GNU Classpath.
GNU Classpath is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2, or (at your option)
any later version.
GNU Classpath is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with GNU Classpath; see the file COPYING. If not, write to the
Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301 USA.
Linking this library statically or dynamically with other modules is
making a combined work based on this library. Thus, the terms and
conditions of the GNU General Public License cover the whole
combination.
As a special exception, the copyright holders of this library give you
permission to link this library with independent modules to produce an
executable, regardless of the license terms of these independent
modules, and to copy and distribute the resulting executable under
terms of your choice, provided that you also meet, for each linked
independent module, the terms and conditions of the license of that
module. An independent module is a module which is not derived from
or based on this library. If you modify this library, you may extend
this exception to your version of the library, but you are not
obligated to do so. If you do not wish to do so, delete this
exception statement from your version. */
package java.net;
/**
* Written using on-line Java Platform 1.2 API Specification, as well
* as "The Java Class Libraries", 2nd edition (Addison-Wesley, 1998).
* Status: Believed complete and correct.
*/
/**
* This interface contains one method which maps the protocol portion of
* a URL (eg, "http" in "http://www.urbanophile.com/arenn/") to a
* <code>URLStreamHandler</code> object.
*
* @author Aaron M. Renn (arenn@urbanophile.com)
* @author Warren Levy (warrenl@cygnus.com)
*/
public interface URLStreamHandlerFactory
{
/**
* This method maps the protocol portion of a URL to a
* <code>URLStreamHandler</code> object.
*
* @param protocol The protocol name to map ("http", "ftp", etc).
*
* @return The <code>URLStreamHandler</code> for the specified protocol
*/
URLStreamHandler createURLStreamHandler(String protocol);
} // interface URLStreamHandlerFactory

View file

@ -0,0 +1,77 @@
/* UnknownHostException.java -- The hostname is unknown
Copyright (C) 1998, 1999, 2000, 2001, 2002 Free Software Foundation, Inc.
This file is part of GNU Classpath.
GNU Classpath is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2, or (at your option)
any later version.
GNU Classpath is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with GNU Classpath; see the file COPYING. If not, write to the
Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301 USA.
Linking this library statically or dynamically with other modules is
making a combined work based on this library. Thus, the terms and
conditions of the GNU General Public License cover the whole
combination.
As a special exception, the copyright holders of this library give you
permission to link this library with independent modules to produce an
executable, regardless of the license terms of these independent
modules, and to copy and distribute the resulting executable under
terms of your choice, provided that you also meet, for each linked
independent module, the terms and conditions of the license of that
module. An independent module is a module which is not derived from
or based on this library. If you modify this library, you may extend
this exception to your version of the library, but you are not
obligated to do so. If you do not wish to do so, delete this
exception statement from your version. */
package java.net;
import java.io.IOException;
/**
* This exception indicates that an attempt was made to reference a hostname
* or IP address that is not valid. This could possibly indicate that a
* DNS problem has occurred, but most often means that the host was not
* correctly specified.
*
* @author Aaron M. Renn (arenn@urbanophile.com)
* @author Per Bothner
* @status updated to 1.4
*/
public class UnknownHostException extends IOException
{
/**
* Compatible with JDK 1.0+.
*/
private static final long serialVersionUID = -4639126076052875403L;
/**
* Create a new instance without a descriptive error message.
*/
public UnknownHostException()
{
}
/**
* Create a new instance with a descriptive error message, such as the
* name of the host that could not be resolved.
*
* @param message a message describing the error that occurred
*/
public UnknownHostException(String message)
{
super(message);
}
} // class UnknownHostException

View file

@ -0,0 +1,76 @@
/* UnknownServiceException.java -- A service error occurred
Copyright (C) 1998, 1999, 2000, 2001, 2002 Free Software Foundation, Inc.
This file is part of GNU Classpath.
GNU Classpath is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2, or (at your option)
any later version.
GNU Classpath is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with GNU Classpath; see the file COPYING. If not, write to the
Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301 USA.
Linking this library statically or dynamically with other modules is
making a combined work based on this library. Thus, the terms and
conditions of the GNU General Public License cover the whole
combination.
As a special exception, the copyright holders of this library give you
permission to link this library with independent modules to produce an
executable, regardless of the license terms of these independent
modules, and to copy and distribute the resulting executable under
terms of your choice, provided that you also meet, for each linked
independent module, the terms and conditions of the license of that
module. An independent module is a module which is not derived from
or based on this library. If you modify this library, you may extend
this exception to your version of the library, but you are not
obligated to do so. If you do not wish to do so, delete this
exception statement from your version. */
package java.net;
import java.io.IOException;
/**
* Contrary to what you might think, this does not indicate that the
* TCP/IP service name specified was invalid. Instead it indicates that
* the MIME type returned from a URL could not be determined or that an
* attempt was made to write to a read-only URL.
*
* @author Aaron M. Renn (arenn@urbanophile.com)
* @author Warren Levy (warrenl@cygnus.com)
* @status updated to 1.4
*/
public class UnknownServiceException extends IOException
{
/**
* Compatible with JDK 1.0+.
*/
private static final long serialVersionUID = -4169033248853639508L;
/**
* Create a new instance without a descriptive error message.
*/
public UnknownServiceException()
{
}
/**
* Create a new instance with a descriptive error message.
*
* @param message a message describing the error that occurred
*/
public UnknownServiceException(String message)
{
super(message);
}
} // class UnknownServiceException

View file

@ -0,0 +1,122 @@
# This property file contains dependencies of classes, methods, and
# field on other methods or classes.
#
# Syntax:
#
# <used>: <needed 1> [... <needed N>]
#
# means that when <used> is included, <needed 1> (... <needed N>) must
# be included as well.
#
# <needed X> and <used> are of the form
#
# <class.methodOrField(signature)>
#
# or just
#
# <class>
#
# Within dependencies, variables can be used. A variable is defined as
# follows:
#
# {variable}: value1 value2 ... value<n>
#
# variables can be used on the right side of dependencies as follows:
#
# <used>: com.bla.blu.{variable}.Class.m()V
#
# The use of the variable will expand to <n> dependencies of the form
#
# <used>: com.bla.blu.value1.Class.m()V
# <used>: com.bla.blu.value2.Class.m()V
# ...
# <used>: com.bla.blu.value<n>.Class.m()V
#
# Variables can be redefined when building a system to select the
# required support for features like encodings, protocols, etc.
#
# Hints:
#
# - For methods and fields, the signature is mandatory. For
# specification, please see the Java Virtual Machine Specification by
# SUN. Unlike in the spec, field signatures (types) are in brackets.
#
# - Package names must be separated by '/' (and not '.'). E.g.,
# java/lang/Class (this is necessary, because the '.' is used to
# separate method or field names from classes)
#
# - In case <needed> refers to a class, only the class itself will be
# included in the resulting binary, NOT necessarily all its methods
# and fields. If you want to refer to all methods and fields, you can
# write class.* as an abbreviation.
#
# - Abbreviations for packages are also possible: my/package/* means all
# methods and fields of all classes in my/package.
#
# - A line with a trailing '\' continues in the next line.
java/net/InetAddress: \
java/lang/ClassNotFoundException.<init>(Ljava/lang/String;)V \
java/lang/InternalError.<init>(Ljava/lang/String;)V \
java/net/UnknownHostException.<init>(Ljava/lang/String;)V
java/net/DatagramSocketImpl: \
java/net/DatagramSocketImpl.fd(Ljava/io/FileDescriptor;) \
java/net/DatagramSocketImpl.localPort(I)
java/net/PlainDatagramSocketImpl: \
java/lang/ClassNotFoundException.<init>(Ljava/lang/String;)V \
java/lang/InternalError.<init>(Ljava/lang/String;)V \
java/io/IOException.<init>(Ljava/lang/String;)V \
java/io/FileDescriptor.<init>()V \
java/lang/Boolean.<init>(Z)V \
java/lang/Integer.<init>(I)V \
java/net/InetAddress.getByName(Ljava/lang/String;)Ljava/net/InetAddress; \
java/net/InetAddress.getAddress()[B \
java/lang/Boolean.booleanValue()Z \
java/lang/Integer.intValue()I \
java/net/SocketException.<init>(Ljava/lang/String;)V \
java/net/DatagramPacket.getData()[B \
java/net/SocketImpl.address(Ljava/net/InetAddress;) \
java/net/PlainSocketImpl.native_fd(I) \
java/net/SocketImpl.fd(Ljava/io/FileDescriptor;) \
java/net/SocketImpl.address(Ljava/net/InetAddress;) \
java/net/PlainDatagramSocketImpl.native_fd(I) \
java/net/SocketImpl.localport(I) \
java/net/SocketImpl.port(I)
java/net/PlainSocketImpl: \
java/lang/ClassNotFoundException.<init>(Ljava/lang/String;)V \
java/lang/InternalError.<init>(Ljava/lang/String;)V \
java/io/IOException.<init>(Ljava/lang/String;)V \
java/io/FileDescriptor.<init>()V \
java/lang/Boolean.<init>(Z)V \
java/lang/Integer.<init>(I)V \
java/net/InetAddress.getByName(Ljava/lang/String;)Ljava/net/InetAddress; \
java/net/InetAddress.getAddress()[B \
java/lang/Boolean.booleanValue()Z \
java/lang/Integer.intValue()I \
java/net/SocketException.<init>(Ljava/lang/String;)V \
java/net/DatagramPacket.getData()[B \
java/net/SocketImpl.address(Ljava/net/InetAddress;) \
java/net/PlainSocketImpl.native_fd(I) \
java/net/SocketImpl.fd(Ljava/io/FileDescriptor;) \
java/net/SocketImpl.address(Ljava/net/InetAddress;) \
java/net/PlainDatagramSocketImpl.native_fd(I) \
java/net/SocketImpl.localport(I) \
java/net/SocketImpl.port(I)
# All protocols supported are loaded via URL.getURLStreamHandler from
# class gnu.java.net.protocol.<protocol>.Handler.
#
# This introduces a dependency for all protocols. To allow an easy selection
# and addition of protocols, the library variable {protocols} can be set to
# the set of supported protocols.
#
{protocols}: http file jar
java/net/URL.getURLStreamHandler(Ljava/lang/String;)Ljava/net/URLStreamHandler;: \
gnu/java/net/protocol/{protocols}/Handler.* \
com/aicas/java/net/protocol/rom/Handler.*
# end of file

View file

@ -0,0 +1,46 @@
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<!-- package.html - describes classes in java.net package.
Copyright (C) 2002 Free Software Foundation, Inc.
This file is part of GNU Classpath.
GNU Classpath is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2, or (at your option)
any later version.
GNU Classpath is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with GNU Classpath; see the file COPYING. If not, write to the
Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301 USA.
Linking this library statically or dynamically with other modules is
making a combined work based on this library. Thus, the terms and
conditions of the GNU General Public License cover the whole
combination.
As a special exception, the copyright holders of this library give you
permission to link this library with independent modules to produce an
executable, regardless of the license terms of these independent
modules, and to copy and distribute the resulting executable under
terms of your choice, provided that you also meet, for each linked
independent module, the terms and conditions of the license of that
module. An independent module is a module which is not derived from
or based on this library. If you modify this library, you may extend
this exception to your version of the library, but you are not
obligated to do so. If you do not wish to do so, delete this
exception statement from your version. -->
<html>
<head><title>GNU Classpath - java.net</title></head>
<body>
<p>Network communication through TCP and UDP sockets or URLs.</p>
</body>
</html>