diff options
author | Mark Wielaard <mark@klomp.org> | 2006-01-13 13:17:12 +0000 |
---|---|---|
committer | Mark Wielaard <mark@klomp.org> | 2006-01-13 13:17:12 +0000 |
commit | f1d78899f535230bad6d05ba8ef4761495b1349e (patch) | |
tree | 9a5c024926fb0b86c359b63c6de28292a6f3d3fa | |
parent | e2880df85352a4f46c1fc8b28c4cd08540a2daed (diff) | |
download | classpath-f1d78899f535230bad6d05ba8ef4761495b1349e.tar.gz |
* Update to classpath-0_20-release minus:
- java/beans/EventSetDescriptor.java
- java/util/Hashtable.java
82 files changed, 2485 insertions, 1589 deletions
@@ -1,3 +1,493 @@ +2005-01-13 Mark Wielaard <mark@klomp.org> + + * configure.ac: Set version to 0.20. + * NEWS: Add entries for all the new work done. + +2005-01-13 Mark Wielaard <mark@klomp.org> + + * javax/swing/text/DefaultCaret.java: Chain all AssertionErrors. + +2005-01-13 Mark Wielaard <mark@klomp.org> + + * java/util/regex/Pattern.java (Pattern): Chain REException. + +2006-01-13 Chris Burdess <dog@gnu.org> + + * gnu/xml/xpath/NameTest.java: Removed debugging output. + +2005-01-13 Jeroen Frijters <jeroen@frijters.net> + + * java/security/Security.java + (getProperty): Added hack to skip security check when trusted + code is direct caller. + +2005-01-13 Jeroen Frijters <jeroen@frijters.net> + + * java/io/PrintStream.java + (line_separator, PrintStream(OutputStream,boolean)): Use + SystemProperties. + +2005-01-13 Jeroen Frijters <jeroen@frijters.net> + + * gnu/java/nio/charset/Provider.java: Added comment about its + special relation with CharsetProvider. + (static): Removed. + * gnu/java/nio/charset/iconv/IconvProvider.java: Added comment about + its special relation with CharsetProvider. + (static): Removed. + * java/nio/charset/spi/CharsetProvider.java + (CharsetProvider): Add special case to skip security check for + built in providers. + +2005-01-13 Mark Wielaard <mark@klomp.org> + + * javax/swing/JMenuItem.java (JMenuItem(Action)): Check whether + name, accel, mnemonic and command are defined before setting. + +2005-01-12 Mark Wielaard <mark@klomp.org> + + * javax/swing/plaf/metal/MetalFileChooserUI.java + (FileRenderer.getListCellRendererComponent): Set empty name and null + icon when File is null. + +2006-01-13 Audrius Meskauskas <AudriusA@Bioinformatics.org> + + * gnu/java/rmi/server/UnicastRef.java (newCall): + Throw ConnectException after catching IOException. + +2006-01-12 Lillian Angel <langel@redhat.com> + + * javax/swing/text/DefaultStyledDocument.java + (insertUpdate): Removed unneeded check. + +2006-01-12 Anthony Balkissoon <abalkiss@redhat.com> + + * javax/swing/text/DefaultStyledDocument.java: + (ElementBuffer.insertContentTag): If the direction is JoinNextDirection + and we haven't come immediately after a fracture, adjust the Element + offsets. Added comment explaining the situation. + (insert): Return early if no ElementSpecs passed in. Removed redundant + call to insertUpdate. Fired the UndoableEditUpdate. + +2006-01-12 Ito Kazumitsu <kaz@maczuka.gcd.org> + + Fixes bug #22802 + * gnu/regexp/RE.java(initialize): Fixed the parsing of + character classes within a subexpression. + +2006-12-12 Lillian Angel <langel@redhat.com> + + * javax/swing/text/DefaultStyledDocument.java + (insertUpdate): Added check to check if attribute set is + empty. + (insertUpdate): Added check to determine if last character + is a newline. If it is, we should not be fracturing. + (insert): Added check to determine if attribute set is empty. + If it is, insertUpdate should not be called. + +2006-12-12 Guilhem Lavaux <guilhem@kaffe.org> + + * configure.ac: Check for isnan. + + * native/fdlibm/fdlibm.h: If we have a isnan function then do not + define the macro. + +2006-01-12 Chris Burdess <dog@gnu.org> + + * gnu/xml/stream/XMLParser.java: Corrected the handling of some XML + 1.1 character ranges. + +2006-01-12 Anthony Balkissoon <abalkiss@redhat.com> + + * javax/swing/TransferHandler.java: + (TransferAction<init>): Call super constructor. Fixes Mauve regression + gnu/testlet/javax/swing/JTextField/CopyPaste. + +2006-01-12 Christian Thalinger <twisti@complang.tuwien.ac.at> + + * resource/Makefile.am: Install + logging.properties into $(prefix)/lib. + * resource/Makefile.am (securitydir): Changed to + $(prefix)/lib/security. + +2006-01-12 Roman Kennke <kennke@aicas.com> + + * javax/swing/JTextField.java + (createDefaultModel): Moved installation of the filterNewlines + property to setDocument(). + (setDocument): New method. Installs the filterNewlines property + on the document. + +2006-01-12 Chris Burdess <dog@gnu.org> + + * gnu/xml/dom/DomNode.java, + gnu/xml/transform/ElementAvailableFunction.java: Removed debugging + output. + * gnu/xml/xpath/NameTest.java, + gnu/xml/xpath/NamespaceTest.java, + gnu/xml/xpath/Selector.java: Fix regression for namespace axis + navigation. + * gnu/xml/transform/MessageNode.java: Use standard logging system + for outputting messages. + +2006-01-12 Tom Tromey <tromey@redhat.com> + + * java/net/InetAddress.java (DEFAULT_CACHE_SIZE): Removed. + (DEFAULT_CACHE_PERIOD, DEFAULT_CACHE_PURGE_PCT): Likewise. + (cache_size, cache_period, cache_purge_pct, cache): Likewise. + (static initializer): Removed cache code. + (checkCacheFor, addToCache): Removed. + (getAllByName): Removed cache code. + (lookup_time): Removed. + (InetAddress): Updated. + +2006-01-12 Chris Burdess <dog@gnu.org> + + * gnu/xml/dom/DomDocument.java, + gnu/xml/dom/DomElement.java, + gnu/xml/dom/DomNode.java, + gnu/xml/stream/XMLParser.java, + gnu/xml/transform/Bindings.java, + gnu/xml/transform/ElementAvailableFunction.java, + gnu/xml/transform/ElementNode.java, + gnu/xml/transform/FunctionAvailableFunction.java, + gnu/xml/transform/NamespaceProxy.java, + gnu/xml/transform/StreamSerializer.java, + gnu/xml/transform/Stylesheet.java, + gnu/xml/transform/TransformerImpl.java, + gnu/xml/xpath/Selector.java: Implement isEqualNode correctly for + document and element nodes; correct coalescing semantics when parsing; + attribute-sets can only refer to top-level variables and parameters; + fix namespace retrieval during element-available and + function-available functions; implement xsl:fallback for extension + elements; tokenize whitespace correctly during whitespace stripping; + correct following and previous node axes selectors. + +2006-01-12 Roman Kennke <kennke@aicas.com> + + * java/util/Hashtable.java + (KeyEnumerator.nextElement): Added null check to avoid NPE. + (ValueEnumerator.nextElement): Added null check to avoid NPE. + +2006-01-12 Lillian Angel <langel@redhat.com> + + * javax/swing/text/GapContent.java + (UndoInsertString): Changed name of class to InsertUndo to match the JDK. + +2006-01-12 Mark Wielaard <mark@klomp.org> + + * vm/reference/gnu/java/net/VMPlainSocketImpl.java (connect): + Throw UnknowHostException when name could not be resolved. + +2006-01-12 Jeroen Frijters <jeroen@frijters.net> + + * java/net/URL.java + (static, getURLStreamHandler): Use SystemProperties. + +2006-01-12 Mark Wielaard <mark@klomp.org> + + * vm/reference/gnu/java/net/VMPlainDatagramSocketImpl.java (receive): + Use packet.getLength(). + * native/jni/java-net/gnu_java_net_VMPlainDatagramSocketImpl.c + (nativeReceive): Check whether the receiver wants zero bytes. + +2006-01-12 Mark Wielaard <mark@klomp.org> + + * native/jni/java-net/javanet.c (_javanet_recvfrom): Return -1 when + other side orderly closed connection. + * vm/reference/gnu/java/net/VMPlainSocketImpl.java + (read(PlainSocketImpl)): Mask byte to return unsigned int. Return -1 + when end of stream reached. + +2006-01-12 Mark Wielaard <mark@klomp.org> + + * native/jni/java-net/gnu_java_net_VMPlainDatagramSocketImpl.c: + Remove asserts. + * native/jni/java-net/gnu_java_net_VMPlainSocketImpl.c: Likewise. + * native/jni/java-net/java_net_VMInetAddress.c: Likewise. + * native/jni/java-net/java_net_VMNetworkInterface.c: Likewise. + * native/jni/java-net/javanet.c: Likewise. + +2006-01-12 Mark Wielaard <mark@klomp.org> + + * native/fdlibm/mprec.c (Balloc): Disable assert to workaround + PR classpath/23863. + +2006-01-11 Chris Burdess <dog@gnu.org> + + * gnu/xml/transform/AttributeNode.java, + gnu/xml/transform/ElementNode.java, + gnu/xml/transform/LiteralNode.java, + gnu/xml/transform/StreamSerializer.java, + gnu/xml/transform/StrippingInstruction.java, + gnu/xml/transform/Stylesheet.java, + gnu/xml/transform/TransformerImpl.java, + gnu/xml/transform/ValueOfNode.java, + gnu/xml/xpath/Expr.java, + gnu/xml/xpath/LocalNameFunction.java, + gnu/xml/xpath/NameFunction.java, + gnu/xml/xpath/NameTest.java, + gnu/xml/xpath/NamespaceUriFunction.java, + gnu/xml/xpath/NodeTypeTest.java, + gnu/xml/xpath/SubstringFunction.java, + javax/xml/namespace/QName.java: don't determine element namespace + from namespace aliases when specified; better namespace handling + when serializing elements; don't create HTML meta element unless + head element exists; correct encoding of CDATA sections containing + ']]>'; encode HTML character entity references; use ISO-Latin-1 as + default encoding for HTML output; rewrite of XSLT + strip-space/preserve-space handling; correct doctype-public and + doctype-system output attributes; insert generated doctype before + document element; fixed result tree whitespace stripping + algorithm; fixed semantics of XPath name, local-name, and + namespace-uri functions; name tests handle XML/XMLNS namespaces + correctly; fixed semantics of processing-instruction node test. + * gnu/xml/transform/TransformerFactoryImpl.java: Add main method to + aid debugging. + +2006-01-11 Lillian Angel <langel@redhat.com> + + * javax/swing/text/DefaultStyledDocument.java + (insertFracture): Added calls to addEdit for each time a structure + is changed. addEdit is called on the newBranch, previous, and parent + structures. + +2006-01-11 Anthony Balkissoon <abalkiss@redhat.com> + + * javax/swing/text/DefaultStyledDocument.java: + (ElementBuffer.insertContentTag): Don't adjust the structure here. + This will have been taken care of in insertFracture. Added a comment + explaining that we need to add edits to the DocumentEvent and that + this may be the place to do it. + +2006-01-11 Anthony Balkissoon <abalkiss@redhat.com> + + * javax/swing/text/DefaultStyledDocument.java: + (ElementBuffer.insertUpdate): Properly recreate Elements if the first + tag is an end tag. Avoid NPE by pushing the proper Element on to the + elementStack when there is a start tag with JoinNextDirection. + +2006-01-11 Roman Kennke <kennke@aicas.com> + + Reported by: Fridjof Siebert <siebert@aicas.com> + * java/util/Hashtable.java + (KEYS): Removed unneeded field. + (VALUES): Removed unneeded field. + (ENTRIES): Removed unneeded field. + (keys): Return a KeyEnumerator instance. + (elements): Returns a ValueEnumerator instance. + (toString): Use an EntryIterator instance. + (keySet): Return a KeyIterator instance. + (values): Return a ValueIterator instance. + (entrySet): Return an EntryIterator instance. + (hashCode): Use EntryIterator instance. + (rehash): Changed this loop to avoid redundant reads and make + it obvious that null checking is not needed. + (writeObject): Use EntryIterator instance. + (HashIterator): Removed class. + (Enumerator): Removed class. + (EntryIterator): New class. + (KeyIterator): New class. + (ValueIterator): New class. + (EntryEnumerator): New class. + (KeyEnumerator): New class. + (ValueEnumerator): New class. + +2006-01-11 Lillian Angel <langel@redhat.com> + + * javax/swing/text/DefaultStyledDocument.java + (toString): Shouldn't append the '>' character here. + (createDefaultRoot): Should not set the resolve parent. This + causes problems when comparing attribute sets. + +2006-01-10 Anthony Balkissoon <abalkiss@redhat.com> + + * javax/swing/text/DefaultStyledDocument.java: + (ElementBuffer.insertUpdate): Rewritten to properly handle start and + end tags. + (ElementBuffer.insertFracture): New method. + (ElementBuffer.insertContentTag): Removed unnecessary case for + JoinFractureDirection - this only applies to start tags, not content + tags. + (insertUpdate): Corrected conditions for setting direction to + JoinNextDirection. + +2006-01-10 Roman Kennke <kennke@aicas.com> + + * Makefile.am (EXTRA_DIST): Added ChangeLog-2004. + * ChangeLog-2005: New File. + +2006-01-10 Roman Kennke <kennke@aicas.com> + + * native/jni/java-nio/java_nio_VMDirectByteBuffer.c + (get): Release the array with the correct pointer. + (put): Release the array with the correct pointer. Copy the array + around _before_ releasing it. + +2006-01-10 Roman Kennke <kennke@aicas.com> + + * javax/swing/ViewportLayout.java + (layoutContainer): Fixed condition, to avoid ClasscastException. + +2006-01-10 Roman Kennke <kennke@aicas.com> + + * javax/swing/plaf/basic/BasicSplitPaneDivider.java + (MouseHandler.mousePressed): Fixed indendation. + (MouseHandler.mouseDragged): Fixed indendation. + +2006-01-10 Roman Kennke <kennke@aicas.com> + + * javax/swing/plaf/basic/BasicLookAndFeel.java + (playSound): Added @since 1.4 to the API docs. + +2006-01-10 Roman Kennke <kennke@aicas.com> + + * javax/swing/plaf/basic/BasicListUI.java + (maybeUpdateLayoutState): Also update the layout state, if the + list has been invalidated since the last update. + +2006-01-10 Roman Kennke <kennke@aicas.com> + + * javax/swing/plaf/ComponentUI.java + (update): Fixed indendation. + +2006-01-10 Roman Kennke <kennke@aicas.com> + + * javax/swing/ViewportLayout.java + (layoutContainer): Fixed condition, so that Scrollable components + are always forced to have to Viewport size, when they + return true for getScrollableTracksViewportHeight() and ..Width(). + +2006-01-10 Roman Kennke <kennke@aicas.com> + + * javax/swing/RepaintManager.java + (validateInvalidComponents): Fixed condition to avoid NPE. + +2006-01-10 Roman Kennke <kennke@aicas.com> + + * javax/swing/JViewport.java: + (static_initializer): Removed unused variable myScrollMode. + +2006-01-10 Roman Kennke <kennke@aicas.com> + + * javax/swing/JTabbedPane.java: + Cleared API docs a little. + +2006-01-10 Roman Kennke <kennke@aicas.com> + + * java/util/StringTokenizer.java + (StringTokenizer(String, String, boolean)): + Don't trigger NPE here for conformance with the spec. + +2006-01-10 Roman Kennke <kennke@aicas.com> + + * java/util/ArrayList.java + (DEFAULT_CAPACITY): Changed default capacity to 10, as specified. + +2006-01-10 Roman Kennke <kennke@aicas.com> + + * gnu/java/awt/peer/gtk/GdkGraphics2D.java + (GdkGraphics2D(GdkGraphics2D)): Added null check for the bg + field to avoid NPE. + +2006-01-10 Roman Kennke <kennke@aicas.com> + + * native/jni/java-net/javanet.c + (_javanet_shutdownOutput): Replaced strerror() with + TARGET_NATIVE_LAST_ERROR_STRING() for portability. + (_javanet_shutdownInput): Replaced strerror() with + TARGET_NATIVE_LAST_ERROR_STRING() for portability. + +2006-01-10 Robert Schuster <robertschuster@fsfe.org> + + * java/beans/EventSetDescriptor.java: Reformatted and + fixed API docs. + +2006-01-10 Roman Kennke <kennke@aicas.com> + + * java/lang/SecurityManager.java + Fully qualified AWT class references in API docs. + +2006-01-10 Robert Schuster <robertschuster@fsfe.org> + + * java/beans/EventSetDescriptor.java: + (getGetListenerMethod): New method. + +2006-01-10 Mark Wielaard <mark@klomp.org> + + * lib/Makefile.am (GCJX): Add -g to get linenumber info. + +2006-01-10 Jeroen Frijters <jeroen@frijters.net> + + PR classpath/25727 + * java/util/Hashtable.java + (contains): Call equals on existing value. + (containsKey, get, put, remove): Call equals on existing key. + (getEntry): Call equals on existing entry. + +2006-01-10 Jeroen Frijters <jeroen@frijters.net> + + PR classpath/24618 + * java/util/AbstractMap.java + (equals(Object,Object)): Test for identity first. + * java/util/WeakHashMap.java + (WeakBucket.WeakEntry.equals): Use helper method to determine equality. + (WeakBucket.WeakEntry.toString): Fixed string representation of + null key. + (internalGet): Use helper method to determine equality. + +2006-01-09 Robert Schuster <robertschuster@fsfe.org> + + * java/beans/EventSetDescriptor.java: Implemented the two 1.4 + constructors. + +2006-01-09 Anthony Balkissoon <abalkiss@redhat.com> + + * javax/swing/text/PlainDocument.java: + (insertUpdate): Handle special case of an insertion immediately + following a newline character. + +2006-01-09 Roman Kennke <kennke@aicas.com> + + * native/jni/java-net/gnu_java_net_VMPlainSocketImpl.c + (connect): Added stream parameter to _connect() call. + * native/jni/java-net/gnu_java_net_VMPlainDatagramSocketImpl.c + (connect): Added stream parameter to _connect() call. + * native/jni/java-net/javanet.c + (_javanet_create_localfd): Added stream parameter. Look up + fd field based on the stream parameter either in SocketImpl or + in DatagramSocketImpl. + (_javanet_connect): Added stream parameter. Call create_localfd + using this stream parameter. Set localPort field either in + SocketImpl or in DatagramSocketImpl, depending on the stream + flag. + * native/jni/java-net/javanet.c + (_javanet_connect): Added stream parameter. + +2006-01-09 Audrius Meskauskas <AudriusA@Bioinformatics.org> + + * javax.management.Attribute.java: Grammar and + formatting fixes. + +2006-01-09 Mark Wielaard <mark@klomp.org> + + * gnu/java/nio/channels/FileChannelImpl.java (map): Throw correct + exception when channel is not readable or writable. + * native/jni/java-nio/gnu_java_nio_channels_FileChannelImpl.c + (mapImpl): Add PROT_WRITE when mode == 'c' (MAP_PRIVATE). Make sure + there is enough space to mmap(). + +2006-01-09 Robert Schuster <robertschuster@fsfe.org> + + * java/beans/Introspector.java: + (getBeanInfo(Class, int)): New method. + (getBeanInfo(Class, Class): Moved common code in a new method. + (merge): New method. + +2006-01-09 Robert Schuster <robertschuster@fsfe.org> + + * java/beans/XMLEncoder.java: Fix spelling mistakes. + 2006-01-09 Anthony Balkissoon <abalkiss@redhat.com> * javax/swing/text/DefaultStyledDocument.java: @@ -37,6 +527,12 @@ 2006-01-09 Roman Kennke <kennke@aicas.com> + * java/net/DatagramSocketImpl.java + (localPort): Renamed to localport for correct access from native + code. + +2006-01-09 Roman Kennke <kennke@aicas.com> + * javax/swing/Popup.java (LightweightPopup.hide): Repaint the layered pane when popup is removed. diff --git a/Makefile.am b/Makefile.am index f17b9c718..4a09172e1 100644 --- a/Makefile.am +++ b/Makefile.am @@ -9,7 +9,7 @@ ACLOCAL_AMFLAGS = -I m4 native: lib EXTRA_DIST = HACKING BUGS THANKYOU mauve-classpath LICENSE \ - ChangeLog-2003 ChangeLog-2004 \ + ChangeLog-2003 ChangeLog-2004 ChangeLog-2005 \ ChangeLog.gnujaxp.1 ChangeLog.gnujaxp.2 ChangeLog.libxmlj \ autogen.sh @@ -1,10 +1,47 @@ -New in release 0.20 +New in release 0.20 (Jan 13, 2006) + +* New StAX pull parser and SAX-over-StAX driver. Lots of DOM, SAX/StAX, + XPath and XSLT improvements. Support for XInclude and XML Base added. + Conformance is now regularly tested against various test-suites at + http://builder.classpath.org/xml/ See also doc/README.jaxp. + +* Full beans XMLEncoder implementation. + +* javax.sound.sampled implementation. + +* javax.print.attribute and javax.print.event implementated. + +* Lots of new datatransfer, print swing and swing.text work and optimization. + +* Additional 1.5 support. Including new (separate) generic branch release. + +* SecurityManager cleanups and start of review of all Permission checks + (includes adding lots of new checks to the Mauve test-suite). + +* Buildable on cygwin. + +* Fully buildable as "in-workspace" library-plus-vm inside (native) Eclipse + see http://developer.classpath.org/mediation/ClasspathHackingWithEclipse + +* Full example that shows a real world CORBA and Free Swing implementation. + See examples/gnu/classpath/examples/CORBA/swing/README.html + +* A list of bug fixes can be found at: +http://gcc.gnu.org/bugzilla/buglist.cgi?product=classpath&target_milestone=0.20 Runtime interface changes: * New method VMStackWalker.getClassLoader() was added to avoid an infinite loop between getCallingClassLoader() and Class.getClassLoader(). +* The included fdlibm implementation has seen several cleanups to handle + new architectures and namespacing issues (in particular for ppc, darwin + and non-C99 compilers). Please double check any arithmetic test against + new platforms/runtimes. + +* The gnu.java.net.Plain[Datagram]Socket implementations have been + turned into VM reference classes with JNI/Posix implementations. + New in release 0.19 (Nov 2, 2005) * The Swing RepaintManager has been reworked for more efficient painting, diff --git a/configure.ac b/configure.ac index 853d2c47a..42f608f01 100644 --- a/configure.ac +++ b/configure.ac @@ -6,7 +6,7 @@ dnl ----------------------------------------------------------- dnl define([AC_CACHE_LOAD], )dnl dnl define([AC_CACHE_SAVE], )dnl -AC_INIT([GNU Classpath],[0.20-generics-pre],[classpath@gnu.org],[classpath]) +AC_INIT([GNU Classpath],[0.20-generics],[classpath@gnu.org],[classpath]) AC_CONFIG_SRCDIR(java/lang/System.java) AC_CANONICAL_TARGET @@ -270,7 +270,8 @@ if test "x${COMPILE_JNI}" = xyes; then localtime_r \ strerror_r \ fcntl \ - mmap munmap mincore msync madvise getpagesize sysconf]) + mmap munmap mincore msync madvise getpagesize sysconf \ + isnan]) AC_HEADER_TIME AC_STRUCT_TM diff --git a/gnu/java/awt/peer/gtk/GdkGraphics2D.java b/gnu/java/awt/peer/gtk/GdkGraphics2D.java index d07820a97..195304dce 100644 --- a/gnu/java/awt/peer/gtk/GdkGraphics2D.java +++ b/gnu/java/awt/peer/gtk/GdkGraphics2D.java @@ -180,11 +180,14 @@ public class GdkGraphics2D extends Graphics2D else fg = new Color(g.fg.getRGB()); - if (g.bg.getAlpha() != -1) - bg = new Color(g.bg.getRed(), g.bg.getGreen(), g.bg.getBlue(), - g.bg.getAlpha()); - else - bg = new Color(g.bg.getRGB()); + if (g.bg != null) + { + if (g.bg.getAlpha() != -1) + bg = new Color(g.bg.getRed(), g.bg.getGreen(), g.bg.getBlue(), + g.bg.getAlpha()); + else + bg = new Color(g.bg.getRGB()); + } if (g.clip == null) clip = null; diff --git a/gnu/java/nio/channels/FileChannelImpl.java b/gnu/java/nio/channels/FileChannelImpl.java index 466f3dd55..a557c7d3b 100644 --- a/gnu/java/nio/channels/FileChannelImpl.java +++ b/gnu/java/nio/channels/FileChannelImpl.java @@ -1,5 +1,5 @@ /* FileChannelImpl.java -- - Copyright (C) 2002, 2004, 2005 Free Software Foundation, Inc. + Copyright (C) 2002, 2004, 2005, 2006 Free Software Foundation, Inc. This file is part of GNU Classpath. @@ -301,8 +301,10 @@ public final class FileChannelImpl extends FileChannel else if (mode == MapMode.READ_WRITE || mode == MapMode.PRIVATE) { nmode = mode == MapMode.READ_WRITE ? '+' : 'c'; - if ((this.mode & (READ|WRITE)) != (READ|WRITE)) + if ((this.mode & WRITE) != WRITE) throw new NonWritableChannelException(); + if ((this.mode & READ) != READ) + throw new NonReadableChannelException(); } else throw new IllegalArgumentException ("mode: " + mode); diff --git a/gnu/java/nio/charset/Provider.java b/gnu/java/nio/charset/Provider.java index c7f7ed278..01c2650a8 100644 --- a/gnu/java/nio/charset/Provider.java +++ b/gnu/java/nio/charset/Provider.java @@ -1,5 +1,5 @@ /* Provider.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. @@ -49,6 +49,11 @@ import java.util.Iterator; * Charset provider for the required charsets. Used by * {@link Charset#charsetForName} and * {@link Charset#availableCharsets}. * + * Note: This class is a privileged class, because it can be instantiated without + * requiring the RuntimePermission("charsetProvider"). There is a check in + * java.nio.charset.spi.CharsetProvider to skip the security check if the provider + * is an instance of this class. + * * @author Jesse Rosenstock * @author Robert Schuster (thebohemian@gmx.net) * @see Charset @@ -57,14 +62,6 @@ public final class Provider extends CharsetProvider { private static Provider singleton; - static - { - synchronized (Provider.class) - { - singleton = null; - } - } - /** * Map from charset name to charset canonical name. The strings * are all lower-case to allow case-insensitive retrieval of diff --git a/gnu/java/nio/charset/iconv/IconvProvider.java b/gnu/java/nio/charset/iconv/IconvProvider.java index 873e9ecda..6fd8b7440 100644 --- a/gnu/java/nio/charset/iconv/IconvProvider.java +++ b/gnu/java/nio/charset/iconv/IconvProvider.java @@ -1,5 +1,5 @@ /* IconvProvider.java -- - Copyright (C) 2005 Free Software Foundation, Inc. + Copyright (C) 2005, 2006 Free Software Foundation, Inc. This file is part of GNU Classpath. @@ -48,20 +48,17 @@ import java.util.Vector; /** * Charset provider wrapping iconv. * + * Note: This class is a privileged class, because it can be instantiated without + * requiring the RuntimePermission("charsetProvider"). There is a check in + * java.nio.charset.spi.CharsetProvider to skip the security check if the provider + * is an instance of this class. + * * @author Sven de Marothy */ public final class IconvProvider extends CharsetProvider { private static IconvProvider singleton; - static - { - synchronized (IconvProvider.class) - { - singleton = null; - } - } - // Declaring the construtor public may violate the use of singleton. // But it must be public so that an instance of this class can be // created by Class.newInstance(), which is the case when this provider is diff --git a/gnu/java/rmi/server/UnicastRef.java b/gnu/java/rmi/server/UnicastRef.java index c1b871fb8..8097a0466 100644 --- a/gnu/java/rmi/server/UnicastRef.java +++ b/gnu/java/rmi/server/UnicastRef.java @@ -47,6 +47,7 @@ import java.io.ObjectOutput; import java.io.ObjectOutputStream; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; +import java.rmi.ConnectException; import java.rmi.Remote; import java.rmi.RemoteException; import java.rmi.server.ObjID; @@ -195,7 +196,7 @@ public RemoteCall newCall(RemoteObject obj, Operation[] op, int opnum, long hash conn = manager.getConnection(); } catch (IOException e1) { - throw new RemoteException("connection failed to host: " + manager.serverName, e1); + throw new ConnectException("connection failed to host: " + manager.serverName, e1); } //obj: useless? diff --git a/gnu/regexp/RE.java b/gnu/regexp/RE.java index 9735ed15d..9ac9b53d1 100644 --- a/gnu/regexp/RE.java +++ b/gnu/regexp/RE.java @@ -376,7 +376,7 @@ public class RE extends REToken { // what is proper interpretation of '{' at start of string? // // This method used to check "repeat.empty.token" to avoid such regexp - // as "(a*){2.}", but now "repeat.empty.token" is allowed. + // as "(a*){2,}", but now "repeat.empty.token" is allowed. else if ((unit.ch == '{') && syntax.get(RESyntax.RE_INTERVALS) && (syntax.get(RESyntax.RE_NO_BK_BRACES) ^ (unit.bk || quot))) { int newIndex = getMinMax(pattern,index,minMax,syntax); @@ -551,13 +551,50 @@ public class RE extends REToken { int nested = 0; while ( ((nextIndex = getCharUnit(pattern,endIndex,unit,false)) > 0) - && !(nested == 0 && (unit.ch == ')') && (syntax.get(RESyntax.RE_NO_BK_PARENS) ^ (unit.bk || quot))) ) + && !(nested == 0 && (unit.ch == ')') && (syntax.get(RESyntax.RE_NO_BK_PARENS) ^ (unit.bk || quot))) ) { if ((endIndex = nextIndex) >= pLength) throw new REException(getLocalizedMessage("subexpr.no.end"),REException.REG_ESUBREG,nextIndex); + else if ((unit.ch == '[') && !(unit.bk || quot)) { + // I hate to do something similar to the LIST OPERATOR matters + // above, but ... + int listIndex = nextIndex; + if (listIndex < pLength && pattern[listIndex] == '^') listIndex++; + if (listIndex < pLength && pattern[listIndex] == ']') listIndex++; + int listEndIndex = -1; + int listNest = 0; + while (listIndex < pLength && listEndIndex < 0) { + switch(pattern[listIndex++]) { + case '\\': + listIndex++; + break; + case '[': + // Sun's API document says that regexp like "[a-d[m-p]]" + // is legal. Even something like "[[[^]]]]" is accepted. + listNest++; + if (listIndex < pLength && pattern[listIndex] == '^') listIndex++; + if (listIndex < pLength && pattern[listIndex] == ']') listIndex++; + break; + case ']': + if (listNest == 0) + listEndIndex = listIndex; + listNest--; + break; + } + } + if (listEndIndex >= 0) { + nextIndex = listEndIndex; + if ((endIndex = nextIndex) >= pLength) + throw new REException(getLocalizedMessage("subexpr.no.end"),REException.REG_ESUBREG,nextIndex); + else + continue; + } + throw new REException(getLocalizedMessage("subexpr.no.end"),REException.REG_ESUBREG,nextIndex); + } else if (unit.ch == '(' && (syntax.get(RESyntax.RE_NO_BK_PARENS) ^ (unit.bk || quot))) nested++; else if (unit.ch == ')' && (syntax.get(RESyntax.RE_NO_BK_PARENS) ^ (unit.bk || quot))) nested--; + } // endIndex is now position at a ')','\)' // nextIndex is end of string or position after ')' or '\)' diff --git a/gnu/xml/dom/DomDocument.java b/gnu/xml/dom/DomDocument.java index 29b8dc72e..900d03ac3 100644 --- a/gnu/xml/dom/DomDocument.java +++ b/gnu/xml/dom/DomDocument.java @@ -1313,6 +1313,31 @@ public class DomDocument return config; } + public boolean isEqualNode(Node arg) + { + if (!super.isEqualNode(arg)) + return false; + Document d = (Document) arg; + String dversion = d.getXmlVersion(); + if (dversion == null || !dversion.equals(version)) + return false; + boolean dstandalone = d.getXmlStandalone(); + if (dstandalone != standalone) + return false; + String dencoding = d.getXmlEncoding(); + if (dencoding == null || dencoding.equalsIgnoreCase("UTF-8")) + { + if (encoding != null && !encoding.equalsIgnoreCase("UTF-8")) + return false; + } + else + { + if (!dencoding.equals(encoding)) + return false; + } + return true; + } + public void normalizeDocument() { boolean save = building; diff --git a/gnu/xml/dom/DomElement.java b/gnu/xml/dom/DomElement.java index 34509f647..f55b084cc 100644 --- a/gnu/xml/dom/DomElement.java +++ b/gnu/xml/dom/DomElement.java @@ -519,5 +519,38 @@ public class DomElement Attr attr = (Attr) attrs.getNamedItemNS(namespaceURI, localName); setIdAttributeNode(attr, isId); } + + public boolean isEqualNode(Node arg) + { + if (!super.isEqualNode(arg)) + return false; + getAttributes(); + NamedNodeMap argAttrs = arg.getAttributes(); + int len = argAttrs.getLength(); + if (argAttrs == null || (len != attributes.length)) + return false; + for (int i = 0; i < len; i++) + { + Node argCtx = argAttrs.item(i); + // Don't compare namespace nodes + if (XMLConstants.XMLNS_ATTRIBUTE_NS_URI + .equals(argCtx.getNamespaceURI())) + continue; + // Find corresponding attribute node + DomNode ctx = attributes.first; + for (; ctx != null; ctx = ctx.next) + { + if (XMLConstants.XMLNS_ATTRIBUTE_NS_URI + .equals(ctx.getNamespaceURI())) + continue; + if (!ctx.isEqualNode(argCtx)) + continue; + break; + } + if (ctx == null) + return false; // not found + } + return true; + } } diff --git a/gnu/xml/dom/DomNode.java b/gnu/xml/dom/DomNode.java index 5cd5be269..93f7c6f64 100644 --- a/gnu/xml/dom/DomNode.java +++ b/gnu/xml/dom/DomNode.java @@ -1749,7 +1749,10 @@ public abstract class DomNode switch (ctx.nodeType) { case TEXT_NODE: - while (ctx.next != null && ctx.next.nodeType == TEXT_NODE) + case CDATA_SECTION_NODE: + while (ctx.next != null && + (ctx.next.nodeType == TEXT_NODE || + ctx.next.nodeType == CDATA_SECTION_NODE)) { Text text = (Text) ctx; text.appendData(ctx.next.getNodeValue()); @@ -1989,39 +1992,56 @@ public abstract class DomNode public boolean isEqualNode(Node arg) { if (this == arg) - { - return true; - } + return true; if (arg == null) + return false; + if (nodeType != arg.getNodeType()) + return false; + switch (nodeType) { - return false; - } - if (nodeType != arg.getNodeType() || - !equal(getNodeName(), arg.getNodeName()) || - !equal(getLocalName(), arg.getLocalName()) || - !equal(getNamespaceURI(), arg.getNamespaceURI()) || - !equal(getPrefix(), arg.getPrefix()) || - !equal(getNodeValue(), arg.getNodeValue())) - { - return false; + case ELEMENT_NODE: + case ATTRIBUTE_NODE: + if (!equal(getLocalName(), arg.getLocalName()) || + !equal(getNamespaceURI(), arg.getNamespaceURI())) + return false; + break; + case PROCESSING_INSTRUCTION_NODE: + if (!equal(getNodeName(), arg.getNodeName()) || + !equal(getNodeValue(), arg.getNodeValue())) + return false; + break; + case COMMENT_NODE: + case TEXT_NODE: + case CDATA_SECTION_NODE: + if (!equal(getNodeValue(), arg.getNodeValue())) + return false; + break; } // Children Node argCtx = arg.getFirstChild(); getFirstChild(); // because of DomAttr lazy children - for (DomNode ctx = first; ctx != null; ctx = ctx.next) + DomNode ctx = first; + for (; ctx != null && argCtx != null; ctx = ctx.next) { - if (!ctx.isEqualNode(argCtx)) + if (nodeType == DOCUMENT_NODE) { - return false; + // Ignore whitespace outside document element + while (ctx != null && ctx.nodeType == TEXT_NODE) + ctx = ctx.next; + while (argCtx != null && ctx.getNodeType() == TEXT_NODE) + argCtx = argCtx.getNextSibling(); + if (ctx == null && argCtx != null) + return false; + else if (argCtx == null && ctx != null) + return false; } + if (!ctx.isEqualNode(argCtx)) + return false; argCtx = argCtx.getNextSibling(); } - if (argCtx != null) - { - return false; - } + if (ctx != null || argCtx != null) + return false; - // TODO Attr NamedNodeMap // TODO DocumentType return true; } @@ -2157,5 +2177,14 @@ public abstract class DomNode } } + public void list(java.io.PrintStream out, int indent) + { + for (int i = 0; i < indent; i++) + out.print(" "); + out.println(toString()); + for (DomNode ctx = first; ctx != null; ctx = ctx.next) + ctx.list(out, indent + 1); + } + } diff --git a/gnu/xml/stream/XMLParser.java b/gnu/xml/stream/XMLParser.java index f856f9372..6f10b9303 100644 --- a/gnu/xml/stream/XMLParser.java +++ b/gnu/xml/stream/XMLParser.java @@ -282,8 +282,8 @@ public class XMLParser private final boolean stringInterning; /** - * If true, adjacent text will always be reported as one event. - * Otherwise multiple text events (chunks) may be reported. + * If true, CDATA sections will be merged with adjacent text nodes into a + * single event. */ private final boolean coalescing; @@ -366,8 +366,8 @@ public class XMLParser * (necessary if there are external entities to be resolved) * @param validating if the parser is to be a validating parser * @param namespaceAware if the parser should support XML Namespaces - * @param coalescing if text should be reported as a single event instead - * of a series of events + * @param coalescing if CDATA sections should be merged into adjacent text + * nodes * @param replaceERefs if entity references should be automatically * replaced by their replacement text (otherwise they will be reported as * entity-reference events) @@ -423,8 +423,8 @@ public class XMLParser * (necessary if there are external entities to be resolved) * @param validating if the parser is to be a validating parser * @param namespaceAware if the parser should support XML Namespaces - * @param coalescing if text should be reported as a single event instead - * of a series of events + * @param coalescing if CDATA sections should be merged into adjacent text + * nodes * @param replaceERefs if entity references should be automatically * replaced by their replacement text (otherwise they will be reported as * entity-reference events) @@ -1357,7 +1357,7 @@ public class XMLParser throw new EOFException(); else if (input.xml11) { - if (!isXML11Char(c)) + if (!isXML11Char(c) || isXML11RestrictedChar(c)) error("illegal XML 1.1 character", "U+" + Integer.toHexString(c)); } @@ -3088,12 +3088,16 @@ public class XMLParser case 0x3c: // '<' reset(); read(tmpBuf, 0, i); - done = true; - break; // end of text sequence + i = len; + if (coalescing && tryRead(TEST_CDATA)) + readUntil(TEST_END_CDATA); // read CDATA section into buf + else + done = true; // end of text sequence + break; default: if (input.xml11) { - if (!isXML11Char(c)) + if (!isXML11Char(c) || isXML11RestrictedChar(c)) error("illegal XML 1.1 character", "U+" + Integer.toHexString(c)); } @@ -3106,7 +3110,7 @@ public class XMLParser } // if text buffer >= 2MB, return it as a chunk // to avoid excessive memory use - if (!coalescing && buf.length() >= 2097152) + if (buf.length() >= 2097152) done = true; } if (entities) diff --git a/gnu/xml/transform/AttributeNode.java b/gnu/xml/transform/AttributeNode.java index 1e0eb1e96..bc5bc30c9 100644 --- a/gnu/xml/transform/AttributeNode.java +++ b/gnu/xml/transform/AttributeNode.java @@ -1,5 +1,5 @@ /* AttributeNode.java -- - Copyright (C) 2004 Free Software Foundation, Inc. + Copyright (C) 2004,2006 Free Software Foundation, Inc. This file is part of GNU Classpath. @@ -75,13 +75,9 @@ final class AttributeNode namespace.clone(stylesheet), source); if (children != null) - { - ret.children = children.clone(stylesheet); - } + ret.children = children.clone(stylesheet); if (next != null) - { - ret.next = next.clone(stylesheet); - } + ret.next = next.clone(stylesheet); return ret; } @@ -113,9 +109,7 @@ final class AttributeNode // Use XPath string-value of fragment namespaceValue = Expr.stringValue(fragment); if (namespaceValue.length() == 0) - { - namespaceValue = null; - } + namespaceValue = null; } String prefix = getPrefix(nameValue); @@ -124,9 +118,7 @@ final class AttributeNode if (prefix != null) { if (XMLConstants.XML_NS_PREFIX.equals(prefix)) - { - namespaceValue = XMLConstants.XML_NS_URI; - } + namespaceValue = XMLConstants.XML_NS_URI; else { // Resolve namespace for this prefix @@ -153,9 +145,7 @@ final class AttributeNode // Resolve prefix for this namespace prefix = source.lookupPrefix(namespaceValue); if (prefix != null) - { - nameValue = prefix + ":" + nameValue; - } + nameValue = prefix + ":" + nameValue; else { if (namespaceValue != null) @@ -196,27 +186,19 @@ final class AttributeNode if (attrs != null) { if (namespace != null) - { - attrs.setNamedItemNS(attr); - } + attrs.setNamedItemNS(attr); else - { - attrs.setNamedItem(attr); - } + attrs.setNamedItem(attr); } if (children != null) - { - children.apply(stylesheet, mode, - context, pos, len, - attr, null); - } + children.apply(stylesheet, mode, + context, pos, len, + attr, null); } if (next != null) - { - next.apply(stylesheet, mode, - context, pos, len, - parent, nextSibling); - } + next.apply(stylesheet, mode, + context, pos, len, + parent, nextSibling); } final String getPrefix(String name) @@ -241,13 +223,9 @@ final class AttributeNode public boolean references(QName var) { if (name != null && name.references(var)) - { - return true; - } + return true; if (namespace != null && namespace.references(var)) - { - return true; - } + return true; return super.references(var); } diff --git a/gnu/xml/transform/Bindings.java b/gnu/xml/transform/Bindings.java index c372ea830..4ee083223 100644 --- a/gnu/xml/transform/Bindings.java +++ b/gnu/xml/transform/Bindings.java @@ -78,6 +78,11 @@ public class Bindings */ final LinkedList withParameters; + /** + * Only search globals. + */ + boolean global; + Bindings(Stylesheet stylesheet) { this.stylesheet = stylesheet; @@ -136,6 +141,12 @@ public class Bindings public boolean containsKey(QName name, int type) { + if (global) + { + Map ctx1 = (Map) variables.getLast(); + Map ctx2 = (Map) parameters.getLast(); + return (ctx1.containsKey(name) || ctx2.containsKey(name)); + } Iterator i = null; switch (type) { @@ -165,6 +176,17 @@ public class Bindings public Object get(QName name, Node context, int pos, int len) { + if (global) + { + Map ctx = (Map) variables.getLast(); + Object ret = ctx.get(name); + if (ret == null) + { + ctx = (Map) parameters.getLast(); + ret = ctx.get(name); + } + return ret; + } //System.err.println("bindings.get: "+name); //System.err.println("\t"+toString()); Object ret = null; diff --git a/gnu/xml/transform/ElementAvailableFunction.java b/gnu/xml/transform/ElementAvailableFunction.java index 84cb6207a..aa1598169 100644 --- a/gnu/xml/transform/ElementAvailableFunction.java +++ b/gnu/xml/transform/ElementAvailableFunction.java @@ -144,8 +144,8 @@ class ElementAvailableFunction { return elements.contains(localName) ? Boolean.TRUE : Boolean.FALSE; - // TODO extension elements } + // TODO extension elements return Boolean.FALSE; } @@ -153,16 +153,12 @@ class ElementAvailableFunction { NamespaceContext n = nsctx; if (context instanceof NamespaceContext) - { - n = (NamespaceContext) context; - } + n = (NamespaceContext) context; ElementAvailableFunction f = new ElementAvailableFunction(n); int len = args.size(); List args2 = new ArrayList(len); for (int i = 0; i < len; i++) - { - args2.add(((Expr) args.get(i)).clone(context)); - } + args2.add(((Expr) args.get(i)).clone(context)); f.setArguments(args2); return f; } @@ -172,12 +168,15 @@ class ElementAvailableFunction for (Iterator i = args.iterator(); i.hasNext(); ) { if (((Expr) i.next()).references(var)) - { - return true; - } + return true; } return false; } + public String toString() + { + return "element-available(" + args.get(0) + ")"; + } + } diff --git a/gnu/xml/transform/ElementNode.java b/gnu/xml/transform/ElementNode.java index d8f7f6db6..092c56a4b 100644 --- a/gnu/xml/transform/ElementNode.java +++ b/gnu/xml/transform/ElementNode.java @@ -82,14 +82,10 @@ final class ElementNode elementExcludeResultPrefixes = new HashSet(); StringTokenizer st = new StringTokenizer(attr.getNodeValue()); while (st.hasMoreTokens()) - { - elementExcludeResultPrefixes.add(st.nextToken()); - } + elementExcludeResultPrefixes.add(st.nextToken()); } else - { - elementExcludeResultPrefixes = Collections.EMPTY_SET; - } + elementExcludeResultPrefixes = Collections.EMPTY_SET; } TemplateNode clone(Stylesheet stylesheet) @@ -99,19 +95,15 @@ final class ElementNode namespace.clone(stylesheet), uas, source); if (children != null) - { - ret.children = children.clone(stylesheet); - } + ret.children = children.clone(stylesheet); if (next != null) - { - ret.next = next.clone(stylesheet); - } + ret.next = next.clone(stylesheet); return ret; } void doApply(Stylesheet stylesheet, QName mode, - Node context, int pos, int len, - Node parent, Node nextSibling) + Node context, int pos, int len, + Node parent, Node nextSibling) throws TransformerException { Document doc = (parent instanceof Document) ? (Document) parent : @@ -137,96 +129,70 @@ final class ElementNode // Use XPath string-value of fragment namespaceValue = Expr.stringValue(fragment); if (namespaceValue.length() == 0) - { - namespaceValue = null; - } - } - - String prefix = getPrefix(nameValue); - if (XMLConstants.XMLNS_ATTRIBUTE.equals(prefix)) - { - int ci = nameValue.indexOf(':'); - nameValue = nameValue.substring(ci + 1); + namespaceValue = null; } else - { - // Namespace aliasing - if (prefix == null) - { - prefix = "#default"; - } - String resultPrefix = - (String) stylesheet.namespaceAliases.get(prefix); - if (resultPrefix != null) - { - if ("#default".equals(resultPrefix)) - { - resultPrefix = null; - } - namespaceValue = source.lookupNamespaceURI(resultPrefix); - } - if (prefix == "#default") + { + String prefix = getPrefix(nameValue); + if (XMLConstants.XMLNS_ATTRIBUTE.equals(prefix)) { - prefix = null; + int ci = nameValue.indexOf(':'); + nameValue = nameValue.substring(ci + 1); } - // Look up ordinary namespace for this prefix - if (namespaceValue == null) + else { - if (XMLConstants.XML_NS_PREFIX.equals(prefix)) + // Namespace aliasing + if (prefix == null) + prefix = "#default"; + String resultPrefix = + (String) stylesheet.namespaceAliases.get(prefix); + if (resultPrefix != null) { - namespaceValue = XMLConstants.XML_NS_URI; + if ("#default".equals(resultPrefix)) + resultPrefix = null; + namespaceValue = source.lookupNamespaceURI(resultPrefix); } - else + if (prefix == "#default") + prefix = null; + // Look up ordinary namespace for this prefix + if (namespaceValue == null) { - // Resolve namespace for this prefix - namespaceValue = source.lookupNamespaceURI(prefix); + if (XMLConstants.XML_NS_PREFIX.equals(prefix)) + namespaceValue = XMLConstants.XML_NS_URI; + else + { + // Resolve namespace for this prefix + namespaceValue = source.lookupNamespaceURI(prefix); + } } } - /*if (prefix == null) - { - // Resolve prefix for this namespace - prefix = parent.lookupPrefix(namespaceValue); - if (prefix != null) - { - nameValue = prefix + ":" + nameValue; - } - }*/ } + // Create element Element element = (namespaceValue != null) ? doc.createElementNS(namespaceValue, nameValue) : - doc.createElement(nameValue); + doc.createElement(nameValue); if (nextSibling != null) - { - parent.insertBefore(element, nextSibling); - } + parent.insertBefore(element, nextSibling); else - { - parent.appendChild(element); - } + parent.appendChild(element); stylesheet.addNamespaceNodes(source, element, doc, elementExcludeResultPrefixes); if (uas != null) { StringTokenizer st = new StringTokenizer(uas, " "); while (st.hasMoreTokens()) - { - addAttributeSet(stylesheet, mode, context, pos, len, - element, null, st.nextToken()); - } + addAttributeSet(stylesheet, mode, context, pos, len, + element, null, st.nextToken()); } if (children != null) - { - children.apply(stylesheet, mode, - context, pos, len, - element, null); - } + children.apply(stylesheet, mode, + context, pos, len, + element, null); if (next != null) - { - next.apply(stylesheet, mode, - context, pos, len, - parent, nextSibling); - } + next.apply(stylesheet, mode, + context, pos, len, + parent, nextSibling); } final String getPrefix(String name) @@ -240,41 +206,33 @@ final class ElementNode Node parent, Node nextSibling, String attributeSet) throws TransformerException { + stylesheet.bindings.global = true; for (Iterator i = stylesheet.attributeSets.iterator(); i.hasNext(); ) { AttributeSet as = (AttributeSet) i.next(); if (!as.name.equals(attributeSet)) - { - continue; - } + continue; if (as.uas != null) { StringTokenizer st = new StringTokenizer(as.uas, " "); while (st.hasMoreTokens()) - { - addAttributeSet(stylesheet, mode, context, pos, len, - parent, nextSibling, st.nextToken()); - } + addAttributeSet(stylesheet, mode, context, pos, len, + parent, nextSibling, st.nextToken()); } if (as.children != null) - { - as.children.apply(stylesheet, mode, - context, pos, len, - parent, nextSibling); - } + as.children.apply(stylesheet, mode, + context, pos, len, + parent, nextSibling); } + stylesheet.bindings.global = false; } public boolean references(QName var) { if (name != null && name.references(var)) - { - return true; - } + return true; if (namespace != null && namespace.references(var)) - { - return true; - } + return true; return super.references(var); } @@ -283,6 +241,11 @@ final class ElementNode StringBuffer buf = new StringBuffer(getClass().getName()); buf.append('['); buf.append("name="); + if (namespace != null) + { + buf.append(",namespace="); + buf.append(namespace); + } buf.append(name); if (uas != null) { diff --git a/gnu/xml/transform/FunctionAvailableFunction.java b/gnu/xml/transform/FunctionAvailableFunction.java index 7daf7ea3f..ab86401d0 100644 --- a/gnu/xml/transform/FunctionAvailableFunction.java +++ b/gnu/xml/transform/FunctionAvailableFunction.java @@ -147,11 +147,16 @@ class FunctionAvailableFunction uri = nsctx.getNamespaceURI(prefix); if (uri == null) { - return xsltFunctions.contains(localName) || - xpathFunctions.contains(localName) ? + return (xpathFunctions.contains(localName) || + xsltFunctions.contains(localName)) ? Boolean.TRUE : Boolean.FALSE; - // TODO extension functions } + else if (Stylesheet.XSL_NS.equals(uri)) + { + return xsltFunctions.contains(localName) ? + Boolean.TRUE : Boolean.FALSE; + } + // TODO extension functions return Boolean.FALSE; } @@ -159,16 +164,12 @@ class FunctionAvailableFunction { NamespaceContext n = nsctx; if (context instanceof NamespaceContext) - { - n = (NamespaceContext) context; - } + n = (NamespaceContext) context; FunctionAvailableFunction f = new FunctionAvailableFunction(n); int len = args.size(); List args2 = new ArrayList(len); for (int i = 0; i < len; i++) - { - args2.add(((Expr) args.get(i)).clone(context)); - } + args2.add(((Expr) args.get(i)).clone(context)); f.setArguments(args2); return f; } @@ -178,12 +179,15 @@ class FunctionAvailableFunction for (Iterator i = args.iterator(); i.hasNext(); ) { if (((Expr) i.next()).references(var)) - { - return true; - } + return true; } return false; } + public String toString() + { + return "function-available(" + args.get(0) + ")"; + } + } diff --git a/gnu/xml/transform/LiteralNode.java b/gnu/xml/transform/LiteralNode.java index 0be2b35c8..453c22c5e 100644 --- a/gnu/xml/transform/LiteralNode.java +++ b/gnu/xml/transform/LiteralNode.java @@ -1,5 +1,5 @@ /* LiteralNode.java -- - Copyright (C) 2004 Free Software Foundation, Inc. + Copyright (C) 2004,2006 Free Software Foundation, Inc. This file is part of GNU Classpath. @@ -77,38 +77,28 @@ final class LiteralNode elementExcludeResultPrefixes = new HashSet(); StringTokenizer st = new StringTokenizer(attr.getNodeValue()); while (st.hasMoreTokens()) - { - elementExcludeResultPrefixes.add(st.nextToken()); - } + elementExcludeResultPrefixes.add(st.nextToken()); } else - { - elementExcludeResultPrefixes = Collections.EMPTY_SET; - } + elementExcludeResultPrefixes = Collections.EMPTY_SET; } else - { - elementExcludeResultPrefixes = null; - } + elementExcludeResultPrefixes = null; } TemplateNode clone(Stylesheet stylesheet) { TemplateNode ret = new LiteralNode(source); if (children != null) - { - ret.children = children.clone(stylesheet); - } + ret.children = children.clone(stylesheet); if (next != null) - { - ret.next = next.clone(stylesheet); - } + ret.next = next.clone(stylesheet); return ret; } void doApply(Stylesheet stylesheet, QName mode, - Node context, int pos, int len, - Node parent, Node nextSibling) + Node context, int pos, int len, + Node parent, Node nextSibling) throws TransformerException { Node result = null; @@ -127,17 +117,13 @@ final class LiteralNode { String prefix = source.getPrefix(); if (prefix == null) - { - prefix = "#default"; - } + prefix = "#default"; String resultPrefix = (String) stylesheet.namespaceAliases.get(prefix); if (resultPrefix != null) { if ("#default".equals(resultPrefix)) - { - resultPrefix = null; - } + resultPrefix = null; String uri = source.lookupNamespaceURI(resultPrefix); String name = source.getNodeName(); // Create a new element node in the result document @@ -189,33 +175,23 @@ final class LiteralNode result = result2; } if (nextSibling != null) - { - parent.insertBefore(result, nextSibling); - } + parent.insertBefore(result, nextSibling); else - { - parent.appendChild(result); - } + parent.appendChild(result); if (nodeType == Node.ELEMENT_NODE) - { - stylesheet.addNamespaceNodes(source, result, doc, - elementExcludeResultPrefixes); - } + stylesheet.addNamespaceNodes(source, result, doc, + elementExcludeResultPrefixes); // children if (children != null) - { - children.apply(stylesheet, mode, - context, pos, len, - result, null); - } + children.apply(stylesheet, mode, + context, pos, len, + result, null); } // next sibling if (next != null) - { - next.apply(stylesheet, mode, - context, pos, len, - parent, nextSibling); - } + next.apply(stylesheet, mode, + context, pos, len, + parent, nextSibling); } public String toString() diff --git a/gnu/xml/transform/MessageNode.java b/gnu/xml/transform/MessageNode.java index 1df716836..e8e07c6da 100644 --- a/gnu/xml/transform/MessageNode.java +++ b/gnu/xml/transform/MessageNode.java @@ -1,5 +1,5 @@ /* MessageNode.java -- - Copyright (C) 2004 Free Software Foundation, Inc. + Copyright (C) 2004,2006 Free Software Foundation, Inc. This file is part of GNU Classpath. @@ -37,6 +37,7 @@ exception statement from your version. */ package gnu.xml.transform; +import java.util.logging.Logger; import javax.xml.namespace.QName; import javax.xml.transform.TransformerException; import org.w3c.dom.Document; @@ -53,6 +54,8 @@ final class MessageNode extends TemplateNode { + static final Logger logger = Logger.getLogger("gnu.xml.transform"); + final boolean terminate; MessageNode(boolean terminate) @@ -64,13 +67,9 @@ final class MessageNode { TemplateNode ret = new MessageNode(terminate); if (children != null) - { - ret.children = children.clone(stylesheet); - } + ret.children = children.clone(stylesheet); if (next != null) - { - ret.next = next.clone(stylesheet); - } + ret.next = next.clone(stylesheet); return ret; } @@ -86,16 +85,12 @@ final class MessageNode DocumentFragment fragment = doc.createDocumentFragment(); children.apply(stylesheet, mode, context, pos, len, fragment, null); String message = Expr.stringValue(fragment); - System.err.println(message); + logger.info(message); if (terminate) - { - stylesheet.terminated = true; - } + stylesheet.terminated = true; } if (next != null && !terminate) - { - next.apply(stylesheet, mode, context, pos, len, parent, nextSibling); - } + next.apply(stylesheet, mode, context, pos, len, parent, nextSibling); } } diff --git a/gnu/xml/transform/NamespaceProxy.java b/gnu/xml/transform/NamespaceProxy.java new file mode 100644 index 000000000..b3c233cd7 --- /dev/null +++ b/gnu/xml/transform/NamespaceProxy.java @@ -0,0 +1,77 @@ +/* NamespaceProxy.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 java.util.Collections; +import java.util.Iterator; +import javax.xml.namespace.NamespaceContext; +import org.w3c.dom.Node; + +/** + * A namespace context using a DOM node to resolve the namespace. + * + * @author <a href='mailto:dog@gnu.org'>Chris Burdess</a> + */ +class NamespaceProxy + implements NamespaceContext +{ + + private final Node node; + + NamespaceProxy(Node node) + { + this.node = node; + } + + public String getNamespaceURI(String prefix) + { + return (node == null) ? null : node.lookupNamespaceURI(prefix); + } + + public String getPrefix(String namespaceURI) + { + return (node == null) ? null : node.lookupPrefix(namespaceURI); + } + + public Iterator getPrefixes(String namespaceURI) + { + // TODO + return Collections.singleton(getPrefix(namespaceURI)).iterator(); + } + +} diff --git a/gnu/xml/transform/StreamSerializer.java b/gnu/xml/transform/StreamSerializer.java index 74b10057c..fb8b1a601 100644 --- a/gnu/xml/transform/StreamSerializer.java +++ b/gnu/xml/transform/StreamSerializer.java @@ -1,5 +1,5 @@ /* StreamSerializer.java -- - Copyright (C) 2004 Free Software Foundation, Inc. + Copyright (C) 2004,2006 Free Software Foundation, Inc. This file is part of GNU Classpath. @@ -49,6 +49,8 @@ import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; +import java.util.Iterator; +import java.util.LinkedList; import java.util.Map; import javax.xml.XMLConstants; import org.w3c.dom.Attr; @@ -149,16 +151,25 @@ public class StreamSerializer HTML_BOOLEAN_ATTRIBUTES.put("script", set); } + // HTML namespace URIs + static final HashSet HTML_URIS = new HashSet(); + static { + HTML_URIS.add("http://www.w3.org/1999/xhtml"); + } + protected final String encoding; final Charset charset; final CharsetEncoder encoder; final int mode; - final Map namespaces; + final LinkedList namespaces; protected String eol; Collection cdataSectionElements = Collections.EMPTY_SET; protected boolean discardDefaultContent; protected boolean xmlDeclaration = true; + + // has a META element with the encoding been added? + private boolean htmlEncoded; public StreamSerializer() { @@ -174,14 +185,12 @@ public class StreamSerializer { this.mode = mode; if (encoding == null) - { - encoding = "UTF-8"; - } + encoding = (mode == Stylesheet.OUTPUT_HTML) ? "ISO-8859-1" : "UTF-8"; this.encoding = encoding.intern(); charset = Charset.forName(this.encoding); encoder = charset.newEncoder(); this.eol = (eol != null) ? eol : System.getProperty("line.separator"); - namespaces = new HashMap(); + namespaces = new LinkedList(); } void setCdataSectionElements(Collection c) @@ -212,18 +221,14 @@ public class StreamSerializer throws IOException { if (out == null) - { - throw new NullPointerException("no output stream"); - } + throw new NullPointerException("no output stream"); + htmlEncoded = false; String value, prefix; Node children; String uri = node.getNamespaceURI(); - boolean defined = false; short nt = node.getNodeType(); if (convertToCdata && nt == Node.TEXT_NODE) - { - nt = Node.CDATA_SECTION_NODE; - } + nt = Node.CDATA_SECTION_NODE; switch (nt) { case Node.ATTRIBUTE_NODE: @@ -233,27 +238,28 @@ public class StreamSerializer (prefix != null && prefix.startsWith("xmlns:"))) { String nsuri = node.getNodeValue(); - if (isDefined(nsuri)) - { - break; - } + if (isDefined(nsuri, prefix)) + break; String name = node.getLocalName(); if (name == null) { + // Namespace-unaware name = node.getNodeName(); + int ci = name.indexOf(':'); + if (ci != -1) + name = name.substring(ci + 1); } define(nsuri, name); } - else if (uri != null && !isDefined(uri)) + else if (uri != null && !isDefined(uri, prefix)) { prefix = define(uri, prefix); String nsname = (prefix == null) ? "xmlns" : "xmlns:" + prefix; out.write(SPACE); out.write(encodeText(nsname)); out.write(EQ); - String nsvalue = "'" + encode(uri, true, true) + "'"; + String nsvalue = "\"" + encode(uri, true, true) + "\""; out.write(nsvalue.getBytes(encoding)); - defined = true; } out.write(SPACE); String a_nodeName = node.getNodeName(); @@ -262,27 +268,26 @@ public class StreamSerializer if (mode == Stylesheet.OUTPUT_HTML && a_nodeName.equals(a_nodeValue) && isHTMLBoolean((Attr) node, a_nodeName)) - { - break; - } + break; out.write(EQ); - value = "'" + encode(a_nodeValue, true, true) + "'"; + value = "\"" + encode(a_nodeValue, true, true) + "\""; out.write(encodeText(value)); break; case Node.ELEMENT_NODE: + pushNamespaceContext(); value = node.getNodeName(); out.write(BRA); out.write(encodeText(value)); - if (uri != null && !isDefined(uri)) + prefix = node.getPrefix(); + if (uri != null && !isDefined(uri, prefix)) { - prefix = define(uri, node.getPrefix()); + prefix = define(uri, prefix); String nsname = (prefix == null) ? "xmlns" : "xmlns:" + prefix; out.write(SPACE); out.write(encodeText(nsname)); out.write(EQ); - String nsvalue = "'" + encode(uri, true, true) + "'"; + String nsvalue = "\"" + encode(uri, true, true) + "\""; out.write(encodeText(nsvalue)); - defined = true; } NamedNodeMap attrs = node.getAttributes(); if (attrs != null) @@ -296,9 +301,7 @@ public class StreamSerializer // NOOP } else - { - serialize(attr, out, false); - } + serialize(attr, out, false); } } convertToCdata = cdataSectionElements.contains(value); @@ -317,27 +320,35 @@ public class StreamSerializer out.write(encodeText(value)); out.write(KET); } + popNamespaceContext(); break; case Node.TEXT_NODE: value = node.getNodeValue(); if (!"yes".equals(node.getUserData("disable-output-escaping"))) - { - value = encode(value, false, false); - } + value = encode(value, false, false); out.write(encodeText(value)); break; case Node.CDATA_SECTION_NODE: - value = "<![CDATA[" + node.getNodeValue() + "]]>"; - out.write(encodeText(value)); + value = node.getNodeValue(); + // Where any instanceof of ]]> occur, split into multiple CDATA + // sections + int bbk = value.indexOf("]]>"); + while (bbk != -1) + { + String head = value.substring(0, bbk + 2); + out.write(encodeText("<![CDATA[" + head + "]]>")); + value = value.substring(bbk + 2); + bbk = value.indexOf("]]>"); + } + // Write final tail value + out.write(encodeText("<![CDATA[" + value + "]]>")); break; case Node.COMMENT_NODE: value = "<!--" + node.getNodeValue() + "-->"; out.write(encodeText(value)); Node cp = node.getParentNode(); if (cp != null && cp.getNodeType() == Node.DOCUMENT_NODE) - { - out.write(encodeText(eol)); - } + out.write(encodeText(eol)); break; case Node.DOCUMENT_NODE: case Node.DOCUMENT_FRAGMENT_NODE: @@ -355,29 +366,23 @@ public class StreamSerializer (Document) node : null; String version = (doc != null) ? doc.getXmlVersion() : null; if (version == null) - { - version = (String) node.getUserData("version"); - } + version = (String) node.getUserData("version"); if (version == null) - { - version = "1.0"; - } + version = "1.0"; out.write(BRA); out.write(0x3f); - out.write("xml version='".getBytes("US-ASCII")); + out.write("xml version=\"".getBytes("US-ASCII")); out.write(version.getBytes("US-ASCII")); - out.write(APOS); + out.write(0x22); if (!("UTF-8".equalsIgnoreCase(encoding))) { - out.write(" encoding='".getBytes("US-ASCII")); + out.write(" encoding=\"".getBytes("US-ASCII")); out.write(encoding.getBytes("US-ASCII")); - out.write(APOS); + out.write(0x22); } if ((doc != null && doc.getXmlStandalone()) || "yes".equals(node.getUserData("standalone"))) - { - out.write(" standalone='yes'".getBytes("US-ASCII")); - } + out.write(" standalone=\"yes\"".getBytes("US-ASCII")); out.write(0x3f); out.write(KET); out.write(encodeText(eol)); @@ -387,12 +392,10 @@ public class StreamSerializer } else if (mode == Stylesheet.OUTPUT_HTML) { - // Ensure that encoding is accessible + // Ensure that encoding is accessible if head element is present String mediaType = (String) node.getUserData("media-type"); if (mediaType == null) - { - mediaType = "text/html"; - } + mediaType = "text/html"; String contentType = mediaType + "; charset=" + ((encoding.indexOf(' ') != -1) ? "\"" + encoding + "\"" : @@ -403,133 +406,87 @@ public class StreamSerializer for (Node ctx = node.getFirstChild(); ctx != null; ctx = ctx.getNextSibling()) { - if (ctx.getNodeType() == Node.ELEMENT_NODE) + if (ctx.getNodeType() == Node.ELEMENT_NODE && + isHTMLElement(ctx, "html")) { html = ctx; break; } } - if (html == null) - { - html = doc.createElement("html"); - node.appendChild(html); - } - Node head = null; - for (Node ctx = html.getFirstChild(); ctx != null; - ctx = ctx.getNextSibling()) + if (html != null) { - if (ctx.getNodeType() == Node.ELEMENT_NODE) - { - String name = ctx.getLocalName(); - if (name == null) - { - name = ctx.getNodeName(); - } - if ("head".equalsIgnoreCase(name)) - { - head = ctx; - break; - } - } - } - if (head == null) - { - head = doc.createElement("head"); - Node c1 = null; + Node head = null; for (Node ctx = html.getFirstChild(); ctx != null; ctx = ctx.getNextSibling()) { - if (ctx.getNodeType() == Node.ELEMENT_NODE) + if (isHTMLElement(ctx, "head")) { - c1 = ctx; + head = ctx; break; } } - if (c1 != null) - { - html.insertBefore(head, c1); - } - else - { - html.appendChild(head); - } - } - Node meta = null; - Node metaContent = null; - for (Node ctx = head.getFirstChild(); ctx != null; - ctx = ctx.getNextSibling()) - { - if (ctx.getNodeType() == Node.ELEMENT_NODE) + if (head != null) { - String name = ctx.getLocalName(); - if (name == null) - { - name = ctx.getNodeName(); - } - if ("meta".equalsIgnoreCase(name)) + Node meta = null; + Node metaContent = null; + for (Node ctx = head.getFirstChild(); ctx != null; + ctx = ctx.getNextSibling()) { - NamedNodeMap metaAttrs = ctx.getAttributes(); - int len = metaAttrs.getLength(); - String httpEquiv = null; - Node content = null; - for (int i = 0; i < len; i++) + if (isHTMLElement(ctx, "meta")) { - Node attr = metaAttrs.item(i); - String attrName = attr.getNodeName(); - if ("http-equiv".equalsIgnoreCase(attrName)) + NamedNodeMap metaAttrs = ctx.getAttributes(); + int len = metaAttrs.getLength(); + String httpEquiv = null; + Node content = null; + for (int i = 0; i < len; i++) { - httpEquiv = attr.getNodeValue(); + Node attr = metaAttrs.item(i); + String attrName = attr.getNodeName(); + if ("http-equiv".equalsIgnoreCase(attrName)) + httpEquiv = attr.getNodeValue(); + else if ("content".equalsIgnoreCase(attrName)) + content = attr; } - else if ("content".equalsIgnoreCase(attrName)) + if ("Content-Type".equalsIgnoreCase(httpEquiv)) { - content = attr; + meta = ctx; + metaContent = content; + break; } } - if ("Content-Type".equalsIgnoreCase(httpEquiv)) - { - meta = ctx; - metaContent = content; - break; - } } + if (meta == null) + { + meta = doc.createElement("meta"); + // Insert first + Node first = head.getFirstChild(); + if (first == null) + head.appendChild(meta); + else + head.insertBefore(meta, first); + Node metaHttpEquiv = doc.createAttribute("http-equiv"); + meta.getAttributes().setNamedItem(metaHttpEquiv); + metaHttpEquiv.setNodeValue("Content-Type"); + } + if (metaContent == null) + { + metaContent = doc.createAttribute("content"); + meta.getAttributes().setNamedItem(metaContent); + } + metaContent.setNodeValue(contentType); + htmlEncoded = true; } } - if (meta == null) - { - meta = doc.createElement("meta"); - // Insert first - Node first = head.getFirstChild(); - if (first == null) - { - head.appendChild(meta); - } - else - { - head.insertBefore(meta, first); - } - Node metaHttpEquiv = doc.createAttribute("http-equiv"); - meta.getAttributes().setNamedItem(metaHttpEquiv); - metaHttpEquiv.setNodeValue("Content-Type"); - } - if (metaContent == null) - { - metaContent = doc.createAttribute("content"); - meta.getAttributes().setNamedItem(metaContent); - } - metaContent.setNodeValue(contentType); - // phew } children = node.getFirstChild(); if (children != null) - { - serialize(children, out, convertToCdata); - } + serialize(children, out, convertToCdata); break; case Node.DOCUMENT_TYPE_NODE: DocumentType doctype = (DocumentType) node; out.write(BRA); out.write(BANG); - out.write(encodeText("DOCTYPE ")); + out.write(encodeText("DOCTYPE ")); value = doctype.getNodeName(); out.write(encodeText(value)); String publicId = doctype.getPublicId(); @@ -569,41 +526,73 @@ public class StreamSerializer out.write(encodeText(eol)); } break; + default: + System.err.println("Unhandled node type: "+nt); } - if (defined) + } + + boolean isHTMLElement(Node node, String name) + { + if (node.getNodeType() != Node.ELEMENT_NODE) + return false; + String localName = node.getLocalName(); + if (localName == null) + localName = node.getNodeName(); + if (!name.equalsIgnoreCase(localName)) + return false; + String uri = node.getNamespaceURI(); + return (uri == null || HTML_URIS.contains(uri)); + } + + boolean isDefined(String uri, String prefix) + { + if (XMLConstants.XML_NS_URI.equals(uri)) + return "xml".equals(prefix); + if (XMLConstants.XMLNS_ATTRIBUTE_NS_URI.equals(uri)) + return "xmlns".equals(prefix); + if (prefix == null) + prefix = ""; + for (Iterator i = namespaces.iterator(); i.hasNext(); ) { - undefine(uri); + Map ctx = (Map) i.next(); + String val = (String) ctx.get(uri); + if (val != null && val.equals(prefix)) + return true; } + return false; } - boolean isDefined(String uri) + void pushNamespaceContext() { - return XMLConstants.XML_NS_URI.equals(uri) || - XMLConstants.XMLNS_ATTRIBUTE_NS_URI.equals(uri) || - namespaces.containsKey(uri); + namespaces.addFirst(new HashMap()); } String define(String uri, String prefix) { - while (namespaces.containsValue(prefix)) + if (namespaces.isEmpty()) + return prefix; + HashMap ctx = (HashMap) namespaces.getFirst(); + while (ctx.containsValue(prefix)) { // Fabricate new prefix prefix = prefix + "_"; } - namespaces.put(uri, prefix); + ctx.put(uri, prefix); return prefix; } - void undefine(String uri) + void popNamespaceContext() { - namespaces.remove(uri); + namespaces.removeFirst(); } final byte[] encodeText(String text) throws IOException { encoder.reset(); - if (!encoder.canEncode(text)) + boolean htmlNeedingEncoding = + (mode == Stylesheet.OUTPUT_HTML && !htmlEncoded); + if (!encoder.canEncode(text) || htmlNeedingEncoding) { // Check each character StringBuffer buf = new StringBuffer(); @@ -611,11 +600,7 @@ public class StreamSerializer for (int i = 0; i < len; i++) { char c = text.charAt(i); - if (encoder.canEncode(c)) - { - buf.append(c); - } - else + if (!encoder.canEncode(c)) { // Replace with character entity reference String hex = Integer.toHexString((int) c); @@ -623,6 +608,20 @@ public class StreamSerializer buf.append(hex); buf.append(';'); } + else if (htmlNeedingEncoding) + { + String entityName = getHTMLCharacterEntity(c); + if (entityName != null) + { + buf.append('&'); + buf.append(entityName); + buf.append(';'); + } + else + buf.append(c); + } + else + buf.append(c); } text = buf.toString(); } @@ -656,17 +655,13 @@ public class StreamSerializer if (c == '<') { if (buf == null) - { - buf = new StringBuffer(text.substring(0, i)); - } + buf = new StringBuffer(text.substring(0, i)); buf.append("<"); } else if (c == '>') { if (buf == null) - { - buf = new StringBuffer(text.substring(0, i)); - } + buf = new StringBuffer(text.substring(0, i)); buf.append(">"); } else if (c == '&') @@ -675,25 +670,19 @@ public class StreamSerializer text.charAt(i + 1) == '{') { if (buf != null) - { - buf.append(c); - } + buf.append(c); } else { if (buf == null) - { - buf = new StringBuffer(text.substring(0, i)); - } + buf = new StringBuffer(text.substring(0, i)); buf.append("&"); } } else if (c == '\'' && inAttr) { if (buf == null) - { - buf = new StringBuffer(text.substring(0, i)); - } + buf = new StringBuffer(text.substring(0, i)); if (mode == Stylesheet.OUTPUT_HTML) // HTML does not define ', use character entity ref buf.append("'"); @@ -703,9 +692,7 @@ public class StreamSerializer else if (c == '"' && inAttr) { if (buf == null) - { - buf = new StringBuffer(text.substring(0, i)); - } + buf = new StringBuffer(text.substring(0, i)); buf.append("""); } else if (encodeCtl) @@ -713,23 +700,17 @@ public class StreamSerializer if (c < 0x20) { if (buf == null) - { - buf = new StringBuffer(text.substring(0, i)); - } + buf = new StringBuffer(text.substring(0, i)); buf.append('&'); buf.append('#'); buf.append((int) c); buf.append(';'); } else if (buf != null) - { - buf.append(c); - } + buf.append(c); } else if (buf != null) - { - buf.append(c); - } + buf.append(c); } return (buf == null) ? text : buf.toString(); } @@ -763,4 +744,109 @@ public class StreamSerializer return (attributes != null && attributes.contains(attrName)); } + static String getHTMLCharacterEntity(char c) + { + // Hardcode these here to avoid loading the HTML DTD + switch (c) + { + case 160: return "nbsp"; + case 161: return "iexcl"; + case 162: return "cent"; + case 163: return "pound"; + case 164: return "curren"; + case 165: return "yen"; + case 166: return "brvbar"; + case 167: return "sect"; + case 168: return "uml"; + case 169: return "copy"; + case 170: return "ordf"; + case 171: return "laquo"; + case 172: return "not"; + case 173: return "shy"; + case 174: return "reg"; + case 175: return "macr"; + case 176: return "deg"; + case 177: return "plusmn"; + case 178: return "sup2"; + case 179: return "sup3"; + case 180: return "acute"; + case 181: return "micro"; + case 182: return "para"; + case 183: return "middot"; + case 184: return "cedil"; + case 185: return "sup1"; + case 186: return "ordm"; + case 187: return "raquo"; + case 188: return "frac14"; + case 189: return "frac12"; + case 190: return "frac34"; + case 191: return "iquest"; + case 192: return "Agrave"; + case 193: return "Aacute"; + case 194: return "Acirc"; + case 195: return "Atilde"; + case 196: return "Auml"; + case 197: return "Aring"; + case 198: return "AElig"; + case 199: return "Ccedil"; + case 200: return "Egrave"; + case 201: return "Eacute"; + case 202: return "Ecirc"; + case 203: return "Euml"; + case 204: return "Igrave"; + case 205: return "Iacute"; + case 206: return "Icirc"; + case 207: return "Iuml"; + case 208: return "ETH"; + case 209: return "Ntilde"; + case 210: return "Ograve"; + case 211: return "Oacute"; + case 212: return "Ocirc"; + case 213: return "Otilde"; + case 214: return "Ouml"; + case 215: return "times"; + case 216: return "Oslash"; + case 217: return "Ugrave"; + case 218: return "Uacute"; + case 219: return "Ucirc"; + case 220: return "Uuml"; + case 221: return "Yacute"; + case 222: return "THORN"; + case 223: return "szlig"; + case 224: return "agrave"; + case 225: return "aacute"; + case 226: return "acirc"; + case 227: return "atilde"; + case 228: return "auml"; + case 229: return "aring"; + case 230: return "aelig"; + case 231: return "ccedil"; + case 232: return "egrave"; + case 233: return "eacute"; + case 234: return "ecirc"; + case 235: return "euml"; + case 236: return "igrave"; + case 237: return "iacute"; + case 238: return "icirc"; + case 239: return "iuml"; + case 240: return "eth"; + case 241: return "ntilde"; + case 242: return "ograve"; + case 243: return "oacute"; + case 244: return "ocirc"; + case 245: return "otilde"; + case 246: return "ouml"; + case 247: return "divide"; + case 248: return "oslash"; + case 249: return "ugrave"; + case 250: return "uacute"; + case 251: return "ucirc"; + case 252: return "uuml"; + case 253: return "yacute"; + case 254: return "thorn"; + case 255: return "yuml"; + default: return null; + } + } + } diff --git a/gnu/xml/transform/StrippingInstruction.java b/gnu/xml/transform/StrippingInstruction.java new file mode 100644 index 000000000..c6391b9c5 --- /dev/null +++ b/gnu/xml/transform/StrippingInstruction.java @@ -0,0 +1,73 @@ +/* StrippingInstruction.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 gnu.xml.xpath.NameTest; + +/** + * An entry in a strip-space or preserve-space list. + * + * @author <a href='mailto:dog@gnu.org'>Chris Burdess</a> + */ +class StrippingInstruction +{ + + final NameTest element; + final int precedence; + + StrippingInstruction(NameTest element, int precedence) + { + this.element = element; + this.precedence = precedence; + } + + /** + * Returns the <i>default priority</i> of the element name test. + * @see http://www.w3.org/TR/xslt#dt-default-priority + */ + float getPriority() + { + if (element.matchesAny()) + return -0.5f; + else if (element.matchesAnyLocalName()) + return -0.25f; + else + return 0.0f; + } + +} diff --git a/gnu/xml/transform/Stylesheet.java b/gnu/xml/transform/Stylesheet.java index 99431b699..51accaa3b 100644 --- a/gnu/xml/transform/Stylesheet.java +++ b/gnu/xml/transform/Stylesheet.java @@ -1,5 +1,5 @@ /* Stylesheet.java -- - Copyright (C) 2004 Free Software Foundation, Inc. + Copyright (C) 2004,2006 Free Software Foundation, Inc. This file is part of GNU Classpath. @@ -88,6 +88,8 @@ class Stylesheet { static final String XSL_NS = "http://www.w3.org/1999/XSL/Transform"; + private static final NameTest STYLESHEET_PRESERVE_TEXT = + new NameTest(new QName(XSL_NS, "text"), false, false); static final int OUTPUT_XML = 0; static final int OUTPUT_HTML = 1; @@ -208,6 +210,7 @@ class Stylesheet preserveSpace = new LinkedHashSet(); outputCdataSectionElements = new LinkedHashSet(); xpath = (XPathImpl) factory.xpathFactory.newXPath(); + xpath.setNamespaceContext(this); if (parent == null) { bindings = new Bindings(this); @@ -218,7 +221,6 @@ class Stylesheet keys = new LinkedList(); decimalFormats = new LinkedHashMap(); initDefaultDecimalFormat(); - xpath.setNamespaceContext(this); xpath.setXPathFunctionResolver(this); } else @@ -241,7 +243,6 @@ class Stylesheet templates = root.templates; keys = root.keys; decimalFormats = root.decimalFormats; - xpath.setNamespaceContext(root); xpath.setXPathFunctionResolver(root); } xpath.setXPathVariableResolver(bindings); @@ -276,9 +277,7 @@ class Stylesheet { Stylesheet stylesheet = this; while (stylesheet.parent != null) - { - stylesheet = stylesheet.parent; - } + stylesheet = stylesheet.parent; return stylesheet; } @@ -408,9 +407,7 @@ class Stylesheet throws TransformerException { if (debug) - { - System.err.println("getTemplate: mode="+mode+" context="+context); - } + System.err.println("getTemplate: mode="+mode+" context="+context); Set candidates = new TreeSet(); for (Iterator j = templates.iterator(); j.hasNext(); ) { @@ -425,15 +422,11 @@ class Stylesheet throw new TransformerException(msg); } if (!currentTemplate.imports(t)) - { - isMatch = false; - } + isMatch = false; } //System.err.println("\t"+context+" "+t+"="+isMatch); if (isMatch) - { - candidates.add(t); - } + candidates.add(t); } //System.err.println("\tcandidates="+candidates); if (candidates.isEmpty()) @@ -441,9 +434,7 @@ class Stylesheet // Apply built-in template // Current template is unchanged if (debug) - { - System.err.println("\tbuiltInTemplate context="+context); - } + System.err.println("\tbuiltInTemplate context="+context); switch (context.getNodeType()) { case Node.ELEMENT_NODE: @@ -453,6 +444,7 @@ class Stylesheet case Node.COMMENT_NODE: return builtInNodeTemplate; case Node.TEXT_NODE: + case Node.CDATA_SECTION_NODE: case Node.ATTRIBUTE_NODE: return builtInTextTemplate; default: @@ -465,9 +457,7 @@ class Stylesheet // Set current template currentTemplate = t; if (debug) - { - System.err.println("\ttemplate="+t+" context="+context); - } + System.err.println("\ttemplate="+t+" context="+context); return t.node; } } @@ -475,25 +465,17 @@ class Stylesheet TemplateNode getTemplate(QName mode, QName name) throws TransformerException { - //System.err.println("getTemplate: mode="+mode+" name="+name); Set candidates = new TreeSet(); for (Iterator j = templates.iterator(); j.hasNext(); ) { Template t = (Template) j.next(); boolean isMatch = t.matches(name); - //System.err.println("\t"+name+" "+t+"="+isMatch); if (isMatch) - { - candidates.add(t); - } + candidates.add(t); } if (candidates.isEmpty()) - { - return null; - //throw new TransformerException("template '" + name + "' not found"); - } + return null; Template t = (Template) candidates.iterator().next(); - //System.err.println("\ttemplate="+t+" context="+context); return t.node; } @@ -538,42 +520,30 @@ class Stylesheet output = node; String method = getAttribute(attrs, "method"); if ("xml".equals(method) || method == null) - { - outputMethod = OUTPUT_XML; - } + outputMethod = OUTPUT_XML; else if ("html".equals(method)) - { - outputMethod = OUTPUT_HTML; - } + outputMethod = OUTPUT_HTML; else if ("text".equals(method)) - { - outputMethod = OUTPUT_TEXT; - } + outputMethod = OUTPUT_TEXT; else { String msg = "unsupported output method: " + method; DOMSourceLocator l = new DOMSourceLocator(node); throw new TransformerConfigurationException(msg, l); } - outputPublicId = getAttribute(attrs, "public-id"); - outputSystemId = getAttribute(attrs, "system-id"); + outputPublicId = getAttribute(attrs, "doctype-public"); + outputSystemId = getAttribute(attrs, "doctype-system"); outputEncoding = getAttribute(attrs, "encoding"); String indent = getAttribute(attrs, "indent"); if (indent != null) - { - outputIndent = "yes".equals(indent); - } + outputIndent = "yes".equals(indent); outputVersion = getAttribute(attrs, "version"); String omitXmlDecl = getAttribute(attrs, "omit-xml-declaration"); if (omitXmlDecl != null) - { - outputOmitXmlDeclaration = "yes".equals(omitXmlDecl); - } + outputOmitXmlDeclaration = "yes".equals(omitXmlDecl); String standalone = getAttribute(attrs, "standalone"); if (standalone != null) - { - outputStandalone = "yes".equals(standalone); - } + outputStandalone = "yes".equals(standalone); outputMediaType = getAttribute(attrs, "media-type"); String cdataSectionElements = getAttribute(attrs, "cdata-section-elements"); @@ -581,9 +551,7 @@ class Stylesheet { StringTokenizer st = new StringTokenizer(cdataSectionElements, " "); while (st.hasMoreTokens()) - { - outputCdataSectionElements.add(st.nextToken()); - } + outputCdataSectionElements.add(st.nextToken()); } } @@ -728,9 +696,7 @@ class Stylesheet parse(node.getFirstChild(), false); } else if ("template".equals(name)) - { - templates.add(parseTemplate(node, attrs)); - } + templates.add(parseTemplate(node, attrs)); else if ("param".equals(name) || "variable".equals(name)) { @@ -779,9 +745,7 @@ class Stylesheet factory.newStylesheet(source, precedence + delta, this); } else if ("output".equals(name)) - { - parseOutput(node, attrs); - } + parseOutput(node, attrs); else if ("preserve-space".equals(name)) { String elements = @@ -790,7 +754,9 @@ class Stylesheet " \t\n\r"); while (st.hasMoreTokens()) { - preserveSpace.add(parseNameTest(st.nextToken())); + NameTest element = parseNameTest(st.nextToken()); + preserveSpace.add(new StrippingInstruction(element, + precedence)); } } else if ("strip-space".equals(name)) @@ -801,25 +767,19 @@ class Stylesheet " \t\n\r"); while (st.hasMoreTokens()) { - stripSpace.add(parseNameTest(st.nextToken())); + NameTest element = parseNameTest(st.nextToken()); + stripSpace.add(new StrippingInstruction(element, + precedence)); } } else if ("key".equals(name)) - { - parseKey(node, attrs); - } + parseKey(node, attrs); else if ("decimal-format".equals(name)) - { - parseDecimalFormat(node, attrs); - } + parseDecimalFormat(node, attrs); else if ("namespace-alias".equals(name)) - { - parseNamespaceAlias(node, attrs); - } + parseNamespaceAlias(node, attrs); else if ("attribute-set".equals(name)) - { - parseAttributeSet(node, attrs); - } + parseAttributeSet(node, attrs); } else if (root) { @@ -867,12 +827,10 @@ class Stylesheet final NameTest parseNameTest(String token) { if ("*".equals(token)) - { - return new NameTest(null, true, true); - } + return new NameTest(null, true, true); else if (token.endsWith(":*")) { - QName qName = getQName(token.substring(0, token.length() - 2)); + QName qName = getQName(token); return new NameTest(qName, true, false); } else @@ -984,7 +942,13 @@ class Stylesheet return ret; } - boolean isPreserved(Text text) + /** + * Whitespace stripping. + * @param text the text node + * @param source true if a source node, false if a stylesheet text node + * @see http://www.w3.org/TR/xslt#strip + */ + boolean isPreserved(Text text, boolean source) throws TransformerConfigurationException { // Check characters in text @@ -996,39 +960,73 @@ class Stylesheet { char c = value.charAt(i); if (c != 0x20 && c != 0x09 && c != 0x0a && c != 0x0d) - { - return true; - } + return true; } } // Check parent node Node ctx = text.getParentNode(); - if (!preserveSpace.isEmpty()) + if (source) { - for (Iterator i = preserveSpace.iterator(); i.hasNext(); ) + // Source document text node + boolean preserve = true; + float psPriority = 0.0f, ssPriority = 0.0f; + if (!stripSpace.isEmpty()) { - NameTest preserveTest = (NameTest) i.next(); - if (preserveTest.matches(ctx, 1, 1)) + // Conflict resolution + StrippingInstruction ssi = null, psi = null; + for (Iterator i = stripSpace.iterator(); i.hasNext(); ) + { + StrippingInstruction si = (StrippingInstruction) i.next(); + if (si.element.matches(ctx, 1, 1)) + { + if (ssi != null) + { + if (si.precedence < ssi.precedence) + continue; + float p = si.getPriority(); + if (p < ssPriority) + continue; + } + ssi = si; + } + } + for (Iterator i = preserveSpace.iterator(); i.hasNext(); ) { - boolean override = false; - if (!stripSpace.isEmpty()) + StrippingInstruction si = (StrippingInstruction) i.next(); + if (si.element.matches(ctx, 1, 1)) { - for (Iterator j = stripSpace.iterator(); j.hasNext(); ) + if (psi != null) { - NameTest stripTest = (NameTest) j.next(); - if (stripTest.matches(ctx, 1, 1)) - { - override = true; - break; - } + if (si.precedence < psi.precedence) + continue; + float p = si.getPriority(); + if (p < psPriority) + continue; } + psi = si; } - if (!override) + } + if (ssi != null) + { + if (psi != null) { - return true; + if (psi.precedence < ssi.precedence) + preserve = false; + else if (psPriority < ssPriority) + preserve = false; } + else + preserve = false; } } + if (preserve) + return true; + } + else + { + // Stylesheet text node + if (STYLESHEET_PRESERVE_TEXT.matches(ctx, 1, 1)) + return true; } // Check whether any ancestor specified xml:space while (ctx != null) @@ -1038,24 +1036,14 @@ class Stylesheet Element element = (Element) ctx; String xmlSpace = element.getAttribute("xml:space"); if ("default".equals(xmlSpace)) - { - break; - } + break; else if ("preserve".equals(xmlSpace)) - { - return true; - } + return true; else if (xmlSpace.length() > 0) { String msg = "Illegal value for xml:space: " + xmlSpace; throw new TransformerConfigurationException(msg); } - else if ("text".equals(ctx.getLocalName()) && - XSL_NS.equals(ctx.getNamespaceURI())) - { - // xsl:text implies xml:space='preserve' - return true; - } } ctx = ctx.getParentNode(); } @@ -1071,45 +1059,27 @@ class Stylesheet if ("document".equals(localName) && (arity == 1 || arity == 2)) { if (current == null) - { throw new RuntimeException("current is null"); - } return new DocumentFunction(getRootStylesheet(), current); } else if ("key".equals(localName) && (arity == 2)) - { - return new KeyFunction(getRootStylesheet()); - } + return new KeyFunction(getRootStylesheet()); else if ("format-number".equals(localName) && (arity == 2 || arity == 3)) - { - return new FormatNumberFunction(getRootStylesheet()); - } + return new FormatNumberFunction(getRootStylesheet()); else if ("current".equals(localName) && (arity == 0)) - { - return new CurrentFunction(getRootStylesheet()); - } + return new CurrentFunction(getRootStylesheet()); else if ("unparsed-entity-uri".equals(localName) && (arity == 1)) - { - return new UnparsedEntityUriFunction(); - } + return new UnparsedEntityUriFunction(); else if ("generate-id".equals(localName) && (arity == 1 || arity == 0)) - { - return new GenerateIdFunction(); - } + return new GenerateIdFunction(); else if ("system-property".equals(localName) && (arity == 1)) - { - return new SystemPropertyFunction(); - } + return new SystemPropertyFunction(); else if ("element-available".equals(localName) && (arity == 1)) - { - return new ElementAvailableFunction(this); - } + return new ElementAvailableFunction(new NamespaceProxy(current)); else if ("function-available".equals(localName) && (arity == 1)) - { - return new FunctionAvailableFunction(this); - } + return new FunctionAvailableFunction(new NamespaceProxy(current)); } return null; } @@ -1127,9 +1097,7 @@ class Stylesheet QName mode = (m == null) ? null : getQName(m); String s = getAttribute(attrs, "select"); if (s == null) - { - s = "child::node()"; - } + s = "child::node()"; Node children = node.getFirstChild(); List sortKeys = parseSortKeys(children); List withParams = parseWithParams(children); @@ -1411,13 +1379,9 @@ class Stylesheet if (tnode != null) { if (first == null) - { - first = tnode; - } + first = tnode; if (previous != null) - { - previous.next = tnode; - } + previous.next = tnode; previous = tnode; } node = next; @@ -1438,25 +1402,15 @@ class Stylesheet { String name = node.getLocalName(); if ("apply-templates".equals(name)) - { - return parseApplyTemplates(node); - } + return parseApplyTemplates(node); else if ("call-template".equals(name)) - { - return parseCallTemplate(node); - } + return parseCallTemplate(node); else if ("value-of".equals(name)) - { - return parseValueOf(node); - } + return parseValueOf(node); else if ("for-each".equals(name)) - { - return parseForEach(node); - } + return parseForEach(node); else if ("if".equals(name)) - { - return parseIf(node); - } + return parseIf(node); else if ("choose".equals(name)) { Node children = node.getFirstChild(); @@ -1465,9 +1419,7 @@ class Stylesheet return ret; } else if ("when".equals(name)) - { - return parseWhen(node); - } + return parseWhen(node); else if ("otherwise".equals(name)) { Node children = node.getFirstChild(); @@ -1476,25 +1428,15 @@ class Stylesheet return ret; } else if ("element".equals(name)) - { - return parseElement(node); - } + return parseElement(node); else if ("attribute".equals(name)) - { - return parseAttribute(node); - } + return parseAttribute(node); else if ("text".equals(name)) - { - return parseText(node); - } + return parseText(node); else if ("copy".equals(name)) - { - return parseCopy(node); - } + return parseCopy(node); else if ("processing-instruction".equals(name)) - { - return parseProcessingInstruction(node); - } + return parseProcessingInstruction(node); else if ("comment".equals(name)) { Node children = node.getFirstChild(); @@ -1503,9 +1445,7 @@ class Stylesheet return ret; } else if ("number".equals(name)) - { - return parseNumber(node); - } + return parseNumber(node); else if ("param".equals(name) || "variable".equals(name)) { @@ -1538,13 +1478,9 @@ class Stylesheet return ret; } else if ("copy-of".equals(name)) - { - return parseCopyOf(node); - } + return parseCopyOf(node); else if ("message".equals(name)) - { - return parseMessage(node); - } + return parseMessage(node); else if ("apply-imports".equals(name)) { Node children = node.getFirstChild(); @@ -1562,22 +1498,30 @@ class Stylesheet String prefix = node.getPrefix(); if (extensionElementPrefixes.contains(prefix)) { - // Pass over extension elements + // Check for xsl:fallback + for (Node ctx = node.getFirstChild(); ctx != null; + ctx = ctx.getNextSibling()) + { + String ctxUri = ctx.getNamespaceURI(); + if (XSL_NS.equals(ctxUri) && + "fallback".equals(ctx.getLocalName())) + { + ctx = ctx.getFirstChild(); + return (ctx == null) ? null : parse(ctx); + } + } + // Otherwise pass over extension element return null; } switch (node.getNodeType()) { case Node.TEXT_NODE: + case Node.CDATA_SECTION_NODE: // Determine whether to strip whitespace Text text = (Text) node; - if (!isPreserved(text)) + if (!isPreserved(text, false)) { // Strip - /*String data = text.getData().trim(); - if (data.length() > 0) - { - text.setData(data); - } // else */ text.getParentNode().removeChild(text); return null; } @@ -1623,9 +1567,7 @@ class Stylesheet String aname = attr.getNodeName(); if (Stylesheet.XSL_NS.equals(ans) && "use-attribute-sets".equals(attr.getLocalName())) - { - continue; - } + continue; String value = attr.getNodeValue(); TemplateNode grandchild = parseAttributeValueTemplate(value, node); @@ -1640,8 +1582,9 @@ class Stylesheet } String ename = node.getNodeName(); TemplateNode n = parseAttributeValueTemplate(ename, node); - TemplateNode ns = (namespaceUri == null) ? null : - parseAttributeValueTemplate(namespaceUri, node); + //TemplateNode ns = (namespaceUri == null) ? null : + // parseAttributeValueTemplate(namespaceUri, node); + TemplateNode ns = null; ElementNode ret = new ElementNode(n, ns, useAttributeSets, node); ret.children = child; @@ -1676,9 +1619,7 @@ class Stylesheet NamedNodeMap attrs = node.getAttributes(); String s = getAttribute(attrs, "select"); if (s == null) - { - s = "."; - } + s = "."; Expr select = (Expr) xpath.compile(s); String l = getAttribute(attrs, "lang"); TemplateNode lang = (l == null) ? null : @@ -1728,9 +1669,7 @@ class Stylesheet ret.add(new WithParam(name, expr)); } else - { - ret.add(new WithParam(name, content)); - } + ret.add(new WithParam(name, content)); } node = node.getNextSibling(); } @@ -1757,27 +1696,19 @@ class Stylesheet { String prefix = attr.getLocalName(); if (XMLConstants.XMLNS_ATTRIBUTE.equals(prefix)) - { - prefix = "#default"; - } + prefix = "#default"; String ns = attr.getNodeValue(); // Should the namespace be excluded? if (XSL_NS.equals(ns) || extensionElementPrefixes.contains(prefix) || elementExcludeResultPrefixes.contains(prefix) || excludeResultPrefixes.contains(prefix)) - { - continue; - } + continue; // Is the namespace already defined on the target? if (prefix == "#default") - { - prefix = null; - } + prefix = null; if (target.lookupNamespaceURI(prefix) != null) - { - continue; - } + continue; attr = attr.cloneNode(true); attr = doc.adoptNode(attr); target.getAttributes().setNamedItemNS(attr); @@ -1786,23 +1717,17 @@ class Stylesheet } Node parent = source.getParentNode(); if (parent != null) - { - addNamespaceNodes(parent, target, doc, elementExcludeResultPrefixes); - } + addNamespaceNodes(parent, target, doc, elementExcludeResultPrefixes); } static final String getAttribute(NamedNodeMap attrs, String name) { Node attr = attrs.getNamedItem(name); if (attr == null) - { - return null; - } + return null; String ret = attr.getNodeValue(); if (ret.length() == 0) - { - return null; - } + return null; return ret; } diff --git a/gnu/xml/transform/TransformerFactoryImpl.java b/gnu/xml/transform/TransformerFactoryImpl.java index dde2017ff..16e3363f8 100644 --- a/gnu/xml/transform/TransformerFactoryImpl.java +++ b/gnu/xml/transform/TransformerFactoryImpl.java @@ -1,5 +1,5 @@ /* TransformerFactoryImpl.java -- - Copyright (C) 2004 Free Software Foundation, Inc. + Copyright (C) 2004,2006 Free Software Foundation, Inc. This file is part of GNU Classpath. @@ -37,7 +37,11 @@ exception statement from your version. */ package gnu.xml.transform; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.InputStream; import java.io.IOException; +import java.io.OutputStream; import java.net.URL; import java.util.Iterator; import java.util.LinkedHashMap; @@ -73,7 +77,7 @@ public class TransformerFactoryImpl { final XPathFactory xpathFactory; - final XSLURIResolver resolver; + final XSLURIResolver resolver; ErrorListener userListener; URIResolver userResolver; @@ -341,5 +345,46 @@ public class TransformerFactoryImpl { return userListener; } + + /** + * Syntax: TransformerFactoryImpl [<stylesheet> [<input> [<output>]]] + */ + public static void main(String[] args) + throws Exception + { + InputStream stylesheet = null, in = null; + OutputStream out = null; + try + { + if (args.length > 0) + { + stylesheet = new FileInputStream(args[0]); + if (args.length > 1) + { + in = new FileInputStream(args[1]); + if (args.length > 2) + out = new FileOutputStream(args[2]); + } + } + if (in == null) + in = System.in; + if (out == null) + out = System.out; + TransformerFactory f = new TransformerFactoryImpl(); + Transformer t = (stylesheet != null) ? + f.newTransformer(new StreamSource(stylesheet)) : + f.newTransformer(); + t.transform(new StreamSource(in), new StreamResult(out)); + } + finally + { + if (stylesheet != null) + stylesheet.close(); + if (in != null && in instanceof FileInputStream) + in.close(); + if (out != null && out instanceof FileOutputStream) + out.close(); + } + } } diff --git a/gnu/xml/transform/TransformerImpl.java b/gnu/xml/transform/TransformerImpl.java index 78bca52d3..b7ff66884 100644 --- a/gnu/xml/transform/TransformerImpl.java +++ b/gnu/xml/transform/TransformerImpl.java @@ -1,5 +1,5 @@ /* TransformerImpl.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. @@ -128,8 +128,6 @@ class TransformerImpl { // Suppress mutation events ((DomDocument) doc).setBuilding(true); - // TODO find a better/more generic way of doing this than - // casting } // Get the result tree Node parent = null, nextSibling = null; @@ -147,8 +145,6 @@ class TransformerImpl DomDocument drdoc = (DomDocument) rdoc; drdoc.setBuilding(true); drdoc.setCheckWellformedness(false); - // TODO find a better/more generic way of doing this than - // casting } } boolean created = false; @@ -184,9 +180,7 @@ class TransformerImpl { // Done transforming, reset document if (doc instanceof DomDocument) - { - ((DomDocument) doc).setBuilding(false); - } + ((DomDocument) doc).setBuilding(false); throw e; } } @@ -214,17 +208,11 @@ class TransformerImpl } Document sourceDoc = context.getOwnerDocument(); if (sourceDoc != resultDoc) - { - clone = resultDoc.adoptNode(clone); - } + clone = resultDoc.adoptNode(clone); if (nextSibling != null) - { - parent.insertBefore(clone, nextSibling); - } + parent.insertBefore(clone, nextSibling); else - { - parent.appendChild(clone); - } + parent.appendChild(clone); } else { @@ -256,15 +244,18 @@ class TransformerImpl DomDocument resultDoc = (DomDocument) parent; Node root = resultDoc.getDocumentElement(); // Add doctype if specified - if ((publicId != null || systemId != null) && - root != null) + if (publicId != null || systemId != null) { - // We must know the name of the root element to - // create the document type - resultDoc.appendChild(new DomDoctype(resultDoc, - root.getNodeName(), - publicId, - systemId)); + if (root != null) + { + // We must know the name of the root element to + // create the document type + DocumentType doctype = new DomDoctype(resultDoc, + root.getNodeName(), + publicId, + systemId); + resultDoc.insertBefore(doctype, root); + } } resultDoc.setBuilding(false); resultDoc.setCheckWellformedness(true); @@ -279,43 +270,25 @@ class TransformerImpl (Document) parent : parent.getOwnerDocument(); DOMImplementation impl = resultDoc.getImplementation(); - DocumentType doctype = - impl.createDocumentType(resultDoc.getNodeName(), - publicId, - systemId); - // Try to insert doctype before first element - Node ctx = parent.getFirstChild(); - for (; ctx != null && - ctx.getNodeType() != Node.ELEMENT_NODE; - ctx = ctx.getNextSibling()) + Node root = resultDoc.getDocumentElement(); + if (root != null) { - } - if (ctx != null) - { - parent.insertBefore(doctype, ctx); - } - else - { - parent.appendChild(doctype); + DocumentType doctype = + impl.createDocumentType(root.getNodeName(), + publicId, + systemId); + resultDoc.insertBefore(doctype, root); } } } if (version != null) - { - parent.setUserData("version", version, stylesheet); - } + parent.setUserData("version", version, stylesheet); if (omitXmlDeclaration) - { - parent.setUserData("omit-xml-declaration", "yes", stylesheet); - } + parent.setUserData("omit-xml-declaration", "yes", stylesheet); if (standalone) - { - parent.setUserData("standalone", "yes", stylesheet); - } + parent.setUserData("standalone", "yes", stylesheet); if (mediaType != null) - { - parent.setUserData("media-type", mediaType, stylesheet); - } + parent.setUserData("media-type", mediaType, stylesheet); if (cdataSectionElements != null) { List list = new LinkedList(); @@ -390,13 +363,9 @@ class TransformerImpl if (ex != null) { if (errorListener != null) - { - errorListener.error(new TransformerException(ex)); - } + errorListener.error(new TransformerException(ex)); else - { - ex.printStackTrace(System.err); - } + ex.printStackTrace(System.err); } } else if (outputTarget instanceof SAXResult) @@ -407,22 +376,16 @@ class TransformerImpl ContentHandler ch = sr.getHandler(); LexicalHandler lh = sr.getLexicalHandler(); if (lh == null && ch instanceof LexicalHandler) - { - lh = (LexicalHandler) ch; - } + lh = (LexicalHandler) ch; SAXSerializer serializer = new SAXSerializer(); serializer.serialize(parent, ch, lh); } catch (SAXException e) { if (errorListener != null) - { - errorListener.error(new TransformerException(e)); - } + errorListener.error(new TransformerException(e)); else - { - e.printStackTrace(System.err); - } + e.printStackTrace(System.err); } } } @@ -430,7 +393,7 @@ class TransformerImpl /** * Strip whitespace from the source tree. */ - void strip(Node node) + boolean strip(Node node) throws TransformerConfigurationException { short nt = node.getNodeType(); @@ -438,44 +401,101 @@ class TransformerImpl { // Replace entity reference with its content Node parent = node.getParentNode(); + Node nextSibling = node.getNextSibling(); Node child = node.getFirstChild(); - if (child != null) - { - strip(child); - } while (child != null) { Node next = child.getNextSibling(); node.removeChild(child); - parent.insertBefore(child, node); + if (nextSibling != null) + parent.insertBefore(child, nextSibling); + else + parent.appendChild(child); child = next; } - parent.removeChild(node); + return true; } if (nt == Node.TEXT_NODE || nt == Node.CDATA_SECTION_NODE) { - if (!stylesheet.isPreserved((Text) node)) + // Denormalize text into whitespace and non-whitespace nodes + String text = node.getNodeValue(); + String[] tokens = tokenizeWhitespace(text); + if (tokens.length > 1) { - node.getParentNode().removeChild(node); - } - else - { - String text = node.getNodeValue(); - String stripped = text.trim(); - if (!text.equals(stripped)) + node.setNodeValue(tokens[0]); + Node parent = node.getParentNode(); + Node nextSibling = node.getNextSibling(); + Document doc = node.getOwnerDocument(); + for (int i = 1; i < tokens.length; i++) { - node.setNodeValue(stripped); + Node newChild = (nt == Node.CDATA_SECTION_NODE) ? + doc.createCDATASection(tokens[i]) : + doc.createTextNode(tokens[i]); + if (nextSibling != null) + parent.insertBefore(newChild, nextSibling); + else + parent.appendChild(newChild); } } + return !stylesheet.isPreserved((Text) node, true); } else { - for (Node child = node.getFirstChild(); child != null; - child = child.getNextSibling()) + Node child = node.getFirstChild(); + while (child != null) { - strip(child); + boolean remove = strip(child); + Node next = child.getNextSibling(); + if (remove) + node.removeChild(child); + child = next; } } + return false; + } + + /** + * Tokenize the specified text into contiguous whitespace-only and + * non-whitespace chunks. + */ + private static String[] tokenizeWhitespace(String text) + { + int len = text.length(); + int start = 0, end = len - 1; + // Find index of text start + for (int i = 0; i < len; i++) + { + char c = text.charAt(i); + boolean whitespace = (c == ' ' || c == '\n' || c == '\t' || c == '\r'); + if (whitespace) + start++; + else + break; + } + if (start == end) // all whitespace + return new String[] { text }; + // Find index of text end + for (int i = end; i > start; i--) + { + char c = text.charAt(i); + boolean whitespace = (c == ' ' || c == '\n' || c == '\t' || c == '\r'); + if (whitespace) + end--; + else + break; + } + if (start == 0 && end == len - 1) // all non-whitespace + return new String[] { text }; + // whitespace, then text, then whitespace + String[] ret = (start > 0 && end < len - 1) ? + new String[3] : new String[2]; + int i = 0; + if (start > 0) + ret[i++] = text.substring(0, start); + ret[i++] = text.substring(start, end + 1); + if (end < len - 1) + ret[i++] = text.substring(end + 1); + return ret; } /** @@ -495,9 +515,7 @@ class TransformerImpl { Writer writer = sr.getWriter(); if (writer != null) - { - out = new WriterOutputStream(writer); - } + out = new WriterOutputStream(writer); } if (out == null) { @@ -542,9 +560,7 @@ class TransformerImpl try { if (out != null && created) - { - out.close(); - } + out.close(); } catch (IOException e) { @@ -566,17 +582,13 @@ class TransformerImpl public void setParameter(String name, Object value) { if (stylesheet != null) - { - stylesheet.bindings.set(new QName(null, name), value, Bindings.PARAM); - } + stylesheet.bindings.set(new QName(null, name), value, Bindings.PARAM); } public Object getParameter(String name) { if (stylesheet != null) - { - return stylesheet.bindings.get(new QName(null, name), null, 1, 1); - } + return stylesheet.bindings.get(new QName(null, name), null, 1, 1); return null; } @@ -603,13 +615,9 @@ class TransformerImpl throws IllegalArgumentException { if (oformat == null) - { - outputProperties.clear(); - } + outputProperties.clear(); else - { - outputProperties.putAll(oformat); - } + outputProperties.putAll(oformat); } public Properties getOutputProperties() @@ -691,9 +699,7 @@ class TransformerImpl StringBuffer buf = new StringBuffer(); buf.append('\n'); for (int i = 0; i < offset + 1; i++) - { - buf.append(INDENT_WHITESPACE); - } + buf.append(INDENT_WHITESPACE); String ws = buf.toString(); for (Iterator i = children.iterator(); i.hasNext(); ) { @@ -705,9 +711,7 @@ class TransformerImpl buf.append('\n'); ws = buf.toString(); for (int i = 0; i < offset; i++) - { - buf.append(INDENT_WHITESPACE); - } + buf.append(INDENT_WHITESPACE); node.appendChild(doc.createTextNode(ws)); } } @@ -751,9 +755,7 @@ class TransformerImpl while (ctx != null) { if (ctx.hasChildNodes()) - { - convertCdataSectionElements(doc, ctx, list); - } + convertCdataSectionElements(doc, ctx, list); ctx = ctx.getNextSibling(); } } @@ -763,9 +765,7 @@ class TransformerImpl String ln1 = qname.getLocalPart(); String ln2 = node.getLocalName(); if (ln2 == null) - { - return ln1.equals(node.getNodeName()); - } + return ln1.equals(node.getNodeName()); else { String uri1 = qname.getNamespaceURI(); diff --git a/gnu/xml/transform/ValueOfNode.java b/gnu/xml/transform/ValueOfNode.java index 430598a94..24c229ea3 100644 --- a/gnu/xml/transform/ValueOfNode.java +++ b/gnu/xml/transform/ValueOfNode.java @@ -1,5 +1,5 @@ /* ValueOfNode.java -- - Copyright (C) 2004 Free Software Foundation, Inc. + Copyright (C) 2004,2006 Free Software Foundation, Inc. This file is part of GNU Classpath. @@ -69,26 +69,18 @@ final class ValueOfNode TemplateNode ret = new ValueOfNode(select.clone(stylesheet), disableOutputEscaping); if (children != null) - { - ret.children = children.clone(stylesheet); - } + ret.children = children.clone(stylesheet); if (next != null) - { - ret.next = next.clone(stylesheet); - } + ret.next = next.clone(stylesheet); return ret; } void doApply(Stylesheet stylesheet, QName mode, - Node context, int pos, int len, - Node parent, Node nextSibling) + Node context, int pos, int len, + Node parent, Node nextSibling) throws TransformerException { Object ret = select.evaluate(context, pos, len); - /*if (stylesheet.debug) - { - System.err.println("value-of: " + select + " -> " + ret); - }*/ String value; if (ret instanceof Collection) { @@ -100,47 +92,35 @@ final class ValueOfNode } value = buf.toString(); } + else if (ret == null) + value = ""; else - { - value = Expr._string(context, ret); - } + value = Expr._string(context, ret); if (stylesheet.debug) - { - System.err.println("value-of: "+context+" "+ select + " -> "+ value); - } + System.err.println("value-of: "+context+" "+ select + " -> "+ value); if (value != null && value.length() > 0) { Document doc = (parent instanceof Document) ? (Document) parent : parent.getOwnerDocument(); Text textNode = doc.createTextNode(value); if (disableOutputEscaping) - { - textNode.setUserData("disable-output-escaping", "yes", stylesheet); - } + textNode.setUserData("disable-output-escaping", "yes", stylesheet); if (nextSibling != null) - { - parent.insertBefore(textNode, nextSibling); - } + parent.insertBefore(textNode, nextSibling); else - { - parent.appendChild(textNode); - } + parent.appendChild(textNode); } // value-of doesn't process children if (next != null) - { - next.apply(stylesheet, mode, - context, pos, len, - parent, nextSibling); - } + next.apply(stylesheet, mode, + context, pos, len, + parent, nextSibling); } public boolean references(QName var) { if (select != null && select.references(var)) - { - return true; - } + return true; return super.references(var); } @@ -151,9 +131,7 @@ final class ValueOfNode buf.append("select="); buf.append(select); if (disableOutputEscaping) - { - buf.append(",disableOutputEscaping"); - } + buf.append(",disableOutputEscaping"); buf.append(']'); return buf.toString(); } diff --git a/gnu/xml/xpath/Expr.java b/gnu/xml/xpath/Expr.java index b4b55dcf9..76fd49eef 100644 --- a/gnu/xml/xpath/Expr.java +++ b/gnu/xml/xpath/Expr.java @@ -1,5 +1,5 @@ /* Expr.java -- - Copyright (C) 2004 Free Software Foundation, Inc. + Copyright (C) 2004,2006 Free Software Foundation, Inc. This file is part of GNU Classpath. @@ -233,9 +233,11 @@ public abstract class Expr */ public static String _local_name(Node context, Collection nodeSet) { - Node node = (nodeSet == null || nodeSet.size() == 0) ? context : - firstNode(nodeSet); - return node.getLocalName(); + if (nodeSet == null || nodeSet.isEmpty()) + return ""; + Node node = firstNode(nodeSet); + String ret = node.getLocalName(); + return (ret == null) ? "" : ret; } /** @@ -248,9 +250,11 @@ public abstract class Expr */ public static String _namespace_uri(Node context, Collection nodeSet) { - Node node = (nodeSet == null || nodeSet.size() == 0) ? context : - firstNode(nodeSet); - return node.getNamespaceURI(); + if (nodeSet == null || nodeSet.isEmpty()) + return ""; + Node node = firstNode(nodeSet); + String ret = node.getNamespaceURI(); + return (ret == null) ? "" : ret; } /** @@ -271,17 +275,18 @@ public abstract class Expr */ public static String _name(Node context, Collection nodeSet) { - Node node = (nodeSet == null || nodeSet.size() == 0) ? context : - firstNode(nodeSet); + if (nodeSet == null || nodeSet.isEmpty()) + return ""; + Node node = firstNode(nodeSet); + String ret = null; switch (node.getNodeType()) { case Node.ATTRIBUTE_NODE: case Node.ELEMENT_NODE: case Node.PROCESSING_INSTRUCTION_NODE: - return node.getNodeName(); - default: - return ""; + ret = node.getNodeName(); } + return (ret == null) ? "" : ret; } /** @@ -371,7 +376,10 @@ public abstract class Expr } if (object instanceof Double) { - return ((Double) object).doubleValue() != 0.0; + Double value = (Double) object; + if (value.isNaN()) + return false; + return value.doubleValue() != 0.0; } if (object instanceof String) { @@ -473,4 +481,15 @@ public abstract class Expr } } + static int intValue(Object val) + { + if (val instanceof Double) + { + Double d = (Double) val; + return d.isNaN() ? 0 : d.intValue(); + } + else + return (int) Math.ceil(_number(null, val)); + } + } diff --git a/gnu/xml/xpath/LocalNameFunction.java b/gnu/xml/xpath/LocalNameFunction.java index f8ace9cd5..84fb6d482 100644 --- a/gnu/xml/xpath/LocalNameFunction.java +++ b/gnu/xml/xpath/LocalNameFunction.java @@ -1,5 +1,5 @@ /* LocalNameFunction.java -- - Copyright (C) 2004 Free Software Foundation, Inc. + Copyright (C) 2004,2006 Free Software Foundation, Inc. This file is part of GNU Classpath. @@ -38,6 +38,7 @@ exception statement from your version. */ package gnu.xml.xpath; import java.util.Collection; +import java.util.Collections; import java.util.List; import javax.xml.namespace.QName; import org.w3c.dom.Node; @@ -70,7 +71,8 @@ final class LocalNameFunction public Object evaluate(Node context, int pos, int len) { - Object val = (arg == null) ? null : arg.evaluate(context, pos, len); + Object val = (arg == null) ? Collections.singleton(context) : + arg.evaluate(context, pos, len); return _local_name(context, (Collection) val); } diff --git a/gnu/xml/xpath/NameFunction.java b/gnu/xml/xpath/NameFunction.java index dc5e61203..ea49741fa 100644 --- a/gnu/xml/xpath/NameFunction.java +++ b/gnu/xml/xpath/NameFunction.java @@ -1,5 +1,5 @@ /* NameFunction.java -- - Copyright (C) 2004 Free Software Foundation, Inc. + Copyright (C) 2004,2006 Free Software Foundation, Inc. This file is part of GNU Classpath. @@ -38,6 +38,7 @@ exception statement from your version. */ package gnu.xml.xpath; import java.util.Collection; +import java.util.Collections; import java.util.List; import javax.xml.namespace.QName; import org.w3c.dom.Node; @@ -78,7 +79,8 @@ final class NameFunction public Object evaluate(Node context, int pos, int len) { - Object val = (arg == null) ? null : arg.evaluate(context, pos, len); + Object val = (arg == null) ? Collections.singleton(context) : + arg.evaluate(context, pos, len); return _name(context, (Collection) val); } diff --git a/gnu/xml/xpath/NameTest.java b/gnu/xml/xpath/NameTest.java index c89ba4dd1..171010390 100644 --- a/gnu/xml/xpath/NameTest.java +++ b/gnu/xml/xpath/NameTest.java @@ -1,5 +1,5 @@ /* NameTest.java -- - Copyright (C) 2004 Free Software Foundation, Inc. + Copyright (C) 2004,2006 Free Software Foundation, Inc. This file is part of GNU Classpath. @@ -91,29 +91,32 @@ public final class NameTest return false; } if (any) - { - return true; - } + return true; String uri = qName.getNamespaceURI(); String nodeUri = node.getNamespaceURI(); - String nodeLocalName = node.getLocalName(); - if (nodeLocalName != null && !equal(uri, nodeUri)) - { - return false; - } + if (!equal(uri, nodeUri)) + return false; if (anyLocalName) - { - return true; - } + return true; String localName = qName.getLocalPart(); - if (nodeLocalName != null) + String nodeLocalName = getLocalName(node); + return (localName.equals(nodeLocalName)); + } + + static String getLocalName(Node node) + { + String localName = node.getLocalName(); + if (localName == null) { - nodeLocalName = node.getNodeName(); + localName = node.getNodeName(); + int ci = localName.indexOf(':'); + if (ci != -1) + localName = localName.substring(ci + 1); } - return (localName.equals(nodeLocalName)); + return localName; } - final boolean equal(String s1, String s2) + static boolean equal(String s1, String s2) { return (((s1 == null || s1.length() == 0) && (s2 == null || s2.length() == 0)) || @@ -133,9 +136,7 @@ public final class NameTest public String toString () { if (any) - { - return "*"; - } + return "*"; return qName.toString(); } diff --git a/gnu/xml/xpath/NamespaceTest.java b/gnu/xml/xpath/NamespaceTest.java index 6d41166bc..d93b76d9d 100644 --- a/gnu/xml/xpath/NamespaceTest.java +++ b/gnu/xml/xpath/NamespaceTest.java @@ -81,28 +81,22 @@ public final class NamespaceTest if (XMLConstants.XMLNS_ATTRIBUTE_NS_URI.equals(uri) || XMLConstants.XMLNS_ATTRIBUTE.equals(node.getPrefix()) || XMLConstants.XMLNS_ATTRIBUTE.equals(node.getNodeName())) - { - break; - } + break; // Fall through default: // Only process namespace attributes return false; } if (any) - { - return true; - } + return true; + String uri = qName.getNamespaceURI(); + String nodeUri = node.getNamespaceURI(); + if (!NameTest.equal(uri, nodeUri)) + return false; if (anyLocalName) - { - return true; - } + return true; String localName = qName.getLocalPart(); - String nodeLocalName = node.getLocalName(); - if (nodeLocalName == null) - { - nodeLocalName = node.getNodeName(); - } + String nodeLocalName = NameTest.getLocalName(node); return (localName.equals(nodeLocalName)); } @@ -119,9 +113,7 @@ public final class NamespaceTest public String toString () { if (any) - { - return "*"; - } + return "*"; return qName.toString(); } diff --git a/gnu/xml/xpath/NamespaceUriFunction.java b/gnu/xml/xpath/NamespaceUriFunction.java index e67ec4206..3ae46f7ee 100644 --- a/gnu/xml/xpath/NamespaceUriFunction.java +++ b/gnu/xml/xpath/NamespaceUriFunction.java @@ -1,5 +1,5 @@ /* NamespaceUriFunction.java -- - Copyright (C) 2004 Free Software Foundation, Inc. + Copyright (C) 2004,2006 Free Software Foundation, Inc. This file is part of GNU Classpath. @@ -38,6 +38,7 @@ exception statement from your version. */ package gnu.xml.xpath; import java.util.Collection; +import java.util.Collections; import java.util.List; import javax.xml.namespace.QName; import org.w3c.dom.Node; @@ -70,7 +71,8 @@ final class NamespaceUriFunction public Object evaluate(Node context, int pos, int len) { - Object val = (arg == null) ? null : arg.evaluate(context, pos, len); + Object val = (arg == null) ? Collections.singleton(context) : + arg.evaluate(context, pos, len); return _namespace_uri(context, (Collection) val); } diff --git a/gnu/xml/xpath/NodeTypeTest.java b/gnu/xml/xpath/NodeTypeTest.java index 807374132..09e92d0d9 100644 --- a/gnu/xml/xpath/NodeTypeTest.java +++ b/gnu/xml/xpath/NodeTypeTest.java @@ -1,5 +1,5 @@ /* NodeTypeTest.java -- - Copyright (C) 2004 Free Software Foundation, Inc. + Copyright (C) 2004,2006 Free Software Foundation, Inc. This file is part of GNU Classpath. @@ -39,6 +39,7 @@ package gnu.xml.xpath; import javax.xml.namespace.QName; import org.w3c.dom.Node; +import org.w3c.dom.ProcessingInstruction; /** * Tests whether a node is of a given type. @@ -83,17 +84,20 @@ public final class NodeTypeTest case Node.TEXT_NODE: case Node.CDATA_SECTION_NODE: case Node.COMMENT_NODE: + if (type > 0) + { + if (nodeType != type) + return false; + } + return true; case Node.PROCESSING_INSTRUCTION_NODE: if (type > 0) { if (nodeType != type) - { - return false; - } - if (data != null && !data.equals(node.getNodeValue())) - { - return false; - } + return false; + if (data != null && + !data.equals(((ProcessingInstruction) node).getTarget())) + return false; } return true; default: diff --git a/gnu/xml/xpath/Selector.java b/gnu/xml/xpath/Selector.java index 598038064..93408e48b 100644 --- a/gnu/xml/xpath/Selector.java +++ b/gnu/xml/xpath/Selector.java @@ -1,5 +1,5 @@ /* Selector.java -- - Copyright (C) 2004 Free Software Foundation, Inc. + Copyright (C) 2004,2006 Free Software Foundation, Inc. This file is part of GNU Classpath. @@ -85,11 +85,13 @@ public final class Selector public Selector(int axis, List tests) { this.axis = axis; - this.tests = new Test[tests.size()]; - tests.toArray(this.tests); - if (axis == NAMESPACE && - this.tests.length > 0 && - this.tests[0] instanceof NameTest) + int len = tests.size(); + this.tests = new Test[(len == 0) ? 1 : len]; + if (len > 0) + tests.toArray(this.tests); + else + this.tests[0] = new NameTest(null, true, true); + if (axis == NAMESPACE && this.tests[0] instanceof NameTest) { NameTest nt = (NameTest) this.tests[0]; this.tests[0] = new NamespaceTest(nt.qName, nt.anyLocalName, nt.any); @@ -111,16 +113,12 @@ public final class Selector { case CHILD: if (nodeType == Node.ATTRIBUTE_NODE) - { - return false; - } + return false; break; case ATTRIBUTE: case NAMESPACE: if (nodeType != Node.ATTRIBUTE_NODE) - { - return false; - } + return false; break; case DESCENDANT_OR_SELF: return true; @@ -132,13 +130,13 @@ public final class Selector { int pos = getContextPosition(context); int len = getContextSize(context); + if (len == 0) + System.err.println("WARNING: context size is 0"); for (int j = 0; j < tlen && len > 0; j++) { Test test = tests[j]; if (!test.matches(context, pos, len)) - { - return false; - } + return false; } } return true; @@ -149,9 +147,7 @@ public final class Selector int pos = 1; for (ctx = ctx.getPreviousSibling(); ctx != null; ctx = ctx.getPreviousSibling()) - { - pos++; - } + pos++; return pos; } @@ -159,15 +155,17 @@ public final class Selector { if (ctx.getNodeType() == Node.ATTRIBUTE_NODE) { - Node parent = ((Attr) ctx).getOwnerElement(); - return parent.getAttributes().getLength(); - } - Node parent = ctx.getParentNode(); - if (parent != null) - { - return parent.getChildNodes().getLength(); + Node owner = ((Attr) ctx).getOwnerElement(); + return owner.getAttributes().getLength(); } - return 1; + int count = 1; + Node sib = ctx.getPreviousSibling(); + for (; sib != null; sib = sib.getPreviousSibling()) + count++; + sib = ctx.getNextSibling(); + for (; sib != null; sib = sib.getNextSibling()) + count++; + return count; } public Object evaluate(Node context, int pos, int len) @@ -175,7 +173,6 @@ public final class Selector Set acc = new LinkedHashSet(); addCandidates(context, acc); List candidates = new ArrayList(acc); - //Collections.sort(candidates, documentOrderComparator); List ret = filterCandidates(candidates, false); return ret; } @@ -184,11 +181,8 @@ public final class Selector { Set acc = new LinkedHashSet(); for (Iterator i = ns.iterator(); i.hasNext(); ) - { - addCandidates((Node) i.next(), acc); - } + addCandidates((Node) i.next(), acc); List candidates = new ArrayList(acc); - //Collections.sort(candidates, documentOrderComparator); List ret = filterCandidates(candidates, true); return ret; } @@ -230,17 +224,7 @@ public final class Selector } } if (test.matches(node, i + 1, len)) - { - successful.add(node); - } - /* - System.err.println("Testing "+node); - int p = getContextPosition(node); - int l = getContextSize(node); - if (test.matches(node, p, l)) - { - successful.add(node); - }*/ + successful.add(node); } candidates = successful; len = candidates.size(); @@ -305,9 +289,7 @@ public final class Selector { acc.add(child); if (recurse) - { - addChildNodes(child, acc, recurse); - } + addChildNodes(child, acc, recurse); child = child.getNextSibling(); } } @@ -320,55 +302,62 @@ public final class Selector { acc.add(parent); if (recurse) - { - addParentNode(parent, acc, recurse); - } + addParentNode(parent, acc, recurse); } } void addFollowingNodes(Node context, Collection acc, boolean recurse) { - Node cur = context.getNextSibling(); + if (context != null && recurse) + addChildNodes(context, acc, true); + Node cur = (context.getNodeType() == Node.ATTRIBUTE_NODE) ? null : + context.getNextSibling(); while (cur != null) { acc.add(cur); if (recurse) - { - addChildNodes(cur, acc, true); - } + addChildNodes(cur, acc, true); cur = cur.getNextSibling(); } if (recurse) { - context = (context.getNodeType() == Node.ATTRIBUTE_NODE) ? - ((Attr) context).getOwnerElement() : context.getParentNode(); - if (context != null) + while (context != null) { - addFollowingNodes(context, acc, recurse); + context = (context.getNodeType() == Node.ATTRIBUTE_NODE) ? + ((Attr) context).getOwnerElement() : context.getParentNode(); + if (context != null) + { + cur = context.getNextSibling(); + while (cur != null) + { + acc.add(cur); + if (recurse) + addChildNodes(cur, acc, true); + cur = cur.getNextSibling(); + } + } } } } void addPrecedingNodes(Node context, Collection acc, boolean recurse) { - Node cur = context.getPreviousSibling(); + Node cur = (context.getNodeType() == Node.ATTRIBUTE_NODE) ? null : + context.getPreviousSibling(); while (cur != null) { acc.add(cur); if (recurse) - { - addChildNodes(cur, acc, true); - } + addChildNodes(cur, acc, true); cur = cur.getPreviousSibling(); } if (recurse) { - context = (context.getNodeType() == Node.ATTRIBUTE_NODE) ? - ((Attr) context).getOwnerElement() : context.getParentNode(); - if (context != null) - { - addPrecedingNodes(context, acc, recurse); - } + cur = context; + cur = (cur.getNodeType() == Node.ATTRIBUTE_NODE) ? + ((Attr) cur).getOwnerElement() : cur.getParentNode(); + if (cur != null) + addPrecedingNodes(cur, acc, recurse); } } @@ -399,9 +388,7 @@ public final class Selector { Node attr = attrs.item(i); if (isNamespaceAttribute(attr)) - { - acc.add(attr); - } + acc.add(attr); } } } @@ -419,9 +406,7 @@ public final class Selector int len = tests.length; List tests2 = new ArrayList(len); for (int i = 0; i < len; i++) - { - tests2.add(tests[i].clone(context)); - } + tests2.add(tests[i].clone(context)); return new Selector(axis, tests2); } @@ -430,9 +415,7 @@ public final class Selector for (int i = 0; i < tests.length; i++) { if (tests[i].references(var)) - { - return true; - } + return true; } return false; } @@ -451,13 +434,9 @@ public final class Selector case ATTRIBUTE: if (tests.length == 0 || (tests[0] instanceof NameTest)) - { - buf.append('@'); - } + buf.append('@'); else - { - buf.append("attribute::"); - } + buf.append("attribute::"); break; case CHILD: //buf.append("child::"); @@ -481,9 +460,7 @@ public final class Selector if (tests.length == 0 || (tests[0] instanceof NodeTypeTest && ((NodeTypeTest) tests[0]).type == 0)) - { - return ".."; - } + return ".."; buf.append("parent::"); break; case PRECEDING: @@ -496,22 +473,16 @@ public final class Selector if (tests.length == 0 || (tests[0] instanceof NodeTypeTest && ((NodeTypeTest) tests[0]).type == 0)) - { - return "."; - } + return "."; buf.append("self::"); break; } if (tests.length == 0) - { - buf.append('*'); - } + buf.append("[error]"); else { for (int i = 0; i < tests.length; i++) - { - buf.append(tests[i]); - } + buf.append(tests[i]); } return buf.toString(); } diff --git a/gnu/xml/xpath/SubstringFunction.java b/gnu/xml/xpath/SubstringFunction.java index d65c4facb..e926f6c7a 100644 --- a/gnu/xml/xpath/SubstringFunction.java +++ b/gnu/xml/xpath/SubstringFunction.java @@ -78,31 +78,20 @@ final class SubstringFunction Object val1 = arg1.evaluate(context, pos, len); Object val2 = arg2.evaluate(context, pos, len); String s = _string(context, val1); - int p = (val2 instanceof Double) ? - ((Double) val2).intValue() : - (int) Math.round(_number(context, val2)); - p--; + int p = Expr.intValue(val2) - 1; if (p < 0) - { - p = 0; - } + p = 0; int l = s.length() - p; if (l <= 0) - { - return ""; - } + return ""; if (arg3 != null) { Object val3 = arg3.evaluate(context, pos, len); - int v3 = (val3 instanceof Double) ? - ((Double) val3).intValue() : - (int) Math.round(_number(context, val3)); + int v3 = Expr.intValue(val3); if (v3 < l) - { - l = v3; - } + l = v3; } return s.substring(p, p + l); diff --git a/java/beans/EventSetDescriptor.java b/java/beans/EventSetDescriptor.java index 2494baf95..e687b8a30 100644 --- a/java/beans/EventSetDescriptor.java +++ b/java/beans/EventSetDescriptor.java @@ -1,39 +1,39 @@ /* java.beans.EventSetDescriptor - Copyright (C) 1998 Free Software Foundation, Inc. + Copyright (C) 1998, 2006 Free Software Foundation, Inc. -This file is part of GNU Classpath. + 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 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. */ + 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.beans; diff --git a/java/beans/Introspector.java b/java/beans/Introspector.java index 11d3f5879..ae8905590 100644 --- a/java/beans/Introspector.java +++ b/java/beans/Introspector.java @@ -212,6 +212,82 @@ public class Introspector { return cachedInfo; } } + + /** + * Returns a {@BeanInfo} instance for the given Bean class where a flag + * controls the usage of explicit BeanInfo class to retrieve that + * information. + * + * <p>You have three options:</p> + * <p>With {@link #USE_ALL_BEANINFO} the result is the same as + * {@link #getBeanInfo(Class)}.</p> + * + * <p>Calling the method with <code>flag</code> set to + * {@link #IGNORE_IMMEDIATE_BEANINFO} will let it use all + * explicit BeanInfo classes for the beans superclasses + * but not for the bean class itself. Furthermore eventset, + * property and method information is retrieved by introspection + * if the explicit <code>BeanInfos</code> did not provide such data + * (ie. return <code>null</code> on {@link BeanInfo.getMethodDescriptors}, + * {@link BeanInfo.getEventSetDescriptors} and + * {@link BeanInfo.getPropertyDescriptors}.) + * </p> + * + * <p>When the method is called with <code>flag</code< set to + * {@link #IGNORE_ALL_BEANINFO} all the bean data is retrieved + * by inspecting the class.</p> + * + * <p>Note: Any unknown value for <code>flag</code> is interpreted + * as {@link #IGNORE_ALL_BEANINFO}</p>. + * + * @param beanClass The class whose BeanInfo should be returned. + * @param flag Controls the usage of explicit <code>BeanInfo</code> classes. + * @return A BeanInfo object describing the class. + * @throws IntrospectionException If something goes wrong while retrieving + * the bean data. + */ + public static BeanInfo getBeanInfo(Class beanClass, int flag) + throws IntrospectionException + { + IntrospectionIncubator ii; + BeanInfoEmbryo infoEmbryo; + + switch(flag) + { + case USE_ALL_BEANINFO: + return getBeanInfo(beanClass); + case IGNORE_IMMEDIATE_BEANINFO: + Class superclass = beanClass.getSuperclass(); + ExplicitInfo explicit = new ExplicitInfo(superclass, null); + + ii = new IntrospectionIncubator(); + if (explicit.explicitEventSetDescriptors != null) + ii.setEventStopClass(superclass); + + if (explicit.explicitMethodDescriptors != null) + ii.setMethodStopClass(superclass); + + if (explicit.explicitPropertyDescriptors != null) + ii.setPropertyStopClass(superclass); + + ii.addMethods(beanClass.getMethods()); + + infoEmbryo = ii.getBeanInfoEmbryo(); + merge(infoEmbryo, explicit); + + infoEmbryo.setBeanDescriptor(new BeanDescriptor(beanClass, null)); + + return infoEmbryo.getBeanInfo(); + case IGNORE_ALL_BEANINFO: + default: + ii = new IntrospectionIncubator(); + ii.addMethods(beanClass.getMethods()); + infoEmbryo = ii.getBeanInfoEmbryo(); + infoEmbryo.setBeanDescriptor(new BeanDescriptor(beanClass, null)); + + return infoEmbryo.getBeanInfo(); + } + } /** * Flush all of the Introspector's internal caches. @@ -245,6 +321,69 @@ public class Introspector { } } + /** Adds all explicity given bean info data to the introspected + * data. + * + * @param infoEmbryo Bean info data retrieved by introspection. + * @param explicit Bean info data retrieved by BeanInfo classes. + */ + private static void merge(BeanInfoEmbryo infoEmbryo, ExplicitInfo explicit) + { + PropertyDescriptor[] p = explicit.explicitPropertyDescriptors; + if(p!=null) + { + for(int i=0;i<p.length;i++) + { + if(!infoEmbryo.hasProperty(p[i])) + { + infoEmbryo.addProperty(p[i]); + } + } + + // -1 should be used to denote a missing default property but + // for robustness reasons any value below zero is discarded. + // Not doing so would let Classpath fail where the JDK succeeds. + if(explicit.defaultProperty > -1) + { + infoEmbryo.setDefaultPropertyName(p[explicit.defaultProperty].getName()); + } + } + EventSetDescriptor[] e = explicit.explicitEventSetDescriptors; + if(e!=null) + { + for(int i=0;i<e.length;i++) + { + if(!infoEmbryo.hasEvent(e[i])) + { + infoEmbryo.addEvent(e[i]); + } + } + + // -1 should be used to denote a missing default event but + // for robustness reasons any value below zero is discarded. + // Not doing so would let Classpath fail where the JDK succeeds. + if(explicit.defaultEvent > -1) + { + infoEmbryo.setDefaultEventName(e[explicit.defaultEvent].getName()); + } + } + MethodDescriptor[] m = explicit.explicitMethodDescriptors; + if(m!=null) + { + for(int i=0;i<m.length;i++) + { + if(!infoEmbryo.hasMethod(m[i])) + { + infoEmbryo.addMethod(m[i]); + } + } + } + + infoEmbryo.setAdditionalBeanInfo(explicit.explicitBeanInfo); + infoEmbryo.setIcons(explicit.im); + + } + /** * Get the BeanInfo for class <CODE>beanClass</CODE>, * first by looking for explicit information, next by @@ -268,62 +407,19 @@ public class Introspector { ii.addMethods(beanClass.getMethods()); BeanInfoEmbryo currentInfo = ii.getBeanInfoEmbryo(); - PropertyDescriptor[] p = explicit.explicitPropertyDescriptors; - if(p!=null) - { - for(int i=0;i<p.length;i++) - { - if(!currentInfo.hasProperty(p[i])) - { - currentInfo.addProperty(p[i]); - } - } - if(explicit.defaultProperty != -1) - { - currentInfo.setDefaultPropertyName(p[explicit.defaultProperty].getName()); - } - } - EventSetDescriptor[] e = explicit.explicitEventSetDescriptors; - if(e!=null) - { - for(int i=0;i<e.length;i++) - { - if(!currentInfo.hasEvent(e[i])) - { - currentInfo.addEvent(e[i]); - } - } - if(explicit.defaultEvent != -1) - { - currentInfo.setDefaultEventName(e[explicit.defaultEvent].getName()); - } - } - MethodDescriptor[] m = explicit.explicitMethodDescriptors; - if(m!=null) - { - for(int i=0;i<m.length;i++) - { - if(!currentInfo.hasMethod(m[i])) - { - currentInfo.addMethod(m[i]); - } - } - } - // Sets the info's BeanDescriptor to the one we extracted from the - // explicit BeanInfo instance(s) if they contained one. Otherwise we - // create the BeanDescriptor from scratch. - // Note: We do not create a copy the retrieved BeanDescriptor which will allow - // the user to modify the instance while it is cached. However this is how - // the RI does it. - currentInfo.setBeanDescriptor( - (explicit.explicitBeanDescriptor == null ? - new BeanDescriptor(beanClass, null) : - explicit.explicitBeanDescriptor)); - - currentInfo.setAdditionalBeanInfo(explicit.explicitBeanInfo); - currentInfo.setIcons(explicit.im); + merge(currentInfo, explicit); + // Sets the info's BeanDescriptor to the one we extracted from the + // explicit BeanInfo instance(s) if they contained one. Otherwise we + // create the BeanDescriptor from scratch. + // Note: We do not create a copy the retrieved BeanDescriptor which will allow + // the user to modify the instance while it is cached. However this is how + // the RI does it. + currentInfo.setBeanDescriptor( + (explicit.explicitBeanDescriptor == null ? + new BeanDescriptor(beanClass, null) : + explicit.explicitBeanDescriptor)); return currentInfo.getBeanInfo(); } diff --git a/java/io/PrintStream.java b/java/io/PrintStream.java index a4eade81b..4a0716516 100644 --- a/java/io/PrintStream.java +++ b/java/io/PrintStream.java @@ -1,5 +1,5 @@ /* PrintStream.java -- OutputStream for printing output - Copyright (C) 1998, 1999, 2001, 2003, 2004, 2005 + Copyright (C) 1998, 1999, 2001, 2003, 2004, 2005, 2006 Free Software Foundation, Inc. This file is part of GNU Classpath. @@ -42,6 +42,8 @@ package java.io; import java.util.Locale; import java.util.Formatter; +import gnu.classpath.SystemProperties; + /* Written using "Java Class Libraries", 2nd edition, ISBN 0-201-31002-3 * "The Java Language Specification", ISBN 0-201-63451-1 * Status: Believed complete and correct to 1.3 @@ -69,7 +71,7 @@ public class PrintStream extends FilterOutputStream implements Appendable // Line separator string. private static final char[] line_separator - = System.getProperty("line.separator").toCharArray(); + = SystemProperties.getProperty("line.separator").toCharArray(); /** * Encoding name @@ -117,7 +119,7 @@ public class PrintStream extends FilterOutputStream implements Appendable super (out); try { - this.encoding = System.getProperty("file.encoding"); + this.encoding = SystemProperties.getProperty("file.encoding"); } catch (SecurityException e){ this.encoding = "ISO8859_1"; } catch (IllegalArgumentException e){ diff --git a/java/lang/SecurityManager.java b/java/lang/SecurityManager.java index ff542bc48..c069f3440 100644 --- a/java/lang/SecurityManager.java +++ b/java/lang/SecurityManager.java @@ -41,9 +41,6 @@ package java.lang; import gnu.classpath.VMStackWalker; import java.awt.AWTPermission; -import java.awt.Frame; -import java.awt.Toolkit; -import java.awt.Window; import java.io.File; import java.io.FileDescriptor; import java.io.FileInputStream; @@ -837,7 +834,7 @@ public class SecurityManager * @param window the window to create * @return true if there is permission to show the window without warning * @throws NullPointerException if window is null - * @see Window#Window(Frame) + * @see java.awt.Window#Window(java.awt.Frame) */ public boolean checkTopLevelWindow(Object window) { @@ -862,7 +859,7 @@ public class SecurityManager * an exception. * * @throws SecurityException if permission is denied - * @see Toolkit#getPrintJob(Frame, String, Properties) + * @see java.awt.Toolkit#getPrintJob(java.awt.Frame, String, Properties) * @since 1.1 */ public void checkPrintJobAccess() @@ -878,7 +875,7 @@ public class SecurityManager * rather than throwing an exception. * * @throws SecurityException if permission is denied - * @see Toolkit#getSystemClipboard() + * @see java.awt.Toolkit#getSystemClipboard() * @since 1.1 */ public void checkSystemClipboardAccess() @@ -894,7 +891,7 @@ public class SecurityManager * rather than throwing an exception. * * @throws SecurityException if permission is denied - * @see Toolkit#getSystemEventQueue() + * @see java.awt.Toolkit#getSystemEventQueue() * @since 1.1 */ public void checkAwtEventQueueAccess() diff --git a/java/net/InetAddress.java b/java/net/InetAddress.java index 89d46afb7..7277331bb 100644 --- a/java/net/InetAddress.java +++ b/java/net/InetAddress.java @@ -43,7 +43,6 @@ import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.ObjectStreamException; import java.io.Serializable; -import java.util.HashMap; import java.util.StringTokenizer; /** @@ -66,22 +65,6 @@ public class InetAddress implements Serializable private static final long serialVersionUID = 3286316764910316507L; /** - * The default DNS hash table size, - * Use a prime number happy with hash table. - */ - private static final int DEFAULT_CACHE_SIZE = 89; - - /** - * The default caching period in minutes. - */ - private static final int DEFAULT_CACHE_PERIOD = 4 * 60; - - /** - * Percentage of cache entries to purge when the table gets full. - */ - private static final int DEFAULT_CACHE_PURGE_PCT = 30; - - /** * The special IP address INADDR_ANY. */ private static InetAddress inaddr_any; @@ -96,50 +79,8 @@ public class InetAddress implements Serializable */ static InetAddress LOCALHOST; - /** - * The size of the cache. - */ - private static int cache_size = 0; - - /** - * The length of time we will continue to read the address from cache - * before forcing another lookup. - */ - private static int cache_period = 0; - - /** - * What percentage of the cache we will purge if it gets full. - */ - private static int cache_purge_pct = 0; - - /** - * HashMap to use as DNS lookup cache. - * Use HashMap because all accesses to cache are already synchronized. - */ - private static HashMap cache; - static { - // Look for properties that override default caching behavior - cache_size = - Integer.getInteger("gnu.java.net.dns_cache_size", DEFAULT_CACHE_SIZE) - .intValue(); - cache_period = - Integer.getInteger("gnu.java.net.dns_cache_period", - DEFAULT_CACHE_PERIOD * 60 * 1000).intValue(); - - cache_purge_pct = - Integer.getInteger("gnu.java.net.dns_cache_purge_pct", - DEFAULT_CACHE_PURGE_PCT).intValue(); - - // Fallback to defaults if necessary - if ((cache_purge_pct < 1) || (cache_purge_pct > 100)) - cache_purge_pct = DEFAULT_CACHE_PURGE_PCT; - - // Create the cache - if (cache_size != 0) - cache = new HashMap(cache_size); - // precompute the ANY_IF address try { @@ -174,11 +115,6 @@ public class InetAddress implements Serializable String hostName; /** - * The time this address was looked up. - */ - transient long lookup_time; - - /** * The field 'family' seems to be the AF_ value. * FIXME: Much of the code in the other java.net classes does not make * use of this family field. A better implementation would be to make @@ -200,8 +136,6 @@ public class InetAddress implements Serializable addr = (null == ipaddr) ? null : (byte[]) ipaddr.clone(); hostName = hostname; - lookup_time = System.currentTimeMillis(); - family = 2; /* AF_INET */ } @@ -660,12 +594,6 @@ public class InetAddress implements Serializable return addresses; } - // Check the cache for this host before doing a lookup - addresses = checkCacheFor(hostname); - - if (addresses != null) - return addresses; - // Not in cache, try the lookup byte[][] iplist = VMInetAddress.getHostByName(hostname); @@ -682,71 +610,10 @@ public class InetAddress implements Serializable addresses[i] = new Inet4Address(iplist[i], hostname); } - addToCache(hostname, addresses); return addresses; } /** - * This method checks the DNS cache to see if we have looked this hostname - * up before. If so, we return the cached addresses unless it has been in the - * cache too long. - * - * @param hostname The hostname to check for - * - * @return The InetAddress for this hostname or null if not available - */ - private static synchronized InetAddress[] checkCacheFor(String hostname) - { - InetAddress[] addresses = null; - - if (cache_size == 0) - return null; - - Object obj = cache.get(hostname); - if (obj == null) - return null; - - if (obj instanceof InetAddress[]) - addresses = (InetAddress[]) obj; - - if (addresses == null) - return null; - - if (cache_period != -1) - if ((System.currentTimeMillis() - addresses[0].lookup_time) > cache_period) - { - cache.remove(hostname); - return null; - } - - return addresses; - } - - /** - * This method adds an InetAddress object to our DNS cache. Note that - * if the cache is full, then we run a purge to get rid of old entries. - * This will cause a performance hit, thus applications using lots of - * lookups should set the cache size to be very large. - * - * @param hostname The hostname to cache this address under - * @param obj The InetAddress or InetAddress array to store - */ - private static synchronized void addToCache(String hostname, Object obj) - { - if (cache_size == 0) - return; - - // Check to see if hash table is full - if (cache_size != -1) - if (cache.size() == cache_size) - { - // FIXME Add code to purge later. - } - - cache.put(hostname, obj); - } - - /** * Returns the special address INADDR_ANY used for binding to a local * port on all IP addresses hosted by a the local host. * diff --git a/java/net/URL.java b/java/net/URL.java index fdd6a46b4..168c67a19 100644 --- a/java/net/URL.java +++ b/java/net/URL.java @@ -1,5 +1,5 @@ /* URL.java -- Uniform Resource Locator Class - Copyright (C) 1998, 1999, 2000, 2002, 2003, 2004, 2005 + Copyright (C) 1998, 1999, 2000, 2002, 2003, 2004, 2005, 2006 Free Software Foundation, Inc. This file is part of GNU Classpath. @@ -38,6 +38,7 @@ exception statement from your version. */ package java.net; +import gnu.classpath.SystemProperties; import gnu.java.net.URLParseError; import java.io.IOException; @@ -198,7 +199,7 @@ public final class URL implements Serializable static { - String s = System.getProperty("gnu.java.net.nocache_protocol_handlers"); + String s = SystemProperties.getProperty("gnu.java.net.nocache_protocol_handlers"); if (s == null) cache_handlers = true; @@ -867,7 +868,7 @@ public final class URL implements Serializable // Except in very unusual environments the JDK specified one shouldn't // ever be needed (or available). String ph_search_path = - System.getProperty("java.protocol.handler.pkgs"); + SystemProperties.getProperty("java.protocol.handler.pkgs"); // Tack our default package on at the ends. if (ph_search_path != null) diff --git a/java/nio/charset/spi/CharsetProvider.java b/java/nio/charset/spi/CharsetProvider.java index 5a3bbd9fd..03653f807 100644 --- a/java/nio/charset/spi/CharsetProvider.java +++ b/java/nio/charset/spi/CharsetProvider.java @@ -1,5 +1,5 @@ /* CharsetProvider.java -- charset service provider interface - Copyright (C) 2002, 2005 Free Software Foundation + Copyright (C) 2002, 2005, 2006 Free Software Foundation This file is part of GNU Classpath. @@ -67,8 +67,12 @@ public abstract class CharsetProvider */ protected CharsetProvider() { + // We only do the security check for custom providers, not for the + // built in ones. SecurityManager s = System.getSecurityManager(); - if (s != null) + if (s != null && + ! (this instanceof gnu.java.nio.charset.Provider + || this instanceof gnu.java.nio.charset.iconv.IconvProvider)) s.checkPermission(new RuntimePermission("charsetProvider")); } diff --git a/java/security/Security.java b/java/security/Security.java index 6266300c0..d8d746b05 100644 --- a/java/security/Security.java +++ b/java/security/Security.java @@ -1,5 +1,6 @@ /* Security.java --- Java base security class implementation - Copyright (C) 1999, 2001, 2002, 2003, 2004, 2005 Free Software Foundation, Inc. + Copyright (C) 1999, 2001, 2002, 2003, 2004, 2005, 2006 + Free Software Foundation, Inc. This file is part of GNU Classpath. @@ -41,6 +42,7 @@ package java.security; import gnu.classpath.SystemProperties; import gnu.classpath.Configuration; +import gnu.classpath.VMStackWalker; import java.io.IOException; import java.io.InputStream; @@ -391,8 +393,11 @@ public final class Security */ public static String getProperty(String key) { + // XXX To prevent infinite recursion when the SecurityManager calls us, + // don't do a security check if the caller is trusted (by virtue of having + // been loaded by the bootstrap class loader). SecurityManager sm = System.getSecurityManager(); - if (sm != null) + if (sm != null && VMStackWalker.getCallingClassLoader() != null) sm.checkSecurityAccess("getProperty." + key); return secprops.getProperty(key); diff --git a/java/util/AbstractMap.java b/java/util/AbstractMap.java index 6e19e4086..9b543b026 100644 --- a/java/util/AbstractMap.java +++ b/java/util/AbstractMap.java @@ -600,13 +600,13 @@ public abstract class AbstractMap<K, V> implements Map<K, V> * * @param o1 the first object * @param o2 the second object - * @return o1 == null ? o2 == null : o1.equals(o2) + * @return o1 == o2 || (o1 != null && o1.equals(o2)) */ // Package visible for use throughout java.util. // It may be inlined since it is final. static final boolean equals(Object o1, Object o2) { - return o1 == null ? o2 == null : o1.equals(o2); + return o1 == o2 || (o1 != null && o1.equals(o2)); } /** diff --git a/java/util/ArrayList.java b/java/util/ArrayList.java index 6bbf3d01b..0693049b5 100644 --- a/java/util/ArrayList.java +++ b/java/util/ArrayList.java @@ -92,7 +92,7 @@ public class ArrayList<E> extends AbstractList<E> /** * The default capacity for new ArrayLists. */ - private static final int DEFAULT_CAPACITY = 16; + private static final int DEFAULT_CAPACITY = 10; /** * The number of elements in this list. diff --git a/java/util/StringTokenizer.java b/java/util/StringTokenizer.java index 3d4e55890..0b59abe2f 100644 --- a/java/util/StringTokenizer.java +++ b/java/util/StringTokenizer.java @@ -132,8 +132,7 @@ public class StringTokenizer implements Enumeration<Object> { len = str.length(); this.str = str; - // The toString() hack causes the NullPointerException. - this.delim = delim.toString(); + this.delim = delim; this.retDelims = returnDelims; this.pos = 0; } diff --git a/java/util/WeakHashMap.java b/java/util/WeakHashMap.java index c38d7e3aa..4114ed97d 100644 --- a/java/util/WeakHashMap.java +++ b/java/util/WeakHashMap.java @@ -477,7 +477,7 @@ public class WeakHashMap<K,V> extends AbstractMap<K,V> if (o instanceof Map.Entry) { Map.Entry e = (Map.Entry) o; - return key.equals(e.getKey()) + return WeakHashMap.equals(getKey(), e.getKey()) && WeakHashMap.equals(value, e.getValue()); } return false; @@ -485,7 +485,7 @@ public class WeakHashMap<K,V> extends AbstractMap<K,V> public String toString() { - return key + "=" + value; + return getKey() + "=" + value; } } @@ -659,7 +659,7 @@ public class WeakHashMap<K,V> extends AbstractMap<K,V> while (bucket != null) { WeakBucket.WeakEntry entry = bucket.getEntry(); - if (entry != null && key.equals(entry.key)) + if (entry != null && equals(key, entry.key)) return entry; bucket = bucket.next; diff --git a/java/util/regex/Pattern.java b/java/util/regex/Pattern.java index 6a31ef9bf..d39f1cfb0 100644 --- a/java/util/regex/Pattern.java +++ b/java/util/regex/Pattern.java @@ -103,8 +103,11 @@ public final class Pattern implements Serializable } catch (REException e) { - throw new PatternSyntaxException(e.getMessage(), + PatternSyntaxException pse; + pse = new PatternSyntaxException(e.getMessage(), regex, e.getPosition()); + pse.initCause(e); + throw pse; } } diff --git a/javax/management/Attribute.java b/javax/management/Attribute.java index 376779b69..5c4a65e40 100644 --- a/javax/management/Attribute.java +++ b/javax/management/Attribute.java @@ -40,7 +40,7 @@ package javax.management; import java.io.Serializable; /** - * Represents an MBean attribute, having the name and the assined value. The + * Represents an MBean attribute, having the name and the assigned value. The * MBean objects use this class to get and set attributes values. * * @since 1.5 @@ -129,8 +129,8 @@ public class Attribute */ public int hashCode() { - int n = m_name==null?0:m_name.hashCode(); - int v = m_value==null?0:m_value.hashCode(); + int n = m_name == null ? 0 : m_name.hashCode(); + int v = m_value == null ? 0 : m_value.hashCode(); return n ^ v; } diff --git a/javax/swing/JMenuItem.java b/javax/swing/JMenuItem.java index c3c10d6ef..b2cfbd14a 100644 --- a/javax/swing/JMenuItem.java +++ b/javax/swing/JMenuItem.java @@ -1,5 +1,5 @@ /* JMenuItem.java -- - Copyright (C) 2002, 2004, 2005 Free Software Foundation, Inc. + Copyright (C) 2002, 2004, 2005,2006 Free Software Foundation, Inc. This file is part of GNU Classpath. @@ -119,10 +119,21 @@ public class JMenuItem extends AbstractButton implements Accessible, init(null, null); if (action != null) { - setName((String) action.getValue(Action.NAME)); - setAccelerator((KeyStroke) action.getValue(Action.ACCELERATOR_KEY)); - setMnemonic(((Integer) action.getValue(Action.MNEMONIC_KEY)).intValue()); - setActionCommand((String) action.getValue(Action.ACTION_COMMAND_KEY)); + String name = (String) action.getValue(Action.NAME); + if (name != null) + setName(name); + + KeyStroke accel = (KeyStroke) action.getValue(Action.ACCELERATOR_KEY); + if (accel != null) + setAccelerator(accel); + + Integer mnemonic = (Integer) action.getValue(Action.MNEMONIC_KEY); + if (mnemonic != null) + setMnemonic(mnemonic.intValue()); + + String command = (String) action.getValue(Action.ACTION_COMMAND_KEY); + if (command != null) + setActionCommand(command); } } diff --git a/javax/swing/JTabbedPane.java b/javax/swing/JTabbedPane.java index 8e32ebdf8..8a7d4c07f 100644 --- a/javax/swing/JTabbedPane.java +++ b/javax/swing/JTabbedPane.java @@ -497,7 +497,7 @@ public class JTabbedPane extends JComponent implements Serializable, */ public int getMnemonic() { - return (int) mnemonicKey; + return mnemonicKey; } /** @@ -592,9 +592,11 @@ public class JTabbedPane extends JComponent implements Serializable, /** * Creates a new JTabbedPane object using wrap tab layout and the given - * tabPlacement. + * <code>tabPlacement</code>, where <code>tabPlacement</code> can be one + * of the following values: {@link #TOP}, {@link #BOTTOM}, {@link #LEFT} or + * {@link #RIGHT}. * - * @param tabPlacement Where the tabs will be placed. + * @param tabPlacement where the tabs will be placed */ public JTabbedPane(int tabPlacement) { @@ -602,11 +604,14 @@ public class JTabbedPane extends JComponent implements Serializable, } /** - * Creates a new JTabbedPane object with the given tabPlacement and - * tabLayoutPolicy. + * Creates a new JTabbedPane object with the given <code>tabPlacement</code> + * and <code>tabLayoutPolicy</code>. The <code>tabPlacement</code> can be one + * of the following values: {@link #TOP}, {@link #BOTTOM}, {@link #LEFT} or + * {@link #RIGHT}. The <code>tabLayoutPolicy</code> can be either + * {@link #SCROLL_TAB_LAYOUT} or {@link #WRAP_TAB_LAYOUT}. * - * @param tabPlacement Where the tabs will be placed. - * @param tabLayoutPolicy The way tabs will be placed. + * @param tabPlacement where the tabs will be placed + * @param tabLayoutPolicy the way tabs will be placed * * @throws IllegalArgumentException If tabLayoutPolicy or tabPlacement are * not valid. diff --git a/javax/swing/JTextField.java b/javax/swing/JTextField.java index 8dc2f2569..c49031061 100644 --- a/javax/swing/JTextField.java +++ b/javax/swing/JTextField.java @@ -203,9 +203,22 @@ public class JTextField extends JTextComponent */ protected Document createDefaultModel() { - PlainDocument doc = new PlainDocument(); + return new PlainDocument(); + } + + /** + * Sets the document to be used for this JTextField. + * + * This sets the document property <code>filterNewlines</code> to + * <code>true</code> and then calls the super behaviour to setup a view and + * revalidate the text field. + * + * @param doc the document to set + */ + public void setDocument(Document doc) + { doc.putProperty("filterNewlines", Boolean.TRUE); - return doc; + super.setDocument(doc); } /** diff --git a/javax/swing/JViewport.java b/javax/swing/JViewport.java index 3a1632730..debb5742e 100644 --- a/javax/swing/JViewport.java +++ b/javax/swing/JViewport.java @@ -259,7 +259,6 @@ public class JViewport extends JComponent implements Accessible String scrollModeProp = SystemProperties.getProperty("gnu.javax.swing.JViewport.scrollMode", "BLIT"); - int myScrollMode; if (scrollModeProp.equalsIgnoreCase("simple")) defaultScrollMode = SIMPLE_SCROLL_MODE; else if (scrollModeProp.equalsIgnoreCase("backingstore")) diff --git a/javax/swing/RepaintManager.java b/javax/swing/RepaintManager.java index 385fe7925..0be81053d 100644 --- a/javax/swing/RepaintManager.java +++ b/javax/swing/RepaintManager.java @@ -536,8 +536,8 @@ public class RepaintManager { Component comp = (Component) i.next(); // Find validate root. - while (!(comp instanceof JComponent) - || !((JComponent) comp).isValidateRoot() + while ((!(comp instanceof JComponent) + || !((JComponent) comp).isValidateRoot()) && comp.getParent() != null) comp = comp.getParent(); diff --git a/javax/swing/TransferHandler.java b/javax/swing/TransferHandler.java index 6115043ed..830feee83 100644 --- a/javax/swing/TransferHandler.java +++ b/javax/swing/TransferHandler.java @@ -54,6 +54,7 @@ public class TransferHandler implements Serializable public TransferAction(String command) { + super(command); this.command = command; } diff --git a/javax/swing/ViewportLayout.java b/javax/swing/ViewportLayout.java index 54935a89f..79fd26c56 100644 --- a/javax/swing/ViewportLayout.java +++ b/javax/swing/ViewportLayout.java @@ -145,9 +145,9 @@ public class ViewportLayout implements LayoutManager, Serializable portBounds.y + portBounds.height); // vertical implementation of the above rules - if ((! (view instanceof Scrollable) - || ((Scrollable) view).getScrollableTracksViewportHeight()) - && viewPref.height < portBounds.height) + if ((! (view instanceof Scrollable) && viewPref.height < portBounds.height + || (view instanceof Scrollable + && ((Scrollable) view).getScrollableTracksViewportHeight()))) viewPref.height = portBounds.height; if (portBounds.height >= viewMinimum.height) @@ -160,9 +160,9 @@ public class ViewportLayout implements LayoutManager, Serializable } // horizontal implementation of the above rules - if ((! (view instanceof Scrollable) - || ((Scrollable) view).getScrollableTracksViewportWidth()) - && viewPref.width < portBounds.width) + if ((! (view instanceof Scrollable) && viewPref.width < portBounds.width + || (view instanceof Scrollable + && ((Scrollable) view).getScrollableTracksViewportWidth()))) viewPref.width = portBounds.width; if (portBounds.width >= viewMinimum.width) diff --git a/javax/swing/plaf/ComponentUI.java b/javax/swing/plaf/ComponentUI.java index 6a736f258..be7b68a44 100644 --- a/javax/swing/plaf/ComponentUI.java +++ b/javax/swing/plaf/ComponentUI.java @@ -41,7 +41,6 @@ package javax.swing.plaf; import java.awt.Color; import java.awt.Dimension; import java.awt.Graphics; -import java.awt.Rectangle; import javax.accessibility.Accessible; import javax.swing.JComponent; @@ -185,12 +184,12 @@ public abstract class ComponentUI public void update(Graphics g, JComponent c) { if (c.isOpaque()) - { - Color oldColor = g.getColor(); - g.setColor(c.getBackground()); - g.fillRect(0, 0, c.getWidth(), c.getHeight()); - g.setColor(oldColor); - } + { + Color oldColor = g.getColor(); + g.setColor(c.getBackground()); + g.fillRect(0, 0, c.getWidth(), c.getHeight()); + g.setColor(oldColor); + } paint(g, c); } diff --git a/javax/swing/plaf/basic/BasicListUI.java b/javax/swing/plaf/basic/BasicListUI.java index 593e7780f..00d157a62 100644 --- a/javax/swing/plaf/basic/BasicListUI.java +++ b/javax/swing/plaf/basic/BasicListUI.java @@ -894,7 +894,7 @@ public class BasicListUI extends ListUI */ protected void maybeUpdateLayoutState() { - if (updateLayoutStateNeeded != 0) + if (updateLayoutStateNeeded != 0 || !list.isValid()) { updateLayoutState(); updateLayoutStateNeeded = 0; diff --git a/javax/swing/plaf/basic/BasicLookAndFeel.java b/javax/swing/plaf/basic/BasicLookAndFeel.java index 2cbca5d30..f5217be1f 100644 --- a/javax/swing/plaf/basic/BasicLookAndFeel.java +++ b/javax/swing/plaf/basic/BasicLookAndFeel.java @@ -1498,6 +1498,8 @@ public abstract class BasicLookAndFeel extends LookAndFeel * <code>AuditoryCues.playList</code>. * * @param audioAction the audio action to play + * + * @since 1.4 */ protected void playSound(Action audioAction) { diff --git a/javax/swing/plaf/basic/BasicSplitPaneDivider.java b/javax/swing/plaf/basic/BasicSplitPaneDivider.java index a6369c2e3..ff17ff084 100644 --- a/javax/swing/plaf/basic/BasicSplitPaneDivider.java +++ b/javax/swing/plaf/basic/BasicSplitPaneDivider.java @@ -45,7 +45,6 @@ import java.awt.Dimension; import java.awt.Graphics; import java.awt.Insets; import java.awt.LayoutManager; -import java.awt.Point; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.event.MouseMotionListener; @@ -589,7 +588,7 @@ public class BasicSplitPaneDivider extends Container public void mouseReleased(MouseEvent e) { if (isDragging) - dragger.completeDrag(e); + dragger.completeDrag(e); isDragging = false; } @@ -602,7 +601,7 @@ public class BasicSplitPaneDivider extends Container public void mouseDragged(MouseEvent e) { if (dragger != null) - dragger.continueDrag(e); + dragger.continueDrag(e); } /** diff --git a/javax/swing/plaf/metal/MetalFileChooserUI.java b/javax/swing/plaf/metal/MetalFileChooserUI.java index 65e54cf42..967c40d29 100644 --- a/javax/swing/plaf/metal/MetalFileChooserUI.java +++ b/javax/swing/plaf/metal/MetalFileChooserUI.java @@ -647,8 +647,16 @@ public class MetalFileChooserUI { FileView v = getFileView(getFileChooser()); File f = (File) value; - setText(v.getName(f)); - setIcon(v.getIcon(f)); + if (f != null) + { + setText(v.getName(f)); + setIcon(v.getIcon(f)); + } + else + { + setText(""); + setIcon(null); + } setOpaque(true); if (isSelected) { diff --git a/javax/swing/text/DefaultCaret.java b/javax/swing/text/DefaultCaret.java index 0d00bf8d5..45bb33e60 100644 --- a/javax/swing/text/DefaultCaret.java +++ b/javax/swing/text/DefaultCaret.java @@ -1,5 +1,5 @@ /* DefaultCaret.java -- - Copyright (C) 2002, 2004, 2005 Free Software Foundation, Inc. + Copyright (C) 2002, 2004, 2005, 2006 Free Software Foundation, Inc. This file is part of GNU Classpath. @@ -668,8 +668,10 @@ public class DefaultCaret extends Rectangle } catch (BadLocationException e) { - assert false : "Unexpected bad caret location: " + dot; - return; + AssertionError ae; + ae = new AssertionError("Unexpected bad caret location: " + dot); + ae.initCause(e); + throw ae; } if (rect == null) @@ -863,13 +865,17 @@ public class DefaultCaret extends Rectangle visible = true; Rectangle area = null; + int dot = getDot(); try { - area = getComponent().modelToView(getDot()); + area = getComponent().modelToView(dot); } - catch (BadLocationException ex) + catch (BadLocationException e) { - assert false : "Unexpected bad caret location: " + getDot(); + AssertionError ae; + ae = new AssertionError("Unexpected bad caret location: " + dot); + ae.initCause(e); + throw ae; } if (area != null) damage(area); @@ -902,13 +908,17 @@ public class DefaultCaret extends Rectangle visible = v; updateTimerStatus(); Rectangle area = null; + int dot = getDot(); try { - area = getComponent().modelToView(getDot()); + area = getComponent().modelToView(dot); } - catch (BadLocationException ex) + catch (BadLocationException e) { - assert false: "Unexpected bad caret location: " + getDot(); + AssertionError ae; + ae = new AssertionError("Unexpected bad caret location: " + dot); + ae.initCause(e); + throw ae; } if (area != null) damage(area); diff --git a/javax/swing/text/DefaultStyledDocument.java b/javax/swing/text/DefaultStyledDocument.java index 1df77b44d..bc459b5d4 100644 --- a/javax/swing/text/DefaultStyledDocument.java +++ b/javax/swing/text/DefaultStyledDocument.java @@ -367,7 +367,6 @@ public class DefaultStyledDocument extends AbstractDocument public String toString() { StringBuilder b = new StringBuilder(); - b.append('<'); switch (type) { case StartTagType: @@ -780,22 +779,74 @@ public class DefaultStyledDocument extends AbstractDocument * {@link #insert}. * * @param data the element specifications for the elements to be inserte - */ + */ protected void insertUpdate(ElementSpec[] data) { + if (data[0].getType() == ElementSpec.EndTagType) + { + // fracture deepest child here + BranchElement paragraph = (BranchElement) elementStack.peek(); + Element curr = paragraph.getParentElement(); + int index = curr.getElementIndex(offset); + while (!curr.isLeaf()) + { + index = curr.getElementIndex(offset); + curr = curr.getElement(index); + } + Element parent = curr.getParentElement(); + Element newEl1 = createLeafElement(parent, + curr.getAttributes(), + curr.getStartOffset(), offset); + Element grandParent = parent.getParentElement(); + BranchElement nextBranch = + (BranchElement) grandParent.getElement + (grandParent.getElementIndex(parent.getEndOffset())); + Element firstLeaf = nextBranch.getElement(0); + while (!firstLeaf.isLeaf()) + { + firstLeaf = firstLeaf.getElement(0); + } + BranchElement parent2 = (BranchElement) firstLeaf.getParentElement(); + Element newEl2 = + createLeafElement(parent2, + firstLeaf.getAttributes(), + offset, firstLeaf.getEndOffset()); + parent2.replace(0, 1, new Element[] { newEl2 }); + + + ((BranchElement) parent). + replace(index, 1, new Element[] { newEl1 }); + } + for (int i = 0; i < data.length; i++) { + BranchElement paragraph = (BranchElement) elementStack.peek(); switch (data[i].getType()) { case ElementSpec.StartTagType: - numStartTags++; - documentEvent.modified = true; + switch (data[i].getDirection()) + { + case ElementSpec.JoinFractureDirection: + insertFracture(data[i]); + break; + case ElementSpec.JoinNextDirection: + int index = paragraph.getElementIndex(offset); + elementStack.push(paragraph.getElement(index)); + break; + case ElementSpec.OriginateDirection: + Element current = (Element) elementStack.peek(); + Element newParagraph = + insertParagraph((BranchElement) current, offset); + elementStack.push(newParagraph); + break; + default: + break; + } break; case ElementSpec.EndTagType: - numEndTags++; - documentEvent.modified = true; + elementStack.pop(); break; - default: + case ElementSpec.ContentType: insertContentTag(data[i]); break; } @@ -889,8 +940,87 @@ public class DefaultStyledDocument extends AbstractDocument } /** + * Inserts a fracture into the document structure. + * + * @param tag - the element spec. + */ + private void insertFracture(ElementSpec tag) + { + // This is the parent of the paragraph about to be fractured. We will + // create a new child of this parent. + BranchElement parent = (BranchElement) elementStack.peek(); + int parentIndex = parent.getElementIndex(offset); + + // This is the old paragraph. We must remove all its children that + // occur after offset and move them to a new paragraph. We must + // also recreate its child that occurs at offset to have the proper + // end offset. The remainder of this child will also go in the new + // paragraph. + BranchElement previous = (BranchElement) parent.getElement(parentIndex); + + // This is the new paragraph. + BranchElement newBranch = + (BranchElement) createBranchElement(parent, previous.getAttributes()); + + + // The steps we must take to properly fracture are: + // 1. Recreate the LeafElement at offset to have the correct end offset. + // 2. Create a new LeafElement with the remainder of the LeafElement in + // #1 ==> this is whatever was in that LeafElement to the right of the + // inserted newline. + // 3. Find the paragraph at offset and remove all its children that + // occur _after_ offset. These will be moved to the newly created + // paragraph. + // 4. Move the LeafElement created in #2 and all the LeafElements removed + // in #3 to the newly created paragraph. + // 5. Add the new paragraph to the parent. + int previousIndex = previous.getElementIndex(offset); + int numReplaced = previous.getElementCount() - previousIndex; + Element previousLeaf = previous.getElement(previousIndex); + AttributeSet prevLeafAtts = previous.getAttributes(); + + // This recreates the child at offset to have the proper end offset. + // (Step 1). + Element newPreviousLeaf = + createLeafElement(previous, + prevLeafAtts, previousLeaf.getStartOffset(), + offset); + // This creates the new child, which is the remainder of the old child. + // (Step 2). + + Element firstLeafInNewBranch = + createLeafElement(newBranch, prevLeafAtts, + offset, previousLeaf.getEndOffset()); + + // Now we move the new LeafElement and all the old children that occurred + // after the offset to the new paragraph. (Step 4). + Element[] newLeaves = new Element[numReplaced]; + newLeaves[0] = firstLeafInNewBranch; + for (int i = 1; i < numReplaced; i++) + newLeaves[i] = previous.getElement(previousIndex + i); + newBranch.replace(0, 0, newLeaves); + addEdit(newBranch, 0, null, newLeaves); + + // Now we remove the children after the offset from the previous + // paragraph. (Step 3). + int removeSize = previous.getElementCount() - previousIndex; + Element[] add = new Element[] { newPreviousLeaf }; + Element[] remove = new Element[removeSize]; + for (int j = 0; j < removeSize; j++) + remove[j] = previous.getElement(previousIndex + j); + previous.replace(previousIndex, removeSize, add); + addEdit(previous, previousIndex, remove, add); + + // Finally we add the new paragraph to the parent. (Step 5). + Element[] nb = new Element[] { newBranch }; + int index = parentIndex + 1; + parent.replace(index, 0, nb); + addEdit(parent, index, null, nb); + } + + /** * Inserts a content element into the document structure. - * + * * @param tag the element spec */ private void insertContentTag(ElementSpec tag) @@ -908,32 +1038,37 @@ public class DefaultStyledDocument extends AbstractDocument } else if (dir == ElementSpec.JoinNextDirection) { + // FIXME: + // Have to handle JoinNext differently depending on whether + // or not it comes after a fracture. If comes after a fracture, + // the insertFracture method takes care of everything and nothing + // needs to be done here. Otherwise, we need to adjust the + // Element structure. For now, I check if the elementStack's + // top Element is the immediate parent of the LeafElement at + // offset - if so, we did not come immediately after a + // fracture. This seems awkward and should probably be improved. + // We may be doing too much in insertFracture because we are + // adjusting the offsets, the correct thing to do may be to + // create a new branch element and push it on to element stack + // and then this method here can be more general. + BranchElement paragraph = (BranchElement) elementStack.peek(); - int currentIndex = paragraph.getElementIndex(offset); - Element current = paragraph.getElement(currentIndex); - Element next = paragraph.getElement(currentIndex + 1); - - if (next == null) - return; - - Element newEl1 = createLeafElement(paragraph, - current.getAttributes(), - current.getStartOffset(), - offset); - Element newEl2 = createLeafElement(paragraph, - current.getAttributes(), - offset, - next.getEndOffset()); - - Element[] add = new Element[] { newEl1, newEl2 }; - Element[] remove = new Element[] { current, next }; - paragraph.replace(currentIndex, 2, add); - // Add this action to the document event. - addEdit(paragraph, currentIndex, remove, add); - } - else if (dir == ElementSpec.JoinFractureDirection) - { - // TODO: What should be done here? + int index = paragraph.getElementIndex(offset); + Element target = paragraph.getElement(index); + if (target.isLeaf() && paragraph.getElementCount() > (index + 1)) + { + Element next = paragraph.getElement(index + 1); + Element newEl1 = createLeafElement(paragraph, + target.getAttributes(), + target.getStartOffset(), + offset); + Element newEl2 = createLeafElement(paragraph, + next.getAttributes(), offset, + next.getEndOffset()); + Element[] add = new Element[] { newEl1, newEl2 }; + paragraph.replace (index, 2, add); + addEdit(paragraph, index, new Element[] { target, next }, add); + } } else if (dir == ElementSpec.OriginateDirection) { @@ -1236,7 +1371,6 @@ public class DefaultStyledDocument extends AbstractDocument SectionElement section = new SectionElement(); BranchElement paragraph = new BranchElement(section, null); - paragraph.setResolveParent(getStyle(StyleContext.DEFAULT_STYLE)); tmp = new Element[1]; tmp[0] = paragraph; section.replace(0, 0, tmp); @@ -1652,11 +1786,25 @@ public class DefaultStyledDocument extends AbstractDocument // If we are inserting after a newline then this value comes from // handleInsertAfterNewline. if (finalStartTag != null) - { + { if (prevCharWasNewline) finalStartTag.setDirection(finalStartDirection); else if (prevParagraph.getEndOffset() != endOffset) - finalStartTag.setDirection(ElementSpec.JoinFractureDirection); + { + try + { + String last = getText(endOffset - 1, 1); + if (!last.equals("\n")) + finalStartTag.setDirection(ElementSpec.JoinFractureDirection); + } + catch (BadLocationException ble) + { + // This shouldn't happen. + AssertionError ae = new AssertionError(); + ae.initCause(ble); + throw ae; + } + } else { // If there is an element AFTER this one, then set the @@ -1671,10 +1819,33 @@ public class DefaultStyledDocument extends AbstractDocument // If we are at the last index, then check if we could probably be // joined with the next element. - ElementSpec last = (ElementSpec) specs.lastElement(); - if (next.getAttributes().isEqual(attr) - && last.getType() == ElementSpec.ContentType) - last.setDirection(ElementSpec.JoinNextDirection); + // This means: + // - we must be a ContentTag + // - if there is a next Element, we must have the same attributes + // - if there is no next Element, but one will be created, + // we must have the same attributes as the higher-level run. + ElementSpec last = (ElementSpec) specs.lastElement(); + if (last.getType() == ElementSpec.ContentType) + { + Element currentRun = + prevParagraph.getElement(prevParagraph.getElementIndex(offset)); + if (currentRun.getEndOffset() == endOffset) + { + if (endOffset < getLength() && next.getAttributes().isEqual(attr) + && last.getType() == ElementSpec.ContentType) + last.setDirection(ElementSpec.JoinNextDirection); + } + else + { + if (finalStartTag != null + && finalStartTag.getDirection() == + ElementSpec.JoinFractureDirection + && currentRun.getAttributes().isEqual(attr)) + { + last.setDirection(ElementSpec.JoinNextDirection); + } + } + } // If we are at the first new element, then check if it could be // joined with the previous element. @@ -1789,6 +1960,8 @@ public class DefaultStyledDocument extends AbstractDocument protected void insert(int offset, ElementSpec[] data) throws BadLocationException { + if (data == null || data.length == 0) + return; try { // writeLock() and writeUnlock() should always be in a try/finally @@ -1824,18 +1997,11 @@ public class DefaultStyledDocument extends AbstractDocument DocumentEvent.EventType.INSERT); ev.addEdit(edit); - for (int i = 0; i < data.length; i++) - { - ElementSpec spec = data[i]; - AttributeSet atts = spec.getAttributes(); - if (atts != null) - insertUpdate(ev, atts); - } - // Finally we must update the document structure and fire the insert // update event. buffer.insert(offset, length, data, ev); fireInsertUpdate(ev); + fireUndoableEditUpdate(new UndoableEditEvent(this, ev)); } finally { diff --git a/javax/swing/text/GapContent.java b/javax/swing/text/GapContent.java index c0f9beae2..cce7a8a27 100644 --- a/javax/swing/text/GapContent.java +++ b/javax/swing/text/GapContent.java @@ -131,11 +131,11 @@ public class GapContent } } - class UndoInsertString extends AbstractUndoableEdit + class InsertUndo extends AbstractUndoableEdit { public int where, length; String text; - public UndoInsertString(int start, int len) + public InsertUndo(int start, int len) { where = start; length = len; @@ -317,7 +317,7 @@ public class GapContent replace(where, 0, str.toCharArray(), strLen); - return new UndoInsertString(where, strLen); + return new InsertUndo(where, strLen); } /** diff --git a/javax/swing/text/PlainDocument.java b/javax/swing/text/PlainDocument.java index 0c00a06ff..2200cae80 100644 --- a/javax/swing/text/PlainDocument.java +++ b/javax/swing/text/PlainDocument.java @@ -113,6 +113,46 @@ public class PlainDocument extends AbstractDocument int elementIndex = rootElement.getElementIndex(offset); Element firstElement = rootElement.getElement(elementIndex); + // If we're inserting immediately after a newline we have to fix the + // Element structure. + if (offset > 0) + { + try + { + String s = getText(offset - 1, 1); + if (s.equals("\n")) + { + int newEl2EndOffset = end; + boolean replaceNext = false; + if (rootElement.getElementCount() > elementIndex + 1) + { + replaceNext = true; + newEl2EndOffset = + rootElement.getElement(elementIndex + 1).getEndOffset(); + } + Element newEl1 = + createLeafElement(rootElement, firstElement.getAttributes(), + firstElement.getStartOffset(), offset); + Element newEl2 = + createLeafElement (rootElement, firstElement.getAttributes(), + offset, newEl2EndOffset); + if (replaceNext) + rootElement.replace(elementIndex, 2, new Element[] { newEl1, newEl2 }); + else + rootElement.replace(elementIndex, 1, new Element[] { newEl1, newEl2 }); + firstElement = newEl2; + elementIndex ++; + } + } + catch (BadLocationException ble) + { + // This shouldn't happen. + AssertionError ae = new AssertionError(); + ae.initCause(ble); + throw ae; + } + } + // added and removed are Element arrays used to add an ElementEdit // to the DocumentEvent if there were entire lines added or removed. Element[] removed = new Element[1]; diff --git a/javax/xml/namespace/QName.java b/javax/xml/namespace/QName.java index 19700b32e..edc6678e3 100644 --- a/javax/xml/namespace/QName.java +++ b/javax/xml/namespace/QName.java @@ -1,5 +1,5 @@ /* QName.java - An XML qualified name. - Copyright (C) 2004, 2005 Free Software Foundation, Inc. + Copyright (C) 2004,2005,2006 Free Software Foundation, Inc. This file is part of GNU Classpath. @@ -67,16 +67,17 @@ public class QName implements Serializable public QName(String namespaceURI, String localPart, String prefix) { if (namespaceURI == null) - { - namespaceURI = XMLConstants.NULL_NS_URI; - } + namespaceURI = XMLConstants.NULL_NS_URI; if (localPart == null) - { - throw new IllegalArgumentException(); - } + throw new IllegalArgumentException(); if (prefix == null) + prefix = XMLConstants.DEFAULT_NS_PREFIX; + else { - prefix = XMLConstants.DEFAULT_NS_PREFIX; + if (XMLConstants.XML_NS_PREFIX.equals(prefix)) + namespaceURI = XMLConstants.XML_NS_URI; + else if (XMLConstants.XMLNS_ATTRIBUTE.equals(prefix)) + namespaceURI = XMLConstants.XMLNS_ATTRIBUTE_NS_URI; } this.namespaceURI = namespaceURI; this.localPart = localPart; @@ -151,9 +152,7 @@ public class QName implements Serializable if (start != -1) { if (end < start) - { - throw new IllegalArgumentException(qNameAsString); - } + throw new IllegalArgumentException(qNameAsString); namespaceUri = qNameAsString.substring(start + 1, end); qNameAsString = qNameAsString.substring(end + 1); } diff --git a/lib/Makefile.am b/lib/Makefile.am index fb6cb26c6..9eef74641 100644 --- a/lib/Makefile.am +++ b/lib/Makefile.am @@ -29,7 +29,7 @@ JAVAC = $(ECJ) -1.5 -warn:-deprecation,serial,typeHiding,unchecked,unused,vararg #JAVAC = $(KJC) -classpath .:$(USER_CLASSLIB) -d . @classes else if FOUND_GCJX -JAVAC = $(GCJX) -encoding UTF-8 -classpath .:$(USER_CLASSLIB) -d . @classes +JAVAC = $(GCJX) -g -encoding UTF-8 -classpath .:$(USER_CLASSLIB) -d . @classes endif # FOUND_GCJX #endif # FOUND_KJC #endif # FOUND_GCJ diff --git a/native/fdlibm/fdlibm.h b/native/fdlibm/fdlibm.h index a4a55523e..13ee449d7 100644 --- a/native/fdlibm/fdlibm.h +++ b/native/fdlibm/fdlibm.h @@ -96,7 +96,7 @@ extern double erfc __P((double)); extern double gamma __P((double)); extern double hypot __P((double, double)); -#ifndef isnan +#if !defined(isnan) && !defined(HAVE_ISNAN) #define isnan(x) ((x) != (x)) #endif diff --git a/native/fdlibm/mprec.c b/native/fdlibm/mprec.c index 48bf0d1aa..0badf60c4 100644 --- a/native/fdlibm/mprec.c +++ b/native/fdlibm/mprec.c @@ -97,7 +97,9 @@ _DEFUN (Balloc, (ptr, k), struct _Jv_reent *ptr _AND int k) int i = 0; int j = 1; - assert ((1 << k) < MAX_BIGNUM_WDS); + /* FIXME - assert disabled because of PR classpath/23863 + * assert ((1 << k) < MAX_BIGNUM_WDS); + */ while ((ptr->_allocation_map & j) && i < MAX_BIGNUMS) i++, j <<= 1; diff --git a/native/jni/java-net/gnu_java_net_VMPlainDatagramSocketImpl.c b/native/jni/java-net/gnu_java_net_VMPlainDatagramSocketImpl.c index e7cb55727..1b3cb97e0 100644 --- a/native/jni/java-net/gnu_java_net_VMPlainDatagramSocketImpl.c +++ b/native/jni/java-net/gnu_java_net_VMPlainDatagramSocketImpl.c @@ -1,5 +1,5 @@ /* VMPlainDatagramSocketImpl.c - Native methods for PlainDatagramSocketImpl - Copyright (C) 2005 Free Software Foundation, Inc. + Copyright (C) 2005, 2006 Free Software Foundation, Inc. This file is part of GNU Classpath. @@ -41,7 +41,6 @@ exception statement from your version. */ #include <stdlib.h> #include <stdio.h> #include <string.h> -#include <assert.h> #include <jni.h> #include <jcl.h> @@ -72,8 +71,6 @@ Java_gnu_java_net_VMPlainDatagramSocketImpl_create(JNIEnv *env, jclass klass __attribute__ ((__unused__)) , jobject obj) { - assert(env!=NULL); - assert((*env)!=NULL); #ifndef WITHOUT_NETWORK _javanet_create(env, obj, 0); @@ -91,8 +88,6 @@ Java_gnu_java_net_VMPlainDatagramSocketImpl_close(JNIEnv *env, jclass klass __attribute__ ((__unused__)), jobject obj) { - assert(env!=NULL); - assert((*env)!=NULL); #ifndef WITHOUT_NETWORK _javanet_close(env, obj, 0); @@ -112,10 +107,8 @@ Java_gnu_java_net_VMPlainDatagramSocketImpl_connect(JNIEnv *env, jobject addr, jint port) { #ifndef WITHOUT_NETWORK - assert(env!=NULL); - assert((*env)!=NULL); - _javanet_connect(env, obj, addr, port); + _javanet_connect(env, obj, addr, port, 0); #else /* not WITHOUT_NETWORK */ #endif /* not WITHOUT_NETWORK */ } @@ -133,8 +126,6 @@ Java_gnu_java_net_VMPlainDatagramSocketImpl_bind(JNIEnv *env, jobject obj, jint port, jobject addr) { - assert(env!=NULL); - assert((*env)!=NULL); #ifndef WITHOUT_NETWORK _javanet_bind(env, obj, addr, port, 0); @@ -154,8 +145,6 @@ Java_gnu_java_net_VMPlainDatagramSocketImpl_setOption(JNIEnv *env, jint option_id, jobject val) { - assert(env!=NULL); - assert((*env)!=NULL); #ifndef WITHOUT_NETWORK _javanet_set_option(env, obj, option_id, val); @@ -174,8 +163,6 @@ Java_gnu_java_net_VMPlainDatagramSocketImpl_getOption(JNIEnv *env, jobject obj, jint option_id) { - assert(env!=NULL); - assert((*env)!=NULL); #ifndef WITHOUT_NETWORK return(_javanet_get_option(env, obj, option_id)); @@ -204,12 +191,6 @@ Java_gnu_java_net_VMPlainDatagramSocketImpl_nativeReceive(JNIEnv *env, int addr, *port, *bytes_read; char *addressBytes; - assert(env!=NULL); - assert((*env)!=NULL); - assert((*env)->GetArrayLength(env, receivedFromAddress) > 4); - assert((*env)->GetArrayLength(env, receivedFromPort ) > 1); - assert((*env)->GetArrayLength(env, receivedLength ) > 1); - addr = 0; port = (int*)(*env)->GetIntArrayElements(env, receivedFromPort, NULL); @@ -230,6 +211,12 @@ Java_gnu_java_net_VMPlainDatagramSocketImpl_nativeReceive(JNIEnv *env, /* Receive the packet */ /* should we try some sort of validation on the length? */ (*bytes_read) = _javanet_recvfrom(env, obj, arr, offset, length, &addr, port); + + /* Special case the strange situation where the receiver didn't want any + bytes. */ + if (length == 0 && (*bytes_read) == -1) + *bytes_read = 0; + if ((*bytes_read) == -1) { (*env)->ReleaseIntArrayElements(env, receivedFromPort, (jint*)port, 0); @@ -281,9 +268,6 @@ Java_gnu_java_net_VMPlainDatagramSocketImpl_nativeSendTo(JNIEnv *env, #ifndef WITHOUT_NETWORK jint netAddress; - assert(env!=NULL); - assert((*env)!=NULL); - /* check if address given, tr 7.3.2005 */ if (addr != NULL) { @@ -327,9 +311,6 @@ Java_gnu_java_net_VMPlainDatagramSocketImpl_join(JNIEnv *env, int fd; int result; - assert(env!=NULL); - assert((*env)!=NULL); - /* check if address given, tr 7.3.2005 */ if (addr != NULL) { @@ -383,9 +364,6 @@ Java_gnu_java_net_VMPlainDatagramSocketImpl_leave(JNIEnv *env, int fd; int result; - assert(env!=NULL); - assert((*env)!=NULL); - /* check if address given, tr 7.3.2005 */ if (addr != NULL) { diff --git a/native/jni/java-net/gnu_java_net_VMPlainSocketImpl.c b/native/jni/java-net/gnu_java_net_VMPlainSocketImpl.c index 93284b3af..cf10ee4b5 100644 --- a/native/jni/java-net/gnu_java_net_VMPlainSocketImpl.c +++ b/native/jni/java-net/gnu_java_net_VMPlainSocketImpl.c @@ -1,5 +1,5 @@ /* VMPlainSocketImpl.c - Native methods for PlainSocketImpl class - Copyright (C) 2005 Free Software Foundation, Inc. + Copyright (C) 2005, 2006 Free Software Foundation, Inc. This file is part of GNU Classpath. @@ -41,7 +41,6 @@ exception statement from your version. */ #include <stdlib.h> #include <stdio.h> #include <string.h> -#include <assert.h> #include <jni.h> #include <jcl.h> @@ -73,9 +72,6 @@ Java_gnu_java_net_VMPlainSocketImpl_create(JNIEnv *env, jobject obj) { #ifndef WITHOUT_NETWORK - assert(env!=NULL); - assert((*env)!=NULL); - _javanet_create(env, obj, JNI_TRUE); #else /* not WITHOUT_NETWORK */ #endif /* not WITHOUT_NETWORK */ @@ -93,9 +89,6 @@ Java_gnu_java_net_VMPlainSocketImpl_close(JNIEnv *env, jobject obj) { #ifndef WITHOUT_NETWORK - assert(env!=NULL); - assert((*env)!=NULL); - _javanet_close(env, obj, 1); #else /* not WITHOUT_NETWORK */ #endif /* not WITHOUT_NETWORK */ @@ -113,10 +106,7 @@ Java_gnu_java_net_VMPlainSocketImpl_connect(JNIEnv *env, jobject addr, jint port) { #ifndef WITHOUT_NETWORK - assert(env!=NULL); - assert((*env)!=NULL); - - _javanet_connect(env, obj, addr, port); + _javanet_connect(env, obj, addr, port, 1); #else /* not WITHOUT_NETWORK */ #endif /* not WITHOUT_NETWORK */ } @@ -135,9 +125,6 @@ Java_gnu_java_net_VMPlainSocketImpl_bind(JNIEnv *env, jint port) { #ifndef WITHOUT_NETWORK - assert(env!=NULL); - assert((*env)!=NULL); - _javanet_bind(env, obj, addr, port, 1); #else /* not WITHOUT_NETWORK */ #endif /* not WITHOUT_NETWORK */ @@ -155,9 +142,6 @@ Java_gnu_java_net_VMPlainSocketImpl_listen(JNIEnv *env, jobject obj, jint queuelen) { #ifndef WITHOUT_NETWORK - assert(env!=NULL); - assert((*env)!=NULL); - _javanet_listen(env, obj, queuelen); #else /* not WITHOUT_NETWORK */ #endif /* not WITHOUT_NETWORK */ @@ -175,9 +159,6 @@ Java_gnu_java_net_VMPlainSocketImpl_accept(JNIEnv *env, jobject obj, jobject impl) { #ifndef WITHOUT_NETWORK - assert(env!=NULL); - assert((*env)!=NULL); - _javanet_accept(env, obj, impl); #else /* not WITHOUT_NETWORK */ #endif /* not WITHOUT_NETWORK */ @@ -197,9 +178,6 @@ Java_gnu_java_net_VMPlainSocketImpl_available(JNIEnv *env, int bytesAvailable; int result; - assert(env!=NULL); - assert((*env)!=NULL); - cls = (*env)->GetObjectClass(env, obj); if (cls == 0) { @@ -241,9 +219,6 @@ Java_gnu_java_net_VMPlainSocketImpl_setOption(JNIEnv *env, jint option_id, jobject val) { #ifndef WITHOUT_NETWORK - assert(env!=NULL); - assert((*env)!=NULL); - _javanet_set_option(env, obj, option_id, val); #else /* not WITHOUT_NETWORK */ #endif /* not WITHOUT_NETWORK */ @@ -261,9 +236,6 @@ Java_gnu_java_net_VMPlainSocketImpl_getOption(JNIEnv *env, jint option_id) { #ifndef WITHOUT_NETWORK - assert(env!=NULL); - assert((*env)!=NULL); - return(_javanet_get_option(env, obj, option_id)); #else /* not WITHOUT_NETWORK */ return NULL; @@ -282,9 +254,6 @@ Java_gnu_java_net_VMPlainSocketImpl_read(JNIEnv *env, jint offset, jint len) { #ifndef WITHOUT_NETWORK - assert(env!=NULL); - assert((*env)!=NULL); - return(_javanet_recvfrom(env, obj, buf, offset, len, 0, 0)); #else /* not WITHOUT_NETWORK */ return 0; @@ -303,9 +272,6 @@ Java_gnu_java_net_VMPlainSocketImpl_write(JNIEnv *env, jint offset, jint len) { #ifndef WITHOUT_NETWORK - assert(env!=NULL); - assert((*env)!=NULL); - _javanet_sendto(env, obj, buf, offset, len, 0, 0); #else /* not WITHOUT_NETWORK */ #endif /* not WITHOUT_NETWORK */ @@ -317,9 +283,6 @@ Java_gnu_java_net_VMPlainSocketImpl_shutdownInput (JNIEnv * env, jobject this) { #ifndef WITHOUT_NETWORK - assert (env != NULL); - assert ((*env) != NULL); - _javanet_shutdownInput (env, this); #else /* not WITHOUT_NETWORK */ #endif /* not WITHOUT_NETWORK */ @@ -331,9 +294,6 @@ Java_gnu_java_net_VMPlainSocketImpl_shutdownOutput (JNIEnv * env, jobject this) { #ifndef WITHOUT_NETWORK - assert (env != NULL); - assert ((*env) != NULL); - _javanet_shutdownOutput (env, this); #else /* not WITHOUT_NETWORK */ #endif /* not WITHOUT_NETWORK */ diff --git a/native/jni/java-net/java_net_VMInetAddress.c b/native/jni/java-net/java_net_VMInetAddress.c index 0ba00d1c3..86ac06e6f 100644 --- a/native/jni/java-net/java_net_VMInetAddress.c +++ b/native/jni/java-net/java_net_VMInetAddress.c @@ -1,5 +1,5 @@ /* VMInetAddress.c - Native methods for InetAddress class - Copyright (C) 1998, 2002, 2005 Free Software Foundation, Inc. + Copyright (C) 1998, 2002, 2005, 2006 Free Software Foundation, Inc. This file is part of GNU Classpath. @@ -41,7 +41,6 @@ exception statement from your version. */ #include <stdlib.h> #include <stdio.h> #include <string.h> -#include <assert.h> #include <jni.h> #include <jcl.h> @@ -69,9 +68,6 @@ Java_java_net_VMInetAddress_getLocalHostname (JNIEnv * env, int result; jstring retval; - assert (env != NULL); - assert ((*env) != NULL); - #ifndef WITHOUT_NETWORK TARGET_NATIVE_NETWORK_GET_HOSTNAME (hostname, sizeof (hostname), result); if (result != TARGET_NATIVE_OK) @@ -100,9 +96,6 @@ Java_java_net_VMInetAddress_lookupInaddrAny (JNIEnv * env, jarray IParray; jbyte *octets; - assert (env != NULL); - assert ((*env) != NULL); - /* Allocate an array for the IP address */ IParray = (*env)->NewByteArray (env, 4); if (IParray == NULL) @@ -150,9 +143,6 @@ Java_java_net_VMInetAddress_getHostByAddr (JNIEnv * env, int result; jstring retval; - assert (env != NULL); - assert ((*env) != NULL); - /* Grab the byte[] array with the IP out of the input data */ len = (*env)->GetArrayLength (env, arr); if (len != 4) @@ -215,9 +205,6 @@ Java_java_net_VMInetAddress_getHostByName (JNIEnv * env, jarray ret_octets; int max_addresses; - assert (env != NULL); - assert ((*env) != NULL); - /* Grab the hostname string */ hostname = (*env)->GetStringUTFChars (env, host, 0); if (!hostname) diff --git a/native/jni/java-net/java_net_VMNetworkInterface.c b/native/jni/java-net/java_net_VMNetworkInterface.c index 71f5e8927..f05e9fcc5 100644 --- a/native/jni/java-net/java_net_VMNetworkInterface.c +++ b/native/jni/java-net/java_net_VMNetworkInterface.c @@ -1,5 +1,5 @@ /* VMNetworkInterface.c - Native methods for NetworkInterface class - Copyright (C) 2003, 2005 Free Software Foundation, Inc. + Copyright (C) 2003, 2005, 2006 Free Software Foundation, Inc. This file is part of GNU Classpath. @@ -41,7 +41,6 @@ exception statement from your version. */ #include <stdlib.h> #include <stdio.h> #include <string.h> -#include <assert.h> #include <jni.h> #include <jcl.h> diff --git a/native/jni/java-net/javanet.c b/native/jni/java-net/javanet.c index 31afbc869..0f296a604 100644 --- a/native/jni/java-net/javanet.c +++ b/native/jni/java-net/javanet.c @@ -1,5 +1,5 @@ /* javanet.c - Common internal functions for the java.net package - Copyright (C) 1998, 2002, 2004, 2005 Free Software Foundation, Inc. + Copyright (C) 1998, 2002, 2004, 2005, 2006 Free Software Foundation, Inc. This file is part of GNU Classpath. @@ -41,7 +41,6 @@ exception statement from your version. */ #include <stdlib.h> #include <stdio.h> #include <string.h> -#include <assert.h> #include <jni.h> #include <jcl.h> @@ -77,9 +76,6 @@ _javanet_set_int_field (JNIEnv * env, jobject obj, jclass cls; jfieldID fid; - assert (env != NULL); - assert ((*env) != NULL); - cls = (*env)->FindClass (env, class); if (cls == NULL) return; @@ -106,9 +102,6 @@ _javanet_get_int_field (JNIEnv * env, jobject obj, const char *field) jfieldID fid; int fd; - assert (env != NULL); - assert ((*env) != NULL); - DBG ("_javanet_get_int_field(): Entered _javanet_get_int_field\n"); cls = (*env)->GetObjectClass (env, obj); @@ -133,20 +126,20 @@ _javanet_get_int_field (JNIEnv * env, jobject obj, const char *field) * need to include it. */ static void -_javanet_create_localfd (JNIEnv * env, jobject this) +_javanet_create_localfd (JNIEnv * env, jobject this, jboolean stream) { jclass this_cls, fd_cls; jfieldID fid; jmethodID mid; jobject fd_obj; - assert (env != NULL); - assert ((*env) != NULL); - DBG ("_javanet_create_localfd(): Entered _javanet_create_localfd\n"); /* Look up the fd field */ - this_cls = (*env)->FindClass (env, "java/net/SocketImpl"); + if (stream) + this_cls = (*env)->FindClass(env, "java/net/SocketImpl"); + else + this_cls = (*env)->FindClass(env, "java/net/DatagramSocketImpl"); if (this_cls == NULL) return; @@ -194,9 +187,6 @@ _javanet_create_boolean (JNIEnv * env, jboolean val) jmethodID mid; jobject obj; - assert (env != NULL); - assert ((*env) != NULL); - cls = (*env)->FindClass (env, "java/lang/Boolean"); if (cls == NULL) return NULL; @@ -224,9 +214,6 @@ _javanet_create_integer (JNIEnv * env, jint val) jmethodID mid; jobject obj; - assert (env != NULL); - assert ((*env) != NULL); - cls = (*env)->FindClass (env, "java/lang/Integer"); if (cls == NULL) return NULL; @@ -258,9 +245,6 @@ _javanet_create_inetaddress (JNIEnv * env, int netaddr) jstring ip_str; jobject ia; - assert (env != NULL); - assert ((*env) != NULL); - /* Build a string IP address */ TARGET_NATIVE_NETWORK_INT_TO_IPADDRESS_BYTES (netaddr, octets[0], @@ -315,9 +299,6 @@ _javanet_set_remhost_addr (JNIEnv * env, jobject this, jobject ia) jclass this_cls; jfieldID fid; - assert (env != NULL); - assert ((*env) != NULL); - /* Set the variable in the object */ this_cls = (*env)->FindClass (env, "java/net/SocketImpl"); if (this_cls == NULL) @@ -343,9 +324,6 @@ _javanet_set_remhost (JNIEnv * env, jobject this, int netaddr) { jobject ia; - assert (env != NULL); - assert ((*env) != NULL); - DBG ("_javanet_set_remhost(): Entered _javanet_set_remhost\n"); /* Get an InetAddress object */ @@ -372,9 +350,6 @@ _javanet_get_netaddr (JNIEnv * env, jobject addr) jbyte *octets; int netaddr, len; - assert (env != NULL); - assert ((*env) != NULL); - DBG ("_javanet_get_netaddr(): Entered _javanet_get_netaddr\n"); if (addr == NULL) @@ -441,9 +416,6 @@ _javanet_create (JNIEnv * env, jobject this, jboolean stream) int fd; int result; - assert (env != NULL); - assert ((*env) != NULL); - if (stream) { /* create a stream socket */ @@ -514,9 +486,6 @@ _javanet_close (JNIEnv * env, jobject this, int stream) int result; int error = 0; - assert (env != NULL); - assert ((*env) != NULL); - fd = _javanet_get_int_field (env, this, "native_fd"); if (fd == -1) return; @@ -552,7 +521,8 @@ _javanet_close (JNIEnv * env, jobject this, int stream) * Connects to the specified destination. */ void -_javanet_connect (JNIEnv * env, jobject this, jobject addr, jint port) +_javanet_connect (JNIEnv * env, jobject this, jobject addr, jint port, + jboolean stream) { #ifndef WITHOUT_NETWORK int netaddr, fd; @@ -560,9 +530,6 @@ _javanet_connect (JNIEnv * env, jobject this, jobject addr, jint port) int local_address, local_port; int remote_address, remote_port; - assert (env != NULL); - assert ((*env) != NULL); - DBG ("_javanet_connect(): Entered _javanet_connect\n"); /* Pre-process input variables */ @@ -613,7 +580,7 @@ _javanet_connect (JNIEnv * env, jobject this, jobject addr, jint port) return; } - _javanet_create_localfd (env, this); + _javanet_create_localfd (env, this, stream); if ((*env)->ExceptionOccurred (env)) { /* We don't care whether this succeeds. close() will cleanup later. */ @@ -622,8 +589,13 @@ _javanet_connect (JNIEnv * env, jobject this, jobject addr, jint port) } DBG ("_javanet_connect(): Created fd\n"); - _javanet_set_int_field (env, this, "java/net/SocketImpl", "localport", - local_port); + if (stream) + _javanet_set_int_field (env, this, "java/net/SocketImpl", "localport", + local_port); + else + _javanet_set_int_field (env, this, "java/net/DatagramSocketImpl", + "localPort", local_port); + if ((*env)->ExceptionOccurred (env)) { /* We don't care whether this succeeds. close() will cleanup later. */ @@ -643,31 +615,36 @@ _javanet_connect (JNIEnv * env, jobject this, jobject addr, jint port) return; } - if (remote_address == netaddr) - { - _javanet_set_remhost_addr (env, this, addr); - } - else - { - _javanet_set_remhost (env, this, remote_address); - } - if ((*env)->ExceptionOccurred (env)) + if (stream) { - /* We don't care whether this succeeds. close() will cleanup later. */ - TARGET_NATIVE_NETWORK_SOCKET_CLOSE (fd, result); - return; - } - DBG ("_javanet_connect(): Set the remote host\n"); + if (remote_address == netaddr) + { + _javanet_set_remhost_addr (env, this, addr); + } + else + { + _javanet_set_remhost (env, this, remote_address); + } + if ((*env)->ExceptionOccurred (env)) + { + /* We don't care whether this succeeds. close() will cleanup later. + */ + TARGET_NATIVE_NETWORK_SOCKET_CLOSE (fd, result); + return; + } + DBG ("_javanet_connect(): Set the remote host\n"); - _javanet_set_int_field (env, this, "java/net/SocketImpl", "port", - remote_port); - if ((*env)->ExceptionOccurred (env)) - { - /* We don't care whether this succeeds. close() will cleanup later. */ - TARGET_NATIVE_NETWORK_SOCKET_CLOSE (fd, result); - return; + _javanet_set_int_field (env, this, "java/net/SocketImpl", "port", + remote_port); + if ((*env)->ExceptionOccurred (env)) + { + /* We don't care whether this succeeds. close() will cleanup later. + */ + TARGET_NATIVE_NETWORK_SOCKET_CLOSE (fd, result); + return; + } + DBG ("_javanet_connect(): Set the remote port\n"); } - DBG ("_javanet_connect(): Set the remote port\n"); #else /* not WITHOUT_NETWORK */ #endif /* not WITHOUT_NETWORK */ } @@ -693,9 +670,6 @@ _javanet_bind (JNIEnv * env, jobject this, jobject addr, jint port, int result; int local_address, local_port; - assert (env != NULL); - assert ((*env) != NULL); - DBG ("_javanet_bind(): Entering native bind()\n"); /* Get the address to connect to */ @@ -797,9 +771,6 @@ _javanet_listen (JNIEnv * env, jobject this, jint queuelen) int fd; int result; - assert (env != NULL); - assert ((*env) != NULL); - /* Get the real file descriptor */ fd = _javanet_get_int_field (env, this, "native_fd"); if (fd == -1) @@ -836,9 +807,6 @@ _javanet_accept (JNIEnv * env, jobject this, jobject impl) int local_address, local_port; int remote_address, remote_port; - assert (env != NULL); - assert ((*env) != NULL); - /* Get the real file descriptor */ fd = _javanet_get_int_field (env, this, "native_fd"); if (fd == -1) @@ -897,7 +865,7 @@ _javanet_accept (JNIEnv * env, jobject this, jobject impl) return; } - _javanet_create_localfd (env, impl); + _javanet_create_localfd (env, impl, 1); if ((*env)->ExceptionOccurred (env)) { /* We don't care whether this succeeds. close() will cleanup later. */ @@ -971,9 +939,6 @@ _javanet_recvfrom (JNIEnv * env, jobject this, jarray buf, int offset, int from_address, from_port; int received_bytes; - assert (env != NULL); - assert ((*env) != NULL); - DBG ("_javanet_recvfrom(): Entered _javanet_recvfrom\n"); /* Get the real file descriptor */ @@ -1040,6 +1005,11 @@ _javanet_recvfrom (JNIEnv * env, jobject this, jarray buf, int offset, (*port) = from_port; } + /* zero bytes received means recv() noticed the other side orderly + closing the connection. */ + if (received_bytes == 0) + received_bytes = -1; + return (received_bytes); #else /* not WITHOUT_NETWORK */ #endif /* not WITHOUT_NETWORK */ @@ -1065,9 +1035,6 @@ _javanet_sendto (JNIEnv * env, jobject this, jarray buf, int offset, int len, jbyte *p; int bytes_sent; - assert (env != NULL); - assert ((*env) != NULL); - /* Get the real file descriptor */ fd = _javanet_get_int_field (env, this, "native_fd"); if (fd == -1) @@ -1138,9 +1105,6 @@ _javanet_set_option (JNIEnv * env, jobject this, jint option_id, jobject val) int address; int result; - assert (env != NULL); - assert ((*env) != NULL); - /* Get the real file descriptor */ fd = _javanet_get_int_field (env, this, "native_fd"); if (fd == -1) @@ -1355,9 +1319,6 @@ _javanet_get_option (JNIEnv * env, jobject this, jint option_id) int address; int result; - assert (env != NULL); - assert ((*env) != NULL); - /* Get the real file descriptor */ fd = _javanet_get_int_field (env, this, "native_fd"); if (fd == -1) @@ -1531,9 +1492,6 @@ _javanet_shutdownInput (JNIEnv * env, jobject this) { int fd; - assert (env != NULL); - assert ((*env) != NULL); - /* Get the real file descriptor. */ fd = _javanet_get_int_field (env, this, "native_fd"); if (fd == -1) @@ -1546,7 +1504,8 @@ _javanet_shutdownInput (JNIEnv * env, jobject this) /* Shutdown input stream of socket. */ if (shutdown (fd, SHUT_RD) == -1) { - JCL_ThrowException (env, SOCKET_EXCEPTION, strerror (errno)); + JCL_ThrowException (env, SOCKET_EXCEPTION, + TARGET_NATIVE_LAST_ERROR_STRING()); return; } } @@ -1556,9 +1515,6 @@ _javanet_shutdownOutput (JNIEnv * env, jobject this) { int fd; - assert (env != NULL); - assert ((*env) != NULL); - /* Get the real file descriptor. */ fd = _javanet_get_int_field (env, this, "native_fd"); if (fd == -1) @@ -1571,7 +1527,8 @@ _javanet_shutdownOutput (JNIEnv * env, jobject this) /* Shutdown output stream of socket. */ if (shutdown (fd, SHUT_WR) == -1) { - JCL_ThrowException (env, SOCKET_EXCEPTION, strerror (errno)); + JCL_ThrowException (env, SOCKET_EXCEPTION, + TARGET_NATIVE_LAST_ERROR_STRING()); return; } } diff --git a/native/jni/java-net/javanet.h b/native/jni/java-net/javanet.h index 7c77ea77f..c173b1059 100644 --- a/native/jni/java-net/javanet.h +++ b/native/jni/java-net/javanet.h @@ -92,7 +92,7 @@ extern int _javanet_get_int_field(JNIEnv *, jobject, const char *); extern int _javanet_get_netaddr(JNIEnv *, jobject); extern void _javanet_create(JNIEnv *, jobject, jboolean); extern void _javanet_close(JNIEnv *, jobject, int); -extern void _javanet_connect(JNIEnv *, jobject, jobject, jint); +extern void _javanet_connect(JNIEnv *, jobject, jobject, jint, jboolean); extern void _javanet_bind(JNIEnv *, jobject, jobject, jint, int); extern void _javanet_listen(JNIEnv *, jobject, jint); extern void _javanet_accept(JNIEnv *, jobject, jobject); diff --git a/native/jni/java-nio/gnu_java_nio_channels_FileChannelImpl.c b/native/jni/java-nio/gnu_java_nio_channels_FileChannelImpl.c index a9894994b..5aed63f35 100644 --- a/native/jni/java-nio/gnu_java_nio_channels_FileChannelImpl.c +++ b/native/jni/java-nio/gnu_java_nio_channels_FileChannelImpl.c @@ -1,5 +1,5 @@ /* gnu_java_nio_channels_FileChannelImpl.c - - Copyright (C) 2003, 2004, 2005 Free Software Foundation, Inc. + Copyright (C) 2003, 2004, 2005, 2006 Free Software Foundation, Inc. This file is part of GNU Classpath. @@ -538,11 +538,27 @@ Java_gnu_java_nio_channels_FileChannelImpl_mapImpl (JNIEnv *env, jobject obj, return NULL; } + fd = get_native_fd (env, obj); + prot = PROT_READ; - if (mode == '+') - prot |= PROT_WRITE; + if (mode == '+' || mode == 'c') + { + /* When writing we need to make sure the file is big enough, + otherwise the result of mmap is undefined. */ + jlong filesize; + filesize = Java_gnu_java_nio_channels_FileChannelImpl_size(env, obj); + if (filesize == -1) + return NULL; + if (position + size > filesize) + if (ftruncate(fd, position + size) == -1) + { + JCL_ThrowException (env, IO_EXCEPTION, strerror (errno)); + return NULL; + } + prot |= PROT_WRITE; + } + flags = (mode == 'c' ? MAP_PRIVATE : MAP_SHARED); - fd = get_native_fd (env, obj); p = mmap (NULL, (size_t) ALIGN_UP (size, pagesize), prot, flags, fd, ALIGN_DOWN (position, pagesize)); if (p == MAP_FAILED) diff --git a/native/jni/java-nio/java_nio_VMDirectByteBuffer.c b/native/jni/java-nio/java_nio_VMDirectByteBuffer.c index 06e29906a..f725cf2a4 100644 --- a/native/jni/java-nio/java_nio_VMDirectByteBuffer.c +++ b/native/jni/java-nio/java_nio_VMDirectByteBuffer.c @@ -93,8 +93,8 @@ Java_java_nio_VMDirectByteBuffer_get__Lgnu_classpath_Pointer_2I_3BII jobject address, jint index, jbyteArray dst, jint dst_offset, jint dst_len) { jbyte *src = (jbyte *) JCL_GetRawData (env, address) + index; - jbyte *_dst = (*env)->GetByteArrayElements (env, dst, NULL) + dst_offset; - memcpy (_dst, src, dst_len); + jbyte *_dst = (*env)->GetByteArrayElements (env, dst, NULL); + memcpy (_dst + dst_offset, src, dst_len); (*env)->ReleaseByteArrayElements (env, dst, _dst, 0); } @@ -103,10 +103,10 @@ Java_java_nio_VMDirectByteBuffer_put__Lgnu_classpath_Pointer_2I_3BII (JNIEnv *env, jclass clazz __attribute__ ((__unused__)), jobject address, jint index, jbyteArray src, jint src_offset, jint src_len) { - jbyte *_src = (*env)->GetByteArrayElements (env, src, NULL) + src_offset; - jbyte *dst = (jbyte *)JCL_GetRawData (env, address) + index; + jbyte *_src = (*env)->GetByteArrayElements (env, src, NULL); + jbyte *dst = (jbyte *)JCL_GetRawData (env, address); + memcpy (dst + index, _src + src_offset, src_len); (*env)->ReleaseByteArrayElements (env, src, _src, 0); - memcpy (dst, _src, src_len); } JNIEXPORT void JNICALL diff --git a/resource/Makefile.am b/resource/Makefile.am index aa9ffa1dc..436981022 100644 --- a/resource/Makefile.am +++ b/resource/Makefile.am @@ -1,4 +1,7 @@ ## used by automake to generate Makefile.in +logging_DATA = java/util/logging/logging.properties +loggingdir = $(prefix)/lib + security_DATA = java/security/classpath.security -securitydir = $(libdir)/security +securitydir = $(prefix)/lib/security diff --git a/vm/reference/gnu/java/net/VMPlainDatagramSocketImpl.java b/vm/reference/gnu/java/net/VMPlainDatagramSocketImpl.java index 1df675476..958c21874 100644 --- a/vm/reference/gnu/java/net/VMPlainDatagramSocketImpl.java +++ b/vm/reference/gnu/java/net/VMPlainDatagramSocketImpl.java @@ -155,7 +155,7 @@ public final class VMPlainDatagramSocketImpl int[] receivedLength = new int[1]; nativeReceive(socket, packet.getData(), packet.getOffset(), - packet.getData().length - packet.getOffset(), + packet.getLength(), receiveFromAddress, receiveFromPort, receivedLength); packet.setAddress(InetAddress.getByAddress(receiveFromAddress)); diff --git a/vm/reference/gnu/java/net/VMPlainSocketImpl.java b/vm/reference/gnu/java/net/VMPlainSocketImpl.java index b62fb6e98..76be558dc 100644 --- a/vm/reference/gnu/java/net/VMPlainSocketImpl.java +++ b/vm/reference/gnu/java/net/VMPlainSocketImpl.java @@ -1,5 +1,5 @@ /* VMPlainSocketImpl.java -- VM interface for default socket implementation - Copyright (C) 2005 Free Software Foundation, Inc. + Copyright (C) 2005, 2006 Free Software Foundation, Inc. This file is part of GNU Classpath. @@ -44,6 +44,7 @@ import java.net.SocketAddress; import java.net.SocketException; import java.net.SocketImpl; import java.net.SocketOptions; +import java.net.UnknownHostException; import gnu.classpath.Configuration; @@ -199,15 +200,17 @@ public final class VMPlainSocketImpl * * @param socket the socket object * - * @return read byte + * @return read byte or -1 if end of stream. * * @throws IOException if an error occurs */ static int read(PlainSocketImpl socket) throws IOException { byte[] buf = new byte[1]; - read(socket, buf, 0, 1); - return buf[0]; + if (read(socket, buf, 0, 1) > 0) + return buf[0] & 0xFF; + else + return -1; } /** @@ -277,7 +280,7 @@ public final class VMPlainSocketImpl InetAddress addr = sockAddr.getAddress(); if (addr == null) - throw new IllegalArgumentException("address is unresolved: " + sockAddr); + throw new UnknownHostException(sockAddr.getHostName()); int port = sockAddr.getPort(); |