You can subscribe to this list here.
2006 |
Jan
|
Feb
|
Mar
|
Apr
|
May
|
Jun
|
Jul
|
Aug
|
Sep
|
Oct
|
Nov
|
Dec
(97) |
---|---|---|---|---|---|---|---|---|---|---|---|---|
2007 |
Jan
(127) |
Feb
(34) |
Mar
(16) |
Apr
(26) |
May
(55) |
Jun
(107) |
Jul
(36) |
Aug
(72) |
Sep
(90) |
Oct
(41) |
Nov
(27) |
Dec
(13) |
2008 |
Jan
(37) |
Feb
(39) |
Mar
(98) |
Apr
(115) |
May
(134) |
Jun
(120) |
Jul
(86) |
Aug
(149) |
Sep
(68) |
Oct
(66) |
Nov
(104) |
Dec
(49) |
2009 |
Jan
(131) |
Feb
(132) |
Mar
(125) |
Apr
(172) |
May
(161) |
Jun
(43) |
Jul
(47) |
Aug
(38) |
Sep
(18) |
Oct
(6) |
Nov
(1) |
Dec
(15) |
2010 |
Jan
(21) |
Feb
(8) |
Mar
(10) |
Apr
(4) |
May
(9) |
Jun
|
Jul
(1) |
Aug
|
Sep
|
Oct
(2) |
Nov
|
Dec
(4) |
2011 |
Jan
(23) |
Feb
(10) |
Mar
(13) |
Apr
(3) |
May
|
Jun
(19) |
Jul
(11) |
Aug
(22) |
Sep
|
Oct
(4) |
Nov
(2) |
Dec
(12) |
2012 |
Jan
(3) |
Feb
(4) |
Mar
(7) |
Apr
(3) |
May
|
Jun
(1) |
Jul
(1) |
Aug
(30) |
Sep
(3) |
Oct
(2) |
Nov
|
Dec
(8) |
2013 |
Jan
(3) |
Feb
(40) |
Mar
|
Apr
|
May
|
Jun
(1) |
Jul
|
Aug
|
Sep
|
Oct
|
Nov
(12) |
Dec
|
2021 |
Jan
|
Feb
|
Mar
|
Apr
|
May
|
Jun
|
Jul
|
Aug
|
Sep
(2) |
Oct
|
Nov
|
Dec
|
From: <hag...@us...> - 2006-12-14 10:17:18
|
Revision: 2919 http://jnode.svn.sourceforge.net/jnode/?rev=2919&view=rev Author: hagar-wize Date: 2006-12-14 02:17:15 -0800 (Thu, 14 Dec 2006) Log Message: ----------- Classpath patches Modified Paths: -------------- trunk/core/src/classpath/gnu/gnu/java/net/PlainDatagramSocketImpl.java trunk/core/src/classpath/gnu/gnu/java/net/PlainSocketImpl.java trunk/core/src/classpath/gnu/gnu/java/nio/charset/ISO_8859_1.java trunk/core/src/classpath/gnu/gnu/java/nio/charset/US_ASCII.java trunk/core/src/classpath/gnu/gnu/java/nio/charset/iconv/IconvEncoder.java Modified: trunk/core/src/classpath/gnu/gnu/java/net/PlainDatagramSocketImpl.java =================================================================== --- trunk/core/src/classpath/gnu/gnu/java/net/PlainDatagramSocketImpl.java 2006-12-14 10:15:31 UTC (rev 2918) +++ trunk/core/src/classpath/gnu/gnu/java/net/PlainDatagramSocketImpl.java 2006-12-14 10:17:15 UTC (rev 2919) @@ -1,5 +1,5 @@ /* PlainDatagramSocketImpl.java -- Default DatagramSocket implementation - Copyright (C) 1998, 1999, 2001, 2003, 2004, 2005 Free Software Foundation, Inc. + Copyright (C) 1998, 1999, 2001, 2003, 2004, 2005, 2006 Free Software Foundation, Inc. This file is part of GNU Classpath. @@ -38,7 +38,10 @@ package gnu.java.net; +import gnu.java.nio.VMChannel; + import java.io.IOException; +import java.io.InterruptedIOException; import java.net.DatagramPacket; import java.net.DatagramSocketImpl; import java.net.InetAddress; @@ -46,8 +49,8 @@ import java.net.NetworkInterface; import java.net.SocketAddress; import java.net.SocketException; -import java.net.SocketOptions; -import gnu.classpath.Configuration; +import java.net.SocketTimeoutException; +import java.nio.ByteBuffer; /** * Written using on-line Java Platform 1.2 API Specification, as well @@ -65,17 +68,12 @@ */ public final class PlainDatagramSocketImpl extends DatagramSocketImpl { - // @vm-specific removed System.loadLibrary - + private final VMChannel channel; + /** - * Option id for the IP_TTL (time to live) value. + * The platform-specific socket implementation. */ - private static final int IP_TTL = 0x1E61; // 7777 - - /** - * This is the actual underlying file descriptor - */ - int native_fd = -1; + private final VMPlainSocketImpl impl; /** * Lock object to serialize threads wanting to receive @@ -90,24 +88,26 @@ /** * Default do nothing constructor */ - public PlainDatagramSocketImpl() + public PlainDatagramSocketImpl() throws IOException { + channel = new VMChannel(); + impl = new VMPlainSocketImpl(channel); } - protected void finalize() throws Throwable + /*protected void finalize() throws Throwable { synchronized (this) { - if (native_fd != -1) + if (channel.getState().isValid()) close(); } super.finalize(); - } + }*/ - public int getNativeFD() + /*public int getNativeFD() { return native_fd; - } + }*/ /** * Binds this socket to a particular port and interface @@ -120,9 +120,20 @@ protected synchronized void bind(int port, InetAddress addr) throws SocketException { - // @vm-specific no natives - //TODO implement me - throw new SocketException("Not implemented"); + try + { + impl.bind(new InetSocketAddress(addr, port)); + } + catch (SocketException se) + { + throw se; + } + catch (IOException ioe) + { + SocketException se = new SocketException(); + se.initCause(ioe); + throw se; + } } /** @@ -130,13 +141,58 @@ * * @exception SocketException If an error occurs */ - protected synchronized void create() throws SocketException { - // @vm-specific no natives - //TODO implement me - throw new SocketException("Not implemented"); + protected synchronized void create() throws SocketException + { + try + { + channel.initSocket(false); + } + catch (SocketException se) + { + throw se; + } + catch (IOException ioe) + { + SocketException se = new SocketException(); + se.initCause(ioe); + throw se; + } } /** + * Connects to the remote address and port specified as arguments. + * + * @param addr The remote address to connect to + * @param port The remote port to connect to + * + * @exception SocketException If an error occurs + */ + protected void connect(InetAddress addr, int port) throws SocketException + { + channel.connect(new InetSocketAddress(addr, port), 0); + } + + /** + * Disconnects the socket. + * + * @since 1.4 + */ + protected void disconnect() + { + synchronized (this) + { + try + { + if (channel.getState().isValid()) + channel.disconnect(); + } + catch (IOException ioe) + { + } + } + } + + /** * Sets the Time to Live value for the socket * * @param ttl The new TTL value @@ -145,7 +201,7 @@ */ protected synchronized void setTimeToLive(int ttl) throws IOException { - setOption(IP_TTL, new Integer(ttl)); + impl.setTimeToLive(ttl); } /** @@ -157,48 +213,60 @@ */ protected synchronized int getTimeToLive() throws IOException { - Object obj = getOption(IP_TTL); + return impl.getTimeToLive(); + } - if (! (obj instanceof Integer)) - throw new IOException("Internal Error"); + protected int getLocalPort() + { + if (channel == null) + return -1; - return ((Integer) obj).intValue(); + try + { + InetSocketAddress local = channel.getLocalAddress(); + if (local == null) + return -1; + return local.getPort(); + } + catch (IOException ioe) + { + return -1; + } } /** * Sends a packet of data to a remote host * - * @param addr The address to send to - * @param port The port to send to - * @param buf The buffer to send - * @param offset The offset of the data in the buffer to send - * @param len The length of the data to send - * - * @exception IOException If an error occurs - */ - private void sendto (InetAddress addr, int port, - byte[] buf, int offset, int len) - throws IOException { - // @vm-specific no natives - //TODO implement me - throw new SocketException("Not implemented"); - } - - /** - * Sends a packet of data to a remote host - * * @param packet The packet to send * * @exception IOException If an error occurs */ protected void send(DatagramPacket packet) throws IOException { - synchronized(SEND_LOCK) + synchronized (SEND_LOCK) { - sendto(packet.getAddress(), packet.getPort(), packet.getData(), - packet.getOffset(), packet.getLength()); + ByteBuffer buf = ByteBuffer.wrap(packet.getData(), + packet.getOffset(), + packet.getLength()); + InetAddress remote = packet.getAddress(); + int port = packet.getPort(); + if (remote == null) + throw new NullPointerException(); + if (port <= 0) + throw new SocketException("invalid port " + port); + while (true) + { + try + { + channel.send(buf, new InetSocketAddress(remote, port)); + break; + } + catch (InterruptedIOException ioe) + { + // Ignore; interrupted system call. + } + } } - } /** @@ -211,63 +279,123 @@ protected void receive(DatagramPacket packet) throws IOException { - synchronized(RECEIVE_LOCK) - { - receive0(packet); - } + synchronized(RECEIVE_LOCK) + { + ByteBuffer buf = ByteBuffer.wrap(packet.getData(), + packet.getOffset(), + packet.getLength()); + SocketAddress addr = null; + while (true) + { + try + { + addr = channel.receive(buf); + break; + } + catch (SocketTimeoutException ste) + { + throw ste; + } + catch (InterruptedIOException iioe) + { + // Ignore. Loop. + } + } + if (addr != null) + packet.setSocketAddress(addr); + packet.setLength(buf.position() - packet.getOffset()); + } } - /** - * Native call to receive a UDP packet from the network - * - * @param packet The packet to fill in with the data received - * - * @exception IOException IOException If an error occurs - */ - private void receive0(DatagramPacket packet) throws IOException { - // @vm-specific no natives - //TODO implement me - throw new SocketException("Not implemented"); - } /** * Sets the value of an option on the socket * - * @param option_id The identifier of the option to set - * @param val The value of the option to set + * @param optionId The identifier of the option to set + * @param value The value of the option to set * * @exception SocketException If an error occurs */ - public synchronized void setOption(int option_id, Object val) - throws SocketException { - // @vm-specific no natives - //TODO implement me - throw new SocketException("Not implemented"); + public synchronized void setOption(int optionId, Object value) + throws SocketException + { + switch (optionId) + { + case IP_MULTICAST_IF: + case IP_MULTICAST_IF2: + impl.setMulticastInterface(optionId, (InetAddress) value); + break; + + case IP_MULTICAST_LOOP: + case SO_BROADCAST: + case SO_KEEPALIVE: + case SO_OOBINLINE: + case TCP_NODELAY: + case IP_TOS: + case SO_LINGER: + case SO_RCVBUF: + case SO_SNDBUF: + case SO_TIMEOUT: + case SO_REUSEADDR: + impl.setOption(optionId, value); + return; + + default: + throw new SocketException("cannot set option " + optionId); + } } /** * Retrieves the value of an option on the socket * - * @param option_id The identifier of the option to retrieve + * @param optionId The identifier of the option to retrieve * * @return The value of the option * * @exception SocketException If an error occurs */ - public synchronized Object getOption(int option_id) - throws SocketException { - // @vm-specific no natives - //TODO implement me - throw new SocketException("Not implemented"); + public synchronized Object getOption(int optionId) + throws SocketException + { + if (optionId == SO_BINDADDR) + { + try + { + InetSocketAddress local = channel.getLocalAddress(); + if (local == null) + return null; + return local.getAddress(); + } + catch (SocketException se) + { + throw se; + } + catch (IOException ioe) + { + SocketException se = new SocketException(); + se.initCause(ioe); + throw se; + } + } + if (optionId == IP_MULTICAST_IF || optionId == IP_MULTICAST_IF2) + return impl.getMulticastInterface(optionId); + + return impl.getOption(optionId); } /** * Closes the socket */ - protected synchronized void close() { - // @vm-specific no natives - //TODO implement me - throw new RuntimeException("Not implemented"); + protected synchronized void close() + { + try + { + if (channel.getState().isValid()) + channel.close(); + } + catch (IOException ioe) + { + } } /** @@ -305,9 +433,9 @@ * * @exception IOException If an error occurs */ - protected synchronized void join(InetAddress addr) throws IOException { - // @vm-specific no natives - throw new SocketException("Not implemented"); + protected synchronized void join(InetAddress addr) throws IOException + { + impl.join(addr); } /** @@ -317,10 +445,9 @@ * * @exception IOException If an error occurs */ - protected synchronized void leave(InetAddress addr) throws IOException { - // @vm-specific no natives - //TODO implement me - throw new SocketException("Not implemented"); + protected synchronized void leave(InetAddress addr) throws IOException + { + impl.leave(addr); } /** @@ -338,14 +465,22 @@ } public void joinGroup(SocketAddress address, NetworkInterface netIf) + throws IOException { - throw new InternalError - ("PlainDatagramSocketImpl::joinGroup is not implemented"); + if (address == null) + throw new NullPointerException(); + if (!(address instanceof InetSocketAddress)) + throw new SocketException("unknown address type"); + impl.joinGroup((InetSocketAddress) address, netIf); } public void leaveGroup(SocketAddress address, NetworkInterface netIf) + throws IOException { - throw new InternalError - ("PlainDatagramSocketImpl::leaveGroup is not implemented"); + if (address == null) + throw new NullPointerException(); + if (!(address instanceof InetSocketAddress)) + throw new SocketException("unknown address type"); + impl.leaveGroup((InetSocketAddress) address, netIf); } } Modified: trunk/core/src/classpath/gnu/gnu/java/net/PlainSocketImpl.java =================================================================== --- trunk/core/src/classpath/gnu/gnu/java/net/PlainSocketImpl.java 2006-12-14 10:15:31 UTC (rev 2918) +++ trunk/core/src/classpath/gnu/gnu/java/net/PlainSocketImpl.java 2006-12-14 10:17:15 UTC (rev 2919) @@ -39,16 +39,20 @@ package gnu.java.net; +import gnu.java.nio.SocketChannelImpl; +import gnu.java.nio.VMChannel; + import java.io.InputStream; import java.io.IOException; +import java.io.InterruptedIOException; import java.io.OutputStream; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.SocketAddress; import java.net.SocketException; import java.net.SocketImpl; -import java.net.SocketOptions; -import gnu.classpath.Configuration; +import java.net.SocketTimeoutException; +import java.nio.ByteBuffer; /** * Written using on-line Java Platform 1.2 API Specification, as well @@ -66,25 +70,13 @@ * @author Nic Ferrier (nfe...@ta...) * @author Aaron M. Renn (ar...@ur...) */ -public final class PlainSocketImpl extends SocketImpl +public class PlainSocketImpl extends SocketImpl { - // Static initializer to load native library. - static - { - if (Configuration.INIT_LOAD_LIBRARY) - { - System.loadLibrary("javanet"); - } - } /** - * The OS file handle representing the socket. - * This is used for reads and writes to/from the socket and - * to close it. - * - * When the socket is closed this is reset to -1. + * The underlying plain socket VM implementation. */ - int native_fd = -1; + protected VMPlainSocketImpl impl; /** * A cached copy of the in stream for reading from the socket. @@ -101,8 +93,14 @@ * is being invoked on this socket. */ private boolean inChannelOperation; - + /** + * The socket channel we use for IO operation. Package-private for + * use by inner classes. + */ + SocketChannelImpl channel; + + /** * Indicates whether we should ignore whether any associated * channel is set to non-blocking mode. Certain operations * throw an <code>IllegalBlockingModeException</code> if the @@ -124,48 +122,44 @@ } /** - * Default do nothing constructor + * Default do nothing constructor. */ public PlainSocketImpl() { + this.impl = new VMPlainSocketImpl(); } - - protected void finalize() throws Throwable - { - synchronized (this) - { - if (native_fd != -1) - try - { - close(); - } - catch (IOException ex) - { - } - } - super.finalize(); - } - public int getNativeFD() - { - return native_fd; - } - /** * 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 * Integer. The option_id parameter is one of the defined constants in * this interface. * - * @param option_id The identifier of the option - * @param val The value to set the option to + * @param optionId The identifier of the option + * @param value The value to set the option to * - * @exception SocketException If an error occurs + * @throws SocketException if an error occurs */ - public void setOption(int optID, Object value) throws SocketException { - // @vm-specific no natives - //TODO implement me - throw new SocketException("Not implemented"); + public void setOption(int optionId, Object value) throws SocketException + { + switch (optionId) + { + case SO_LINGER: + case IP_MULTICAST_LOOP: + case SO_BROADCAST: + case SO_KEEPALIVE: + case SO_OOBINLINE: + case TCP_NODELAY: + case IP_TOS: + case SO_RCVBUF: + case SO_SNDBUF: + case SO_TIMEOUT: + case SO_REUSEADDR: + impl.setOption(optionId, value); + return; + default: + throw new SocketException("Unrecognized TCP option: " + optionId); + } } /** @@ -173,133 +167,144 @@ * will be an Integer for options that have integer values. The option_id * is one of the defined constants in this interface. * - * @param option_id The option identifier + * @param optionId the option identifier * - * @return The current value of the option + * @return the current value of the option * - * @exception SocketException If an error occurs + * @throws SocketException if an error occurs */ - public Object getOption(int optID) throws SocketException { - // @vm-specific no natives - //TODO implement me - throw new SocketException("Not implemented"); + public Object getOption(int optionId) throws SocketException + { + if (optionId == SO_BINDADDR) + { + try + { + return channel.getVMChannel().getLocalAddress().getAddress(); + } + catch (IOException ioe) + { + SocketException se = new SocketException(); + se.initCause(ioe); + throw se; + } + } + + // This filters options which are invalid for TCP. + switch (optionId) + { + case SO_LINGER: + case IP_MULTICAST_LOOP: + case SO_BROADCAST: + case SO_KEEPALIVE: + case SO_OOBINLINE: + case TCP_NODELAY: + case IP_TOS: + case SO_RCVBUF: + case SO_SNDBUF: + case SO_TIMEOUT: + case SO_REUSEADDR: + return impl.getOption(optionId); + default: + throw new SocketException("Unrecognized TCP option: " + optionId); + } + } - /** - * Flushes the input stream and closes it. If you read from the input stream - * after calling this method a <code>IOException</code> will be thrown. - * - * @throws IOException if an error occurs - */ - public void shutdownInput() + public void shutdownInput() throws IOException { - // @vm-specific no natives - //TODO implement me - throw new InternalError ("PlainSocketImpl::shutdownInput not implemented"); + impl.shutdownInput(); } - /** - * Flushes the output stream and closes it. If you write to the output stream - * after calling this method a <code>IOException</code> will be thrown. - * - * @throws IOException if an error occurs - */ public void shutdownOutput() throws IOException { - // @vm-specific no natives - //TODO implement me - throw new InternalError ("PlainSocketImpl::shutdownOutput not implemented"); + impl.shutdownOutput(); } /** * 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. + * is not connected to any remote address/port. The stream parameter will be + * ignored since PlainSocketImpl always is a stream socket. Datagram sockets + * are handled by PlainDatagramSocketImpl. * - * @param stream true for a stream socket, false for a datagram socket + * @param stream <code>true</code> for stream sockets, <code>false</code> for + * datagram sockets */ - protected synchronized void create(boolean stream) throws IOException { - // @vm-specific no natives - //TODO implement me - throw new SocketException("Not implemented"); + protected synchronized void create(boolean stream) throws IOException + { + channel = new SocketChannelImpl(false); + VMChannel vmchannel = channel.getVMChannel(); + vmchannel.initSocket(stream); + channel.configureBlocking(true); + impl.getState().setChannelFD(vmchannel.getState()); } /** * Connects to the remote hostname and port specified as arguments. * - * @param hostname The remote hostname to connect to - * @param port The remote port to connect to + * @param hostname the remote hostname to connect to + * @param port the remote port to connect to * - * @exception IOException If an error occurs + * @throws IOException If an error occurs */ - protected synchronized void connect(String host, int port) throws IOException + protected synchronized void connect(String hostname, int port) + throws IOException { - connect(InetAddress.getByName(host), port); + connect(InetAddress.getByName(hostname), port); } /** * Connects to the remote address and port specified as arguments. * - * @param addr The remote address to connect to - * @param port The remote port to connect to + * @param addr the remote address to connect to + * @param port the remote port to connect to * - * @exception IOException If an error occurs + * @throws IOException If an error occurs */ - protected void connect(InetAddress addr, int port) throws IOException { - // @vm-specific no natives - //TODO implement me - throw new SocketException("Not implemented"); + protected void connect(InetAddress addr, int port) throws IOException + { + connect(new InetSocketAddress(addr, port), 0); } /** * Connects to the remote socket address with a specified timeout. * - * @param timeout The timeout to use for this connect, 0 means infinite. + * @param address the remote address to connect to + * @param timeout the timeout to use for this connect, 0 means infinite. * - * @exception IOException If an error occurs + * @throws IOException If an error occurs */ - protected synchronized void connect(SocketAddress address, int timeout) throws IOException + protected synchronized void connect(SocketAddress address, int timeout) + throws IOException { - InetSocketAddress sockAddr = (InetSocketAddress) address; - InetAddress addr = sockAddr.getAddress(); - - if (addr == null) - throw new IllegalArgumentException("address is unresolved: " + sockAddr); - - int port = sockAddr.getPort(); + if (channel == null) + create(true); + boolean connected = channel.connect(address, timeout); + if (!connected) + throw new SocketTimeoutException("connect timed out"); - if (timeout < 0) - throw new IllegalArgumentException("negative timeout"); - - Object oldTimeoutObj = null; - - try - { - oldTimeoutObj = this.getOption (SocketOptions.SO_TIMEOUT); - this.setOption (SocketOptions.SO_TIMEOUT, new Integer (timeout)); - connect (addr, port); - } - finally - { - if (oldTimeoutObj != null) - this.setOption (SocketOptions.SO_TIMEOUT, oldTimeoutObj); - } + // Using the given SocketAddress is important to preserve + // hostnames given by the caller. + InetSocketAddress addr = (InetSocketAddress) address; + this.address = addr.getAddress(); + this.port = addr.getPort(); } /** * Binds to the specified port on the specified addr. Note that this addr * must represent a local IP address. **** How bind to INADDR_ANY? **** * - * @param addr The address to bind to - * @param port The port number to bind to + * @param addr the address to bind to + * @param port the port number to bind to * - * @exception IOException If an error occurs + * @throws IOException if an error occurs */ protected synchronized void bind(InetAddress addr, int port) - throws IOException { - // @vm-specific no natives - throw new SocketException("Not implemented"); + throws IOException + { + if (channel == null) + create(true); + impl.bind(new InetSocketAddress(addr, port)); + localport = channel.getVMChannel().getLocalAddress().getPort(); } /** @@ -310,13 +315,12 @@ * * @param queuelen The length of the pending connection queue * - * @exception IOException If an error occurs + * @throws IOException If an error occurs */ protected synchronized void listen(int queuelen) - throws IOException { - // @vm-specific no natives - //TODO implement me - throw new SocketException("Not implemented"); + throws IOException + { + impl.listen(queuelen); } /** @@ -326,78 +330,64 @@ * @param impl The SocketImpl object to accept this connection. */ protected synchronized void accept(SocketImpl impl) - throws IOException { - // @vm-specific no natives - //TODO implement me - throw new SocketException("Not implemented"); + throws IOException + { + if (channel == null) + create(true); + if (!(impl instanceof PlainSocketImpl)) + throw new IOException("incompatible SocketImpl: " + + impl.getClass().getName()); + PlainSocketImpl that = (PlainSocketImpl) impl; + VMChannel c = channel.getVMChannel().accept(); + that.impl.getState().setChannelFD(c.getState()); + that.channel = new SocketChannelImpl(c); + that.setOption(SO_REUSEADDR, Boolean.TRUE); + // Reset the inherited timeout. + that.setOption(SO_TIMEOUT, Integer.valueOf(0)); + } /** * Returns the number of bytes that the caller can read from this socket * without blocking. * - * @return The number of readable bytes before blocking + * @return the number of readable bytes before blocking * - * @exception IOException If an error occurs + * @throws IOException if an error occurs */ - protected int available() throws IOException { - // @vm-specific no natives - //TODO implement me - throw new SocketException("Not implemented"); + protected int available() throws IOException + { + if (channel == null) + throw new SocketException("not connected"); + return channel.getVMChannel().available(); } /** * Closes the socket. This will cause any InputStream or OutputStream * objects for this Socket to be closed as well. + * * <p> * Note that if the SO_LINGER option is set on this socket, then the * operation could block. + * </p> * - * @exception IOException If an error occurs + * @throws IOException if an error occurs */ - protected void close() throws IOException { - // @vm-specific no natives - //TODO implement me - throw new SocketException("Not implemented"); + protected void close() throws IOException + { + if (impl.getState().isValid()) + impl.close(); + + address = null; + port = -1; } - public void sendUrgentData(int data) + public void sendUrgentData(int data) throws IOException { - throw new InternalError ("PlainSocketImpl::sendUrgentData not implemented"); + impl.sendUrgentData(data); } /** - * Internal method used by SocketInputStream for reading data from - * the connection. Reads up to len bytes of data into the buffer - * buf starting at offset bytes into the buffer. - * - * @return The actual number of bytes read or -1 if end of stream. - * - * @exception IOException If an error occurs - */ - protected int read(byte[] buf, int offset, int len) - throws IOException { - // @vm-specific no natives - //TODO implement me - throw new SocketException("Not implemented"); - - } - - /** - * Internal method used by SocketOuputStream for writing data to - * the connection. Writes up to len bytes of data from the buffer - * buf starting at offset bytes into the buffer. - * - * @exception IOException If an error occurs - */ - protected void write(byte[] buf, int offset, int len) - throws IOException { - // @vm-specific no natives - //TODO implement me - throw new SocketException("Not implemented"); - } - - /** * Returns an InputStream object for reading from this socket. This will * be an instance of SocketInputStream. * @@ -409,7 +399,7 @@ { if (in == null) in = new SocketInputStream(); - + return in; } @@ -425,15 +415,104 @@ { if (out == null) out = new SocketOutputStream(); - + return out; } + + public VMChannel getVMChannel() + { + if (channel == null) + return null; + return channel.getVMChannel(); + } + /* (non-Javadoc) + * @see java.net.SocketImpl#getInetAddress() + */ + protected InetAddress getInetAddress() + { + if (channel == null) + return null; + + try + { + InetSocketAddress remote = channel.getVMChannel().getPeerAddress(); + if (remote == null) + return null; + // To mimic behavior of the RI the InetAddress instance which was + // used to establish the connection is returned instead of one that + // was created by the native layer (this preserves exact hostnames). + if (address != null) + return address; + + return remote.getAddress(); + } + catch (IOException ioe) + { + return null; + } + } + + /* (non-Javadoc) + * @see java.net.SocketImpl#getLocalPort() + */ + protected int getLocalPort() + { + if (channel == null) + return -1; + try + { + InetSocketAddress local = channel.getVMChannel().getLocalAddress(); + if (local == null) + return -1; + return local.getPort(); + } + catch (IOException ioe) + { + return -1; + } + } + + public InetSocketAddress getLocalAddress() + { + if (channel == null) + return null; + try + { + return channel.getVMChannel().getLocalAddress(); + } + catch (IOException ioe) + { + return null; + } + } + + /* (non-Javadoc) + * @see java.net.SocketImpl#getPort() + */ + protected int getPort() + { + if (channel == null) + return -1; + + try + { + InetSocketAddress remote = channel.getVMChannel().getPeerAddress(); + if (remote == null) + return -1; + return remote.getPort(); + } + catch (IOException ioe) + { + return -1; + } + } + /** * This class contains an implementation of <code>InputStream</code> for * sockets. It in an internal only class used by <code>PlainSocketImpl</code>. * - * @author Nic Ferrier (nfe...@ta...) + * @author Nic Ferrier <nfe...@ta...> */ final class SocketInputStream extends InputStream @@ -465,13 +544,23 @@ */ public int read() throws IOException { - byte buf[] = new byte [1]; - int bytes_read = read(buf, 0, 1); - - if (bytes_read == -1) - return -1; - - return buf[0] & 0xFF; + if (channel == null) + throw new SocketException("not connected"); + while (true) + { + try + { + return channel.getVMChannel().read(); + } + catch (SocketTimeoutException ste) + { + throw ste; + } + catch (InterruptedIOException iioe) + { + // Ignore; NIO may throw this; net io shouldn't + } + } } /** @@ -488,12 +577,24 @@ */ public int read (byte[] buf, int offset, int len) throws IOException { - int bytes_read = PlainSocketImpl.this.read (buf, offset, len); - - if (bytes_read == 0) - return -1; - - return bytes_read; + if (channel == null) + throw new SocketException("not connected"); + ByteBuffer b = ByteBuffer.wrap(buf, offset, len); + while (true) + { + try + { + return channel.read(b); + } + catch (SocketTimeoutException ste) + { + throw ste; + } + catch (InterruptedIOException iioe) + { + // Ignored; NIO may throw this; net IO not. + } + } } } @@ -503,7 +604,7 @@ * <code>getOutputStream method</code>. It expects only to be used in that * context. * - * @author Nic Ferrier (nfe...@ta...) + * @author Nic Ferrier <nfe...@ta...> */ final class SocketOutputStream extends OutputStream @@ -529,8 +630,20 @@ */ public void write(int b) throws IOException { - byte buf[] = { (byte) b }; - write(buf, 0, 1); + if (channel == null) + throw new SocketException("not connected"); + while (true) + { + try + { + channel.getVMChannel().write(b); + return; + } + catch (InterruptedIOException iioe) + { + // Ignored. + } + } } /** @@ -545,7 +658,21 @@ */ public void write (byte[] buf, int offset, int len) throws IOException { - PlainSocketImpl.this.write (buf, offset, len); + if (channel == null) + throw new SocketException("not connected"); + ByteBuffer b = ByteBuffer.wrap(buf, offset, len); + while (b.hasRemaining()) + { + try + { + if (channel.write(b) == -1) + throw new IOException("channel has been closed"); + } + catch (InterruptedIOException iioe) + { + // Ignored. + } + } } } } Modified: trunk/core/src/classpath/gnu/gnu/java/nio/charset/ISO_8859_1.java =================================================================== --- trunk/core/src/classpath/gnu/gnu/java/nio/charset/ISO_8859_1.java 2006-12-14 10:15:31 UTC (rev 2918) +++ trunk/core/src/classpath/gnu/gnu/java/nio/charset/ISO_8859_1.java 2006-12-14 10:17:15 UTC (rev 2919) @@ -128,6 +128,19 @@ super (cs, 1.0f, 1.0f); } + public boolean canEncode(char c) + { + return c <= 0xff; + } + + public boolean canEncode(CharSequence cs) + { + for (int i = 0; i < cs.length(); ++i) + if (! canEncode(cs.charAt(i))) + return false; + return true; + } + protected CoderResult encodeLoop (CharBuffer in, ByteBuffer out) { // TODO: Optimize this in the case in.hasArray() / out.hasArray() Modified: trunk/core/src/classpath/gnu/gnu/java/nio/charset/US_ASCII.java =================================================================== --- trunk/core/src/classpath/gnu/gnu/java/nio/charset/US_ASCII.java 2006-12-14 10:15:31 UTC (rev 2918) +++ trunk/core/src/classpath/gnu/gnu/java/nio/charset/US_ASCII.java 2006-12-14 10:17:15 UTC (rev 2919) @@ -134,6 +134,19 @@ super (cs, 1.0f, 1.0f); } + public boolean canEncode(char c) + { + return c <= 0x7f; + } + + public boolean canEncode(CharSequence cs) + { + for (int i = 0; i < cs.length(); ++i) + if (! canEncode(cs.charAt(i))) + return false; + return true; + } + protected CoderResult encodeLoop (CharBuffer in, ByteBuffer out) { // TODO: Optimize this in the case in.hasArray() / out.hasArray() @@ -141,7 +154,7 @@ { char c = in.get (); - if (c > Byte.MAX_VALUE) + if (c > 0x7f) { in.position (in.position () - 1); return CoderResult.unmappableForLength (1); Modified: trunk/core/src/classpath/gnu/gnu/java/nio/charset/iconv/IconvEncoder.java =================================================================== --- trunk/core/src/classpath/gnu/gnu/java/nio/charset/iconv/IconvEncoder.java 2006-12-14 10:15:31 UTC (rev 2918) +++ trunk/core/src/classpath/gnu/gnu/java/nio/charset/iconv/IconvEncoder.java 2006-12-14 10:17:15 UTC (rev 2919) @@ -43,7 +43,6 @@ import java.nio.ByteBuffer; import java.nio.CharBuffer; import java.nio.charset.Charset; -import java.nio.charset.CharsetDecoder; import java.nio.charset.CharsetEncoder; import java.nio.charset.CoderResult; This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <hag...@us...> - 2006-12-14 10:15:32
|
Revision: 2918 http://jnode.svn.sourceforge.net/jnode/?rev=2918&view=rev Author: hagar-wize Date: 2006-12-14 02:15:31 -0800 (Thu, 14 Dec 2006) Log Message: ----------- Classpath patches Modified Paths: -------------- trunk/core/src/classpath/gnu/gnu/java/nio/charset/iconv/IconvDecoder.java Modified: trunk/core/src/classpath/gnu/gnu/java/nio/charset/iconv/IconvDecoder.java =================================================================== --- trunk/core/src/classpath/gnu/gnu/java/nio/charset/iconv/IconvDecoder.java 2006-12-14 10:15:03 UTC (rev 2917) +++ trunk/core/src/classpath/gnu/gnu/java/nio/charset/iconv/IconvDecoder.java 2006-12-14 10:15:31 UTC (rev 2918) @@ -44,7 +44,6 @@ import java.nio.CharBuffer; import java.nio.charset.Charset; import java.nio.charset.CharsetDecoder; -import java.nio.charset.CharsetEncoder; import java.nio.charset.CoderResult; //todo jnode - native - remove it This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <hag...@us...> - 2006-12-14 10:15:05
|
Revision: 2917 http://jnode.svn.sourceforge.net/jnode/?rev=2917&view=rev Author: hagar-wize Date: 2006-12-14 02:15:03 -0800 (Thu, 14 Dec 2006) Log Message: ----------- Classpath patches Modified Paths: -------------- trunk/core/src/classpath/gnu/gnu/java/nio/charset/ByteCharset.java Modified: trunk/core/src/classpath/gnu/gnu/java/nio/charset/ByteCharset.java =================================================================== --- trunk/core/src/classpath/gnu/gnu/java/nio/charset/ByteCharset.java 2006-12-14 10:09:53 UTC (rev 2916) +++ trunk/core/src/classpath/gnu/gnu/java/nio/charset/ByteCharset.java 2006-12-14 10:15:03 UTC (rev 2917) @@ -156,6 +156,22 @@ } } + public boolean canEncode(char c) + { + byte b = (c < lookup.length) ? lookup[c] : 0; + return b != 0 || c == 0; + } + + public boolean canEncode(CharSequence cs) + { + for (int i = 0; i < cs.length(); ++i) + { + if (! canEncode(cs.charAt(i))) + return false; + } + return true; + } + protected CoderResult encodeLoop (CharBuffer in, ByteBuffer out) { // TODO: Optimize this in the case in.hasArray() / out.hasArray() This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <hag...@us...> - 2006-12-14 10:09:54
|
Revision: 2916 http://jnode.svn.sourceforge.net/jnode/?rev=2916&view=rev Author: hagar-wize Date: 2006-12-14 02:09:53 -0800 (Thu, 14 Dec 2006) Log Message: ----------- Classpath patches Added Paths: ----------- trunk/core/src/classpath/vm/java/net/VMPlainDatagramSocketImpl.java trunk/core/src/classpath/vm/java/net/VMPlainSocketImpl.java Added: trunk/core/src/classpath/vm/java/net/VMPlainDatagramSocketImpl.java =================================================================== --- trunk/core/src/classpath/vm/java/net/VMPlainDatagramSocketImpl.java (rev 0) +++ trunk/core/src/classpath/vm/java/net/VMPlainDatagramSocketImpl.java 2006-12-14 10:09:53 UTC (rev 2916) @@ -0,0 +1,260 @@ +/* PlainDatagramSocketImpl.java -- VM interface for DatagramSocket impl + Copyright (C) 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 gnu.java.net; + +import gnu.classpath.Configuration; + +import java.io.IOException; +import java.net.DatagramPacket; +import java.net.InetAddress; +import java.net.NetworkInterface; +import java.net.SocketAddress; +import java.net.SocketException; + +/** + * The VM interface for {@link gnu.java.net.PlainDatagramSocketImpl}. + * + * @author Ingo Proetel (pr...@ai...) + * @author Roman Kennke (ke...@ai...) + */ +public final class VMPlainDatagramSocketImpl +{ + /** + * Option id for the IP_TTL (time to live) value. + */ + static final int IP_TTL = 0x1E61; // 7777 + + + // Static initializer to load native library + static + { + if (Configuration.INIT_LOAD_LIBRARY) + { + System.loadLibrary("javanet"); + } + } + + /** + * Binds this socket to a particular port and interface + * + * @param socket the socket object + * @param port the port to bind to + * @param addr the address to bind to + * + * @throws SocketException If an error occurs + */ + static native void bind(PlainDatagramSocketImpl socket, int port, + InetAddress addr) + throws SocketException; + + /** + * Creates a new datagram socket. + * + * @param socket the socket object + * + * @throws SocketException If an error occurs + */ + static native void create(PlainDatagramSocketImpl socket) + throws SocketException; + + /** + * Connects to the remote address and port specified as arguments. + * + * @param socket the socket object + * @param addr the remote address to connect to + * @param port the remote port to connect to + * + * @throws SocketException If an error occurs + */ + static native void connect(PlainDatagramSocketImpl socket, InetAddress addr, + int port) + throws SocketException; + + /** + * Sends a packet of data to a remote host. + * + * @param socket the socket object + * @param packet the packet to send + * + * @throws IOException If an error occurs + */ + static void send(PlainDatagramSocketImpl socket, DatagramPacket packet) + throws IOException + { + nativeSendTo(socket, packet.getAddress(), packet.getPort(), + packet.getData(), packet.getOffset(), packet.getLength()); + } + + + /** + * Sends a packet of data to a remote host. + * + * @param socket the socket object + * @param addr the address to send to + * @param port the port to send to + * @param buf the buffer to send + * @param offset the offset of the data in the buffer to send + * @param len the length of the data to send + * + * @throws IOException If an error occurs + */ + private static native void nativeSendTo(PlainDatagramSocketImpl socket, + InetAddress addr, int port, + byte[] buf, int offset, int len) + throws IOException; + + /** + * Receives a UDP packet from the network + * + * @param socket the socket object + * @param packet the packet to fill in with the data received + * + * @throws IOException IOException If an error occurs + */ + static void receive(PlainDatagramSocketImpl socket, DatagramPacket packet) + throws IOException + { + byte[] receiveFromAddress = new byte[4]; + int[] receiveFromPort = new int[1]; + int[] receivedLength = new int[1]; + + nativeReceive(socket, packet.getData(), packet.getOffset(), + packet.getLength(), + receiveFromAddress, receiveFromPort, receivedLength); + + packet.setAddress(InetAddress.getByAddress(receiveFromAddress)); + packet.setPort(receiveFromPort[0]); + packet.setLength(receivedLength[0]); + } + + private static native void nativeReceive(PlainDatagramSocketImpl socket, + byte[] buf, int offset, int len, + byte[] receiveFromAddress, + int[] receiveFromPort, + int[] receivedLength) + throws IOException; + + /** + * Sets the value of an option on the socket + * + * @param socket the socket object + * @param optionId the identifier of the option to set + * @param value the value of the option to set + * + * @exception SocketException If an error occurs + */ + static native void setOption(PlainDatagramSocketImpl socket, int optionId, + Object value) + throws SocketException; + + /** + * Retrieves the value of an option on the socket. + * + * @param socket the socket object + * @param optionId the identifier of the option to retrieve + * + * @return the value of the option + * + * @throws SocketException if an error occurs + */ + static native Object getOption(PlainDatagramSocketImpl socket, int optionId) + throws SocketException; + + /** + * Closes the socket. + * + * @param socket the socket object + */ + static native void close(PlainDatagramSocketImpl socket); + + /** + * Joins a multicast group + * + * @param addr The group to join + * + * @exception IOException If an error occurs + */ + static native void join(PlainDatagramSocketImpl socket, InetAddress addr) + throws IOException; + + /** + * Leaves a multicast group + * + * @param addr The group to leave + * + * @exception IOException If an error occurs + */ + static native void leave(PlainDatagramSocketImpl socket, InetAddress addr) + throws IOException; + + /** + * Joins a multicast group. + * + * @param socket the socket object + * @param address the socket address + * @param netIf the network interface + * + * @throws IOException if I/O errors occur + */ + static void joinGroup(PlainDatagramSocketImpl socket, SocketAddress address, + NetworkInterface netIf) + throws IOException + { + throw new InternalError + ("PlainDatagramSocketImpl::joinGroup is not implemented"); + } + + /** + * Leaves a multicast group. + * + * @param socket the socket object + * @param address the socket address + * @param netIf the network interface + * + * @throws IOException if I/O errors occur + */ + static void leaveGroup(PlainDatagramSocketImpl socket, SocketAddress address, + NetworkInterface netIf) + throws IOException + { + throw new InternalError + ("PlainDatagramSocketImpl::leaveGroup is not implemented"); + } + +} Added: trunk/core/src/classpath/vm/java/net/VMPlainSocketImpl.java =================================================================== --- trunk/core/src/classpath/vm/java/net/VMPlainSocketImpl.java (rev 0) +++ trunk/core/src/classpath/vm/java/net/VMPlainSocketImpl.java 2006-12-14 10:09:53 UTC (rev 2916) @@ -0,0 +1,512 @@ +/* VMPlainSocketImpl.java -- VM interface for default socket implementation + Copyright (C) 2005, 2006 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 gnu.java.net; + +import java.io.IOException; +import java.net.Inet4Address; +import java.net.Inet6Address; +import java.net.InetAddress; +import java.net.InetSocketAddress; +import java.net.NetworkInterface; +import java.net.SocketException; +import java.net.SocketOptions; + +import gnu.classpath.Configuration; +import gnu.java.nio.VMChannel; + +/** + * The VM interface for {@link gnu.java.net.PlainSocketImpl}. + * + * @author Ingo Proetel (pr...@ai...) + * @author Roman Kennke (ke...@ai...) + */ +public final class VMPlainSocketImpl +{ + /** Option id for time to live + */ + private static final int CP_IP_TTL = 0x1E61; + + private final State nfd; + + /** + * Static initializer to load native library. + */ + static + { + if (Configuration.INIT_LOAD_LIBRARY) + { + System.loadLibrary("javanet"); + } + } + + public VMPlainSocketImpl() + { + // XXX consider adding security check here. + nfd = new State(); + } + + public VMPlainSocketImpl(VMChannel channel) throws IOException + { + this(); + nfd.setChannelFD(channel.getState()); + } + + public State getState() + { + return nfd; + } + + /** This method exists to hide the CP_IP_TTL value from + * higher levels. + * + * Always think of JNode ... :) + */ + public void setTimeToLive(int ttl) + throws SocketException + { + try + { + setOption(nfd.getNativeFD(), CP_IP_TTL, ttl); + } + catch (IOException ioe) + { + SocketException se = new SocketException(); + se.initCause(ioe); + throw se; + } + } + + public int getTimeToLive() + throws SocketException + { + try + { + return getOption(nfd.getNativeFD(), CP_IP_TTL); + } + catch (IOException ioe) + { + SocketException se = new SocketException(); + se.initCause(ioe); + throw se; + } + } + + public void setOption(int optionId, Object optionValue) + throws SocketException + { + int value; + if (optionValue instanceof Integer) + value = ((Integer) optionValue).intValue(); + else if (optionValue instanceof Boolean) + // Switching off the linger behavior is done by setting + // the value to -1. This is how the Java API interprets + // it. + value = ((Boolean) optionValue).booleanValue() + ? 1 + : (optionId == SocketOptions.SO_LINGER) + ? -1 + : 0; + else + throw new IllegalArgumentException("option value type " + + optionValue.getClass().getName()); + + try + { + setOption(nfd.getNativeFD(), optionId, value); + } + catch (IOException ioe) + { + SocketException se = new SocketException(); + se.initCause(ioe); + throw se; + } + } + + private static native void setOption(int fd, int id, int value) + throws SocketException; + + public void setMulticastInterface(int optionId, InetAddress addr) + throws SocketException + { + try + { + if (addr instanceof Inet4Address) + setMulticastInterface(nfd.getNativeFD(), optionId, (Inet4Address) addr); + else if (addr instanceof Inet6Address) + { + NetworkInterface iface = NetworkInterface.getByInetAddress(addr); + setMulticastInterface6(nfd.getNativeFD(), optionId, iface.getName()); + } + else + throw new SocketException("Unknown address format: " + addr); + } + catch (SocketException se) + { + throw se; + } + catch (IOException ioe) + { + SocketException se = new SocketException(); + se.initCause(ioe); + throw se; + } + } + + private static native void setMulticastInterface(int fd, + int optionId, + Inet4Address addr); + + private static native void setMulticastInterface6(int fd, + int optionId, + String ifName); + + /** + * Get a socket option. This implementation is only required to support + * socket options that are boolean values, which include: + * + * SocketOptions.IP_MULTICAST_LOOP + * SocketOptions.SO_BROADCAST + * SocketOptions.SO_KEEPALIVE + * SocketOptions.SO_OOBINLINE + * SocketOptions.SO_REUSEADDR + * SocketOptions.TCP_NODELAY + * + * and socket options that are integer values, which include: + * + * SocketOptions.IP_TOS + * SocketOptions.SO_LINGER + * SocketOptions.SO_RCVBUF + * SocketOptions.SO_SNDBUF + * SocketOptions.SO_TIMEOUT + * + * @param optionId The option ID to fetch. + * @return A {@link Boolean} or {@link Integer} containing the socket + * option. + * @throws SocketException + */ + public Object getOption(int optionId) throws SocketException + { + int value; + try + { + value = getOption(nfd.getNativeFD(), optionId); + } + catch (IOException ioe) + { + SocketException se = new SocketException(); + se.initCause(ioe); + throw se; + } + + switch (optionId) + { + case SocketOptions.IP_MULTICAST_LOOP: + case SocketOptions.SO_BROADCAST: + case SocketOptions.SO_KEEPALIVE: + case SocketOptions.SO_OOBINLINE: + case SocketOptions.SO_REUSEADDR: + case SocketOptions.TCP_NODELAY: + return Boolean.valueOf(value != 0); + + case SocketOptions.IP_TOS: + case SocketOptions.SO_LINGER: + case SocketOptions.SO_RCVBUF: + case SocketOptions.SO_SNDBUF: + case SocketOptions.SO_TIMEOUT: + return new Integer(value); + + default: + throw new SocketException("getting option " + optionId + + " not supported here"); + } + } + + private static native int getOption(int fd, int id) throws SocketException; + + /** + * Returns an Inet4Address or Inet6Address instance belonging to the + * interface which is set as the multicast interface. + * + * The optionId is provided to make it possible that the native + * implementation may do something different depending on whether + * the value is SocketOptions.IP_MULTICAST_IF or + * SocketOptions.IP_MULTICAST_IF2. + */ + public InetAddress getMulticastInterface(int optionId) + throws SocketException + { + try + { + return getMulticastInterface(nfd.getNativeFD(), optionId); + } + catch (IOException ioe) + { + SocketException se = new SocketException(); + se.initCause(ioe); + throw se; + } + } + + private static native InetAddress getMulticastInterface(int fd, + int optionId); + + /** + * Binds this socket to the given local address and port. + * + * @param address The address to bind to; the InetAddress is either + * an IPv4 or IPv6 address. + * @throws IOException If binding fails; for example, if the port + * in the given InetSocketAddress is privileged, and the current + * process has insufficient privileges. + */ + public void bind(InetSocketAddress address) throws IOException + { + InetAddress addr = address.getAddress(); + if (addr instanceof Inet4Address) + { + bind (nfd.getNativeFD(), addr.getAddress(), address.getPort()); + } + else if (addr instanceof Inet6Address) + bind6 (nfd.getNativeFD(), addr.getAddress(), address.getPort()); + else + throw new SocketException ("unsupported address type"); + } + + /** + * Native bind function for IPv4 addresses. The addr array must be + * exactly four bytes long. + * + * VMs without native support need not implement this. + * + * @param fd The native file descriptor integer. + * @param addr The IPv4 address, in network byte order. + * @param port The port to bind to. + * @throws IOException + */ + private static native void bind(int fd, byte[] addr, int port) + throws IOException; + + /** + * Native bind function for IPv6 addresses. The addr array must be + * exactly sixteen bytes long. + * + * VMs without native support need not implement this. + * + * @param fd The native file descriptor integer. + * @param addr The IPv6 address, in network byte order. + * @param port The port to bind to. + * @throws IOException + */ + private static native void bind6(int fd, byte[] addr, int port) + throws IOException; + + /** + * Listen on this socket for incoming connections. + * + * @param backlog The backlog of connections. + * @throws IOException If listening fails. + * @see gnu.java.nio.VMChannel#accept() + */ + public void listen(int backlog) throws IOException + { + listen(nfd.getNativeFD(), backlog); + } + + /** + * Native listen function. VMs without native support need not implement + * this. + * + * @param fd The file descriptor integer. + * @param backlog The listen backlog size. + * @throws IOException + */ + private static native void listen(int fd, int backlog) throws IOException; + + public void join(InetAddress group) throws IOException + { + if (group instanceof Inet4Address) + join(nfd.getNativeFD(), group.getAddress()); + else if (group instanceof Inet6Address) + join6(nfd.getNativeFD(), group.getAddress()); + else + throw new IllegalArgumentException("unknown address type"); + } + + private static native void join(int fd, byte[] addr) throws IOException; + + private static native void join6(int fd, byte[] addr) throws IOException; + + public void leave(InetAddress group) throws IOException + { + if (group instanceof Inet4Address) + leave(nfd.getNativeFD(), group.getAddress()); + else if (group instanceof Inet6Address) + leave6(nfd.getNativeFD(), group.getAddress()); + else + throw new IllegalArgumentException("unknown address type"); + } + + private static native void leave(int fd, byte[] addr) throws IOException; + + private static native void leave6(int fd, byte[] addr) throws IOException; + + public void joinGroup(InetSocketAddress addr, NetworkInterface netif) + throws IOException + { + InetAddress address = addr.getAddress(); + + if (address instanceof Inet4Address) + joinGroup(nfd.getNativeFD(), address.getAddress(), + netif != null ? netif.getName() : null); + else if (address instanceof Inet6Address) + joinGroup6(nfd.getNativeFD(), address.getAddress(), + netif != null ? netif.getName() : null); + else + throw new IllegalArgumentException("unknown address type"); + } + + private static native void joinGroup(int fd, byte[] addr, String ifname) + throws IOException; + + private static native void joinGroup6(int fd, byte[] addr, String ifname) + throws IOException; + + public void leaveGroup(InetSocketAddress addr, NetworkInterface netif) + throws IOException + { + InetAddress address = addr.getAddress(); + if (address instanceof Inet4Address) + leaveGroup(nfd.getNativeFD(), address.getAddress(), + netif != null ? netif.getName() : null); + else if (address instanceof Inet6Address) + leaveGroup6(nfd.getNativeFD(), address.getAddress(), + netif != null ? netif.getName() : null); + else + throw new IllegalArgumentException("unknown address type"); + } + + private static native void leaveGroup(int fd, byte[] addr, String ifname) + throws IOException; + + private static native void leaveGroup6(int fd, byte[] addr, String ifname) + throws IOException; + + + public void shutdownInput() throws IOException + { + shutdownInput(nfd.getNativeFD()); + } + + private static native void shutdownInput(int native_fd) throws IOException; + + public void shutdownOutput() throws IOException + { + shutdownOutput(nfd.getNativeFD()); + } + + private static native void shutdownOutput(int native_fd) throws IOException; + + public void sendUrgentData(int data) throws IOException + { + sendUrgentData(nfd.getNativeFD(), data); + } + + private static native void sendUrgentData(int natfive_fd, int data) throws IOException; + + public void close() throws IOException + { + nfd.close(); + } + + // Inner classes. + + /** + * Our wrapper for the native file descriptor. In this implementation, + * it is a simple wrapper around {@link VMChannel.State}, to simplify + * management of the native state. + */ + public final class State + { + private VMChannel.State channelFd; + + State() + { + channelFd = null; + } + + public boolean isValid() + { + if (channelFd != null) + return channelFd.isValid(); + return false; + } + + public int getNativeFD() throws IOException + { + return channelFd.getNativeFD(); + } + + public void setChannelFD(final VMChannel.State nfd) throws IOException + { + if (this.channelFd != null && this.channelFd.isValid()) + throw new IOException("file descriptor already initialized"); + this.channelFd = nfd; + } + + public void close() throws IOException + { + if (channelFd == null) + throw new IOException("invalid file descriptor"); + channelFd.close(); + } + + protected void finalize() throws Throwable + { + try + { + if (isValid()) + close(); + } + finally + { + super.finalize(); + } + } + } +} + This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <hag...@us...> - 2006-12-14 10:08:00
|
Revision: 2915 http://jnode.svn.sourceforge.net/jnode/?rev=2915&view=rev Author: hagar-wize Date: 2006-12-14 02:07:59 -0800 (Thu, 14 Dec 2006) Log Message: ----------- Classpath patches Modified Paths: -------------- trunk/core/src/classpath/vm/java/io/VMOpenMode.java Modified: trunk/core/src/classpath/vm/java/io/VMOpenMode.java =================================================================== --- trunk/core/src/classpath/vm/java/io/VMOpenMode.java 2006-12-14 10:06:39 UTC (rev 2914) +++ trunk/core/src/classpath/vm/java/io/VMOpenMode.java 2006-12-14 10:07:59 UTC (rev 2915) @@ -23,7 +23,7 @@ import org.apache.log4j.Logger; -import gnu.java.nio.channels.FileChannelImpl; +import gnu.java.nio.FileChannelImpl; /** * @author epr This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <hag...@us...> - 2006-12-14 10:06:40
|
Revision: 2914 http://jnode.svn.sourceforge.net/jnode/?rev=2914&view=rev Author: hagar-wize Date: 2006-12-14 02:06:39 -0800 (Thu, 14 Dec 2006) Log Message: ----------- Classpath patches Modified Paths: -------------- trunk/core/src/classpath/java/java/io/FileDescriptor.java trunk/core/src/classpath/java/java/io/FileInputStream.java Modified: trunk/core/src/classpath/java/java/io/FileDescriptor.java =================================================================== --- trunk/core/src/classpath/java/java/io/FileDescriptor.java 2006-12-14 10:05:45 UTC (rev 2913) +++ trunk/core/src/classpath/java/java/io/FileDescriptor.java 2006-12-14 10:06:39 UTC (rev 2914) @@ -134,6 +134,7 @@ */ public boolean valid () { - return channel != null && channel.isOpen(); + ByteChannel c = channel; + return (c != null) && (c.isOpen()); } } Modified: trunk/core/src/classpath/java/java/io/FileInputStream.java =================================================================== --- trunk/core/src/classpath/java/java/io/FileInputStream.java 2006-12-14 10:05:45 UTC (rev 2913) +++ trunk/core/src/classpath/java/java/io/FileInputStream.java 2006-12-14 10:06:39 UTC (rev 2914) @@ -38,8 +38,9 @@ package java.io; -import gnu.java.nio.channels.FileChannelImpl; +import gnu.java.nio.FileChannelImpl; +import java.nio.ByteBuffer; import java.nio.channels.FileChannel; /* Written using "Java Class Libraries", 2nd edition, ISBN 0-201-31002-3 @@ -107,8 +108,21 @@ if (s != null) s.checkRead(file.getPath()); + try + { ch = FileChannelImpl.create(file, FileChannelImpl.READ); } + catch (FileNotFoundException fnfe) + { + throw fnfe; + } + catch (IOException ioe) + { + FileNotFoundException fnfe = new FileNotFoundException(file.getPath()); + fnfe.initCause(ioe); + throw fnfe; + } + } /** * This method initializes a <code>FileInputStream</code> to read from the @@ -266,7 +280,7 @@ || offset + len > buf.length) throw new ArrayIndexOutOfBoundsException(); - return ch.read(buf, offset, len); + return ch.read(ByteBuffer.wrap(buf, offset, len)); } /** This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <hag...@us...> - 2006-12-14 10:05:46
|
Revision: 2913 http://jnode.svn.sourceforge.net/jnode/?rev=2913&view=rev Author: hagar-wize Date: 2006-12-14 02:05:45 -0800 (Thu, 14 Dec 2006) Log Message: ----------- Classpath patches Modified Paths: -------------- trunk/core/src/classpath/vm/java/nio/channels/VMChannels.java Modified: trunk/core/src/classpath/vm/java/nio/channels/VMChannels.java =================================================================== --- trunk/core/src/classpath/vm/java/nio/channels/VMChannels.java 2006-12-14 10:04:53 UTC (rev 2912) +++ trunk/core/src/classpath/vm/java/nio/channels/VMChannels.java 2006-12-14 10:05:45 UTC (rev 2913) @@ -23,7 +23,7 @@ import gnu.java.nio.ChannelInputStream; import gnu.java.nio.ChannelOutputStream; -import gnu.java.nio.channels.FileChannelImpl; +import gnu.java.nio.FileChannelImpl; import java.io.FileInputStream; import java.io.FileOutputStream; This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <hag...@us...> - 2006-12-14 10:04:55
|
Revision: 2912 http://jnode.svn.sourceforge.net/jnode/?rev=2912&view=rev Author: hagar-wize Date: 2006-12-14 02:04:53 -0800 (Thu, 14 Dec 2006) Log Message: ----------- Classpath patches Removed Paths: ------------- trunk/core/src/classpath/gnu/gnu/java/nio/channels/FileChannelImpl.java Deleted: trunk/core/src/classpath/gnu/gnu/java/nio/channels/FileChannelImpl.java =================================================================== --- trunk/core/src/classpath/gnu/gnu/java/nio/channels/FileChannelImpl.java 2006-12-14 09:54:07 UTC (rev 2911) +++ trunk/core/src/classpath/gnu/gnu/java/nio/channels/FileChannelImpl.java 2006-12-14 10:04:53 UTC (rev 2912) @@ -1,583 +0,0 @@ -/* FileChannelImpl.java -- - Copyright (C) 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 gnu.java.nio.channels; - -import gnu.java.nio.FileLockImpl; - -import java.io.File; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.io.VMFile; -import java.io.VMIOUtils; -import java.io.VMOpenMode; -import java.nio.ByteBuffer; -import java.nio.MappedByteBuffer; -import java.nio.channels.ClosedChannelException; -import java.nio.channels.FileChannel; -import java.nio.channels.FileLock; -import java.nio.channels.NonReadableChannelException; -import java.nio.channels.NonWritableChannelException; -import java.nio.channels.ReadableByteChannel; -import java.nio.channels.WritableByteChannel; - -import org.jnode.java.io.VMFileHandle; - -/** - * This file is not user visible ! - * But alas, Java does not have a concept of friendly packages - * so this class is public. - * Instances of this class are created by invoking getChannel - * Upon a Input/Output/RandomAccessFile object. - */ -public final class FileChannelImpl extends FileChannel -{ - // These are mode values for open(). - public static final int READ = 1; - public static final int WRITE = 2; - public static final int APPEND = 4; - - // EXCL is used only when making a temp file. - public static final int EXCL = 8; - public static final int SYNC = 16; - public static final int DSYNC = 32; - - // System's notion of file descriptor. It might seem redundant to - // initialize this given that it is reassigned in the constructors. - // However, this is necessary because if open() throws an exception - // we want to make sure this has the value -1. This is the most - // efficient way to accomplish that. - private VMFileHandle fh; - - private int mode; - - public FileChannelImpl () - { - } - - /* Open a file. MODE is a combination of the above mode flags. */ - /* This is a static factory method, so that VM implementors can decide - * substitute subclasses of FileChannelImpl. */ - public static FileChannelImpl create(File file, int mode) - throws FileNotFoundException - { - return new FileChannelImpl(file, mode); - } - - private FileChannelImpl(File file, int mode) - throws FileNotFoundException - { - final String path = file.getPath(); - fh = open (path, mode); - this.mode = mode; - - // First open the file and then check if it is a a directory - // to avoid race condition. - if (file.isDirectory()) - { - try - { - close(); - } - catch (IOException e) - { - /* ignore it */ - } - - throw new FileNotFoundException(path + " is a directory"); - } - } - - public static FileChannelImpl in; - public static FileChannelImpl out; - public static FileChannelImpl err; - - private VMFileHandle open (String path, int mode) throws FileNotFoundException - { - try - { - return VMIOUtils.getAPI().open(VMFile.getNormalizedPath(path), VMOpenMode.valueOf(mode)); - } - catch (IOException e) - { - FileNotFoundException fnf = new FileNotFoundException("can't find "+path); - fnf.initCause(e); - throw fnf; - } - } - - public int available () throws IOException - { - return fh.available(); - } - - private long implPosition () throws IOException - { - return fh.getPosition(); - } - - private void seek (long newPosition) throws IOException - { - fh.setPosition(newPosition); - } - - private void implTruncate (long size) throws IOException - { - fh.setLength(size); - } - - public void unlock (long pos, long len) throws IOException - { - fh.unlock(pos, len); - } - - public long size () throws IOException - { - return fh.getLength(); - } - - protected void implCloseChannel() throws IOException - { - fh.close(); - } - - /** - * Makes sure the Channel is properly closed. - */ - protected void finalize() throws IOException - { - this.close(); - } - - public int read (ByteBuffer dst) throws IOException - { -// int result; -// byte[] buffer = new byte [dst.remaining ()]; -// -// result = read (buffer, 0, buffer.length); -// -// if (result > 0) -// dst.put (buffer, 0, result); -// -// return result; - return fh.read(dst); - } - - public int read (ByteBuffer dst, long position) - throws IOException - { - if (position < 0) - throw new IllegalArgumentException ("position: " + position); - long oldPosition = implPosition (); - position (position); - int result = read(dst); - position (oldPosition); - - return result; - } - - public int read () - throws IOException - { - return fh.read(); - } - - public int read (byte[] buffer, int offset, int length) - throws IOException - { - ByteBuffer buf = ByteBuffer.wrap(buffer, offset, length); - return fh.read(buf); - } - - public long read (ByteBuffer[] dsts, int offset, int length) - throws IOException - { - long result = 0; - - for (int i = offset; i < offset + length; i++) - { - result += read (dsts [i]); - } - - return result; - } - - public int write (ByteBuffer src) throws IOException - { - int len = src.remaining (); - if (src.hasArray()) - { - byte[] buffer = src.array(); - write(buffer, src.arrayOffset() + src.position(), len); - src.position(src.position() + len); - } - else - { - // Use a more efficient method! FIXME! - byte[] buffer = new byte [len]; - src.get (buffer, 0, len); - write (buffer, 0, len); - } - return len; - } - - public int write (ByteBuffer src, long position) - throws IOException - { - if (position < 0) - throw new IllegalArgumentException ("position: " + position); - - if (!isOpen ()) - throw new ClosedChannelException (); - - if ((mode & WRITE) == 0) - throw new NonWritableChannelException (); - - int result; - long oldPosition; - - oldPosition = implPosition (); - seek (position); - result = write(src); - seek (oldPosition); - - return result; - } - - public void write (byte[] buffer, int offset, int length) - throws IOException - { - fh.write(ByteBuffer.wrap(buffer, offset, length)); - } - - public void write (int b) throws IOException - { - fh.write(b); - } - - public long write(ByteBuffer[] srcs, int offset, int length) - throws IOException - { - long result = 0; - - for (int i = offset;i < offset + length;i++) - { - result += write (srcs[i]); - } - - return result; - } - - public MappedByteBuffer mapImpl (char mode, long position, int size) - throws IOException - { - return fh.mapImpl(mode, position, size); - } - - public MappedByteBuffer map (FileChannel.MapMode mode, - long position, long size) - throws IOException - { - char nmode = 0; - if (mode == MapMode.READ_ONLY) - { - nmode = 'r'; - if ((this.mode & READ) == 0) - throw new NonReadableChannelException(); - } - else if (mode == MapMode.READ_WRITE || mode == MapMode.PRIVATE) - { - nmode = mode == MapMode.READ_WRITE ? '+' : 'c'; - if ((this.mode & (READ|WRITE)) != (READ|WRITE)) - throw new NonWritableChannelException(); - } - else - throw new IllegalArgumentException ("mode: " + mode); - - if (position < 0 || size < 0 || size > Integer.MAX_VALUE) - throw new IllegalArgumentException ("position: " + position - + ", size: " + size); - return mapImpl(nmode, position, (int) size); - } - - /** - * msync with the disk - */ - public void force (boolean metaData) throws IOException - { - if (!isOpen ()) - throw new ClosedChannelException (); - - force (); - } - - private void force () - { - // @vm-specific - //TODO implement me - } - - // like transferTo, but with a count of less than 2Gbytes - private int smallTransferTo (long position, int count, - WritableByteChannel target) - throws IOException - { - ByteBuffer buffer; - try - { - // Try to use a mapped buffer if we can. If this fails for - // any reason we'll fall back to using a ByteBuffer. - buffer = map (MapMode.READ_ONLY, position, count); - } - catch (IOException e) - { - buffer = ByteBuffer.allocate (count); - read (buffer, position); - buffer.flip(); - } - - return target.write (buffer); - } - - public long transferTo (long position, long count, - WritableByteChannel target) - throws IOException - { - if (position < 0 - || count < 0) - throw new IllegalArgumentException (); - - if (!isOpen ()) - throw new ClosedChannelException (); - - if ((mode & READ) == 0) - throw new NonReadableChannelException (); - - final int pageSize = 65536; - long total = 0; - - while (count > 0) - { - int transferred - = smallTransferTo (position, (int)Math.min (count, pageSize), - target); - if (transferred < 0) - break; - total += transferred; - position += transferred; - count -= transferred; - } - - return total; - } - - // like transferFrom, but with a count of less than 2Gbytes - private int smallTransferFrom (ReadableByteChannel src, long position, - int count) - throws IOException - { - ByteBuffer buffer = null; - - if (src instanceof FileChannel) - { - try - { - // Try to use a mapped buffer if we can. If this fails - // for any reason we'll fall back to using a ByteBuffer. - buffer = ((FileChannel)src).map (MapMode.READ_ONLY, position, - count); - } - catch (IOException e) - { - } - } - - if (buffer == null) - { - buffer = ByteBuffer.allocate ((int) count); - src.read (buffer); - buffer.flip(); - } - - return write (buffer, position); - } - - public long transferFrom (ReadableByteChannel src, long position, - long count) - throws IOException - { - if (position < 0 - || count < 0) - throw new IllegalArgumentException (); - - if (!isOpen ()) - throw new ClosedChannelException (); - - if ((mode & WRITE) == 0) - throw new NonWritableChannelException (); - - final int pageSize = 65536; - long total = 0; - - while (count > 0) - { - int transferred = smallTransferFrom (src, position, - (int)Math.min (count, pageSize)); - if (transferred < 0) - break; - total += transferred; - position += transferred; - count -= transferred; - } - - return total; - } - - public FileLock tryLock (long position, long size, boolean shared) - throws IOException - { - if (position < 0 - || size < 0) - throw new IllegalArgumentException ("position: " + position - + ", size: " + size); - - if (!isOpen ()) - throw new ClosedChannelException (); - - if (shared && ((mode & READ) == 0)) - throw new NonReadableChannelException (); - - if (!shared && ((mode & WRITE) == 0)) - throw new NonWritableChannelException (); - - boolean completed = false; - - try - { - begin(); - boolean lockable = lock(position, size, shared, false); - completed = true; - return (lockable - ? new FileLockImpl(this, position, size, shared) - : null); - } - finally - { - end(completed); - } - } - - /** Try to acquire a lock at the given position and size. - * On success return true. - * If wait as specified, block until we can get it. - * Otherwise return false. - */ - private boolean lock(long position, long size, - boolean shared, boolean wait) throws IOException - { - return fh.lock(); - } - - public FileLock lock (long position, long size, boolean shared) - throws IOException - { - if (position < 0 - || size < 0) - throw new IllegalArgumentException (); - - if (!isOpen ()) - throw new ClosedChannelException (); - - boolean completed = false; - - try - { - boolean lockable = lock(position, size, shared, true); - completed = true; - return (lockable - ? new FileLockImpl(this, position, size, shared) - : null); - } - finally - { - end(completed); - } - } - - public long position () - throws IOException - { - if (!isOpen ()) - throw new ClosedChannelException (); - - return implPosition (); - } - - public FileChannel position (long newPosition) - throws IOException - { - if (newPosition < 0) - throw new IllegalArgumentException (); - - if (!isOpen ()) - throw new ClosedChannelException (); - - // FIXME note semantics if seeking beyond eof. - // We should seek lazily - only on a write. - seek (newPosition); - return this; - } - - public FileChannel truncate (long size) - throws IOException - { - if (size < 0) - throw new IllegalArgumentException (); - - if (!isOpen ()) - throw new ClosedChannelException (); - - if ((mode & WRITE) == 0) - throw new NonWritableChannelException (); - - if (size < size ()) - implTruncate (size); - - return this; - } -} This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <hag...@us...> - 2006-12-14 09:54:09
|
Revision: 2911 http://jnode.svn.sourceforge.net/jnode/?rev=2911&view=rev Author: hagar-wize Date: 2006-12-14 01:54:07 -0800 (Thu, 14 Dec 2006) Log Message: ----------- Classpath patches Modified Paths: -------------- trunk/core/src/classpath/java/java/io/FileDescriptor.java Modified: trunk/core/src/classpath/java/java/io/FileDescriptor.java =================================================================== --- trunk/core/src/classpath/java/java/io/FileDescriptor.java 2006-12-14 09:34:50 UTC (rev 2910) +++ trunk/core/src/classpath/java/java/io/FileDescriptor.java 2006-12-14 09:54:07 UTC (rev 2911) @@ -39,7 +39,7 @@ package java.io; -import gnu.java.nio.channels.FileChannelImpl; +import gnu.java.nio.FileChannelImpl; import java.nio.channels.ByteChannel; import java.nio.channels.FileChannel; This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <hag...@us...> - 2006-12-14 09:34:52
|
Revision: 2910 http://jnode.svn.sourceforge.net/jnode/?rev=2910&view=rev Author: hagar-wize Date: 2006-12-14 01:34:50 -0800 (Thu, 14 Dec 2006) Log Message: ----------- Classpath patches Added Paths: ----------- trunk/core/src/classpath/gnu/gnu/java/nio/FileChannelImpl.java Added: trunk/core/src/classpath/gnu/gnu/java/nio/FileChannelImpl.java =================================================================== --- trunk/core/src/classpath/gnu/gnu/java/nio/FileChannelImpl.java (rev 0) +++ trunk/core/src/classpath/gnu/gnu/java/nio/FileChannelImpl.java 2006-12-14 09:34:50 UTC (rev 2910) @@ -0,0 +1,572 @@ +/* FileChannelImpl.java -- + Copyright (C) 2002, 2004, 2005, 2006 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 gnu.java.nio; + +import gnu.classpath.Configuration; +import gnu.java.nio.FileLockImpl; +import gnu.java.nio.VMChannel; + +import java.io.File; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.nio.ByteBuffer; +import java.nio.MappedByteBuffer; +import java.nio.channels.ClosedChannelException; +import java.nio.channels.FileChannel; +import java.nio.channels.FileLock; +import java.nio.channels.NonReadableChannelException; +import java.nio.channels.NonWritableChannelException; +import java.nio.channels.ReadableByteChannel; +import java.nio.channels.WritableByteChannel; + +/** + * This file is not user visible ! + * But alas, Java does not have a concept of friendly packages + * so this class is public. + * Instances of this class are created by invoking getChannel + * Upon a Input/Output/RandomAccessFile object. + */ +public final class FileChannelImpl extends FileChannel +{ + // These are mode values for open(). + public static final int READ = 1; + public static final int WRITE = 2; + public static final int APPEND = 4; + + // EXCL is used only when making a temp file. + public static final int EXCL = 8; + public static final int SYNC = 16; + public static final int DSYNC = 32; + + public static final FileChannelImpl in; + public static final FileChannelImpl out; + public static final FileChannelImpl err; + + //private static native void init(); + + static + { + if (Configuration.INIT_LOAD_LIBRARY) + { + System.loadLibrary("javanio"); + } + + //init(); + + FileChannelImpl ch = null; + try + { + ch = new FileChannelImpl(VMChannel.getStdin(), READ); + } + catch (IOException ioe) + { + throw new Error(ioe); + } + in = ch; + + ch = null; + try + { + ch = new FileChannelImpl(VMChannel.getStdout(), WRITE); + } + catch (IOException ioe) + { + throw new Error(ioe); + } + out = ch; + + ch = null; + try + { + ch = new FileChannelImpl(VMChannel.getStderr(), WRITE); + } + catch (IOException ioe) + { + throw new Error(ioe); + } + err = ch; + } + + /** + * This is the actual native file descriptor value + */ + private VMChannel ch; + + private int mode; + + final String description; + + /* Open a file. MODE is a combination of the above mode flags. */ + /* This is a static factory method, so that VM implementors can decide + * substitute subclasses of FileChannelImpl. */ + public static FileChannelImpl create(File file, int mode) + throws IOException + { + return new FileChannelImpl(file, mode); + } + + private FileChannelImpl(File file, int mode) + throws IOException + { + String path = file.getPath(); + description = path; + this.mode = mode; + this.ch = new VMChannel(); + ch.openFile(path, mode); + + // First open the file and then check if it is a a directory + // to avoid race condition. + if (file.isDirectory()) + { + try + { + close(); + } + catch (IOException e) + { + /* ignore it */ + } + + throw new FileNotFoundException(description + " is a directory"); + } + } + + /** + * Constructor for default channels in, out and err. + * + * Used by init() (native code). + * + * @param fd the file descriptor (0, 1, 2 for stdin, stdout, stderr). + * + * @param mode READ or WRITE + */ + FileChannelImpl (VMChannel ch, int mode) + { + this.mode = mode; + this.description = "descriptor(" + ch.getState() + ")"; + this.ch = ch; + } + + public int available() throws IOException + { + return ch.available(); + } + + private long implPosition() throws IOException + { + return ch.position(); + } + + private void seek(long newPosition) throws IOException + { + ch.seek(newPosition); + } + + private void implTruncate(long size) throws IOException + { + ch.truncate(size); + } + + public void unlock(long pos, long len) throws IOException + { + ch.unlock(pos, len); + } + + public long size () throws IOException + { + return ch.size(); + } + + protected void implCloseChannel() throws IOException + { + ch.close(); + } + + /** + * Makes sure the Channel is properly closed. + */ + protected void finalize() throws IOException + { + if (ch.getState().isValid()) + close(); + } + + public int read (ByteBuffer dst) throws IOException + { + return ch.read(dst); + } + + public int read (ByteBuffer dst, long position) + throws IOException + { + if (position < 0) + throw new IllegalArgumentException ("position: " + position); + long oldPosition = implPosition (); + position (position); + int result = read(dst); + position (oldPosition); + + return result; + } + + public int read() throws IOException + { + return ch.read(); + } + + public long read (ByteBuffer[] dsts, int offset, int length) + throws IOException + { + return ch.readScattering(dsts, offset, length); + } + + public int write (ByteBuffer src) throws IOException + { + return ch.write(src); + } + + public int write (ByteBuffer src, long position) + throws IOException + { + if (position < 0) + throw new IllegalArgumentException ("position: " + position); + + if (!isOpen ()) + throw new ClosedChannelException (); + + if ((mode & WRITE) == 0) + throw new NonWritableChannelException (); + + int result; + long oldPosition; + + oldPosition = implPosition (); + seek (position); + result = write(src); + seek (oldPosition); + + return result; + } + + public void write (int b) throws IOException + { + ch.write(b); + } + + public long write(ByteBuffer[] srcs, int offset, int length) + throws IOException + { + return ch.writeGathering(srcs, offset, length); + } + + public MappedByteBuffer map (FileChannel.MapMode mode, + long position, long size) + throws IOException + { + char nmode = 0; + if (mode == MapMode.READ_ONLY) + { + nmode = 'r'; + if ((this.mode & READ) == 0) + throw new NonReadableChannelException(); + } + else if (mode == MapMode.READ_WRITE || mode == MapMode.PRIVATE) + { + nmode = mode == MapMode.READ_WRITE ? '+' : 'c'; + if ((this.mode & WRITE) != WRITE) + throw new NonWritableChannelException(); + if ((this.mode & READ) != READ) + throw new NonReadableChannelException(); + } + else + throw new IllegalArgumentException ("mode: " + mode); + + if (position < 0 || size < 0 || size > Integer.MAX_VALUE) + throw new IllegalArgumentException ("position: " + position + + ", size: " + size); + return ch.map(nmode, position, (int) size); + } + + /** + * msync with the disk + */ + public void force (boolean metaData) throws IOException + { + if (!isOpen ()) + throw new ClosedChannelException (); + + ch.flush(metaData); + } + + // like transferTo, but with a count of less than 2Gbytes + private int smallTransferTo (long position, int count, + WritableByteChannel target) + throws IOException + { + ByteBuffer buffer; + try + { + // Try to use a mapped buffer if we can. If this fails for + // any reason we'll fall back to using a ByteBuffer. + buffer = map (MapMode.READ_ONLY, position, count); + } + catch (IOException e) + { + buffer = ByteBuffer.allocate (count); + read (buffer, position); + buffer.flip(); + } + + return target.write (buffer); + } + + public long transferTo (long position, long count, + WritableByteChannel target) + throws IOException + { + if (position < 0 + || count < 0) + throw new IllegalArgumentException ("position: " + position + + ", count: " + count); + + if (!isOpen ()) + throw new ClosedChannelException (); + + if ((mode & READ) == 0) + throw new NonReadableChannelException (); + + final int pageSize = 65536; + long total = 0; + + while (count > 0) + { + int transferred + = smallTransferTo (position, (int)Math.min (count, pageSize), + target); + if (transferred < 0) + break; + total += transferred; + position += transferred; + count -= transferred; + } + + return total; + } + + // like transferFrom, but with a count of less than 2Gbytes + private int smallTransferFrom (ReadableByteChannel src, long position, + int count) + throws IOException + { + ByteBuffer buffer = null; + + if (src instanceof FileChannel) + { + try + { + // Try to use a mapped buffer if we can. If this fails + // for any reason we'll fall back to using a ByteBuffer. + buffer = ((FileChannel)src).map (MapMode.READ_ONLY, position, + count); + } + catch (IOException e) + { + } + } + + if (buffer == null) + { + buffer = ByteBuffer.allocate ((int) count); + src.read (buffer); + buffer.flip(); + } + + return write (buffer, position); + } + + public long transferFrom (ReadableByteChannel src, long position, + long count) + throws IOException + { + if (position < 0 + || count < 0) + throw new IllegalArgumentException ("position: " + position + + ", count: " + count); + + if (!isOpen ()) + throw new ClosedChannelException (); + + if ((mode & WRITE) == 0) + throw new NonWritableChannelException (); + + final int pageSize = 65536; + long total = 0; + + while (count > 0) + { + int transferred = smallTransferFrom (src, position, + (int)Math.min (count, pageSize)); + if (transferred < 0) + break; + total += transferred; + position += transferred; + count -= transferred; + } + + return total; + } + + // Shared sanity checks between lock and tryLock methods. + private void lockCheck(long position, long size, boolean shared) + throws IOException + { + if (position < 0 + || size < 0) + throw new IllegalArgumentException ("position: " + position + + ", size: " + size); + + if (!isOpen ()) + throw new ClosedChannelException(); + + if (shared && ((mode & READ) == 0)) + throw new NonReadableChannelException(); + + if (!shared && ((mode & WRITE) == 0)) + throw new NonWritableChannelException(); + } + + public FileLock tryLock (long position, long size, boolean shared) + throws IOException + { + lockCheck(position, size, shared); + + boolean completed = false; + try + { + begin(); + boolean lockable = ch.lock(position, size, shared, false); + completed = true; + return (lockable + ? new FileLockImpl(this, position, size, shared) + : null); + } + finally + { + end(completed); + } + } + + public FileLock lock (long position, long size, boolean shared) + throws IOException + { + lockCheck(position, size, shared); + + boolean completed = false; + try + { + boolean lockable = ch.lock(position, size, shared, true); + completed = true; + return (lockable + ? new FileLockImpl(this, position, size, shared) + : null); + } + finally + { + end(completed); + } + } + + public long position () + throws IOException + { + if (!isOpen ()) + throw new ClosedChannelException (); + + return implPosition (); + } + + public FileChannel position (long newPosition) + throws IOException + { + if (newPosition < 0) + throw new IllegalArgumentException ("newPosition: " + newPosition); + + if (!isOpen ()) + throw new ClosedChannelException (); + + // FIXME note semantics if seeking beyond eof. + // We should seek lazily - only on a write. + seek (newPosition); + return this; + } + + public FileChannel truncate (long size) + throws IOException + { + if (size < 0) + throw new IllegalArgumentException ("size: " + size); + + if (!isOpen ()) + throw new ClosedChannelException (); + + if ((mode & WRITE) == 0) + throw new NonWritableChannelException (); + + if (size < size ()) + implTruncate (size); + + return this; + } + + public String toString() + { + return (super.toString() + + "[ fd: " + ch.getState() + + "; mode: " + Integer.toOctalString(mode) + + "; " + description + " ]"); + } + + /** + * @return The native file descriptor. + * / + public int getNativeFD() + { + return fd; + }*/ +} This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <hag...@us...> - 2006-12-14 09:30:35
|
Revision: 2909 http://jnode.svn.sourceforge.net/jnode/?rev=2909&view=rev Author: hagar-wize Date: 2006-12-14 01:30:34 -0800 (Thu, 14 Dec 2006) Log Message: ----------- Classpath patches Modified Paths: -------------- trunk/core/src/classpath/gnu/gnu/java/nio/SocketChannelSelectionKey.java trunk/core/src/classpath/gnu/gnu/java/nio/SocketChannelSelectionKeyImpl.java Modified: trunk/core/src/classpath/gnu/gnu/java/nio/SocketChannelSelectionKey.java =================================================================== --- trunk/core/src/classpath/gnu/gnu/java/nio/SocketChannelSelectionKey.java 2006-12-14 09:29:10 UTC (rev 2908) +++ trunk/core/src/classpath/gnu/gnu/java/nio/SocketChannelSelectionKey.java 2006-12-14 09:30:34 UTC (rev 2909) @@ -38,6 +38,7 @@ package gnu.java.nio; +import java.io.IOException; import java.nio.channels.spi.AbstractSelectableChannel; public final class SocketChannelSelectionKey @@ -49,10 +50,16 @@ super (channel, selector); } + // FIXME don't use file descriptor integers public int getNativeFD() { - NIOSocket socket = - (NIOSocket) ((SocketChannelImpl) ch).socket(); - return socket.getPlainSocketImpl().getNativeFD(); + try + { + return ((SocketChannelImpl) ch).getVMChannel().getState().getNativeFD(); + } + catch (IOException ioe) + { + throw new IllegalStateException(ioe); + } } } Modified: trunk/core/src/classpath/gnu/gnu/java/nio/SocketChannelSelectionKeyImpl.java =================================================================== --- trunk/core/src/classpath/gnu/gnu/java/nio/SocketChannelSelectionKeyImpl.java 2006-12-14 09:29:10 UTC (rev 2908) +++ trunk/core/src/classpath/gnu/gnu/java/nio/SocketChannelSelectionKeyImpl.java 2006-12-14 09:30:34 UTC (rev 2909) @@ -1,69 +1,78 @@ -/* SocketChannelSelectionKey.java -- Selection key for Socket Channel - Copyright (C) 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 gnu.java.nio; - - -/** - * @author Michael Barker <mi...@mi...> - * - */ -public class SocketChannelSelectionKeyImpl extends SelectionKeyImpl -{ - - SocketChannelImpl ch; - - /** - * @param ch - * @param impl - */ - public SocketChannelSelectionKeyImpl(SocketChannelImpl ch, SelectorImpl impl) - { - super(ch, impl); - this.ch = (SocketChannelImpl) ch; - } - - /** - * Returns the native file/socket descriptor as an int. - */ - public int getNativeFD() - { - return ch.getPlainSocketImpl().getNativeFD(); - } - -} +/* SocketChannelSelectionKey.java -- Selection key for Socket Channel + Copyright (C) 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 gnu.java.nio; + +import java.io.IOException; + + +/** + * @author Michael Barker <mi...@mi...> + * + */ +public class SocketChannelSelectionKeyImpl extends SelectionKeyImpl +{ + + SocketChannelImpl ch; + + /** + * @param ch + * @param impl + */ + public SocketChannelSelectionKeyImpl(SocketChannelImpl ch, SelectorImpl impl) + { + super(ch, impl); + this.ch = (SocketChannelImpl) ch; + } + + /** + * Returns the native file/socket descriptor as an int. + */ + public int getNativeFD() + { + try + { + return ch.getVMChannel().getState().getNativeFD(); + } + catch (IOException ioe) + { + return 0; // FIXME + } + } + +} This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <hag...@us...> - 2006-12-14 09:29:11
|
Revision: 2908 http://jnode.svn.sourceforge.net/jnode/?rev=2908&view=rev Author: hagar-wize Date: 2006-12-14 01:29:10 -0800 (Thu, 14 Dec 2006) Log Message: ----------- Classpath patches Modified Paths: -------------- trunk/core/src/classpath/gnu/gnu/java/nio/PipeImpl.java trunk/core/src/classpath/gnu/gnu/java/nio/SelectionKeyImpl.java trunk/core/src/classpath/gnu/gnu/java/nio/SelectorImpl.java trunk/core/src/classpath/gnu/gnu/java/nio/SelectorProviderImpl.java trunk/core/src/classpath/gnu/gnu/java/nio/ServerSocketChannelImpl.java trunk/core/src/classpath/gnu/gnu/java/nio/ServerSocketChannelSelectionKey.java Added Paths: ----------- trunk/core/src/classpath/gnu/gnu/java/nio/VMChannelOwner.java Modified: trunk/core/src/classpath/gnu/gnu/java/nio/PipeImpl.java =================================================================== --- trunk/core/src/classpath/gnu/gnu/java/nio/PipeImpl.java 2006-12-14 09:24:37 UTC (rev 2907) +++ trunk/core/src/classpath/gnu/gnu/java/nio/PipeImpl.java 2006-12-14 09:29:10 UTC (rev 2908) @@ -37,6 +37,7 @@ package gnu.java.nio; + import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.Pipe; @@ -45,38 +46,39 @@ class PipeImpl extends Pipe { public static final class SourceChannelImpl extends Pipe.SourceChannel + implements VMChannelOwner { - private int native_fd; + private VMChannel vmch; public SourceChannelImpl (SelectorProvider selectorProvider, - int native_fd) + VMChannel channel) { super (selectorProvider); - this.native_fd = native_fd; + vmch = channel; } protected final void implCloseSelectableChannel() throws IOException { - throw new Error ("Not implemented"); + vmch.close(); } protected void implConfigureBlocking (boolean blocking) throws IOException { - throw new Error ("Not implemented"); + vmch.setBlocking(blocking); } public final int read (ByteBuffer src) throws IOException { - throw new Error ("Not implemented"); + return vmch.read(src); } public final long read (ByteBuffer[] srcs) throws IOException { - return read (srcs, 0, srcs.length); + return vmch.readScattering(srcs, 0, srcs.length); } public final synchronized long read (ByteBuffer[] srcs, int offset, @@ -89,54 +91,49 @@ || len > srcs.length - offset) throw new IndexOutOfBoundsException(); - long bytesRead = 0; - - for (int index = 0; index < len; index++) - bytesRead += read (srcs [offset + index]); - - return bytesRead; - + return vmch.readScattering(srcs, offset, len); } - public final int getNativeFD() + public VMChannel getVMChannel() { - return native_fd; + return vmch; } } public static final class SinkChannelImpl extends Pipe.SinkChannel + implements VMChannelOwner { - private int native_fd; + private VMChannel vmch; public SinkChannelImpl (SelectorProvider selectorProvider, - int native_fd) + VMChannel channel) { super (selectorProvider); - this.native_fd = native_fd; + vmch = channel; } protected final void implCloseSelectableChannel() throws IOException { - throw new Error ("Not implemented"); + vmch.close(); } protected final void implConfigureBlocking (boolean blocking) throws IOException { - throw new Error ("Not implemented"); + vmch.setBlocking(blocking); } public final int write (ByteBuffer dst) throws IOException { - throw new Error ("Not implemented"); + return vmch.write(dst); } public final long write (ByteBuffer[] srcs) throws IOException { - return write (srcs, 0, srcs.length); + return vmch.writeGathering(srcs, 0, srcs.length); } public final synchronized long write (ByteBuffer[] srcs, int offset, int len) @@ -148,17 +145,12 @@ || len > srcs.length - offset) throw new IndexOutOfBoundsException(); - long bytesWritten = 0; - - for (int index = 0; index < len; index++) - bytesWritten += write (srcs [offset + index]); - - return bytesWritten; + return vmch.writeGathering(srcs, offset, len); } - public final int getNativeFD() + public VMChannel getVMChannel() { - return native_fd; + return vmch; } } @@ -169,7 +161,9 @@ throws IOException { super(); - VMPipe.init (this, provider); + VMChannel[] pipe = VMPipe.pipe(); + sink = new SinkChannelImpl(provider, pipe[0]); + source = new SourceChannelImpl(provider, pipe[1]); } public Pipe.SinkChannel sink() Modified: trunk/core/src/classpath/gnu/gnu/java/nio/SelectionKeyImpl.java =================================================================== --- trunk/core/src/classpath/gnu/gnu/java/nio/SelectionKeyImpl.java 2006-12-14 09:24:37 UTC (rev 2907) +++ trunk/core/src/classpath/gnu/gnu/java/nio/SelectionKeyImpl.java 2006-12-14 09:29:10 UTC (rev 2908) @@ -1,5 +1,5 @@ /* SelectionKeyImpl.java -- - Copyright (C) 2002, 2003 Free Software Foundation, Inc. + Copyright (C) 2002, 2003, 2006 Free Software Foundation, Inc. This file is part of GNU Classpath. @@ -47,8 +47,8 @@ { private int readyOps; private int interestOps; - private SelectorImpl impl; - SelectableChannel ch; + private final SelectorImpl impl; + final SelectableChannel ch; public SelectionKeyImpl (SelectableChannel ch, SelectorImpl impl) { @@ -61,7 +61,7 @@ return ch; } - public int readyOps () + public synchronized int readyOps () { if (!isValid()) throw new CancelledKeyException(); @@ -69,7 +69,7 @@ return readyOps; } - public SelectionKey readyOps (int ops) + public synchronized SelectionKey readyOps (int ops) { if (!isValid()) throw new CancelledKeyException(); @@ -83,15 +83,21 @@ if (!isValid()) throw new CancelledKeyException(); - return interestOps; + synchronized (impl.selectedKeys()) + { + return interestOps; } + } public SelectionKey interestOps (int ops) { if (!isValid()) throw new CancelledKeyException(); + synchronized (impl.selectedKeys()) + { interestOps = ops; + } return this; } @@ -100,5 +106,6 @@ return impl; } + /* @deprecated */ public abstract int getNativeFD(); } Modified: trunk/core/src/classpath/gnu/gnu/java/nio/SelectorImpl.java =================================================================== --- trunk/core/src/classpath/gnu/gnu/java/nio/SelectorImpl.java 2006-12-14 09:24:37 UTC (rev 2907) +++ trunk/core/src/classpath/gnu/gnu/java/nio/SelectorImpl.java 2006-12-14 09:29:10 UTC (rev 2908) @@ -54,8 +54,8 @@ public class SelectorImpl extends AbstractSelector { - private Set keys; - private Set selected; + private Set<SelectionKey> keys; + private Set<SelectionKey> selected; /** * A dummy object whose monitor regulates access to both our @@ -83,8 +83,8 @@ { super (provider); - keys = new HashSet (); - selected = new HashSet (); + keys = new HashSet<SelectionKey> (); + selected = new HashSet<SelectionKey> (); } protected void finalize() throws Throwable @@ -110,7 +110,7 @@ } } - public final Set keys() + public final Set<SelectionKey> keys() { if (!isOpen()) throw new ClosedSelectorException(); @@ -136,7 +136,7 @@ { int[] result; int counter = 0; - Iterator it = keys.iterator (); + Iterator<SelectionKey> it = keys.iterator (); // Count the number of file descriptors needed while (it.hasNext ()) @@ -253,7 +253,7 @@ selectThread = null; } - Iterator it = keys.iterator (); + Iterator<SelectionKey> it = keys.iterator (); while (it.hasNext ()) { @@ -317,7 +317,7 @@ } } - public final Set selectedKeys() + public final Set<SelectionKey> selectedKeys() { if (!isOpen()) throw new ClosedSelectorException(); @@ -350,10 +350,10 @@ private final void deregisterCancelledKeys() { - Set ckeys = cancelledKeys (); + Set<SelectionKey> ckeys = cancelledKeys (); synchronized (ckeys) { - Iterator it = ckeys.iterator(); + Iterator<SelectionKey> it = ckeys.iterator(); while (it.hasNext ()) { Modified: trunk/core/src/classpath/gnu/gnu/java/nio/SelectorProviderImpl.java =================================================================== --- trunk/core/src/classpath/gnu/gnu/java/nio/SelectorProviderImpl.java 2006-12-14 09:24:37 UTC (rev 2907) +++ trunk/core/src/classpath/gnu/gnu/java/nio/SelectorProviderImpl.java 2006-12-14 09:29:10 UTC (rev 2908) @@ -37,6 +37,9 @@ package gnu.java.nio; + +import gnu.classpath.SystemProperties; + import java.io.IOException; import java.nio.channels.DatagramChannel; import java.nio.channels.Pipe; @@ -47,6 +50,11 @@ public class SelectorProviderImpl extends SelectorProvider { + private static final String SELECTOR_IMPL_KQUEUE = "kqueue"; + private static final String SELECTOR_IMPL_EPOLL = "epoll"; + private static final String SELECTOR_IMPL = "gnu.java.nio.selectorImpl"; + private static boolean epoll_failed = false; + public SelectorProviderImpl () { } @@ -66,6 +74,35 @@ public AbstractSelector openSelector () throws IOException { + String selectorImpl = "default"; + if (KqueueSelectorImpl.kqueue_supported()) + selectorImpl = SELECTOR_IMPL_KQUEUE; + if (EpollSelectorImpl.epoll_supported() && !epoll_failed) + selectorImpl = SELECTOR_IMPL_EPOLL; + selectorImpl = SystemProperties.getProperty(SELECTOR_IMPL, selectorImpl); + + if (selectorImpl.equals(SELECTOR_IMPL_KQUEUE)) + return new KqueueSelectorImpl(this); + + if (selectorImpl.equals(SELECTOR_IMPL_EPOLL)) + { + // We jump through these hoops because even though epoll may look + // like it's available (sys/epoll.h exists, and you can link against + // all the epoll functions) it may not be available in the kernel + // (especially 2.4 kernels), meaning you will get ENOSYS at run time. + // + // Madness! + try + { + return new EpollSelectorImpl(this); + } + catch (InternalError e) + { + // epoll_create throws this on ENOSYS. + epoll_failed = true; + } + } + return new SelectorImpl (this); } Modified: trunk/core/src/classpath/gnu/gnu/java/nio/ServerSocketChannelImpl.java =================================================================== --- trunk/core/src/classpath/gnu/gnu/java/nio/ServerSocketChannelImpl.java 2006-12-14 09:24:37 UTC (rev 2907) +++ trunk/core/src/classpath/gnu/gnu/java/nio/ServerSocketChannelImpl.java 2006-12-14 09:29:10 UTC (rev 2908) @@ -48,7 +48,9 @@ import java.nio.channels.spi.SelectorProvider; public final class ServerSocketChannelImpl extends ServerSocketChannel + implements VMChannelOwner { + private VMChannel channel; private NIOServerSocket serverSocket; private boolean connected; @@ -56,13 +58,15 @@ throws IOException { super (provider); - serverSocket = new NIOServerSocket (this); + serverSocket = new NIOServerSocket(this); + channel = serverSocket.getPlainSocketImpl().getVMChannel(); configureBlocking(true); - } + } + // XXX do we need this? public void finalizer() { - if (connected) + if (channel.getState().isValid()) { try { @@ -70,20 +74,20 @@ } catch (Exception e) { - } - } - } + } + } + } protected void implCloseSelectableChannel () throws IOException { - connected = false; - serverSocket.close(); - } + connected = false; + channel.close(); + } protected void implConfigureBlocking (boolean blocking) throws IOException { - serverSocket.setSoTimeout (blocking ? 0 : NIOConstants.DEFAULT_TIMEOUT); - } + channel.setBlocking(blocking); + } public SocketChannel accept () throws IOException { @@ -98,27 +102,28 @@ try { begin(); - serverSocket.getPlainSocketImpl().setInChannelOperation(true); - // indicate that a channel is initiating the accept operation - // so that the socket ignores the fact that we might be in - // non-blocking mode. - NIOSocket socket = (NIOSocket) serverSocket.accept(); - completed = true; - return socket.getChannel(); + VMChannel client = channel.accept(); + if (client == null) + return null; + else + { + completed = true; + return new SocketChannelImpl(provider(), client, false); + } } - catch (SocketTimeoutException e) - { - return null; - } finally { - serverSocket.getPlainSocketImpl().setInChannelOperation(false); end (completed); } - } + } - public ServerSocket socket () + public ServerSocket socket() { return serverSocket; - } + } + + public VMChannel getVMChannel() + { + return channel; + } } Modified: trunk/core/src/classpath/gnu/gnu/java/nio/ServerSocketChannelSelectionKey.java =================================================================== --- trunk/core/src/classpath/gnu/gnu/java/nio/ServerSocketChannelSelectionKey.java 2006-12-14 09:24:37 UTC (rev 2907) +++ trunk/core/src/classpath/gnu/gnu/java/nio/ServerSocketChannelSelectionKey.java 2006-12-14 09:29:10 UTC (rev 2908) @@ -38,6 +38,7 @@ package gnu.java.nio; +import java.io.IOException; import java.nio.channels.spi.AbstractSelectableChannel; public final class ServerSocketChannelSelectionKey @@ -49,10 +50,16 @@ super (channel, selector); } + // FIXME don't use file descriptor integers public int getNativeFD() { - NIOServerSocket socket = - (NIOServerSocket) ((ServerSocketChannelImpl) ch).socket(); - return socket.getPlainSocketImpl().getNativeFD(); + try + { + return ((ServerSocketChannelImpl) ch).getVMChannel().getState().getNativeFD(); + } + catch (IOException ioe) + { + throw new IllegalStateException(ioe); + } } } Added: trunk/core/src/classpath/gnu/gnu/java/nio/VMChannelOwner.java =================================================================== --- trunk/core/src/classpath/gnu/gnu/java/nio/VMChannelOwner.java (rev 0) +++ trunk/core/src/classpath/gnu/gnu/java/nio/VMChannelOwner.java 2006-12-14 09:29:10 UTC (rev 2908) @@ -0,0 +1,57 @@ +/* NativeFD.java -- interface for Channels that have an underlying file descriptor. + Copyright (C) 2006 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 gnu.java.nio; + +/** + * This interface is meant to be implemented by any {@link Channel} + * implementation we support that uses a platform-specific {@link VMChannel} + * at their core. This is primarily used by {@link Selector} implementations, + * for easier access to the native state. + * + * @author Casey Marshall (cs...@gn...) + */ +interface VMChannelOwner +{ + /** + * Return the underlying platform-specific Channel instance. + * + * @return The platform channel object. + */ + VMChannel getVMChannel(); +} This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <hag...@us...> - 2006-12-14 09:24:38
|
Revision: 2907 http://jnode.svn.sourceforge.net/jnode/?rev=2907&view=rev Author: hagar-wize Date: 2006-12-14 01:24:37 -0800 (Thu, 14 Dec 2006) Log Message: ----------- Classpath patches Modified Paths: -------------- trunk/core/src/classpath/gnu/gnu/java/nio/DatagramChannelImpl.java trunk/core/src/classpath/gnu/gnu/java/nio/DatagramChannelSelectionKey.java trunk/core/src/classpath/gnu/gnu/java/nio/FileLockImpl.java trunk/core/src/classpath/gnu/gnu/java/nio/NIOSocket.java Added Paths: ----------- trunk/core/src/classpath/gnu/gnu/java/nio/EpollSelectionKeyImpl.java trunk/core/src/classpath/gnu/gnu/java/nio/EpollSelectorImpl.java trunk/core/src/classpath/gnu/gnu/java/nio/KqueueSelectionKeyImpl.java trunk/core/src/classpath/gnu/gnu/java/nio/KqueueSelectorImpl.java trunk/core/src/classpath/gnu/gnu/java/nio/NIOSocketImpl.java Modified: trunk/core/src/classpath/gnu/gnu/java/nio/DatagramChannelImpl.java =================================================================== --- trunk/core/src/classpath/gnu/gnu/java/nio/DatagramChannelImpl.java 2006-12-13 19:25:39 UTC (rev 2906) +++ trunk/core/src/classpath/gnu/gnu/java/nio/DatagramChannelImpl.java 2006-12-14 09:24:37 UTC (rev 2907) @@ -55,8 +55,10 @@ * @author Michael Koch */ public final class DatagramChannelImpl extends DatagramChannel + implements VMChannelOwner { private NIODatagramSocket socket; + private VMChannel channel; /** * Indicates whether this channel initiated whatever operation @@ -64,6 +66,16 @@ */ private boolean inChannelOperation; + protected DatagramChannelImpl (SelectorProvider provider) + throws IOException + { + super (provider); + socket = new NIODatagramSocket (new PlainDatagramSocketImpl(), this); + channel = new VMChannel(); + channel.initSocket(false); + configureBlocking(true); + } + /** * Indicates whether our datagram socket should ignore whether * we are set to non-blocking mode. Certain operations on our @@ -85,14 +97,6 @@ inChannelOperation = b; } - protected DatagramChannelImpl (SelectorProvider provider) - throws IOException - { - super (provider); - socket = new NIODatagramSocket (new PlainDatagramSocketImpl(), this); - configureBlocking(true); - } - public DatagramSocket socket () { return socket; @@ -101,13 +105,13 @@ protected void implCloseSelectableChannel () throws IOException { - socket.close (); + channel.close(); } protected void implConfigureBlocking (boolean blocking) throws IOException { - socket.setSoTimeout (blocking ? 0 : NIOConstants.DEFAULT_TIMEOUT); + channel.setBlocking(blocking); } public DatagramChannel connect (SocketAddress remote) @@ -116,29 +120,43 @@ if (!isOpen()) throw new ClosedChannelException(); - socket.connect (remote); + try + { + channel.connect((InetSocketAddress) remote, 0); + } + catch (ClassCastException cce) + { + throw new IOException("unsupported socked address type"); + } return this; } public DatagramChannel disconnect () throws IOException { - socket.disconnect (); + channel.disconnect(); return this; } - public boolean isConnected () + public boolean isConnected() { - return socket.isConnected (); + try + { + return channel.getPeerAddress() != null; + } + catch (IOException ioe) + { + return false; + } } - + public int write (ByteBuffer src) throws IOException { if (!isConnected ()) throw new NotYetConnectedException (); - return send (src, socket.getRemoteSocketAddress()); + return channel.write(src); } public long write (ByteBuffer[] srcs, int offset, int length) @@ -152,13 +170,11 @@ || (length < 0) || (length > (srcs.length - offset))) throw new IndexOutOfBoundsException(); - - long result = 0; - for (int index = offset; index < offset + length; index++) - result += write (srcs [index]); - - return result; + /* We are connected, meaning we will write these bytes to + * the host we connected to, so we don't need to explicitly + * give the host. */ + return channel.writeGathering(srcs, offset, length); } public int read (ByteBuffer dst) @@ -167,9 +183,7 @@ if (!isConnected ()) throw new NotYetConnectedException (); - int remaining = dst.remaining(); - receive (dst); - return remaining - dst.remaining(); + return channel.read(dst); } public long read (ByteBuffer[] dsts, int offset, int length) @@ -184,12 +198,8 @@ || (length > (dsts.length - offset))) throw new IndexOutOfBoundsException(); - long result = 0; - - for (int index = offset; index < offset + length; index++) - result += read (dsts [index]); - - return result; + /* Likewise, see the comment int write above. */ + return channel.readScattering(dsts, offset, length); } public SocketAddress receive (ByteBuffer dst) @@ -200,51 +210,14 @@ try { - DatagramPacket packet; - int len = dst.remaining(); - - if (dst.hasArray()) - { - packet = new DatagramPacket (dst.array(), - dst.arrayOffset() + dst.position(), - len); - } - else - { - packet = new DatagramPacket (new byte [len], len); - } - - boolean completed = false; - - try - { - begin(); - setInChannelOperation(true); - socket.receive (packet); - completed = true; - } - finally - { - end (completed); - setInChannelOperation(false); - } - - if (!dst.hasArray()) - { - dst.put (packet.getData(), packet.getOffset(), packet.getLength()); - } - else - { - dst.position (dst.position() + packet.getLength()); - } - - return packet.getSocketAddress(); + begin(); + return channel.receive(dst); } - catch (SocketTimeoutException e) - { - return null; + finally + { + end(true); + } } - } public int send (ByteBuffer src, SocketAddress target) throws IOException @@ -252,46 +225,18 @@ if (!isOpen()) throw new ClosedChannelException(); - if (target instanceof InetSocketAddress - && ((InetSocketAddress) target).isUnresolved()) + if (!(target instanceof InetSocketAddress)) + throw new IOException("can only send to inet socket addresses"); + + InetSocketAddress dst = (InetSocketAddress) target; + if (dst.isUnresolved()) throw new IOException("Target address not resolved"); - byte[] buffer; - int offset = 0; - int len = src.remaining(); - - if (src.hasArray()) - { - buffer = src.array(); - offset = src.arrayOffset() + src.position(); - } - else - { - buffer = new byte [len]; - src.get (buffer); + return channel.send(src, dst); } - - DatagramPacket packet = new DatagramPacket (buffer, offset, len, target); - - boolean completed = false; - try + + public VMChannel getVMChannel() { - begin(); - setInChannelOperation(true); - socket.send(packet); - completed = true; - } - finally - { - end (completed); - setInChannelOperation(false); - } - - if (src.hasArray()) - { - src.position (src.position() + len); - } - - return len; + return channel; } } Modified: trunk/core/src/classpath/gnu/gnu/java/nio/DatagramChannelSelectionKey.java =================================================================== --- trunk/core/src/classpath/gnu/gnu/java/nio/DatagramChannelSelectionKey.java 2006-12-13 19:25:39 UTC (rev 2906) +++ trunk/core/src/classpath/gnu/gnu/java/nio/DatagramChannelSelectionKey.java 2006-12-14 09:24:37 UTC (rev 2907) @@ -38,6 +38,7 @@ package gnu.java.nio; +import java.io.IOException; import java.nio.channels.spi.AbstractSelectableChannel; /** @@ -52,10 +53,16 @@ super (channel, selector); } + // FIXME don't use file descriptor integers public int getNativeFD() { - NIODatagramSocket socket = - (NIODatagramSocket) ((DatagramChannelImpl) ch).socket(); - return socket.getPlainDatagramSocketImpl().getNativeFD(); + try + { + return ((DatagramChannelImpl) ch).getVMChannel().getState().getNativeFD(); + } + catch (IOException ioe) + { + throw new IllegalStateException(ioe); + } } } Added: trunk/core/src/classpath/gnu/gnu/java/nio/EpollSelectionKeyImpl.java =================================================================== --- trunk/core/src/classpath/gnu/gnu/java/nio/EpollSelectionKeyImpl.java (rev 0) +++ trunk/core/src/classpath/gnu/gnu/java/nio/EpollSelectionKeyImpl.java 2006-12-14 09:24:37 UTC (rev 2907) @@ -0,0 +1,122 @@ +/* EpollSelectionKeyImpl.java -- selection key for the epoll selector. + Copyright (C) 2006 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 gnu.java.nio; + +import java.io.IOException; +import java.nio.channels.CancelledKeyException; +import java.nio.channels.SelectableChannel; +import java.nio.channels.SelectionKey; +import java.nio.channels.Selector; +import java.nio.channels.spi.AbstractSelectionKey; + +/** + * @author Casey Marshall (cs...@gn...) + */ +public class EpollSelectionKeyImpl extends AbstractSelectionKey +{ + final int fd; + private final EpollSelectorImpl selector; + private final SelectableChannel channel; + int interestOps; + int selectedOps; + int key; + boolean valid; + boolean cancelled; + + EpollSelectionKeyImpl(EpollSelectorImpl selector, + SelectableChannel channel, int fd) + { + this.selector = selector; + this.channel = channel; + this.fd = fd; + } + + /* (non-Javadoc) + * @see java.nio.channels.SelectionKey#channel() + */ + public SelectableChannel channel() + { + return channel; + } + + /* (non-Javadoc) + * @see java.nio.channels.SelectionKey#interestOps() + */ + public int interestOps() + { + return interestOps; + } + + /* (non-Javadoc) + * @see java.nio.channels.SelectionKey#interestOps(int) + */ + public SelectionKey interestOps(int ops) + { + if (cancelled) + throw new CancelledKeyException(); + if ((ops & ~(channel.validOps())) != 0) + throw new IllegalArgumentException("unsupported channel ops"); + try + { + selector.epoll_modify(this, ops); + interestOps = ops; + } + catch (IOException ioe) + { + throw new IllegalArgumentException(ioe); + } + return this; + } + + /* (non-Javadoc) + * @see java.nio.channels.SelectionKey#readyOps() + */ + public int readyOps() + { + return selectedOps; + } + + /* (non-Javadoc) + * @see java.nio.channels.SelectionKey#selector() + */ + public Selector selector() + { + return selector; + } +} Added: trunk/core/src/classpath/gnu/gnu/java/nio/EpollSelectorImpl.java =================================================================== --- trunk/core/src/classpath/gnu/gnu/java/nio/EpollSelectorImpl.java (rev 0) +++ trunk/core/src/classpath/gnu/gnu/java/nio/EpollSelectorImpl.java 2006-12-14 09:24:37 UTC (rev 2907) @@ -0,0 +1,399 @@ +/* EpollSelectorImpl.java -- selector implementation using epoll + Copyright (C) 2006 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 gnu.java.nio; + +import gnu.classpath.Configuration; + +import java.io.IOException; +import java.nio.ByteBuffer; +import java.nio.channels.SelectableChannel; +import java.nio.channels.SelectionKey; +import java.nio.channels.Selector; +import java.nio.channels.spi.AbstractSelectableChannel; +import java.nio.channels.spi.AbstractSelector; +import java.nio.channels.spi.SelectorProvider; +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Iterator; +import java.util.Set; + +/** + * An implementation of {@link Selector} that uses the epoll event + * notification mechanism on GNU/Linux. + * + * @author Casey Marshall (cs...@gn...) + */ +public class EpollSelectorImpl extends AbstractSelector +{ + // XXX is this reasonable? Does it matter? + private static final int DEFAULT_EPOLL_SIZE = 128; + private static final int sizeof_struct_epoll_event; + + private static final int OP_ACCEPT = SelectionKey.OP_ACCEPT; + private static final int OP_CONNECT = SelectionKey.OP_CONNECT; + private static final int OP_READ = SelectionKey.OP_READ; + private static final int OP_WRITE = SelectionKey.OP_WRITE; + + /** our epoll file descriptor. */ + private int epoll_fd; + + private final HashMap keys; + private Set selectedKeys; + private Thread waitingThread; + private ByteBuffer events; + + private static final int INITIAL_CAPACITY; + private static final int MAX_DOUBLING_CAPACITY; + private static final int CAPACITY_INCREMENT; + + static + { + if (Configuration.INIT_LOAD_LIBRARY) + System.loadLibrary("javanio"); + + if (epoll_supported()) + sizeof_struct_epoll_event = sizeof_struct(); + else + sizeof_struct_epoll_event = -1; + + INITIAL_CAPACITY = 64 * sizeof_struct_epoll_event; + MAX_DOUBLING_CAPACITY = 1024 * sizeof_struct_epoll_event; + CAPACITY_INCREMENT = 128 * sizeof_struct_epoll_event; + } + + public EpollSelectorImpl(SelectorProvider provider) + throws IOException + { + super(provider); + epoll_fd = epoll_create(DEFAULT_EPOLL_SIZE); + keys = new HashMap(); + selectedKeys = null; + events = ByteBuffer.allocateDirect(INITIAL_CAPACITY); + } + + /* (non-Javadoc) + * @see java.nio.channels.Selector#keys() + */ + public Set keys() + { + return new HashSet(keys.values()); + } + + /* (non-Javadoc) + * @see java.nio.channels.Selector#select() + */ + public int select() throws IOException + { + return doSelect(-1); + } + + /* (non-Javadoc) + * @see java.nio.channels.Selector#select(long) + */ + public int select(long timeout) throws IOException + { + if (timeout > Integer.MAX_VALUE) + throw new IllegalArgumentException("timeout is too large"); + if (timeout < 0) + throw new IllegalArgumentException("invalid timeout"); + return doSelect((int) timeout); + } + + private int doSelect(int timeout) throws IOException + { + synchronized (keys) + { + Set cancelledKeys = cancelledKeys(); + synchronized (cancelledKeys) + { + for (Iterator it = cancelledKeys.iterator(); it.hasNext(); ) + { + EpollSelectionKeyImpl key = (EpollSelectionKeyImpl) it.next(); + epoll_delete(epoll_fd, key.fd); + key.valid = false; + keys.remove(Integer.valueOf(key.fd)); + it.remove(); + deregister(key); + } + + // Clear out closed channels. The fds are removed from the epoll + // fd when closed, so there is no need to remove them manually. + for (Iterator it = keys.values().iterator(); it.hasNext(); ) + { + EpollSelectionKeyImpl key = (EpollSelectionKeyImpl) it.next(); + SelectableChannel ch = key.channel(); + if (ch instanceof VMChannelOwner) + { + if (!((VMChannelOwner) ch).getVMChannel().getState().isValid()) + it.remove(); + } + } + + // Don't bother if we have nothing to select. + if (keys.isEmpty()) + return 0; + + int ret; + try + { + begin(); + waitingThread = Thread.currentThread(); + ret = epoll_wait(epoll_fd, events, keys.size(), timeout); + } + finally + { + Thread.interrupted(); + waitingThread = null; + end(); + } + + HashSet s = new HashSet(ret); + for (int i = 0; i < ret; i++) + { + events.position(i * sizeof_struct_epoll_event); + ByteBuffer b = events.slice(); + int fd = selected_fd(b); + EpollSelectionKeyImpl key + = (EpollSelectionKeyImpl) keys.get(Integer.valueOf(fd)); + if (key == null) + throw new IOException("fd was selected, but no key found"); + key.selectedOps = selected_ops(b) & key.interestOps; + s.add(key); + } + + reallocateBuffer(); + + selectedKeys = s; + return ret; + } + } + } + + /* (non-Javadoc) + * @see java.nio.channels.Selector#selectedKeys() + */ + public Set selectedKeys() + { + if (selectedKeys == null) + return Collections.EMPTY_SET; + return selectedKeys; + } + + /* (non-Javadoc) + * @see java.nio.channels.Selector#selectNow() + */ + public int selectNow() throws IOException + { + return doSelect(0); + } + + /* (non-Javadoc) + * @see java.nio.channels.Selector#wakeup() + */ + public Selector wakeup() + { + try + { + waitingThread.interrupt(); + } + catch (NullPointerException npe) + { + // Ignored, thrown if we are not in a blocking op. + } + return this; + } + + /* (non-Javadoc) + * @see java.nio.channels.spi.AbstractSelector#implCloseSelector() + */ + protected void implCloseSelector() throws IOException + { + VMChannel.close(epoll_fd); + } + + /* (non-Javadoc) + * @see java.nio.channels.spi.AbstractSelector#register(java.nio.channels.spi.AbstractSelectableChannel, int, java.lang.Object) + */ + protected SelectionKey register(AbstractSelectableChannel ch, int ops, Object att) + { + if (!(ch instanceof VMChannelOwner)) + throw new IllegalArgumentException("unsupported channel type"); + + VMChannel channel = ((VMChannelOwner) ch).getVMChannel(); + try + { + int native_fd = channel.getState().getNativeFD(); + synchronized (keys) + { + if (keys.containsKey(Integer.valueOf(native_fd))) + throw new IllegalArgumentException("channel already registered"); + EpollSelectionKeyImpl result = + new EpollSelectionKeyImpl(this, ch, native_fd); + if ((ops & ~(ch.validOps())) != 0) + throw new IllegalArgumentException("invalid ops for channel"); + result.interestOps = ops; + result.selectedOps = 0; + result.valid = true; + result.attach(att); + result.key = System.identityHashCode(result); + epoll_add(epoll_fd, result.fd, ops); + keys.put(Integer.valueOf(native_fd), result); + reallocateBuffer(); + return result; + } + } + catch (IOException ioe) + { + throw new IllegalArgumentException(ioe); + } + } + + private void reallocateBuffer() + { + // Ensure we have enough space for all potential events that may be + // returned. + if (events.capacity() < keys.size() * sizeof_struct_epoll_event) + { + int cap = events.capacity(); + if (cap < MAX_DOUBLING_CAPACITY) + cap <<= 1; + else + cap += CAPACITY_INCREMENT; + events = ByteBuffer.allocateDirect(cap); + } + // Ensure that the events buffer is not too large, given the number of + // events registered. + else if (events.capacity() > keys.size() * sizeof_struct_epoll_event * 2 + 1 + && events.capacity() > INITIAL_CAPACITY) + { + int cap = events.capacity() >>> 1; + events = ByteBuffer.allocateDirect(cap); + } + } + + void epoll_modify(EpollSelectionKeyImpl key, int ops) throws IOException + { + epoll_modify(epoll_fd, key.fd, ops); + } + + /** + * Tell if epoll is supported by this system, and support was compiled in. + * + * @return True if this system supports event notification with epoll. + */ + public static native boolean epoll_supported(); + + + /** + * Returns the size of `struct epoll_event'. + * + * @return The size of `struct epoll_event'. + */ + private static native int sizeof_struct(); + + + /** + * Open a new epoll file descriptor. + * + * @param size The size hint for the new epoll descriptor. + * @return The new file descriptor integer. + * @throws IOException If allocating a new epoll descriptor fails. + */ + private static native int epoll_create(int size) throws IOException; + + /** + * Add a file descriptor to this selector. + * + * @param efd The epoll file descriptor. + * @param fd The file descriptor to add (or modify). + * @param ops The interest opts. + */ + private static native void epoll_add(int efd, int fd, int ops) + throws IOException; + + /** + * Modify the interest ops of the key selecting for the given FD. + * + * @param efd The epoll file descriptor. + * @param fd The file descriptor to modify. + * @param ops The ops. + * @throws IOException + */ + private static native void epoll_modify(int efd, int fd, int ops) + throws IOException; + + /** + * Remove a file descriptor from this selector. + * + * @param efd The epoll file descriptor. + * @param fd The file descriptor. + * @throws IOException + */ + private static native void epoll_delete(int efd, int fd) throws IOException; + + /** + * Select events. + * + * @param efd The epoll file descriptor. + * @param state The buffer to hold selected events. + * @param n The number of events that may be put in `state'. + * @param timeout The timeout. + * @return The number of events selected. + * @throws IOException + */ + private static native int epoll_wait(int efd, ByteBuffer state, int n, int timeout) + throws IOException; + + /** + * Fetch the fd value from a selected struct epoll_event. + * + * @param struct The direct buffer holding the struct. + * @return The fd value. + */ + private static native int selected_fd(ByteBuffer struct); + + /** + * Fetch the enabled operations from a selected struct epoll_event. + * + * @param struct The direct buffer holding the struct. + * @return The selected operations. + */ + private static native int selected_ops(ByteBuffer struct); +} Modified: trunk/core/src/classpath/gnu/gnu/java/nio/FileLockImpl.java =================================================================== --- trunk/core/src/classpath/gnu/gnu/java/nio/FileLockImpl.java 2006-12-13 19:25:39 UTC (rev 2906) +++ trunk/core/src/classpath/gnu/gnu/java/nio/FileLockImpl.java 2006-12-14 09:24:37 UTC (rev 2907) @@ -38,8 +38,6 @@ package gnu.java.nio; -import gnu.java.nio.channels.FileChannelImpl; - import java.io.IOException; import java.nio.channels.FileLock; Added: trunk/core/src/classpath/gnu/gnu/java/nio/KqueueSelectionKeyImpl.java =================================================================== --- trunk/core/src/classpath/gnu/gnu/java/nio/KqueueSelectionKeyImpl.java (rev 0) +++ trunk/core/src/classpath/gnu/gnu/java/nio/KqueueSelectionKeyImpl.java 2006-12-14 09:24:37 UTC (rev 2907) @@ -0,0 +1,189 @@ +/* KqueueSelectionKeyImpl.java -- selection key for kqueue/kevent. + Copyright (C) 2006 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 gnu.java.nio; + + +import java.io.IOException; +import java.nio.ByteBuffer; +import java.nio.channels.SelectableChannel; +import java.nio.channels.SelectionKey; +import java.nio.channels.Selector; +import java.nio.channels.spi.AbstractSelectionKey; + +/** + * @author Casey Marshall (cs...@gn...) + */ +public class KqueueSelectionKeyImpl extends AbstractSelectionKey +{ + int interestOps; + int readyOps; + int activeOps = 0; + int key; + int fd; + + /** The selector we were created for. */ + private final KqueueSelectorImpl selector; + + /** The channel we are attached to. */ + private final SelectableChannel channel; + + private final VMChannelOwner natChannel; + + public KqueueSelectionKeyImpl(KqueueSelectorImpl selector, + SelectableChannel channel) + { + this.selector = selector; + this.channel = channel; + natChannel = (VMChannelOwner) channel; + interestOps = 0; + readyOps = 0; + } + + /* (non-Javadoc) + * @see java.nio.channels.SelectionKey#channel() + */ + //@Override + public SelectableChannel channel() + { + return channel; + } + + /* (non-Javadoc) + * @see java.nio.channels.SelectionKey#interestOps() + */ + //@Override + public int interestOps() + { + return interestOps; + } + + /* (non-Javadoc) + * @see java.nio.channels.SelectionKey#interestOps(int) + */ + //@Override + public SelectionKey interestOps(int ops) + { + if (!isValid()) + throw new IllegalStateException("key is invalid"); + if ((ops & ~channel.validOps()) != 0) + throw new IllegalArgumentException("channel does not support all operations"); + + selector.setInterestOps(this, ops); + return this; + } + + /* (non-Javadoc) + * @see java.nio.channels.SelectionKey#readyOps() + */ + //@Override + public int readyOps() + { + return readyOps; + } + + /* (non-Javadoc) + * @see java.nio.channels.SelectionKey#selector() + */ + //@Override + public Selector selector() + { + return selector; + } + + public String toString() + { + if (!isValid()) + return super.toString() + " [ fd: " + fd + " <<invalid>> ]"; + return super.toString() + " [ fd: " + fd + " interest ops: {" + + ((interestOps & OP_ACCEPT) != 0 ? " OP_ACCEPT" : "") + + ((interestOps & OP_CONNECT) != 0 ? " OP_CONNECT" : "") + + ((interestOps & OP_READ) != 0 ? " OP_READ" : "") + + ((interestOps & OP_WRITE) != 0 ? " OP_WRITE" : "") + + " }; ready ops: {" + + ((readyOps & OP_ACCEPT) != 0 ? " OP_ACCEPT" : "") + + ((readyOps & OP_CONNECT) != 0 ? " OP_CONNECT" : "") + + ((readyOps & OP_READ) != 0 ? " OP_READ" : "") + + ((readyOps & OP_WRITE) != 0 ? " OP_WRITE" : "") + + " } ]"; + } + + public int hashCode() + { + return fd; + } + + public boolean equals(Object o) + { + if (!(o instanceof KqueueSelectionKeyImpl)) + return false; + KqueueSelectionKeyImpl that = (KqueueSelectionKeyImpl) o; + return that.fd == this.fd && that.channel.equals(this.channel); + } + + + boolean isReadActive() + { + return (activeOps & (OP_READ | OP_ACCEPT)) != 0; + } + + boolean isReadInterested() + { + return (interestOps & (OP_READ | OP_ACCEPT)) != 0; + } + + boolean isWriteActive() + { + return (activeOps & (OP_WRITE | OP_CONNECT)) != 0; + } + + boolean isWriteInterested() + { + return (interestOps & (OP_WRITE | OP_CONNECT)) != 0; + } + + boolean needCommitRead() + { + return isReadActive() == (!isReadInterested()); + } + + boolean needCommitWrite() + { + return isWriteActive() == (!isWriteInterested()); + } +} Added: trunk/core/src/classpath/gnu/gnu/java/nio/KqueueSelectorImpl.java =================================================================== --- trunk/core/src/classpath/gnu/gnu/java/nio/KqueueSelectorImpl.java (rev 0) +++ trunk/core/src/classpath/gnu/gnu/java/nio/KqueueSelectorImpl.java 2006-12-14 09:24:37 UTC (rev 2907) @@ -0,0 +1,527 @@ +/* KqueueSelectorImpl.java -- Selector for systems with kqueue event notification. + Copyright (C) 2006 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 gnu.java.nio; + + +import java.io.IOException; +import java.nio.ByteBuffer; +import java.nio.ByteOrder; +import java.nio.channels.ClosedSelectorException; +import java.nio.channels.SelectableChannel; +import java.nio.channels.SelectionKey; +import java.nio.channels.Selector; +import java.nio.channels.spi.AbstractSelectableChannel; +import java.nio.channels.spi.AbstractSelector; +import java.nio.channels.spi.SelectorProvider; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Iterator; +import java.util.Map; +import java.util.Set; + +/** + * A {@link Selector} implementation that uses the <code>kqueue</code> + * event notification facility. + * + * @author Casey Marshall (cs...@gn...) + */ +public class KqueueSelectorImpl extends AbstractSelector +{ + // Prepended underscore to field name to make it distinct + // from the method with the similar name. + private static final int _sizeof_struct_kevent; + + private static final int MAX_DOUBLING_CAPACITY = 16384; + private static final int CAP_INCREMENT = 1024; + private static final int INITIAL_CAPACITY; + + static + { + try + { + System.loadLibrary("javanio"); + } + catch (Exception x) + { + x.printStackTrace(); + } + + if (kqueue_supported ()) + _sizeof_struct_kevent = sizeof_struct_kevent(); + else + _sizeof_struct_kevent = -1; + INITIAL_CAPACITY = 16 * _sizeof_struct_kevent; + } + + /** + * Tell if kqueue-based selectors are supported on this system. + * + * @return True if this system has kqueue support, and support for it was + * compiled in to Classpath. + */ + public static native boolean kqueue_supported(); + + /* Our native file descriptor. */ + private int kq; + + private HashMap/*<Integer,KqueueSelectionKeyImpl>*/ keys; + private HashSet/*<KqueueSelectionKeyImpl>*/ selected; + private Thread blockedThread; + private ByteBuffer events; + + private static final int OP_ACCEPT = SelectionKey.OP_ACCEPT; + private static final int OP_CONNECT = SelectionKey.OP_CONNECT; + private static final int OP_READ = SelectionKey.OP_READ; + private static final int OP_WRITE = SelectionKey.OP_WRITE; + + public KqueueSelectorImpl(SelectorProvider provider) throws IOException + { + super(provider); + kq = implOpen(); + keys = new HashMap/*<KqueueSelectionKeyImpl>*/(); + events = ByteBuffer.allocateDirect(INITIAL_CAPACITY); + } + + protected void implCloseSelector() throws IOException + { + implClose(kq); + kq = -1; + } + + /* (non-Javadoc) + * @see java.nio.channels.Selector#keys() + */ + public Set keys() + { + if (!isOpen()) + throw new ClosedSelectorException(); + + return new HashSet(keys.values()); + } + + /* (non-Javadoc) + * @see java.nio.channels.Selector#select() + */ + public int select() throws IOException + { + return doSelect(-1); + } + + /* (non-Javadoc) + * @see java.nio.channels.Selector#select(long) + */ + public int select(long timeout) throws IOException + { + if (timeout == 0) + timeout = -1; + return doSelect(timeout); + } + + /* (non-Javadoc) + * @see java.nio.channels.Selector#selectedKeys() + */ + public Set selectedKeys() + { + if (!isOpen()) + throw new ClosedSelectorException(); + + return selected; + } + + /* (non-Javadoc) + * @see java.nio.channels.Selector#selectNow() + */ + public int selectNow() throws IOException + { + return doSelect(0); + } + + /* (non-Javadoc) + * @see java.nio.channels.Selector#wakeup() + */ + public Selector wakeup() + { + if (blockedThread != null) + blockedThread.interrupt(); + return this; + } + + public String toString() + { + return super.toString() + " [ fd: " + kq + " ]"; + } + + public boolean equals(Object o) + { + if (!(o instanceof KqueueSelectorImpl)) + return false; + + return ((KqueueSelectorImpl) o).kq == kq; + } + + int doSelect(long timeout) throws IOException + { + Set cancelled = cancelledKeys(); + synchronized (cancelled) + { + synchronized (keys) + { + for (Iterator it = cancelled.iterator(); it.hasNext(); ) + { + KqueueSelectionKeyImpl key = (KqueueSelectionKeyImpl) it.next(); + key.interestOps = 0; + } + + int events_size = (2 * _sizeof_struct_kevent) * keys.size(); + int num_events = 0; + + for (Iterator it = keys.entrySet().iterator(); it.hasNext(); ) + { + Map.Entry e = (Map.Entry) it.next(); + KqueueSelectionKeyImpl key = (KqueueSelectionKeyImpl) e.getValue(); + + SelectableChannel ch = key.channel(); + if (ch instanceof VMChannelOwner) + { + if (!((VMChannelOwner) ch).getVMChannel().getState().isValid()) + { + // closed channel; removed from kqueue automatically. + it.remove(); + continue; + } + } + + // If this key is registering a read filter, add it to the buffer. + if (key.needCommitRead()) + { + kevent_set(events, num_events, key.fd, + key.interestOps & (OP_READ | OP_ACCEPT), + key.activeOps & (OP_READ | OP_ACCEPT), key.key); + num_events++; + } + + // If this key is registering a write filter, add it to the buffer. + if (key.needCommitWrite()) + { + kevent_set(events, num_events, key.fd, + key.interestOps & (OP_WRITE | OP_CONNECT), + key.activeOps & (OP_WRITE | OP_CONNECT), key.key); + num_events++; + } + } + events.rewind().limit(events.capacity()); + + //System.out.println("dump of keys to select:"); + //dump_selection_keys(events.duplicate()); + + int n = 0; + try + { + //System.out.println("[" + kq + "] kevent enter selecting from " + keys.size()); + begin(); + blockedThread = Thread.currentThread(); + if (blockedThread.isInterrupted()) + timeout = 0; + n = kevent(kq, events, num_events, + events.capacity() / _sizeof_struct_kevent, timeout); + } + finally + { + end(); + blockedThread = null; + Thread.interrupted(); + //System.out.println("[" + kq + "kevent exit selected " + n); + } + + //System.out.println("dump of keys selected:"); + //dump_selection_keys((ByteBuffer) events.duplicate().limit(n * _sizeof_struct_kevent)); + + // Commit the operations we've just added in the call to kevent. + for (Iterator it = keys.values().iterator(); it.hasNext(); ) + { + KqueueSelectionKeyImpl key = (KqueueSelectionKeyImpl) it.next(); + key.activeOps = key.interestOps; + } + + selected = new HashSet/*<KqueueSelectionKeyImpl>*/(n); + int x = 0; + for (int i = 0; i < n; i++) + { + events.position(x).limit(x + _sizeof_struct_kevent); + x += _sizeof_struct_kevent; + int y = fetch_key(events.slice()); + KqueueSelectionKeyImpl key = + (KqueueSelectionKeyImpl) keys.get(new Integer(y)); + + if (key == null) + { + System.out.println("WARNING! no key found for selected key " + y); + continue; + } + // Keys that have been cancelled may be returned here; don't + // add them to the selected set. + if (!key.isValid()) + continue; + key.readyOps = ready_ops(events.slice(), key.interestOps); + selected.add(key); + } + + // Finally, remove the cancelled keys. + for (Iterator it = cancelled.iterator(); it.hasNext(); ) + { + KqueueSelectionKeyImpl key = (KqueueSelectionKeyImpl) it.next(); + keys.remove(new Integer(key.key)); + deregister(key); + it.remove(); + } + + reallocateBuffer(); + + return selected.size(); + } + } + } + + protected SelectionKey register(AbstractSelectableChannel channel, + int interestOps, + Object attachment) + { + int native_fd = -1; + try + { + if (channel instanceof VMChannelOwner) + native_fd = ((VMChannelOwner) channel).getVMChannel() + .getState().getNativeFD(); + else + throw new IllegalArgumentException("cannot handle channel type " + + channel.getClass().getName()); + } + catch (IOException ioe) + { + throw new IllegalArgumentException("channel is closed or invalid"); + } + + KqueueSelectionKeyImpl result = new KqueueSelectionKeyImpl(this, channel); + result.interestOps = interestOps; + result.attach(attachment); + result.fd = native_fd; + result.key = System.identityHashCode(result); + synchronized (keys) + { + while (keys.containsKey(new Integer(result.key))) + result.key++; + keys.put(new Integer(result.key), result); + reallocateBuffer(); + } + return result; + } + + void setInterestOps(KqueueSelectionKeyImpl key, int ops) + { + synchronized (keys) + { + key.interestOps = ops; + } + } + + /** + * Reallocate the events buffer. This is the destination buffer for + * events returned by kevent. This method will: + * + * * Grow the buffer if there is insufficent space for all registered + * events. + * * Shrink the buffer if it is more than twice the size needed. + * + */ + private void reallocateBuffer() + { + synchronized (keys) + { + if (events.capacity() < (2 * _sizeof_struct_kevent) * keys.size()) + { + int cap = events.capacity(); + if (cap >= MAX_DOUBLING_CAPACITY) + cap += CAP_INCREMENT; + else + cap = cap << 1; + + events = ByteBuffer.allocateDirect(cap); + } + else if (events.capacity() > 4 * (_sizeof_struct_kevent) * keys.size() + 1 + && events.capacity() > INITIAL_CAPACITY) + { + int cap = events.capacity(); + cap = cap >>> 1; + events = ByteBuffer.allocateDirect(cap); + } + } + } + + //synchronized void updateOps(KqueueSelectionKeyImpl key, int interestOps) + //{ + // updateOps(key, interestOps, 0, false); + //} + + /*void updateOps(KqueueSelectionKeyImpl key, int interestOps, + int activeOps, int fd) + { + //System.out.println(">> updating kqueue selection key:"); + //dump_selection_keys(key.nstate.duplicate()); + //System.out.println("<<"); + synchronized (keys) + { + kevent_set(key.nstate, fd, interestOps, activeOps, key.key); + } + //System.out.println(">> updated kqueue selection key:"); + //dump_selection_keys(key.nstate.duplicate()); + //System.out.println("<<"); + }*/ + + private void dump_selection_keys(ByteBuffer keys) + { + // WARNING! This method is not guaranteed to be portable! This works + // on darwin/x86, but the sizeof and offsetof these fields may be + // different on other platforms! + int i = 0; + keys.order(ByteOrder.nativeOrder()); + while (keys.hasRemaining()) + { + System.out.println("struct kevent { ident: " + + Integer.toString(keys.getInt()) + + " filter: " + + Integer.toHexString(keys.getShort() & 0xFFFF) + + " flags: " + + Integer.toHexString(keys.getShort() & 0xFFFF) + + " fflags: " + + Integer.toHexString(keys.getInt()) + + " data: " + + Integer.toHexString(keys.getInt()) + + " udata: " + + Integer.toHexString(keys.getInt()) + + " }"); + } + } + + /** + * Return the size of a <code>struct kevent</code> on this system. + * + * @return The size of <code>struct kevent</code>. + */ + private static native int sizeof_struct_kevent(); + + /** + * Opens a kqueue descriptor. + * + * @return The new kqueue descriptor. + * @throws IOException If opening fails. + */ + private static native int implOpen() throws IOException; + + /** + * Closes the kqueue file descriptor. + * + * @param kq The kqueue file descriptor. + * @throws IOException + */ + private static native void implClose(int kq) throws IOException; + + /** + * Initialize the specified native state for the given interest ops. + * + * @param nstate The native state structures; in this buffer should be + * the <code>struct kevent</code>s created for a key. + * @param fd The file descriptor. If 0, the native FD is unmodified. + * @param interestOps The operations to enable. + * @param key A unique key that will reference the associated key later. + * @param delete Set to true if this event should be deleted from the + * kqueue (if false, this event is added/updated). + */ + private static native void kevent_set(ByteBuffer nstate, int i, int fd, + int interestOps, int activeOps, int key); + + /** + * Poll for events. The source events are stored in <code>events</code>, + * which is also where polled events will be placed. + * + * @param events The events to poll. This buffer is also the destination + * for events read from the queue. + * @param nevents The number of events to poll (that is, the number of + * events in the <code>events</code> buffer). + * @param nout The maximum number of events that may be returned. + * @param timeout The timeout. A timeout of -1 returns immediately; a timeout + * of 0 waits indefinitely. + * @return The number of events read. + */ + private static native int kevent(int kq, ByteBuffer events, int nevents, + int nout, long timeout); + + /** + * Fetch a polled key from a native state buffer. For each kevent key we + * create, we put the native state info (one or more <code>struct + * kevent</code>s) in that key's {@link KqueueSelectionKeyImpl#nstate} + * buffer, and place the pointer of the key in the <code>udata</code> field + * of that structure. This method fetches that pointer from the given + * buffer (assumed to be a <code>struct kqueue</code>) and returns it. + * + * @param nstate The buffer containing the <code>struct kqueue</code> to read. + * @return The key object. + */ + private static native int fetch_key(ByteBuffer nstate); + + /** + * Fetch the ready ops of the associated native state. That is, this + * inspects the first argument as a <code>struct kevent</code>, looking + * at its operation (the input is assumed to have been returned via a + * previous call to <code>kevent</code>), and translating that to the + * appropriate Java bit set, based on the second argument. + * + * @param nstate The native state. + * @param interestOps The enabled operations for the key. + * @return The bit set representing the ready operations. + */ + private static native int ready_ops(ByteBuffer nstate, int interestOps); + + /** + * Check if kevent returned EV_EOF for a selection key. + * + * @param nstate The native state. + * @return True if the kevent call returned EOF. + */ + private static native boolean check_eof(ByteBuffer nstate); +} Modified: trunk/core/src/classpath/gnu/gnu/java/nio/NIOSocket.java =================================================================== --- trunk/core/src/classpath/gnu/gnu/java/nio/NIOSocket.java 2006-12-13 19:25:39 UTC (rev 2906) +++ trunk/core/src/classpath/gnu/gnu/java/nio/NIOSocket.java 2006-12-14 09:24:37 UTC (rev 2907) @@ -48,30 +48,33 @@ */ public final class NIOSocket extends Socket { - private PlainSocketImpl impl; private SocketChannelImpl channel; - protected NIOSocket (PlainSocketImpl impl, SocketChannelImpl channel) + protected NIOSocket (SocketChannelImpl channel) throws IOException { - super (impl); - this.impl = impl; + super (new NIOSocketImpl(channel)); this.channel = channel; } - public final PlainSocketImpl getPlainSocketImpl() - { - return impl; - } + //public final PlainSocketImpl getPlainSocketImpl() + //{ + // return impl; + //} - final void setChannel (SocketChannelImpl channel) - { - this.impl = channel.getPlainSocketImpl(); - this.channel = channel; - } + //final void setChannel (SocketChannelImpl channel) + //{ + // this.impl = channel.getPlainSocketImpl(); + // this.channel = channel; + //} public final SocketChannel getChannel() { return channel; } + + public boolean isConnected() + { + return channel.isConnected(); + } } Added: trunk/core/src/classpath/gnu/gnu/java/nio/NIOSocketImpl.java =================================================================== --- trunk/core/src/classpath/gnu/gnu/java/nio/NIOSocketImpl.java (rev 0) +++ trunk/core/src/classpath/gnu/gnu/java/nio/NIOSocketImpl.java 2006-12-14 09:24:37 UTC (rev 2907) @@ -0,0 +1,110 @@ +/* NIOSocketImpl.java -- subclass of PlainSocketImpl for NIO. + Copyright (C) 2006 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 gnu.java.nio; + +import gnu.java.net.PlainSocketImpl; + +import java.io.IOException; +import java.net.InetAddress; + +/** + * @author Casey Marshall (cs...@gn...) + */ +public class NIOSocketImpl extends PlainSocketImpl +{ + + private final SocketChannelImpl channel; + + NIOSocketImpl(SocketChannelImpl channel) throws IOException + { + this.channel = channel; + impl.getState().setChannelFD(channel.getVMChannel().getState()); + } + + /* (non-Javadoc) + * @see java.net.SocketImpl#getInetAddress() + */ + //@Override + protected InetAddress getInetAddress() + { + try + { + return channel.getVMChannel().getPeerAddress().getAddress(); + } + catch (IOException ioe) + { + return null; + } + catch (NullPointerException npe) + { + // Socket is not connected yet. + return null; + } + } + + /* (non-Javadoc) + * @see java.net.SocketImpl#getPort() + */ + //@Override + protected int getPort() + { + try + { + return channel.getVMChannel().getPeerAddress().getPort(); + } + catch (IOException ioe) + { + return -1; + } + catch (NullPointerException npe) + { + // Socket is not connected yet. + return -1; + } + } + + /* (non-Javadoc) + * @see gnu.java.net.PlainSocketImpl#create(boolean) + */ + //@Override + protected synchronized void create(boolean stream) + { + // Ignored; the socket has already been created. + } +} This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <ep...@us...> - 2006-12-13 19:25:42
|
Revision: 2906 http://jnode.svn.sourceforge.net/jnode/?rev=2906&view=rev Author: epr Date: 2006-12-13 11:25:39 -0800 (Wed, 13 Dec 2006) Log Message: ----------- Copied remotely Added Paths: ----------- branches/jikesRVM/ Copied: branches/jikesRVM (from rev 2905, trunk) This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <Qa...@us...> - 2006-12-12 22:50:00
|
Revision: 2905 http://jnode.svn.sourceforge.net/jnode/?rev=2905&view=rev Author: QaDeS Date: 2006-12-12 14:49:58 -0800 (Tue, 12 Dec 2006) Log Message: ----------- proportional font cursor fix (generic) tiny cleanups Modified Paths: -------------- trunk/distr/src/apps/org/jnode/apps/console/ShellEmu.java trunk/gui/src/driver/org/jnode/driver/console/swing/SwingTextScreenConsoleManager.java trunk/gui/src/driver/org/jnode/driver/textscreen/swing/SwingPcTextScreen.java Modified: trunk/distr/src/apps/org/jnode/apps/console/ShellEmu.java =================================================================== --- trunk/distr/src/apps/org/jnode/apps/console/ShellEmu.java 2006-12-12 22:20:48 UTC (rev 2904) +++ trunk/distr/src/apps/org/jnode/apps/console/ShellEmu.java 2006-12-12 22:49:58 UTC (rev 2905) @@ -14,7 +14,7 @@ public static void main(String[] argv) throws Exception { initEnv(); SwingTextScreenConsoleManager cm = new SwingTextScreenConsoleManager(); - new Thread(new CommandShell((TextConsole) cm.createConsole(null, + new Thread(new CommandShell((TextConsole) cm.createConsole("Console 1", ConsoleManager.CreateOptions.TEXT | ConsoleManager.CreateOptions.SCROLLABLE))). start(); } Modified: trunk/gui/src/driver/org/jnode/driver/console/swing/SwingTextScreenConsoleManager.java =================================================================== --- trunk/gui/src/driver/org/jnode/driver/console/swing/SwingTextScreenConsoleManager.java 2006-12-12 22:20:48 UTC (rev 2904) +++ trunk/gui/src/driver/org/jnode/driver/console/swing/SwingTextScreenConsoleManager.java 2006-12-12 22:49:58 UTC (rev 2905) @@ -35,6 +35,7 @@ initializeKeyboard(systemScreen.getKeyboardDevice()); addPointerDevice(systemScreen.getPointerDevivce()); frame = new JFrame("Console"); + frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.addWindowListener(new WindowAdapter(){ public void windowClosed(WindowEvent e) { closeAll(); Modified: trunk/gui/src/driver/org/jnode/driver/textscreen/swing/SwingPcTextScreen.java =================================================================== --- trunk/gui/src/driver/org/jnode/driver/textscreen/swing/SwingPcTextScreen.java 2006-12-12 22:20:48 UTC (rev 2904) +++ trunk/gui/src/driver/org/jnode/driver/textscreen/swing/SwingPcTextScreen.java 2006-12-12 22:49:58 UTC (rev 2905) @@ -15,6 +15,7 @@ import java.awt.Color; import java.awt.Dimension; import java.awt.Font; +import java.awt.FontMetrics; import java.awt.Graphics; import java.awt.KeyboardFocusManager; import java.awt.event.*; @@ -88,11 +89,11 @@ int offset = i * SCREEN_WIDTH; int lenght = SCREEN_WIDTH; if (offset <= cursorOffset && cursorOffset < offset + SCREEN_WIDTH) { - char[] line = new char[SCREEN_WIDTH]; - for (int j = 0; j < SCREEN_WIDTH; j++) { - line[j] = offset + j == cursorOffset ? '_' : ' '; - } - g.drawChars(line, 0, lenght, margin, h + i * h); + FontMetrics fm = getFontMetrics(getFont()); + int x = margin + fm.charsWidth(buffer, offset, cursorOffset - offset); + int y = h + i * h; + int width = fm.charWidth(buffer[cursorOffset]); + g.drawLine(x, y, x+width, y); } g.drawChars(buffer, offset, lenght, margin, h + i * h); This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <ls...@us...> - 2006-12-12 22:20:53
|
Revision: 2904 http://jnode.svn.sourceforge.net/jnode/?rev=2904&view=rev Author: lsantha Date: 2006-12-12 14:20:48 -0800 (Tue, 12 Dec 2006) Log Message: ----------- test env. Added Paths: ----------- trunk/distr/src/apps/org/jnode/apps/console/ShellEmu.java trunk/distr/src/apps/org/jnode/apps/editor/EditEmu.java Added: trunk/distr/src/apps/org/jnode/apps/console/ShellEmu.java =================================================================== --- trunk/distr/src/apps/org/jnode/apps/console/ShellEmu.java (rev 0) +++ trunk/distr/src/apps/org/jnode/apps/console/ShellEmu.java 2006-12-12 22:20:48 UTC (rev 2904) @@ -0,0 +1,21 @@ +package org.jnode.apps.console; + +import org.jnode.test.gui.Emu; +import org.jnode.driver.console.swing.SwingTextScreenConsoleManager; +import org.jnode.driver.console.TextConsole; +import org.jnode.driver.console.ConsoleManager; +import org.jnode.shell.CommandShell; + +/** + * @author Levente S\u00e1ntha + */ +public class ShellEmu extends Emu { + + public static void main(String[] argv) throws Exception { + initEnv(); + SwingTextScreenConsoleManager cm = new SwingTextScreenConsoleManager(); + new Thread(new CommandShell((TextConsole) cm.createConsole(null, + ConsoleManager.CreateOptions.TEXT | ConsoleManager.CreateOptions.SCROLLABLE))). + start(); + } +} Added: trunk/distr/src/apps/org/jnode/apps/editor/EditEmu.java =================================================================== --- trunk/distr/src/apps/org/jnode/apps/editor/EditEmu.java (rev 0) +++ trunk/distr/src/apps/org/jnode/apps/editor/EditEmu.java 2006-12-12 22:20:48 UTC (rev 2904) @@ -0,0 +1,31 @@ +package org.jnode.apps.editor; + +import org.jnode.driver.console.ConsoleManager; +import org.jnode.driver.console.swing.SwingTextScreenConsoleManager; +import org.jnode.driver.console.textscreen.TextScreenConsole; +import org.jnode.test.gui.Emu; + +import java.io.File; + +/** + * @author Levente S\u00e1ntha + */ +public class EditEmu extends Emu { + public static void main(String[] argv) throws Exception{ + initEnv(); + + + if(argv.length == 0){ + System.out.println("No file specified"); + return; + } + + SwingTextScreenConsoleManager cm = new SwingTextScreenConsoleManager(); + final TextScreenConsole console = cm.createConsole(null, + ConsoleManager.CreateOptions.TEXT | ConsoleManager.CreateOptions.NO_SYSTEM_OUT_ERR_IN); + + TextEditor te = new TextEditor(console); + File f = new File(argv[0]); + te.loadFile(f); + } +} This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <ls...@us...> - 2006-12-12 22:19:33
|
Revision: 2903 http://jnode.svn.sourceforge.net/jnode/?rev=2903&view=rev Author: lsantha Date: 2006-12-12 14:19:32 -0800 (Tue, 12 Dec 2006) Log Message: ----------- test env. Added Paths: ----------- trunk/gui/src/test/org/jnode/test/gui/Emu.java Added: trunk/gui/src/test/org/jnode/test/gui/Emu.java =================================================================== --- trunk/gui/src/test/org/jnode/test/gui/Emu.java (rev 0) +++ trunk/gui/src/test/org/jnode/test/gui/Emu.java 2006-12-12 22:19:32 UTC (rev 2903) @@ -0,0 +1,196 @@ +package org.jnode.test.gui; + +import org.jnode.plugin.ExtensionPoint; +import org.jnode.plugin.Extension; +import org.jnode.plugin.ExtensionPointListener; +import org.jnode.plugin.PluginDescriptor; +import org.jnode.naming.InitialNaming; +import org.jnode.naming.NameSpace; +import org.jnode.driver.DeviceManager; +import org.jnode.driver.AbstractDeviceManager; +import org.jnode.driver.DeviceFinder; +import org.jnode.driver.DeviceToDriverMapper; +import org.jnode.driver.Device; +import org.jnode.driver.DriverException; +import org.jnode.shell.alias.AliasManager; +import org.jnode.shell.alias.def.DefaultAliasManager; +import org.jnode.shell.ShellManager; +import org.jnode.shell.def.DefaultShellManager; +import org.apache.log4j.Logger; + +import javax.naming.NamingException; +import javax.naming.NameAlreadyBoundException; +import javax.naming.NameNotFoundException; +import java.util.Map; +import java.util.HashMap; +import java.util.Set; +import java.util.List; +import java.util.ArrayList; +import java.util.Collections; + +/** + * @author Levente S\u00e1ntha + */ +public class Emu { + protected static void initEnv() throws NamingException { + if(true){ + InitialNaming.setNameSpace(new NameSpace() { + private Map<Class<?>, Object> space = new HashMap<Class<?>, Object>(); + + public <T> void bind(Class<T> name, T service) throws NamingException, NameAlreadyBoundException { + if (space.get(name) != null) throw new NameAlreadyBoundException(); + space.put(name, service); + } + + public void unbind(Class<?> name) { + space.remove(name); + } + + public <T> T lookup(Class<T> name) throws NameNotFoundException { + T obj = (T) space.get(name); + if (obj == null) throw new NameNotFoundException(name.getName()); + return obj; + } + + public Set<Class<?>> nameSet() { + return space.keySet(); + } + }); + InitialNaming.bind(DeviceManager.NAME, DeviceManager.INSTANCE); + final AliasManager aliasMgr = new DefaultAliasManager(new DummyExtensionPoint()); + final ShellManager shellMgr = new DefaultShellManager(); + InitialNaming.bind(AliasManager.NAME, aliasMgr); + InitialNaming.bind(ShellManager.NAME, shellMgr); + } + } + + private static class DummyExtensionPoint implements ExtensionPoint { + public String getSimpleIdentifier() { + return "A"; + } + + public String getUniqueIdentifier() { + return "aaa"; + } + + public String getName() { + return "B"; + } + + public Extension[] getExtensions() { + return new Extension[0]; + } + + public void addListener(ExtensionPointListener listener) { + } + + public void addPriorityListener(ExtensionPointListener listener) { + } + + public void removeListener(ExtensionPointListener listener) { + } + + public PluginDescriptor getDeclaringPluginDescriptor() { + return null; + } + } + + public static class DeviceManager extends AbstractDeviceManager { + public static final Logger log = Logger.getLogger(DeviceManager.class); + + public static final DeviceManager INSTANCE = new DeviceManager(); + + private List<DeviceFinder> finders = new ArrayList<DeviceFinder>(); + + private List<DeviceToDriverMapper> mappers = new ArrayList<DeviceToDriverMapper>(); + + private DeviceManager() { + } + + public void removeAll() { + finders.clear(); + mappers.clear(); + + for (Device device : getDevices()) { + try { + unregister(device); + } catch (DriverException e) { + log.error("can't unregister " + device); + } + } + } + + public void add(DeviceFinder finder, DeviceToDriverMapper mapper) { + boolean doStart = false; + + if (!finders.contains(finder)) { + finders.add(finder); + doStart = true; + } + + if (!mappers.contains(mapper)) { + mappers.add(mapper); + doStart = true; + } + + if (doStart) { + start(); + } + } + + /** + * Start this manager + */ + final public void start() { + // Thread thread = new Thread() + // { + // public void run() + // { + log.debug("Loading extensions ..."); + loadExtensions(); + log.debug("Extensions loaded !"); + // } + // }; + // thread.start(); + + try { + // must be called before findDeviceDrivers + log.debug("findDevices ..."); + findDevices(); + + log.debug("findDeviceDrivers ..."); + findDeviceDrivers(); + + log.debug("StubDeviceManager initialized !"); + } catch (InterruptedException e) { + log.fatal("can't find devices", e); + } + } + + /** + * Refresh the list of finders, based on the mappers extension-point. + * + * @param finders + */ + protected final void refreshFinders(List<DeviceFinder> finders) { + log.info("refreshFinders"); + finders.clear(); + finders.addAll(this.finders); + } + + /** + * Refresh the list of mappers, based on the mappers extension-point. + * + * @param mappers + */ + protected final void refreshMappers(List<DeviceToDriverMapper> mappers) { + log.info("refreshMappers"); + mappers.clear(); + mappers.addAll(this.mappers); + + // Now sort them + Collections.sort(mappers, MapperComparator.INSTANCE); + } + } + +} This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <ls...@us...> - 2006-12-12 21:17:20
|
Revision: 2902 http://jnode.svn.sourceforge.net/jnode/?rev=2902&view=rev Author: lsantha Date: 2006-12-12 13:17:16 -0800 (Tue, 12 Dec 2006) Log Message: ----------- Migrating to Java 5 level classpath. Removed Paths: ------------- trunk/core/src/classpath/5.0/java/ This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <ls...@us...> - 2006-12-12 21:15:26
|
Revision: 2901 http://jnode.svn.sourceforge.net/jnode/?rev=2901&view=rev Author: lsantha Date: 2006-12-12 13:15:24 -0800 (Tue, 12 Dec 2006) Log Message: ----------- Migrating to Java 5 level classpath. Added Paths: ----------- trunk/core/src/classpath/java/java/lang/reflect/AnnotatedElement.java trunk/core/src/classpath/java/java/lang/reflect/GenericDeclaration.java trunk/core/src/classpath/java/java/lang/reflect/TypeVariable.java Added: trunk/core/src/classpath/java/java/lang/reflect/AnnotatedElement.java =================================================================== --- trunk/core/src/classpath/java/java/lang/reflect/AnnotatedElement.java (rev 0) +++ trunk/core/src/classpath/java/java/lang/reflect/AnnotatedElement.java 2006-12-12 21:15:24 UTC (rev 2901) @@ -0,0 +1,115 @@ +/* AnnotatedElement.java + Copyright (C) 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.lang.reflect; + +import java.lang.annotation.Annotation; + +/** + * <p> + * Represents an element that can be annotated. The methods of this interface + * provide reflection-based access to the annotations associated with a + * particular element, such as a class, field, method or package. Each + * annotation returned by these methods is both immutable and serializable. + * The returned arrays may be freely modified, without any effect on the + * arrays returned to future callers. + * </p> + * <p> + * If an annotation refers to a type or enumeration constant that is + * inaccessible, then a <code>TypeNotPresentException</code> or + * <code>EnumConstantNotPresentException</code> will be thrown. Likewise, + * invalid annotations will produce either a + * <code>AnnotationTypeMismatchException</code> or + * <code>IncompleteAnnotationException</code>. + * </p> + * + * @author Tom Tromey (tr...@re...) + * @author Andrew John Hughes (gnu...@me...) + * @since 1.5 + */ +public interface AnnotatedElement +{ + + /** + * Returns the element's annotation for the specified annotation type, + * or <code>null</code> if no such annotation exists. + * + * @param annotationClass the type of annotation to look for. + * @return this element's annotation for the specified type, or + * <code>null</code> if no such annotation exists. + * @throws NullPointerException if the annotation class is <code>null</code>. + */ + <T extends Annotation> T getAnnotation(Class<T> annotationClass); + + /** + * Returns all annotations associated with the element. If there are + * no annotations associated with the element, then a zero-length array + * will be returned. The returned array may be modified by the client + * code, but this will have no effect on the annotation content of the + * element, and hence no effect on the return value of this method for + * future callers. + * + * @return this element's annotations. + */ + Annotation[] getAnnotations(); + + /** + * Returns all annotations directly defined by the element. If there are + * no annotations directly associated with the element, then a zero-length + * array will be returned. The returned array may be modified by the client + * code, but this will have no effect on the annotation content of this + * class, and hence no effect on the return value of this method for + * future callers. + * + * @return the annotations directly defined by the element. + * @since 1.5 + */ + Annotation[] getDeclaredAnnotations(); + + /** + * Returns true if an annotation for the specified type is associated + * with the element. This is primarily a short-hand for using marker + * annotations. + * + * @param annotationClass the type of annotation to look for. + * @return true if an annotation exists for the specified type. + * @since 1.5 + */ + boolean isAnnotationPresent(Class<? extends Annotation> annotationClass); + +} Added: trunk/core/src/classpath/java/java/lang/reflect/GenericDeclaration.java =================================================================== --- trunk/core/src/classpath/java/java/lang/reflect/GenericDeclaration.java (rev 0) +++ trunk/core/src/classpath/java/java/lang/reflect/GenericDeclaration.java 2006-12-12 21:15:24 UTC (rev 2901) @@ -0,0 +1,62 @@ +/* GenericDeclaration.java + Copyright (C) 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.lang.reflect; + +/** + * Represents an entity that declares one or more type parameters. + * This includes classes and methods (including constructors). + * + * @author Tom Tromey (tr...@re...) + * @author Andrew John Hughes (gnu...@me...) + * @since 1.5 + */ +public interface GenericDeclaration +{ + /** + * Returns a <code>TypeVariable</code> object for each type variable + * declared by this entity, in order of declaration. An empty array + * is returned if no type variables are declared. + * + * @return an array of <code>TypeVariable</code> objects. + * @throws GenericSignatureFormatError if the signature format within the + * class file does not conform to that specified in the 3rd edition + * of the Java Virtual Machine Specification. + */ + TypeVariable<?>[] getTypeParameters(); +} Added: trunk/core/src/classpath/java/java/lang/reflect/TypeVariable.java =================================================================== --- trunk/core/src/classpath/java/java/lang/reflect/TypeVariable.java (rev 0) +++ trunk/core/src/classpath/java/java/lang/reflect/TypeVariable.java 2006-12-12 21:15:24 UTC (rev 2901) @@ -0,0 +1,96 @@ +/* TypeVariable.java + Copyright (C) 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.lang.reflect; + +/** + * <p> + * This is a common interface for all type variables provided by + * the Java language. Instances are created the first time a type + * variable is needed by one of the reflective methods declared in + * this package. + * </p> + * <p> + * Creating a type variable requires resolving the appropriate type. + * This may involve resolving other classes as a side effect (e.g. + * if the type is nested inside other classes). Creation should not + * involve resolving the bounds. Repeated creation has no effect; an + * equivalent instance is returned. Caching is not required, but all + * instances must be <code>equal()</code> to each other. + * </p> + * + * @author Tom Tromey (tr...@re...) + * @author Andrew John Hughes (gnu...@me...) + * @since 1.5 + */ +public interface TypeVariable<T extends GenericDeclaration> extends Type +{ + + /** + * Returns an array of <code>Type</code> objects which represent the upper + * bounds of this type variable. There is always a default bound of + * <code>Object</code>. Any <code>ParameterizedType</code>s will be + * created as necessary, and other types resolved. + * + * @return an array of <code>Type</code> objects representing the upper + * bounds. + * @throws TypeNotPresentException if any of the bounds refer to a + * non-existant type. + * @throws MalformedParameterizedTypeException if the creation of a + * <code>ParameterizedType</code> fails. + */ + Type[] getBounds(); + + + /** + * Returns a representation of the declaration used to declare this + * type variable. + * + * @return the <code>GenericDeclaration</code> object for this type + * variable. + */ + T getGenericDeclaration(); + + /** + * Returns the name of the type variable, as written in the source + * code. + * + * @return the name of the type variable. + */ + String getName(); +} This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <ls...@us...> - 2006-12-12 21:14:53
|
Revision: 2900 http://jnode.svn.sourceforge.net/jnode/?rev=2900&view=rev Author: lsantha Date: 2006-12-12 13:14:46 -0800 (Tue, 12 Dec 2006) Log Message: ----------- Migrating to Java 5 level classpath. Added Paths: ----------- trunk/core/src/classpath/java/java/lang/Boolean.java trunk/core/src/classpath/java/java/lang/Byte.java trunk/core/src/classpath/java/java/lang/Character.java trunk/core/src/classpath/java/java/lang/Comparable.java trunk/core/src/classpath/java/java/lang/Deprecated.java trunk/core/src/classpath/java/java/lang/Double.java trunk/core/src/classpath/java/java/lang/Enum.java trunk/core/src/classpath/java/java/lang/EnumConstantNotPresentException.java trunk/core/src/classpath/java/java/lang/Float.java trunk/core/src/classpath/java/java/lang/Integer.java trunk/core/src/classpath/java/java/lang/Iterable.java trunk/core/src/classpath/java/java/lang/Long.java trunk/core/src/classpath/java/java/lang/Object.java trunk/core/src/classpath/java/java/lang/Override.java trunk/core/src/classpath/java/java/lang/Short.java trunk/core/src/classpath/java/java/lang/String.java trunk/core/src/classpath/java/java/lang/StringBuilder.java trunk/core/src/classpath/java/java/lang/SuppressWarnings.java Added: trunk/core/src/classpath/java/java/lang/Boolean.java =================================================================== --- trunk/core/src/classpath/java/java/lang/Boolean.java (rev 0) +++ trunk/core/src/classpath/java/java/lang/Boolean.java 2006-12-12 21:14:46 UTC (rev 2900) @@ -0,0 +1,251 @@ +/* Boolean.java -- object wrapper for boolean + Copyright (C) 1998, 2001, 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.lang; + +import java.io.Serializable; + +/** + * Instances of class <code>Boolean</code> represent primitive + * <code>boolean</code> values. + * + * @author Paul Fisher + * @author Eric Blake (eb...@em...) + * @since 1.0 + * @status updated to 1.5 + */ +public final class Boolean implements Serializable, Comparable<Boolean> +{ + /** + * Compatible with JDK 1.0.2+. + */ + private static final long serialVersionUID = -3665804199014368530L; + + /** + * This field is a <code>Boolean</code> object representing the + * primitive value <code>true</code>. This instance is returned + * by the static <code>valueOf()</code> methods if they return + * a <code>Boolean</code> representing <code>true</code>. + */ + public static final Boolean TRUE = new Boolean(true); + + /** + * This field is a <code>Boolean</code> object representing the + * primitive value <code>false</code>. This instance is returned + * by the static <code>valueOf()</code> methods if they return + * a <code>Boolean</code> representing <code>false</code>. + */ + public static final Boolean FALSE = new Boolean(false); + + /** + * The primitive type <code>boolean</code> is represented by this + * <code>Class</code> object. + * + * @since 1.1 + */ + public static final Class<Boolean> TYPE = (Class<Boolean>) VMClassLoader.getPrimitiveClass('Z'); + + /** + * The immutable value of this Boolean. + * @serial the wrapped value + */ + private final boolean value; + + /** + * Create a <code>Boolean</code> object representing the value of the + * argument <code>value</code>. In general the use of the static + * method <code>valueof(boolean)</code> is more efficient since it will + * not create a new object. + * + * @param value the primitive value of this <code>Boolean</code> + * @see #valueOf(boolean) + */ + public Boolean(boolean value) + { + this.value = value; + } + + /** + * Creates a <code>Boolean</code> object representing the primitive + * <code>true</code> if and only if <code>s</code> matches + * the string "true" ignoring case, otherwise the object will represent + * the primitive <code>false</code>. In general the use of the static + * method <code>valueof(String)</code> is more efficient since it will + * not create a new object. + * + * @param s the <code>String</code> representation of <code>true</code> + * or false + */ + public Boolean(String s) + { + value = "true".equalsIgnoreCase(s); + } + + /** + * Return the primitive <code>boolean</code> value of this + * <code>Boolean</code> object. + * + * @return true or false, depending on the value of this Boolean + */ + public boolean booleanValue() + { + return value; + } + + /** + * Returns the Boolean <code>TRUE</code> if the given boolean is + * <code>true</code>, otherwise it will return the Boolean + * <code>FALSE</code>. + * + * @param b the boolean to wrap + * @return the wrapper object + * @see #TRUE + * @see #FALSE + * @since 1.4 + */ + public static Boolean valueOf(boolean b) + { + return b ? TRUE : FALSE; + } + + /** + * Returns the Boolean <code>TRUE</code> if and only if the given + * String is equal, ignoring case, to the the String "true", otherwise + * it will return the Boolean <code>FALSE</code>. + * + * @param s the string to convert + * @return a wrapped boolean from the string + */ + public static Boolean valueOf(String s) + { + return "true".equalsIgnoreCase(s) ? TRUE : FALSE; + } + + /** + * Returns "true" if the value of the give boolean is <code>true</code> and + * returns "false" if the value of the given boolean is <code>false</code>. + * + * @param b the boolean to convert + * @return the string representation of the boolean + * @since 1.4 + */ + public static String toString(boolean b) + { + return b ? "true" : "false"; + } + + /** + * Returns "true" if the value of this object is <code>true</code> and + * returns "false" if the value of this object is <code>false</code>. + * + * @return the string representation of this + */ + public String toString() + { + return value ? "true" : "false"; + } + + /** + * Returns the integer <code>1231</code> if this object represents + * the primitive <code>true</code> and the integer <code>1237</code> + * otherwise. + * + * @return the hash code + */ + public int hashCode() + { + return value ? 1231 : 1237; + } + + /** + * If the <code>obj</code> is an instance of <code>Boolean</code> and + * has the same primitive value as this object then <code>true</code> + * is returned. In all other cases, including if the <code>obj</code> + * is <code>null</code>, <code>false</code> is returned. + * + * @param obj possibly an instance of any <code>Class</code> + * @return true if <code>obj</code> equals this + */ + public boolean equals(Object obj) + { + return obj instanceof Boolean && value == ((Boolean) obj).value; + } + + /** + * If the value of the system property <code>name</code> matches + * "true" ignoring case then the function returns <code>true</code>. + * + * @param name the property name to look up + * @return true if the property resulted in "true" + * @throws SecurityException if accessing the system property is forbidden + * @see System#getProperty(String) + */ + public static boolean getBoolean(String name) + { + if (name == null || "".equals(name)) + return false; + return "true".equalsIgnoreCase(System.getProperty(name)); + } + + /** + * Compares this Boolean to another. + * + * @param other the Boolean to compare this Boolean to + * @return 0 if both Booleans represent the same value, a positive number + * if this Boolean represents true and the other false, and a negative + * number otherwise. + * @since 1.5 + */ + public int compareTo(Boolean other) + { + return value == other.value ? 0 : (value ? 1 : -1); + } + + /** + * If the String argument is "true", ignoring case, return true. + * Otherwise, return false. + * + * @param b String to parse + * @since 1.5 + */ + public static boolean parseBoolean(String b) + { + return "true".equalsIgnoreCase(b) ? true : false; + } + +} Added: trunk/core/src/classpath/java/java/lang/Byte.java =================================================================== --- trunk/core/src/classpath/java/java/lang/Byte.java (rev 0) +++ trunk/core/src/classpath/java/java/lang/Byte.java 2006-12-12 21:14:46 UTC (rev 2900) @@ -0,0 +1,373 @@ +/* Byte.java -- object wrapper for byte + Copyright (C) 1998, 2001, 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.lang; + +/** + * Instances of class <code>Byte</code> represent primitive <code>byte</code> + * values. + * + * Additionally, this class provides various helper functions and variables + * useful to bytes. + * + * @author Paul Fisher + * @author John Keiser + * @author Per Bothner + * @author Eric Blake (eb...@em...) + * @author Tom Tromey (tr...@re...) + * @author Andrew John Hughes (gnu...@me...) + * @since 1.1 + * @status updated to 1.5 + */ +public final class Byte extends Number implements Comparable<Byte> +{ + /** + * Compatible with JDK 1.1+. + */ + private static final long serialVersionUID = -7183698231559129828L; + + /** + * The minimum value a <code>byte</code> can represent is -128 (or + * -2<sup>7</sup>). + */ + public static final byte MIN_VALUE = -128; + + /** + * The maximum value a <code>byte</code> can represent is 127 (or + * 2<sup>7</sup> - 1). + */ + public static final byte MAX_VALUE = 127; + + /** + * The primitive type <code>byte</code> is represented by this + * <code>Class</code> object. + */ + public static final Class<Byte> TYPE = (Class<Byte>) VMClassLoader.getPrimitiveClass('B'); + + /** + * The number of bits needed to represent a <code>byte</code>. + * @since 1.5 + */ + public static final int SIZE = 8; + + // This caches Byte values, and is used by boxing conversions via + // valueOf(). We're required to cache all possible values here. + private static Byte[] byteCache = new Byte[MAX_VALUE - MIN_VALUE + 1]; + + + /** + * The immutable value of this Byte. + * + * @serial the wrapped byte + */ + private final byte value; + + /** + * Create a <code>Byte</code> object representing the value of the + * <code>byte</code> argument. + * + * @param value the value to use + */ + public Byte(byte value) + { + this.value = value; + } + + /** + * Create a <code>Byte</code> object representing the value specified + * by the <code>String</code> argument + * + * @param s the string to convert + * @throws NumberFormatException if the String does not contain a byte + * @see #valueOf(String) + */ + public Byte(String s) + { + value = parseByte(s, 10); + } + + /** + * Converts the <code>byte</code> to a <code>String</code> and assumes + * a radix of 10. + * + * @param b the <code>byte</code> to convert to <code>String</code> + * @return the <code>String</code> representation of the argument + */ + public static String toString(byte b) + { + return String.valueOf(b); + } + + /** + * Converts the specified <code>String</code> into a <code>byte</code>. + * This function assumes a radix of 10. + * + * @param s the <code>String</code> to convert + * @return the <code>byte</code> value of <code>s</code> + * @throws NumberFormatException if <code>s</code> cannot be parsed as a + * <code>byte</code> + * @see #parseByte(String) + */ + public static byte parseByte(String s) + { + return parseByte(s, 10); + } + + /** + * Converts the specified <code>String</code> into an <code>int</code> + * using the specified radix (base). The string must not be <code>null</code> + * or empty. It may begin with an optional '-', which will negate the answer, + * provided that there are also valid digits. Each digit is parsed as if by + * <code>Character.digit(d, radix)</code>, and must be in the range + * <code>0</code> to <code>radix - 1</code>. Finally, the result must be + * within <code>MIN_VALUE</code> to <code>MAX_VALUE</code>, inclusive. + * Unlike Double.parseDouble, you may not have a leading '+'. + * + * @param s the <code>String</code> to convert + * @param radix the radix (base) to use in the conversion + * @return the <code>String</code> argument converted to <code>byte</code> + * @throws NumberFormatException if <code>s</code> cannot be parsed as a + * <code>byte</code> + */ + public static byte parseByte(String s, int radix) + { + int i = Integer.parseInt(s, radix, false); + if ((byte) i != i) + throw new NumberFormatException(); + return (byte) i; + } + + /** + * Creates a new <code>Byte</code> object using the <code>String</code> + * and specified radix (base). + * + * @param s the <code>String</code> to convert + * @param radix the radix (base) to convert with + * @return the new <code>Byte</code> + * @throws NumberFormatException if <code>s</code> cannot be parsed as a + * <code>byte</code> + * @see #parseByte(String, int) + */ + public static Byte valueOf(String s, int radix) + { + return new Byte(parseByte(s, radix)); + } + + /** + * Creates a new <code>Byte</code> object using the <code>String</code>, + * assuming a radix of 10. + * + * @param s the <code>String</code> to convert + * @return the new <code>Byte</code> + * @throws NumberFormatException if <code>s</code> cannot be parsed as a + * <code>byte</code> + * @see #Byte(String) + * @see #parseByte(String) + */ + public static Byte valueOf(String s) + { + return new Byte(parseByte(s, 10)); + } + + /** + * Returns a <code>Byte</code> object wrapping the value. + * In contrast to the <code>Byte</code> constructor, this method + * will cache some values. It is used by boxing conversion. + * + * @param val the value to wrap + * @return the <code>Byte</code> + */ + public static Byte valueOf(byte val) + { + synchronized (byteCache) + { + if (byteCache[val - MIN_VALUE] == null) + byteCache[val - MIN_VALUE] = new Byte(val); + return byteCache[val - MIN_VALUE]; + } + } + + /** + * Convert the specified <code>String</code> into a <code>Byte</code>. + * The <code>String</code> may represent decimal, hexadecimal, or + * octal numbers. + * + * <p>The extended BNF grammar is as follows:<br> + * <pre> + * <em>DecodableString</em>: + * ( [ <code>-</code> ] <em>DecimalNumber</em> ) + * | ( [ <code>-</code> ] ( <code>0x</code> | <code>0X</code> + * | <code>#</code> ) { <em>HexDigit</em> }+ ) + * | ( [ <code>-</code> ] <code>0</code> { <em>OctalDigit</em> } ) + * <em>DecimalNumber</em>: + * <em>DecimalDigit except '0'</em> { <em>DecimalDigit</em> } + * <em>DecimalDigit</em>: + * <em>Character.digit(d, 10) has value 0 to 9</em> + * <em>OctalDigit</em>: + * <em>Character.digit(d, 8) has value 0 to 7</em> + * <em>DecimalDigit</em>: + * <em>Character.digit(d, 16) has value 0 to 15</em> + * </pre> + * Finally, the value must be in the range <code>MIN_VALUE</code> to + * <code>MAX_VALUE</code>, or an exception is thrown. + * + * @param s the <code>String</code> to interpret + * @return the value of the String as a <code>Byte</code> + * @throws NumberFormatException if <code>s</code> cannot be parsed as a + * <code>byte</code> + * @throws NullPointerException if <code>s</code> is null + * @see Integer#decode(String) + */ + public static Byte decode(String s) + { + int i = Integer.parseInt(s, 10, true); + if ((byte) i != i) + throw new NumberFormatException(); + return new Byte((byte) i); + } + + /** + * Return the value of this <code>Byte</code>. + * + * @return the byte value + */ + public byte byteValue() + { + return value; + } + + /** + * Return the value of this <code>Byte</code> as a <code>short</code>. + * + * @return the short value + */ + public short shortValue() + { + return value; + } + + /** + * Return the value of this <code>Byte</code> as an <code>int</code>. + * + * @return the int value + */ + public int intValue() + { + return value; + } + + /** + * Return the value of this <code>Byte</code> as a <code>long</code>. + * + * @return the long value + */ + public long longValue() + { + return value; + } + + /** + * Return the value of this <code>Byte</code> as a <code>float</code>. + * + * @return the float value + */ + public float floatValue() + { + return value; + } + + /** + * Return the value of this <code>Byte</code> as a <code>double</code>. + * + * @return the double value + */ + public double doubleValue() + { + return value; + } + + /** + * Converts the <code>Byte</code> value to a <code>String</code> and + * assumes a radix of 10. + * + * @return the <code>String</code> representation of this <code>Byte</code> + * @see Integer#toString() + */ + public String toString() + { + return String.valueOf(value); + } + + /** + * Return a hashcode representing this Object. <code>Byte</code>'s hash + * code is simply its value. + * + * @return this Object's hash code + */ + public int hashCode() + { + return value; + } + + /** + * Returns <code>true</code> if <code>obj</code> is an instance of + * <code>Byte</code> and represents the same byte value. + * + * @param obj the object to compare + * @return whether these Objects are semantically equal + */ + public boolean equals(Object obj) + { + return obj instanceof Byte && value == ((Byte) obj).value; + } + + /** + * Compare two Bytes numerically by comparing their <code>byte</code> values. + * The result is positive if the first is greater, negative if the second + * is greater, and 0 if the two are equal. + * + * @param b the Byte to compare + * @return the comparison + * @since 1.2 + */ + public int compareTo(Byte b) + { + return value - b.value; + } + +} Added: trunk/core/src/classpath/java/java/lang/Character.java =================================================================== --- trunk/core/src/classpath/java/java/lang/Character.java (rev 0) +++ trunk/core/src/classpath/java/java/lang/Character.java 2006-12-12 21:14:46 UTC (rev 2900) @@ -0,0 +1,4551 @@ +/* java.lang.Character -- Wrapper class for char, and Unicode subsets + Copyright (C) 1998, 1999, 2001, 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.lang; + +import gnu.java.lang.CharData; + +import java.io.Serializable; +import java.text.Collator; +import java.util.Locale; + +/** + * Wrapper class for the primitive char data type. In addition, this class + * allows one to retrieve property information and perform transformations + * on the defined characters in the Unicode Standard, Version 4.0.0. + * java.lang.Character is designed to be very dynamic, and as such, it + * retrieves information on the Unicode character set from a separate + * database, gnu.java.lang.CharData, which can be easily upgraded. + * + * <p>For predicates, boundaries are used to describe + * the set of characters for which the method will return true. + * This syntax uses fairly normal regular expression notation. + * See 5.13 of the Unicode Standard, Version 4.0, for the + * boundary specification. + * + * <p>See <a href="http://www.unicode.org">http://www.unicode.org</a> + * for more information on the Unicode Standard. + * + * @author Tom Tromey (tr...@cy...) + * @author Paul N. Fisher + * @author Jochen Hoenicke + * @author Eric Blake (eb...@em...) + * @author Andrew John Hughes (gnu...@me...) + * @see CharData + * @since 1.0 + * @status partly updated to 1.5; some things still missing + */ +public final class Character implements Serializable, Comparable<Character> +{ + /** + * A subset of Unicode blocks. + * + * @author Paul N. Fisher + * @author Eric Blake (eb...@em...) + * @since 1.2 + */ + public static class Subset + { + /** The name of the subset. */ + private final String name; + + /** + * Construct a new subset of characters. + * + * @param name the name of the subset + * @throws NullPointerException if name is null + */ + protected Subset(String name) + { + // Note that name.toString() is name, unless name was null. + this.name = name.toString(); + } + + /** + * Compares two Subsets for equality. This is <code>final</code>, and + * restricts the comparison on the <code>==</code> operator, so it returns + * true only for the same object. + * + * @param o the object to compare + * @return true if o is this + */ + public final boolean equals(Object o) + { + return o == this; + } + + /** + * Makes the original hashCode of Object final, to be consistent with + * equals. + * + * @return the hash code for this object + */ + public final int hashCode() + { + return super.hashCode(); + } + + /** + * Returns the name of the subset. + * + * @return the name + */ + public final String toString() + { + return name; + } + } // class Subset + + /** + * A family of character subsets in the Unicode specification. A character + * is in at most one of these blocks. + * + * This inner class was generated automatically from + * <code>doc/unicode/Blocks-4.0.0.txt</code>, by some perl scripts. + * This Unicode definition file can be found on the + * <a href="http://www.unicode.org">http://www.unicode.org</a> website. + * JDK 1.5 uses Unicode version 4.0.0. + * + * @author scripts/unicode-blocks.pl (written by Eric Blake) + * @since 1.2 + */ + public static final class UnicodeBlock extends Subset + { + /** The start of the subset. */ + private final int start; + + /** The end of the subset. */ + private final int end; + + /** The canonical name of the block according to the Unicode standard. */ + private final String canonicalName; + + /** Enumeration for the <code>forName()</code> method */ + private enum NameType { CANONICAL, NO_SPACES, CONSTANT; }; + + /** + * Constructor for strictly defined blocks. + * + * @param start the start character of the range + * @param end the end character of the range + * @param name the block name + * @param canonicalName the name of the block as defined in the Unicode + * standard. + */ + private UnicodeBlock(int start, int end, String name, + String canonicalName) + { + super(name); + this.start = start; + this.end = end; + this.canonicalName = canonicalName; + } + + /** + * Returns the Unicode character block which a character belongs to. + * <strong>Note</strong>: This method does not support the use of + * supplementary characters. For such support, <code>of(int)</code> + * should be used instead. + * + * @param ch the character to look up + * @return the set it belongs to, or null if it is not in one + */ + public static UnicodeBlock of(char ch) + { + return of((int) ch); + } + + /** + * Returns the Unicode character block which a code point belongs to. + * + * @param codePoint the character to look up + * @return the set it belongs to, or null if it is not in one. + * @throws IllegalArgumentException if the specified code point is + * invalid. + * @since 1.5 + */ + public static UnicodeBlock of(int codePoint) + { + if (codePoint > MAX_CODE_POINT) + throw new IllegalArgumentException("The supplied integer value is " + + "too large to be a codepoint."); + // Simple binary search for the correct block. + int low = 0; + int hi = sets.length - 1; + while (low <= hi) + { + int mid = (low + hi) >> 1; + UnicodeBlock b = sets[mid]; + if (codePoint < b.start) + hi = mid - 1; + else if (codePoint > b.end) + low = mid + 1; + else + return b; + } + return null; + } + + /** + * <p> + * Returns the <code>UnicodeBlock</code> with the given name, as defined + * by the Unicode standard. The version of Unicode in use is defined by + * the <code>Character</code> class, and the names are given in the + * <code>Blocks-<version>.txt</code> file corresponding to that version. + * The name may be specified in one of three ways: + * </p> + * <ol> + * <li>The canonical, human-readable name used by the Unicode standard. + * This is the name with all spaces and hyphens retained. For example, + * `Basic Latin' retrieves the block, UnicodeBlock.BASIC_LATIN.</li> + * <li>The canonical name with all spaces removed e.g. `BasicLatin'.</li> + * <li>The name used for the constants specified by this class, which + * is the canonical name with all spaces and hyphens replaced with + * underscores e.g. `BASIC_LATIN'</li> + * </ol> + * <p> + * The names are compared case-insensitively using the case comparison + * associated with the U.S. English locale. The method recognises the + * previous names used for blocks as well as the current ones. At + * present, this simply means that the deprecated `SURROGATES_AREA' + * will be recognised by this method (the <code>of()</code> methods + * only return one of the three new surrogate blocks). + * </p> + * + * @param blockName the name of the block to look up. + * @return the specified block. + * @throws NullPointerException if the <code>blockName</code> is + * <code>null</code>. + * @throws IllegalArgumentException if the name does not match any Unicode + * block. + * @since 1.5 + */ + public static final UnicodeBlock forName(String blockName) + { + NameType type; + if (blockName.indexOf(' ') != -1) + type = NameType.CANONICAL; + else if (blockName.indexOf('_') != -1) + type = NameType.CONSTANT; + else + type = NameType.NO_SPACES; + Collator usCollator = Collator.getInstance(Locale.US); + usCollator.setStrength(Collator.PRIMARY); + /* Special case for deprecated blocks not in sets */ + switch (type) + { + case CANONICAL: + if (usCollator.compare(blockName, "Surrogates Area") == 0) + return SURROGATES_AREA; + break; + case NO_SPACES: + if (usCollator.compare(blockName, "SurrogatesArea") == 0) + return SURROGATES_AREA; + break; + case CONSTANT: + if (usCollator.compare(blockName, "SURROGATES_AREA") == 0) + return SURROGATES_AREA; + break; + } + /* Other cases */ + switch (type) + { + case CANONICAL: + for (UnicodeBlock block : sets) + if (usCollator.compare(blockName, block.canonicalName) == 0) + return block; + break; + case NO_SPACES: + for (UnicodeBlock block : sets) + { + String nsName = block.canonicalName.replaceAll(" ",""); + if (usCollator.compare(blockName, nsName) == 0) + return block; + } + break; + case CONSTANT: + for (UnicodeBlock block : sets) + if (usCollator.compare(blockName, block.toString()) == 0) + return block; + break; + } + throw new IllegalArgumentException("No Unicode block found for " + + blockName + "."); + } + + /** + * Basic Latin. + * 0x0000 - 0x007F. + */ + public static final UnicodeBlock BASIC_LATIN + = new UnicodeBlock(0x0000, 0x007F, + "BASIC_LATIN", + "Basic Latin"); + + /** + * Latin-1 Supplement. + * 0x0080 - 0x00FF. + */ + public static final UnicodeBlock LATIN_1_SUPPLEMENT + = new UnicodeBlock(0x0080, 0x00FF, + "LATIN_1_SUPPLEMENT", + "Latin-1 Supplement"); + + /** + * Latin Extended-A. + * 0x0100 - 0x017F. + */ + public static final UnicodeBlock LATIN_EXTENDED_A + = new UnicodeBlock(0x0100, 0x017F, + "LATIN_EXTENDED_A", + "Latin Extended-A"); + + /** + * Latin Extended-B. + * 0x0180 - 0x024F. + */ + public static final UnicodeBlock LATIN_EXTENDED_B + = new UnicodeBlock(0x0180, 0x024F, + "LATIN_EXTENDED_B", + "Latin Extended-B"); + + /** + * IPA Extensions. + * 0x0250 - 0x02AF. + */ + public static final UnicodeBlock IPA_EXTENSIONS + = new UnicodeBlock(0x0250, 0x02AF, + "IPA_EXTENSIONS", + "IPA Extensions"); + + /** + * Spacing Modifier Letters. + * 0x02B0 - 0x02FF. + */ + public static final UnicodeBlock SPACING_MODIFIER_LETTERS + = new UnicodeBlock(0x02B0, 0x02FF, + "SPACING_MODIFIER_LETTERS", + "Spacing Modifier Letters"); + + /** + * Combining Diacritical Marks. + * 0x0300 - 0x036F. + */ + public static final UnicodeBlock COMBINING_DIACRITICAL_MARKS + = new UnicodeBlock(0x0300, 0x036F, + "COMBINING_DIACRITICAL_MARKS", + "Combining Diacritical Marks"); + + /** + * Greek. + * 0x0370 - 0x03FF. + */ + public static final UnicodeBlock GREEK + = new UnicodeBlock(0x0370, 0x03FF, + "GREEK", + "Greek"); + + /** + * Cyrillic. + * 0x0400 - 0x04FF. + */ + public static final UnicodeBlock CYRILLIC + = new UnicodeBlock(0x0400, 0x04FF, + "CYRILLIC", + "Cyrillic"); + + /** + * Cyrillic Supplementary. + * 0x0500 - 0x052F. + * @since 1.5 + */ + public static final UnicodeBlock CYRILLIC_SUPPLEMENTARY + = new UnicodeBlock(0x0500, 0x052F, + "CYRILLIC_SUPPLEMENTARY", + "Cyrillic Supplementary"); + + /** + * Armenian. + * 0x0530 - 0x058F. + */ + public static final UnicodeBlock ARMENIAN + = new UnicodeBlock(0x0530, 0x058F, + "ARMENIAN", + "Armenian"); + + /** + * Hebrew. + * 0x0590 - 0x05FF. + */ + public static final UnicodeBlock HEBREW + = new UnicodeBlock(0x0590, 0x05FF, + "HEBREW", + "Hebrew"); + + /** + * Arabic. + * 0x0600 - 0x06FF. + */ + public static final UnicodeBlock ARABIC + = new UnicodeBlock(0x0600, 0x06FF, + "ARABIC", + "Arabic"); + + /** + * Syriac. + * 0x0700 - 0x074F. + * @since 1.4 + */ + public static final UnicodeBlock SYRIAC + = new UnicodeBlock(0x0700, 0x074F, + "SYRIAC", + "Syriac"); + + /** + * Thaana. + * 0x0780 - 0x07BF. + * @since 1.4 + */ + public static final UnicodeBlock THAANA + = new UnicodeBlock(0x0780, 0x07BF, + "THAANA", + "Thaana"); + + /** + * Devanagari. + * 0x0900 - 0x097F. + */ + public static final UnicodeBlock DEVANAGARI + = new UnicodeBlock(0x0900, 0x097F, + "DEVANAGARI", + "Devanagari"); + + /** + * Bengali. + * 0x0980 - 0x09FF. + */ + public static final UnicodeBlock BENGALI + = new UnicodeBlock(0x0980, 0x09FF, + "BENGALI", + "Bengali"); + + /** + * Gurmukhi. + * 0x0A00 - 0x0A7F. + */ + public static final UnicodeBlock GURMUKHI + = new UnicodeBlock(0x0A00, 0x0A7F, + "GURMUKHI", + "Gurmukhi"); + + /** + * Gujarati. + * 0x0A80 - 0x0AFF. + */ + public static final UnicodeBlock GUJARATI + = new UnicodeBlock(0x0A80, 0x0AFF, + "GUJARATI", + "Gujarati"); + + /** + * Oriya. + * 0x0B00 - 0x0B7F. + */ + public static final UnicodeBlock ORIYA + = new UnicodeBlock(0x0B00, 0x0B7F, + "ORIYA", + "Oriya"); + + /** + * Tamil. + * 0x0B80 - 0x0BFF. + */ + public static final UnicodeBlock TAMIL + = new UnicodeBlock(0x0B80, 0x0BFF, + "TAMIL", + "Tamil"); + + /** + * Telugu. + * 0x0C00 - 0x0C7F. + */ + public static final UnicodeBlock TELUGU + = new UnicodeBlock(0x0C00, 0x0C7F, + "TELUGU", + "Telugu"); + + /** + * Kannada. + * 0x0C80 - 0x0CFF. + */ + public static final UnicodeBlock KANNADA + = new UnicodeBlock(0x0C80, 0x0CFF, + "KANNADA", + "Kannada"); + + /** + * Malayalam. + * 0x0D00 - 0x0D7F. + */ + public static final UnicodeBlock MALAYALAM + = new UnicodeBlock(0x0D00, 0x0D7F, + "MALAYALAM", + "Malayalam"); + + /** + * Sinhala. + * 0x0D80 - 0x0DFF. + * @since 1.4 + */ + public static final UnicodeBlock SINHALA + = new UnicodeBlock(0x0D80, 0x0DFF, + "SINHALA", + "Sinhala"); + + /** + * Thai. + * 0x0E00 - 0x0E7F. + */ + public static final UnicodeBlock THAI + = new UnicodeBlock(0x0E00, 0x0E7F, + "THAI", + "Thai"); + + /** + * Lao. + * 0x0E80 - 0x0EFF. + */ + public static final UnicodeBlock LAO + = new UnicodeBlock(0x0E80, 0x0EFF, + "LAO", + "Lao"); + + /** + * Tibetan. + * 0x0F00 - 0x0FFF. + */ + public static final UnicodeBlock TIBETAN + = new UnicodeBlock(0x0F00, 0x0FFF, + "TIBETAN", + "Tibetan"); + + /** + * Myanmar. + * 0x1000 - 0x109F. + * @since 1.4 + */ + public static final UnicodeBlock MYANMAR + = new UnicodeBlock(0x1000, 0x109F, + "MYANMAR", + "Myanmar"); + + /** + * Georgian. + * 0x10A0 - 0x10FF. + */ + public static final UnicodeBlock GEORGIAN + = new UnicodeBlock(0x10A0, 0x10FF, + "GEORGIAN", + "Georgian"); + + /** + * Hangul Jamo. + * 0x1100 - 0x11FF. + */ + public static final UnicodeBlock HANGUL_JAMO + = new UnicodeBlock(0x1100, 0x11FF, + "HANGUL_JAMO", + "Hangul Jamo"); + + /** + * Ethiopic. + * 0x1200 - 0x137F. + * @since 1.4 + */ + public static final UnicodeBlock ETHIOPIC + = new UnicodeBlock(0x1200, 0x137F, + "ETHIOPIC", + "Ethiopic"); + + /** + * Cherokee. + * 0x13A0 - 0x13FF. + * @since 1.4 + */ + public static final UnicodeBlock CHEROKEE + = new UnicodeBlock(0x13A0, 0x13FF, + "CHEROKEE", + "Cherokee"); + + /** + * Unified Canadian Aboriginal Syllabics. + * 0x1400 - 0x167F. + * @since 1.4 + */ + public static final UnicodeBlock UNIFIED_CANADIAN_ABORIGINAL_SYLLABICS + = new UnicodeBlock(0x1400, 0x167F, + "UNIFIED_CANADIAN_ABORIGINAL_SYLLABICS", + "Unified Canadian Aboriginal Syllabics"); + + /** + * Ogham. + * 0x1680 - 0x169F. + * @since 1.4 + */ + public static final UnicodeBlock OGHAM + = new UnicodeBlock(0x1680, 0x169F, + "OGHAM", + "Ogham"); + + /** + * Runic. + * 0x16A0 - 0x16FF. + * @since 1.4 + */ + public static final UnicodeBlock RUNIC + = new UnicodeBlock(0x16A0, 0x16FF, + "RUNIC", + "Runic"); + + /** + * Tagalog. + * 0x1700 - 0x171F. + * @since 1.5 + */ + public static final UnicodeBlock TAGALOG + = new UnicodeBlock(0x1700, 0x171F, + "TAGALOG", + "Tagalog"); + + /** + * Hanunoo. + * 0x1720 - 0x173F. + * @since 1.5 + */ + public static final UnicodeBlock HANUNOO + = new UnicodeBlock(0x1720, 0x173F, + "HANUNOO", + "Hanunoo"); + + /** + * Buhid. + * 0x1740 - 0x175F. + * @since 1.5 + */ + public static final UnicodeBlock BUHID + = new UnicodeBlock(0x1740, 0x175F, + "BUHID", + "Buhid"); + + /** + * Tagbanwa. + * 0x1760 - 0x177F. + * @since 1.5 + */ + public static final UnicodeBlock TAGBANWA + = new UnicodeBlock(0x1760, 0x177F, + "TAGBANWA", + "Tagbanwa"); + + /** + * Khmer. + * 0x1780 - 0x17FF. + * @since 1.4 + */ + public static final UnicodeBlock KHMER + = new UnicodeBlock(0x1780, 0x17FF, + "KHMER", + "Khmer"); + + /** + * Mongolian. + * 0x1800 - 0x18AF. + * @since 1.4 + */ + public static final UnicodeBlock MONGOLIAN + = new UnicodeBlock(0x1800, 0x18AF, + "MONGOLIAN", + "Mongolian"); + + /** + * Limbu. + * 0x1900 - 0x194F. + * @since 1.5 + */ + public static final UnicodeBlock LIMBU + = new UnicodeBlock(0x1900, 0x194F, + "LIMBU", + "Limbu"); + + /** + * Tai Le. + * 0x1950 - 0x197F. + * @since 1.5 + */ + public static final UnicodeBlock TAI_LE + = new UnicodeBlock(0x1950, 0x197F, + "TAI_LE", + "Tai Le"); + + /** + * Khmer Symbols. + * 0x19E0 - 0x19FF. + * @since 1.5 + */ + public static final UnicodeBlock KHMER_SYMBOLS + = new UnicodeBlock(0x19E0, 0x19FF, + "KHMER_SYMBOLS", + "Khmer Symbols"); + + /** + * Phonetic Extensions. + * 0x1D00 - 0x1D7F. + * @since 1.5 + */ + public static final UnicodeBlock PHONETIC_EXTENSIONS + = new UnicodeBlock(0x1D00, 0x1D7F, + "PHONETIC_EXTENSIONS", + "Phonetic Extensions"); + + /** + * Latin Extended Additional. + * 0x1E00 - 0x1EFF. + */ + public static final UnicodeBlock LATIN_EXTENDED_ADDITIONAL + = new UnicodeBlock(0x1E00, 0x1EFF, + "LATIN_EXTENDED_ADDITIONAL", + "Latin Extended Additional"); + + /** + * Greek Extended. + * 0x1F00 - 0x1FFF. + */ + public static final UnicodeBlock GREEK_EXTENDED + = new UnicodeBlock(0x1F00, 0x1FFF, + "GREEK_EXTENDED", + "Greek Extended"); + + /** + * General Punctuation. + * 0x2000 - 0x206F. + */ + public static final UnicodeBlock GENERAL_PUNCTUATION + = new UnicodeBlock(0x2000, 0x206F, + "GENERAL_PUNCTUATION", + "General Punctuation"); + + /** + * Superscripts and Subscripts. + * 0x2070 - 0x209F. + */ + public static final UnicodeBlock SUPERSCRIPTS_AND_SUBSCRIPTS + = new UnicodeBlock(0x2070, 0x209F, + "SUPERSCRIPTS_AND_SUBSCRIPTS", + "Superscripts and Subscripts"); + + /** + * Currency Symbols. + * 0x20A0 - 0x20CF. + */ + public static final UnicodeBlock CURRENCY_SYMBOLS + = new UnicodeBlock(0x20A0, 0x20CF, + "CURRENCY_SYMBOLS", + "Currency Symbols"); + + /** + * Combining Marks for Symbols. + * 0x20D0 - 0x20FF. + */ + public static final UnicodeBlock COMBINING_MARKS_FOR_SYMBOLS + = new UnicodeBlock(0x20D0, 0x20FF, + "COMBINING_MARKS_FOR_SYMBOLS", + "Combining Marks for Symbols"); + + /** + * Letterlike Symbols. + * 0x2100 - 0x214F. + */ + public static final UnicodeBlock LETTERLIKE_SYMBOLS + = new UnicodeBlock(0x2100, 0x214F, + "LETTERLIKE_SYMBOLS", + "Letterlike Symbols"); + + /** + * Number Forms. + * 0x2150 - 0x218F. + */ + public static final UnicodeBlock NUMBER_FORMS + = new UnicodeBlock(0x2150, 0x218F, + "NUMBER_FORMS", + "Number Forms"); + + /** + * Arrows. + * 0x2190 - 0x21FF. + */ + public static final UnicodeBlock ARROWS + = new UnicodeBlock(0x2190, 0x21FF, + "ARROWS", + "Arrows"); + + /** + * Mathematical Operators. + * 0x2200 - 0x22FF. + */ + public static final UnicodeBlock MATHEMATICAL_OPERATORS + = new UnicodeBlock(0x2200, 0x22FF, + "MATHEMATICAL_OPERATORS", + "Mathematical Operators"); + + /** + * Miscellaneous Technical. + * 0x2300 - 0x23FF. + */ + public static final UnicodeBlock MISCELLANEOUS_TECHNICAL + = new UnicodeBlock(0x2300, 0x23FF, + "MISCELLANEOUS_TECHNICAL", + "Miscellaneous Technical"); + + /** + * Control Pictures. + * 0x2400 - 0x243F. + */ + public static final UnicodeBlock CONTROL_PICTURES + = new UnicodeBlock(0x2400, 0x243F, + "CONTROL_PICTURES", + "Control Pictures"); + + /** + * Optical Character Recognition. + * 0x2440 - 0x245F. + */ + public static final UnicodeBlock OPTICAL_CHARACTER_RECOGNITION + = new UnicodeBlock(0x2440, 0x245F, + "OPTICAL_CHARACTER_RECOGNITION", + "Optical Character Recognition"); + + /** + * Enclosed Alphanumerics. + * 0x2460 - 0x24FF. + */ + public static final UnicodeBlock ENCLOSED_ALPHANUMERICS + = new UnicodeBlock(0x2460, 0x24FF, + "ENCLOSED_ALPHANUMERICS", + "Enclosed Alphanumerics"); + + /** + * Box Drawing. + * 0x2500 - 0x257F. + */ + public static final UnicodeBlock BOX_DRAWING + = new UnicodeBlock(0x2500, 0x257F, + "BOX_DRAWING", + "Box Drawing"); + + /** + * Block Elements. + * 0x2580 - 0x259F. + */ + public static final UnicodeBlock BLOCK_ELEMENTS + = new UnicodeBlock(0x2580, 0x259F, + "BLOCK_ELEMENTS", + "Block Elements"); + + /** + * Geometric Shapes. + * 0x25A0 - 0x25FF. + */ + public static final UnicodeBlock GEOMETRIC_SHAPES + = new UnicodeBlock(0x25A0, 0x25FF, + "GEOMETRIC_SHAPES", + "Geometric Shapes"); + + /** + * Miscellaneous Symbols. + * 0x2600 - 0x26FF. + */ + public static final UnicodeBlock MISCELLANEOUS_SYMBOLS + = new UnicodeBlock(0x2600, 0x26FF, + "MISCELLANEOUS_SYMBOLS", + "Miscellaneous Symbols"); + + /** + * Dingbats. + * 0x2700 - 0x27BF. + */ + public static final UnicodeBlock DINGBATS + = new UnicodeBlock(0x2700, 0x27BF, + "DINGBATS", + "Dingbats"); + + /** + * Miscellaneous Mathematical Symbols-A. + * 0x27C0 - 0x27EF. + * @since 1.5 + */ + public static final UnicodeBlock MISCELLANEOUS_MATHEMATICAL_SYMBOLS_A + = new UnicodeBlock(0x27C0, 0x27EF, + "MISCELLANEOUS_MATHEMATICAL_SYMBOLS_A", + "Miscellaneous Mathematical Symbols-A"); + + /** + * Supplemental Arrows-A. + * 0x27F0 - 0x27FF. + * @since 1.5 + */ + public static final UnicodeBlock SUPPLEMENTAL_ARROWS_A + = new UnicodeBlock(0x27F0, 0x27FF, + "SUPPLEMENTAL_ARROWS_A", + "Supplemental Arrows-A"); + + /** + * Braille Patterns. + * 0x2800 - 0x28FF. + * @since 1.4 + */ + public static final UnicodeBlock BRAILLE_PATTERNS + = new UnicodeBlock(0x2800, 0x28FF, + "BRAILLE_PATTERNS", + "Braille Patterns"); + + /** + * Supplemental Arrows-B. + * 0x2900 - 0x297F. + * @since 1.5 + */ + public static final UnicodeBlock SUPPLEMENTAL_ARROWS_B + = new UnicodeBlock(0x2900, 0x297F, + "SUPPLEMENTAL_ARROWS_B", + "Supplemental Arrows-B"); + + /** + * Miscellaneous Mathematical Symbols-B. + * 0x2980 - 0x29FF. + * @since 1.5 + */ + public static final UnicodeBlock MISCELLANEOUS_MATHEMATICAL_SYMBOLS_B + = new UnicodeBlock(0x2980, 0x29FF, + "MISCELLANEOUS_MATHEMATICAL_SYMBOLS_B", + "Miscellaneous Mathematical Symbols-B"); + + /** + * Supplemental Mathematical Operators. + * 0x2A00 - 0x2AFF. + * @since 1.5 + */ + public static final UnicodeBlock SUPPLEMENTAL_MATHEMATICAL_OPERATORS + = new UnicodeBlock(0x2A00, 0x2AFF, + "SUPPLEMENTAL_MATHEMATICAL_OPERATORS", + "Supplemental Mathematical Operators"); + + /** + * Miscellaneous Symbols and Arrows. + * 0x2B00 - 0x2BFF. + * @since 1.5 + */ + public static final UnicodeBlock MISCELLANEOUS_SYMBOLS_AND_ARROWS + = new UnicodeBlock(0x2B00, 0x2BFF, + "MISCELLANEOUS_SYMBOLS_AND_ARROWS", + "Miscellaneous Symbols and Arrows"); + + /** + * CJK Radicals Supplement. + * 0x2E80 - 0x2EFF. + * @since 1.4 + */ + public static final UnicodeBlock CJK_RADICALS_SUPPLEMENT + = new UnicodeBlock(0x2E80, 0x2EFF, + "CJK_RADICALS_SUPPLEMENT", + "CJK Radicals Supplement"); + + /** + * Kangxi Radicals. + * 0x2F00 - 0x2FDF. + * @since 1.4 + */ + public static final UnicodeBlock KANGXI_RADICALS + = new UnicodeBlock(0x2F00, 0x2FDF, + "KANGXI_RADICALS", + "Kangxi Radicals"); + + /** + * Ideographic Description Characters. + * 0x2FF0 - 0x2FFF. + * @since 1.4 + */ + public static final UnicodeBlock IDEOGRAPHIC_DESCRIPTION_CHARACTERS + = new UnicodeBlock(0x2FF0, 0x2FFF, + "IDEOGRAPHIC_DESCRIPTION_CHARACTERS", + "Ideographic Description Characters"); + + /** + * CJK Symbols and Punctuation. + * 0x3000 - 0x303F. + */ + public static final UnicodeBlock CJK_SYMBOLS_AND_PUNCTUATION + = new UnicodeBlock(0x3000, 0x303F, + "CJK_SYMBOLS_AND_PUNCTUATION", + "CJK Symbols and Punctuation"); + + /** + * Hiragana. + * 0x3040 - 0x309F. + */ + public static final UnicodeBlock HIRAGANA + = new UnicodeBlock(0x3040, 0x309F, + "HIRAGANA", + "Hiragana"); + + /** + * Katakana. + * 0x30A0 - 0x30FF. + */ + public static final UnicodeBlock KATAKANA + = new UnicodeBlock(0x30A0, 0x30FF, + "KATAKANA", + "Katakana"); + + /** + * Bopomofo. + * 0x3100 - 0x312F. + */ + public static final UnicodeBlock BOPOMOFO + = new UnicodeBlock(0x3100, 0x312F, + "BOPOMOFO", + "Bopomofo"); + + /** + * Hangul Compatibility Jamo. + * 0x3130 - 0x318F. + */ + public static final UnicodeBlock HANGUL_COMPATIBILITY_JAMO + = new UnicodeBlock(0x3130, 0x318F, + "HANGUL_COMPATIBILITY_JAMO", + "Hangul Compatibility Jamo"); + + /** + * Kanbun. + * 0x3190 - 0x319F. + */ + public static final UnicodeBlock KANBUN + = new UnicodeBlock(0x3190, 0x319F, + "KANBUN", + "Kanbun"); + + /** + * Bopomofo Extended. + * 0x31A0 - 0x31BF. + * @since 1.4 + */ + public static final UnicodeBlock BOPOMOFO_EXTENDED + = new UnicodeBlock(0x31A0, 0x31BF, + "BOPOMOFO_EXTENDED", + "Bopomofo Extended"); + + /** + * Katakana Phonetic Extensions. + * 0x31F0 - 0x31FF. + * @since 1.5 + */ + public static final UnicodeBlock KATAKANA_PHONETIC_EXTENSIONS + = new UnicodeBlock(0x31F0, 0x31FF, + "KATAKANA_PHONETIC_EXTENSIONS", + "Katakana Phonetic Extensions"); + + /** + * Enclosed CJK Letters and Months. + * 0x3200 - 0x32FF. + */ + public static final UnicodeBlock ENCLOSED_CJK_LETTERS_AND_MONTHS + = new UnicodeBlock(0x3200, 0x32FF, + "ENCLOSED_CJK_LETTERS_AND_MONTHS", + "Enclosed CJK Letters and Months"); + + /** + * CJK Compatibility. + * 0x3300 - 0x33FF. + */ + public static final UnicodeBlock CJK_COMPATIBILITY + = new UnicodeBlock(0x3300, 0x33FF, + "CJK_COMPATIBILITY", + "CJK Compatibility"); + + /** + * CJK Unified Ideographs Extension A. + * 0x3400 - 0x4DBF. + * @since 1.4 + */ + public static final UnicodeBlock CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A + = new UnicodeBlock(0x3400, 0x4DBF, + "CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A", + "CJK Unified Ideographs Extension A"); + + /** + * Yijing Hexagram Symbols. + * 0x4DC0 - 0x4DFF. + * @since 1.5 + */ + public static final UnicodeBlock YIJING_HEXAGRAM_SYMBOLS + = new UnicodeBlock(0x4DC0, 0x4DFF, + "YIJING_HEXAGRAM_SYMBOLS", + "Yijing Hexagram Symbols"); + + /** + * CJK Unified Ideographs. + * 0x4E00 - 0x9FFF. + */ + public static final UnicodeBlock CJK_UNIFIED_IDEOGRAPHS + = new UnicodeBlock(0x4E00, 0x9FFF, + "CJK_UNIFIED_IDEOGRAPHS", + "CJK Unified Ideographs"); + + /** + * Yi Syllables. + * 0xA000 - 0xA48F. + * @since 1.4 + */ + public static final UnicodeBlock YI_SYLLABLES + = new UnicodeBlock(0xA000, 0xA48F, + "YI_SYLLABLES", + "Yi Syllables"); + + /** + * Yi Radicals. + * 0xA490 - 0xA4CF. + * @since 1.4 + */ + public static final UnicodeBlock YI_RADICALS + = new UnicodeBlock(0xA490, 0xA4CF, + "YI_RADICALS", + "Yi Radicals"); + + /** + * Hangul Syllables. + * 0xAC00 - 0xD7AF. + */ + public static final UnicodeBlock HANGUL_SYLLABLES + = new UnicodeBlock(0xAC00, 0xD7AF, + "HANGUL_SYLLABLES", + "Hangul Syllables"); + + /** + * High Surrogates. + * 0xD800 - 0xDB7F. + * @since 1.5 + */ + public static final UnicodeBlock HIGH_SURROGATES + = new UnicodeBlock(0xD800, 0xDB7F, + "HIGH_SURROGATES", + "High Surrogates"); + + /** + * High Private Use Surrogates. + * 0xDB80 - 0xDBFF. + * @since 1.5 + */ + public static final UnicodeBlock HIGH_PRIVATE_USE_SURROGATES + = new UnicodeBlock(0xDB80, 0xDBFF, + "HIGH_PRIVATE_USE_SURROGATES", + "High Private Use Surrogates"); + + /** + * Low Surrogates. + * 0xDC00 - 0xDFFF. + * @since 1.5 + */ + public static final UnicodeBlock LOW_SURROGATES + = new UnicodeBlock(0xDC00, 0xDFFF, + "LOW_SURROGATES", + "Low Surrogates"); + + /** + * Private Use Area. + * 0xE000 - 0xF8FF. + */ + public static final UnicodeBlock PRIVATE_USE_AREA + = new UnicodeBlock(0xE000, 0xF8FF, + "PRIVATE_USE_AREA", + "Private Use Area"); + + /** + * CJK Compatibility Ideographs. + * 0xF900 - 0xFAFF. + */ + public static final UnicodeBlock CJK_COMPATIBILITY_IDEOGRAPHS + = new UnicodeBlock(0xF900, 0xFAFF, + "CJK_COMPATIBILITY_IDEOGRAPHS", + "CJK Compatibility Ideographs"); + + /** + * Alphabetic Presentation Forms. + * 0xFB00 - 0xFB4F. + */ + public static final UnicodeBlock ALPHABETIC_PRESENTATION_FORMS + = new UnicodeBlock(0xFB00, 0xFB4F, + "ALPHABETIC_PRESENTATION_FORMS", + "Alphabetic Presentation Forms"); + + /** + * Arabic Presentation Forms-A. + * 0xFB50 - 0xFDFF. + */ + public static final UnicodeBlock ARABIC_PRESENTATION_FORMS_A + = new UnicodeBlock(0xFB50, 0xFDFF, + "ARABIC_PRESENTATION_FORMS_A", + "Arabic Presentation Forms-A"); + + /** + * Variation Selectors. + * 0xFE00 - 0xFE0F. + * @since 1.5 + */ + public static final UnicodeBlock VARIATION_SELECTORS + = new UnicodeBlock(0xFE00, 0xFE0F, + "VARIATION_SELECTORS", + "Variation Selectors"); + + /** + * Combining Half Marks. + * 0xFE20 - 0xFE2F. + */ + public static final UnicodeBlock COMBINING_HALF_MARKS + = new UnicodeBlock(0xFE20, 0xFE2F, + "COMBINING_HALF_MARKS", + "Combining Half Marks"); + + /** + * CJK Compatibility Forms. + * 0xFE30 - 0xFE4F. + */ + public static final UnicodeBlock CJK_COMPATIBILITY_FORMS + = new UnicodeBlock(0xFE30, 0xFE4F, + "CJK_COMPATIBILITY_FORMS", + "CJK Compatibility Forms"); + + /** + * Small Form Variants. + * 0xFE50 - 0xFE6F. + */ + public static final UnicodeBlock SMALL_FORM_VARIANTS + = new UnicodeBlock(0xFE50, 0xFE6F, + "SMALL_FORM_VARIANTS", + "Small Form Variants"); + + /** + * Arabic Presentation Forms-B. + * 0xFE70 - 0xFEFF. + */ + public static final UnicodeBlock ARABIC_PRESENTATION_FORMS_B + = new UnicodeBlock(0xFE70, 0xFEFF, + "ARABIC_PRESENTATION_FORMS_B", + "Arabic Presentation Forms-B"); + + /** + * Halfwidth and Fullwidth Forms. + * 0xFF00 - 0xFFEF. + */ + public static final UnicodeBlock HALFWIDTH_AND_FULLWIDTH_FORMS + = new UnicodeBlock(0xFF00, 0xFFEF, + "HALF... [truncated message content] |
From: <ls...@us...> - 2006-12-12 21:13:42
|
Revision: 2899 http://jnode.svn.sourceforge.net/jnode/?rev=2899&view=rev Author: lsantha Date: 2006-12-12 13:13:38 -0800 (Tue, 12 Dec 2006) Log Message: ----------- Migrating to Java 5 level classpath. Added Paths: ----------- trunk/core/src/classpath/java/java/lang/ref/ trunk/core/src/classpath/java/java/lang/ref/PhantomReference.java trunk/core/src/classpath/java/java/lang/ref/Reference.java trunk/core/src/classpath/java/java/lang/ref/ReferenceQueue.java trunk/core/src/classpath/java/java/lang/ref/SoftReference.java trunk/core/src/classpath/java/java/lang/ref/WeakReference.java trunk/core/src/classpath/java/java/lang/ref/package.html Added: trunk/core/src/classpath/java/java/lang/ref/PhantomReference.java =================================================================== --- trunk/core/src/classpath/java/java/lang/ref/PhantomReference.java (rev 0) +++ trunk/core/src/classpath/java/java/lang/ref/PhantomReference.java 2006-12-12 21:13:38 UTC (rev 2899) @@ -0,0 +1,73 @@ +/* java.lang.ref.PhantomReference + Copyright (C) 1999, 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.lang.ref; + +/** + * A phantom reference is useful, to get notified, when an object got + * finalized. You can't access that object though, since it is + * finalized. This is the reason, why <code>get()</code> always + * returns null. + * + * @author Jochen Hoenicke + */ +public class PhantomReference<T> + extends Reference<T> +{ + /** + * Creates a new phantom reference. + * @param referent the object that should be watched. + * @param q the queue that should be notified, if the referent was + * finalized. This mustn't be <code>null</code>. + * @exception NullPointerException if q is null. + */ + public PhantomReference(T referent, ReferenceQueue<? super T> q) + { + super(referent, q); + } + + /** + * Returns the object, this reference refers to. + * @return <code>null</code>, since the refered object may be + * finalized and thus not accessible. + */ + public T get() + { + return null; + } +} Added: trunk/core/src/classpath/java/java/lang/ref/Reference.java =================================================================== --- trunk/core/src/classpath/java/java/lang/ref/Reference.java (rev 0) +++ trunk/core/src/classpath/java/java/lang/ref/Reference.java 2006-12-12 21:13:38 UTC (rev 2899) @@ -0,0 +1,177 @@ +/* java.lang.ref.Reference + Copyright (C) 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.lang.ref; + +/** + * This is the base class of all references. A reference allows + * refering to an object without preventing the garbage collector to + * collect it. The only way to get the referred object is via the + * <code>get()</code>-method. This method will return + * <code>null</code> if the object was collected. <br> + * + * A reference may be registered with a queue. When a referred + * element gets collected the reference will be put on the queue, so + * that you will be notified. <br> + * + * There are currently three types of references: soft reference, + * weak reference and phantom reference. <br> + * + * Soft references will be cleared if the garbage collector is told + * to free some memory and there are no unreferenced or weakly referenced + * objects. It is useful for caches. <br> + * + * Weak references will be cleared as soon as the garbage collector + * determines that the refered object is only weakly reachable. They + * are useful as keys in hashtables (see <code>WeakHashtable</code>) as + * you get notified when nobody has the key anymore. + * + * Phantom references don't prevent finalization. If an object is only + * phantom reachable, it will be finalized, and the reference will be + * enqueued, but not cleared. Since you mustn't access an finalized + * object, the <code>get</code> method of a phantom reference will never + * work. It is useful to keep track, when an object is finalized. + * + * @author Jochen Hoenicke + * @see java.util.WeakHashMap + */ +public abstract class Reference<T> +{ + /** + * The underlying object. This field is handled in a special way by + * the garbage collector. + */ + T referent; + + /** + * The queue this reference is registered on. This is null, if this + * wasn't registered to any queue or reference was already enqueued. + */ + ReferenceQueue<? super T> queue; + + /** + * Link to the next entry on the queue. If this is null, this + * reference is not enqueued. Otherwise it points to the next + * reference. The last reference on a queue will point to itself + * (not to null, that value is used to mark a not enqueued + * reference). + */ + Reference nextOnQueue; + + /** + * This lock should be taken by the garbage collector, before + * determining reachability. It will prevent the get()-method to + * return the reference so that reachability doesn't change. + */ + static Object lock = new Object(); + + /** + * Creates a new reference that is not registered to any queue. + * Since it is package private, it is not possible to overload this + * class in a different package. + * @param ref the object we refer to. + */ + Reference(T ref) + { + referent = ref; + } + + /** + * Creates a reference that is registered to a queue. Since this is + * package private, it is not possible to overload this class in a + * different package. + * @param ref the object we refer to. + * @param q the reference queue to register on. + * @exception NullPointerException if q is null. + */ + Reference(T ref, ReferenceQueue<? super T> q) + { + if (q == null) + throw new NullPointerException(); + referent = ref; + queue = q; + } + + /** + * Returns the object, this reference refers to. + * @return the object, this reference refers to, or null if the + * reference was cleared. + */ + public T get() + { + synchronized (lock) + { + return referent; + } + } + + /** + * Clears the reference, so that it doesn't refer to its object + * anymore. For soft and weak references this is called by the + * garbage collector. For phantom references you should call + * this when enqueuing the reference. + */ + public void clear() + { + referent = null; + } + + /** + * Tells if the object is enqueued on a reference queue. + * @return true if it is enqueued, false otherwise. + */ + public boolean isEnqueued() + { + return nextOnQueue != null; + } + + /** + * Enqueue an object on a reference queue. This is normally executed + * by the garbage collector. + */ + public boolean enqueue() + { + if (queue != null && nextOnQueue == null) + { + queue.enqueue(this); + queue = null; + return true; + } + return false; + } +} Added: trunk/core/src/classpath/java/java/lang/ref/ReferenceQueue.java =================================================================== --- trunk/core/src/classpath/java/java/lang/ref/ReferenceQueue.java (rev 0) +++ trunk/core/src/classpath/java/java/lang/ref/ReferenceQueue.java 2006-12-12 21:13:38 UTC (rev 2899) @@ -0,0 +1,145 @@ +/* java.lang.ref.ReferenceQueue + Copyright (C) 1999, 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.lang.ref; + +/** + * This is the queue, where references can enqueue themselve on. Each + * reference may be registered to a queue at initialization time and + * will be appended to the queue, when the enqueue method is called. + * + * The enqueue method may be automatically called by the garbage + * collector if it detects, that the object is only reachable through + * the Reference objects. + * + * @author Jochen Hoenicke + * @see Reference#enqueue() + */ +public class ReferenceQueue<T> +{ + /** + * This is a linked list of references. If this is null, the list is + * empty. Otherwise this points to the first reference on the queue. + * The first reference will point to the next reference via the + * <code>nextOnQueue</code> field. The last reference will point to + * itself (not to null, since <code>nextOnQueue</code> is used to + * determine if a reference is enqueued). + */ + private Reference<? extends T> first; + + /** + * Creates a new empty reference queue. + */ + public ReferenceQueue() + { + } + + /** + * Checks if there is a reference on the queue, returning it + * immediately. The reference will be dequeued. + * + * @return a reference on the queue, if there is one, + * <code>null</code> otherwise. + */ + public synchronized Reference<? extends T> poll() + { + return dequeue(); + } + + /** + * This is called by reference to enqueue itself on this queue. + * @param ref the reference that should be enqueued. + */ + synchronized void enqueue(Reference<? extends T> ref) + { + /* last reference will point to itself */ + ref.nextOnQueue = first == null ? ref : first; + first = ref; + /* this wakes only one remove thread. */ + notify(); + } + + /** + * Remove a reference from the queue, if there is one. + * @return the first element of the queue, or null if there isn't any. + */ + private Reference<? extends T> dequeue() + { + if (first == null) + return null; + + Reference<? extends T> result = first; + first = (first == first.nextOnQueue) ? null : first.nextOnQueue; + result.nextOnQueue = null; + return result; + } + + /** + * Removes a reference from the queue, blocking for <code>timeout</code> + * until a reference is enqueued. + * @param timeout the timeout period in milliseconds, <code>0</code> means + * wait forever. + * @return the reference removed from the queue, or + * <code>null</code> if timeout period expired. + * @exception InterruptedException if the wait was interrupted. + */ + public synchronized Reference<? extends T> remove(long timeout) + throws InterruptedException + { + if (first == null) + { + wait(timeout); + } + + return dequeue(); + } + + + /** + * Removes a reference from the queue, blocking until a reference is + * enqueued. + * + * @return the reference removed from the queue. + * @exception InterruptedException if the wait was interrupted. + */ + public Reference<? extends T> remove() + throws InterruptedException + { + return remove(0L); + } +} Added: trunk/core/src/classpath/java/java/lang/ref/SoftReference.java =================================================================== --- trunk/core/src/classpath/java/java/lang/ref/SoftReference.java (rev 0) +++ trunk/core/src/classpath/java/java/lang/ref/SoftReference.java 2006-12-12 21:13:38 UTC (rev 2899) @@ -0,0 +1,84 @@ +/* java.lang.ref.SoftReference + Copyright (C) 1999, 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.lang.ref; + +/** + * A soft reference will be cleared, if the object is only softly + * reachable and the garbage collection needs more memory. The garbage + * collection will use an intelligent strategy to determine which soft + * references it should clear. This makes a soft reference ideal for + * caches.<br> + * + * @author Jochen Hoenicke + */ +public class SoftReference<T> + extends Reference<T> +{ + /** + * Create a new soft reference, that is not registered to any queue. + * @param referent the object we refer to. + */ + public SoftReference(T referent) + { + super(referent); + } + + /** + * Create a new soft reference. + * @param referent the object we refer to. + * @param q the reference queue to register on. + * @exception NullPointerException if q is null. + */ + public SoftReference(T referent, ReferenceQueue<? super T> q) + { + super(referent, q); + } + + /** + * Returns the object, this reference refers to. + * @return the object, this reference refers to, or null if the + * reference was cleared. + */ + public T get() + { + /* Why is this overloaded??? + * Maybe for a kind of LRU strategy. */ + return super.get(); + } +} Added: trunk/core/src/classpath/java/java/lang/ref/WeakReference.java =================================================================== --- trunk/core/src/classpath/java/java/lang/ref/WeakReference.java (rev 0) +++ trunk/core/src/classpath/java/java/lang/ref/WeakReference.java 2006-12-12 21:13:38 UTC (rev 2899) @@ -0,0 +1,79 @@ +/* java.lang.ref.WeakReference + Copyright (C) 1999, 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.lang.ref; + +/** + * A weak reference will be cleared, if the object is only weakly + * reachable. It is useful for lookup tables, where you aren't + * interested in an entry, if the key isn't reachable anymore. + * <code>WeakHashtable</code> is a complete implementation of such a + * table. <br> + * + * It is also useful to make objects unique: You create a set of weak + * references to those objects, and when you create a new object you + * look in this set, if the object already exists and return it. If + * an object is not referenced anymore, the reference will + * automatically cleared, and you may remove it from the set. <br> + * + * @author Jochen Hoenicke + * @see java.util.WeakHashMap + */ +public class WeakReference<T> + extends Reference<T> +{ + /** + * Create a new weak reference, that is not registered to any queue. + * @param referent the object we refer to. + */ + public WeakReference(T referent) + { + super(referent); + } + + /** + * Create a new weak reference. + * @param referent the object we refer to. + * @param q the reference queue to register on. + * @exception NullPointerException if q is null. + */ + public WeakReference(T referent, ReferenceQueue<? super T> q) + { + super(referent, q); + } +} Added: trunk/core/src/classpath/java/java/lang/ref/package.html =================================================================== --- trunk/core/src/classpath/java/java/lang/ref/package.html (rev 0) +++ trunk/core/src/classpath/java/java/lang/ref/package.html 2006-12-12 21:13:38 UTC (rev 2899) @@ -0,0 +1,46 @@ +<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN"> +<!-- package.html - describes classes in java.lang.ref 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.lang.ref</title></head> + +<body> +<p>Low level manipulation and monitoring of object references.</p> + +</body> +</html> This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <ls...@us...> - 2006-12-12 21:13:11
|
Revision: 2898 http://jnode.svn.sourceforge.net/jnode/?rev=2898&view=rev Author: lsantha Date: 2006-12-12 13:13:08 -0800 (Tue, 12 Dec 2006) Log Message: ----------- Migrating to Java 5 level classpath. Added Paths: ----------- trunk/core/src/classpath/java/java/lang/annotation/ trunk/core/src/classpath/java/java/lang/annotation/Annotation.java trunk/core/src/classpath/java/java/lang/annotation/AnnotationFormatError.java trunk/core/src/classpath/java/java/lang/annotation/AnnotationTypeMismatchException.java trunk/core/src/classpath/java/java/lang/annotation/Documented.java trunk/core/src/classpath/java/java/lang/annotation/ElementType.java trunk/core/src/classpath/java/java/lang/annotation/IncompleteAnnotationException.java trunk/core/src/classpath/java/java/lang/annotation/Inherited.java trunk/core/src/classpath/java/java/lang/annotation/Retention.java trunk/core/src/classpath/java/java/lang/annotation/RetentionPolicy.java trunk/core/src/classpath/java/java/lang/annotation/Target.java trunk/core/src/classpath/java/java/lang/annotation/package.html Added: trunk/core/src/classpath/java/java/lang/annotation/Annotation.java =================================================================== --- trunk/core/src/classpath/java/java/lang/annotation/Annotation.java (rev 0) +++ trunk/core/src/classpath/java/java/lang/annotation/Annotation.java 2006-12-12 21:13:08 UTC (rev 2898) @@ -0,0 +1,135 @@ +/* Annotation.java - Base interface for all annotations + Copyright (C) 2004 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.lang.annotation; + +/** + * This is the common interface for all annotations. Note that classes + * that implement this class manually are not classed as annotations, and + * that this interface does not define an annotation type in itself. + * + * @author Tom Tromey (tr...@re...) + * @author Andrew John Hughes (gnu...@me...) + * @since 1.5 + */ +public interface Annotation +{ + + /** + * Returns the type of this annotation. + * + * @return the class of which this annotation is an instance. + */ + Class<? extends Annotation> annotationType(); + + /** + * <p> + * Returns true if the supplied object is equivalent to this annotation. + * For this property to hold, the following must be true of <code>o</code>: + * </p> + * <ul> + * <li>The object is also an instance of the same annotation type.</li> + * <li>The members of the supplied annotation are equal to those of this + * annotation, according to the following: + * <ul> + * <li>If the members are <code>float</code>s, then, for floats + * <code>x</code> and <code>y</code>, + * <code>Float.valueOf(x).equals(Float.valueOf(y)</code> must return + * true. This differs from the usual (<code>==</code>) comparison + * in that <code>NaN</code> is considered equal to itself and positive + * and negative zero are seen as different.</li> + * <li>Likewise, if the members are <code>double</code>s, then, for doubles + * <code>x</code> and <code>y</code>, + * <code>Double.valueOf(x).equals(Double.valueOf(y)</code> must return + * true. This differs from the usual (<code>==</code>) comparison + * in that <code>NaN</code> is considered equal to itself and positive + * and negative zero are seen as different.</li> + * <li>Strings, classes, enumerations and annotations are considered + * equal according to the <code>equals()</code> implementation for these + * types.</li> + * <li>Arrays are considered equal according to <code>Arrays.equals()</code> + * </li> + * <li>Any remaining types are considered equal using <code>==</code>.</li> + * </li> + * </ul> + * + * @param o the object to compare with this annotation. + * @return true if the supplied object is an annotation with equivalent + * members. + */ + boolean equals(Object o); + + /** + * <p> + * Returns the hash code of the annotation. This is computed as the + * sum of the hash codes of the annotation's members. + * </p> + * <p> + * The hash code of a member of the annotation is the result of XORing + * the hash code of its value with the result of multiplying the hash code + * of its name by 127. Formally, if the value is <code>v</code> and the + * name is <code>n</code>, the hash code of the member is + * v.hashCode() XOR (127 * String.hashCode(n)). <code>v.hashCode()</code> + * is defined as follows: + * </p> + * <ul> + * <li>The hash code of a primitive value (i.e. <code>byte</code>, + * <code>char</code>, <code>double</code>, <code>float</code>, + * <code>int</code>, <code>long</code>, <code>short</code> and + * <code>boolean</code>) is the hash code obtained from its corresponding + * wrapper class using <code>valueOf(v).hashCode()</code>, where + * <code>v</code> is the primitive value.</li> + * <li>The hash code of an enumeration, string, class or other annotation + * is obtained using <code>v.hashCode()</code>.</li> + * <li>The hash code of an array is computed using + * <code>Arrays.hashCode(v)</code>.</li> + * </ul> + * + * @return the hash code of the annotation, computed as the sum of its + * member hashcodes. + */ + int hashCode(); + + /** + * Returns a textual representation of the annotation. This is + * implementation-dependent, but is expected to include the classname + * and the names and values of each member. + * + * @return a textual representation of the annotation. + */ + String toString(); +} Added: trunk/core/src/classpath/java/java/lang/annotation/AnnotationFormatError.java =================================================================== --- trunk/core/src/classpath/java/java/lang/annotation/AnnotationFormatError.java (rev 0) +++ trunk/core/src/classpath/java/java/lang/annotation/AnnotationFormatError.java 2006-12-12 21:13:08 UTC (rev 2898) @@ -0,0 +1,105 @@ +/* AnnotationFormatError.java - Thrown when an binary annotation is malformed + Copyright (C) 2004, 2005 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.lang.annotation; + +/** + * Thrown when an annotation found in a class file is + * malformed. When the virtual machine finds a class file + * containing annotations, it attempts to parse them. + * This error is thrown if this operation fails. + * + * @author Tom Tromey (tr...@re...) + * @author Andrew John Hughes (gnu...@me...) + * @since 1.5 + */ +public class AnnotationFormatError extends Error +{ + private static final long serialVersionUID = -4256701562333669892L; + + /** + * Constructs a new <code>AnnotationFormatError</code> + * using the specified message to give details of the error. + * + * @param message the message to use in the error output. + */ + public AnnotationFormatError(String message) + { + super(message); + } + + /** + * <p> + * Constructs a new <code>AnnotationFormatError</code> + * using the specified message to give details of the error. + * The supplied cause <code>Throwable</code> is used to + * provide additional history, with regards to the root + * of the problem. It is perfectly valid for this to be null, if + * the cause is unknown. + * </p> + * <p> + * <strong>Note</strong>: if a cause is supplied, the error + * message from this cause is not automatically included in the + * error message given by this error. + * </p> + * + * @param message the message to use in the error output + * @param cause the cause of this error, or null if the cause + * is unknown. + */ + public AnnotationFormatError(String message, Throwable cause) + { + super(message, cause); + } + + /** + * Constructs a new <code>AnnotationFormatError</code> using + * the supplied cause <code>Throwable</code> to + * provide additional history, with regards to the root + * of the problem. It is perfectly valid for this to be null, if + * the cause is unknown. If the cause is not null, the error + * message from this cause will also be used as the message + * for this error. + * + * @param cause the cause of the error. + */ + public AnnotationFormatError(Throwable cause) + { + super(cause); + } + +} Added: trunk/core/src/classpath/java/java/lang/annotation/AnnotationTypeMismatchException.java =================================================================== --- trunk/core/src/classpath/java/java/lang/annotation/AnnotationTypeMismatchException.java (rev 0) +++ trunk/core/src/classpath/java/java/lang/annotation/AnnotationTypeMismatchException.java 2006-12-12 21:13:08 UTC (rev 2898) @@ -0,0 +1,116 @@ +/* AnnotationTypeMismatchException.java - Thrown when annotation has changed + Copyright (C) 2004, 2005 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.lang.annotation; + +import java.lang.reflect.Method; + +/** + * Thrown when accessing an element within an annotation for + * which the type has changed, since compilation or serialization + * took place. The mismatch between the compiled or serialized + * type and the current type causes this exception to be thrown. + * + * @author Tom Tromey (tr...@re...) + * @author Andrew John Hughes (gnu...@me...) + * @since 1.5 + */ +public class AnnotationTypeMismatchException extends RuntimeException +{ + + /** + * For compatability with Sun's JDK + */ + private static final long serialVersionUID = 8125925355765570191L; + + /** + * Constructs an <code>AnnotationTypeMismatchException</code> + * which is due to a mismatched type in the annotation + * element, <code>m</code>. The erroneous type used for the + * data in <code>m</code> is represented by the string, + * <code>type</code>. This string is of an undefined format, + * and may contain the value as well as the type. + * + * @param m the element from the annotation. + * @param type the name of the erroneous type found in <code>m</code>. + */ + public AnnotationTypeMismatchException(Method m, String type) + { + this.element = m; + this.foundType = type; + } + + /** + * Returns the element from the annotation, for which a + * mismatch occurred. + * + * @return the element with the mismatched type. + */ + public Method element() + { + return element; + } + + /** + * Returns the erroneous type used by the element, + * represented as a <code>String</code>. The format + * of this <code>String</code> is not explicitly specified, + * and may contain the value as well as the type. + * + * @return the type found in the element. + */ + public String foundType() + { + return foundType; + } + + // Names are chosen from serialization spec. + /** + * The element from the annotation. + * + * @serial the element with the mismatched type. + */ + private Method element; + + /** + * The erroneous type used by the element. + * + * @serial the type found in the element. + */ + private String foundType; + +} Added: trunk/core/src/classpath/java/java/lang/annotation/Documented.java =================================================================== --- trunk/core/src/classpath/java/java/lang/annotation/Documented.java (rev 0) +++ trunk/core/src/classpath/java/java/lang/annotation/Documented.java 2006-12-12 21:13:08 UTC (rev 2898) @@ -0,0 +1,50 @@ +/* Documented.java - Indicates documented source element + Copyright (C) 2004, 2005 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.lang.annotation; + +import static java.lang.annotation.RetentionPolicy.RUNTIME; + +/** + * @author Tom Tromey (tr...@re...) + * @author Andrew John Hughes (gnu...@me...) + * @since 1.5 + */ +@Documented @Retention(RUNTIME) +public @interface Documented +{ +} Added: trunk/core/src/classpath/java/java/lang/annotation/ElementType.java =================================================================== --- trunk/core/src/classpath/java/java/lang/annotation/ElementType.java (rev 0) +++ trunk/core/src/classpath/java/java/lang/annotation/ElementType.java 2006-12-12 21:13:08 UTC (rev 2898) @@ -0,0 +1,59 @@ +/* ElementType.java - Enum listing Java source elements + Copyright (C) 2004 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.lang.annotation; + +/** + * @since 1.5 + */ +public enum ElementType +{ + ANNOTATION_TYPE, + CONSTRUCTOR, + FIELD, + LOCAL_VARIABLE, + METHOD, + PACKAGE, + PARAMETER, + TYPE; + + /** + * For compatability with Sun's JDK + */ + private static final long serialVersionUID = 2798216111136361587L; + +} Added: trunk/core/src/classpath/java/java/lang/annotation/IncompleteAnnotationException.java =================================================================== --- trunk/core/src/classpath/java/java/lang/annotation/IncompleteAnnotationException.java (rev 0) +++ trunk/core/src/classpath/java/java/lang/annotation/IncompleteAnnotationException.java 2006-12-12 21:13:08 UTC (rev 2898) @@ -0,0 +1,107 @@ +/* IncompleteAnnotationException.java - Thrown when annotation has changed + Copyright (C) 2004 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.lang.annotation; + +/** + * Thrown when accessing an element within an annotation which + * was added since compilation or serialization took place, and + * does not have a default value. + * + * @author Tom Tromey (tr...@re...) + * @author Andrew John Hughes (gnu...@me...) + * @since 1.5 + */ +public class IncompleteAnnotationException extends RuntimeException +{ + + /** + * Constructs a new <code>IncompleteAnnotationException</code> + * which indicates that the element, <code>name</code>, was missing + * from the annotation, <code>type</code> at compile time and does + * not have a default value. + * + * @param type the type of annotation from which an element is missing. + * @param name the name of the missing element. + */ + public IncompleteAnnotationException(Class<? extends Annotation> type, + String name) + { + this.annotationType = type; + this.elementName = name; + } + + /** + * Returns the class representing the type of annotation + * from which an element was missing. + * + * @return the type of annotation. + */ + public Class<? extends Annotation> annotationType() + { + return annotationType; + } + + /** + * Returns the name of the missing annotation element. + * + * @return the element name. + */ + public String elementName() + { + return elementName; + } + + // Names are chosen from serialization spec. + + /** + * The class representing the type of annotation from + * which an element was found to be missing. + * + * @serial the type of the annotation from which an + * element was missing. + */ + private Class<? extends Annotation> annotationType; + + /** + * The name of the missing element. + * + * @serial the name of the missing element. + */ + private String elementName; + +} Added: trunk/core/src/classpath/java/java/lang/annotation/Inherited.java =================================================================== --- trunk/core/src/classpath/java/java/lang/annotation/Inherited.java (rev 0) +++ trunk/core/src/classpath/java/java/lang/annotation/Inherited.java 2006-12-12 21:13:08 UTC (rev 2898) @@ -0,0 +1,51 @@ +/* Inherited.java - Indicates inherited annotation + Copyright (C) 2004, 2005 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.lang.annotation; + +import static java.lang.annotation.RetentionPolicy.RUNTIME; +import static java.lang.annotation.ElementType.ANNOTATION_TYPE; + +/** + * @author Tom Tromey (tr...@re...) + * @author Andrew John Hughes (gnu...@me...) + * @since 1.5 + */ +@Documented @Retention(RUNTIME) @Target(ANNOTATION_TYPE) +public @interface Inherited +{ +} Added: trunk/core/src/classpath/java/java/lang/annotation/Retention.java =================================================================== --- trunk/core/src/classpath/java/java/lang/annotation/Retention.java (rev 0) +++ trunk/core/src/classpath/java/java/lang/annotation/Retention.java 2006-12-12 21:13:08 UTC (rev 2898) @@ -0,0 +1,59 @@ +/* Retention.java - Retention policy for an annotation + Copyright (C) 2004, 2005 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.lang.annotation; + +import static java.lang.annotation.RetentionPolicy.RUNTIME; +import static java.lang.annotation.ElementType.ANNOTATION_TYPE; + +/** + * This annotation is used to specify the desired lifetime of another + * annotation. + * + * @author Tom Tromey (tr...@re...) + * @author Andrew John Hughes (gnu...@me...) + * @see RetentionPolicy + * @since 1.5 + */ +@Documented @Retention(RUNTIME) @Target(ANNOTATION_TYPE) +public @interface Retention +{ + /** + * The value holds the lifetime of the annotation. + */ + RetentionPolicy value(); +} Added: trunk/core/src/classpath/java/java/lang/annotation/RetentionPolicy.java =================================================================== --- trunk/core/src/classpath/java/java/lang/annotation/RetentionPolicy.java (rev 0) +++ trunk/core/src/classpath/java/java/lang/annotation/RetentionPolicy.java 2006-12-12 21:13:08 UTC (rev 2898) @@ -0,0 +1,66 @@ +/* RetentionPolicy.java - Enum listing lifetimes for an annotation + Copyright (C) 2004 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.lang.annotation; + +/** + * This enum is used to control the lifetime of an annotation. + * + * @see Retention + * + * @since 1.5 + */ +public enum RetentionPolicy +{ + /** Indicates that the annotation should be stored in class files. */ + CLASS, + + /** Indicates that the annotation should be available at runtime. */ + RUNTIME, + + /** + * Indicates that the annotation should only be available when + * parsing the source code. + */ + SOURCE; + + /** + * For compatability with Sun's JDK + */ + private static final long serialVersionUID = -1700821648800605045L; + +} Added: trunk/core/src/classpath/java/java/lang/annotation/Target.java =================================================================== --- trunk/core/src/classpath/java/java/lang/annotation/Target.java (rev 0) +++ trunk/core/src/classpath/java/java/lang/annotation/Target.java 2006-12-12 21:13:08 UTC (rev 2898) @@ -0,0 +1,52 @@ +/* Target.java - Indicate where an annotation may be applied + Copyright (C) 2004, 2005 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.lang.annotation; + +import static java.lang.annotation.RetentionPolicy.RUNTIME; +import static java.lang.annotation.ElementType.ANNOTATION_TYPE; + +/** + * @author Tom Tromey (tr...@re...) + * @author Andrew John Hughes (gnu...@me...) + * @since 1.5 + */ +@Documented @Retention(RUNTIME) @Target(ANNOTATION_TYPE) +public @interface Target +{ + ElementType[] value(); +} Added: trunk/core/src/classpath/java/java/lang/annotation/package.html =================================================================== --- trunk/core/src/classpath/java/java/lang/annotation/package.html (rev 0) +++ trunk/core/src/classpath/java/java/lang/annotation/package.html 2006-12-12 21:13:08 UTC (rev 2898) @@ -0,0 +1,46 @@ +<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN"> +<!-- package.html - describes classes in java.lang.annotation package. + Copyright (C) 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. --> + +<html> +<head><title>GNU Classpath - java.lang.annotation</title></head> + +<body> +<p>Classes to handle annotations.</p> + +</body> +</html> This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <ls...@us...> - 2006-12-12 21:12:31
|
Revision: 2897 http://jnode.svn.sourceforge.net/jnode/?rev=2897&view=rev Author: lsantha Date: 2006-12-12 13:12:29 -0800 (Tue, 12 Dec 2006) Log Message: ----------- Migrating to Java 5 level classpath. Added Paths: ----------- trunk/core/src/classpath/java/java/util/AbstractCollection.java trunk/core/src/classpath/java/java/util/AbstractList.java trunk/core/src/classpath/java/java/util/AbstractMap.java trunk/core/src/classpath/java/java/util/AbstractQueue.java trunk/core/src/classpath/java/java/util/AbstractSequentialList.java trunk/core/src/classpath/java/java/util/AbstractSet.java trunk/core/src/classpath/java/java/util/ArrayList.java trunk/core/src/classpath/java/java/util/Arrays.java trunk/core/src/classpath/java/java/util/BitSet.java trunk/core/src/classpath/java/java/util/Collection.java trunk/core/src/classpath/java/java/util/Collections.java trunk/core/src/classpath/java/java/util/Comparator.java trunk/core/src/classpath/java/java/util/Dictionary.java trunk/core/src/classpath/java/java/util/DuplicateFormatFlagsException.java trunk/core/src/classpath/java/java/util/EnumMap.java trunk/core/src/classpath/java/java/util/EnumSet.java trunk/core/src/classpath/java/java/util/Enumeration.java trunk/core/src/classpath/java/java/util/FormatFlagsConversionMismatchException.java trunk/core/src/classpath/java/java/util/Formattable.java trunk/core/src/classpath/java/java/util/FormattableFlags.java trunk/core/src/classpath/java/java/util/Formatter.java trunk/core/src/classpath/java/java/util/FormatterClosedException.java trunk/core/src/classpath/java/java/util/HashMap.java trunk/core/src/classpath/java/java/util/HashSet.java trunk/core/src/classpath/java/java/util/Hashtable.java trunk/core/src/classpath/java/java/util/IdentityHashMap.java trunk/core/src/classpath/java/java/util/IllegalFormatCodePointException.java trunk/core/src/classpath/java/java/util/IllegalFormatConversionException.java trunk/core/src/classpath/java/java/util/IllegalFormatException.java trunk/core/src/classpath/java/java/util/IllegalFormatFlagsException.java trunk/core/src/classpath/java/java/util/IllegalFormatPrecisionException.java trunk/core/src/classpath/java/java/util/IllegalFormatWidthException.java trunk/core/src/classpath/java/java/util/Iterator.java trunk/core/src/classpath/java/java/util/LinkedHashMap.java trunk/core/src/classpath/java/java/util/LinkedHashSet.java trunk/core/src/classpath/java/java/util/LinkedList.java trunk/core/src/classpath/java/java/util/List.java trunk/core/src/classpath/java/java/util/ListIterator.java trunk/core/src/classpath/java/java/util/Map.java trunk/core/src/classpath/java/java/util/MissingFormatArgumentException.java trunk/core/src/classpath/java/java/util/MissingFormatWidthException.java trunk/core/src/classpath/java/java/util/PriorityQueue.java trunk/core/src/classpath/java/java/util/Properties.java trunk/core/src/classpath/java/java/util/Queue.java trunk/core/src/classpath/java/java/util/Set.java trunk/core/src/classpath/java/java/util/SortedMap.java trunk/core/src/classpath/java/java/util/SortedSet.java trunk/core/src/classpath/java/java/util/Stack.java trunk/core/src/classpath/java/java/util/TreeMap.java trunk/core/src/classpath/java/java/util/TreeSet.java trunk/core/src/classpath/java/java/util/UnknownFormatConversionException.java trunk/core/src/classpath/java/java/util/UnknownFormatFlagsException.java trunk/core/src/classpath/java/java/util/Vector.java trunk/core/src/classpath/java/java/util/WeakHashMap.java Added: trunk/core/src/classpath/java/java/util/AbstractCollection.java =================================================================== --- trunk/core/src/classpath/java/java/util/AbstractCollection.java (rev 0) +++ trunk/core/src/classpath/java/java/util/AbstractCollection.java 2006-12-12 21:12:29 UTC (rev 2897) @@ -0,0 +1,490 @@ +/* AbstractCollection.java -- Abstract implementation of most of Collection + Copyright (C) 1998, 2000, 2001, 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.util; + +import java.lang.reflect.Array; + +/** + * A basic implementation of most of the methods in the Collection interface to + * make it easier to create a collection. To create an unmodifiable Collection, + * just subclass AbstractCollection and provide implementations of the + * iterator() and size() methods. The Iterator returned by iterator() need only + * provide implementations of hasNext() and next() (that is, it may throw an + * UnsupportedOperationException if remove() is called). To create a modifiable + * Collection, you must in addition provide an implementation of the + * add(Object) method and the Iterator returned by iterator() must provide an + * implementation of remove(). Other methods should be overridden if the + * backing data structure allows for a more efficient implementation. The + * precise implementation used by AbstractCollection is documented, so that + * subclasses can tell which methods could be implemented more efficiently. + * <p> + * + * The programmer should provide a no-argument constructor, and one that + * accepts another Collection, as recommended by the Collection interface. + * Unfortunately, there is no way to enforce this in Java. + * + * @author Original author unknown + * @author Bryce McKinlay + * @author Eric Blake (eb...@em...) + * @author Tom Tromey (tr...@re...) + * @author Andrew John Hughes (gnu...@me...) + * @see Collection + * @see AbstractSet + * @see AbstractList + * @since 1.2 + * @status updated to 1.4 + */ +public abstract class AbstractCollection<E> + implements Collection<E>, Iterable<E> +{ + /** + * The main constructor, for use by subclasses. + */ + protected AbstractCollection() + { + } + + /** + * Return an Iterator over this collection. The iterator must provide the + * hasNext and next methods and should in addition provide remove if the + * collection is modifiable. + * + * @return an iterator + */ + public abstract Iterator<E> iterator(); + + /** + * Return the number of elements in this collection. If there are more than + * Integer.MAX_VALUE elements, return Integer.MAX_VALUE. + * + * @return the size + */ + public abstract int size(); + + /** + * Add an object to the collection (optional operation). This implementation + * always throws an UnsupportedOperationException - it should be + * overridden if the collection is to be modifiable. If the collection + * does not accept duplicates, simply return false. Collections may specify + * limitations on what may be added. + * + * @param o the object to add + * @return true if the add operation caused the Collection to change + * @throws UnsupportedOperationException if the add operation is not + * supported on this collection + * @throws NullPointerException if the collection does not support null + * @throws ClassCastException if the object is of the wrong type + * @throws IllegalArgumentException if some aspect of the object prevents + * it from being added + */ + public boolean add(E o) + { + throw new UnsupportedOperationException(); + } + + /** + * Add all the elements of a given collection to this collection (optional + * operation). This implementation obtains an Iterator over the given + * collection and iterates over it, adding each element with the + * add(Object) method (thus this method will fail with an + * UnsupportedOperationException if the add method does). The behavior is + * unspecified if the specified collection is modified during the iteration, + * including the special case of trying addAll(this) on a non-empty + * collection. + * + * @param c the collection to add the elements of to this collection + * @return true if the add operation caused the Collection to change + * @throws UnsupportedOperationException if the add operation is not + * supported on this collection + * @throws NullPointerException if the specified collection is null + * @throws ClassCastException if the type of any element in c is + * not a valid type for addition. + * @throws IllegalArgumentException if some aspect of any element + * in c prevents it being added. + * @throws NullPointerException if any element in c is null and this + * collection doesn't allow null values. + * @see #add(Object) + */ + public boolean addAll(Collection<? extends E> c) + { + Iterator<? extends E> itr = c.iterator(); + boolean modified = false; + int pos = c.size(); + while (--pos >= 0) + modified |= add(itr.next()); + return modified; + } + + /** + * Remove all elements from the collection (optional operation). This + * implementation obtains an iterator over the collection and calls next + * and remove on it repeatedly (thus this method will fail with an + * UnsupportedOperationException if the Iterator's remove method does) + * until there are no more elements to remove. + * Many implementations will have a faster way of doing this. + * + * @throws UnsupportedOperationException if the Iterator returned by + * iterator does not provide an implementation of remove + * @see Iterator#remove() + */ + public void clear() + { + Iterator<E> itr = iterator(); + int pos = size(); + while (--pos >= 0) + { + itr.next(); + itr.remove(); + } + } + + /** + * Test whether this collection contains a given object. That is, if the + * collection has an element e such that (o == null ? e == null : + * o.equals(e)). This implementation obtains an iterator over the collection + * and iterates over it, testing each element for equality with the given + * object. If it is equal, true is returned. Otherwise false is returned when + * the end of the collection is reached. + * + * @param o the object to remove from this collection + * @return true if this collection contains an object equal to o + */ + public boolean contains(Object o) + { + Iterator<E> itr = iterator(); + int pos = size(); + while (--pos >= 0) + if (equals(o, itr.next())) + return true; + return false; + } + + /** + * Tests whether this collection contains all the elements in a given + * collection. This implementation iterates over the given collection, + * testing whether each element is contained in this collection. If any one + * is not, false is returned. Otherwise true is returned. + * + * @param c the collection to test against + * @return true if this collection contains all the elements in the given + * collection + * @throws NullPointerException if the given collection is null + * @see #contains(Object) + */ + public boolean containsAll(Collection<?> c) + { + Iterator<?> itr = c.iterator(); + int pos = c.size(); + while (--pos >= 0) + if (!contains(itr.next())) + return false; + return true; + } + + /** + * Test whether this collection is empty. This implementation returns + * size() == 0. + * + * @return true if this collection is empty. + * @see #size() + */ + public boolean isEmpty() + { + return size() == 0; + } + + /** + * Remove a single instance of an object from this collection (optional + * operation). That is, remove one element e such that + * <code>(o == null ? e == null : o.equals(e))</code>, if such an element + * exists. This implementation obtains an iterator over the collection + * and iterates over it, testing each element for equality with the given + * object. If it is equal, it is removed by the iterator's remove method + * (thus this method will fail with an UnsupportedOperationException if + * the Iterator's remove method does). After the first element has been + * removed, true is returned; if the end of the collection is reached, false + * is returned. + * + * @param o the object to remove from this collection + * @return true if the remove operation caused the Collection to change, or + * equivalently if the collection did contain o. + * @throws UnsupportedOperationException if this collection's Iterator + * does not support the remove method + * @see Iterator#remove() + */ + public boolean remove(Object o) + { + Iterator<E> itr = iterator(); + int pos = size(); + while (--pos >= 0) + if (equals(o, itr.next())) + { + itr.remove(); + return true; + } + return false; + } + + /** + * Remove from this collection all its elements that are contained in a given + * collection (optional operation). This implementation iterates over this + * collection, and for each element tests if it is contained in the given + * collection. If so, it is removed by the Iterator's remove method (thus + * this method will fail with an UnsupportedOperationException if the + * Iterator's remove method does). + * + * @param c the collection to remove the elements of + * @return true if the remove operation caused the Collection to change + * @throws UnsupportedOperationException if this collection's Iterator + * does not support the remove method + * @throws NullPointerException if the collection, c, is null. + * @see Iterator#remove() + */ + public boolean removeAll(Collection<?> c) + { + return removeAllInternal(c); + } + + /** + * Remove from this collection all its elements that are contained in a given + * collection (optional operation). This implementation iterates over this + * collection, and for each element tests if it is contained in the given + * collection. If so, it is removed by the Iterator's remove method (thus + * this method will fail with an UnsupportedOperationException if the + * Iterator's remove method does). This method is necessary for ArrayList, + * which cannot publicly override removeAll but can optimize this call. + * + * @param c the collection to remove the elements of + * @return true if the remove operation caused the Collection to change + * @throws UnsupportedOperationException if this collection's Iterator + * does not support the remove method + * @throws NullPointerException if the collection, c, is null. + * @see Iterator#remove() + */ + // Package visible for use throughout java.util. + boolean removeAllInternal(Collection<?> c) + { + Iterator<E> itr = iterator(); + boolean modified = false; + int pos = size(); + while (--pos >= 0) + if (c.contains(itr.next())) + { + itr.remove(); + modified = true; + } + return modified; + } + + /** + * Remove from this collection all its elements that are not contained in a + * given collection (optional operation). This implementation iterates over + * this collection, and for each element tests if it is contained in the + * given collection. If not, it is removed by the Iterator's remove method + * (thus this method will fail with an UnsupportedOperationException if + * the Iterator's remove method does). + * + * @param c the collection to retain the elements of + * @return true if the remove operation caused the Collection to change + * @throws UnsupportedOperationException if this collection's Iterator + * does not support the remove method + * @throws NullPointerException if the collection, c, is null. + * @see Iterator#remove() + */ + public boolean retainAll(Collection<?> c) + { + return retainAllInternal(c); + } + + /** + * Remove from this collection all its elements that are not contained in a + * given collection (optional operation). This implementation iterates over + * this collection, and for each element tests if it is contained in the + * given collection. If not, it is removed by the Iterator's remove method + * (thus this method will fail with an UnsupportedOperationException if + * the Iterator's remove method does). This method is necessary for + * ArrayList, which cannot publicly override retainAll but can optimize + * this call. + * + * @param c the collection to retain the elements of + * @return true if the remove operation caused the Collection to change + * @throws UnsupportedOperationException if this collection's Iterator + * does not support the remove method + * @throws NullPointerException if the collection, c, is null. + * @see Iterator#remove() + */ + // Package visible for use throughout java.util. + boolean retainAllInternal(Collection<?> c) + { + Iterator<E> itr = iterator(); + boolean modified = false; + int pos = size(); + while (--pos >= 0) + if (!c.contains(itr.next())) + { + itr.remove(); + modified = true; + } + return modified; + } + + /** + * Return an array containing the elements of this collection. This + * implementation creates an Object array of size size() and then iterates + * over the collection, setting each element of the array from the value + * returned by the iterator. The returned array is safe, and is not backed + * by the collection. + * + * @return an array containing the elements of this collection + */ + public Object[] toArray() + { + Iterator<E> itr = iterator(); + int size = size(); + Object[] a = new Object[size]; + for (int pos = 0; pos < size; pos++) + a[pos] = itr.next(); + return a; + } + + /** + * Copy the collection into a given array if it will fit, or into a + * dynamically created array of the same run-time type as the given array if + * not. If there is space remaining in the array, the first element after the + * end of the collection is set to null (this is only useful if the + * collection is known to contain no null elements, however). This + * implementation first tests whether the given array is large enough to hold + * all the elements of the collection. If not, the reflection API is used to + * allocate a new array of the same run-time type. Next an iterator is + * obtained over the collection and the elements are placed in the array as + * they are returned by the iterator. Finally the first spare element, if + * any, of the array is set to null, and the created array is returned. + * The returned array is safe; it is not backed by the collection. Note that + * null may not mark the last element, if the collection allows null + * elements. + * + * @param a the array to copy into, or of the correct run-time type + * @return the array that was produced + * @throws NullPointerException if the given array is null + * @throws ArrayStoreException if the type of the array precludes holding + * one of the elements of the Collection + */ + public <T> T[] toArray(T[] a) + { + int size = size(); + if (a.length < size) + a = (T[]) Array.newInstance(a.getClass().getComponentType(), + size); + else if (a.length > size) + a[size] = null; + + Iterator<E> itr = iterator(); + for (int pos = 0; pos < size; pos++) + { + try + { + a[pos] = (T) (itr.next()); + } + catch (ClassCastException exception) + { + throw new ArrayStoreException("The element is of the wrong type "+ + "for storing in this array."); + } + } + return a; + } + + /** + * Creates a String representation of the Collection. The string returned is + * of the form "[a, b, ...]" where a and b etc are the results of calling + * toString on the elements of the collection. This implementation obtains an + * Iterator over the Collection and adds each element to a StringBuffer as it + * is returned by the iterator. "<this>" is inserted when the collection + * contains itself (only works for direct containment, not for collections + * inside collections). + * + * @return a String representation of the Collection + */ + public String toString() + { + Iterator itr = iterator(); + StringBuffer r = new StringBuffer("["); + boolean hasNext = itr.hasNext(); + while (hasNext) + { + Object o = itr.next(); + if (o == this) + r.append("<this>"); + else + r.append(o); + hasNext = itr.hasNext(); + if (hasNext) + r.append(", "); + } + r.append("]"); + return r.toString(); + } + + /** + * Compare two objects according to Collection semantics. + * + * @param o1 the first object + * @param o2 the second object + * @return o1 == null ? o2 == null : o1.equals(o2) + */ + // Package visible for use throughout java.util. + // It may be inlined since it is final. + static final boolean equals(Object o1, Object o2) + { + return o1 == null ? o2 == null : o1.equals(o2); + } + + /** + * Hash an object according to Collection semantics. + * + * @param o the object to hash + * @return o1 == null ? 0 : o1.hashCode() + */ + // Package visible for use throughout java.util. + // It may be inlined since it is final. + static final int hashCode(Object o) + { + return o == null ? 0 : o.hashCode(); + } +} Added: trunk/core/src/classpath/java/java/util/AbstractList.java =================================================================== --- trunk/core/src/classpath/java/java/util/AbstractList.java (rev 0) +++ trunk/core/src/classpath/java/java/util/AbstractList.java 2006-12-12 21:12:29 UTC (rev 2897) @@ -0,0 +1,1204 @@ +/* AbstractList.java -- Abstract implementation of most of List + Copyright (C) 1998, 1999, 2000, 2001, 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.util; + +/** + * A basic implementation of most of the methods in the List interface to make + * it easier to create a List based on a random-access data structure. If + * the list is sequential (such as a linked list), use AbstractSequentialList. + * To create an unmodifiable list, it is only necessary to override the + * size() and get(int) methods (this contrasts with all other abstract + * collection classes which require an iterator to be provided). To make the + * list modifiable, the set(int, Object) method should also be overridden, and + * to make the list resizable, the add(int, Object) and remove(int) methods + * should be overridden too. Other methods should be overridden if the + * backing data structure allows for a more efficient implementation. + * The precise implementation used by AbstractList is documented, so that + * subclasses can tell which methods could be implemented more efficiently. + * <p> + * + * As recommended by Collection and List, the subclass should provide at + * least a no-argument and a Collection constructor. This class is not + * synchronized. + * + * @author Original author unknown + * @author Bryce McKinlay + * @author Eric Blake (eb...@em...) + * @see Collection + * @see List + * @see AbstractSequentialList + * @see AbstractCollection + * @see ListIterator + * @since 1.2 + * @status updated to 1.4 + */ +public abstract class AbstractList<E> + extends AbstractCollection<E> + implements List<E> +{ + /** + * A count of the number of structural modifications that have been made to + * the list (that is, insertions and removals). Structural modifications + * are ones which change the list size or affect how iterations would + * behave. This field is available for use by Iterator and ListIterator, + * in order to throw a {@link ConcurrentModificationException} in response + * to the next operation on the iterator. This <i>fail-fast</i> behavior + * saves the user from many subtle bugs otherwise possible from concurrent + * modification during iteration. + * <p> + * + * To make lists fail-fast, increment this field by just 1 in the + * <code>add(int, Object)</code> and <code>remove(int)</code> methods. + * Otherwise, this field may be ignored. + */ + protected transient int modCount; + + /** + * The main constructor, for use by subclasses. + */ + protected AbstractList() + { + } + + /** + * Returns the elements at the specified position in the list. + * + * @param index the element to return + * @return the element at that position + * @throws IndexOutOfBoundsException if index < 0 || index >= size() + */ + public abstract E get(int index); + + /** + * Insert an element into the list at a given position (optional operation). + * This shifts all existing elements from that position to the end one + * index to the right. This version of add has no return, since it is + * assumed to always succeed if there is no exception. This implementation + * always throws UnsupportedOperationException, and must be overridden to + * make a modifiable List. If you want fail-fast iterators, be sure to + * increment modCount when overriding this. + * + * @param index the location to insert the item + * @param o the object to insert + * @throws UnsupportedOperationException if this list does not support the + * add operation + * @throws IndexOutOfBoundsException if index < 0 || index > size() + * @throws ClassCastException if o cannot be added to this list due to its + * type + * @throws IllegalArgumentException if o cannot be added to this list for + * some other reason + * @see #modCount + */ + public void add(int index, E o) + { + throw new UnsupportedOperationException(); + } + + /** + * Add an element to the end of the list (optional operation). If the list + * imposes restraints on what can be inserted, such as no null elements, + * this should be documented. This implementation calls + * <code>add(size(), o);</code>, and will fail if that version does. + * + * @param o the object to add + * @return true, as defined by Collection for a modified list + * @throws UnsupportedOperationException if this list does not support the + * add operation + * @throws ClassCastException if o cannot be added to this list due to its + * type + * @throws IllegalArgumentException if o cannot be added to this list for + * some other reason + * @see #add(int, Object) + */ + public boolean add(E o) + { + add(size(), o); + return true; + } + + /** + * Insert the contents of a collection into the list at a given position + * (optional operation). Shift all elements at that position to the right + * by the number of elements inserted. This operation is undefined if + * this list is modified during the operation (for example, if you try + * to insert a list into itself). This implementation uses the iterator of + * the collection, repeatedly calling add(int, Object); this will fail + * if add does. This can often be made more efficient. + * + * @param index the location to insert the collection + * @param c the collection to insert + * @return true if the list was modified by this action, that is, if c is + * non-empty + * @throws UnsupportedOperationException if this list does not support the + * addAll operation + * @throws IndexOutOfBoundsException if index < 0 || index > size() + * @throws ClassCastException if some element of c cannot be added to this + * list due to its type + * @throws IllegalArgumentException if some element of c cannot be added + * to this list for some other reason + * @throws NullPointerException if the specified collection is null + * @see #add(int, Object) + */ + public boolean addAll(int index, Collection<? extends E> c) + { + Iterator<? extends E> itr = c.iterator(); + int size = c.size(); + for (int pos = size; pos > 0; pos--) + add(index++, itr.next()); + return size > 0; + } + + /** + * Clear the list, such that a subsequent call to isEmpty() would return + * true (optional operation). This implementation calls + * <code>removeRange(0, size())</code>, so it will fail unless remove + * or removeRange is overridden. + * + * @throws UnsupportedOperationException if this list does not support the + * clear operation + * @see #remove(int) + * @see #removeRange(int, int) + */ + public void clear() + { + removeRange(0, size()); + } + + /** + * Test whether this list is equal to another object. A List is defined to be + * equal to an object if and only if that object is also a List, and the two + * lists have the same sequence. Two lists l1 and l2 are equal if and only + * if <code>l1.size() == l2.size()</code>, and for every integer n between 0 + * and <code>l1.size() - 1</code> inclusive, <code>l1.get(n) == null ? + * l2.get(n) == null : l1.get(n).equals(l2.get(n))</code>. + * <p> + * + * This implementation returns true if the object is this, or false if the + * object is not a List. Otherwise, it iterates over both lists (with + * iterator()), returning false if two elements compare false or one list + * is shorter, and true if the iteration completes successfully. + * + * @param o the object to test for equality with this list + * @return true if o is equal to this list + * @see Object#equals(Object) + * @see #hashCode() + */ + public boolean equals(Object o) + { + if (o == this) + return true; + if (! (o instanceof List)) + return false; + int size = size(); + if (size != ((List) o).size()) + return false; + + Iterator<E> itr1 = iterator(); + Iterator itr2 = ((List) o).iterator(); + + while (--size >= 0) + if (! equals(itr1.next(), itr2.next())) + return false; + return true; + } + + /** + * Obtains a hash code for this list. In order to obey the general + * contract of the hashCode method of class Object, this value is + * calculated as follows: + * +<pre>hashCode = 1; +Iterator i = list.iterator(); +while (i.hasNext()) +{ + Object obj = i.next(); + hashCode = 31 * hashCode + (obj == null ? 0 : obj.hashCode()); +}</pre> + * + * This ensures that the general contract of Object.hashCode() is adhered to. + * + * @return the hash code of this list + * + * @see Object#hashCode() + * @see #equals(Object) + */ + public int hashCode() + { + int hashCode = 1; + Iterator<E> itr = iterator(); + int pos = size(); + while (--pos >= 0) + hashCode = 31 * hashCode + hashCode(itr.next()); + return hashCode; + } + + /** + * Obtain the first index at which a given object is to be found in this + * list. This implementation follows a listIterator() until a match is found, + * or returns -1 if the list end is reached. + * + * @param o the object to search for + * @return the least integer n such that <code>o == null ? get(n) == null : + * o.equals(get(n))</code>, or -1 if there is no such index + */ + public int indexOf(Object o) + { + ListIterator<E> itr = listIterator(); + int size = size(); + for (int pos = 0; pos < size; pos++) + if (equals(o, itr.next())) + return pos; + return -1; + } + + /** + * Obtain an Iterator over this list, whose sequence is the list order. + * This implementation uses size(), get(int), and remove(int) of the + * backing list, and does not support remove unless the list does. This + * implementation is fail-fast if you correctly maintain modCount. + * Also, this implementation is specified by Sun to be distinct from + * listIterator, although you could easily implement it as + * <code>return listIterator(0)</code>. + * + * @return an Iterator over the elements of this list, in order + * @see #modCount + */ + public Iterator<E> iterator() + { + // Bah, Sun's implementation forbids using listIterator(0). + return new Iterator<E>() + { + private int pos = 0; + private int size = size(); + private int last = -1; + private int knownMod = modCount; + + // This will get inlined, since it is private. + /** + * Checks for modifications made to the list from + * elsewhere while iteration is in progress. + * + * @throws ConcurrentModificationException if the + * list has been modified elsewhere. + */ + private void checkMod() + { + if (knownMod != modCount) + throw new ConcurrentModificationException(); + } + + /** + * Tests to see if there are any more objects to + * return. + * + * @return True if the end of the list has not yet been + * reached. + */ + public boolean hasNext() + { + return pos < size; + } + + /** + * Retrieves the next object from the list. + * + * @return The next object. + * @throws NoSuchElementException if there are + * no more objects to retrieve. + * @throws ConcurrentModificationException if the + * list has been modified elsewhere. + */ + public E next() + { + checkMod(); + if (pos == size) + throw new NoSuchElementException(); + last = pos; + return get(pos++); + } + + /** + * Removes the last object retrieved by <code>next()</code> + * from the list, if the list supports object removal. + * + * @throws ConcurrentModificationException if the list + * has been modified elsewhere. + * @throws IllegalStateException if the iterator is positioned + * before the start of the list or the last object has already + * been removed. + * @throws UnsupportedOperationException if the list does + * not support removing elements. + */ + public void remove() + { + checkMod(); + if (last < 0) + throw new IllegalStateException(); + AbstractList.this.remove(last); + pos--; + size--; + last = -1; + knownMod = modCount; + } + }; + } + + /** + * Obtain the last index at which a given object is to be found in this + * list. This implementation grabs listIterator(size()), then searches + * backwards for a match or returns -1. + * + * @return the greatest integer n such that <code>o == null ? get(n) == null + * : o.equals(get(n))</code>, or -1 if there is no such index + */ + public int lastIndexOf(Object o) + { + int pos = size(); + ListIterator<E> itr = listIterator(pos); + while (--pos >= 0) + if (equals(o, itr.previous())) + return pos; + return -1; + } + + /** + * Obtain a ListIterator over this list, starting at the beginning. This + * implementation returns listIterator(0). + * + * @return a ListIterator over the elements of this list, in order, starting + * at the beginning + */ + public ListIterator<E> listIterator() + { + return listIterator(0); + } + + /** + * Obtain a ListIterator over this list, starting at a given position. + * A first call to next() would return the same as get(index), and a + * first call to previous() would return the same as get(index - 1). + * <p> + * + * This implementation uses size(), get(int), set(int, Object), + * add(int, Object), and remove(int) of the backing list, and does not + * support remove, set, or add unless the list does. This implementation + * is fail-fast if you correctly maintain modCount. + * + * @param index the position, between 0 and size() inclusive, to begin the + * iteration from + * @return a ListIterator over the elements of this list, in order, starting + * at index + * @throws IndexOutOfBoundsException if index < 0 || index > size() + * @see #modCount + */ + public ListIterator<E> listIterator(final int index) + { + if (index < 0 || index > size()) + throw new IndexOutOfBoundsException("Index: " + index + ", Size:" + + size()); + + return new ListIterator<E>() + { + private int knownMod = modCount; + private int position = index; + private int lastReturned = -1; + private int size = size(); + + // This will get inlined, since it is private. + /** + * Checks for modifications made to the list from + * elsewhere while iteration is in progress. + * + * @throws ConcurrentModificationException if the + * list has been modified elsewhere. + */ + private void checkMod() + { + if (knownMod != modCount) + throw new ConcurrentModificationException(); + } + + /** + * Tests to see if there are any more objects to + * return. + * + * @return True if the end of the list has not yet been + * reached. + */ + public boolean hasNext() + { + return position < size; + } + + /** + * Tests to see if there are objects prior to the + * current position in the list. + * + * @return True if objects exist prior to the current + * position of the iterator. + */ + public boolean hasPrevious() + { + return position > 0; + } + + /** + * Retrieves the next object from the list. + * + * @return The next object. + * @throws NoSuchElementException if there are no + * more objects to retrieve. + * @throws ConcurrentModificationException if the + * list has been modified elsewhere. + */ + public E next() + { + checkMod(); + if (position == size) + throw new NoSuchElementException(); + lastReturned = position; + return get(position++); + } + + /** + * Retrieves the previous object from the list. + * + * @return The next object. + * @throws NoSuchElementException if there are no + * previous objects to retrieve. + * @throws ConcurrentModificationException if the + * list has been modified elsewhere. + */ + public E previous() + { + checkMod(); + if (position == 0) + throw new NoSuchElementException(); + lastReturned = --position; + return get(lastReturned); + } + + /** + * Returns the index of the next element in the + * list, which will be retrieved by <code>next()</code> + * + * @return The index of the next element. + */ + public int nextIndex() + { + return position; + } + + /** + * Returns the index of the previous element in the + * list, which will be retrieved by <code>previous()</code> + * + * @return The index of the previous element. + */ + public int previousIndex() + { + return position - 1; + } + + /** + * Removes the last object retrieved by <code>next()</code> + * or <code>previous()</code> from the list, if the list + * supports object removal. + * + * @throws IllegalStateException if the iterator is positioned + * before the start of the list or the last object has already + * been removed. + * @throws UnsupportedOperationException if the list does + * not support removing elements. + * @throws ConcurrentModificationException if the list + * has been modified elsewhere. + */ + public void remove() + { + checkMod(); + if (lastReturned < 0) + throw new IllegalStateException(); + AbstractList.this.remove(lastReturned); + size--; + position = lastReturned; + lastReturned = -1; + knownMod = modCount; + } + + /** + * Replaces the last object retrieved by <code>next()</code> + * or <code>previous</code> with o, if the list supports object + * replacement and an add or remove operation has not already + * been performed. + * + * @throws IllegalStateException if the iterator is positioned + * before the start of the list or the last object has already + * been removed. + * @throws UnsupportedOperationException if the list doesn't support + * the addition or removal of elements. + * @throws ClassCastException if the type of o is not a valid type + * for this list. + * @throws IllegalArgumentException if something else related to o + * prevents its addition. + * @throws ConcurrentModificationException if the list + * has been modified elsewhere. + */ + public void set(E o) + { + checkMod(); + if (lastReturned < 0) + throw new IllegalStateException(); + AbstractList.this.set(lastReturned, o); + } + + /** + * Adds the supplied object before the element that would be returned + * by a call to <code>next()</code>, if the list supports addition. + * + * @param o The object to add to the list. + * @throws UnsupportedOperationException if the list doesn't support + * the addition of new elements. + * @throws ClassCastException if the type of o is not a valid type + * for this list. + * @throws IllegalArgumentException if something else related to o + * prevents its addition. + * @throws ConcurrentModificationException if the list + * has been modified elsewhere. + */ + public void add(E o) + { + checkMod(); + AbstractList.this.add(position++, o); + size++; + lastReturned = -1; + knownMod = modCount; + } + }; + } + + /** + * Remove the element at a given position in this list (optional operation). + * Shifts all remaining elements to the left to fill the gap. This + * implementation always throws an UnsupportedOperationException. + * If you want fail-fast iterators, be sure to increment modCount when + * overriding this. + * + * @param index the position within the list of the object to remove + * @return the object that was removed + * @throws UnsupportedOperationException if this list does not support the + * remove operation + * @throws IndexOutOfBoundsException if index < 0 || index >= size() + * @see #modCount + */ + public E remove(int index) + { + throw new UnsupportedOperationException(); + } + + /** + * Remove a subsection of the list. This is called by the clear and + * removeRange methods of the class which implements subList, which are + * difficult for subclasses to override directly. Therefore, this method + * should be overridden instead by the more efficient implementation, if one + * exists. Overriding this can reduce quadratic efforts to constant time + * in some cases! + * <p> + * + * This implementation first checks for illegal or out of range arguments. It + * then obtains a ListIterator over the list using listIterator(fromIndex). + * It then calls next() and remove() on this iterator repeatedly, toIndex - + * fromIndex times. + * + * @param fromIndex the index, inclusive, to remove from. + * @param toIndex the index, exclusive, to remove to. + * @throws UnsupportedOperationException if the list does + * not support removing elements. + */ + protected void removeRange(int fromIndex, int toIndex) + { + ListIterator<E> itr = listIterator(fromIndex); + for (int index = fromIndex; index < toIndex; index++) + { + itr.next(); + itr.remove(); + } + } + + /** + * Replace an element of this list with another object (optional operation). + * This implementation always throws an UnsupportedOperationException. + * + * @param index the position within this list of the element to be replaced + * @param o the object to replace it with + * @return the object that was replaced + * @throws UnsupportedOperationException if this list does not support the + * set operation + * @throws IndexOutOfBoundsException if index < 0 || index >= size() + * @throws ClassCastException if o cannot be added to this list due to its + * type + * @throws IllegalArgumentException if o cannot be added to this list for + * some other reason + */ + public E set(int index, E o) + { + throw new UnsupportedOperationException(); + } + + /** + * Obtain a List view of a subsection of this list, from fromIndex + * (inclusive) to toIndex (exclusive). If the two indices are equal, the + * sublist is empty. The returned list should be modifiable if and only + * if this list is modifiable. Changes to the returned list should be + * reflected in this list. If this list is structurally modified in + * any way other than through the returned list, the result of any subsequent + * operations on the returned list is undefined. + * <p> + * + * This implementation returns a subclass of AbstractList. It stores, in + * private fields, the offset and size of the sublist, and the expected + * modCount of the backing list. If the backing list implements RandomAccess, + * the sublist will also. + * <p> + * + * The subclass's <code>set(int, Object)</code>, <code>get(int)</code>, + * <code>add(int, Object)</code>, <code>remove(int)</code>, + * <code>addAll(int, Collection)</code> and + * <code>removeRange(int, int)</code> methods all delegate to the + * corresponding methods on the backing abstract list, after + * bounds-checking the index and adjusting for the offset. The + * <code>addAll(Collection c)</code> method merely returns addAll(size, c). + * The <code>listIterator(int)</code> method returns a "wrapper object" + * over a list iterator on the backing list, which is created with the + * corresponding method on the backing list. The <code>iterator()</code> + * method merely returns listIterator(), and the <code>size()</code> method + * merely returns the subclass's size field. + * <p> + * + * All methods first check to see if the actual modCount of the backing + * list is equal to its expected value, and throw a + * ConcurrentModificationException if it is not. + * + * @param fromIndex the index that the returned list should start from + * (inclusive) + * @param toIndex the index that the returned list should go to (exclusive) + * @return a List backed by a subsection of this list + * @throws IndexOutOfBoundsException if fromIndex < 0 + * || toIndex > size() + * @throws IllegalArgumentException if fromIndex > toIndex + * @see ConcurrentModificationException + * @see RandomAccess + */ + public List<E> subList(int fromIndex, int toIndex) + { + // This follows the specification of AbstractList, but is inconsistent + // with the one in List. Don't you love Sun's inconsistencies? + if (fromIndex > toIndex) + throw new IllegalArgumentException(fromIndex + " > " + toIndex); + if (fromIndex < 0 || toIndex > size()) + throw new IndexOutOfBoundsException(); + + if (this instanceof RandomAccess) + return new RandomAccessSubList<E>(this, fromIndex, toIndex); + return new SubList<E>(this, fromIndex, toIndex); + } + + /** + * This class follows the implementation requirements set forth in + * {@link AbstractList#subList(int, int)}. It matches Sun's implementation + * by using a non-public top-level class in the same package. + * + * @author Original author unknown + * @author Eric Blake (eb...@em...) + */ + private static class SubList<E> extends AbstractList<E> + { + // Package visible, for use by iterator. + /** The original list. */ + final AbstractList<E> backingList; + /** The index of the first element of the sublist. */ + final int offset; + /** The size of the sublist. */ + int size; + + /** + * Construct the sublist. + * + * @param backing the list this comes from + * @param fromIndex the lower bound, inclusive + * @param toIndex the upper bound, exclusive + */ + SubList(AbstractList<E> backing, int fromIndex, int toIndex) + { + backingList = backing; + modCount = backing.modCount; + offset = fromIndex; + size = toIndex - fromIndex; + } + + /** + * This method checks the two modCount fields to ensure that there has + * not been a concurrent modification, returning if all is okay. + * + * @throws ConcurrentModificationException if the backing list has been + * modified externally to this sublist + */ + // This can be inlined. Package visible, for use by iterator. + void checkMod() + { + if (modCount != backingList.modCount) + throw new ConcurrentModificationException(); + } + + /** + * This method checks that a value is between 0 and size (inclusive). If + * it is not, an exception is thrown. + * + * @param index the value to check + * @throws IndexOutOfBoundsException if index < 0 || index > size() + */ + // This will get inlined, since it is private. + private void checkBoundsInclusive(int index) + { + if (index < 0 || index > size) + throw new IndexOutOfBoundsException("Index: " + index + ", Size:" + + size); + } + + /** + * This method checks that a value is between 0 (inclusive) and size + * (exclusive). If it is not, an exception is thrown. + * + * @param index the value to check + * @throws IndexOutOfBoundsException if index < 0 || index >= size() + */ + // This will get inlined, since it is private. + private void checkBoundsExclusive(int index) + { + if (index < 0 || index >= size) + throw new IndexOutOfBoundsException("Index: " + index + ", Size:" + + size); + } + + /** + * Specified by AbstractList.subList to return the private field size. + * + * @return the sublist size + * @throws ConcurrentModificationException if the backing list has been + * modified externally to this sublist + */ + public int size() + { + checkMod(); + return size; + } + + /** + * Specified by AbstractList.subList to delegate to the backing list. + * + * @param index the location to modify + * @param o the new value + * @return the old value + * @throws ConcurrentModificationException if the backing list has been + * modified externally to this sublist + * @throws UnsupportedOperationException if the backing list does not + * support the set operation + * @throws IndexOutOfBoundsException if index < 0 || index >= size() + * @throws ClassCastException if o cannot be added to the backing list due + * to its type + * @throws IllegalArgumentException if o cannot be added to the backing list + * for some other reason + */ + public E set(int index, E o) + { + checkMod(); + checkBoundsExclusive(index); + return backingList.set(index + offset, o); + } + + /** + * Specified by AbstractList.subList to delegate to the backing list. + * + * @param index the location to get from + * @return the object at that location + * @throws ConcurrentModificationException if the backing list has been + * modified externally to this sublist + * @throws IndexOutOfBoundsException if index < 0 || index >= size() + */ + public E get(int index) + { + checkMod(); + checkBoundsExclusive(index); + return backingList.get(index + offset); + } + + /** + * Specified by AbstractList.subList to delegate to the backing list. + * + * @param index the index to insert at + * @param o the object to add + * @throws ConcurrentModificationException if the backing list has been + * modified externally to this sublist + * @throws IndexOutOfBoundsException if index < 0 || index > size() + * @throws UnsupportedOperationException if the backing list does not + * support the add operation. + * @throws ClassCastException if o cannot be added to the backing list due + * to its type. + * @throws IllegalArgumentException if o cannot be added to the backing + * list for some other reason. + */ + public void add(int index, E o) + { + checkMod(); + checkBoundsInclusive(index); + backingList.add(index + offset, o); + size++; + modCount = backingList.modCount; + } + + /** + * Specified by AbstractList.subList to delegate to the backing list. + * + * @param index the index to remove + * @return the removed object + * @throws ConcurrentModificationException if the backing list has been + * modified externally to this sublist + * @throws IndexOutOfBoundsException if index < 0 || index >= size() + * @throws UnsupportedOperationException if the backing list does not + * support the remove operation + */ + public E remove(int index) + { + checkMod(); + checkBoundsExclusive(index); + E o = backingList.remove(index + offset); + size--; + modCount = backingList.modCount; + return o; + } + + /** + * Specified by AbstractList.subList to delegate to the backing list. + * This does no bounds checking, as it assumes it will only be called + * by trusted code like clear() which has already checked the bounds. + * + * @param fromIndex the lower bound, inclusive + * @param toIndex the upper bound, exclusive + * @throws ConcurrentModificationException if the backing list has been + * modified externally to this sublist + * @throws UnsupportedOperationException if the backing list does + * not support removing elements. + */ + protected void removeRange(int fromIndex, int toIndex) + { + checkMod(); + + backingList.removeRange(offset + fromIndex, offset + toIndex); + size -= toIndex - fromIndex; + modCount = backingList.modCount; + } + + /** + * Specified by AbstractList.subList to delegate to the backing list. + * + * @param index the location to insert at + * @param c the collection to insert + * @return true if this list was modified, in other words, c is non-empty + * @throws ConcurrentModificationException if the backing list has been + * modified externally to this sublist + * @throws IndexOutOfBoundsException if index < 0 || index > size() + * @throws UnsupportedOperationException if this list does not support the + * addAll operation + * @throws ClassCastException if some element of c cannot be added to this + * list due to its type + * @throws IllegalArgumentException if some element of c cannot be added + * to this list for some other reason + * @throws NullPointerException if the specified collection is null + */ + public boolean addAll(int index, Collection<? extends E> c) + { + checkMod(); + checkBoundsInclusive(index); + int csize = c.size(); + boolean result = backingList.addAll(offset + index, c); + size += csize; + modCount = backingList.modCount; + return result; + } + + /** + * Specified by AbstractList.subList to return addAll(size, c). + * + * @param c the collection to insert + * @return true if this list was modified, in other words, c is non-empty + * @throws ConcurrentModificationException if the backing list has been + * modified externally to this sublist + * @throws UnsupportedOperationException if this list does not support the + * addAll operation + * @throws ClassCastException if some element of c cannot be added to this + * list due to its type + * @throws IllegalArgumentException if some element of c cannot be added + * to this list for some other reason + * @throws NullPointerException if the specified collection is null + */ + public boolean addAll(Collection<? extends E> c) + { + return addAll(size, c); + } + + /** + * Specified by AbstractList.subList to return listIterator(). + * + * @return an iterator over the sublist + */ + public Iterator<E> iterator() + { + return listIterator(); + } + + /** + * Specified by AbstractList.subList to return a wrapper around the + * backing list's iterator. + * + * @param index the start location of the iterator + * @return a list iterator over the sublist + * @throws ConcurrentModificationException if the backing list has been + * modified externally to this sublist + * @throws IndexOutOfBoundsException if the value is out of range + */ + public ListIterator<E> listIterator(final int index) ... [truncated message content] |
From: <ls...@us...> - 2006-12-12 21:10:02
|
Revision: 2896 http://jnode.svn.sourceforge.net/jnode/?rev=2896&view=rev Author: lsantha Date: 2006-12-12 13:09:56 -0800 (Tue, 12 Dec 2006) Log Message: ----------- Migrating to Java 5 level classpath. Added Paths: ----------- trunk/core/src/classpath/java/java/io/ trunk/core/src/classpath/java/java/io/BufferedInputStream.java trunk/core/src/classpath/java/java/io/BufferedOutputStream.java trunk/core/src/classpath/java/java/io/BufferedReader.java trunk/core/src/classpath/java/java/io/BufferedWriter.java trunk/core/src/classpath/java/java/io/ByteArrayInputStream.java trunk/core/src/classpath/java/java/io/ByteArrayOutputStream.java trunk/core/src/classpath/java/java/io/CharArrayReader.java trunk/core/src/classpath/java/java/io/CharArrayWriter.java trunk/core/src/classpath/java/java/io/CharConversionException.java trunk/core/src/classpath/java/java/io/Closeable.java trunk/core/src/classpath/java/java/io/DataInput.java trunk/core/src/classpath/java/java/io/DataInputStream.java trunk/core/src/classpath/java/java/io/DataOutput.java trunk/core/src/classpath/java/java/io/DataOutputStream.java trunk/core/src/classpath/java/java/io/DeleteFileHelper.java trunk/core/src/classpath/java/java/io/EOFException.java trunk/core/src/classpath/java/java/io/Externalizable.java trunk/core/src/classpath/java/java/io/File.java trunk/core/src/classpath/java/java/io/FileDescriptor.java trunk/core/src/classpath/java/java/io/FileFilter.java trunk/core/src/classpath/java/java/io/FileInputStream.java trunk/core/src/classpath/java/java/io/FileNotFoundException.java trunk/core/src/classpath/java/java/io/FileOutputStream.java trunk/core/src/classpath/java/java/io/FilePermission.java trunk/core/src/classpath/java/java/io/FileReader.java trunk/core/src/classpath/java/java/io/FileWriter.java trunk/core/src/classpath/java/java/io/FilenameFilter.java trunk/core/src/classpath/java/java/io/FilterInputStream.java trunk/core/src/classpath/java/java/io/FilterOutputStream.java trunk/core/src/classpath/java/java/io/FilterReader.java trunk/core/src/classpath/java/java/io/FilterWriter.java trunk/core/src/classpath/java/java/io/Flushable.java trunk/core/src/classpath/java/java/io/IOException.java trunk/core/src/classpath/java/java/io/InputStream.java trunk/core/src/classpath/java/java/io/InputStreamReader.java trunk/core/src/classpath/java/java/io/InterruptedIOException.java trunk/core/src/classpath/java/java/io/InvalidClassException.java trunk/core/src/classpath/java/java/io/InvalidObjectException.java trunk/core/src/classpath/java/java/io/LineNumberInputStream.java trunk/core/src/classpath/java/java/io/LineNumberReader.java trunk/core/src/classpath/java/java/io/NotActiveException.java trunk/core/src/classpath/java/java/io/NotSerializableException.java trunk/core/src/classpath/java/java/io/ObjectInput.java trunk/core/src/classpath/java/java/io/ObjectInputStream.java trunk/core/src/classpath/java/java/io/ObjectInputValidation.java trunk/core/src/classpath/java/java/io/ObjectOutput.java trunk/core/src/classpath/java/java/io/ObjectOutputStream.java trunk/core/src/classpath/java/java/io/ObjectStreamClass.java trunk/core/src/classpath/java/java/io/ObjectStreamConstants.java trunk/core/src/classpath/java/java/io/ObjectStreamException.java trunk/core/src/classpath/java/java/io/ObjectStreamField.java trunk/core/src/classpath/java/java/io/OptionalDataException.java trunk/core/src/classpath/java/java/io/OutputStream.java trunk/core/src/classpath/java/java/io/OutputStreamWriter.java trunk/core/src/classpath/java/java/io/PipedInputStream.java trunk/core/src/classpath/java/java/io/PipedOutputStream.java trunk/core/src/classpath/java/java/io/PipedReader.java trunk/core/src/classpath/java/java/io/PipedWriter.java trunk/core/src/classpath/java/java/io/PrintStream.java trunk/core/src/classpath/java/java/io/PrintWriter.java trunk/core/src/classpath/java/java/io/PushbackInputStream.java trunk/core/src/classpath/java/java/io/PushbackReader.java trunk/core/src/classpath/java/java/io/RandomAccessFile.java trunk/core/src/classpath/java/java/io/Reader.java trunk/core/src/classpath/java/java/io/SequenceInputStream.java trunk/core/src/classpath/java/java/io/Serializable.java trunk/core/src/classpath/java/java/io/SerializablePermission.java trunk/core/src/classpath/java/java/io/StreamCorruptedException.java trunk/core/src/classpath/java/java/io/StreamTokenizer.java trunk/core/src/classpath/java/java/io/StringBufferInputStream.java trunk/core/src/classpath/java/java/io/StringReader.java trunk/core/src/classpath/java/java/io/StringWriter.java trunk/core/src/classpath/java/java/io/SyncFailedException.java trunk/core/src/classpath/java/java/io/UTFDataFormatException.java trunk/core/src/classpath/java/java/io/UnsupportedEncodingException.java trunk/core/src/classpath/java/java/io/WriteAbortedException.java trunk/core/src/classpath/java/java/io/Writer.java trunk/core/src/classpath/java/java/io/class-dependencies.conf trunk/core/src/classpath/java/java/io/package.html Added: trunk/core/src/classpath/java/java/io/BufferedInputStream.java =================================================================== --- trunk/core/src/classpath/java/java/io/BufferedInputStream.java (rev 0) +++ trunk/core/src/classpath/java/java/io/BufferedInputStream.java 2006-12-12 21:09:56 UTC (rev 2896) @@ -0,0 +1,379 @@ +/* BufferedInputStream.java -- An input stream that implements buffering + Copyright (C) 1998, 1999, 2001, 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.io; + +/* Written using "Java Class Libraries", 2nd edition, ISBN 0-201-31002-3 + * "The Java Language Specification", ISBN 0-201-63451-1 + * plus online API docs for JDK 1.2 beta from http://www.javasoft.com. + * Status: Believed complete and correct. + */ + +/** + * This subclass of <code>FilterInputStream</code> buffers input from an + * underlying implementation to provide a possibly more efficient read + * mechanism. It maintains the buffer and buffer state in instance + * variables that are available to subclasses. The default buffer size + * of 2048 bytes can be overridden by the creator of the stream. + * <p> + * This class also implements mark/reset functionality. It is capable + * of remembering any number of input bytes, to the limits of + * system memory or the size of <code>Integer.MAX_VALUE</code> + * <p> + * Please note that this class does not properly handle character + * encodings. Consider using the <code>BufferedReader</code> class which + * does. + * + * @author Aaron M. Renn (ar...@ur...) + * @author Warren Levy (wa...@cy...) + * @author Jeroen Frijters (je...@fr...) + */ +public class BufferedInputStream extends FilterInputStream +{ + + /** + * This is the default buffer size + */ + private static final int DEFAULT_BUFFER_SIZE = 2048; + + /** + * The buffer used for storing data from the underlying stream. + */ + protected byte[] buf; + + /** + * The number of valid bytes currently in the buffer. It is also the index + * of the buffer position one byte past the end of the valid data. + */ + protected int count; + + /** + * The index of the next character that will by read from the buffer. + * When <code>pos == count</code>, the buffer is empty. + */ + protected int pos; + + /** + * The value of <code>pos</code> when the <code>mark()</code> method was + * called. + * This is set to -1 if there is no mark set. + */ + protected int markpos = -1; + + /** + * This is the maximum number of bytes than can be read after a + * call to <code>mark()</code> before the mark can be discarded. + * After this may bytes are read, the <code>reset()</code> method + * may not be called successfully. + */ + protected int marklimit; + + /** + * This is the initial buffer size. When the buffer is grown because + * of marking requirements, it will be grown by bufferSize increments. + * The underlying stream will be read in chunks of bufferSize. + */ + private final int bufferSize; + + /** + * This method initializes a new <code>BufferedInputStream</code> that will + * read from the specified subordinate stream with a default buffer size + * of 2048 bytes + * + * @param in The subordinate stream to read from + */ + public BufferedInputStream(InputStream in) + { + this(in, DEFAULT_BUFFER_SIZE); + } + + /** + * This method initializes a new <code>BufferedInputStream</code> that will + * read from the specified subordinate stream with a buffer size that + * is specified by the caller. + * + * @param in The subordinate stream to read from + * @param size The buffer size to use + * + * @exception IllegalArgumentException when size is smaller then 1 + */ + public BufferedInputStream(InputStream in, int size) + { + super(in); + if (size <= 0) + throw new IllegalArgumentException(); + buf = new byte[size]; + // initialize pos & count to bufferSize, to prevent refill from + // allocating a new buffer (if the caller starts out by calling mark()). + pos = count = bufferSize = size; + } + + /** + * This method returns the number of bytes that can be read from this + * stream before a read can block. A return of 0 indicates that blocking + * might (or might not) occur on the very next read attempt. + * <p> + * The number of available bytes will be the number of read ahead bytes + * stored in the internal buffer plus the number of available bytes in + * the underlying stream. + * + * @return The number of bytes that can be read before blocking could occur + * + * @exception IOException If an error occurs + */ + public synchronized int available() throws IOException + { + return count - pos + super.available(); + } + + /** + * This method closes the underlying input stream and frees any + * resources associated with it. Sets <code>buf</code> to <code>null</code>. + * + * @exception IOException If an error occurs. + */ + public void close() throws IOException + { + // Free up the array memory. + buf = null; + pos = count = 0; + markpos = -1; + super.close(); + } + + /** + * This method marks a position in the input to which the stream can be + * "reset" by calling the <code>reset()</code> method. The parameter + * <code>readlimit</code> is the number of bytes that can be read from the + * stream after setting the mark before the mark becomes invalid. For + * example, if <code>mark()</code> is called with a read limit of 10, then + * when 11 bytes of data are read from the stream before the + * <code>reset()</code> method is called, then the mark is invalid and the + * stream object instance is not required to remember the mark. + * <p> + * Note that the number of bytes that can be remembered by this method + * can be greater than the size of the internal read buffer. It is also + * not dependent on the subordinate stream supporting mark/reset + * functionality. + * + * @param readlimit The number of bytes that can be read before the mark + * becomes invalid + */ + public synchronized void mark(int readlimit) + { + marklimit = readlimit; + markpos = pos; + } + + /** + * This method returns <code>true</code> to indicate that this class + * supports mark/reset functionality. + * + * @return <code>true</code> to indicate that mark/reset functionality is + * supported + * + */ + public boolean markSupported() + { + return true; + } + + /** + * This method reads an unsigned byte from the input stream and returns it + * as an int in the range of 0-255. This method also will return -1 if + * the end of the stream has been reached. + * <p> + * This method will block until the byte can be read. + * + * @return The byte read or -1 if end of stream + * + * @exception IOException If an error occurs + */ + public synchronized int read() throws IOException + { + if (pos >= count && !refill()) + return -1; // EOF + + return buf[pos++] & 0xFF; + } + + /** + * This method reads bytes from a stream and stores them into a caller + * supplied buffer. It starts storing the data at index <code>off</code> + * into the buffer and attempts to read <code>len</code> bytes. This method + * can return before reading the number of bytes requested, but it will try + * to read the requested number of bytes by repeatedly calling the underlying + * stream as long as available() for this stream continues to return a + * non-zero value (or until the requested number of bytes have been read). + * The actual number of bytes read is returned as an int. A -1 is returned + * to indicate the end of the stream. + * <p> + * This method will block until some data can be read. + * + * @param b The array into which the bytes read should be stored + * @param off The offset into the array to start storing bytes + * @param len The requested number of bytes to read + * + * @return The actual number of bytes read, or -1 if end of stream. + * + * @exception IOException If an error occurs. + * @exception IndexOutOfBoundsException when <code>off</code> or + * <code>len</code> are negative, or when <code>off + len</code> + * is larger then the size of <code>b</code>, + */ + public synchronized int read(byte[] b, int off, int len) throws IOException + { + if (off < 0 || len < 0 || b.length - off < len) + throw new IndexOutOfBoundsException(); + + if (len == 0) + return 0; + + if (pos >= count && !refill()) + return -1; // No bytes were read before EOF. + + int totalBytesRead = Math.min(count - pos, len); + System.arraycopy(buf, pos, b, off, totalBytesRead); + pos += totalBytesRead; + off += totalBytesRead; + len -= totalBytesRead; + + while (len > 0 && super.available() > 0 && refill()) + { + int remain = Math.min(count - pos, len); + System.arraycopy(buf, pos, b, off, remain); + pos += remain; + off += remain; + len -= remain; + totalBytesRead += remain; + } + + return totalBytesRead; + } + + /** + * This method resets a stream to the point where the <code>mark()</code> + * method was called. Any bytes that were read after the mark point was + * set will be re-read during subsequent reads. + * <p> + * This method will throw an IOException if the number of bytes read from + * the stream since the call to <code>mark()</code> exceeds the mark limit + * passed when establishing the mark. + * + * @exception IOException If <code>mark()</code> was never called or more + * then <code>marklimit</code> bytes were read since the last + * call to <code>mark()</code> + */ + public synchronized void reset() throws IOException + { + if (markpos == -1) + throw new IOException(buf == null ? "Stream closed." : "Invalid mark."); + + pos = markpos; + } + + /** + * This method skips the specified number of bytes in the stream. It + * returns the actual number of bytes skipped, which may be less than the + * requested amount. + * + * @param n The requested number of bytes to skip + * + * @return The actual number of bytes skipped. + * + * @exception IOException If an error occurs + */ + public synchronized long skip(long n) throws IOException + { + if (buf == null) + throw new IOException("Stream closed."); + + final long origN = n; + + while (n > 0L) + { + if (pos >= count && !refill()) + break; + + int numread = (int) Math.min((long) (count - pos), n); + pos += numread; + n -= numread; + } + + return origN - n; + } + + /** + * Called to refill the buffer (when count is equal to pos). + * + * @return <code>true</code> when at least one additional byte was read + * into <code>buf</code>, <code>false</code> otherwise (at EOF). + */ + private boolean refill() throws IOException + { + if (buf == null) + throw new IOException("Stream closed."); + + if (markpos == -1 || count - markpos >= marklimit) + { + markpos = -1; + pos = count = 0; + } + else + { + byte[] newbuf = buf; + if (markpos < bufferSize) + { + newbuf = new byte[count - markpos + bufferSize]; + } + System.arraycopy(buf, markpos, newbuf, 0, count - markpos); + buf = newbuf; + count -= markpos; + pos -= markpos; + markpos = 0; + } + + int numread = super.read(buf, count, bufferSize); + + if (numread <= 0) // EOF + return false; + + count += numread; + return true; + } +} Added: trunk/core/src/classpath/java/java/io/BufferedOutputStream.java =================================================================== --- trunk/core/src/classpath/java/java/io/BufferedOutputStream.java (rev 0) +++ trunk/core/src/classpath/java/java/io/BufferedOutputStream.java 2006-12-12 21:09:56 UTC (rev 2896) @@ -0,0 +1,192 @@ +/* BufferedOutputStream.java -- Buffer output into large blocks before writing + 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.io; + +/** + * This class accumulates bytes written in a buffer instead of immediately + * writing the data to the underlying output sink. The bytes are instead + * as one large block when the buffer is filled, or when the stream is + * closed or explicitly flushed. This mode operation can provide a more + * efficient mechanism for writing versus doing numerous small unbuffered + * writes. + * + * @author Aaron M. Renn (ar...@ur...) + */ +public class BufferedOutputStream extends FilterOutputStream +{ + /** + * This is the default buffer size + */ + private static final int DEFAULT_BUFFER_SIZE = 512; + + /** + * This is the internal byte array used for buffering output before + * writing it. + */ + protected byte[] buf; + + /** + * This is the number of bytes that are currently in the buffer and + * are waiting to be written to the underlying stream. It always points to + * the index into the buffer where the next byte of data will be stored + */ + protected int count; + + /** + * This method initializes a new <code>BufferedOutputStream</code> instance + * that will write to the specified subordinate <code>OutputStream</code> + * and which will use a default buffer size of 512 bytes. + * + * @param out The underlying <code>OutputStream</code> to write data to + */ + public BufferedOutputStream(OutputStream out) + { + this(out, DEFAULT_BUFFER_SIZE); + } + + /** + * This method initializes a new <code>BufferedOutputStream</code> instance + * that will write to the specified subordinate <code>OutputStream</code> + * and which will use the specified buffer size + * + * @param out The underlying <code>OutputStream</code> to write data to + * @param size The size of the internal buffer + */ + public BufferedOutputStream(OutputStream out, int size) + { + super(out); + + buf = new byte[size]; + } + + /** + * This method causes any currently buffered bytes to be immediately + * written to the underlying output stream. + * + * @exception IOException If an error occurs + */ + public synchronized void flush() throws IOException + { + if (count == 0) + return; + + out.write(buf, 0, count); + count = 0; + out.flush(); + } + + /** + * This method flushes any remaining buffered bytes then closes the + * underlying output stream. Any further attempts to write to this stream + * may throw an exception + * + public synchronized void close() throws IOException + { + flush(); + out.close(); + } + */ + + /** + * This method runs when the object is garbage collected. It is + * responsible for ensuring that all buffered bytes are written and + * for closing the underlying stream. + * + * @exception IOException If an error occurs (ignored by the Java runtime) + * + protected void finalize() throws IOException + { + close(); + } + */ + + /** + * This method writes a single byte of data. This will be written to the + * buffer instead of the underlying data source. However, if the buffer + * is filled as a result of this write request, it will be flushed to the + * underlying output stream. + * + * @param b The byte of data to be written, passed as an int + * + * @exception IOException If an error occurs + */ + public synchronized void write(int b) throws IOException + { + if (count == buf.length) + flush(); + + buf[count] = (byte)(b & 0xFF); + ++count; + } + + /** + * This method writes <code>len</code> bytes from the byte array + * <code>buf</code> starting at position <code>offset</code> in the buffer. + * These bytes will be written to the internal buffer. However, if this + * write operation fills the buffer, the buffer will be flushed to the + * underlying output stream. + * + * @param buf The array of bytes to write. + * @param offset The index into the byte array to start writing from. + * @param len The number of bytes to write. + * + * @exception IOException If an error occurs + */ + public synchronized void write(byte[] buf, int offset, int len) + throws IOException + { + // Buffer can hold everything. Note that the case where LEN < 0 + // is automatically handled by the downstream write. + if (len < (this.buf.length - count)) + { + System.arraycopy(buf, offset, this.buf, count, len); + count += len; + } + else + { + // The write was too big. So flush the buffer and write the new + // bytes directly to the underlying stream, per the JDK 1.2 + // docs. + flush(); + out.write (buf, offset, len); + } + } + +} // class BufferedOutputStream + Added: trunk/core/src/classpath/java/java/io/BufferedReader.java =================================================================== --- trunk/core/src/classpath/java/java/io/BufferedReader.java (rev 0) +++ trunk/core/src/classpath/java/java/io/BufferedReader.java 2006-12-12 21:09:56 UTC (rev 2896) @@ -0,0 +1,581 @@ +/* BufferedReader.java + Copyright (C) 1998, 1999, 2000, 2001, 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.io; + +/* Written using "Java Class Libraries", 2nd edition, plus online + * API docs for JDK 1.2 beta from http://www.javasoft.com. + * Status: Believed complete and correct. + */ + +/** + * This subclass of <code>FilterReader</code> buffers input from an + * underlying implementation to provide a possibly more efficient read + * mechanism. It maintains the buffer and buffer state in instance + * variables that are available to subclasses. The default buffer size + * of 8192 chars can be overridden by the creator of the stream. + * <p> + * This class also implements mark/reset functionality. It is capable + * of remembering any number of input chars, to the limits of + * system memory or the size of <code>Integer.MAX_VALUE</code> + * + * @author Per Bothner (bo...@cy...) + * @author Aaron M. Renn (ar...@ur...) + */ +public class BufferedReader extends Reader +{ + Reader in; + char[] buffer; + /* Index of current read position. Must be >= 0 and <= limit. */ + /* There is a special case where pos may be equal to limit+1; this + * is used as an indicator that a readLine was done with a '\r' was + * the very last char in the buffer. Since we don't want to read-ahead + * and potentially block, we set pos this way to indicate the situation + * and deal with it later. Doing it this way rather than having a + * separate boolean field to indicate the condition has the advantage + * that it is self-clearing on things like mark/reset. + */ + int pos; + /* Limit of valid data in buffer. Must be >= pos and <= buffer.length. */ + /* This can be < pos in the one special case described above. */ + int limit; + + /* The value -1 means there is no mark, or the mark has been invalidated. + Otherwise, markPos is the index in the buffer of the marked position. + Must be >= 0 and <= pos. + Note we do not explicitly store the read-limit. + The implicit read-limit is (buffer.length - markPos), which is + guaranteed to be >= the read-limit requested in the call to mark. */ + int markPos = -1; + + // The JCL book specifies the default buffer size as 8K characters. + // This is package-private because it is used by LineNumberReader. + static final int DEFAULT_BUFFER_SIZE = 8192; + + /** + * The line buffer for <code>readLine</code>. + */ + private StringBuffer sbuf = null; + + /** + * Create a new <code>BufferedReader</code> that will read from the + * specified subordinate stream with a default buffer size of 8192 chars. + * + * @param in The subordinate stream to read from + */ + public BufferedReader(Reader in) + { + this(in, DEFAULT_BUFFER_SIZE); + } + + /** + * Create a new <code>BufferedReader</code> that will read from the + * specified subordinate stream with a buffer size that is specified by the + * caller. + * + * @param in The subordinate stream to read from + * @param size The buffer size to use + * + * @exception IllegalArgumentException if size <= 0 + */ + public BufferedReader(Reader in, int size) + { + super(in.lock); + if (size <= 0) + throw new IllegalArgumentException("Illegal buffer size: " + size); + this.in = in; + buffer = new char[size]; + } + + /** + * This method closes the underlying stream and frees any associated + * resources. + * + * @exception IOException If an error occurs + */ + public void close() throws IOException + { + synchronized (lock) + { + if (in != null) + in.close(); + in = null; + buffer = null; + } + } + + /** + * Returns <code>true</code> to indicate that this class supports mark/reset + * functionality. + * + * @return <code>true</code> + */ + public boolean markSupported() + { + return true; + } + + /** + * Mark a position in the input to which the stream can be + * "reset" by calling the <code>reset()</code> method. The parameter + * <code>readLimit</code> is the number of chars that can be read from the + * stream after setting the mark before the mark becomes invalid. For + * example, if <code>mark()</code> is called with a read limit of 10, then + * when 11 chars of data are read from the stream before the + * <code>reset()</code> method is called, then the mark is invalid and the + * stream object instance is not required to remember the mark. + * <p> + * Note that the number of chars that can be remembered by this method + * can be greater than the size of the internal read buffer. It is also + * not dependent on the subordinate stream supporting mark/reset + * functionality. + * + * @param readLimit The number of chars that can be read before the mark + * becomes invalid + * + * @exception IOException If an error occurs + * @exception IllegalArgumentException if readLimit is negative. + */ + public void mark(int readLimit) throws IOException + { + if (readLimit < 0) + throw new IllegalArgumentException("Read-ahead limit is negative"); + + synchronized (lock) + { + checkStatus(); + // In this method we need to be aware of the special case where + // pos + 1 == limit. This indicates that a '\r' was the last char + // in the buffer during a readLine. We'll want to maintain that + // condition after we shift things around and if a larger buffer is + // needed to track readLimit, we'll have to make it one element + // larger to ensure we don't invalidate the mark too early, if the + // char following the '\r' is NOT a '\n'. This is ok because, per + // the spec, we are not required to invalidate when passing readLimit. + // + // Note that if 'pos > limit', then doing 'limit -= pos' will cause + // limit to be negative. This is the only way limit will be < 0. + + if (pos + readLimit > limit) + { + char[] old_buffer = buffer; + int extraBuffSpace = 0; + if (pos > limit) + extraBuffSpace = 1; + if (readLimit + extraBuffSpace > limit) + buffer = new char[readLimit + extraBuffSpace]; + limit -= pos; + if (limit >= 0) + { + System.arraycopy(old_buffer, pos, buffer, 0, limit); + pos = 0; + } + } + + if (limit < 0) + { + // Maintain the relationship of 'pos > limit'. + pos = 1; + limit = markPos = 0; + } + else + markPos = pos; + // Now pos + readLimit <= buffer.length. thus if we need to read + // beyond buffer.length, then we are allowed to invalidate markPos. + } + } + + /** + * Reset the stream to the point where the <code>mark()</code> method + * was called. Any chars that were read after the mark point was set will + * be re-read during subsequent reads. + * <p> + * This method will throw an IOException if the number of chars read from + * the stream since the call to <code>mark()</code> exceeds the mark limit + * passed when establishing the mark. + * + * @exception IOException If an error occurs; + */ + public void reset() throws IOException + { + synchronized (lock) + { + checkStatus(); + if (markPos < 0) + throw new IOException("mark never set or invalidated"); + + // Need to handle the extremely unlikely case where a readLine was + // done with a '\r' as the last char in the buffer; which was then + // immediately followed by a mark and a reset with NO intervening + // read of any sort. In that case, setting pos to markPos would + // lose that info and a subsequent read would thus not skip a '\n' + // (if one exists). The value of limit in this rare case is zero. + // We can assume that if limit is zero for other reasons, then + // pos is already set to zero and doesn't need to be readjusted. + if (limit > 0) + pos = markPos; + } + } + + /** + * This method determines whether or not a stream is ready to be read. If + * this method returns <code>false</code> then this stream could (but is + * not guaranteed to) block on the next read attempt. + * + * @return <code>true</code> if this stream is ready to be read, + * <code>false</code> otherwise + * + * @exception IOException If an error occurs + */ + public boolean ready() throws IOException + { + synchronized (lock) + { + checkStatus(); + return pos < limit || in.ready(); + } + } + + /** + * This method read chars from a stream and stores them into a caller + * supplied buffer. It starts storing the data at index + * <code>offset</code> into + * the buffer and attempts to read <code>len</code> chars. This method can + * return before reading the number of chars requested. The actual number + * of chars read is returned as an int. A -1 is returned to indicate the + * end of the stream. + * <p> + * This method will block until some data can be read. + * + * @param buf The array into which the chars read should be stored + * @param offset The offset into the array to start storing chars + * @param count The requested number of chars to read + * + * @return The actual number of chars read, or -1 if end of stream. + * + * @exception IOException If an error occurs. + * @exception IndexOutOfBoundsException If offset and count are not + * valid regarding buf. + */ + public int read(char[] buf, int offset, int count) throws IOException + { + if (offset < 0 || offset + count > buf.length || count < 0) + throw new IndexOutOfBoundsException(); + + synchronized (lock) + { + checkStatus(); + // Once again, we need to handle the special case of a readLine + // that has a '\r' at the end of the buffer. In this case, we'll + // need to skip a '\n' if it is the next char to be read. + // This special case is indicated by 'pos > limit'. + boolean retAtEndOfBuffer = false; + + int avail = limit - pos; + if (count > avail) + { + if (avail > 0) + count = avail; + else // pos >= limit + { + if (limit == buffer.length) + markPos = -1; // read too far - invalidate the mark. + if (pos > limit) + { + // Set a boolean and make pos == limit to simplify things. + retAtEndOfBuffer = true; + --pos; + } + if (markPos < 0) + { + // Optimization: can read directly into buf. + if (count >= buffer.length && !retAtEndOfBuffer) + return in.read(buf, offset, count); + pos = limit = 0; + } + avail = in.read(buffer, limit, buffer.length - limit); + if (retAtEndOfBuffer && avail > 0 && buffer[limit] == '\n') + { + --avail; + limit++; + } + if (avail < count) + { + if (avail <= 0) + return avail; + count = avail; + } + limit += avail; + } + } + System.arraycopy(buffer, pos, buf, offset, count); + pos += count; + return count; + } + } + + /* Read more data into the buffer. Update pos and limit appropriately. + Assumes pos==limit initially. May invalidate the mark if read too much. + Return number of chars read (never 0), or -1 on eof. */ + private int fill() throws IOException + { + checkStatus(); + // Handle the special case of a readLine that has a '\r' at the end of + // the buffer. In this case, we'll need to skip a '\n' if it is the + // next char to be read. This special case is indicated by 'pos > limit'. + boolean retAtEndOfBuffer = false; + if (pos > limit) + { + retAtEndOfBuffer = true; + --pos; + } + + if (markPos >= 0 && limit == buffer.length) + markPos = -1; + if (markPos < 0) + pos = limit = 0; + int count = in.read(buffer, limit, buffer.length - limit); + if (count > 0) + limit += count; + + if (retAtEndOfBuffer && buffer[pos] == '\n') + { + --count; + // If the mark was set to the location of the \n, then we + // must change it to fully pretend that the \n does not + // exist. + if (markPos == pos) + ++markPos; + ++pos; + } + + return count; + } + + public int read() throws IOException + { + synchronized (lock) + { + checkStatus(); + if (pos >= limit && fill () <= 0) + return -1; + return buffer[pos++]; + } + } + + /* Return the end of the line starting at this.pos and ending at limit. + * The index returns is *before* any line terminators, or limit + * if no line terminators were found. + */ + private int lineEnd(int limit) + { + int i = pos; + for (; i < limit; i++) + { + char ch = buffer[i]; + if (ch == '\n' || ch == '\r') + break; + } + return i; + } + + /** + * This method reads a single line of text from the input stream, returning + * it as a <code>String</code>. A line is terminated by "\n", a "\r", or + * an "\r\n" sequence. The system dependent line separator is not used. + * The line termination characters are not returned in the resulting + * <code>String</code>. + * + * @return The line of text read, or <code>null</code> if end of stream. + * + * @exception IOException If an error occurs + */ + public String readLine() throws IOException + { + checkStatus(); + // Handle the special case where a previous readLine (with no intervening + // reads/skips) had a '\r' at the end of the buffer. + // In this case, we'll need to skip a '\n' if it's the next char to be read. + // This special case is indicated by 'pos > limit'. + if (pos > limit) + { + int ch = read(); + if (ch < 0) + return null; + if (ch != '\n') + --pos; + } + int i = lineEnd(limit); + if (i < limit) + { + String str = String.valueOf(buffer, pos, i - pos); + pos = i + 1; + // If the last char in the buffer is a '\r', we must remember + // to check if the next char to be read after the buffer is refilled + // is a '\n'. If so, skip it. To indicate this condition, we set pos + // to be limit + 1, which normally is never possible. + if (buffer[i] == '\r') + if (pos == limit || buffer[pos] == '\n') + pos++; + return str; + } + if (sbuf == null) + sbuf = new StringBuffer(200); + else + sbuf.setLength(0); + sbuf.append(buffer, pos, i - pos); + pos = i; + // We only want to return null when no characters were read before + // EOF. So we must keep track of this separately. Otherwise we + // would treat an empty `sbuf' as an EOF condition, which is wrong + // when there is just a newline. + boolean eof = false; + for (;;) + { + // readLine should block. So we must not return until a -1 is reached. + if (pos >= limit) + { + // here count == 0 isn't sufficient to give a failure. + int count = fill(); + if (count < 0) + { + eof = true; + break; + } + continue; + } + int ch = buffer[pos++]; + if (ch == '\n' || ch == '\r') + { + // Check here if a '\r' was the last char in the buffer; if so, + // mark it as in the comment above to indicate future reads + // should skip a newline that is the next char read after + // refilling the buffer. + if (ch == '\r') + if (pos == limit || buffer[pos] == '\n') + pos++; + break; + } + i = lineEnd(limit); + sbuf.append(buffer, pos - 1, i - (pos - 1)); + pos = i; + } + return (sbuf.length() == 0 && eof) ? null : sbuf.toString(); + } + + /** + * This method skips the specified number of chars in the stream. It + * returns the actual number of chars skipped, which may be less than the + * requested amount. + * <p> + * This method first discards chars in the buffer, then calls the + * <code>skip</code> method on the underlying stream to skip the + * remaining chars. + * + * @param count The requested number of chars to skip + * + * @return The actual number of chars skipped. + * + * @exception IOException If an error occurs. + * @exception IllegalArgumentException If count is negative. + */ + public long skip(long count) throws IOException + { + synchronized (lock) + { + checkStatus(); + if (count < 0) + throw new IllegalArgumentException("skip value is negative"); + if (count == 0) + return 0; + // Yet again, we need to handle the special case of a readLine + // that has a '\r' at the end of the buffer. In this case, we need + // to ignore a '\n' if it is the next char to be read. + // This special case is indicated by 'pos > limit' (i.e. avail < 0). + // To simplify things, if we're dealing with the special case for + // readLine, just read the next char (since the fill method will + // skip the '\n' for us). By doing this, we'll have to back up pos. + // That's easier than trying to keep track of whether we've skipped + // one element or not. + if (pos > limit) + { + if (read() < 0) + return 0; + else + --pos; + } + + int avail = limit - pos; + + if (count < avail) + { + pos += count; + return count; + } + + pos = limit; + long todo = count - avail; + if (todo > buffer.length) + { + markPos = -1; + todo -= in.skip(todo); + } + else + { + while (todo > 0) + { + avail = fill(); + if (avail <= 0) + break; + if (avail > todo) + avail = (int) todo; + pos += avail; + todo -= avail; + } + } + return count - todo; + } + } + + private void checkStatus() throws IOException + { + if (in == null) + throw new IOException("Stream closed"); + } +} Added: trunk/core/src/classpath/java/java/io/BufferedWriter.java =================================================================== --- trunk/core/src/classpath/java/java/io/BufferedWriter.java (rev 0) +++ trunk/core/src/classpath/java/java/io/BufferedWriter.java 2006-12-12 21:09:56 UTC (rev 2896) @@ -0,0 +1,262 @@ +/* BufferedWriter.java -- Buffer output into large blocks before writing + 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.io; + +/* Written using "Java Class Libraries", 2nd edition, ISBN 0-201-31002-3 + * "The Java Language Specification", ISBN 0-201-63451-1 + * Status: Complete to version 1.1. + */ + +/** + * This class accumulates chars written in a buffer instead of immediately + * writing the data to the underlying output sink. The chars are instead + * as one large block when the buffer is filled, or when the stream is + * closed or explicitly flushed. This mode operation can provide a more + * efficient mechanism for writing versus doing numerous small unbuffered + * writes. + * + * @author Aaron M. Renn (ar...@ur...) + * @author Tom Tromey (tr...@cy...) + * @date September 25, 1998 + */ +public class BufferedWriter extends Writer +{ + /** + * This is the default buffer size + */ + private static final int DEFAULT_BUFFER_SIZE = 8192; + + /** + * This is the underlying <code>Writer</code> to which this object + * sends its output. + */ + private Writer out; + + /** + * This is the internal char array used for buffering output before + * writing it. + */ + char[] buffer; + + /** + * This is the number of chars that are currently in the buffer and + * are waiting to be written to the underlying stream. It always points to + * the index into the buffer where the next char of data will be stored + */ + int count; + + /** + * This method initializes a new <code>BufferedWriter</code> instance + * that will write to the specified subordinate <code>Writer</code> + * and which will use a default buffer size of 8192 chars. + * + * @param out The underlying <code>Writer</code> to write data to + */ + public BufferedWriter (Writer out) + { + this (out, DEFAULT_BUFFER_SIZE); + } + + /** + * This method initializes a new <code>BufferedWriter</code> instance + * that will write to the specified subordinate <code>Writer</code> + * and which will use the specified buffer size + * + * @param out The underlying <code>Writer</code> to write data to + * @param size The size of the internal buffer + */ + public BufferedWriter (Writer out, int size) + { + super(out.lock); + this.out = out; + this.buffer = new char[size]; + this.count = 0; + } + + /** + * This method flushes any remaining buffered chars then closes the + * underlying output stream. Any further attempts to write to this stream + * may throw an exception + * + * @exception IOException If an error occurs. + */ + public void close () throws IOException + { + synchronized (lock) + { + // It is safe to call localFlush even if the stream is already + // closed. + localFlush (); + out.close(); + buffer = null; + } + } + + /** + * This method causes any currently buffered chars to be immediately + * written to the underlying output stream. + * + * @exception IOException If an error occurs + */ + public void flush () throws IOException + { + synchronized (lock) + { + if (buffer == null) + throw new IOException ("Stream closed"); + localFlush (); + out.flush(); + } + } + + /** + * This method writes out a system depedent line separator sequence. The + * actual value written is detemined from the <xmp>line.separator</xmp> + * system property. + * + * @exception IOException If an error occurs + */ + public void newLine () throws IOException + { + write (System.getProperty("line.separator")); + } + + /** + * This method writes a single char of data. This will be written to the + * buffer instead of the underlying data source. However, if the buffer + * is filled as a result of this write request, it will be flushed to the + * underlying output stream. + * + * @param oneChar The char of data to be written, passed as an int + * + * @exception IOException If an error occurs + */ + public void write (int oneChar) throws IOException + { + synchronized (lock) + { + if (buffer == null) + throw new IOException ("Stream closed"); + buffer[count++] = (char) oneChar; + if (count == buffer.length) + localFlush (); + } + } + + /** + * This method writes <code>len</code> chars from the char array + * <code>buf</code> starting at position <code>offset</code> in the buffer. + * These chars will be written to the internal buffer. However, if this + * write operation fills the buffer, the buffer will be flushed to the + * underlying output stream. + * + * @param buf The array of chars to write. + * @param offset The index into the char array to start writing from. + * @param len The number of chars to write. + * + * @exception IOException If an error occurs + */ + public void write (char[] buf, int offset, int len) throws IOException + { + synchronized (lock) + { + if (buffer == null) + throw new IOException ("Stream closed"); + + // Bypass buffering if there is too much incoming data. + if (count + len > buffer.length) + { + localFlush (); + out.write(buf, offset, len); + } + else + { + System.arraycopy(buf, offset, buffer, count, len); + count += len; + if (count == buffer.length) + localFlush (); + } + } + } + + /** + * This method writes <code>len</code> chars from the <code>String</code> + * <code>str</code> starting at position <code>offset</code> in the string. + * These chars will be written to the internal buffer. However, if this + * write operation fills the buffer, the buffer will be flushed to the + * underlying output stream. + * + * @param str The <code>String</code> to write. + * @param offset The index into the string to start writing from. + * @param len The number of chars to write. + * + * @exception IOException If an error occurs + */ + public void write (String str, int offset, int len) throws IOException + { + synchronized (lock) + { + if (buffer == null) + throw new IOException ("Stream closed"); + + if (count + len > buffer.length) + { + localFlush (); + out.write(str, offset, len); + } + else + { + str.getChars(offset, offset + len, buffer, count); + count += len; + if (count == buffer.length) + localFlush (); + } + } + } + + // This should only be called with the lock held. + private void localFlush () throws IOException + { + if (count > 0) + { + out.write(buffer, 0, count); + count = 0; + } + } +} Added: trunk/core/src/classpath/java/java/io/ByteArrayInputStream.java =================================================================== --- trunk/core/src/classpath/java/java/io/ByteArrayInputStream.java (rev 0) +++ trunk/core/src/classpath/java/java/io/ByteArrayInputStream.java 2006-12-12 21:09:56 UTC (rev 2896) @@ -0,0 +1,251 @@ +/* ByteArrayInputStream.java -- Read an array as a stream + Copyright (C) 1998, 1999, 2001, 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.io; + +/** + * This class permits an array of bytes to be read as an input stream. + * + * @author Warren Levy (wa...@cy...) + * @author Aaron M. Renn (ar...@ur...) + */ +public class ByteArrayInputStream extends InputStream +{ + /** + * The array that contains the data supplied during read operations + */ + protected byte[] buf; + + /** + * The array index of the next byte to be read from the buffer + * <code>buf</code> + */ + protected int pos; + + /** + * The currently marked position in the stream. This defaults to 0, so a + * reset operation on the stream resets it to read from array index 0 in + * the buffer - even if the stream was initially created with an offset + * greater than 0 + */ + protected int mark; + + /** + * This indicates the maximum number of bytes that can be read from this + * stream. It is the array index of the position after the last valid + * byte in the buffer <code>buf</code> + */ + protected int count; + + /** + * Create a new ByteArrayInputStream that will read bytes from the passed + * in byte array. This stream will read from the beginning to the end + * of the array. It is identical to calling an overloaded constructor + * as <code>ByteArrayInputStream(buf, 0, buf.length)</code>. + * <p> + * Note that this array is not copied. If its contents are changed + * while this stream is being read, those changes will be reflected in the + * bytes supplied to the reader. Please use caution in changing the + * contents of the buffer while this stream is open. + * + * @param buffer The byte array buffer this stream will read from. + */ + public ByteArrayInputStream(byte[] buffer) + { + this(buffer, 0, buffer.length); + } + + /** + * Create a new ByteArrayInputStream that will read bytes from the + * passed in byte array. This stream will read from position + * <code>offset</code> in the array for a length of + * <code>length</code> bytes past <code>offset</code>. If the + * stream is reset to a position before <code>offset</code> then + * more than <code>length</code> bytes can be read from the stream. + * The <code>length</code> value should be viewed as the array index + * one greater than the last position in the buffer to read. + * <p> + * Note that this array is not copied. If its contents are changed + * while this stream is being read, those changes will be reflected in the + * bytes supplied to the reader. Please use caution in changing the + * contents of the buffer while this stream is open. + * + * @param buffer The byte array buffer this stream will read from. + * @param offset The index into the buffer to start reading bytes from + * @param length The number of bytes to read from the buffer + */ + public ByteArrayInputStream(byte[] buffer, int offset, int length) + { + if (offset < 0 || length < 0 || offset > buffer.length) + throw new IllegalArgumentException(); + + buf = buffer; + + count = offset + length; + if (count > buf.length) + count = buf.length; + + pos = offset; + mark = pos; + } + + /** + * This method returns the number of bytes available to be read from this + * stream. The value returned will be equal to <code>count - pos</code>. + * + * @return The number of bytes that can be read from this stream + * before blocking, which is all of them + */ + public synchronized int available() + { + return count - pos; + } + + /** + * This method sets the mark position in this stream to the current + * position. Note that the <code>readlimit</code> parameter in this + * method does nothing as this stream is always capable of + * remembering all the bytes int it. + * <p> + * Note that in this class the mark position is set by default to + * position 0 in the stream. This is in constrast to some other + * stream types where there is no default mark position. + * + * @param readLimit The number of bytes this stream must remember. + * This parameter is ignored. + */ + public synchronized void mark(int readLimit) + { + // readLimit is ignored per Java Class Lib. book, p.220. + mark = pos; + } + + /** + * This method overrides the <code>markSupported</code> method in + * <code>InputStream</code> in order to return <code>true</code> - + * indicating that this stream class supports mark/reset + * functionality. + * + * @return <code>true</code> to indicate that this class supports + * mark/reset. + */ + public boolean markSupported() + { + return true; + } + + /** + * This method reads one byte from the stream. The <code>pos</code> + * counter is advanced to the next byte to be read. The byte read is + * returned as an int in the range of 0-255. If the stream position + * is already at the end of the buffer, no by... [truncated message content] |
From: <Qa...@us...> - 2006-12-12 07:47:46
|
Revision: 2895 http://jnode.svn.sourceforge.net/jnode/?rev=2895&view=rev Author: QaDeS Date: 2006-12-11 23:47:44 -0800 (Mon, 11 Dec 2006) Log Message: ----------- inverted mouse wheel scrolling Modified Paths: -------------- trunk/core/src/driver/org/jnode/driver/console/textscreen/ScrollableTextScreenConsole.java Modified: trunk/core/src/driver/org/jnode/driver/console/textscreen/ScrollableTextScreenConsole.java =================================================================== --- trunk/core/src/driver/org/jnode/driver/console/textscreen/ScrollableTextScreenConsole.java 2006-12-10 22:12:03 UTC (rev 2894) +++ trunk/core/src/driver/org/jnode/driver/console/textscreen/ScrollableTextScreenConsole.java 2006-12-12 07:47:44 UTC (rev 2895) @@ -103,9 +103,9 @@ if (isFocused() && (event.getZ() != 0)) { final int z = event.getZ(); if (z < 0) { + scrollUp(Math.abs(z)); + } else { scrollDown(Math.abs(z)); - } else { - scrollUp(Math.abs(z)); } event.consume(); } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |