|
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();
+ ...
[truncated message content] |
|
From: <ls...@us...> - 2007-01-07 12:37:20
|
Revision: 3017
http://jnode.svn.sourceforge.net/jnode/?rev=3017&view=rev
Author: lsantha
Date: 2007-01-07 04:37:19 -0800 (Sun, 07 Jan 2007)
Log Message:
-----------
Classpath patches.
Modified Paths:
--------------
trunk/core/src/classpath/gnu/gnu/java/lang/management/MemoryPoolMXBeanImpl.java
trunk/core/src/classpath/gnu/gnu/java/lang/management/OperatingSystemMXBeanImpl.java
trunk/core/src/classpath/gnu/gnu/java/lang/management/ThreadMXBeanImpl.java
trunk/core/src/classpath/gnu/gnu/java/net/DefaultContentHandlerFactory.java
trunk/core/src/classpath/gnu/gnu/java/net/GetLocalHostAction.java
trunk/core/src/classpath/gnu/gnu/java/net/HeaderFieldHelper.java
trunk/core/src/classpath/gnu/gnu/java/net/IndexListParser.java
trunk/core/src/classpath/gnu/gnu/java/net/loader/JarURLLoader.java
trunk/core/src/classpath/gnu/gnu/java/net/loader/URLLoader.java
trunk/core/src/classpath/gnu/gnu/java/net/loader/URLStreamHandlerCache.java
trunk/core/src/classpath/gnu/gnu/java/net/protocol/ftp/FTPConnection.java
trunk/core/src/classpath/gnu/gnu/java/net/protocol/ftp/FTPURLConnection.java
trunk/core/src/classpath/gnu/gnu/java/net/protocol/http/ChunkedInputStream.java
trunk/core/src/classpath/gnu/gnu/java/net/protocol/http/HTTPConnection.java
trunk/core/src/classpath/gnu/gnu/java/net/protocol/http/HTTPURLConnection.java
trunk/core/src/classpath/gnu/gnu/java/net/protocol/http/Headers.java
trunk/core/src/classpath/gnu/gnu/java/net/protocol/http/Request.java
trunk/core/src/classpath/gnu/gnu/java/net/protocol/http/SimpleCookieManager.java
trunk/core/src/classpath/gnu/gnu/java/net/protocol/jar/Connection.java
trunk/core/src/classpath/gnu/gnu/java/net/protocol/jar/Handler.java
trunk/core/src/classpath/gnu/gnu/java/security/action/GetPropertyAction.java
trunk/core/src/classpath/gnu/gnu/java/security/action/GetSecurityPropertyAction.java
Added Paths:
-----------
trunk/core/src/classpath/gnu/gnu/java/math/Fixed.java
trunk/core/src/classpath/gnu/gnu/java/net/DefaultProxySelector.java
trunk/core/src/classpath/gnu/gnu/java/security/Requires.java
trunk/core/src/classpath/gnu/gnu/java/security/util/ByteBufferOutputStream.java
trunk/core/src/classpath/gnu/gnu/java/security/x509/ext/GeneralName.java
trunk/core/src/classpath/gnu/gnu/java/security/x509/ext/GeneralSubtree.java
trunk/core/src/classpath/gnu/gnu/java/security/x509/ext/NameConstraints.java
Modified: trunk/core/src/classpath/gnu/gnu/java/lang/management/MemoryPoolMXBeanImpl.java
===================================================================
--- trunk/core/src/classpath/gnu/gnu/java/lang/management/MemoryPoolMXBeanImpl.java 2007-01-07 12:36:12 UTC (rev 3016)
+++ trunk/core/src/classpath/gnu/gnu/java/lang/management/MemoryPoolMXBeanImpl.java 2007-01-07 12:37:19 UTC (rev 3017)
@@ -41,6 +41,7 @@
import java.lang.management.MemoryPoolMXBean;
import java.lang.management.MemoryUsage;
+import java.lang.management.MemoryType;
import javax.management.NotCompliantMBeanException;
@@ -133,9 +134,9 @@
return null;
}
- public String getType()
+ public MemoryType getType()
{
- return VMMemoryPoolMXBeanImpl.getType(name);
+ return null;
}
public MemoryUsage getUsage()
Modified: trunk/core/src/classpath/gnu/gnu/java/lang/management/OperatingSystemMXBeanImpl.java
===================================================================
--- trunk/core/src/classpath/gnu/gnu/java/lang/management/OperatingSystemMXBeanImpl.java 2007-01-07 12:36:12 UTC (rev 3016)
+++ trunk/core/src/classpath/gnu/gnu/java/lang/management/OperatingSystemMXBeanImpl.java 2007-01-07 12:37:19 UTC (rev 3017)
@@ -86,5 +86,10 @@
{
return System.getProperty("os.version");
}
-
+
+
+ public double getSystemLoadAverage() {
+ //todo implement
+ throw new UnsupportedOperationException();
+ }
}
Modified: trunk/core/src/classpath/gnu/gnu/java/lang/management/ThreadMXBeanImpl.java
===================================================================
--- trunk/core/src/classpath/gnu/gnu/java/lang/management/ThreadMXBeanImpl.java 2007-01-07 12:36:12 UTC (rev 3016)
+++ trunk/core/src/classpath/gnu/gnu/java/lang/management/ThreadMXBeanImpl.java 2007-01-07 12:37:19 UTC (rev 3017)
@@ -287,5 +287,30 @@
"supported.");
}
+
+ public ThreadInfo[] dumpAllThreads(boolean lockedMonitors, boolean lockedSynchronizers) {
+ //todo implement
+ throw new UnsupportedOperationException();
+ }
+
+ public long[] findDeadlockedThreads() {
+ //todo implement
+ throw new UnsupportedOperationException();
+ }
+
+ public ThreadInfo[] getThreadInfo(long[] ids, boolean lockedMonitors, boolean lockedSynchronizers) {
+ //todo implement
+ throw new UnsupportedOperationException();
+ }
+
+ public boolean isObjectMonitorUsageSupported() {
+ //todo implement
+ throw new UnsupportedOperationException();
+ }
+
+ public boolean isSynchronizerUsageSupported() {
+ //todo implement
+ throw new UnsupportedOperationException();
+ }
}
Added: trunk/core/src/classpath/gnu/gnu/java/math/Fixed.java
===================================================================
--- trunk/core/src/classpath/gnu/gnu/java/math/Fixed.java (rev 0)
+++ trunk/core/src/classpath/gnu/gnu/java/math/Fixed.java 2007-01-07 12:37:19 UTC (rev 3017)
@@ -0,0 +1,207 @@
+/* Fixed.java -- Utility methods for fixed point arithmetics
+ 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.math;
+
+/**
+ * Utility methods for fixed point arithmetics.
+ */
+public final class Fixed
+{
+
+ /**
+ * Private constructor to avoid instantiation.
+ */
+ private Fixed()
+ {
+ // Forbidden constructor.
+ }
+
+ /**
+ * Divides two fixed point values with <code>n</code> digits.
+ *
+ * @param n the number of digits
+ * @param a the first operand as fixed point value
+ * @param b the second operand as fixed point value
+ *
+ * @return <code>a / b</code> as fixed point value
+ */
+ public static int div(int n, int a, int b)
+ {
+ return (int) ((((long) a) << n) / b);
+ }
+
+ /**
+ * Multiplies two fixed point values with <code>n</code> digits.
+ *
+ * @param n the number of digits
+ * @param a the first operand as fixed point value
+ * @param b the second operand as fixed point value
+ *
+ * @return <code>a * b</code> as fixed point value
+ */
+ public static int mul(int n, int a, int b)
+ {
+ return (int) ((((long) a) * b) >> n);
+ }
+
+ /**
+ * Returns the ceiling value of a fixed point value <code>a</code> with
+ * the <code>n</code> digits.
+ *
+ * @param n the number of digits
+ * @param a the fixed point value
+ *
+ * @return <code>ceil(a)</code> as fixed point value
+ */
+ public static int ceil(int n, int a)
+ {
+ return (a + (1 << n - 1)) & -(1 << n);
+ }
+
+ /**
+ * Returns the floor value of a fixed point value <code>a</code> with
+ * <code>n</code> digits.
+ *
+ * @param n the number of digits
+ * @param a the fixed point value
+ *
+ * @return <code>floor(a)</code> as fixed point value
+ */
+ public static int floor(int n, int a)
+ {
+ return a & -(1 << n);
+ }
+
+ /**
+ * Returns the round value of a fixed point value <code>a</code> with
+ * the <code>n</code> digits.
+ *
+ * @param n the number of digits
+ * @param a the fixed point value
+ *
+ * @return <code>round(a)</code> as fixed point value
+ */
+ public static int round(int n, int a)
+ {
+ return (a + (1 << (n - 1))) & -(1 << n);
+ }
+
+ /**
+ * Returns the fixed point value <code>a</code> with <code>n</code> digits
+ * as float.
+ *
+ * @param n the number of digits
+ * @param a the fixed point value
+ *
+ * @return the float value of <code>a</code>
+ */
+ public static float floatValue(int n, int a)
+ {
+ return ((float) a) / (1 << n);
+ }
+
+ /**
+ * Returns the fixed point value <code>a</code> with <code>n</code> digits
+ * as double.
+ *
+ * @param n the number of digits
+ * @param a the fixed point value
+ *
+ * @return the double value of <code>a</code>
+ */
+ public static double doubleValue(int n, int a)
+ {
+ return ((double) a) / (1 << n);
+ }
+
+ /**
+ * Returns the fixed point value that corresponds to the specified float
+ * value <code>a</code> with <code>n</code> digits.
+ *
+ * @param n the number of digits
+ * @param a the float value
+ *
+ * @return the fixed point value
+ */
+ public static int fixedValue(int n, float a)
+ {
+ return (int) (a * (1 << n));
+ }
+
+ /**
+ * Returns the fixed point value that corresponds to the specified double
+ * value <code>a</code> with <code>n</code> digits.
+ *
+ * @param n the number of digits
+ * @param a the double value
+ *
+ * @return the fixed point value
+ */
+ public static int fixedValue(int n, double a)
+ {
+ return (int) (a * (1 << n));
+ }
+
+ /**
+ * Returns the integer value of the specified fixed point value
+ * <code>a</code>. This simply cuts of the digits (== floor(a)).
+ *
+ * @param n the number of digits
+ * @param a the fixed point value
+ *
+ * @return the integer value
+ */
+ public static int intValue(int n, int a)
+ {
+ return a >> n;
+ }
+
+ /**
+ * Returns a fixed point decimal as rounded integer value.
+ *
+ * @param n the number of digits
+ * @param a the fixed point number
+ *
+ * @return the fixed point decimal as rounded integer value
+ */
+ public static int roundIntValue(int n, int a)
+ {
+ return (a + (1 << (n - 1))) >> n;
+ }
+}
Modified: trunk/core/src/classpath/gnu/gnu/java/net/DefaultContentHandlerFactory.java
===================================================================
--- trunk/core/src/classpath/gnu/gnu/java/net/DefaultContentHandlerFactory.java 2007-01-07 12:36:12 UTC (rev 3016)
+++ trunk/core/src/classpath/gnu/gnu/java/net/DefaultContentHandlerFactory.java 2007-01-07 12:37:19 UTC (rev 3017)
@@ -81,8 +81,8 @@
"image/x-xpixmap"
};
- private static HashSet imageTypes
- = new HashSet(Arrays.asList(known_image_types));
+ private static HashSet<String> imageTypes
+ = new HashSet<String>(Arrays.asList(known_image_types));
public ContentHandler createContentHandler(String mimeType)
{
Added: trunk/core/src/classpath/gnu/gnu/java/net/DefaultProxySelector.java
===================================================================
--- trunk/core/src/classpath/gnu/gnu/java/net/DefaultProxySelector.java (rev 0)
+++ trunk/core/src/classpath/gnu/gnu/java/net/DefaultProxySelector.java 2007-01-07 12:37:19 UTC (rev 3017)
@@ -0,0 +1,80 @@
+/* DefaultProxySelector.java --
+ 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.net;
+
+import java.io.IOException;
+import java.net.Proxy;
+import java.net.ProxySelector;
+import java.net.SocketAddress;
+import java.net.URI;
+import java.util.ArrayList;
+import java.util.List;
+
+public final class DefaultProxySelector
+ extends ProxySelector
+{
+ private static final List<Proxy> proxies = new ArrayList<Proxy>();
+
+ static
+ {
+ // The default proxy selector supports only direct connections.
+ proxies.add(Proxy.NO_PROXY);
+ }
+
+ public DefaultProxySelector()
+ {
+ // Do nothing by default.
+ }
+
+ public void connectFailed(URI uri, SocketAddress sa, IOException ioe)
+ {
+ if (uri == null || sa == null || ioe == null)
+ throw new IllegalArgumentException();
+
+ // Do nothing by default.
+ }
+
+ public List<Proxy> select(URI uri)
+ {
+ if (uri == null)
+ throw new IllegalArgumentException();
+
+ return proxies;
+ }
+}
Modified: trunk/core/src/classpath/gnu/gnu/java/net/GetLocalHostAction.java
===================================================================
--- trunk/core/src/classpath/gnu/gnu/java/net/GetLocalHostAction.java 2007-01-07 12:36:12 UTC (rev 3016)
+++ trunk/core/src/classpath/gnu/gnu/java/net/GetLocalHostAction.java 2007-01-07 12:37:19 UTC (rev 3017)
@@ -48,9 +48,9 @@
* @author Chris Burdess (do...@gn...)
*/
public class GetLocalHostAction
- implements PrivilegedAction
+ implements PrivilegedAction<InetAddress>
{
- public Object run()
+ public InetAddress run()
{
try
{
Modified: trunk/core/src/classpath/gnu/gnu/java/net/HeaderFieldHelper.java
===================================================================
--- trunk/core/src/classpath/gnu/gnu/java/net/HeaderFieldHelper.java 2007-01-07 12:36:12 UTC (rev 3016)
+++ trunk/core/src/classpath/gnu/gnu/java/net/HeaderFieldHelper.java 2007-01-07 12:37:19 UTC (rev 3017)
@@ -49,8 +49,8 @@
*/
public class HeaderFieldHelper
{
- private Vector headerFieldKeys;
- private Vector headerFieldValues;
+ private Vector<String> headerFieldKeys;
+ private Vector<String> headerFieldValues;
public HeaderFieldHelper()
{
@@ -59,8 +59,8 @@
public HeaderFieldHelper (int size)
{
- headerFieldKeys = new Vector (size);
- headerFieldValues = new Vector (size);
+ headerFieldKeys = new Vector<String> (size);
+ headerFieldValues = new Vector<String> (size);
}
public void addHeaderField (String key, String value)
@@ -75,7 +75,7 @@
try
{
- key = (String) headerFieldKeys.elementAt (index);
+ key = headerFieldKeys.elementAt (index);
}
catch (ArrayIndexOutOfBoundsException e)
{
@@ -90,7 +90,7 @@
try
{
- value = (String) headerFieldValues.elementAt (index);
+ value = headerFieldValues.elementAt (index);
}
catch (ArrayIndexOutOfBoundsException e)
{
@@ -105,8 +105,7 @@
try
{
- value = (String) headerFieldValues.elementAt
- (headerFieldKeys.indexOf(key));
+ value = headerFieldValues.elementAt(headerFieldKeys.indexOf(key));
}
catch (ArrayIndexOutOfBoundsException e)
{
@@ -115,9 +114,9 @@
return value;
}
- public Map getHeaderFields()
+ public Map<String, String> getHeaderFields()
{
- HashMap headers = new HashMap();
+ HashMap<String, String> headers = new HashMap<String, String>();
int max = headerFieldKeys.size();
for (int index = 0; index < max; index++)
Modified: trunk/core/src/classpath/gnu/gnu/java/net/IndexListParser.java
===================================================================
--- trunk/core/src/classpath/gnu/gnu/java/net/IndexListParser.java 2007-01-07 12:36:12 UTC (rev 3016)
+++ trunk/core/src/classpath/gnu/gnu/java/net/IndexListParser.java 2007-01-07 12:37:19 UTC (rev 3017)
@@ -43,6 +43,7 @@
import java.net.URL;
import java.util.HashSet;
import java.util.LinkedHashMap;
+import java.util.Set;
import java.util.jar.JarFile;
/**
@@ -70,7 +71,8 @@
double versionNumber;
// Map each jar to the prefixes defined for the jar.
// This is intentionally kept in insertion order.
- LinkedHashMap prefixes = new LinkedHashMap();
+ LinkedHashMap<URL, Set<String>> prefixes
+ = new LinkedHashMap<URL, Set<String>>();
/**
* Parses the given jarfile's INDEX.LIST file if it exists.
@@ -107,7 +109,7 @@
while ((line = br.readLine()) != null)
{
URL jarURL = new URL(baseURL, line);
- HashSet values = new HashSet();
+ HashSet<String> values = new HashSet<String>();
// Read the names in the section.
while ((line = br.readLine()) != null)
@@ -174,7 +176,7 @@
*
* @return an map of all the headers, or null if no INDEX.LIST was found
*/
- public LinkedHashMap getHeaders()
+ public LinkedHashMap<URL, Set<String>> getHeaders()
{
return prefixes;
}
Modified: trunk/core/src/classpath/gnu/gnu/java/net/loader/JarURLLoader.java
===================================================================
--- trunk/core/src/classpath/gnu/gnu/java/net/loader/JarURLLoader.java 2007-01-07 12:36:12 UTC (rev 3016)
+++ trunk/core/src/classpath/gnu/gnu/java/net/loader/JarURLLoader.java 2007-01-07 12:37:19 UTC (rev 3017)
@@ -32,7 +32,7 @@
// Base jar: url for all resources loaded from jar.
final URL baseJarURL;
// The "Class-Path" attribute of this Jar's manifest.
- ArrayList classPath;
+ ArrayList<URLLoader> classPath;
// If not null, a mapping from INDEX.LIST for this jar only.
// This is a set of all prefixes and top-level files that
// ought to be available in this jar.
@@ -90,20 +90,20 @@
IndexListParser parser = new IndexListParser(jarfile, baseJarURL,
baseURL);
- LinkedHashMap indexMap = parser.getHeaders();
+ LinkedHashMap<URL, Set<String>> indexMap = parser.getHeaders();
if (indexMap != null)
{
// Note that the index also computes
// the resulting Class-Path -- there are jars out there
// where the index lists some required jars which do
// not appear in the Class-Path attribute in the manifest.
- this.classPath = new ArrayList();
- Iterator it = indexMap.entrySet().iterator();
+ this.classPath = new ArrayList<URLLoader>();
+ Iterator<Map.Entry<URL, Set<String>>> it = indexMap.entrySet().iterator();
while (it.hasNext())
{
- Map.Entry entry = (Map.Entry) it.next();
- URL subURL = (URL) entry.getKey();
- Set prefixes = (Set) entry.getValue();
+ Map.Entry<URL, Set<String>> entry = it.next();
+ URL subURL = entry.getKey();
+ Set<String> prefixes = entry.getValue();
if (subURL.equals(baseURL))
this.indexSet = prefixes;
else
@@ -127,7 +127,7 @@
= attributes.getValue(Attributes.Name.CLASS_PATH))
!= null))
{
- this.classPath = new ArrayList();
+ this.classPath = new ArrayList<URLLoader>();
StringTokenizer st = new StringTokenizer(classPathString, " ");
while (st.hasMoreElements ())
{
@@ -144,7 +144,7 @@
cache, factory,
subURL, subURL);
this.classPath.add(subLoader);
- ArrayList extra = subLoader.getClassPath();
+ ArrayList<URLLoader> extra = subLoader.getClassPath();
if (extra != null)
this.classPath.addAll(extra);
}
@@ -208,7 +208,7 @@
}
}
- public ArrayList getClassPath()
+ public ArrayList<URLLoader> getClassPath()
{
return classPath;
}
Modified: trunk/core/src/classpath/gnu/gnu/java/net/loader/URLLoader.java
===================================================================
--- trunk/core/src/classpath/gnu/gnu/java/net/loader/URLLoader.java 2007-01-07 12:36:12 UTC (rev 3016)
+++ trunk/core/src/classpath/gnu/gnu/java/net/loader/URLLoader.java 2007-01-07 12:37:19 UTC (rev 3017)
@@ -140,7 +140,7 @@
* Return a list of new URLLoader objects representing any
* class path entries added by this container.
*/
- public ArrayList getClassPath()
+ public ArrayList<URLLoader> getClassPath()
{
return null;
}
Modified: trunk/core/src/classpath/gnu/gnu/java/net/loader/URLStreamHandlerCache.java
===================================================================
--- trunk/core/src/classpath/gnu/gnu/java/net/loader/URLStreamHandlerCache.java 2007-01-07 12:36:12 UTC (rev 3016)
+++ trunk/core/src/classpath/gnu/gnu/java/net/loader/URLStreamHandlerCache.java 2007-01-07 12:37:19 UTC (rev 3017)
@@ -51,7 +51,8 @@
* private protocol handler cache (also a HashMap), so we can avoid
* creating handlers each time the same protocol comes.
*/
- private HashMap factoryCache = new HashMap(5);
+ private HashMap<URLStreamHandlerFactory, HashMap<String, URLStreamHandler>> factoryCache
+ = new HashMap<URLStreamHandlerFactory, HashMap<String, URLStreamHandler>>(5);
public URLStreamHandlerCache()
{
@@ -62,7 +63,7 @@
// Since we only support three protocols so far, 5 is enough
// for cache initial size.
if (factory != null && factoryCache.get(factory) == null)
- factoryCache.put(factory, new HashMap(5));
+ factoryCache.put(factory, new HashMap<String, URLStreamHandler>(5));
}
public synchronized URLStreamHandler get(URLStreamHandlerFactory factory,
@@ -71,8 +72,8 @@
if (factory == null)
return null;
// Check if there're handler for the same protocol in cache.
- HashMap cache = (HashMap) factoryCache.get(factory);
- URLStreamHandler handler = (URLStreamHandler) cache.get(protocol);
+ HashMap<String, URLStreamHandler> cache = factoryCache.get(factory);
+ URLStreamHandler handler = cache.get(protocol);
if (handler == null)
{
// Add it to cache.
Modified: trunk/core/src/classpath/gnu/gnu/java/net/protocol/ftp/FTPConnection.java
===================================================================
--- trunk/core/src/classpath/gnu/gnu/java/net/protocol/ftp/FTPConnection.java 2007-01-07 12:36:12 UTC (rev 3016)
+++ trunk/core/src/classpath/gnu/gnu/java/net/protocol/ftp/FTPConnection.java 2007-01-07 12:37:19 UTC (rev 3017)
@@ -1139,7 +1139,7 @@
* @param pathname the directory pathname, or null
* @return a list of filenames(strings)
*/
- public List nameList(String pathname)
+ public List<String> nameList(String pathname)
throws IOException
{
if (dtp == null || transferMode == MODE_STREAM)
@@ -1164,7 +1164,7 @@
in = new BufferedInputStream(in);
in = new CRLFInputStream(in); // TODO ensure that TYPE is correct
LineInputStream li = new LineInputStream(in);
- List ret = new ArrayList();
+ ArrayList<String> ret = new ArrayList<String>();
for (String line = li.readLine();
line != null;
line = li.readLine())
Modified: trunk/core/src/classpath/gnu/gnu/java/net/protocol/ftp/FTPURLConnection.java
===================================================================
--- trunk/core/src/classpath/gnu/gnu/java/net/protocol/ftp/FTPURLConnection.java 2007-01-07 12:36:12 UTC (rev 3016)
+++ trunk/core/src/classpath/gnu/gnu/java/net/protocol/ftp/FTPURLConnection.java 2007-01-07 12:37:19 UTC (rev 3017)
@@ -50,7 +50,9 @@
import java.net.URL;
import java.net.URLConnection;
import java.security.AccessController;
+import java.util.ArrayList;
import java.util.HashMap;
+import java.util.List;
import java.util.Map;
/**
@@ -112,7 +114,7 @@
{
username = "anonymous";
GetLocalHostAction a = new GetLocalHostAction();
- InetAddress localhost =(InetAddress) AccessController.doPrivileged(a);
+ InetAddress localhost = AccessController.doPrivileged(a);
password = SystemProperties.getProperty("user.name") + "@" +
((localhost == null) ? "localhost" : localhost.getHostName());
}
@@ -232,9 +234,9 @@
return null;
}
- public Map getRequestProperties()
+ public Map<String, List<String>> getRequestProperties()
{
- Map map = new HashMap();
+ Map<String, List<String>> map = new HashMap<String, List<String>>();
addRequestPropertyValue(map, "passive");
addRequestPropertyValue(map, "representationType");
addRequestPropertyValue(map, "fileStructure");
@@ -242,10 +244,13 @@
return map;
}
- private void addRequestPropertyValue(Map map, String key)
+ private void addRequestPropertyValue(Map<String, List<String>> map,
+ String key)
{
String value = getRequestProperty(key);
- map.put(key, value);
+ ArrayList<String> l = new ArrayList<String>();
+ l.add(value);
+ map.put(key, l);
}
public void setRequestProperty(String key, String value)
Modified: trunk/core/src/classpath/gnu/gnu/java/net/protocol/http/ChunkedInputStream.java
===================================================================
--- trunk/core/src/classpath/gnu/gnu/java/net/protocol/http/ChunkedInputStream.java 2007-01-07 12:36:12 UTC (rev 3016)
+++ trunk/core/src/classpath/gnu/gnu/java/net/protocol/http/ChunkedInputStream.java 2007-01-07 12:37:19 UTC (rev 3017)
@@ -58,10 +58,6 @@
public class ChunkedInputStream
extends InputStream
{
-
- private static final byte CR = 0x0d;
- private static final byte LF = 0x0a;
-
Headers headers;
/** The underlying stream. */
Modified: trunk/core/src/classpath/gnu/gnu/java/net/protocol/http/HTTPConnection.java
===================================================================
--- trunk/core/src/classpath/gnu/gnu/java/net/protocol/http/HTTPConnection.java 2007-01-07 12:36:12 UTC (rev 3016)
+++ trunk/core/src/classpath/gnu/gnu/java/net/protocol/http/HTTPConnection.java 2007-01-07 12:37:19 UTC (rev 3017)
@@ -48,6 +48,7 @@
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;
+import java.net.SocketException;
import java.security.GeneralSecurityException;
import java.util.ArrayList;
import java.util.HashMap;
@@ -128,7 +129,7 @@
*/
protected int minorVersion;
- private final List handshakeCompletedListeners;
+ private final List<HandshakeCompletedListener> handshakeCompletedListeners;
/**
* The socket this connection communicates on.
@@ -153,7 +154,7 @@
/**
* Nonce values seen by this connection.
*/
- private Map nonceCounts;
+ private Map<String, Integer> nonceCounts;
/**
* The cookie manager for this connection.
@@ -227,17 +228,24 @@
* @param secure whether to use a secure connection
* @param connectionTimeout the connection timeout
* @param timeout the socket read timeout
+ *
+ * @throws IllegalArgumentException if either connectionTimeout or
+ * timeout less than zero.
*/
public HTTPConnection(String hostname, int port, boolean secure,
int connectionTimeout, int timeout)
{
+ if (connectionTimeout < 0 || timeout < 0)
+ throw new IllegalArgumentException();
+
this.hostname = hostname;
this.port = port;
this.secure = secure;
this.connectionTimeout = connectionTimeout;
this.timeout = timeout;
majorVersion = minorVersion = 1;
- handshakeCompletedListeners = new ArrayList(2);
+ handshakeCompletedListeners
+ = new ArrayList<HandshakeCompletedListener>(2);
}
/**
@@ -350,7 +358,8 @@
/**
* The pool
*/
- final LinkedList connectionPool = new LinkedList();
+ final LinkedList<HTTPConnection> connectionPool
+ = new LinkedList<HTTPConnection>();
/**
* Maximum si...
[truncated message content] |
|
From: <ls...@us...> - 2007-01-07 18:39:40
|
Revision: 3042
http://jnode.svn.sourceforge.net/jnode/?rev=3042&view=rev
Author: lsantha
Date: 2007-01-07 10:39:36 -0800 (Sun, 07 Jan 2007)
Log Message:
-----------
Classpath patches.
Modified Paths:
--------------
trunk/core/src/classpath/gnu/gnu/java/io/Base64InputStream.java
trunk/core/src/classpath/gnu/gnu/java/lang/InstrumentationImpl.java
trunk/core/src/classpath/gnu/gnu/java/lang/management/BeanImpl.java
trunk/core/src/classpath/gnu/gnu/java/lang/management/MemoryMXBeanImpl.java
trunk/core/src/classpath/gnu/gnu/java/lang/management/MemoryPoolMXBeanImpl.java
trunk/core/src/classpath/gnu/gnu/java/lang/management/OperatingSystemMXBeanImpl.java
trunk/core/src/classpath/gnu/gnu/java/lang/management/ThreadMXBeanImpl.java
trunk/core/src/classpath/gnu/gnu/java/lang/reflect/ClassSignatureParser.java
trunk/core/src/classpath/gnu/gnu/java/lang/reflect/GenericSignatureParser.java
trunk/core/src/classpath/gnu/gnu/java/lang/reflect/MethodSignatureParser.java
trunk/core/src/classpath/gnu/gnu/java/nio/charset/ByteCharset.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/rmi/server/ActivatableRef.java
trunk/core/src/classpath/gnu/gnu/java/rmi/server/RMIObjectInputStream.java
trunk/core/src/classpath/gnu/gnu/java/security/Engine.java
trunk/core/src/classpath/gnu/gnu/java/security/x509/X509Certificate.java
trunk/core/src/classpath/gnu/gnu/java/security/x509/ext/CertificatePolicies.java
trunk/core/src/classpath/gnu/gnu/java/security/x509/ext/ExtendedKeyUsage.java
trunk/core/src/classpath/gnu/gnu/java/security/x509/ext/Extension.java
trunk/core/src/classpath/gnu/gnu/java/security/x509/ext/GeneralNames.java
trunk/core/src/classpath/gnu/gnu/java/security/x509/ext/IssuerAlternativeNames.java
trunk/core/src/classpath/gnu/gnu/java/security/x509/ext/SubjectAlternativeNames.java
trunk/core/src/classpath/gnu/gnu/java/util/regex/RESyntax.java
trunk/core/src/classpath/gnu/gnu/java/util/regex/RETokenNamedProperty.java
trunk/core/src/classpath/gnu/gnu/java/util/regex/RETokenRepeated.java
trunk/core/src/classpath/gnu/gnu/javax/crypto/RSACipherImpl.java
trunk/core/src/classpath/gnu/gnu/javax/crypto/jce/cipher/CipherAdapter.java
trunk/core/src/classpath/gnu/gnu/javax/crypto/pad/PKCS7.java
trunk/core/src/classpath/gnu/gnu/javax/net/ssl/provider/InputSecurityParameters.java
trunk/core/src/classpath/gnu/gnu/javax/net/ssl/provider/SimpleSessionContext.java
Modified: trunk/core/src/classpath/gnu/gnu/java/io/Base64InputStream.java
===================================================================
--- trunk/core/src/classpath/gnu/gnu/java/io/Base64InputStream.java 2007-01-07 18:38:08 UTC (rev 3041)
+++ trunk/core/src/classpath/gnu/gnu/java/io/Base64InputStream.java 2007-01-07 18:39:36 UTC (rev 3042)
@@ -139,7 +139,9 @@
while (count < len)
{
int i;
- while (Character.isWhitespace((char) (i = in.read())));
+ while (Character.isWhitespace((char) (i = in.read())))
+ ;
+
int pos = BASE_64.indexOf((char) i);
if (pos >= 0)
{
@@ -173,11 +175,13 @@
case 1:
throw new IOException("malformed Base-64 input");
case 2:
- while (Character.isWhitespace((char) (i = in.read())));
+ while (Character.isWhitespace((char) (i = in.read())))
+ ;
if (i != BASE_64_PAD)
throw new IOException("malformed Base-64 input");
case 3:
- while (Character.isWhitespace((char) (i = in.read())));
+ while (Character.isWhitespace((char) (i = in.read())))
+ ;
}
eof = true;
break;
Modified: trunk/core/src/classpath/gnu/gnu/java/lang/InstrumentationImpl.java
===================================================================
--- trunk/core/src/classpath/gnu/gnu/java/lang/InstrumentationImpl.java 2007-01-07 18:38:08 UTC (rev 3041)
+++ trunk/core/src/classpath/gnu/gnu/java/lang/InstrumentationImpl.java 2007-01-07 18:39:36 UTC (rev 3042)
@@ -1,6 +1,6 @@
/* InstrumentationImpl.java -- GNU implementation of
java.lang.instrument.Instrumentation
- Copyright (C) 2005 Free Software Foundation, Inc.
+ Copyright (C) 2005, 2006 Free Software Foundation, Inc.
This file is part of GNU Classpath.
@@ -63,11 +63,11 @@
{
/* List of transformers */
- /* FIXME[GENERICS]: Should be ClassFileTransformer list */
- private ArrayList transformers = new ArrayList();
+ private ArrayList<ClassFileTransformer> transformers =
+ new ArrayList<ClassFileTransformer>();
- private InstrumentationImpl()
+ InstrumentationImpl()
{
}
@@ -210,9 +210,8 @@
*
* @return the new class file
*/
- /* FIXME[GENERICS]: Should be Class<?> */
public byte[] callTransformers(ClassLoader loader, String className,
- Class classBeingRedefined, ProtectionDomain protectionDomain,
+ Class<?> classBeingRedefined, ProtectionDomain protectionDomain,
byte[] classfileBuffer)
{
byte[] newBuffer = null;
@@ -220,11 +219,10 @@
ClassFileTransformer current;
synchronized (transformers)
{
- Iterator i = transformers.iterator();
+ Iterator<ClassFileTransformer> i = transformers.iterator();
while (i.hasNext())
{
- /* FIXME[GENERICS]: Remove cast */
- current = (ClassFileTransformer) i.next();
+ current = i.next();
try
{
newBuffer = current.transform(loader, className,
Modified: trunk/core/src/classpath/gnu/gnu/java/lang/management/BeanImpl.java
===================================================================
--- trunk/core/src/classpath/gnu/gnu/java/lang/management/BeanImpl.java 2007-01-07 18:38:08 UTC (rev 3041)
+++ trunk/core/src/classpath/gnu/gnu/java/lang/management/BeanImpl.java 2007-01-07 18:39:36 UTC (rev 3042)
@@ -201,32 +201,36 @@
return ((Enum) value).name();
Class vClass = value.getClass();
if (vClass.isArray())
- return value;
+ vClass = vClass.getComponentType();
String cName = vClass.getName();
String[] allowedTypes = OpenType.ALLOWED_CLASSNAMES;
for (int a = 0; a < allowedTypes.length; ++a)
if (cName.equals(allowedTypes[a]))
return value;
+ OpenMBeanInfo info = (OpenMBeanInfo) getMBeanInfo();
+ MBeanAttributeInfo[] attribs =
+ (MBeanAttributeInfo[]) info.getAttributes();
+ OpenType type = null;
+ for (int a = 0; a < attribs.length; ++a)
+ if (attribs[a].getName().equals(attribute))
+ type = ((OpenMBeanAttributeInfo) attribs[a]).getOpenType();
if (value instanceof List)
{
+ try
+ {
+ Class e =
+ Class.forName(((ArrayType) type).getElementOpenType().getClassName());
List l = (List) value;
- Class e = null;
- TypeVariable[] vars = vClass.getTypeParameters();
- for (int a = 0; a < vars.length; ++a)
- if (vars[a].getName().equals("E"))
- e = (Class) vars[a].getGenericDeclaration();
- if (e == null)
- e = Object.class;
Object[] array = (Object[]) Array.newInstance(e, l.size());
return l.toArray(array);
}
- OpenMBeanInfo info = (OpenMBeanInfo) getMBeanInfo();
- OpenMBeanAttributeInfo[] attribs =
- (OpenMBeanAttributeInfo[]) info.getAttributes();
- OpenType type = null;
- for (int a = 0; a < attribs.length; ++a)
- if (attribs[a].getName().equals("attribute"))
- type = attribs[a].getOpenType();
+ catch (ClassNotFoundException e)
+ {
+ throw (InternalError) (new InternalError("The class of the list " +
+ "element type could not " +
+ "be created").initCause(e));
+ }
+ }
if (value instanceof Map)
{
TabularType ttype = (TabularType) type;
@@ -425,6 +429,34 @@
return new OpenMBeanParameterInfoSupport("TransParam",
"Translated parameter",
SimpleType.VOID);
+ if (type.startsWith("java.util.Map"))
+ {
+ int lparam = type.indexOf("<");
+ int comma = type.indexOf(",", lparam);
+ int rparam = type.indexOf(">", comma);
+ String key = type.substring(lparam + 1, comma).trim();
+ OpenType k = translate(key).getOpenType();
+ OpenType v = translate(type.substring(comma + 1, rparam).trim()).getOpenType();
+ CompositeType ctype = new CompositeType(Map.class.getName(), Map.class.getName(),
+ new String[] { "key", "value" },
+ new String[] { "Map key", "Map value"},
+ new OpenType[] { k, v});
+ TabularType ttype = new TabularType(key, key, ctype,
+ new String[] { "key" });
+ return new OpenMBeanParameterInfoSupport("TransParam",
+ "Translated parameter",
+ ttype);
+ }
+ if (type.startsWith("java.util.List"))
+ {
+ int lparam = type.indexOf("<");
+ int rparam = type.indexOf(">");
+ OpenType e = translate(type.substring(lparam + 1, rparam).trim()).getOpenType();
+ return new OpenMBeanParameterInfoSupport("TransParam",
+ "Translated parameter",
+ new ArrayType(1, e)
+ );
+ }
Class c;
try
{
@@ -432,8 +464,9 @@
}
catch (ClassNotFoundException e)
{
- throw new InternalError("The class for a type used in a management bean " +
- "could not be loaded.");
+ throw (InternalError)
+ (new InternalError("The class for a type used in a management bean " +
+ "could not be loaded.").initCause(e));
}
if (c.isEnum())
{
@@ -450,9 +483,9 @@
try
{
c.getMethod("from", new Class[] { CompositeData.class });
- Method[] methods = c.getMethods();
- List names = new ArrayList();
- List types = new ArrayList();
+ Method[] methods = c.getDeclaredMethods();
+ List<String> names = new ArrayList<String>();
+ List<OpenType> types = new ArrayList<OpenType>();
for (int a = 0; a < methods.length; ++a)
{
String name = methods[a].getName();
@@ -462,10 +495,10 @@
types.add(getTypeFromClass(methods[a].getReturnType()));
}
}
- String[] fields = (String[]) names.toArray();
+ String[] fields = names.toArray(new String[names.size()]);
CompositeType ctype = new CompositeType(c.getName(), c.getName(),
fields, fields,
- (OpenType[]) types.toArray());
+ types.toArray(new OpenType[types.size()]));
return new OpenMBeanParameterInfoSupport("TransParam",
"Translated parameter",
ctype);
@@ -474,46 +507,11 @@
{
/* Ignored; we expect this if this isn't a from(CompositeData) class */
}
- if (Map.class.isAssignableFrom(c))
- {
- OpenType k = SimpleType.VOID;
- OpenType v = SimpleType.VOID;
- TypeVariable[] vars = c.getTypeParameters();
- for (int a = 0; a < vars.length; ++a)
- {
- if (vars[a].getName().equals("K"))
- k = getTypeFromClass((Class) vars[a].getGenericDeclaration());
- if (vars[a].getName().equals("V"))
- v = getTypeFromClass((Class) vars[a].getGenericDeclaration());
- }
- CompositeType ctype = new CompositeType(Map.class.getName(), Map.class.getName(),
- new String[] { "key", "value" },
- new String[] { "Map key", "Map value"},
- new OpenType[] { k, v});
- TabularType ttype = new TabularType(c.getName(), c.getName(), ctype,
- new String[] { "key" });
- return new OpenMBeanParameterInfoSupport("TransParam",
- "Translated parameter",
- ttype);
- }
- if (List.class.isAssignableFrom(c))
- {
- OpenType e = SimpleType.VOID;
- TypeVariable[] vars = c.getTypeParameters();
- for (int a = 0; a < vars.length; ++a)
- {
- if (vars[a].getName().equals("E"))
- e = getTypeFromClass((Class) vars[a].getGenericDeclaration());
- }
- return new OpenMBeanParameterInfoSupport("TransParam",
- "Translated parameter",
- new ArrayType(1, e)
- );
- }
if (c.isArray())
{
int depth;
- for (depth = 0; c.getName().charAt(depth) == '['; ++depth);
+ for (depth = 0; c.getName().charAt(depth) == '['; ++depth)
+ ;
OpenType ot = getTypeFromClass(c.getComponentType());
return new OpenMBeanParameterInfoSupport("TransParam",
"Translated parameter",
Modified: trunk/core/src/classpath/gnu/gnu/java/lang/management/MemoryMXBeanImpl.java
===================================================================
--- trunk/core/src/classpath/gnu/gnu/java/lang/management/MemoryMXBeanImpl.java 2007-01-07 18:38:08 UTC (rev 3041)
+++ trunk/core/src/classpath/gnu/gnu/java/lang/management/MemoryMXBeanImpl.java 2007-01-07 18:39:36 UTC (rev 3042)
@@ -37,6 +37,8 @@
package gnu.java.lang.management;
+import gnu.classpath.ListenerData;
+
import java.lang.management.MemoryMXBean;
import java.lang.management.MemoryNotificationInfo;
import java.lang.management.MemoryUsage;
@@ -168,49 +170,6 @@
VMMemoryMXBeanImpl.setVerbose(verbose);
}
- private class ListenerData
- {
- private NotificationListener listener;
- private NotificationFilter filter;
- private Object passback;
-
- public ListenerData(NotificationListener listener,
- NotificationFilter filter, Object passback)
- {
- this.listener = listener;
- this.filter = filter;
- this.passback = passback;
- }
-
- public NotificationListener getListener()
- {
- return listener;
- }
-
- public NotificationFilter getFilter()
- {
- return filter;
- }
-
- public Object getPassback()
- {
- return passback;
- }
-
- public boolean equals(Object obj)
- {
- if (obj instanceof ListenerData)
- {
- ListenerData data = (ListenerData) obj;
- return (data.getListener() == listener &&
- data.getFilter() == filter &&
- data.getPassback() == passback);
- }
- return false;
- }
-
- }
-
public void addNotificationListener(NotificationListener listener,
NotificationFilter filter,
Object passback)
Modified: trunk/core/src/classpath/gnu/gnu/java/lang/management/MemoryPoolMXBeanImpl.java
===================================================================
--- trunk/core/src/classpath/gnu/gnu/java/lang/management/MemoryPoolMXBeanImpl.java 2007-01-07 18:38:08 UTC (rev 3041)
+++ trunk/core/src/classpath/gnu/gnu/java/lang/management/MemoryPoolMXBeanImpl.java 2007-01-07 18:39:36 UTC (rev 3042)
@@ -40,8 +40,8 @@
import gnu.classpath.SystemProperties;
import java.lang.management.MemoryPoolMXBean;
+import java.lang.management.MemoryType;
import java.lang.management.MemoryUsage;
-import java.lang.management.MemoryType;
import javax.management.NotCompliantMBeanException;
@@ -136,7 +136,8 @@
public MemoryType getType()
{
- return null;
+ return
+ MemoryType.valueOf(VMMemoryPoolMXBeanImpl.getType(name));
}
public MemoryUsage getUsage()
Modified: trunk/core/src/classpath/gnu/gnu/java/lang/management/OperatingSystemMXBeanImpl.java
===================================================================
--- trunk/core/src/classpath/gnu/gnu/java/lang/management/OperatingSystemMXBeanImpl.java 2007-01-07 18:38:08 UTC (rev 3041)
+++ trunk/core/src/classpath/gnu/gnu/java/lang/management/OperatingSystemMXBeanImpl.java 2007-01-07 18:39:36 UTC (rev 3042)
@@ -82,14 +82,14 @@
return System.getProperty("os.name");
}
+ public double getSystemLoadAverage()
+ {
+ return VMOperatingSystemMXBeanImpl.getSystemLoadAverage();
+ }
+
public String getVersion()
{
return System.getProperty("os.version");
}
-
- public double getSystemLoadAverage() {
- //todo implement
- throw new UnsupportedOperationException();
- }
}
Modified: trunk/core/src/classpath/gnu/gnu/java/lang/management/ThreadMXBeanImpl.java
===================================================================
--- trunk/core/src/classpath/gnu/gnu/java/lang/management/ThreadMXBeanImpl.java 2007-01-07 18:38:08 UTC (rev 3041)
+++ trunk/core/src/classpath/gnu/gnu/java/lang/management/ThreadMXBeanImpl.java 2007-01-07 18:39:36 UTC (rev 3042)
@@ -85,6 +85,18 @@
"gnu.java.lang.management.ThreadTimeInitallyEnabled";
/**
+ * Constant for monitor usage monitoring support.
+ */
+ private static final String MONITOR_SUPPORT =
+ "gnu.java.lang.management.MonitorUsageMonitoringSupport";
+
+ /**
+ * Constant for ownable synchronizer usage monitoring support.
+ */
+ private static final String SYNCHRONIZER_SUPPORT =
+ "gnu.java.lang.management.OwnableSynchronizerUsageMonitoringSupport";
+
+ /**
* Flag to indicate whether time monitoring is enabled or not.
*/
private boolean timeEnabled;
@@ -112,6 +124,23 @@
contentionEnabled = false;
}
+ public ThreadInfo[] dumpAllThreads(boolean lockedMonitors,
+ boolean lockedSynchronizers)
+ {
+ return getThreadInfo(getAllThreadIds(), lockedMonitors,
+ lockedSynchronizers);
+ }
+
+ public long[] findDeadlockedThreads()
+ {
+ checkMonitorPermissions();
+ if (!isSynchronizerUsageSupported())
+ throw new UnsupportedOperationException("Ownable synchronizer usage " +
+ "monitoring is not provided " +
+ "by this VM.");
+ return VMThreadMXBeanImpl.findDeadlockedThreads();
+ }
+
public long[] findMonitorDeadlockedThreads()
{
checkMonitorPermissions();
@@ -207,6 +236,27 @@
return infos;
}
+ public ThreadInfo[] getThreadInfo(long[] ids, boolean lockedMonitors,
+ boolean lockedSynchronizers)
+ {
+ checkMonitorPermissions();
+ if (lockedMonitors && !isObjectMonitorUsageSupported())
+ throw new UnsupportedOperationException("Monitor usage monitoring is " +
+ "not provided by this VM.");
+ if (lockedSynchronizers && !isSynchronizerUsageSupported())
+ throw new UnsupportedOperationException("Ownable synchronizer usage " +
+ "monitoring is not provided " +
+ "by this VM.");
+ ThreadInfo[] infos = getThreadInfo(ids, Integer.MAX_VALUE);
+ if (lockedMonitors)
+ for (ThreadInfo info : infos)
+ VMThreadMXBeanImpl.getMonitorInfo(info);
+ if (lockedSynchronizers)
+ for (ThreadInfo info : infos)
+ VMThreadMXBeanImpl.getLockInfo(info);
+ return infos;
+ }
+
public long getThreadUserTime(long id)
{
if (!isThreadCpuTimeSupported())
@@ -231,6 +281,16 @@
return SystemProperties.getProperty(CURRENT_THREAD_TIME_SUPPORT) != null;
}
+ public boolean isObjectMonitorUsageSupported()
+ {
+ return SystemProperties.getProperty(MONITOR_SUPPORT) != null;
+ }
+
+ public boolean isSynchronizerUsageSupported()
+ {
+ return SystemProperties.getProperty(SYNCHRONIZER_SUPPORT) != null;
+ }
+
public boolean isThreadContentionMonitoringEnabled()
{
if (isThreadContentionMonitoringSupported())
@@ -287,30 +347,5 @@
"supported.");
}
-
- public ThreadInfo[] dumpAllThreads(boolean lockedMonitors, boolean lockedSynchronizers) {
- //todo implement
- throw new UnsupportedOperationException();
- }
-
- public long[] findDeadlockedThreads() {
- //todo implement
- throw new UnsupportedOperationException();
- }
-
- public ThreadInfo[] getThreadInfo(long[] ids, boolean lockedMonitors, boolean lockedSynchronizers) {
- //todo implement
- throw new UnsupportedOperationException();
- }
-
- public boolean isObjectMonitorUsageSupported() {
- //todo implement
- throw new UnsupportedOperationException();
- }
-
- public boolean isSynchronizerUsageSupported() {
- //todo implement
- throw new UnsupportedOperationException();
- }
}
Modified: trunk/core/src/classpath/gnu/gnu/java/lang/reflect/ClassSignatureParser.java
===================================================================
--- trunk/core/src/classpath/gnu/gnu/java/lang/reflect/ClassSignatureParser.java 2007-01-07 18:38:08 UTC (rev 3041)
+++ trunk/core/src/classpath/gnu/gnu/java/lang/reflect/ClassSignatureParser.java 2007-01-07 18:39:36 UTC (rev 3042)
@@ -61,7 +61,7 @@
}
// SuperclassSignature
superclassType = readClassTypeSignature();
- ArrayList interfaces = new ArrayList();
+ ArrayList<Type> interfaces = new ArrayList<Type>();
while (peekChar() == 'L')
{
// SuperinterfaceSignature
Modified: trunk/core/src/classpath/gnu/gnu/java/lang/reflect/GenericSignatureParser.java
===================================================================
--- trunk/core/src/classpath/gnu/gnu/java/lang/reflect/GenericSignatureParser.java 2007-01-07 18:38:08 UTC (rev 3041)
+++ trunk/core/src/classpath/gnu/gnu/java/lang/reflect/GenericSignatureParser.java 2007-01-07 18:39:36 UTC (rev 3042)
@@ -60,11 +60,10 @@
return this;
}
- /* FIXME[GENERICS]: Remove cast */
public Type[] getBounds()
{
resolve(bounds);
- return (Type[]) bounds.clone();
+ return bounds.clone();
}
public GenericDeclaration getGenericDeclaration()
@@ -141,10 +140,9 @@
return this;
}
- /* FIXME[GENERICS]: Remove cast */
public Type[] getActualTypeArguments()
{
- return (Type[]) typeArgs.clone();
+ return typeArgs.clone();
}
public Type getRawType()
@@ -276,12 +274,11 @@
GenericDeclaration d = decl;
while (d != null)
{
- TypeVariable[] vars = d.getTypeParameters();
- for (int a = 0; a < vars.length ; ++a)
+ for (TypeVariable t : d.getTypeParameters())
{
- if (vars[a].getName().equals(name))
+ if (t.getName().equals(name))
{
- return vars[a];
+ return t;
}
}
d = getParent(d);
@@ -414,7 +411,7 @@
TypeVariable[] readFormalTypeParameters()
{
consume('<');
- ArrayList params = new ArrayList();
+ ArrayList<TypeVariable> params = new ArrayList<TypeVariable>();
do
{
// TODO should we handle name clashes?
@@ -430,7 +427,7 @@
{
String identifier = readIdentifier();
consume(':');
- ArrayList bounds = new ArrayList();
+ ArrayList<Type> bounds = new ArrayList<Type>();
if (peekChar() != ':')
{
bounds.add(readFieldTypeSignature());
@@ -501,7 +498,7 @@
private Type[] readTypeArguments()
{
consume('<');
- ArrayList list = new ArrayList();
+ ArrayList<Type> list = new ArrayList<Type>();
do
{
list.add(readTypeArgument());
Modified: trunk/core/src/classpath/gnu/gnu/java/lang/reflect/MethodSignatureParser.java
===================================================================
--- trunk/core/src/classpath/gnu/gnu/java/lang/reflect/MethodSignatureParser.java 2007-01-07 18:38:08 UTC (rev 3041)
+++ trunk/core/src/classpath/gnu/gnu/java/lang/reflect/MethodSignatureParser.java 2007-01-07 18:39:36 UTC (rev 3042)
@@ -72,7 +72,7 @@
typeParameters = new TypeVariable[0];
}
consume('(');
- ArrayList args = new ArrayList();
+ ArrayList<Type> args = new ArrayList<Type>();
while (peekChar() != ')')
{
args.add(readTypeSignature());
@@ -81,7 +81,7 @@
args.toArray(argTypes);
consume(')');
retType = readTypeSignature();
- ArrayList throwsSigs = new ArrayList();
+ ArrayList<Type> throwsSigs = new ArrayList<Type>();
while (peekChar() == '^')
{
consume('^');
Modified: trunk/core/src/classpath/gnu/gnu/java/nio/charset/ByteCharset.java
===================================================================
--- trunk/core/src/classpath/gnu/gnu/java/nio/charset/ByteCharset.java 2007-01-07 18:38:08 UTC (rev 3041)
+++ trunk/core/src/classpath/gnu/gnu/java/nio/charset/ByteCharset.java 2007-01-07 18:39:36 UTC (rev 3042)
@@ -115,8 +115,8 @@
return CoderResult.OVERFLOW;
}
- if((c = lookup[(int) (b & 0xFF)]) == NONE);
- // return CoderResult.unmappableForLength (1);
+ if((c = lookup[(int) (b & 0xFF)]) == NONE)
+ return CoderResult.unmappableForLength (1);
out.put (c);
}
@@ -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()
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 2007-01-07 18:38:08 UTC (rev 3041)
+++ trunk/core/src/classpath/gnu/gnu/java/nio/charset/ISO_8859_1.java 2007-01-07 18:39:36 UTC (rev 3042)
@@ -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 2007-01-07 18:38:08 UTC (rev 3041)
+++ trunk/core/src/classpath/gnu/gnu/java/nio/charset/US_ASCII.java 2007-01-07 18:39:36 UTC (rev 3042)
@@ -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/rmi/server/ActivatableRef.java
===================================================================
--- trunk/core/src/classpath/gnu/gnu/java/rmi/server/ActivatableRef.java 2007-01-07 18:38:08 UTC (rev 3041)
+++ trunk/core/src/classpath/gnu/gnu/java/rmi/server/ActivatableRef.java 2007-01-07 18:39:36 UTC (rev 3042)
@@ -112,8 +112,10 @@
public void readExternal(ObjectInput in) throws IOException,
ClassNotFoundException
{
+ actId = (ActivationID) in.readObject();
+ String type = in.readUTF();
+ // XXX handle type.equals("") (null reference)
super.readExternal(in);
- actId = (ActivationID) in.readObject();
}
/**
@@ -121,8 +123,10 @@
*/
public void writeExternal(ObjectOutput out) throws IOException
{
+ out.writeObject(actId);
+ // XXX write a "" if the "nested" reference is a null reference
+ out.writeUTF("UnicastRef2");
super.writeExternal(out);
- out.writeObject(actId);
}
/**
Modified: trunk/core/src/classpath/gnu/gnu/java/rmi/server/RMIObjectInputStream.java
===================================================================
--- trunk/core/src/classpath/gnu/gnu/java/rmi/server/RMIObjectInputStream.java 2007-01-07 18:38:08 UTC (rev 3041)
+++ trunk/core/src/classpath/gnu/gnu/java/rmi/server/RMIObjectInputStream.java 2007-01-07 18:39:36 UTC (rev 3042)
@@ -1,5 +1,5 @@
/* RMIObjectInputStream.java --
- Copyright (c) 1996, 1997, 1998, 1999, 2002, 2004
+ Copyright (c) 1996, 1997, 1998, 1999, 2002, 2004, 2006
Free Software Foundation, Inc.
This file is part of GNU Classpath.
@@ -39,11 +39,11 @@
package gnu.java.rmi.server;
+import gnu.classpath.VMStackWalker;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectStreamClass;
-import java.lang.reflect.Proxy;
import java.net.MalformedURLException;
import java.rmi.server.RMIClassLoader;
import java.util.ArrayList;
@@ -57,16 +57,14 @@
}
protected Class resolveClass(ObjectStreamClass desc) throws IOException, ClassNotFoundException {
- String annotation = (String)getAnnotation();
-
try {
- if(annotation == null)
- return (RMIClassLoader.loadClass(desc.getName()));
- else
- return (RMIClassLoader.loadClass(annotation, desc.getName()));
+ return RMIClassLoader.loadClass(
+ (String)getAnnotation(),
+ desc.getName(),
+ VMStackWalker.firstNonNullClassLoader());
}
- catch (MalformedURLException _) {
- throw new ClassNotFoundException(desc.getName());
+ catch (MalformedURLException x) {
+ throw new ClassNotFoundException(desc.getName(), x);
}
}
@@ -81,45 +79,16 @@
protected Class resolveProxyClass(String intfs[]) throws IOException,
ClassNotFoundException
{
- String annotation = (String) getAnnotation();
-
- Class clss[] = new Class[intfs.length];
-
- for (int i = 0; i < intfs.length; i++)
- {
- if (annotation == null)
- clss[i] = RMIClassLoader.loadClass(intfs[i]);
- else
- clss[i] = RMIClassLoader.loadClass(annotation, intfs[i]);
- }
-
- ClassLoader loader;
-
- if (clss.length > 0)
- {
- // Chain all class loaders (they may differ).
- ArrayList loaders = new ArrayList(intfs.length);
- ClassLoader cx;
- for (int i = 0; i < clss.length; i++)
- {
- cx = clss[i].getClassLoader();
- if (!loaders.contains(c...
[truncated message content] |
|
From: <ls...@us...> - 2007-01-09 20:23:03
|
Revision: 3059
http://jnode.svn.sourceforge.net/jnode/?rev=3059&view=rev
Author: lsantha
Date: 2007-01-09 12:23:01 -0800 (Tue, 09 Jan 2007)
Log Message:
-----------
Classpath patches.
Modified Paths:
--------------
trunk/core/src/classpath/gnu/gnu/java/nio/SelectorImpl.java
Added Paths:
-----------
trunk/core/src/classpath/gnu/gnu/java/awt/print/
trunk/core/src/classpath/gnu/gnu/java/awt/print/JavaPrinterJob.java
trunk/core/src/classpath/gnu/gnu/java/awt/print/PostScriptGraphics2D.java
trunk/core/src/classpath/gnu/gnu/java/awt/print/SpooledDocument.java
Added: trunk/core/src/classpath/gnu/gnu/java/awt/print/JavaPrinterJob.java
===================================================================
--- trunk/core/src/classpath/gnu/gnu/java/awt/print/JavaPrinterJob.java (rev 0)
+++ trunk/core/src/classpath/gnu/gnu/java/awt/print/JavaPrinterJob.java 2007-01-09 20:23:01 UTC (rev 3059)
@@ -0,0 +1,403 @@
+/* JavaPrinterJob.java -- AWT printing implemented on javax.print.
+ 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.awt.print;
+
+import java.awt.HeadlessException;
+import java.awt.print.PageFormat;
+import java.awt.print.Pageable;
+import java.awt.print.Printable;
+import java.awt.print.PrinterException;
+import java.awt.print.PrinterJob;
+import java.util.Locale;
+
+import javax.print.CancelablePrintJob;
+import javax.print.DocFlavor;
+import javax.print.DocPrintJob;
+import javax.print.PrintException;
+import javax.print.PrintService;
+import javax.print.PrintServiceLookup;
+import javax.print.ServiceUI;
+import javax.print.attribute.HashPrintRequestAttributeSet;
+import javax.print.attribute.IntegerSyntax;
+import javax.print.attribute.PrintRequestAttributeSet;
+import javax.print.attribute.TextSyntax;
+import javax.print.attribute.standard.Copies;
+import javax.print.attribute.standard.JobName;
+import javax.print.attribute.standard.OrientationRequested;
+import javax.print.attribute.standard.RequestingUserName;
+
+/**
+ * This is the default implementation of PrinterJob
+ *
+ * @author Sven de Marothy
+ */
+public class JavaPrinterJob extends PrinterJob
+{
+ /**
+ * The print service associated with this job
+ */
+ private PrintService printer = null;
+
+ /**
+ * Printing options;
+ */
+ private PrintRequestAttributeSet attributes;
+
+ /**
+ * Available print services
+ */
+ private static PrintService[] services;
+
+ /**
+ * The actual print job.
+ */
+ private DocPrintJob printJob;
+
+ /**
+ * The Printable object to print.
+ */
+ private Printable printable;
+
+ /**
+ * Page format.
+ */
+ private PageFormat pageFormat;
+
+ /**
+ * A pageable, or null
+ */
+ private Pageable pageable = null;
+
+ /**
+ * Cancelled or not
+ */
+ private boolean cancelled = false;
+
+ static
+ {
+ // lookup all services without any constraints
+ services = PrintServiceLookup.lookupPrintServices
+ (DocFlavor.INPUT_STREAM.POSTSCRIPT, null);
+ }
+
+ private static final Class copyClass = (new Copies(1)).getClass();
+ private static final Class jobNameClass = (new JobName("", null)).getClass();
+ private static final Class userNameClass = (new RequestingUserName("", null)).getClass();
+
+ /**
+ * Initializes a new instance of <code>PrinterJob</code>.
+ */
+ public JavaPrinterJob()
+ {
+ attributes = new HashPrintRequestAttributeSet();
+ setCopies(1);
+ setJobName("Java Printing");
+ pageFormat = new PageFormat(); // default page format.
+ }
+
+ private void getPageAttributes()
+ {
+ OrientationRequested orientation = (OrientationRequested)
+ attributes.get( OrientationRequested.LANDSCAPE.getCategory() );
+ if( orientation == null)
+ return;
+
+ if( orientation.equals(OrientationRequested.PORTRAIT) )
+ pageFormat.setOrientation(PageFormat.PORTRAIT);
+ else if( orientation.equals(OrientationRequested.LANDSCAPE) )
+ pageFormat.setOrientation(PageFormat.LANDSCAPE);
+ else if( orientation.equals(OrientationRequested.REVERSE_LANDSCAPE) )
+ pageFormat.setOrientation(PageFormat.REVERSE_LANDSCAPE);
+ }
+
+ /**
+ * Returns the number of copies to be printed.
+ *
+ * @return The number of copies to be printed.
+ */
+ public int getCopies()
+ {
+ return ((IntegerSyntax)attributes.get( jobNameClass )).getValue();
+ }
+
+ /**
+ * Sets the number of copies to be printed.
+ *
+ * @param copies The number of copies to be printed.
+ */
+ public void setCopies(int copies)
+ {
+ attributes.add( new Copies( copies ) );
+ }
+
+ /**
+ * Returns the name of the print job.
+ *
+ * @return The name of the print job.
+ */
+ public String getJobName()
+ {
+ return ((TextSyntax)attributes.get( jobNameClass )).getValue();
+ }
+
+ /**
+ * Sets the name of the print job.
+ *
+ * @param job_name The name of the print job.
+ */
+ public void setJobName(String job_name)
+ {
+ attributes.add( new JobName(job_name, Locale.getDefault()) );
+ }
+
+ /**
+ * Returns the printing user name.
+ *
+ * @return The printing username.
+ */
+ public String getUserName()
+ {
+ return ((TextSyntax)attributes.get( userNameClass )).getValue();
+ }
+
+ /**
+ * Cancels an in progress print job.
+ */
+ public void cancel()
+ {
+ try
+ {
+ if(printJob != null && (printJob instanceof CancelablePrintJob))
+ {
+ ((CancelablePrintJob)printJob).cancel();
+ cancelled = true;
+ }
+ }
+ catch(PrintException pe)
+ {
+ }
+ }
+
+ /**
+ * Tests whether or not this job has been cancelled.
+ *
+ * @return <code>true</code> if this job has been cancelled, <code>false</code>
+ * otherwise.
+ */
+ public boolean isCancelled()
+ {
+ return cancelled;
+ }
+
+ /**
+ * Clones the specified <code>PageFormat</code> object then alters the
+ * clone so that it represents the default page format.
+ *
+ * @param page_format The <code>PageFormat</code> to clone.
+ *
+ * @return A new default page format.
+ */
+ public PageFormat defaultPage(PageFormat page_format)
+ {
+ return new PageFormat();
+ }
+
+ /**
+ * Displays a dialog box to the user which allows the page format
+ * attributes to be modified.
+ *
+ * @param page_format The <code>PageFormat</code> object to modify.
+ *
+ * @return The modified <code>PageFormat</code>.
+ */
+ public PageFormat pageDialog(PageFormat page_format)
+ throws HeadlessException
+ {
+ return defaultPage(null);
+ }
+
+ /**
+ * Prints the pages.
+ */
+ public void print() throws PrinterException
+ {
+ if( printable == null && pageable == null ) // nothing to print?
+ return;
+
+ PostScriptGraphics2D pg = new PostScriptGraphics2D( this );
+ SpooledDocument doc = pg.spoolPostScript( printable, pageFormat,
+ pageable );
+
+ cancelled = false;
+ printJob = printer.createPrintJob();
+ try
+ {
+ printJob.print(doc, attributes);
+ }
+ catch (PrintException pe)
+ {
+ PrinterException p = new PrinterException();
+ p.initCause(pe);
+ throw p;
+ }
+ // no printjob active.
+ printJob = null;
+ }
+
+ /**
+ * Prints the page with given attributes.
+ */
+ public void print (PrintRequestAttributeSet attributes)
+ throws PrinterException
+ {
+ this.attributes = attributes;
+ print();
+ }
+
+ /**
+ * Displays a dialog box to the user which allows the print job
+ * attributes to be modified.
+ *
+ * @return <code>false</code> if the user cancels the dialog box,
+ * <code>true</code> otherwise.
+ */
+ public boolean printDialog() throws HeadlessException
+ {
+ return printDialog( attributes );
+ }
+
+ /**
+ * Displays a dialog box to the user which allows the print job
+ * attributes to be modified.
+ *
+ * @return <code>false</code> if the user cancels the dialog box,
+ * <code>true</code> otherwise.
+ */
+ public boolean printDialog(PrintRequestAttributeSet attributes)
+ throws HeadlessException
+ {
+ PrintService chosenPrinter = ServiceUI.printDialog
+ (null, 50, 50, services, null,
+ DocFlavor.INPUT_STREAM.POSTSCRIPT, attributes);
+
+ getPageAttributes();
+
+ if( chosenPrinter != null )
+ {
+ try
+ {
+ setPrintService( chosenPrinter );
+ }
+ catch(PrinterException pe)
+ {
+ // Should not happen.
+ }
+ return true;
+ }
+ return false;
+ }
+
+ /**
+ * This sets the pages that are to be printed.
+ *
+ * @param pageable The pages to be printed, which may not be <code>null</code>.
+ */
+ public void setPageable(Pageable pageable)
+ {
+ if( pageable == null )
+ throw new NullPointerException("Pageable cannot be null.");
+ this.pageable = pageable;
+ }
+
+ /**
+ * Sets this specified <code>Printable</code> as the one to use for
+ * rendering the pages on the print device.
+ *
+ * @param printable The <code>Printable</code> for the print job.
+ */
+ public void setPrintable(Printable printable)
+ {
+ this.printable = printable;
+ }
+
+ /**
+ * Sets the <code>Printable</code> and the page format for the pages
+ * to be printed.
+ *
+ * @param printable The <code>Printable</code> for the print job.
+ * @param page_format The <code>PageFormat</code> for the print job.
+ */
+ public void setPrintable(Printable printable, PageFormat page_format)
+ {
+ this.printable = printable;
+ this.pageFormat = page_format;
+ }
+
+ /**
+ * Makes any alterations to the specified <code>PageFormat</code>
+ * necessary to make it work with the current printer. The alterations
+ * are made to a clone of the input object, which is then returned.
+ *
+ * @param page_format The <code>PageFormat</code> to validate.
+ *
+ * @return The validated <code>PageFormat</code>.
+ */
+ public PageFormat validatePage(PageFormat page_format)
+ {
+ // FIXME
+ return page_format;
+ }
+
+ /**
+ * Change the printer for this print job to service. Subclasses that
+ * support setting the print service override this method. Throws
+ * PrinterException when the class doesn't support setting the printer,
+ * the service doesn't support Pageable or Printable interfaces for 2D
+ * print output.
+ * @param service The new printer to use.
+ * @throws PrinterException if service is not valid.
+ */
+ public void setPrintService(PrintService service)
+ throws PrinterException
+ {
+ if(!service.isDocFlavorSupported(DocFlavor.INPUT_STREAM.POSTSCRIPT))
+ throw new PrinterException("This printer service is not supported.");
+ printer = service;
+ }
+}
Added: trunk/core/src/classpath/gnu/gnu/java/awt/print/PostScriptGraphics2D.java
===================================================================
--- trunk/core/src/classpath/gnu/gnu/java/awt/print/PostScriptGraphics2D.java (rev 0)
+++ trunk/core/src/classpath/gnu/gnu/java/awt/print/PostScriptGraphics2D.java 2007-01-09 20:23:01 UTC (rev 3059)
@@ -0,0 +1,1350 @@
+/* PostScriptGraphics2D.java -- AWT printer rendering class.
+ 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.awt.print;
+
+import java.awt.BasicStroke;
+import java.awt.Color;
+import java.awt.Composite;
+import java.awt.Paint;
+import java.awt.Font;
+import java.awt.FontMetrics;
+import java.awt.GradientPaint;
+import java.awt.Graphics;
+import java.awt.GraphicsConfiguration;
+import java.awt.Graphics2D;
+import java.awt.Image;
+import java.awt.Polygon;
+import java.awt.Rectangle;
+import java.awt.RenderingHints;
+import java.awt.Shape;
+import java.awt.Stroke;
+import java.awt.geom.AffineTransform;
+import java.awt.geom.Arc2D;
+import java.awt.geom.Ellipse2D;
+import java.awt.geom.RoundRectangle2D;
+import java.awt.geom.PathIterator;
+import java.awt.geom.Point2D;
+import java.awt.geom.Rectangle2D;
+import java.awt.font.FontRenderContext;
+import java.awt.font.GlyphVector;
+import java.awt.font.TextLayout;
+import java.awt.image.BufferedImage;
+import java.awt.image.BufferedImageOp;
+import java.awt.image.renderable.RenderableImage;
+import java.awt.image.RenderedImage;
+import java.awt.image.ImageObserver;
+import java.awt.image.PixelGrabber;
+import java.awt.print.PageFormat;
+import java.awt.print.Pageable;
+import java.awt.print.Paper;
+import java.awt.print.Printable;
+import java.awt.print.PrinterException;
+import java.awt.print.PrinterGraphics;
+import java.awt.print.PrinterJob;
+import java.io.BufferedWriter;
+import java.io.File;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.OutputStreamWriter;
+import java.io.PrintWriter;
+import java.text.AttributedCharacterIterator;
+import java.util.Map;
+
+/**
+ * Class PostScriptGraphics2D - Class that implements the Graphics2D object,
+ * writing the output to a PostScript or EPS file
+ *
+ * @author Sven de Marothy
+ *
+ */
+class PostScriptGraphics2D extends Graphics2D
+{
+ /**
+ * The associated printer job.
+ */
+ private PrinterJob printerJob;
+
+ /**
+ * Output file.
+ */
+ private PrintWriter out;
+
+ // Graphics data
+ private AffineTransform currentTransform = new AffineTransform();
+ private AffineTransform pageTransform;
+ private RenderingHints renderingHints;
+ private Paint currentPaint = null;
+ private Shape clipShape = null;
+ private Font currentFont = null;
+ private Color currentColor = Color.black;
+ private Color backgroundColor = Color.white;
+ private Stroke currentStroke = null;
+ private static Stroke ordinaryStroke = new BasicStroke(0.0f,
+ BasicStroke.CAP_BUTT,
+ BasicStroke.JOIN_MITER);
+ private float cx; // current drawing position
+ private float cy; // current drawing position
+ private boolean currentFontIsPS; // set if currentFont is one of the above
+
+ // settings
+ private double pageX = 595;
+ private double pageY = 842;
+ private double Y = pageY;
+ private boolean gradientOn = false;
+
+ /**
+ * Constructor
+ *
+ */
+ public PostScriptGraphics2D( PrinterJob pg )
+ {
+ printerJob = pg;
+ // create transform objects
+ pageTransform = new AffineTransform();
+ currentTransform = new AffineTransform();
+
+ /*
+ Create Rendering hints
+ No text aliasing
+ Quality color and rendering
+ Bicubic interpolation
+ Fractional metrics supported
+ */
+ renderingHints = new RenderingHints(null);
+ renderingHints.put(RenderingHints.KEY_RENDERING,
+ RenderingHints.VALUE_RENDER_QUALITY);
+ renderingHints.put(RenderingHints.KEY_TEXT_ANTIALIASING,
+ RenderingHints.VALUE_TEXT_ANTIALIAS_OFF);
+ renderingHints.put(RenderingHints.KEY_INTERPOLATION,
+ RenderingHints.VALUE_INTERPOLATION_BICUBIC);
+ renderingHints.put(RenderingHints.KEY_FRACTIONALMETRICS,
+ RenderingHints.VALUE_FRACTIONALMETRICS_ON);
+ renderingHints.put(RenderingHints.KEY_COLOR_RENDERING,
+ RenderingHints.VALUE_COLOR_RENDER_QUALITY);
+ }
+
+ /**
+ * Spool a document to PostScript.
+ * If Pageable is non-null, it will print that, otherwise it will use
+ * the supplied printable and pageFormat.
+ */
+ public SpooledDocument spoolPostScript(Printable printable,
+ PageFormat pageFormat,
+ Pageable pageable)
+ throws PrinterException
+ {
+ try
+ {
+ // spool to a temporary file
+ File temp = File.createTempFile("cpspool", ".ps");
+ temp.deleteOnExit();
+
+ out = new PrintWriter(new BufferedWriter
+ (new OutputStreamWriter
+ (new FileOutputStream(temp),
+ "ISO8859_1"), 1000000));
+
+ writePSHeader();
+
+ if(pageable != null)
+ {
+ for(int index = 0; index < pageable.getNumberOfPages(); index++)
+ spoolPage(out, pageable.getPrintable(index),
+ pageable.getPageFormat(index), index);
+ }
+ else
+ {
+ int index = 0;
+ while(spoolPage(out, printable, pageFormat, index++) ==
+ Printable.PAGE_EXISTS)
+ ;
+ }
+ out.println("%%Trailer");
+ out.println("%%EOF");
+ out.close();
+ return new SpooledDocument( temp );
+ }
+ catch (IOException e)
+ {
+ PrinterException pe = new PrinterException();
+ pe.initCause(e);
+ throw pe;
+ }
+ }
+
+ //--------------------------------------------------------------------------
+
+ /**
+ * Write the postscript file header,
+ * setup the page format and transforms.
+ */
+ private void writePSHeader()
+ {
+ out.println("%!PS-Adobe-3.0");
+ out.println("%%Title: "+printerJob.getJobName());
+ out.println("%%Creator: GNU Classpath ");
+ out.println("%%DocumentData: Clean8Bit");
+
+ out.println("%%DocumentNeededResources: font Times-Roman Helvetica Courier");
+ out.println("%%EndComments");
+
+ out.println("%%BeginProlog");
+ out.println("%%EndProlog");
+ out.println("%%BeginSetup");
+
+ out.println("%%EndFeature");
+ setupFonts();
+ out.println("%%EndSetup");
+
+ // set default fonts and colors
+ setFont( new Font("Dialog", Font.PLAIN, 12) );
+ currentColor = Color.white;
+ currentStroke = new BasicStroke();
+ setPaint(currentColor);
+ setStroke(currentStroke);
+ }
+
+ /**
+ * setupFonts - set up the font dictionaries for
+ * helvetica, times and courier
+ */
+ private void setupFonts()
+ {
+ out.println("/helveticaISO");
+ out.println("/Helvetica findfont dup length dict begin");
+ out.println("{ 1 index /FID eq { pop pop } { def } ifelse } forall");
+ out.println("/Encoding ISOLatin1Encoding def");
+ out.println("currentdict end definefont pop");
+
+ out.println("/timesISO");
+ out.println("/Times-Roman findfont dup length dict begin");
+ out.println("{ 1 index /FID eq { pop pop } { def } ifelse } forall");
+ out.println("/Encoding ISOLatin1Encoding def");
+ out.println("currentdict end definefont pop");
+
+ out.println("/courierISO");
+ out.println("/Courier findfont dup length dict begin");
+ out.println("{ 1 index /FID eq { pop pop } { def } ifelse } forall");
+ out.println("/Encoding ISOLatin1Encoding def");
+ out.println("currentdict end definefont pop");
+ }
+
+ /**
+ * Spools a single page, returns NO_SUCH_PAGE unsuccessful,
+ * PAGE_EXISTS if it was.
+ */
+ public int spoolPage(PrintWriter out,
+ Printable printable,
+ PageFormat pageFormat,
+ int index) throws IOException, PrinterException
+ {
+ out.println("%%BeginPageSetup");
+
+ Paper p = pageFormat.getPaper();
+ pageX = p.getWidth();
+ pageY = p.getHeight();
+
+ if( pageFormat.getOrientation() == PageFormat.PORTRAIT )
+ out.println( "%%Orientation: Portrait" );
+ else
+ {
+ out.println( "%%Orientation: Landscape" );
+ double t = pageX;
+ pageX = pageY;
+ pageY = t;
+ }
+
+ setClip(0, 0, (int)pageX, (int)pageY);
+
+ out.println("gsave % first save");
+
+ // 595x842; 612x792 respectively
+ out.println("<< /PageSize [" +pageX + " "+pageY+ "] >> setpagedevice");
+
+ if( pageFormat.getOrientation() != PageFormat.LANDSCAPE )
+ {
+ pageTransform.translate(pageX, 0);
+ pageTransform.scale(-1.0, 1.0);
+ }
+
+ // save the original CTM
+ pushCTM();
+ concatCTM(pageTransform);
+ setTransform(new AffineTransform());
+
+ out.println("%%EndPageSetup");
+
+ out.println("gsave");
+
+ if( printable.print(this, pageFormat, index) == Printable.NO_SUCH_PAGE )
+ return Printable.NO_SUCH_PAGE;
+
+ out.println("grestore");
+ out.println("showpage");
+
+ return Printable.PAGE_EXISTS;
+ }
+
+ /** push the Current Transformation Matrix onto the PS stack */
+ private void pushCTM()
+ {
+ out.println("matrix currentmatrix % pushCTM()");
+ }
+
+ /** pop the Current Transformation Matrix from the PS stack */
+ private void popCTM()
+ {
+ out.println("setmatrix % restore CTM");
+ }
+
+ ///////////////////////////////////////////////////////////////////////////
+
+ public Graphics create()
+ {
+ return null;
+ }
+
+ public void drawOval(int x, int y, int width, int height)
+ {
+ out.println("% drawOval()");
+ setStroke(ordinaryStroke);
+ draw(new Ellipse2D.Double(x, y, width, height));
+ setStroke(currentStroke);
+ }
+
+ public void drawPolyline(int[] xPoints, int[] yPoints, int nPoints)
+ {
+ if (nPoints <= 0 || xPoints.length < nPoints || yPoints.length < nPoints)
+ return;
+ out.println("newpath % drawPolyLine()");
+ out.println(xPoints[0] + " " + yPoints[0] + " moveto");
+ for (int i = 1; i < nPoints; i++)
+ out.println(xPoints[i] + " " + yPoints[i] + " lineto");
+ out.println("closepath");
+ out.println("stroke");
+ }
+
+ public void drawRoundRect(int x, int y, int width, int height, int arcWidth,
+ int arcHeight)
+ {
+ out.println("% drawRoundRect()");
+ RoundRectangle2D.Double rr = new RoundRectangle2D.Double(x, y, width,
+ height, arcWidth,
+ arcHeight);
+ setStroke(ordinaryStroke);
+ draw(rr);
+ setStroke(currentStroke);
+ }
+
+ public void fillRoundRect(int x, int y, int width, int height, int arcWidth,
+ int arcHeight)
+ {
+ out.println("% fillRoundRect()");
+ RoundRectangle2D.Double rr = new RoundRectangle2D.Double(x, y, width,
+ height, arcWidth,
+ arcHeight);
+ fill(rr);
+ }
+
+ public void drawArc(int x, int y, int width, int height, int startAngle,
+ int arcAngle)
+ {
+ setStroke(ordinaryStroke);
+ draw(new Arc2D.Double(x, y, width, height, startAngle, arcAngle, Arc2D.OPEN));
+ setStroke(currentStroke);
+ }
+
+ public void fillArc(int x, int y, int width, int height, int startAngle,
+ int arcAngle)
+ {
+ fill(new Arc2D.Double(x, y, width, height, startAngle, arcAngle, Arc2D.PIE));
+ }
+
+ public void fillOval(int x, int y, int width, int height)
+ {
+ out.println("% fillOval()");
+ fill( new Ellipse2D.Double(x, y, width, height) );
+ }
+
+ public void fillPolygon(int[] x, int[] y, int nPoints)
+ {
+ out.println("% fillPolygon()");
+ fill( new Polygon(x, y, nPoints) );
+ }
+
+ public void drawLine(int x1, int y1, int x2, int y2)
+ {
+ out.println("% drawLine()");
+ setStroke(ordinaryStroke);
+ out.println("newpath");
+ out.println(x1 + " " + (y1) + " moveto");
+ out.println(x2 + " " + (y2) + " lineto");
+ out.println("stroke");
+ setStroke(currentStroke);
+ }
+
+ //--------------- Image drawing ------------------------------------------
+ public boolean drawImage(Image img, int x, int y, Color bgcolor,
+ ImageObserver observer)
+ {
+ int w = img.getWidth(null);
+ int h = img.getHeight(null);
+
+ return drawImage(img, x, y, x + w, y + h, 0, 0, w - 1, h - 1, bgcolor,
+ observer);
+ }
+
+ public boolean drawImage(Image img, int dx1, int dy1, int dx2, int dy2,
+ int sx1, int sy1, int sx2, int sy2, Color bgcolor,
+ ImageObserver observer)
+ {
+ int n = 0;
+ boolean flipx = false;
+ boolean flipy = false;
+
+ // swap X and Y's
+ if (sx1 > sx2)
+ {
+ n = sx1;
+ sx1 = sx2;
+ sx2 = n;
+ flipx = ! flipx;
+ }
+ if (sy1 > sy2)
+ {
+ n = sy1;
+ sy1 = sy2;
+ sy2 = n;
+ flipy = ! flipy;
+ }
+ if (dx1 > dx2)
+ {
+ n = dx1;
+ dx1 = dx2;
+ dx2 = n;
+ flipx = ! flipx;
+ }
+ if (dy1 > dy2)
+ {
+ n = dy1;
+ dy1 = dy2;
+ dy2 = n;
+ flipy = ! flipy;
+ }
+ n = 0;
+ int sw = sx2 - sx1; // source width
+ int sh = sy2 - sy1; // source height
+ int[] pixels = new int[sw * sh]; // pixel buffer
+ int dw = dx2 - dx1; // destination width
+ int dh = dy2 - dy1; // destination height
+ double x_scale = ((double) dw) / ((double) sw);
+ double y_scale = ((double) dh) / ((double) sh);
+
+ out.println("% drawImage() 2");
+ out.println("gsave");
+ out.println(dx1 + " " + dy1 + " translate");
+ out.println(dw + " " + dh + " scale");
+ out.println(sw + " " + sh + " 8 [" + (flipx ? -sw : sw) + " 0 0 "
+ + (flipy ? -sh : sh) + " " + (flipx ? sw : 0) + " "
+ + (flipy ? sh : 0) + " ]");
+ out.println("{currentfile 3 string readhexstring pop} bind");
+ out.println("false 3 colorimage");
+
+ PixelGrabber pg = new PixelGrabber(img, sx1, sy1, sw, sh, pixels, 0, sw);
+ try
+ {
+ pg.grabPixels();
+ }
+ catch (InterruptedException e)
+ {
+ System.err.println("interrupted waiting for pixels!");
+ return (false);
+ }
+
+ if ((pg.getStatus() & ImageObserver.ABORT) != 0)
+ {
+ System.err.println("image fetch aborted or errored");
+ return (false);
+ }
+
+ for (int j = 0; j < sh; j++)
+ {
+ for (int i = 0; i < sw; i++)
+ {
+ out.print(colorTripleHex(new Color(pixels[j * sw + i])));
+ if (((++n) % 11) == 0)
+ out.println();
+ }
+ }
+
+ out.println();
+ out.println("%%EOF");
+ out.println("grestore");
+ return true;
+ }
+
+ public boolean drawImage(Image img, int dx1, int dy1, int dx2, int dy2,
+ int sx1, int sy1, int sx2, int sy2,
+ ImageObserver observer)
+ {
+ return drawImage(img, dx1, dy1, dx2, dy2, sx1, sy1, sx2, sy2, null,
+ observer);
+ }
+
+ public boolean drawImage(Image img, int x, int y, ImageObserver observer)
+ {
+ return drawImage(img, x, y, null, observer);
+ }
+
+ public boolean drawImage(Image img, int x, int y, int width, int height,
+ Color bgcolor, ImageObserver observer)
+ {
+ int sw = img.getWidth(null);
+ int sh = img.getHeight(null);
+ return drawImage(img, x, y, x + width, y + height, /* destination */
+ 0, 0, sw - 1, sh - 1, /* source */
+ bgcolor, observer);
+ // correct?
+ }
+
+ public boolean drawImage(Image img, int x, int y, int width, int height,
+ ImageObserver observer)
+ {
+ return drawImage(img, x, y, width, height, null, observer);
+ }
+
+ /** Renders a BufferedImage that is filtered with a BufferedImageOp. */
+ public void drawImage(BufferedImage img, BufferedImageOp op, int x, int y)
+ {
+ BufferedImage result = op.filter(img, null);
+ drawImage(result, x, y, null);
+ }
+
+ /** Renders an image, applying a transform from image space
+ into user space before drawing. */
+ public boolean drawImage(Image img, AffineTransform xform, ImageObserver obs)
+ {
+ AffineTransform oldTransform = new AffineTransform(c...
[truncated message content] |
|
From: <ls...@us...> - 2008-06-01 13:30:29
|
Revision: 4170
http://jnode.svn.sourceforge.net/jnode/?rev=4170&view=rev
Author: lsantha
Date: 2008-06-01 06:30:27 -0700 (Sun, 01 Jun 2008)
Log Message:
-----------
Removed unused classes.
Removed Paths:
-------------
trunk/core/src/classpath/gnu/gnu/java/awt/image/
trunk/core/src/classpath/gnu/gnu/java/locale/
trunk/core/src/classpath/gnu/gnu/java/text/
trunk/core/src/classpath/gnu/gnu/java/util/DoubleEnumeration.java
trunk/core/src/classpath/gnu/gnu/javax/swing/
Deleted: trunk/core/src/classpath/gnu/gnu/java/util/DoubleEnumeration.java
===================================================================
--- trunk/core/src/classpath/gnu/gnu/java/util/DoubleEnumeration.java 2008-06-01 12:51:23 UTC (rev 4169)
+++ trunk/core/src/classpath/gnu/gnu/java/util/DoubleEnumeration.java 2008-06-01 13:30:27 UTC (rev 4170)
@@ -1,138 +0,0 @@
-/* gnu.java.util.DoubleEnumeration
- Copyright (C) 1998, 1999, 2001, 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 gnu.java.util;
-
-import java.util.Enumeration;
-import java.util.NoSuchElementException;
-
-
-/**
- * This is a helper class that combines two Enumerations.
- * It returns the elements of the first Enumeration until it has
- * no more elements and then returns the elements of the second
- * Enumeration.<br>
- *
- * In the default case:
- * <pre>
- * doubleEnum = new DoubleEnumeration(enum1, enum2);
- * while (doubleEnum.hasMoreElements()) {
- * Object o = doubleEnum.nextElement();
- * do_something(o);
- * }
- * </pre>
- * it calls hasMoreElements of the Enumerations as few times as
- * possible.
- * The references to the Enumerations are cleared as soon as they have no
- * more elements to help garbage collecting.
- *
- * @author Jochen Hoenicke
- * @author Mark Wielaard (ma...@kl...)
- */
-public class DoubleEnumeration<T> implements Enumeration<T>
-{
- /**
- * This is true as long as one of the enumerations has more
- * elements.
- * Only valid when hasChecked is true.
- * Set in <code>hasMoreElements()</code>
- */
- private boolean hasMore;
- /**
- * This is true, if it is sure that hasMore indicates wether there are
- * more elements.
- * Set to true in <code>hasMoreElements()</code>.
- * Set to false in <code>getNextElement()</code>.
- */
- private boolean hasChecked;
- /**
- * The first enumeration.
- */
- private Enumeration<T> e1;
- /**
- * The second enumeration.
- */
- private Enumeration<T> e2;
-
- /**
- * Creates a new Enumeration combining the given two enumerations.
- * The enumerations mustn't be accessed by other classes.
- */
- public DoubleEnumeration(Enumeration<T> e1, Enumeration<T> e2)
- {
- this.e1 = e1;
- this.e2 = e2;
- hasChecked = false;
- }
-
- /**
- * Returns true, if at least one of the two enumerations has more
- * elements.
- */
- public boolean hasMoreElements()
- {
- if (hasChecked)
- return hasMore;
-
- hasMore = (e1 != null && e1.hasMoreElements());
-
- if (!hasMore) {
- e1 = e2;
- e2 = null;
- hasMore = (e1 != null && e1.hasMoreElements());
- }
-
- hasChecked = true;
- return hasMore;
- }
-
- /**
- * Returns the next element. This returns the next element of the
- * first enumeration, if it has more elements, otherwise the next
- * element of the second enumeration. If both enumeration don't have
- * any elements it throws a <code>NoSuchElementException</code>.
- */
- public T nextElement()
- {
- if (!hasMoreElements())
- throw new NoSuchElementException();
- else {
- hasChecked = false;
- return e1.nextElement();
- }
- }
-}
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|