You can subscribe to this list here.
2006 |
Jan
|
Feb
|
Mar
|
Apr
|
May
|
Jun
|
Jul
|
Aug
|
Sep
|
Oct
|
Nov
|
Dec
(97) |
---|---|---|---|---|---|---|---|---|---|---|---|---|
2007 |
Jan
(127) |
Feb
(34) |
Mar
(16) |
Apr
(26) |
May
(55) |
Jun
(107) |
Jul
(36) |
Aug
(72) |
Sep
(90) |
Oct
(41) |
Nov
(27) |
Dec
(13) |
2008 |
Jan
(37) |
Feb
(39) |
Mar
(98) |
Apr
(115) |
May
(134) |
Jun
(120) |
Jul
(86) |
Aug
(149) |
Sep
(68) |
Oct
(66) |
Nov
(104) |
Dec
(49) |
2009 |
Jan
(131) |
Feb
(132) |
Mar
(125) |
Apr
(172) |
May
(161) |
Jun
(43) |
Jul
(47) |
Aug
(38) |
Sep
(18) |
Oct
(6) |
Nov
(1) |
Dec
(15) |
2010 |
Jan
(21) |
Feb
(8) |
Mar
(10) |
Apr
(4) |
May
(9) |
Jun
|
Jul
(1) |
Aug
|
Sep
|
Oct
(2) |
Nov
|
Dec
(4) |
2011 |
Jan
(23) |
Feb
(10) |
Mar
(13) |
Apr
(3) |
May
|
Jun
(19) |
Jul
(11) |
Aug
(22) |
Sep
|
Oct
(4) |
Nov
(2) |
Dec
(12) |
2012 |
Jan
(3) |
Feb
(4) |
Mar
(7) |
Apr
(3) |
May
|
Jun
(1) |
Jul
(1) |
Aug
(30) |
Sep
(3) |
Oct
(2) |
Nov
|
Dec
(8) |
2013 |
Jan
(3) |
Feb
(40) |
Mar
|
Apr
|
May
|
Jun
(1) |
Jul
|
Aug
|
Sep
|
Oct
|
Nov
(12) |
Dec
|
2021 |
Jan
|
Feb
|
Mar
|
Apr
|
May
|
Jun
|
Jul
|
Aug
|
Sep
(2) |
Oct
|
Nov
|
Dec
|
From: <ls...@us...> - 2007-01-07 12:48:36
|
Revision: 3019 http://jnode.svn.sourceforge.net/jnode/?rev=3019&view=rev Author: lsantha Date: 2007-01-07 04:48:35 -0800 (Sun, 07 Jan 2007) Log Message: ----------- Classpath patches. Modified Paths: -------------- trunk/core/src/classpath/gnu/gnu/javax/net/ssl/provider/ClientHello.java trunk/core/src/classpath/gnu/gnu/javax/net/ssl/provider/ClientKeyExchange.java trunk/core/src/classpath/gnu/gnu/javax/net/ssl/provider/CompressionMethod.java trunk/core/src/classpath/gnu/gnu/javax/net/ssl/provider/Constructed.java trunk/core/src/classpath/gnu/gnu/javax/net/ssl/provider/ContentType.java trunk/core/src/classpath/gnu/gnu/javax/net/ssl/provider/DiffieHellman.java Added Paths: ----------- trunk/core/src/classpath/gnu/gnu/javax/net/ssl/provider/ClientCertificateTypeList.java trunk/core/src/classpath/gnu/gnu/javax/net/ssl/provider/ClientDHE_PSKParameters.java trunk/core/src/classpath/gnu/gnu/javax/net/ssl/provider/ClientDiffieHellmanPublic.java trunk/core/src/classpath/gnu/gnu/javax/net/ssl/provider/ClientHandshake.java trunk/core/src/classpath/gnu/gnu/javax/net/ssl/provider/ClientHelloBuilder.java trunk/core/src/classpath/gnu/gnu/javax/net/ssl/provider/ClientHelloV2.java trunk/core/src/classpath/gnu/gnu/javax/net/ssl/provider/ClientKeyExchangeBuilder.java trunk/core/src/classpath/gnu/gnu/javax/net/ssl/provider/ClientPSKParameters.java trunk/core/src/classpath/gnu/gnu/javax/net/ssl/provider/ClientRSA_PSKParameters.java trunk/core/src/classpath/gnu/gnu/javax/net/ssl/provider/CompressionMethodList.java trunk/core/src/classpath/gnu/gnu/javax/net/ssl/provider/Debug.java trunk/core/src/classpath/gnu/gnu/javax/net/ssl/provider/DelegatedTask.java trunk/core/src/classpath/gnu/gnu/javax/net/ssl/provider/EmptyExchangeKeys.java trunk/core/src/classpath/gnu/gnu/javax/net/ssl/provider/EncryptedPreMasterSecret.java Added: trunk/core/src/classpath/gnu/gnu/javax/net/ssl/provider/ClientCertificateTypeList.java =================================================================== --- trunk/core/src/classpath/gnu/gnu/javax/net/ssl/provider/ClientCertificateTypeList.java (rev 0) +++ trunk/core/src/classpath/gnu/gnu/javax/net/ssl/provider/ClientCertificateTypeList.java 2007-01-07 12:48:35 UTC (rev 3019) @@ -0,0 +1,227 @@ +/* ClientCertificateTypeList.java -- A list of certificate types. + Copyright (C) 2006 Free Software Foundation, Inc. + +This file is a 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 of the License, 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; if not, write to the Free Software +Foundation, Inc., 51 Franklin St, 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.javax.net.ssl.provider; + +import gnu.javax.net.ssl.provider.CertificateRequest.ClientCertificateType; + +import java.io.PrintWriter; +import java.io.StringWriter; + +import java.nio.ByteBuffer; + +import java.util.ConcurrentModificationException; +import java.util.ListIterator; +import java.util.NoSuchElementException; + +public class ClientCertificateTypeList implements Iterable<ClientCertificateType> +{ + private final ByteBuffer buffer; + private int modCount; + + public ClientCertificateTypeList (final ByteBuffer buffer) + { + this.buffer = buffer; + modCount = 0; + } + + public int size () + { + return (buffer.get (0) & 0xFF); + } + + public CertificateRequest.ClientCertificateType get (final int index) + { + int size = size (); + if (index < 0 || index >= size) + throw new IndexOutOfBoundsException ("limit: " + size + + "; requested: " + index); + return CertificateRequest.ClientCertificateType.forValue + (buffer.get (index + 1) & 0xFF); + } + + public java.util.Iterator<ClientCertificateType> iterator() + { + return new Iterator(); + } + + public void put (final int index, final CertificateRequest.ClientCertificateType type) + { + int size = size (); + if (index < 0 || index >= size) + throw new IndexOutOfBoundsException ("limit: " + size + + "; requested: " + index); + buffer.put (index + 1, (byte) type.getValue ()); + modCount++; + } + + public void setSize (final int newSize) + { + if (newSize < 0 || newSize > 255) + throw new IllegalArgumentException ("size must be between 0 and 255"); + if (newSize + 1 > buffer.capacity ()) + throw new IllegalArgumentException ("limit: " + (buffer.capacity () - 1) + + "; requested: " + newSize); + buffer.put (0, (byte) newSize); + modCount++; + } + + public String toString () + { + return toString (null); + } + + public String toString (final String prefix) + { + StringWriter str = new StringWriter (); + PrintWriter out = new PrintWriter (str); + if (prefix != null) out.print (prefix); + out.print ("["); + out.print (size ()); + out.println ("] {"); + for (Iterator it = new Iterator (); it.hasNext (); ) + { + if (prefix != null) out.print (prefix); + out.print (" "); + out.print (it.next ()); + if (it.hasNext ()) + out.print (","); + out.println (); + } + if (prefix != null) out.print (prefix); + out.println ("};"); + return str.toString (); + } + + public boolean equals (Object o) + { + if (!(o instanceof ClientCertificateTypeList)) + return false; + ClientCertificateTypeList that = (ClientCertificateTypeList) o; + + if (size () != that.size ()) + return false; + + for (Iterator it1 = new Iterator (), it2 = that.new Iterator (); + it1.hasNext () && it2.hasNext (); ) + { + if (!it1.next ().equals (it2.next ())) + return false; + } + return true; + } + + public class Iterator implements ListIterator<CertificateRequest.ClientCertificateType> + { + private int index; + private final int modCount; + + Iterator () + { + index = 0; + modCount = ClientCertificateTypeList.this.modCount; + } + + public void add (CertificateRequest.ClientCertificateType type) + { + throw new UnsupportedOperationException (); + } + + public boolean hasNext () + { + return (index < size ()); + } + + public boolean hasPrevious () + { + return (index > 0); + } + + public CertificateRequest.ClientCertificateType next () throws NoSuchElementException + { + if (modCount != ClientCertificateTypeList.this.modCount) + throw new ConcurrentModificationException (); + try + { + return get (index++); + } + catch (IndexOutOfBoundsException ioobe) + { + throw new NoSuchElementException (); + } + } + + public int nextIndex () + { + if (hasNext ()) + return (index + 1); + return -1; + } + + public CertificateRequest.ClientCertificateType previous () throws NoSuchElementException + { + if (index == 0) + throw new NoSuchElementException (); + if (modCount != ClientCertificateTypeList.this.modCount) + throw new ConcurrentModificationException (); + try + { + return get (--index); + } + catch (IndexOutOfBoundsException ioobe) + { + throw new NoSuchElementException (); + } + } + + public int previousIndex () + { + return (index - 1); + } + + public void remove () + { + throw new UnsupportedOperationException (); + } + + public void set (final CertificateRequest.ClientCertificateType type) + { + put (index, type); + } + } +} \ No newline at end of file Added: trunk/core/src/classpath/gnu/gnu/javax/net/ssl/provider/ClientDHE_PSKParameters.java =================================================================== --- trunk/core/src/classpath/gnu/gnu/javax/net/ssl/provider/ClientDHE_PSKParameters.java (rev 0) +++ trunk/core/src/classpath/gnu/gnu/javax/net/ssl/provider/ClientDHE_PSKParameters.java 2007-01-07 12:48:35 UTC (rev 3019) @@ -0,0 +1,122 @@ +/* ClientDHE_PSKParameters.java -- + Copyright (C) 2006 Free Software Foundation, Inc. + +This file is a 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 of the License, 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; if not, write to the Free Software +Foundation, Inc., 51 Franklin St, 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.javax.net.ssl.provider; + +import java.nio.ByteBuffer; +import java.nio.charset.Charset; + +/** + * <pre> + struct { + select (KeyExchangeAlgorithm) { + /* other cases for rsa, diffie_hellman, etc. */ + case diffie_hellman_psk: /* NEW */ + opaque psk_identity<0..2^16-1>; + ClientDiffieHellmanPublic public; + } exchange_keys; + } ClientKeyExchange;</pre> + * + * @author Casey Marshall (cs...@gn...) + */ +public class ClientDHE_PSKParameters extends ExchangeKeys implements Builder, Constructed +{ + public ClientDHE_PSKParameters(ByteBuffer buffer) + { + super(buffer); + } + + public ClientDHE_PSKParameters(String identity, ClientDiffieHellmanPublic dh) + { + super(null); + Charset utf8 = Charset.forName("UTF-8"); + ByteBuffer idBuf = utf8.encode(identity); + buffer = ByteBuffer.allocate(2 + idBuf.remaining() + dh.length()); + buffer.putShort((short) idBuf.remaining()); + buffer.put(idBuf); + buffer.put(dh.buffer()); + buffer.rewind(); + } + + /* (non-Javadoc) + * @see gnu.javax.net.ssl.provider.Builder#buffer() + */ + public ByteBuffer buffer() + { + return (ByteBuffer) buffer.duplicate().rewind().limit(length()); + } + + private int identityLength() + { + return (buffer.getShort(0) & 0xFFFF) + 2; + } + + public String identity() + { + Charset utf8 = Charset.forName("UTF-8"); + return utf8.decode((ByteBuffer) buffer.duplicate().position(2).limit + (identityLength())).toString(); + } + + /* (non-Javadoc) + * @see gnu.javax.net.ssl.provider.Constructed#length() + */ + public int length() + { + int length = (buffer.getShort(0) & 0xFFFF) + 2; + // XXX always explicit? + length += (buffer.getShort(length) & 0xFFFF) + 2; + return length; + } + + public ClientDiffieHellmanPublic params() + { + return new ClientDiffieHellmanPublic(((ByteBuffer) buffer.duplicate() + .position(identityLength()).limit(length())).slice()); + } + + /* (non-Javadoc) + * @see gnu.javax.net.ssl.provider.Constructed#toString(java.lang.String) + */ + public String toString(String prefix) + { + // TODO Auto-generated method stub + return null; + } + +} Added: trunk/core/src/classpath/gnu/gnu/javax/net/ssl/provider/ClientDiffieHellmanPublic.java =================================================================== --- trunk/core/src/classpath/gnu/gnu/javax/net/ssl/provider/ClientDiffieHellmanPublic.java (rev 0) +++ trunk/core/src/classpath/gnu/gnu/javax/net/ssl/provider/ClientDiffieHellmanPublic.java 2007-01-07 12:48:35 UTC (rev 3019) @@ -0,0 +1,129 @@ +/* ClientDiffieHellmanPublic.java -- Client Diffie-Hellman value. + Copyright (C) 2006 Free Software Foundation, Inc. + +This file is a 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 of the License, 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; if not, write to the Free Software +Foundation, Inc., 51 Franklin St, 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.javax.net.ssl.provider; + +import java.io.PrintWriter; +import java.io.StringWriter; + +import java.math.BigInteger; + +import java.nio.ByteBuffer; + +/** + * The client's explicit Diffie Hellman value. + * + * <pre> +struct { + select (PublicValueEncoding) { + case implicit: struct { }; + case explicit: opaque dh_Yc<1..2^16-1>; + } dh_public; +} ClientDiffieHellmanPublic;</pre> + */ +public class ClientDiffieHellmanPublic extends ExchangeKeys implements Builder +{ + public ClientDiffieHellmanPublic(final ByteBuffer buffer) + { + super(buffer); + } + + public ClientDiffieHellmanPublic(final BigInteger Yc) + { + super(wrap(Yc)); + } + + private static ByteBuffer wrap(BigInteger Yc) + { + byte[] b = Util.trim(Yc); + ByteBuffer ret = ByteBuffer.allocate(b.length + 2); + ret.putShort((short) b.length); + ret.put(b); + return (ByteBuffer) ret.rewind(); + } + + public ByteBuffer buffer() + { + return (ByteBuffer) buffer.duplicate().rewind().limit(length()); + } + + public BigInteger publicValue() + { + int len = length() - 2; + byte[] b = new byte[len]; + buffer.position(2); + buffer.get(b); + buffer.rewind(); + return new BigInteger(1, b); + } + + public void setPublicValue(final BigInteger Yc) + { + byte[] buf = Util.trim(Yc); + if (buffer.capacity() < buf.length + 2) + buffer = ByteBuffer.allocate(buf.length + 2); + buffer.putShort((short) buf.length); + buffer.put(buf); + buffer.rewind(); + } + + public int length () + { + return (buffer.getShort(0) & 0xFFFF) + 2; + } + + public String toString () + { + return toString (null); + } + + public String toString (final String prefix) + { + StringWriter str = new StringWriter (); + PrintWriter out = new PrintWriter (str); + if (prefix != null) out.print (prefix); + out.println ("struct {"); + if (prefix != null) out.print (prefix); + out.print (" dh_Yc = "); + out.print (publicValue ().toString (16)); + out.println (';'); + if (prefix != null) out.print (prefix); + out.print ("} ClientDiffieHellmanPublic;"); + return str.toString (); + } +} Added: trunk/core/src/classpath/gnu/gnu/javax/net/ssl/provider/ClientHandshake.java =================================================================== --- trunk/core/src/classpath/gnu/gnu/javax/net/ssl/provider/ClientHandshake.java (rev 0) +++ trunk/core/src/classpath/gnu/gnu/javax/net/ssl/provider/ClientHandshake.java 2007-01-07 12:48:35 UTC (rev 3019) @@ -0,0 +1,1150 @@ +/* ClientHandshake.java -- + Copyright (C) 2006 Free Software Foundation, Inc. + +This file is a 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 of the License, 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; if not, write to the Free Software +Foundation, Inc., 51 Franklin St, 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.javax.net.ssl.provider; + +import static gnu.javax.net.ssl.provider.ClientHandshake.State.*; +import static gnu.javax.net.ssl.provider.KeyExchangeAlgorithm.*; + +import gnu.classpath.debug.Component; +import gnu.java.security.action.GetSecurityPropertyAction; +import gnu.javax.crypto.key.dh.GnuDHPublicKey; +import gnu.javax.net.ssl.AbstractSessionContext; +import gnu.javax.net.ssl.Session; +import gnu.javax.net.ssl.provider.Alert.Description; +import gnu.javax.net.ssl.provider.Alert.Level; +import gnu.javax.net.ssl.provider.CertificateRequest.ClientCertificateType; +import gnu.javax.net.ssl.provider.ServerNameList.NameType; +import gnu.javax.net.ssl.provider.ServerNameList.ServerName; + +import java.nio.ByteBuffer; +import java.security.AccessController; +import java.security.InvalidAlgorithmParameterException; +import java.security.InvalidKeyException; +import java.security.KeyManagementException; +import java.security.KeyPair; +import java.security.KeyPairGenerator; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.security.PrivateKey; +import java.security.SignatureException; +import java.security.cert.CertificateException; +import java.security.cert.X509Certificate; +import java.security.interfaces.RSAPublicKey; +import java.util.Arrays; +import java.util.Collections; +import java.util.LinkedList; +import java.util.List; +import java.util.zip.Deflater; +import java.util.zip.Inflater; + +import javax.crypto.BadPaddingException; +import javax.crypto.Cipher; +import javax.crypto.IllegalBlockSizeException; +import javax.crypto.NoSuchPaddingException; +import javax.crypto.SecretKey; +import javax.crypto.interfaces.DHPrivateKey; +import javax.crypto.interfaces.DHPublicKey; +import javax.crypto.spec.DHParameterSpec; +import javax.net.ssl.SSLException; +import javax.net.ssl.SSLPeerUnverifiedException; +import javax.net.ssl.X509ExtendedKeyManager; +import javax.net.ssl.SSLEngineResult.HandshakeStatus; +import javax.security.auth.x500.X500Principal; + +/** + * @author Casey Marshall (cs...@gn...) + */ +public class ClientHandshake extends AbstractHandshake +{ + static enum State + { + WRITE_CLIENT_HELLO (false, true), + READ_SERVER_HELLO (true, false), + READ_CERTIFICATE (true, false), + READ_SERVER_KEY_EXCHANGE (true, false), + READ_CERTIFICATE_REQUEST (true, false), + READ_SERVER_HELLO_DONE (true, false), + WRITE_CERTIFICATE (false, true), + WRITE_CLIENT_KEY_EXCHANGE (false, true), + WRITE_CERTIFICATE_VERIFY (false, true), + WRITE_FINISHED (false, true), + READ_FINISHED (true, false), + DONE (false, false); + + private final boolean isWriteState; + private final boolean isReadState; + + private State(boolean isReadState, boolean isWriteState) + { + this.isReadState = isReadState; + this.isWriteState = isWriteState; + } + + boolean isReadState() + { + return isReadState; + } + + boolean isWriteState() + { + return isWriteState; + } + } + + private State state; + private ByteBuffer outBuffer; + private boolean continuedSession; + private SessionImpl continued; + private KeyPair dhPair; + private String keyAlias; + private PrivateKey privateKey; + private MaxFragmentLength maxFragmentLengthSent; + private boolean truncatedHMacSent; + private ProtocolVersion sentVersion; + + // Delegated tasks. + private CertVerifier certVerifier; + private ParamsVerifier paramsVerifier; + private DelegatedTask keyExchange; + private CertLoader certLoader; + private GenCertVerify genCertVerify; + + public ClientHandshake(SSLEngineImpl engine) throws NoSuchAlgorithmException + { + super(engine); + state = WRITE_CLIENT_HELLO; + continuedSession = false; + } + + /* (non-Javadoc) + * @see gnu.javax.net.ssl.provider.AbstractHandshake#implHandleInput() + */ + @Override protected HandshakeStatus implHandleInput() throws SSLException + { + if (state == DONE) + return HandshakeStatus.FINISHED; + + if (state.isWriteState() + || (outBuffer != null && outBuffer.hasRemaining())) + return HandshakeStatus.NEED_WRAP; + + // Copy the current buffer, and prepare it for reading. + ByteBuffer buffer = handshakeBuffer.duplicate (); + buffer.flip(); + buffer.position(handshakeOffset); + + Handshake handshake = new Handshake(buffer.slice(), + engine.session().suite, + engine.session().version); + + if (Debug.DEBUG) + logger.logv(Component.SSL_HANDSHAKE, "processing in state {0}:\n{1}", + state, handshake); + + switch (state) + { + // Server Hello. + case READ_SERVER_HELLO: + { + if (handshake.type() != Handshake.Type.SERVER_HELLO) + throw new AlertException(new Alert(Alert.Level.FATAL, + Alert.Description.UNEXPECTED_MESSAGE)); + ServerHello hello = (ServerHello) handshake.body(); + serverRandom = hello.random().copy(); + engine.session().suite = hello.cipherSuite(); + engine.session().version = hello.version(); + compression = hello.compressionMethod(); + Session.ID serverId = new Session.ID(hello.sessionId()); + if (continued != null + && continued.id().equals(serverId)) + { + continuedSession = true; + engine.setSession(continued); + } + else if (engine.getEnableSessionCreation()) + { + ((AbstractSessionContext) engine.contextImpl + .engineGetClientSessionContext()).put(engine.session()); + } + ExtensionList extensions = hello.extensions(); + if (extensions != null) + { + for (Extension extension : extensions) + { + Extension.Type type = extension.type(); + if (type == null) + continue; + switch (type) + { + case MAX_FRAGMENT_LENGTH: + MaxFragmentLength mfl + = (MaxFragmentLength) extension.value(); + if (maxFragmentLengthSent == mfl) + engine.session().setApplicationBufferSize(mfl.maxLength()); + break; + + case TRUNCATED_HMAC: + if (truncatedHMacSent) + engine.session().setTruncatedMac(true); + break; + } + } + } + + KeyExchangeAlgorithm kex = engine.session().suite.keyExchangeAlgorithm(); + if (continuedSession) + { + byte[][] keys = generateKeys(clientRandom, serverRandom, + engine.session()); + setupSecurityParameters(keys, true, engine, compression); + state = READ_FINISHED; + } + else if (kex == RSA || kex == DH_DSS || kex == DH_RSA + || kex == DHE_DSS || kex == DHE_RSA || kex == RSA_PSK) + state = READ_CERTIFICATE; + else if (kex == DH_anon || kex == PSK || kex == DHE_PSK) + state = READ_SERVER_KEY_EXCHANGE; + else + state = READ_CERTIFICATE_REQUEST; + } + break; + + // Server Certificate. + case READ_CERTIFICATE: + { + if (handshake.type() != Handshake.Type.CERTIFICATE) + { + // We need a certificate for non-anonymous suites. + if (engine.session().suite.signatureAlgorithm() != SignatureAlgorithm.ANONYMOUS) + throw new AlertException(new Alert(Level.FATAL, + Description.UNEXPECTED_MESSAGE)); + state = READ_SERVER_KEY_EXCHANGE; + } + Certificate cert = (Certificate) handshake.body(); + X509Certificate[] chain = null; + try + { + chain = cert.certificates().toArray(new X509Certificate[0]); + } + catch (CertificateException ce) + { + throw new AlertException(new Alert(Level.FATAL, + Description.BAD_CERTIFICATE), + ce); + } + catch (NoSuchAlgorithmException nsae) + { + throw new AlertException(new Alert(Level.FATAL, + Description.UNSUPPORTED_CERTIFICATE), + nsae); + } + engine.session().setPeerCertificates(chain); + certVerifier = new CertVerifier(true, chain); + tasks.add(certVerifier); + + // If we are doing an RSA key exchange, generate our parameters. + KeyExchangeAlgorithm kea = engine.session().suite.keyExchangeAlgorithm(); + if (kea == RSA || kea == RSA_PSK) + { + keyExchange = new RSAGen(kea == RSA); + tasks.add(keyExchange); + if (kea == RSA) + state = READ_CERTIFICATE_REQUEST; + else + state = READ_SERVER_KEY_EXCHANGE; + } + else + state = READ_SERVER_KEY_EXCHANGE; + } + break; + + // Server Key Exchange. + case READ_SERVER_KEY_EXCHANGE: + { + CipherSuite s = engine.session().suite; + KeyExchangeAlgorithm kexalg = s.keyExchangeAlgorithm(); + // XXX also SRP. + if (kexalg != DHE_DSS && kexalg != DHE_RSA && kexalg != DH_anon + && kexalg != DHE_PSK && kexalg != PSK && kexalg != RSA_PSK) + throw new AlertException(new Alert(Level.FATAL, + Description.UNEXPECTED_MESSAGE)); + + if (handshake.type() != Handshake.Type.SERVER_KEY_EXCHANGE) + { + if (kexalg != RSA_PSK && kexalg != PSK) + throw new AlertException(new Alert(Level.FATAL, + Description.UNEXPECTED_MESSAGE)); + state = READ_CERTIFICATE_REQUEST; + return HandshakeStatus.NEED_UNWRAP; + } + + ServerKeyExchange skex = (ServerKeyExchange) handshake.body(); + ByteBuffer paramsBuffer = null; + if (kexalg == DHE_DSS || kexalg == DHE_RSA || kexalg == DH_anon) + { + ServerDHParams dhParams = (ServerDHParams) skex.params(); + ByteBuffer b = dhParams.buffer(); + paramsBuffer = ByteBuffer.allocate(b.remaining()); + paramsBuffer.put(b); + } + + if (s.signatureAlgorithm() != SignatureAlgorithm.ANONYMOUS) + { + byte[] signature = skex.signature().signature(); + paramsVerifier = new ParamsVerifier(paramsBuffer, signature); + tasks.add(paramsVerifier); + } + + if (kexalg == DHE_DSS || kexalg == DHE_RSA || kexalg == DH_anon) + { + ServerDHParams dhParams = (ServerDHParams) skex.params(); + DHPublicKey serverKey = new GnuDHPublicKey(null, + dhParams.p(), + dhParams.g(), + dhParams.y()); + DHParameterSpec params = new DHParameterSpec(dhParams.p(), + dhParams.g()); + keyExchange = new ClientDHGen(serverKey, params, true); + tasks.add(keyExchange); + } + if (kexalg == DHE_PSK) + { + ServerDHE_PSKParameters pskParams = (ServerDHE_PSKParameters) + skex.params(); + ServerDHParams dhParams = pskParams.params(); + DHPublicKey serverKey = new GnuDHPublicKey(null, + dhParams.p(), + dhParams.g(), + dhParams.y()); + DHParameterSpec params = new DHParameterSpec(dhParams.p(), + dhParams.g()); + keyExchange = new ClientDHGen(serverKey, params, false); + tasks.add(keyExchange); + } + state = READ_CERTIFICATE_REQUEST; + } + break; + + // Certificate Request. + case READ_CERTIFICATE_REQUEST: + { + if (handshake.type() != Handshake.Type.CERTIFICATE_REQUEST) + { + state = READ_SERVER_HELLO_DONE; + return HandshakeStatus.NEED_UNWRAP; + } + + CertificateRequest req = (CertificateRequest) handshake.body(); + ClientCertificateTypeList types = req.types(); + LinkedList<String> typeList = new LinkedList<String>(); + for (ClientCertificateType t : types) + typeList.add(t.name()); + + X500PrincipalList issuers = req.authorities(); + LinkedList<X500Principal> issuerList = new LinkedList<X500Principal>(); + for (X500Principal p : issuers) + issuerList.add(p); + + certLoader = new CertLoader(typeList, issuerList); + tasks.add(certLoader); + } + break; + + // Server Hello Done. + case READ_SERVER_HELLO_DONE: + { + if (handshake.type() != Handshake.Type.SERVER_HELLO_DONE) + throw new AlertException(new Alert(Level.FATAL, + Description.UNEXPECTED_MESSAGE)); + state = WRITE_CERTIFICATE; + } + break; + + // Finished. + case READ_FINISHED: + { + if (handshake.type() != Handshake.Type.FINISHED) + throw new AlertException(new Alert(Level.FATAL, + Description.UNEXPECTED_MESSAGE)); + + Finished serverFinished = (Finished) handshake.body(); + MessageDigest md5copy = null; + MessageDigest shacopy = null; + try + { + md5copy = (MessageDigest) md5.clone(); + shacopy = (MessageDigest) sha.clone(); + } + catch (CloneNotSupportedException cnse) + { + // We're improperly configured to use a non-cloneable + // md5/sha-1, OR there's a runtime bug. + throw new SSLException(cnse); + } + Finished clientFinished = + new Finished(generateFinished(md5copy, shacopy, + false, engine.session()), + engine.session().version); + + if (Debug.DEBUG) + logger.logv(Component.SSL_HANDSHAKE, "clientFinished: {0}", + clientFinished); + + if (engine.session().version == ProtocolVersion.SSL_3) + { + if (!Arrays.equals(clientFinished.md5Hash(), + serverFinished.md5Hash()) + || !Arrays.equals(clientFinished.shaHash(), + serverFinished.shaHash())) + { + engine.session().invalidate(); + throw new SSLException("session verify failed"); + } + } + else + { + if (!Arrays.equals(clientFinished.verifyData(), + serverFinished.verifyData())) + { + engine.session().invalidate(); + throw new SSLException("session verify failed"); + } + } + + if (continuedSession) + { + engine.changeCipherSpec(); + state = WRITE_FINISHED; + } + else + state = DONE; + } + break; + + default: + throw new IllegalStateException("invalid state: " + state); + } + + handshakeOffset += handshake.length() + 4; + + if (!tasks.isEmpty()) + return HandshakeStatus.NEED_TASK; + if (state.isWriteState() + || (outBuffer != null && outBuffer.hasRemaining())) + return HandshakeStatus.NEED_WRAP; + if (state.isReadState()) + return HandshakeStatus.NEED_UNWRAP; + + return HandshakeStatus.FINISHED; + } + + /* (non-Javadoc) + * @see gnu.javax.net.ssl.provider.AbstractHandshake#implHandleOutput(java.nio.ByteBuffer) + */ + @Override protected HandshakeStatus implHandleOutput(ByteBuffer fragment) + throws SSLException + { + if (Debug.DEBUG) + logger.logv(Component.SSL_HANDSHAKE, "output to {0}; state:{1}; outBuffer:{2}", + fragment, state, outBuffer); + + // Drain the output buffer, if it needs it. + if (outBuffer != null && outBuffer.hasRemaining()) + { + int l = Math.min(fragment.remaining(), outBuffer.remaining()); + fragment.put((ByteBuffer) outBuffer.duplicate().limit(outBuffer.position() + l)); + outBuffer.position(outBuffer.position() + l); + } + + if (!fragment.hasRemaining()) + { + if (state.isWriteState() || outBuffer.hasRemaining()) + return HandshakeStatus.NEED_WRAP; + else + return HandshakeStatus.NEED_UNWRAP; + } + +outer_loop: + while (fragment.remaining() >= 4 && state.isWriteState()) + { + if (Debug.DEBUG) + logger.logv(Component.SSL_HANDSHAKE, "loop state={0}", state); + + switch (state) + { + case WRITE_CLIENT_HELLO: + { + ClientHelloBuilder hello = new ClientHelloBuilder(); + AbstractSessionContext ctx = (AbstractSessionContext) + engine.contextImpl.engineGetClientSessionContext(); + continued = (SessionImpl) ctx.getSession(engine.getPeerHost(), + engine.getPeerPort()); + engine.session().setId(new Session.ID(new byte[0])); + Session.ID sid = engine.session().id(); + // If we have a session that we may want to continue, send + // that ID. + if (continued != null) + sid = continued.id(); + + hello.setSessionId(sid.id()); + sentVersion = chooseVersion(); + hello.setVersion(sentVersion); + hello.setCipherSuites(getSuites()); + hello.setCompressionMethods(getCompressionMethods()); + Random r = hello.random(); + r.setGmtUnixTime(Util.unixTime()); + byte[] nonce = new byte[28]; + engine.session().random().nextBytes(nonce); + r.setRandomBytes(nonce); + clientRandom = r.copy(); + if (enableExtensions()) + { + List<Extension> extensions = new LinkedList<Extension>(); + MaxFragmentLength fraglen = maxFragmentLength(); + if (fraglen != null) + { + extensions.add(new Extension(Extension.Type.MAX_FRAGMENT_LENGTH, + fraglen)); + maxFragmentLengthSent = fraglen; + } + + String host = engine.getPeerHost(); + if (host != null) + { + ServerName name + = new ServerName(NameType.HOST_NAME, host); + ServerNameList names + = new ServerNameList(Collections.singletonList(name)); + extensions.add(new Extension(Extension.Type.SERVER_NAME, + names)); + } + + if (truncatedHMac()) + { + extensions.add(new Extension(Extension.Type.TRUNCATED_HMAC, + new TruncatedHMAC())); + truncatedHMacSent = true; + } + + ExtensionList elist = new ExtensionList(extensions); + hello.setExtensions(elist.buffer()); + } + else + hello.setDisableExtensions(true); + + if (Debug.DEBUG) + logger.logv(Component.SSL_HANDSHAKE, "{0}", hello); + + fragment.putInt((Handshake.Type.CLIENT_HELLO.getValue() << 24) + | (hello.length() & 0xFFFFFF)); + outBuffer = hello.buffer(); + int l = Math.min(fragment.remaining(), outBuffer.remaining()); + fragment.put((ByteBuffer) outBuffer.duplicate() + .limit(outBuffer.position() + l)); + outBuffer.position(outBuffer.position() + l); + + state = READ_SERVER_HELLO; + } + break; + + case WRITE_CERTIFICATE: + { + java.security.cert.Certificate[] chain + = engine.session().getLocalCertificates(); + if (chain != null) + { + CertificateBuilder cert + = new CertificateBuilder(CertificateType.X509); + try + { + cert.setCertificates(Arrays.asList(chain)); + } + catch (CertificateException ce) + { + throw new AlertException(new Alert(Level.FATAL, + Description.INTERNAL_ERROR), + ce); + } + + outBuffer = cert.buffer(); + + fragment.putInt((Handshake.Type.CERTIFICATE.getValue() << 24) + | (cert.length() & 0xFFFFFF)); + + int l = Math.min(fragment.remaining(), outBuffer.remaining()); + fragment.put((ByteBuffer) outBuffer.duplicate() + .limit(outBuffer.position() + l)); + outBuffer.position(outBuffer.position() + l); + } + state = WRITE_CLIENT_KEY_EXCHANGE; + } + break; + + case WRITE_CLIENT_KEY_EXCHANGE: + { + KeyExchangeAlgorithm kea = engine.session().suite.keyExchangeAlgorithm(); + ClientKeyExchangeBuilder ckex + = new ClientKeyExchangeBuilder(engine.session().suite, + engine.session().version); + if (kea == DHE_DSS || kea == DHE_RSA || kea == DH_anon + || kea == DH_DSS || kea == DH_RSA) + { + assert(dhPair != null); + DHPublicKey pubkey = (DHPublicKey) dhPair.getPublic(); + ClientDiffieHellmanPublic pub + = new ClientDiffieHellmanPublic(pubkey.getY()); + ckex.setExchangeKeys(pub.buffer()); + } + if (kea == RSA || kea == RSA_PSK) + { + assert(keyExchange instanceof RSAGen); + assert(keyExchange.hasRun()); + if (keyExchange.thrown() != null) + throw new AlertException(new Alert(Level.FATAL, + Description.HANDSHAKE_FAILURE), + keyExchange.thrown()); + EncryptedPreMasterSecret epms + = new EncryptedPreMasterSecret(((RSAGen) keyExchange).encryptedSecret(), + engine.session().version); + if (kea == RSA) + ckex.setExchangeKeys(epms.buffer()); + else + { + String identity = getPSKIdentity(); + if (identity == null) + throw new SSLException("no pre-shared-key identity;" + + " set the security property" + + " \"jessie.client.psk.identity\""); + ClientRSA_PSKParameters params = + new ClientRSA_PSKParameters(identity, epms.buffer()); + ckex.setExchangeKeys(params.buffer()); + generatePSKSecret(identity, preMasterSecret, true); + } + } + if (kea == DHE_PSK) + { + assert(keyExchange instanceof ClientDHGen); + assert(dhPair != null); + String identity = getPSKIdentity(); + if (identity == null) + throw new SSLException("no pre-shared key identity; set" + + " the security property" + + " \"jessie.client.psk.identity\""); + DHPublicKey pubkey = (DHPublicKey) dhPair.getPublic(); + ClientDHE_PSKParameters params = + new ClientDHE_PSKParameters(identity, + new ClientDiffieHellmanPublic(pubkey.getY())); + ckex.setExchangeKeys(params.buffer()); + generatePSKSecret(identity, preMasterSecret, true); + } + if (kea == PSK) + { + String identity = getPSKIdentity(); + if (identity == null) + throw new SSLException("no pre-shared key identity; set" + + " the security property" + + " \"jessie.client.psk.identity\""); + generatePSKSecret(identity, null, true); + ClientPSKParameters params = new ClientPSKParameters(identity); + ckex.setExchangeKeys(params.buffer()); + } + if (kea == NONE) + { + Inflater inflater = null; + Deflater deflater = null; + if (compression == CompressionMethod.ZLIB) + { + inflater = new Inflater(); + deflater = new Deflater(); + } + inParams = new InputSecurityParameters(null, null, inflater, + engine.session(), + engine.session().suite); + outParams = new OutputSecurityParameters(null, null, deflater, + engine.session(), + engine.session().suite); + engine.session().privateData.masterSecret = new byte[0]; + } + + if (Debug.DEBUG) + logger.logv(Component.SSL_HANDSHAKE, "{0}", ckex); + + outBuffer = ckex.buffer(); + if (Debug.DEBUG) + logger.logv(Component.SSL_HANDSHAKE, "client kex buffer {0}", outBuffer); + fragment.putInt((Handshake.Type.CLIENT_KEY_EXCHANGE.getValue() << 24) + | (ckex.length() & 0xFFFFFF)); + int l = Math.min(fragment.remaining(), outBuffer.remaining()); + fragment.put((ByteBuffer) outBuffer.duplicate().limit(outBuffer.position() + l)); + outBuffer.position(outBuffer.position() + l); + + if (privateKey != null) + { + genCertVerify = new GenCertVerify(md5, sha); + tasks.add(genCertVerify); + state = WRITE_CERTIFICATE_VERIFY; + } + else + { + engine.changeCipherSpec(); + state = WRITE_FINISHED; + } + } + // Both states terminate in a NEED_TASK, or a need to change cipher + // specs; so we can't write any more messages here. + break outer_loop; + + case WRITE_CERTIFICATE_VERIFY: + { + assert(genCertVerify != null); + assert(genCertVerify.hasRun()); + CertificateVerify verify = new CertificateVerify(genCertVerify.signed(), + engine.session().suite.signatureAlgorithm()); + + outBuffer = verify.buffer(); + fragment.putInt((Handshake.Type.CERTIFICATE_VERIFY.getValue() << 24) + | (verify.length() & 0xFFFFFF)); + int l = Math.min(fragment.remaining(), outBuffer.remaining()); + fragment.put((ByteBuffer) outBuffer.duplicate().limit(outBuffer.position() + l)); + outBuffer.position(outBuffer.position() + l); + + // XXX This is a potential problem: we may not have drained + // outBuffer, but set the changeCipherSpec toggle. + engine.changeCipherSpec(); + state = WRITE_FINISHED; + } + break outer_loop; + + case WRITE_FINISHED: + { + MessageDigest md5copy = null; + MessageDigest shacopy = null; + try + { + md5copy = (MessageDigest) md5.clone(); + shacopy = (MessageDigest) sha.clone(); + } + catch (CloneNotSupportedException cnse) + { + // We're improperly configured to use a non-cloneable + // md5/sha-1, OR there's a runtime bug. + throw new SSLException(cnse); + } + outBuffer + = generateFinished(md5copy, shacopy, true, + engine.session()); + + fragment.putInt((Handshake.Type.FINISHED.getValue() << 24) + | outBuffer.remaining() & 0xFFFFFF); + + int l = Math.min(outBuffer.remaining(), fragment.remaining()); + fragment.put((ByteBuffer) outBuffer.duplicate().limit(outBuffer.position() + l)); + outBuffer.position(outBuffer.position() + l); + + if (continuedSession) + state = DONE; + else + state = READ_FINISHED; + } + break; + + default: + throw new IllegalStateException("invalid state: " + state); + } + } + + if (!tasks.isEmpty()) + return HandshakeStatus.NEED_TASK; + if (state.isWriteState() || + (outBuffer != null && outBuffer.hasRemaining())) + return HandshakeStatus.NEED_WRAP; + if (state.isReadState()) + return HandshakeStatus.NEED_UNWRAP; + + return HandshakeStatus.FINISHED; + } + + /* (non-Javadoc) + * @see gnu.javax.net.ssl.provider.AbstractHandshake#status() + */ + @Override HandshakeStatus status() + { + if (state.isReadState()) + return HandshakeStatus.NEED_UNWRAP; + if (state.isWriteState()) + return HandshakeStatus.NEED_WRAP; + return HandshakeStatus.FINISHED; + } + + @Override void checkKeyExchange() throws SSLException + { + // XXX implement. + } + + /* (non-Javadoc) + * @see gnu.javax.net.ssl.provider.AbstractHandshake#handleV2Hello(java.nio.ByteBuffer) + */ + @Override void handleV2Hello(ByteBuffer hello) throws SSLException + { + throw new SSLException("this should be impossible"); + } + + private ProtocolVersion chooseVersion() throws SSLException + { + // Select the highest enabled version, for our initial key exchange. + ProtocolVersion version = null; + for (String ver : engine.getEnabledProtocols()) + { + try + { + ProtocolVersion v = ProtocolVersion.forName(ver); + if (version == null || version.compareTo(v) < 0) + version = v; + } + catch (Exception x) + { + continue; + } + } + + if (version == null) + throw new SSLException("no suitable enabled versions"); + + return version; + } + + private List<CipherSuite> getSuites() throws SSLException + { + List<CipherSuite> suites = new LinkedList<CipherSuite>(); + for (String s : engine.getEnabledCipherSuites()) + { + CipherSuite suite = CipherSuite.forName(s); + if (suite != null) + suites.add(suite); + } + if (suites.isEmpty()) + throw new SSLException("no cipher suites enabled"); + return suites; + } + + private List<CompressionMethod> getCompressionMethods() + { + List<CompressionMethod> methods = new LinkedList<CompressionMethod>(); + GetSecurityPropertyAction gspa = new GetSecurityPropertyAction("jessie.enable.compression"); + if (Boolean.valueOf(AccessController.doPrivileged(gspa))) + methods.add(CompressionMethod.ZLIB); + methods.add(CompressionMethod.NULL); + return methods; + } + + private boolean enableExtensions() + { + GetSecurityPropertyAction action + = new GetSecurityPropertyAction("jessie.client.enable.extensions"); + return Boolean.valueOf(AccessController.doPrivileged(action)); + } + + private MaxFragmentLength maxFragmentLength() + { + GetSecurityPropertyAction action + = new GetSecurityPropertyAction("jessie.client.maxFragmentLength"); + String s = AccessController.doPrivileged(action); + if (s != null) + { + try + { + int len = Integer.parseInt(s); + switch (len) + { + case 9: + case (1 << 9): return MaxFragmentLength.LEN_2_9; + case 10: + case (1 << 10): return MaxFragmentLength.LEN_2_10; + case 11: + case (1 << 11): return MaxFragmentLength.LEN_2_11; + case 12: + case (1 << 12): return MaxFragmentLength.LEN_2_12; + } + } + catch (NumberFormatException nfe) + { + } + } + return null; + } + + private boolean truncatedHMac() + { + GetSecurityPropertyAction action + = new GetSecurityPropertyAction("jessie.client.truncatedHMac"); + return Boolean.valueOf(AccessController.doPrivileged(action)); + } + + private String getPSKIdentity() + { + GetSecurityPropertyAction action + = new GetSecurityPropertyAction("jessie.client.psk.identity"); + return AccessController.doPrivileged(action); + } + + // Delegated tasks. + + class ParamsVerifier extends DelegatedTask + { + private final ByteBuffer paramsBuffer; + private final byte[] signature; + private boolean verified; + + ParamsVerifier(ByteBuffer paramsBuffer, byte[] signature) + { + this.paramsBuffer = paramsBuffer; + this.signature = signature; + } + + public void implRun() + throws InvalidKeyException, NoSuchAlgorithmException, + SSLPeerUnverifiedException, SignatureException + { + java.security.Signature s + = java.security.Signature.getInstance(engine.session().suite + .signatureAlgorithm().algorithm()); + s.initVerify(engine.session().getPeerCertificates()[0]); + s.update(paramsBuffer); + verified = s.verify(signature); + synchronized (this) + { + notifyAll(); + } + } + + boolean verified() + { + return verified; + } + } + + class ClientDHGen extends DelegatedTask + { + private final DHPublicKey serverKey; + private final DHParameterSpec params; + private final boolean full; + + ClientDHGen(DHPublicKey serverKey, DHParameterSpec params, boolean full) + { + this.serverKey = serverKey; + this.params = params; + this.full = full; + } + + public void implRun() + throws InvalidAlgorithmParameterException, NoSuchAlgorithmException, + SSLException + { + if (Debug.DEBUG) + logger.log(Component.SSL_DELEGATED_TASK, "running client DH phase"); + if (paramsVerifier != null) + { + synchronized (paramsVerifier) + { + try + { + while (!paramsVerifier.hasRun()) + paramsVerifier.wait(500); + } + catch (InterruptedException ie) + { + // Ignore. + } + } + } + KeyPairGenerator gen = KeyPairGenerator.getInstance("DH"); + gen.initialize(params, engine.session().random()); + dhPair = gen.generateKeyPair(); + if (Debug.DEBUG_KEY_EXCHANGE) + logger.logv(Component.SSL_KEY_EXCHANGE, + "client keys public:{0} private:{1}", dhPair.getPublic(), + dhPair.getPrivate()); + + initDiffieHellman((DHPrivateKey) dhPair.getPrivate(), engine.session().random()); + + // We have enough info to do the full key exchange; so let's do it. + DHPhase phase = new DHPhase(serverKey, full); + phase.run(); + if (phase.thrown() != null) + throw new SSLException(phase.thrown()); + } + + DHPublicKey serverKey() + { + return serverKey; + } + } + + class CertLoader extends DelegatedTask + { + private final List<String> keyTypes; + private final List<X500Principal> issuers; + + CertLoader(List<String> keyTypes, List<X500Principal> issuers) + { + this.keyTypes = keyTypes; + this.issuers = issuers; + } + + public void implRun() + { + X509ExtendedKeyManager km = engine.contextImpl.keyManager; + if (km == null) + return; + keyAlias = km.chooseEngineClientAlias(keyTypes.toArray(new String[keyTypes.size()]), + issuers.toArray(new X500Principal[issuers.size()]), + engine); + engine.session().setLocalCertificates(km.getCertificateChain(keyAlias)); + privateKey = km.getPrivateKey(keyAlias); + } + } + + class RSAGen extends DelegatedTask + { + private byte[] encryptedPreMasterSecret; + private final boolean full; + + RSAGen() + { + this(true); + } + + RSAGen(boolean full) + { + this.full = full; + } + + public void implRun() + throws BadPaddingException, IllegalBlockSizeException, InvalidKeyException, + NoSuchAlgorithmException, NoSuchPaddingException, + SSLException + { + if (certVerifier != null) + { + synchronized (certVerifier) + { + try + { + while (!certVerifier.hasRun()) + certVerifier.wait(500); + } + catch (InterruptedException ie) + { + // Ignore. + } + } + } + preMasterSecret = new byte[48]; + engine.session().random().nextBytes(preMasterSecret); + preMasterSecret[0] = (byte) sentVersion.major(); + preMasterSecret[1] = (byte) sentVersion.minor(); + Cipher rsa = Cipher.getInstance("RSA"); + java.security.cert.Certificate cert + = engine.session().getPeerCertificates()[0]; + rsa.init(Cipher.ENCRYPT_MODE, cert); + encryptedPreMasterSecret = rs... [truncated message content] |
From: <ls...@us...> - 2007-01-07 12:47:50
|
Revision: 3018 http://jnode.svn.sourceforge.net/jnode/?rev=3018&view=rev Author: lsantha Date: 2007-01-07 04:47:49 -0800 (Sun, 07 Jan 2007) Log Message: ----------- Classpath patches. Modified Paths: -------------- trunk/core/src/classpath/gnu/gnu/javax/net/ssl/provider/Alert.java trunk/core/src/classpath/gnu/gnu/javax/net/ssl/provider/AlertException.java trunk/core/src/classpath/gnu/gnu/javax/net/ssl/provider/Certificate.java trunk/core/src/classpath/gnu/gnu/javax/net/ssl/provider/CertificateRequest.java trunk/core/src/classpath/gnu/gnu/javax/net/ssl/provider/CertificateType.java trunk/core/src/classpath/gnu/gnu/javax/net/ssl/provider/CertificateVerify.java trunk/core/src/classpath/gnu/gnu/javax/net/ssl/provider/CipherSuite.java Added Paths: ----------- trunk/core/src/classpath/gnu/gnu/javax/net/ssl/provider/AbstractHandshake.java trunk/core/src/classpath/gnu/gnu/javax/net/ssl/provider/Builder.java trunk/core/src/classpath/gnu/gnu/javax/net/ssl/provider/CertificateBuilder.java trunk/core/src/classpath/gnu/gnu/javax/net/ssl/provider/CertificateRequestBuilder.java trunk/core/src/classpath/gnu/gnu/javax/net/ssl/provider/CertificateStatusRequest.java trunk/core/src/classpath/gnu/gnu/javax/net/ssl/provider/CertificateStatusType.java trunk/core/src/classpath/gnu/gnu/javax/net/ssl/provider/CertificateURL.java trunk/core/src/classpath/gnu/gnu/javax/net/ssl/provider/CipherAlgorithm.java trunk/core/src/classpath/gnu/gnu/javax/net/ssl/provider/CipherSuiteList.java Added: trunk/core/src/classpath/gnu/gnu/javax/net/ssl/provider/AbstractHandshake.java =================================================================== --- trunk/core/src/classpath/gnu/gnu/javax/net/ssl/provider/AbstractHandshake.java (rev 0) +++ trunk/core/src/classpath/gnu/gnu/javax/net/ssl/provider/AbstractHandshake.java 2007-01-07 12:47:49 UTC (rev 3018) @@ -0,0 +1,1205 @@ +/* AbstractHandshake.java -- abstract handshake handler. + Copyright (C) 2006 Free Software Foundation, Inc. + +This file is a 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 of the License, 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; if not, write to the Free Software +Foundation, Inc., 51 Franklin St, 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.javax.net.ssl.provider; + +import gnu.classpath.debug.Component; +import gnu.classpath.debug.SystemLogger; +import gnu.java.security.action.GetSecurityPropertyAction; +import gnu.java.security.prng.IRandom; +import gnu.java.security.prng.LimitReachedException; +import gnu.java.security.util.ByteArray; +import gnu.javax.security.auth.callback.CertificateCallback; +import gnu.javax.security.auth.callback.DefaultCallbackHandler; + +import java.nio.ByteBuffer; +import java.security.AccessController; +import java.security.DigestException; +import java.security.InvalidAlgorithmParameterException; +import java.security.InvalidKeyException; +import java.security.KeyManagementException; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.security.PrivilegedExceptionAction; +import java.security.SecureRandom; +import java.security.cert.CertificateException; +import java.security.cert.X509Certificate; +import java.util.Arrays; +import java.util.HashMap; +import java.util.LinkedList; +import java.util.zip.Deflater; +import java.util.zip.Inflater; + +import javax.crypto.Cipher; +import javax.crypto.KeyAgreement; +import javax.crypto.Mac; +import javax.crypto.NoSuchPaddingException; +import javax.crypto.SecretKey; +import javax.crypto.interfaces.DHPrivateKey; +import javax.crypto.interfaces.DHPublicKey; +import javax.crypto.spec.IvParameterSpec; +import javax.crypto.spec.SecretKeySpec; +import javax.net.ssl.SSLEngineResult; +import javax.net.ssl.SSLException; +import javax.net.ssl.X509TrustManager; +import javax.net.ssl.SSLEngineResult.HandshakeStatus; +import javax.security.auth.callback.Callback; +import javax.security.auth.callback.CallbackHandler; +import javax.security.auth.callback.ConfirmationCallback; + +/** + * The base interface for handshake implementations. Concrete + * subclasses of this class (one for the server, one for the client) + * handle the HANDSHAKE content-type in communications. + */ +public abstract class AbstractHandshake +{ + protected static final SystemLogger logger = SystemLogger.SYSTEM; + + /** + * "server finished" -- TLS 1.0 and later + */ + protected static final byte[] SERVER_FINISHED + = new byte[] { + 115, 101, 114, 118, 101, 114, 32, 102, 105, 110, 105, 115, + 104, 101, 100 + }; + + /** + * "client finished" -- TLS 1.0 and later + */ + protected static final byte[] CLIENT_FINISHED + = new byte[] { + 99, 108, 105, 101, 110, 116, 32, 102, 105, 110, 105, 115, + 104, 101, 100 + }; + + /** + * "key expansion" -- TLS 1.0 and later + */ + private static final byte[] KEY_EXPANSION = + new byte[] { 107, 101, 121, 32, 101, 120, 112, + 97, 110, 115, 105, 111, 110 }; + + /** + * "master secret" -- TLS 1.0 and later + */ + private static final byte[] MASTER_SECRET + = new byte[] { + 109, 97, 115, 116, 101, 114, 32, 115, 101, 99, 114, 101, 116 + }; + + /** + * "client write key" -- TLS 1.0 exportable whitener. + */ + private static final byte[] CLIENT_WRITE_KEY + = new byte[] { + 99, 108, 105, 101, 110, 116, 32, 119, 114, 105, 116, 101, 32, 107, + 101, 121 + }; + + /** + * "server write key" -- TLS 1.0 exportable whitener. + */ + private static final byte[] SERVER_WRITE_KEY + = new byte[] { + 115, 101, 114, 118, 101, 114, 32, 119, 114, 105, 116, 101, 32, 107, + 101, 121 + }; + + private static final byte[] IV_BLOCK + = new byte[] { + 73, 86, 32, 98, 108, 111, 99, 107 + }; + + /** + * SSL 3.0; the string "CLNT" + */ + private static final byte[] SENDER_CLIENT + = new byte[] { 0x43, 0x4C, 0x4E, 0x54 }; + + /** + * SSL 3.0; the string "SRVR" + */ + private static final byte[] SENDER_SERVER + = new byte[] { 0x53, 0x52, 0x56, 0x52 }; + + /** + * SSL 3.0; the value 0x36 40 (for SHA-1 hashes) or 48 (for MD5 hashes) + * times. + */ + protected static final byte[] PAD1 = new byte[48]; + + /** + * SSL 3.0; the value 0x5c 40 (for SHA-1 hashes) or 48 (for MD5 hashes) + * times. + */ + protected static final byte[] PAD2 = new byte[48]; + + static + { + Arrays.fill(PAD1, SSLHMac.PAD1); + Arrays.fill(PAD2, SSLHMac.PAD2); + } + + /** + * The currently-read handshake messages. There may be zero, or + * multiple, handshake messages in this buffer. + */ + protected ByteBuffer handshakeBuffer; + + /** + * The offset into `handshakeBuffer' where the first unread + * handshake message resides. + */ + protected int handshakeOffset; + + protected MessageDigest sha; + protected MessageDigest md5; + + protected final SSLEngineImpl engine; + protected KeyAgreement keyAgreement; + protected byte[] preMasterSecret; + protected InputSecurityParameters inParams; + protected OutputSecurityParameters outParams; + protected LinkedList<DelegatedTask> tasks; + protected Random serverRandom; + protected Random clientRandom; + protected CompressionMethod compression; + + protected AbstractHandshake(SSLEngineImpl engine) + throws NoSuchAlgorithmException + { + this.engine = engine; + sha = MessageDigest.getInstance("SHA-1"); + md5 = MessageDigest.getInstance("MD5"); + tasks = new LinkedList<DelegatedTask>(); + } + + /** + * Handles the next input message in the handshake. This is called + * in response to a call to {@link javax.net.ssl.SSLEngine#unwrap} + * for a message with content-type HANDSHAKE. + * + * @param record The input record. The callee should not assume that + * the record's buffer is writable, and should not try to use it for + * output or temporary storage. + * @return An {@link SSLEngineResult} describing the result. + */ + public final HandshakeStatus handleInput (ByteBuffer fragment) + throws SSLException + { + if (!tasks.isEmpty()) + return HandshakeStatus.NEED_TASK; + + HandshakeStatus status = status(); + if (status != HandshakeStatus.NEED_UNWRAP) + return status; + + // Try to read another... + if (!pollHandshake(fragment)) + return HandshakeStatus.NEED_UNWRAP; + + while (hasMessage() && status != HandshakeStatus.NEED_WRAP) + { + int pos = handshakeOffset; + status = implHandleInput(); + int len = handshakeOffset - pos; + if (len == 0) + { + // Don't bother; the impl is just telling us to go around + // again. + continue; + } + if (doHash()) + { + if (Debug.DEBUG) + logger.logv(Component.SSL_HANDSHAKE, "hashing output\n{0}", + Util.hexDump((ByteBuffer) handshakeBuffer + .duplicate().position(pos) + .limit(pos+len), " >> ")); + sha.update((ByteBuffer) handshakeBuffer.duplicate() + .position(pos).limit(pos+len)); + md5.update((ByteBuffer) handshakeBuffer.duplicate() + .position(pos).limit(pos+len)); + } + } + return status; + } + + /** + * Called to process more handshake data. This method will be called + * repeatedly while there is remaining handshake data, and while the + * status is + * @return + * @throws SSLException + */ + protected abstract HandshakeStatus implHandleInput() + throws SSLException; + + /** + * Produce more handshake output. This is called in response to a + * call to {@link javax.net.ssl.SSLEngine#wrap}, when the handshake + * is still in progress. + * + * @param record The output record; the callee should put its output + * handshake message (or a part of it) in the argument's + * <code>fragment</code>, and should set the record length + * appropriately. + * @return An {@link SSLEngineResult} describing the result. + */ + public final HandshakeStatus handleOutput (ByteBuffer fragment) + throws SSLException + { + if (!tasks.isEmpty()) + return HandshakeStatus.NEED_TASK; + + int orig = fragment.position(); + SSLEngineResult.HandshakeStatus status = implHandleOutput(fragment); + if (doHash()) + { + if (Debug.DEBUG) + logger.logv(Component.SSL_HANDSHAKE, "hashing output:\n{0}", + Util.hexDump((ByteBuffer) fragment.duplicate().flip().position(orig), " >> ")); + sha.update((ByteBuffer) fragment.duplicate().flip().position(orig)); + md5.update((ByteBuffer) fragment.duplicate().flip().position(orig)); + } + return status; + } + + /** + * Called to implement the underlying output handling. The callee should + * attempt to fill the given buffer as much as it can; this can include + * multiple, and even partial, handshake messages. + * + * @param fragment The buffer the callee should write handshake messages to. + * @return The new status of the handshake. + * @throws SSLException If an error occurs processing the output message. + */ + protected abstract SSLEngineResult.HandshakeStatus implHandleOutput (ByteBuffer fragment) + throws SSLException; + + /** + * Return a new instance of input security parameters, initialized with + * the session key. It is, of course, only valid to invoke this method + * once the handshake is complete, and the session keys established. + * + * <p>In the presence of a well-behaving peer, this should be called once + * the <code>ChangeCipherSpec</code> message is recieved. + * + * @return The input parameters for the newly established session. + * @throws SSLException If the handshake is not complete. + */ + final InputSecurityParameters getInputParams() throws SSLException + { + checkKeyExchange(); + return inParams; + } + + /** + * Return a new instance of output security parameters, initialized with + * the session key. This should be called after the + * <code>ChangeCipherSpec</code> message is sent to the peer. + * + * @return The output parameters for the newly established session. + * @throws SSLException If the handshake is not complete. + */ + final OutputSecurityParameters getOutputParams() throws SSLException + { + checkKeyExchange(); + return outParams; + } + + /** + * Fetch a delegated task waiting to run, if any. + * + * @return The task. + */ + final Runnable getTask() + { + if (tasks.isEmpty()) + return null; + return tasks.removeFirst(); + } + + /** + * Used by the skeletal code to query the current status of the handshake. + * This <em>should</em> be the same value as returned by the previous call + * to {@link #implHandleOutput(ByteBuffer)} or {@link + * #implHandleInput(ByteBuffer)}. + * + * @return The current handshake status. + */ + abstract HandshakeStatus status(); + + /** + * Check if the key exchange completed successfully, throwing an exception + * if not. + * + * <p>Note that we assume that the caller of our SSLEngine is correct, and + * that they did run the delegated tasks that encapsulate the key exchange. + * What we are primarily checking, therefore, is that no error occurred in the + * key exchange operation itself. + * + * @throws SSLException If the key exchange did not complete successfully. + */ + abstract void checkKeyExchange() throws SSLException; + + /** + * Handle an SSLv2 client hello. This is only used by SSL servers. + * + * @param hello The hello message. + */ + abstract void handleV2Hello(ByteBuffer hello) throws SSLException; + + /** + * Attempt to read the next handshake message from the given + * record. If only a partial handshake message is available, then + * this method saves the incoming bytes and returns false. If a + * complete handshake is read, or if there was one buffered in the + * handshake buffer, this method returns true, and `handshakeBuffer' + * can be used to read the handshake. + * + * @param record The input record. + * @return True if a complete handshake is present in the buffer; + * false if only a partial one. + */ + protected boolean pollHandshake (final ByteBuffer fragment) + { + // Allocate space for the new fragment. + if (handshakeBuffer == null + || handshakeBuffer.remaining() < fragment.remaining()) + { + // We need space for anything still unread in the handshake + // buffer... + int len = ((handshakeBuffer == null) ? 0 + : handshakeBuffer.position() - handshakeOffset); + + // Plus room for the incoming record. + len += fragment.remaining(); + reallocateBuffer(len); + } + + if (Debug.DEBUG) + logger.logv(Component.SSL_HANDSHAKE, "inserting {0} into {1}", + fragment, handshakeBuffer); + + // Put the fragment into the buffer. + handshakeBuffer.put(fragment); + + return hasMessage(); + } + + protected boolean doHash() + { + return true; + } + + /** + * Tell if the handshake buffer currently has a full handshake + * message. + */ + protected boolean hasMessage() + { + if (handshakeBuffer == null) + return false; + ByteBuffer tmp = handshakeBuffer.duplicate(); + tmp.flip(); + tmp.position(handshakeOffset); + if (Debug.DEBUG) + logger.logv(Component.SSL_HANDSHAKE, "current buffer: {0}; test buffer {1}", + handshakeBuffer, tmp); + if (tmp.remaining() < 4) + return false; + Handshake handshake = new Handshake(tmp.slice()); + if (Debug.DEBUG) + logger.logv(Component.SSL_HANDSHAKE, "handshake len:{0} remaining:{1}", + handshake.length(), tmp.remaining()); + return (handshake.length() <= tmp.remaining() - 4); + } + + /** + * Reallocate the handshake buffer so it can hold `totalLen' + * bytes. The smallest buffer allocated is 1024 bytes, and the size + * doubles from there until the buffer is sufficiently large. + */ + private void reallocateBuffer (final int totalLen) + { + int len = handshakeBuffer == null ? -1 + : handshakeBuffer.capacity() - (handshakeBuffer.limit() - handshakeOffset); + if (len >= totalLen) + { + // Big enough; no need to reallocate; but maybe shift the contents + // down. + if (handshakeOffset > 0) + { + handshakeBuffer.flip().position(handshakeOffset); + handshakeBuffer.compact(); + handshakeOffset = 0; + } + return; + } + + // Start at 1K (probably the system's page size). Double the size + // from there. + len = 1024; + while (len < totalLen) + len = len << 1; + ByteBuffer newBuf = ByteBuffer.allocate (len); + + // Copy the unread bytes from the old buffer. + if (handshakeBuffer != null) + { + handshakeBuffer.flip (); + handshakeBuffer.position(handshakeOffset); + newBuf.put(handshakeBuffer); + } + handshakeBuffer = newBuf; + + // We just put only unread handshake messages in the new buffer; + // the offset of the next one is now zero. + handshakeOffset = 0; + } + + /** + * Generate a certificate verify message for SSLv3. In SSLv3, a different + * algorithm was used to generate this value was subtly different than + * that used in TLSv1.0 and later. In TLSv1.0 and later, this value is + * just the digest over the handshake messages. + * + * <p>SSLv3 uses the algorithm: + * + * <pre> +CertificateVerify.signature.md5_hash + MD5(master_secret + pad_2 + + MD5(handshake_messages + master_secret + pad_1)); +Certificate.signature.sha_hash + SHA(master_secret + pad_2 + + SHA(handshake_messages + master_secret + pad_1));</pre> + * + * @param md5 The running MD5 hash of the handshake. + * @param sha The running SHA-1 hash of the handshake. + * @param session The current session being negotiated. + * @return The computed to-be-signed value. + */ + protected byte[] genV3CertificateVerify(MessageDigest md5, + MessageDigest sha, + SessionImpl session) + { + byte[] md5value = null; + if (session.suite.signatureAlgorithm() == SignatureAlgorithm.RSA) + { + md5.update(session.privateData.masterSecret); + md5.update(PAD1, 0, 48); + byte[] tmp = md5.digest(); + md5.reset(); + md5.update(session.privateData.masterSecret); + md5.update(PAD2, 0, 48); + md5.update(tmp); + md5value = md5.digest(); + } + + sha.update(session.privateData.masterSecret); + sha.update(PAD1, 0, 40); + byte[] tmp = sha.digest(); + sha.reset(); + sha.update(session.privateData.masterSecret); + sha.update(PAD2, 0, 40); + sha.update(tmp); + byte[] shavalue = sha.digest(); + + if (md5value != null) + return Util.concat(md5value, shavalue); + + return shavalue; + } + + /** + * Generate the session keys from the computed master secret. + * + * @param clientRandom The client's nonce. + * @param serverRandom The server's nonce. + * @param session The session being established. + * @return The derived keys. + */ + protected byte[][] generateKeys(Random clientRandom, Random serverRandom, + SessionImpl session) + { + int maclen = 20; // SHA-1. + if (session.suite.macAlgorithm() == MacAlgorithm.MD5) + maclen = 16; + int ivlen = 0; + if (session.suite.cipherAlgorithm() == CipherAlgorithm.DES + || session.suite.cipherAlgorithm() == CipherAlgorithm.DESede) + ivlen = 8; + if (session.suite.cipherAlgorithm() == CipherAlgorithm.AES) + ivlen = 16; + int keylen = session.suite.keyLength(); + + byte[][] keys = new byte[6][]; + keys[0] = new byte[maclen]; // client_write_MAC_secret + keys[1] = new byte[maclen]; // server_write_MAC_secret + keys[2] = new byte[keylen]; // client_write_key + keys[3] = new byte[keylen]; // server_write_key + keys[4] = new byte[ivlen]; // client_write_iv + keys[5] = new byte[ivlen]; // server_write_iv + + IRandom prf = null; + if (session.version == ProtocolVersion.SSL_3) + { + byte[] seed = new byte[clientRandom.length() + + serverRandom.length()]; + serverRandom.buffer().get(seed, 0, serverRandom.length()); + clientRandom.buffer().get(seed, serverRandom.length(), + clientRandom.length()); + prf = new SSLRandom(); + HashMap<String,byte[]> attr = new HashMap<String,byte[]>(2); + attr.put(SSLRandom.SECRET, session.privateData.masterSecret); + attr.put(SSLRandom.SEED, seed); + prf.init(attr); + } + else + { + byte[] seed = new byte[KEY_EXPANSION.length + + clientRandom.length() + + serverRandom.length()]; + System.arraycopy(KEY_EXPANSION, 0, seed, 0, KEY_EXPANSION.length); + serverRandom.buffer().get(seed, KEY_EXPANSION.length, + serverRandom.length()); + clientRandom.buffer().get(seed, (KEY_EXPANSION.length + + serverRandom.length()), + clientRandom.length()); + + prf = new TLSRandom(); + HashMap<String,byte[]> attr = new HashMap<String,byte[]>(2); + attr.put(TLSRandom.SECRET, session.privateData.masterSecret); + attr.put(TLSRandom.SEED, seed); + prf.init(attr); + } + + try + { + prf.nextBytes(keys[0], 0, keys[0].length); + prf.nextBytes(keys[1], 0, keys[1].length); + prf.nextBytes(keys[2], 0, keys[2].length); + prf.nextBytes(keys[3], 0, keys[3].length); + + if (session.suite.isExportable()) + { + if (session.version == ProtocolVersion.SSL_3) + { + MessageDigest md5 = MessageDigest.getInstance("MD5"); + md5.update(clientRandom.buffer()); + md5.update(serverRandom.buffer()); + byte[] d = md5.digest(); + System.arraycopy(d, 0, keys[4], 0, keys[4].length); + + md5.reset(); + md5.update(serverRandom.buffer()); + md5.update(clientRandom.buffer()); + d = md5.digest(); + System.arraycopy(d, 0, keys[5], 0, keys[5].length); + + md5.reset(); + md5.update(keys[2]); + md5.update(clientRandom.buffer()); + md5.update(serverRandom.buffer()); + keys[2] = Util.trim(md5.digest(), 8); + + md5.reset(); + md5.update(keys[3]); + md5.update(serverRandom.buffer()); + md5.update(clientRandom.buffer()); + keys[3] = Util.trim(md5.digest(), 8); + } + else + { + TLSRandom prf2 = new TLSRandom(); + HashMap<String,byte[]> attr = new HashMap<String,byte[]>(2); + attr.put(TLSRandom.SECRET, keys[2]); + byte[] seed = new byte[CLIENT_WRITE_KEY.length + + clientRandom.length() + + serverRandom.length()]; + System.arraycopy(CLIENT_WRITE_KEY, 0, seed, 0, + CLIENT_WRITE_KEY.length); + clientRandom.buffer().get(seed, CLIENT_WRITE_KEY.length, + clientRandom.length()); + serverRandom.buffer().get(seed, CLIENT_WRITE_KEY.length + + clientRandom.length(), + serverRandom.length()); + attr.put(TLSRandom.SEED, seed); + prf2.init(attr); + keys[2] = new byte[8]; + prf2.nextBytes(keys[2], 0, keys[2].length); + + attr.put(TLSRandom.SECRET, keys[3]); + seed = new byte[SERVER_WRITE_KEY.length + + serverRandom.length() + + clientRandom.length()]; + System.arraycopy(SERVER_WRITE_KEY, 0, seed, 0, + SERVER_WRITE_KEY.length); + serverRandom.buffer().get(seed, SERVER_WRITE_KEY.length, + serverRandom.length()); + clientRandom.buffer().get(seed, SERVER_WRITE_KEY.length + + serverRandom.length(), + + clientRandom.length()); + attr.put(TLSRandom.SEED, seed); + prf2.init(attr); + keys[3] = new byte[8]; + prf2.nextBytes(keys[3], 0, keys[3].length); + + attr.put(TLSRandom.SECRET, new byte[0]); + seed = new byte[IV_BLOCK.length + + clientRandom.length() + + serverRandom.length()]; + System.arraycopy(IV_BLOCK, 0, seed, 0, IV_BLOCK.length); + clientRandom.buffer().get(seed, IV_BLOCK.length, + clientRandom.length()); + serverRandom.buffer().get(seed, IV_BLOCK.length + + clientRandom.length(), + serverRandom.length()); + attr.put(TLSRandom.SEED, seed); + prf2.init(attr); + prf2.nextBytes(keys[4], 0, keys[4].length); + prf2.nextBytes(keys[5], 0, keys[5].length); + } + } + else + { + prf.nextBytes(keys[4], 0, keys[4].length); + prf.nextBytes(keys[5], 0, keys[5].length); + } + } + catch (LimitReachedException lre) + { + // Won't happen with our implementation. + throw new Error(lre); + } + catch (NoSuchAlgorithmException nsae) + { + throw new Error(nsae); + } + + if (Debug.DEBUG_KEY_EXCHANGE) + logger.logv(Component.SSL_KEY_EXCHANGE, + "keys generated;\n [0]: {0}\n [1]: {1}\n [2]: {2}\n" + + " [3]: {3}\n [4]: {4}\n [5]: {5}", + Util.toHexString(keys[0], ':'), + Util.toHexString(keys[1], ':'), + Util.toHexString(keys[2], ':'), + Util.toHexString(keys[3], ':'), + Util.toHexString(keys[4], ':'), + Util.toHexString(keys[5], ':')); + return keys; + } + + /** + * Generate a "finished" message. The hashes passed in are modified + * by this function, so they should be clone copies of the digest if + * the hash function needs to be used more. + * + * @param md5 The MD5 computation. + * @param sha The SHA-1 computation. + * @param isClient Whether or not the client-side finished message is + * being computed. + * @param session The current session. + * @return A byte buffer containing the computed finished message. + */ + protected ByteBuffer generateFinished(MessageDigest md5, + MessageDigest sha, + boolean isClient, + SessionImpl session) + { + ByteBuffer finishedBuffer = null; + if (session.version.compareTo(ProtocolVersion.TLS_1) >= 0) + { + finishedBuffer = ByteBuffer.allocate(12); + TLSRandom prf = new TLSRandom(); + byte[] md5val = md5.digest(); + byte[] shaval = sha.digest(); + if (Debug.DEBUG) + logger.logv(Component.SSL_HANDSHAKE, "finished md5:{0} sha:{1}", + Util.toHexString(md5val, ':'), + Util.toHexString(shaval, ':')); + byte[] seed = new byte[CLIENT_FINISHED.length + + md5val.length + + shaval.length]; + if (isClient) + System.arraycopy(CLIENT_FINISHED, 0, seed, 0, CLIENT_FINISHED.length); + else + System.arraycopy(SERVER_FINISHED, 0, seed, 0, SERVER_FINISHED.length); + System.arraycopy(md5val, 0, + seed, CLIENT_FINISHED.length, + md5val.length); + System.arraycopy(shaval, 0, + seed, CLIENT_FINISHED.length + md5val.length, + shaval.length); + HashMap<String, Object> params = new HashMap<String, Object>(2); + params.put(TLSRandom.SECRET, session.privateData.masterSecret); + params.put(TLSRandom.SEED, seed); + prf.init(params); + byte[] buf = new byte[12]; + prf.nextBytes(buf, 0, buf.length); + finishedBuffer.put(buf).position(0); + } + else + { + // The SSLv3 algorithm is: + // + // enum { client(0x434C4E54), server(0x53525652) } Sender; + // + // struct { + // opaque md5_hash[16]; + // opaque sha_hash[20]; + // } Finished; + // + // md5_hash MD5(master_secret + pad2 + + // MD5(handshake_messages + Sender + + // master_secret + pad1)); + // sha_hash SHA(master_secret + pad2 + + // SHA(handshake_messages + Sender + + // master_secret + pad1)); + // + + finishedBuffer = ByteBuffer.allocate(36); + + md5.update(isClient ? SENDER_CLIENT : SENDER_SERVER); + md5.update(session.privateData.masterSecret); + md5.update(PAD1); + + byte[] tmp = md5.digest(); + md5.reset(); + md5.update(session.privateData.masterSecret); + md5.update(PAD2); + md5.update(tmp); + finishedBuffer.put(md5.digest()); + + sha.update(isClient ? SENDER_CLIENT : SENDER_SERVER); + sha.update(session.privateData.masterSecret); + sha.update(PAD1, 0, 40); + + tmp = sha.digest(); + sha.reset(); + sha.update(session.privateData.masterSecret); + sha.update(PAD2, 0, 40); + sha.update(tmp); + finishedBuffer.put(sha.digest()).position(0); + } + return finishedBuffer; + } + + protected void initDiffieHellman(DHPrivateKey dhKey, SecureRandom random) + throws SSLException + { + try + { + keyAgreement = KeyAgreement.getInstance("DH"); + keyAgreement.init(dhKey, random); + } + catch (InvalidKeyException ike) + { + throw new SSLException(ike); + } + catch (NoSuchAlgorithmException nsae) + { + throw new SSLException(nsae); + } + } + + protected void generateMasterSecret(Random clientRandom, + Random serverRandom, + SessionImpl session) + throws SSLException + { + assert(clientRandom != null); + assert(serverRandom != null); + assert(session != null); + + if (Debug.DEBUG_KEY_EXCHANGE) + logger.logv(Component.SSL_KEY_EXCHANGE, "preMasterSecret:\n{0}", + new ByteArray(preMasterSecret)); + + if (session.version == ProtocolVersion.SSL_3) + { + try + { + MessageDigest _md5 = MessageDigest.getInstance("MD5"); + MessageDigest _sha = MessageDigest.getInstance("SHA"); + session.privateData.masterSecret = new byte[48]; + + _sha.update((byte) 'A'); + _sha.update(preMasterSecret); + _sha.update(clientRandom.buffer()); + _sha.update(serverRandom.buffer()); + _md5.update(preMasterSecret); + _md5.update(_sha.digest()); + _md5.digest(session.privateData.masterSecret, 0, 16); + + _sha.update((byte) 'B'); + _sha.update((byte) 'B'); + _sha.update(preMasterSecret); + _sha.update(clientRandom.buffer()); + _sha.update(serverRandom.buffer()); + _md5.update(preMasterSecret); + _md5.update(_sha.digest()); + _md5.digest(session.privateData.masterSecret, 16, 16); + + _sha.update((byte) 'C'); + _sha.update((byte) 'C'); + _sha.update((byte) 'C'); + _sha.update(preMasterSecret); + _sha.update(clientRandom.buffer()); + _sha.update(serverRandom.buffer()); + _md5.update(preMasterSecret); + _md5.update(_sha.digest()); + _md5.digest(session.privateData.masterSecret, 32, 16); + } + catch (DigestException de) + { + throw new SSLException(de); + } + catch (NoSuchAlgorithmException nsae) + { + throw new SSLException(nsae); + } + } + else // TLSv1.0 and later + { + byte[] seed = new byte[clientRandom.length() + + serverRandom.length() + + MASTER_SECRET.length]; + System.arraycopy(MASTER_SECRET, 0, seed, 0, MASTER_SECRET.length); + clientRandom.buffer().get(seed, MASTER_SECRET.length, + clientRandom.length()); + serverRandom.buffer().get(seed, + MASTER_SECRET.length + clientRandom.length(), + serverRandom.length()); + TLSRandom prf = new TLSRandom(); + HashMap<String,byte[]> attr = new HashMap<String,byte[]>(2); + attr.put(TLSRandom.SECRET, preMasterSecret); + attr.put(TLSRandom.SEED, seed); + prf.init(attr); + + session.privateData.masterSecret = new byte[48]; + prf.nextBytes(session.privateData.masterSecret, 0, 48); + } + + if (Debug.DEBUG_KEY_EXCHANGE) + logger.log(Component.SSL_KEY_EXCHANGE, "master_secret: {0}", + new ByteArray(session.privateData.masterSecret)); + + // Wipe out the preMasterSecret. + for (int i = 0; i < preMasterSecret.length; i++) + preMasterSecret[i] = 0; + } + + protected void setupSecurityParameters(byte[][] keys, boolean isClient, + SSLEngineImpl engine, + CompressionMethod compression) + throws SSLException + { + assert(keys.length == 6); + assert(engine != null); + assert(compression != null); + + try + { + CipherSuite s = engine.session().suite; + Cipher inCipher = s.cipher(); + Mac inMac = s.mac(engine.session().version); + Inflater inflater = (compression == CompressionMethod.ZLIB + ? new Inflater() : null); + inCipher.init(Cipher.DECRYPT_MODE, + new SecretKeySpec(keys[isClient ? 3 : 2], + s.cipherAlgorithm().toString()), + new IvParameterSpec(keys[isClient ? 5 : 4])); + inMac.init(new SecretKeySpec(keys[isClient ? 1 : 0], + inMac.getAlgorithm())); + inParams = new InputSecurityParameters(inCipher, inMac, + inflater, + engine.session(), s); + + Cipher outCipher = s.cipher(); + Mac outMac = s.mac(engine.session().version); + Deflater deflater = (compression == CompressionMethod.ZLIB + ? new Deflater() : null); + outCipher.init(Cipher.ENCRYPT_MODE, + new SecretKeySpec(keys[isClient ? 2 : 3], + s.cipherAlgorithm().toString()), + new IvParameterSpec(keys[isClient ? 4 : 5])); + outMac.init(new SecretKeySpec(keys[isClient ? 0 : 1], + outMac.getAlgorithm())); + outParams = new OutputSecurityParameters(outCipher, outMac, + deflater, + engine.session(), s); + } + catch (InvalidAlgorithmParameterException iape) + { + throw new SSLException(iape); + } + catch (InvalidKeyException ike) + { + throw new SSLException(ike); + } + catch (NoSuchAlgorithmException nsae) + { + throw new SSLException(nsae); + } + catch (NoSuchPaddingException nspe) + { + throw new SSLException(nspe); + } + } + + protected void generatePSKSecret(String identity, byte[] otherkey, + boolean isClient) + throws SSLException + { + SecretKey key = null; + try + { + key = engine.contextImpl.pskManager.getKey(identity); + } + catch (KeyManagementException kme) + { + } + if (key != null) + { + byte[] keyb = key.getEncoded(); + if (otherkey == null) + { + otherkey = new byte[keyb.length]; + } + preMasterSecret = new byte[otherkey.length + keyb.length + 4]; + preMasterSecret[0] = (byte) (otherkey.length >>> 8); + preMasterSecret[1] = (byte) otherkey.length; + System.arraycopy(otherkey, 0, preMasterSecret, 2, otherkey.length); + preMasterSecret[otherkey.length + 2] + = (byte) (keyb.length >>> 8); + preMasterSecret[otherkey.length + 3] + = (byte) keyb.length; + System.arraycopy(keyb, 0, preMasterSecret, + otherkey.length + 4, keyb.length); + } + else + { + // Generate a random, fake secret. + preMasterSecret = new byte[8]; + preMasterSecret[1] = 2; + preMasterSecret[5] = 2; + preMasterSecret[6] = (byte) engine.session().random().nextInt(); + preMasterSecret[7] = (byte) engine.session().random().nextInt(); + } + + if (Debug.DEBUG_KEY_EXCHANGE) + logger.logv(Component.SSL_KEY_EXCHANGE, "PSK identity {0} key {1}", + identity, key); + + generateMasterSecret(clientRandom, serverRandom, + engine.session()); + byte[][] keys = generateKeys(clientRandom, serverRandom, + engine.session()); + setupSecurityParameters(keys, isClient, engine, compression); + } + + protected class DHPhase extends DelegatedTask + { + private final DHPublicKey key; + private final boolean full; + + protected DHPhase(DHPublicKey key) + { + this(key, true); + } + + protected DHPhase(DHPublicKey key, boolean full) + { + this.key = key; + this.full = full; + } + + protected void implRun() throws InvalidKeyException, SSLException + { + keyAgreement.doPhase(key, true); + preMasterSecret = keyAgreement.generateSecret(); + if (full) + { + generateMasterSecret(clientRandom, serverRandom, engine.session()); + byte[][] keys = generateKeys(clientRandom, serverRandom, engine.session()); + setupSecurityParameters(keys, engine.getUseClientMode(), engine, compression); + } + } + } + + protected class CertVerifier extends DelegatedTask + { + private final boolean clientSide; + private final X509Certificate[] chain; + private boolean verified; + + protected CertVerifier(boolean clientSide, X509Certificate[] chain) + { + this.clientSide = clientSide; + this.chain = chain; + } + + boolean verified() + { + return verified; + } + + protected void implRun() + { + X509TrustManager tm = engine.contextImpl.trustManager; + if (clientSide) + { + try + { + tm.checkServerTrusted(chain, null); + verified = true; + } + catch (CertificateException ce) + { + if (Debug.DEBUG) + logger.log(Component.SSL_DELEGATED_TASK, "cert verify", ce); + // For client connections, ask the user if the certificate is OK. + CallbackHandler verify = new DefaultCallbackHandler(); + GetSecurityPropertyAction gspa + = new GetSecurityPropertyAction("jessie.certificate.handler"); + String clazz = AccessController.doPrivileged(gspa); + try + { + ClassLoader cl = + AccessController.doPrivileged(new PrivilegedExceptionAction<ClassLoader>() + { + public ClassLoader run() throws Exception + { + return ClassLoader.getSystemClassLoader(); + } + }); + verify = (CallbackHandler) cl.loadClass(clazz).newInstance(); + } + catch (Exception x) + { + // Ignore. + if (Debug.DEBUG) + logger.log(Component.SSL_DELEGATED_TASK, + "callback handler loading", x); + } + // XXX Internationalize + CertificateCallback confirm = + new CertificateCallback(chain[0], + "The server's certificate could not be verified. There is no proof " + + "that this server is who it claims to be, or that their certificate " + + "is valid. Do you wish to continue connecting? "); + + try + { + verify.handle(new Callback[] { confirm }); + verified = confirm.getSelectedIndex() == ConfirmationCallback.YES; + } + catch (Exception x) + { + if (Debug.DEBUG) + logger.log(Component.SSL_DELEGATED_TASK, + "callback handler exception", x); + verified = false; + } + } + } + else + { + try + { + tm.checkClientTrusted(chain, null); + } + catch (CertificateException ce) + { + verified = false; + } + } + + if (verified) + engine.session().setPeerVerified(true); + } + } + + protected class DHE_PSKGen extends DelegatedTask + { + private final DHPublicKey dhKey; + private final SecretKey psKey; + private final boolean isClient; + + protected DHE_PSKGen(DHPublicKey dhKey, SecretKey psKey, boolean isClient) + { + this.dhKey = dhKey; + this.psKey = psKey; + this.isClient = isClient; + } + + /* (non-Javadoc) + * @see gnu.javax.net.ssl.provider.DelegatedTask#implRun() + */ + @Override protected void implRun() throws Throwable + { + keyAgreement.doPhase(dhKey, true); + byte[] dhSecret = keyAgreement.generateSecret(); + byte[] psSecret = null; + if (psKey != null) + psSecret = psKey.getEncoded(); + else + { + psSecret = new byte[8]; + engine.session().random().nextBytes(psSecret); + } + + preMasterSecret = new byte[dhSecret.length + psSecret.length + 4]; + preMasterSecret[0] = (byte) (dhSecret.length >>> 8); + preMasterSecret[1] = (byte) dhSecret.length; + System.arraycopy(dhSecret, 0, preMasterSecret, 2, dhSecret.length); + preMasterSecret[dhSecret.length + 2] = (byte) (psSecret.length >>> 8); + preMasterSecret[dhSecret.length + 3] = (byte) psSecret.length; + System.arraycopy(psSecret, 0, preMasterSecret, dhSecret.length + 4, + psSecret.length); + + generateMasterSecret(clientRandom, serverRandom, engine.session()); + byte[][] keys = generateKeys(clientRandom, serverRandom, engine.session()); + setupSecurityParameters(keys, isClient, engine, compression); + } + } +} \ No newline at end of file Modified: trunk/core/src/classpath/gnu/gnu/javax/net/ssl/provider/Alert.java =================================================================== --- trunk/core/src/classpath/gnu/gnu/javax/net/ssl/provider/Alert.java 2007-01-07 12:37:19 UTC (rev 3017) +++ trunk/core/src/classpath/gnu/gnu/javax/net/ssl/provider/Alert.java 2007-01-07 12:47:49 UTC (rev 3018) @@ -38,11 +38,11 @@ package gnu.javax.net.ssl.provider; -import java.io.EOFException; -import java.io.InputStream; -import java.io.IOException; -import java.io.OutputStream; +import java.io.PrintWriter; +import java.io.StringWriter; +import java.nio.ByteBuffer; + /** * An alert message in the SSL protocol. Alerts are sent both as warnings * which may allow execution to continue, or they may be fatal, which will @@ -57,206 +57,107 @@ * } * </pre> */ -final class Alert implements Constructed +public final class Alert implements Constructed { // Fields. // ------------------------------------------------------------------------- - /** The alert level enumerated. */ - private final Level level; + /** The underlying byte buffer. */ + private final ByteBuffer buffer; - /** The alert description enumerated. */ - private final Description description; - // Constructor. // ------------------------------------------------------------------------- - Alert(Level level, Description description) + public Alert (final ByteBuffer buffer) { - this.level = level; - this.description = description; + this.buffer = buffer; } - // Class method. - // ------------------------------------------------------------------------- - - static Alert read(InputStream in) throws IOException + public Alert (final Level level, final Description description) { - Level level = Level.read(in); - Description desc = Description.read(in); - return new Alert(level, desc); + level.getClass (); + description.getClass (); + ByteBuffer b = ByteBuffer.allocate (2); + b.put (0, (byte) level.getValue ()); + b.put (1, (byte) description.getValue ()); + this.buffer = b.asReadOnlyBuffer (); } - static Alert forName(String name) - { - if (name == null) + // Instance methods. + // ------------------------------------------------------------------------- + + public int length () { - return new Alert(Level.FATAL, Description.INTERNAL_ERROR); + return 2; } - Description desc = Description.INTERNAL_ERROR; - if (name.equals("close_notify")) + + byte[] getEncoded() { - desc = Description.CLOSE_NOTIFY; + byte[] buf = new byte[2]; + buffer.position (0); + buffer.get (buf); + return buf; } - else if (name.equals("unexpected_message")) + + public Level level() { - desc = Description.UNEXPECTED_MESSAGE; + return Level.forInteger (buffer.get (0) & 0xFF); } - else if (name.equals("bad_record_mac")) + + public Description description() { - desc = Description.BAD_RECORD_MAC; + return Description.forInteger (buffer.get (1) & 0xFF); } - else if (name.equals("DECRYPTION_FAILED")) + + public void setLevel (final Level level) { - desc = Description.DECRYPTION_FAILED; + buffer.put (0, (byte) level.getValue ()); } - else if (name.equals("record_overflow")) - { - desc = Description.RECORD_OVERFLOW; - } - else if (name.equals("decompression_failure")) - { - desc = Description.DECOMPRESSION_FAILURE; - } - else if (name.equals("handshake_failure")) - { - desc = Description.HANDSHAKE_FAILURE; - } - else if (name.equals("no_certificate")) - { - desc = Description.NO_CERTIFICATE; - } - else if (name.equals("bad_certificate")) - { - desc = Description.BAD_CERTIFICATE; - } - else if (name.equals("unsupported_certificate")) - { - desc = Description.UNSUPPORTED_CERTIFICATE; - } - else if (name.equals("certificate_revoked")) - { - desc = Description.CERTIFICATE_REVOKED; - } - else if (name.equals("certificate_expired")) - { - desc = Description.CERTIFICATE_EXPIRED; - } - else if (name.equals("certificate_unknown")) - { - desc = Description.CERTIFICATE_UNKNOWN; - } - else if (name.equals("illegal_parameter")) - { - desc = Description.ILLEGAL_PARAMETER; - } - else if (name.equals("unknown_ca")) - { - desc = Description.UNKNOWN_CA; - } - else if (name.equals("access_denied")) - { - desc = Description.ACCESS_DENIED; - } - else if (name.equals("decode_error")) - { - desc = Description.DECODE_ERROR; - } - else if (name.equals("decrypt_error")) - { - desc = Description.DECRYPT_ERROR; - } - else if (name.equals("export_restriction")) - { - desc = Description.EXPORT_RESTRICTION; - } - else if (name.equals("protocol_version")) - { - desc = Description.PROTOCOL_VERSION; - } - else if (name.equals("insufficient_security")) - { - desc = Description.INSUFFICIENT_SECURITY; - } - else if (name.equals("internal_error")) - { - desc = Description.INTERNAL_ERROR; - } - else if (name.equals("user_canceled")) - { - desc = Description.USER_CANCELED; - } - else if (name.equals("no_renegotiation")) - { - desc = Description.NO_RENEGOTIATION; - } - else if (name.equals("unsupported_extension")) - { - desc = Description.UNSUPPORTED_EXTENSION; - } - else if (name.equals("certificate_unobtainable")) - { - desc = Description.CERTIFICATE_UNOBTAINABLE; - } - else if (name.equals("unrecognized_name")) - { - desc = Description.UNRECOGNIZED_NAME; - } - else if (name.equals("bad_certificate_status_response")) - { - desc = Description.BAD_CERTIFICATE_STATUS_RESPONSE; - } - else if (name.equals("bad_certificate_hash_value")) - { - desc = Description.BAD_CERTIFICATE_HASH_VALUE; - } - else if (name.equals("unknown_srp_username")) - { - desc = Description.UNKNOWN_SRP_USERNAME; - } - else if (name.equals("missing_srp_username")) - { - desc = Description.MISSING_SRP_USERNAME; - } - return new Alert(Level.FATAL, desc); - } - // Instance methods. - // ------------------------------------------------------------------------- - - public void write(OutputStream out) throws IOException + public void setDescription (final Description description) { - out.write((byte) level.getValue()); - out.write((byte) description.getValue()); + buffer.put (1, (byte) description.getValue ()); } - byte[] getEncoded() + public boolean equals (Object o) { - return new byte[] { (byte) level.getValue(), - (byte) description.getValue() }; + if (!(o instanceof Alert)) + return false; + Alert that = (Alert) o; + return that.buffer.position (0).equals (buffer.position (0)); } - Level getLevel() + public int hashCode () { - return level; + return buffer.getShort (0) & 0xFFFF; } - Description getDescription() + public String toString() { - return description; + return toString (null); } - public String toString() + public String toString (final String prefix) { - String nl = System.getProperty("line.separator"); - return "struct {" + nl + - " level = " + level + ";" + nl + - " description = " + description + ";" + nl + - "} Alert;" + nl; + StringWriter str = new StringWriter (); + PrintWriter out = new PrintWriter (str); + if (prefix != null) out.print (prefix); + out.println ("struct {"); + if (prefix != null) out.print (prefix); + out.print (" level: "); + out.print (level ()); + out.println (";"); + if (prefix != null) out.print (prefix); + out.print (" description: "); + out.print (description ()); + out.println (";"); + if (prefix != null) out.print (prefix); + out.print ("} Alert;"); + return str.toString (); } - // Inner classes. + // Enumerations. // ------------------------------------------------------------------------- /** @@ -266,129 +167,88 @@ * enum { warning(1), fatal(2), (255) } AlertLevel; * </pre> */ - static final class Level implements Enumerated + public static enum Level { - // Constants and fields. - // ----------------------------------------------------------------------- + WARNING (1), FATAL (2); - static final Level WARNING = new Level(1), FATAL = new Level(2); - private final int value; - // Constructor. - // ----------------------------------------------------------------------- - private Level(int value) { this.value = value; } - // Class method. - // ----------------------------------------------------------------------- - - static Level read(InputStream in) throws IOException - { - int i = in.read(); - if (i == -1) + public static Level forInteger (final int value) { - throw new EOFException("unexpected end of stream"); - } - switch (i & 0xFF) + switch (value & 0xFF) { case 1: return WARNING; case 2: return FATAL; - default: return new Level(i); - } + default: throw new IllegalArgumentException ("invalid alert level: " + value); } - - // Instance methods. - // ----------------------------------------------------------------------- - - public byte[] getEncoded() - { - return new byte[] { (byte) value }; } public int getValue() { return value; } - - public String toString() - { - switch (value) - { - case 1: return "warning"; - case 2: return "fatal"; - default: return "unknown(" + value + ")"; - } - } } /** * The description enumeration. */ - static final class Description implements Enumerated + public static enum Description { + CLOSE_NOTIFY ( 0), + UNEXPECTED_MESSAGE ( 10), + BAD_RECORD_MAC ( 20), + DECRYPTION_FAILED ( 21), + RECORD_OVERFLOW ( 22), + DECOMPRESSION_FAILURE ( 30), + HANDSHAKE_FAILURE ( 40), + NO_CERTIFICATE ( 41), + BAD_CERTIFICATE ( 42), + UNSUPPORTED_CERTIFICATE ( 43), + CERTIFICATE_REVOKED ( 44), + CERTIFICATE_EXPIRED ( 45), + CERTIFICATE_UNKNOWN ( 46), + ILLEGAL_PARAMETER ( 47), + UNKNOWN_CA ( 48), + ACCESS_DENIED ( 49), + DECODE_ERROR ( 50), + DECRYPT_ERROR ( 51), + EXPORT_RESTRICTION ( 60), + PROTOCOL_VERSION ( 70), + INSUFFICIENT_SECURITY ( 71), + INTERNAL_ERROR ( 80), + USER_CANCELED ( 90), + NO_RENEGOTIATION (100), + UNSUPPORTED_EXTENSION (110), + CERTIFICATE_UNOBTAINABLE (111), + UNRECOGNIZED_NAME (112), + BAD_CERTIFICATE_STATUS_RESPONSE (113), + BAD_CERTIFICATE_HASH_VALUE (114), + UNKNOWN_SRP_USERNAME (120), + MISSING_SRP_USERNAME (121); - // Constants and fields. - // ----------------------------------------------------------------------- - - static final Description - CLOSE_NOTIFY = new Description( 0), - UNEXPECTED_MESSAGE = new Description( 10), - BAD_RECORD_MAC = new Description( 20), - DECRYPTION_FAILED = new Description( 21), - RECORD_OVERFLOW = new Description( 22), - DECOMPRESSION_FAILURE = new Description( 30), - HANDSHAKE_FAILURE = new Description( 40), - NO_CERTIFICATE = new Description( 41), - BAD_CERTIFICATE = new Description( 42), - UNSUPPORTED_CERTIFICATE = new Description( 43), - CERTIFICATE_REVOKED = new Description( 44), - CERTIFICATE_EXPIRED = new Description( 45), - CERTIFICATE_UNKNOWN = new Description( 46), - ILLEGAL_PARAMETER = new Description( 47), - UNKNOWN_CA = new Description( 48), - ACCESS_DENIED = new Description( 49), - DECODE_ERROR = new Description( 50), - DECRYPT_ERROR = new Description( 51), - EXPORT_RESTRICTION = new Description( 60), - PROTOCOL_VERSION = new Description( 70), - INSUFFICIENT_SECURITY = new Description( 71), - INTERNAL_ERROR = new Description( 80), - USER_CANCELED = new Description( 90), - NO_RENEGOTIATION = new Description(100), - UNSUPPORTED_EXTENSION = new Description(110), - CERTIFICATE_UNOBTAINABLE = new Description(111), - UNRECOGNIZED_NAME = new Description(112), - BAD_CERTIFICATE_STATUS_RESPONSE = new Description(113), - BAD_CERTIFICATE_HASH_VALUE = new Description(114), - UNKNOWN_SRP_USERNAME = new Description(120), - MISSING_SRP_USERNAME = new Description(121); - private final int value; - // Constructor. - // ----------------------------------------------------------------------- - private Description(int value) { this.value = value; } - // Class method. - // ----------------------------------------------------------------------- - - static Description read(InputStream in) throws IOException - { - int i = in.read(); - if (i == -1) + /** + * Return an alert description object based on the specified integer + * value. + * + * @param value The raw description value. + * @return The appropriate description object. + */ + public static Description forInteger (final int value) { - throw new EOFException("unexpected end of input stream"); - } - switch (i) + switch (value & 0xFF) ... [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 size of the pool. @@ -471,14 +480,32 @@ { String ttl = SystemProperties.getProperty("classpath.net.http.keepAliveTTL"); - connectionTTL = (ttl != null && ttl.length() > 0) ? - 1000 * Math.max(1, Integer.parseInt(ttl)) : 10000; + connectionTTL = 10000; + if (ttl != null && ttl.length() > 0) + try + { + int v = 1000 * Integer.parseInt(ttl); + if (v >= 0) + connectionTTL = v; + } + catch (NumberFormatException _) + { + // Ignore. + } String mc = SystemProperties.getProperty("http.maxConnections"); - maxConnections = (mc != null && mc.length() > 0) ? - Math.max(Integer.parseInt(mc), 1) : 5; - if (maxConnections < 1) - maxConnections = 1; + maxConnections = 5; + if (mc != null && mc.length() > 0) + try + { + int v = Integer.parseInt(mc); + if (v > 0) + maxConnections = v; + } + catch (NumberFormatException _) + { + // Ignore. + } HTTPConnection c = null; @@ -490,12 +517,23 @@ { c = cc; it.remove(); + // Update the timeout. + if (c.socket != null) + try + { + c.socket.setSoTimeout(timeout); + } + catch (SocketException _) + { + // Ignore. + } break; } } if (c == null) { - c = new HTTPConnection(host, port, secure, connectionTimeout, timeout); + c = new HTTPConnection(host, port, secure, + connectionTimeout, timeout); c.setPool(this); } return c; @@ -821,7 +859,7 @@ { return 0; } - return((Integer) nonceCounts.get(nonce)).intValue(); + return nonceCounts.get(nonce).intValue(); } /** @@ -832,7 +870,7 @@ int current = getNonceCount(nonce); if (nonceCounts == null) { - nonceCounts = new HashMap(); + nonceCounts = new HashMap<String, Integer>(); } nonceCounts.put(nonce, new Integer(current + 1)); } Modified: trunk/core/src/classpath/gnu/gnu/java/net/protocol/http/HTTPURLConnection.java =================================================================== --- trunk/core/src/classpath/gnu/gnu/java/net/protocol/http/HTTPURLConnection.java 2007-01-07 12:36:12 UTC (rev 3016) +++ trunk/core/src/classpath/gnu/gnu/java/net/protocol/http/HTTPURLConnection.java 2007-01-07 12:37:19 UTC (rev 3017) @@ -50,11 +50,11 @@ import java.security.cert.Certificate; import java.util.Collections; import java.util.Date; +import java.util.List; import java.util.Map; import javax.net.ssl.HandshakeCompletedEvent; import javax.net.ssl.HandshakeCompletedListener; -import javax.net.ssl.HostnameVerifier; import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.SSLPeerUnverifiedException; import javax.net.ssl.SSLSocketFactory; @@ -75,7 +75,7 @@ // These are package private for use in anonymous inner classes. String proxyHostname; - int proxyPort; + int proxyPort = -1; String agent; boolean keepAlive; @@ -99,18 +99,21 @@ { super(url); requestHeaders = new Headers(); - proxyHostname = SystemProperties.getProperty("http.proxyHost"); - if (proxyHostname != null && proxyHostname.length() > 0) + String proxy = SystemProperties.getProperty("http.proxyHost"); + if (proxy != null && proxy.length() > 0) { String port = SystemProperties.getProperty("http.proxyPort"); if (port != null && port.length() > 0) { + try + { proxyPort = Integer.parseInt(port); + proxyHostname = proxy; } - else + catch (NumberFormatException _) { - proxyHostname = null; - proxyPort = -1; + // Ignore. + } } } agent = SystemProperties.getProperty("http.agent"); @@ -149,6 +152,14 @@ final Credentials creds = (username == null) ? null : new Credentials (username, password); + if ("POST".equals(method)) + { + String contentType = requestHeaders.getValue("Content-Type"); + if (null == contentType) + requestHeaders.addValue("Content-Type", + "application/x-www-form-urlencoded"); + } + boolean retry; do { @@ -159,7 +170,8 @@ if (secure) { SSLSocketFactory factory = getSSLSocketFactory(); - HostnameVerifier verifier = getHostnameVerifier(); + // FIXME: use the verifier + // HostnameVerifier verifier = getHostnameVerifier(); if (factory != null) { connection.setSSLSocketFactory(factory); @@ -414,12 +426,12 @@ return requestHeaders.getValue(key); } - public Map getRequestProperties() + public Map<String, List<String>> getRequestProperties() { if (connected) throw new IllegalStateException("Already connected"); - Map m = requestHeaders.getAsMap(); + Map<String, List<String>> m = requestHeaders.getAsMap(); return Collections.unmodifiableMap(m); } @@ -495,7 +507,7 @@ return errorSink; } - public Map getHeaderFields() + public Map<String,List<String>> getHeaderFields() { if (!connected) { @@ -508,7 +520,7 @@ return null; } } - Map m = response.getHeaders().getAsMap(); + Map<String,List<String>> m = response.getHeaders().getAsMap(); m.put(null, Collections.singletonList(getStatusLine(response))); return Collections.unmodifiableMap(m); } @@ -654,13 +666,13 @@ } /** - * Set the connection timeout speed, in milliseconds, or zero if the timeout + * Set the read timeout, in milliseconds, or zero if the timeout * is to be considered infinite. * * Overloaded. * */ - public void setConnectTimeout(int timeout) + public void setReadTimeout(int timeout) throws IllegalArgumentException { super.setConnectTimeout( timeout ); @@ -668,9 +680,9 @@ return; try { - connection.getSocket().setSoTimeout( timeout ); + connection.getSocket().setSoTimeout(timeout); } - catch(IOException se) + catch (IOException se) { // Ignore socket exceptions. } Modified: trunk/core/src/classpath/gnu/gnu/java/net/protocol/http/Headers.java =================================================================== --- trunk/core/src/classpath/gnu/gnu/java/net/protocol/http/Headers.java 2007-01-07 12:36:12 UTC (rev 3016) +++ trunk/core/src/classpath/gnu/gnu/java/net/protocol/http/Headers.java 2007-01-07 12:37:19 UTC (rev 3017) @@ -42,6 +42,7 @@ import java.io.IOException; import java.io.InputStream; +import java.lang.Iterable; import java.text.DateFormat; import java.text.ParseException; import java.util.ArrayList; @@ -49,6 +50,7 @@ import java.util.Date; import java.util.Iterator; import java.util.LinkedHashMap; +import java.util.List; import java.util.Map; /** @@ -60,12 +62,13 @@ * @author Chris Burdess (do...@gn...) * @author David Daney (dd...@av...) */ -class Headers +class Headers implements Iterable<Headers.HeaderElement> { /** * A list of HeaderElements */ - private final ArrayList headers = new ArrayList(); + private final ArrayList<HeaderElement> headers + = new ArrayList<HeaderElement>(); /** * The HTTP dateformat used to parse date header fields. @@ -102,7 +105,7 @@ * * @return the Iterator. */ - Iterator iterator() + public Iterator<HeaderElement> iterator() { return headers.iterator(); } @@ -118,7 +121,7 @@ { for (int i = headers.size() - 1; i >= 0; i--) { - HeaderElement e = (HeaderElement)headers.get(i); + HeaderElement e = headers.get(i); if (e.name.equalsIgnoreCase(header)) { return e.value; @@ -219,7 +222,7 @@ { for (int i = headers.size() - 1; i >= 0; i--) { - HeaderElement e = (HeaderElement)headers.get(i); + HeaderElement e = headers.get(i); if (e.name.equalsIgnoreCase(name)) { e.value = value; @@ -240,9 +243,9 @@ */ public void putAll(Headers o) { - for (Iterator it = o.iterator(); it.hasNext(); ) + for (Iterator<HeaderElement> it = o.iterator(); it.hasNext(); ) { - HeaderElement e = (HeaderElement)it.next(); + HeaderElement e = it.next(); remove(e.name); addValue(e.name, e.value); } @@ -256,9 +259,9 @@ */ public void remove(String name) { - for (Iterator it = headers.iterator(); it.hasNext(); ) + for (Iterator<HeaderElement> it = headers.iterator(); it.hasNext(); ) { - HeaderElement e = (HeaderElement)it.next(); + HeaderElement e = it.next(); if (e.name.equalsIgnoreCase(name)) it.remove(); } @@ -358,26 +361,26 @@ * * @return a Map containing all the headers. */ - public Map getAsMap() + public Map<String,List<String>> getAsMap() { - LinkedHashMap m = new LinkedHashMap(); - for (Iterator it = headers.iterator(); it.hasNext(); ) + LinkedHashMap<String,List<String>> m = new LinkedHashMap<String,List<String>>(); + for (Iterator<HeaderElement> it = headers.iterator(); it.hasNext(); ) { - HeaderElement e = (HeaderElement)it.next(); - ArrayList l = (ArrayList)m.get(e.name); + HeaderElement e = it.next(); + ArrayList<String> l = (ArrayList<String>)m.get(e.name); if (l == null) { - l = new ArrayList(1); + l = new ArrayList<String>(1); l.add(e.value); m.put(e.name, l); } else l.add(0, e.value); } - for (Iterator it = m.entrySet().iterator(); it.hasNext(); ) + for (Iterator<Map.Entry<String,List<String>>> it = m.entrySet().iterator(); it.hasNext(); ) { - Map.Entry me = (Map.Entry)it.next(); - ArrayList l = (ArrayList)me.getValue(); + Map.Entry<String,List<String>> me = it.next(); + List<String> l = me.getValue(); me.setValue(Collections.unmodifiableList(l)); } return m; @@ -397,7 +400,7 @@ if (i >= headers.size() || i < 0) return null; - return ((HeaderElement)headers.get(i)).name; + return headers.get(i).name; } /** @@ -414,8 +417,6 @@ if (i >= headers.size() || i < 0) return null; - return ((HeaderElement)headers.get(i)).value; + return headers.get(i).value; } - } - Modified: trunk/core/src/classpath/gnu/gnu/java/net/protocol/http/Request.java =================================================================== --- trunk/core/src/classpath/gnu/gnu/java/net/protocol/http/Request.java 2007-01-07 12:36:12 UTC (rev 3016) +++ trunk/core/src/classpath/gnu/gnu/java/net/protocol/http/Request.java 2007-01-07 12:37:19 UTC (rev 3017) @@ -96,7 +96,7 @@ /** * Map of response header handlers. */ - protected Map responseHeaderHandlers; + protected Map<String, ResponseHeaderHandler> responseHeaderHandlers; /** * The authenticator. @@ -121,7 +121,7 @@ this.method = method; this.path = path; requestHeaders = new Headers(); - responseHeaderHandlers = new HashMap(); + responseHeaderHandlers = new HashMap<String, ResponseHeaderHandler>(); } /** @@ -302,9 +302,8 @@ String line = method + ' ' + requestUri + ' ' + version + CRLF; out.write(line.getBytes(US_ASCII)); // Request headers - for (Iterator i = requestHeaders.iterator(); i.hasNext(); ) + for (Headers.HeaderElement elt : requestHeaders) { - Headers.HeaderElement elt = (Headers.HeaderElement)i.next(); line = elt.name + HEADER_SEP + elt.value + CRLF; out.write(line.getBytes(US_ASCII)); } @@ -439,9 +438,8 @@ void notifyHeaderHandlers(Headers headers) { - for (Iterator i = headers.iterator(); i.hasNext(); ) + for (Headers.HeaderElement entry : headers) { - Headers.HeaderElement entry = (Headers.HeaderElement) i.next(); // Handle Set-Cookie if ("Set-Cookie".equalsIgnoreCase(entry.name)) handleSetCookie(entry.value); @@ -461,7 +459,6 @@ throws IOException { long contentLength = -1; - Headers trailer = null; // Persistent connections are the default in HTTP/1.1 boolean doClose = "close".equalsIgnoreCase(getHeader("Connection")) || Modified: trunk/core/src/classpath/gnu/gnu/java/net/protocol/http/SimpleCookieManager.java =================================================================== --- trunk/core/src/classpath/gnu/gnu/java/net/protocol/http/SimpleCookieManager.java 2007-01-07 12:36:12 UTC (rev 3016) +++ trunk/core/src/classpath/gnu/gnu/java/net/protocol/http/SimpleCookieManager.java 2007-01-07 12:37:19 UTC (rev 3017) @@ -1,5 +1,5 @@ /* CookieManager.java -- - Copyright (C) 2004 Free Software Foundation, Inc. + Copyright (C) 2004, 2006 Free Software Foundation, Inc. This file is part of GNU Classpath. @@ -42,7 +42,6 @@ import java.util.Date; import java.util.HashMap; import java.util.Iterator; -import java.util.List; import java.util.Map; /** @@ -59,23 +58,23 @@ * The cookie cache. * This is a dictionary mapping domains to maps of cookies by name. */ - protected Map cookies; + protected Map<String, Map<String, Cookie>> cookies; /** * Constructor. */ public SimpleCookieManager() { - cookies = new HashMap(); + cookies = new HashMap<String, Map<String, Cookie>>(); } public void setCookie(Cookie cookie) { String domain = cookie.getDomain(); - Map map =(Map) cookies.get(domain); + Map<String, Cookie> map = cookies.get(domain); if (map == null) { - map = new HashMap(); + map = new HashMap<String, Cookie>(); cookies.put(domain, map); } String name = cookie.getName(); @@ -84,7 +83,7 @@ public Cookie[] getCookies(String host, boolean secure, String path) { - List matches = new ArrayList(); + ArrayList<Cookie> matches = new ArrayList<Cookie>(); Date now = new Date(); if (Character.isLetter(host.charAt(0))) { @@ -102,17 +101,16 @@ return ret; } - private void addCookies(List matches, String domain, boolean secure, - String path, Date now) + private void addCookies(ArrayList<Cookie> matches, String domain, + boolean secure, String path, Date now) { - Map map = (Map) cookies.get(domain); + Map<String, Cookie> map = cookies.get(domain); if (map != null) { - List expired = new ArrayList(); - for (Iterator i = map.entrySet().iterator(); i.hasNext(); ) + ArrayList<String> expired = new ArrayList<String>(); + for (Map.Entry<String, Cookie> entry : map.entrySet()) { - Map.Entry entry = (Map.Entry) i.next(); - Cookie cookie = (Cookie) entry.getValue(); + Cookie cookie = entry.getValue(); Date expires = cookie.getExpiryDate(); if (expires != null && expires.before(now)) { @@ -129,7 +127,7 @@ } } // Good housekeeping - for (Iterator i = expired.iterator(); i.hasNext(); ) + for (Iterator<String> i = expired.iterator(); i.hasNext(); ) { map.remove(i.next()); } Modified: trunk/core/src/classpath/gnu/gnu/java/net/protocol/jar/Connection.java =================================================================== --- trunk/core/src/classpath/gnu/gnu/java/net/protocol/jar/Connection.java 2007-01-07 12:36:12 UTC (rev 3016) +++ trunk/core/src/classpath/gnu/gnu/java/net/protocol/jar/Connection.java 2007-01-07 12:37:19 UTC (rev 3017) @@ -76,7 +76,8 @@ public static class JarFileCache { - private static Hashtable cache = new Hashtable(); + private static Hashtable<URL, JarFile> cache + = new Hashtable<URL, JarFile>(); private static final int READBUFSIZE = 4*1024; public static synchronized JarFile get (URL url, boolean useCaches) @@ -85,7 +86,7 @@ JarFile jf; if (useCaches) { - jf = (JarFile) cache.get (url); + jf = cache.get (url); if (jf != null) return jf; } Modified: trunk/core/src/classpath/gnu/gnu/java/net/protocol/jar/Handler.java =================================================================== --- trunk/core/src/classpath/gnu/gnu/java/net/protocol/jar/Handler.java 2007-01-07 12:36:12 UTC (rev 3016) +++ trunk/core/src/classpath/gnu/gnu/java/net/protocol/jar/Handler.java 2007-01-07 12:37:19 UTC (rev 3017) @@ -1,5 +1,5 @@ /* gnu.java.net.protocol.jar.Handler - jar protocol handler for java.net - Copyright (C) 1999, 2002, 2003, 2005 Free Software Foundation, Inc. + Copyright (C) 1999, 2002, 2003, 2005, 2006 Free Software Foundation, Inc. This file is part of GNU Classpath. @@ -45,6 +45,9 @@ import java.net.URL; import java.net.URLConnection; import java.net.URLStreamHandler; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.StringTokenizer; /** * @author Kresten Krab Thorup (kr...@gn...) @@ -114,7 +117,7 @@ file = file.substring(0, idx + 1) + url_string; } - setURL (url, "jar", url.getHost(), url.getPort(), file, null); + setURL (url, "jar", url.getHost(), url.getPort(), flat(file), null); return; } @@ -149,6 +152,45 @@ } /** + * Makes the given jar url string 'flat' by removing any . and .. from + * jar file path because ZipFile entries can only handle flat paths. + * Inside jar files '/' is always the path separator. + */ + private static String flat(String url_string) + { + int jar_stop = url_string.indexOf("!/"); + String jar_path = url_string.substring(jar_stop + 1, url_string.length()); + + if (jar_path.indexOf("/.") < 0) + return url_string; + + ArrayList<String> tokens = new ArrayList<String>(); + StringTokenizer st = new StringTokenizer(jar_path, "/"); + while (st.hasMoreTokens()) + { + String token = st.nextToken(); + if (token.equals(".")) + continue; + else if (token.equals("..")) + { + if (! tokens.isEmpty()) + tokens.remove(tokens.size() - 1); + } + else + tokens.add(token); + } + + StringBuffer path = new StringBuffer(url_string.length()); + path.append(url_string.substring(0, jar_stop + 1)); + + Iterator<String> it = tokens.iterator(); + while (it.hasNext()) + path.append('/').append(it.next()); + + return path.toString(); + } + + /** * This method converts a Jar URL object into a String. * * @param url The URL object to convert Added: trunk/core/src/classpath/gnu/gnu/java/security/Requires.java =================================================================== --- trunk/core/src/classpath/gnu/gnu/java/security/Requires.java (rev 0) +++ trunk/core/src/classpath/gnu/gnu/java/security/Requires.java 2007-01-07 12:37:19 UTC (rev 3017) @@ -0,0 +1,59 @@ +/* Requires.java -- mark methods as requiring permission. + Copyright (C) 2006 Free Software Foundation, Inc. + +This file is a 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 of the License, 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; if not, write to the Free Software +Foundation, Inc., 51 Franklin St, 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.security; + +import java.lang.annotation.Documented; +import java.lang.annotation.Retention; +import java.lang.annotation.Target; +import static java.lang.annotation.ElementType.METHOD; +import static java.lang.annotation.RetentionPolicy.CLASS; +import java.security.Permission; + +/** + * + * + * @author Casey Marshall (cs...@gn...) + */ +@Documented @Retention(CLASS) @Target(METHOD) +public @interface Requires +{ + Class<? extends Permission> permissionClass(); + String target(); + String action(); +} Modified: trunk/core/src/classpath/gnu/gnu/java/security/action/GetPropertyAction.java =================================================================== --- trunk/core/src/classpath/gnu/gnu/java/security/action/GetPropertyAction.java 2007-01-07 12:36:12 UTC (rev 3016) +++ trunk/core/src/classpath/gnu/gnu/java/security/action/GetPropertyAction.java 2007-01-07 12:37:19 UTC (rev 3017) @@ -49,7 +49,7 @@ * String port = AccessController.doPrivileged(action); * </code> */ -public class GetPropertyAction implements PrivilegedAction +public class GetPropertyAction implements PrivilegedAction<String> { String name; String value = null; @@ -68,7 +68,7 @@ setParameters(propName, defaultValue); } - public Object run() + public String run() { return System.getProperty(name, value); } Modified: trunk/core/src/classpath/gnu/gnu/java/security/action/GetSecurityPropertyAction.java =================================================================== --- trunk/core/src/classpath/gnu/gnu/java/security/action/GetSecurityPropertyAction.java 2007-01-07 12:36:12 UTC (rev 3016) +++ trunk/core/src/classpath/gnu/gnu/java/security/action/GetSecurityPropertyAction.java 2007-01-07 12:37:19 UTC (rev 3017) @@ -50,7 +50,7 @@ * String passwd = AccessController.doPrivileged(action); * </code> */ -public class GetSecurityPropertyAction implements PrivilegedAction +public class GetSecurityPropertyAction implements PrivilegedAction<String> { private String name; private String value; @@ -83,7 +83,7 @@ return this; } - public Object run() + public String run() { String val = Security.getProperty(name); if (val == null) Added: trunk/core/src/classpath/gnu/gnu/java/security/util/ByteBufferOutputStream.java =================================================================== --- trunk/core/src/classpath/gnu/gnu/java/security/util/ByteBufferOutputStream.java (rev 0) +++ trunk/core/src/classpath/gnu/gnu/java/security/util/ByteBufferOutputStream.java 2007-01-07 12:37:19 UTC (rev 3017) @@ -0,0 +1,118 @@ +/* ByteBufferOutputStream.java -- output stream with a growable underlying + byte buffer. + Copyright (C) 2006 Free Software Foundation, Inc. + +This file is a 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 of the License, 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; if not, write to the Free Software +Foundation, Inc., 51 Franklin St, 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.security.util; + +import java.io.IOException; +import java.io.OutputStream; + +import java.nio.ByteBuffer; + +/** + * An output stream that writes bytes to a ByteBuffer, which will be resized + * if more space is needed. + * + * @author Casey Marshall (cs...@gn...) + */ +public class ByteBufferOutputStream extends OutputStream +{ + private ByteBuffer buffer; + + public ByteBufferOutputStream() + { + this(256); + } + + public ByteBufferOutputStream(int initialCapacity) + { + buffer = ByteBuffer.allocate(initialCapacity); + } + + /* (non-Javadoc) + * @see java.io.OutputStream#write(int) + */ + public @Override synchronized void write(int b) throws IOException + { + if (!buffer.hasRemaining()) + growBuffer(); + buffer.put((byte) b); + } + + public @Override synchronized void write(byte[] b, int offset, int length) + { + if (buffer.remaining() < length) + growBuffer(); + buffer.put(b, offset, length); + } + + public @Override void write(byte[] b) + { + write(b, 0, b.length); + } + + /** + * Get the current state of the buffer. The returned buffer will have + * its position set to zero, its capacity set to the current limit, + * and its limit set to its capacity. + * + * @return The buffer. + */ + public ByteBuffer buffer() + { + return ((ByteBuffer) buffer.duplicate().flip()).slice(); + } + + public String toString() + { + return super.toString() + " [ buffer: " + buffer + " ]"; + } + + private void growBuffer() + { + int newCapacity = buffer.capacity(); + if (newCapacity < 16384) // If the buffer isn't huge yet, double its size + newCapacity = newCapacity << 1; + else // Otherwize, increment by a bit. + newCapacity += 4096; + ByteBuffer newBuffer = ByteBuffer.allocate(newCapacity); + buffer.flip(); + newBuffer.put(buffer); + buffer = newBuffer; + } +} Added: trunk/core/src/classpath/gnu/gnu/java/security/x509/ext/GeneralName.java =================================================================== --- trunk/core/src/classpath/gnu/gnu/java/security/x509/ext/GeneralName.java (rev 0) +++ trunk/core/src/classpath/gnu/gnu/java/security/x509/ext/GeneralName.java 2007-01-07 12:37:19 UTC (rev 3017) @@ -0,0 +1,232 @@ +/* GeneralName.java -- a GeneralName. + Copyright (C) 2006 Free Software Foundation, Inc. + +This file is a 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 of the License, 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; if not, write to the Free Software +Foundation, Inc., 51 Franklin St, 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.security.x509.ext; + +import gnu.java.security.der.DER; +import gnu.java.security.der.DERReader; +import gnu.java.security.der.DERValue; +import gnu.java.security.x509.Util; + +import java.io.IOException; +import java.util.Arrays; + +/**... [truncated message content] |
From: <ls...@us...> - 2007-01-07 12:36:14
|
Revision: 3016 http://jnode.svn.sourceforge.net/jnode/?rev=3016&view=rev Author: lsantha Date: 2007-01-07 04:36:12 -0800 (Sun, 07 Jan 2007) Log Message: ----------- Classpath patches. Modified Paths: -------------- trunk/core/src/classpath/gnu/gnu/java/awt/java2d/AbstractGraphics2D.java trunk/core/src/classpath/gnu/gnu/java/awt/java2d/PolyEdge.java trunk/core/src/classpath/gnu/gnu/java/awt/java2d/QuadSegment.java trunk/core/src/classpath/gnu/gnu/java/awt/java2d/TexturePaintContext.java Added Paths: ----------- trunk/core/src/classpath/gnu/gnu/java/awt/java2d/ActiveEdges.java trunk/core/src/classpath/gnu/gnu/java/awt/java2d/Scanline.java trunk/core/src/classpath/gnu/gnu/java/awt/java2d/ScanlineConverter.java Modified: trunk/core/src/classpath/gnu/gnu/java/awt/java2d/AbstractGraphics2D.java =================================================================== --- trunk/core/src/classpath/gnu/gnu/java/awt/java2d/AbstractGraphics2D.java 2007-01-07 12:35:22 UTC (rev 3015) +++ trunk/core/src/classpath/gnu/gnu/java/awt/java2d/AbstractGraphics2D.java 2007-01-07 12:36:12 UTC (rev 3016) @@ -67,8 +67,6 @@ import java.awt.geom.GeneralPath; import java.awt.geom.Line2D; import java.awt.geom.NoninvertibleTransformException; -import java.awt.geom.PathIterator; -import java.awt.geom.Rectangle2D; import java.awt.geom.RoundRectangle2D; import java.awt.image.BufferedImage; import java.awt.image.BufferedImageOp; @@ -82,7 +80,6 @@ import java.text.AttributedCharacterIterator; import java.util.ArrayList; import java.util.HashMap; -import java.util.Iterator; import java.util.Map; /** @@ -100,6 +97,20 @@ * {@link #updateRaster(Raster, int, int, int, int)} method, which always gets * called after a chunk of data got painted into the raster. * </p> + * <p>Alternativly the backend can provide a method for filling Shapes by + * overriding the protected method fillShape(). This can be accomplished + * by a polygon filling function of the backend. Keep in mind though that + * Shapes can be quite complex (i.e. non-convex and containing holes, etc) + * which is not supported by all polygon fillers. Also it must be noted + * that fillShape() is expected to handle painting and compositing as well as + * clipping and transformation. If your backend can't support this natively, + * then you can fallback to the implementation in this class. You'll need + * to provide a writable Raster then, see above.</p> + * <p>Another alternative is to implement fillScanline() which only requires + * the backend to be able to draw horizontal lines in device space, + * which is usually very cheap. + * The implementation should still handle painting and compositing, + * but no more clipping and transformation is required by the backend.</p> * <p>The backend is free to provide implementations for the various raw* * methods for optimized AWT 1.1 style painting of some primitives. This should * accelerate painting of Swing greatly. When doing so, the backend must also @@ -126,6 +137,9 @@ * in plain Java because they involve lots of shuffling around with large * arrays. In fact, you really would want to let the graphics card to the * work, they are made for this.</li> + * <li>Provide an accelerated implementation for fillShape(). For instance, + * OpenGL can fill shapes very efficiently. There are some considerations + * to be made though, see above for details.</li> * </ol> * </p> * @@ -137,6 +151,11 @@ { /** + * The default font to use on the graphics object. + */ + private static final Font FONT = new Font("SansSerif", Font.PLAIN, 12); + + /** * Accuracy of the sampling in the anti-aliasing shape filler. * Lower values give more speed, while higher values give more quality. * It is advisable to choose powers of two. @@ -144,6 +163,19 @@ private static final int AA_SAMPLING = 8; /** + * Caches certain shapes to avoid massive creation of such Shapes in + * the various draw* and fill* methods. + */ + private static final ThreadLocal shapeCache = + new ThreadLocal(); + + /** + * The scanline converters by thread. + */ + private static final ThreadLocal scanlineConverters = + new ThreadLocal(); + + /** * The transformation for this Graphics2D instance */ protected AffineTransform transform; @@ -154,6 +186,11 @@ private Paint paint; /** + * The paint context during rendering. + */ + private PaintContext paintContext; + + /** * The background. */ private Color background; @@ -184,11 +221,6 @@ private RenderingHints renderingHints; /** - * The paint raster. - */ - private Raster paintRaster; - - /** * The raster of the destination surface. This is where the painting is * performed. */ @@ -219,8 +251,19 @@ * AbstractGraphics2D object and will be the most commonly used setting * in Swing rendering and should therefore be optimized as much as possible. */ - private boolean isOptimized; + private boolean isOptimized = true; + private static final BasicStroke STANDARD_STROKE = new BasicStroke(); + + private static final HashMap STANDARD_HINTS; + static { + HashMap hints = new HashMap(); + hints.put(RenderingHints.KEY_TEXT_ANTIALIASING, + RenderingHints.VALUE_TEXT_ANTIALIAS_DEFAULT); + hints.put(RenderingHints.KEY_ANTIALIASING, + RenderingHints.VALUE_ANTIALIAS_DEFAULT); + STANDARD_HINTS = hints; + } /** * Creates a new AbstractGraphics2D instance. */ @@ -229,13 +272,8 @@ transform = new AffineTransform(); background = Color.WHITE; composite = AlphaComposite.SrcOver; - stroke = new BasicStroke(); - HashMap hints = new HashMap(); - hints.put(RenderingHints.KEY_TEXT_ANTIALIASING, - RenderingHints.VALUE_TEXT_ANTIALIAS_DEFAULT); - hints.put(RenderingHints.KEY_ANTIALIASING, - RenderingHints.VALUE_ANTIALIAS_DEFAULT); - renderingHints = new RenderingHints(hints); + stroke = STANDARD_STROKE; + renderingHints = new RenderingHints(STANDARD_HINTS); } /** @@ -270,7 +308,6 @@ public boolean drawImage(Image image, AffineTransform xform, ImageObserver obs) { - boolean ret = false; Rectangle areaOfInterest = new Rectangle(0, 0, image.getWidth(obs), image.getHeight(obs)); return drawImageImpl(image, xform, obs, areaOfInterest); @@ -941,15 +978,8 @@ */ public void drawGlyphVector(GlyphVector gv, float x, float y) { - int numGlyphs = gv.getNumGlyphs(); translate(x, y); - // TODO: We could use fill(gv.getOutline()), but that seems to be - // slightly more inefficient. - for (int i = 0; i < numGlyphs; i++) - { - Shape o = gv.getGlyphOutline(i); - fillShape(o, true); - } + fillShape(gv.getOutline(), true); translate(-x, -y); } @@ -982,7 +1012,8 @@ else copy.clip = new GeneralPath(clip); - copy.renderingHints = new RenderingHints(renderingHints); + copy.renderingHints = new RenderingHints(null); + copy.renderingHints.putAll(renderingHints); copy.transform = new AffineTransform(transform); // The remaining state is inmmutable and doesn't need to be copied. return copy; @@ -1143,17 +1174,34 @@ { if (isOptimized) { - int tx = (int) transform.getTranslateX(); - int ty = (int) transform.getTranslateY(); - rawDrawLine(x1 + tx, y1 + ty, x2 + tx, y2 + ty); + rawDrawLine(x1, y1, x2, y2); } else { - Line2D line = new Line2D.Double(x1, y1, x2, y2); - draw(line); + ShapeCache sc = getShapeCache(); + if (sc.line == null) + sc.line = new Line2D.Float(); + sc.line.setLine(x1, y1, x2, y2); + draw(sc.line); } } + public void drawRect(int x, int y, int w, int h) + { + if (isOptimized) + { + rawDrawRect(x, y, w, h); + } + else + { + ShapeCache sc = getShapeCache(); + if (sc.rect == null) + sc.rect = new Rectangle(); + sc.rect.setBounds(x, y, w, h); + draw(sc.rect); + } + } + /** * Fills a rectangle with the current paint. * @@ -1166,13 +1214,15 @@ { if (isOptimized) { - int tx = (int) transform.getTranslateX(); - int ty = (int) transform.getTranslateY(); - rawFillRect(x + tx, y + ty, width, height); + rawFillRect(x, y, width, height); } else { - fill(new Rectangle(x, y, width, height)); + ShapeCache sc = getShapeCache(); + if (sc.rect == null) + sc.rect = new Rectangle(); + sc.rect.setBounds(x, y, width, height); + fill(sc.rect); } } @@ -1213,8 +1263,11 @@ public void drawRoundRect(int x, int y, int width, int height, int arcWidth, int arcHeight) { - draw(new RoundRectangle2D.Double(x, y, width, height, arcWidth, - arcHeight)); + ShapeCache sc = getShapeCache(); + if (sc.roundRect == null) + sc.roundRect = new RoundRectangle2D.Float(); + sc.roundRect.setRoundRect(x, y, width, height, arcWidth, arcHeight); + draw(sc.roundRect); } /** @@ -1230,8 +1283,11 @@ public void fillRoundRect(int x, int y, int width, int height, int arcWidth, int arcHeight) { - fill(new RoundRectangle2D.Double(x, y, width, height, arcWidth, - arcHeight)); + ShapeCache sc = getShapeCache(); + if (sc.roundRect == null) + sc.roundRect = new RoundRectangle2D.Float(); + sc.roundRect.setRoundRect(x, y, width, height, arcWidth, arcHeight); + fill(sc.roundRect); } /** @@ -1244,7 +1300,11 @@ */ public void drawOval(int x, int y, int width, int height) { - draw(new Ellipse2D.Double(x, y, width, height)); + ShapeCache sc = getShapeCache(); + if (sc.ellipse == null) + sc.ellipse = new Ellipse2D.Float(); + sc.ellipse.setFrame(x, y, width, height); + draw(sc.ellipse); } /** @@ -1257,7 +1317,11 @@ */ public void fillOval(int x, int y, int width, int height) { - fill(new Ellipse2D.Double(x, y, width, height)); + ShapeCache sc = getShapeCache(); + if (sc.ellipse == null) + sc.ellipse = new Ellipse2D.Float(); + sc.ellipse.setFrame(x, y, width, height); + fill(sc.ellipse); } /** @@ -1266,8 +1330,11 @@ public void drawArc(int x, int y, int width, int height, int arcStart, int arcAngle) { - draw(new Arc2D.Double(x, y, width, height, arcStart, arcAngle, - Arc2D.OPEN)); + ShapeCache sc = getShapeCache(); + if (sc.arc == null) + sc.arc = new Arc2D.Float(); + sc.arc.setArc(x, y, width, height, arcStart, arcAngle, Arc2D.OPEN); + draw(sc.arc); } /** @@ -1276,8 +1343,11 @@ public void fillArc(int x, int y, int width, int height, int arcStart, int arcAngle) { - fill(new Arc2D.Double(x, y, width, height, arcStart, arcAngle, - Arc2D.OPEN)); + ShapeCache sc = getShapeCache(); + if (sc.arc == null) + sc.arc = new Arc2D.Float(); + sc.arc.setArc(x, y, width, height, arcStart, arcAngle, Arc2D.PIE); + draw(sc.arc); } public void drawPolyline(int[] xPoints, int[] yPoints, int npoints) @@ -1291,7 +1361,13 @@ */ public void drawPolygon(int[] xPoints, int[] yPoints, int npoints) { - draw(new Polygon(xPoints, yPoints, npoints)); + ShapeCache sc = getShapeCache(); + if (sc.polygon == null) + sc.polygon = new Polygon(); + sc.polygon.xpoints = xPoints; + sc.polygon.ypoints = yPoints; + sc.polygon.npoints = npoints; + draw(sc.polygon); } /** @@ -1299,7 +1375,13 @@ */ public void fillPolygon(int[] xPoints, int[] yPoints, int npoints) { - fill(new Polygon(xPoints, yPoints, npoints)); + ShapeCache sc = getShapeCache(); + if (sc.polygon == null) + sc.polygon = new Polygon(); + sc.polygon.xpoints = xPoints; + sc.polygon.ypoints = yPoints; + sc.polygon.npoints = npoints; + fill(sc.polygon); } /** @@ -1460,8 +1542,12 @@ } /** - * Fills the specified shape. The shape has already been clipped against the - * current clip. + * Fills the specified shape. Override this if your backend can efficiently + * fill shapes. This is possible on many systems via a polygon fill + * method or something similar. But keep in mind that Shapes can be quite + * complex (non-convex, with holes etc), which is not necessarily supported + * by all polygon fillers. Also note that you must perform clipping + * before filling the shape. * * @param s the shape to fill * @param isFont <code>true</code> if the shape is a font outline @@ -1484,21 +1570,14 @@ antialias = (v == RenderingHints.VALUE_ANTIALIAS_ON); } - Rectangle2D userBounds = s.getBounds2D(); - Rectangle2D deviceBounds = new Rectangle2D.Double(); - ArrayList segs = getSegments(s, transform, deviceBounds, false); - Rectangle2D clipBounds = new Rectangle2D.Double(); - ArrayList clipSegs = getSegments(clip, transform, clipBounds, true); - segs.addAll(clipSegs); - Rectangle2D inclClipBounds = new Rectangle2D.Double(); - Rectangle2D.union(clipBounds, deviceBounds, inclClipBounds); - if (segs.size() > 0) - { + ScanlineConverter sc = getScanlineConverter(); + int resolution = 0; if (antialias) - fillShapeAntialias(segs, deviceBounds, userBounds, inclClipBounds); - else - fillShapeImpl(segs, deviceBounds, userBounds, inclClipBounds); + { + // Adjust resolution according to rendering hints. + resolution = 2; } + sc.renderShape(this, s, clip, transform, resolution); } /** @@ -1533,6 +1612,11 @@ draw(new Line2D.Float(x0, y0, x1, y1)); } + protected void rawDrawRect(int x, int y, int w, int h) + { + draw(new Rectangle(x, y, w, h)); + } + /** * Draws a string in optimization mode. The implementation should respect the * clip and translation. It can assume that the clip is a rectangle and that @@ -1627,153 +1711,16 @@ } /** - * Fills the specified polygon. This should be overridden by backends - * that support accelerated (native) polygon filling, which is the - * case for most toolkit window and offscreen image implementations. + * Paints a scanline between x0 and x1. Override this when your backend + * can efficiently draw/fill horizontal lines. * - * The polygon is already clipped when this method is called. - */ - private void fillShapeImpl(ArrayList segs, Rectangle2D deviceBounds2D, - Rectangle2D userBounds, - Rectangle2D inclClipBounds) - { - // This is an implementation of a polygon scanline conversion algorithm - // described here: - // http://www.cs.berkeley.edu/~ug/slide/pipeline/assignments/scan/ - - // Create table of all edges. - // The edge buckets, sorted and indexed by their Y values. - - double minX = deviceBounds2D.getMinX(); - double minY = deviceBounds2D.getMinY(); - double maxX = deviceBounds2D.getMaxX(); - double maxY = deviceBounds2D.getMaxY(); - double icMinY = inclClipBounds.getMinY(); - double icMaxY = inclClipBounds.getMaxY(); - Rectangle deviceBounds = new Rectangle((int) minX, (int) minY, - (int) Math.ceil(maxX) - (int) minX, - (int) Math.ceil(maxY) - (int) minY); - PaintContext pCtx = paint.createContext(getColorModel(), deviceBounds, - userBounds, transform, renderingHints); - - ArrayList[] edgeTable = new ArrayList[(int) Math.ceil(icMaxY) - - (int) Math.ceil(icMinY) + 1]; - - for (Iterator i = segs.iterator(); i.hasNext();) - { - PolyEdge edge = (PolyEdge) i.next(); - int yindex = (int) ((int) Math.ceil(edge.y0) - (int) Math.ceil(icMinY)); - if (edgeTable[yindex] == null) // Create bucket when needed. - edgeTable[yindex] = new ArrayList(); - edgeTable[yindex].add(edge); // Add edge to the bucket of its line. - } - - // TODO: The following could be useful for a future optimization. -// // Sort all the edges in the edge table within their buckets. -// for (int y = 0; y < edgeTable.length; y++) -// { -// if (edgeTable[y] != null) -// Collections.sort(edgeTable[y]); -// } - - // The activeEdges list contains all the edges of the current scanline - // ordered by their intersection points with this scanline. - ArrayList activeEdges = new ArrayList(); - PolyEdgeComparator comparator = new PolyEdgeComparator(); - - // Scan all relevant lines. - int minYInt = (int) Math.ceil(icMinY); - - Rectangle devClip = getDeviceBounds(); - int scanlineMax = (int) Math.min(maxY, devClip.getMaxY()); - for (int y = minYInt; y < scanlineMax; y++) - { - ArrayList bucket = edgeTable[y - minYInt]; - // Update all the x intersections in the current activeEdges table - // and remove entries that are no longer in the scanline. - for (Iterator i = activeEdges.iterator(); i.hasNext();) - { - PolyEdge edge = (PolyEdge) i.next(); - if (y > edge.y1) - i.remove(); - else - { - edge.xIntersection += edge.slope; - //edge.xIntersection = edge.x0 + edge.slope * (y - edge.y0); - //System.err.println("edge.xIntersection: " + edge.xIntersection); - } - } - - if (bucket != null) - activeEdges.addAll(bucket); - - // Sort current edges. We are using a bubble sort, because the order - // of the intersections will not change in most situations. They - // will only change, when edges intersect each other. - int size = activeEdges.size(); - if (size > 1) - { - for (int i = 1; i < size; i++) - { - PolyEdge e1 = (PolyEdge) activeEdges.get(i - 1); - PolyEdge e2 = (PolyEdge) activeEdges.get(i); - if (comparator.compare(e1, e2) > 0) - { - // Swap e2 with its left neighbor until it 'fits'. - int j = i; - do - { - activeEdges.set(j, e1); - activeEdges.set(j - 1, e2); - j--; - if (j >= 1) - e1 = (PolyEdge) activeEdges.get(j - 1); - } while (j >= 1 && comparator.compare(e1, e2) > 0); - } - } - } - - // Now draw all pixels inside the polygon. - // This is the last edge that intersected the scanline. - PolyEdge previous = null; // Gets initialized below. - boolean insideShape = false; - boolean insideClip = false; - //System.err.println("scanline: " + y); - for (Iterator i = activeEdges.iterator(); i.hasNext();) - { - PolyEdge edge = (PolyEdge) i.next(); - if (edge.y1 <= y) - continue; - - // Draw scanline when we are inside the shape AND inside the - // clip. - if (insideClip && insideShape) - { - int x0 = (int) previous.xIntersection; - int x1 = (int) edge.xIntersection; - if (x0 < x1) - fillScanline(pCtx, x0, x1, y); - } - // Update state. - previous = edge; - if (edge.isClip) - insideClip = ! insideClip; - else - insideShape = ! insideShape; - } - } - pCtx.dispose(); - } - - /** - * Paints a scanline between x0 and x1. - * * @param x0 the left offset * @param x1 the right offset * @param y the scanline */ - protected void fillScanline(PaintContext pCtx, int x0, int x1, int y) + protected void fillScanline(int x0, int x1, int y) { + PaintContext pCtx = paintContext; Raster paintRaster = pCtx.getRaster(x0, y, x1 - x0, 1); ColorModel paintColorModel = pCtx.getColorModel(); CompositeContext cCtx = composite.createContext(paintColorModel, @@ -1785,200 +1732,7 @@ cCtx.dispose(); } - /** - * Fills arbitrary shapes in an anti-aliased fashion. - * - * @param segs the line segments which define the shape which is to be filled - */ - private void fillShapeAntialias(ArrayList segs, Rectangle2D deviceBounds2D, - Rectangle2D userBounds, - Rectangle2D inclClipBounds) - { - // This is an implementation of a polygon scanline conversion algorithm - // described here: - // http://www.cs.berkeley.edu/~ug/slide/pipeline/assignments/scan/ - // The antialiasing is implemented using a sampling technique, we do - // not scan whole lines but fractions of the line. - double minX = deviceBounds2D.getMinX(); - double minY = deviceBounds2D.getMinY(); - double maxX = deviceBounds2D.getMaxX(); - double maxY = deviceBounds2D.getMaxY(); - double icMinY = inclClipBounds.getMinY(); - double icMaxY = inclClipBounds.getMaxY(); - double icMinX = inclClipBounds.getMinX(); - double icMaxX = inclClipBounds.getMaxX(); - Rectangle deviceBounds = new Rectangle((int) minX, (int) minY, - (int) Math.ceil(maxX) - (int) minX, - (int) Math.ceil(maxY) - (int) minY); - PaintContext pCtx = paint.createContext(ColorModel.getRGBdefault(), - deviceBounds, - userBounds, transform, - renderingHints); - - // This array will contain the oversampled transparency values for - // each pixel in the scanline. - int numScanlines = (int) Math.ceil(icMaxY) - (int) icMinY; - int numScanlinePixels = (int) Math.ceil(icMaxX) - (int) icMinX + 1; - if (alpha == null || alpha.length < (numScanlinePixels + 1)) - alpha = new int[numScanlinePixels + 1]; - - int firstLine = (int) icMinY; - //System.err.println("minY: " + minY); - int firstSubline = (int) (Math.ceil((icMinY - Math.floor(icMinY)) * AA_SAMPLING)); - double firstLineDouble = firstLine + firstSubline / (double) AA_SAMPLING; - //System.err.println("firstSubline: " + firstSubline); - - // Create table of all edges. - // The edge buckets, sorted and indexed by their Y values. - //System.err.println("numScanlines: " + numScanlines); - if (edgeTable == null - || edgeTable.length < numScanlines * AA_SAMPLING + AA_SAMPLING) - edgeTable = new ArrayList[numScanlines * AA_SAMPLING + AA_SAMPLING]; - - //System.err.println("firstLineDouble: " + firstLineDouble); - - for (Iterator i = segs.iterator(); i.hasNext();) - { - PolyEdge edge = (PolyEdge) i.next(); - int yindex = (int) (Math.ceil((edge.y0 - firstLineDouble) * AA_SAMPLING)); - //System.err.println("yindex: " + yindex + " for y0: " + edge.y0); - // Initialize edge's slope and initial xIntersection. - edge.slope = ((edge.x1 - edge.x0) / (edge.y1 - edge.y0)) / AA_SAMPLING; - if (edge.y0 == edge.y1) // Horizontal edge. - edge.xIntersection = Math.min(edge.x0, edge.x1); - else - { - double alignedFirst = Math.ceil(edge.y0 * AA_SAMPLING) / AA_SAMPLING; - edge.xIntersection = edge.x0 + (edge.slope * AA_SAMPLING) * (alignedFirst - edge.y0); - } - //System.err.println(edge); - // FIXME: Sanity check should not be needed when clipping works. - if (yindex >= 0 && yindex < edgeTable.length) - { - if (edgeTable[yindex] == null) // Create bucket when needed. - edgeTable[yindex] = new ArrayList(); - edgeTable[yindex].add(edge); // Add edge to the bucket of its line. - } - } - - // The activeEdges list contains all the edges of the current scanline - // ordered by their intersection points with this scanline. - ArrayList activeEdges = new ArrayList(); - PolyEdgeComparator comparator = new PolyEdgeComparator(); - - // Scan all lines. - int yindex = 0; - //System.err.println("firstLine: " + firstLine + ", maxY: " + maxY + ", firstSubline: " + firstSubline); - for (int y = firstLine; y <= icMaxY; y++) - { - int leftX = (int) icMaxX; - int rightX = (int) icMinX; - boolean emptyScanline = true; - for (int subY = firstSubline; subY < AA_SAMPLING; subY++) - { - //System.err.println("scanline: " + y + ", subScanline: " + subY); - ArrayList bucket = edgeTable[yindex]; - // Update all the x intersections in the current activeEdges table - // and remove entries that are no longer in the scanline. - for (Iterator i = activeEdges.iterator(); i.hasNext();) - { - PolyEdge edge = (PolyEdge) i.next(); - // TODO: Do the following using integer arithmetics. - if ((y + ((double) subY / (double) AA_SAMPLING)) > edge.y1) - i.remove(); - else - { - edge.xIntersection += edge.slope; - //System.err.println("edge: " + edge); - //edge.xIntersection = edge.x0 + edge.slope * (y - edge.y0); - //System.err.println("edge.xIntersection: " + edge.xIntersection); - } - } - - if (bucket != null) - { - activeEdges.addAll(bucket); - edgeTable[yindex].clear(); - } - - // Sort current edges. We are using a bubble sort, because the order - // of the intersections will not change in most situations. They - // will only change, when edges intersect each other. - int size = activeEdges.size(); - if (size > 1) - { - for (int i = 1; i < size; i++) - { - PolyEdge e1 = (PolyEdge) activeEdges.get(i - 1); - PolyEdge e2 = (PolyEdge) activeEdges.get(i); - if (comparator.compare(e1, e2) > 0) - { - // Swap e2 with its left neighbor until it 'fits'. - int j = i; - do - { - activeEdges.set(j, e1); - activeEdges.set(j - 1, e2); - j--; - if (j >= 1) - e1 = (PolyEdge) activeEdges.get(j - 1); - } while (j >= 1 && comparator.compare(e1, e2) > 0); - } - } - } - - // Now draw all pixels inside the polygon. - // This is the last edge that intersected the scanline. - PolyEdge previous = null; // Gets initialized below. - boolean insideClip = false; - boolean insideShape = false; - //System.err.println("scanline: " + y + ", subscanline: " + subY); - for (Iterator i = activeEdges.iterator(); i.hasNext();) - { - PolyEdge edge = (PolyEdge) i.next(); - if (edge.y1 <= (y + (subY / (double) AA_SAMPLING))) - continue; - - if (insideClip && insideShape) - { - // TODO: Use integer arithmetics here. - if (edge.y1 > (y + (subY / (double) AA_SAMPLING))) - { - //System.err.println(edge); - // TODO: Eliminate the aligments. - int x0 = (int) Math.min(Math.max(previous.xIntersection, minX), maxX); - int x1 = (int) Math.min(Math.max(edge.xIntersection, minX), maxX); - //System.err.println("minX: " + minX + ", x0: " + x0 + ", x1: " + x1 + ", maxX: " + maxX); - // TODO: Pull out cast. - int left = x0 - (int) minX; - int right = x1 - (int) minX + 1; - alpha[left]++; - alpha[right]--; - leftX = Math.min(x0, leftX); - rightX = Math.max(x1+2, rightX); - emptyScanline = false; - } - } - previous = edge; - if (edge.isClip) - insideClip = ! insideClip; - else - insideShape = ! insideShape; - } - yindex++; - } - firstSubline = 0; - // Render full scanline. - //System.err.println("scanline: " + y); - if (! emptyScanline) - fillScanlineAA(alpha, leftX, (int) y, rightX - leftX, pCtx, - (int) minX); - } - - pCtx.dispose(); - } - /** * Fills a horizontal line between x0 and x1 for anti aliased rendering. * the alpha array contains the deltas of the alpha values from one pixel @@ -1986,7 +1740,7 @@ * * @param alpha the alpha values in the scanline * @param x0 the beginning of the scanline - * @param y the y coordinate of the line + * @param yy the y coordinate of the line */ private void fillScanlineAA(int[] alpha, int x0, int yy, int numPixels, PaintContext pCtx, int offs) @@ -1997,7 +1751,6 @@ Raster paintRaster = pCtx.getRaster(x0, yy, numPixels, 1); //System.err.println("paintColorModel: " + pCtx.getColorModel()); WritableRaster aaRaster = paintRaster.createCompatibleWritableRaster(); - int numBands = paintRaster.getNumBands(); ColorModel cm = pCtx.getColorModel(); double lastAlpha = 0.; int lastAlphaInt = 0; @@ -2040,7 +1793,6 @@ cCtx.dispose(); } - /** * Initializes this graphics object. This must be called by subclasses in * order to correctly initialize the state of this object. @@ -2048,13 +1800,8 @@ protected void init() { setPaint(Color.BLACK); - setFont(new Font("SansSerif", Font.PLAIN, 12)); + setFont(FONT); isOptimized = true; - - // FIXME: Should not be necessary. A clip of null should mean - // 'clip against device bounds. - destinationRaster = getDestinationRaster(); - clip = getDeviceBounds(); } /** @@ -2156,10 +1903,10 @@ private static Rectangle computeIntersection(int x, int y, int w, int h, Rectangle rect) { - int x2 = (int) rect.x; - int y2 = (int) rect.y; - int w2 = (int) rect.width; - int h2 = (int) rect.height; + int x2 = rect.x; + int y2 = rect.y; + int w2 = rect.width; + int h2 = rect.height; int dx = (x > x2) ? x : x2; int dy = (y > y2) ? y : y2; @@ -2194,76 +1941,34 @@ } /** - * Converts the specified shape into a list of segments. + * Returns the ShapeCache for the calling thread. * - * @param s the shape to convert - * @param t the transformation to apply before converting - * @param deviceBounds an output parameter; holds the bounding rectangle of - * s in device space after return - * @param isClip true when the shape is a clip, false for normal shapes; - * this influences the settings in the created PolyEdge instances. - * - * @return a list of PolyEdge that form the shape in device space + * @return the ShapeCache for the calling thread */ - private ArrayList getSegments(Shape s, AffineTransform t, - Rectangle2D deviceBounds, boolean isClip) + private ShapeCache getShapeCache() { - // Flatten the path. TODO: Determine the best flattening factor - // wrt to speed and quality. - PathIterator path = s.getPathIterator(getTransform(), 1.0); - - // Build up polygons and let the native backend render this using - // rawFillShape() which would provide a default implementation for - // drawPixel using a PolyScan algorithm. - double[] seg = new double[6]; - - // TODO: Use ArrayList<PolyEdge> here when availble. - ArrayList segs = new ArrayList(); - double segX = 0.; // The start point of the current edge. - double segY = 0.; - double polyX = 0.; // The start point of the current polygon. - double polyY = 0.; - - double minX = Integer.MAX_VALUE; - double maxX = Integer.MIN_VALUE; - double minY = Integer.MAX_VALUE; - double maxY = Integer.MIN_VALUE; - - //System.err.println("fill polygon"); - while (! path.isDone()) + ShapeCache sc = (ShapeCache) shapeCache.get(); + if (sc == null) { - int segType = path.currentSegment(seg); - minX = Math.min(minX, seg[0]); - maxX = Math.max(maxX, seg[0]); - minY = Math.min(minY, seg[1]); - maxY = Math.max(maxY, seg[1]); - - //System.err.println("segment: " + segType + ", " + seg[0] + ", " + seg[1]); - if (segType == PathIterator.SEG_MOVETO) - { - segX = seg[0]; - segY = seg[1]; - polyX = seg[0]; - polyY = seg[1]; + sc = new ShapeCache(); + shapeCache.set(sc); } - else if (segType == PathIterator.SEG_CLOSE) - { - // Close the polyline. - PolyEdge edge = new PolyEdge(segX, segY, - polyX, polyY, isClip); - segs.add(edge); + return sc; } - else if (segType == PathIterator.SEG_LINETO) + + /** + * Returns the scanline converter for this thread. + * + * @return the scanline converter for this thread + */ + private ScanlineConverter getScanlineConverter() + { + ScanlineConverter sc = (ScanlineConverter) scanlineConverters.get(); + if (sc == null) { - PolyEdge edge = new PolyEdge(segX, segY, - seg[0], seg[1], isClip); - segs.add(edge); - segX = seg[0]; - segY = seg[1]; - } - path.next(); + sc = new ScanlineConverter(); + scanlineConverters.set(sc); } - deviceBounds.setRect(minX, minY, maxX - minX, maxY - minY); - return segs; + return sc; } } Added: trunk/core/src/classpath/gnu/gnu/java/awt/java2d/ActiveEdges.java =================================================================== --- trunk/core/src/classpath/gnu/gnu/java/awt/java2d/ActiveEdges.java (rev 0) +++ trunk/core/src/classpath/gnu/gnu/java/awt/java2d/ActiveEdges.java 2007-01-07 12:36:12 UTC (rev 3016) @@ -0,0 +1,195 @@ +/* ActiveEdges.java -- A collection of active edges for scanline conversion + 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.java2d; + +/** + * A collection of active edges for scanline conversion. + */ +final class ActiveEdges +{ + + /** + * The active edges. This can contain null values at arbirary locations. + * The method #sort() packs this together. + */ + private PolyEdge[] activeEdges; + + /** + * The actual number of active edges. The array can be bigger than this + * number. + */ + private int numActiveEdges; + + /** + * Creates a new ActiveEdges object. + */ + ActiveEdges() + { + activeEdges = new PolyEdge[8]; + numActiveEdges = 0; + } + + /** + * Clears out all active edges. This is cheap as it simply resets the + * counter to 0. It does not release all references to PolyEdge instances. + */ + void clear() + { + numActiveEdges = 0; + } + + /** + * Adds the specified edge to the list of active edges. This does not yet + * sort the edges and therefore does destroy any order of the list. + * + * @param edge the edge to add + */ + void add(PolyEdge edge) + { + // Grow array when necessary. + int oldSize = activeEdges.length; + if (numActiveEdges >= oldSize) + { + int newSize = oldSize + oldSize / 4 + 1; + PolyEdge[] newEdges = new PolyEdge[newSize]; + System.arraycopy(activeEdges, 0, newEdges, 0, oldSize); + activeEdges = newEdges; + } + activeEdges[numActiveEdges] = edge; + numActiveEdges++; + } + + /** + * Intersects all active edges, sorts them according to their intersection + * points and packs the array to remove unneeded edges. This does also + * remove any edges that do not intersect the scanline (i.e. they end above + * of the scanline). + * + * @param y the scanline height + */ + void intersectSortAndPack(int n, int y) + { + // Intersect and pack in one go. + int last = 0; + PolyEdge tmp; + for (int i = 0; i < numActiveEdges; i++) + { + PolyEdge edge = activeEdges[i]; + // Clear out edge that ends above the scanline. + if (edge != null && edge.y1 >= y) + { + assert edge.y1 >= y && edge.y0 <= y : "edge must cross scanline"; + edge.intersect(n, y); + activeEdges[last] = edge; + last++; + + // Bubble up the added edge. + for (int j = last - 1; j > 0; j--) + { + if (activeEdges[j].xIntersection + < activeEdges[j - 1].xIntersection) + { + tmp = activeEdges[j]; + activeEdges[j] = activeEdges[j - 1]; + activeEdges[j - 1] = tmp; + } + else + { + // The beginning of the list is already sorted. + break; + } + } + } + } + numActiveEdges = last; + + } + + /** + * Returns the number of active edges. This is only reliable after a + * call to {@link #intersectSortAndPack(int, int)}. + * + * @return the number of active edges + */ + int getNumActiveEdges() + { + return numActiveEdges; + } + + /** + * Returns the active edge at the position <code>i</code>. + * + * @param i the index + * + * @return the active edge at the specified index + */ + PolyEdge getActiveEdge(int i) + { + return activeEdges[i]; + } + + /** + * Removes all edges that end above the specified height. + * + * @param y the cut-off height + */ + void remove(int y) + { + for (int i = 0; i < numActiveEdges; i++) + { + PolyEdge edge = activeEdges[i]; + if (edge != null && edge.y1 < y) + { + activeEdges[i] = null; + } + } + } + + public String toString() + { + StringBuilder s = new StringBuilder(); + s.append("[ActiveEdges] "); + for (int i = 0; i < numActiveEdges; i++) + { + s.append(activeEdges[i]); + s.append(','); + } + return s.toString(); + } +} Modified: trunk/core/src/classpath/gnu/gnu/java/awt/java2d/PolyEdge.java =================================================================== --- trunk/core/src/classpath/gnu/gnu/java/awt/java2d/PolyEdge.java 2007-01-07 12:35:22 UTC (rev 3015) +++ trunk/core/src/classpath/gnu/gnu/java/awt/java2d/PolyEdge.java 2007-01-07 12:36:12 UTC (rev 3016) @@ -38,31 +38,38 @@ package gnu.java.awt.java2d; +import gnu.java.math.Fixed; + /** - * An edge in a polygon. This is used by the scanline conversion algorithm - * implemented in {@link AbstractGraphics2D#rawFillShape}. + * An edge in a polygon. * * @author Roman Kennke (ke...@ai...) */ -public class PolyEdge +final class PolyEdge implements Comparable { /** * The start and end coordinates of the edge. y0 is always smaller or equal * than y1. + * + * These values are stored as fixed-point decimals. */ - public double x0, y0, x1, y1; + public int x0, y0, x1, y1; /** * The slope of the edge. This is dx / dy. + * + * This is a fixed point decimal. */ - double slope; + private int slope; /** * The intersection of this edge with the current scanline. + * + * This is a fixed point decimal. */ - double xIntersection; + int xIntersection; /** * Indicates whether this edge is from the clip or from the target shape. @@ -70,6 +77,24 @@ boolean isClip; /** + * Implements a linked list for the edge pool. + */ + PolyEdge poolNext; + + /** + * Implements a linked list for the scanline edge lists. + */ + PolyEdge scanlineNext; + + /** + * Create an uninitialized edge. + */ + PolyEdge() + { + // Nothing to do here. + } + + /** * Creates a new PolyEdge with the specified coordinates. * * @param x0 the starting point, x coordinate @@ -77,8 +102,21 @@ * @param x1 the end point, x coordinate * @param y1 the end point, y coordinate */ - PolyEdge(double x0, double y0, double x1, double y1, boolean clip) + PolyEdge(int n, int x0, int y0, int x1, int y1, boolean clip) { + init(n, x0, y0, x1, y1, clip); + } + + /** + * (Re-) Initializes this edge. + * + * @param x0 + * @param y0 + * @param x1 + * @param y1 + */ + void init(int n, int x0, int y0, int x1, int y1, boolean clip) + { isClip = clip; if (y0 < y1) { @@ -94,11 +132,7 @@ this.x1 = x0; this.y1 = y0; } - slope = (this.x1 - this.x0) / (this.y1 - this.y0); - if (this.y0 == this.y1) // Horizontal edge. - xIntersection = Math.min(this.x0, this.x1); - else - xIntersection = this.x0 + slope * (Math.ceil(this.y0) - this.y0); + slope = Fixed.div(n, this.x1 - this.x0, this.y1 - this.y0); } /** @@ -115,6 +149,19 @@ return comp; } + /** + * Intersects this edge with the scanline at height y. The result is + * stored in {@link #xIntersection}. + * + * @param y the scanline + */ + void intersect(int n, int y) + { + int dy = y - y0; + int dx = Fixed.mul(n, slope, dy); + xIntersection = x0 + dx; + } + public String toString() { return "Edge: " + x0 + ", " + y0 + ", " + x1 + ", " + y1 + ", slope: " Modified: trunk/core/src/classpath/gnu/gnu/java/awt/java2d/QuadSegment.java =================================================================== --- trunk/core/src/classpath/gnu/gnu/java/awt/java2d/QuadSegment.java 2007-01-07 12:35:22 UTC (rev 3015) +++ trunk/core/src/classpath/gnu/gnu/java/awt/java2d/QuadSegment.java 2007-01-07 12:36:12 UTC (rev 3016) @@ -145,8 +145,53 @@ Point2D cp; QuadSegment s; - if( plus ) + if(!plus) { + n1[0] = -n1[0]; + n1[1] = -n1[1]; + n2[0] = -n2[0]; + n2[1] = -n2[1]; + } + + // Handle special cases where the control point is equal to an end point + // or end points are equal (ie, straight lines) + if (curve.getP1().equals(curve.getCtrlPt())) + { + cp = curve.getCtrlPt(); + cp.setLocation(cp.getX() + n2[0], cp.getY() + n2[1]); + n1[0] = n2[0]; + n1[1] = n2[1]; + } + else if (curve.getP2().equals(curve.getCtrlPt())) + { + cp = curve.getCtrlPt(); + cp.setLocation(cp.getX() + n1[0], cp.getY() + n1[1]); + n2[0] = n1[0]; + n2[1] = n1[1]; + } + else if (curve.getP1().equals(curve.getP2())) + { + cp = curve.getCtrlPt(); + + double deltaX = curve.getX1() - curve.getCtrlX(); + double deltaY = curve.getY1() - curve.getCtrlY(); + double length = Math.sqrt((deltaX * deltaX) + (deltaY * deltaY)); + double ratio = radius / length; + deltaX *= ratio; + deltaY *= ratio; + + if (plus) + cp.setLocation(cp.getX() + deltaX, cp.getY() + deltaY); + else + cp.setLocation(cp.getX() - deltaX, cp.getY() - deltaY); + } + else if (n1[0] == n2[0] && n1[1] == n2[1]) + { + cp = curve.getCtrlPt(); + cp.setLocation(cp.getX() + n1[0], cp.getY() + n1[1]); + } + else + { cp = lineIntersection(curve.getX1() + n1[0], curve.getY1() + n1[1], curve.getCtrlX() + n1[0], @@ -155,25 +200,11 @@ curve.getCtrlY() + n2[1], curve.getX2() + n2[0], curve.getY2() + n2[1], true); - s = new QuadSegment(curve.getX1() + n1[0], curve.getY1() + n1[1], - cp.getX(), cp.getY(), - curve.getX2() + n2[0], curve.getY2() + n2[1]); } - else - { - cp = lineIntersection(curve.getX1() - n1[0], - curve.getY1() - n1[1], - curve.getCtrlX() - n1[0], - curve.getCtrlY() - n1[1], - curve.getCtrlX() - n2[0], - curve.getCtrlY() - n2[1], - curve.getX2() - n2[0], - curve.getY2() - n2[1], true); - s = new QuadSegment(curve.getX1() - n1[0], curve.getY1() - n1[1], + s = new QuadSegment(curve.getX1() + n1[0], curve.getY1() + n1[1], cp.getX(), cp.getY(), - curve.getX2() - n2[0], curve.getY2() - n2[1]); - } + curve.getX2() + n2[0], curve.getY2() + n2[1]); return s; } Added: trunk/core/src/classpath/gnu/gnu/java/awt/java2d/Scanline.java =================================================================== --- trunk/core/src/classpath/gnu/gnu/java/awt/java2d/Scanline.java (rev 0) +++ trunk/core/src/classpath/gnu/gnu/java/awt/java2d/Scanline.java 2007-01-07 12:36:12 UTC (rev 3016) @@ -0,0 +1,91 @@ +/* Scanline.java -- A scanline for the scanline converter + 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.java2d; + +/** + * Represents a scanline in the {@link ScanlineConverter}. This is basically + * a sorted list of {@link PolyEdge}s that is made for maximum reuse. + */ +class Scanline +{ + + /** + * The actual edges array. The fields can be null. + */ + private PolyEdge edges; + + /** + * Clears this scanline. This only resets the number of edges to 0. The + * actual PolyEdge objects are preserved for possible later reuse. + */ + void clear() + { + edges = null; + } + + /** + * Create a new Scanline. + */ + Scanline() + { + // Nothing to do. + } + + /** + * Inserts an edge into this scanline. This is performed in a sorted fashion, + * and so that it reuses as much existing resources as possible. + */ + void addEdge(PolyEdge edge) + { + + // Allocate PolyEdge when necessary or reuse an old one. + edge.scanlineNext = edges; + edges = edge; + } + + /** + * Returns the edges queue. + * + * @return the edges queue + */ + PolyEdge getEdges() + { + return edges; + } +} Added: trunk/core/src/classpath/gnu/gnu/java/awt/java2d/ScanlineConverter.java =================================================================== --- trunk/core/src/classpath/gnu/gnu/java/awt/java2d/ScanlineConverter.java (rev 0) +++ trunk/core/src/classpath/gnu/gnu/java/awt/java2d/ScanlineConverter.java 2007-01-07 12:36:12 UTC (rev 3016) @@ -0,0 +1,404 @@ +/* ScanlineConverter.java -- Rasterizes Shapes + 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.java2d; + +import gnu.java.math.Fixed; + +import java.awt.Shape; +import java.awt.geom.AffineTransform; +import java.awt.geom.PathIterator; + +/** + * Rasterizes {@link Shape} objects on an AbstractGraphics2D. + */ +final class ScanlineConverter +{ + + /** + * The number of digits to use for fixed point arithmetics. + */ + private static int FIXED_DIGITS = 6; + + /** + * The fixed value for the number 1. + */ + private static int ONE = Fixed.fixedValue(FIXED_DIGITS, 1); + + /** + * The actual number of scanlines. + */ + private int numScanlines; + + /** + * The number of scanlines. This can contain more elements than we have + * scanlines. The real number of scanlines is stored in + * {@link #numScanlines}. This can also contain null values for empty + * scanlines. + */ + private Scanline[] scanlines; + + /** + * The upper bounds which correspond to the index 0 in the scanline array. + * + * This is a fixed point value. + */ + private int upperBounds; + + /** + * The resolution of the scanline converter. + * + * This is a fixed point value. + */ + private int resolution; + + /** + * One half step according to the resolution. This is stored to avoid + * unnecessary operations during rendering. + */ + private int halfStep; + + /** + * This is used in {@link #addShape(PathIterator, boolean)} to + * receive the coordinates of the path. + */ + private float[] coords; + + /** + * The active edges. + */ + private ActiveEdges activeEdges; + + private PolyEdge edgePool; + private PolyEdge edgePoolLast; + + private int minY; + private int maxY; + + /** + * Create a new ScanlineConverter. + */ + ScanlineConverter() + { + scanlines = new Scanline[10]; + coords = new float[6]; + activeEdges = new ActiveEdges(); + edgePool = new PolyEdge(); + edgePoolLast = edgePool; + } + + /** + * Renders the specified shape using the specified clip and transform. + * + * @param shape the shape to render + * @param clip the clip + * @param trans the transform + */ + void renderShape(AbstractGraphics2D g, Shape shape, Shape clip, + AffineTransform trans, int res) + { + // Prepare resolution and upper bounds. + clear(); + setResolution(res); + + boolean haveClip = clip != null; + + // Add shapes. + PathIterator path = shape.getPathIterator(trans, resolution); + addShape(path, false); + if (haveClip) + { + path= clip.getPathIterator(trans, resolution); + addShape(path, true); + } + + setUpperBounds(minY); + + PolyEdge edge = edgePool; + while (edge != edgePoolLast) + { + addEdge(edge); + edge = edge.poolNext; + } + + int y = upperBounds; + int lastIndex = scanlineIndex(y - resolution); + int index; + activeEdges.clear(); + // The render loop... + Scanline scanline = null; + while (y <= maxY) + { + // First we put together our list of active edges. + index = scanlineIndex(y); + // If we go outside the scanline array we still need to render the + // remaining edges until they end. + scanline = index < scanlines.length ? scanlines[index] : null; + if (scanline != null) + { + edge = scanline.getEdges(); + while (edge != null) + { + activeEdges.add(edge); + edge = edge.scanlineNext; + } + } + + // Then we intersect all active edges with the current scanline + // and sort them according to their intersection points. + activeEdges.intersectSortAndPack(FIXED_DIGITS, y + halfStep); + + // Ok, now we can perform the actual scanlining. + boolean push = lastIndex != index; + doScanline(g, y, push, haveClip); + + // Remove obsolete active edges. + //activeEdges.remove(y + halfStep); + + // Go on with the next line... + y += resolution; + lastIndex = index; + } + } + + /** + * Clears all scanlines. + */ + private void clear() + { + // Reset edge pool. + edgePoolLast = edgePool; + + // Reset scanlines. + for (int i = scanlines.length - 1; i >= 0 ; i--) + { + Scanline sl = scanlines[i]; + if (sl != null) + sl.clear(); + } + + // Reset bounds. + minY = Integer.MAX_VALUE; + maxY = Integer.MIN_VALUE; + } + + /** + * Performs the scanlining on the current set of active edges. + */ + private void doScanline(AbstractGraphics2D g, int y, boolean push, + boolean haveClip) + { + // We begin outside the clip and outside the shape. We only draw when + // we are inside the clip AND inside the shape. + boolean inClip = ! haveClip; + boolean inShape = false; + PolyEdge lastEdge = null; + int numEdges = activeEdges.getNumActiveEdges(); + for (int i = 0; i < numEdges; i++) + { + PolyEdge edge = activeEdges.getActiveEdge(i); + if (inClip && inShape) + { + assert lastEdge != null; + int x0 = lastEdge.xIntersection; + int x1 = edge.xIntersection; + assert x0 <= x1; + if (push) + { + if (resolution == ONE) + { + // Non-AA rendering. + g.fillScanline(Fixed.intValue(FIXED_DIGITS, x0), + Fixed.intValue(FIXED_DIGITS, x1 - resolution), + Fixed.intValue(FIXED_DIGITS, y)); + } + else + { + // AA rendering. + // FIXME: Implement. + System.err.println("Implement AA rendering."); + } + } + } + if (edge.isClip) + inClip = ! inClip; + else + inShape = ! inShape; + + lastEdge = edge; + } + } + + /** + * Sets the resolution. A value of 0 rasterizes the shape normally without + * anti-aliasing. Greater values renders with a resolution of 2 ^ res. + * + * @param res the resolution + */ + private void setResolution(int res) + { + int one = Fixed.fixedValue(FIXED_DIGITS, 1); + resolution = one / (1 << res); + halfStep = resolution / 2; + } + + /** + * Sets the vertical bounds of that shape that is beeing rendered. + * + * @param y0 the upper bounds + */ + private void setUpperBounds(int y0) + { + upperBounds = fit(y0); + } + + /** + * Add a shape to the scanline converter. + * + * @param path + * @param clip + */ + private void addShape(PathIterator path, boolean clip) + { + int startX = 0; + int startY = 0; + int lastX = 0; + int lastY = 0; + while (! path.isDone()) + { + int type = path.currentSegment(coords); + switch (type) + { + case PathIterator.SEG_MOVETO: + startX = lastX = Fixed.fixedValue(FIXED_DIGITS, coords[0]); + startY = lastY = Fixed.fixedValue(FIXED_DIGITS, coords[1]); + minY = Math.min(startY, minY); + maxY = Math.max(startY, maxY); + break; + case PathIterator.SEG_LINETO: + int x = Fixed.fixedValue(FIXED_DIGITS, coords[0]); + int y = Fixed.fixedValue(FIXED_DIGITS, coords[1]); + edgePoolAdd(lastX, lastY, x, y, clip); + lastX = x; + last... [truncated message content] |
From: <ls...@us...> - 2007-01-07 12:35:26
|
Revision: 3015 http://jnode.svn.sourceforge.net/jnode/?rev=3015&view=rev Author: lsantha Date: 2007-01-07 04:35:22 -0800 (Sun, 07 Jan 2007) Log Message: ----------- Classpath patches. Modified Paths: -------------- trunk/core/src/classpath/gnu/gnu/classpath/SystemProperties.java Modified: trunk/core/src/classpath/gnu/gnu/classpath/SystemProperties.java =================================================================== --- trunk/core/src/classpath/gnu/gnu/classpath/SystemProperties.java 2007-01-07 08:34:32 UTC (rev 3014) +++ trunk/core/src/classpath/gnu/gnu/classpath/SystemProperties.java 2007-01-07 12:35:22 UTC (rev 3015) @@ -169,4 +169,5 @@ { return (String) properties.remove(name); } + } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <ls...@us...> - 2007-01-07 08:34:33
|
Revision: 3014 http://jnode.svn.sourceforge.net/jnode/?rev=3014&view=rev Author: lsantha Date: 2007-01-07 00:34:32 -0800 (Sun, 07 Jan 2007) Log Message: ----------- Classpath patches. Modified Paths: -------------- trunk/all/build.xml Modified: trunk/all/build.xml =================================================================== --- trunk/all/build.xml 2007-01-07 08:34:13 UTC (rev 3013) +++ trunk/all/build.xml 2007-01-07 08:34:32 UTC (rev 3014) @@ -483,6 +483,9 @@ <fileset dir="${root.dir}/core/src/classpath/tools"> <patternset refid="cp-includes-pattern"/> </fileset> + <fileset dir="${root.dir}/core/src/classpath/sun"> + <patternset refid="cp-includes-pattern"/> + </fileset> </vmsources> <vmspecificsources> <fileset dir="${root.dir}/core/src/classpath/vm"> This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <ls...@us...> - 2007-01-07 08:34:14
|
Revision: 3013 http://jnode.svn.sourceforge.net/jnode/?rev=3013&view=rev Author: lsantha Date: 2007-01-07 00:34:13 -0800 (Sun, 07 Jan 2007) Log Message: ----------- Classpath patches. Modified Paths: -------------- trunk/core/descriptors/org.classpath.core.xml Modified: trunk/core/descriptors/org.classpath.core.xml =================================================================== --- trunk/core/descriptors/org.classpath.core.xml 2007-01-07 08:33:13 UTC (rev 3012) +++ trunk/core/descriptors/org.classpath.core.xml 2007-01-07 08:34:13 UTC (rev 3013) @@ -90,11 +90,13 @@ <export name="java.security.interfaces.*"/> <export name="java.security.spec.*"/> <export name="java.text.*"/> + <export name="java.text.spi.*"/> <export name="java.util.*"/> <export name="java.util.jar.*"/> <export name="java.util.logging.*"/> <export name="java.util.prefs.*"/> <export name="java.util.regex.*"/> + <export name="java.util.spi.*"/> <export name="java.util.zip.*"/> <export name="javax.isolate.*"/> This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <ls...@us...> - 2007-01-07 08:33:14
|
Revision: 3012 http://jnode.svn.sourceforge.net/jnode/?rev=3012&view=rev Author: lsantha Date: 2007-01-07 00:33:13 -0800 (Sun, 07 Jan 2007) Log Message: ----------- Classpath patches. Modified Paths: -------------- trunk/core/src/classpath/gnu/gnu/CORBA/DynAn/gnuDynValue.java trunk/core/src/classpath/gnu/gnu/CORBA/Poa/gnuPOA.java trunk/core/src/classpath/gnu/gnu/classpath/ServiceFactory.java trunk/core/src/classpath/gnu/gnu/classpath/debug/Component.java trunk/core/src/classpath/gnu/gnu/classpath/debug/SystemLogger.java trunk/core/src/classpath/gnu/gnu/java/awt/AWTUtilities.java trunk/core/src/classpath/gnu/gnu/java/beans/encoder/ScanEngine.java trunk/core/src/classpath/gnu/gnu/java/locale/LocaleHelper.java trunk/core/src/classpath/gnu/gnu/java/util/DoubleEnumeration.java trunk/core/src/classpath/gnu/gnu/java/util/prefs/EventDispatcher.java trunk/core/src/classpath/gnu/gnu/java/util/prefs/MemoryBasedPreferences.java trunk/core/src/classpath/gnu/gnu/javax/imageio/png/PNGICCProfile.java trunk/core/src/classpath/gnu/gnu/javax/rmi/CORBA/UtilDelegateImpl.java trunk/core/src/classpath/gnu/gnu/javax/security/auth/login/ConfigFileParser.java trunk/core/src/classpath/gnu/gnu/javax/swing/text/html/css/CSSParser.java trunk/core/src/classpath/gnu/gnu/javax/swing/text/html/parser/gnuDTD.java trunk/core/src/classpath/gnu/gnu/javax/swing/text/html/parser/support/Parser.java trunk/core/src/classpath/gnu/gnu/javax/swing/text/html/parser/support/low/Constants.java trunk/core/src/classpath/gnu/gnu/javax/swing/text/html/parser/support/textPreProcessor.java trunk/core/src/classpath/gnu/gnu/xml/dom/DomAttr.java trunk/core/src/classpath/gnu/gnu/xml/dom/DomNode.java trunk/core/src/classpath/gnu/gnu/xml/dom/ls/SAXEventSink.java trunk/core/src/classpath/gnu/gnu/xml/pipeline/DomConsumer.java trunk/core/src/classpath/gnu/gnu/xml/stream/SAXParser.java trunk/core/src/classpath/gnu/gnu/xml/stream/XMLStreamWriterImpl.java trunk/core/src/classpath/gnu/gnu/xml/transform/StreamSerializer.java trunk/core/src/classpath/gnu/gnu/xml/transform/TransformerFactoryImpl.java trunk/core/src/classpath/gnu/gnu/xml/transform/TransformerImpl.java trunk/core/src/classpath/gnu/gnu/xml/transform/XSLURIResolver.java trunk/core/src/classpath/gnu/gnu/xml/util/XCat.java trunk/core/src/classpath/gnu/gnu/xml/xpath/Expr.java Added Paths: ----------- trunk/core/src/classpath/gnu/gnu/xml/transform/SAXTemplatesHandler.java trunk/core/src/classpath/gnu/gnu/xml/transform/SAXTransformerHandler.java Modified: trunk/core/src/classpath/gnu/gnu/CORBA/DynAn/gnuDynValue.java =================================================================== --- trunk/core/src/classpath/gnu/gnu/CORBA/DynAn/gnuDynValue.java 2007-01-07 08:31:59 UTC (rev 3011) +++ trunk/core/src/classpath/gnu/gnu/CORBA/DynAn/gnuDynValue.java 2007-01-07 08:33:13 UTC (rev 3012) @@ -172,7 +172,6 @@ else return super.current_member_kind(); } - ; /** @inheritDoc */ public String current_member_name() throws TypeMismatch, InvalidValue @@ -182,7 +181,6 @@ else return super.current_member_name(); } - ; /** @inheritDoc */ public NameDynAnyPair[] get_members_as_dyn_any() throws InvalidValue @@ -191,7 +189,6 @@ throw new InvalidValue(ISNULL); return super.gnu_get_members_as_dyn_any(); } - ; /** @inheritDoc */ public NameValuePair[] get_members() throws InvalidValue @@ -201,7 +198,6 @@ else return super.gnu_get_members(); } - ; /** @inheritDoc */ public void set_members_as_dyn_any(NameDynAnyPair[] value) @@ -210,7 +206,6 @@ super.set_members_as_dyn_any(value); isNull = false; } - ; /** @inheritDoc */ public void set_members(NameValuePair[] value) @@ -219,7 +214,6 @@ super.set_members(value); isNull = false; } - ; /** @inheritDoc */ public boolean is_null() Modified: trunk/core/src/classpath/gnu/gnu/CORBA/Poa/gnuPOA.java =================================================================== --- trunk/core/src/classpath/gnu/gnu/CORBA/Poa/gnuPOA.java 2007-01-07 08:31:59 UTC (rev 3011) +++ trunk/core/src/classpath/gnu/gnu/CORBA/Poa/gnuPOA.java 2007-01-07 08:33:13 UTC (rev 3012) @@ -1348,7 +1348,6 @@ { return name; } - ; /** * Return the parent of this POA. Modified: trunk/core/src/classpath/gnu/gnu/classpath/ServiceFactory.java =================================================================== --- trunk/core/src/classpath/gnu/gnu/classpath/ServiceFactory.java 2007-01-07 08:31:59 UTC (rev 3011) +++ trunk/core/src/classpath/gnu/gnu/classpath/ServiceFactory.java 2007-01-07 08:33:13 UTC (rev 3012) @@ -49,6 +49,7 @@ import java.util.Enumeration; import java.util.Iterator; import java.util.NoSuchElementException; +import java.util.ServiceConfigurationError; import java.util.logging.Level; import java.util.logging.LogRecord; import java.util.logging.Logger; @@ -176,7 +177,6 @@ */ private static final Logger LOGGER = Logger.getLogger("gnu.classpath"); - /** * Declared private in order to prevent constructing instances of * this utility class. @@ -225,6 +225,51 @@ public static Iterator lookupProviders(Class spi, ClassLoader loader) { + return lookupProviders(spi, loader, false); + } + + /** + * Finds service providers that are implementing the specified + * Service Provider Interface. + * + * <p><b>On-demand loading:</b> Loading and initializing service + * providers is delayed as much as possible. The rationale is that + * typical clients will iterate through the set of installed service + * providers until one is found that matches some criteria (like + * supported formats, or quality of service). In such scenarios, it + * might make sense to install only the frequently needed service + * providers on the local machine. More exotic providers can be put + * onto a server; the server will only be contacted when no suitable + * service could be found locally. + * + * <p><b>Security considerations:</b> Any loaded service providers + * are loaded through the specified ClassLoader, or the system + * ClassLoader if <code>classLoader</code> is + * <code>null</code>. When <code>lookupProviders</code> is called, + * the current {@link AccessControlContext} gets recorded. This + * captured security context will determine the permissions when + * services get loaded via the <code>next()</code> method of the + * returned <code>Iterator</code>. + * + * @param spi the service provider interface which must be + * implemented by any loaded service providers. + * + * @param loader the class loader that will be used to load the + * service providers, or <code>null</code> for the system class + * loader. For using the context class loader, see {@link + * #lookupProviders(Class)}. + * @param error true if a {@link ServiceConfigurationError} + * should be thrown when an error occurs, rather + * than it merely being logged. + * @return an iterator over instances of <code>spi</code>. + * + * @throws IllegalArgumentException if <code>spi</code> is + * <code>null</code>. + */ + public static Iterator lookupProviders(Class spi, + ClassLoader loader, + boolean error) + { String resourceName; Enumeration urls; @@ -246,10 +291,14 @@ * does not return anything (no providers installed). */ log(Level.WARNING, "cannot access {0}", resourceName, ioex); + if (error) + throw new ServiceConfigurationError("Failed to access + " + + resourceName, ioex); + else return Collections.EMPTY_LIST.iterator(); } - return new ServiceIterator(spi, urls, loader, + return new ServiceIterator(spi, urls, loader, error, AccessController.getContext()); } @@ -342,6 +391,11 @@ */ private Object nextProvider; + /** + * True if a {@link ServiceConfigurationError} should be thrown + * when an error occurs, instead of it merely being logged. + */ + private boolean error; /** * Constructs an Iterator that loads and initializes services on @@ -359,16 +413,21 @@ * @param loader the ClassLoader that gets used for loading * service providers. * + * @param error true if a {@link ServiceConfigurationError} + * should be thrown when an error occurs, rather + * than it merely being logged. + * * @param securityContext the security context to use when loading * and initializing service providers. */ ServiceIterator(Class spi, Enumeration urls, ClassLoader loader, - AccessControlContext securityContext) + boolean error, AccessControlContext securityContext) { this.spi = spi; this.urls = urls; this.loader = loader; this.securityContext = securityContext; + this.error = error; this.nextProvider = loadNextServiceProvider(); } @@ -426,6 +485,9 @@ log(Level.WARNING, "IOException upon reading {0}", currentURL, readProblem); line = null; + if (error) + throw new ServiceConfigurationError("Error reading " + + currentURL, readProblem); } /* When we are at the end of one list of services, @@ -477,6 +539,13 @@ log(Level.WARNING, msg, new Object[] { line, spi.getName(), currentURL }, ex); + if (error) + throw new ServiceConfigurationError("Cannot load service "+ + "provider class " + + line + " specified by "+ + "\"META-INF/services/"+ + spi.getName() + "\" in "+ + currentURL, ex); continue; } } @@ -497,6 +566,9 @@ catch (Exception ex) { log(Level.WARNING, "cannot close {0}", currentURL, ex); + if (error) + throw new ServiceConfigurationError("Cannot close " + + currentURL, ex); } reader = null; currentURL = null; @@ -515,6 +587,9 @@ catch (Exception ex) { log(Level.WARNING, "cannot open {0}", currentURL, ex); + if (error) + throw new ServiceConfigurationError("Cannot open " + + currentURL, ex); } } while (reader == null); Modified: trunk/core/src/classpath/gnu/gnu/classpath/debug/Component.java =================================================================== --- trunk/core/src/classpath/gnu/gnu/classpath/debug/Component.java 2007-01-07 08:31:59 UTC (rev 3011) +++ trunk/core/src/classpath/gnu/gnu/classpath/debug/Component.java 2007-01-07 08:33:13 UTC (rev 3012) @@ -98,8 +98,13 @@ */ public static final Component SSL_KEY_EXCHANGE = new Component ("SSL KEY EXCHANGE", 2); - /* Indices 3 and 4 reserved for future use by SSL components. */ + /** + * Trace running of delegated tasks. + */ + public static final Component SSL_DELEGATED_TASK = new Component ("SSL DELEGATED TASK", 3); + /* Index 4 reserved for future use by SSL components. */ + /** * Trace the operation of cryptographic primitives. */ Modified: trunk/core/src/classpath/gnu/gnu/classpath/debug/SystemLogger.java =================================================================== --- trunk/core/src/classpath/gnu/gnu/classpath/debug/SystemLogger.java 2007-01-07 08:31:59 UTC (rev 3011) +++ trunk/core/src/classpath/gnu/gnu/classpath/debug/SystemLogger.java 2007-01-07 08:33:13 UTC (rev 3012) @@ -42,11 +42,12 @@ import java.security.AccessController; import java.util.StringTokenizer; +import java.util.logging.Level; import java.util.logging.Logger; -public final class SystemLogger +public final class SystemLogger extends Logger { - public static final Logger SYSTEM = Logger.getLogger ("gnu.classpath"); + public static final SystemLogger SYSTEM = new SystemLogger(); static { @@ -62,12 +63,40 @@ Component c = Component.forName (tok.nextToken ()); if (c != null) PreciseFilter.GLOBAL.enable (c); - SYSTEM.log (java.util.logging.Level.INFO, "enabled: {0}", c); + SYSTEM.log (Level.INFO, "enabled: {0}", c); } } + } - java.util.logging.Handler[] h = SYSTEM.getHandlers (); - for (int i = 0; i < h.length; i++) - System.out.println (h[i]); + /** + * Fetch the system logger instance. The logger returned is meant for debug + * and diagnostic logging for Classpath internals. + * + * @return The system logger. + */ + public static SystemLogger getSystemLogger() + { + // XXX Check some permission here? + return SYSTEM; } + + /** + * Keep only one instance of the system logger. + */ + private SystemLogger() + { + super("gnu.classpath", null); + } + + /** + * Variable-arguments log method. + * + * @param level The level to log to. + * @param format The format string. + * @param args The arguments. + */ + public void logv(Level level, String format, Object... args) + { + log(level, format, args); + } } Modified: trunk/core/src/classpath/gnu/gnu/java/awt/AWTUtilities.java =================================================================== --- trunk/core/src/classpath/gnu/gnu/java/awt/AWTUtilities.java 2007-01-07 08:31:59 UTC (rev 3011) +++ trunk/core/src/classpath/gnu/gnu/java/awt/AWTUtilities.java 2007-01-07 08:33:13 UTC (rev 3012) @@ -1,5 +1,5 @@ /* AWTUtilities.java -- Common utility methods for AWT and Swing. - Copyright (C) 2005 Free Software Foundation, Inc. + Copyright (C) 2005, 2007 Free Software Foundation, Inc. This file is part of GNU Classpath. @@ -47,6 +47,7 @@ import java.awt.Rectangle; import java.awt.Toolkit; import java.awt.Window; +import java.awt.event.KeyEvent; import java.awt.event.MouseEvent; import java.util.AbstractSequentialList; import java.util.List; @@ -694,4 +695,204 @@ { return java.awt.EventQueue.isDispatchThread(); } + + /** + * Returns whether the specified key code is valid. + */ + public static boolean isValidKey(int keyCode) + { + switch (keyCode) + { + case KeyEvent.VK_ENTER: + case KeyEvent.VK_BACK_SPACE: + case KeyEvent.VK_TAB: + case KeyEvent.VK_CANCEL: + case KeyEvent.VK_CLEAR: + case KeyEvent.VK_SHIFT: + case KeyEvent.VK_CONTROL: + case KeyEvent.VK_ALT: + case KeyEvent.VK_PAUSE: + case KeyEvent.VK_CAPS_LOCK: + case KeyEvent.VK_ESCAPE: + case KeyEvent.VK_SPACE: + case KeyEvent.VK_PAGE_UP: + case KeyEvent.VK_PAGE_DOWN: + case KeyEvent.VK_END: + case KeyEvent.VK_HOME: + case KeyEvent.VK_LEFT: + case KeyEvent.VK_UP: + case KeyEvent.VK_RIGHT: + case KeyEvent.VK_DOWN: + case KeyEvent.VK_COMMA: + case KeyEvent.VK_MINUS: + case KeyEvent.VK_PERIOD: + case KeyEvent.VK_SLASH: + case KeyEvent.VK_0: + case KeyEvent.VK_1: + case KeyEvent.VK_2: + case KeyEvent.VK_3: + case KeyEvent.VK_4: + case KeyEvent.VK_5: + case KeyEvent.VK_6: + case KeyEvent.VK_7: + case KeyEvent.VK_8: + case KeyEvent.VK_9: + case KeyEvent.VK_SEMICOLON: + case KeyEvent.VK_EQUALS: + case KeyEvent.VK_A: + case KeyEvent.VK_B: + case KeyEvent.VK_C: + case KeyEvent.VK_D: + case KeyEvent.VK_E: + case KeyEvent.VK_F: + case KeyEvent.VK_G: + case KeyEvent.VK_H: + case KeyEvent.VK_I: + case KeyEvent.VK_J: + case KeyEvent.VK_K: + case KeyEvent.VK_L: + case KeyEvent.VK_M: + case KeyEvent.VK_N: + case KeyEvent.VK_O: + case KeyEvent.VK_P: + case KeyEvent.VK_Q: + case KeyEvent.VK_R: + case KeyEvent.VK_S: + case KeyEvent.VK_T: + case KeyEvent.VK_U: + case KeyEvent.VK_V: + case KeyEvent.VK_W: + case KeyEvent.VK_X: + case KeyEvent.VK_Y: + case KeyEvent.VK_Z: + case KeyEvent.VK_OPEN_BRACKET: + case KeyEvent.VK_BACK_SLASH: + case KeyEvent.VK_CLOSE_BRACKET: + case KeyEvent.VK_NUMPAD0: + case KeyEvent.VK_NUMPAD1: + case KeyEvent.VK_NUMPAD2: + case KeyEvent.VK_NUMPAD3: + case KeyEvent.VK_NUMPAD4: + case KeyEvent.VK_NUMPAD5: + case KeyEvent.VK_NUMPAD6: + case KeyEvent.VK_NUMPAD7: + case KeyEvent.VK_NUMPAD8: + case KeyEvent.VK_NUMPAD9: + case KeyEvent.VK_MULTIPLY: + case KeyEvent.VK_ADD: + case KeyEvent.VK_SEPARATOR: + case KeyEvent.VK_SUBTRACT: + case KeyEvent.VK_DECIMAL: + case KeyEvent.VK_DIVIDE: + case KeyEvent.VK_DELETE: + case KeyEvent.VK_NUM_LOCK: + case KeyEvent.VK_SCROLL_LOCK: + case KeyEvent.VK_F1: + case KeyEvent.VK_F2: + case KeyEvent.VK_F3: + case KeyEvent.VK_F4: + case KeyEvent.VK_F5: + case KeyEvent.VK_F6: + case KeyEvent.VK_F7: + case KeyEvent.VK_F8: + case KeyEvent.VK_F9: + case KeyEvent.VK_F10: + case KeyEvent.VK_F11: + case KeyEvent.VK_F12: + case KeyEvent.VK_F13: + case KeyEvent.VK_F14: + case KeyEvent.VK_F15: + case KeyEvent.VK_F16: + case KeyEvent.VK_F17: + case KeyEvent.VK_F18: + case KeyEvent.VK_F19: + case KeyEvent.VK_F20: + case KeyEvent.VK_F21: + case KeyEvent.VK_F22: + case KeyEvent.VK_F23: + case KeyEvent.VK_F24: + case KeyEvent.VK_PRINTSCREEN: + case KeyEvent.VK_INSERT: + case KeyEvent.VK_HELP: + case KeyEvent.VK_META: + case KeyEvent.VK_BACK_QUOTE: + case KeyEvent.VK_QUOTE: + case KeyEvent.VK_KP_UP: + case KeyEvent.VK_KP_DOWN: + case KeyEvent.VK_KP_LEFT: + case KeyEvent.VK_KP_RIGHT: + case KeyEvent.VK_DEAD_GRAVE: + case KeyEvent.VK_DEAD_ACUTE: + case KeyEvent.VK_DEAD_CIRCUMFLEX: + case KeyEvent.VK_DEAD_TILDE: + case KeyEvent.VK_DEAD_MACRON: + case KeyEvent.VK_DEAD_BREVE: + case KeyEvent.VK_DEAD_ABOVEDOT: + case KeyEvent.VK_DEAD_DIAERESIS: + case KeyEvent.VK_DEAD_ABOVERING: + case KeyEvent.VK_DEAD_DOUBLEACUTE: + case KeyEvent.VK_DEAD_CARON: + case KeyEvent.VK_DEAD_CEDILLA: + case KeyEvent.VK_DEAD_OGONEK: + case KeyEvent.VK_DEAD_IOTA: + case KeyEvent.VK_DEAD_VOICED_SOUND: + case KeyEvent.VK_DEAD_SEMIVOICED_SOUND: + case KeyEvent.VK_AMPERSAND: + case KeyEvent.VK_ASTERISK: + case KeyEvent.VK_QUOTEDBL: + case KeyEvent.VK_LESS: + case KeyEvent.VK_GREATER: + case KeyEvent.VK_BRACELEFT: + case KeyEvent.VK_BRACERIGHT: + case KeyEvent.VK_AT: + case KeyEvent.VK_COLON: + case KeyEvent.VK_CIRCUMFLEX: + case KeyEvent.VK_DOLLAR: + case KeyEvent.VK_EURO_SIGN: + case KeyEvent.VK_EXCLAMATION_MARK: + case KeyEvent.VK_INVERTED_EXCLAMATION_MARK: + case KeyEvent.VK_LEFT_PARENTHESIS: + case KeyEvent.VK_NUMBER_SIGN: + case KeyEvent.VK_PLUS: + case KeyEvent.VK_RIGHT_PARENTHESIS: + case KeyEvent.VK_UNDERSCORE: + case KeyEvent.VK_FINAL: + case KeyEvent.VK_CONVERT: + case KeyEvent.VK_NONCONVERT: + case KeyEvent.VK_ACCEPT: + case KeyEvent.VK_MODECHANGE: + case KeyEvent.VK_KANA: + case KeyEvent.VK_KANJI: + case KeyEvent.VK_ALPHANUMERIC: + case KeyEvent.VK_KATAKANA: + case KeyEvent.VK_HIRAGANA: + case KeyEvent.VK_FULL_WIDTH: + case KeyEvent.VK_HALF_WIDTH: + case KeyEvent.VK_ROMAN_CHARACTERS: + case KeyEvent.VK_ALL_CANDIDATES: + case KeyEvent.VK_PREVIOUS_CANDIDATE: + case KeyEvent.VK_CODE_INPUT: + case KeyEvent.VK_JAPANESE_KATAKANA: + case KeyEvent.VK_JAPANESE_HIRAGANA: + case KeyEvent.VK_JAPANESE_ROMAN: + case KeyEvent.VK_KANA_LOCK: + case KeyEvent.VK_INPUT_METHOD_ON_OFF: + case KeyEvent.VK_CUT: + case KeyEvent.VK_COPY: + case KeyEvent.VK_PASTE: + case KeyEvent.VK_UNDO: + case KeyEvent.VK_AGAIN: + case KeyEvent.VK_FIND: + case KeyEvent.VK_PROPS: + case KeyEvent.VK_STOP: + case KeyEvent.VK_COMPOSE: + case KeyEvent.VK_ALT_GRAPH: + case KeyEvent.VK_BEGIN: + case KeyEvent.VK_CONTEXT_MENU: + case KeyEvent.VK_WINDOWS: + return true; + default: + return false; + } + } } Modified: trunk/core/src/classpath/gnu/gnu/java/beans/encoder/ScanEngine.java =================================================================== --- trunk/core/src/classpath/gnu/gnu/java/beans/encoder/ScanEngine.java 2007-01-07 08:31:59 UTC (rev 3011) +++ trunk/core/src/classpath/gnu/gnu/java/beans/encoder/ScanEngine.java 2007-01-07 08:33:13 UTC (rev 3012) @@ -153,7 +153,7 @@ writer = new StAXWriter(os); root = new Root(); - final ScannerState start = current = new GenericScannerState(root);; + final ScannerState start = current = new GenericScannerState(root); ScannerState conf; // Use the ReportingScannerState to debug serialization issues. Modified: trunk/core/src/classpath/gnu/gnu/java/locale/LocaleHelper.java =================================================================== --- trunk/core/src/classpath/gnu/gnu/java/locale/LocaleHelper.java 2007-01-07 08:31:59 UTC (rev 3011) +++ trunk/core/src/classpath/gnu/gnu/java/locale/LocaleHelper.java 2007-01-07 08:33:13 UTC (rev 3012) @@ -55,105 +55,44 @@ public class LocaleHelper { /** - * This method is used by the localized name lookup methods to retrieve - * the localized name of a particular piece of locale data. - * If the display name can not be localized to the supplied - * locale, it will fall back on other output in the following order: - * - * <ul> - * <li>the localized name in the default locale</li> - * <li>the localized name in English (optional)</li> - * <li>the localized name in the root locale bundle (optional)</li> - * <li>the localized input string</li> - * </ul> * <p> - * If the supplied key is merely the empty string, then the empty string is - * returned. + * This method is used by the localized name lookup methods to + * retrieve the next locale to try. The next locale is derived + * from the supplied locale by applying the first applicable + * rule from the following: * </p> + * <ol> + * <li>If the variant contains a <code>'_'</code>, then + * this and everything following it is trimmed.</li> + * <li>If the variant is non-empty, it is converted to + * an empty string.</li> + * <li>If the country is non-empty, it is converted to + * an empty string.</li> + * <li>If the language is non-empty, it is converted to + * an empty string (forming {@link java.util.Locale#ROOT})</li> + * </ol> + * <p> + * The base fallback locale is {@link java.util.Locale#ROOT}. + * </p> * - * @param inLocale the locale to use for formatting the display string. - * @param key the locale data used as a key to the localized lookup tables. - * @param name the name of the hashtable containing the localized data. - * @param checkEnglish true if the method should fall back on data - * from the English locale. - * @param checkRoot true if the method should fall back on data from the - * unlocalized root locale. - * @return a <code>String</code>, hopefully containing the localized - * variant of the input data. - * @throws NullPointerException if <code>inLocale</code> is null. + * @param locale the locale for which a localized piece of + * data could not be obtained. + * @return the next fallback locale to try. */ - public static String getLocalizedString(Locale inLocale, String key, - String name, boolean checkEnglish, - boolean checkRoot) - { - String localizedString; - String property; - - if (key.equals("")) - return ""; - property = name + "." + key; - /* Localize to inLocale */ - try + public static Locale getFallbackLocale(Locale locale) { - localizedString = - ResourceBundle.getBundle("gnu.java.locale.LocaleInformation", - inLocale).getString(property); - } - catch (MissingResourceException exception) - { - localizedString = null; - } - /* Localize to default locale */ - if (localizedString == null) - { - try - { - ResourceBundle bundle; - - bundle = - ResourceBundle.getBundle("gnu.java.locale.LocaleInformation"); - localizedString = bundle.getString(property); - } - catch (MissingResourceException exception) - { - localizedString = null; - } - } - /* Localize to English */ - if (localizedString == null && checkEnglish) - { - try - { - localizedString = - ResourceBundle.getBundle("gnu.java.locale.LocaleInformation", - Locale.ENGLISH).getString(property); - } - catch (MissingResourceException exception) - { - localizedString = null; - } - } - /* Return unlocalized version */ - if (localizedString == null && checkRoot) - { - try - { - localizedString = - ResourceBundle.getBundle("gnu.java.locale.LocaleInformation", - new Locale("","","") - ).getString(property); - } - catch (MissingResourceException exception) - { - localizedString = null; - } - } - /* Return original input string */ - if (localizedString == null) - { - localizedString = key; - } - return localizedString; + String language = locale.getLanguage(); + String country = locale.getCountry(); + String variant = locale.getVariant(); + int uscore = variant.indexOf('_'); + if (uscore != -1) + return new Locale(language, country, + variant.substring(0, uscore)); + if (!variant.isEmpty()) + return new Locale(language, country, ""); + if (!country.isEmpty()) + return new Locale(language, "", ""); + return Locale.ROOT; } /** Modified: trunk/core/src/classpath/gnu/gnu/java/util/DoubleEnumeration.java =================================================================== --- trunk/core/src/classpath/gnu/gnu/java/util/DoubleEnumeration.java 2007-01-07 08:31:59 UTC (rev 3011) +++ trunk/core/src/classpath/gnu/gnu/java/util/DoubleEnumeration.java 2007-01-07 08:33:13 UTC (rev 3012) @@ -1,5 +1,5 @@ /* gnu.java.util.DoubleEnumeration - Copyright (C) 1998, 1999, 2001 Free Software Foundation, Inc. + Copyright (C) 1998, 1999, 2001, 2004 Free Software Foundation, Inc. This file is part of GNU Classpath. @@ -63,7 +63,7 @@ * @author Jochen Hoenicke * @author Mark Wielaard (ma...@kl...) */ -public class DoubleEnumeration implements Enumeration +public class DoubleEnumeration<T> implements Enumeration<T> { /** * This is true as long as one of the enumerations has more @@ -82,17 +82,17 @@ /** * The first enumeration. */ - private Enumeration e1; + private Enumeration<T> e1; /** * The second enumeration. */ - private Enumeration e2; + 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 e1, Enumeration e2) + public DoubleEnumeration(Enumeration<T> e1, Enumeration<T> e2) { this.e1 = e1; this.e2 = e2; @@ -126,7 +126,7 @@ * element of the second enumeration. If both enumeration don't have * any elements it throws a <code>NoSuchElementException</code>. */ - public Object nextElement() + public T nextElement() { if (!hasMoreElements()) throw new NoSuchElementException(); Modified: trunk/core/src/classpath/gnu/gnu/java/util/prefs/EventDispatcher.java =================================================================== --- trunk/core/src/classpath/gnu/gnu/java/util/prefs/EventDispatcher.java 2007-01-07 08:31:59 UTC (rev 3011) +++ trunk/core/src/classpath/gnu/gnu/java/util/prefs/EventDispatcher.java 2007-01-07 08:33:13 UTC (rev 3012) @@ -53,7 +53,7 @@ // This is a queue of events to dispatch. This thread waits on // the queue and when notified will remove events until the queue // is empty. - private static final ArrayList queue = new ArrayList(); + private static final ArrayList<Runnable> queue = new ArrayList<Runnable>(); // FIXME: this thread probably ought to go in some classpath-internal // ThreadGroup. But we don't have that yet. @@ -81,7 +81,7 @@ // Ignore. } } - r = (Runnable) queue.remove(0); + r = queue.remove(0); } // Invoke outside the synchronization, so that // we aren't blocking other threads from posting events. Modified: trunk/core/src/classpath/gnu/gnu/java/util/prefs/MemoryBasedPreferences.java =================================================================== --- trunk/core/src/classpath/gnu/gnu/java/util/prefs/MemoryBasedPreferences.java 2007-01-07 08:31:59 UTC (rev 3011) +++ trunk/core/src/classpath/gnu/gnu/java/util/prefs/MemoryBasedPreferences.java 2007-01-07 08:33:13 UTC (rev 3012) @@ -52,7 +52,7 @@ private final boolean isUser; /** Contains all the preference entries of this node. */ - private HashMap entries = new HashMap(); + private HashMap<String, String> entries = new HashMap<String, String>(); /** * Creates a new preferences node with the given name and parent. @@ -98,7 +98,7 @@ * this node. */ protected String[] keysSpi() throws BackingStoreException { - return (String[]) entries.keySet().toArray(new String[entries.size()]); + return entries.keySet().toArray(new String[entries.size()]); } /** @@ -106,7 +106,7 @@ * null when the key has not been set. */ protected String getSpi(String key) { - return (String) entries.get(key); + return entries.get(key); } /** Modified: trunk/core/src/classpath/gnu/gnu/javax/imageio/png/PNGICCProfile.java =================================================================== --- trunk/core/src/classpath/gnu/gnu/javax/imageio/png/PNGICCProfile.java 2007-01-07 08:31:59 UTC (rev 3011) +++ trunk/core/src/classpath/gnu/gnu/javax/imageio/png/PNGICCProfile.java 2007-01-07 08:33:13 UTC (rev 3012) @@ -61,7 +61,9 @@ { super( type, data, crc ); int i = 0; - while( data[i++] != 0 ); + while( data[i++] != 0 ) + ; + try { name = new String(data, 0, i, "8859_1"); Modified: trunk/core/src/classpath/gnu/gnu/javax/rmi/CORBA/UtilDelegateImpl.java =================================================================== --- trunk/core/src/classpath/gnu/gnu/javax/rmi/CORBA/UtilDelegateImpl.java 2007-01-07 08:31:59 UTC (rev 3011) +++ trunk/core/src/classpath/gnu/gnu/javax/rmi/CORBA/UtilDelegateImpl.java 2007-01-07 08:33:13 UTC (rev 3012) @@ -1,5 +1,5 @@ /* UtilDelegateImpl.java -- - Copyright (C) 2002, 2005 Free Software Foundation, Inc. + Copyright (C) 2002, 2005, 2006 Free Software Foundation, Inc. This file is part of GNU Classpath. @@ -38,6 +38,8 @@ package gnu.javax.rmi.CORBA; +import gnu.classpath.VMStackWalker; + import gnu.CORBA.Minor; import gnu.CORBA.ObjectCreator; import gnu.CORBA.Poa.ORB_1_4; @@ -70,6 +72,7 @@ import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; +import java.net.MalformedURLException; import java.rmi.AccessException; import java.rmi.MarshalException; import java.rmi.NoSuchObjectException; @@ -374,37 +377,24 @@ throws ClassNotFoundException { if (loader == null) - loader = Thread.currentThread().getContextClassLoader(); + loader = VMStackWalker.firstNonNullClassLoader(); String p_useCodebaseOnly = System.getProperty("java.rmi.server.useCodebaseOnly"); boolean useCodebaseOnly = p_useCodebaseOnly != null && p_useCodebaseOnly.trim().equalsIgnoreCase("true"); - try - { - if (remoteCodebase != null && !useCodebaseOnly) - return RMIClassLoader.loadClass(remoteCodebase, className); - } - catch (Exception e) - { - // This failed but try others. - } + if (useCodebaseOnly) + remoteCodebase = null; try { - if (remoteCodebase == null || useCodebaseOnly) - return RMIClassLoader.loadClass(remoteCodebase, className); + return RMIClassLoader.loadClass(remoteCodebase, className, loader); } - catch (Exception e) + catch (MalformedURLException x) { - // This failed but try others. + throw new ClassNotFoundException(className, x); } - - if (loader != null) - return Class.forName(className, true, loader); - - throw new ClassNotFoundException(className + " at " + remoteCodebase); } /** Modified: trunk/core/src/classpath/gnu/gnu/javax/security/auth/login/ConfigFileParser.java =================================================================== --- trunk/core/src/classpath/gnu/gnu/javax/security/auth/login/ConfigFileParser.java 2007-01-07 08:31:59 UTC (rev 3011) +++ trunk/core/src/classpath/gnu/gnu/javax/security/auth/login/ConfigFileParser.java 2007-01-07 08:33:13 UTC (rev 3012) @@ -122,7 +122,9 @@ initParser(r); while (parseAppOrOtherEntry()) - ; // do nothing + { + /* do nothing */ + } } private void initParser(Reader r) throws IOException @@ -157,7 +159,9 @@ List lmis = new ArrayList(); while (parseACE(lmis)) - ; // do nothing + { + /* do nothing */ + } c = cft.nextToken(); if (c != '}') Modified: trunk/core/src/classpath/gnu/gnu/javax/swing/text/html/css/CSSParser.java =================================================================== --- trunk/core/src/classpath/gnu/gnu/javax/swing/text/html/css/CSSParser.java 2007-01-07 08:31:59 UTC (rev 3011) +++ trunk/core/src/classpath/gnu/gnu/javax/swing/text/html/css/CSSParser.java 2007-01-07 08:33:13 UTC (rev 3012) @@ -308,7 +308,9 @@ { // FIXME: Handle block and ATKEYWORD. boolean success = parseAny(s); - while (parseAny(s)); + while (parseAny(s)) + ; + return success; } @@ -329,7 +331,8 @@ boolean ret = parseAny(sel); if (ret) { - while (parseAny(sel)); + while (parseAny(sel)) + ; } return ret; } Modified: trunk/core/src/classpath/gnu/gnu/javax/swing/text/html/parser/gnuDTD.java =================================================================== --- trunk/core/src/classpath/gnu/gnu/javax/swing/text/html/parser/gnuDTD.java 2007-01-07 08:31:59 UTC (rev 3011) +++ trunk/core/src/classpath/gnu/gnu/javax/swing/text/html/parser/gnuDTD.java 2007-01-07 08:33:13 UTC (rev 3012) @@ -390,7 +390,6 @@ allowed.add(allowed_values [ i ]); } } - ; AttributeList attr = new AttributeList(name, type, modifier, default_value, allowed, null); Modified: trunk/core/src/classpath/gnu/gnu/javax/swing/text/html/parser/support/Parser.java =================================================================== --- trunk/core/src/classpath/gnu/gnu/javax/swing/text/html/parser/support/Parser.java 2007-01-07 08:31:59 UTC (rev 3011) +++ trunk/core/src/classpath/gnu/gnu/javax/swing/text/html/parser/support/Parser.java 2007-01-07 08:33:13 UTC (rev 3012) @@ -56,6 +56,7 @@ import java.util.Vector; import javax.swing.text.ChangedCharSetException; +import javax.swing.text.SimpleAttributeSet; import javax.swing.text.html.HTML; import javax.swing.text.html.parser.AttributeList; import javax.swing.text.html.parser.DTD; @@ -250,9 +251,9 @@ * Get the attributes of the current tag. * @return The attribute set, representing the attributes of the current tag. */ - public htmlAttributeSet getAttributes() + public SimpleAttributeSet getAttributes() { - return attributes; + return new SimpleAttributeSet(attributes); } /** @@ -497,6 +498,9 @@ mustBe(t.kind); } hTag = new Token(start, last); + + // Consume any whitespace immediately following a comment. + optional(WS); handleComment(); } @@ -579,6 +583,8 @@ ); } } + // Consume any whitespace that follows the Sgml insertion. + optional(WS); } /** @@ -658,7 +664,10 @@ else text = textProcessor.preprocess(buffer); - if (text != null && text.length > 0) + if (text != null && text.length > 0 + // According to the specs we need to discard whitespace immediately + // before a closing tag. + && (text.length > 1 || text[0] != ' ' || ! TAG_CLOSE.matches(this))) { TagElement pcdata = new TagElement(dtd.getElement("#pcdata")); attributes = htmlAttributeSet.EMPTY_HTML_ATTRIBUTE_SET; @@ -889,6 +898,8 @@ protected void parseDocument() throws ParseException { + // Read up any initial whitespace. + optional(WS); while (getTokenAhead().kind != EOF) { advanced = false; @@ -979,13 +990,15 @@ + next.getImage() + "'"); attrValue = value.getImage(); } - else if (next.kind == SLASH) - // The slash in this context is treated as the ordinary - // character, not as a token. The slash may be part of + else if (next.kind == SLASH || next.kind == OTHER) + // The slash and other characters (like %) in this context is + // treated as the ordinary + // character, not as a token. The character may be part of // the unquoted URL. { StringBuffer image = new StringBuffer(value.getImage()); - while (next.kind == NUMTOKEN || next.kind == SLASH) + while (next.kind == NUMTOKEN || next.kind == SLASH + || next.kind == OTHER) { image.append(getNextToken().getImage()); next = getTokenAhead(); @@ -1177,6 +1190,13 @@ { validator.validateTag(tag, attributes); handleEmptyTag(tag); + HTML.Tag h = tag.getHTMLTag(); + // When a block tag is closed, consume whitespace that follows after + // it. + // For some unknown reason a FRAME tag is not treated as block element. + // However in this case it should be treated as such. + if (isBlock(h)) + optional(WS); } catch (ChangedCharSetException ex) { @@ -1192,7 +1212,7 @@ */ private void _handleEndTag(TagElement tag) { - validator.closeTag(tag); + if (validator.closeTag(tag)) _handleEndTag_remaining(tag); } @@ -1213,6 +1233,11 @@ if (preformatted < 0) preformatted = 0; + // When a block tag is closed, consume whitespace that follows after + // it. + if (isBlock(h)) + optional(WS); + if (h == HTML.Tag.TITLE) { titleOpen = false; @@ -1239,6 +1264,9 @@ HTML.Tag h = tag.getHTMLTag(); + if (isBlock(h)) + optional(WS); + if (h.isPreformatted()) preformatted++; @@ -1354,7 +1382,7 @@ if (c == '\r') buffer.append(' '); // CR replaced by space else if (c == '\n') - ; // LF ignored + { /* LF ignored */ } else if (c == '\t') buffer.append(' '); // Tab replaced by space else @@ -1418,8 +1446,6 @@ hTag = new Token(start, next); - attributes.setResolveParent(defaulter.getDefaultParameters(name.getImage())); - if (!end) { // The tag body contains errors. If additionally the tag @@ -1457,9 +1483,14 @@ if (te.getElement().type == DTDConstants.EMPTY) _handleEmptyTag(te); else + { + // According to the specs we need to consume whitespace following + // immediately after a opening tag. + optional(WS); _handleStartTag(te); } } + } /** * This should fire additional actions in response to the @@ -1483,4 +1514,19 @@ { error("Whitespace here is not permitted"); } + + /** + * Returns true when the specified tag should be considered a block tag + * wrt whitespace handling. We need this special handling, since there + * are a couple of tags that we must treat as block tags but which aren't + * officially block tags. + * + * @param tag the tag to check + * @return true when the specified tag should be considered a block tag + * wrt whitespace handling + */ + private boolean isBlock(HTML.Tag tag) + { + return tag.isBlock() || tag == HTML.Tag.STYLE || tag == HTML.Tag.FRAME; + } } Modified: trunk/core/src/classpath/gnu/gnu/javax/swing/text/html/parser/support/low/Constants.java =================================================================== --- trunk/core/src/classpath/gnu/gnu/javax/swing/text/html/parser/support/low/Constants.java 2007-01-07 08:31:59 UTC (rev 3011) +++ trunk/core/src/classpath/gnu/gnu/javax/swing/text/html/parser/support/low/Constants.java 2007-01-07 08:33:13 UTC (rev 3012) @@ -209,6 +209,17 @@ } ); + /** + * Ordinary HTML tag closing pattern. + */ + public static final pattern TAG_CLOSE = + new pattern(new node[] + { + new node(BEGIN), new node(WS, true), new node(SLASH), + new node(WS, true), new node(NUMTOKEN) + } + ); + /* Special tokens */ /** Modified: trunk/core/src/classpath/gnu/gnu/javax/swing/text/html/parser/support/textPreProcessor.java =================================================================== --- trunk/core/src/classpath/gnu/gnu/javax/swing/text/html/parser/support/textPreProcessor.java 2007-01-07 08:31:59 UTC (rev 3011) +++ trunk/core/src/classpath/gnu/gnu/javax/swing/text/html/parser/support/textPreProcessor.java 2007-01-07 08:33:13 UTC (rev 3012) @@ -42,17 +42,17 @@ /** * Pre - processes text in text parts of the html document. - * Not thread - safe. + * * @author Audrius Meskauskas, Lithuania (Aud...@Bi...) */ public class textPreProcessor { /** - * Pre - process non-preformatted text. - * \t, \r and \n mutate into spaces, then multiple spaces mutate - * into single one, all whitespace around tags is consumed. - * The content of the passed buffer is destroyed. - * @param text A text to pre-process. + * Pre - process non-preformatted text. \t, \r and \n mutate into spaces, then + * multiple spaces mutate into single one, all whitespace around tags is + * consumed. The content of the passed buffer is destroyed. + * + * @param a_text A text to pre-process. */ public char[] preprocess(StringBuffer a_text) { @@ -64,18 +64,15 @@ int a = 0; int b = text.length - 1; - try - { - while (Constants.bWHITESPACE.get(text [ a ])) + // Remove leading/trailing whitespace, leaving at most one character + int len = text.length; + while (a + 1 < len && Constants.bWHITESPACE.get(text[a]) + && Constants.bWHITESPACE.get(text[a + 1])) a++; - while (Constants.bWHITESPACE.get(text [ b ])) + + while (b > a && Constants.bWHITESPACE.get(text[b]) + && Constants.bWHITESPACE.get(text[b - 1])) b--; - } - catch (ArrayIndexOutOfBoundsException sx) - { - // A text fragment, consisting from line breaks only. - return null; - } a_text.setLength(0); @@ -83,10 +80,9 @@ boolean spaceNow; char c; - chars: - for (int i = a; i <= b; i++) + chars: for (int i = a; i <= b; i++) { - c = text [ i ]; + c = text[i]; spaceNow = Constants.bWHITESPACE.get(c); if (spacesWere && spaceNow) continue chars; Modified: trunk/core/src/classpath/gnu/gnu/xml/dom/DomAttr.java =================================================================== --- trunk/core/src/classpath/gnu/gnu/xml/dom/DomAttr.java 2007-01-07 08:31:59 UTC (rev 3011) +++ trunk/core/src/classpath/gnu/gnu/xml/dom/DomAttr.java 2007-01-07 08:33:13 UTC (rev 3012) @@ -316,7 +316,7 @@ private void mutating(String oldValue, String newValue, short why) { - if (!reportMutations || parent == null) + if (!reportMutations || parent == null || equal(newValue, oldValue)) { return; } Modified: trunk/core/src/classpath/gnu/gnu/xml/dom/DomNode.java =================================================================== --- trunk/core/src/classpath/gnu/gnu/xml/dom/DomNode.java 2007-01-07 08:31:59 UTC (rev 3011) +++ trunk/core/src/classpath/gnu/gnu/xml/dom/DomNode.java 2007-01-07 08:33:13 UTC (rev 3012) @@ -668,6 +668,7 @@ { insertionEvent(null, child); } + length++; } return child; @@ -1561,7 +1562,7 @@ // Climb to the top of this subtree and handle capture, letting // each node (from the top down) capture until one stops it or // until we get to this one. - current = parent; + current = (parent == null) ? this : parent; if (current.depth >= ANCESTORS_INIT) { DomNode[] newants = new DomNode[current.depth + 1]; Modified: trunk/core/src/classpath/gnu/gnu/xml/dom/ls/SAXEventSink.java =================================================================== --- trunk/core/src/classpath/gnu/gnu/xml/dom/ls/SAXEventSink.java 2007-01-07 08:31:59 UTC (rev 3011) +++ trunk/core/src/classpath/gnu/gnu/xml/dom/ls/SAXEventSink.java 2007-01-07 08:33:13 UTC (rev 3012) @@ -43,6 +43,7 @@ import java.util.List; import javax.xml.XMLConstants; import org.w3c.dom.Attr; +import org.w3c.dom.Document; import org.w3c.dom.DocumentType; import org.w3c.dom.Element; import org.w3c.dom.Entity; @@ -72,7 +73,7 @@ * * @author <a href='mailto:do...@gn...'>Chris Burdess</a> */ -class SAXEventSink +public class SAXEventSink implements ContentHandler, LexicalHandler, DTDHandler, DeclHandler { @@ -110,6 +111,11 @@ interrupted = true; } + protected Document getDocument() + { + return doc; + } + // -- ContentHandler2 -- public void setDocumentLocator(Locator locator) Modified: trunk/core/src/classpath/gnu/gnu/xml/pipeline/DomConsumer.java =================================================================== --- trunk/core/src/classpath/gnu/gnu/xml/pipeline/DomConsumer.java 2007-01-07 08:31:59 UTC (rev 3011) +++ trunk/core/src/classpath/gnu/gnu/xml/pipeline/DomConsumer.java 2007-01-07 08:33:13 UTC (rev 3012) @@ -365,7 +365,7 @@ throws SAXException { SAXParseException e; - ErrorHandler errHandler = consumer.getErrorHandler ();; + ErrorHandler errHandler = consumer.getErrorHandler (); if (locator == null) e = new SAXParseException (message, null, null, -1, -1, x); Modified: trunk/core/src/classpath/gnu/gnu/xml/stream/SAXParser.java =================================================================== --- trunk/core/src/classpath/gnu/gnu/xml/stream/SAXParser.java 2007-01-07 08:31:59 UTC (rev 3011) +++ trunk/core/src/classpath/gnu/gnu/xml/stream/SAXParser.java 2007-01-07 08:33:13 UTC (rev 3012) @@ -1021,9 +1021,18 @@ SAXParser parser = new SAXParser(validating, namespaceAware, xIncludeAware); InputSource input = new InputSource(args[pos]); + java.io.FileReader fr = new java.io.FileReader(args[pos]); + input.setCharacterStream(fr); + try + { XMLReader reader = parser.getXMLReader(); reader.setContentHandler(handler); reader.parse(input); + } + finally + { + fr.close(); + } pos++; } } Modified: trunk/core/src/classpath/gnu/gnu/xml/stream/XMLStreamWriterImpl.java =================================================================== --- trunk/core/src/classpath/gnu/gnu/xml/stream/XMLStreamWriterImpl.java 2007-01-07 08:31:59 UTC (rev 3011) +++ trunk/core/src/classpath/gnu/gnu/xml/stream/XMLStreamWriterImpl.java 2007-01-07 08:33:13 UTC (rev 3012) @@ -664,12 +664,10 @@ public void writeDTD(String dtd) throws XMLStreamException { - // Really thoroughly pointless method... try { - if (!isName(dtd)) - throw new IllegalArgumentException("illegal Name: " + dtd); - + // XXX: Should we parse the doctypedecl at this point to ensure + // wellformedness? writer.write("<!DOCTYPE "); writer.write(dtd); writer.write('>'); Added: trunk/core/src/classpath/gnu/gnu/xml/transform/SAXTemplatesHandler.java =================================================================== --- trunk/core/src/classpath/gnu/gnu/xml/transform/SAXTemplatesHandler.java (rev 0) +++ trunk/core/src/classpath/gnu/gnu/xml/transform/SAXTemplatesHandler.java 2007-01-07 08:33:13 UTC (rev 3012) @@ -0,0 +1,97 @@ +/* SAXTemplatesHandler.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.xml.transform; + +import javax.xml.transform.Templates; +import javax.xml.transform.TransformerConfigurationException; +import javax.xml.transform.dom.DOMSource; +import javax.xml.transform.sax.TemplatesHandler; +import org.w3c.dom.Document; +import gnu.xml.dom.ls.SAXEventSink; + +/** + * A content handler that acts as a sink for SAX parse events, + * constructing an XSL stylesheet. + * Internally, this class simply creates a DOM tree from the events, + * and then parses the DOM into a Templates object. + * + * @author Chris Burdess (do...@gn...) + */ +class SAXTemplatesHandler + extends SAXEventSink + implements TemplatesHandler +{ + + final TransformerFactoryImpl factory; + String systemId; + + SAXTemplatesHandler(TransformerFactoryImpl factory) + { + this.factory = factory; + } + + public String getSystemId() + { + return systemId; + } + + public void setSystemId(String systemId) + { + this.systemId = systemId; + } + + public Templates getTemplates() + { + Document doc = getDocument(); + if (doc == null) + throw new IllegalStateException("Parsing of stylesheet incomplete"); + DOMSource ds = new DOMSource(doc, systemId); + try + { + return factory.newTemplates(ds); + } + catch (TransformerConfigurationException e) + { + String msg = "Unable to construct templates from this event stream"; + IllegalStateException e2 = new IllegalStateException(msg); + e2.initCause(e); + throw e2; + } + } + +} Added: trunk/core/src/classpath/gnu/gnu/xml/transform/SAXTransformerHandler.java =================================================================== --- trunk/core/src/classpath/gnu/gnu/xml/transform/SAXTransformerHandler.java (rev 0) +++ trunk/core/src/classpath/gnu/gnu/xml/transform/SAXTransformerHandler.java 2007-01-07 08:33:13 UTC (rev 3012) @@ -0,0 +1,111 @@ +/* SAXTransformerHandler.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.xml.transform; + +import javax.xml.transform.Result; +import javax.xml.transform.Transformer; +import javax.xml.transform.TransformerException; +import javax.xml.transform.dom.DOMSource; +import javax.xml.transform.sax.TransformerHandler; +import org.w3c.dom.Document; +import org.xml.sax.SAXException; +import gnu.xml.dom.ls.SAXEventSink; + +/** + * A SAX event sink that processes an XML source represented as a stream of + * SAX events into a result tree. + * This works by simply buffering all the events into a DOM tree and then + * using this DOM tree as the source of the transformation. + * + * @author Chris Burdess (do...@gn...) + */ +class SAXTransformerHandler + extends SAXEventSink + implements TransformerHandler +{ + + final TransformerFactoryImpl factory; + final Transformer transformer; + String systemId; + Result result; + + SAXTransformerHandler(TransformerFactoryImpl factory, Transformer transformer) + { + this.factory = factory; + this.transformer = transformer; + } + + public String getSystemId() + { + return systemId; + } + + public void setSystemId(String systemId) + { + this.systemId = systemId; + } + + public Transformer getTransformer() + { + return transformer; + } + + public void setResult(Result result) + { + this.result = result; + } + + public void endDocument() + throws SAXException + { + super.endDocument(); + try + { + Document doc = getDocument(); + DOMSource ds = new DOMSource(doc, systemId); + transformer.transform(ds, result); + } + catch (TransformerException e) + { + SAXException e2 = new SAXException(e.getMessage()); + e2.initCause(e); + throw e2; + } + } + +} Modified: trunk/core/src/classpath/gnu/gnu/xml/transform/StreamSerializer.java =================================================================== --- trunk/core/src/classpath/gnu/gnu/xml/transform/StreamSerializer.java 2007-01-07 08:31:59 UTC (rev 3011) +++ trunk/core/src/classpath/gnu/gnu/xml/transform/StreamSerializer.java 2007-01-07 08:33:13 UTC (rev 3012) @@ -324,7 +324,8 @@ break; case Node.TEXT_NODE: value = node.getNodeValue(); - if (!"yes".equals(node.getUserData("disable-output-escaping"))) + if (!"yes".equals(node.getUserData("disable-output-escaping")) && + mode != Stylesheet.OUTPUT_TEXT) value = encode(value, false, false); out.write(encodeText(value)); break; Modified: trunk/core/src/classpath/gnu/gnu/xml/transform/TransformerFactoryImpl.java =================================================================== --- trunk/core/src/classpath/gnu/gnu/xml/transform/TransformerFactoryImpl.java 2007-01-07 08:31:59 UTC (rev 3011) +++ trunk/core/src/classpath/gnu/gnu/xml/transform/TransformerFactoryImpl.java 2007-01-07 08:33:13 UTC (rev 3012) @@ -60,11 +60,15 @@ import javax.xml.transform.dom.DOMSource; import javax.xml.transform.sax.SAXResult; import javax.xml.transform.sax.SAXSource; +import javax.xml.transform.sax.SAXTransformerFactory; +import javax.xml.transform.sax.TemplatesHandler; +import javax.xml.transform.sax.TransformerHandler; import javax.xml.transform.stream.StreamResult; import javax.xml.transform.stream.StreamSource; import javax.xml.xpath.XPathFactory; import org.w3c.dom.Document; import org.w3c.dom.Node; +import org.xml.sax.XMLFilter; import gnu.xml.dom.DomDocument; /** @@ -73,7 +77,7 @@ * @author <a href='mailto:do...@gn...'>Chris Burdess</a> */ public class TransformerFactoryImpl - extends TransformerFactory + extends SAXTransformerFactory { final XPathFactory xpathFactory; @@ -316,7 +320,8 @@ StreamSource.FEATURE.equals(name) || StreamResult.FEATURE.equals(name) || DOMSource.FEATURE.equals(name) || - DOMResult.FEATURE.equals(name)) + DOMResult.FEATURE.equals(name) || + SAXTransformerFactory.FEATURE.equals(name)) { return true; } @@ -346,6 +351,49 @@ return userListener; } + // -- SAXTransformerFactory -- + + public TemplatesHandler newTemplatesHandler() + throws TransformerConfigurationException + { + return new SAXTemplatesHandler(this); + } + + public TransformerHandler newTransformerHandler() + throws TransformerConfigurationException + { + Transformer transformer = newTransformer(); + return new SAXTransformerHandler(this, transformer); + } + + public TransformerHandler newTransformerHandler(Source source) + throws TransformerConfigurationException + { + Transformer transformer = newTransformer(source); + return new SAXTransformerHandler(this, transformer); + } + + public TransformerHandler newTransformerHandler(Templates templates) + throws TransformerConfigurationException + { + Transformer transformer = templates.newTransformer(); + return new SAXTransformerHandler(this, transformer); + } + + public XMLFilter newXMLFilter(Source source) + throws TransformerConfigurationException + { + throw new UnsupportedOperationException(); + } + + public XMLFilter newXMLFilter(Templates templates) + throws TransformerConfigurationException + { + throw new UnsupportedOperationException(); + } + + // -- SAXTransformerFactory end -- + /** * Syntax: TransformerFactoryImpl [<stylesheet> [<input> [<output>]]] */ Modified: trunk/core/src/classpath/gnu/gnu/xml/transform/TransformerImpl.java =================================================================== --- trunk/core/src/classpath/gnu/gnu/xml/transform/TransformerImpl.java 2007-01-07 08:31:59 UT... [truncated message content] |
From: <ls...@us...> - 2007-01-07 08:32:01
|
Revision: 3011 http://jnode.svn.sourceforge.net/jnode/?rev=3011&view=rev Author: lsantha Date: 2007-01-07 00:31:59 -0800 (Sun, 07 Jan 2007) Log Message: ----------- Classpath patches. Modified Paths: -------------- trunk/core/src/classpath/java/java/applet/AppletContext.java trunk/core/src/classpath/java/java/beans/BeanDescriptor.java trunk/core/src/classpath/java/java/beans/Beans.java trunk/core/src/classpath/java/java/beans/DefaultPersistenceDelegate.java trunk/core/src/classpath/java/java/beans/DesignMode.java trunk/core/src/classpath/java/java/beans/Encoder.java trunk/core/src/classpath/java/java/beans/EventHandler.java trunk/core/src/classpath/java/java/beans/EventSetDescriptor.java trunk/core/src/classpath/java/java/beans/FeatureDescriptor.java trunk/core/src/classpath/java/java/beans/IndexedPropertyDescriptor.java trunk/core/src/classpath/java/java/beans/Introspector.java trunk/core/src/classpath/java/java/beans/PersistenceDelegate.java trunk/core/src/classpath/java/java/beans/PropertyDescriptor.java trunk/core/src/classpath/java/java/beans/PropertyEditorManager.java trunk/core/src/classpath/java/java/beans/SimpleBeanInfo.java trunk/core/src/classpath/java/java/beans/Statement.java trunk/core/src/classpath/java/java/beans/XMLEncoder.java trunk/core/src/classpath/java/java/beans/beancontext/BeanContextServicesSupport.java trunk/core/src/classpath/java/java/beans/beancontext/BeanContextSupport.java trunk/core/src/classpath/java/java/lang/Math.java trunk/core/src/classpath/java/java/lang/String.java trunk/core/src/classpath/java/java/lang/instrument/ClassDefinition.java trunk/core/src/classpath/java/java/lang/instrument/ClassFileTransformer.java trunk/core/src/classpath/java/java/lang/ref/Reference.java trunk/core/src/classpath/java/java/lang/ref/ReferenceQueue.java trunk/core/src/classpath/java/java/sql/Array.java trunk/core/src/classpath/java/java/sql/CallableStatement.java trunk/core/src/classpath/java/java/sql/Connection.java trunk/core/src/classpath/java/java/sql/DriverManager.java trunk/core/src/classpath/java/java/sql/Ref.java trunk/core/src/classpath/java/java/sql/ResultSet.java trunk/core/src/classpath/java/java/sql/Struct.java trunk/core/src/classpath/java/java/sql/Timestamp.java trunk/core/src/classpath/java/java/text/AttributedCharacterIterator.java trunk/core/src/classpath/java/java/text/AttributedString.java trunk/core/src/classpath/java/java/text/AttributedStringIterator.java trunk/core/src/classpath/java/java/text/Bidi.java trunk/core/src/classpath/java/java/text/BreakIterator.java trunk/core/src/classpath/java/java/text/CollationKey.java trunk/core/src/classpath/java/java/text/Collator.java trunk/core/src/classpath/java/java/text/DateFormatSymbols.java trunk/core/src/classpath/java/java/text/DecimalFormat.java trunk/core/src/classpath/java/java/text/DecimalFormatSymbols.java trunk/core/src/classpath/java/java/text/MessageFormat.java trunk/core/src/classpath/java/java/text/NumberFormat.java trunk/core/src/classpath/java/java/util/AbstractCollection.java trunk/core/src/classpath/java/java/util/AbstractMap.java trunk/core/src/classpath/java/java/util/Arrays.java trunk/core/src/classpath/java/java/util/Calendar.java trunk/core/src/classpath/java/java/util/Collections.java trunk/core/src/classpath/java/java/util/Currency.java trunk/core/src/classpath/java/java/util/Date.java trunk/core/src/classpath/java/java/util/Formatter.java trunk/core/src/classpath/java/java/util/IdentityHashMap.java trunk/core/src/classpath/java/java/util/LinkedList.java trunk/core/src/classpath/java/java/util/ListResourceBundle.java trunk/core/src/classpath/java/java/util/Locale.java trunk/core/src/classpath/java/java/util/PriorityQueue.java trunk/core/src/classpath/java/java/util/PropertyResourceBundle.java trunk/core/src/classpath/java/java/util/ResourceBundle.java trunk/core/src/classpath/java/java/util/StringTokenizer.java trunk/core/src/classpath/java/java/util/TreeMap.java trunk/core/src/classpath/java/java/util/TreeSet.java trunk/core/src/classpath/java/java/util/UUID.java trunk/core/src/classpath/java/java/util/Vector.java trunk/core/src/classpath/java/java/util/concurrent/locks/AbstractQueuedLongSynchronizer.java trunk/core/src/classpath/java/java/util/concurrent/locks/AbstractQueuedSynchronizer.java trunk/core/src/classpath/java/java/util/logging/LogManager.java Added Paths: ----------- trunk/core/src/classpath/java/java/util/ServiceConfigurationError.java trunk/core/src/classpath/java/java/util/ServiceLoader.java Modified: trunk/core/src/classpath/java/java/applet/AppletContext.java =================================================================== --- trunk/core/src/classpath/java/java/applet/AppletContext.java 2007-01-07 08:30:02 UTC (rev 3010) +++ trunk/core/src/classpath/java/java/applet/AppletContext.java 2007-01-07 08:31:59 UTC (rev 3011) @@ -52,7 +52,7 @@ * * @author Aaron M. Renn (ar...@ur...) * @since 1.0 - * @status updated to 1.4 + * @status updated to 1.5 */ public interface AppletContext { @@ -90,7 +90,7 @@ * * @return a list of all the applets */ - Enumeration getApplets(); + Enumeration<Applet> getApplets(); /** * Displays the web page pointed to by the specified URL in the window @@ -150,5 +150,5 @@ * @return an iterator over the association keys * @since 1.4 */ - Iterator getStreamKeys(); + Iterator<String> getStreamKeys(); } // interface AppletContext Modified: trunk/core/src/classpath/java/java/beans/BeanDescriptor.java =================================================================== --- trunk/core/src/classpath/java/java/beans/BeanDescriptor.java 2007-01-07 08:30:02 UTC (rev 3010) +++ trunk/core/src/classpath/java/java/beans/BeanDescriptor.java 2007-01-07 08:31:59 UTC (rev 3011) @@ -48,14 +48,14 @@ **/ public class BeanDescriptor extends FeatureDescriptor { - Class beanClass; - Class customizerClass; + Class<?> beanClass; + Class<?> customizerClass; /** Create a new BeanDescriptor with the given beanClass and ** no customizer class. ** @param beanClass the class of the Bean. **/ - public BeanDescriptor(Class beanClass) { + public BeanDescriptor(Class<?> beanClass) { this(beanClass,null); } @@ -64,7 +64,7 @@ ** @param beanClass the class of the Bean. ** @param customizerClass the class of the Bean's Customizer. **/ - public BeanDescriptor(Class beanClass, Class customizerClass) { + public BeanDescriptor(Class<?> beanClass, Class<?> customizerClass) { this.beanClass = beanClass; this.customizerClass = customizerClass; @@ -78,12 +78,12 @@ } /** Get the Bean's class. **/ - public Class getBeanClass() { + public Class<?> getBeanClass() { return beanClass; } /** Get the Bean's customizer's class. **/ - public Class getCustomizerClass() { + public Class<?> getCustomizerClass() { return customizerClass; } } Modified: trunk/core/src/classpath/java/java/beans/Beans.java =================================================================== --- trunk/core/src/classpath/java/java/beans/Beans.java 2007-01-07 08:30:02 UTC (rev 3010) +++ trunk/core/src/classpath/java/java/beans/Beans.java 2007-01-07 08:31:59 UTC (rev 3011) @@ -295,7 +295,7 @@ * @return the Bean as a new view, or if the operation * could not be performed, the Bean itself. */ - public static Object getInstanceOf(Object bean, Class newClass) + public static Object getInstanceOf(Object bean, Class<?> newClass) { return bean; } @@ -314,7 +314,7 @@ * @return whether the Bean can be cast to the class type * in question. */ - public static boolean isInstanceOf(Object bean, Class newBeanClass) + public static boolean isInstanceOf(Object bean, Class<?> newBeanClass) { return newBeanClass.isInstance(bean); } Modified: trunk/core/src/classpath/java/java/beans/DefaultPersistenceDelegate.java =================================================================== --- trunk/core/src/classpath/java/java/beans/DefaultPersistenceDelegate.java 2007-01-07 08:30:02 UTC (rev 3010) +++ trunk/core/src/classpath/java/java/beans/DefaultPersistenceDelegate.java 2007-01-07 08:31:59 UTC (rev 3011) @@ -154,8 +154,8 @@ return new Expression(oldInstance, oldInstance.getClass(), "new", args); } - protected void initialize(Class type, Object oldInstance, Object newInstance, - Encoder out) + protected void initialize(Class<?> type, Object oldInstance, + Object newInstance, Encoder out) { // Calling the supertype's implementation of initialize makes it // possible that descendants of classes like AbstractHashMap Modified: trunk/core/src/classpath/java/java/beans/DesignMode.java =================================================================== --- trunk/core/src/classpath/java/java/beans/DesignMode.java 2007-01-07 08:30:02 UTC (rev 3010) +++ trunk/core/src/classpath/java/java/beans/DesignMode.java 2007-01-07 08:31:59 UTC (rev 3011) @@ -1,5 +1,5 @@ /* java.beans.DesignMode - Copyright (C) 1999 Free Software Foundation, Inc. + Copyright (C) 1999, 2006, Free Software Foundation, Inc. This file is part of GNU Classpath. @@ -39,7 +39,8 @@ package java.beans; /** - * <code>BeanContextChild</code> implementors implement this to get information about whether they are in a design time or runtime environment. + * <code>BeanContextChild</code> implementors implement this to get information + * about whether they are in a design time or runtime environment. * The reason this is restricted to <code>BeanContextChild</code>ren is that * only things in the <code>BeanContext</code> hierarchy are given this * information in the first place. @@ -48,11 +49,11 @@ * @since JDK1.2 * @see java.beans.beancontext.BeanContextChild */ +public interface DesignMode +{ -public interface DesignMode { /** * Use this name when firing <code>PropertyChangeEvent</code>s from your Bean. - * @fixme Check whether PROPERTYNAME is set to same value as Sun. */ String PROPERTYNAME = "designTime"; @@ -78,7 +79,7 @@ * the BeanContext can <em>change</em> the status of the Bean from * design time to runtime. But it appears that it may be so. * - * @see java.util.PropertyChangeEvent + * @see java.beans.PropertyChangeEvent * @see java.beans.beancontext.BeanContext * @see #PROPERTYNAME */ @@ -90,4 +91,5 @@ * runtime. */ boolean isDesignTime(); + } Modified: trunk/core/src/classpath/java/java/beans/Encoder.java =================================================================== --- trunk/core/src/classpath/java/java/beans/Encoder.java 2007-01-07 08:30:02 UTC (rev 3010) +++ trunk/core/src/classpath/java/java/beans/Encoder.java 2007-01-07 08:31:59 UTC (rev 3011) @@ -181,7 +181,7 @@ return exceptionListener; } - public PersistenceDelegate getPersistenceDelegate(Class type) + public PersistenceDelegate getPersistenceDelegate(Class<?> type) { // This is not specified but the JDK behaves like this. if (type == null) @@ -215,7 +215,8 @@ * access is thread safe. * </p> */ - public void setPersistenceDelegate(Class type, PersistenceDelegate delegate) + public void setPersistenceDelegate(Class<?> type, + PersistenceDelegate delegate) { // If the argument is null this will cause a NullPointerException // which is expected behavior. Modified: trunk/core/src/classpath/java/java/beans/EventHandler.java =================================================================== --- trunk/core/src/classpath/java/java/beans/EventHandler.java 2007-01-07 08:30:02 UTC (rev 3010) +++ trunk/core/src/classpath/java/java/beans/EventHandler.java 2007-01-07 08:31:59 UTC (rev 3011) @@ -463,7 +463,8 @@ * @param action Target property or method to invoke. * @return A constructed proxy object. */ - public static Object create(Class listenerInterface, Object target, String action) + public static <T> T create(Class<T> listenerInterface, Object target, + String action) { return create(listenerInterface, target, action, null, null); } @@ -552,7 +553,7 @@ * @param eventPropertyName Name of property to extract from event. * @return A constructed proxy object. */ - public static Object create(Class listenerInterface, Object target, + public static <T> T create(Class<T> listenerInterface, Object target, String action, String eventPropertyName) { return create(listenerInterface, target, action, eventPropertyName, null); @@ -587,7 +588,7 @@ * @param listenerMethodName Listener method to implement. * @return A constructed proxy object. */ - public static Object create(Class listenerInterface, Object target, + public static <T> T create(Class<T> listenerInterface, Object target, String action, String eventPropertyName, String listenerMethodName) { @@ -597,10 +598,9 @@ // Create proxy object passing in the event handler Object proxy = Proxy.newProxyInstance(listenerInterface.getClassLoader(), - new Class[] {listenerInterface}, + new Class<?>[] {listenerInterface}, eh); - return proxy; + return (T) proxy; } - } Modified: trunk/core/src/classpath/java/java/beans/EventSetDescriptor.java =================================================================== --- trunk/core/src/classpath/java/java/beans/EventSetDescriptor.java 2007-01-07 08:30:02 UTC (rev 3010) +++ trunk/core/src/classpath/java/java/beans/EventSetDescriptor.java 2007-01-07 08:31:59 UTC (rev 3011) @@ -164,8 +164,8 @@ * if listenerType is not an EventListener, or if methods are not * found or are invalid. */ - public EventSetDescriptor(Class eventSourceClass, String eventSetName, - Class listenerType, String listenerMethodName) + public EventSetDescriptor(Class<?> eventSourceClass, String eventSetName, + Class<?> listenerType, String listenerMethodName) throws IntrospectionException { setName(eventSetName); @@ -225,8 +225,8 @@ * if listenerType is not an EventListener or if methods are not * found or are invalid. */ - public EventSetDescriptor(Class eventSourceClass, String eventSetName, - Class listenerType, String[] listenerMethodNames, + public EventSetDescriptor(Class<?> eventSourceClass, String eventSetName, + Class<?> listenerType, String[] listenerMethodNames, String addListenerMethodName, String removeListenerMethodName) throws IntrospectionException @@ -287,8 +287,8 @@ * found or are invalid. * @since 1.4 */ - public EventSetDescriptor(Class eventSourceClass, String eventSetName, - Class listenerType, String[] listenerMethodNames, + public EventSetDescriptor(Class<?> eventSourceClass, String eventSetName, + Class<?> listenerType, String[] listenerMethodNames, String addListenerMethodName, String removeListenerMethodName, String getListenerMethodName) @@ -357,7 +357,7 @@ * methods are invalid. * @since 1.4 */ - public EventSetDescriptor(String eventSetName, Class listenerType, + public EventSetDescriptor(String eventSetName, Class<?> listenerType, Method[] listenerMethods, Method addListenerMethod, Method removeListenerMethod, Method getListenerMethod) @@ -402,7 +402,7 @@ * if the listenerType is not an EventListener, or any of the * methods are invalid. */ - public EventSetDescriptor(String eventSetName, Class listenerType, + public EventSetDescriptor(String eventSetName, Class<?> listenerType, Method[] listenerMethods, Method addListenerMethod, Method removeListenerMethod) throws IntrospectionException @@ -449,7 +449,7 @@ * if the listenerType is not an EventListener, or any of the * methods are invalid. */ - public EventSetDescriptor(String eventSetName, Class listenerType, + public EventSetDescriptor(String eventSetName, Class<?> listenerType, MethodDescriptor[] listenerMethodDescriptors, Method addListenerMethod, Method removeListenerMethod) @@ -484,7 +484,7 @@ /** Returns the class that contains the event firing methods. */ - public Class getListenerType() + public Class<?> getListenerType() { return listenerType; } Modified: trunk/core/src/classpath/java/java/beans/FeatureDescriptor.java =================================================================== --- trunk/core/src/classpath/java/java/beans/FeatureDescriptor.java 2007-01-07 08:30:02 UTC (rev 3010) +++ trunk/core/src/classpath/java/java/beans/FeatureDescriptor.java 2007-01-07 08:31:59 UTC (rev 3011) @@ -68,14 +68,14 @@ boolean hidden; boolean preferred; - Hashtable valueHash; + Hashtable<String,Object> valueHash; /** * Instantiate this FeatureDescriptor with appropriate default values. */ public FeatureDescriptor() { - valueHash = new Hashtable(); + valueHash = new Hashtable<String,Object>(); } /** @@ -225,7 +225,7 @@ * @return an Enumerator over all the programmatic key names associated * with this feature. */ - public Enumeration attributeNames() + public Enumeration<String> attributeNames() { return valueHash.keys(); } Modified: trunk/core/src/classpath/java/java/beans/IndexedPropertyDescriptor.java =================================================================== --- trunk/core/src/classpath/java/java/beans/IndexedPropertyDescriptor.java 2007-01-07 08:30:02 UTC (rev 3010) +++ trunk/core/src/classpath/java/java/beans/IndexedPropertyDescriptor.java 2007-01-07 08:31:59 UTC (rev 3011) @@ -76,7 +76,7 @@ */ public class IndexedPropertyDescriptor extends PropertyDescriptor { - private Class indexedPropertyType; + private Class<?> indexedPropertyType; private Method setIndex; private Method getIndex; @@ -112,7 +112,7 @@ * @exception IntrospectionException if the methods are not found or * invalid. */ - public IndexedPropertyDescriptor(String name, Class beanClass) + public IndexedPropertyDescriptor(String name, Class<?> beanClass) throws IntrospectionException { super(name); @@ -161,7 +161,7 @@ * * @exception IntrospectionException if the methods are not found or invalid. */ - public IndexedPropertyDescriptor(String name, Class beanClass, + public IndexedPropertyDescriptor(String name, Class<?> beanClass, String getMethodName, String setMethodName, String getIndexName, String setIndexName) throws IntrospectionException @@ -272,7 +272,7 @@ : Array.newInstance(this.indexedPropertyType,0).getClass()); } - public Class getIndexedPropertyType() + public Class<?> getIndexedPropertyType() { return indexedPropertyType; } Modified: trunk/core/src/classpath/java/java/beans/Introspector.java =================================================================== --- trunk/core/src/classpath/java/java/beans/Introspector.java 2007-01-07 08:30:02 UTC (rev 3010) +++ trunk/core/src/classpath/java/java/beans/Introspector.java 2007-01-07 08:31:59 UTC (rev 3011) @@ -182,7 +182,8 @@ public static final int IGNORE_ALL_BEANINFO = 3; static String[] beanInfoSearchPath = {"gnu.java.beans.info"}; - static Hashtable beanInfoCache = new Hashtable(); + static Hashtable<Class<?>,BeanInfo> beanInfoCache = + new Hashtable<Class<?>,BeanInfo>(); private Introspector() {} @@ -195,13 +196,13 @@ * @param beanClass the class to get BeanInfo about. * @return the BeanInfo object representing the class. */ - public static BeanInfo getBeanInfo(Class beanClass) + public static BeanInfo getBeanInfo(Class<?> beanClass) throws IntrospectionException { BeanInfo cachedInfo; synchronized(beanClass) { - cachedInfo = (BeanInfo)beanInfoCache.get(beanClass); + cachedInfo = beanInfoCache.get(beanClass); if(cachedInfo != null) { return cachedInfo; @@ -245,7 +246,7 @@ * @throws IntrospectionException If something goes wrong while retrieving * the bean data. */ - public static BeanInfo getBeanInfo(Class beanClass, int flag) + public static BeanInfo getBeanInfo(Class<?> beanClass, int flag) throws IntrospectionException { IntrospectionIncubator ii; @@ -312,7 +313,7 @@ * @throws NullPointerException if clz is null. * @since 1.2 */ - public static void flushFromCaches(Class clz) + public static void flushFromCaches(Class<?> clz) { synchronized (clz) { @@ -394,7 +395,7 @@ * @param stopClass the class to stop at. * @return the BeanInfo object representing the class. */ - public static BeanInfo getBeanInfo(Class beanClass, Class stopClass) + public static BeanInfo getBeanInfo(Class<?> beanClass, Class<?> stopClass) throws IntrospectionException { ExplicitInfo explicit = new ExplicitInfo(beanClass, stopClass); Modified: trunk/core/src/classpath/java/java/beans/PersistenceDelegate.java =================================================================== --- trunk/core/src/classpath/java/java/beans/PersistenceDelegate.java 2007-01-07 08:30:02 UTC (rev 3010) +++ trunk/core/src/classpath/java/java/beans/PersistenceDelegate.java 2007-01-07 08:31:59 UTC (rev 3011) @@ -52,8 +52,8 @@ public abstract class PersistenceDelegate { - protected void initialize(Class type, Object oldInstance, Object newInstance, - Encoder out) + protected void initialize(Class<?> type, Object oldInstance, + Object newInstance, Encoder out) { if (type != Object.class) { Modified: trunk/core/src/classpath/java/java/beans/PropertyDescriptor.java =================================================================== --- trunk/core/src/classpath/java/java/beans/PropertyDescriptor.java 2007-01-07 08:30:02 UTC (rev 3010) +++ trunk/core/src/classpath/java/java/beans/PropertyDescriptor.java 2007-01-07 08:31:59 UTC (rev 3011) @@ -65,11 +65,11 @@ **/ public class PropertyDescriptor extends FeatureDescriptor { - Class propertyType; + Class<?> propertyType; Method getMethod; Method setMethod; - Class propertyEditorClass; + Class<?> propertyEditorClass; boolean bound; boolean constrained; @@ -103,7 +103,7 @@ ** @exception IntrospectionException if the methods are not found ** or invalid. **/ - public PropertyDescriptor(String name, Class beanClass) + public PropertyDescriptor(String name, Class<?> beanClass) throws IntrospectionException { setName(name); @@ -159,7 +159,7 @@ **/ public PropertyDescriptor( String name, - Class beanClass, + Class<?> beanClass, String getMethodName, String setMethodName) throws IntrospectionException @@ -213,7 +213,7 @@ ** This is the type the get method returns and the set method ** takes in. **/ - public Class getPropertyType() + public Class<?> getPropertyType() { return propertyType; } @@ -330,7 +330,7 @@ } /** Get the PropertyEditor class. Defaults to null. **/ - public Class getPropertyEditorClass() + public Class<?> getPropertyEditorClass() { return propertyEditorClass; } @@ -341,7 +341,7 @@ ** @param propertyEditorClass the PropertyEditor class for this ** class to use. **/ - public void setPropertyEditorClass(Class propertyEditorClass) + public void setPropertyEditorClass(Class<?> propertyEditorClass) { this.propertyEditorClass = propertyEditorClass; } @@ -516,10 +516,10 @@ * @return The common property type of the two method. * @throws IntrospectionException If any of the above requirements are not met. */ - private Class checkMethods(Method readMethod, Method writeMethod) + private Class<?> checkMethods(Method readMethod, Method writeMethod) throws IntrospectionException { - Class newPropertyType = propertyType; + Class<?> newPropertyType = propertyType; // a valid read method has zero arguments and a non-void return type. if (readMethod != null) Modified: trunk/core/src/classpath/java/java/beans/PropertyEditorManager.java =================================================================== --- trunk/core/src/classpath/java/java/beans/PropertyEditorManager.java 2007-01-07 08:30:02 UTC (rev 3010) +++ trunk/core/src/classpath/java/java/beans/PropertyEditorManager.java 2007-01-07 08:31:59 UTC (rev 3011) @@ -83,7 +83,8 @@ public class PropertyEditorManager { - static java.util.Hashtable editors = new java.util.Hashtable(); + static java.util.Hashtable<Class<?>,Class<?>> editors = + new java.util.Hashtable<Class<?>,Class<?>>(); static String[] editorSearchPath = { "gnu.java.beans.editors", "sun.beans.editors" }; @@ -118,7 +119,7 @@ * will edit. * @param editorClass the PropertyEditor class. */ - public static void registerEditor(Class editedClass, Class editorClass) + public static void registerEditor(Class<?> editedClass, Class<?> editorClass) { editors.put(editedClass, editorClass); } @@ -132,7 +133,7 @@ * @return a PropertyEditor instance that can edit the * specified class. */ - public static PropertyEditor findEditor(Class editedClass) + public static PropertyEditor findEditor(Class<?> editedClass) { try { Modified: trunk/core/src/classpath/java/java/beans/SimpleBeanInfo.java =================================================================== --- trunk/core/src/classpath/java/java/beans/SimpleBeanInfo.java 2007-01-07 08:30:02 UTC (rev 3010) +++ trunk/core/src/classpath/java/java/beans/SimpleBeanInfo.java 2007-01-07 08:31:59 UTC (rev 3011) @@ -1,5 +1,5 @@ /* java.beans.SimpleBeanInfo - Copyright (C) 1998 Free Software Foundation, Inc. + Copyright (C) 1998, 2006, Free Software Foundation, Inc. This file is part of GNU Classpath. @@ -40,6 +40,7 @@ import java.awt.Image; import java.awt.Toolkit; +import java.net.URL; /** ** SimpleBeanInfo is a class you may extend to more easily @@ -130,10 +131,16 @@ ** and its BeanInfo are both loaded by the same ** ClassLoader, generally a reasonable assumption. ** @param location the URL relative - ** @return the Image in question. + ** @return the Image in question (possibly <code>null</code>). **/ - public Image loadImage(String location) { - return Toolkit.getDefaultToolkit().getImage(getClass().getResource(location)); + public Image loadImage(String location) + { + if (location == null) + return null; + URL url = getClass().getResource(location); + if (url == null) + return null; + return Toolkit.getDefaultToolkit().getImage(url); } } Modified: trunk/core/src/classpath/java/java/beans/Statement.java =================================================================== --- trunk/core/src/classpath/java/java/beans/Statement.java 2007-01-07 08:30:02 UTC (rev 3010) +++ trunk/core/src/classpath/java/java/beans/Statement.java 2007-01-07 08:31:59 UTC (rev 3011) @@ -1,5 +1,5 @@ /* Statement.java - Copyright (C) 2004, 2005 Free Software Foundation, Inc. + Copyright (C) 2004, 2005, 2006, Free Software Foundation, Inc. This file is part of GNU Classpath. @@ -346,16 +346,20 @@ /** Return the statement object. */ public Object getTarget() { return target; } - /** Return a string representation. */ + /** + * Returns a string representation of this <code>Statement</code>. + * + * @return A string representation of this <code>Statement</code>. + */ public String toString() { StringBuffer result = new StringBuffer(); - String targetName = target.getClass().getName(); - if ( targetName.startsWith("java")) - { - targetName = targetName.substring(targetName.lastIndexOf('.') + 1); - } + String targetName; + if (target != null) + targetName = target.getClass().getSimpleName(); + else + targetName = "null"; result.append(targetName); result.append("."); @@ -369,10 +373,10 @@ result.append( ( arguments[i] == null ) ? "null" : ( arguments[i] instanceof String ) ? "\"" + arguments[i] + "\"" : - arguments[i].getClass().getName()); + arguments[i].getClass().getSimpleName()); sep = ", "; } - result.append(")"); + result.append(");"); return result.toString(); } Modified: trunk/core/src/classpath/java/java/beans/XMLEncoder.java =================================================================== --- trunk/core/src/classpath/java/java/beans/XMLEncoder.java 2007-01-07 08:30:02 UTC (rev 3010) +++ trunk/core/src/classpath/java/java/beans/XMLEncoder.java 2007-01-07 08:31:59 UTC (rev 3011) @@ -248,7 +248,7 @@ scanEngine.writeObject(o); - if (get(o) == null); + if (get(o) == null) super.writeObject(o); accessCounter--; Modified: trunk/core/src/classpath/java/java/beans/beancontext/BeanContextServicesSupport.java =================================================================== --- trunk/core/src/classpath/java/java/beans/beancontext/BeanContextServicesSupport.java 2007-01-07 08:30:02 UTC (rev 3010) +++ trunk/core/src/classpath/java/java/beans/beancontext/BeanContextServicesSupport.java 2007-01-07 08:31:59 UTC (rev 3011) @@ -46,12 +46,21 @@ import java.io.Serializable; import java.util.ArrayList; import java.util.HashMap; +import java.util.HashSet; import java.util.Iterator; +import java.util.List; import java.util.Locale; +import java.util.Set; import java.util.TooManyListenersException; /** + * This is a helper class for implementing a bean context which + * supplies services. It is intended to be used either by + * subclassing or by calling methods of this implementation + * from another. + * * @author Michael Koch + * @author Andrew John Hughes (gnu...@me...) * @since 1.2 */ public class BeanContextServicesSupport @@ -77,38 +86,39 @@ { private static final long serialVersionUID = 7078212910685744490L; - private BCSSProxyServiceProvider() + private BeanContextServiceProvider provider; + + private BCSSProxyServiceProvider(BeanContextServiceProvider p) { + provider = p; } public Iterator getCurrentServiceSelectors (BeanContextServices bcs, Class serviceClass) - throws NotImplementedException { - throw new Error ("Not implemented"); + return provider.getCurrentServiceSelectors(bcs, serviceClass); } public Object getService (BeanContextServices bcs, Object requestor, Class serviceClass, Object serviceSelector) - throws NotImplementedException { - throw new Error ("Not implemented"); + return provider.getService(bcs, requestor, serviceClass, + serviceSelector); } public void releaseService (BeanContextServices bcs, Object requestor, Object service) - throws NotImplementedException { - throw new Error ("Not implemented"); + provider.releaseService(bcs, requestor, service); } public void serviceRevoked (BeanContextServiceRevokedEvent bcsre) - throws NotImplementedException { - throw new Error ("Not implemented"); + if (provider instanceof BeanContextServiceRevokedListener) + ((BeanContextServiceRevokedListener) provider).serviceRevoked(bcsre); } } @@ -119,51 +129,233 @@ protected BeanContextServiceProvider serviceProvider; - private BCSSServiceProvider() + private Class serviceClass; + + private BCSSServiceProvider(Class serviceClass, + BeanContextServiceProvider provider) { + this.serviceClass = serviceClass; + serviceProvider = provider; } protected BeanContextServiceProvider getServiceProvider() { return serviceProvider; } + + private Class getServiceClass() + { + return serviceClass; + } + } + /** + * Represents a request for a service. This is + * a common superclass used by the classes which maintain + * the listener-requestor and service-requestor relationships. + * + * @author Andrew John Hughes (gnu...@me...) + */ + private static abstract class Request + { + private Object requestor; + + public Request(Object requestor) + { + this.requestor = requestor; + } + + public boolean equals(Object obj) + { + if (obj instanceof Request) + { + Request req = (Request) obj; + return req.getRequestor().equals(requestor); + } + return false; + } + + public Object getRequestor() + { + return requestor; + } + + } + + /** + * Represents a relationship between a service requestor + * and a revocation listener. + * + * @author Andrew John Hughes (gnu...@me...) + */ + private static class ServiceRequest + extends Request + { + + private BeanContextServiceRevokedListener listener; + + public ServiceRequest(Object requestor, + BeanContextServiceRevokedListener listener) + { + super(requestor); + this.listener = listener; + } + + public boolean equals(Object obj) + { + if (obj instanceof ServiceRequest) + { + ServiceRequest sr = (ServiceRequest) obj; + return (super.equals(obj) && + sr.getListener().equals(listener)); + } + return false; + } + + public BeanContextServiceRevokedListener getListener() + { + return listener; + } + } + + /** + * Represents a relationship between a service requestor + * and a service instance. + * + * @author Andrew John Hughes (gnu...@me...) + */ + private static class ServiceLease + extends Request + { + + private Object service; + + public ServiceLease(Object requestor, Object service) + { + super(requestor); + this.service = service; + } + + public boolean equals(Object obj) + { + if (obj instanceof ServiceLease) + { + ServiceLease sl = (ServiceLease) obj; + return (super.equals(obj) && + sl.getService().equals(service)); + } + return false; + } + + public Object getService() + { + return service; + } + } + + /** + * A collection of listeners who receive availability + * and revocation notifications. + */ protected transient ArrayList bcsListeners; protected transient BCSSProxyServiceProvider proxy; + /** + * The number of serializable service providers. + */ protected transient int serializable; + /** + * A map of registered services, linking the service + * class to its associated {@link BCSSServiceProvider}. + */ protected transient HashMap services; + /** + * A map of children to a list of services they + * have obtained. + */ + private transient HashMap serviceUsers; + + /** + * A map of services to {@link ServiceRequest}s. + */ + private transient HashMap serviceRequests; + + /** + * A map of {@link ServiceLease}s to providers. + */ + private transient HashMap serviceLeases; + + /** + * Construct a {@link BeanContextServicesSupport} instance. + */ public BeanContextServicesSupport () { super(); } + /** + * Construct a {@link BeanContextServicesSupport} instance. + * + * @param peer the bean context services peer (<code>null</code> permitted). + */ public BeanContextServicesSupport (BeanContextServices peer) { super(peer); } + /** + * Construct a {@link BeanContextServicesSupport} instance. + * + * @param peer the bean context peer (<code>null</code> permitted). + * @param locale the locale (<code>null</code> permitted, equivalent to + * the default locale). + */ public BeanContextServicesSupport(BeanContextServices peer, Locale locale) { super(peer, locale); } + /** + * Construct a {@link BeanContextServicesSupport} instance. + * + * @param peer the bean context peer (<code>null</code> permitted). + * @param locale the locale (<code>null</code> permitted, equivalent to + * the default locale). + * @param dtime a flag indicating whether or not the bean context is in + * design time mode. + */ public BeanContextServicesSupport(BeanContextServices peer, Locale locale, boolean dtime) { super(peer, locale, dtime); } + /** + * Construct a {@link BeanContextServicesSupport} instance. + * + * @param peer the bean context peer (<code>null</code> permitted). + * @param locale the locale (<code>null</code> permitted, equivalent to + * the default locale). + * @param dtime a flag indicating whether or not the bean context is in + * design time mode. + * @param visible initial value of the <code>okToUseGui</code> flag. + */ public BeanContextServicesSupport(BeanContextServices peer, Locale locale, boolean dtime, boolean visible) { super(peer, locale, dtime, visible); } + /** + * Adds a new listener for service availability and + * revocation events. + * + * @param listener the listener to add. + */ public void addBeanContextServicesListener (BeanContextServicesListener listener) { @@ -174,60 +366,168 @@ } } + /** + * Registers a new service from the specified service provider. + * The service is internally associated with the service provider + * and a <code>BeanContextServiceAvailableEvent</code> is fired. If + * the service is already registered, then this method instead + * returns <code>false</code>. This is equivalent to calling + * <code>addService(serviceClass, bcsp, true)</code>. + * + * @param serviceClass the class of the service to be registered. + * @param bcsp the provider of the given service. + * @return true if the service was registered successfully. + * @see #addService(Class, BeanContextServiceProvider, boolean) + */ public boolean addService (Class serviceClass, BeanContextServiceProvider bcsp) { return addService(serviceClass, bcsp, true); } + /** + * Registers a new service from the specified service provider. + * The service is internally associated with the service provider + * and (if <code>fireEvent</code> is true) a + * <code>BeanContextServiceAvailableEvent</code> is fired. If + * the service is already registered, then this method instead + * returns <code>false</code>. + * + * @param serviceClass the class of the service to be registered. + * @param bcsp the provider of the given service. + * @param fireEvent true if a service availability event should + * be fired. + * @return true if the service was registered successfully. + */ protected boolean addService (Class serviceClass, BeanContextServiceProvider bcsp, boolean fireEvent) { + synchronized (globalHierarchyLock) + { synchronized (services) { if (services.containsKey(serviceClass)) return false; - services.put(serviceClass, bcsp); + services.put(serviceClass, + createBCSSServiceProvider(serviceClass, bcsp)); if (bcsp instanceof Serializable) ++serializable; + if (fireEvent) fireServiceAdded(serviceClass); return true; } } + } + /** + * Deserializes any service providers which are serializable. This + * method is called by the <code>readObject</code> method of + * {@link BeanContextSupport} prior to deserialization of the children. + * Subclasses may envelope its behaviour in order to read further + * serialized data to the stream. + * + * @param oos the stream from which data is being deserialized. + * @throws IOException if an I/O error occurs. + * @throws ClassNotFoundException if the class of a deserialized object + * can not be found. + */ protected void bcsPreDeserializationHook (ObjectInputStream ois) - throws ClassNotFoundException, IOException, NotImplementedException + throws ClassNotFoundException, IOException { - throw new Error ("Not implemented"); + serializable = ois.readInt(); + for (int a = 0; a < serializable; ++a) + { + BCSSServiceProvider bcsssp = (BCSSServiceProvider) ois.readObject(); + addService(bcsssp.getServiceClass(), bcsssp.getServiceProvider()); + } } + /** + * Serializes any service providers which are serializable. This + * method is called by the <code>writeObject</code> method of + * {@link BeanContextSupport} prior to serialization of the children. + * Subclasses may envelope its behaviour in order to add further + * serialized data to the stream. + * + * @param oos the stream to which data is being serialized. + * @throws IOException if an I/O error occurs. + */ protected void bcsPreSerializationHook (ObjectOutputStream oos) - throws IOException, NotImplementedException + throws IOException { - throw new Error ("Not implemented"); + oos.writeInt(serializable); + synchronized (services) + { + Iterator i = services.values().iterator(); + while (i.hasNext()) + { + BCSSServiceProvider bcsssp = (BCSSServiceProvider) i.next(); + if (bcsssp.getServiceProvider() instanceof Serializable) + oos.writeObject(bcsssp); + } + } } + /** + * Revokes any services used by a child that has just been removed. + * The superclass ({@link BeanContextSupport}) calls this method + * when a child has just been successfully removed. Subclasses can + * extend this method in order to perform additional operations + * on child removal. + * + * @param child the child being removed. + * @param bcsc the support object for the child. + */ protected void childJustRemovedHook (Object child, BeanContextSupport.BCSChild bcsc) - throws NotImplementedException { - throw new Error ("Not implemented"); + if (child instanceof BeanContextChild) + { + BeanContextChild bcchild = (BeanContextChild) child; + Iterator childServices = ((List) serviceUsers.get(bcchild)).iterator(); + while (childServices.hasNext()) + releaseService(bcchild, this, childServices.next()); + serviceUsers.remove(bcchild); + } } + /** + * Overrides the {@link BeanContextSupport#createBCSChild} method + * so as to use a {@link BCSSChild} instead. + * + * @param targetChild the child to create the child for. + * @param peer the peer which relates to the child if a proxy is used. + * @return a new instance of {@link BCSSChild}. + */ protected BeanContextSupport.BCSChild createBCSChild (Object targetChild, Object peer) { return new BCSSChild(targetChild, peer); } + /** + * Provides a hook so that subclasses can replace the + * {@link BCSSServiceProvider} class, used to store registered + * service providers, with a subclass without replacing the + * {@link #addService(Class, BeanContextServiceProvider)} method. + * + * @param sc the class of service being registered. + * @param bcsp the provider of the service. + * @return a instance of {@link BCSSServiceProvider} wrapping the provider. + */ protected BeanContextServicesSupport.BCSSServiceProvider createBCSSServiceProvider (Class sc, BeanContextServiceProvider bcsp) - throws NotImplementedException { - throw new Error ("Not implemented"); + return new BCSSServiceProvider(sc, bcsp); } + /** + * Sends a <code>BeanContextServiceAvailableEvent</code> to all + * registered listeners. + * + * @param bcssae the event to send. + */ protected final void fireServiceAdded (BeanContextServiceAvailableEvent bcssae) { synchronized (bcsListeners) @@ -242,12 +542,25 @@ } } + /** + * Sends a <code>BeanContextServiceAvailableEvent</code> to all + * registered listeners. + * + * @param serviceClass the service that is now available. + * @see #fireServiceAdded(BeanContextServiceAvailableEvent) + */ protected final void fireServiceAdded (Class serviceClass) { fireServiceAdded(new BeanContextServiceAvailableEvent(this, serviceClass)); } + /** + * Sends a <code>BeanContextServiceRevokedEvent</code> to all + * registered listeners. + * + * @param event the event to send. + */ protected final void fireServiceRevoked(BeanContextServiceRevokedEvent event) { synchronized (bcsListeners) @@ -259,9 +572,26 @@ = (BeanContextServicesListener) bcsListeners.get(i); bcsl.serviceRevoked(event); } + List requests = (List) serviceRequests.get(event.getServiceClass()); + if (requests != null) + { + Iterator i = requests.iterator(); + while (i.hasNext()) + { + ServiceRequest r = (ServiceRequest) i.next(); + r.getListener().serviceRevoked(event); + } + } } } + /** + * Sends a <code>BeanContextServiceRevokedEvent</code> to all + * registered listeners. + * + * @param serviceClass the service that has been revoked. + * @see #fireServiceRevoked(BeanContextServiceRevokedEvent) + */ protected final void fireServiceRevoked (Class serviceClass, boolean revokeNow) { @@ -269,53 +599,168 @@ revokeNow)); } + /** + * Returns the services peer given at construction time, + * or <code>null</code> if no peer was given. + * + * @return the {@link BeanContextServices} peer. + */ public BeanContextServices getBeanContextServicesPeer () - throws NotImplementedException { - throw new Error ("Not implemented"); + return (BeanContextServices) beanContextChildPeer; } + /** + * Returns <code>child</code> as an instance of + * {@link BeanContextServicesListener}, or <code>null</code> if + * <code>child</code> does not implement that interface. + * + * @param child the child (<code>null</code> permitted). + * + * @return The child cast to {@link BeanContextServicesListener}. + */ protected static final BeanContextServicesListener - getChildBeanContextServicesListener (Object child) - throws NotImplementedException + getChildBeanContextServicesListener(Object child) { - throw new Error ("Not implemented"); + if (child instanceof BeanContextServicesListener) + return (BeanContextServicesListener) child; + else + return null; } + /** + * Returns an iterator over the currently available + * services. + * + * @return an iterator over the currently available services. + */ public Iterator getCurrentServiceClasses () { + synchronized (globalHierarchyLock) + { synchronized (services) { return services.keySet().iterator(); } } + } + /** + * Returns an iterator over the service selectors of the service + * provider for the given service. The iterator is actually + * obtained by calling the + * {@link BeanContextServiceProvider#getCurrentServiceSelectors} + * of the provider itself. If the specified service is not available, + * <code>null</code> is returned. + * + * @param serviceClass the service whose provider's selectors should + * be iterated over. + * @return an {@link Iterator} over the service selectors of the + * provider of the given service. + */ public Iterator getCurrentServiceSelectors (Class serviceClass) { + synchronized (globalHierarchyLock) + { synchronized (services) { - // FIXME: what if service does not exist? Must write a test. BeanContextServiceProvider bcsp - = (BeanContextServiceProvider) services.get(serviceClass); + = ((BCSSServiceProvider) + services.get(serviceClass)).getServiceProvider(); + if (bcsp == null) + return null; + else return bcsp.getCurrentServiceSelectors(this, serviceClass); } } + } + /** + * Retrieves the specified service. If a provider for the service + * is registered in this context, then the request is passed on to + * the provider and the service returned. Otherwise, the request + * is delegated to a parent {@link BeanContextServices}, if possible. + * If the service can not be found at all, then <code>null</code> + * is returned. + * + * @param child the child obtaining the reference. + * @param requestor the requestor of the service, which may be the + * child itself. + * @param serviceClass the service being requested. + * @param serviceSelector an additional service-dependent parameter + * (may be <code>null</code> if not appropriate). + * @param bcsrl a listener used to notify the requestor that the service + * has since been revoked. + * @return a reference to the service requested, or <code>null</code>. + * @throws TooManyListenersException according to Sun's documentation. + */ public Object getService (BeanContextChild child, Object requestor, Class serviceClass, Object serviceSelector, BeanContextServiceRevokedListener bcsrl) - throws TooManyListenersException, NotImplementedException + throws TooManyListenersException { - throw new Error ("Not implemented"); + synchronized (globalHierarchyLock) + { + synchronized (services) + { + Object service; + BeanContextServiceProvider provider = ((BCSSServiceProvider) + services.get(serviceClass)).getServiceProvider(); + if (provider != null) + { + service = provider.getService(this, requestor, serviceClass, + serviceSelector); + List childServices = (List) serviceUsers.get(child); + if (childServices == null) + { + childServices = new ArrayList(); + serviceUsers.put(child, childServices); + } + childServices.add(serviceClass); + } + else + { + BeanContextServices peer = getBeanContextServicesPeer(); + if (peer != null) + service = peer.getService(child, requestor, serviceClass, + serviceSelector, bcsrl); + else + service = null; + } + if (service != null) + { + ServiceRequest request = new ServiceRequest(requestor, bcsrl); + Set requests = (Set) serviceRequests.get(serviceClass); + if (requests == null) + { + requests = new HashSet(); + serviceRequests.put(serviceClass, requests); + } + requests.add(request); + ServiceLease lease = new ServiceLease(requestor, service); + serviceLeases.put(lease, provider); + } + return service; + } + } } + /** + * Returns true if the specified service is available. + * + * @param serviceClass the service to check for. + * @return true if the service is available. + */ public boolean hasService (Class serviceClass) { + synchronized (globalHierarchyLock) + { synchronized (services) { return services.containsKey(serviceClass); } } + } public void initialize () { @@ -323,25 +768,62 @@ bcsListeners = new ArrayList(); services = new HashMap(); + serviceUsers = new HashMap(); + serviceRequests = new HashMap(); + serviceLeases = new HashMap(); } - protected void initializeBeanContextResources () - throws NotImplementedException + /** + * Subclasses may override this method to allocate resources + * from the nesting bean context. + */ + protected void initializeBeanContextResources() { - throw new Error ("Not implemented"); + /* Purposefully left empty */ } - protected void releaseBeanContextResources () - throws NotImplementedException + /** + * Relinquishes any resources obtained from the parent context. + * Specifically, those services obtained from the parent are revoked. + * Subclasses may override this method to deallocate resources + * from the nesting bean context. + */ + protected void releaseBeanContextResources() { - throw new Error ("Not implemented"); + /* Purposefully left empty */ } + /** + * Releases the reference to a service held by a + * {@link BeanContextChild} (or an arbitrary object associated + * with it). It simply calls the appropriate method on the + * underlying provider. + * + * @param child the child who holds the reference. + * @param requestor the object that requested the reference. + * @param service the service being released. + */ public void releaseService (BeanContextChild child, Object requestor, Object service) - throws NotImplementedException { - throw new Error ("Not implemented"); + synchronized (globalHierarchyLock) + { + synchronized (services) + { + ServiceLease lease = new ServiceLease(requestor, service); + BeanContextServiceProvider provider = (BeanContextServiceProvider) + serviceLeases.get(lease); + if (provider != null) + provider.releaseService(this, requestor, service); + else + { + BeanContextServices peer = getBeanContextServicesPeer(); + if (peer != null) + peer.releaseService(child, requestor, service); + } + serviceLeases.remove(lease); + } + } } public void removeBeanContextServicesListener @@ -349,17 +831,35 @@ { synchronized (bcsListeners) { - int index = bcsListeners.indexOf(listener); - if (index > -1) - bcsListeners.remove(index); + bcsListeners.remove(listener); } } + /** + * Revokes the given service. A {@link BeanContextServiceRevokedEvent} is + * emitted to all registered {@link BeanContextServiceRevokedListener}s + * and {@link BeanContextServiceListener}s. If <code>revokeCurrentServicesNow</code> + * is true, termination of the service is immediate. Otherwise, prior + * acquisitions of the service by requestors remain valid. + * + * @param serviceClass the service to revoke. + * @param bcsp the provider of the revoked service. + * @param revokeCurrentServicesNow true if this is an exceptional circumstance + * where service should be immediately revoked. + */ public void revokeService (Class serviceClass, BeanContextServiceProvider bcsp, boolean revokeCurrentServicesNow) - throws NotImplementedException { - throw new Error ("Not implemented"); + synchronized (globalHierarchyLock) + { + synchronized (services) + { + fireServiceRevoked(serviceClass, revokeCurrentServicesNow); + services.remove(serviceClass); + if (bcsp instanceof Serializable) + --serializable; + } + } } public void serviceAvailable (BeanContextServiceAvailableEvent bcssae) Modified: trunk/core/src/classpath/java/java/beans/beancontext/BeanContextSupport.java =================================================================== --- trunk/core/src/classpath/java/java/beans/beancontext/BeanContextSupport.java 2007-01-07 08:30:02 UTC (rev 3010) +++ trunk/core/src/classpath/java/java/beans/beancontext/BeanContextSupport.java 2007-01-07 08:31:59 UTC (rev 3011) @@ -38,8 +38,6 @@ package java.beans.beancontext; -import gnu.classpath.NotImplementedException; - import java.beans.Beans; import java.beans.DesignMode; import java.beans.PropertyChangeEvent; @@ -57,6 +55,7 @@ import java.util.Collection; import java.util.HashMap; import java.util.Iterator; +import java.util.List; import java.util.Locale; /** @@ -74,20 +73,52 @@ { private static final long serialVersionUID = -4879613978649577204L; - // This won't show up in japi, but we mark it as a stub anyway, - // so that searches for NotImplementedException will find it. + /** + * Deserializes a stored bean context. Hook methods are provided to allow + * subclasses to perform their own deserialization after the default + * deserialization but prior to the deserialization of the children. Note that + * {@link #readChildren(ObjectInputStream)} is only called if there + * is no distinct peer. If there is, the peer is expected to call + * the method instead. + * + * @param s the stream to deserialize. + * @throws ClassNotFoundException if the class of an object being deserialized + * could not be found. + * @throws IOException if an I/O error occurs. + */ private void readObject (ObjectInputStream s) - throws ClassNotFoundException, IOException, NotImplementedException + throws ClassNotFoundException, IOException { - throw new Error ("Not implemented"); + s.defaultReadObject(); + bcsPreDeserializationHook(s); + BeanContext peer = getBeanContextPeer(); + if (peer == null || peer == this) + readChildren(s); } - // This won't show up in japi, but we mark it as a stub anyway, - // so that searches for NotImplementedException will find it. + /** + * Serializes a bean context. Hook methods are provided to allow + * subclasses to perform their own serialization after the default + * serialization but prior to serialization of the children. Note that + * {@link #writeChildren(ObjectOutputStream)} is only called if there + * is no distinct peer. If there is, the peer is expected to call + * the method instead. + * + * @param s the stream to serialize. + * @throws ClassNotFoundException if the class of an object being deserialized + * could not be found. + * @throws IOException if an I/O error occurs. + */ private void writeObject (ObjectOutputStream s) - throws ClassNotFoundException, IOException, NotImplementedException + throws ClassNotFoundException, IOException { - throw new Error ("Not implemented"); + serializing = true; + s.defaultWriteObject(); + bcsPreSerializationHook(s); + BeanContext peer = getBeanContextPeer(); + if (peer == null || peer == this) + writeChildren(s); + serializing = false; } protected class BCSChild implements Serializable @@ -102,6 +133,12 @@ this.targetChild = targetChild; this.peer = peer; } + + private Object getTargetChild() + { + return targetChild; + } + } protected static final class BCSIterator implements Iterator @@ -139,47 +176,68 @@ protected transient boolean okToUseGui; + private transient boolean serializing; + /** * Construct a BeanContextSupport instance. */ public BeanContextSupport () { - this (null, null, true, true); + this (null, null, false, true); } /** * Construct a BeanContextSupport instance. + * + * @param peer the bean context peer (<code>null</code> permitted). */ - public BeanContextSupport (BeanContext peer) + public BeanContextSupport(BeanContext peer) { - this (peer, null, true, true); + this (peer, null, false, true); } /** * Construct a BeanContextSupport instance. + * + * @param peer the bean context peer (<code>null</code> permitted). + * @param locale the locale (<code>null</code> permitted, equivalent to + * the default locale). */ - ... [truncated message content] |
From: <ls...@us...> - 2007-01-07 08:30:04
|
Revision: 3010 http://jnode.svn.sourceforge.net/jnode/?rev=3010&view=rev Author: lsantha Date: 2007-01-07 00:30:02 -0800 (Sun, 07 Jan 2007) Log Message: ----------- Classpath patches. Modified Paths: -------------- trunk/core/src/classpath/javax/javax/accessibility/AccessibleRelationSet.java trunk/core/src/classpath/javax/javax/accessibility/AccessibleStateSet.java Modified: trunk/core/src/classpath/javax/javax/accessibility/AccessibleRelationSet.java =================================================================== --- trunk/core/src/classpath/javax/javax/accessibility/AccessibleRelationSet.java 2007-01-07 08:29:31 UTC (rev 3009) +++ trunk/core/src/classpath/javax/javax/accessibility/AccessibleRelationSet.java 2007-01-07 08:30:02 UTC (rev 3010) @@ -64,7 +64,8 @@ * @see #toArray() * @see #clear() */ - protected Vector relations = new Vector(); + protected Vector<AccessibleRelation> relations + = new Vector<AccessibleRelation>(); /** * Create an empty relation set. Modified: trunk/core/src/classpath/javax/javax/accessibility/AccessibleStateSet.java =================================================================== --- trunk/core/src/classpath/javax/javax/accessibility/AccessibleStateSet.java 2007-01-07 08:29:31 UTC (rev 3009) +++ trunk/core/src/classpath/javax/javax/accessibility/AccessibleStateSet.java 2007-01-07 08:30:02 UTC (rev 3010) @@ -62,7 +62,7 @@ * @see #toArray() * @see #clear() */ - protected Vector states = new Vector(); + protected Vector<AccessibleState> states = new Vector<AccessibleState>(); /** * Create an empty state set. This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <ls...@us...> - 2007-01-07 08:29:33
|
Revision: 3009 http://jnode.svn.sourceforge.net/jnode/?rev=3009&view=rev Author: lsantha Date: 2007-01-07 00:29:31 -0800 (Sun, 07 Jan 2007) Log Message: ----------- Classpath patches. Modified Paths: -------------- trunk/core/src/classpath/vm/gnu/classpath/VMStackWalker.java trunk/core/src/classpath/vm/java/lang/reflect/Constructor.java trunk/core/src/classpath/vm/java/lang/reflect/Method.java Modified: trunk/core/src/classpath/vm/gnu/classpath/VMStackWalker.java =================================================================== --- trunk/core/src/classpath/vm/gnu/classpath/VMStackWalker.java 2007-01-07 08:26:36 UTC (rev 3008) +++ trunk/core/src/classpath/vm/gnu/classpath/VMStackWalker.java 2007-01-07 08:29:31 UTC (rev 3009) @@ -1,35 +1,51 @@ -/* - * $Id$ - * - * JNode.org - * Copyright (C) 2003-2006 JNode.org - * - * This library is free software; you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as published - * by the Free Software Foundation; either version 2.1 of the License, or - * (at your option) any later version. - * - * This library 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 Lesser General Public - * License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this library; If not, write to the Free Software Foundation, Inc., - * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. - */ +/* VMStackWalker.java -- Reference implementation of VM hooks for stack access + Copyright (C) 2005, 2006 Free Software Foundation +This file is part of GNU Classpath. + +GNU Classpath is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2, or (at your option) +any later version. + +GNU Classpath is distributed in the hope that it will be useful, but +WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +General Public License for more details. + +You should have received a copy of the GNU General Public License +along with GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA +02110-1301 USA. + +Linking this library statically or dynamically with other modules is +making a combined work based on this library. Thus, the terms and +conditions of the GNU General Public License cover the whole +combination. + +As a special exception, the copyright holders of this library give you +permission to link this library with independent modules to produce an +executable, regardless of the license terms of these independent +modules, and to copy and distribute the resulting executable under +terms of your choice, provided that you also meet, for each linked +independent module, the terms and conditions of the license of that +module. An independent module is a module which is not derived from +or based on this library. If you modify this library, you may extend +this exception to your version of the library, but you are not +obligated to do so. If you do not wish to do so, delete this +exception statement from your version. */ + package gnu.classpath; import org.jnode.vm.VmSystem; /** - * This class provides access to the classes on the Java stack for reflection - * and security purposes. + * This class provides access to the classes on the Java stack + * for reflection and security purposes. * * <p> - * This class is only available to priviledged code (i.e., code loaded by the - * bootstrap loader). + * This class is only available to privileged code (i.e., code loaded + * by the bootstrap loader). * * @author John Keiser * @author Eric Blake <eb...@em...> @@ -37,12 +53,12 @@ */ public final class VMStackWalker { /** - * Get a list of all the classes currently executing methods on the Java - * stack. <code>getClassContext()[0]</code> is the class associated with - * the currently executing method, i.e., the method that called + * Get a list of all the classes currently executing methods on the + * Java stack. <code>getClassContext()[0]</code> is the class associated + * with the currently executing method, i.e., the method that called * <code>VMStackWalker.getClassContext()</code> (possibly through - * reflection). So you may need to pop off these stack frames from the top - * of the stack: + * reflection). So you may need to pop off these stack frames from + * the top of the stack: * <ul> * <li><code>VMStackWalker.getClassContext()</code> * <li><code>Method.invoke()</code> @@ -55,15 +71,15 @@ } /** - * Get the class associated with the method invoking the method invoking - * this method, or <code>null</code> if the stack is not that deep (e.g., - * invoked via JNI invocation API). This method is an optimization for the - * expression <code>getClassContext()[1]</code> and should return the same - * result. + * Get the class associated with the method invoking the method + * invoking this method, or <code>null</code> if the stack is not + * that deep (e.g., invoked via JNI invocation API). This method + * is an optimization for the expression <code>getClassContext()[1]</code> + * and should return the same result. * * <p> - * VM implementers are encouraged to provide a more efficient version of - * this method. + * VM implementers are encouraged to provide a more efficient + * version of this method. */ public static Class getCallingClass() { Class[] ctx = getClassContext(); @@ -74,14 +90,14 @@ /** * Get the class loader associated with the Class returned by - * <code>getCallingClass()</code>, or <code>null</code> if no such - * class exists or it is the boot loader. This method is an optimization for - * the expression <code>getClassContext()[1].getClassLoader()</code> and - * should return the same result. + * <code>getCallingClass()</code>, or <code>null</code> if no such class + * exists or it is the boot loader. This method is an optimization for the + * expression <code>VMStackWalker.getClassLoader(getClassContext()[1])</code> + * and should return the same result. * * <p> - * VM implementers are encouraged to provide a more efficient version of - * this method. + * VM implementers are encouraged to provide a more efficient + * version of this method. */ public static ClassLoader getCallingClassLoader() { Class[] ctx = getClassContext(); @@ -89,4 +105,31 @@ return null; return ctx[4].getClassLoader(); } + + /** + * Retrieve the class's ClassLoader, or <code>null</code> if loaded + * by the bootstrap loader. I.e., this should return the same thing + * as {@link java.lang.VMClass#getClassLoader}. This duplicate version + * is here to work around access permissions. + */ + public static ClassLoader getClassLoader(Class cl){ + //TODO FIX it according to the javadoc above + return cl.getClassLoader(); + }; + + /** + * Walk up the stack and return the first non-null class loader. + * If there aren't any non-null class loaders on the stack, return null. + */ + public static ClassLoader firstNonNullClassLoader() + { + Class[] stack = getClassContext(); + for (int i = 0; i < stack.length; i++) + { + ClassLoader loader = getClassLoader(stack[i]); + if (loader != null) + return loader; } + return null; + } +} Modified: trunk/core/src/classpath/vm/java/lang/reflect/Constructor.java =================================================================== --- trunk/core/src/classpath/vm/java/lang/reflect/Constructor.java 2007-01-07 08:26:36 UTC (rev 3008) +++ trunk/core/src/classpath/vm/java/lang/reflect/Constructor.java 2007-01-07 08:29:31 UTC (rev 3009) @@ -1,24 +1,41 @@ -/* - * $Id$ - * - * JNode.org - * Copyright (C) 2003-2006 JNode.org - * - * This library is free software; you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as published - * by the Free Software Foundation; either version 2.1 of the License, or - * (at your option) any later version. - * - * This library 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 Lesser General Public - * License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this library; If not, write to the Free Software Foundation, Inc., - * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. - */ - +/* java.lang.reflect.Constructor - reflection of Java constructors + Copyright (C) 1998, 2001, 2004, 2005 Free Software Foundation, Inc. + +This file is part of GNU Classpath. + +GNU Classpath is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2, or (at your option) +any later version. + +GNU Classpath is distributed in the hope that it will be useful, but +WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +General Public License for more details. + +You should have received a copy of the GNU General Public License +along with GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA +02110-1301 USA. + +Linking this library statically or dynamically with other modules is +making a combined work based on this library. Thus, the terms and +conditions of the GNU General Public License cover the whole +combination. + +As a special exception, the copyright holders of this library give you +permission to link this library with independent modules to produce an +executable, regardless of the license terms of these independent +modules, and to copy and distribute the resulting executable under +terms of your choice, provided that you also meet, for each linked +independent module, the terms and conditions of the license of that +module. An independent module is a module which is not derived from +or based on this library. If you modify this library, you may extend +this exception to your version of the library, but you are not +obligated to do so. If you do not wish to do so, delete this +exception statement from your version. */ + + package java.lang.reflect; import java.lang.annotation.Annotation; @@ -55,6 +72,8 @@ * @author Eric Blake <eb...@em...> * @see Member * @see Class + * @see java.lang.Class#getConstructor(Class[]) + * @see java.lang.Class#getDeclaredConstructor(Class[]) * @see java.lang.Class#getConstructors() * @see java.lang.Class#getDeclaredConstructors() * @since 1.1 @@ -299,8 +318,49 @@ MethodSignatureParser p = new MethodSignatureParser(this, sig); return p.getTypeParameters(); } + /** + * Returns an array of <code>Type</code> objects that represents + * the exception types declared by this constructor, in declaration order. + * An array of size zero is returned if this constructor declares no + * exceptions. + * + * @return the exception types declared by this constructor. + * @throws GenericSignatureFormatError if the generic signature does + * not conform to the format specified in the Virtual Machine + * specification, version 3. + * @since 1.5 + */ + public Type[] getGenericExceptionTypes() + { + String sig = getSignature(); + if (sig == null) + return getExceptionTypes(); + MethodSignatureParser p = new MethodSignatureParser(this, sig); + return p.getGenericExceptionTypes(); + } + /** + * Returns an array of <code>Type</code> objects that represents + * the parameter list for this constructor, in declaration order. + * An array of size zero is returned if this constructor takes no + * parameters. + * + * @return a list of the types of the constructor's parameters + * @throws GenericSignatureFormatError if the generic signature does + * not conform to the format specified in the Virtual Machine + * specification, version 3. + * @since 1.5 + */ + public Type[] getGenericParameterTypes() + { + String sig = getSignature(); + if (sig == null) + return getParameterTypes(); + MethodSignatureParser p = new MethodSignatureParser(this, sig); + return p.getGenericParameterTypes(); + } + /** * @see java.lang.reflect.AnnotatedElement#getAnnotation(java.lang.Class) */ @@ -322,6 +382,7 @@ return vmMethod.getDeclaredAnnotations(); } + /** * @see java.lang.reflect.AnnotatedElement#isAnnotationPresent(java.lang.Class) */ Modified: trunk/core/src/classpath/vm/java/lang/reflect/Method.java =================================================================== --- trunk/core/src/classpath/vm/java/lang/reflect/Method.java 2007-01-07 08:26:36 UTC (rev 3008) +++ trunk/core/src/classpath/vm/java/lang/reflect/Method.java 2007-01-07 08:29:31 UTC (rev 3009) @@ -1,24 +1,41 @@ -/* - * $Id$ - * - * JNode.org - * Copyright (C) 2003-2006 JNode.org - * - * This library is free software; you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as published - * by the Free Software Foundation; either version 2.1 of the License, or - * (at your option) any later version. - * - * This library 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 Lesser General Public - * License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this library; If not, write to the Free Software Foundation, Inc., - * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. - */ - +/* java.lang.reflect.Method - reflection of Java methods + Copyright (C) 1998, 2001, 2002, 2005 Free Software Foundation, Inc. + +This file is part of GNU Classpath. + +GNU Classpath is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2, or (at your option) +any later version. + +GNU Classpath is distributed in the hope that it will be useful, but +WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +General Public License for more details. + +You should have received a copy of the GNU General Public License +along with GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA +02110-1301 USA. + +Linking this library statically or dynamically with other modules is +making a combined work based on this library. Thus, the terms and +conditions of the GNU General Public License cover the whole +combination. + +As a special exception, the copyright holders of this library give you +permission to link this library with independent modules to produce an +executable, regardless of the license terms of these independent +modules, and to copy and distribute the resulting executable under +terms of your choice, provided that you also meet, for each linked +independent module, the terms and conditions of the license of that +module. An independent module is a module which is not derived from +or based on this library. If you modify this library, you may extend +this exception to your version of the library, but you are not +obligated to do so. If you do not wish to do so, delete this +exception statement from your version. */ + + package java.lang.reflect; import java.lang.annotation.Annotation; @@ -29,6 +46,8 @@ import org.jnode.vm.classmgr.VmMethod; import gnu.java.lang.reflect.MethodSignatureParser; +import java.util.Arrays; + /** * The Method class represents a member method of a class. It also allows * dynamic invocation, via reflection. This works for both static and @@ -55,6 +74,8 @@ * @author Eric Blake <eb...@em...> * @see Member * @see Class + * @see java.lang.Class#getMethod(String,Class[]) + * @see java.lang.Class#getDeclaredMethod(String,Class[]) * @see java.lang.Class#getMethods() * @see java.lang.Class#getDeclaredMethods() * @since 1.1 @@ -319,8 +340,7 @@ * specification, version 3. * @since 1.5 */ - /* FIXME[GENERICS]: Should be TypeVariable<Method>[] */ - public TypeVariable[] getTypeParameters() + public TypeVariable<Method>[] getTypeParameters() { String sig = getSignature(); if (sig == null) @@ -338,13 +358,73 @@ return null; } + /** + * Returns an array of <code>Type</code> objects that represents + * the exception types declared by this method, in declaration order. + * An array of size zero is returned if this method declares no + * exceptions. + * + * @return the exception types declared by this method. + * @throws GenericSignatureFormatError if the generic signature does + * not conform to the format specified in the Virtual Machine + * specification, version 3. + * @since 1.5 + */ + public Type[] getGenericExceptionTypes() + { + String sig = getSignature(); + if (sig == null) + return getExceptionTypes(); + MethodSignatureParser p = new MethodSignatureParser(this, sig); + return p.getGenericExceptionTypes(); + } + /** + * Returns an array of <code>Type</code> objects that represents + * the parameter list for this method, in declaration order. + * An array of size zero is returned if this method takes no + * parameters. + * + * @return a list of the types of the method's parameters + * @throws GenericSignatureFormatError if the generic signature does + * not conform to the format specified in the Virtual Machine + * specification, version 3. + * @since 1.5 + */ + public Type[] getGenericParameterTypes() + { + String sig = getSignature(); + if (sig == null) + return getParameterTypes(); + MethodSignatureParser p = new MethodSignatureParser(this, sig); + return p.getGenericParameterTypes(); + } + + /** + * Returns the return type of this method. + * + * @return the return type of this method + * @throws GenericSignatureFormatError if the generic signature does + * not conform to the format specified in the Virtual Machine + * specification, version 3. + * @since 1.5 + */ + public Type getGenericReturnType() + { + String sig = getSignature(); + if (sig == null) + return getReturnType(); + MethodSignatureParser p = new MethodSignatureParser(this, sig); + return p.getGenericReturnType(); + } + /** * @see java.lang.reflect.AnnotatedElement#getAnnotation(java.lang.Class) */ public <T extends Annotation> T getAnnotation(Class<T> annotationClass) { return vmMethod.getAnnotation(annotationClass); } + /** * @see java.lang.reflect.AnnotatedElement#getAnnotations() */ This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <ls...@us...> - 2007-01-07 08:26:38
|
Revision: 3008 http://jnode.svn.sourceforge.net/jnode/?rev=3008&view=rev Author: lsantha Date: 2007-01-07 00:26:36 -0800 (Sun, 07 Jan 2007) Log Message: ----------- Classpath patches. Modified Paths: -------------- trunk/core/src/classpath/tools/gnu/classpath/tools/jar/Creator.java trunk/core/src/classpath/tools/gnu/classpath/tools/jar/Indexer.java trunk/core/src/classpath/tools/gnu/classpath/tools/jar/Main.java trunk/core/src/classpath/tools/gnu/classpath/tools/jar/WorkSet.java trunk/core/src/classpath/tools/gnu/classpath/tools/jarsigner/Main.java trunk/core/src/classpath/tools/gnu/classpath/tools/native2ascii/Native2ASCII.java trunk/core/src/classpath/tools/gnu/classpath/tools/serialver/SerialVer.java Modified: trunk/core/src/classpath/tools/gnu/classpath/tools/jar/Creator.java =================================================================== --- trunk/core/src/classpath/tools/gnu/classpath/tools/jar/Creator.java 2007-01-07 08:25:33 UTC (rev 3007) +++ trunk/core/src/classpath/tools/gnu/classpath/tools/jar/Creator.java 2007-01-07 08:26:36 UTC (rev 3008) @@ -60,7 +60,7 @@ extends Action { JarOutputStream outputStream; - HashSet writtenItems = new HashSet(); + HashSet<String> writtenItems = new HashSet<String>(); // The manifest to use, or null if we don't want a manifest. Manifest manifest; @@ -142,18 +142,21 @@ throws IOException { boolean isDirectory = file.isDirectory(); - InputStream inputStream = null; if (isDirectory) { if (filename.charAt(filename.length() - 1) != '/') filename += '/'; + writeFile(isDirectory, null, filename, verbose); } else - inputStream = new FileInputStream(file); + { + InputStream inputStream = new FileInputStream(file); writeFile(isDirectory, inputStream, filename, verbose); + inputStream.close(); + } } - private void addEntries(ArrayList result, Entry entry) + private void addEntries(ArrayList<Entry> result, Entry entry) { if (entry.file.isDirectory()) { @@ -173,10 +176,10 @@ result.add(entry); } - private ArrayList getAllEntries(Main parameters) + private ArrayList<Entry> getAllEntries(Main parameters) { Iterator it = parameters.entries.iterator(); - ArrayList allEntries = new ArrayList(); + ArrayList<Entry> allEntries = new ArrayList<Entry>(); while (it.hasNext()) { Entry entry = (Entry) it.next(); Modified: trunk/core/src/classpath/tools/gnu/classpath/tools/jar/Indexer.java =================================================================== --- trunk/core/src/classpath/tools/gnu/classpath/tools/jar/Indexer.java 2007-01-07 08:25:33 UTC (rev 3007) +++ trunk/core/src/classpath/tools/gnu/classpath/tools/jar/Indexer.java 2007-01-07 08:26:36 UTC (rev 3008) @@ -72,7 +72,7 @@ // Index the files in this jar. // The results look a little better if we keep them // in insertion order. - LinkedHashSet entries = new LinkedHashSet(); + LinkedHashSet<String> entries = new LinkedHashSet<String>(); Enumeration e = jf.entries(); while (e.hasMoreElements()) { Modified: trunk/core/src/classpath/tools/gnu/classpath/tools/jar/Main.java =================================================================== --- trunk/core/src/classpath/tools/gnu/classpath/tools/jar/Main.java 2007-01-07 08:25:33 UTC (rev 3007) +++ trunk/core/src/classpath/tools/gnu/classpath/tools/jar/Main.java 2007-01-07 08:26:36 UTC (rev 3008) @@ -78,7 +78,7 @@ File manifestFile; /** A list of Entry objects, each describing a file to write. */ - ArrayList entries = new ArrayList(); + ArrayList<Entry> entries = new ArrayList<Entry>(); /** Used only while parsing, holds the first argument for -C. */ String changedDirectory; Modified: trunk/core/src/classpath/tools/gnu/classpath/tools/jar/WorkSet.java =================================================================== --- trunk/core/src/classpath/tools/gnu/classpath/tools/jar/WorkSet.java 2007-01-07 08:25:33 UTC (rev 3007) +++ trunk/core/src/classpath/tools/gnu/classpath/tools/jar/WorkSet.java 2007-01-07 08:26:36 UTC (rev 3008) @@ -44,13 +44,13 @@ public class WorkSet { - private HashSet allItems; + private HashSet<String> allItems; private void initSet(ArrayList entries) { if (entries == null || entries.isEmpty()) return; - allItems = new HashSet(); + allItems = new HashSet<String>(); Iterator it = entries.iterator(); while (it.hasNext()) { Modified: trunk/core/src/classpath/tools/gnu/classpath/tools/jarsigner/Main.java =================================================================== --- trunk/core/src/classpath/tools/gnu/classpath/tools/jarsigner/Main.java 2007-01-07 08:25:33 UTC (rev 3007) +++ trunk/core/src/classpath/tools/gnu/classpath/tools/jarsigner/Main.java 2007-01-07 08:26:36 UTC (rev 3008) @@ -123,7 +123,7 @@ private CallbackHandler handler; /** The command line parser. */ private ToolParser cmdLineParser; - protected ArrayList fileAndAlias = new ArrayList();; + protected ArrayList fileAndAlias = new ArrayList(); private Main() { Modified: trunk/core/src/classpath/tools/gnu/classpath/tools/native2ascii/Native2ASCII.java =================================================================== --- trunk/core/src/classpath/tools/gnu/classpath/tools/native2ascii/Native2ASCII.java 2007-01-07 08:25:33 UTC (rev 3007) +++ trunk/core/src/classpath/tools/gnu/classpath/tools/native2ascii/Native2ASCII.java 2007-01-07 08:26:36 UTC (rev 3008) @@ -180,6 +180,5 @@ public static void main(String[] args) { new Native2ASCII().run(args); - String encoding = System.getProperty("file.encoding"); //$NON-NLS-1$ } } Modified: trunk/core/src/classpath/tools/gnu/classpath/tools/serialver/SerialVer.java =================================================================== --- trunk/core/src/classpath/tools/gnu/classpath/tools/serialver/SerialVer.java 2007-01-07 08:25:33 UTC (rev 3007) +++ trunk/core/src/classpath/tools/gnu/classpath/tools/serialver/SerialVer.java 2007-01-07 08:26:36 UTC (rev 3008) @@ -45,12 +45,12 @@ public class SerialVer { // List of classes to load. - ArrayList classes = new ArrayList(); + ArrayList<String> classes = new ArrayList<String>(); // The class path to use. String classpath; // FIXME: taken from ClassLoader, should share it. - private static void addFileURL(ArrayList list, String file) + private static void addFileURL(ArrayList<URL> list, String file) { try { @@ -72,7 +72,7 @@ { StringTokenizer tok = new StringTokenizer(classpath, File.pathSeparator, true); - ArrayList list = new ArrayList(); + ArrayList<URL> list = new ArrayList<URL>(); while (tok.hasMoreTokens()) { String s = tok.nextToken(); This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <ls...@us...> - 2007-01-07 08:25:34
|
Revision: 3007 http://jnode.svn.sourceforge.net/jnode/?rev=3007&view=rev Author: lsantha Date: 2007-01-07 00:25:33 -0800 (Sun, 07 Jan 2007) Log Message: ----------- Classpath patches. Modified Paths: -------------- trunk/core/src/classpath/javax/javax/sql/RowSet.java trunk/core/src/classpath/javax/javax/swing/border/CompoundBorder.java Modified: trunk/core/src/classpath/javax/javax/sql/RowSet.java =================================================================== --- trunk/core/src/classpath/javax/javax/sql/RowSet.java 2007-01-07 08:25:14 UTC (rev 3006) +++ trunk/core/src/classpath/javax/javax/sql/RowSet.java 2007-01-07 08:25:33 UTC (rev 3007) @@ -78,9 +78,9 @@ void setTransactionIsolation(int level) throws SQLException; - Map getTypeMap() throws SQLException; + Map<String, Class<?>> getTypeMap() throws SQLException; - void setTypeMap(Map map) throws SQLException; + void setTypeMap(Map<String, Class<?>> map) throws SQLException; String getCommand(); Modified: trunk/core/src/classpath/javax/javax/swing/border/CompoundBorder.java =================================================================== --- trunk/core/src/classpath/javax/javax/swing/border/CompoundBorder.java 2007-01-07 08:25:14 UTC (rev 3006) +++ trunk/core/src/classpath/javax/javax/swing/border/CompoundBorder.java 2007-01-07 08:25:33 UTC (rev 3007) @@ -115,15 +115,24 @@ */ public boolean isBorderOpaque() { - // While it would be safe to assume true for the opacity of - // a null border, this behavior would not be according to - // the API specification. Also, it is pathological to have - // null borders anyway. - if ((insideBorder == null) || (outsideBorder == null)) - return false; + // Although the API specification states that this method + // returns true if both the inside and outside borders are non-null + // and opaque, and false otherwise, a mauve test shows that if both + // the inside or outside borders are null, then true is returned. + if ((insideBorder == null) && (outsideBorder == null)) + return true; - return insideBorder.isBorderOpaque() - && outsideBorder.isBorderOpaque(); + // A mauve test shows that if the inside border has a null value, + // then true is returned if the outside border is opaque; if the + // outside border has a null value, then true is returned if the + // inside border is opaque; else, true is returned if both the + // inside and outside borders are opaque. + if (insideBorder == null) + return outsideBorder.isBorderOpaque(); + else if (outsideBorder == null) + return insideBorder.isBorderOpaque(); + else + return insideBorder.isBorderOpaque() && outsideBorder.isBorderOpaque(); } /** This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <ls...@us...> - 2007-01-07 08:25:15
|
Revision: 3006 http://jnode.svn.sourceforge.net/jnode/?rev=3006&view=rev Author: lsantha Date: 2007-01-07 00:25:14 -0800 (Sun, 07 Jan 2007) Log Message: ----------- Classpath patches. Modified Paths: -------------- trunk/core/src/classpath/javax/javax/xml/parsers/DocumentBuilderFactory.java trunk/core/src/classpath/javax/javax/xml/validation/SchemaFactory.java Modified: trunk/core/src/classpath/javax/javax/xml/parsers/DocumentBuilderFactory.java =================================================================== --- trunk/core/src/classpath/javax/javax/xml/parsers/DocumentBuilderFactory.java 2007-01-07 08:24:57 UTC (rev 3005) +++ trunk/core/src/classpath/javax/javax/xml/parsers/DocumentBuilderFactory.java 2007-01-07 08:25:14 UTC (rev 3006) @@ -50,7 +50,7 @@ * Factory for obtaining document builders. * Instances of this class are <em>not</em> guaranteed to be thread safe. * - * @author (a href='mailto:do...@gn...'>Chris Burdess</a) + * @author <a href='mailto:do...@gn...'>Chris Burdess</a> */ public abstract class DocumentBuilderFactory { Modified: trunk/core/src/classpath/javax/javax/xml/validation/SchemaFactory.java =================================================================== --- trunk/core/src/classpath/javax/javax/xml/validation/SchemaFactory.java 2007-01-07 08:24:57 UTC (rev 3005) +++ trunk/core/src/classpath/javax/javax/xml/validation/SchemaFactory.java 2007-01-07 08:25:14 UTC (rev 3006) @@ -37,8 +37,14 @@ package javax.xml.validation; +import java.io.BufferedReader; import java.io.File; +import java.io.FileInputStream; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.IOException; import java.net.URL; +import java.util.Properties; import javax.xml.XMLConstants; import javax.xml.transform.Source; import javax.xml.transform.stream.StreamSource; @@ -68,6 +74,71 @@ */ public static final SchemaFactory newInstance(String schemaLanguage) { + ClassLoader loader = Thread.currentThread().getContextClassLoader(); + if (loader == null) + { + loader = SchemaFactory.class.getClassLoader(); + } + final String factoryClassName = "javax.xml.validation.SchemaFactory"; + String className = null; + int count = 0; + do + { + className = getFactoryClassName(loader, schemaLanguage, count++); + if (className != null) + { + try + { + Class t = (loader != null) ? loader.loadClass(className) : + Class.forName(className); + return (SchemaFactory) t.newInstance(); + } + catch (Exception e) + { + // Ignore any errors and continue algorithm. + // This method doesn't have a means of propagating + // class instantiation errors. + className = null; + } + } + } + while (className == null && count < 2); + try + { + String serviceKey = "/META-INF/services/" + factoryClassName; + InputStream in = (loader != null) ? + loader.getResourceAsStream(serviceKey) : + SchemaFactory.class.getResourceAsStream(serviceKey); + if (in != null) + { + BufferedReader r = + new BufferedReader(new InputStreamReader(in)); + try + { + for (String line = r.readLine(); line != null; + line = r.readLine()) + { + Class t = (loader != null) ? loader.loadClass(className) : + Class.forName(className); + SchemaFactory ret = (SchemaFactory) t.newInstance(); + if (ret.isSchemaLanguageSupported(schemaLanguage)) + return ret; + } + } + catch (Exception e) + { + // Fall through. See above. + } + finally + { + r.close(); + } + } + } + catch (IOException e) + { + } + // Default schema factories for Classpath if (XMLConstants.W3C_XML_SCHEMA_NS_URI.equals(schemaLanguage)) return new gnu.xml.validation.xmlschema.XMLSchemaSchemaFactory(); if (XMLConstants.RELAXNG_NS_URI.equals(schemaLanguage)) @@ -75,6 +146,36 @@ throw new IllegalArgumentException(schemaLanguage); } + private static String getFactoryClassName(ClassLoader loader, + String schemaLanguage, int attempt) + { + final String factoryClassName = "javax.xml.validation.SchemaFactory"; + final String propertyName = factoryClassName + ":" + schemaLanguage; + switch (attempt) + { + case 0: + return System.getProperty(propertyName); + case 1: + try + { + File file = new File(System.getProperty("java.home")); + file = new File(file, "lib"); + file = new File(file, "jaxp.properties"); + InputStream in = new FileInputStream(file); + Properties props = new Properties(); + props.load(in); + in.close(); + return props.getProperty(propertyName); + } + catch (IOException e) + { + return null; + } + default: + return null; + } + } + /** * Indicates whether the specified schema language is supported. * @param schemaLanguage the URI of a schema language (see This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <ls...@us...> - 2007-01-07 08:24:58
|
Revision: 3005 http://jnode.svn.sourceforge.net/jnode/?rev=3005&view=rev Author: lsantha Date: 2007-01-07 00:24:57 -0800 (Sun, 07 Jan 2007) Log Message: ----------- Classpath patches. Modified Paths: -------------- trunk/core/src/classpath/org/org/omg/CORBA/ORB.java trunk/core/src/classpath/org/org/omg/CosNaming/_NamingContextExtImplBase.java trunk/core/src/classpath/org/org/omg/CosNaming/_NamingContextImplBase.java Modified: trunk/core/src/classpath/org/org/omg/CORBA/ORB.java =================================================================== --- trunk/core/src/classpath/org/org/omg/CORBA/ORB.java 2007-01-07 08:24:38 UTC (rev 3004) +++ trunk/core/src/classpath/org/org/omg/CORBA/ORB.java 2007-01-07 08:24:57 UTC (rev 3005) @@ -208,6 +208,34 @@ } /** + * Create a typecode, representing a tree-like structure. + * This structure contains a member that is a sequence of the same type, + * as the structure itself. You can imagine as if the folder definition + * contains a variable-length array of the enclosed (nested) folder + * definitions. In this way, it is possible to have a tree like + * structure that can be transferred via CORBA CDR stream. + * + * @deprecated It is easier and clearler to use a combination of + * create_recursive_tc and create_sequence_tc instead. + * + * @param bound the maximal expected number of the nested components + * on each node; 0 if not limited. + * + * @param offset the position of the field in the returned structure + * that contains the sequence of the structures of the same field. + * The members before this field are intialised using parameterless + * StructMember constructor. + * + * @return a typecode, defining a stucture, where a member at the + * <code>offset</code> position defines an array of the identical + * structures. + * + * @see #create_recursive_tc(String) + * @see #create_sequence_tc(int, TypeCode) + */ + public abstract TypeCode create_recursive_sequence_tc(int bound, int offset); + + /** * Create alias typecode for the given typecode. */ public abstract TypeCode create_alias_tc(String id, String name, @@ -252,7 +280,6 @@ { throw new NO_IMPLEMENT(); } - ; /** * The support for {@link DynAny} and derived interfaces @@ -268,7 +295,6 @@ { throw new NO_IMPLEMENT(); } - ; /** * The support for {@link DynArray} @@ -285,7 +311,6 @@ { throw new NO_IMPLEMENT(); } - ; /** * The support for {@link DynEnum} @@ -302,7 +327,6 @@ { throw new NO_IMPLEMENT(); } - ; /** * The support for {@link DynSequence} @@ -319,7 +343,6 @@ { throw new NO_IMPLEMENT(); } - ; /** * The support for {@link DynStruct} and derived interfaces @@ -336,7 +359,6 @@ { throw new NO_IMPLEMENT(); } - ; /** * The support for {@link DynUnion} and derived interfaces @@ -353,7 +375,6 @@ { throw new NO_IMPLEMENT(); } - ; /** * Create a typecode, defining the given enumeration. @@ -645,33 +666,6 @@ return t; } - /** - * Create a typecode, representing a tree-like structure. - * This structure contains a member that is a sequence of the same type, - * as the structure itself. You can imagine as if the folder definition - * contains a variable-length array of the enclosed (nested) folder - * definitions. In this way, it is possible to have a tree like - * structure that can be transferred via CORBA CDR stream. - * - * @deprecated It is easier and clearler to use a combination of - * create_recursive_tc and create_sequence_tc instead. - * - * @param bound the maximal expected number of the nested components - * on each node; 0 if not limited. - * - * @param offset the position of the field in the returned structure - * that contains the sequence of the structures of the same field. - * The members before this field are intialised using parameterless - * StructMember constructor. - * - * @return a typecode, defining a stucture, where a member at the - * <code>offset</code> position defines an array of the identical - * structures. - * - * @see #create_recursive_tc(String) - * @see #create_sequence_tc(int, TypeCode) - */ - public abstract TypeCode create_recursive_sequence_tc(int bound, int offset); /** * Create a typecode which serves as a placeholder for typcode, containing Modified: trunk/core/src/classpath/org/org/omg/CosNaming/_NamingContextExtImplBase.java =================================================================== --- trunk/core/src/classpath/org/org/omg/CosNaming/_NamingContextExtImplBase.java 2007-01-07 08:24:38 UTC (rev 3004) +++ trunk/core/src/classpath/org/org/omg/CosNaming/_NamingContextExtImplBase.java 2007-01-07 08:24:57 UTC (rev 3005) @@ -66,7 +66,7 @@ extends _NamingContextImplBase implements NamingContextExt, InvokeHandler { - static Hashtable _methods = new Hashtable(); + static Hashtable<String,Integer> _methods = new Hashtable<String,Integer>(); static { Modified: trunk/core/src/classpath/org/org/omg/CosNaming/_NamingContextImplBase.java =================================================================== --- trunk/core/src/classpath/org/org/omg/CosNaming/_NamingContextImplBase.java 2007-01-07 08:24:38 UTC (rev 3004) +++ trunk/core/src/classpath/org/org/omg/CosNaming/_NamingContextImplBase.java 2007-01-07 08:24:57 UTC (rev 3005) @@ -82,7 +82,7 @@ * As there are quite many methods, it may be sensible to use the hashtable. * This field is also reused in NamingContextPOA. */ - static Hashtable methods = new Hashtable(); + static Hashtable<String,Integer> methods = new Hashtable<String,Integer>(); /** * Put all methods into the table. This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <ls...@us...> - 2007-01-07 08:24:39
|
Revision: 3004 http://jnode.svn.sourceforge.net/jnode/?rev=3004&view=rev Author: lsantha Date: 2007-01-07 00:24:38 -0800 (Sun, 07 Jan 2007) Log Message: ----------- Classpath patches. Modified Paths: -------------- trunk/core/src/classpath/javax/javax/security/auth/Subject.java trunk/core/src/classpath/javax/javax/security/auth/login/AppConfigurationEntry.java trunk/core/src/classpath/javax/javax/security/auth/spi/LoginModule.java Modified: trunk/core/src/classpath/javax/javax/security/auth/Subject.java =================================================================== --- trunk/core/src/classpath/javax/javax/security/auth/Subject.java 2007-01-07 08:23:33 UTC (rev 3003) +++ trunk/core/src/classpath/javax/javax/security/auth/Subject.java 2007-01-07 08:24:38 UTC (rev 3004) @@ -91,8 +91,9 @@ readOnly = false; } - public Subject (final boolean readOnly, final Set principals, - final Set pubCred, final Set privCred) + public Subject (final boolean readOnly, + final Set<? extends Principal> principals, + final Set<?> pubCred, final Set<?> privCred) { if (principals == null || pubCred == null || privCred == null) { @@ -265,12 +266,12 @@ privCred.containsAll (that.getPrivateCredentials()); } - public Set getPrincipals() + public Set<Principal> getPrincipals() { return principals; } - public Set getPrincipals(Class clazz) + public <T extends Principal> Set<T> getPrincipals(Class<T> clazz) { HashSet result = new HashSet (principals.size()); for (Iterator it = principals.iterator(); it.hasNext(); ) @@ -284,12 +285,12 @@ return Collections.unmodifiableSet (result); } - public Set getPrivateCredentials() + public Set<Object> getPrivateCredentials() { return privCred; } - public Set getPrivateCredentials (Class clazz) + public <T> Set<T> getPrivateCredentials (Class<T> clazz) { HashSet result = new HashSet (privCred.size()); for (Iterator it = privCred.iterator(); it.hasNext(); ) @@ -303,12 +304,12 @@ return Collections.unmodifiableSet (result); } - public Set getPublicCredentials() + public Set<Object> getPublicCredentials() { return pubCred; } - public Set getPublicCredentials (Class clazz) + public <T> Set<T> getPublicCredentials (Class<T> clazz) { HashSet result = new HashSet (pubCred.size()); for (Iterator it = pubCred.iterator(); it.hasNext(); ) Modified: trunk/core/src/classpath/javax/javax/security/auth/login/AppConfigurationEntry.java =================================================================== --- trunk/core/src/classpath/javax/javax/security/auth/login/AppConfigurationEntry.java 2007-01-07 08:23:33 UTC (rev 3003) +++ trunk/core/src/classpath/javax/javax/security/auth/login/AppConfigurationEntry.java 2007-01-07 08:24:38 UTC (rev 3004) @@ -56,7 +56,7 @@ public AppConfigurationEntry (final String loginModuleName, final LoginModuleControlFlag controlFlag, - final Map options) + final Map<String, ?> options) { if (loginModuleName == null || loginModuleName.length() == 0) throw new IllegalArgumentException ("module name cannot be null nor empty"); @@ -88,7 +88,7 @@ return loginModuleName; } - public Map getOptions() + public Map<String, ?> getOptions() { return options; } Modified: trunk/core/src/classpath/javax/javax/security/auth/spi/LoginModule.java =================================================================== --- trunk/core/src/classpath/javax/javax/security/auth/spi/LoginModule.java 2007-01-07 08:23:33 UTC (rev 3003) +++ trunk/core/src/classpath/javax/javax/security/auth/spi/LoginModule.java 2007-01-07 08:24:38 UTC (rev 3004) @@ -95,7 +95,7 @@ * @param options A mapping of options given to this module. */ void initialize(Subject subject, CallbackHandler handler, - Map sharedState, Map options); + Map<String, ?> sharedState, Map<String, ?> options); /** * Authenticates a subject to the system. This is the primary This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <ls...@us...> - 2007-01-07 08:23:34
|
Revision: 3003 http://jnode.svn.sourceforge.net/jnode/?rev=3003&view=rev Author: lsantha Date: 2007-01-07 00:23:33 -0800 (Sun, 07 Jan 2007) Log Message: ----------- Classpath patches. Modified Paths: -------------- trunk/core/src/classpath/javax/javax/sound/midi/Instrument.java trunk/core/src/classpath/javax/javax/sound/midi/Sequence.java trunk/core/src/classpath/javax/javax/sound/midi/SoundbankResource.java trunk/core/src/classpath/javax/javax/sound/sampled/AudioFileFormat.java trunk/core/src/classpath/javax/javax/sound/sampled/AudioFormat.java trunk/core/src/classpath/javax/javax/sound/sampled/AudioSystem.java trunk/core/src/classpath/javax/javax/sound/sampled/BooleanControl.java trunk/core/src/classpath/javax/javax/sound/sampled/DataLine.java trunk/core/src/classpath/javax/javax/sound/sampled/Line.java trunk/core/src/classpath/javax/javax/sound/sampled/Port.java Modified: trunk/core/src/classpath/javax/javax/sound/midi/Instrument.java =================================================================== --- trunk/core/src/classpath/javax/javax/sound/midi/Instrument.java 2007-01-07 08:23:15 UTC (rev 3002) +++ trunk/core/src/classpath/javax/javax/sound/midi/Instrument.java 2007-01-07 08:23:33 UTC (rev 3003) @@ -59,7 +59,7 @@ * @param dataClass the class used to represent sample data for this instrument */ protected Instrument(Soundbank soundbank, Patch patch, - String name, Class dataClass) + String name, Class<?> dataClass) { super(soundbank, name, dataClass); this.patch = patch; Modified: trunk/core/src/classpath/javax/javax/sound/midi/Sequence.java =================================================================== --- trunk/core/src/classpath/javax/javax/sound/midi/Sequence.java 2007-01-07 08:23:15 UTC (rev 3002) +++ trunk/core/src/classpath/javax/javax/sound/midi/Sequence.java 2007-01-07 08:23:33 UTC (rev 3003) @@ -65,7 +65,7 @@ /** * The MIDI tracks used by this sequence. */ - protected Vector tracks; + protected Vector<Track> tracks; /** * Tempo-based timing. Resolution is specified in ticks per beat. @@ -107,7 +107,7 @@ this.divisionType = divisionType; this.resolution = resolution; - tracks = new Vector(numTracks); + tracks = new Vector<Track>(numTracks); while (numTracks > 0) tracks.set(--numTracks, new Track()); } @@ -189,7 +189,7 @@ */ public Track[] getTracks() { - return (Track[]) tracks.toArray(new Track[tracks.size()]); + return tracks.toArray(new Track[tracks.size()]); } /** @@ -224,10 +224,10 @@ public long getTickLength() { long length = 0; - Iterator itr = tracks.iterator(); + Iterator<Track> itr = tracks.iterator(); while (itr.hasNext()) { - Track track = (Track) itr.next(); + Track track = itr.next(); long trackTicks = track.ticks(); if (trackTicks > length) length = trackTicks; Modified: trunk/core/src/classpath/javax/javax/sound/midi/SoundbankResource.java =================================================================== --- trunk/core/src/classpath/javax/javax/sound/midi/SoundbankResource.java 2007-01-07 08:23:15 UTC (rev 3002) +++ trunk/core/src/classpath/javax/javax/sound/midi/SoundbankResource.java 2007-01-07 08:23:33 UTC (rev 3003) @@ -58,7 +58,7 @@ * @param name the name of the resource * @param dataClass the class used to represent the audio data */ - protected SoundbankResource(Soundbank soundbank, String name, Class dataClass) + protected SoundbankResource(Soundbank soundbank, String name, Class<?> dataClass) { this.soundbank = soundbank; this.name = name; @@ -90,7 +90,7 @@ * * @return the class used to represent the audio data for this resource */ - public Class getDataClass() + public Class<?> getDataClass() { return dataClass; } Modified: trunk/core/src/classpath/javax/javax/sound/sampled/AudioFileFormat.java =================================================================== --- trunk/core/src/classpath/javax/javax/sound/sampled/AudioFileFormat.java 2007-01-07 08:23:15 UTC (rev 3002) +++ trunk/core/src/classpath/javax/javax/sound/sampled/AudioFileFormat.java 2007-01-07 08:23:33 UTC (rev 3003) @@ -122,7 +122,7 @@ private AudioFormat format; private Type type; private int frameLength; - private Map properties; + private Map<String, Object> properties; /** * Create a new AudioFileFormat given the type, the format, and the @@ -138,7 +138,7 @@ this.format = fmt; this.type = type; this.frameLength = frameLen; - this.properties = Collections.EMPTY_MAP; + this.properties = Collections.<String, Object> emptyMap(); } /** @@ -153,13 +153,13 @@ * @param properties the properties */ public AudioFileFormat(Type type, AudioFormat fmt, int frameLen, - Map properties) + Map<String, Object> properties) { this.byteLength = AudioSystem.NOT_SPECIFIED; this.format = fmt; this.type = type; this.frameLength = frameLen; - this.properties = Collections.unmodifiableMap(new HashMap(properties)); + this.properties = Collections.unmodifiableMap(new HashMap<String, Object>(properties)); } /** @@ -177,7 +177,7 @@ this.format = fmt; this.type = type; this.frameLength = frameLen; - this.properties = Collections.EMPTY_MAP; + this.properties = Collections.<String, Object> emptyMap(); } /** @@ -226,7 +226,7 @@ * Return the properties associated with this format, as a Map. * The returned Map is unmodifiable. */ - public Map properties() + public Map<String, Object> properties() { return properties; } Modified: trunk/core/src/classpath/javax/javax/sound/sampled/AudioFormat.java =================================================================== --- trunk/core/src/classpath/javax/javax/sound/sampled/AudioFormat.java 2007-01-07 08:23:15 UTC (rev 3002) +++ trunk/core/src/classpath/javax/javax/sound/sampled/AudioFormat.java 2007-01-07 08:23:33 UTC (rev 3003) @@ -133,7 +133,7 @@ */ protected int sampleSizeInBits; - private Map properties; + private Map<String, Object> properties; /** * Create a new audio format, given various attributes of it. @@ -158,7 +158,7 @@ this.frameSize = frameSize; this.frameRate = frameRate; this.bigEndian = bigEndian; - this.properties = Collections.EMPTY_MAP; + this.properties = Collections.<String, Object> emptyMap(); } /** @@ -177,7 +177,7 @@ */ public AudioFormat(Encoding encoding, float sampleRate, int sampleSizeInBits, int channels, int frameSize, float frameRate, - boolean bigEndian, Map properties) + boolean bigEndian, Map<String, Object> properties) { this.encoding = encoding; this.sampleRate = sampleRate; @@ -186,7 +186,7 @@ this.frameSize = frameSize; this.frameRate = frameRate; this.bigEndian = bigEndian; - this.properties = Collections.unmodifiableMap(new HashMap(properties)); + this.properties = Collections.unmodifiableMap(new HashMap<String, Object>(properties)); } /** @@ -218,7 +218,7 @@ this.frameSize = (sampleSizeInBits + 7) / 8 * channels; this.frameRate = sampleRate; this.bigEndian = bigEndian; - this.properties = Collections.EMPTY_MAP; + this.properties = Collections.<String, Object> emptyMap(); } /** @@ -319,7 +319,7 @@ * Return a read-only Map holding the properties associated with * this format. */ - public Map properties() + public Map<String, Object> properties() { return properties; } Modified: trunk/core/src/classpath/javax/javax/sound/sampled/AudioSystem.java =================================================================== --- trunk/core/src/classpath/javax/javax/sound/sampled/AudioSystem.java 2007-01-07 08:23:15 UTC (rev 3002) +++ trunk/core/src/classpath/javax/javax/sound/sampled/AudioSystem.java 2007-01-07 08:23:33 UTC (rev 3003) @@ -160,7 +160,8 @@ */ public static AudioFileFormat.Type[] getAudioFileTypes() { - HashSet result = new HashSet(); + HashSet<AudioFileFormat.Type> result + = new HashSet<AudioFileFormat.Type>(); Iterator i = ServiceFactory.lookupProviders(AudioFileWriter.class); while (i.hasNext()) { @@ -169,7 +170,7 @@ for (int j = 0; j < types.length; ++j) result.add(types[j]); } - return (AudioFileFormat.Type[]) result.toArray(new AudioFileFormat.Type[result.size()]); + return result.toArray(new AudioFileFormat.Type[result.size()]); } /** @@ -180,7 +181,8 @@ */ public static AudioFileFormat.Type[] getAudioFileTypes(AudioInputStream ais) { - HashSet result = new HashSet(); + HashSet<AudioFileFormat.Type> result + = new HashSet<AudioFileFormat.Type>(); Iterator i = ServiceFactory.lookupProviders(AudioFileWriter.class); while (i.hasNext()) { @@ -189,7 +191,7 @@ for (int j = 0; j < types.length; ++j) result.add(types[j]); } - return (AudioFileFormat.Type[]) result.toArray(new AudioFileFormat.Type[result.size()]); + return result.toArray(new AudioFileFormat.Type[result.size()]); } /** @@ -204,7 +206,6 @@ public static AudioInputStream getAudioInputStream(AudioFormat.Encoding targ, AudioInputStream ais) { - HashSet result = new HashSet(); Iterator i = ServiceFactory.lookupProviders(FormatConversionProvider.class); while (i.hasNext()) { @@ -228,7 +229,6 @@ public static AudioInputStream getAudioInputStream(AudioFormat targ, AudioInputStream ais) { - HashSet result = new HashSet(); Iterator i = ServiceFactory.lookupProviders(FormatConversionProvider.class); while (i.hasNext()) { @@ -416,7 +416,7 @@ */ public static Mixer.Info[] getMixerInfo() { - HashSet result = new HashSet(); + HashSet<Mixer.Info> result = new HashSet<Mixer.Info>(); Iterator i = ServiceFactory.lookupProviders(MixerProvider.class); while (i.hasNext()) { @@ -425,7 +425,7 @@ for (int j = 0; j < is.length; ++j) result.add(is[j]); } - return (Mixer.Info[]) result.toArray(new Mixer.Info[result.size()]); + return result.toArray(new Mixer.Info[result.size()]); } /** @@ -474,7 +474,7 @@ */ public static Line.Info[] getSourceLineInfo(Line.Info info) { - HashSet result = new HashSet(); + HashSet<Line.Info> result = new HashSet<Line.Info>(); Mixer.Info[] infos = getMixerInfo(); for (int i = 0; i < infos.length; ++i) { @@ -483,7 +483,7 @@ for (int j = 0; j < srcs.length; ++j) result.add(srcs[j]); } - return (Line.Info[]) result.toArray(new Line.Info[result.size()]); + return result.toArray(new Line.Info[result.size()]); } /** @@ -534,7 +534,8 @@ */ public static AudioFormat.Encoding[] getTargetEncodings(AudioFormat.Encoding source) { - HashSet result = new HashSet(); + HashSet<AudioFormat.Encoding> result + = new HashSet<AudioFormat.Encoding>(); Iterator i = ServiceFactory.lookupProviders(FormatConversionProvider.class); while (i.hasNext()) { @@ -545,7 +546,7 @@ for (int j = 0; j < es.length; ++j) result.add(es[j]); } - return (AudioFormat.Encoding[]) result.toArray(new AudioFormat.Encoding[result.size()]); + return result.toArray(new AudioFormat.Encoding[result.size()]); } /** @@ -555,7 +556,8 @@ */ public static AudioFormat.Encoding[] getTargetEncodings(AudioFormat source) { - HashSet result = new HashSet(); + HashSet<AudioFormat.Encoding> result + = new HashSet<AudioFormat.Encoding>(); Iterator i = ServiceFactory.lookupProviders(FormatConversionProvider.class); while (i.hasNext()) { @@ -564,7 +566,7 @@ for (int j = 0; j < es.length; ++j) result.add(es[j]); } - return (AudioFormat.Encoding[]) result.toArray(new AudioFormat.Encoding[result.size()]); + return result.toArray(new AudioFormat.Encoding[result.size()]); } /** @@ -576,7 +578,7 @@ public static AudioFormat[] getTargetFormats(AudioFormat.Encoding encoding, AudioFormat sourceFmt) { - HashSet result = new HashSet(); + HashSet<AudioFormat> result = new HashSet<AudioFormat>(); Iterator i = ServiceFactory.lookupProviders(FormatConversionProvider.class); while (i.hasNext()) { @@ -585,7 +587,7 @@ for (int j = 0; j < es.length; ++j) result.add(es[j]); } - return (AudioFormat[]) result.toArray(new AudioFormat[result.size()]); + return result.toArray(new AudioFormat[result.size()]); } /** @@ -595,7 +597,7 @@ */ public static Line.Info[] getTargetLineInfo(Line.Info info) { - HashSet result = new HashSet(); + HashSet<Line.Info> result = new HashSet<Line.Info>(); Mixer.Info[] infos = getMixerInfo(); for (int i = 0; i < infos.length; ++i) { @@ -604,7 +606,7 @@ for (int j = 0; j < targs.length; ++j) result.add(targs[j]); } - return (Line.Info[]) result.toArray(new Line.Info[result.size()]); + return result.toArray(new Line.Info[result.size()]); } /** Modified: trunk/core/src/classpath/javax/javax/sound/sampled/BooleanControl.java =================================================================== --- trunk/core/src/classpath/javax/javax/sound/sampled/BooleanControl.java 2007-01-07 08:23:15 UTC (rev 3002) +++ trunk/core/src/classpath/javax/javax/sound/sampled/BooleanControl.java 2007-01-07 08:23:33 UTC (rev 3003) @@ -72,7 +72,6 @@ } } - private Type type; private boolean value; private String trueLabel; private String falseLabel; Modified: trunk/core/src/classpath/javax/javax/sound/sampled/DataLine.java =================================================================== --- trunk/core/src/classpath/javax/javax/sound/sampled/DataLine.java 2007-01-07 08:23:15 UTC (rev 3002) +++ trunk/core/src/classpath/javax/javax/sound/sampled/DataLine.java 2007-01-07 08:23:33 UTC (rev 3003) @@ -64,7 +64,7 @@ * @param klass the class of the line * @param fmt the supported format */ - public Info(Class klass, AudioFormat fmt) + public Info(Class<?> klass, AudioFormat fmt) { super(klass); this.minBufferSize = AudioSystem.NOT_SPECIFIED; @@ -80,7 +80,7 @@ * @param minSize the minimum buffer size * @param maxSize the maximum buffer size */ - public Info(Class klass, AudioFormat[] fmts, int minSize, int maxSize) + public Info(Class<?> klass, AudioFormat[] fmts, int minSize, int maxSize) { super(klass); this.minBufferSize = minSize; @@ -96,7 +96,7 @@ * @param fmt the supported format * @param size the buffer size */ - public Info(Class klass, AudioFormat fmt, int size) + public Info(Class<?> klass, AudioFormat fmt, int size) { super(klass); this.minBufferSize = size; Modified: trunk/core/src/classpath/javax/javax/sound/sampled/Line.java =================================================================== --- trunk/core/src/classpath/javax/javax/sound/sampled/Line.java 2007-01-07 08:23:15 UTC (rev 3002) +++ trunk/core/src/classpath/javax/javax/sound/sampled/Line.java 2007-01-07 08:23:33 UTC (rev 3003) @@ -57,7 +57,7 @@ * for instance TargetDataLine.class. * @param klass the class of the line */ - public Info(Class klass) + public Info(Class<?> klass) { this.klass = klass; } @@ -65,7 +65,7 @@ /** * Return the line's class. */ - public Class getLineClass() + public Class<?> getLineClass() { return klass; } Modified: trunk/core/src/classpath/javax/javax/sound/sampled/Port.java =================================================================== --- trunk/core/src/classpath/javax/javax/sound/sampled/Port.java 2007-01-07 08:23:15 UTC (rev 3002) +++ trunk/core/src/classpath/javax/javax/sound/sampled/Port.java 2007-01-07 08:23:33 UTC (rev 3003) @@ -89,7 +89,7 @@ * @param name the name of the line * @param isSource true if this is an input source */ - public Info(Class klass, String name, boolean isSource) + public Info(Class<?> klass, String name, boolean isSource) { super(klass); this.name = name; This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <ls...@us...> - 2007-01-07 08:23:17
|
Revision: 3002 http://jnode.svn.sourceforge.net/jnode/?rev=3002&view=rev Author: lsantha Date: 2007-01-07 00:23:15 -0800 (Sun, 07 Jan 2007) Log Message: ----------- Classpath patches. Modified Paths: -------------- trunk/core/src/classpath/javax/javax/rmi/CORBA/Tie.java Modified: trunk/core/src/classpath/javax/javax/rmi/CORBA/Tie.java =================================================================== --- trunk/core/src/classpath/javax/javax/rmi/CORBA/Tie.java 2007-01-07 08:22:57 UTC (rev 3001) +++ trunk/core/src/classpath/javax/javax/rmi/CORBA/Tie.java 2007-01-07 08:23:15 UTC (rev 3002) @@ -103,7 +103,7 @@ /** * Get the object that delegates calls to this tie. * - * @see org.omg.PortableServer.Servant#_this_object + * @see org.omg.PortableServer.Servant#_this_object() */ org.omg.CORBA.Object thisObject(); @@ -112,12 +112,12 @@ * Depending on the POA policies, it may be possible to activate the Tie * again. The ties that are not derived from * {@link org.omg.PortableServer.Servant} deactivate themselves by - * {@link ORB.disconnect}. + * {@link ORB#disconnect}. * * @throws NoSuchObjectException if there are no objects served by this Tie, * or if the these objects are already deactivated. * - * @see org.omg.PortableServer.POA#deactivate_object + * @see org.omg.PortableServer.POAOperations#deactivate_object */ void deactivate() throws NoSuchObjectException; This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <ls...@us...> - 2007-01-07 08:23:00
|
Revision: 3001 http://jnode.svn.sourceforge.net/jnode/?rev=3001&view=rev Author: lsantha Date: 2007-01-07 00:22:57 -0800 (Sun, 07 Jan 2007) Log Message: ----------- Classpath patches. Modified Paths: -------------- trunk/core/src/classpath/javax/javax/naming/CannotProceedException.java trunk/core/src/classpath/javax/javax/naming/CompositeName.java trunk/core/src/classpath/javax/javax/naming/CompoundName.java trunk/core/src/classpath/javax/javax/naming/Context.java trunk/core/src/classpath/javax/javax/naming/InitialContext.java trunk/core/src/classpath/javax/javax/naming/Name.java trunk/core/src/classpath/javax/javax/naming/NamingEnumeration.java trunk/core/src/classpath/javax/javax/naming/Reference.java trunk/core/src/classpath/javax/javax/naming/ReferralException.java trunk/core/src/classpath/javax/javax/naming/directory/Attribute.java trunk/core/src/classpath/javax/javax/naming/directory/Attributes.java trunk/core/src/classpath/javax/javax/naming/directory/BasicAttribute.java trunk/core/src/classpath/javax/javax/naming/directory/BasicAttributes.java trunk/core/src/classpath/javax/javax/naming/directory/DirContext.java trunk/core/src/classpath/javax/javax/naming/directory/InitialDirContext.java trunk/core/src/classpath/javax/javax/naming/ldap/ControlFactory.java trunk/core/src/classpath/javax/javax/naming/ldap/InitialLdapContext.java trunk/core/src/classpath/javax/javax/naming/ldap/LdapReferralException.java trunk/core/src/classpath/javax/javax/naming/spi/DirObjectFactory.java trunk/core/src/classpath/javax/javax/naming/spi/DirStateFactory.java trunk/core/src/classpath/javax/javax/naming/spi/DirectoryManager.java trunk/core/src/classpath/javax/javax/naming/spi/InitialContextFactory.java trunk/core/src/classpath/javax/javax/naming/spi/InitialContextFactoryBuilder.java trunk/core/src/classpath/javax/javax/naming/spi/NamingManager.java trunk/core/src/classpath/javax/javax/naming/spi/ObjectFactory.java trunk/core/src/classpath/javax/javax/naming/spi/ObjectFactoryBuilder.java trunk/core/src/classpath/javax/javax/naming/spi/Resolver.java trunk/core/src/classpath/javax/javax/naming/spi/StateFactory.java Modified: trunk/core/src/classpath/javax/javax/naming/CannotProceedException.java =================================================================== --- trunk/core/src/classpath/javax/javax/naming/CannotProceedException.java 2007-01-07 08:22:28 UTC (rev 3000) +++ trunk/core/src/classpath/javax/javax/naming/CannotProceedException.java 2007-01-07 08:22:57 UTC (rev 3001) @@ -51,7 +51,7 @@ // Serialized fields. protected Name remainingNewName; - protected Hashtable environment; + protected Hashtable<?, ?> environment; protected Name altName; protected Context altNameCtx; @@ -65,12 +65,12 @@ super (msg); } - public Hashtable getEnvironment() + public Hashtable<?, ?> getEnvironment() { return environment; } - public void setEnvironment(Hashtable environment) + public void setEnvironment(Hashtable<?, ?> environment) { this.environment = environment; } Modified: trunk/core/src/classpath/javax/javax/naming/CompositeName.java =================================================================== --- trunk/core/src/classpath/javax/javax/naming/CompositeName.java 2007-01-07 08:22:28 UTC (rev 3000) +++ trunk/core/src/classpath/javax/javax/naming/CompositeName.java 2007-01-07 08:22:57 UTC (rev 3001) @@ -58,16 +58,16 @@ { private static final long serialVersionUID = 1667768148915813118L; - private transient Vector elts; + private transient Vector<String> elts; public CompositeName () { - elts = new Vector (); + elts = new Vector<String> (); } - protected CompositeName (Enumeration comps) + protected CompositeName (Enumeration<String> comps) { - elts = new Vector (); + elts = new Vector<String> (); try { while (comps.hasMoreElements ()) @@ -80,7 +80,7 @@ public CompositeName (String n) throws InvalidNameException { - elts = new Vector (); + elts = new Vector<String> (); // Parse the string into its components. final char no_quote = 'x'; // Use 'x' to mean no quoting. char quote = no_quote; @@ -151,7 +151,7 @@ public Name addAll (int posn, Name n) throws InvalidNameException { - Enumeration e = n.getAll (); + Enumeration<String> e = n.getAll (); try { while (e.hasMoreElements ()) @@ -168,7 +168,7 @@ public Name addAll (Name suffix) throws InvalidNameException { - Enumeration e = suffix.getAll (); + Enumeration<String> e = suffix.getAll (); try { while (e.hasMoreElements ()) @@ -193,8 +193,8 @@ int last = Math.min (cn.elts.size (), elts.size ()); for (int i = 0; i < last; ++i) { - String f = (String) elts.get (i); - int comp = f.compareTo ((String) cn.elts.get (i)); + String f = elts.get (i); + int comp = f.compareTo (cn.elts.get (i)); if (comp != 0) return comp; } @@ -227,10 +227,10 @@ public String get (int posn) { - return (String) elts.get (posn); + return elts.get (posn); } - public Enumeration getAll () + public Enumeration<String> getAll () { return elts.elements (); } @@ -239,7 +239,7 @@ { CompositeName cn = new CompositeName (); for (int i = 0; i < posn; ++i) - cn.elts.add ((String) elts.get (i)); + cn.elts.add (elts.get (i)); return cn; } @@ -249,7 +249,7 @@ throw new ArrayIndexOutOfBoundsException (posn); CompositeName cn = new CompositeName (); for (int i = posn; i < elts.size (); ++i) - cn.elts.add ((String) elts.get (i)); + cn.elts.add (elts.get (i)); return cn; } @@ -299,7 +299,7 @@ { // For simplicity we choose to always quote using escapes and // never quotes. - String elt = (String) elts.get (i); + String elt = elts.get (i); if (i > 0 || (i == elts.size () - 1 && elt.equals (""))) result.append ('/'); @@ -327,9 +327,9 @@ throws IOException, ClassNotFoundException { int size = s.readInt(); - elts = new Vector(size); + elts = new Vector<String>(size); for (int i = 0; i < size; i++) - elts.add(s.readObject()); + elts.add((String) s.readObject()); } private void writeObject(ObjectOutputStream s) throws IOException Modified: trunk/core/src/classpath/javax/javax/naming/CompoundName.java =================================================================== --- trunk/core/src/classpath/javax/javax/naming/CompoundName.java 2007-01-07 08:22:28 UTC (rev 3000) +++ trunk/core/src/classpath/javax/javax/naming/CompoundName.java 2007-01-07 08:22:57 UTC (rev 3001) @@ -68,14 +68,14 @@ private CompoundName (Properties syntax) { - elts = new Vector (); + elts = new Vector<String> (); mySyntax = syntax; initializeSyntax (); } - protected CompoundName (Enumeration comps, Properties syntax) + protected CompoundName (Enumeration<String> comps, Properties syntax) { - elts = new Vector (); + elts = new Vector<String> (); mySyntax = syntax; initializeSyntax (); try @@ -91,7 +91,7 @@ public CompoundName (String n, Properties syntax) throws InvalidNameException { - elts = new Vector (); + elts = new Vector<String> (); mySyntax = syntax; initializeSyntax (); @@ -186,7 +186,7 @@ int len = elts.size (); for (i = 0; i < len / 2; ++i) { - Object t = elts.set (i, elts.get (len - i - 1)); + String t = elts.set (i, elts.get (len - i - 1)); elts.set (len - i - 1, t); } } @@ -210,7 +210,7 @@ public Name addAll (int posn, Name n) throws InvalidNameException { - Enumeration e = n.getAll (); + Enumeration<String> e = n.getAll (); try { while (e.hasMoreElements ()) @@ -227,7 +227,7 @@ public Name addAll (Name suffix) throws InvalidNameException { - Enumeration e = suffix.getAll (); + Enumeration<String> e = suffix.getAll (); try { while (e.hasMoreElements ()) @@ -252,8 +252,8 @@ int last = Math.min (cn.elts.size (), elts.size ()); for (int i = 0; i < last; ++i) { - String f = canonicalize ((String) elts.get (i)); - int comp = f.compareTo (canonicalize ((String) cn.elts.get (i))); + String f = canonicalize (elts.get (i)); + int comp = f.compareTo (canonicalize (cn.elts.get (i))); if (comp != 0) return comp; } @@ -270,8 +270,8 @@ int delta = elts.size () - cn.elts.size (); for (int i = 0; i < cn.elts.size (); ++i) { - String f = canonicalize ((String) elts.get (delta + i)); - if (! f.equals (canonicalize ((String) cn.elts.get (i)))) + String f = canonicalize (elts.get (delta + i)); + if (! f.equals (canonicalize (cn.elts.get (i)))) return false; } return true; @@ -286,10 +286,10 @@ public String get (int posn) { - return (String) elts.get (posn); + return elts.get (posn); } - public Enumeration getAll () + public Enumeration<String> getAll () { return elts.elements (); } @@ -316,7 +316,7 @@ { int h = 0; for (int i = 0; i < elts.size (); ++i) - h += canonicalize ((String) elts.get (i)).hashCode (); + h += canonicalize (elts.get (i)).hashCode (); return h; } @@ -344,8 +344,8 @@ return false; for (int i = 0; i < cn.elts.size (); ++i) { - String f = canonicalize ((String) elts.get (i)); - if (! f.equals (canonicalize ((String) cn.elts.get (i)))) + String f = canonicalize (elts.get (i)); + if (! f.equals (canonicalize (cn.elts.get (i)))) return false; } return true; @@ -383,7 +383,7 @@ // Find the appropriate element. FIXME: not clear what FLAT // means. int offset = (direction == RIGHT_TO_LEFT) ? (size - i - 1) : i; - String element = (String) elts.get (offset); + String element = elts.get (offset); if (i > 0 || (i == size - 1 && element.equals (""))) result.append (separator); @@ -478,7 +478,7 @@ { mySyntax = (Properties) s.readObject(); int count = s.readInt(); - elts = new Vector(count); + elts = new Vector<String>(count); for (int i = 0; i < count; i++) elts.addElement((String) s.readObject()); } @@ -499,7 +499,7 @@ protected transient Properties mySyntax; // The actual elements. - private transient Vector elts; + private transient Vector<String> elts; // The following are all used for syntax. private transient int direction; Modified: trunk/core/src/classpath/javax/javax/naming/Context.java =================================================================== --- trunk/core/src/classpath/javax/javax/naming/Context.java 2007-01-07 08:22:28 UTC (rev 3000) +++ trunk/core/src/classpath/javax/javax/naming/Context.java 2007-01-07 08:22:57 UTC (rev 3001) @@ -270,7 +270,7 @@ * @return the enumeration over the names, known for the given subcontext. * @throws NamingException */ - NamingEnumeration list(Name name) throws NamingException; + NamingEnumeration<NameClassPair> list(Name name) throws NamingException; /** * Creates and returns the enumeration over the name bindings that are present @@ -284,7 +284,7 @@ * @return the enumeration over the names, known for the given subcontext. * @throws NamingException */ - NamingEnumeration list(String name) throws NamingException; + NamingEnumeration<NameClassPair> list(String name) throws NamingException; /** * Creates and returns the enumeration over the name - object bindings that @@ -297,7 +297,7 @@ * @return the enumeration over the names, known for the given subcontext. * @throws NamingException */ - NamingEnumeration listBindings(Name name) throws NamingException; + NamingEnumeration<Binding> listBindings(Name name) throws NamingException; /** * Creates and returns the enumeration over the name - object bindings that @@ -310,7 +310,7 @@ * @return the enumeration over the names, known for the given subcontext. * @throws NamingException */ - NamingEnumeration listBindings(String name) throws NamingException; + NamingEnumeration<Binding> listBindings(String name) throws NamingException; /** * Creates the new naming subcontext and binds it to the current (this) @@ -467,7 +467,7 @@ * @return the table, representing the environment of this context * @throws NamingException */ - Hashtable getEnvironment() throws NamingException; + Hashtable<?,?> getEnvironment() throws NamingException; /** * Releases all resources, associated with this context. The close() method Modified: trunk/core/src/classpath/javax/javax/naming/InitialContext.java =================================================================== --- trunk/core/src/classpath/javax/javax/naming/InitialContext.java 2007-01-07 08:22:28 UTC (rev 3000) +++ trunk/core/src/classpath/javax/javax/naming/InitialContext.java 2007-01-07 08:22:57 UTC (rev 3001) @@ -73,21 +73,21 @@ /** * The environment, associated with this initial context. */ - protected Hashtable myProps; + protected Hashtable<Object,Object> myProps; /** * The list of the properties, to that the second alternative value must * be appended after the colon to the first possible value. Used in * {@link #merge(Hashtable, Hashtable)} */ - static final HashSet colon_list; + static final HashSet<String> colon_list; static { - colon_list = new HashSet(); + colon_list = new HashSet<String>(); colon_list.add(Context.OBJECT_FACTORIES); colon_list.add(Context.URL_PKG_PREFIXES); colon_list.add(Context.STATE_FACTORIES); - }; + } /** * The properties that are searched in the agreed places in the @@ -111,7 +111,7 @@ * created. * @throws NamingException */ - public InitialContext(Hashtable environment) throws NamingException + public InitialContext(Hashtable<?,?> environment) throws NamingException { init(environment); } @@ -166,13 +166,13 @@ * not later reuse this structure for other purposes. * @since 1.3 */ - protected void init(Hashtable environment) throws NamingException + protected void init(Hashtable<?, ?> environment) throws NamingException { // If is documented that the caller should not modify the environment. if (environment != null) - myProps = environment; + myProps = (Hashtable<Object, Object>) environment; else - myProps = new Hashtable(); + myProps = new Hashtable<Object, Object>(); Applet napplet = (Applet) myProps.get(Context.APPLET); @@ -262,7 +262,8 @@ * in this table. * @param additional the second table, from where additional values are taken */ - static void merge (Hashtable primary, Hashtable additional) + static void merge (Hashtable<Object, Object> primary, + Hashtable<Object, Object> additional) { Enumeration en = additional.keys(); @@ -424,25 +425,25 @@ } /** @inheritDoc */ - public NamingEnumeration list (Name name) throws NamingException + public NamingEnumeration<NameClassPair> list (Name name) throws NamingException { return getURLOrDefaultInitCtx (name).list (name); } /** @inheritDoc */ - public NamingEnumeration list (String name) throws NamingException + public NamingEnumeration<NameClassPair> list (String name) throws NamingException { return getURLOrDefaultInitCtx (name).list (name); } /** @inheritDoc */ - public NamingEnumeration listBindings (Name name) throws NamingException + public NamingEnumeration<Binding> listBindings (Name name) throws NamingException { return getURLOrDefaultInitCtx (name).listBindings (name); } /** @inheritDoc */ - public NamingEnumeration listBindings (String name) throws NamingException + public NamingEnumeration<Binding> listBindings (String name) throws NamingException { return getURLOrDefaultInitCtx (name).listBindings (name); } @@ -522,7 +523,7 @@ } /** @inheritDoc */ - public Hashtable getEnvironment () throws NamingException + public Hashtable<?,?> getEnvironment () throws NamingException { return myProps; } Modified: trunk/core/src/classpath/javax/javax/naming/Name.java =================================================================== --- trunk/core/src/classpath/javax/javax/naming/Name.java 2007-01-07 08:22:28 UTC (rev 3000) +++ trunk/core/src/classpath/javax/javax/naming/Name.java 2007-01-07 08:22:57 UTC (rev 3001) @@ -60,7 +60,7 @@ * @author Anthony Green (gr...@re...) * @author Mark Wielaard (ma...@kl...) */ -public interface Name extends Cloneable, Serializable, Comparable +public interface Name extends Cloneable, Serializable, Comparable<Object> { // This class is implemented as gnu.javax.naming.ictxImpl.trans.GnuName @@ -82,7 +82,7 @@ * Returns a non-null (but possibly empty) <code>Enumeration</code> of the * components of the <code>Name</code> as <code>String</code>s. */ - Enumeration getAll(); + Enumeration<String> getAll(); /** * Gets the component at the given index. Modified: trunk/core/src/classpath/javax/javax/naming/NamingEnumeration.java =================================================================== --- trunk/core/src/classpath/javax/javax/naming/NamingEnumeration.java 2007-01-07 08:22:28 UTC (rev 3000) +++ trunk/core/src/classpath/javax/javax/naming/NamingEnumeration.java 2007-01-07 08:22:57 UTC (rev 3001) @@ -52,7 +52,7 @@ * exception has been thrown, not other method should be called of that * enumeration.</p> */ -public interface NamingEnumeration extends Enumeration +public interface NamingEnumeration<T> extends Enumeration<T> { /** * Returns the next element in this enumeration. The naming - specific @@ -62,7 +62,7 @@ * @return the next element of this enumeration * @throws NamingException */ - Object next() throws NamingException; + T next() throws NamingException; /** * Checks if there are more unvisited elements in the enumeration, throwing Modified: trunk/core/src/classpath/javax/javax/naming/Reference.java =================================================================== --- trunk/core/src/classpath/javax/javax/naming/Reference.java 2007-01-07 08:22:28 UTC (rev 3000) +++ trunk/core/src/classpath/javax/javax/naming/Reference.java 2007-01-07 08:22:57 UTC (rev 3001) @@ -58,7 +58,7 @@ * The list of addresses, stored in this reference. The object may be * have by several different addresses. */ - protected Vector addrs; + protected Vector<RefAddr> addrs; /** * The name of the class factory to create an instance of the object, @@ -83,7 +83,7 @@ public Reference (String className) { this.className = className; - addrs = new Vector (); + addrs = new Vector<RefAddr> (); } /** @@ -93,7 +93,7 @@ public Reference (String className, RefAddr addr) { this.className = className; - addrs = new Vector (); + addrs = new Vector<RefAddr> (); addrs.add (addr); } @@ -112,7 +112,7 @@ this.className = className; this.classFactory = factoryClassName; this.classFactoryLocation = factoryLocation; - addrs = new Vector (); + addrs = new Vector<RefAddr> (); } /** @@ -131,7 +131,7 @@ this.className = className; this.classFactory = factoryClassName; this.classFactoryLocation = factoryLocation; - addrs = new Vector (); + addrs = new Vector<RefAddr> (); addrs.add (addr); } @@ -164,7 +164,7 @@ { Reference r = new Reference (className, classFactory, classFactoryLocation); - r.addrs = (Vector) addrs.clone (); + r.addrs = (Vector<RefAddr>) addrs.clone (); return r; } @@ -193,7 +193,7 @@ */ public RefAddr get (int posn) { - return (RefAddr) addrs.get (posn); + return addrs.get (posn); } /** @@ -208,7 +208,7 @@ { for (int i = 0; i < addrs.size (); ++i) { - RefAddr r = (RefAddr) addrs.get (i); + RefAddr r = addrs.get (i); if (addrType.equals (r.getType ())) return r; } @@ -218,7 +218,7 @@ /** * Get the enumeration over all defined addresses of the object. */ - public Enumeration getAll () + public Enumeration<RefAddr> getAll () { return addrs.elements (); } Modified: trunk/core/src/classpath/javax/javax/naming/ReferralException.java =================================================================== --- trunk/core/src/classpath/javax/javax/naming/ReferralException.java 2007-01-07 08:22:28 UTC (rev 3000) +++ trunk/core/src/classpath/javax/javax/naming/ReferralException.java 2007-01-07 08:22:57 UTC (rev 3001) @@ -61,7 +61,7 @@ public abstract Object getReferralInfo(); public abstract Context getReferralContext() throws NamingException; - public abstract Context getReferralContext(Hashtable env) + public abstract Context getReferralContext(Hashtable<?, ?> env) throws NamingException; public abstract boolean skipReferral(); public abstract void retryReferral(); Modified: trunk/core/src/classpath/javax/javax/naming/directory/Attribute.java =================================================================== --- trunk/core/src/classpath/javax/javax/naming/directory/Attribute.java 2007-01-07 08:22:28 UTC (rev 3000) +++ trunk/core/src/classpath/javax/javax/naming/directory/Attribute.java 2007-01-07 08:22:57 UTC (rev 3001) @@ -51,7 +51,7 @@ { long serialVersionUID = 8707690322213556804L; - NamingEnumeration getAll() throws NamingException; + NamingEnumeration<?> getAll() throws NamingException; Object get() throws NamingException; int size(); String getID(); Modified: trunk/core/src/classpath/javax/javax/naming/directory/Attributes.java =================================================================== --- trunk/core/src/classpath/javax/javax/naming/directory/Attributes.java 2007-01-07 08:22:28 UTC (rev 3000) +++ trunk/core/src/classpath/javax/javax/naming/directory/Attributes.java 2007-01-07 08:22:57 UTC (rev 3001) @@ -52,8 +52,8 @@ boolean isCaseIgnored(); int size(); Attribute get(String attrID); - NamingEnumeration getAll(); - NamingEnumeration getIDs(); + NamingEnumeration<? extends Attribute> getAll(); + NamingEnumeration<String> getIDs(); Attribute put(String attrID, Object val); Attribute put(Attribute attr); Attribute remove(String attrID); Modified: trunk/core/src/classpath/javax/javax/naming/directory/BasicAttribute.java =================================================================== --- trunk/core/src/classpath/javax/javax/naming/directory/BasicAttribute.java 2007-01-07 08:22:28 UTC (rev 3000) +++ trunk/core/src/classpath/javax/javax/naming/directory/BasicAttribute.java 2007-01-07 08:22:57 UTC (rev 3001) @@ -62,7 +62,7 @@ /** True if this attribute's values are ordered. */ protected boolean ordered; /** Values for this attribute. */ - protected transient Vector values; + protected transient Vector<Object> values; // Used by cloning. private BasicAttribute () @@ -78,7 +78,7 @@ { attrID = id; this.ordered = ordered; - values = new Vector (); + values = new Vector<Object> (); } public BasicAttribute (String id, Object value) @@ -90,7 +90,7 @@ { attrID = id; this.ordered = ordered; - values = new Vector (); + values = new Vector<Object> (); values.add (value); } @@ -118,7 +118,7 @@ BasicAttribute c = new BasicAttribute (); c.attrID = attrID; c.ordered = ordered; - c.values = (Vector) values.clone (); + c.values = (Vector<Object>) values.clone (); return c; } @@ -182,7 +182,7 @@ return values.get (index); } - public NamingEnumeration getAll () + public NamingEnumeration<?> getAll () throws NamingException { return new BasicAttributeEnumeration (); @@ -307,7 +307,7 @@ { s.defaultReadObject(); int size = s.readInt(); - values = new Vector(size); + values = new Vector<Object>(size); for (int i=0; i < size; i++) values.add(s.readObject()); } Modified: trunk/core/src/classpath/javax/javax/naming/directory/BasicAttributes.java =================================================================== --- trunk/core/src/classpath/javax/javax/naming/directory/BasicAttributes.java 2007-01-07 08:22:28 UTC (rev 3000) +++ trunk/core/src/classpath/javax/javax/naming/directory/BasicAttributes.java 2007-01-07 08:22:57 UTC (rev 3001) @@ -63,7 +63,7 @@ public BasicAttributes (boolean ignoreCase) { this.ignoreCase = ignoreCase; - this.attributes = new Vector (); + this.attributes = new Vector<Attribute>(); } public BasicAttributes (String attrID, Object val) @@ -74,7 +74,7 @@ public BasicAttributes (String attrID, Object val, boolean ignoreCase) { this.ignoreCase = ignoreCase; - attributes = new Vector (); + attributes = new Vector<Attribute>(); attributes.add (new BasicAttribute (attrID, val)); } @@ -82,7 +82,7 @@ { // Slightly inefficient as we make a garbage Vector here. BasicAttributes ba = new BasicAttributes (ignoreCase); - ba.attributes = (Vector) attributes.clone (); + ba.attributes = (Vector<Attribute>) attributes.clone (); return ba; } @@ -117,7 +117,7 @@ { for (int i = 0; i < attributes.size (); ++i) { - Attribute at = (Attribute) attributes.get (i); + Attribute at = attributes.get (i); if ((ignoreCase && attrID.equalsIgnoreCase (at.getID ())) || (! ignoreCase && attrID.equals (at.getID ()))) return at; @@ -126,16 +126,42 @@ return null; } - public NamingEnumeration getAll () + public NamingEnumeration<Attribute> getAll () { - return new BasicAttributesEnumeration (false); + return new BasicAttributesEnumeration(); } - public NamingEnumeration getIDs () + public NamingEnumeration<String> getIDs () { - return new BasicAttributesEnumeration (true); + final NamingEnumeration<Attribute> attrs = getAll(); + return new NamingEnumeration<String>() { + public boolean hasMore() throws NamingException + { + return attrs.hasMore(); + } + + public boolean hasMoreElements() + { + return attrs.hasMoreElements(); } + public String next() throws NamingException + { + return attrs.next().getID(); + } + + public String nextElement() + { + return attrs.nextElement().getID(); + } + + public void close() throws NamingException + { + attrs.close(); + } + }; + } + public int hashCode () { int val = 0; @@ -197,16 +223,16 @@ // This is set by the serialization spec. private boolean ignoreCase; // Package-private to avoid a trampoline. - transient Vector attributes; + transient Vector<Attribute> attributes; private void readObject(ObjectInputStream s) throws IOException, ClassNotFoundException { s.defaultReadObject(); int size = s.readInt(); - attributes = new Vector(size); + attributes = new Vector<Attribute>(size); for (int i = 0; i < size; i++) - attributes.add(s.readObject()); + attributes.add((Attribute) s.readObject()); } private void writeObject(ObjectOutputStream s) throws IOException @@ -218,14 +244,13 @@ } // Used when enumerating. - private class BasicAttributesEnumeration implements NamingEnumeration + private class BasicAttributesEnumeration + implements NamingEnumeration<Attribute> { int where = 0; - boolean id; - public BasicAttributesEnumeration (boolean id) + public BasicAttributesEnumeration () { - this.id = id; } public void close () throws NamingException @@ -237,7 +262,7 @@ return hasMoreElements (); } - public Object next () throws NamingException + public Attribute next () throws NamingException { return nextElement (); } @@ -247,13 +272,13 @@ return where < attributes.size (); } - public Object nextElement () throws NoSuchElementException + public Attribute nextElement () throws NoSuchElementException { if (where >= attributes.size ()) throw new NoSuchElementException ("no more elements"); - Attribute at = (Attribute) attributes.get (where); + Attribute at = attributes.get (where); ++where; - return id ? (Object) at.getID () : (Object) at; + return at; } } } Modified: trunk/core/src/classpath/javax/javax/naming/directory/DirContext.java =================================================================== --- trunk/core/src/classpath/javax/javax/naming/directory/DirContext.java 2007-01-07 08:22:28 UTC (rev 3000) +++ trunk/core/src/classpath/javax/javax/naming/directory/DirContext.java 2007-01-07 08:22:57 UTC (rev 3001) @@ -72,12 +72,32 @@ DirContext getSchema(String name) throws NamingException; DirContext getSchemaClassDefinition(Name name) throws NamingException; DirContext getSchemaClassDefinition(String name) throws NamingException; - NamingEnumeration search(Name name, Attributes matchingAttributes, String[] attributesToReturn) throws NamingException; - NamingEnumeration search(String name, Attributes matchingAttributes, String[] attributesToReturn) throws NamingException; - NamingEnumeration search(Name name, Attributes matchingAttributes) throws NamingException; - NamingEnumeration search(String name, Attributes matchingAttributes) throws NamingException; - NamingEnumeration search(Name name, String filter, SearchControls cons) throws NamingException; - NamingEnumeration search(String name, String filter, SearchControls cons) throws NamingException; - NamingEnumeration search(Name name, String filterExpr, Object[] filterArgs, SearchControls cons) throws NamingException; - NamingEnumeration search(String name, String filterExpr, Object[] filterArgs, SearchControls cons) throws NamingException; + NamingEnumeration<SearchResult> search(Name name, + Attributes matchingAttributes, + String[] attributesToReturn) + throws NamingException; + NamingEnumeration<SearchResult> search(String name, + Attributes matchingAttributes, + String[] attributesToReturn) + throws NamingException; + NamingEnumeration<SearchResult> search(Name name, + Attributes matchingAttributes) + throws NamingException; + NamingEnumeration<SearchResult> search(String name, + Attributes matchingAttributes) + throws NamingException; + NamingEnumeration<SearchResult> search(Name name, String filter, + SearchControls cons) + throws NamingException; + NamingEnumeration<SearchResult> search(String name, String filter, + SearchControls cons) + throws NamingException; + NamingEnumeration<SearchResult> search(Name name, String filterExpr, + Object[] filterArgs, + SearchControls cons) + throws NamingException; + NamingEnumeration<SearchResult> search(String name, String filterExpr, + Object[] filterArgs, + SearchControls cons) + throws NamingException; } Modified: trunk/core/src/classpath/javax/javax/naming/directory/InitialDirContext.java =================================================================== --- trunk/core/src/classpath/javax/javax/naming/directory/InitialDirContext.java 2007-01-07 08:22:28 UTC (rev 3000) +++ trunk/core/src/classpath/javax/javax/naming/directory/InitialDirContext.java 2007-01-07 08:22:57 UTC (rev 3001) @@ -66,7 +66,7 @@ super (lazy); } - public InitialDirContext (Hashtable environment) + public InitialDirContext (Hashtable<?, ?> environment) throws NamingException { super (environment); @@ -205,7 +205,8 @@ return getURLOrDefaultInitDirCtx (name).getSchemaClassDefinition (name); } - public NamingEnumeration search(Name name, Attributes matchingAttributes, + public NamingEnumeration<SearchResult> search(Name name, + Attributes matchingAttributes, String[] attributesToReturn) throws NamingException { @@ -213,7 +214,8 @@ attributesToReturn); } - public NamingEnumeration search(String name, Attributes matchingAttributes, + public NamingEnumeration<SearchResult> search(String name, + Attributes matchingAttributes, String[] attributesToReturn) throws NamingException { @@ -221,42 +223,47 @@ attributesToReturn); } - public NamingEnumeration search(Name name, Attributes matchingAttributes) + public NamingEnumeration<SearchResult> search(Name name, + Attributes matchingAttributes) throws NamingException { return getURLOrDefaultInitDirCtx (name).search (name, matchingAttributes); } - public NamingEnumeration search(String name, Attributes matchingAttributes) + public NamingEnumeration<SearchResult> search(String name, + Attributes matchingAttributes) throws NamingException { return getURLOrDefaultInitDirCtx (name).search (name, matchingAttributes); } - public NamingEnumeration search(Name name, String filter, + public NamingEnumeration<SearchResult> search(Name name, String filter, SearchControls cons) throws NamingException { return getURLOrDefaultInitDirCtx (name).search (name, filter, cons); } - public NamingEnumeration search(String name, String filter, + public NamingEnumeration<SearchResult> search(String name, String filter, SearchControls cons) throws NamingException { return getURLOrDefaultInitDirCtx (name).search (name, filter, cons); } - public NamingEnumeration search(Name name, String filterExpr, - Object[] filterArgs, SearchControls cons) + public NamingEnumeration<SearchResult> search(Name name, String filterExpr, + Object[] filterArgs, + SearchControls cons) throws NamingException { return getURLOrDefaultInitDirCtx (name).search (name, filterExpr, filterArgs, cons); } - public NamingEnumeration search(String name, String filterExpr, - Object[] filterArgs, SearchControls cons) + public NamingEnumeration<SearchResult> search(String name, + String filterExpr, + Object[] filterArgs, + SearchControls cons) throws NamingException { return getURLOrDefaultInitDirCtx (name).search (name, filterExpr, Modified: trunk/core/src/classpath/javax/javax/naming/ldap/ControlFactory.java =================================================================== --- trunk/core/src/classpath/javax/javax/naming/ldap/ControlFactory.java 2007-01-07 08:22:28 UTC (rev 3000) +++ trunk/core/src/classpath/javax/javax/naming/ldap/ControlFactory.java 2007-01-07 08:22:57 UTC (rev 3001) @@ -59,7 +59,7 @@ public static Control getControlInstance (Control control, Context ctx, - Hashtable env) + Hashtable<?, ?> env) throws NamingException { String path = (String) env.get (LdapContext.CONTROL_FACTORIES); Modified: trunk/core/src/classpath/javax/javax/naming/ldap/InitialLdapContext.java =================================================================== --- trunk/core/src/classpath/javax/javax/naming/ldap/InitialLdapContext.java 2007-01-07 08:22:28 UTC (rev 3000) +++ trunk/core/src/classpath/javax/javax/naming/ldap/InitialLdapContext.java 2007-01-07 08:22:57 UTC (rev 3001) @@ -60,22 +60,24 @@ this (null, null); } - public InitialLdapContext (Hashtable environment, Control[] connControls) + public InitialLdapContext (Hashtable<?, ?> environment, + Control[] connControls) throws NamingException { super (false); + Hashtable<Object, Object> myenv = null; if (connControls != null) { if (environment == null) - environment = new Hashtable (); + myenv = new Hashtable<Object, Object> (); else - environment = (Hashtable) environment.clone (); - environment.put ("java.naming.ldap.control.connect", + myenv = (Hashtable<Object, Object>) environment.clone (); + myenv.put ("java.naming.ldap.control.connect", connControls); } - init (environment); + init (myenv); } private LdapContext getDefaultInitLdapCtx () Modified: trunk/core/src/classpath/javax/javax/naming/ldap/LdapReferralException.java =================================================================== --- trunk/core/src/classpath/javax/javax/naming/ldap/LdapReferralException.java 2007-01-07 08:22:28 UTC (rev 3000) +++ trunk/core/src/classpath/javax/javax/naming/ldap/LdapReferralException.java 2007-01-07 08:22:57 UTC (rev 3001) @@ -61,8 +61,9 @@ } public abstract Context getReferralContext() throws NamingException; - public abstract Context getReferralContext(Hashtable env) + public abstract Context getReferralContext(Hashtable<?, ?> env) throws NamingException; - public abstract Context getReferralContext(Hashtable env, Control[] reqCtls) + public abstract Context getReferralContext(Hashtable<?, ?> env, + Control[] reqCtls) throws NamingException; } Modified: trunk/core/src/classpath/javax/javax/naming/spi/DirObjectFactory.java =================================================================== --- trunk/core/src/classpath/javax/javax/naming/spi/DirObjectFactory.java 2007-01-07 08:22:28 UTC (rev 3000) +++ trunk/core/src/classpath/javax/javax/naming/spi/DirObjectFactory.java 2007-01-07 08:22:57 UTC (rev 3001) @@ -51,6 +51,6 @@ public interface DirObjectFactory extends ObjectFactory { Object getObjectInstance(Object obj, Name name, Context nameCtx, - Hashtable environment, Attributes attrs) + Hashtable<?, ?> environment, Attributes attrs) throws Exception; } Modified: trunk/core/src/classpath/javax/javax/naming/spi/DirStateFactory.java =================================================================== --- trunk/core/src/classpath/javax/javax/naming/spi/DirStateFactory.java 2007-01-07 08:22:28 UTC (rev 3000) +++ trunk/core/src/classpath/javax/javax/naming/spi/DirStateFactory.java 2007-01-07 08:22:57 UTC (rev 3001) @@ -77,7 +77,7 @@ DirStateFactory.Result getStateToBind(Object obj, Name name, Context nameCtx, - Hashtable environment, + Hashtable<?, ?> environment, Attributes inAttrs) throws NamingException; } Modified: trunk/core/src/classpath/javax/javax/naming/spi/DirectoryManager.java =================================================================== --- trunk/core/src/classpath/javax/javax/naming/spi/DirectoryManager.java 2007-01-07 08:22:28 UTC (rev 3000) +++ trunk/core/src/classpath/javax/javax/naming/spi/DirectoryManager.java 2007-01-07 08:22:57 UTC (rev 3001) @@ -93,7 +93,7 @@ public static Object getObjectInstance (Object refInfo, Name name, Context nameCtx, - Hashtable environment, + Hashtable<?, ?> environment, Attributes attrs) throws Exception { @@ -186,7 +186,7 @@ public static DirStateFactory.Result getStateToBind (Object obj, Name name, Context nameCtx, - Hashtable environment, + Hashtable<?, ?> environment, Attributes attrs) throws NamingException { Modified: trunk/core/src/classpath/javax/javax/naming/spi/InitialContextFactory.java =================================================================== --- trunk/core/src/classpath/javax/javax/naming/spi/InitialContextFactory.java 2007-01-07 08:22:28 UTC (rev 3000) +++ trunk/core/src/classpath/javax/javax/naming/spi/InitialContextFactory.java 2007-01-07 08:22:57 UTC (rev 3001) @@ -66,5 +66,6 @@ * @return the new initial context * @throws NamingException if the naming exception has occured */ - Context getInitialContext(Hashtable environment) throws NamingException; + Context getInitialContext (Hashtable<?, ?> environment) + throws NamingException; } Modified: trunk/core/src/classpath/javax/javax/naming/spi/InitialContextFactoryBuilder.java =================================================================== --- trunk/core/src/classpath/javax/javax/naming/spi/InitialContextFactoryBuilder.java 2007-01-07 08:22:28 UTC (rev 3000) +++ trunk/core/src/classpath/javax/javax/naming/spi/InitialContextFactoryBuilder.java 2007-01-07 08:22:57 UTC (rev 3001) @@ -53,14 +53,14 @@ public interface InitialContextFactoryBuilder { /** - * Create the new inital context factory + * Create the new initial context factory * - * @param environment the properties, used for creation of the initial context - * factory. The parameter is owned by the caller: it is safe to reuse + * @param environment the properties, used for creation of the initial + * context factory. The parameter is owned by the caller: it is safe to reuse * the table for other purposes after the method returns. * @return the created initial context factory, never null. * @throws NamingException on failure */ - InitialContextFactory createInitialContextFactory (Hashtable environment) + InitialContextFactory createInitialContextFactory (Hashtable<?, ?> environment) throws NamingException; } Modified: trunk/core/src/classpath/javax/javax/naming/spi/NamingManager.java =================================================================== --- trunk/core/src/classpath/javax/javax/naming/spi/NamingManager.java 2007-01-07 08:22:28 UTC (rev 3000) +++ trunk/core/src/classpath/javax/javax/naming/spi/NamingManager.java 2007-01-07 08:22:57 UTC (rev 3001) @@ -110,7 +110,7 @@ * class, named by this property, cannot be instantiated. * @throws NamingException if throws by the context factory */ - public static Context getInitialContext (Hashtable environment) + public static Context getInitialContext (Hashtable<?, ?> environment) throws NamingException { InitialContextFactory icf = null; @@ -187,7 +187,7 @@ * @throws NamingException if thrown by the factory when creating the context. */ static Context getURLContext(Object refInfo, Name name, Context nameCtx, - String scheme, Hashtable environment) + String scheme, Hashtable<?,?> environment) throws NamingException { // Doc specifies com.sun.jndi.url as the final destination, but we cannot @@ -329,15 +329,15 @@ * </p> * <p> * The class name of the factory that creates the context has the naming - * pattern scheme-idURLContextFactory. For instance, the factory for the "ftp" - * sheme should be named "ftpURLContextFactory". The Context.URL_PKG_PREFIXES - * environment property contains the colon-separated list of the possible - * package prefixes. The package name is constructed concatenating the package - * prefix with the scheme id. + * pattern scheme-idURLContextFactory. For instance, the factory for the + * "ftp" scheme should be named "ftpURLContextFactory". + * The Context.URL_PKG_PREFIXES environment property contains the + * colon-separated list of the possible package prefixes. The package name + * is constructed by concatenating the package prefix with the scheme id. * </p> * <p> - * If the factory class cannot be found in the specified packages, system will - * try to use the default internal factory for the given scheme. + * If the factory class cannot be found in the specified packages, the + * system will try to use the default internal factory for the given scheme. * </p> * <p> * After the factory is instantiated, its method @@ -345,13 +345,14 @@ * is called to create and return the object instance. * * @param scheme the url scheme that must be supported by the given context - * @param environment the properties for creating the factory and context (may - * be null) + * @param environment the properties for creating the factory and context + * (may be null) * @return the created context - * @throws NamingException if thrown by the factory when creating the context. + * @throws NamingException if thrown by the factory when creating the + * context. */ public static Context getURLContext (String scheme, - Hashtable environment) + Hashtable<?, ?> environment) throws NamingException { return getURLContext (null, null, null, scheme, environment); @@ -450,7 +451,7 @@ public static Object getObjectInstance (Object refInfo, Name name, Context nameCtx, - Hashtable environment) + Hashtable<?, ?> environment) throws Exception { ObjectFactory factory = null; @@ -623,7 +624,7 @@ * @throws NamingException */ public static Object getStateToBind (Object obj, Name name, - Context nameCtx, Hashtable environment) + Context nameCtx, Hashtable<?, ?> environment) throws NamingException { StringTokenizer tokens = getPlusPath (Context.STATE_FACTORIES, Modified: trunk/core/src/classpath/javax/javax/naming/spi/ObjectFactory.java =================================================================== --- trunk/core/src/classpath/javax/javax/naming/spi/ObjectFactory.java 2007-01-07 08:22:28 UTC (rev 3000) +++ trunk/core/src/classpath/javax/javax/naming/spi/ObjectFactory.java 2007-01-07 08:22:57 UTC (rev 3001) @@ -70,6 +70,7 @@ * * @see NamingManager#getObjectInstance(Object, Name, Context, Hashtable) */ - Object getObjectInstance(Object refObj, Name name, Context nameCtx, - Hashtable environment) throws Exception; + Object getObjectInstance (Object refObj, Name name, Context nameCtx, + Hashtable<?, ?> environment) + throws Exception; } Modified: trunk/core/src/classpath/javax/javax/naming/spi/ObjectFactoryBuilder.java =================================================================== --- trunk/core/src/classpath/javax/javax/naming/spi/ObjectFactoryBuilder.java 2007-01-07 08:22:28 UTC (rev 3000) +++ trunk/core/src/classpath/javax/javax/naming/spi/ObjectFactoryBuilder.java 2007-01-07 08:22:57 UTC (rev 3001) @@ -65,6 +65,6 @@ * @throws NamingException */ ObjectFactory createObjectFactory(Object refInfo, - Hashtable environment) + Hashtable<?, ?> environment) throws NamingException; } Modified: trunk/core/src/classpath/javax/javax/naming/spi/Resolver.java =================================================================== --- trunk/core/src/classpath/javax/javax/naming/spi/Resolver.java 2007-01-07 08:22:28 UTC (rev 3000) +++ trunk/core/src/classpath/javax/javax/naming/spi/Resolver.java 2007-01-07 08:22:57 UTC (rev 3001) @@ -41,7 +41,6 @@ import javax.naming.Context; import javax.naming.Name; import javax.naming.NamingException; -import javax.naming.NotContextException; /** * <p>Represents the object, capable for the at least partial name resolution. @@ -54,31 +53,10 @@ */ public interface Resolver { - /** - * Partially resolve the name, stopping at the first instance of the context - * that is an instance of the contextType - * - * @param name the name to resolve - * @param contextType the class of the context, on that the resolution should - * be terminated - * @return the complete or partial name resolution - * @throws NotContextException if the context of the contextType is not found - * @throws NamingException on other failure - */ - ResolveResult resolveToClass(Name name, Class contextType) + ResolveResult resolveToClass(Name name, + Class<? extends Context> contextType) throws NamingException; - - /** - * Partially resolve the name, stopping at the first instance of the context - * that is an instance of the contextType - * - * @param name the name to resolve - * @param contextType the class of the context, on that the resolution should - * be terminated - * @return the complete or partial name resolution - * @throws NotContextException if the context of the contextType is not found - * @throws NamingException on other failure - */ - ResolveResult resolveToClass(String name, Class contextType) + ResolveResult resolveToClass(String name, + Class<? extends Context> contextType) throws NamingException; } Modified: trunk/core/src/classpath/javax/javax/naming/spi/StateFactory.java =================================================================== --- trunk/core/src/classpath/javax/javax/naming/spi/StateFactory.java 2007-01-07 08:22:28 UTC (rev 3000) +++ trunk/core/src/classpath/javax/javax/naming/spi/StateFactory.java 2007-01-07 08:22:57 UTC (rev 3001) @@ -75,5 +75,5 @@ * @see DirectoryManager#getStateToBind */ Object getStateToBind(Object obj, Name name, Context nameCtx, - Hashtable environment) throws NamingException; + Hashtable<?, ?> environment) throws NamingException; } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <ls...@us...> - 2007-01-07 08:22:29
|
Revision: 3000 http://jnode.svn.sourceforge.net/jnode/?rev=3000&view=rev Author: lsantha Date: 2007-01-07 00:22:28 -0800 (Sun, 07 Jan 2007) Log Message: ----------- Classpath patches. Modified Paths: -------------- trunk/core/src/classpath/javax/javax/management/AttributeList.java trunk/core/src/classpath/javax/javax/management/MBeanAttributeInfo.java trunk/core/src/classpath/javax/javax/management/MBeanConstructorInfo.java trunk/core/src/classpath/javax/javax/management/MBeanOperationInfo.java trunk/core/src/classpath/javax/javax/management/MBeanServerDelegate.java trunk/core/src/classpath/javax/javax/management/MBeanServerFactory.java trunk/core/src/classpath/javax/javax/management/ObjectName.java trunk/core/src/classpath/javax/javax/management/StandardMBean.java Modified: trunk/core/src/classpath/javax/javax/management/AttributeList.java =================================================================== --- trunk/core/src/classpath/javax/javax/management/AttributeList.java 2007-01-07 08:19:52 UTC (rev 2999) +++ trunk/core/src/classpath/javax/javax/management/AttributeList.java 2007-01-07 08:22:28 UTC (rev 3000) @@ -49,7 +49,7 @@ * @since 1.5 */ public class AttributeList - extends ArrayList + extends ArrayList<Object> { /** Modified: trunk/core/src/classpath/javax/javax/management/MBeanAttributeInfo.java =================================================================== --- trunk/core/src/classpath/javax/javax/management/MBeanAttributeInfo.java 2007-01-07 08:19:52 UTC (rev 2999) +++ trunk/core/src/classpath/javax/javax/management/MBeanAttributeInfo.java 2007-01-07 08:22:28 UTC (rev 3000) @@ -38,6 +38,7 @@ package javax.management; import java.lang.reflect.Method; +import java.lang.reflect.Type; /** * Describes the attributes of a management bean. @@ -109,13 +110,21 @@ "not be null."); if (getter == null) { - attributeType = setter.getParameterTypes()[0].getName(); + Type t = setter.getGenericParameterTypes()[0]; + if (t instanceof Class) + attributeType = ((Class) t).getName(); + else + attributeType = t.toString(); isRead = false; is = false; } else { - attributeType = getter.getReturnType().getName(); + Type t = getter.getGenericReturnType(); + if (t instanceof Class) + attributeType = ((Class) t).getName(); + else + attributeType = t.toString(); isRead = true; is = getter.getName().startsWith("is"); } Modified: trunk/core/src/classpath/javax/javax/management/MBeanConstructorInfo.java =================================================================== --- trunk/core/src/classpath/javax/javax/management/MBeanConstructorInfo.java 2007-01-07 08:19:52 UTC (rev 2999) +++ trunk/core/src/classpath/javax/javax/management/MBeanConstructorInfo.java 2007-01-07 08:22:28 UTC (rev 3000) @@ -38,6 +38,7 @@ package javax.management; import java.lang.reflect.Constructor; +import java.lang.reflect.Type; import java.util.Arrays; @@ -77,12 +78,18 @@ public MBeanConstructorInfo(String desc, Constructor cons) { super(cons.getName(), desc); - Class[] paramTypes = cons.getParameterTypes(); + Type[] paramTypes = cons.getGenericParameterTypes(); signature = new MBeanParameterInfo[paramTypes.length]; for (int a = 0; a < paramTypes.length; ++a) + { + Type t = paramTypes[a]; + if (t instanceof Class) signature[a] = new MBeanParameterInfo(null, - paramTypes[a].getName(), + ((Class) t).getName(), null); + else + signature[a] = new MBeanParameterInfo(null, t.toString(), null); + } } /** Modified: trunk/core/src/classpath/javax/javax/management/MBeanOperationInfo.java =================================================================== --- trunk/core/src/classpath/javax/javax/management/MBeanOperationInfo.java 2007-01-07 08:19:52 UTC (rev 2999) +++ trunk/core/src/classpath/javax/javax/management/MBeanOperationInfo.java 2007-01-07 08:22:28 UTC (rev 3000) @@ -38,6 +38,7 @@ package javax.management; import java.lang.reflect.Method; +import java.lang.reflect.Type; import java.util.Arrays; @@ -113,13 +114,23 @@ public MBeanOperationInfo(String desc, Method method) { super(method.getName(), desc); - Class[] paramTypes = method.getParameterTypes(); + Type[] paramTypes = method.getGenericParameterTypes(); signature = new MBeanParameterInfo[paramTypes.length]; for (int a = 0; a < paramTypes.length; ++a) + { + Type t = paramTypes[a]; + if (t instanceof Class) signature[a] = new MBeanParameterInfo(null, - paramTypes[a].getName(), + ((Class) t).getName(), null); - type = method.getReturnType().getName(); + else + signature[a] = new MBeanParameterInfo(null, t.toString(), null); + } + Type retType = method.getGenericReturnType(); + if (retType instanceof Class) + type = ((Class) retType).getName(); + else + type = retType.toString(); if (method.getReturnType() == Void.TYPE) { if (paramTypes.length == 0) Modified: trunk/core/src/classpath/javax/javax/management/MBeanServerDelegate.java =================================================================== --- trunk/core/src/classpath/javax/javax/management/MBeanServerDelegate.java 2007-01-07 08:19:52 UTC (rev 2999) +++ trunk/core/src/classpath/javax/javax/management/MBeanServerDelegate.java 2007-01-07 08:22:28 UTC (rev 3000) @@ -69,7 +69,7 @@ /** * The listeners registered with the delegate. */ - private List listeners; + private final List listeners = new ArrayList(); /** * The sequence identifier used by the delegate. @@ -120,8 +120,6 @@ { if (listener == null) throw new IllegalArgumentException("A null listener was supplied."); - if (listeners == null) - listeners = new ArrayList(); listeners.add(new ListenerData(listener, filter, passback)); } Modified: trunk/core/src/classpath/javax/javax/management/MBeanServerFactory.java =================================================================== --- trunk/core/src/classpath/javax/javax/management/MBeanServerFactory.java 2007-01-07 08:19:52 UTC (rev 2999) +++ trunk/core/src/classpath/javax/javax/management/MBeanServerFactory.java 2007-01-07 08:22:28 UTC (rev 3000) @@ -89,7 +89,7 @@ /** * The map of registered servers (identifiers to servers). */ - private static Map servers; + private static final Map servers = new HashMap(); /** * Private constructor to prevent instance creation. @@ -154,10 +154,10 @@ */ public static MBeanServer createMBeanServer(String domain) { - /* FIXME: Check for permission "createMBeanServer" */ + SecurityManager sm = System.getSecurityManager(); + if (sm != null) + sm.checkPermission(new MBeanServerPermission("createMBeanServer")); MBeanServer server = createServer(domain); - if (servers == null) - servers = new HashMap(); try { ObjectName dn = new @@ -208,7 +208,9 @@ */ public static ArrayList findMBeanServer(String id) { - /* FIXME: Check for permission "findMBeanServer" */ + SecurityManager sm = System.getSecurityManager(); + if (sm != null) + sm.checkPermission(new MBeanServerPermission("findMBeanServer")); if (id == null) return new ArrayList(servers.values()); ArrayList list = new ArrayList(); @@ -297,7 +299,9 @@ */ public static MBeanServer newMBeanServer(String domain) { - /* FIXME: Check for permission "newMBeanServer" */ + SecurityManager sm = System.getSecurityManager(); + if (sm != null) + sm.checkPermission(new MBeanServerPermission("newMBeanServer")); return createServer(domain); } @@ -330,7 +334,8 @@ builder.getClass() != MBeanServerBuilder.class) builder = new MBeanServerBuilder(); } - else if (!(builderClass.equals(builder.getClass().getName()))) + else if (!(builder != null && + builderClass.equals(builder.getClass().getName()))) { ClassLoader cl = Thread.currentThread().getContextClassLoader(); if (cl == null) @@ -387,7 +392,9 @@ */ public static void releaseMBeanServer(MBeanServer server) { - /* FIXME: Check for permission "releaseMBeanServer" */ + SecurityManager sm = System.getSecurityManager(); + if (sm != null) + sm.checkPermission(new MBeanServerPermission("releaseMBeanServer")); Iterator i = servers.values().iterator(); while (i.hasNext()) { Modified: trunk/core/src/classpath/javax/javax/management/ObjectName.java =================================================================== --- trunk/core/src/classpath/javax/javax/management/ObjectName.java 2007-01-07 08:19:52 UTC (rev 2999) +++ trunk/core/src/classpath/javax/javax/management/ObjectName.java 2007-01-07 08:22:28 UTC (rev 3000) @@ -565,16 +565,15 @@ /** * Returns the properties in a {@link java.util.Hashtable}. The table * contains each of the properties as keys mapped to their value. The - * returned table may be unmodifiable. If the case that the table is - * modifiable, changes made to it will not be reflected in the object - * name. + * returned table is not unmodifiable, but changes made to it will not + * be reflected in the object name. * * @return a {@link java.util.Hashtable}, containing each of the object * name's properties. */ public Hashtable getKeyPropertyList() { - return (Hashtable) Collections.unmodifiableMap(new Hashtable(properties)); + return new Hashtable(properties); } /** Modified: trunk/core/src/classpath/javax/javax/management/StandardMBean.java =================================================================== --- trunk/core/src/classpath/javax/javax/management/StandardMBean.java 2007-01-07 08:19:52 UTC (rev 2999) +++ trunk/core/src/classpath/javax/javax/management/StandardMBean.java 2007-01-07 08:22:28 UTC (rev 3000) @@ -665,7 +665,10 @@ ainfo, cinfo, oinfo, null); String cname = getClassName(info); String desc = getDescription(info); - info = new MBeanInfo(cname, desc, ainfo, cinfo, oinfo, null); + MBeanNotificationInfo[] ninfo = null; + if (impl instanceof NotificationBroadcaster) + ninfo = ((NotificationBroadcaster) impl).getNotificationInfo(); + info = new MBeanInfo(cname, desc, ainfo, cinfo, oinfo, ninfo); cacheMBeanInfo(info); return info; } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <ls...@us...> - 2007-01-07 08:19:54
|
Revision: 2999 http://jnode.svn.sourceforge.net/jnode/?rev=2999&view=rev Author: lsantha Date: 2007-01-07 00:19:52 -0800 (Sun, 07 Jan 2007) Log Message: ----------- Classpath patches. Modified Paths: -------------- trunk/core/src/classpath/javax/javax/imageio/IIOImage.java trunk/core/src/classpath/javax/javax/imageio/ImageIO.java trunk/core/src/classpath/javax/javax/imageio/ImageReader.java trunk/core/src/classpath/javax/javax/imageio/ImageWriteParam.java trunk/core/src/classpath/javax/javax/imageio/ImageWriter.java trunk/core/src/classpath/javax/javax/imageio/metadata/IIOMetadataFormat.java trunk/core/src/classpath/javax/javax/imageio/metadata/IIOMetadataFormatImpl.java trunk/core/src/classpath/javax/javax/imageio/spi/IIORegistry.java trunk/core/src/classpath/javax/javax/imageio/spi/IIOServiceProvider.java trunk/core/src/classpath/javax/javax/imageio/spi/ImageInputStreamSpi.java trunk/core/src/classpath/javax/javax/imageio/spi/ImageOutputStreamSpi.java trunk/core/src/classpath/javax/javax/imageio/spi/RegisterableService.java trunk/core/src/classpath/javax/javax/imageio/spi/ServiceRegistry.java trunk/core/src/classpath/javax/javax/imageio/stream/FileCacheImageOutputStream.java Modified: trunk/core/src/classpath/javax/javax/imageio/IIOImage.java =================================================================== --- trunk/core/src/classpath/javax/javax/imageio/IIOImage.java 2007-01-07 05:43:57 UTC (rev 2998) +++ trunk/core/src/classpath/javax/javax/imageio/IIOImage.java 2007-01-07 08:19:52 UTC (rev 2999) @@ -79,8 +79,7 @@ /** * A list of BufferedImage thumbnails of this image. */ - // for 1.5 these lists are List<? extends BufferedImage> - protected List thumbnails; + protected List<? extends BufferedImage> thumbnails; /** * Construct an IIOImage containing raster image data, thumbnails @@ -92,7 +91,8 @@ * * @exception IllegalArgumentException if raster is null */ - public IIOImage (Raster raster, List thumbnails, IIOMetadata metadata) + public IIOImage (Raster raster, List<? extends BufferedImage> thumbnails, + IIOMetadata metadata) { if (raster == null) throw new IllegalArgumentException ("raster may not be null"); @@ -112,7 +112,8 @@ * * @exception IllegalArgumentException if image is null */ - public IIOImage (RenderedImage image, List thumbnails, IIOMetadata metadata) + public IIOImage (RenderedImage image, List<? extends BufferedImage> thumbnails, + IIOMetadata metadata) { if (image == null) throw new IllegalArgumentException ("image may not be null"); @@ -192,7 +193,7 @@ * * @return a list of thumbnails or null */ - public List getThumbnails() + public List<? extends BufferedImage> getThumbnails() { return thumbnails; } @@ -260,7 +261,7 @@ * * @param thumbnails a new list of thumbnails or null */ - public void setThumbnails (List thumbnails) + public void setThumbnails (List<? extends BufferedImage> thumbnails) { this.thumbnails = thumbnails; } Modified: trunk/core/src/classpath/javax/javax/imageio/ImageIO.java =================================================================== --- trunk/core/src/classpath/javax/javax/imageio/ImageIO.java 2007-01-07 05:43:57 UTC (rev 2998) +++ trunk/core/src/classpath/javax/javax/imageio/ImageIO.java 2007-01-07 08:19:52 UTC (rev 2999) @@ -315,27 +315,37 @@ } } - private static final class ImageReaderIterator implements Iterator + private static final class ImageReaderIterator + implements Iterator<ImageReader> { - Iterator it; + Iterator<ImageReaderSpi> it; Object readerExtension; - public ImageReaderIterator(Iterator it, Object readerExtension) + public ImageReaderIterator(Iterator<ImageReaderSpi> it, + Object readerExtension) { this.it = it; this.readerExtension = readerExtension; } + public ImageReaderIterator(Iterator<ImageReaderSpi> it) + { + this.it = it; + } + public boolean hasNext() { return it.hasNext(); } - public Object next() + public ImageReader next() { try { - return ((ImageReaderSpi) it.next()).createReaderInstance(readerExtension); + ImageReaderSpi spi = it.next(); + return (readerExtension == null + ? spi.createReaderInstance() + : spi.createReaderInstance(readerExtension)); } catch (IOException e) { @@ -349,27 +359,37 @@ } } - private static final class ImageWriterIterator implements Iterator + private static final class ImageWriterIterator + implements Iterator<ImageWriter> { - Iterator it; + Iterator<ImageWriterSpi> it; Object writerExtension; - public ImageWriterIterator(Iterator it, Object writerExtension) + public ImageWriterIterator(Iterator<ImageWriterSpi> it, + Object writerExtension) { this.it = it; this.writerExtension = writerExtension; } + public ImageWriterIterator(Iterator<ImageWriterSpi> it) + { + this.it = it; + } + public boolean hasNext() { return it.hasNext(); } - public Object next() + public ImageWriter next() { try { - return ((ImageWriterSpi) it.next()).createWriterInstance(writerExtension); + ImageWriterSpi spi = it.next(); + return (writerExtension == null + ? spi.createWriterInstance() + : spi.createWriterInstance(writerExtension)); } catch (IOException e) { @@ -386,13 +406,14 @@ private static File cacheDirectory; private static boolean useCache = true; - private static Iterator getReadersByFilter(Class type, + private static Iterator<ImageReader> getReadersByFilter(Class<ImageReaderSpi> type, ServiceRegistry.Filter filter, Object readerExtension) { try { - Iterator it = getRegistry().getServiceProviders(type, filter, true); + Iterator<ImageReaderSpi> it + = getRegistry().getServiceProviders(type, filter, true); return new ImageReaderIterator(it, readerExtension); } catch (IllegalArgumentException e) @@ -401,13 +422,14 @@ } } - private static Iterator getWritersByFilter(Class type, + private static Iterator<ImageWriter> getWritersByFilter(Class<ImageWriterSpi> type, ServiceRegistry.Filter filter, Object writerExtension) { try { - Iterator it = getRegistry().getServiceProviders(type, filter, true); + Iterator<ImageWriterSpi> it + = getRegistry().getServiceProviders(type, filter, true); return new ImageWriterIterator(it, writerExtension); } catch (IllegalArgumentException e) @@ -436,7 +458,7 @@ * * @exception IllegalArgumentException if formatName is null */ - public static Iterator getImageReadersByFormatName(String formatName) + public static Iterator<ImageReader> getImageReadersByFormatName(String formatName) { if (formatName == null) throw new IllegalArgumentException("formatName may not be null"); @@ -457,7 +479,7 @@ * * @exception IllegalArgumentException if MIMEType is null */ - public static Iterator getImageReadersByMIMEType(String MIMEType) + public static Iterator<ImageReader> getImageReadersByMIMEType(String MIMEType) { if (MIMEType == null) throw new IllegalArgumentException("MIMEType may not be null"); @@ -477,7 +499,7 @@ * * @exception IllegalArgumentException if fileSuffix is null */ - public static Iterator getImageReadersBySuffix(String fileSuffix) + public static Iterator<ImageReader> getImageReadersBySuffix(String fileSuffix) { if (fileSuffix == null) throw new IllegalArgumentException("formatName may not be null"); @@ -497,7 +519,7 @@ * * @exception IllegalArgumentException if formatName is null */ - public static Iterator getImageWritersByFormatName(String formatName) + public static Iterator<ImageWriter> getImageWritersByFormatName(String formatName) { if (formatName == null) throw new IllegalArgumentException("formatName may not be null"); @@ -518,7 +540,7 @@ * * @exception IllegalArgumentException if MIMEType is null */ - public static Iterator getImageWritersByMIMEType(String MIMEType) + public static Iterator<ImageWriter> getImageWritersByMIMEType(String MIMEType) { if (MIMEType == null) throw new IllegalArgumentException("MIMEType may not be null"); @@ -538,7 +560,7 @@ * * @exception IllegalArgumentException if fileSuffix is null */ - public static Iterator getImageWritersBySuffix(String fileSuffix) + public static Iterator<ImageWriter> getImageWritersBySuffix(String fileSuffix) { if (fileSuffix == null) throw new IllegalArgumentException("fileSuffix may not be null"); @@ -1068,8 +1090,7 @@ if (writer == null) throw new IllegalArgumentException ("null argument"); - ImageWriterSpi spi = (ImageWriterSpi) getRegistry() - .getServiceProviderByClass(writer.getClass()); + ImageWriterSpi spi = writer.getOriginatingProvider(); String[] readerSpiNames = spi.getImageReaderSpiNames(); @@ -1098,14 +1119,16 @@ * * @return an iterator over a collection of image readers */ - public static Iterator getImageReaders (Object input) + public static Iterator<ImageReader> getImageReaders (Object input) { if (input == null) throw new IllegalArgumentException ("null argument"); - return getRegistry().getServiceProviders (ImageReaderSpi.class, + Iterator<ImageReaderSpi> spiIterator + = getRegistry().getServiceProviders (ImageReaderSpi.class, new ReaderObjectFilter(input), true); + return new ImageReaderIterator(spiIterator); } /** @@ -1118,16 +1141,18 @@ * * @return an iterator over a collection of image writers */ - public static Iterator getImageWriters (ImageTypeSpecifier type, + public static Iterator<ImageWriter> getImageWriters (ImageTypeSpecifier type, String formatName) { if (type == null || formatName == null) throw new IllegalArgumentException ("null argument"); - return getRegistry().getServiceProviders (ImageWriterSpi.class, + final Iterator<ImageWriterSpi> spiIterator + = getRegistry().getServiceProviders (ImageWriterSpi.class, new WriterObjectFilter(type, formatName), true); + return new ImageWriterIterator(spiIterator); } /** @@ -1149,8 +1174,7 @@ if (reader == null) throw new IllegalArgumentException ("null argument"); - ImageReaderSpi spi = (ImageReaderSpi) getRegistry() - .getServiceProviderByClass(reader.getClass()); + ImageReaderSpi spi = reader.getOriginatingProvider(); String[] writerSpiNames = spi.getImageWriterSpiNames(); @@ -1184,15 +1208,33 @@ * @exception IllegalArgumentException if either reader or writer is * null */ - public static Iterator getImageTranscoders (ImageReader reader, + public static Iterator<ImageTranscoder> getImageTranscoders (ImageReader reader, ImageWriter writer) { if (reader == null || writer == null) throw new IllegalArgumentException ("null argument"); - return getRegistry().getServiceProviders (ImageTranscoderSpi.class, + final Iterator<ImageTranscoderSpi> spiIterator + = getRegistry().getServiceProviders (ImageTranscoderSpi.class, new TranscoderFilter (reader, writer), true); + return new Iterator<ImageTranscoder>() + { + public boolean hasNext() + { + return spiIterator.hasNext(); + } + + public ImageTranscoder next() + { + return spiIterator.next().createTranscoderInstance(); + } + + public void remove() + { + throw new UnsupportedOperationException(); + } + }; } } Modified: trunk/core/src/classpath/javax/javax/imageio/ImageReader.java =================================================================== --- trunk/core/src/classpath/javax/javax/imageio/ImageReader.java 2007-01-07 05:43:57 UTC (rev 2998) +++ trunk/core/src/classpath/javax/javax/imageio/ImageReader.java 2007-01-07 08:19:52 UTC (rev 2999) @@ -116,7 +116,7 @@ * A list of installed progress listeners. Initially null, meaning * no installed listeners. */ - protected List progressListeners = null; + protected List<IIOReadProgressListener> progressListeners = null; /** * true if this reader should only read data further ahead in the @@ -129,19 +129,19 @@ * A list of installed update listeners. Initially null, meaning no * installed listeners. */ - protected List updateListeners = null; + protected List<IIOReadUpdateListener> updateListeners = null; /** * A list of installed warning listeners. Initially null, meaning * no installed listeners. */ - protected List warningListeners = null; + protected List<IIOReadWarningListener> warningListeners = null; /** * A list of warning locales corresponding with the list of * installed warning listeners. Initially null, meaning no locales. */ - protected List warningLocales = null; + protected List<Locale> warningLocales = null; /** * Construct an image reader. @@ -371,7 +371,7 @@ * out-of-bounds * @exception IOException if a read error occurs */ - public abstract Iterator getImageTypes(int imageIndex) + public abstract Iterator<ImageTypeSpecifier> getImageTypes(int imageIndex) throws IOException; /** @@ -1594,7 +1594,7 @@ * height is greater than Integer.MAX_VALUE */ protected static BufferedImage getDestination (ImageReadParam param, - Iterator imageTypes, + Iterator<ImageTypeSpecifier> imageTypes, int width, int height) throws IIOException @@ -1694,7 +1694,7 @@ */ public IIOMetadata getImageMetadata (int imageIndex, String formatName, - Set nodeNames) + Set<String> nodeNames) throws IOException { if (formatName == null || nodeNames == null) @@ -1808,7 +1808,7 @@ * @exception IOException if a read error occurs */ public IIOMetadata getStreamMetadata (String formatName, - Set nodeNames) + Set<String> nodeNames) throws IOException { if (formatName == null || nodeNames == null) @@ -1915,7 +1915,7 @@ * destination image regions are empty * @exception IOException if a read error occurs */ - public Iterator readAll (Iterator params) + public Iterator<IIOImage> readAll (Iterator<? extends ImageReadParam> params) throws IOException { List l = new ArrayList (); Modified: trunk/core/src/classpath/javax/javax/imageio/ImageWriteParam.java =================================================================== --- trunk/core/src/classpath/javax/javax/imageio/ImageWriteParam.java 2007-01-07 05:43:57 UTC (rev 2998) +++ trunk/core/src/classpath/javax/javax/imageio/ImageWriteParam.java 2007-01-07 08:19:52 UTC (rev 2999) @@ -278,7 +278,7 @@ public String[] getCompressionQualityDescriptions() { checkNotExplicitCompression(); - checkCompressionTypesSet();; + checkCompressionTypesSet(); return null; } @@ -286,7 +286,7 @@ public float[] getCompressionQualityValues() { checkNotExplicitCompression(); - checkCompressionTypesSet();; + checkCompressionTypesSet(); return null; } Modified: trunk/core/src/classpath/javax/javax/imageio/ImageWriter.java =================================================================== --- trunk/core/src/classpath/javax/javax/imageio/ImageWriter.java 2007-01-07 05:43:57 UTC (rev 2998) +++ trunk/core/src/classpath/javax/javax/imageio/ImageWriter.java 2007-01-07 08:19:52 UTC (rev 2999) @@ -40,6 +40,7 @@ import java.awt.Dimension; import java.awt.Rectangle; +import java.awt.image.BufferedImage; import java.awt.image.Raster; import java.awt.image.RenderedImage; import java.io.IOException; @@ -102,19 +103,19 @@ * A list of installed progress listeners. Initially null, meaning * no installed listeners. */ - protected List progressListeners = null; + protected List<IIOWriteProgressListener> progressListeners = null; /** * A list of installed warning listeners. Initially null, meaning * no installed listeners. */ - protected List warningListeners = null; + protected List<IIOWriteWarningListener> warningListeners = null; /** * A list of warning locales corresponding with the list of * installed warning listeners. Initially null, meaning no locales. */ - protected List warningLocales = null; + protected List<Locale> warningLocales = null; /** * Construct an image writer. @@ -1076,7 +1077,7 @@ public void prepareInsertEmpty (int imageIndex, ImageTypeSpecifier imageType, int width, int height, IIOMetadata imageMetadata, - List thumbnails, + List<? extends BufferedImage> thumbnails, ImageWriteParam param) throws IOException { @@ -1149,7 +1150,7 @@ ImageTypeSpecifier imageType, int width, int height, IIOMetadata imageMetadata, - List thumbnails, + List<? extends BufferedImage> thumbnails, ImageWriteParam param) throws IOException { Modified: trunk/core/src/classpath/javax/javax/imageio/metadata/IIOMetadataFormat.java =================================================================== --- trunk/core/src/classpath/javax/javax/imageio/metadata/IIOMetadataFormat.java 2007-01-07 05:43:57 UTC (rev 2998) +++ trunk/core/src/classpath/javax/javax/imageio/metadata/IIOMetadataFormat.java 2007-01-07 08:19:52 UTC (rev 2999) @@ -106,15 +106,15 @@ int getObjectArrayMinLength (String elementName); - Class getObjectClass (String elementName); + Class<?> getObjectClass (String elementName); Object getObjectDefaultValue (String elementName); Object[] getObjectEnumerations (String elementName); - Comparable getObjectMaxValue (String elementName); + Comparable<?> getObjectMaxValue (String elementName); - Comparable getObjectMinValue (String elementName); + Comparable<?> getObjectMinValue (String elementName); int getObjectValueType (String elementName); Modified: trunk/core/src/classpath/javax/javax/imageio/metadata/IIOMetadataFormatImpl.java =================================================================== --- trunk/core/src/classpath/javax/javax/imageio/metadata/IIOMetadataFormatImpl.java 2007-01-07 05:43:57 UTC (rev 2998) +++ trunk/core/src/classpath/javax/javax/imageio/metadata/IIOMetadataFormatImpl.java 2007-01-07 08:19:52 UTC (rev 2999) @@ -462,7 +462,7 @@ int dataType, boolean required, String defaultValue, - List enumeratedValues) + List<String> enumeratedValues) { IIOMetadataNode node = (IIOMetadataNode) nodes.get (elementName); node.setAttributeNode (new IIOMetadataNodeAttrEnumerated (node, @@ -568,8 +568,8 @@ node.setUserObject (null); } - protected void addObjectValue (String elementName, Class classType, - boolean required, Object defaultValue) + protected <T> void addObjectValue (String elementName, Class<T> classType, + boolean required, T defaultValue) { IIOMetadataNode node = (IIOMetadataNode) nodes.get (elementName); addNodeObject (node, new NodeObject (node, @@ -578,9 +578,9 @@ defaultValue)); } - protected void addObjectValue (String elementName, Class classType, - boolean required, Object defaultValue, - List enumeratedValues) + protected <T> void addObjectValue (String elementName, Class<T> classType, + boolean required, T defaultValue, + List<? extends T> enumeratedValues) { IIOMetadataNode node = (IIOMetadataNode) nodes.get (elementName); addNodeObject (node, new NodeObjectEnumerated (node, @@ -590,10 +590,11 @@ enumeratedValues)); } - protected void addObjectValue (String elementName, Class classType, - Object defaultValue, - Comparable minValue, - Comparable maxValue, + protected <T extends Object & Comparable<? super T>> + void addObjectValue (String elementName, Class<T> classType, + T defaultValue, + Comparable<? super T> minValue, + Comparable<? super T> maxValue, boolean minInclusive, boolean maxInclusive) { @@ -607,7 +608,7 @@ maxInclusive)); } - protected void addObjectValue (String elementName, Class classType, + protected void addObjectValue (String elementName, Class<?> classType, int arrayMinLength, int arrayMaxLength) { IIOMetadataNode node = (IIOMetadataNode) nodes.get (elementName); @@ -836,7 +837,7 @@ return ((Integer) ((NodeObjectArray) getNodeObject (node)).getArrayMinLength ()).intValue(); } - public Class getObjectClass (String elementName) + public Class<?> getObjectClass (String elementName) { IIOMetadataNode node = (IIOMetadataNode) nodes.get (elementName); return getNodeObject (node).getClassType (); @@ -854,13 +855,13 @@ return ((NodeObjectEnumerated) getNodeObject (node)).getEnumerations (); } - public Comparable getObjectMaxValue (String elementName) + public Comparable<?> getObjectMaxValue (String elementName) { IIOMetadataNode node = (IIOMetadataNode) nodes.get (elementName); return ((NodeObjectBounded) getNodeObject (node)).getMaxValue (); } - public Comparable getObjectMinValue (String elementName) + public Comparable<?> getObjectMinValue (String elementName) { IIOMetadataNode node = (IIOMetadataNode) nodes.get (elementName); return ((NodeObjectBounded) getNodeObject (node)).getMinValue (); Modified: trunk/core/src/classpath/javax/javax/imageio/spi/IIORegistry.java =================================================================== --- trunk/core/src/classpath/javax/javax/imageio/spi/IIORegistry.java 2007-01-07 05:43:57 UTC (rev 2998) +++ trunk/core/src/classpath/javax/javax/imageio/spi/IIORegistry.java 2007-01-07 08:19:52 UTC (rev 2999) @@ -39,13 +39,13 @@ package javax.imageio.spi; import gnu.classpath.ServiceFactory; -import gnu.java.awt.ClasspathToolkit; import java.awt.Toolkit; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; +import gnu.java.awt.ClasspathToolkit; import gnu.javax.imageio.bmp.BMPImageReaderSpi; import gnu.javax.imageio.bmp.BMPImageWriterSpi; import gnu.javax.imageio.gif.GIFImageReaderSpi; Modified: trunk/core/src/classpath/javax/javax/imageio/spi/IIOServiceProvider.java =================================================================== --- trunk/core/src/classpath/javax/javax/imageio/spi/IIOServiceProvider.java 2007-01-07 05:43:57 UTC (rev 2998) +++ trunk/core/src/classpath/javax/javax/imageio/spi/IIOServiceProvider.java 2007-01-07 08:19:52 UTC (rev 2999) @@ -110,7 +110,7 @@ * @param category the service category for which this provider has * been registered as an implementor. */ - public void onRegistration(ServiceRegistry registry, Class category) + public void onRegistration(ServiceRegistry registry, Class<?> category) { } @@ -128,7 +128,7 @@ * @param category the service category for which this provider has * been registered as an implementor. */ - public void onDeregistration(ServiceRegistry registry, Class category) + public void onDeregistration(ServiceRegistry registry, Class<?> category) { } Modified: trunk/core/src/classpath/javax/javax/imageio/spi/ImageInputStreamSpi.java =================================================================== --- trunk/core/src/classpath/javax/javax/imageio/spi/ImageInputStreamSpi.java 2007-01-07 05:43:57 UTC (rev 2998) +++ trunk/core/src/classpath/javax/javax/imageio/spi/ImageInputStreamSpi.java 2007-01-07 08:19:52 UTC (rev 2999) @@ -59,7 +59,7 @@ * Indicates which kind of input is processable by the streams * created by {@link #createInputStreamInstance(Object)}. */ - protected Class inputClass; + protected Class<?> inputClass; /** @@ -80,7 +80,7 @@ * or <code>version</code> is <code>null</code>. */ public ImageInputStreamSpi(String vendorName, String version, - Class inputClass) + Class<?> inputClass) { super(vendorName, version); this.inputClass = inputClass; @@ -91,7 +91,7 @@ * Determines which kind of input is processable by the streams * created by {@link #createInputStreamInstance(Object)}. */ - public Class getInputClass() + public Class<?> getInputClass() { return inputClass; } Modified: trunk/core/src/classpath/javax/javax/imageio/spi/ImageOutputStreamSpi.java =================================================================== --- trunk/core/src/classpath/javax/javax/imageio/spi/ImageOutputStreamSpi.java 2007-01-07 05:43:57 UTC (rev 2998) +++ trunk/core/src/classpath/javax/javax/imageio/spi/ImageOutputStreamSpi.java 2007-01-07 08:19:52 UTC (rev 2999) @@ -59,7 +59,7 @@ * Indicates which kind of output is produced by the streams * created by {@link #createOutputStreamInstance(Object)}. */ - protected Class outputClass; + protected Class<?> outputClass; /** @@ -80,7 +80,7 @@ * or <code>version</code> is <code>null</code>. */ public ImageOutputStreamSpi(String vendorName, String version, - Class outputClass) + Class<?> outputClass) { super(vendorName, version); this.outputClass = outputClass; @@ -91,7 +91,7 @@ * Determines which kind of output is produced by the streams * created by {@link #createOutputStreamInstance(Object)}. */ - public Class getOutputClass() + public Class<?> getOutputClass() { return outputClass; } Modified: trunk/core/src/classpath/javax/javax/imageio/spi/RegisterableService.java =================================================================== --- trunk/core/src/classpath/javax/javax/imageio/spi/RegisterableService.java 2007-01-07 05:43:57 UTC (rev 2998) +++ trunk/core/src/classpath/javax/javax/imageio/spi/RegisterableService.java 2007-01-07 08:19:52 UTC (rev 2999) @@ -62,7 +62,7 @@ * @param category the service category for which this provider has * been registered as an implementor. */ - void onRegistration(ServiceRegistry registry, Class category); + void onRegistration(ServiceRegistry registry, Class<?> category); /** @@ -78,6 +78,6 @@ * @param category the service category for which this provider has * been registered as an implementor. */ - void onDeregistration(ServiceRegistry registry, Class category); + void onDeregistration(ServiceRegistry registry, Class<?> category); } Modified: trunk/core/src/classpath/javax/javax/imageio/spi/ServiceRegistry.java =================================================================== --- trunk/core/src/classpath/javax/javax/imageio/spi/ServiceRegistry.java 2007-01-07 05:43:57 UTC (rev 2998) +++ trunk/core/src/classpath/javax/javax/imageio/spi/ServiceRegistry.java 2007-01-07 08:19:52 UTC (rev 2999) @@ -121,7 +121,7 @@ * @throws ClassCastException if <code>categories</code> does not * iterate over instances of {@link java.lang.Class}. */ - public ServiceRegistry(Iterator categories) + public ServiceRegistry(Iterator<Class<?>> categories) { ArrayList cats = new ArrayList(/* expected size */ 10); @@ -178,7 +178,7 @@ * @throws IllegalArgumentException if <code>spi</code> is * <code>null</code>. */ - public static Iterator lookupProviders(Class spi, + public static <T> Iterator<T> lookupProviders(Class<T> spi, ClassLoader loader) { return ServiceFactory.lookupProviders(spi, loader); @@ -200,7 +200,7 @@ * * @see #lookupProviders(Class, ClassLoader) */ - public static Iterator lookupProviders(Class spi) + public static <T> Iterator<T> lookupProviders(Class<T> spi) { return ServiceFactory.lookupProviders(spi); } @@ -212,7 +212,7 @@ * @return an unmodifiable {@link * java.util.Iterator}<{@link java.lang.Class}>. */ - public Iterator getCategories() + public Iterator<Class<?>> getCategories() { return new Iterator() { @@ -317,8 +317,8 @@ * @throws ClassCastException if <code>provider</code> does not * implement <code>category</code>. */ - public synchronized boolean registerServiceProvider(Object provider, - Class category) + public synchronized <T> boolean registerServiceProvider(T provider, + Class<T> category) { for (int i = 0; i < categories.length; i++) if (categories[i] == category) @@ -383,7 +383,7 @@ * #ServiceRegistry(Iterator) constructor} of this * <code>ServiceRegistry</code>. */ - public synchronized void registerServiceProviders(Iterator providers) + public synchronized void registerServiceProviders(Iterator<?> providers) { if (providers == null) throw new IllegalArgumentException(); @@ -467,8 +467,8 @@ * @throws ClassCastException if <code>provider</code> does not * implement <code>category</code>. */ - public synchronized boolean deregisterServiceProvider(Object provider, - Class category) + public synchronized <T> boolean deregisterServiceProvider(T provider, + Class<T> category) { for (int i = 0; i < categories.length; i++) if (categories[i] == category) @@ -535,7 +535,7 @@ * #ServiceRegistry(Iterator) constructor} of this * <code>ServiceRegistry</code>. */ - public synchronized void deregisterAll(Class category) + public synchronized void deregisterAll(Class<?> category) { boolean ok = false; @@ -663,7 +663,8 @@ * * @see #getServiceProviders(Class, Filter, boolean) */ - public Iterator getServiceProviders(Class category, boolean useOrdering) + public <T> Iterator<T> getServiceProviders(Class<T> category, + boolean useOrdering) { return getServiceProviders(category, null, useOrdering); } @@ -691,7 +692,7 @@ * #ServiceRegistry(Iterator) constructor} of this * <code>ServiceRegistry</code>. */ - public synchronized Iterator getServiceProviders(Class category, + public synchronized <T> Iterator<T> getServiceProviders(Class<T> category, Filter filter, boolean useOrdering) { @@ -751,7 +752,7 @@ * * @param providerClass a class to search for. */ - public synchronized Object getServiceProviderByClass(Class providerClass) + public synchronized <T> T getServiceProviderByClass(Class<T> providerClass) { if (providerClass == null) throw new IllegalArgumentException(); @@ -772,7 +773,7 @@ { Object provider = iter.next(); if (providerClass.isInstance(provider)) - return provider; + return (T) provider; } } @@ -799,9 +800,9 @@ * @see #unsetOrdering * @see #getServiceProviders(Class, Filter, boolean) */ - public synchronized boolean setOrdering(Class category, - Object firstProvider, - Object secondProvider) + public synchronized <T> boolean setOrdering(Class<T> category, + T firstProvider, + T secondProvider) { return addConstraint(getCategoryID(category), firstProvider, secondProvider); @@ -826,9 +827,9 @@ * * @see #setOrdering */ - public synchronized boolean unsetOrdering(Class category, - Object firstProvider, - Object secondProvider) + public synchronized <T> boolean unsetOrdering(Class<T> category, + T firstProvider, + T secondProvider) { return removeConstraint(getCategoryID(category), firstProvider, secondProvider); @@ -956,6 +957,6 @@ * criteria; <code>false</code> if it does not match. */ boolean filter(Object provider); - }; + } } Modified: trunk/core/src/classpath/javax/javax/imageio/stream/FileCacheImageOutputStream.java =================================================================== --- trunk/core/src/classpath/javax/javax/imageio/stream/FileCacheImageOutputStream.java 2007-01-07 05:43:57 UTC (rev 2998) +++ trunk/core/src/classpath/javax/javax/imageio/stream/FileCacheImageOutputStream.java 2007-01-07 08:19:52 UTC (rev 2999) @@ -38,11 +38,10 @@ package javax.imageio.stream; -import gnu.classpath.NotImplementedException; - import java.io.File; import java.io.IOException; import java.io.OutputStream; +import java.io.RandomAccessFile; /** * @author Michael Koch (kon...@gm...) @@ -50,34 +49,32 @@ public class FileCacheImageOutputStream extends ImageOutputStreamImpl { private OutputStream stream; - private File cacheDir; + private File cacheFile; + private RandomAccessFile cache; + private long maxPos; - public FileCacheImageOutputStream(OutputStream stream, File cacheDir) + public FileCacheImageOutputStream(OutputStream s, File cacheDir) throws IOException { - super(); - this.stream = stream; - // FIXME: We do not support caching yet. - this.cacheDir = cacheDir; + stream = s; + cacheFile = File.createTempFile("imageio", ".tmp", cacheDir); + cache = new RandomAccessFile(cacheFile, "rw"); + maxPos = 0; } public void close() throws IOException { - if (stream != null) - { - stream.close(); + maxPos = cache.length(); + seek(maxPos); + flushBefore(maxPos); + super.close(); + cache.close(); + cacheFile.delete(); + stream.flush(); stream = null; } - } - private void checkStreamClosed() - throws IOException - { - if (stream == null) - throw new IOException("stream closed"); - } - public boolean isCached() { return true; @@ -94,32 +91,88 @@ } public int read() - throws IOException, NotImplementedException + throws IOException { - // FIXME: Implement me. - throw new Error("not implemented"); + bitOffset = 0; + int val = cache.read(); + if (val != -1) + streamPos++; + return val; } public int read(byte[] data, int offset, int len) - throws IOException, NotImplementedException + throws IOException { - // FIXME: Implement me. - throw new Error("not implemented"); + bitOffset = 0; + int num = cache.read(data, offset, len); + if (num != -1) + streamPos += num; + return num; } public void write(byte[] data, int offset, int len) throws IOException { - checkStreamClosed(); - // FIXME: Flush pending bits. - stream.write(data, offset, len); + flushBits(); + cache.write(data, offset, len); + streamPos += len; + maxPos = Math.max(streamPos, maxPos); } public void write(int value) throws IOException { - checkStreamClosed(); - // FIXME: Flush pending bits. - stream.write(value); + flushBits(); + cache.write(value); + streamPos++; + maxPos = Math.max(streamPos, maxPos); } + + public long length() + { + long l; + try + { + l = cache.length(); + } + catch (IOException ex) + { + l = -1; + } + return l; + } + + public void seek(long pos) + throws IOException + { + checkClosed(); + if (pos < flushedPos) + throw new IndexOutOfBoundsException(); + cache.seek(pos); + streamPos = cache.getFilePointer(); + maxPos = Math.max(streamPos, maxPos); + bitOffset = 0; + } + + public void flushBefore(long pos) + throws IOException + { + long oldPos = flushedPos; + super.flushBefore(pos); + long flushed = flushedPos - oldPos; + if (flushed > 0) + { + int len = 512; + byte[] buf = new byte[len]; + cache.seek(oldPos); + while (flushed > 0) + { + int l = (int) Math.min(flushed, len); + cache.readFully(buf, 0, l); + stream.write(buf, 0, l); + flushed -= l; + } + stream.flush(); + } + } } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <ls...@us...> - 2007-01-07 05:43:59
|
Revision: 2998 http://jnode.svn.sourceforge.net/jnode/?rev=2998&view=rev Author: lsantha Date: 2007-01-06 21:43:57 -0800 (Sat, 06 Jan 2007) Log Message: ----------- Classpath patches. Added Paths: ----------- trunk/core/src/classpath/vm/sun/ trunk/core/src/classpath/vm/sun/misc/ trunk/core/src/classpath/vm/sun/misc/Unsafe.java trunk/core/src/classpath/vm/sun/reflect/ trunk/core/src/classpath/vm/sun/reflect/Reflection.java trunk/core/src/classpath/vm/sun/reflect/misc/ trunk/core/src/classpath/vm/sun/reflect/misc/ReflectUtil.java Added: trunk/core/src/classpath/vm/sun/misc/Unsafe.java =================================================================== --- trunk/core/src/classpath/vm/sun/misc/Unsafe.java (rev 0) +++ trunk/core/src/classpath/vm/sun/misc/Unsafe.java 2007-01-07 05:43:57 UTC (rev 2998) @@ -0,0 +1,328 @@ +/* Unsafe.java - Unsafe operations needed for concurrency + Copyright (C) 2006 Free Software Foundation + +This file is part of GNU Classpath. + +GNU Classpath is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2, or (at your option) +any later version. + +GNU Classpath is distributed in the hope that it will be useful, but +WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +General Public License for more details. + +You should have received a copy of the GNU General Public License +along with GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA +02110-1301 USA. + +Linking this library statically or dynamically with other modules is +making a combined work based on this library. Thus, the terms and +conditions of the GNU General Public License cover the whole +combination. + +As a special exception, the copyright holders of this library give you +permission to link this library with independent modules to produce an +executable, regardless of the license terms of these independent +modules, and to copy and distribute the resulting executable under +terms of your choice, provided that you also meet, for each linked +independent module, the terms and conditions of the license of that +module. An independent module is a module which is not derived from +or based on this library. If you modify this library, you may extend +this exception to your version of the library, but you are not +obligated to do so. If you do not wish to do so, delete this +exception statement from your version. */ + +package sun.misc; + +import java.lang.reflect.Field; + +/** + * This class should provide access to low-level operations and its + * use should be limited to trusted code. Fields can be accessed using + * memory addresses, with undefined behaviour occurring if invalid memory + * addresses are given. + * + * @author Tom Tromey (tr...@re...) + * @author Andrew John Hughes (gnu...@me...) + */ +public class Unsafe +{ + // Singleton class. + private static Unsafe unsafe = new Unsafe(); + + /** + * Private default constructor to prevent creation of an arbitrary + * number of instances. + */ + private Unsafe() + { + } + + /** + * Retrieve the singleton instance of <code>Unsafe</code>. The calling + * method should guard this instance from untrusted code, as it provides + * access to low-level operations such as direct memory access. + * + * @throws SecurityException if a security manager exists and prevents + * access to the system properties. + */ + public static Unsafe getUnsafe() + { + SecurityManager sm = System.getSecurityManager(); + if (sm != null) + sm.checkPropertiesAccess(); + return unsafe; + } + + /** + * Returns the memory address offset of the given static field. + * The offset is merely used as a means to access a particular field + * in the other methods of this class. The value is unique to the given + * field and the same value should be returned on each subsequent call. + * + * @param field the field whose offset should be returned. + * @return the offset of the given field. + */ + public native long objectFieldOffset(Field field); + + /** + * Compares the value of the integer field at the specified offset + * in the supplied object with the given expected value, and updates + * it if they match. The operation of this method should be atomic, + * thus providing an uninterruptible way of updating an integer field. + * + * @param obj the object containing the field to modify. + * @param offset the offset of the integer field within <code>obj</code>. + * @param expect the expected value of the field. + * @param update the new value of the field if it equals <code>expect</code>. + * @return true if the field was changed. + */ + public native boolean compareAndSwapInt(Object obj, long offset, + int expect, int update); + + /** + * Compares the value of the long field at the specified offset + * in the supplied object with the given expected value, and updates + * it if they match. The operation of this method should be atomic, + * thus providing an uninterruptible way of updating a long field. + * + * @param obj the object containing the field to modify. + * @param offset the offset of the long field within <code>obj</code>. + * @param expect the expected value of the field. + * @param update the new value of the field if it equals <code>expect</code>. + * @return true if the field was changed. + */ + public native boolean compareAndSwapLong(Object obj, long offset, + long expect, long update); + + /** + * Compares the value of the object field at the specified offset + * in the supplied object with the given expected value, and updates + * it if they match. The operation of this method should be atomic, + * thus providing an uninterruptible way of updating an object field. + * + * @param obj the object containing the field to modify. + * @param offset the offset of the object field within <code>obj</code>. + * @param expect the expected value of the field. + * @param update the new value of the field if it equals <code>expect</code>. + * @return true if the field was changed. + */ + public native boolean compareAndSwapObject(Object obj, long offset, + Object expect, Object update); + + /** + * Sets the value of the integer field at the specified offset in the + * supplied object to the given value. This is an ordered or lazy + * version of <code>putIntVolatile(Object,long,int)</code>, which + * doesn't guarantee the immediate visibility of the change to other + * threads. It is only really useful where the integer field is + * <code>volatile</code>, and is thus expected to change unexpectedly. + * + * @param obj the object containing the field to modify. + * @param offset the offset of the integer field within <code>obj</code>. + * @param value the new value of the field. + * @see #putIntVolatile(Object,long,int) + */ + public native void putOrderedInt(Object obj, long offset, int value); + + /** + * Sets the value of the long field at the specified offset in the + * supplied object to the given value. This is an ordered or lazy + * version of <code>putLongVolatile(Object,long,long)</code>, which + * doesn't guarantee the immediate visibility of the change to other + * threads. It is only really useful where the long field is + * <code>volatile</code>, and is thus expected to change unexpectedly. + * + * @param obj the object containing the field to modify. + * @param offset the offset of the long field within <code>obj</code>. + * @param value the new value of the field. + * @see #putLongVolatile(Object,long,long) + */ + public native void putOrderedLong(Object obj, long offset, long value); + + /** + * Sets the value of the object field at the specified offset in the + * supplied object to the given value. This is an ordered or lazy + * version of <code>putObjectVolatile(Object,long,Object)</code>, which + * doesn't guarantee the immediate visibility of the change to other + * threads. It is only really useful where the object field is + * <code>volatile</code>, and is thus expected to change unexpectedly. + * + * @param obj the object containing the field to modify. + * @param offset the offset of the object field within <code>obj</code>. + * @param value the new value of the field. + */ + public native void putOrderedObject(Object obj, long offset, Object value); + + /** + * Sets the value of the integer field at the specified offset in the + * supplied object to the given value, with volatile store semantics. + * + * @param obj the object containing the field to modify. + * @param offset the offset of the integer field within <code>obj</code>. + * @param value the new value of the field. + */ + public native void putIntVolatile(Object obj, long offset, int value); + + /** + * Retrieves the value of the integer field at the specified offset in the + * supplied object with volatile load semantics. + * + * @param obj the object containing the field to read. + * @param offset the offset of the integer field within <code>obj</code>. + */ + public native int getIntVolatile(Object obj, long offset); + + /** + * Sets the value of the long field at the specified offset in the + * supplied object to the given value, with volatile store semantics. + * + * @param obj the object containing the field to modify. + * @param offset the offset of the long field within <code>obj</code>. + * @param value the new value of the field. + * @see #putLong(Object,long,long) + */ + public native void putLongVolatile(Object obj, long offset, long value); + + /** + * Sets the value of the long field at the specified offset in the + * supplied object to the given value. + * + * @param obj the object containing the field to modify. + * @param offset the offset of the long field within <code>obj</code>. + * @param value the new value of the field. + * @see #putLongVolatile(Object,long,long) + */ + public native void putLong(Object obj, long offset, long value); + + /** + * Retrieves the value of the long field at the specified offset in the + * supplied object with volatile load semantics. + * + * @param obj the object containing the field to read. + * @param offset the offset of the long field within <code>obj</code>. + * @see #getLong(Object,long) + */ + public native long getLongVolatile(Object obj, long offset); + + /** + * Retrieves the value of the long field at the specified offset in the + * supplied object. + * + * @param obj the object containing the field to read. + * @param offset the offset of the long field within <code>obj</code>. + * @see #getLongVolatile(Object,long) + */ + public native long getLong(Object obj, long offset); + + /** + * Sets the value of the object field at the specified offset in the + * supplied object to the given value, with volatile store semantics. + * + * @param obj the object containing the field to modify. + * @param offset the offset of the object field within <code>obj</code>. + * @param value the new value of the field. + * @see #putObject(Object,long,Object) + */ + public native void putObjectVolatile(Object obj, long offset, Object value); + + /** + * Sets the value of the object field at the specified offset in the + * supplied object to the given value. + * + * @param obj the object containing the field to modify. + * @param offset the offset of the object field within <code>obj</code>. + * @param value the new value of the field. + * @see #putObjectVolatile(Object,long,Object) + */ + public native void putObject(Object obj, long offset, Object value); + + /** + * Retrieves the value of the object field at the specified offset in the + * supplied object with volatile load semantics. + * + * @param obj the object containing the field to read. + * @param offset the offset of the object field within <code>obj</code>. + */ + public native Object getObjectVolatile(Object obj, long offset); + + /** + * Returns the offset of the first element for a given array class. + * To access elements of the array class, this value may be used along + * with that returned by + * <a href="#arrayIndexScale"><code>arrayIndexScale</code></a>, + * if non-zero. + * + * @param arrayClass the class for which the first element's address should + * be obtained. + * @return the offset of the first element of the array class. + * @see arrayIndexScale(Class) + */ + public native int arrayBaseOffset(Class arrayClass); + + /** + * Returns the scale factor used for addressing elements of the supplied + * array class. Where a suitable scale factor can not be returned (e.g. + * for primitive types), zero should be returned. The returned value + * can be used with + * <a href="#arrayBaseOffset"><code>arrayBaseOffset</code></a> + * to access elements of the class. + * + * @param arrayClass the class whose scale factor should be returned. + * @return the scale factor, or zero if not supported for this array class. + */ + public native int arrayIndexScale(Class arrayClass); + + /** + * Releases the block on a thread created by + * <a href="#park"><code>park</code></a>. This method can also be used + * to terminate a blockage caused by a prior call to <code>park</code>. + * This operation is unsafe, as the thread must be guaranteed to be + * live. This is true of Java, but not native code. + * + * @param thread the thread to unblock. + */ + public native void unpark(Thread thread); + + /** + * Blocks the thread until a matching + * <a href="#unpark"><code>unpark</code></a> occurs, the thread is + * interrupted or the optional timeout expires. If an <code>unpark</code> + * call has already occurred, this also counts. A timeout value of zero + * is defined as no timeout. When <code>isAbsolute</code> is + * <code>true</code>, the timeout is in milliseconds relative to the + * epoch. Otherwise, the value is the number of nanoseconds which must + * occur before timeout. This call may also return spuriously (i.e. + * for no apparent reason). + * + * @param isAbsolute true if the timeout is specified in milliseconds from + * the epoch. + * @param time either the number of nanoseconds to wait, or a time in + * milliseconds from the epoch to wait for. + */ + public native void park(boolean isAbsolute, long time); + +} Added: trunk/core/src/classpath/vm/sun/reflect/Reflection.java =================================================================== --- trunk/core/src/classpath/vm/sun/reflect/Reflection.java (rev 0) +++ trunk/core/src/classpath/vm/sun/reflect/Reflection.java 2007-01-07 05:43:57 UTC (rev 2998) @@ -0,0 +1,51 @@ +/* Reflection.java - JSR 166 reflection hooks + Copyright (C) 2006 Free Software Foundation + +This file is part of GNU Classpath. + +GNU Classpath is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2, or (at your option) +any later version. + +GNU Classpath is distributed in the hope that it will be useful, but +WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +General Public License for more details. + +You should have received a copy of the GNU General Public License +along with GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA +02110-1301 USA. + +Linking this library statically or dynamically with other modules is +making a combined work based on this library. Thus, the terms and +conditions of the GNU General Public License cover the whole +combination. + +As a special exception, the copyright holders of this library give you +permission to link this library with independent modules to produce an +executable, regardless of the license terms of these independent +modules, and to copy and distribute the resulting executable under +terms of your choice, provided that you also meet, for each linked +independent module, the terms and conditions of the license of that +module. An independent module is a module which is not derived from +or based on this library. If you modify this library, you may extend +this exception to your version of the library, but you are not +obligated to do so. If you do not wish to do so, delete this +exception statement from your version. */ + +package sun.reflect; + +import gnu.classpath.VMStackWalker; + +public class Reflection +{ + /** + * A stack-walking wrapper method used by the JSR 166 RI. + */ + public static Class getCallerClass(int depth) + { + return VMStackWalker.getClassContext()[depth]; + } +} Added: trunk/core/src/classpath/vm/sun/reflect/misc/ReflectUtil.java =================================================================== --- trunk/core/src/classpath/vm/sun/reflect/misc/ReflectUtil.java (rev 0) +++ trunk/core/src/classpath/vm/sun/reflect/misc/ReflectUtil.java 2007-01-07 05:43:57 UTC (rev 2998) @@ -0,0 +1,113 @@ +/* ReflectUtil.java - JSR 166 reflection hooks + Copyright (C) 2006 Free Software Foundation + +This file is part of GNU Classpath. + +GNU Classpath is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2, or (at your option) +any later version. + +GNU Classpath is distributed in the hope that it will be useful, but +WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +General Public License for more details. + +You should have received a copy of the GNU General Public License +along with GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA +02110-1301 USA. + +Linking this library statically or dynamically with other modules is +making a combined work based on this library. Thus, the terms and +conditions of the GNU General Public License cover the whole +combination. + +As a special exception, the copyright holders of this library give you +permission to link this library with independent modules to produce an +executable, regardless of the license terms of these independent +modules, and to copy and distribute the resulting executable under +terms of your choice, provided that you also meet, for each linked +independent module, the terms and conditions of the license of that +module. An independent module is a module which is not derived from +or based on this library. If you modify this library, you may extend +this exception to your version of the library, but you are not +obligated to do so. If you do not wish to do so, delete this +exception statement from your version. */ + +package sun.reflect.misc; + +import java.lang.reflect.Modifier; + +public class ReflectUtil +{ + // We use this inaccessible inner class as an argument type + // in verifyMemberAccess. All current users of this method + // in the JSR 166 RI pass 'null' for this argument, and + // consequently we don't know what it means. Using a funny + // type like this for the argument means that if the RI changes, + // we will see a compilation error. + private static class MustBeNull + { + } + + /** + * Check if the current thread is allowed to access the package of + * the declaringClass. + * + * @param declaringClass class name to check access to + * @throws SecurityException if permission is denied + * @throws NullPointerException if declaringClass is null + */ + public static void checkPackageAccess(Class declaringClass) + { + SecurityManager sm; + if ((sm = System.getSecurityManager()) != null) + { + while (declaringClass.isArray()) + declaringClass = declaringClass.getComponentType(); + String name = declaringClass.getName(); + int i = name.lastIndexOf('.'); + if (i != -1) // if declaringClass is a member of a package + { + name = name.substring(0, i); + sm.checkPackageAccess(name); + } + } + } + + /** + * Perform access checks on a member of a class. This API is + * derived from the public domain code in the JSR 166 reference + * implementation. + * @param caller the class requesting access to the member + * @param declarer the declaring class of the member + * @param ignored unknown parameter; always null + * @param modifiers the modifiers on the member + * @return true if access is granted, false otherwise + */ + public static void ensureMemberAccess(Class caller, + Class declarer, + MustBeNull ignored, + int modifiers) + { + // Same class, always ok. + if (caller == declarer) + return; + // Public access is ok. + if ((modifiers & Modifier.PUBLIC) != 0) + return; + // Protected access and request comes from + // a subclass of the declarer -- ok. + if ((modifiers & Modifier.PROTECTED) != 0 + && declarer.isAssignableFrom(caller)) + return; + // Package-private access, or protected access, + // and the packages are the same --ok. + if ((modifiers & Modifier.PRIVATE) == 0 + && caller.getPackage() == declarer.getPackage()) + return; + // Otherwise, no. + throw new IllegalAccessError(); + } +} This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <ls...@us...> - 2007-01-07 05:43:42
|
Revision: 2997 http://jnode.svn.sourceforge.net/jnode/?rev=2997&view=rev Author: lsantha Date: 2007-01-06 21:43:40 -0800 (Sat, 06 Jan 2007) Log Message: ----------- Classpath patches. Added Paths: ----------- trunk/core/src/classpath/sun/ trunk/core/src/classpath/sun/sun/ trunk/core/src/classpath/sun/sun/misc/ trunk/core/src/classpath/sun/sun/misc/Service.java trunk/core/src/classpath/sun/sun/misc/ServiceConfigurationError.java trunk/core/src/classpath/sun/sun/reflect/ trunk/core/src/classpath/sun/sun/reflect/annotation/ trunk/core/src/classpath/sun/sun/reflect/annotation/AnnotationInvocationHandler.java trunk/core/src/classpath/sun/sun/reflect/annotation/AnnotationParser.java trunk/core/src/classpath/sun/sun/reflect/annotation/AnnotationType.java trunk/core/src/classpath/sun/sun/reflect/annotation/EnumConstantNotPresentExceptionProxy.java trunk/core/src/classpath/sun/sun/reflect/annotation/ExceptionProxy.java Added: trunk/core/src/classpath/sun/sun/misc/Service.java =================================================================== --- trunk/core/src/classpath/sun/sun/misc/Service.java (rev 0) +++ trunk/core/src/classpath/sun/sun/misc/Service.java 2007-01-07 05:43:40 UTC (rev 2997) @@ -0,0 +1,66 @@ +/* Service.java -- A wrapper around GNU service provision. + Copyright (C) 2006 Free Software Foundation + +This file is part of GNU Classpath. + +GNU Classpath is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2, or (at your option) +any later version. + +GNU Classpath is distributed in the hope that it will be useful, but +WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +General Public License for more details. + +You should have received a copy of the GNU General Public License +along with GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA +02110-1301 USA. + +Linking this library statically or dynamically with other modules is +making a combined work based on this library. Thus, the terms and +conditions of the GNU General Public License cover the whole +combination. + +As a special exception, the copyright holders of this library give you +permission to link this library with independent modules to produce an +executable, regardless of the license terms of these independent +modules, and to copy and distribute the resulting executable under +terms of your choice, provided that you also meet, for each linked +independent module, the terms and conditions of the license of that +module. An independent module is a module which is not derived from +or based on this library. If you modify this library, you may extend +this exception to your version of the library, but you are not +obligated to do so. If you do not wish to do so, delete this +exception statement from your version. */ + + +package sun.misc; + +import gnu.classpath.ServiceFactory; + +import java.util.Iterator; + +public class Service +{ + + /** + * Returns an {@link Iterator} over the service providers which + * provide a service of the given class, and are available from + * the specified classloader. + * + * @param c the service provider interface which must be + * implemented by any loaded service providers. + * @param cl the class loader that will be used to load the + * service providers, or <code>null</code> for the system class + * loader. + * @return an iterator over the service providers. + */ + public static <P> Iterator<P> providers(Class<P> c, ClassLoader cl) + { + return (Iterator<P>) ServiceFactory.lookupProviders(c, cl); + } + +} + Added: trunk/core/src/classpath/sun/sun/misc/ServiceConfigurationError.java =================================================================== --- trunk/core/src/classpath/sun/sun/misc/ServiceConfigurationError.java (rev 0) +++ trunk/core/src/classpath/sun/sun/misc/ServiceConfigurationError.java 2007-01-07 05:43:40 UTC (rev 2997) @@ -0,0 +1,64 @@ +/* ServiceConfigurationError.java -- An error from service configuration. + Copyright (C) 2006 Free Software Foundation + +This file is part of GNU Classpath. + +GNU Classpath is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2, or (at your option) +any later version. + +GNU Classpath is distributed in the hope that it will be useful, but +WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +General Public License for more details. + +You should have received a copy of the GNU General Public License +along with GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA +02110-1301 USA. + +Linking this library statically or dynamically with other modules is +making a combined work based on this library. Thus, the terms and +conditions of the GNU General Public License cover the whole +combination. + +As a special exception, the copyright holders of this library give you +permission to link this library with independent modules to produce an +executable, regardless of the license terms of these independent +modules, and to copy and distribute the resulting executable under +terms of your choice, provided that you also meet, for each linked +independent module, the terms and conditions of the license of that +module. An independent module is a module which is not derived from +or based on this library. If you modify this library, you may extend +this exception to your version of the library, but you are not +obligated to do so. If you do not wish to do so, delete this +exception statement from your version. */ + + +package sun.misc; + +public class ServiceConfigurationError + extends Error +{ + + /** + * Constructs a new {@link ServiceConfigurationError} + */ + public ServiceConfigurationError() + { + super(); + } + + /** + * Constructs a new {@link ServiceConfigurationError} + * with the specified message. + */ + public ServiceConfigurationError(String message) + { + super(message); + } + + +} + Added: trunk/core/src/classpath/sun/sun/reflect/annotation/AnnotationInvocationHandler.java =================================================================== --- trunk/core/src/classpath/sun/sun/reflect/annotation/AnnotationInvocationHandler.java (rev 0) +++ trunk/core/src/classpath/sun/sun/reflect/annotation/AnnotationInvocationHandler.java 2007-01-07 05:43:40 UTC (rev 2997) @@ -0,0 +1,340 @@ +/* sun.reflect.annotation.AnnotationInvocationHandler + 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 sun.reflect.annotation; + +import java.io.Serializable; +import java.lang.annotation.AnnotationTypeMismatchException; +import java.lang.annotation.IncompleteAnnotationException; +import java.lang.reflect.InvocationHandler; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.util.Arrays; +import java.util.Iterator; +import java.util.Map; + +/** + * This class exists for serialization compatibility with the JDK. + * VMs can choose to implement annotations by constructing proxies + * with this invocation handler, but that is not required. + * If a different strategy for proxy objects is chosen, they can + * have a writeReplace method to substitute a Proxy based on this + * invocation handler is used for serialization. + */ +public final class AnnotationInvocationHandler + implements InvocationHandler, Serializable +{ + private static final long serialVersionUID = 6182022883658399397L; + private final Class type; + private final Map memberValues; + + /** + * Construct a new invocation handler for an annotation proxy. + * Note that the VM is responsible for filling the memberValues map + * with the default values of all the annotation members. + */ + public AnnotationInvocationHandler(Class type, Map memberValues) + { + this.type = type; + this.memberValues = memberValues; + } + + /** + * Compare an instance of AnnotationInvocationHandler with another object. + * Note that the other object does not have to be an + * AnnotationInvocationHandler, any implementation of the annotation + * interface is allowed to be compared for equality. + * Note that this makes the equals method asymmetric, but this behavior + * is specified by Annotation.equals and identical to the JDK. + * + * This method is public for use by other parts of the VM. Some VMs + * (can) use different representations of annotations that reuse this + * method. + */ + public static boolean equals(Class type, Map memberValues, Object other) + { + if (type.isInstance(other)) + { + try + { + Method[] methods = type.getDeclaredMethods(); + if (methods.length == memberValues.size()) + { + for (int i = 0; i < methods.length; i++) + { + String key = methods[i].getName(); + Object val = methods[i].invoke(other, new Object[0]); + if (! deepEquals(memberValues.get(key), val)) + { + return false; + } + } + return true; + } + } + catch (IllegalAccessException _) + { + // Ignore exception, like the JDK + } + catch (InvocationTargetException _) + { + // Ignore exception, like the JDK + } + } + return false; + } + + private static boolean deepEquals(Object o1, Object o2) + { + if (o1 == o2) + return true; + + if (o1 == null || o2 == null) + return false; + + if (o1 instanceof boolean[] && o2 instanceof boolean[]) + return Arrays.equals((boolean[]) o1, (boolean[]) o2); + + if (o1 instanceof byte[] && o2 instanceof byte[]) + return Arrays.equals((byte[]) o1, (byte[]) o2); + + if (o1 instanceof char[] && o2 instanceof char[]) + return Arrays.equals((char[]) o1, (char[]) o2); + + if (o1 instanceof short[] && o2 instanceof short[]) + return Arrays.equals((short[]) o1, (short[]) o2); + + if (o1 instanceof int[] && o2 instanceof int[]) + return Arrays.equals((int[]) o1, (int[]) o2); + + if (o1 instanceof float[] && o2 instanceof float[]) + return Arrays.equals((float[]) o1, (float[]) o2); + + if (o1 instanceof long[] && o2 instanceof long[]) + return Arrays.equals((long[]) o1, (long[]) o2); + + if (o1 instanceof double[] && o2 instanceof double[]) + return Arrays.equals((double[]) o1, (double[]) o2); + + if (o1 instanceof Object[] && o2 instanceof Object[]) + return Arrays.equals((Object[]) o1, (Object[]) o2); + + return o1.equals(o2); + } + + private static int deepHashCode(Object obj) + { + if (obj instanceof boolean[]) + return Arrays.hashCode((boolean[]) obj); + + if (obj instanceof byte[]) + return Arrays.hashCode((byte[]) obj); + + if (obj instanceof char[]) + return Arrays.hashCode((char[]) obj); + + if (obj instanceof short[]) + return Arrays.hashCode((short[]) obj); + + if (obj instanceof int[]) + return Arrays.hashCode((int[]) obj); + + if (obj instanceof float[]) + return Arrays.hashCode((float[]) obj); + + if (obj instanceof long[]) + return Arrays.hashCode((long[]) obj); + + if (obj instanceof double[]) + return Arrays.hashCode((double[]) obj); + + if (obj instanceof Object[]) + return Arrays.hashCode((Object[]) obj); + + return obj.hashCode(); + } + + /** + * Compute the hashCode for an annotation. Note that the algorithm is + * specified by Annotation.hashCode. + * + * This method is public for use by other parts of the VM. Some VMs + * (can) use different representations of annotations that reuse this + * method. + */ + public static int hashCode(Class type, Map memberValues) + { + int h = 0; + Iterator iter = memberValues.keySet().iterator(); + while (iter.hasNext()) + { + Object key = iter.next(); + Object val = memberValues.get(key); + h += deepHashCode(val) ^ 127 * key.hashCode(); + } + return h; + } + + private static String deepToString(Object obj) + { + if (obj instanceof boolean[]) + return Arrays.toString((boolean[]) obj); + + if (obj instanceof byte[]) + return Arrays.toString((byte[]) obj); + + if (obj instanceof char[]) + return Arrays.toString((char[]) obj); + + if (obj instanceof short[]) + return Arrays.toString((short[]) obj); + + if (obj instanceof int[]) + return Arrays.toString((int[]) obj); + + if (obj instanceof float[]) + return Arrays.toString((float[]) obj); + + if (obj instanceof long[]) + return Arrays.toString((long[]) obj); + + if (obj instanceof double[]) + return Arrays.toString((double[]) obj); + + if (obj instanceof Object[]) + return Arrays.toString((Object[]) obj); + + return obj.toString(); + } + + /** + * This method is public for use by other parts of the VM. Some VMs + * (can) use different representations of annotations that reuse this + * method. + */ + public static String toString(Class type, Map memberValues) + { + StringBuffer sb = new StringBuffer(); + sb.append('@').append(type.getName()).append('('); + String sep = ""; + Iterator iter = memberValues.keySet().iterator(); + while (iter.hasNext()) + { + Object key = iter.next(); + Object val = memberValues.get(key); + sb.append(sep).append(key).append('=').append(deepToString(val)); + sep = ", "; + } + sb.append(')'); + return sb.toString(); + } + + private static Class getBoxedReturnType(Method method) + { + Class returnType = method.getReturnType(); + + if (returnType == boolean.class) + return Boolean.class; + + if (returnType == byte.class) + return Byte.class; + + if (returnType == char.class) + return Character.class; + + if (returnType == short.class) + return Short.class; + + if (returnType == int.class) + return Integer.class; + + if (returnType == float.class) + return Float.class; + + if (returnType == long.class) + return Long.class; + + if (returnType == double.class) + return Double.class; + + return returnType; + } + + public Object invoke(Object proxy, Method method, Object[] args) + throws Throwable + { + String methodName = method.getName().intern(); + if (args == null || args.length == 0) + { + if (methodName == "toString") + { + return toString(type, memberValues); + } + else if (methodName == "hashCode") + { + return Integer.valueOf(hashCode(type, memberValues)); + } + else if (methodName == "annotationType") + { + return type; + } + else + { + Object val = memberValues.get(methodName); + if (val == null) + { + throw new IncompleteAnnotationException(type, methodName); + } + if (! getBoxedReturnType(method).isInstance(val)) + { + throw new AnnotationTypeMismatchException(method, + val.getClass().getName()); + } + return val; + } + } + else if (args.length == 1) + { + if (methodName == "equals") + { + return Boolean.valueOf(equals(type, memberValues, args[0])); + } + } + throw new InternalError("Invalid annotation proxy"); + } +} Added: trunk/core/src/classpath/sun/sun/reflect/annotation/AnnotationParser.java =================================================================== --- trunk/core/src/classpath/sun/sun/reflect/annotation/AnnotationParser.java (rev 0) +++ trunk/core/src/classpath/sun/sun/reflect/annotation/AnnotationParser.java 2007-01-07 05:43:40 UTC (rev 2997) @@ -0,0 +1,57 @@ +/* sun.reflect.annotation.AnnotationParser + 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 sun.reflect.annotation; + +import gnu.classpath.NotImplementedException; + +import java.lang.annotation.Annotation; + +import java.util.Map; + +public class AnnotationParser +{ + + public static Annotation annotationForMap(Class<? extends Annotation> annoType, + Map<String, Object> map) + throws NotImplementedException + { + return null; + } + +} Added: trunk/core/src/classpath/sun/sun/reflect/annotation/AnnotationType.java =================================================================== --- trunk/core/src/classpath/sun/sun/reflect/annotation/AnnotationType.java (rev 0) +++ trunk/core/src/classpath/sun/sun/reflect/annotation/AnnotationType.java 2007-01-07 05:43:40 UTC (rev 2997) @@ -0,0 +1,52 @@ +/* sun.reflect.annotation.AnnotationType + 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 sun.reflect.annotation; + +import gnu.classpath.NotImplementedException; + +public class AnnotationType +{ + + public static Class<?> invocationHandlerReturnType(Class<?> returnClass) + throws NotImplementedException + { + return null; + } + +} Added: trunk/core/src/classpath/sun/sun/reflect/annotation/EnumConstantNotPresentExceptionProxy.java =================================================================== --- trunk/core/src/classpath/sun/sun/reflect/annotation/EnumConstantNotPresentExceptionProxy.java (rev 0) +++ trunk/core/src/classpath/sun/sun/reflect/annotation/EnumConstantNotPresentExceptionProxy.java 2007-01-07 05:43:40 UTC (rev 2997) @@ -0,0 +1,52 @@ +/* sun.reflect.annotation.EnumConstantNotPresentExceptionProxy + 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 sun.reflect.annotation; + +import gnu.classpath.NotImplementedException; + +public class EnumConstantNotPresentExceptionProxy + extends ExceptionProxy +{ + + public EnumConstantNotPresentExceptionProxy(Class c, String s) + throws NotImplementedException + { + } + +} Added: trunk/core/src/classpath/sun/sun/reflect/annotation/ExceptionProxy.java =================================================================== --- trunk/core/src/classpath/sun/sun/reflect/annotation/ExceptionProxy.java (rev 0) +++ trunk/core/src/classpath/sun/sun/reflect/annotation/ExceptionProxy.java 2007-01-07 05:43:40 UTC (rev 2997) @@ -0,0 +1,46 @@ +/* sun.reflect.annotation.ExceptionProxy + 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 sun.reflect.annotation; + +import gnu.classpath.NotImplementedException; + +public class ExceptionProxy +{ + +} This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <ls...@us...> - 2007-01-07 05:43:17
|
Revision: 2996 http://jnode.svn.sourceforge.net/jnode/?rev=2996&view=rev Author: lsantha Date: 2007-01-06 21:43:15 -0800 (Sat, 06 Jan 2007) Log Message: ----------- Classpath patches. Added Paths: ----------- trunk/core/src/classpath/java/java/text/spi/ trunk/core/src/classpath/java/java/text/spi/BreakIteratorProvider.java trunk/core/src/classpath/java/java/text/spi/CollatorProvider.java trunk/core/src/classpath/java/java/text/spi/DateFormatSymbolsProvider.java trunk/core/src/classpath/java/java/text/spi/package.html Added: trunk/core/src/classpath/java/java/text/spi/BreakIteratorProvider.java =================================================================== --- trunk/core/src/classpath/java/java/text/spi/BreakIteratorProvider.java (rev 0) +++ trunk/core/src/classpath/java/java/text/spi/BreakIteratorProvider.java 2007-01-07 05:43:15 UTC (rev 2996) @@ -0,0 +1,124 @@ +/* BreakIteratorProvider.java -- Providers of localized instances + Copyright (C) 2007 Free Software Foundation, Inc. + +This file is part of GNU Classpath. + +GNU Classpath is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2, or (at your option) +any later version. + +GNU Classpath is distributed in the hope that it will be useful, but +WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +General Public License for more details. + +You should have received a copy of the GNU General Public License +along with GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA +02110-1301 USA. + +Linking this library statically or dynamically with other modules is +making a combined work based on this library. Thus, the terms and +conditions of the GNU General Public License cover the whole +combination. + +As a special exception, the copyright holders of this library give you +permission to link this library with independent modules to produce an +executable, regardless of the license terms of these independent +modules, and to copy and distribute the resulting executable under +terms of your choice, provided that you also meet, for each linked +independent module, the terms and conditions of the license of that +module. An independent module is a module which is not derived from +or based on this library. If you modify this library, you may extend +this exception to your version of the library, but you are not +obligated to do so. If you do not wish to do so, delete this +exception statement from your version. */ + +package java.text.spi; + +import java.text.BreakIterator; + +import java.util.Locale; + +import java.util.spi.LocaleServiceProvider; + +/** + * A {@link BreakIteratorProvider} provides localized + * instances of {@link java.text.BreakIterator}. + * + * @author Andrew John Hughes (gnu...@me...) + * @since 1.6 + */ +public abstract class BreakIteratorProvider + extends LocaleServiceProvider +{ + + /** + * Constructs a new {@link BreakIteratorProvider}. + * Provided for implicit invocation by subclasses. + */ + protected BreakIteratorProvider() + { + } + + /** + * Returns a {@link java.text.BreakIterator} instance + * for character breaks in the specified + * {@link java.util.Locale}. + * + * @param locale the desired locale. + * @return the localized instance for character breaks. + * @throws NullPointerException if the locale is null. + * @throws IllegalArgumentException if the locale is not one + * returned by + * {@link getAvailableLocales()} + * @see java.text.BreakIterator#getCharacterInstance(java.util.Locale) + */ + public abstract BreakIterator getCharacterInstance(Locale locale); + + /** + * Returns a {@link java.text.BreakIterator} instance + * for line breaks in the specified {@link java.util.Locale}. + * + * @param locale the desired locale. + * @return the localized instance for line breaks. + * @throws NullPointerException if the locale is null. + * @throws IllegalArgumentException if the locale is not one + * returned by + * {@link getAvailableLocales()} + * @see java.text.BreakIterator#getLineInstance(java.util.Locale) + */ + public abstract BreakIterator getLineInstance(Locale locale); + + /** + * Returns a {@link java.text.BreakIterator} instance + * for sentence breaks in the specified + * {@link java.util.Locale}. + * + * @param locale the desired locale. + * @return the localized instance for sentence breaks. + * @throws NullPointerException if the locale is null. + * @throws IllegalArgumentException if the locale is not one + * returned by + * {@link getAvailableLocales()} + * @see java.text.BreakIterator#getSentenceInstance(java.util.Locale) + */ + public abstract BreakIterator getSentenceInstance(Locale locale); + + /** + * Returns a {@link java.text.BreakIterator} instance + * for word breaks in the specified + * {@link java.util.Locale}. + * + * @param locale the desired locale. + * @return the localized instance for word breaks. + * @throws NullPointerException if the locale is null. + * @throws IllegalArgumentException if the locale is not one + * returned by + * {@link getAvailableLocales()} + * @see java.text.BreakIterator#getWordInstance(java.util.Locale) + */ + public abstract BreakIterator getWordInstance(Locale locale); + +} Added: trunk/core/src/classpath/java/java/text/spi/CollatorProvider.java =================================================================== --- trunk/core/src/classpath/java/java/text/spi/CollatorProvider.java (rev 0) +++ trunk/core/src/classpath/java/java/text/spi/CollatorProvider.java 2007-01-07 05:43:15 UTC (rev 2996) @@ -0,0 +1,79 @@ +/* CollatorProvider.java -- Providers of localized instances + Copyright (C) 2007 Free Software Foundation, Inc. + +This file is part of GNU Classpath. + +GNU Classpath is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2, or (at your option) +any later version. + +GNU Classpath is distributed in the hope that it will be useful, but +WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +General Public License for more details. + +You should have received a copy of the GNU General Public License +along with GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA +02110-1301 USA. + +Linking this library statically or dynamically with other modules is +making a combined work based on this library. Thus, the terms and +conditions of the GNU General Public License cover the whole +combination. + +As a special exception, the copyright holders of this library give you +permission to link this library with independent modules to produce an +executable, regardless of the license terms of these independent +modules, and to copy and distribute the resulting executable under +terms of your choice, provided that you also meet, for each linked +independent module, the terms and conditions of the license of that +module. An independent module is a module which is not derived from +or based on this library. If you modify this library, you may extend +this exception to your version of the library, but you are not +obligated to do so. If you do not wish to do so, delete this +exception statement from your version. */ + +package java.text.spi; + +import java.text.Collator; + +import java.util.Locale; + +import java.util.spi.LocaleServiceProvider; + +/** + * A {@link CollatorProvider} provides localized + * instances of {@link java.text.Collator}. + * + * @author Andrew John Hughes (gnu...@me...) + * @since 1.6 + */ +public abstract class CollatorProvider + extends LocaleServiceProvider +{ + + /** + * Constructs a new {@link CollatorProvider}. + * Provided for implicit invocation by subclasses. + */ + protected CollatorProvider() + { + } + + /** + * Returns a {@link java.text.Collator} instance + * for the specified {@link java.util.Locale}. + * + * @param locale the desired locale. + * @return the localized instance. + * @throws NullPointerException if the locale is null. + * @throws IllegalArgumentException if the locale is not one + * returned by + * {@link getAvailableLocales()} + * @see java.text.Collator#getInstance(java.util.Locale) + */ + public abstract Collator getInstance(Locale locale); + +} Added: trunk/core/src/classpath/java/java/text/spi/DateFormatSymbolsProvider.java =================================================================== --- trunk/core/src/classpath/java/java/text/spi/DateFormatSymbolsProvider.java (rev 0) +++ trunk/core/src/classpath/java/java/text/spi/DateFormatSymbolsProvider.java 2007-01-07 05:43:15 UTC (rev 2996) @@ -0,0 +1,79 @@ +/* DateFormatSymbolsProvider.java -- Providers of localized instances + Copyright (C) 2007 Free Software Foundation, Inc. + +This file is part of GNU Classpath. + +GNU Classpath is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2, or (at your option) +any later version. + +GNU Classpath is distributed in the hope that it will be useful, but +WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +General Public License for more details. + +You should have received a copy of the GNU General Public License +along with GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA +02110-1301 USA. + +Linking this library statically or dynamically with other modules is +making a combined work based on this library. Thus, the terms and +conditions of the GNU General Public License cover the whole +combination. + +As a special exception, the copyright holders of this library give you +permission to link this library with independent modules to produce an +executable, regardless of the license terms of these independent +modules, and to copy and distribute the resulting executable under +terms of your choice, provided that you also meet, for each linked +independent module, the terms and conditions of the license of that +module. An independent module is a module which is not derived from +or based on this library. If you modify this library, you may extend +this exception to your version of the library, but you are not +obligated to do so. If you do not wish to do so, delete this +exception statement from your version. */ + +package java.text.spi; + +import java.text.DateFormatSymbols; + +import java.util.Locale; + +import java.util.spi.LocaleServiceProvider; + +/** + * A {@link DateFormatSymbolsProvider} provides localized + * instances of {@link java.text.DateFormatSymbols}. + * + * @author Andrew John Hughes (gnu...@me...) + * @since 1.6 + */ +public abstract class DateFormatSymbolsProvider + extends LocaleServiceProvider +{ + + /** + * Constructs a new {@link DateFormatSymbolsProvider}. + * Provided for implicit invocation by subclasses. + */ + protected DateFormatSymbolsProvider() + { + } + + /** + * Returns a {@link java.text.DateFormatSymbols} instance + * for the specified {@link java.util.Locale}. + * + * @param locale the locale to express the symbols in. + * @return the localized instance. + * @throws NullPointerException if the locale is null. + * @throws IllegalArgumentException if the locale is not one + * returned by + * {@link getAvailableLocales()} + * @see java.text.DateFormatSymbols#getInstance(java.util.Locale) + */ + public abstract DateFormatSymbols getInstance(Locale locale); + +} Added: trunk/core/src/classpath/java/java/text/spi/package.html =================================================================== --- trunk/core/src/classpath/java/java/text/spi/package.html (rev 0) +++ trunk/core/src/classpath/java/java/text/spi/package.html 2007-01-07 05:43:15 UTC (rev 2996) @@ -0,0 +1,50 @@ +<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN"> +<!-- package.html - describes classes in java.text.spi package. + Copyright (C) 2007 Free Software Foundation, Inc. + +This file is part of GNU Classpath. + +GNU Classpath is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2, or (at your option) +any later version. + +GNU Classpath is distributed in the hope that it will be useful, but +WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +General Public License for more details. + +You should have received a copy of the GNU General Public License +along with GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA +02110-1301 USA. + +Linking this library statically or dynamically with other modules is +making a combined work based on this library. Thus, the terms and +conditions of the GNU General Public License cover the whole +combination. + +As a special exception, the copyright holders of this library give you +permission to link this library with independent modules to produce an +executable, regardless of the license terms of these independent +modules, and to copy and distribute the resulting executable under +terms of your choice, provided that you also meet, for each linked +independent module, the terms and conditions of the license of that +module. An independent module is a module which is not derived from +or based on this library. If you modify this library, you may extend +this exception to your version of the library, but you are not +obligated to do so. If you do not wish to do so, delete this +exception statement from your version. --> + +<html> +<head><title>GNU Classpath - java.text.spi</title></head> + +<body> + +<p> +A series of service provider interfaces for use by the +classes in <code>java.text</code>. +</p> +<p><span style="font-weight: bold;">Since</span>: 1.6</p> +</body> +</html> This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <ls...@us...> - 2007-01-07 05:42:07
|
Revision: 2995 http://jnode.svn.sourceforge.net/jnode/?rev=2995&view=rev Author: lsantha Date: 2007-01-06 21:42:06 -0800 (Sat, 06 Jan 2007) Log Message: ----------- Classpath patches. Modified Paths: -------------- trunk/core/descriptors/org.classpath.ext.core.xml Modified: trunk/core/descriptors/org.classpath.ext.core.xml =================================================================== --- trunk/core/descriptors/org.classpath.ext.core.xml 2007-01-07 05:41:44 UTC (rev 2994) +++ trunk/core/descriptors/org.classpath.ext.core.xml 2007-01-07 05:42:06 UTC (rev 2995) @@ -61,6 +61,9 @@ <export name="java.rmi.dgc.*"/> <export name="java.rmi.registry.*"/> <export name="java.rmi.server.*"/> + <export name="java.util.concurrent.*"/> + <export name="java.util.concurrent.atomic.*"/> + <export name="java.util.concurrent.locks.*"/> <export name="javax.accessibility.*"/> <export name="javax.management.*"/> @@ -72,6 +75,11 @@ <export name="javax.sound.sampled.*"/> <export name="javax.sound.sampled.spi.*"/> + + <export name="sun.misc.*"/> + <export name="sun.reflect.*"/> + <export name="sun.reflect.annotation.*"/> + <export name="sun.reflect.misc.*"/> </library> </runtime> This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |