# HG changeset patch # User Jaroslav Tulach # Date 1358969963 -3600 # Node ID 05224402145d224ff35f96590c63f0c89c41dc29 # Parent 388e48c0a37aff48e7dd17e93611f5151c09541d First attempt to separate 'mini' profile from the rest of JDK APIs diff -r 388e48c0a37a -r 05224402145d benchmarks/matrix-multiplication/pom.xml --- a/benchmarks/matrix-multiplication/pom.xml Wed Jan 23 20:16:48 2013 +0100 +++ b/benchmarks/matrix-multiplication/pom.xml Wed Jan 23 20:39:23 2013 +0100 @@ -31,7 +31,7 @@ org.apidesign.bck2brwsr - emul + emul.mini 0.3-SNAPSHOT diff -r 388e48c0a37a -r 05224402145d emul/mini/pom.xml --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/emul/mini/pom.xml Wed Jan 23 20:39:23 2013 +0100 @@ -0,0 +1,42 @@ + + + 4.0.0 + + org.apidesign.bck2brwsr + emul.pom + 0.3-SNAPSHOT + + org.apidesign.bck2brwsr + emul.mini + 0.3-SNAPSHOT + Minimal API Profile + http://maven.apache.org + + UTF-8 + + + + org.apidesign.bck2brwsr + core + 0.3-SNAPSHOT + jar + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 2.5.1 + + + netbeans.ignore.jdk.bootsclasspath + + 1.7 + 1.7 + + + + + diff -r 388e48c0a37a -r 05224402145d emul/mini/src/main/java/java/io/ByteArrayInputStream.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/emul/mini/src/main/java/java/io/ByteArrayInputStream.java Wed Jan 23 20:39:23 2013 +0100 @@ -0,0 +1,283 @@ +/* + * Copyright (c) 1994, 2010, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code 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 + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package java.io; + +/** + * A ByteArrayInputStream contains + * an internal buffer that contains bytes that + * may be read from the stream. An internal + * counter keeps track of the next byte to + * be supplied by the read method. + *

+ * Closing a ByteArrayInputStream has no effect. The methods in + * this class can be called after the stream has been closed without + * generating an IOException. + * + * @author Arthur van Hoff + * @see java.io.StringBufferInputStream + * @since JDK1.0 + */ +public +class ByteArrayInputStream extends InputStream { + + /** + * An array of bytes that was provided + * by the creator of the stream. Elements buf[0] + * through buf[count-1] are the + * only bytes that can ever be read from the + * stream; element buf[pos] is + * the next byte to be read. + */ + protected byte buf[]; + + /** + * The index of the next character to read from the input stream buffer. + * This value should always be nonnegative + * and not larger than the value of count. + * The next byte to be read from the input stream buffer + * will be buf[pos]. + */ + protected int pos; + + /** + * The currently marked position in the stream. + * ByteArrayInputStream objects are marked at position zero by + * default when constructed. They may be marked at another + * position within the buffer by the mark() method. + * The current buffer position is set to this point by the + * reset() method. + *

+ * If no mark has been set, then the value of mark is the offset + * passed to the constructor (or 0 if the offset was not supplied). + * + * @since JDK1.1 + */ + protected int mark = 0; + + /** + * The index one greater than the last valid character in the input + * stream buffer. + * This value should always be nonnegative + * and not larger than the length of buf. + * It is one greater than the position of + * the last byte within buf that + * can ever be read from the input stream buffer. + */ + protected int count; + + /** + * Creates a ByteArrayInputStream + * so that it uses buf as its + * buffer array. + * The buffer array is not copied. + * The initial value of pos + * is 0 and the initial value + * of count is the length of + * buf. + * + * @param buf the input buffer. + */ + public ByteArrayInputStream(byte buf[]) { + this.buf = buf; + this.pos = 0; + this.count = buf.length; + } + + /** + * Creates ByteArrayInputStream + * that uses buf as its + * buffer array. The initial value of pos + * is offset and the initial value + * of count is the minimum of offset+length + * and buf.length. + * The buffer array is not copied. The buffer's mark is + * set to the specified offset. + * + * @param buf the input buffer. + * @param offset the offset in the buffer of the first byte to read. + * @param length the maximum number of bytes to read from the buffer. + */ + public ByteArrayInputStream(byte buf[], int offset, int length) { + this.buf = buf; + this.pos = offset; + this.count = Math.min(offset + length, buf.length); + this.mark = offset; + } + + /** + * Reads the next byte of data from this input stream. The value + * byte is returned as an int in the range + * 0 to 255. If no byte is available + * because the end of the stream has been reached, the value + * -1 is returned. + *

+ * This read method + * cannot block. + * + * @return the next byte of data, or -1 if the end of the + * stream has been reached. + */ + public synchronized int read() { + return (pos < count) ? (buf[pos++] & 0xff) : -1; + } + + /** + * Reads up to len bytes of data into an array of bytes + * from this input stream. + * If pos equals count, + * then -1 is returned to indicate + * end of file. Otherwise, the number k + * of bytes read is equal to the smaller of + * len and count-pos. + * If k is positive, then bytes + * buf[pos] through buf[pos+k-1] + * are copied into b[off] through + * b[off+k-1] in the manner performed + * by System.arraycopy. The + * value k is added into pos + * and k is returned. + *

+ * This read method cannot block. + * + * @param b the buffer into which the data is read. + * @param off the start offset in the destination array b + * @param len the maximum number of bytes read. + * @return the total number of bytes read into the buffer, or + * -1 if there is no more data because the end of + * the stream has been reached. + * @exception NullPointerException If b is null. + * @exception IndexOutOfBoundsException If off is negative, + * len is negative, or len is greater than + * b.length - off + */ + public synchronized int read(byte b[], int off, int len) { + if (b == null) { + throw new NullPointerException(); + } else if (off < 0 || len < 0 || len > b.length - off) { + throw new IndexOutOfBoundsException(); + } + + if (pos >= count) { + return -1; + } + + int avail = count - pos; + if (len > avail) { + len = avail; + } + if (len <= 0) { + return 0; + } + PushbackInputStream.arraycopy(buf, pos, b, off, len); + pos += len; + return len; + } + + /** + * Skips n bytes of input from this input stream. Fewer + * bytes might be skipped if the end of the input stream is reached. + * The actual number k + * of bytes to be skipped is equal to the smaller + * of n and count-pos. + * The value k is added into pos + * and k is returned. + * + * @param n the number of bytes to be skipped. + * @return the actual number of bytes skipped. + */ + public synchronized long skip(long n) { + long k = count - pos; + if (n < k) { + k = n < 0 ? 0 : n; + } + + pos += k; + return k; + } + + /** + * Returns the number of remaining bytes that can be read (or skipped over) + * from this input stream. + *

+ * The value returned is count - pos, + * which is the number of bytes remaining to be read from the input buffer. + * + * @return the number of remaining bytes that can be read (or skipped + * over) from this input stream without blocking. + */ + public synchronized int available() { + return count - pos; + } + + /** + * Tests if this InputStream supports mark/reset. The + * markSupported method of ByteArrayInputStream + * always returns true. + * + * @since JDK1.1 + */ + public boolean markSupported() { + return true; + } + + /** + * Set the current marked position in the stream. + * ByteArrayInputStream objects are marked at position zero by + * default when constructed. They may be marked at another + * position within the buffer by this method. + *

+ * If no mark has been set, then the value of the mark is the + * offset passed to the constructor (or 0 if the offset was not + * supplied). + * + *

Note: The readAheadLimit for this class + * has no meaning. + * + * @since JDK1.1 + */ + public void mark(int readAheadLimit) { + mark = pos; + } + + /** + * Resets the buffer to the marked position. The marked position + * is 0 unless another position was marked or an offset was specified + * in the constructor. + */ + public synchronized void reset() { + pos = mark; + } + + /** + * Closing a ByteArrayInputStream has no effect. The methods in + * this class can be called after the stream has been closed without + * generating an IOException. + *

+ */ + public void close() throws IOException { + } + +} diff -r 388e48c0a37a -r 05224402145d emul/mini/src/main/java/java/io/Closeable.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/emul/mini/src/main/java/java/io/Closeable.java Wed Jan 23 20:39:23 2013 +0100 @@ -0,0 +1,48 @@ +/* + * Copyright (c) 2003, 2010, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code 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 + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package java.io; + +import java.io.IOException; + +/** + * A {@code Closeable} is a source or destination of data that can be closed. + * The close method is invoked to release resources that the object is + * holding (such as open files). + * + * @since 1.5 + */ + +public interface Closeable extends AutoCloseable { + + /** + * Closes this stream and releases any system resources associated + * with it. If the stream is already closed then invoking this + * method has no effect. + * + * @throws IOException if an I/O error occurs + */ + public void close() throws IOException; +} diff -r 388e48c0a37a -r 05224402145d emul/mini/src/main/java/java/io/DataInput.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/emul/mini/src/main/java/java/io/DataInput.java Wed Jan 23 20:39:23 2013 +0100 @@ -0,0 +1,635 @@ +/* + * Copyright (c) 1995, 2006, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code 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 + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package java.io; + +/** + * The DataInput interface provides + * for reading bytes from a binary stream and + * reconstructing from them data in any of + * the Java primitive types. There is also + * a + * facility for reconstructing a String + * from data in + * modified UTF-8 + * format. + *

+ * It is generally true of all the reading + * routines in this interface that if end of + * file is reached before the desired number + * of bytes has been read, an EOFException + * (which is a kind of IOException) + * is thrown. If any byte cannot be read for + * any reason other than end of file, an IOException + * other than EOFException is + * thrown. In particular, an IOException + * may be thrown if the input stream has been + * closed. + * + *

Modified UTF-8

+ *

+ * Implementations of the DataInput and DataOutput interfaces represent + * Unicode strings in a format that is a slight modification of UTF-8. + * (For information regarding the standard UTF-8 format, see section + * 3.9 Unicode Encoding Forms of The Unicode Standard, Version + * 4.0). + * Note that in the following tables, the most significant bit appears in the + * far left-hand column. + *

+ * All characters in the range '\u0001' to + * '\u007F' are represented by a single byte: + * + *

+ * + * + * + * + * + * + * + * + * + *
Bit Values
Byte 1 + * + * + * + *
0
+ *
bits 6-0
+ *
+ *
+ *
+ * + *

+ * The null character '\u0000' and characters in the + * range '\u0080' to '\u07FF' are + * represented by a pair of bytes: + * + *

+ * + * + * + * + * + * + * + * + * + * + * + * + * + *
Bit Values
Byte 1 + * + * + * + *
1
+ *
1
+ *
0
+ *
bits 10-6
+ *
+ *
Byte 2 + * + * + * + *
1
+ *
0
+ *
bits 5-0
+ *
+ *
+ *
+ * + *
+ * char values in the range '\u0800' to + * '\uFFFF' are represented by three bytes: + * + *
+ * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
Bit Values
Byte 1 + * + * + * + *
1
+ *
1
+ *
1
+ *
0
+ *
bits 15-12
+ *
+ *
Byte 2 + * + * + * + *
1
+ *
0
+ *
bits 11-6
+ *
+ *
Byte 3 + * + * + * + *
1
+ *
0
+ *
bits 5-0
+ *
+ *
+ *
+ * + *

+ * The differences between this format and the + * standard UTF-8 format are the following: + *

    + *
  • The null byte '\u0000' is encoded in 2-byte format + * rather than 1-byte, so that the encoded strings never have + * embedded nulls. + *
  • Only the 1-byte, 2-byte, and 3-byte formats are used. + *
  • Supplementary characters + * are represented in the form of surrogate pairs. + *
+ * @author Frank Yellin + * @see java.io.DataInputStream + * @see java.io.DataOutput + * @since JDK1.0 + */ +public +interface DataInput { + /** + * Reads some bytes from an input + * stream and stores them into the buffer + * array b. The number of bytes + * read is equal + * to the length of b. + *

+ * This method blocks until one of the + * following conditions occurs:

+ *

    + *
  • b.length + * bytes of input data are available, in which + * case a normal return is made. + * + *
  • End of + * file is detected, in which case an EOFException + * is thrown. + * + *
  • An I/O error occurs, in + * which case an IOException other + * than EOFException is thrown. + *
+ *

+ * If b is null, + * a NullPointerException is thrown. + * If b.length is zero, then + * no bytes are read. Otherwise, the first + * byte read is stored into element b[0], + * the next one into b[1], and + * so on. + * If an exception is thrown from + * this method, then it may be that some but + * not all bytes of b have been + * updated with data from the input stream. + * + * @param b the buffer into which the data is read. + * @exception EOFException if this stream reaches the end before reading + * all the bytes. + * @exception IOException if an I/O error occurs. + */ + void readFully(byte b[]) throws IOException; + + /** + * + * Reads len + * bytes from + * an input stream. + *

+ * This method + * blocks until one of the following conditions + * occurs:

+ *

    + *
  • len bytes + * of input data are available, in which case + * a normal return is made. + * + *
  • End of file + * is detected, in which case an EOFException + * is thrown. + * + *
  • An I/O error occurs, in + * which case an IOException other + * than EOFException is thrown. + *
+ *

+ * If b is null, + * a NullPointerException is thrown. + * If off is negative, or len + * is negative, or off+len is + * greater than the length of the array b, + * then an IndexOutOfBoundsException + * is thrown. + * If len is zero, + * then no bytes are read. Otherwise, the first + * byte read is stored into element b[off], + * the next one into b[off+1], + * and so on. The number of bytes read is, + * at most, equal to len. + * + * @param b the buffer into which the data is read. + * @param off an int specifying the offset into the data. + * @param len an int specifying the number of bytes to read. + * @exception EOFException if this stream reaches the end before reading + * all the bytes. + * @exception IOException if an I/O error occurs. + */ + void readFully(byte b[], int off, int len) throws IOException; + + /** + * Makes an attempt to skip over + * n bytes + * of data from the input + * stream, discarding the skipped bytes. However, + * it may skip + * over some smaller number of + * bytes, possibly zero. This may result from + * any of a + * number of conditions; reaching + * end of file before n bytes + * have been skipped is + * only one possibility. + * This method never throws an EOFException. + * The actual + * number of bytes skipped is returned. + * + * @param n the number of bytes to be skipped. + * @return the number of bytes actually skipped. + * @exception IOException if an I/O error occurs. + */ + int skipBytes(int n) throws IOException; + + /** + * Reads one input byte and returns + * true if that byte is nonzero, + * false if that byte is zero. + * This method is suitable for reading + * the byte written by the writeBoolean + * method of interface DataOutput. + * + * @return the boolean value read. + * @exception EOFException if this stream reaches the end before reading + * all the bytes. + * @exception IOException if an I/O error occurs. + */ + boolean readBoolean() throws IOException; + + /** + * Reads and returns one input byte. + * The byte is treated as a signed value in + * the range -128 through 127, + * inclusive. + * This method is suitable for + * reading the byte written by the writeByte + * method of interface DataOutput. + * + * @return the 8-bit value read. + * @exception EOFException if this stream reaches the end before reading + * all the bytes. + * @exception IOException if an I/O error occurs. + */ + byte readByte() throws IOException; + + /** + * Reads one input byte, zero-extends + * it to type int, and returns + * the result, which is therefore in the range + * 0 + * through 255. + * This method is suitable for reading + * the byte written by the writeByte + * method of interface DataOutput + * if the argument to writeByte + * was intended to be a value in the range + * 0 through 255. + * + * @return the unsigned 8-bit value read. + * @exception EOFException if this stream reaches the end before reading + * all the bytes. + * @exception IOException if an I/O error occurs. + */ + int readUnsignedByte() throws IOException; + + /** + * Reads two input bytes and returns + * a short value. Let a + * be the first byte read and b + * be the second byte. The value + * returned + * is: + *

(short)((a << 8) | (b & 0xff))
+     * 
+ * This method + * is suitable for reading the bytes written + * by the writeShort method of + * interface DataOutput. + * + * @return the 16-bit value read. + * @exception EOFException if this stream reaches the end before reading + * all the bytes. + * @exception IOException if an I/O error occurs. + */ + short readShort() throws IOException; + + /** + * Reads two input bytes and returns + * an int value in the range 0 + * through 65535. Let a + * be the first byte read and + * b + * be the second byte. The value returned is: + *

(((a & 0xff) << 8) | (b & 0xff))
+     * 
+ * This method is suitable for reading the bytes + * written by the writeShort method + * of interface DataOutput if + * the argument to writeShort + * was intended to be a value in the range + * 0 through 65535. + * + * @return the unsigned 16-bit value read. + * @exception EOFException if this stream reaches the end before reading + * all the bytes. + * @exception IOException if an I/O error occurs. + */ + int readUnsignedShort() throws IOException; + + /** + * Reads two input bytes and returns a char value. + * Let a + * be the first byte read and b + * be the second byte. The value + * returned is: + *

(char)((a << 8) | (b & 0xff))
+     * 
+ * This method + * is suitable for reading bytes written by + * the writeChar method of interface + * DataOutput. + * + * @return the char value read. + * @exception EOFException if this stream reaches the end before reading + * all the bytes. + * @exception IOException if an I/O error occurs. + */ + char readChar() throws IOException; + + /** + * Reads four input bytes and returns an + * int value. Let a-d + * be the first through fourth bytes read. The value returned is: + *

+     * 
+     * (((a & 0xff) << 24) | ((b & 0xff) << 16) |
+     *  ((c & 0xff) << 8) | (d & 0xff))
+     * 
+ * This method is suitable + * for reading bytes written by the writeInt + * method of interface DataOutput. + * + * @return the int value read. + * @exception EOFException if this stream reaches the end before reading + * all the bytes. + * @exception IOException if an I/O error occurs. + */ + int readInt() throws IOException; + + /** + * Reads eight input bytes and returns + * a long value. Let a-h + * be the first through eighth bytes read. + * The value returned is: + *

 
+     * (((long)(a & 0xff) << 56) |
+     *  ((long)(b & 0xff) << 48) |
+     *  ((long)(c & 0xff) << 40) |
+     *  ((long)(d & 0xff) << 32) |
+     *  ((long)(e & 0xff) << 24) |
+     *  ((long)(f & 0xff) << 16) |
+     *  ((long)(g & 0xff) <<  8) |
+     *  ((long)(h & 0xff)))
+     * 
+ *

+ * This method is suitable + * for reading bytes written by the writeLong + * method of interface DataOutput. + * + * @return the long value read. + * @exception EOFException if this stream reaches the end before reading + * all the bytes. + * @exception IOException if an I/O error occurs. + */ + long readLong() throws IOException; + + /** + * Reads four input bytes and returns + * a float value. It does this + * by first constructing an int + * value in exactly the manner + * of the readInt + * method, then converting this int + * value to a float in + * exactly the manner of the method Float.intBitsToFloat. + * This method is suitable for reading + * bytes written by the writeFloat + * method of interface DataOutput. + * + * @return the float value read. + * @exception EOFException if this stream reaches the end before reading + * all the bytes. + * @exception IOException if an I/O error occurs. + */ + float readFloat() throws IOException; + + /** + * Reads eight input bytes and returns + * a double value. It does this + * by first constructing a long + * value in exactly the manner + * of the readlong + * method, then converting this long + * value to a double in exactly + * the manner of the method Double.longBitsToDouble. + * This method is suitable for reading + * bytes written by the writeDouble + * method of interface DataOutput. + * + * @return the double value read. + * @exception EOFException if this stream reaches the end before reading + * all the bytes. + * @exception IOException if an I/O error occurs. + */ + double readDouble() throws IOException; + + /** + * Reads the next line of text from the input stream. + * It reads successive bytes, converting + * each byte separately into a character, + * until it encounters a line terminator or + * end of + * file; the characters read are then + * returned as a String. Note + * that because this + * method processes bytes, + * it does not support input of the full Unicode + * character set. + *

+ * If end of file is encountered + * before even one byte can be read, then null + * is returned. Otherwise, each byte that is + * read is converted to type char + * by zero-extension. If the character '\n' + * is encountered, it is discarded and reading + * ceases. If the character '\r' + * is encountered, it is discarded and, if + * the following byte converts to the + * character '\n', then that is + * discarded also; reading then ceases. If + * end of file is encountered before either + * of the characters '\n' and + * '\r' is encountered, reading + * ceases. Once reading has ceased, a String + * is returned that contains all the characters + * read and not discarded, taken in order. + * Note that every character in this string + * will have a value less than \u0100, + * that is, (char)256. + * + * @return the next line of text from the input stream, + * or null if the end of file is + * encountered before a byte can be read. + * @exception IOException if an I/O error occurs. + */ + String readLine() throws IOException; + + /** + * Reads in a string that has been encoded using a + * modified UTF-8 + * format. + * The general contract of readUTF + * is that it reads a representation of a Unicode + * character string encoded in modified + * UTF-8 format; this string of characters + * is then returned as a String. + *

+ * First, two bytes are read and used to + * construct an unsigned 16-bit integer in + * exactly the manner of the readUnsignedShort + * method . This integer value is called the + * UTF length and specifies the number + * of additional bytes to be read. These bytes + * are then converted to characters by considering + * them in groups. The length of each group + * is computed from the value of the first + * byte of the group. The byte following a + * group, if any, is the first byte of the + * next group. + *

+ * If the first byte of a group + * matches the bit pattern 0xxxxxxx + * (where x means "may be 0 + * or 1"), then the group consists + * of just that byte. The byte is zero-extended + * to form a character. + *

+ * If the first byte + * of a group matches the bit pattern 110xxxxx, + * then the group consists of that byte a + * and a second byte b. If there + * is no byte b (because byte + * a was the last of the bytes + * to be read), or if byte b does + * not match the bit pattern 10xxxxxx, + * then a UTFDataFormatException + * is thrown. Otherwise, the group is converted + * to the character:

+ *

(char)(((a& 0x1F) << 6) | (b & 0x3F))
+     * 
+ * If the first byte of a group + * matches the bit pattern 1110xxxx, + * then the group consists of that byte a + * and two more bytes b and c. + * If there is no byte c (because + * byte a was one of the last + * two of the bytes to be read), or either + * byte b or byte c + * does not match the bit pattern 10xxxxxx, + * then a UTFDataFormatException + * is thrown. Otherwise, the group is converted + * to the character:

+ *


+     * (char)(((a & 0x0F) << 12) | ((b & 0x3F) << 6) | (c & 0x3F))
+     * 
+ * If the first byte of a group matches the + * pattern 1111xxxx or the pattern + * 10xxxxxx, then a UTFDataFormatException + * is thrown. + *

+ * If end of file is encountered + * at any time during this entire process, + * then an EOFException is thrown. + *

+ * After every group has been converted to + * a character by this process, the characters + * are gathered, in the same order in which + * their corresponding groups were read from + * the input stream, to form a String, + * which is returned. + *

+ * The writeUTF + * method of interface DataOutput + * may be used to write data that is suitable + * for reading by this method. + * @return a Unicode string. + * @exception EOFException if this stream reaches the end + * before reading all the bytes. + * @exception IOException if an I/O error occurs. + * @exception UTFDataFormatException if the bytes do not represent a + * valid modified UTF-8 encoding of a string. + */ + String readUTF() throws IOException; +} diff -r 388e48c0a37a -r 05224402145d emul/mini/src/main/java/java/io/DataInputStream.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/emul/mini/src/main/java/java/io/DataInputStream.java Wed Jan 23 20:39:23 2013 +0100 @@ -0,0 +1,704 @@ +/* + * Copyright (c) 1994, 2006, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code 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 + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package java.io; + +import org.apidesign.bck2brwsr.core.JavaScriptBody; + +/** + * A data input stream lets an application read primitive Java data + * types from an underlying input stream in a machine-independent + * way. An application uses a data output stream to write data that + * can later be read by a data input stream. + *

+ * DataInputStream is not necessarily safe for multithreaded access. + * Thread safety is optional and is the responsibility of users of + * methods in this class. + * + * @author Arthur van Hoff + * @see java.io.DataOutputStream + * @since JDK1.0 + */ +public +class DataInputStream extends FilterInputStream implements DataInput { + + /** + * Creates a DataInputStream that uses the specified + * underlying InputStream. + * + * @param in the specified input stream + */ + public DataInputStream(InputStream in) { + super(in); + } + + /** + * working arrays initialized on demand by readUTF + */ + private byte bytearr[] = new byte[80]; + private char chararr[] = new char[80]; + + /** + * Reads some number of bytes from the contained input stream and + * stores them into the buffer array b. The number of + * bytes actually read is returned as an integer. This method blocks + * until input data is available, end of file is detected, or an + * exception is thrown. + * + *

If b is null, a NullPointerException is + * thrown. If the length of b is zero, then no bytes are + * read and 0 is returned; otherwise, there is an attempt + * to read at least one byte. If no byte is available because the + * stream is at end of file, the value -1 is returned; + * otherwise, at least one byte is read and stored into b. + * + *

The first byte read is stored into element b[0], the + * next one into b[1], and so on. The number of bytes read + * is, at most, equal to the length of b. Let k + * be the number of bytes actually read; these bytes will be stored in + * elements b[0] through b[k-1], leaving + * elements b[k] through b[b.length-1] + * unaffected. + * + *

The read(b) method has the same effect as: + *

+     * read(b, 0, b.length)
+     * 
+ * + * @param b the buffer into which the data is read. + * @return the total number of bytes read into the buffer, or + * -1 if there is no more data because the end + * of the stream has been reached. + * @exception IOException if the first byte cannot be read for any reason + * other than end of file, the stream has been closed and the underlying + * input stream does not support reading after close, or another I/O + * error occurs. + * @see java.io.FilterInputStream#in + * @see java.io.InputStream#read(byte[], int, int) + */ + public final int read(byte b[]) throws IOException { + return in.read(b, 0, b.length); + } + + /** + * Reads up to len bytes of data from the contained + * input stream into an array of bytes. An attempt is made to read + * as many as len bytes, but a smaller number may be read, + * possibly zero. The number of bytes actually read is returned as an + * integer. + * + *

This method blocks until input data is available, end of file is + * detected, or an exception is thrown. + * + *

If len is zero, then no bytes are read and + * 0 is returned; otherwise, there is an attempt to read at + * least one byte. If no byte is available because the stream is at end of + * file, the value -1 is returned; otherwise, at least one + * byte is read and stored into b. + * + *

The first byte read is stored into element b[off], the + * next one into b[off+1], and so on. The number of bytes read + * is, at most, equal to len. Let k be the number of + * bytes actually read; these bytes will be stored in elements + * b[off] through b[off+k-1], + * leaving elements b[off+k] through + * b[off+len-1] unaffected. + * + *

In every case, elements b[0] through + * b[off] and elements b[off+len] through + * b[b.length-1] are unaffected. + * + * @param b the buffer into which the data is read. + * @param off the start offset in the destination array b + * @param len the maximum number of bytes read. + * @return the total number of bytes read into the buffer, or + * -1 if there is no more data because the end + * of the stream has been reached. + * @exception NullPointerException If b is null. + * @exception IndexOutOfBoundsException If off is negative, + * len is negative, or len is greater than + * b.length - off + * @exception IOException if the first byte cannot be read for any reason + * other than end of file, the stream has been closed and the underlying + * input stream does not support reading after close, or another I/O + * error occurs. + * @see java.io.FilterInputStream#in + * @see java.io.InputStream#read(byte[], int, int) + */ + public final int read(byte b[], int off, int len) throws IOException { + return in.read(b, off, len); + } + + /** + * See the general contract of the readFully + * method of DataInput. + *

+ * Bytes + * for this operation are read from the contained + * input stream. + * + * @param b the buffer into which the data is read. + * @exception EOFException if this input stream reaches the end before + * reading all the bytes. + * @exception IOException the stream has been closed and the contained + * input stream does not support reading after close, or + * another I/O error occurs. + * @see java.io.FilterInputStream#in + */ + public final void readFully(byte b[]) throws IOException { + readFully(b, 0, b.length); + } + + /** + * See the general contract of the readFully + * method of DataInput. + *

+ * Bytes + * for this operation are read from the contained + * input stream. + * + * @param b the buffer into which the data is read. + * @param off the start offset of the data. + * @param len the number of bytes to read. + * @exception EOFException if this input stream reaches the end before + * reading all the bytes. + * @exception IOException the stream has been closed and the contained + * input stream does not support reading after close, or + * another I/O error occurs. + * @see java.io.FilterInputStream#in + */ + public final void readFully(byte b[], int off, int len) throws IOException { + if (len < 0) + throw new IndexOutOfBoundsException(); + int n = 0; + while (n < len) { + int count = in.read(b, off + n, len - n); + if (count < 0) + throw new EOFException(); + n += count; + } + } + + /** + * See the general contract of the skipBytes + * method of DataInput. + *

+ * Bytes for this operation are read from the contained + * input stream. + * + * @param n the number of bytes to be skipped. + * @return the actual number of bytes skipped. + * @exception IOException if the contained input stream does not support + * seek, or the stream has been closed and + * the contained input stream does not support + * reading after close, or another I/O error occurs. + */ + public final int skipBytes(int n) throws IOException { + int total = 0; + int cur = 0; + + while ((total 0)) { + total += cur; + } + + return total; + } + + /** + * See the general contract of the readBoolean + * method of DataInput. + *

+ * Bytes for this operation are read from the contained + * input stream. + * + * @return the boolean value read. + * @exception EOFException if this input stream has reached the end. + * @exception IOException the stream has been closed and the contained + * input stream does not support reading after close, or + * another I/O error occurs. + * @see java.io.FilterInputStream#in + */ + public final boolean readBoolean() throws IOException { + int ch = in.read(); + if (ch < 0) + throw new EOFException(); + return (ch != 0); + } + + /** + * See the general contract of the readByte + * method of DataInput. + *

+ * Bytes + * for this operation are read from the contained + * input stream. + * + * @return the next byte of this input stream as a signed 8-bit + * byte. + * @exception EOFException if this input stream has reached the end. + * @exception IOException the stream has been closed and the contained + * input stream does not support reading after close, or + * another I/O error occurs. + * @see java.io.FilterInputStream#in + */ + public final byte readByte() throws IOException { + int ch = in.read(); + if (ch < 0) + throw new EOFException(); + return (byte)(ch); + } + + /** + * See the general contract of the readUnsignedByte + * method of DataInput. + *

+ * Bytes + * for this operation are read from the contained + * input stream. + * + * @return the next byte of this input stream, interpreted as an + * unsigned 8-bit number. + * @exception EOFException if this input stream has reached the end. + * @exception IOException the stream has been closed and the contained + * input stream does not support reading after close, or + * another I/O error occurs. + * @see java.io.FilterInputStream#in + */ + public final int readUnsignedByte() throws IOException { + int ch = in.read(); + if (ch < 0) + throw new EOFException(); + return ch; + } + + /** + * See the general contract of the readShort + * method of DataInput. + *

+ * Bytes + * for this operation are read from the contained + * input stream. + * + * @return the next two bytes of this input stream, interpreted as a + * signed 16-bit number. + * @exception EOFException if this input stream reaches the end before + * reading two bytes. + * @exception IOException the stream has been closed and the contained + * input stream does not support reading after close, or + * another I/O error occurs. + * @see java.io.FilterInputStream#in + */ + public final short readShort() throws IOException { + int ch1 = in.read(); + int ch2 = in.read(); + if ((ch1 | ch2) < 0) + throw new EOFException(); + return (short)((ch1 << 8) + (ch2 << 0)); + } + + /** + * See the general contract of the readUnsignedShort + * method of DataInput. + *

+ * Bytes + * for this operation are read from the contained + * input stream. + * + * @return the next two bytes of this input stream, interpreted as an + * unsigned 16-bit integer. + * @exception EOFException if this input stream reaches the end before + * reading two bytes. + * @exception IOException the stream has been closed and the contained + * input stream does not support reading after close, or + * another I/O error occurs. + * @see java.io.FilterInputStream#in + */ + public final int readUnsignedShort() throws IOException { + int ch1 = in.read(); + int ch2 = in.read(); + if ((ch1 | ch2) < 0) + throw new EOFException(); + return (ch1 << 8) + (ch2 << 0); + } + + /** + * See the general contract of the readChar + * method of DataInput. + *

+ * Bytes + * for this operation are read from the contained + * input stream. + * + * @return the next two bytes of this input stream, interpreted as a + * char. + * @exception EOFException if this input stream reaches the end before + * reading two bytes. + * @exception IOException the stream has been closed and the contained + * input stream does not support reading after close, or + * another I/O error occurs. + * @see java.io.FilterInputStream#in + */ + public final char readChar() throws IOException { + int ch1 = in.read(); + int ch2 = in.read(); + if ((ch1 | ch2) < 0) + throw new EOFException(); + return (char)((ch1 << 8) + (ch2 << 0)); + } + + /** + * See the general contract of the readInt + * method of DataInput. + *

+ * Bytes + * for this operation are read from the contained + * input stream. + * + * @return the next four bytes of this input stream, interpreted as an + * int. + * @exception EOFException if this input stream reaches the end before + * reading four bytes. + * @exception IOException the stream has been closed and the contained + * input stream does not support reading after close, or + * another I/O error occurs. + * @see java.io.FilterInputStream#in + */ + public final int readInt() throws IOException { + int ch1 = in.read(); + int ch2 = in.read(); + int ch3 = in.read(); + int ch4 = in.read(); + if ((ch1 | ch2 | ch3 | ch4) < 0) + throw new EOFException(); + return ((ch1 << 24) + (ch2 << 16) + (ch3 << 8) + (ch4 << 0)); + } + + private byte readBuffer[] = new byte[8]; + + /** + * See the general contract of the readLong + * method of DataInput. + *

+ * Bytes + * for this operation are read from the contained + * input stream. + * + * @return the next eight bytes of this input stream, interpreted as a + * long. + * @exception EOFException if this input stream reaches the end before + * reading eight bytes. + * @exception IOException the stream has been closed and the contained + * input stream does not support reading after close, or + * another I/O error occurs. + * @see java.io.FilterInputStream#in + */ + public final long readLong() throws IOException { + readFully(readBuffer, 0, 8); + return (((long)readBuffer[0] << 56) + + ((long)(readBuffer[1] & 255) << 48) + + ((long)(readBuffer[2] & 255) << 40) + + ((long)(readBuffer[3] & 255) << 32) + + ((long)(readBuffer[4] & 255) << 24) + + ((readBuffer[5] & 255) << 16) + + ((readBuffer[6] & 255) << 8) + + ((readBuffer[7] & 255) << 0)); + } + + /** + * See the general contract of the readFloat + * method of DataInput. + *

+ * Bytes + * for this operation are read from the contained + * input stream. + * + * @return the next four bytes of this input stream, interpreted as a + * float. + * @exception EOFException if this input stream reaches the end before + * reading four bytes. + * @exception IOException the stream has been closed and the contained + * input stream does not support reading after close, or + * another I/O error occurs. + * @see java.io.DataInputStream#readInt() + * @see java.lang.Float#intBitsToFloat(int) + */ + public final float readFloat() throws IOException { + return Float.intBitsToFloat(readInt()); + } + + /** + * See the general contract of the readDouble + * method of DataInput. + *

+ * Bytes + * for this operation are read from the contained + * input stream. + * + * @return the next eight bytes of this input stream, interpreted as a + * double. + * @exception EOFException if this input stream reaches the end before + * reading eight bytes. + * @exception IOException the stream has been closed and the contained + * input stream does not support reading after close, or + * another I/O error occurs. + * @see java.io.DataInputStream#readLong() + * @see java.lang.Double#longBitsToDouble(long) + */ + public final double readDouble() throws IOException { + int hi = readInt(); + int low = readInt(); + return toDouble(hi, low); + } + + @JavaScriptBody(args={ "hi", "low" }, + body= + "if (low == 0) {\n" + + " if (hi === 0x7ff00000) return Number.POSITIVE_INFINITY;\n" + + " if (hi === 0xfff00000) return Number.NEGATIVE_INFINITY;\n" + + "}\n" + + "if (hi >= 0x7ff00000 && hi <= 0x7fffffff) return Number.NaN;\n" + + "if (hi >= 0xfff00000 && hi <= 0xffffffff) return Number.NaN;\n" + + "var s = (hi & 0x80000000) === 0 ? 1 : -1;\n" + + "var e = (hi >> 20) & 0x7ff;\n" + + "var to32 = low >> 0;\n" + + "if (e === 0) {\n" + + " if (to32 & 0x80000000) {\n" + + " hi = hi << 1 + 1; low = low << 1;\n" + + " } else {\n" + + " hi = hi << 1; low = low << 1;\n" + + " }\n" + + "} else {\n" + + " hi = (hi & 0xfffff) | 0x100000;\n" + + "}\n" + + "to32 = low >> 0;\n" + + "var m = Math.pow(2.0, 32) * hi + to32;\n" + + "var r = s * m * Math.pow(2.0, e - 1075);\n" + + "//throw 'exp: ' + e + ' sign: ' + s + ' hi:' + hi + ' low: ' + low + ' m: ' + m + ' r: ' + r;\n" + + "return r;\n" + ) + private static double toDouble(int hi, int low) { + long both = hi; + both = (both << 32) & low; + return Double.doubleToLongBits(both); + } + + private char lineBuffer[]; + + /** + * See the general contract of the readLine + * method of DataInput. + *

+ * Bytes + * for this operation are read from the contained + * input stream. + * + * @deprecated This method does not properly convert bytes to characters. + * As of JDK 1.1, the preferred way to read lines of text is via the + * BufferedReader.readLine() method. Programs that use the + * DataInputStream class to read lines can be converted to use + * the BufferedReader class by replacing code of the form: + *

+     *     DataInputStream d = new DataInputStream(in);
+     * 
+ * with: + *
+     *     BufferedReader d
+     *          = new BufferedReader(new InputStreamReader(in));
+     * 
+ * + * @return the next line of text from this input stream. + * @exception IOException if an I/O error occurs. + * @see java.io.BufferedReader#readLine() + * @see java.io.FilterInputStream#in + */ + @Deprecated + public final String readLine() throws IOException { + char buf[] = lineBuffer; + + if (buf == null) { + buf = lineBuffer = new char[128]; + } + + int room = buf.length; + int offset = 0; + int c; + +loop: while (true) { + switch (c = in.read()) { + case -1: + case '\n': + break loop; + + case '\r': + int c2 = in.read(); + if ((c2 != '\n') && (c2 != -1)) { + if (!(in instanceof PushbackInputStream)) { + this.in = new PushbackInputStream(in); + } + ((PushbackInputStream)in).unread(c2); + } + break loop; + + default: + if (--room < 0) { + buf = new char[offset + 128]; + room = buf.length - offset - 1; + arraycopy(lineBuffer, 0, buf, 0, offset); + lineBuffer = buf; + } + buf[offset++] = (char) c; + break; + } + } + if ((c == -1) && (offset == 0)) { + return null; + } + return String.copyValueOf(buf, 0, offset); + } + + /** + * See the general contract of the readUTF + * method of DataInput. + *

+ * Bytes + * for this operation are read from the contained + * input stream. + * + * @return a Unicode string. + * @exception EOFException if this input stream reaches the end before + * reading all the bytes. + * @exception IOException the stream has been closed and the contained + * input stream does not support reading after close, or + * another I/O error occurs. + * @exception UTFDataFormatException if the bytes do not represent a valid + * modified UTF-8 encoding of a string. + * @see java.io.DataInputStream#readUTF(java.io.DataInput) + */ + public final String readUTF() throws IOException { + return readUTF(this); + } + + /** + * Reads from the + * stream in a representation + * of a Unicode character string encoded in + * modified UTF-8 format; + * this string of characters is then returned as a String. + * The details of the modified UTF-8 representation + * are exactly the same as for the readUTF + * method of DataInput. + * + * @param in a data input stream. + * @return a Unicode string. + * @exception EOFException if the input stream reaches the end + * before all the bytes. + * @exception IOException the stream has been closed and the contained + * input stream does not support reading after close, or + * another I/O error occurs. + * @exception UTFDataFormatException if the bytes do not represent a + * valid modified UTF-8 encoding of a Unicode string. + * @see java.io.DataInputStream#readUnsignedShort() + */ + public final static String readUTF(DataInput in) throws IOException { + int utflen = in.readUnsignedShort(); + byte[] bytearr = null; + char[] chararr = null; + if (in instanceof DataInputStream) { + DataInputStream dis = (DataInputStream)in; + if (dis.bytearr.length < utflen){ + dis.bytearr = new byte[utflen*2]; + dis.chararr = new char[utflen*2]; + } + chararr = dis.chararr; + bytearr = dis.bytearr; + } else { + bytearr = new byte[utflen]; + chararr = new char[utflen]; + } + + int c, char2, char3; + int count = 0; + int chararr_count=0; + + in.readFully(bytearr, 0, utflen); + + while (count < utflen) { + c = (int) bytearr[count] & 0xff; + if (c > 127) break; + count++; + chararr[chararr_count++]=(char)c; + } + + while (count < utflen) { + c = (int) bytearr[count] & 0xff; + switch (c >> 4) { + case 0: case 1: case 2: case 3: case 4: case 5: case 6: case 7: + /* 0xxxxxxx*/ + count++; + chararr[chararr_count++]=(char)c; + break; + case 12: case 13: + /* 110x xxxx 10xx xxxx*/ + count += 2; + if (count > utflen) + throw new UTFDataFormatException( + "malformed input: partial character at end"); + char2 = (int) bytearr[count-1]; + if ((char2 & 0xC0) != 0x80) + throw new UTFDataFormatException( + "malformed input around byte " + count); + chararr[chararr_count++]=(char)(((c & 0x1F) << 6) | + (char2 & 0x3F)); + break; + case 14: + /* 1110 xxxx 10xx xxxx 10xx xxxx */ + count += 3; + if (count > utflen) + throw new UTFDataFormatException( + "malformed input: partial character at end"); + char2 = (int) bytearr[count-2]; + char3 = (int) bytearr[count-1]; + if (((char2 & 0xC0) != 0x80) || ((char3 & 0xC0) != 0x80)) + throw new UTFDataFormatException( + "malformed input around byte " + (count-1)); + chararr[chararr_count++]=(char)(((c & 0x0F) << 12) | + ((char2 & 0x3F) << 6) | + ((char3 & 0x3F) << 0)); + break; + default: + /* 10xx xxxx, 1111 xxxx */ + throw new UTFDataFormatException( + "malformed input around byte " + count); + } + } + // The number of chars produced may be less than utflen + return new String(chararr, 0, chararr_count); + } + static void arraycopy(char[] value, int srcBegin, char[] dst, int dstBegin, int count) { + while (count-- > 0) { + dst[dstBegin++] = value[srcBegin++]; + } + } +} diff -r 388e48c0a37a -r 05224402145d emul/mini/src/main/java/java/io/EOFException.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/emul/mini/src/main/java/java/io/EOFException.java Wed Jan 23 20:39:23 2013 +0100 @@ -0,0 +1,65 @@ +/* + * Copyright (c) 1995, 2008, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code 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 + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package java.io; + +/** + * Signals that an end of file or end of stream has been reached + * unexpectedly during input. + *

+ * This exception is mainly used by data input streams to signal end of + * stream. Note that many other input operations return a special value on + * end of stream rather than throwing an exception. + *

+ * + * @author Frank Yellin + * @see java.io.DataInputStream + * @see java.io.IOException + * @since JDK1.0 + */ +public +class EOFException extends IOException { + private static final long serialVersionUID = 6433858223774886977L; + + /** + * Constructs an EOFException with null + * as its error detail message. + */ + public EOFException() { + super(); + } + + /** + * Constructs an EOFException with the specified detail + * message. The string s may later be retrieved by the + * {@link java.lang.Throwable#getMessage} method of class + * java.lang.Throwable. + * + * @param s the detail message. + */ + public EOFException(String s) { + super(s); + } +} diff -r 388e48c0a37a -r 05224402145d emul/mini/src/main/java/java/io/FilterInputStream.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/emul/mini/src/main/java/java/io/FilterInputStream.java Wed Jan 23 20:39:23 2013 +0100 @@ -0,0 +1,245 @@ +/* + * Copyright (c) 1994, 2010, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code 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 + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package java.io; + +/** + * A FilterInputStream contains + * some other input stream, which it uses as + * its basic source of data, possibly transforming + * the data along the way or providing additional + * functionality. The class FilterInputStream + * itself simply overrides all methods of + * InputStream with versions that + * pass all requests to the contained input + * stream. Subclasses of FilterInputStream + * may further override some of these methods + * and may also provide additional methods + * and fields. + * + * @author Jonathan Payne + * @since JDK1.0 + */ +public +class FilterInputStream extends InputStream { + /** + * The input stream to be filtered. + */ + protected volatile InputStream in; + + /** + * Creates a FilterInputStream + * by assigning the argument in + * to the field this.in so as + * to remember it for later use. + * + * @param in the underlying input stream, or null if + * this instance is to be created without an underlying stream. + */ + protected FilterInputStream(InputStream in) { + this.in = in; + } + + /** + * Reads the next byte of data from this input stream. The value + * byte is returned as an int in the range + * 0 to 255. If no byte is available + * because the end of the stream has been reached, the value + * -1 is returned. This method blocks until input data + * is available, the end of the stream is detected, or an exception + * is thrown. + *

+ * This method + * simply performs in.read() and returns the result. + * + * @return the next byte of data, or -1 if the end of the + * stream is reached. + * @exception IOException if an I/O error occurs. + * @see java.io.FilterInputStream#in + */ + public int read() throws IOException { + return in.read(); + } + + /** + * Reads up to byte.length bytes of data from this + * input stream into an array of bytes. This method blocks until some + * input is available. + *

+ * This method simply performs the call + * read(b, 0, b.length) and returns + * the result. It is important that it does + * not do in.read(b) instead; + * certain subclasses of FilterInputStream + * depend on the implementation strategy actually + * used. + * + * @param b the buffer into which the data is read. + * @return the total number of bytes read into the buffer, or + * -1 if there is no more data because the end of + * the stream has been reached. + * @exception IOException if an I/O error occurs. + * @see java.io.FilterInputStream#read(byte[], int, int) + */ + public int read(byte b[]) throws IOException { + return read(b, 0, b.length); + } + + /** + * Reads up to len bytes of data from this input stream + * into an array of bytes. If len is not zero, the method + * blocks until some input is available; otherwise, no + * bytes are read and 0 is returned. + *

+ * This method simply performs in.read(b, off, len) + * and returns the result. + * + * @param b the buffer into which the data is read. + * @param off the start offset in the destination array b + * @param len the maximum number of bytes read. + * @return the total number of bytes read into the buffer, or + * -1 if there is no more data because the end of + * the stream has been reached. + * @exception NullPointerException If b is null. + * @exception IndexOutOfBoundsException If off is negative, + * len is negative, or len is greater than + * b.length - off + * @exception IOException if an I/O error occurs. + * @see java.io.FilterInputStream#in + */ + public int read(byte b[], int off, int len) throws IOException { + return in.read(b, off, len); + } + + /** + * Skips over and discards n bytes of data from the + * input stream. The skip method may, for a variety of + * reasons, end up skipping over some smaller number of bytes, + * possibly 0. The actual number of bytes skipped is + * returned. + *

+ * This method simply performs in.skip(n). + * + * @param n the number of bytes to be skipped. + * @return the actual number of bytes skipped. + * @exception IOException if the stream does not support seek, + * or if some other I/O error occurs. + */ + public long skip(long n) throws IOException { + return in.skip(n); + } + + /** + * Returns an estimate of the number of bytes that can be read (or + * skipped over) from this input stream without blocking by the next + * caller of a method for this input stream. The next caller might be + * the same thread or another thread. A single read or skip of this + * many bytes will not block, but may read or skip fewer bytes. + *

+ * This method returns the result of {@link #in in}.available(). + * + * @return an estimate of the number of bytes that can be read (or skipped + * over) from this input stream without blocking. + * @exception IOException if an I/O error occurs. + */ + public int available() throws IOException { + return in.available(); + } + + /** + * Closes this input stream and releases any system resources + * associated with the stream. + * This + * method simply performs in.close(). + * + * @exception IOException if an I/O error occurs. + * @see java.io.FilterInputStream#in + */ + public void close() throws IOException { + in.close(); + } + + /** + * Marks the current position in this input stream. A subsequent + * call to the reset method repositions this stream at + * the last marked position so that subsequent reads re-read the same bytes. + *

+ * The readlimit argument tells this input stream to + * allow that many bytes to be read before the mark position gets + * invalidated. + *

+ * This method simply performs in.mark(readlimit). + * + * @param readlimit the maximum limit of bytes that can be read before + * the mark position becomes invalid. + * @see java.io.FilterInputStream#in + * @see java.io.FilterInputStream#reset() + */ + public synchronized void mark(int readlimit) { + in.mark(readlimit); + } + + /** + * Repositions this stream to the position at the time the + * mark method was last called on this input stream. + *

+ * This method + * simply performs in.reset(). + *

+ * Stream marks are intended to be used in + * situations where you need to read ahead a little to see what's in + * the stream. Often this is most easily done by invoking some + * general parser. If the stream is of the type handled by the + * parse, it just chugs along happily. If the stream is not of + * that type, the parser should toss an exception when it fails. + * If this happens within readlimit bytes, it allows the outer + * code to reset the stream and try another parser. + * + * @exception IOException if the stream has not been marked or if the + * mark has been invalidated. + * @see java.io.FilterInputStream#in + * @see java.io.FilterInputStream#mark(int) + */ + public synchronized void reset() throws IOException { + in.reset(); + } + + /** + * Tests if this input stream supports the mark + * and reset methods. + * This method + * simply performs in.markSupported(). + * + * @return true if this stream type supports the + * mark and reset method; + * false otherwise. + * @see java.io.FilterInputStream#in + * @see java.io.InputStream#mark(int) + * @see java.io.InputStream#reset() + */ + public boolean markSupported() { + return in.markSupported(); + } +} diff -r 388e48c0a37a -r 05224402145d emul/mini/src/main/java/java/io/IOException.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/emul/mini/src/main/java/java/io/IOException.java Wed Jan 23 20:39:23 2013 +0100 @@ -0,0 +1,101 @@ +/* + * Copyright (c) 1994, 2006, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code 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 + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package java.io; + +/** + * Signals that an I/O exception of some sort has occurred. This + * class is the general class of exceptions produced by failed or + * interrupted I/O operations. + * + * @author unascribed + * @see java.io.InputStream + * @see java.io.OutputStream + * @since JDK1.0 + */ +public +class IOException extends Exception { + static final long serialVersionUID = 7818375828146090155L; + + /** + * Constructs an {@code IOException} with {@code null} + * as its error detail message. + */ + public IOException() { + super(); + } + + /** + * Constructs an {@code IOException} with the specified detail message. + * + * @param message + * The detail message (which is saved for later retrieval + * by the {@link #getMessage()} method) + */ + public IOException(String message) { + super(message); + } + + /** + * Constructs an {@code IOException} with the specified detail message + * and cause. + * + *

Note that the detail message associated with {@code cause} is + * not automatically incorporated into this exception's detail + * message. + * + * @param message + * The detail message (which is saved for later retrieval + * by the {@link #getMessage()} method) + * + * @param cause + * The cause (which is saved for later retrieval by the + * {@link #getCause()} method). (A null value is permitted, + * and indicates that the cause is nonexistent or unknown.) + * + * @since 1.6 + */ + public IOException(String message, Throwable cause) { + super(message, cause); + } + + /** + * Constructs an {@code IOException} with the specified cause and a + * detail message of {@code (cause==null ? null : cause.toString())} + * (which typically contains the class and detail message of {@code cause}). + * This constructor is useful for IO exceptions that are little more + * than wrappers for other throwables. + * + * @param cause + * The cause (which is saved for later retrieval by the + * {@link #getCause()} method). (A null value is permitted, + * and indicates that the cause is nonexistent or unknown.) + * + * @since 1.6 + */ + public IOException(Throwable cause) { + super(cause); + } +} diff -r 388e48c0a37a -r 05224402145d emul/mini/src/main/java/java/io/InputStream.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/emul/mini/src/main/java/java/io/InputStream.java Wed Jan 23 20:39:23 2013 +0100 @@ -0,0 +1,370 @@ +/* + * Copyright (c) 1994, 2006, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code 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 + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package java.io; + +/** + * This abstract class is the superclass of all classes representing + * an input stream of bytes. + * + *

Applications that need to define a subclass of InputStream + * must always provide a method that returns the next byte of input. + * + * @author Arthur van Hoff + * @see java.io.BufferedInputStream + * @see java.io.ByteArrayInputStream + * @see java.io.DataInputStream + * @see java.io.FilterInputStream + * @see java.io.InputStream#read() + * @see java.io.OutputStream + * @see java.io.PushbackInputStream + * @since JDK1.0 + */ +public abstract class InputStream implements Closeable { + + // SKIP_BUFFER_SIZE is used to determine the size of skipBuffer + private static final int SKIP_BUFFER_SIZE = 2048; + // skipBuffer is initialized in skip(long), if needed. + private static byte[] skipBuffer; + + /** + * Reads the next byte of data from the input stream. The value byte is + * returned as an int in the range 0 to + * 255. If no byte is available because the end of the stream + * has been reached, the value -1 is returned. This method + * blocks until input data is available, the end of the stream is detected, + * or an exception is thrown. + * + *

A subclass must provide an implementation of this method. + * + * @return the next byte of data, or -1 if the end of the + * stream is reached. + * @exception IOException if an I/O error occurs. + */ + public abstract int read() throws IOException; + + /** + * Reads some number of bytes from the input stream and stores them into + * the buffer array b. The number of bytes actually read is + * returned as an integer. This method blocks until input data is + * available, end of file is detected, or an exception is thrown. + * + *

If the length of b is zero, then no bytes are read and + * 0 is returned; otherwise, there is an attempt to read at + * least one byte. If no byte is available because the stream is at the + * end of the file, the value -1 is returned; otherwise, at + * least one byte is read and stored into b. + * + *

The first byte read is stored into element b[0], the + * next one into b[1], and so on. The number of bytes read is, + * at most, equal to the length of b. Let k be the + * number of bytes actually read; these bytes will be stored in elements + * b[0] through b[k-1], + * leaving elements b[k] through + * b[b.length-1] unaffected. + * + *

The read(b) method for class InputStream + * has the same effect as:

 read(b, 0, b.length) 
+ * + * @param b the buffer into which the data is read. + * @return the total number of bytes read into the buffer, or + * -1 if there is no more data because the end of + * the stream has been reached. + * @exception IOException If the first byte cannot be read for any reason + * other than the end of the file, if the input stream has been closed, or + * if some other I/O error occurs. + * @exception NullPointerException if b is null. + * @see java.io.InputStream#read(byte[], int, int) + */ + public int read(byte b[]) throws IOException { + return read(b, 0, b.length); + } + + /** + * Reads up to len bytes of data from the input stream into + * an array of bytes. An attempt is made to read as many as + * len bytes, but a smaller number may be read. + * The number of bytes actually read is returned as an integer. + * + *

This method blocks until input data is available, end of file is + * detected, or an exception is thrown. + * + *

If len is zero, then no bytes are read and + * 0 is returned; otherwise, there is an attempt to read at + * least one byte. If no byte is available because the stream is at end of + * file, the value -1 is returned; otherwise, at least one + * byte is read and stored into b. + * + *

The first byte read is stored into element b[off], the + * next one into b[off+1], and so on. The number of bytes read + * is, at most, equal to len. Let k be the number of + * bytes actually read; these bytes will be stored in elements + * b[off] through b[off+k-1], + * leaving elements b[off+k] through + * b[off+len-1] unaffected. + * + *

In every case, elements b[0] through + * b[off] and elements b[off+len] through + * b[b.length-1] are unaffected. + * + *

The read(b, off, len) method + * for class InputStream simply calls the method + * read() repeatedly. If the first such call results in an + * IOException, that exception is returned from the call to + * the read(b, off, len) method. If + * any subsequent call to read() results in a + * IOException, the exception is caught and treated as if it + * were end of file; the bytes read up to that point are stored into + * b and the number of bytes read before the exception + * occurred is returned. The default implementation of this method blocks + * until the requested amount of input data len has been read, + * end of file is detected, or an exception is thrown. Subclasses are encouraged + * to provide a more efficient implementation of this method. + * + * @param b the buffer into which the data is read. + * @param off the start offset in array b + * at which the data is written. + * @param len the maximum number of bytes to read. + * @return the total number of bytes read into the buffer, or + * -1 if there is no more data because the end of + * the stream has been reached. + * @exception IOException If the first byte cannot be read for any reason + * other than end of file, or if the input stream has been closed, or if + * some other I/O error occurs. + * @exception NullPointerException If b is null. + * @exception IndexOutOfBoundsException If off is negative, + * len is negative, or len is greater than + * b.length - off + * @see java.io.InputStream#read() + */ + public int read(byte b[], int off, int len) throws IOException { + if (b == null) { + throw new NullPointerException(); + } else if (off < 0 || len < 0 || len > b.length - off) { + throw new IndexOutOfBoundsException(); + } else if (len == 0) { + return 0; + } + + int c = read(); + if (c == -1) { + return -1; + } + b[off] = (byte)c; + + int i = 1; + try { + for (; i < len ; i++) { + c = read(); + if (c == -1) { + break; + } + b[off + i] = (byte)c; + } + } catch (IOException ee) { + } + return i; + } + + /** + * Skips over and discards n bytes of data from this input + * stream. The skip method may, for a variety of reasons, end + * up skipping over some smaller number of bytes, possibly 0. + * This may result from any of a number of conditions; reaching end of file + * before n bytes have been skipped is only one possibility. + * The actual number of bytes skipped is returned. If n is + * negative, no bytes are skipped. + * + *

The skip method of this class creates a + * byte array and then repeatedly reads into it until n bytes + * have been read or the end of the stream has been reached. Subclasses are + * encouraged to provide a more efficient implementation of this method. + * For instance, the implementation may depend on the ability to seek. + * + * @param n the number of bytes to be skipped. + * @return the actual number of bytes skipped. + * @exception IOException if the stream does not support seek, + * or if some other I/O error occurs. + */ + public long skip(long n) throws IOException { + + long remaining = n; + int nr; + if (skipBuffer == null) + skipBuffer = new byte[SKIP_BUFFER_SIZE]; + + byte[] localSkipBuffer = skipBuffer; + + if (n <= 0) { + return 0; + } + + while (remaining > 0) { + nr = read(localSkipBuffer, 0, + (int) Math.min(SKIP_BUFFER_SIZE, remaining)); + if (nr < 0) { + break; + } + remaining -= nr; + } + + return n - remaining; + } + + /** + * Returns an estimate of the number of bytes that can be read (or + * skipped over) from this input stream without blocking by the next + * invocation of a method for this input stream. The next invocation + * might be the same thread or another thread. A single read or skip of this + * many bytes will not block, but may read or skip fewer bytes. + * + *

Note that while some implementations of {@code InputStream} will return + * the total number of bytes in the stream, many will not. It is + * never correct to use the return value of this method to allocate + * a buffer intended to hold all data in this stream. + * + *

A subclass' implementation of this method may choose to throw an + * {@link IOException} if this input stream has been closed by + * invoking the {@link #close()} method. + * + *

The {@code available} method for class {@code InputStream} always + * returns {@code 0}. + * + *

This method should be overridden by subclasses. + * + * @return an estimate of the number of bytes that can be read (or skipped + * over) from this input stream without blocking or {@code 0} when + * it reaches the end of the input stream. + * @exception IOException if an I/O error occurs. + */ + public int available() throws IOException { + return 0; + } + + /** + * Closes this input stream and releases any system resources associated + * with the stream. + * + *

The close method of InputStream does + * nothing. + * + * @exception IOException if an I/O error occurs. + */ + public void close() throws IOException {} + + /** + * Marks the current position in this input stream. A subsequent call to + * the reset method repositions this stream at the last marked + * position so that subsequent reads re-read the same bytes. + * + *

The readlimit arguments tells this input stream to + * allow that many bytes to be read before the mark position gets + * invalidated. + * + *

The general contract of mark is that, if the method + * markSupported returns true, the stream somehow + * remembers all the bytes read after the call to mark and + * stands ready to supply those same bytes again if and whenever the method + * reset is called. However, the stream is not required to + * remember any data at all if more than readlimit bytes are + * read from the stream before reset is called. + * + *

Marking a closed stream should not have any effect on the stream. + * + *

The mark method of InputStream does + * nothing. + * + * @param readlimit the maximum limit of bytes that can be read before + * the mark position becomes invalid. + * @see java.io.InputStream#reset() + */ + public synchronized void mark(int readlimit) {} + + /** + * Repositions this stream to the position at the time the + * mark method was last called on this input stream. + * + *

The general contract of reset is: + * + *

    + * + *
  • If the method markSupported returns + * true, then: + * + *
    • If the method mark has not been called since + * the stream was created, or the number of bytes read from the stream + * since mark was last called is larger than the argument + * to mark at that last call, then an + * IOException might be thrown. + * + *
    • If such an IOException is not thrown, then the + * stream is reset to a state such that all the bytes read since the + * most recent call to mark (or since the start of the + * file, if mark has not been called) will be resupplied + * to subsequent callers of the read method, followed by + * any bytes that otherwise would have been the next input data as of + * the time of the call to reset.
    + * + *
  • If the method markSupported returns + * false, then: + * + *
    • The call to reset may throw an + * IOException. + * + *
    • If an IOException is not thrown, then the stream + * is reset to a fixed state that depends on the particular type of the + * input stream and how it was created. The bytes that will be supplied + * to subsequent callers of the read method depend on the + * particular type of the input stream.
+ * + *

The method reset for class InputStream + * does nothing except throw an IOException. + * + * @exception IOException if this stream has not been marked or if the + * mark has been invalidated. + * @see java.io.InputStream#mark(int) + * @see java.io.IOException + */ + public synchronized void reset() throws IOException { + throw new IOException("mark/reset not supported"); + } + + /** + * Tests if this input stream supports the mark and + * reset methods. Whether or not mark and + * reset are supported is an invariant property of a + * particular input stream instance. The markSupported method + * of InputStream returns false. + * + * @return true if this stream instance supports the mark + * and reset methods; false otherwise. + * @see java.io.InputStream#mark(int) + * @see java.io.InputStream#reset() + */ + public boolean markSupported() { + return false; + } + +} diff -r 388e48c0a37a -r 05224402145d emul/mini/src/main/java/java/io/PushbackInputStream.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/emul/mini/src/main/java/java/io/PushbackInputStream.java Wed Jan 23 20:39:23 2013 +0100 @@ -0,0 +1,388 @@ +/* + * Copyright (c) 1994, 2011, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code 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 + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package java.io; + +/** + * A PushbackInputStream adds + * functionality to another input stream, namely + * the ability to "push back" or "unread" + * one byte. This is useful in situations where + * it is convenient for a fragment of code + * to read an indefinite number of data bytes + * that are delimited by a particular byte + * value; after reading the terminating byte, + * the code fragment can "unread" it, so that + * the next read operation on the input stream + * will reread the byte that was pushed back. + * For example, bytes representing the characters + * constituting an identifier might be terminated + * by a byte representing an operator character; + * a method whose job is to read just an identifier + * can read until it sees the operator and + * then push the operator back to be re-read. + * + * @author David Connelly + * @author Jonathan Payne + * @since JDK1.0 + */ +public +class PushbackInputStream extends FilterInputStream { + /** + * The pushback buffer. + * @since JDK1.1 + */ + protected byte[] buf; + + /** + * The position within the pushback buffer from which the next byte will + * be read. When the buffer is empty, pos is equal to + * buf.length; when the buffer is full, pos is + * equal to zero. + * + * @since JDK1.1 + */ + protected int pos; + + /** + * Check to make sure that this stream has not been closed + */ + private void ensureOpen() throws IOException { + if (in == null) + throw new IOException("Stream closed"); + } + + /** + * Creates a PushbackInputStream + * with a pushback buffer of the specified size, + * and saves its argument, the input stream + * in, for later use. Initially, + * there is no pushed-back byte (the field + * pushBack is initialized to + * -1). + * + * @param in the input stream from which bytes will be read. + * @param size the size of the pushback buffer. + * @exception IllegalArgumentException if size is <= 0 + * @since JDK1.1 + */ + public PushbackInputStream(InputStream in, int size) { + super(in); + if (size <= 0) { + throw new IllegalArgumentException("size <= 0"); + } + this.buf = new byte[size]; + this.pos = size; + } + + /** + * Creates a PushbackInputStream + * and saves its argument, the input stream + * in, for later use. Initially, + * there is no pushed-back byte (the field + * pushBack is initialized to + * -1). + * + * @param in the input stream from which bytes will be read. + */ + public PushbackInputStream(InputStream in) { + this(in, 1); + } + + /** + * Reads the next byte of data from this input stream. The value + * byte is returned as an int in the range + * 0 to 255. If no byte is available + * because the end of the stream has been reached, the value + * -1 is returned. This method blocks until input data + * is available, the end of the stream is detected, or an exception + * is thrown. + * + *

This method returns the most recently pushed-back byte, if there is + * one, and otherwise calls the read method of its underlying + * input stream and returns whatever value that method returns. + * + * @return the next byte of data, or -1 if the end of the + * stream has been reached. + * @exception IOException if this input stream has been closed by + * invoking its {@link #close()} method, + * or an I/O error occurs. + * @see java.io.InputStream#read() + */ + public int read() throws IOException { + ensureOpen(); + if (pos < buf.length) { + return buf[pos++] & 0xff; + } + return super.read(); + } + + /** + * Reads up to len bytes of data from this input stream into + * an array of bytes. This method first reads any pushed-back bytes; after + * that, if fewer than len bytes have been read then it + * reads from the underlying input stream. If len is not zero, the method + * blocks until at least 1 byte of input is available; otherwise, no + * bytes are read and 0 is returned. + * + * @param b the buffer into which the data is read. + * @param off the start offset in the destination array b + * @param len the maximum number of bytes read. + * @return the total number of bytes read into the buffer, or + * -1 if there is no more data because the end of + * the stream has been reached. + * @exception NullPointerException If b is null. + * @exception IndexOutOfBoundsException If off is negative, + * len is negative, or len is greater than + * b.length - off + * @exception IOException if this input stream has been closed by + * invoking its {@link #close()} method, + * or an I/O error occurs. + * @see java.io.InputStream#read(byte[], int, int) + */ + public int read(byte[] b, int off, int len) throws IOException { + ensureOpen(); + if (b == null) { + throw new NullPointerException(); + } else if (off < 0 || len < 0 || len > b.length - off) { + throw new IndexOutOfBoundsException(); + } else if (len == 0) { + return 0; + } + + int avail = buf.length - pos; + if (avail > 0) { + if (len < avail) { + avail = len; + } + arraycopy(buf, pos, b, off, avail); + pos += avail; + off += avail; + len -= avail; + } + if (len > 0) { + len = super.read(b, off, len); + if (len == -1) { + return avail == 0 ? -1 : avail; + } + return avail + len; + } + return avail; + } + + /** + * Pushes back a byte by copying it to the front of the pushback buffer. + * After this method returns, the next byte to be read will have the value + * (byte)b. + * + * @param b the int value whose low-order + * byte is to be pushed back. + * @exception IOException If there is not enough room in the pushback + * buffer for the byte, or this input stream has been closed by + * invoking its {@link #close()} method. + */ + public void unread(int b) throws IOException { + ensureOpen(); + if (pos == 0) { + throw new IOException("Push back buffer is full"); + } + buf[--pos] = (byte)b; + } + + /** + * Pushes back a portion of an array of bytes by copying it to the front + * of the pushback buffer. After this method returns, the next byte to be + * read will have the value b[off], the byte after that will + * have the value b[off+1], and so forth. + * + * @param b the byte array to push back. + * @param off the start offset of the data. + * @param len the number of bytes to push back. + * @exception IOException If there is not enough room in the pushback + * buffer for the specified number of bytes, + * or this input stream has been closed by + * invoking its {@link #close()} method. + * @since JDK1.1 + */ + public void unread(byte[] b, int off, int len) throws IOException { + ensureOpen(); + if (len > pos) { + throw new IOException("Push back buffer is full"); + } + pos -= len; + arraycopy(b, off, buf, pos, len); + } + + /** + * Pushes back an array of bytes by copying it to the front of the + * pushback buffer. After this method returns, the next byte to be read + * will have the value b[0], the byte after that will have the + * value b[1], and so forth. + * + * @param b the byte array to push back + * @exception IOException If there is not enough room in the pushback + * buffer for the specified number of bytes, + * or this input stream has been closed by + * invoking its {@link #close()} method. + * @since JDK1.1 + */ + public void unread(byte[] b) throws IOException { + unread(b, 0, b.length); + } + + /** + * Returns an estimate of the number of bytes that can be read (or + * skipped over) from this input stream without blocking by the next + * invocation of a method for this input stream. The next invocation might be + * the same thread or another thread. A single read or skip of this + * many bytes will not block, but may read or skip fewer bytes. + * + *

The method returns the sum of the number of bytes that have been + * pushed back and the value returned by {@link + * java.io.FilterInputStream#available available}. + * + * @return the number of bytes that can be read (or skipped over) from + * the input stream without blocking. + * @exception IOException if this input stream has been closed by + * invoking its {@link #close()} method, + * or an I/O error occurs. + * @see java.io.FilterInputStream#in + * @see java.io.InputStream#available() + */ + public int available() throws IOException { + ensureOpen(); + int n = buf.length - pos; + int avail = super.available(); + return n > (Integer.MAX_VALUE - avail) + ? Integer.MAX_VALUE + : n + avail; + } + + /** + * Skips over and discards n bytes of data from this + * input stream. The skip method may, for a variety of + * reasons, end up skipping over some smaller number of bytes, + * possibly zero. If n is negative, no bytes are skipped. + * + *

The skip method of PushbackInputStream + * first skips over the bytes in the pushback buffer, if any. It then + * calls the skip method of the underlying input stream if + * more bytes need to be skipped. The actual number of bytes skipped + * is returned. + * + * @param n {@inheritDoc} + * @return {@inheritDoc} + * @exception IOException if the stream does not support seek, + * or the stream has been closed by + * invoking its {@link #close()} method, + * or an I/O error occurs. + * @see java.io.FilterInputStream#in + * @see java.io.InputStream#skip(long n) + * @since 1.2 + */ + public long skip(long n) throws IOException { + ensureOpen(); + if (n <= 0) { + return 0; + } + + long pskip = buf.length - pos; + if (pskip > 0) { + if (n < pskip) { + pskip = n; + } + pos += pskip; + n -= pskip; + } + if (n > 0) { + pskip += super.skip(n); + } + return pskip; + } + + /** + * Tests if this input stream supports the mark and + * reset methods, which it does not. + * + * @return false, since this class does not support the + * mark and reset methods. + * @see java.io.InputStream#mark(int) + * @see java.io.InputStream#reset() + */ + public boolean markSupported() { + return false; + } + + /** + * Marks the current position in this input stream. + * + *

The mark method of PushbackInputStream + * does nothing. + * + * @param readlimit the maximum limit of bytes that can be read before + * the mark position becomes invalid. + * @see java.io.InputStream#reset() + */ + public synchronized void mark(int readlimit) { + } + + /** + * Repositions this stream to the position at the time the + * mark method was last called on this input stream. + * + *

The method reset for class + * PushbackInputStream does nothing except throw an + * IOException. + * + * @exception IOException if this method is invoked. + * @see java.io.InputStream#mark(int) + * @see java.io.IOException + */ + public synchronized void reset() throws IOException { + throw new IOException("mark/reset not supported"); + } + + /** + * Closes this input stream and releases any system resources + * associated with the stream. + * Once the stream has been closed, further read(), unread(), + * available(), reset(), or skip() invocations will throw an IOException. + * Closing a previously closed stream has no effect. + * + * @exception IOException if an I/O error occurs. + */ + public synchronized void close() throws IOException { + if (in == null) + return; + in.close(); + in = null; + buf = null; + } + static void arraycopy(byte[] value, int srcBegin, byte[] dst, int dstBegin, int count) { + while (count-- > 0) { + dst[dstBegin++] = value[srcBegin++]; + } + } +} diff -r 388e48c0a37a -r 05224402145d emul/mini/src/main/java/java/io/Serializable.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/emul/mini/src/main/java/java/io/Serializable.java Wed Jan 23 20:39:23 2013 +0100 @@ -0,0 +1,170 @@ +/* + * Copyright (c) 1996, 2005, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code 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 + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package java.io; + +/** + * Serializability of a class is enabled by the class implementing the + * java.io.Serializable interface. Classes that do not implement this + * interface will not have any of their state serialized or + * deserialized. All subtypes of a serializable class are themselves + * serializable. The serialization interface has no methods or fields + * and serves only to identify the semantics of being serializable.

+ * + * To allow subtypes of non-serializable classes to be serialized, the + * subtype may assume responsibility for saving and restoring the + * state of the supertype's public, protected, and (if accessible) + * package fields. The subtype may assume this responsibility only if + * the class it extends has an accessible no-arg constructor to + * initialize the class's state. It is an error to declare a class + * Serializable if this is not the case. The error will be detected at + * runtime.

+ * + * During deserialization, the fields of non-serializable classes will + * be initialized using the public or protected no-arg constructor of + * the class. A no-arg constructor must be accessible to the subclass + * that is serializable. The fields of serializable subclasses will + * be restored from the stream.

+ * + * When traversing a graph, an object may be encountered that does not + * support the Serializable interface. In this case the + * NotSerializableException will be thrown and will identify the class + * of the non-serializable object.

+ * + * Classes that require special handling during the serialization and + * deserialization process must implement special methods with these exact + * signatures:

+ * + *

+ * private void writeObject(java.io.ObjectOutputStream out)
+ *     throws IOException
+ * private void readObject(java.io.ObjectInputStream in)
+ *     throws IOException, ClassNotFoundException;
+ * private void readObjectNoData()
+ *     throws ObjectStreamException;
+ * 
+ * + *

The writeObject method is responsible for writing the state of the + * object for its particular class so that the corresponding + * readObject method can restore it. The default mechanism for saving + * the Object's fields can be invoked by calling + * out.defaultWriteObject. The method does not need to concern + * itself with the state belonging to its superclasses or subclasses. + * State is saved by writing the individual fields to the + * ObjectOutputStream using the writeObject method or by using the + * methods for primitive data types supported by DataOutput. + * + *

The readObject method is responsible for reading from the stream and + * restoring the classes fields. It may call in.defaultReadObject to invoke + * the default mechanism for restoring the object's non-static and + * non-transient fields. The defaultReadObject method uses information in + * the stream to assign the fields of the object saved in the stream with the + * correspondingly named fields in the current object. This handles the case + * when the class has evolved to add new fields. The method does not need to + * concern itself with the state belonging to its superclasses or subclasses. + * State is saved by writing the individual fields to the + * ObjectOutputStream using the writeObject method or by using the + * methods for primitive data types supported by DataOutput. + * + *

The readObjectNoData method is responsible for initializing the state of + * the object for its particular class in the event that the serialization + * stream does not list the given class as a superclass of the object being + * deserialized. This may occur in cases where the receiving party uses a + * different version of the deserialized instance's class than the sending + * party, and the receiver's version extends classes that are not extended by + * the sender's version. This may also occur if the serialization stream has + * been tampered; hence, readObjectNoData is useful for initializing + * deserialized objects properly despite a "hostile" or incomplete source + * stream. + * + *

Serializable classes that need to designate an alternative object to be + * used when writing an object to the stream should implement this + * special method with the exact signature:

+ * + *

+ * ANY-ACCESS-MODIFIER Object writeReplace() throws ObjectStreamException;
+ * 

+ * + * This writeReplace method is invoked by serialization if the method + * exists and it would be accessible from a method defined within the + * class of the object being serialized. Thus, the method can have private, + * protected and package-private access. Subclass access to this method + * follows java accessibility rules.

+ * + * Classes that need to designate a replacement when an instance of it + * is read from the stream should implement this special method with the + * exact signature.

+ * + *

+ * ANY-ACCESS-MODIFIER Object readResolve() throws ObjectStreamException;
+ * 

+ * + * This readResolve method follows the same invocation rules and + * accessibility rules as writeReplace.

+ * + * The serialization runtime associates with each serializable class a version + * number, called a serialVersionUID, which is used during deserialization to + * verify that the sender and receiver of a serialized object have loaded + * classes for that object that are compatible with respect to serialization. + * If the receiver has loaded a class for the object that has a different + * serialVersionUID than that of the corresponding sender's class, then + * deserialization will result in an {@link InvalidClassException}. A + * serializable class can declare its own serialVersionUID explicitly by + * declaring a field named "serialVersionUID" that must be static, + * final, and of type long:

+ * + *

+ * ANY-ACCESS-MODIFIER static final long serialVersionUID = 42L;
+ * 
+ * + * If a serializable class does not explicitly declare a serialVersionUID, then + * the serialization runtime will calculate a default serialVersionUID value + * for that class based on various aspects of the class, as described in the + * Java(TM) Object Serialization Specification. However, it is strongly + * recommended that all serializable classes explicitly declare + * serialVersionUID values, since the default serialVersionUID computation is + * highly sensitive to class details that may vary depending on compiler + * implementations, and can thus result in unexpected + * InvalidClassExceptions during deserialization. Therefore, to + * guarantee a consistent serialVersionUID value across different java compiler + * implementations, a serializable class must declare an explicit + * serialVersionUID value. It is also strongly advised that explicit + * serialVersionUID declarations use the private modifier where + * possible, since such declarations apply only to the immediately declaring + * class--serialVersionUID fields are not useful as inherited members. Array + * classes cannot declare an explicit serialVersionUID, so they always have + * the default computed value, but the requirement for matching + * serialVersionUID values is waived for array classes. + * + * @author unascribed + * @see java.io.ObjectOutputStream + * @see java.io.ObjectInputStream + * @see java.io.ObjectOutput + * @see java.io.ObjectInput + * @see java.io.Externalizable + * @since JDK1.1 + */ +public interface Serializable { +} diff -r 388e48c0a37a -r 05224402145d emul/mini/src/main/java/java/io/UTFDataFormatException.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/emul/mini/src/main/java/java/io/UTFDataFormatException.java Wed Jan 23 20:39:23 2013 +0100 @@ -0,0 +1,69 @@ +/* + * Copyright (c) 1995, 2008, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code 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 + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package java.io; + +/** + * Signals that a malformed string in + * modified UTF-8 + * format has been read in a data + * input stream or by any class that implements the data input + * interface. + * See the + * DataInput + * class description for the format in + * which modified UTF-8 strings are read and written. + * + * @author Frank Yellin + * @see java.io.DataInput + * @see java.io.DataInputStream#readUTF(java.io.DataInput) + * @see java.io.IOException + * @since JDK1.0 + */ +public +class UTFDataFormatException extends IOException { + private static final long serialVersionUID = 420743449228280612L; + + /** + * Constructs a UTFDataFormatException with + * null as its error detail message. + */ + public UTFDataFormatException() { + super(); + } + + /** + * Constructs a UTFDataFormatException with the + * specified detail message. The string s can be + * retrieved later by the + * {@link java.lang.Throwable#getMessage} + * method of class java.lang.Throwable. + * + * @param s the detail message. + */ + public UTFDataFormatException(String s) { + super(s); + } +} diff -r 388e48c0a37a -r 05224402145d emul/mini/src/main/java/java/io/UnsupportedEncodingException.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/emul/mini/src/main/java/java/io/UnsupportedEncodingException.java Wed Jan 23 20:39:23 2013 +0100 @@ -0,0 +1,52 @@ +/* + * Copyright (c) 1996, 2008, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code 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 + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +package java.io; + +/** + * The Character Encoding is not supported. + * + * @author Asmus Freytag + * @since JDK1.1 + */ +public class UnsupportedEncodingException + extends IOException +{ + private static final long serialVersionUID = -4274276298326136670L; + + /** + * Constructs an UnsupportedEncodingException without a detail message. + */ + public UnsupportedEncodingException() { + super(); + } + + /** + * Constructs an UnsupportedEncodingException with a detail message. + * @param s Describes the reason for the exception. + */ + public UnsupportedEncodingException(String s) { + super(s); + } +} diff -r 388e48c0a37a -r 05224402145d emul/mini/src/main/java/java/lang/AbstractStringBuilder.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/emul/mini/src/main/java/java/lang/AbstractStringBuilder.java Wed Jan 23 20:39:23 2013 +0100 @@ -0,0 +1,1424 @@ +/* + * Copyright (c) 2003, 2010, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code 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 + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package java.lang; + +/** + * A mutable sequence of characters. + *

+ * Implements a modifiable string. At any point in time it contains some + * particular sequence of characters, but the length and content of the + * sequence can be changed through certain method calls. + * + * @author Michael McCloskey + * @author Martin Buchholz + * @author Ulf Zibis + * @since 1.5 + */ +abstract class AbstractStringBuilder implements Appendable, CharSequence { + /** + * The value is used for character storage. + */ + char[] value; + + /** + * The count is the number of characters used. + */ + int count; + + /** + * This no-arg constructor is necessary for serialization of subclasses. + */ + AbstractStringBuilder() { + } + + /** + * Creates an AbstractStringBuilder of the specified capacity. + */ + AbstractStringBuilder(int capacity) { + value = new char[capacity]; + } + + /** + * Returns the length (character count). + * + * @return the length of the sequence of characters currently + * represented by this object + */ + public int length() { + return count; + } + + /** + * Returns the current capacity. The capacity is the amount of storage + * available for newly inserted characters, beyond which an allocation + * will occur. + * + * @return the current capacity + */ + public int capacity() { + return value.length; + } + + /** + * Ensures that the capacity is at least equal to the specified minimum. + * If the current capacity is less than the argument, then a new internal + * array is allocated with greater capacity. The new capacity is the + * larger of: + *

    + *
  • The minimumCapacity argument. + *
  • Twice the old capacity, plus 2. + *
+ * If the minimumCapacity argument is nonpositive, this + * method takes no action and simply returns. + * + * @param minimumCapacity the minimum desired capacity. + */ + public void ensureCapacity(int minimumCapacity) { + if (minimumCapacity > 0) + ensureCapacityInternal(minimumCapacity); + } + + /** + * This method has the same contract as ensureCapacity, but is + * never synchronized. + */ + private void ensureCapacityInternal(int minimumCapacity) { + // overflow-conscious code + if (minimumCapacity - value.length > 0) + expandCapacity(minimumCapacity); + } + + /** + * This implements the expansion semantics of ensureCapacity with no + * size check or synchronization. + */ + void expandCapacity(int minimumCapacity) { + int newCapacity = value.length * 2 + 2; + if (newCapacity - minimumCapacity < 0) + newCapacity = minimumCapacity; + if (newCapacity < 0) { + if (minimumCapacity < 0) // overflow + throw new OutOfMemoryError(); + newCapacity = Integer.MAX_VALUE; + } + value = copyOf(value, newCapacity); + } + + /** + * Attempts to reduce storage used for the character sequence. + * If the buffer is larger than necessary to hold its current sequence of + * characters, then it may be resized to become more space efficient. + * Calling this method may, but is not required to, affect the value + * returned by a subsequent call to the {@link #capacity()} method. + */ + public void trimToSize() { + if (count < value.length) { + value = copyOf(value, count); + } + } + + /** + * Sets the length of the character sequence. + * The sequence is changed to a new character sequence + * whose length is specified by the argument. For every nonnegative + * index k less than newLength, the character at + * index k in the new character sequence is the same as the + * character at index k in the old sequence if k is less + * than the length of the old character sequence; otherwise, it is the + * null character '\u0000'. + * + * In other words, if the newLength argument is less than + * the current length, the length is changed to the specified length. + *

+ * If the newLength argument is greater than or equal + * to the current length, sufficient null characters + * ('\u0000') are appended so that + * length becomes the newLength argument. + *

+ * The newLength argument must be greater than or equal + * to 0. + * + * @param newLength the new length + * @throws IndexOutOfBoundsException if the + * newLength argument is negative. + */ + public void setLength(int newLength) { + if (newLength < 0) + throw new StringIndexOutOfBoundsException(newLength); + ensureCapacityInternal(newLength); + + if (count < newLength) { + for (; count < newLength; count++) + value[count] = '\0'; + } else { + count = newLength; + } + } + + /** + * Returns the char value in this sequence at the specified index. + * The first char value is at index 0, the next at index + * 1, and so on, as in array indexing. + *

+ * The index argument must be greater than or equal to + * 0, and less than the length of this sequence. + * + *

If the char value specified by the index is a + * surrogate, the surrogate + * value is returned. + * + * @param index the index of the desired char value. + * @return the char value at the specified index. + * @throws IndexOutOfBoundsException if index is + * negative or greater than or equal to length(). + */ + public char charAt(int index) { + if ((index < 0) || (index >= count)) + throw new StringIndexOutOfBoundsException(index); + return value[index]; + } + + /** + * Returns the character (Unicode code point) at the specified + * index. The index refers to char values + * (Unicode code units) and ranges from 0 to + * {@link #length()} - 1. + * + *

If the char value specified at the given index + * is in the high-surrogate range, the following index is less + * than the length of this sequence, and the + * char value at the following index is in the + * low-surrogate range, then the supplementary code point + * corresponding to this surrogate pair is returned. Otherwise, + * the char value at the given index is returned. + * + * @param index the index to the char values + * @return the code point value of the character at the + * index + * @exception IndexOutOfBoundsException if the index + * argument is negative or not less than the length of this + * sequence. + */ + public int codePointAt(int index) { + if ((index < 0) || (index >= count)) { + throw new StringIndexOutOfBoundsException(index); + } + return Character.codePointAt(value, index); + } + + /** + * Returns the character (Unicode code point) before the specified + * index. The index refers to char values + * (Unicode code units) and ranges from 1 to {@link + * #length()}. + * + *

If the char value at (index - 1) + * is in the low-surrogate range, (index - 2) is not + * negative, and the char value at (index - + * 2) is in the high-surrogate range, then the + * supplementary code point value of the surrogate pair is + * returned. If the char value at index - + * 1 is an unpaired low-surrogate or a high-surrogate, the + * surrogate value is returned. + * + * @param index the index following the code point that should be returned + * @return the Unicode code point value before the given index. + * @exception IndexOutOfBoundsException if the index + * argument is less than 1 or greater than the length + * of this sequence. + */ + public int codePointBefore(int index) { + int i = index - 1; + if ((i < 0) || (i >= count)) { + throw new StringIndexOutOfBoundsException(index); + } + return Character.codePointBefore(value, index); + } + + /** + * Returns the number of Unicode code points in the specified text + * range of this sequence. The text range begins at the specified + * beginIndex and extends to the char at + * index endIndex - 1. Thus the length (in + * chars) of the text range is + * endIndex-beginIndex. Unpaired surrogates within + * this sequence count as one code point each. + * + * @param beginIndex the index to the first char of + * the text range. + * @param endIndex the index after the last char of + * the text range. + * @return the number of Unicode code points in the specified text + * range + * @exception IndexOutOfBoundsException if the + * beginIndex is negative, or endIndex + * is larger than the length of this sequence, or + * beginIndex is larger than endIndex. + */ + public int codePointCount(int beginIndex, int endIndex) { + if (beginIndex < 0 || endIndex > count || beginIndex > endIndex) { + throw new IndexOutOfBoundsException(); + } + return Character.codePointCountImpl(value, beginIndex, endIndex-beginIndex); + } + + /** + * Returns the index within this sequence that is offset from the + * given index by codePointOffset code + * points. Unpaired surrogates within the text range given by + * index and codePointOffset count as + * one code point each. + * + * @param index the index to be offset + * @param codePointOffset the offset in code points + * @return the index within this sequence + * @exception IndexOutOfBoundsException if index + * is negative or larger then the length of this sequence, + * or if codePointOffset is positive and the subsequence + * starting with index has fewer than + * codePointOffset code points, + * or if codePointOffset is negative and the subsequence + * before index has fewer than the absolute value of + * codePointOffset code points. + */ + public int offsetByCodePoints(int index, int codePointOffset) { + if (index < 0 || index > count) { + throw new IndexOutOfBoundsException(); + } + return Character.offsetByCodePointsImpl(value, 0, count, + index, codePointOffset); + } + + /** + * Characters are copied from this sequence into the + * destination character array dst. The first character to + * be copied is at index srcBegin; the last character to + * be copied is at index srcEnd-1. The total number of + * characters to be copied is srcEnd-srcBegin. The + * characters are copied into the subarray of dst starting + * at index dstBegin and ending at index: + *

+     * dstbegin + (srcEnd-srcBegin) - 1
+     * 
+ * + * @param srcBegin start copying at this offset. + * @param srcEnd stop copying at this offset. + * @param dst the array to copy the data into. + * @param dstBegin offset into dst. + * @throws NullPointerException if dst is + * null. + * @throws IndexOutOfBoundsException if any of the following is true: + *
    + *
  • srcBegin is negative + *
  • dstBegin is negative + *
  • the srcBegin argument is greater than + * the srcEnd argument. + *
  • srcEnd is greater than + * this.length(). + *
  • dstBegin+srcEnd-srcBegin is greater than + * dst.length + *
+ */ + public void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin) + { + if (srcBegin < 0) + throw new StringIndexOutOfBoundsException(srcBegin); + if ((srcEnd < 0) || (srcEnd > count)) + throw new StringIndexOutOfBoundsException(srcEnd); + if (srcBegin > srcEnd) + throw new StringIndexOutOfBoundsException("srcBegin > srcEnd"); + arraycopy(value, srcBegin, dst, dstBegin, srcEnd - srcBegin); + } + + /** + * The character at the specified index is set to ch. This + * sequence is altered to represent a new character sequence that is + * identical to the old character sequence, except that it contains the + * character ch at position index. + *

+ * The index argument must be greater than or equal to + * 0, and less than the length of this sequence. + * + * @param index the index of the character to modify. + * @param ch the new character. + * @throws IndexOutOfBoundsException if index is + * negative or greater than or equal to length(). + */ + public void setCharAt(int index, char ch) { + if ((index < 0) || (index >= count)) + throw new StringIndexOutOfBoundsException(index); + value[index] = ch; + } + + /** + * Appends the string representation of the {@code Object} argument. + *

+ * The overall effect is exactly as if the argument were converted + * to a string by the method {@link String#valueOf(Object)}, + * and the characters of that string were then + * {@link #append(String) appended} to this character sequence. + * + * @param obj an {@code Object}. + * @return a reference to this object. + */ + public AbstractStringBuilder append(Object obj) { + return append(String.valueOf(obj)); + } + + /** + * Appends the specified string to this character sequence. + *

+ * The characters of the {@code String} argument are appended, in + * order, increasing the length of this sequence by the length of the + * argument. If {@code str} is {@code null}, then the four + * characters {@code "null"} are appended. + *

+ * Let n be the length of this character sequence just prior to + * execution of the {@code append} method. Then the character at + * index k in the new character sequence is equal to the character + * at index k in the old character sequence, if k is less + * than n; otherwise, it is equal to the character at index + * k-n in the argument {@code str}. + * + * @param str a string. + * @return a reference to this object. + */ + public AbstractStringBuilder append(String str) { + if (str == null) str = "null"; + int len = str.length(); + ensureCapacityInternal(count + len); + str.getChars(0, len, value, count); + count += len; + return this; + } + + // Documentation in subclasses because of synchro difference + public AbstractStringBuilder append(StringBuffer sb) { + if (sb == null) + return append("null"); + int len = sb.length(); + ensureCapacityInternal(count + len); + sb.getChars(0, len, value, count); + count += len; + return this; + } + + // Documentation in subclasses because of synchro difference + public AbstractStringBuilder append(CharSequence s) { + if (s == null) + s = "null"; + if (s instanceof String) + return this.append((String)s); + if (s instanceof StringBuffer) + return this.append((StringBuffer)s); + return this.append(s, 0, s.length()); + } + + /** + * Appends a subsequence of the specified {@code CharSequence} to this + * sequence. + *

+ * Characters of the argument {@code s}, starting at + * index {@code start}, are appended, in order, to the contents of + * this sequence up to the (exclusive) index {@code end}. The length + * of this sequence is increased by the value of {@code end - start}. + *

+ * Let n be the length of this character sequence just prior to + * execution of the {@code append} method. Then the character at + * index k in this character sequence becomes equal to the + * character at index k in this sequence, if k is less than + * n; otherwise, it is equal to the character at index + * k+start-n in the argument {@code s}. + *

+ * If {@code s} is {@code null}, then this method appends + * characters as if the s parameter was a sequence containing the four + * characters {@code "null"}. + * + * @param s the sequence to append. + * @param start the starting index of the subsequence to be appended. + * @param end the end index of the subsequence to be appended. + * @return a reference to this object. + * @throws IndexOutOfBoundsException if + * {@code start} is negative, or + * {@code start} is greater than {@code end} or + * {@code end} is greater than {@code s.length()} + */ + public AbstractStringBuilder append(CharSequence s, int start, int end) { + if (s == null) + s = "null"; + if ((start < 0) || (start > end) || (end > s.length())) + throw new IndexOutOfBoundsException( + "start " + start + ", end " + end + ", s.length() " + + s.length()); + int len = end - start; + ensureCapacityInternal(count + len); + for (int i = start, j = count; i < end; i++, j++) + value[j] = s.charAt(i); + count += len; + return this; + } + + /** + * Appends the string representation of the {@code char} array + * argument to this sequence. + *

+ * The characters of the array argument are appended, in order, to + * the contents of this sequence. The length of this sequence + * increases by the length of the argument. + *

+ * The overall effect is exactly as if the argument were converted + * to a string by the method {@link String#valueOf(char[])}, + * and the characters of that string were then + * {@link #append(String) appended} to this character sequence. + * + * @param str the characters to be appended. + * @return a reference to this object. + */ + public AbstractStringBuilder append(char[] str) { + int len = str.length; + ensureCapacityInternal(count + len); + arraycopy(str, 0, value, count, len); + count += len; + return this; + } + + /** + * Appends the string representation of a subarray of the + * {@code char} array argument to this sequence. + *

+ * Characters of the {@code char} array {@code str}, starting at + * index {@code offset}, are appended, in order, to the contents + * of this sequence. The length of this sequence increases + * by the value of {@code len}. + *

+ * The overall effect is exactly as if the arguments were converted + * to a string by the method {@link String#valueOf(char[],int,int)}, + * and the characters of that string were then + * {@link #append(String) appended} to this character sequence. + * + * @param str the characters to be appended. + * @param offset the index of the first {@code char} to append. + * @param len the number of {@code char}s to append. + * @return a reference to this object. + * @throws IndexOutOfBoundsException + * if {@code offset < 0} or {@code len < 0} + * or {@code offset+len > str.length} + */ + public AbstractStringBuilder append(char str[], int offset, int len) { + if (len > 0) // let arraycopy report AIOOBE for len < 0 + ensureCapacityInternal(count + len); + arraycopy(str, offset, value, count, len); + count += len; + return this; + } + + /** + * Appends the string representation of the {@code boolean} + * argument to the sequence. + *

+ * The overall effect is exactly as if the argument were converted + * to a string by the method {@link String#valueOf(boolean)}, + * and the characters of that string were then + * {@link #append(String) appended} to this character sequence. + * + * @param b a {@code boolean}. + * @return a reference to this object. + */ + public AbstractStringBuilder append(boolean b) { + if (b) { + ensureCapacityInternal(count + 4); + value[count++] = 't'; + value[count++] = 'r'; + value[count++] = 'u'; + value[count++] = 'e'; + } else { + ensureCapacityInternal(count + 5); + value[count++] = 'f'; + value[count++] = 'a'; + value[count++] = 'l'; + value[count++] = 's'; + value[count++] = 'e'; + } + return this; + } + + /** + * Appends the string representation of the {@code char} + * argument to this sequence. + *

+ * The argument is appended to the contents of this sequence. + * The length of this sequence increases by {@code 1}. + *

+ * The overall effect is exactly as if the argument were converted + * to a string by the method {@link String#valueOf(char)}, + * and the character in that string were then + * {@link #append(String) appended} to this character sequence. + * + * @param c a {@code char}. + * @return a reference to this object. + */ + public AbstractStringBuilder append(char c) { + ensureCapacityInternal(count + 1); + value[count++] = c; + return this; + } + + /** + * Appends the string representation of the {@code int} + * argument to this sequence. + *

+ * The overall effect is exactly as if the argument were converted + * to a string by the method {@link String#valueOf(int)}, + * and the characters of that string were then + * {@link #append(String) appended} to this character sequence. + * + * @param i an {@code int}. + * @return a reference to this object. + */ + public AbstractStringBuilder append(int i) { + return append(Integer.toString(i)); + } + + /** + * Appends the string representation of the {@code long} + * argument to this sequence. + *

+ * The overall effect is exactly as if the argument were converted + * to a string by the method {@link String#valueOf(long)}, + * and the characters of that string were then + * {@link #append(String) appended} to this character sequence. + * + * @param l a {@code long}. + * @return a reference to this object. + */ + public AbstractStringBuilder append(long l) { + if (l == Long.MIN_VALUE) { + append("-9223372036854775808"); + return this; + } + int appendedLength = (l < 0) ? Long.stringSize(-l) + 1 + : Long.stringSize(l); + int spaceNeeded = count + appendedLength; + ensureCapacityInternal(spaceNeeded); + Long.getChars(l, spaceNeeded, value); + count = spaceNeeded; + return this; + } + + /** + * Appends the string representation of the {@code float} + * argument to this sequence. + *

+ * The overall effect is exactly as if the argument were converted + * to a string by the method {@link String#valueOf(float)}, + * and the characters of that string were then + * {@link #append(String) appended} to this character sequence. + * + * @param f a {@code float}. + * @return a reference to this object. + */ + public AbstractStringBuilder append(float f) { + return append(Float.toString(f)); + } + + /** + * Appends the string representation of the {@code double} + * argument to this sequence. + *

+ * The overall effect is exactly as if the argument were converted + * to a string by the method {@link String#valueOf(double)}, + * and the characters of that string were then + * {@link #append(String) appended} to this character sequence. + * + * @param d a {@code double}. + * @return a reference to this object. + */ + public AbstractStringBuilder append(double d) { + return append(Double.toString(d)); + } + + /** + * Removes the characters in a substring of this sequence. + * The substring begins at the specified {@code start} and extends to + * the character at index {@code end - 1} or to the end of the + * sequence if no such character exists. If + * {@code start} is equal to {@code end}, no changes are made. + * + * @param start The beginning index, inclusive. + * @param end The ending index, exclusive. + * @return This object. + * @throws StringIndexOutOfBoundsException if {@code start} + * is negative, greater than {@code length()}, or + * greater than {@code end}. + */ + public AbstractStringBuilder delete(int start, int end) { + if (start < 0) + throw new StringIndexOutOfBoundsException(start); + if (end > count) + end = count; + if (start > end) + throw new StringIndexOutOfBoundsException(); + int len = end - start; + if (len > 0) { + arraycopy(value, start+len, value, start, count-end); + count -= len; + } + return this; + } + + /** + * Appends the string representation of the {@code codePoint} + * argument to this sequence. + * + *

The argument is appended to the contents of this sequence. + * The length of this sequence increases by + * {@link Character#charCount(int) Character.charCount(codePoint)}. + * + *

The overall effect is exactly as if the argument were + * converted to a {@code char} array by the method + * {@link Character#toChars(int)} and the character in that array + * were then {@link #append(char[]) appended} to this character + * sequence. + * + * @param codePoint a Unicode code point + * @return a reference to this object. + * @exception IllegalArgumentException if the specified + * {@code codePoint} isn't a valid Unicode code point + */ + public AbstractStringBuilder appendCodePoint(int codePoint) { + final int count = this.count; + + if (Character.isBmpCodePoint(codePoint)) { + ensureCapacityInternal(count + 1); + value[count] = (char) codePoint; + this.count = count + 1; + } else if (Character.isValidCodePoint(codePoint)) { + ensureCapacityInternal(count + 2); + Character.toSurrogates(codePoint, value, count); + this.count = count + 2; + } else { + throw new IllegalArgumentException(); + } + return this; + } + + /** + * Removes the char at the specified position in this + * sequence. This sequence is shortened by one char. + * + *

Note: If the character at the given index is a supplementary + * character, this method does not remove the entire character. If + * correct handling of supplementary characters is required, + * determine the number of chars to remove by calling + * Character.charCount(thisSequence.codePointAt(index)), + * where thisSequence is this sequence. + * + * @param index Index of char to remove + * @return This object. + * @throws StringIndexOutOfBoundsException if the index + * is negative or greater than or equal to + * length(). + */ + public AbstractStringBuilder deleteCharAt(int index) { + if ((index < 0) || (index >= count)) + throw new StringIndexOutOfBoundsException(index); + arraycopy(value, index+1, value, index, count-index-1); + count--; + return this; + } + + /** + * Replaces the characters in a substring of this sequence + * with characters in the specified String. The substring + * begins at the specified start and extends to the character + * at index end - 1 or to the end of the + * sequence if no such character exists. First the + * characters in the substring are removed and then the specified + * String is inserted at start. (This + * sequence will be lengthened to accommodate the + * specified String if necessary.) + * + * @param start The beginning index, inclusive. + * @param end The ending index, exclusive. + * @param str String that will replace previous contents. + * @return This object. + * @throws StringIndexOutOfBoundsException if start + * is negative, greater than length(), or + * greater than end. + */ + public AbstractStringBuilder replace(int start, int end, String str) { + if (start < 0) + throw new StringIndexOutOfBoundsException(start); + if (start > count) + throw new StringIndexOutOfBoundsException("start > length()"); + if (start > end) + throw new StringIndexOutOfBoundsException("start > end"); + + if (end > count) + end = count; + int len = str.length(); + int newCount = count + len - (end - start); + ensureCapacityInternal(newCount); + + arraycopy(value, end, value, start + len, count - end); + str.getChars(value, start); + count = newCount; + return this; + } + + /** + * Returns a new String that contains a subsequence of + * characters currently contained in this character sequence. The + * substring begins at the specified index and extends to the end of + * this sequence. + * + * @param start The beginning index, inclusive. + * @return The new string. + * @throws StringIndexOutOfBoundsException if start is + * less than zero, or greater than the length of this object. + */ + public String substring(int start) { + return substring(start, count); + } + + /** + * Returns a new character sequence that is a subsequence of this sequence. + * + *

An invocation of this method of the form + * + *

+     * sb.subSequence(begin, end)
+ * + * behaves in exactly the same way as the invocation + * + *
+     * sb.substring(begin, end)
+ * + * This method is provided so that this class can + * implement the {@link CharSequence} interface.

+ * + * @param start the start index, inclusive. + * @param end the end index, exclusive. + * @return the specified subsequence. + * + * @throws IndexOutOfBoundsException + * if start or end are negative, + * if end is greater than length(), + * or if start is greater than end + * @spec JSR-51 + */ + public CharSequence subSequence(int start, int end) { + return substring(start, end); + } + + /** + * Returns a new String that contains a subsequence of + * characters currently contained in this sequence. The + * substring begins at the specified start and + * extends to the character at index end - 1. + * + * @param start The beginning index, inclusive. + * @param end The ending index, exclusive. + * @return The new string. + * @throws StringIndexOutOfBoundsException if start + * or end are negative or greater than + * length(), or start is + * greater than end. + */ + public String substring(int start, int end) { + if (start < 0) + throw new StringIndexOutOfBoundsException(start); + if (end > count) + throw new StringIndexOutOfBoundsException(end); + if (start > end) + throw new StringIndexOutOfBoundsException(end - start); + return new String(value, start, end - start); + } + + /** + * Inserts the string representation of a subarray of the {@code str} + * array argument into this sequence. The subarray begins at the + * specified {@code offset} and extends {@code len} {@code char}s. + * The characters of the subarray are inserted into this sequence at + * the position indicated by {@code index}. The length of this + * sequence increases by {@code len} {@code char}s. + * + * @param index position at which to insert subarray. + * @param str A {@code char} array. + * @param offset the index of the first {@code char} in subarray to + * be inserted. + * @param len the number of {@code char}s in the subarray to + * be inserted. + * @return This object + * @throws StringIndexOutOfBoundsException if {@code index} + * is negative or greater than {@code length()}, or + * {@code offset} or {@code len} are negative, or + * {@code (offset+len)} is greater than + * {@code str.length}. + */ + public AbstractStringBuilder insert(int index, char[] str, int offset, + int len) + { + if ((index < 0) || (index > length())) + throw new StringIndexOutOfBoundsException(index); + if ((offset < 0) || (len < 0) || (offset > str.length - len)) + throw new StringIndexOutOfBoundsException( + "offset " + offset + ", len " + len + ", str.length " + + str.length); + ensureCapacityInternal(count + len); + arraycopy(value, index, value, index + len, count - index); + arraycopy(str, offset, value, index, len); + count += len; + return this; + } + + /** + * Inserts the string representation of the {@code Object} + * argument into this character sequence. + *

+ * The overall effect is exactly as if the second argument were + * converted to a string by the method {@link String#valueOf(Object)}, + * and the characters of that string were then + * {@link #insert(int,String) inserted} into this character + * sequence at the indicated offset. + *

+ * The {@code offset} argument must be greater than or equal to + * {@code 0}, and less than or equal to the {@linkplain #length() length} + * of this sequence. + * + * @param offset the offset. + * @param obj an {@code Object}. + * @return a reference to this object. + * @throws StringIndexOutOfBoundsException if the offset is invalid. + */ + public AbstractStringBuilder insert(int offset, Object obj) { + return insert(offset, String.valueOf(obj)); + } + + /** + * Inserts the string into this character sequence. + *

+ * The characters of the {@code String} argument are inserted, in + * order, into this sequence at the indicated offset, moving up any + * characters originally above that position and increasing the length + * of this sequence by the length of the argument. If + * {@code str} is {@code null}, then the four characters + * {@code "null"} are inserted into this sequence. + *

+ * The character at index k in the new character sequence is + * equal to: + *

    + *
  • the character at index k in the old character sequence, if + * k is less than {@code offset} + *
  • the character at index k{@code -offset} in the + * argument {@code str}, if k is not less than + * {@code offset} but is less than {@code offset+str.length()} + *
  • the character at index k{@code -str.length()} in the + * old character sequence, if k is not less than + * {@code offset+str.length()} + *

+ * The {@code offset} argument must be greater than or equal to + * {@code 0}, and less than or equal to the {@linkplain #length() length} + * of this sequence. + * + * @param offset the offset. + * @param str a string. + * @return a reference to this object. + * @throws StringIndexOutOfBoundsException if the offset is invalid. + */ + public AbstractStringBuilder insert(int offset, String str) { + if ((offset < 0) || (offset > length())) + throw new StringIndexOutOfBoundsException(offset); + if (str == null) + str = "null"; + int len = str.length(); + ensureCapacityInternal(count + len); + arraycopy(value, offset, value, offset + len, count - offset); + str.getChars(value, offset); + count += len; + return this; + } + + /** + * Inserts the string representation of the {@code char} array + * argument into this sequence. + *

+ * The characters of the array argument are inserted into the + * contents of this sequence at the position indicated by + * {@code offset}. The length of this sequence increases by + * the length of the argument. + *

+ * The overall effect is exactly as if the second argument were + * converted to a string by the method {@link String#valueOf(char[])}, + * and the characters of that string were then + * {@link #insert(int,String) inserted} into this character + * sequence at the indicated offset. + *

+ * The {@code offset} argument must be greater than or equal to + * {@code 0}, and less than or equal to the {@linkplain #length() length} + * of this sequence. + * + * @param offset the offset. + * @param str a character array. + * @return a reference to this object. + * @throws StringIndexOutOfBoundsException if the offset is invalid. + */ + public AbstractStringBuilder insert(int offset, char[] str) { + if ((offset < 0) || (offset > length())) + throw new StringIndexOutOfBoundsException(offset); + int len = str.length; + ensureCapacityInternal(count + len); + arraycopy(value, offset, value, offset + len, count - offset); + arraycopy(str, 0, value, offset, len); + count += len; + return this; + } + + /** + * Inserts the specified {@code CharSequence} into this sequence. + *

+ * The characters of the {@code CharSequence} argument are inserted, + * in order, into this sequence at the indicated offset, moving up + * any characters originally above that position and increasing the length + * of this sequence by the length of the argument s. + *

+ * The result of this method is exactly the same as if it were an + * invocation of this object's + * {@link #insert(int,CharSequence,int,int) insert}(dstOffset, s, 0, s.length()) + * method. + * + *

If {@code s} is {@code null}, then the four characters + * {@code "null"} are inserted into this sequence. + * + * @param dstOffset the offset. + * @param s the sequence to be inserted + * @return a reference to this object. + * @throws IndexOutOfBoundsException if the offset is invalid. + */ + public AbstractStringBuilder insert(int dstOffset, CharSequence s) { + if (s == null) + s = "null"; + if (s instanceof String) + return this.insert(dstOffset, (String)s); + return this.insert(dstOffset, s, 0, s.length()); + } + + /** + * Inserts a subsequence of the specified {@code CharSequence} into + * this sequence. + *

+ * The subsequence of the argument {@code s} specified by + * {@code start} and {@code end} are inserted, + * in order, into this sequence at the specified destination offset, moving + * up any characters originally above that position. The length of this + * sequence is increased by {@code end - start}. + *

+ * The character at index k in this sequence becomes equal to: + *

    + *
  • the character at index k in this sequence, if + * k is less than {@code dstOffset} + *
  • the character at index k{@code +start-dstOffset} in + * the argument {@code s}, if k is greater than or equal to + * {@code dstOffset} but is less than {@code dstOffset+end-start} + *
  • the character at index k{@code -(end-start)} in this + * sequence, if k is greater than or equal to + * {@code dstOffset+end-start} + *

+ * The {@code dstOffset} argument must be greater than or equal to + * {@code 0}, and less than or equal to the {@linkplain #length() length} + * of this sequence. + *

The start argument must be nonnegative, and not greater than + * {@code end}. + *

The end argument must be greater than or equal to + * {@code start}, and less than or equal to the length of s. + * + *

If {@code s} is {@code null}, then this method inserts + * characters as if the s parameter was a sequence containing the four + * characters {@code "null"}. + * + * @param dstOffset the offset in this sequence. + * @param s the sequence to be inserted. + * @param start the starting index of the subsequence to be inserted. + * @param end the end index of the subsequence to be inserted. + * @return a reference to this object. + * @throws IndexOutOfBoundsException if {@code dstOffset} + * is negative or greater than {@code this.length()}, or + * {@code start} or {@code end} are negative, or + * {@code start} is greater than {@code end} or + * {@code end} is greater than {@code s.length()} + */ + public AbstractStringBuilder insert(int dstOffset, CharSequence s, + int start, int end) { + if (s == null) + s = "null"; + if ((dstOffset < 0) || (dstOffset > this.length())) + throw new IndexOutOfBoundsException("dstOffset "+dstOffset); + if ((start < 0) || (end < 0) || (start > end) || (end > s.length())) + throw new IndexOutOfBoundsException( + "start " + start + ", end " + end + ", s.length() " + + s.length()); + int len = end - start; + ensureCapacityInternal(count + len); + arraycopy(value, dstOffset, value, dstOffset + len, + count - dstOffset); + for (int i=start; i + * The overall effect is exactly as if the second argument were + * converted to a string by the method {@link String#valueOf(boolean)}, + * and the characters of that string were then + * {@link #insert(int,String) inserted} into this character + * sequence at the indicated offset. + *

+ * The {@code offset} argument must be greater than or equal to + * {@code 0}, and less than or equal to the {@linkplain #length() length} + * of this sequence. + * + * @param offset the offset. + * @param b a {@code boolean}. + * @return a reference to this object. + * @throws StringIndexOutOfBoundsException if the offset is invalid. + */ + public AbstractStringBuilder insert(int offset, boolean b) { + return insert(offset, String.valueOf(b)); + } + + /** + * Inserts the string representation of the {@code char} + * argument into this sequence. + *

+ * The overall effect is exactly as if the second argument were + * converted to a string by the method {@link String#valueOf(char)}, + * and the character in that string were then + * {@link #insert(int,String) inserted} into this character + * sequence at the indicated offset. + *

+ * The {@code offset} argument must be greater than or equal to + * {@code 0}, and less than or equal to the {@linkplain #length() length} + * of this sequence. + * + * @param offset the offset. + * @param c a {@code char}. + * @return a reference to this object. + * @throws IndexOutOfBoundsException if the offset is invalid. + */ + public AbstractStringBuilder insert(int offset, char c) { + ensureCapacityInternal(count + 1); + arraycopy(value, offset, value, offset + 1, count - offset); + value[offset] = c; + count += 1; + return this; + } + + /** + * Inserts the string representation of the second {@code int} + * argument into this sequence. + *

+ * The overall effect is exactly as if the second argument were + * converted to a string by the method {@link String#valueOf(int)}, + * and the characters of that string were then + * {@link #insert(int,String) inserted} into this character + * sequence at the indicated offset. + *

+ * The {@code offset} argument must be greater than or equal to + * {@code 0}, and less than or equal to the {@linkplain #length() length} + * of this sequence. + * + * @param offset the offset. + * @param i an {@code int}. + * @return a reference to this object. + * @throws StringIndexOutOfBoundsException if the offset is invalid. + */ + public AbstractStringBuilder insert(int offset, int i) { + return insert(offset, String.valueOf(i)); + } + + /** + * Inserts the string representation of the {@code long} + * argument into this sequence. + *

+ * The overall effect is exactly as if the second argument were + * converted to a string by the method {@link String#valueOf(long)}, + * and the characters of that string were then + * {@link #insert(int,String) inserted} into this character + * sequence at the indicated offset. + *

+ * The {@code offset} argument must be greater than or equal to + * {@code 0}, and less than or equal to the {@linkplain #length() length} + * of this sequence. + * + * @param offset the offset. + * @param l a {@code long}. + * @return a reference to this object. + * @throws StringIndexOutOfBoundsException if the offset is invalid. + */ + public AbstractStringBuilder insert(int offset, long l) { + return insert(offset, String.valueOf(l)); + } + + /** + * Inserts the string representation of the {@code float} + * argument into this sequence. + *

+ * The overall effect is exactly as if the second argument were + * converted to a string by the method {@link String#valueOf(float)}, + * and the characters of that string were then + * {@link #insert(int,String) inserted} into this character + * sequence at the indicated offset. + *

+ * The {@code offset} argument must be greater than or equal to + * {@code 0}, and less than or equal to the {@linkplain #length() length} + * of this sequence. + * + * @param offset the offset. + * @param f a {@code float}. + * @return a reference to this object. + * @throws StringIndexOutOfBoundsException if the offset is invalid. + */ + public AbstractStringBuilder insert(int offset, float f) { + return insert(offset, String.valueOf(f)); + } + + /** + * Inserts the string representation of the {@code double} + * argument into this sequence. + *

+ * The overall effect is exactly as if the second argument were + * converted to a string by the method {@link String#valueOf(double)}, + * and the characters of that string were then + * {@link #insert(int,String) inserted} into this character + * sequence at the indicated offset. + *

+ * The {@code offset} argument must be greater than or equal to + * {@code 0}, and less than or equal to the {@linkplain #length() length} + * of this sequence. + * + * @param offset the offset. + * @param d a {@code double}. + * @return a reference to this object. + * @throws StringIndexOutOfBoundsException if the offset is invalid. + */ + public AbstractStringBuilder insert(int offset, double d) { + return insert(offset, String.valueOf(d)); + } + + /** + * Returns the index within this string of the first occurrence of the + * specified substring. The integer returned is the smallest value + * k such that: + *

+     * this.toString().startsWith(str, k)
+     * 
+ * is true. + * + * @param str any string. + * @return if the string argument occurs as a substring within this + * object, then the index of the first character of the first + * such substring is returned; if it does not occur as a + * substring, -1 is returned. + * @throws java.lang.NullPointerException if str is + * null. + */ + public int indexOf(String str) { + return indexOf(str, 0); + } + + /** + * Returns the index within this string of the first occurrence of the + * specified substring, starting at the specified index. The integer + * returned is the smallest value k for which: + *
+     *     k >= Math.min(fromIndex, str.length()) &&
+     *                   this.toString().startsWith(str, k)
+     * 
+ * If no such value of k exists, then -1 is returned. + * + * @param str the substring for which to search. + * @param fromIndex the index from which to start the search. + * @return the index within this string of the first occurrence of the + * specified substring, starting at the specified index. + * @throws java.lang.NullPointerException if str is + * null. + */ + public int indexOf(String str, int fromIndex) { + return toString().indexOf(str, fromIndex); + } + + /** + * Returns the index within this string of the rightmost occurrence + * of the specified substring. The rightmost empty string "" is + * considered to occur at the index value this.length(). + * The returned index is the largest value k such that + *
+     * this.toString().startsWith(str, k)
+     * 
+ * is true. + * + * @param str the substring to search for. + * @return if the string argument occurs one or more times as a substring + * within this object, then the index of the first character of + * the last such substring is returned. If it does not occur as + * a substring, -1 is returned. + * @throws java.lang.NullPointerException if str is + * null. + */ + public int lastIndexOf(String str) { + return lastIndexOf(str, count); + } + + /** + * Returns the index within this string of the last occurrence of the + * specified substring. The integer returned is the largest value k + * such that: + *
+     *     k <= Math.min(fromIndex, str.length()) &&
+     *                   this.toString().startsWith(str, k)
+     * 
+ * If no such value of k exists, then -1 is returned. + * + * @param str the substring to search for. + * @param fromIndex the index to start the search from. + * @return the index within this sequence of the last occurrence of the + * specified substring. + * @throws java.lang.NullPointerException if str is + * null. + */ + public int lastIndexOf(String str, int fromIndex) { + return String.lastIndexOf(value, 0, count, + str.toCharArray(), 0, str.length(), fromIndex); + } + + /** + * Causes this character sequence to be replaced by the reverse of + * the sequence. If there are any surrogate pairs included in the + * sequence, these are treated as single characters for the + * reverse operation. Thus, the order of the high-low surrogates + * is never reversed. + * + * Let n be the character length of this character sequence + * (not the length in char values) just prior to + * execution of the reverse method. Then the + * character at index k in the new character sequence is + * equal to the character at index n-k-1 in the old + * character sequence. + * + *

Note that the reverse operation may result in producing + * surrogate pairs that were unpaired low-surrogates and + * high-surrogates before the operation. For example, reversing + * "\uDC00\uD800" produces "\uD800\uDC00" which is + * a valid surrogate pair. + * + * @return a reference to this object. + */ + public AbstractStringBuilder reverse() { + boolean hasSurrogate = false; + int n = count - 1; + for (int j = (n-1) >> 1; j >= 0; --j) { + char temp = value[j]; + char temp2 = value[n - j]; + if (!hasSurrogate) { + hasSurrogate = (temp >= Character.MIN_SURROGATE && temp <= Character.MAX_SURROGATE) + || (temp2 >= Character.MIN_SURROGATE && temp2 <= Character.MAX_SURROGATE); + } + value[j] = temp2; + value[n - j] = temp; + } + if (hasSurrogate) { + // Reverse back all valid surrogate pairs + for (int i = 0; i < count - 1; i++) { + char c2 = value[i]; + if (Character.isLowSurrogate(c2)) { + char c1 = value[i + 1]; + if (Character.isHighSurrogate(c1)) { + value[i++] = c1; + value[i] = c2; + } + } + } + } + return this; + } + + /** + * Returns a string representing the data in this sequence. + * A new String object is allocated and initialized to + * contain the character sequence currently represented by this + * object. This String is then returned. Subsequent + * changes to this sequence do not affect the contents of the + * String. + * + * @return a string representation of this sequence of characters. + */ + public abstract String toString(); + + /** + * Needed by String for the contentEquals method. + */ + final char[] getValue() { + return value; + } + + static char[] copyOfRange(char[] original, int from, int to) { + int newLength = to - from; + if (newLength < 0) { + throw new IllegalArgumentException(from + " > " + to); + } + char[] copy = new char[newLength]; + arraycopy(original, from, copy, 0, Math.min(original.length - from, newLength)); + return copy; + } + + static void arraycopy(char[] value, int srcBegin, char[] dst, int dstBegin, int count) { + if (srcBegin < dstBegin) { + while (count-- > 0) { + dst[dstBegin + count] = value[srcBegin + count]; + } + } else { + while (count-- > 0) { + dst[dstBegin++] = value[srcBegin++]; + } + } + } + + // access system property + static String getProperty(String nm) { + return null; + } + + static char[] copyOf(char[] original, int newLength) { + char[] copy = new char[newLength]; + arraycopy(original, 0, copy, 0, Math.min(original.length, newLength)); + return copy; + } + +} diff -r 388e48c0a37a -r 05224402145d emul/mini/src/main/java/java/lang/Appendable.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/emul/mini/src/main/java/java/lang/Appendable.java Wed Jan 23 20:39:23 2013 +0100 @@ -0,0 +1,121 @@ +/* + * Copyright (c) 2003, 2004, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code 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 + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package java.lang; + +import java.io.IOException; + +/** + * An object to which char sequences and values can be appended. The + * Appendable interface must be implemented by any class whose + * instances are intended to receive formatted output from a {@link + * java.util.Formatter}. + * + *

The characters to be appended should be valid Unicode characters as + * described in Unicode Character + * Representation. Note that supplementary characters may be composed of + * multiple 16-bit char values. + * + *

Appendables are not necessarily safe for multithreaded access. Thread + * safety is the responsibility of classes that extend and implement this + * interface. + * + *

Since this interface may be implemented by existing classes + * with different styles of error handling there is no guarantee that + * errors will be propagated to the invoker. + * + * @since 1.5 + */ +public interface Appendable { + + /** + * Appends the specified character sequence to this Appendable. + * + *

Depending on which class implements the character sequence + * csq, the entire sequence may not be appended. For + * instance, if csq is a {@link java.nio.CharBuffer} then + * the subsequence to append is defined by the buffer's position and limit. + * + * @param csq + * The character sequence to append. If csq is + * null, then the four characters "null" are + * appended to this Appendable. + * + * @return A reference to this Appendable + * + * @throws IOException + * If an I/O error occurs + */ + Appendable append(CharSequence csq) throws IOException; + + /** + * Appends a subsequence of the specified character sequence to this + * Appendable. + * + *

An invocation of this method of the form out.append(csq, start, + * end) when csq is not null, behaves in + * exactly the same way as the invocation + * + *

+     *     out.append(csq.subSequence(start, end)) 
+ * + * @param csq + * The character sequence from which a subsequence will be + * appended. If csq is null, then characters + * will be appended as if csq contained the four + * characters "null". + * + * @param start + * The index of the first character in the subsequence + * + * @param end + * The index of the character following the last character in the + * subsequence + * + * @return A reference to this Appendable + * + * @throws IndexOutOfBoundsException + * If start or end are negative, start + * is greater than end, or end is greater than + * csq.length() + * + * @throws IOException + * If an I/O error occurs + */ + Appendable append(CharSequence csq, int start, int end) throws IOException; + + /** + * Appends the specified character to this Appendable. + * + * @param c + * The character to append + * + * @return A reference to this Appendable + * + * @throws IOException + * If an I/O error occurs + */ + Appendable append(char c) throws IOException; +} diff -r 388e48c0a37a -r 05224402145d emul/mini/src/main/java/java/lang/ArrayIndexOutOfBoundsException.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/emul/mini/src/main/java/java/lang/ArrayIndexOutOfBoundsException.java Wed Jan 23 20:39:23 2013 +0100 @@ -0,0 +1,67 @@ +/* + * Copyright (c) 1994, 2008, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code 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 + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package java.lang; + +/** + * Thrown to indicate that an array has been accessed with an + * illegal index. The index is either negative or greater than or + * equal to the size of the array. + * + * @author unascribed + * @since JDK1.0 + */ +public +class ArrayIndexOutOfBoundsException extends IndexOutOfBoundsException { + private static final long serialVersionUID = -5116101128118950844L; + + /** + * Constructs an ArrayIndexOutOfBoundsException with no + * detail message. + */ + public ArrayIndexOutOfBoundsException() { + super(); + } + + /** + * Constructs a new ArrayIndexOutOfBoundsException + * class with an argument indicating the illegal index. + * + * @param index the illegal index. + */ + public ArrayIndexOutOfBoundsException(int index) { + super("Array index out of range: " + index); + } + + /** + * Constructs an ArrayIndexOutOfBoundsException class + * with the specified detail message. + * + * @param s the detail message. + */ + public ArrayIndexOutOfBoundsException(String s) { + super(s); + } +} diff -r 388e48c0a37a -r 05224402145d emul/mini/src/main/java/java/lang/AssertionError.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/emul/mini/src/main/java/java/lang/AssertionError.java Wed Jan 23 20:39:23 2013 +0100 @@ -0,0 +1,167 @@ +/* + * Copyright (c) 2000, 2010, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code 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 + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package java.lang; + +/** + * Thrown to indicate that an assertion has failed. + * + *

The seven one-argument public constructors provided by this + * class ensure that the assertion error returned by the invocation: + *

+ *     new AssertionError(expression)
+ * 
+ * has as its detail message the string conversion of + * expression (as defined in section 15.18.1.1 of + * The Java™ Language Specification), + * regardless of the type of expression. + * + * @since 1.4 + */ +public class AssertionError extends Error { + private static final long serialVersionUID = -5013299493970297370L; + + /** + * Constructs an AssertionError with no detail message. + */ + public AssertionError() { + } + + /** + * This internal constructor does no processing on its string argument, + * even if it is a null reference. The public constructors will + * never call this constructor with a null argument. + */ + private AssertionError(String detailMessage) { + super(detailMessage); + } + + /** + * Constructs an AssertionError with its detail message derived + * from the specified object, which is converted to a string as + * defined in section 15.18.1.1 of + * The Java™ Language Specification. + *

+ * If the specified object is an instance of {@code Throwable}, it + * becomes the cause of the newly constructed assertion error. + * + * @param detailMessage value to be used in constructing detail message + * @see Throwable#getCause() + */ + public AssertionError(Object detailMessage) { + this("" + detailMessage); + if (detailMessage instanceof Throwable) + initCause((Throwable) detailMessage); + } + + /** + * Constructs an AssertionError with its detail message derived + * from the specified boolean, which is converted to + * a string as defined in section 15.18.1.1 of + * The Java™ Language Specification. + * + * @param detailMessage value to be used in constructing detail message + */ + public AssertionError(boolean detailMessage) { + this("" + detailMessage); + } + + /** + * Constructs an AssertionError with its detail message derived + * from the specified char, which is converted to a + * string as defined in section 15.18.1.1 of + * The Java™ Language Specification. + * + * @param detailMessage value to be used in constructing detail message + */ + public AssertionError(char detailMessage) { + this("" + detailMessage); + } + + /** + * Constructs an AssertionError with its detail message derived + * from the specified int, which is converted to a + * string as defined in section 15.18.1.1 of + * The Java™ Language Specification. + * + * @param detailMessage value to be used in constructing detail message + */ + public AssertionError(int detailMessage) { + this("" + detailMessage); + } + + /** + * Constructs an AssertionError with its detail message derived + * from the specified long, which is converted to a + * string as defined in section 15.18.1.1 of + * The Java™ Language Specification. + * + * @param detailMessage value to be used in constructing detail message + */ + public AssertionError(long detailMessage) { + this("" + detailMessage); + } + + /** + * Constructs an AssertionError with its detail message derived + * from the specified float, which is converted to a + * string as defined in section 15.18.1.1 of + * The Java™ Language Specification. + * + * @param detailMessage value to be used in constructing detail message + */ + public AssertionError(float detailMessage) { + this("" + detailMessage); + } + + /** + * Constructs an AssertionError with its detail message derived + * from the specified double, which is converted to a + * string as defined in section 15.18.1.1 of + * The Java™ Language Specification. + * + * @param detailMessage value to be used in constructing detail message + */ + public AssertionError(double detailMessage) { + this("" + detailMessage); + } + + /** + * Constructs a new {@code AssertionError} with the specified + * detail message and cause. + * + *

Note that the detail message associated with + * {@code cause} is not automatically incorporated in + * this error's detail message. + * + * @param message the detail message, may be {@code null} + * @param cause the cause, may be {@code null} + * + * @since 1.7 + */ + public AssertionError(String message, Throwable cause) { + super(message, cause); + } +} diff -r 388e48c0a37a -r 05224402145d emul/mini/src/main/java/java/lang/AutoCloseable.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/emul/mini/src/main/java/java/lang/AutoCloseable.java Wed Jan 23 20:39:23 2013 +0100 @@ -0,0 +1,72 @@ +/* + * Copyright (c) 2009, 2011, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code 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 + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package java.lang; + +/** + * A resource that must be closed when it is no longer needed. + * + * @author Josh Bloch + * @since 1.7 + */ +public interface AutoCloseable { + /** + * Closes this resource, relinquishing any underlying resources. + * This method is invoked automatically on objects managed by the + * {@code try}-with-resources statement. + * + *

While this interface method is declared to throw {@code + * Exception}, implementers are strongly encouraged to + * declare concrete implementations of the {@code close} method to + * throw more specific exceptions, or to throw no exception at all + * if the close operation cannot fail. + * + *

Implementers of this interface are also strongly advised + * to not have the {@code close} method throw {@link + * InterruptedException}. + * + * This exception interacts with a thread's interrupted status, + * and runtime misbehavior is likely to occur if an {@code + * InterruptedException} is {@linkplain Throwable#addSuppressed + * suppressed}. + * + * More generally, if it would cause problems for an + * exception to be suppressed, the {@code AutoCloseable.close} + * method should not throw it. + * + *

Note that unlike the {@link java.io.Closeable#close close} + * method of {@link java.io.Closeable}, this {@code close} method + * is not required to be idempotent. In other words, + * calling this {@code close} method more than once may have some + * visible side effect, unlike {@code Closeable.close} which is + * required to have no effect if called more than once. + * + * However, implementers of this interface are strongly encouraged + * to make their {@code close} methods idempotent. + * + * @throws Exception if this resource cannot be closed + */ + void close() throws Exception; +} diff -r 388e48c0a37a -r 05224402145d emul/mini/src/main/java/java/lang/Boolean.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/emul/mini/src/main/java/java/lang/Boolean.java Wed Jan 23 20:39:23 2013 +0100 @@ -0,0 +1,282 @@ +/* + * Copyright (c) 1994, 2006, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code 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 + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package java.lang; + +/** + * The Boolean class wraps a value of the primitive type + * {@code boolean} in an object. An object of type + * {@code Boolean} contains a single field whose type is + * {@code boolean}. + *

+ * In addition, this class provides many methods for + * converting a {@code boolean} to a {@code String} and a + * {@code String} to a {@code boolean}, as well as other + * constants and methods useful when dealing with a + * {@code boolean}. + * + * @author Arthur van Hoff + * @since JDK1.0 + */ +public final class Boolean implements java.io.Serializable, + Comparable +{ + /** + * The {@code Boolean} object corresponding to the primitive + * value {@code true}. + */ + public static final Boolean TRUE = new Boolean(true); + + /** + * The {@code Boolean} object corresponding to the primitive + * value {@code false}. + */ + public static final Boolean FALSE = new Boolean(false); + + /** + * The Class object representing the primitive type boolean. + * + * @since JDK1.1 + */ + public static final Class TYPE = Class.getPrimitiveClass("boolean"); + + /** + * The value of the Boolean. + * + * @serial + */ + private final boolean value; + + /** use serialVersionUID from JDK 1.0.2 for interoperability */ + private static final long serialVersionUID = -3665804199014368530L; + + /** + * Allocates a {@code Boolean} object representing the + * {@code value} argument. + * + *

Note: It is rarely appropriate to use this constructor. + * Unless a new instance is required, the static factory + * {@link #valueOf(boolean)} is generally a better choice. It is + * likely to yield significantly better space and time performance. + * + * @param value the value of the {@code Boolean}. + */ + public Boolean(boolean value) { + this.value = value; + } + + /** + * Allocates a {@code Boolean} object representing the value + * {@code true} if the string argument is not {@code null} + * and is equal, ignoring case, to the string {@code "true"}. + * Otherwise, allocate a {@code Boolean} object representing the + * value {@code false}. Examples:

+ * {@code new Boolean("True")} produces a {@code Boolean} object + * that represents {@code true}.
+ * {@code new Boolean("yes")} produces a {@code Boolean} object + * that represents {@code false}. + * + * @param s the string to be converted to a {@code Boolean}. + */ + public Boolean(String s) { + this(toBoolean(s)); + } + + /** + * Parses the string argument as a boolean. The {@code boolean} + * returned represents the value {@code true} if the string argument + * is not {@code null} and is equal, ignoring case, to the string + * {@code "true"}.

+ * Example: {@code Boolean.parseBoolean("True")} returns {@code true}.
+ * Example: {@code Boolean.parseBoolean("yes")} returns {@code false}. + * + * @param s the {@code String} containing the boolean + * representation to be parsed + * @return the boolean represented by the string argument + * @since 1.5 + */ + public static boolean parseBoolean(String s) { + return toBoolean(s); + } + + /** + * Returns the value of this {@code Boolean} object as a boolean + * primitive. + * + * @return the primitive {@code boolean} value of this object. + */ + public boolean booleanValue() { + return value; + } + + /** + * Returns a {@code Boolean} instance representing the specified + * {@code boolean} value. If the specified {@code boolean} value + * is {@code true}, this method returns {@code Boolean.TRUE}; + * if it is {@code false}, this method returns {@code Boolean.FALSE}. + * If a new {@code Boolean} instance is not required, this method + * should generally be used in preference to the constructor + * {@link #Boolean(boolean)}, as this method is likely to yield + * significantly better space and time performance. + * + * @param b a boolean value. + * @return a {@code Boolean} instance representing {@code b}. + * @since 1.4 + */ + public static Boolean valueOf(boolean b) { + return (b ? TRUE : FALSE); + } + + /** + * Returns a {@code Boolean} with a value represented by the + * specified string. The {@code Boolean} returned represents a + * true value if the string argument is not {@code null} + * and is equal, ignoring case, to the string {@code "true"}. + * + * @param s a string. + * @return the {@code Boolean} value represented by the string. + */ + public static Boolean valueOf(String s) { + return toBoolean(s) ? TRUE : FALSE; + } + + /** + * Returns a {@code String} object representing the specified + * boolean. If the specified boolean is {@code true}, then + * the string {@code "true"} will be returned, otherwise the + * string {@code "false"} will be returned. + * + * @param b the boolean to be converted + * @return the string representation of the specified {@code boolean} + * @since 1.4 + */ + public static String toString(boolean b) { + return b ? "true" : "false"; + } + + /** + * Returns a {@code String} object representing this Boolean's + * value. If this object represents the value {@code true}, + * a string equal to {@code "true"} is returned. Otherwise, a + * string equal to {@code "false"} is returned. + * + * @return a string representation of this object. + */ + public String toString() { + return value ? "true" : "false"; + } + + /** + * Returns a hash code for this {@code Boolean} object. + * + * @return the integer {@code 1231} if this object represents + * {@code true}; returns the integer {@code 1237} if this + * object represents {@code false}. + */ + public int hashCode() { + return value ? 1231 : 1237; + } + + /** + * Returns {@code true} if and only if the argument is not + * {@code null} and is a {@code Boolean} object that + * represents the same {@code boolean} value as this object. + * + * @param obj the object to compare with. + * @return {@code true} if the Boolean objects represent the + * same value; {@code false} otherwise. + */ + public boolean equals(Object obj) { + if (obj instanceof Boolean) { + return value == ((Boolean)obj).booleanValue(); + } + return false; + } + + /** + * Returns {@code true} if and only if the system property + * named by the argument exists and is equal to the string + * {@code "true"}. (Beginning with version 1.0.2 of the + * JavaTM platform, the test of + * this string is case insensitive.) A system property is accessible + * through {@code getProperty}, a method defined by the + * {@code System} class. + *

+ * If there is no property with the specified name, or if the specified + * name is empty or null, then {@code false} is returned. + * + * @param name the system property name. + * @return the {@code boolean} value of the system property. + * @see java.lang.System#getProperty(java.lang.String) + * @see java.lang.System#getProperty(java.lang.String, java.lang.String) + */ + public static boolean getBoolean(String name) { + boolean result = false; + try { + result = toBoolean(AbstractStringBuilder.getProperty(name)); + } catch (IllegalArgumentException e) { + } catch (NullPointerException e) { + } + return result; + } + + /** + * Compares this {@code Boolean} instance with another. + * + * @param b the {@code Boolean} instance to be compared + * @return zero if this object represents the same boolean value as the + * argument; a positive value if this object represents true + * and the argument represents false; and a negative value if + * this object represents false and the argument represents true + * @throws NullPointerException if the argument is {@code null} + * @see Comparable + * @since 1.5 + */ + public int compareTo(Boolean b) { + return compare(this.value, b.value); + } + + /** + * Compares two {@code boolean} values. + * The value returned is identical to what would be returned by: + *

+     *    Boolean.valueOf(x).compareTo(Boolean.valueOf(y))
+     * 
+ * + * @param x the first {@code boolean} to compare + * @param y the second {@code boolean} to compare + * @return the value {@code 0} if {@code x == y}; + * a value less than {@code 0} if {@code !x && y}; and + * a value greater than {@code 0} if {@code x && !y} + * @since 1.7 + */ + public static int compare(boolean x, boolean y) { + return (x == y) ? 0 : (x ? 1 : -1); + } + + private static boolean toBoolean(String name) { + return ((name != null) && name.equalsIgnoreCase("true")); + } +} diff -r 388e48c0a37a -r 05224402145d emul/mini/src/main/java/java/lang/Byte.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/emul/mini/src/main/java/java/lang/Byte.java Wed Jan 23 20:39:23 2013 +0100 @@ -0,0 +1,452 @@ +/* + * Copyright (c) 1996, 2009, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code 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 + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package java.lang; + +/** + * + * The {@code Byte} class wraps a value of primitive type {@code byte} + * in an object. An object of type {@code Byte} contains a single + * field whose type is {@code byte}. + * + *

In addition, this class provides several methods for converting + * a {@code byte} to a {@code String} and a {@code String} to a {@code + * byte}, as well as other constants and methods useful when dealing + * with a {@code byte}. + * + * @author Nakul Saraiya + * @author Joseph D. Darcy + * @see java.lang.Number + * @since JDK1.1 + */ +public final class Byte extends Number implements Comparable { + + /** + * A constant holding the minimum value a {@code byte} can + * have, -27. + */ + public static final byte MIN_VALUE = -128; + + /** + * A constant holding the maximum value a {@code byte} can + * have, 27-1. + */ + public static final byte MAX_VALUE = 127; + + /** + * The {@code Class} instance representing the primitive type + * {@code byte}. + */ + public static final Class TYPE = (Class) Class.getPrimitiveClass("byte"); + + /** + * Returns a new {@code String} object representing the + * specified {@code byte}. The radix is assumed to be 10. + * + * @param b the {@code byte} to be converted + * @return the string representation of the specified {@code byte} + * @see java.lang.Integer#toString(int) + */ + public static String toString(byte b) { + return Integer.toString((int)b, 10); + } + + private static class ByteCache { + private ByteCache(){} + + static final Byte cache[] = new Byte[-(-128) + 127 + 1]; + + static { + for(int i = 0; i < cache.length; i++) + cache[i] = new Byte((byte)(i - 128)); + } + } + + /** + * Returns a {@code Byte} instance representing the specified + * {@code byte} value. + * If a new {@code Byte} instance is not required, this method + * should generally be used in preference to the constructor + * {@link #Byte(byte)}, as this method is likely to yield + * significantly better space and time performance since + * all byte values are cached. + * + * @param b a byte value. + * @return a {@code Byte} instance representing {@code b}. + * @since 1.5 + */ + public static Byte valueOf(byte b) { + final int offset = 128; + return ByteCache.cache[(int)b + offset]; + } + + /** + * Parses the string argument as a signed {@code byte} in the + * radix specified by the second argument. The characters in the + * string must all be digits, of the specified radix (as + * determined by whether {@link java.lang.Character#digit(char, + * int)} returns a nonnegative value) except that the first + * character may be an ASCII minus sign {@code '-'} + * ('\u002D') to indicate a negative value or an + * ASCII plus sign {@code '+'} ('\u002B') to + * indicate a positive value. The resulting {@code byte} value is + * returned. + * + *

An exception of type {@code NumberFormatException} is + * thrown if any of the following situations occurs: + *

    + *
  • The first argument is {@code null} or is a string of + * length zero. + * + *
  • The radix is either smaller than {@link + * java.lang.Character#MIN_RADIX} or larger than {@link + * java.lang.Character#MAX_RADIX}. + * + *
  • Any character of the string is not a digit of the + * specified radix, except that the first character may be a minus + * sign {@code '-'} ('\u002D') or plus sign + * {@code '+'} ('\u002B') provided that the + * string is longer than length 1. + * + *
  • The value represented by the string is not a value of type + * {@code byte}. + *
+ * + * @param s the {@code String} containing the + * {@code byte} + * representation to be parsed + * @param radix the radix to be used while parsing {@code s} + * @return the {@code byte} value represented by the string + * argument in the specified radix + * @throws NumberFormatException If the string does + * not contain a parsable {@code byte}. + */ + public static byte parseByte(String s, int radix) + throws NumberFormatException { + int i = Integer.parseInt(s, radix); + if (i < MIN_VALUE || i > MAX_VALUE) + throw new NumberFormatException( + "Value out of range. Value:\"" + s + "\" Radix:" + radix); + return (byte)i; + } + + /** + * Parses the string argument as a signed decimal {@code + * byte}. The characters in the string must all be decimal digits, + * except that the first character may be an ASCII minus sign + * {@code '-'} ('\u002D') to indicate a negative + * value or an ASCII plus sign {@code '+'} + * ('\u002B') to indicate a positive value. The + * resulting {@code byte} value is returned, exactly as if the + * argument and the radix 10 were given as arguments to the {@link + * #parseByte(java.lang.String, int)} method. + * + * @param s a {@code String} containing the + * {@code byte} representation to be parsed + * @return the {@code byte} value represented by the + * argument in decimal + * @throws NumberFormatException if the string does not + * contain a parsable {@code byte}. + */ + public static byte parseByte(String s) throws NumberFormatException { + return parseByte(s, 10); + } + + /** + * Returns a {@code Byte} object holding the value + * extracted from the specified {@code String} when parsed + * with the radix given by the second argument. The first argument + * is interpreted as representing a signed {@code byte} in + * the radix specified by the second argument, exactly as if the + * argument were given to the {@link #parseByte(java.lang.String, + * int)} method. The result is a {@code Byte} object that + * represents the {@code byte} value specified by the string. + * + *

In other words, this method returns a {@code Byte} object + * equal to the value of: + * + *

+ * {@code new Byte(Byte.parseByte(s, radix))} + *
+ * + * @param s the string to be parsed + * @param radix the radix to be used in interpreting {@code s} + * @return a {@code Byte} object holding the value + * represented by the string argument in the + * specified radix. + * @throws NumberFormatException If the {@code String} does + * not contain a parsable {@code byte}. + */ + public static Byte valueOf(String s, int radix) + throws NumberFormatException { + return valueOf(parseByte(s, radix)); + } + + /** + * Returns a {@code Byte} object holding the value + * given by the specified {@code String}. The argument is + * interpreted as representing a signed decimal {@code byte}, + * exactly as if the argument were given to the {@link + * #parseByte(java.lang.String)} method. The result is a + * {@code Byte} object that represents the {@code byte} + * value specified by the string. + * + *

In other words, this method returns a {@code Byte} object + * equal to the value of: + * + *

+ * {@code new Byte(Byte.parseByte(s))} + *
+ * + * @param s the string to be parsed + * @return a {@code Byte} object holding the value + * represented by the string argument + * @throws NumberFormatException If the {@code String} does + * not contain a parsable {@code byte}. + */ + public static Byte valueOf(String s) throws NumberFormatException { + return valueOf(s, 10); + } + + /** + * Decodes a {@code String} into a {@code Byte}. + * Accepts decimal, hexadecimal, and octal numbers given by + * the following grammar: + * + *
+ *
+ *
DecodableString: + *
Signopt DecimalNumeral + *
Signopt {@code 0x} HexDigits + *
Signopt {@code 0X} HexDigits + *
Signopt {@code #} HexDigits + *
Signopt {@code 0} OctalDigits + *

+ *

Sign: + *
{@code -} + *
{@code +} + *
+ *
+ * + * DecimalNumeral, HexDigits, and OctalDigits + * are as defined in section 3.10.1 of + * The Java™ Language Specification, + * except that underscores are not accepted between digits. + * + *

The sequence of characters following an optional + * sign and/or radix specifier ("{@code 0x}", "{@code 0X}", + * "{@code #}", or leading zero) is parsed as by the {@code + * Byte.parseByte} method with the indicated radix (10, 16, or 8). + * This sequence of characters must represent a positive value or + * a {@link NumberFormatException} will be thrown. The result is + * negated if first character of the specified {@code String} is + * the minus sign. No whitespace characters are permitted in the + * {@code String}. + * + * @param nm the {@code String} to decode. + * @return a {@code Byte} object holding the {@code byte} + * value represented by {@code nm} + * @throws NumberFormatException if the {@code String} does not + * contain a parsable {@code byte}. + * @see java.lang.Byte#parseByte(java.lang.String, int) + */ + public static Byte decode(String nm) throws NumberFormatException { + int i = Integer.decode(nm); + if (i < MIN_VALUE || i > MAX_VALUE) + throw new NumberFormatException( + "Value " + i + " out of range from input " + nm); + return valueOf((byte)i); + } + + /** + * The value of the {@code Byte}. + * + * @serial + */ + private final byte value; + + /** + * Constructs a newly allocated {@code Byte} object that + * represents the specified {@code byte} value. + * + * @param value the value to be represented by the + * {@code Byte}. + */ + public Byte(byte value) { + this.value = value; + } + + /** + * Constructs a newly allocated {@code Byte} object that + * represents the {@code byte} value indicated by the + * {@code String} parameter. The string is converted to a + * {@code byte} value in exactly the manner used by the + * {@code parseByte} method for radix 10. + * + * @param s the {@code String} to be converted to a + * {@code Byte} + * @throws NumberFormatException If the {@code String} + * does not contain a parsable {@code byte}. + * @see java.lang.Byte#parseByte(java.lang.String, int) + */ + public Byte(String s) throws NumberFormatException { + this.value = parseByte(s, 10); + } + + /** + * Returns the value of this {@code Byte} as a + * {@code byte}. + */ + public byte byteValue() { + return value; + } + + /** + * Returns the value of this {@code Byte} as a + * {@code short}. + */ + public short shortValue() { + return (short)value; + } + + /** + * Returns the value of this {@code Byte} as an + * {@code int}. + */ + public int intValue() { + return (int)value; + } + + /** + * Returns the value of this {@code Byte} as a + * {@code long}. + */ + public long longValue() { + return (long)value; + } + + /** + * Returns the value of this {@code Byte} as a + * {@code float}. + */ + public float floatValue() { + return (float)value; + } + + /** + * Returns the value of this {@code Byte} as a + * {@code double}. + */ + public double doubleValue() { + return (double)value; + } + + /** + * Returns a {@code String} object representing this + * {@code Byte}'s value. The value is converted to signed + * decimal representation and returned as a string, exactly as if + * the {@code byte} value were given as an argument to the + * {@link java.lang.Byte#toString(byte)} method. + * + * @return a string representation of the value of this object in + * base 10. + */ + public String toString() { + return Integer.toString((int)value); + } + + /** + * Returns a hash code for this {@code Byte}; equal to the result + * of invoking {@code intValue()}. + * + * @return a hash code value for this {@code Byte} + */ + public int hashCode() { + return (int)value; + } + + /** + * Compares this object to the specified object. The result is + * {@code true} if and only if the argument is not + * {@code null} and is a {@code Byte} object that + * contains the same {@code byte} value as this object. + * + * @param obj the object to compare with + * @return {@code true} if the objects are the same; + * {@code false} otherwise. + */ + public boolean equals(Object obj) { + if (obj instanceof Byte) { + return value == ((Byte)obj).byteValue(); + } + return false; + } + + /** + * Compares two {@code Byte} objects numerically. + * + * @param anotherByte the {@code Byte} to be compared. + * @return the value {@code 0} if this {@code Byte} is + * equal to the argument {@code Byte}; a value less than + * {@code 0} if this {@code Byte} is numerically less + * than the argument {@code Byte}; and a value greater than + * {@code 0} if this {@code Byte} is numerically + * greater than the argument {@code Byte} (signed + * comparison). + * @since 1.2 + */ + public int compareTo(Byte anotherByte) { + return compare(this.value, anotherByte.value); + } + + /** + * Compares two {@code byte} values numerically. + * The value returned is identical to what would be returned by: + *

+     *    Byte.valueOf(x).compareTo(Byte.valueOf(y))
+     * 
+ * + * @param x the first {@code byte} to compare + * @param y the second {@code byte} to compare + * @return the value {@code 0} if {@code x == y}; + * a value less than {@code 0} if {@code x < y}; and + * a value greater than {@code 0} if {@code x > y} + * @since 1.7 + */ + public static int compare(byte x, byte y) { + return x - y; + } + + /** + * The number of bits used to represent a {@code byte} value in two's + * complement binary form. + * + * @since 1.5 + */ + public static final int SIZE = 8; + + /** use serialVersionUID from JDK 1.1. for interoperability */ + private static final long serialVersionUID = -7183698231559129828L; +} diff -r 388e48c0a37a -r 05224402145d emul/mini/src/main/java/java/lang/CharSequence.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/emul/mini/src/main/java/java/lang/CharSequence.java Wed Jan 23 20:39:23 2013 +0100 @@ -0,0 +1,111 @@ +/* + * Copyright (c) 2000, 2003, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code 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 + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package java.lang; + + +/** + * A CharSequence is a readable sequence of char values. This + * interface provides uniform, read-only access to many different kinds of + * char sequences. + * A char value represents a character in the Basic + * Multilingual Plane (BMP) or a surrogate. Refer to Unicode Character Representation for details. + * + *

This interface does not refine the general contracts of the {@link + * java.lang.Object#equals(java.lang.Object) equals} and {@link + * java.lang.Object#hashCode() hashCode} methods. The result of comparing two + * objects that implement CharSequence is therefore, in general, + * undefined. Each object may be implemented by a different class, and there + * is no guarantee that each class will be capable of testing its instances + * for equality with those of the other. It is therefore inappropriate to use + * arbitrary CharSequence instances as elements in a set or as keys in + * a map.

+ * + * @author Mike McCloskey + * @since 1.4 + * @spec JSR-51 + */ + +public interface CharSequence { + + /** + * Returns the length of this character sequence. The length is the number + * of 16-bit chars in the sequence.

+ * + * @return the number of chars in this sequence + */ + int length(); + + /** + * Returns the char value at the specified index. An index ranges from zero + * to length() - 1. The first char value of the sequence is at + * index zero, the next at index one, and so on, as for array + * indexing.

+ * + *

If the char value specified by the index is a + * surrogate, the surrogate + * value is returned. + * + * @param index the index of the char value to be returned + * + * @return the specified char value + * + * @throws IndexOutOfBoundsException + * if the index argument is negative or not less than + * length() + */ + char charAt(int index); + + /** + * Returns a new CharSequence that is a subsequence of this sequence. + * The subsequence starts with the char value at the specified index and + * ends with the char value at index end - 1. The length + * (in chars) of the + * returned sequence is end - start, so if start == end + * then an empty sequence is returned.

+ * + * @param start the start index, inclusive + * @param end the end index, exclusive + * + * @return the specified subsequence + * + * @throws IndexOutOfBoundsException + * if start or end are negative, + * if end is greater than length(), + * or if start is greater than end + */ + CharSequence subSequence(int start, int end); + + /** + * Returns a string containing the characters in this sequence in the same + * order as this sequence. The length of the string will be the length of + * this sequence.

+ * + * @return a string consisting of exactly this sequence of characters + */ + public String toString(); + +} diff -r 388e48c0a37a -r 05224402145d emul/mini/src/main/java/java/lang/Character.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/emul/mini/src/main/java/java/lang/Character.java Wed Jan 23 20:39:23 2013 +0100 @@ -0,0 +1,2382 @@ +/* + * Copyright (c) 2002, 2010, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code 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 + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package java.lang; + +import org.apidesign.bck2brwsr.core.JavaScriptBody; + +/** + * The {@code Character} class wraps a value of the primitive + * type {@code char} in an object. An object of type + * {@code Character} contains a single field whose type is + * {@code char}. + *

+ * In addition, this class provides several methods for determining + * a character's category (lowercase letter, digit, etc.) and for converting + * characters from uppercase to lowercase and vice versa. + *

+ * Character information is based on the Unicode Standard, version 6.0.0. + *

+ * The methods and data of class {@code Character} are defined by + * the information in the UnicodeData file that is part of the + * Unicode Character Database maintained by the Unicode + * Consortium. This file specifies various properties including name + * and general category for every defined Unicode code point or + * character range. + *

+ * The file and its description are available from the Unicode Consortium at: + *

+ * + *

Unicode Character Representations

+ * + *

The {@code char} data type (and therefore the value that a + * {@code Character} object encapsulates) are based on the + * original Unicode specification, which defined characters as + * fixed-width 16-bit entities. The Unicode Standard has since been + * changed to allow for characters whose representation requires more + * than 16 bits. The range of legal code points is now + * U+0000 to U+10FFFF, known as Unicode scalar value. + * (Refer to the + * definition of the U+n notation in the Unicode + * Standard.) + * + *

The set of characters from U+0000 to U+FFFF is + * sometimes referred to as the Basic Multilingual Plane (BMP). + * Characters whose code points are greater + * than U+FFFF are called supplementary characters. The Java + * platform uses the UTF-16 representation in {@code char} arrays and + * in the {@code String} and {@code StringBuffer} classes. In + * this representation, supplementary characters are represented as a pair + * of {@code char} values, the first from the high-surrogates + * range, (\uD800-\uDBFF), the second from the + * low-surrogates range (\uDC00-\uDFFF). + * + *

A {@code char} value, therefore, represents Basic + * Multilingual Plane (BMP) code points, including the surrogate + * code points, or code units of the UTF-16 encoding. An + * {@code int} value represents all Unicode code points, + * including supplementary code points. The lower (least significant) + * 21 bits of {@code int} are used to represent Unicode code + * points and the upper (most significant) 11 bits must be zero. + * Unless otherwise specified, the behavior with respect to + * supplementary characters and surrogate {@code char} values is + * as follows: + * + *

    + *
  • The methods that only accept a {@code char} value cannot support + * supplementary characters. They treat {@code char} values from the + * surrogate ranges as undefined characters. For example, + * {@code Character.isLetter('\u005CuD840')} returns {@code false}, even though + * this specific value if followed by any low-surrogate value in a string + * would represent a letter. + * + *
  • The methods that accept an {@code int} value support all + * Unicode characters, including supplementary characters. For + * example, {@code Character.isLetter(0x2F81A)} returns + * {@code true} because the code point value represents a letter + * (a CJK ideograph). + *
+ * + *

In the Java SE API documentation, Unicode code point is + * used for character values in the range between U+0000 and U+10FFFF, + * and Unicode code unit is used for 16-bit + * {@code char} values that are code units of the UTF-16 + * encoding. For more information on Unicode terminology, refer to the + * Unicode Glossary. + * + * @author Lee Boynton + * @author Guy Steele + * @author Akira Tanaka + * @author Martin Buchholz + * @author Ulf Zibis + * @since 1.0 + */ +public final +class Character implements java.io.Serializable, Comparable { + /** + * The minimum radix available for conversion to and from strings. + * The constant value of this field is the smallest value permitted + * for the radix argument in radix-conversion methods such as the + * {@code digit} method, the {@code forDigit} method, and the + * {@code toString} method of class {@code Integer}. + * + * @see Character#digit(char, int) + * @see Character#forDigit(int, int) + * @see Integer#toString(int, int) + * @see Integer#valueOf(String) + */ + public static final int MIN_RADIX = 2; + + /** + * The maximum radix available for conversion to and from strings. + * The constant value of this field is the largest value permitted + * for the radix argument in radix-conversion methods such as the + * {@code digit} method, the {@code forDigit} method, and the + * {@code toString} method of class {@code Integer}. + * + * @see Character#digit(char, int) + * @see Character#forDigit(int, int) + * @see Integer#toString(int, int) + * @see Integer#valueOf(String) + */ + public static final int MAX_RADIX = 36; + + /** + * The constant value of this field is the smallest value of type + * {@code char}, {@code '\u005Cu0000'}. + * + * @since 1.0.2 + */ + public static final char MIN_VALUE = '\u0000'; + + /** + * The constant value of this field is the largest value of type + * {@code char}, {@code '\u005CuFFFF'}. + * + * @since 1.0.2 + */ + public static final char MAX_VALUE = '\uFFFF'; + + /** + * The {@code Class} instance representing the primitive type + * {@code char}. + * + * @since 1.1 + */ + public static final Class TYPE = Class.getPrimitiveClass("char"); + + /* + * Normative general types + */ + + /* + * General character types + */ + + /** + * General category "Cn" in the Unicode specification. + * @since 1.1 + */ + public static final byte UNASSIGNED = 0; + + /** + * General category "Lu" in the Unicode specification. + * @since 1.1 + */ + public static final byte UPPERCASE_LETTER = 1; + + /** + * General category "Ll" in the Unicode specification. + * @since 1.1 + */ + public static final byte LOWERCASE_LETTER = 2; + + /** + * General category "Lt" in the Unicode specification. + * @since 1.1 + */ + public static final byte TITLECASE_LETTER = 3; + + /** + * General category "Lm" in the Unicode specification. + * @since 1.1 + */ + public static final byte MODIFIER_LETTER = 4; + + /** + * General category "Lo" in the Unicode specification. + * @since 1.1 + */ + public static final byte OTHER_LETTER = 5; + + /** + * General category "Mn" in the Unicode specification. + * @since 1.1 + */ + public static final byte NON_SPACING_MARK = 6; + + /** + * General category "Me" in the Unicode specification. + * @since 1.1 + */ + public static final byte ENCLOSING_MARK = 7; + + /** + * General category "Mc" in the Unicode specification. + * @since 1.1 + */ + public static final byte COMBINING_SPACING_MARK = 8; + + /** + * General category "Nd" in the Unicode specification. + * @since 1.1 + */ + public static final byte DECIMAL_DIGIT_NUMBER = 9; + + /** + * General category "Nl" in the Unicode specification. + * @since 1.1 + */ + public static final byte LETTER_NUMBER = 10; + + /** + * General category "No" in the Unicode specification. + * @since 1.1 + */ + public static final byte OTHER_NUMBER = 11; + + /** + * General category "Zs" in the Unicode specification. + * @since 1.1 + */ + public static final byte SPACE_SEPARATOR = 12; + + /** + * General category "Zl" in the Unicode specification. + * @since 1.1 + */ + public static final byte LINE_SEPARATOR = 13; + + /** + * General category "Zp" in the Unicode specification. + * @since 1.1 + */ + public static final byte PARAGRAPH_SEPARATOR = 14; + + /** + * General category "Cc" in the Unicode specification. + * @since 1.1 + */ + public static final byte CONTROL = 15; + + /** + * General category "Cf" in the Unicode specification. + * @since 1.1 + */ + public static final byte FORMAT = 16; + + /** + * General category "Co" in the Unicode specification. + * @since 1.1 + */ + public static final byte PRIVATE_USE = 18; + + /** + * General category "Cs" in the Unicode specification. + * @since 1.1 + */ + public static final byte SURROGATE = 19; + + /** + * General category "Pd" in the Unicode specification. + * @since 1.1 + */ + public static final byte DASH_PUNCTUATION = 20; + + /** + * General category "Ps" in the Unicode specification. + * @since 1.1 + */ + public static final byte START_PUNCTUATION = 21; + + /** + * General category "Pe" in the Unicode specification. + * @since 1.1 + */ + public static final byte END_PUNCTUATION = 22; + + /** + * General category "Pc" in the Unicode specification. + * @since 1.1 + */ + public static final byte CONNECTOR_PUNCTUATION = 23; + + /** + * General category "Po" in the Unicode specification. + * @since 1.1 + */ + public static final byte OTHER_PUNCTUATION = 24; + + /** + * General category "Sm" in the Unicode specification. + * @since 1.1 + */ + public static final byte MATH_SYMBOL = 25; + + /** + * General category "Sc" in the Unicode specification. + * @since 1.1 + */ + public static final byte CURRENCY_SYMBOL = 26; + + /** + * General category "Sk" in the Unicode specification. + * @since 1.1 + */ + public static final byte MODIFIER_SYMBOL = 27; + + /** + * General category "So" in the Unicode specification. + * @since 1.1 + */ + public static final byte OTHER_SYMBOL = 28; + + /** + * General category "Pi" in the Unicode specification. + * @since 1.4 + */ + public static final byte INITIAL_QUOTE_PUNCTUATION = 29; + + /** + * General category "Pf" in the Unicode specification. + * @since 1.4 + */ + public static final byte FINAL_QUOTE_PUNCTUATION = 30; + + /** + * Error flag. Use int (code point) to avoid confusion with U+FFFF. + */ + static final int ERROR = 0xFFFFFFFF; + + + /** + * Undefined bidirectional character type. Undefined {@code char} + * values have undefined directionality in the Unicode specification. + * @since 1.4 + */ + public static final byte DIRECTIONALITY_UNDEFINED = -1; + + /** + * Strong bidirectional character type "L" in the Unicode specification. + * @since 1.4 + */ + public static final byte DIRECTIONALITY_LEFT_TO_RIGHT = 0; + + /** + * Strong bidirectional character type "R" in the Unicode specification. + * @since 1.4 + */ + public static final byte DIRECTIONALITY_RIGHT_TO_LEFT = 1; + + /** + * Strong bidirectional character type "AL" in the Unicode specification. + * @since 1.4 + */ + public static final byte DIRECTIONALITY_RIGHT_TO_LEFT_ARABIC = 2; + + /** + * Weak bidirectional character type "EN" in the Unicode specification. + * @since 1.4 + */ + public static final byte DIRECTIONALITY_EUROPEAN_NUMBER = 3; + + /** + * Weak bidirectional character type "ES" in the Unicode specification. + * @since 1.4 + */ + public static final byte DIRECTIONALITY_EUROPEAN_NUMBER_SEPARATOR = 4; + + /** + * Weak bidirectional character type "ET" in the Unicode specification. + * @since 1.4 + */ + public static final byte DIRECTIONALITY_EUROPEAN_NUMBER_TERMINATOR = 5; + + /** + * Weak bidirectional character type "AN" in the Unicode specification. + * @since 1.4 + */ + public static final byte DIRECTIONALITY_ARABIC_NUMBER = 6; + + /** + * Weak bidirectional character type "CS" in the Unicode specification. + * @since 1.4 + */ + public static final byte DIRECTIONALITY_COMMON_NUMBER_SEPARATOR = 7; + + /** + * Weak bidirectional character type "NSM" in the Unicode specification. + * @since 1.4 + */ + public static final byte DIRECTIONALITY_NONSPACING_MARK = 8; + + /** + * Weak bidirectional character type "BN" in the Unicode specification. + * @since 1.4 + */ + public static final byte DIRECTIONALITY_BOUNDARY_NEUTRAL = 9; + + /** + * Neutral bidirectional character type "B" in the Unicode specification. + * @since 1.4 + */ + public static final byte DIRECTIONALITY_PARAGRAPH_SEPARATOR = 10; + + /** + * Neutral bidirectional character type "S" in the Unicode specification. + * @since 1.4 + */ + public static final byte DIRECTIONALITY_SEGMENT_SEPARATOR = 11; + + /** + * Neutral bidirectional character type "WS" in the Unicode specification. + * @since 1.4 + */ + public static final byte DIRECTIONALITY_WHITESPACE = 12; + + /** + * Neutral bidirectional character type "ON" in the Unicode specification. + * @since 1.4 + */ + public static final byte DIRECTIONALITY_OTHER_NEUTRALS = 13; + + /** + * Strong bidirectional character type "LRE" in the Unicode specification. + * @since 1.4 + */ + public static final byte DIRECTIONALITY_LEFT_TO_RIGHT_EMBEDDING = 14; + + /** + * Strong bidirectional character type "LRO" in the Unicode specification. + * @since 1.4 + */ + public static final byte DIRECTIONALITY_LEFT_TO_RIGHT_OVERRIDE = 15; + + /** + * Strong bidirectional character type "RLE" in the Unicode specification. + * @since 1.4 + */ + public static final byte DIRECTIONALITY_RIGHT_TO_LEFT_EMBEDDING = 16; + + /** + * Strong bidirectional character type "RLO" in the Unicode specification. + * @since 1.4 + */ + public static final byte DIRECTIONALITY_RIGHT_TO_LEFT_OVERRIDE = 17; + + /** + * Weak bidirectional character type "PDF" in the Unicode specification. + * @since 1.4 + */ + public static final byte DIRECTIONALITY_POP_DIRECTIONAL_FORMAT = 18; + + /** + * The minimum value of a + * + * Unicode high-surrogate code unit + * in the UTF-16 encoding, constant {@code '\u005CuD800'}. + * A high-surrogate is also known as a leading-surrogate. + * + * @since 1.5 + */ + public static final char MIN_HIGH_SURROGATE = '\uD800'; + + /** + * The maximum value of a + * + * Unicode high-surrogate code unit + * in the UTF-16 encoding, constant {@code '\u005CuDBFF'}. + * A high-surrogate is also known as a leading-surrogate. + * + * @since 1.5 + */ + public static final char MAX_HIGH_SURROGATE = '\uDBFF'; + + /** + * The minimum value of a + * + * Unicode low-surrogate code unit + * in the UTF-16 encoding, constant {@code '\u005CuDC00'}. + * A low-surrogate is also known as a trailing-surrogate. + * + * @since 1.5 + */ + public static final char MIN_LOW_SURROGATE = '\uDC00'; + + /** + * The maximum value of a + * + * Unicode low-surrogate code unit + * in the UTF-16 encoding, constant {@code '\u005CuDFFF'}. + * A low-surrogate is also known as a trailing-surrogate. + * + * @since 1.5 + */ + public static final char MAX_LOW_SURROGATE = '\uDFFF'; + + /** + * The minimum value of a Unicode surrogate code unit in the + * UTF-16 encoding, constant {@code '\u005CuD800'}. + * + * @since 1.5 + */ + public static final char MIN_SURROGATE = MIN_HIGH_SURROGATE; + + /** + * The maximum value of a Unicode surrogate code unit in the + * UTF-16 encoding, constant {@code '\u005CuDFFF'}. + * + * @since 1.5 + */ + public static final char MAX_SURROGATE = MAX_LOW_SURROGATE; + + /** + * The minimum value of a + * + * Unicode supplementary code point, constant {@code U+10000}. + * + * @since 1.5 + */ + public static final int MIN_SUPPLEMENTARY_CODE_POINT = 0x010000; + + /** + * The minimum value of a + * + * Unicode code point, constant {@code U+0000}. + * + * @since 1.5 + */ + public static final int MIN_CODE_POINT = 0x000000; + + /** + * The maximum value of a + * + * Unicode code point, constant {@code U+10FFFF}. + * + * @since 1.5 + */ + public static final int MAX_CODE_POINT = 0X10FFFF; + + + /** + * Instances of this class represent particular subsets of the Unicode + * character set. The only family of subsets defined in the + * {@code Character} class is {@link Character.UnicodeBlock}. + * Other portions of the Java API may define other subsets for their + * own purposes. + * + * @since 1.2 + */ + public static class Subset { + + private String name; + + /** + * Constructs a new {@code Subset} instance. + * + * @param name The name of this subset + * @exception NullPointerException if name is {@code null} + */ + protected Subset(String name) { + if (name == null) { + throw new NullPointerException("name"); + } + this.name = name; + } + + /** + * Compares two {@code Subset} objects for equality. + * This method returns {@code true} if and only if + * {@code this} and the argument refer to the same + * object; since this method is {@code final}, this + * guarantee holds for all subclasses. + */ + public final boolean equals(Object obj) { + return (this == obj); + } + + /** + * Returns the standard hash code as defined by the + * {@link Object#hashCode} method. This method + * is {@code final} in order to ensure that the + * {@code equals} and {@code hashCode} methods will + * be consistent in all subclasses. + */ + public final int hashCode() { + return super.hashCode(); + } + + /** + * Returns the name of this subset. + */ + public final String toString() { + return name; + } + } + + // See http://www.unicode.org/Public/UNIDATA/Blocks.txt + // for the latest specification of Unicode Blocks. + + + /** + * The value of the {@code Character}. + * + * @serial + */ + private final char value; + + /** use serialVersionUID from JDK 1.0.2 for interoperability */ + private static final long serialVersionUID = 3786198910865385080L; + + /** + * Constructs a newly allocated {@code Character} object that + * represents the specified {@code char} value. + * + * @param value the value to be represented by the + * {@code Character} object. + */ + public Character(char value) { + this.value = value; + } + + private static class CharacterCache { + private CharacterCache(){} + + static final Character cache[] = new Character[127 + 1]; + + static { + for (int i = 0; i < cache.length; i++) + cache[i] = new Character((char)i); + } + } + + /** + * Returns a Character instance representing the specified + * char value. + * If a new Character instance is not required, this method + * should generally be used in preference to the constructor + * {@link #Character(char)}, as this method is likely to yield + * significantly better space and time performance by caching + * frequently requested values. + * + * This method will always cache values in the range {@code + * '\u005Cu0000'} to {@code '\u005Cu007F'}, inclusive, and may + * cache other values outside of this range. + * + * @param c a char value. + * @return a Character instance representing c. + * @since 1.5 + */ + public static Character valueOf(char c) { + if (c <= 127) { // must cache + return CharacterCache.cache[(int)c]; + } + return new Character(c); + } + + /** + * Returns the value of this {@code Character} object. + * @return the primitive {@code char} value represented by + * this object. + */ + public char charValue() { + return value; + } + + /** + * Returns a hash code for this {@code Character}; equal to the result + * of invoking {@code charValue()}. + * + * @return a hash code value for this {@code Character} + */ + public int hashCode() { + return (int)value; + } + + /** + * Compares this object against the specified object. + * The result is {@code true} if and only if the argument is not + * {@code null} and is a {@code Character} object that + * represents the same {@code char} value as this object. + * + * @param obj the object to compare with. + * @return {@code true} if the objects are the same; + * {@code false} otherwise. + */ + public boolean equals(Object obj) { + if (obj instanceof Character) { + return value == ((Character)obj).charValue(); + } + return false; + } + + /** + * Returns a {@code String} object representing this + * {@code Character}'s value. The result is a string of + * length 1 whose sole component is the primitive + * {@code char} value represented by this + * {@code Character} object. + * + * @return a string representation of this object. + */ + public String toString() { + char buf[] = {value}; + return String.valueOf(buf); + } + + /** + * Returns a {@code String} object representing the + * specified {@code char}. The result is a string of length + * 1 consisting solely of the specified {@code char}. + * + * @param c the {@code char} to be converted + * @return the string representation of the specified {@code char} + * @since 1.4 + */ + public static String toString(char c) { + return String.valueOf(c); + } + + /** + * Determines whether the specified code point is a valid + * + * Unicode code point value. + * + * @param codePoint the Unicode code point to be tested + * @return {@code true} if the specified code point value is between + * {@link #MIN_CODE_POINT} and + * {@link #MAX_CODE_POINT} inclusive; + * {@code false} otherwise. + * @since 1.5 + */ + public static boolean isValidCodePoint(int codePoint) { + // Optimized form of: + // codePoint >= MIN_CODE_POINT && codePoint <= MAX_CODE_POINT + int plane = codePoint >>> 16; + return plane < ((MAX_CODE_POINT + 1) >>> 16); + } + + /** + * Determines whether the specified character (Unicode code point) + * is in the Basic Multilingual Plane (BMP). + * Such code points can be represented using a single {@code char}. + * + * @param codePoint the character (Unicode code point) to be tested + * @return {@code true} if the specified code point is between + * {@link #MIN_VALUE} and {@link #MAX_VALUE} inclusive; + * {@code false} otherwise. + * @since 1.7 + */ + public static boolean isBmpCodePoint(int codePoint) { + return codePoint >>> 16 == 0; + // Optimized form of: + // codePoint >= MIN_VALUE && codePoint <= MAX_VALUE + // We consistently use logical shift (>>>) to facilitate + // additional runtime optimizations. + } + + /** + * Determines whether the specified character (Unicode code point) + * is in the supplementary character range. + * + * @param codePoint the character (Unicode code point) to be tested + * @return {@code true} if the specified code point is between + * {@link #MIN_SUPPLEMENTARY_CODE_POINT} and + * {@link #MAX_CODE_POINT} inclusive; + * {@code false} otherwise. + * @since 1.5 + */ + public static boolean isSupplementaryCodePoint(int codePoint) { + return codePoint >= MIN_SUPPLEMENTARY_CODE_POINT + && codePoint < MAX_CODE_POINT + 1; + } + + /** + * Determines if the given {@code char} value is a + * + * Unicode high-surrogate code unit + * (also known as leading-surrogate code unit). + * + *

Such values do not represent characters by themselves, + * but are used in the representation of + * supplementary characters + * in the UTF-16 encoding. + * + * @param ch the {@code char} value to be tested. + * @return {@code true} if the {@code char} value is between + * {@link #MIN_HIGH_SURROGATE} and + * {@link #MAX_HIGH_SURROGATE} inclusive; + * {@code false} otherwise. + * @see Character#isLowSurrogate(char) + * @see Character.UnicodeBlock#of(int) + * @since 1.5 + */ + public static boolean isHighSurrogate(char ch) { + // Help VM constant-fold; MAX_HIGH_SURROGATE + 1 == MIN_LOW_SURROGATE + return ch >= MIN_HIGH_SURROGATE && ch < (MAX_HIGH_SURROGATE + 1); + } + + /** + * Determines if the given {@code char} value is a + * + * Unicode low-surrogate code unit + * (also known as trailing-surrogate code unit). + * + *

Such values do not represent characters by themselves, + * but are used in the representation of + * supplementary characters + * in the UTF-16 encoding. + * + * @param ch the {@code char} value to be tested. + * @return {@code true} if the {@code char} value is between + * {@link #MIN_LOW_SURROGATE} and + * {@link #MAX_LOW_SURROGATE} inclusive; + * {@code false} otherwise. + * @see Character#isHighSurrogate(char) + * @since 1.5 + */ + public static boolean isLowSurrogate(char ch) { + return ch >= MIN_LOW_SURROGATE && ch < (MAX_LOW_SURROGATE + 1); + } + + /** + * Determines if the given {@code char} value is a Unicode + * surrogate code unit. + * + *

Such values do not represent characters by themselves, + * but are used in the representation of + * supplementary characters + * in the UTF-16 encoding. + * + *

A char value is a surrogate code unit if and only if it is either + * a {@linkplain #isLowSurrogate(char) low-surrogate code unit} or + * a {@linkplain #isHighSurrogate(char) high-surrogate code unit}. + * + * @param ch the {@code char} value to be tested. + * @return {@code true} if the {@code char} value is between + * {@link #MIN_SURROGATE} and + * {@link #MAX_SURROGATE} inclusive; + * {@code false} otherwise. + * @since 1.7 + */ + public static boolean isSurrogate(char ch) { + return ch >= MIN_SURROGATE && ch < (MAX_SURROGATE + 1); + } + + /** + * Determines whether the specified pair of {@code char} + * values is a valid + * + * Unicode surrogate pair. + + *

This method is equivalent to the expression: + *

+     * isHighSurrogate(high) && isLowSurrogate(low)
+     * 
+ * + * @param high the high-surrogate code value to be tested + * @param low the low-surrogate code value to be tested + * @return {@code true} if the specified high and + * low-surrogate code values represent a valid surrogate pair; + * {@code false} otherwise. + * @since 1.5 + */ + public static boolean isSurrogatePair(char high, char low) { + return isHighSurrogate(high) && isLowSurrogate(low); + } + + /** + * Determines the number of {@code char} values needed to + * represent the specified character (Unicode code point). If the + * specified character is equal to or greater than 0x10000, then + * the method returns 2. Otherwise, the method returns 1. + * + *

This method doesn't validate the specified character to be a + * valid Unicode code point. The caller must validate the + * character value using {@link #isValidCodePoint(int) isValidCodePoint} + * if necessary. + * + * @param codePoint the character (Unicode code point) to be tested. + * @return 2 if the character is a valid supplementary character; 1 otherwise. + * @see Character#isSupplementaryCodePoint(int) + * @since 1.5 + */ + public static int charCount(int codePoint) { + return codePoint >= MIN_SUPPLEMENTARY_CODE_POINT ? 2 : 1; + } + + /** + * Converts the specified surrogate pair to its supplementary code + * point value. This method does not validate the specified + * surrogate pair. The caller must validate it using {@link + * #isSurrogatePair(char, char) isSurrogatePair} if necessary. + * + * @param high the high-surrogate code unit + * @param low the low-surrogate code unit + * @return the supplementary code point composed from the + * specified surrogate pair. + * @since 1.5 + */ + public static int toCodePoint(char high, char low) { + // Optimized form of: + // return ((high - MIN_HIGH_SURROGATE) << 10) + // + (low - MIN_LOW_SURROGATE) + // + MIN_SUPPLEMENTARY_CODE_POINT; + return ((high << 10) + low) + (MIN_SUPPLEMENTARY_CODE_POINT + - (MIN_HIGH_SURROGATE << 10) + - MIN_LOW_SURROGATE); + } + + /** + * Returns the code point at the given index of the + * {@code CharSequence}. If the {@code char} value at + * the given index in the {@code CharSequence} is in the + * high-surrogate range, the following index is less than the + * length of the {@code CharSequence}, and the + * {@code char} value at the following index is in the + * low-surrogate range, then the supplementary code point + * corresponding to this surrogate pair is returned. Otherwise, + * the {@code char} value at the given index is returned. + * + * @param seq a sequence of {@code char} values (Unicode code + * units) + * @param index the index to the {@code char} values (Unicode + * code units) in {@code seq} to be converted + * @return the Unicode code point at the given index + * @exception NullPointerException if {@code seq} is null. + * @exception IndexOutOfBoundsException if the value + * {@code index} is negative or not less than + * {@link CharSequence#length() seq.length()}. + * @since 1.5 + */ + public static int codePointAt(CharSequence seq, int index) { + char c1 = seq.charAt(index++); + if (isHighSurrogate(c1)) { + if (index < seq.length()) { + char c2 = seq.charAt(index); + if (isLowSurrogate(c2)) { + return toCodePoint(c1, c2); + } + } + } + return c1; + } + + /** + * Returns the code point at the given index of the + * {@code char} array. If the {@code char} value at + * the given index in the {@code char} array is in the + * high-surrogate range, the following index is less than the + * length of the {@code char} array, and the + * {@code char} value at the following index is in the + * low-surrogate range, then the supplementary code point + * corresponding to this surrogate pair is returned. Otherwise, + * the {@code char} value at the given index is returned. + * + * @param a the {@code char} array + * @param index the index to the {@code char} values (Unicode + * code units) in the {@code char} array to be converted + * @return the Unicode code point at the given index + * @exception NullPointerException if {@code a} is null. + * @exception IndexOutOfBoundsException if the value + * {@code index} is negative or not less than + * the length of the {@code char} array. + * @since 1.5 + */ + public static int codePointAt(char[] a, int index) { + return codePointAtImpl(a, index, a.length); + } + + /** + * Returns the code point at the given index of the + * {@code char} array, where only array elements with + * {@code index} less than {@code limit} can be used. If + * the {@code char} value at the given index in the + * {@code char} array is in the high-surrogate range, the + * following index is less than the {@code limit}, and the + * {@code char} value at the following index is in the + * low-surrogate range, then the supplementary code point + * corresponding to this surrogate pair is returned. Otherwise, + * the {@code char} value at the given index is returned. + * + * @param a the {@code char} array + * @param index the index to the {@code char} values (Unicode + * code units) in the {@code char} array to be converted + * @param limit the index after the last array element that + * can be used in the {@code char} array + * @return the Unicode code point at the given index + * @exception NullPointerException if {@code a} is null. + * @exception IndexOutOfBoundsException if the {@code index} + * argument is negative or not less than the {@code limit} + * argument, or if the {@code limit} argument is negative or + * greater than the length of the {@code char} array. + * @since 1.5 + */ + public static int codePointAt(char[] a, int index, int limit) { + if (index >= limit || limit < 0 || limit > a.length) { + throw new IndexOutOfBoundsException(); + } + return codePointAtImpl(a, index, limit); + } + + // throws ArrayIndexOutofBoundsException if index out of bounds + static int codePointAtImpl(char[] a, int index, int limit) { + char c1 = a[index++]; + if (isHighSurrogate(c1)) { + if (index < limit) { + char c2 = a[index]; + if (isLowSurrogate(c2)) { + return toCodePoint(c1, c2); + } + } + } + return c1; + } + + /** + * Returns the code point preceding the given index of the + * {@code CharSequence}. If the {@code char} value at + * {@code (index - 1)} in the {@code CharSequence} is in + * the low-surrogate range, {@code (index - 2)} is not + * negative, and the {@code char} value at {@code (index - 2)} + * in the {@code CharSequence} is in the + * high-surrogate range, then the supplementary code point + * corresponding to this surrogate pair is returned. Otherwise, + * the {@code char} value at {@code (index - 1)} is + * returned. + * + * @param seq the {@code CharSequence} instance + * @param index the index following the code point that should be returned + * @return the Unicode code point value before the given index. + * @exception NullPointerException if {@code seq} is null. + * @exception IndexOutOfBoundsException if the {@code index} + * argument is less than 1 or greater than {@link + * CharSequence#length() seq.length()}. + * @since 1.5 + */ + public static int codePointBefore(CharSequence seq, int index) { + char c2 = seq.charAt(--index); + if (isLowSurrogate(c2)) { + if (index > 0) { + char c1 = seq.charAt(--index); + if (isHighSurrogate(c1)) { + return toCodePoint(c1, c2); + } + } + } + return c2; + } + + /** + * Returns the code point preceding the given index of the + * {@code char} array. If the {@code char} value at + * {@code (index - 1)} in the {@code char} array is in + * the low-surrogate range, {@code (index - 2)} is not + * negative, and the {@code char} value at {@code (index - 2)} + * in the {@code char} array is in the + * high-surrogate range, then the supplementary code point + * corresponding to this surrogate pair is returned. Otherwise, + * the {@code char} value at {@code (index - 1)} is + * returned. + * + * @param a the {@code char} array + * @param index the index following the code point that should be returned + * @return the Unicode code point value before the given index. + * @exception NullPointerException if {@code a} is null. + * @exception IndexOutOfBoundsException if the {@code index} + * argument is less than 1 or greater than the length of the + * {@code char} array + * @since 1.5 + */ + public static int codePointBefore(char[] a, int index) { + return codePointBeforeImpl(a, index, 0); + } + + /** + * Returns the code point preceding the given index of the + * {@code char} array, where only array elements with + * {@code index} greater than or equal to {@code start} + * can be used. If the {@code char} value at {@code (index - 1)} + * in the {@code char} array is in the + * low-surrogate range, {@code (index - 2)} is not less than + * {@code start}, and the {@code char} value at + * {@code (index - 2)} in the {@code char} array is in + * the high-surrogate range, then the supplementary code point + * corresponding to this surrogate pair is returned. Otherwise, + * the {@code char} value at {@code (index - 1)} is + * returned. + * + * @param a the {@code char} array + * @param index the index following the code point that should be returned + * @param start the index of the first array element in the + * {@code char} array + * @return the Unicode code point value before the given index. + * @exception NullPointerException if {@code a} is null. + * @exception IndexOutOfBoundsException if the {@code index} + * argument is not greater than the {@code start} argument or + * is greater than the length of the {@code char} array, or + * if the {@code start} argument is negative or not less than + * the length of the {@code char} array. + * @since 1.5 + */ + public static int codePointBefore(char[] a, int index, int start) { + if (index <= start || start < 0 || start >= a.length) { + throw new IndexOutOfBoundsException(); + } + return codePointBeforeImpl(a, index, start); + } + + // throws ArrayIndexOutofBoundsException if index-1 out of bounds + static int codePointBeforeImpl(char[] a, int index, int start) { + char c2 = a[--index]; + if (isLowSurrogate(c2)) { + if (index > start) { + char c1 = a[--index]; + if (isHighSurrogate(c1)) { + return toCodePoint(c1, c2); + } + } + } + return c2; + } + + /** + * Returns the leading surrogate (a + * + * high surrogate code unit) of the + * + * surrogate pair + * representing the specified supplementary character (Unicode + * code point) in the UTF-16 encoding. If the specified character + * is not a + * supplementary character, + * an unspecified {@code char} is returned. + * + *

If + * {@link #isSupplementaryCodePoint isSupplementaryCodePoint(x)} + * is {@code true}, then + * {@link #isHighSurrogate isHighSurrogate}{@code (highSurrogate(x))} and + * {@link #toCodePoint toCodePoint}{@code (highSurrogate(x), }{@link #lowSurrogate lowSurrogate}{@code (x)) == x} + * are also always {@code true}. + * + * @param codePoint a supplementary character (Unicode code point) + * @return the leading surrogate code unit used to represent the + * character in the UTF-16 encoding + * @since 1.7 + */ + public static char highSurrogate(int codePoint) { + return (char) ((codePoint >>> 10) + + (MIN_HIGH_SURROGATE - (MIN_SUPPLEMENTARY_CODE_POINT >>> 10))); + } + + /** + * Returns the trailing surrogate (a + * + * low surrogate code unit) of the + * + * surrogate pair + * representing the specified supplementary character (Unicode + * code point) in the UTF-16 encoding. If the specified character + * is not a + * supplementary character, + * an unspecified {@code char} is returned. + * + *

If + * {@link #isSupplementaryCodePoint isSupplementaryCodePoint(x)} + * is {@code true}, then + * {@link #isLowSurrogate isLowSurrogate}{@code (lowSurrogate(x))} and + * {@link #toCodePoint toCodePoint}{@code (}{@link #highSurrogate highSurrogate}{@code (x), lowSurrogate(x)) == x} + * are also always {@code true}. + * + * @param codePoint a supplementary character (Unicode code point) + * @return the trailing surrogate code unit used to represent the + * character in the UTF-16 encoding + * @since 1.7 + */ + public static char lowSurrogate(int codePoint) { + return (char) ((codePoint & 0x3ff) + MIN_LOW_SURROGATE); + } + + /** + * Converts the specified character (Unicode code point) to its + * UTF-16 representation. If the specified code point is a BMP + * (Basic Multilingual Plane or Plane 0) value, the same value is + * stored in {@code dst[dstIndex]}, and 1 is returned. If the + * specified code point is a supplementary character, its + * surrogate values are stored in {@code dst[dstIndex]} + * (high-surrogate) and {@code dst[dstIndex+1]} + * (low-surrogate), and 2 is returned. + * + * @param codePoint the character (Unicode code point) to be converted. + * @param dst an array of {@code char} in which the + * {@code codePoint}'s UTF-16 value is stored. + * @param dstIndex the start index into the {@code dst} + * array where the converted value is stored. + * @return 1 if the code point is a BMP code point, 2 if the + * code point is a supplementary code point. + * @exception IllegalArgumentException if the specified + * {@code codePoint} is not a valid Unicode code point. + * @exception NullPointerException if the specified {@code dst} is null. + * @exception IndexOutOfBoundsException if {@code dstIndex} + * is negative or not less than {@code dst.length}, or if + * {@code dst} at {@code dstIndex} doesn't have enough + * array element(s) to store the resulting {@code char} + * value(s). (If {@code dstIndex} is equal to + * {@code dst.length-1} and the specified + * {@code codePoint} is a supplementary character, the + * high-surrogate value is not stored in + * {@code dst[dstIndex]}.) + * @since 1.5 + */ + public static int toChars(int codePoint, char[] dst, int dstIndex) { + if (isBmpCodePoint(codePoint)) { + dst[dstIndex] = (char) codePoint; + return 1; + } else if (isValidCodePoint(codePoint)) { + toSurrogates(codePoint, dst, dstIndex); + return 2; + } else { + throw new IllegalArgumentException(); + } + } + + /** + * Converts the specified character (Unicode code point) to its + * UTF-16 representation stored in a {@code char} array. If + * the specified code point is a BMP (Basic Multilingual Plane or + * Plane 0) value, the resulting {@code char} array has + * the same value as {@code codePoint}. If the specified code + * point is a supplementary code point, the resulting + * {@code char} array has the corresponding surrogate pair. + * + * @param codePoint a Unicode code point + * @return a {@code char} array having + * {@code codePoint}'s UTF-16 representation. + * @exception IllegalArgumentException if the specified + * {@code codePoint} is not a valid Unicode code point. + * @since 1.5 + */ + public static char[] toChars(int codePoint) { + if (isBmpCodePoint(codePoint)) { + return new char[] { (char) codePoint }; + } else if (isValidCodePoint(codePoint)) { + char[] result = new char[2]; + toSurrogates(codePoint, result, 0); + return result; + } else { + throw new IllegalArgumentException(); + } + } + + static void toSurrogates(int codePoint, char[] dst, int index) { + // We write elements "backwards" to guarantee all-or-nothing + dst[index+1] = lowSurrogate(codePoint); + dst[index] = highSurrogate(codePoint); + } + + /** + * Returns the number of Unicode code points in the text range of + * the specified char sequence. The text range begins at the + * specified {@code beginIndex} and extends to the + * {@code char} at index {@code endIndex - 1}. Thus the + * length (in {@code char}s) of the text range is + * {@code endIndex-beginIndex}. Unpaired surrogates within + * the text range count as one code point each. + * + * @param seq the char sequence + * @param beginIndex the index to the first {@code char} of + * the text range. + * @param endIndex the index after the last {@code char} of + * the text range. + * @return the number of Unicode code points in the specified text + * range + * @exception NullPointerException if {@code seq} is null. + * @exception IndexOutOfBoundsException if the + * {@code beginIndex} is negative, or {@code endIndex} + * is larger than the length of the given sequence, or + * {@code beginIndex} is larger than {@code endIndex}. + * @since 1.5 + */ + public static int codePointCount(CharSequence seq, int beginIndex, int endIndex) { + int length = seq.length(); + if (beginIndex < 0 || endIndex > length || beginIndex > endIndex) { + throw new IndexOutOfBoundsException(); + } + int n = endIndex - beginIndex; + for (int i = beginIndex; i < endIndex; ) { + if (isHighSurrogate(seq.charAt(i++)) && i < endIndex && + isLowSurrogate(seq.charAt(i))) { + n--; + i++; + } + } + return n; + } + + /** + * Returns the number of Unicode code points in a subarray of the + * {@code char} array argument. The {@code offset} + * argument is the index of the first {@code char} of the + * subarray and the {@code count} argument specifies the + * length of the subarray in {@code char}s. Unpaired + * surrogates within the subarray count as one code point each. + * + * @param a the {@code char} array + * @param offset the index of the first {@code char} in the + * given {@code char} array + * @param count the length of the subarray in {@code char}s + * @return the number of Unicode code points in the specified subarray + * @exception NullPointerException if {@code a} is null. + * @exception IndexOutOfBoundsException if {@code offset} or + * {@code count} is negative, or if {@code offset + + * count} is larger than the length of the given array. + * @since 1.5 + */ + public static int codePointCount(char[] a, int offset, int count) { + if (count > a.length - offset || offset < 0 || count < 0) { + throw new IndexOutOfBoundsException(); + } + return codePointCountImpl(a, offset, count); + } + + static int codePointCountImpl(char[] a, int offset, int count) { + int endIndex = offset + count; + int n = count; + for (int i = offset; i < endIndex; ) { + if (isHighSurrogate(a[i++]) && i < endIndex && + isLowSurrogate(a[i])) { + n--; + i++; + } + } + return n; + } + + /** + * Returns the index within the given char sequence that is offset + * from the given {@code index} by {@code codePointOffset} + * code points. Unpaired surrogates within the text range given by + * {@code index} and {@code codePointOffset} count as + * one code point each. + * + * @param seq the char sequence + * @param index the index to be offset + * @param codePointOffset the offset in code points + * @return the index within the char sequence + * @exception NullPointerException if {@code seq} is null. + * @exception IndexOutOfBoundsException if {@code index} + * is negative or larger then the length of the char sequence, + * or if {@code codePointOffset} is positive and the + * subsequence starting with {@code index} has fewer than + * {@code codePointOffset} code points, or if + * {@code codePointOffset} is negative and the subsequence + * before {@code index} has fewer than the absolute value + * of {@code codePointOffset} code points. + * @since 1.5 + */ + public static int offsetByCodePoints(CharSequence seq, int index, + int codePointOffset) { + int length = seq.length(); + if (index < 0 || index > length) { + throw new IndexOutOfBoundsException(); + } + + int x = index; + if (codePointOffset >= 0) { + int i; + for (i = 0; x < length && i < codePointOffset; i++) { + if (isHighSurrogate(seq.charAt(x++)) && x < length && + isLowSurrogate(seq.charAt(x))) { + x++; + } + } + if (i < codePointOffset) { + throw new IndexOutOfBoundsException(); + } + } else { + int i; + for (i = codePointOffset; x > 0 && i < 0; i++) { + if (isLowSurrogate(seq.charAt(--x)) && x > 0 && + isHighSurrogate(seq.charAt(x-1))) { + x--; + } + } + if (i < 0) { + throw new IndexOutOfBoundsException(); + } + } + return x; + } + + /** + * Returns the index within the given {@code char} subarray + * that is offset from the given {@code index} by + * {@code codePointOffset} code points. The + * {@code start} and {@code count} arguments specify a + * subarray of the {@code char} array. Unpaired surrogates + * within the text range given by {@code index} and + * {@code codePointOffset} count as one code point each. + * + * @param a the {@code char} array + * @param start the index of the first {@code char} of the + * subarray + * @param count the length of the subarray in {@code char}s + * @param index the index to be offset + * @param codePointOffset the offset in code points + * @return the index within the subarray + * @exception NullPointerException if {@code a} is null. + * @exception IndexOutOfBoundsException + * if {@code start} or {@code count} is negative, + * or if {@code start + count} is larger than the length of + * the given array, + * or if {@code index} is less than {@code start} or + * larger then {@code start + count}, + * or if {@code codePointOffset} is positive and the text range + * starting with {@code index} and ending with {@code start + count - 1} + * has fewer than {@code codePointOffset} code + * points, + * or if {@code codePointOffset} is negative and the text range + * starting with {@code start} and ending with {@code index - 1} + * has fewer than the absolute value of + * {@code codePointOffset} code points. + * @since 1.5 + */ + public static int offsetByCodePoints(char[] a, int start, int count, + int index, int codePointOffset) { + if (count > a.length-start || start < 0 || count < 0 + || index < start || index > start+count) { + throw new IndexOutOfBoundsException(); + } + return offsetByCodePointsImpl(a, start, count, index, codePointOffset); + } + + static int offsetByCodePointsImpl(char[]a, int start, int count, + int index, int codePointOffset) { + int x = index; + if (codePointOffset >= 0) { + int limit = start + count; + int i; + for (i = 0; x < limit && i < codePointOffset; i++) { + if (isHighSurrogate(a[x++]) && x < limit && + isLowSurrogate(a[x])) { + x++; + } + } + if (i < codePointOffset) { + throw new IndexOutOfBoundsException(); + } + } else { + int i; + for (i = codePointOffset; x > start && i < 0; i++) { + if (isLowSurrogate(a[--x]) && x > start && + isHighSurrogate(a[x-1])) { + x--; + } + } + if (i < 0) { + throw new IndexOutOfBoundsException(); + } + } + return x; + } + + /** + * Determines if the specified character is a lowercase character. + *

+ * A character is lowercase if its general category type, provided + * by {@code Character.getType(ch)}, is + * {@code LOWERCASE_LETTER}, or it has contributory property + * Other_Lowercase as defined by the Unicode Standard. + *

+ * The following are examples of lowercase characters: + *

+     * a b c d e f g h i j k l m n o p q r s t u v w x y z
+     * '\u00DF' '\u00E0' '\u00E1' '\u00E2' '\u00E3' '\u00E4' '\u00E5' '\u00E6'
+     * '\u00E7' '\u00E8' '\u00E9' '\u00EA' '\u00EB' '\u00EC' '\u00ED' '\u00EE'
+     * '\u00EF' '\u00F0' '\u00F1' '\u00F2' '\u00F3' '\u00F4' '\u00F5' '\u00F6'
+     * '\u00F8' '\u00F9' '\u00FA' '\u00FB' '\u00FC' '\u00FD' '\u00FE' '\u00FF'
+     * 
+ *

Many other Unicode characters are lowercase too. + * + *

Note: This method cannot handle supplementary characters. To support + * all Unicode characters, including supplementary characters, use + * the {@link #isLowerCase(int)} method. + * + * @param ch the character to be tested. + * @return {@code true} if the character is lowercase; + * {@code false} otherwise. + * @see Character#isLowerCase(char) + * @see Character#isTitleCase(char) + * @see Character#toLowerCase(char) + * @see Character#getType(char) + */ + public static boolean isLowerCase(char ch) { + return ch == toLowerCase(ch); + } + + /** + * Determines if the specified character is an uppercase character. + *

+ * A character is uppercase if its general category type, provided by + * {@code Character.getType(ch)}, is {@code UPPERCASE_LETTER}. + * or it has contributory property Other_Uppercase as defined by the Unicode Standard. + *

+ * The following are examples of uppercase characters: + *

+     * A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
+     * '\u00C0' '\u00C1' '\u00C2' '\u00C3' '\u00C4' '\u00C5' '\u00C6' '\u00C7'
+     * '\u00C8' '\u00C9' '\u00CA' '\u00CB' '\u00CC' '\u00CD' '\u00CE' '\u00CF'
+     * '\u00D0' '\u00D1' '\u00D2' '\u00D3' '\u00D4' '\u00D5' '\u00D6' '\u00D8'
+     * '\u00D9' '\u00DA' '\u00DB' '\u00DC' '\u00DD' '\u00DE'
+     * 
+ *

Many other Unicode characters are uppercase too.

+ * + *

Note: This method cannot handle supplementary characters. To support + * all Unicode characters, including supplementary characters, use + * the {@link #isUpperCase(int)} method. + * + * @param ch the character to be tested. + * @return {@code true} if the character is uppercase; + * {@code false} otherwise. + * @see Character#isLowerCase(char) + * @see Character#isTitleCase(char) + * @see Character#toUpperCase(char) + * @see Character#getType(char) + * @since 1.0 + */ + public static boolean isUpperCase(char ch) { + return ch == toUpperCase(ch); + } + + /** + * Determines if the specified character is a titlecase character. + *

+ * A character is a titlecase character if its general + * category type, provided by {@code Character.getType(ch)}, + * is {@code TITLECASE_LETTER}. + *

+ * Some characters look like pairs of Latin letters. For example, there + * is an uppercase letter that looks like "LJ" and has a corresponding + * lowercase letter that looks like "lj". A third form, which looks like "Lj", + * is the appropriate form to use when rendering a word in lowercase + * with initial capitals, as for a book title. + *

+ * These are some of the Unicode characters for which this method returns + * {@code true}: + *

    + *
  • {@code LATIN CAPITAL LETTER D WITH SMALL LETTER Z WITH CARON} + *
  • {@code LATIN CAPITAL LETTER L WITH SMALL LETTER J} + *
  • {@code LATIN CAPITAL LETTER N WITH SMALL LETTER J} + *
  • {@code LATIN CAPITAL LETTER D WITH SMALL LETTER Z} + *
+ *

Many other Unicode characters are titlecase too.

+ * + *

Note: This method cannot handle supplementary characters. To support + * all Unicode characters, including supplementary characters, use + * the {@link #isTitleCase(int)} method. + * + * @param ch the character to be tested. + * @return {@code true} if the character is titlecase; + * {@code false} otherwise. + * @see Character#isLowerCase(char) + * @see Character#isUpperCase(char) + * @see Character#toTitleCase(char) + * @see Character#getType(char) + * @since 1.0.2 + */ + public static boolean isTitleCase(char ch) { + return isTitleCase((int)ch); + } + + /** + * Determines if the specified character (Unicode code point) is a titlecase character. + *

+ * A character is a titlecase character if its general + * category type, provided by {@link Character#getType(int) getType(codePoint)}, + * is {@code TITLECASE_LETTER}. + *

+ * Some characters look like pairs of Latin letters. For example, there + * is an uppercase letter that looks like "LJ" and has a corresponding + * lowercase letter that looks like "lj". A third form, which looks like "Lj", + * is the appropriate form to use when rendering a word in lowercase + * with initial capitals, as for a book title. + *

+ * These are some of the Unicode characters for which this method returns + * {@code true}: + *

    + *
  • {@code LATIN CAPITAL LETTER D WITH SMALL LETTER Z WITH CARON} + *
  • {@code LATIN CAPITAL LETTER L WITH SMALL LETTER J} + *
  • {@code LATIN CAPITAL LETTER N WITH SMALL LETTER J} + *
  • {@code LATIN CAPITAL LETTER D WITH SMALL LETTER Z} + *
+ *

Many other Unicode characters are titlecase too.

+ * + * @param codePoint the character (Unicode code point) to be tested. + * @return {@code true} if the character is titlecase; + * {@code false} otherwise. + * @see Character#isLowerCase(int) + * @see Character#isUpperCase(int) + * @see Character#toTitleCase(int) + * @see Character#getType(int) + * @since 1.5 + */ + public static boolean isTitleCase(int codePoint) { + return getType(codePoint) == Character.TITLECASE_LETTER; + } + + /** + * Determines if the specified character is a digit. + *

+ * A character is a digit if its general category type, provided + * by {@code Character.getType(ch)}, is + * {@code DECIMAL_DIGIT_NUMBER}. + *

+ * Some Unicode character ranges that contain digits: + *

    + *
  • {@code '\u005Cu0030'} through {@code '\u005Cu0039'}, + * ISO-LATIN-1 digits ({@code '0'} through {@code '9'}) + *
  • {@code '\u005Cu0660'} through {@code '\u005Cu0669'}, + * Arabic-Indic digits + *
  • {@code '\u005Cu06F0'} through {@code '\u005Cu06F9'}, + * Extended Arabic-Indic digits + *
  • {@code '\u005Cu0966'} through {@code '\u005Cu096F'}, + * Devanagari digits + *
  • {@code '\u005CuFF10'} through {@code '\u005CuFF19'}, + * Fullwidth digits + *
+ * + * Many other character ranges contain digits as well. + * + *

Note: This method cannot handle supplementary characters. To support + * all Unicode characters, including supplementary characters, use + * the {@link #isDigit(int)} method. + * + * @param ch the character to be tested. + * @return {@code true} if the character is a digit; + * {@code false} otherwise. + * @see Character#digit(char, int) + * @see Character#forDigit(int, int) + * @see Character#getType(char) + */ + public static boolean isDigit(char ch) { + return String.valueOf(ch).matches("\\d"); + } + + /** + * Determines if the specified character (Unicode code point) is a digit. + *

+ * A character is a digit if its general category type, provided + * by {@link Character#getType(int) getType(codePoint)}, is + * {@code DECIMAL_DIGIT_NUMBER}. + *

+ * Some Unicode character ranges that contain digits: + *

    + *
  • {@code '\u005Cu0030'} through {@code '\u005Cu0039'}, + * ISO-LATIN-1 digits ({@code '0'} through {@code '9'}) + *
  • {@code '\u005Cu0660'} through {@code '\u005Cu0669'}, + * Arabic-Indic digits + *
  • {@code '\u005Cu06F0'} through {@code '\u005Cu06F9'}, + * Extended Arabic-Indic digits + *
  • {@code '\u005Cu0966'} through {@code '\u005Cu096F'}, + * Devanagari digits + *
  • {@code '\u005CuFF10'} through {@code '\u005CuFF19'}, + * Fullwidth digits + *
+ * + * Many other character ranges contain digits as well. + * + * @param codePoint the character (Unicode code point) to be tested. + * @return {@code true} if the character is a digit; + * {@code false} otherwise. + * @see Character#forDigit(int, int) + * @see Character#getType(int) + * @since 1.5 + */ + public static boolean isDigit(int codePoint) { + return fromCodeChars(codePoint).matches("\\d"); + } + + @JavaScriptBody(args = "c", body = "return String.fromCharCode(c);") + private native static String fromCodeChars(int codePoint); + + /** + * Determines if a character is defined in Unicode. + *

+ * A character is defined if at least one of the following is true: + *

    + *
  • It has an entry in the UnicodeData file. + *
  • It has a value in a range defined by the UnicodeData file. + *
+ * + *

Note: This method cannot handle supplementary characters. To support + * all Unicode characters, including supplementary characters, use + * the {@link #isDefined(int)} method. + * + * @param ch the character to be tested + * @return {@code true} if the character has a defined meaning + * in Unicode; {@code false} otherwise. + * @see Character#isDigit(char) + * @see Character#isLetter(char) + * @see Character#isLetterOrDigit(char) + * @see Character#isLowerCase(char) + * @see Character#isTitleCase(char) + * @see Character#isUpperCase(char) + * @since 1.0.2 + */ + public static boolean isDefined(char ch) { + return isDefined((int)ch); + } + + /** + * Determines if a character (Unicode code point) is defined in Unicode. + *

+ * A character is defined if at least one of the following is true: + *

    + *
  • It has an entry in the UnicodeData file. + *
  • It has a value in a range defined by the UnicodeData file. + *
+ * + * @param codePoint the character (Unicode code point) to be tested. + * @return {@code true} if the character has a defined meaning + * in Unicode; {@code false} otherwise. + * @see Character#isDigit(int) + * @see Character#isLetter(int) + * @see Character#isLetterOrDigit(int) + * @see Character#isLowerCase(int) + * @see Character#isTitleCase(int) + * @see Character#isUpperCase(int) + * @since 1.5 + */ + public static boolean isDefined(int codePoint) { + return getType(codePoint) != Character.UNASSIGNED; + } + + /** + * Determines if the specified character is a letter. + *

+ * A character is considered to be a letter if its general + * category type, provided by {@code Character.getType(ch)}, + * is any of the following: + *

    + *
  • {@code UPPERCASE_LETTER} + *
  • {@code LOWERCASE_LETTER} + *
  • {@code TITLECASE_LETTER} + *
  • {@code MODIFIER_LETTER} + *
  • {@code OTHER_LETTER} + *
+ * + * Not all letters have case. Many characters are + * letters but are neither uppercase nor lowercase nor titlecase. + * + *

Note: This method cannot handle supplementary characters. To support + * all Unicode characters, including supplementary characters, use + * the {@link #isLetter(int)} method. + * + * @param ch the character to be tested. + * @return {@code true} if the character is a letter; + * {@code false} otherwise. + * @see Character#isDigit(char) + * @see Character#isJavaIdentifierStart(char) + * @see Character#isJavaLetter(char) + * @see Character#isJavaLetterOrDigit(char) + * @see Character#isLetterOrDigit(char) + * @see Character#isLowerCase(char) + * @see Character#isTitleCase(char) + * @see Character#isUnicodeIdentifierStart(char) + * @see Character#isUpperCase(char) + */ + public static boolean isLetter(char ch) { + return String.valueOf(ch).matches("\\w") && !isDigit(ch); + } + + /** + * Determines if the specified character (Unicode code point) is a letter. + *

+ * A character is considered to be a letter if its general + * category type, provided by {@link Character#getType(int) getType(codePoint)}, + * is any of the following: + *

    + *
  • {@code UPPERCASE_LETTER} + *
  • {@code LOWERCASE_LETTER} + *
  • {@code TITLECASE_LETTER} + *
  • {@code MODIFIER_LETTER} + *
  • {@code OTHER_LETTER} + *
+ * + * Not all letters have case. Many characters are + * letters but are neither uppercase nor lowercase nor titlecase. + * + * @param codePoint the character (Unicode code point) to be tested. + * @return {@code true} if the character is a letter; + * {@code false} otherwise. + * @see Character#isDigit(int) + * @see Character#isJavaIdentifierStart(int) + * @see Character#isLetterOrDigit(int) + * @see Character#isLowerCase(int) + * @see Character#isTitleCase(int) + * @see Character#isUnicodeIdentifierStart(int) + * @see Character#isUpperCase(int) + * @since 1.5 + */ + public static boolean isLetter(int codePoint) { + return fromCodeChars(codePoint).matches("\\w") && !isDigit(codePoint); + } + + /** + * Determines if the specified character is a letter or digit. + *

+ * A character is considered to be a letter or digit if either + * {@code Character.isLetter(char ch)} or + * {@code Character.isDigit(char ch)} returns + * {@code true} for the character. + * + *

Note: This method cannot handle supplementary characters. To support + * all Unicode characters, including supplementary characters, use + * the {@link #isLetterOrDigit(int)} method. + * + * @param ch the character to be tested. + * @return {@code true} if the character is a letter or digit; + * {@code false} otherwise. + * @see Character#isDigit(char) + * @see Character#isJavaIdentifierPart(char) + * @see Character#isJavaLetter(char) + * @see Character#isJavaLetterOrDigit(char) + * @see Character#isLetter(char) + * @see Character#isUnicodeIdentifierPart(char) + * @since 1.0.2 + */ + public static boolean isLetterOrDigit(char ch) { + return String.valueOf(ch).matches("\\w"); + } + + /** + * Determines if the specified character (Unicode code point) is a letter or digit. + *

+ * A character is considered to be a letter or digit if either + * {@link #isLetter(int) isLetter(codePoint)} or + * {@link #isDigit(int) isDigit(codePoint)} returns + * {@code true} for the character. + * + * @param codePoint the character (Unicode code point) to be tested. + * @return {@code true} if the character is a letter or digit; + * {@code false} otherwise. + * @see Character#isDigit(int) + * @see Character#isJavaIdentifierPart(int) + * @see Character#isLetter(int) + * @see Character#isUnicodeIdentifierPart(int) + * @since 1.5 + */ + public static boolean isLetterOrDigit(int codePoint) { + return fromCodeChars(codePoint).matches("\\w"); + } + + static int getType(int x) { + throw new UnsupportedOperationException(); + } + + /** + * Converts the character argument to lowercase using case + * mapping information from the UnicodeData file. + *

+ * Note that + * {@code Character.isLowerCase(Character.toLowerCase(ch))} + * does not always return {@code true} for some ranges of + * characters, particularly those that are symbols or ideographs. + * + *

In general, {@link String#toLowerCase()} should be used to map + * characters to lowercase. {@code String} case mapping methods + * have several benefits over {@code Character} case mapping methods. + * {@code String} case mapping methods can perform locale-sensitive + * mappings, context-sensitive mappings, and 1:M character mappings, whereas + * the {@code Character} case mapping methods cannot. + * + *

Note: This method cannot handle supplementary characters. To support + * all Unicode characters, including supplementary characters, use + * the {@link #toLowerCase(int)} method. + * + * @param ch the character to be converted. + * @return the lowercase equivalent of the character, if any; + * otherwise, the character itself. + * @see Character#isLowerCase(char) + * @see String#toLowerCase() + */ + public static char toLowerCase(char ch) { + return String.valueOf(ch).toLowerCase().charAt(0); + } + + /** + * Converts the character argument to uppercase using case mapping + * information from the UnicodeData file. + *

+ * Note that + * {@code Character.isUpperCase(Character.toUpperCase(ch))} + * does not always return {@code true} for some ranges of + * characters, particularly those that are symbols or ideographs. + * + *

In general, {@link String#toUpperCase()} should be used to map + * characters to uppercase. {@code String} case mapping methods + * have several benefits over {@code Character} case mapping methods. + * {@code String} case mapping methods can perform locale-sensitive + * mappings, context-sensitive mappings, and 1:M character mappings, whereas + * the {@code Character} case mapping methods cannot. + * + *

Note: This method cannot handle supplementary characters. To support + * all Unicode characters, including supplementary characters, use + * the {@link #toUpperCase(int)} method. + * + * @param ch the character to be converted. + * @return the uppercase equivalent of the character, if any; + * otherwise, the character itself. + * @see Character#isUpperCase(char) + * @see String#toUpperCase() + */ + public static char toUpperCase(char ch) { + return String.valueOf(ch).toUpperCase().charAt(0); + } + + /** + * Returns the numeric value of the character {@code ch} in the + * specified radix. + *

+ * If the radix is not in the range {@code MIN_RADIX} ≤ + * {@code radix} ≤ {@code MAX_RADIX} or if the + * value of {@code ch} is not a valid digit in the specified + * radix, {@code -1} is returned. A character is a valid digit + * if at least one of the following is true: + *

    + *
  • The method {@code isDigit} is {@code true} of the character + * and the Unicode decimal digit value of the character (or its + * single-character decomposition) is less than the specified radix. + * In this case the decimal digit value is returned. + *
  • The character is one of the uppercase Latin letters + * {@code 'A'} through {@code 'Z'} and its code is less than + * {@code radix + 'A' - 10}. + * In this case, {@code ch - 'A' + 10} + * is returned. + *
  • The character is one of the lowercase Latin letters + * {@code 'a'} through {@code 'z'} and its code is less than + * {@code radix + 'a' - 10}. + * In this case, {@code ch - 'a' + 10} + * is returned. + *
  • The character is one of the fullwidth uppercase Latin letters A + * ({@code '\u005CuFF21'}) through Z ({@code '\u005CuFF3A'}) + * and its code is less than + * {@code radix + '\u005CuFF21' - 10}. + * In this case, {@code ch - '\u005CuFF21' + 10} + * is returned. + *
  • The character is one of the fullwidth lowercase Latin letters a + * ({@code '\u005CuFF41'}) through z ({@code '\u005CuFF5A'}) + * and its code is less than + * {@code radix + '\u005CuFF41' - 10}. + * In this case, {@code ch - '\u005CuFF41' + 10} + * is returned. + *
+ * + *

Note: This method cannot handle supplementary characters. To support + * all Unicode characters, including supplementary characters, use + * the {@link #digit(int, int)} method. + * + * @param ch the character to be converted. + * @param radix the radix. + * @return the numeric value represented by the character in the + * specified radix. + * @see Character#forDigit(int, int) + * @see Character#isDigit(char) + */ + public static int digit(char ch, int radix) { + return digit((int)ch, radix); + } + + /** + * Returns the numeric value of the specified character (Unicode + * code point) in the specified radix. + * + *

If the radix is not in the range {@code MIN_RADIX} ≤ + * {@code radix} ≤ {@code MAX_RADIX} or if the + * character is not a valid digit in the specified + * radix, {@code -1} is returned. A character is a valid digit + * if at least one of the following is true: + *

    + *
  • The method {@link #isDigit(int) isDigit(codePoint)} is {@code true} of the character + * and the Unicode decimal digit value of the character (or its + * single-character decomposition) is less than the specified radix. + * In this case the decimal digit value is returned. + *
  • The character is one of the uppercase Latin letters + * {@code 'A'} through {@code 'Z'} and its code is less than + * {@code radix + 'A' - 10}. + * In this case, {@code codePoint - 'A' + 10} + * is returned. + *
  • The character is one of the lowercase Latin letters + * {@code 'a'} through {@code 'z'} and its code is less than + * {@code radix + 'a' - 10}. + * In this case, {@code codePoint - 'a' + 10} + * is returned. + *
  • The character is one of the fullwidth uppercase Latin letters A + * ({@code '\u005CuFF21'}) through Z ({@code '\u005CuFF3A'}) + * and its code is less than + * {@code radix + '\u005CuFF21' - 10}. + * In this case, + * {@code codePoint - '\u005CuFF21' + 10} + * is returned. + *
  • The character is one of the fullwidth lowercase Latin letters a + * ({@code '\u005CuFF41'}) through z ({@code '\u005CuFF5A'}) + * and its code is less than + * {@code radix + '\u005CuFF41'- 10}. + * In this case, + * {@code codePoint - '\u005CuFF41' + 10} + * is returned. + *
+ * + * @param codePoint the character (Unicode code point) to be converted. + * @param radix the radix. + * @return the numeric value represented by the character in the + * specified radix. + * @see Character#forDigit(int, int) + * @see Character#isDigit(int) + * @since 1.5 + */ + public static int digit(int codePoint, int radix) { + throw new UnsupportedOperationException(); + } + + /** + * Returns the {@code int} value that the specified Unicode + * character represents. For example, the character + * {@code '\u005Cu216C'} (the roman numeral fifty) will return + * an int with a value of 50. + *

+ * The letters A-Z in their uppercase ({@code '\u005Cu0041'} through + * {@code '\u005Cu005A'}), lowercase + * ({@code '\u005Cu0061'} through {@code '\u005Cu007A'}), and + * full width variant ({@code '\u005CuFF21'} through + * {@code '\u005CuFF3A'} and {@code '\u005CuFF41'} through + * {@code '\u005CuFF5A'}) forms have numeric values from 10 + * through 35. This is independent of the Unicode specification, + * which does not assign numeric values to these {@code char} + * values. + *

+ * If the character does not have a numeric value, then -1 is returned. + * If the character has a numeric value that cannot be represented as a + * nonnegative integer (for example, a fractional value), then -2 + * is returned. + * + *

Note: This method cannot handle supplementary characters. To support + * all Unicode characters, including supplementary characters, use + * the {@link #getNumericValue(int)} method. + * + * @param ch the character to be converted. + * @return the numeric value of the character, as a nonnegative {@code int} + * value; -2 if the character has a numeric value that is not a + * nonnegative integer; -1 if the character has no numeric value. + * @see Character#forDigit(int, int) + * @see Character#isDigit(char) + * @since 1.1 + */ + public static int getNumericValue(char ch) { + return getNumericValue((int)ch); + } + + /** + * Returns the {@code int} value that the specified + * character (Unicode code point) represents. For example, the character + * {@code '\u005Cu216C'} (the Roman numeral fifty) will return + * an {@code int} with a value of 50. + *

+ * The letters A-Z in their uppercase ({@code '\u005Cu0041'} through + * {@code '\u005Cu005A'}), lowercase + * ({@code '\u005Cu0061'} through {@code '\u005Cu007A'}), and + * full width variant ({@code '\u005CuFF21'} through + * {@code '\u005CuFF3A'} and {@code '\u005CuFF41'} through + * {@code '\u005CuFF5A'}) forms have numeric values from 10 + * through 35. This is independent of the Unicode specification, + * which does not assign numeric values to these {@code char} + * values. + *

+ * If the character does not have a numeric value, then -1 is returned. + * If the character has a numeric value that cannot be represented as a + * nonnegative integer (for example, a fractional value), then -2 + * is returned. + * + * @param codePoint the character (Unicode code point) to be converted. + * @return the numeric value of the character, as a nonnegative {@code int} + * value; -2 if the character has a numeric value that is not a + * nonnegative integer; -1 if the character has no numeric value. + * @see Character#forDigit(int, int) + * @see Character#isDigit(int) + * @since 1.5 + */ + public static int getNumericValue(int codePoint) { + throw new UnsupportedOperationException(); + } + + /** + * Determines if the specified character is ISO-LATIN-1 white space. + * This method returns {@code true} for the following five + * characters only: + * + * + * + * + * + * + * + * + * + * + * + *
{@code '\t'} {@code U+0009}{@code HORIZONTAL TABULATION}
{@code '\n'} {@code U+000A}{@code NEW LINE}
{@code '\f'} {@code U+000C}{@code FORM FEED}
{@code '\r'} {@code U+000D}{@code CARRIAGE RETURN}
{@code ' '} {@code U+0020}{@code SPACE}
+ * + * @param ch the character to be tested. + * @return {@code true} if the character is ISO-LATIN-1 white + * space; {@code false} otherwise. + * @see Character#isSpaceChar(char) + * @see Character#isWhitespace(char) + * @deprecated Replaced by isWhitespace(char). + */ + @Deprecated + public static boolean isSpace(char ch) { + return (ch <= 0x0020) && + (((((1L << 0x0009) | + (1L << 0x000A) | + (1L << 0x000C) | + (1L << 0x000D) | + (1L << 0x0020)) >> ch) & 1L) != 0); + } + + + + /** + * Determines if the specified character is white space according to Java. + * A character is a Java whitespace character if and only if it satisfies + * one of the following criteria: + *

    + *
  • It is a Unicode space character ({@code SPACE_SEPARATOR}, + * {@code LINE_SEPARATOR}, or {@code PARAGRAPH_SEPARATOR}) + * but is not also a non-breaking space ({@code '\u005Cu00A0'}, + * {@code '\u005Cu2007'}, {@code '\u005Cu202F'}). + *
  • It is {@code '\u005Ct'}, U+0009 HORIZONTAL TABULATION. + *
  • It is {@code '\u005Cn'}, U+000A LINE FEED. + *
  • It is {@code '\u005Cu000B'}, U+000B VERTICAL TABULATION. + *
  • It is {@code '\u005Cf'}, U+000C FORM FEED. + *
  • It is {@code '\u005Cr'}, U+000D CARRIAGE RETURN. + *
  • It is {@code '\u005Cu001C'}, U+001C FILE SEPARATOR. + *
  • It is {@code '\u005Cu001D'}, U+001D GROUP SEPARATOR. + *
  • It is {@code '\u005Cu001E'}, U+001E RECORD SEPARATOR. + *
  • It is {@code '\u005Cu001F'}, U+001F UNIT SEPARATOR. + *
+ * + *

Note: This method cannot handle supplementary characters. To support + * all Unicode characters, including supplementary characters, use + * the {@link #isWhitespace(int)} method. + * + * @param ch the character to be tested. + * @return {@code true} if the character is a Java whitespace + * character; {@code false} otherwise. + * @see Character#isSpaceChar(char) + * @since 1.1 + */ + public static boolean isWhitespace(char ch) { + return isWhitespace((int)ch); + } + + /** + * Determines if the specified character (Unicode code point) is + * white space according to Java. A character is a Java + * whitespace character if and only if it satisfies one of the + * following criteria: + *

    + *
  • It is a Unicode space character ({@link #SPACE_SEPARATOR}, + * {@link #LINE_SEPARATOR}, or {@link #PARAGRAPH_SEPARATOR}) + * but is not also a non-breaking space ({@code '\u005Cu00A0'}, + * {@code '\u005Cu2007'}, {@code '\u005Cu202F'}). + *
  • It is {@code '\u005Ct'}, U+0009 HORIZONTAL TABULATION. + *
  • It is {@code '\u005Cn'}, U+000A LINE FEED. + *
  • It is {@code '\u005Cu000B'}, U+000B VERTICAL TABULATION. + *
  • It is {@code '\u005Cf'}, U+000C FORM FEED. + *
  • It is {@code '\u005Cr'}, U+000D CARRIAGE RETURN. + *
  • It is {@code '\u005Cu001C'}, U+001C FILE SEPARATOR. + *
  • It is {@code '\u005Cu001D'}, U+001D GROUP SEPARATOR. + *
  • It is {@code '\u005Cu001E'}, U+001E RECORD SEPARATOR. + *
  • It is {@code '\u005Cu001F'}, U+001F UNIT SEPARATOR. + *
+ *

+ * + * @param codePoint the character (Unicode code point) to be tested. + * @return {@code true} if the character is a Java whitespace + * character; {@code false} otherwise. + * @see Character#isSpaceChar(int) + * @since 1.5 + */ + public static boolean isWhitespace(int codePoint) { + throw new UnsupportedOperationException(); + } + + /** + * Determines if the specified character is an ISO control + * character. A character is considered to be an ISO control + * character if its code is in the range {@code '\u005Cu0000'} + * through {@code '\u005Cu001F'} or in the range + * {@code '\u005Cu007F'} through {@code '\u005Cu009F'}. + * + *

Note: This method cannot handle supplementary characters. To support + * all Unicode characters, including supplementary characters, use + * the {@link #isISOControl(int)} method. + * + * @param ch the character to be tested. + * @return {@code true} if the character is an ISO control character; + * {@code false} otherwise. + * + * @see Character#isSpaceChar(char) + * @see Character#isWhitespace(char) + * @since 1.1 + */ + public static boolean isISOControl(char ch) { + return isISOControl((int)ch); + } + + /** + * Determines if the referenced character (Unicode code point) is an ISO control + * character. A character is considered to be an ISO control + * character if its code is in the range {@code '\u005Cu0000'} + * through {@code '\u005Cu001F'} or in the range + * {@code '\u005Cu007F'} through {@code '\u005Cu009F'}. + * + * @param codePoint the character (Unicode code point) to be tested. + * @return {@code true} if the character is an ISO control character; + * {@code false} otherwise. + * @see Character#isSpaceChar(int) + * @see Character#isWhitespace(int) + * @since 1.5 + */ + public static boolean isISOControl(int codePoint) { + // Optimized form of: + // (codePoint >= 0x00 && codePoint <= 0x1F) || + // (codePoint >= 0x7F && codePoint <= 0x9F); + return codePoint <= 0x9F && + (codePoint >= 0x7F || (codePoint >>> 5 == 0)); + } + + /** + * Determines the character representation for a specific digit in + * the specified radix. If the value of {@code radix} is not a + * valid radix, or the value of {@code digit} is not a valid + * digit in the specified radix, the null character + * ({@code '\u005Cu0000'}) is returned. + *

+ * The {@code radix} argument is valid if it is greater than or + * equal to {@code MIN_RADIX} and less than or equal to + * {@code MAX_RADIX}. The {@code digit} argument is valid if + * {@code 0 <= digit < radix}. + *

+ * If the digit is less than 10, then + * {@code '0' + digit} is returned. Otherwise, the value + * {@code 'a' + digit - 10} is returned. + * + * @param digit the number to convert to a character. + * @param radix the radix. + * @return the {@code char} representation of the specified digit + * in the specified radix. + * @see Character#MIN_RADIX + * @see Character#MAX_RADIX + * @see Character#digit(char, int) + */ + public static char forDigit(int digit, int radix) { + if ((digit >= radix) || (digit < 0)) { + return '\0'; + } + if ((radix < Character.MIN_RADIX) || (radix > Character.MAX_RADIX)) { + return '\0'; + } + if (digit < 10) { + return (char)('0' + digit); + } + return (char)('a' - 10 + digit); + } + + /** + * Compares two {@code Character} objects numerically. + * + * @param anotherCharacter the {@code Character} to be compared. + + * @return the value {@code 0} if the argument {@code Character} + * is equal to this {@code Character}; a value less than + * {@code 0} if this {@code Character} is numerically less + * than the {@code Character} argument; and a value greater than + * {@code 0} if this {@code Character} is numerically greater + * than the {@code Character} argument (unsigned comparison). + * Note that this is strictly a numerical comparison; it is not + * locale-dependent. + * @since 1.2 + */ + public int compareTo(Character anotherCharacter) { + return compare(this.value, anotherCharacter.value); + } + + /** + * Compares two {@code char} values numerically. + * The value returned is identical to what would be returned by: + *

+     *    Character.valueOf(x).compareTo(Character.valueOf(y))
+     * 
+ * + * @param x the first {@code char} to compare + * @param y the second {@code char} to compare + * @return the value {@code 0} if {@code x == y}; + * a value less than {@code 0} if {@code x < y}; and + * a value greater than {@code 0} if {@code x > y} + * @since 1.7 + */ + public static int compare(char x, char y) { + return x - y; + } + + + /** + * The number of bits used to represent a char value in unsigned + * binary form, constant {@code 16}. + * + * @since 1.5 + */ + public static final int SIZE = 16; + + /** + * Returns the value obtained by reversing the order of the bytes in the + * specified char value. + * + * @return the value obtained by reversing (or, equivalently, swapping) + * the bytes in the specified char value. + * @since 1.5 + */ + public static char reverseBytes(char ch) { + return (char) (((ch & 0xFF00) >> 8) | (ch << 8)); + } + +} diff -r 388e48c0a37a -r 05224402145d emul/mini/src/main/java/java/lang/Class.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/emul/mini/src/main/java/java/lang/Class.java Wed Jan 23 20:39:23 2013 +0100 @@ -0,0 +1,1205 @@ +/* + * Copyright (c) 1994, 2010, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code 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 + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package java.lang; + +import java.io.ByteArrayInputStream; +import org.apidesign.bck2brwsr.emul.AnnotationImpl; +import java.io.InputStream; +import java.lang.annotation.Annotation; +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import java.lang.reflect.TypeVariable; +import org.apidesign.bck2brwsr.core.JavaScriptBody; +import org.apidesign.bck2brwsr.emul.MethodImpl; + +/** + * Instances of the class {@code Class} represent classes and + * interfaces in a running Java application. An enum is a kind of + * class and an annotation is a kind of interface. Every array also + * belongs to a class that is reflected as a {@code Class} object + * that is shared by all arrays with the same element type and number + * of dimensions. The primitive Java types ({@code boolean}, + * {@code byte}, {@code char}, {@code short}, + * {@code int}, {@code long}, {@code float}, and + * {@code double}), and the keyword {@code void} are also + * represented as {@code Class} objects. + * + *

{@code Class} has no public constructor. Instead {@code Class} + * objects are constructed automatically by the Java Virtual Machine as classes + * are loaded and by calls to the {@code defineClass} method in the class + * loader. + * + *

The following example uses a {@code Class} object to print the + * class name of an object: + * + *

+ *     void printClassName(Object obj) {
+ *         System.out.println("The class of " + obj +
+ *                            " is " + obj.getClass().getName());
+ *     }
+ * 
+ * + *

It is also possible to get the {@code Class} object for a named + * type (or for void) using a class literal. See Section 15.8.2 of + * The Java™ Language Specification. + * For example: + * + *

+ * {@code System.out.println("The name of class Foo is: "+Foo.class.getName());} + *
+ * + * @param the type of the class modeled by this {@code Class} + * object. For example, the type of {@code String.class} is {@code + * Class}. Use {@code Class} if the class being modeled is + * unknown. + * + * @author unascribed + * @see java.lang.ClassLoader#defineClass(byte[], int, int) + * @since JDK1.0 + */ +public final + class Class implements java.io.Serializable, + java.lang.reflect.GenericDeclaration, + java.lang.reflect.Type, + java.lang.reflect.AnnotatedElement { + private static final int ANNOTATION= 0x00002000; + private static final int ENUM = 0x00004000; + private static final int SYNTHETIC = 0x00001000; + + /* + * Constructor. Only the Java Virtual Machine creates Class + * objects. + */ + private Class() {} + + + /** + * Converts the object to a string. The string representation is the + * string "class" or "interface", followed by a space, and then by the + * fully qualified name of the class in the format returned by + * {@code getName}. If this {@code Class} object represents a + * primitive type, this method returns the name of the primitive type. If + * this {@code Class} object represents void this method returns + * "void". + * + * @return a string representation of this class object. + */ + public String toString() { + return (isInterface() ? "interface " : (isPrimitive() ? "" : "class ")) + + getName(); + } + + + /** + * Returns the {@code Class} object associated with the class or + * interface with the given string name. Invoking this method is + * equivalent to: + * + *
+ * {@code Class.forName(className, true, currentLoader)} + *
+ * + * where {@code currentLoader} denotes the defining class loader of + * the current class. + * + *

For example, the following code fragment returns the + * runtime {@code Class} descriptor for the class named + * {@code java.lang.Thread}: + * + *

+ * {@code Class t = Class.forName("java.lang.Thread")} + *
+ *

+ * A call to {@code forName("X")} causes the class named + * {@code X} to be initialized. + * + * @param className the fully qualified name of the desired class. + * @return the {@code Class} object for the class with the + * specified name. + * @exception LinkageError if the linkage fails + * @exception ExceptionInInitializerError if the initialization provoked + * by this method fails + * @exception ClassNotFoundException if the class cannot be located + */ + public static Class forName(String className) + throws ClassNotFoundException { + if (className.startsWith("[")) { + Class arrType = defineArray(className); + Class c = arrType; + while (c != null && c.isArray()) { + c = c.getComponentType0(); // verify component type is sane + } + return arrType; + } + Class c = loadCls(className, className.replace('.', '_')); + if (c == null) { + throw new ClassNotFoundException(className); + } + return c; + } + + @JavaScriptBody(args = {"n", "c" }, body = + "if (vm[c]) return vm[c].$class;\n" + + "if (vm.loadClass) {\n" + + " vm.loadClass(n);\n" + + " if (vm[c]) return vm[c].$class;\n" + + "}\n" + + "return null;" + ) + private static native Class loadCls(String n, String c); + + + /** + * Creates a new instance of the class represented by this {@code Class} + * object. The class is instantiated as if by a {@code new} + * expression with an empty argument list. The class is initialized if it + * has not already been initialized. + * + *

Note that this method propagates any exception thrown by the + * nullary constructor, including a checked exception. Use of + * this method effectively bypasses the compile-time exception + * checking that would otherwise be performed by the compiler. + * The {@link + * java.lang.reflect.Constructor#newInstance(java.lang.Object...) + * Constructor.newInstance} method avoids this problem by wrapping + * any exception thrown by the constructor in a (checked) {@link + * java.lang.reflect.InvocationTargetException}. + * + * @return a newly allocated instance of the class represented by this + * object. + * @exception IllegalAccessException if the class or its nullary + * constructor is not accessible. + * @exception InstantiationException + * if this {@code Class} represents an abstract class, + * an interface, an array class, a primitive type, or void; + * or if the class has no nullary constructor; + * or if the instantiation fails for some other reason. + * @exception ExceptionInInitializerError if the initialization + * provoked by this method fails. + * @exception SecurityException + * If a security manager, s, is present and any of the + * following conditions is met: + * + *

    + * + *
  • invocation of + * {@link SecurityManager#checkMemberAccess + * s.checkMemberAccess(this, Member.PUBLIC)} denies + * creation of new instances of this class + * + *
  • the caller's class loader is not the same as or an + * ancestor of the class loader for the current class and + * invocation of {@link SecurityManager#checkPackageAccess + * s.checkPackageAccess()} denies access to the package + * of this class + * + *
+ * + */ + @JavaScriptBody(args = { "self", "illegal" }, body = + "\nvar c = self.cnstr;" + + "\nif (c['cons__V']) {" + + "\n if ((c.cons__V.access & 0x1) != 0) {" + + "\n var inst = c();" + + "\n c.cons__V.call(inst);" + + "\n return inst;" + + "\n }" + + "\n return illegal;" + + "\n}" + + "\nreturn null;" + ) + private static native Object newInstance0(Class self, Object illegal); + + public T newInstance() + throws InstantiationException, IllegalAccessException + { + Object illegal = new Object(); + Object inst = newInstance0(this, illegal); + if (inst == null) { + throw new InstantiationException(getName()); + } + if (inst == illegal) { + throw new IllegalAccessException(); + } + return (T)inst; + } + + /** + * Determines if the specified {@code Object} is assignment-compatible + * with the object represented by this {@code Class}. This method is + * the dynamic equivalent of the Java language {@code instanceof} + * operator. The method returns {@code true} if the specified + * {@code Object} argument is non-null and can be cast to the + * reference type represented by this {@code Class} object without + * raising a {@code ClassCastException.} It returns {@code false} + * otherwise. + * + *

Specifically, if this {@code Class} object represents a + * declared class, this method returns {@code true} if the specified + * {@code Object} argument is an instance of the represented class (or + * of any of its subclasses); it returns {@code false} otherwise. If + * this {@code Class} object represents an array class, this method + * returns {@code true} if the specified {@code Object} argument + * can be converted to an object of the array class by an identity + * conversion or by a widening reference conversion; it returns + * {@code false} otherwise. If this {@code Class} object + * represents an interface, this method returns {@code true} if the + * class or any superclass of the specified {@code Object} argument + * implements this interface; it returns {@code false} otherwise. If + * this {@code Class} object represents a primitive type, this method + * returns {@code false}. + * + * @param obj the object to check + * @return true if {@code obj} is an instance of this class + * + * @since JDK1.1 + */ + public boolean isInstance(Object obj) { + String prop = "$instOf_" + getName().replace('.', '_'); + return hasProperty(obj, prop); + } + + @JavaScriptBody(args = { "who", "prop" }, body = + "if (who[prop]) return true; else return false;" + ) + private static native boolean hasProperty(Object who, String prop); + + + /** + * Determines if the class or interface represented by this + * {@code Class} object is either the same as, or is a superclass or + * superinterface of, the class or interface represented by the specified + * {@code Class} parameter. It returns {@code true} if so; + * otherwise it returns {@code false}. If this {@code Class} + * object represents a primitive type, this method returns + * {@code true} if the specified {@code Class} parameter is + * exactly this {@code Class} object; otherwise it returns + * {@code false}. + * + *

Specifically, this method tests whether the type represented by the + * specified {@code Class} parameter can be converted to the type + * represented by this {@code Class} object via an identity conversion + * or via a widening reference conversion. See The Java Language + * Specification, sections 5.1.1 and 5.1.4 , for details. + * + * @param cls the {@code Class} object to be checked + * @return the {@code boolean} value indicating whether objects of the + * type {@code cls} can be assigned to objects of this class + * @exception NullPointerException if the specified Class parameter is + * null. + * @since JDK1.1 + */ + public native boolean isAssignableFrom(Class cls); + + + /** + * Determines if the specified {@code Class} object represents an + * interface type. + * + * @return {@code true} if this object represents an interface; + * {@code false} otherwise. + */ + public boolean isInterface() { + return (getAccess() & 0x200) != 0; + } + + @JavaScriptBody(args = {}, body = "return this.access;") + private native int getAccess(); + + + /** + * Determines if this {@code Class} object represents an array class. + * + * @return {@code true} if this object represents an array class; + * {@code false} otherwise. + * @since JDK1.1 + */ + public boolean isArray() { + return hasProperty(this, "array"); // NOI18N + } + + + /** + * Determines if the specified {@code Class} object represents a + * primitive type. + * + *

There are nine predefined {@code Class} objects to represent + * the eight primitive types and void. These are created by the Java + * Virtual Machine, and have the same names as the primitive types that + * they represent, namely {@code boolean}, {@code byte}, + * {@code char}, {@code short}, {@code int}, + * {@code long}, {@code float}, and {@code double}. + * + *

These objects may only be accessed via the following public static + * final variables, and are the only {@code Class} objects for which + * this method returns {@code true}. + * + * @return true if and only if this class represents a primitive type + * + * @see java.lang.Boolean#TYPE + * @see java.lang.Character#TYPE + * @see java.lang.Byte#TYPE + * @see java.lang.Short#TYPE + * @see java.lang.Integer#TYPE + * @see java.lang.Long#TYPE + * @see java.lang.Float#TYPE + * @see java.lang.Double#TYPE + * @see java.lang.Void#TYPE + * @since JDK1.1 + */ + @JavaScriptBody(args = {}, body = + "if (this.primitive) return true;" + + "else return false;" + ) + public native boolean isPrimitive(); + + /** + * Returns true if this {@code Class} object represents an annotation + * type. Note that if this method returns true, {@link #isInterface()} + * would also return true, as all annotation types are also interfaces. + * + * @return {@code true} if this class object represents an annotation + * type; {@code false} otherwise + * @since 1.5 + */ + public boolean isAnnotation() { + return (getModifiers() & ANNOTATION) != 0; + } + + /** + * Returns {@code true} if this class is a synthetic class; + * returns {@code false} otherwise. + * @return {@code true} if and only if this class is a synthetic class as + * defined by the Java Language Specification. + * @since 1.5 + */ + public boolean isSynthetic() { + return (getModifiers() & SYNTHETIC) != 0; + } + + /** + * Returns the name of the entity (class, interface, array class, + * primitive type, or void) represented by this {@code Class} object, + * as a {@code String}. + * + *

If this class object represents a reference type that is not an + * array type then the binary name of the class is returned, as specified + * by + * The Java™ Language Specification. + * + *

If this class object represents a primitive type or void, then the + * name returned is a {@code String} equal to the Java language + * keyword corresponding to the primitive type or void. + * + *

If this class object represents a class of arrays, then the internal + * form of the name consists of the name of the element type preceded by + * one or more '{@code [}' characters representing the depth of the array + * nesting. The encoding of element type names is as follows: + * + *

+ *
Element Type     Encoding + *
boolean     Z + *
byte     B + *
char     C + *
class or interface + *     Lclassname; + *
double     D + *
float     F + *
int     I + *
long     J + *
short     S + *
+ * + *

The class or interface name classname is the binary name of + * the class specified above. + * + *

Examples: + *

+     * String.class.getName()
+     *     returns "java.lang.String"
+     * byte.class.getName()
+     *     returns "byte"
+     * (new Object[3]).getClass().getName()
+     *     returns "[Ljava.lang.Object;"
+     * (new int[3][4][5][6][7][8][9]).getClass().getName()
+     *     returns "[[[[[[[I"
+     * 
+ * + * @return the name of the class or interface + * represented by this object. + */ + public String getName() { + return jvmName().replace('/', '.'); + } + + @JavaScriptBody(args = {}, body = "return this.jvmName;") + private native String jvmName(); + + + /** + * Returns an array of {@code TypeVariable} objects that represent the + * type variables declared by the generic declaration represented by this + * {@code GenericDeclaration} object, in declaration order. Returns an + * array of length 0 if the underlying generic declaration declares no type + * variables. + * + * @return an array of {@code TypeVariable} objects that represent + * the type variables declared by this generic declaration + * @throws java.lang.reflect.GenericSignatureFormatError if the generic + * signature of this generic declaration does not conform to + * the format specified in + * The Java™ Virtual Machine Specification + * @since 1.5 + */ + public TypeVariable>[] getTypeParameters() { + throw new UnsupportedOperationException(); + } + + /** + * Returns the {@code Class} representing the superclass of the entity + * (class, interface, primitive type or void) represented by this + * {@code Class}. If this {@code Class} represents either the + * {@code Object} class, an interface, a primitive type, or void, then + * null is returned. If this object represents an array class then the + * {@code Class} object representing the {@code Object} class is + * returned. + * + * @return the superclass of the class represented by this object. + */ + @JavaScriptBody(args = {}, body = "return this.superclass;") + public native Class getSuperclass(); + + /** + * Returns the Java language modifiers for this class or interface, encoded + * in an integer. The modifiers consist of the Java Virtual Machine's + * constants for {@code public}, {@code protected}, + * {@code private}, {@code final}, {@code static}, + * {@code abstract} and {@code interface}; they should be decoded + * using the methods of class {@code Modifier}. + * + *

If the underlying class is an array class, then its + * {@code public}, {@code private} and {@code protected} + * modifiers are the same as those of its component type. If this + * {@code Class} represents a primitive type or void, its + * {@code public} modifier is always {@code true}, and its + * {@code protected} and {@code private} modifiers are always + * {@code false}. If this object represents an array class, a + * primitive type or void, then its {@code final} modifier is always + * {@code true} and its interface modifier is always + * {@code false}. The values of its other modifiers are not determined + * by this specification. + * + *

The modifier encodings are defined in The Java Virtual Machine + * Specification, table 4.1. + * + * @return the {@code int} representing the modifiers for this class + * @see java.lang.reflect.Modifier + * @since JDK1.1 + */ + public native int getModifiers(); + + + /** + * Returns the simple name of the underlying class as given in the + * source code. Returns an empty string if the underlying class is + * anonymous. + * + *

The simple name of an array is the simple name of the + * component type with "[]" appended. In particular the simple + * name of an array whose component type is anonymous is "[]". + * + * @return the simple name of the underlying class + * @since 1.5 + */ + public String getSimpleName() { + if (isArray()) + return getComponentType().getSimpleName()+"[]"; + + String simpleName = getSimpleBinaryName(); + if (simpleName == null) { // top level class + simpleName = getName(); + return simpleName.substring(simpleName.lastIndexOf(".")+1); // strip the package name + } + // According to JLS3 "Binary Compatibility" (13.1) the binary + // name of non-package classes (not top level) is the binary + // name of the immediately enclosing class followed by a '$' followed by: + // (for nested and inner classes): the simple name. + // (for local classes): 1 or more digits followed by the simple name. + // (for anonymous classes): 1 or more digits. + + // Since getSimpleBinaryName() will strip the binary name of + // the immediatly enclosing class, we are now looking at a + // string that matches the regular expression "\$[0-9]*" + // followed by a simple name (considering the simple of an + // anonymous class to be the empty string). + + // Remove leading "\$[0-9]*" from the name + int length = simpleName.length(); + if (length < 1 || simpleName.charAt(0) != '$') + throw new IllegalStateException("Malformed class name"); + int index = 1; + while (index < length && isAsciiDigit(simpleName.charAt(index))) + index++; + // Eventually, this is the empty string iff this is an anonymous class + return simpleName.substring(index); + } + + /** + * Returns the "simple binary name" of the underlying class, i.e., + * the binary name without the leading enclosing class name. + * Returns {@code null} if the underlying class is a top level + * class. + */ + private String getSimpleBinaryName() { + Class enclosingClass = null; // XXX getEnclosingClass(); + if (enclosingClass == null) // top level class + return null; + // Otherwise, strip the enclosing class' name + try { + return getName().substring(enclosingClass.getName().length()); + } catch (IndexOutOfBoundsException ex) { + throw new IllegalStateException("Malformed class name"); + } + } + + /** + * Returns an array containing {@code Field} objects reflecting all + * the accessible public fields of the class or interface represented by + * this {@code Class} object. The elements in the array returned are + * not sorted and are not in any particular order. This method returns an + * array of length 0 if the class or interface has no accessible public + * fields, or if it represents an array class, a primitive type, or void. + * + *

Specifically, if this {@code Class} object represents a class, + * this method returns the public fields of this class and of all its + * superclasses. If this {@code Class} object represents an + * interface, this method returns the fields of this interface and of all + * its superinterfaces. + * + *

The implicit length field for array class is not reflected by this + * method. User code should use the methods of class {@code Array} to + * manipulate arrays. + * + *

See The Java Language Specification, sections 8.2 and 8.3. + * + * @return the array of {@code Field} objects representing the + * public fields + * @exception SecurityException + * If a security manager, s, is present and any of the + * following conditions is met: + * + *

    + * + *
  • invocation of + * {@link SecurityManager#checkMemberAccess + * s.checkMemberAccess(this, Member.PUBLIC)} denies + * access to the fields within this class + * + *
  • the caller's class loader is not the same as or an + * ancestor of the class loader for the current class and + * invocation of {@link SecurityManager#checkPackageAccess + * s.checkPackageAccess()} denies access to the package + * of this class + * + *
+ * + * @since JDK1.1 + */ + public Field[] getFields() throws SecurityException { + throw new SecurityException(); + } + + /** + * Returns an array containing {@code Method} objects reflecting all + * the public member methods of the class or interface represented + * by this {@code Class} object, including those declared by the class + * or interface and those inherited from superclasses and + * superinterfaces. Array classes return all the (public) member methods + * inherited from the {@code Object} class. The elements in the array + * returned are not sorted and are not in any particular order. This + * method returns an array of length 0 if this {@code Class} object + * represents a class or interface that has no public member methods, or if + * this {@code Class} object represents a primitive type or void. + * + *

The class initialization method {@code } is not + * included in the returned array. If the class declares multiple public + * member methods with the same parameter types, they are all included in + * the returned array. + * + *

See The Java Language Specification, sections 8.2 and 8.4. + * + * @return the array of {@code Method} objects representing the + * public methods of this class + * @exception SecurityException + * If a security manager, s, is present and any of the + * following conditions is met: + * + *

    + * + *
  • invocation of + * {@link SecurityManager#checkMemberAccess + * s.checkMemberAccess(this, Member.PUBLIC)} denies + * access to the methods within this class + * + *
  • the caller's class loader is not the same as or an + * ancestor of the class loader for the current class and + * invocation of {@link SecurityManager#checkPackageAccess + * s.checkPackageAccess()} denies access to the package + * of this class + * + *
+ * + * @since JDK1.1 + */ + public Method[] getMethods() throws SecurityException { + return MethodImpl.findMethods(this, 0x01); + } + + /** + * Returns a {@code Field} object that reflects the specified public + * member field of the class or interface represented by this + * {@code Class} object. The {@code name} parameter is a + * {@code String} specifying the simple name of the desired field. + * + *

The field to be reflected is determined by the algorithm that + * follows. Let C be the class represented by this object: + *

    + *
  1. If C declares a public field with the name specified, that is the + * field to be reflected.
  2. + *
  3. If no field was found in step 1 above, this algorithm is applied + * recursively to each direct superinterface of C. The direct + * superinterfaces are searched in the order they were declared.
  4. + *
  5. If no field was found in steps 1 and 2 above, and C has a + * superclass S, then this algorithm is invoked recursively upon S. + * If C has no superclass, then a {@code NoSuchFieldException} + * is thrown.
  6. + *
+ * + *

See The Java Language Specification, sections 8.2 and 8.3. + * + * @param name the field name + * @return the {@code Field} object of this class specified by + * {@code name} + * @exception NoSuchFieldException if a field with the specified name is + * not found. + * @exception NullPointerException if {@code name} is {@code null} + * @exception SecurityException + * If a security manager, s, is present and any of the + * following conditions is met: + * + *

    + * + *
  • invocation of + * {@link SecurityManager#checkMemberAccess + * s.checkMemberAccess(this, Member.PUBLIC)} denies + * access to the field + * + *
  • the caller's class loader is not the same as or an + * ancestor of the class loader for the current class and + * invocation of {@link SecurityManager#checkPackageAccess + * s.checkPackageAccess()} denies access to the package + * of this class + * + *
+ * + * @since JDK1.1 + */ + public Field getField(String name) + throws SecurityException { + throw new SecurityException(); + } + + + /** + * Returns a {@code Method} object that reflects the specified public + * member method of the class or interface represented by this + * {@code Class} object. The {@code name} parameter is a + * {@code String} specifying the simple name of the desired method. The + * {@code parameterTypes} parameter is an array of {@code Class} + * objects that identify the method's formal parameter types, in declared + * order. If {@code parameterTypes} is {@code null}, it is + * treated as if it were an empty array. + * + *

If the {@code name} is "{@code };"or "{@code }" a + * {@code NoSuchMethodException} is raised. Otherwise, the method to + * be reflected is determined by the algorithm that follows. Let C be the + * class represented by this object: + *

    + *
  1. C is searched for any matching methods. If no matching + * method is found, the algorithm of step 1 is invoked recursively on + * the superclass of C.
  2. + *
  3. If no method was found in step 1 above, the superinterfaces of C + * are searched for a matching method. If any such method is found, it + * is reflected.
  4. + *
+ * + * To find a matching method in a class C:  If C declares exactly one + * public method with the specified name and exactly the same formal + * parameter types, that is the method reflected. If more than one such + * method is found in C, and one of these methods has a return type that is + * more specific than any of the others, that method is reflected; + * otherwise one of the methods is chosen arbitrarily. + * + *

Note that there may be more than one matching method in a + * class because while the Java language forbids a class to + * declare multiple methods with the same signature but different + * return types, the Java virtual machine does not. This + * increased flexibility in the virtual machine can be used to + * implement various language features. For example, covariant + * returns can be implemented with {@linkplain + * java.lang.reflect.Method#isBridge bridge methods}; the bridge + * method and the method being overridden would have the same + * signature but different return types. + * + *

See The Java Language Specification, sections 8.2 and 8.4. + * + * @param name the name of the method + * @param parameterTypes the list of parameters + * @return the {@code Method} object that matches the specified + * {@code name} and {@code parameterTypes} + * @exception NoSuchMethodException if a matching method is not found + * or if the name is "<init>"or "<clinit>". + * @exception NullPointerException if {@code name} is {@code null} + * @exception SecurityException + * If a security manager, s, is present and any of the + * following conditions is met: + * + *

    + * + *
  • invocation of + * {@link SecurityManager#checkMemberAccess + * s.checkMemberAccess(this, Member.PUBLIC)} denies + * access to the method + * + *
  • the caller's class loader is not the same as or an + * ancestor of the class loader for the current class and + * invocation of {@link SecurityManager#checkPackageAccess + * s.checkPackageAccess()} denies access to the package + * of this class + * + *
+ * + * @since JDK1.1 + */ + public Method getMethod(String name, Class... parameterTypes) + throws SecurityException, NoSuchMethodException { + Method m = MethodImpl.findMethod(this, name, parameterTypes); + if (m == null) { + StringBuilder sb = new StringBuilder(); + sb.append(getName()).append('.').append(name).append('('); + String sep = ""; + for (int i = 0; i < parameterTypes.length; i++) { + sb.append(sep).append(parameterTypes[i].getName()); + sep = ", "; + } + sb.append(')'); + throw new NoSuchMethodException(sb.toString()); + } + return m; + } + + /** + * Character.isDigit answers {@code true} to some non-ascii + * digits. This one does not. + */ + private static boolean isAsciiDigit(char c) { + return '0' <= c && c <= '9'; + } + + /** + * Returns the canonical name of the underlying class as + * defined by the Java Language Specification. Returns null if + * the underlying class does not have a canonical name (i.e., if + * it is a local or anonymous class or an array whose component + * type does not have a canonical name). + * @return the canonical name of the underlying class if it exists, and + * {@code null} otherwise. + * @since 1.5 + */ + public String getCanonicalName() { + if (isArray()) { + String canonicalName = getComponentType().getCanonicalName(); + if (canonicalName != null) + return canonicalName + "[]"; + else + return null; + } +// if (isLocalOrAnonymousClass()) +// return null; +// Class enclosingClass = getEnclosingClass(); + Class enclosingClass = null; + if (enclosingClass == null) { // top level class + return getName(); + } else { + String enclosingName = enclosingClass.getCanonicalName(); + if (enclosingName == null) + return null; + return enclosingName + "." + getSimpleName(); + } + } + + /** + * Finds a resource with a given name. The rules for searching resources + * associated with a given class are implemented by the defining + * {@linkplain ClassLoader class loader} of the class. This method + * delegates to this object's class loader. If this object was loaded by + * the bootstrap class loader, the method delegates to {@link + * ClassLoader#getSystemResourceAsStream}. + * + *

Before delegation, an absolute resource name is constructed from the + * given resource name using this algorithm: + * + *

    + * + *
  • If the {@code name} begins with a {@code '/'} + * ('\u002f'), then the absolute name of the resource is the + * portion of the {@code name} following the {@code '/'}. + * + *
  • Otherwise, the absolute name is of the following form: + * + *
    + * {@code modified_package_name/name} + *
    + * + *

    Where the {@code modified_package_name} is the package name of this + * object with {@code '/'} substituted for {@code '.'} + * ('\u002e'). + * + *

+ * + * @param name name of the desired resource + * @return A {@link java.io.InputStream} object or {@code null} if + * no resource with this name is found + * @throws NullPointerException If {@code name} is {@code null} + * @since JDK1.1 + */ + public InputStream getResourceAsStream(String name) { + name = resolveName(name); + byte[] arr = getResourceAsStream0(name); + return arr == null ? null : new ByteArrayInputStream(arr); + } + + @JavaScriptBody(args = "name", body = + "return (vm.loadBytes) ? vm.loadBytes(name) : null;" + ) + private static native byte[] getResourceAsStream0(String name); + + /** + * Finds a resource with a given name. The rules for searching resources + * associated with a given class are implemented by the defining + * {@linkplain ClassLoader class loader} of the class. This method + * delegates to this object's class loader. If this object was loaded by + * the bootstrap class loader, the method delegates to {@link + * ClassLoader#getSystemResource}. + * + *

Before delegation, an absolute resource name is constructed from the + * given resource name using this algorithm: + * + *

    + * + *
  • If the {@code name} begins with a {@code '/'} + * ('\u002f'), then the absolute name of the resource is the + * portion of the {@code name} following the {@code '/'}. + * + *
  • Otherwise, the absolute name is of the following form: + * + *
    + * {@code modified_package_name/name} + *
    + * + *

    Where the {@code modified_package_name} is the package name of this + * object with {@code '/'} substituted for {@code '.'} + * ('\u002e'). + * + *

+ * + * @param name name of the desired resource + * @return A {@link java.net.URL} object or {@code null} if no + * resource with this name is found + * @since JDK1.1 + */ + public java.net.URL getResource(String name) { + name = resolveName(name); + ClassLoader cl = null; + if (cl==null) { + // A system class. + return ClassLoader.getSystemResource(name); + } + return cl.getResource(name); + } + + + /** + * Add a package name prefix if the name is not absolute Remove leading "/" + * if name is absolute + */ + private String resolveName(String name) { + if (name == null) { + return name; + } + if (!name.startsWith("/")) { + Class c = this; + while (c.isArray()) { + c = c.getComponentType(); + } + String baseName = c.getName(); + int index = baseName.lastIndexOf('.'); + if (index != -1) { + name = baseName.substring(0, index).replace('.', '/') + +"/"+name; + } + } else { + name = name.substring(1); + } + return name; + } + + /** + * Returns the class loader for the class. Some implementations may use + * null to represent the bootstrap class loader. This method will return + * null in such implementations if this class was loaded by the bootstrap + * class loader. + * + *

If a security manager is present, and the caller's class loader is + * not null and the caller's class loader is not the same as or an ancestor of + * the class loader for the class whose class loader is requested, then + * this method calls the security manager's {@code checkPermission} + * method with a {@code RuntimePermission("getClassLoader")} + * permission to ensure it's ok to access the class loader for the class. + * + *

If this object + * represents a primitive type or void, null is returned. + * + * @return the class loader that loaded the class or interface + * represented by this object. + * @throws SecurityException + * if a security manager exists and its + * {@code checkPermission} method denies + * access to the class loader for the class. + * @see java.lang.ClassLoader + * @see SecurityManager#checkPermission + * @see java.lang.RuntimePermission + */ + public ClassLoader getClassLoader() { + throw new SecurityException(); + } + + /** + * Returns the {@code Class} representing the component type of an + * array. If this class does not represent an array class this method + * returns null. + * + * @return the {@code Class} representing the component type of this + * class if this class is an array + * @see java.lang.reflect.Array + * @since JDK1.1 + */ + public Class getComponentType() { + if (isArray()) { + try { + return getComponentType0(); + } catch (ClassNotFoundException cnfe) { + throw new IllegalStateException(cnfe); + } + } + return null; + } + + private Class getComponentType0() throws ClassNotFoundException { + String n = getName().substring(1); + switch (n.charAt(0)) { + case 'L': + n = n.substring(1, n.length() - 1); + return Class.forName(n); + case 'I': + return Integer.TYPE; + case 'J': + return Long.TYPE; + case 'D': + return Double.TYPE; + case 'F': + return Float.TYPE; + case 'B': + return Byte.TYPE; + case 'Z': + return Boolean.TYPE; + case 'S': + return Short.TYPE; + case 'V': + return Void.TYPE; + case 'C': + return Character.TYPE; + case '[': + return defineArray(n); + default: + throw new ClassNotFoundException("Unknown component type of " + getName()); + } + } + + @JavaScriptBody(args = { "sig" }, body = + "var c = Array[sig];\n" + + "if (c) return c;\n" + + "c = vm.java_lang_Class(true);\n" + + "c.jvmName = sig;\n" + + "c.superclass = vm.java_lang_Object(false).$class;\n" + + "c.array = true;\n" + + "Array[sig] = c;\n" + + "return c;" + ) + private static native Class defineArray(String sig); + + /** + * Returns true if and only if this class was declared as an enum in the + * source code. + * + * @return true if and only if this class was declared as an enum in the + * source code + * @since 1.5 + */ + public boolean isEnum() { + // An enum must both directly extend java.lang.Enum and have + // the ENUM bit set; classes for specialized enum constants + // don't do the former. + return (this.getModifiers() & ENUM) != 0 && + this.getSuperclass() == java.lang.Enum.class; + } + + /** + * Casts an object to the class or interface represented + * by this {@code Class} object. + * + * @param obj the object to be cast + * @return the object after casting, or null if obj is null + * + * @throws ClassCastException if the object is not + * null and is not assignable to the type T. + * + * @since 1.5 + */ + public T cast(Object obj) { + if (obj != null && !isInstance(obj)) + throw new ClassCastException(cannotCastMsg(obj)); + return (T) obj; + } + + private String cannotCastMsg(Object obj) { + return "Cannot cast " + obj.getClass().getName() + " to " + getName(); + } + + /** + * Casts this {@code Class} object to represent a subclass of the class + * represented by the specified class object. Checks that that the cast + * is valid, and throws a {@code ClassCastException} if it is not. If + * this method succeeds, it always returns a reference to this class object. + * + *

This method is useful when a client needs to "narrow" the type of + * a {@code Class} object to pass it to an API that restricts the + * {@code Class} objects that it is willing to accept. A cast would + * generate a compile-time warning, as the correctness of the cast + * could not be checked at runtime (because generic types are implemented + * by erasure). + * + * @return this {@code Class} object, cast to represent a subclass of + * the specified class object. + * @throws ClassCastException if this {@code Class} object does not + * represent a subclass of the specified class (here "subclass" includes + * the class itself). + * @since 1.5 + */ + public Class asSubclass(Class clazz) { + if (clazz.isAssignableFrom(this)) + return (Class) this; + else + throw new ClassCastException(this.toString()); + } + + @JavaScriptBody(args = { "ac" }, + body = + "if (this.anno) {" + + " return this.anno['L' + ac.jvmName + ';'];" + + "} else return null;" + ) + private Object getAnnotationData(Class annotationClass) { + throw new UnsupportedOperationException(); + } + /** + * @throws NullPointerException {@inheritDoc} + * @since 1.5 + */ + public A getAnnotation(Class annotationClass) { + Object data = getAnnotationData(annotationClass); + return data == null ? null : AnnotationImpl.create(annotationClass, data); + } + + /** + * @throws NullPointerException {@inheritDoc} + * @since 1.5 + */ + @JavaScriptBody(args = { "ac" }, + body = "if (this.anno && this.anno['L' + ac.jvmName + ';']) { return true; }" + + "else return false;" + ) + public boolean isAnnotationPresent( + Class annotationClass) { + if (annotationClass == null) + throw new NullPointerException(); + + return getAnnotation(annotationClass) != null; + } + + @JavaScriptBody(args = {}, body = "return this.anno;") + private Object getAnnotationData() { + throw new UnsupportedOperationException(); + } + + /** + * @since 1.5 + */ + public Annotation[] getAnnotations() { + Object data = getAnnotationData(); + return data == null ? new Annotation[0] : AnnotationImpl.create(data); + } + + /** + * @since 1.5 + */ + public Annotation[] getDeclaredAnnotations() { + throw new UnsupportedOperationException(); + } + + @JavaScriptBody(args = "type", body = "" + + "var c = vm.java_lang_Class(true);" + + "c.jvmName = type;" + + "c.primitive = true;" + + "return c;" + ) + native static Class getPrimitiveClass(String type); + + @JavaScriptBody(args = {}, body = + "return vm.desiredAssertionStatus ? vm.desiredAssertionStatus : false;" + ) + public native boolean desiredAssertionStatus(); +} diff -r 388e48c0a37a -r 05224402145d emul/mini/src/main/java/java/lang/ClassCastException.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/emul/mini/src/main/java/java/lang/ClassCastException.java Wed Jan 23 20:39:23 2013 +0100 @@ -0,0 +1,60 @@ +/* + * Copyright (c) 1994, 2008, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code 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 + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package java.lang; + +/** + * Thrown to indicate that the code has attempted to cast an object + * to a subclass of which it is not an instance. For example, the + * following code generates a ClassCastException: + *

+ *     Object x = new Integer(0);
+ *     System.out.println((String)x);
+ * 
+ * + * @author unascribed + * @since JDK1.0 + */ +public +class ClassCastException extends RuntimeException { + private static final long serialVersionUID = -9223365651070458532L; + + /** + * Constructs a ClassCastException with no detail message. + */ + public ClassCastException() { + super(); + } + + /** + * Constructs a ClassCastException with the specified + * detail message. + * + * @param s the detail message. + */ + public ClassCastException(String s) { + super(s); + } +} diff -r 388e48c0a37a -r 05224402145d emul/mini/src/main/java/java/lang/ClassFormatError.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/emul/mini/src/main/java/java/lang/ClassFormatError.java Wed Jan 23 20:39:23 2013 +0100 @@ -0,0 +1,56 @@ +/* + * Copyright (c) 1994, 2008, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code 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 + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package java.lang; + +/** + * Thrown when the Java Virtual Machine attempts to read a class + * file and determines that the file is malformed or otherwise cannot + * be interpreted as a class file. + * + * @author unascribed + * @since JDK1.0 + */ +public +class ClassFormatError extends LinkageError { + private static final long serialVersionUID = -8420114879011949195L; + + /** + * Constructs a ClassFormatError with no detail message. + */ + public ClassFormatError() { + super(); + } + + /** + * Constructs a ClassFormatError with the specified + * detail message. + * + * @param s the detail message. + */ + public ClassFormatError(String s) { + super(s); + } +} diff -r 388e48c0a37a -r 05224402145d emul/mini/src/main/java/java/lang/ClassLoader.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/emul/mini/src/main/java/java/lang/ClassLoader.java Wed Jan 23 20:39:23 2013 +0100 @@ -0,0 +1,914 @@ +/* + * Copyright (c) 1994, 2011, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code 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 + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +package java.lang; + +import java.io.InputStream; +import java.io.IOException; +import java.net.URL; +import java.util.Enumeration; +import java.util.NoSuchElementException; +import org.apidesign.bck2brwsr.core.JavaScriptBody; + +/** + * A class loader is an object that is responsible for loading classes. The + * class ClassLoader is an abstract class. Given the binary name of a class, a class loader should attempt to + * locate or generate data that constitutes a definition for the class. A + * typical strategy is to transform the name into a file name and then read a + * "class file" of that name from a file system. + * + *

Every {@link Class Class} object contains a {@link + * Class#getClassLoader() reference} to the ClassLoader that defined + * it. + * + *

Class objects for array classes are not created by class + * loaders, but are created automatically as required by the Java runtime. + * The class loader for an array class, as returned by {@link + * Class#getClassLoader()} is the same as the class loader for its element + * type; if the element type is a primitive type, then the array class has no + * class loader. + * + *

Applications implement subclasses of ClassLoader in order to + * extend the manner in which the Java virtual machine dynamically loads + * classes. + * + *

Class loaders may typically be used by security managers to indicate + * security domains. + * + *

The ClassLoader class uses a delegation model to search for + * classes and resources. Each instance of ClassLoader has an + * associated parent class loader. When requested to find a class or + * resource, a ClassLoader instance will delegate the search for the + * class or resource to its parent class loader before attempting to find the + * class or resource itself. The virtual machine's built-in class loader, + * called the "bootstrap class loader", does not itself have a parent but may + * serve as the parent of a ClassLoader instance. + * + *

Class loaders that support concurrent loading of classes are known as + * parallel capable class loaders and are required to register + * themselves at their class initialization time by invoking the + * {@link + * #registerAsParallelCapable ClassLoader.registerAsParallelCapable} + * method. Note that the ClassLoader class is registered as parallel + * capable by default. However, its subclasses still need to register themselves + * if they are parallel capable.
+ * In environments in which the delegation model is not strictly + * hierarchical, class loaders need to be parallel capable, otherwise class + * loading can lead to deadlocks because the loader lock is held for the + * duration of the class loading process (see {@link #loadClass + * loadClass} methods). + * + *

Normally, the Java virtual machine loads classes from the local file + * system in a platform-dependent manner. For example, on UNIX systems, the + * virtual machine loads classes from the directory defined by the + * CLASSPATH environment variable. + * + *

However, some classes may not originate from a file; they may originate + * from other sources, such as the network, or they could be constructed by an + * application. The method {@link #defineClass(String, byte[], int, int) + * defineClass} converts an array of bytes into an instance of class + * Class. Instances of this newly defined class can be created using + * {@link Class#newInstance Class.newInstance}. + * + *

The methods and constructors of objects created by a class loader may + * reference other classes. To determine the class(es) referred to, the Java + * virtual machine invokes the {@link #loadClass loadClass} method of + * the class loader that originally created the class. + * + *

For example, an application could create a network class loader to + * download class files from a server. Sample code might look like: + * + *

+ *   ClassLoader loader = new NetworkClassLoader(host, port);
+ *   Object main = loader.loadClass("Main", true).newInstance();
+ *        . . .
+ * 
+ * + *

The network class loader subclass must define the methods {@link + * #findClass findClass} and loadClassData to load a class + * from the network. Once it has downloaded the bytes that make up the class, + * it should use the method {@link #defineClass defineClass} to + * create a class instance. A sample implementation is: + * + *

+ *     class NetworkClassLoader extends ClassLoader {
+ *         String host;
+ *         int port;
+ *
+ *         public Class findClass(String name) {
+ *             byte[] b = loadClassData(name);
+ *             return defineClass(name, b, 0, b.length);
+ *         }
+ *
+ *         private byte[] loadClassData(String name) {
+ *             // load the class data from the connection
+ *              . . .
+ *         }
+ *     }
+ * 
+ * + *

Binary names

+ * + *

Any class name provided as a {@link String} parameter to methods in + * ClassLoader must be a binary name as defined by + * The Java™ Language Specification. + * + *

Examples of valid class names include: + *

+ *   "java.lang.String"
+ *   "javax.swing.JSpinner$DefaultEditor"
+ *   "java.security.KeyStore$Builder$FileBuilder$1"
+ *   "java.net.URLClassLoader$3$1"
+ * 
+ * + * @see #resolveClass(Class) + * @since 1.0 + */ +public abstract class ClassLoader { + + @JavaScriptBody(args = {}, body = "") + private static native void registerNatives(); + static { + registerNatives(); + } + + // The parent class loader for delegation + // Note: VM hardcoded the offset of this field, thus all new fields + // must be added *after* it. + private final ClassLoader parent; + + + /** + * Creates a new class loader using the specified parent class loader for + * delegation. + * + *

If there is a security manager, its {@link + * SecurityManager#checkCreateClassLoader() + * checkCreateClassLoader} method is invoked. This may result in + * a security exception.

+ * + * @param parent + * The parent class loader + * + * @throws SecurityException + * If a security manager exists and its + * checkCreateClassLoader method doesn't allow creation + * of a new class loader. + * + * @since 1.2 + */ + protected ClassLoader(ClassLoader parent) { + throw new SecurityException(); + } + + /** + * Creates a new class loader using the ClassLoader returned by + * the method {@link #getSystemClassLoader() + * getSystemClassLoader()} as the parent class loader. + * + *

If there is a security manager, its {@link + * SecurityManager#checkCreateClassLoader() + * checkCreateClassLoader} method is invoked. This may result in + * a security exception.

+ * + * @throws SecurityException + * If a security manager exists and its + * checkCreateClassLoader method doesn't allow creation + * of a new class loader. + */ + protected ClassLoader() { + throw new SecurityException(); + } + + // -- Class -- + + /** + * Loads the class with the specified binary name. + * This method searches for classes in the same manner as the {@link + * #loadClass(String, boolean)} method. It is invoked by the Java virtual + * machine to resolve class references. Invoking this method is equivalent + * to invoking {@link #loadClass(String, boolean) loadClass(name, + * false)}.

+ * + * @param name + * The binary name of the class + * + * @return The resulting Class object + * + * @throws ClassNotFoundException + * If the class was not found + */ + public Class loadClass(String name) throws ClassNotFoundException { + return loadClass(name, false); + } + + /** + * Loads the class with the specified binary name. The + * default implementation of this method searches for classes in the + * following order: + * + *

    + * + *
  1. Invoke {@link #findLoadedClass(String)} to check if the class + * has already been loaded.

  2. + * + *
  3. Invoke the {@link #loadClass(String) loadClass} method + * on the parent class loader. If the parent is null the class + * loader built-in to the virtual machine is used, instead.

  4. + * + *
  5. Invoke the {@link #findClass(String)} method to find the + * class.

  6. + * + *
+ * + *

If the class was found using the above steps, and the + * resolve flag is true, this method will then invoke the {@link + * #resolveClass(Class)} method on the resulting Class object. + * + *

Subclasses of ClassLoader are encouraged to override {@link + * #findClass(String)}, rather than this method.

+ * + *

Unless overridden, this method synchronizes on the result of + * {@link #getClassLoadingLock getClassLoadingLock} method + * during the entire class loading process. + * + * @param name + * The binary name of the class + * + * @param resolve + * If true then resolve the class + * + * @return The resulting Class object + * + * @throws ClassNotFoundException + * If the class could not be found + */ + protected Class loadClass(String name, boolean resolve) + throws ClassNotFoundException + { + synchronized (getClassLoadingLock(name)) { + // First, check if the class has already been loaded + Class c = findLoadedClass(name); + if (c == null) { + try { + if (parent != null) { + c = parent.loadClass(name, false); + } else { + c = findBootstrapClassOrNull(name); + } + } catch (ClassNotFoundException e) { + // ClassNotFoundException thrown if class not found + // from the non-null parent class loader + } + + if (c == null) { + // If still not found, then invoke findClass in order + // to find the class. + c = findClass(name); + +// // this is the defining class loader; record the stats +// sun.misc.PerfCounter.getParentDelegationTime().addTime(t1 - t0); +// sun.misc.PerfCounter.getFindClassTime().addElapsedTimeFrom(t1); +// sun.misc.PerfCounter.getFindClasses().increment(); + } + } + if (resolve) { + resolveClass(c); + } + return c; + } + } + + /** + * Returns the lock object for class loading operations. + * For backward compatibility, the default implementation of this method + * behaves as follows. If this ClassLoader object is registered as + * parallel capable, the method returns a dedicated object associated + * with the specified class name. Otherwise, the method returns this + * ClassLoader object.

+ * + * @param className + * The name of the to-be-loaded class + * + * @return the lock for class loading operations + * + * @throws NullPointerException + * If registered as parallel capable and className is null + * + * @see #loadClass(String, boolean) + * + * @since 1.7 + */ + protected Object getClassLoadingLock(String className) { + Object lock = this; + return lock; + } + + /** + * Finds the class with the specified binary name. + * This method should be overridden by class loader implementations that + * follow the delegation model for loading classes, and will be invoked by + * the {@link #loadClass loadClass} method after checking the + * parent class loader for the requested class. The default implementation + * throws a ClassNotFoundException.

+ * + * @param name + * The binary name of the class + * + * @return The resulting Class object + * + * @throws ClassNotFoundException + * If the class could not be found + * + * @since 1.2 + */ + protected Class findClass(String name) throws ClassNotFoundException { + throw new ClassNotFoundException(name); + } + + /** + * Converts an array of bytes into an instance of class Class. + * Before the Class can be used it must be resolved. This method + * is deprecated in favor of the version that takes a binary name as its first argument, and is more secure. + * + * @param b + * The bytes that make up the class data. The bytes in positions + * off through off+len-1 should have the format + * of a valid class file as defined by + * The Java™ Virtual Machine Specification. + * + * @param off + * The start offset in b of the class data + * + * @param len + * The length of the class data + * + * @return The Class object that was created from the specified + * class data + * + * @throws ClassFormatError + * If the data did not contain a valid class + * + * @throws IndexOutOfBoundsException + * If either off or len is negative, or if + * off+len is greater than b.length. + * + * @throws SecurityException + * If an attempt is made to add this class to a package that + * contains classes that were signed by a different set of + * certificates than this class, or if an attempt is made + * to define a class in a package with a fully-qualified name + * that starts with "{@code java.}". + * + * @see #loadClass(String, boolean) + * @see #resolveClass(Class) + * + * @deprecated Replaced by {@link #defineClass(String, byte[], int, int) + * defineClass(String, byte[], int, int)} + */ + @Deprecated + protected final Class defineClass(byte[] b, int off, int len) + throws ClassFormatError + { + throw new SecurityException(); + } + + /** + * Converts an array of bytes into an instance of class Class. + * Before the Class can be used it must be resolved. + * + *

This method assigns a default {@link java.security.ProtectionDomain + * ProtectionDomain} to the newly defined class. The + * ProtectionDomain is effectively granted the same set of + * permissions returned when {@link + * java.security.Policy#getPermissions(java.security.CodeSource) + * Policy.getPolicy().getPermissions(new CodeSource(null, null))} + * is invoked. The default domain is created on the first invocation of + * {@link #defineClass(String, byte[], int, int) defineClass}, + * and re-used on subsequent invocations. + * + *

To assign a specific ProtectionDomain to the class, use + * the {@link #defineClass(String, byte[], int, int, + * java.security.ProtectionDomain) defineClass} method that takes a + * ProtectionDomain as one of its arguments.

+ * + * @param name + * The expected binary name of the class, or + * null if not known + * + * @param b + * The bytes that make up the class data. The bytes in positions + * off through off+len-1 should have the format + * of a valid class file as defined by + * The Java™ Virtual Machine Specification. + * + * @param off + * The start offset in b of the class data + * + * @param len + * The length of the class data + * + * @return The Class object that was created from the specified + * class data. + * + * @throws ClassFormatError + * If the data did not contain a valid class + * + * @throws IndexOutOfBoundsException + * If either off or len is negative, or if + * off+len is greater than b.length. + * + * @throws SecurityException + * If an attempt is made to add this class to a package that + * contains classes that were signed by a different set of + * certificates than this class (which is unsigned), or if + * name begins with "java.". + * + * @see #loadClass(String, boolean) + * @see #resolveClass(Class) + * @see java.security.CodeSource + * @see java.security.SecureClassLoader + * + * @since 1.1 + */ + protected final Class defineClass(String name, byte[] b, int off, int len) + throws ClassFormatError + { + throw new SecurityException(); + } + + /** + * Links the specified class. This (misleadingly named) method may be + * used by a class loader to link a class. If the class c has + * already been linked, then this method simply returns. Otherwise, the + * class is linked as described in the "Execution" chapter of + * The Java™ Language Specification. + *

+ * + * @param c + * The class to link + * + * @throws NullPointerException + * If c is null. + * + * @see #defineClass(String, byte[], int, int) + */ + protected final void resolveClass(Class c) { + resolveClass0(c); + } + + private native void resolveClass0(Class c); + + + /** + * Returns the class with the given binary name if this + * loader has been recorded by the Java virtual machine as an initiating + * loader of a class with that binary name. Otherwise + * null is returned.

+ * + * @param name + * The binary name of the class + * + * @return The Class object, or null if the class has + * not been loaded + * + * @since 1.1 + */ + protected final Class findLoadedClass(String name) { + if (!checkName(name)) + return null; + return findLoadedClass0(name); + } + + private native final Class findLoadedClass0(String name); + + /** + * Sets the signers of a class. This should be invoked after defining a + * class.

+ * + * @param c + * The Class object + * + * @param signers + * The signers for the class + * + * @since 1.1 + */ + protected final void setSigners(Class c, Object[] signers) { + //c.setSigners(signers); + throw new UnsupportedOperationException(); + } + + + // -- Resource -- + + /** + * Finds the resource with the given name. A resource is some data + * (images, audio, text, etc) that can be accessed by class code in a way + * that is independent of the location of the code. + * + *

The name of a resource is a '/'-separated path name that + * identifies the resource. + * + *

This method will first search the parent class loader for the + * resource; if the parent is null the path of the class loader + * built-in to the virtual machine is searched. That failing, this method + * will invoke {@link #findResource(String)} to find the resource.

+ * + * @param name + * The resource name + * + * @return A URL object for reading the resource, or + * null if the resource could not be found or the invoker + * doesn't have adequate privileges to get the resource. + * + * @since 1.1 + */ + public URL getResource(String name) { + URL url; + if (parent != null) { + url = parent.getResource(name); + } else { + url = getBootstrapResource(name); + } + if (url == null) { + url = findResource(name); + } + return url; + } + + /** + * Finds all the resources with the given name. A resource is some data + * (images, audio, text, etc) that can be accessed by class code in a way + * that is independent of the location of the code. + * + *

The name of a resource is a /-separated path name that + * identifies the resource. + * + *

The search order is described in the documentation for {@link + * #getResource(String)}.

+ * + * @param name + * The resource name + * + * @return An enumeration of {@link java.net.URL URL} objects for + * the resource. If no resources could be found, the enumeration + * will be empty. Resources that the class loader doesn't have + * access to will not be in the enumeration. + * + * @throws IOException + * If I/O errors occur + * + * @see #findResources(String) + * + * @since 1.2 + */ + public Enumeration getResources(String name) throws IOException { + Enumeration[] tmp = new Enumeration[2]; + if (parent != null) { + tmp[0] = parent.getResources(name); + } else { + tmp[0] = getBootstrapResources(name); + } + tmp[1] = findResources(name); + + return new CompoundEnumeration(tmp); + } + + /** + * Finds the resource with the given name. Class loader implementations + * should override this method to specify where to find resources.

+ * + * @param name + * The resource name + * + * @return A URL object for reading the resource, or + * null if the resource could not be found + * + * @since 1.2 + */ + protected URL findResource(String name) { + return null; + } + + /** + * Returns an enumeration of {@link java.net.URL URL} objects + * representing all the resources with the given name. Class loader + * implementations should override this method to specify where to load + * resources from.

+ * + * @param name + * The resource name + * + * @return An enumeration of {@link java.net.URL URL} objects for + * the resources + * + * @throws IOException + * If I/O errors occur + * + * @since 1.2 + */ + protected Enumeration findResources(String name) throws IOException { + return new CompoundEnumeration(new Enumeration[0]); + } + + // index 0: java.lang.ClassLoader.class + // index 1: the immediate caller of index 0. + // index 2: the immediate caller of index 1. + private static native Class getCaller(int index); + + /** + * Registers the caller as parallel capable.

+ * The registration succeeds if and only if all of the following + * conditions are met:
+ * 1. no instance of the caller has been created

+ * 2. all of the super classes (except class Object) of the caller are + * registered as parallel capable

+ * Note that once a class loader is registered as parallel capable, there + * is no way to change it back.

+ * + * @return true if the caller is successfully registered as + * parallel capable and false if otherwise. + * + * @since 1.7 + */ +// protected static boolean registerAsParallelCapable() { +// return false; +// } + + /** + * Find a resource of the specified name from the search path used to load + * classes. This method locates the resource through the system class + * loader (see {@link #getSystemClassLoader()}).

+ * + * @param name + * The resource name + * + * @return A {@link java.net.URL URL} object for reading the + * resource, or null if the resource could not be found + * + * @since 1.1 + */ + public static URL getSystemResource(String name) { + ClassLoader system = getSystemClassLoader(); + if (system == null) { + return getBootstrapResource(name); + } + return system.getResource(name); + } + + /** + * Finds all resources of the specified name from the search path used to + * load classes. The resources thus found are returned as an + * {@link java.util.Enumeration Enumeration} of {@link + * java.net.URL URL} objects. + * + *

The search order is described in the documentation for {@link + * #getSystemResource(String)}.

+ * + * @param name + * The resource name + * + * @return An enumeration of resource {@link java.net.URL URL} + * objects + * + * @throws IOException + * If I/O errors occur + + * @since 1.2 + */ + public static Enumeration getSystemResources(String name) + throws IOException + { + ClassLoader system = getSystemClassLoader(); + if (system == null) { + return getBootstrapResources(name); + } + return system.getResources(name); + } + + + + /** + * Returns an input stream for reading the specified resource. + * + *

The search order is described in the documentation for {@link + * #getResource(String)}.

+ * + * @param name + * The resource name + * + * @return An input stream for reading the resource, or null + * if the resource could not be found + * + * @since 1.1 + */ + public InputStream getResourceAsStream(String name) { + URL url = getResource(name); + try { + return url != null ? url.openStream() : null; + } catch (IOException e) { + return null; + } + } + + /** + * Open for reading, a resource of the specified name from the search path + * used to load classes. This method locates the resource through the + * system class loader (see {@link #getSystemClassLoader()}).

+ * + * @param name + * The resource name + * + * @return An input stream for reading the resource, or null + * if the resource could not be found + * + * @since 1.1 + */ + public static InputStream getSystemResourceAsStream(String name) { + URL url = getSystemResource(name); + try { + return url != null ? url.openStream() : null; + } catch (IOException e) { + return null; + } + } + + + // -- Hierarchy -- + + /** + * Returns the parent class loader for delegation. Some implementations may + * use null to represent the bootstrap class loader. This method + * will return null in such implementations if this class loader's + * parent is the bootstrap class loader. + * + *

If a security manager is present, and the invoker's class loader is + * not null and is not an ancestor of this class loader, then this + * method invokes the security manager's {@link + * SecurityManager#checkPermission(java.security.Permission) + * checkPermission} method with a {@link + * RuntimePermission#RuntimePermission(String) + * RuntimePermission("getClassLoader")} permission to verify + * access to the parent class loader is permitted. If not, a + * SecurityException will be thrown.

+ * + * @return The parent ClassLoader + * + * @throws SecurityException + * If a security manager exists and its checkPermission + * method doesn't allow access to this class loader's parent class + * loader. + * + * @since 1.2 + */ + public final ClassLoader getParent() { + throw new SecurityException(); + } + + /** + * Returns the system class loader for delegation. This is the default + * delegation parent for new ClassLoader instances, and is + * typically the class loader used to start the application. + * + *

This method is first invoked early in the runtime's startup + * sequence, at which point it creates the system class loader and sets it + * as the context class loader of the invoking Thread. + * + *

The default system class loader is an implementation-dependent + * instance of this class. + * + *

If the system property "java.system.class.loader" is defined + * when this method is first invoked then the value of that property is + * taken to be the name of a class that will be returned as the system + * class loader. The class is loaded using the default system class loader + * and must define a public constructor that takes a single parameter of + * type ClassLoader which is used as the delegation parent. An + * instance is then created using this constructor with the default system + * class loader as the parameter. The resulting class loader is defined + * to be the system class loader. + * + *

If a security manager is present, and the invoker's class loader is + * not null and the invoker's class loader is not the same as or + * an ancestor of the system class loader, then this method invokes the + * security manager's {@link + * SecurityManager#checkPermission(java.security.Permission) + * checkPermission} method with a {@link + * RuntimePermission#RuntimePermission(String) + * RuntimePermission("getClassLoader")} permission to verify + * access to the system class loader. If not, a + * SecurityException will be thrown.

+ * + * @return The system ClassLoader for delegation, or + * null if none + * + * @throws SecurityException + * If a security manager exists and its checkPermission + * method doesn't allow access to the system class loader. + * + * @throws IllegalStateException + * If invoked recursively during the construction of the class + * loader specified by the "java.system.class.loader" + * property. + * + * @throws Error + * If the system property "java.system.class.loader" + * is defined but the named class could not be loaded, the + * provider class does not define the required constructor, or an + * exception is thrown by that constructor when it is invoked. The + * underlying cause of the error can be retrieved via the + * {@link Throwable#getCause()} method. + * + * @revised 1.4 + */ + public static ClassLoader getSystemClassLoader() { + throw new SecurityException(); + } + + // Returns true if the specified class loader can be found in this class + // loader's delegation chain. + boolean isAncestor(ClassLoader cl) { + ClassLoader acl = this; + do { + acl = acl.parent; + if (cl == acl) { + return true; + } + } while (acl != null); + return false; + } + + private boolean checkName(String name) { + throw new UnsupportedOperationException(); + } + + private Class findBootstrapClassOrNull(String name) { + throw new UnsupportedOperationException(); + } + + private static URL getBootstrapResource(String name) { + throw new UnsupportedOperationException(); + } + + private static Enumeration getBootstrapResources(String name) { + throw new UnsupportedOperationException(); + } + + private static class CompoundEnumeration implements Enumeration { + private URL next; + private int index; + private final Enumeration[] arr; + + public CompoundEnumeration(Enumeration[] arr) { + this.arr = arr; + this.index = 0; + } + + public boolean hasMoreElements() { + if (next == null) { + if (arr[index].hasMoreElements()) { + next = (URL) arr[index].nextElement(); + } else { + if (index < arr.length) { + index++; + return hasMoreElements(); + } + } + } + return next != null; + } + + public URL nextElement() { + if (!hasMoreElements()) { + throw new NoSuchElementException(); + } + URL r = next; + next = null; + return r; + } + + } +} diff -r 388e48c0a37a -r 05224402145d emul/mini/src/main/java/java/lang/ClassNotFoundException.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/emul/mini/src/main/java/java/lang/ClassNotFoundException.java Wed Jan 23 20:39:23 2013 +0100 @@ -0,0 +1,125 @@ +/* + * Copyright (c) 1995, 2004, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code 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 + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package java.lang; + +/** + * Thrown when an application tries to load in a class through its + * string name using: + *
    + *
  • The forName method in class Class. + *
  • The findSystemClass method in class + * ClassLoader . + *
  • The loadClass method in class ClassLoader. + *
+ *

+ * but no definition for the class with the specified name could be found. + * + *

As of release 1.4, this exception has been retrofitted to conform to + * the general purpose exception-chaining mechanism. The "optional exception + * that was raised while loading the class" that may be provided at + * construction time and accessed via the {@link #getException()} method is + * now known as the cause, and may be accessed via the {@link + * Throwable#getCause()} method, as well as the aforementioned "legacy method." + * + * @author unascribed + * @see java.lang.Class#forName(java.lang.String) + * @see java.lang.ClassLoader#findSystemClass(java.lang.String) + * @see java.lang.ClassLoader#loadClass(java.lang.String, boolean) + * @since JDK1.0 + */ +public class ClassNotFoundException extends ReflectiveOperationException { + /** + * use serialVersionUID from JDK 1.1.X for interoperability + */ + private static final long serialVersionUID = 9176873029745254542L; + + /** + * This field holds the exception ex if the + * ClassNotFoundException(String s, Throwable ex) constructor was + * used to instantiate the object + * @serial + * @since 1.2 + */ + private Throwable ex; + + /** + * Constructs a ClassNotFoundException with no detail message. + */ + public ClassNotFoundException() { + super((Throwable)null); // Disallow initCause + } + + /** + * Constructs a ClassNotFoundException with the + * specified detail message. + * + * @param s the detail message. + */ + public ClassNotFoundException(String s) { + super(s, null); // Disallow initCause + } + + /** + * Constructs a ClassNotFoundException with the + * specified detail message and optional exception that was + * raised while loading the class. + * + * @param s the detail message + * @param ex the exception that was raised while loading the class + * @since 1.2 + */ + public ClassNotFoundException(String s, Throwable ex) { + super(s, null); // Disallow initCause + this.ex = ex; + } + + /** + * Returns the exception that was raised if an error occurred while + * attempting to load the class. Otherwise, returns null. + * + *

This method predates the general-purpose exception chaining facility. + * The {@link Throwable#getCause()} method is now the preferred means of + * obtaining this information. + * + * @return the Exception that was raised while loading a class + * @since 1.2 + */ + public Throwable getException() { + return ex; + } + + /** + * Returns the cause of this exception (the exception that was raised + * if an error occurred while attempting to load the class; otherwise + * null). + * + * @return the cause of this exception. + * @since 1.4 + */ + public Throwable getCause() { + return ex; + } +} diff -r 388e48c0a37a -r 05224402145d emul/mini/src/main/java/java/lang/CloneNotSupportedException.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/emul/mini/src/main/java/java/lang/CloneNotSupportedException.java Wed Jan 23 20:39:23 2013 +0100 @@ -0,0 +1,65 @@ +/* + * Copyright (c) 1995, 2008, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code 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 + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package java.lang; + +/** + * Thrown to indicate that the clone method in class + * Object has been called to clone an object, but that + * the object's class does not implement the Cloneable + * interface. + *

+ * Applications that override the clone method can also + * throw this exception to indicate that an object could not or + * should not be cloned. + * + * @author unascribed + * @see java.lang.Cloneable + * @see java.lang.Object#clone() + * @since JDK1.0 + */ + +public +class CloneNotSupportedException extends Exception { + private static final long serialVersionUID = 5195511250079656443L; + + /** + * Constructs a CloneNotSupportedException with no + * detail message. + */ + public CloneNotSupportedException() { + super(); + } + + /** + * Constructs a CloneNotSupportedException with the + * specified detail message. + * + * @param s the detail message. + */ + public CloneNotSupportedException(String s) { + super(s); + } +} diff -r 388e48c0a37a -r 05224402145d emul/mini/src/main/java/java/lang/Comparable.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/emul/mini/src/main/java/java/lang/Comparable.java Wed Jan 23 20:39:23 2013 +0100 @@ -0,0 +1,137 @@ +/* + * Copyright (c) 1997, 2007, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code 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 + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package java.lang; + +/** + * This interface imposes a total ordering on the objects of each class that + * implements it. This ordering is referred to as the class's natural + * ordering, and the class's compareTo method is referred to as + * its natural comparison method.

+ * + * Lists (and arrays) of objects that implement this interface can be sorted + * automatically by {@link Collections#sort(List) Collections.sort} (and + * {@link Arrays#sort(Object[]) Arrays.sort}). Objects that implement this + * interface can be used as keys in a {@linkplain SortedMap sorted map} or as + * elements in a {@linkplain SortedSet sorted set}, without the need to + * specify a {@linkplain Comparator comparator}.

+ * + * The natural ordering for a class C is said to be consistent + * with equals if and only if e1.compareTo(e2) == 0 has + * the same boolean value as e1.equals(e2) for every + * e1 and e2 of class C. Note that null + * is not an instance of any class, and e.compareTo(null) should + * throw a NullPointerException even though e.equals(null) + * returns false.

+ * + * It is strongly recommended (though not required) that natural orderings be + * consistent with equals. This is so because sorted sets (and sorted maps) + * without explicit comparators behave "strangely" when they are used with + * elements (or keys) whose natural ordering is inconsistent with equals. In + * particular, such a sorted set (or sorted map) violates the general contract + * for set (or map), which is defined in terms of the equals + * method.

+ * + * For example, if one adds two keys a and b such that + * (!a.equals(b) && a.compareTo(b) == 0) to a sorted + * set that does not use an explicit comparator, the second add + * operation returns false (and the size of the sorted set does not increase) + * because a and b are equivalent from the sorted set's + * perspective.

+ * + * Virtually all Java core classes that implement Comparable have natural + * orderings that are consistent with equals. One exception is + * java.math.BigDecimal, whose natural ordering equates + * BigDecimal objects with equal values and different precisions + * (such as 4.0 and 4.00).

+ * + * For the mathematically inclined, the relation that defines + * the natural ordering on a given class C is:

+ *       {(x, y) such that x.compareTo(y) <= 0}.
+ * 
The quotient for this total order is:
+ *       {(x, y) such that x.compareTo(y) == 0}.
+ * 
+ * + * It follows immediately from the contract for compareTo that the + * quotient is an equivalence relation on C, and that the + * natural ordering is a total order on C. When we say that a + * class's natural ordering is consistent with equals, we mean that the + * quotient for the natural ordering is the equivalence relation defined by + * the class's {@link Object#equals(Object) equals(Object)} method:
+ *     {(x, y) such that x.equals(y)}. 

+ * + * This interface is a member of the + * + * Java Collections Framework. + * + * @param the type of objects that this object may be compared to + * + * @author Josh Bloch + * @see java.util.Comparator + * @since 1.2 + */ + +public interface Comparable { + /** + * Compares this object with the specified object for order. Returns a + * negative integer, zero, or a positive integer as this object is less + * than, equal to, or greater than the specified object. + * + *

The implementor must ensure sgn(x.compareTo(y)) == + * -sgn(y.compareTo(x)) for all x and y. (This + * implies that x.compareTo(y) must throw an exception iff + * y.compareTo(x) throws an exception.) + * + *

The implementor must also ensure that the relation is transitive: + * (x.compareTo(y)>0 && y.compareTo(z)>0) implies + * x.compareTo(z)>0. + * + *

Finally, the implementor must ensure that x.compareTo(y)==0 + * implies that sgn(x.compareTo(z)) == sgn(y.compareTo(z)), for + * all z. + * + *

It is strongly recommended, but not strictly required that + * (x.compareTo(y)==0) == (x.equals(y)). Generally speaking, any + * class that implements the Comparable interface and violates + * this condition should clearly indicate this fact. The recommended + * language is "Note: this class has a natural ordering that is + * inconsistent with equals." + * + *

In the foregoing description, the notation + * sgn(expression) designates the mathematical + * signum function, which is defined to return one of -1, + * 0, or 1 according to whether the value of + * expression is negative, zero or positive. + * + * @param o the object to be compared. + * @return a negative integer, zero, or a positive integer as this object + * is less than, equal to, or greater than the specified object. + * + * @throws NullPointerException if the specified object is null + * @throws ClassCastException if the specified object's type prevents it + * from being compared to this object. + */ + public int compareTo(T o); +} diff -r 388e48c0a37a -r 05224402145d emul/mini/src/main/java/java/lang/Deprecated.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/emul/mini/src/main/java/java/lang/Deprecated.java Wed Jan 23 20:39:23 2013 +0100 @@ -0,0 +1,44 @@ +/* + * Copyright (c) 2003, 2010, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code 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 + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package java.lang; + +import java.lang.annotation.*; +import static java.lang.annotation.ElementType.*; + +/** + * A program element annotated @Deprecated is one that programmers + * are discouraged from using, typically because it is dangerous, + * or because a better alternative exists. Compilers warn when a + * deprecated program element is used or overridden in non-deprecated code. + * + * @author Neal Gafter + * @since 1.5 + */ +@Documented +@Retention(RetentionPolicy.RUNTIME) +@Target(value={CONSTRUCTOR, FIELD, LOCAL_VARIABLE, METHOD, PACKAGE, PARAMETER, TYPE}) +public @interface Deprecated { +} diff -r 388e48c0a37a -r 05224402145d emul/mini/src/main/java/java/lang/Double.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/emul/mini/src/main/java/java/lang/Double.java Wed Jan 23 20:39:23 2013 +0100 @@ -0,0 +1,994 @@ +/* + * Copyright (c) 1994, 2010, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code 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 + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package java.lang; + +import org.apidesign.bck2brwsr.core.JavaScriptBody; + +/** + * The {@code Double} class wraps a value of the primitive type + * {@code double} in an object. An object of type + * {@code Double} contains a single field whose type is + * {@code double}. + * + *

In addition, this class provides several methods for converting a + * {@code double} to a {@code String} and a + * {@code String} to a {@code double}, as well as other + * constants and methods useful when dealing with a + * {@code double}. + * + * @author Lee Boynton + * @author Arthur van Hoff + * @author Joseph D. Darcy + * @since JDK1.0 + */ +public final class Double extends Number implements Comparable { + /** + * A constant holding the positive infinity of type + * {@code double}. It is equal to the value returned by + * {@code Double.longBitsToDouble(0x7ff0000000000000L)}. + */ + public static final double POSITIVE_INFINITY = 1.0 / 0.0; + + /** + * A constant holding the negative infinity of type + * {@code double}. It is equal to the value returned by + * {@code Double.longBitsToDouble(0xfff0000000000000L)}. + */ + public static final double NEGATIVE_INFINITY = -1.0 / 0.0; + + /** + * A constant holding a Not-a-Number (NaN) value of type + * {@code double}. It is equivalent to the value returned by + * {@code Double.longBitsToDouble(0x7ff8000000000000L)}. + */ + public static final double NaN = 0.0d / 0.0; + + /** + * A constant holding the largest positive finite value of type + * {@code double}, + * (2-2-52)·21023. It is equal to + * the hexadecimal floating-point literal + * {@code 0x1.fffffffffffffP+1023} and also equal to + * {@code Double.longBitsToDouble(0x7fefffffffffffffL)}. + */ + public static final double MAX_VALUE = 0x1.fffffffffffffP+1023; // 1.7976931348623157e+308 + + /** + * A constant holding the smallest positive normal value of type + * {@code double}, 2-1022. It is equal to the + * hexadecimal floating-point literal {@code 0x1.0p-1022} and also + * equal to {@code Double.longBitsToDouble(0x0010000000000000L)}. + * + * @since 1.6 + */ + public static final double MIN_NORMAL = 0x1.0p-1022; // 2.2250738585072014E-308 + + /** + * A constant holding the smallest positive nonzero value of type + * {@code double}, 2-1074. It is equal to the + * hexadecimal floating-point literal + * {@code 0x0.0000000000001P-1022} and also equal to + * {@code Double.longBitsToDouble(0x1L)}. + */ + public static final double MIN_VALUE = 0x0.0000000000001P-1022; // 4.9e-324 + + /** + * Maximum exponent a finite {@code double} variable may have. + * It is equal to the value returned by + * {@code Math.getExponent(Double.MAX_VALUE)}. + * + * @since 1.6 + */ + public static final int MAX_EXPONENT = 1023; + + /** + * Minimum exponent a normalized {@code double} variable may + * have. It is equal to the value returned by + * {@code Math.getExponent(Double.MIN_NORMAL)}. + * + * @since 1.6 + */ + public static final int MIN_EXPONENT = -1022; + + /** + * The number of bits used to represent a {@code double} value. + * + * @since 1.5 + */ + public static final int SIZE = 64; + + /** + * The {@code Class} instance representing the primitive type + * {@code double}. + * + * @since JDK1.1 + */ + public static final Class TYPE = (Class) Class.getPrimitiveClass("double"); + + /** + * Returns a string representation of the {@code double} + * argument. All characters mentioned below are ASCII characters. + *

    + *
  • If the argument is NaN, the result is the string + * "{@code NaN}". + *
  • Otherwise, the result is a string that represents the sign and + * magnitude (absolute value) of the argument. If the sign is negative, + * the first character of the result is '{@code -}' + * ('\u002D'); if the sign is positive, no sign character + * appears in the result. As for the magnitude m: + *
      + *
    • If m is infinity, it is represented by the characters + * {@code "Infinity"}; thus, positive infinity produces the result + * {@code "Infinity"} and negative infinity produces the result + * {@code "-Infinity"}. + * + *
    • If m is zero, it is represented by the characters + * {@code "0.0"}; thus, negative zero produces the result + * {@code "-0.0"} and positive zero produces the result + * {@code "0.0"}. + * + *
    • If m is greater than or equal to 10-3 but less + * than 107, then it is represented as the integer part of + * m, in decimal form with no leading zeroes, followed by + * '{@code .}' ('\u002E'), followed by one or + * more decimal digits representing the fractional part of m. + * + *
    • If m is less than 10-3 or greater than or + * equal to 107, then it is represented in so-called + * "computerized scientific notation." Let n be the unique + * integer such that 10nm {@literal <} + * 10n+1; then let a be the + * mathematically exact quotient of m and + * 10n so that 1 ≤ a {@literal <} 10. The + * magnitude is then represented as the integer part of a, + * as a single decimal digit, followed by '{@code .}' + * ('\u002E'), followed by decimal digits + * representing the fractional part of a, followed by the + * letter '{@code E}' ('\u0045'), followed + * by a representation of n as a decimal integer, as + * produced by the method {@link Integer#toString(int)}. + *
    + *
+ * How many digits must be printed for the fractional part of + * m or a? There must be at least one digit to represent + * the fractional part, and beyond that as many, but only as many, more + * digits as are needed to uniquely distinguish the argument value from + * adjacent values of type {@code double}. That is, suppose that + * x is the exact mathematical value represented by the decimal + * representation produced by this method for a finite nonzero argument + * d. Then d must be the {@code double} value nearest + * to x; or if two {@code double} values are equally close + * to x, then d must be one of them and the least + * significant bit of the significand of d must be {@code 0}. + * + *

To create localized string representations of a floating-point + * value, use subclasses of {@link java.text.NumberFormat}. + * + * @param d the {@code double} to be converted. + * @return a string representation of the argument. + */ + @JavaScriptBody(args="d", body="var r = d.toString();" + + "if (r.indexOf('.') === -1) r = r + '.0';" + + "return r;") + public static String toString(double d) { + throw new UnsupportedOperationException(); + } + + /** + * Returns a hexadecimal string representation of the + * {@code double} argument. All characters mentioned below + * are ASCII characters. + * + *

    + *
  • If the argument is NaN, the result is the string + * "{@code NaN}". + *
  • Otherwise, the result is a string that represents the sign + * and magnitude of the argument. If the sign is negative, the + * first character of the result is '{@code -}' + * ('\u002D'); if the sign is positive, no sign + * character appears in the result. As for the magnitude m: + * + *
      + *
    • If m is infinity, it is represented by the string + * {@code "Infinity"}; thus, positive infinity produces the + * result {@code "Infinity"} and negative infinity produces + * the result {@code "-Infinity"}. + * + *
    • If m is zero, it is represented by the string + * {@code "0x0.0p0"}; thus, negative zero produces the result + * {@code "-0x0.0p0"} and positive zero produces the result + * {@code "0x0.0p0"}. + * + *
    • If m is a {@code double} value with a + * normalized representation, substrings are used to represent the + * significand and exponent fields. The significand is + * represented by the characters {@code "0x1."} + * followed by a lowercase hexadecimal representation of the rest + * of the significand as a fraction. Trailing zeros in the + * hexadecimal representation are removed unless all the digits + * are zero, in which case a single zero is used. Next, the + * exponent is represented by {@code "p"} followed + * by a decimal string of the unbiased exponent as if produced by + * a call to {@link Integer#toString(int) Integer.toString} on the + * exponent value. + * + *
    • If m is a {@code double} value with a subnormal + * representation, the significand is represented by the + * characters {@code "0x0."} followed by a + * hexadecimal representation of the rest of the significand as a + * fraction. Trailing zeros in the hexadecimal representation are + * removed. Next, the exponent is represented by + * {@code "p-1022"}. Note that there must be at + * least one nonzero digit in a subnormal significand. + * + *
    + * + *
+ * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *

Examples

Floating-point ValueHexadecimal String
{@code 1.0} {@code 0x1.0p0}
{@code -1.0} {@code -0x1.0p0}
{@code 2.0} {@code 0x1.0p1}
{@code 3.0} {@code 0x1.8p1}
{@code 0.5} {@code 0x1.0p-1}
{@code 0.25} {@code 0x1.0p-2}
{@code Double.MAX_VALUE}{@code 0x1.fffffffffffffp1023}
{@code Minimum Normal Value}{@code 0x1.0p-1022}
{@code Maximum Subnormal Value}{@code 0x0.fffffffffffffp-1022}
{@code Double.MIN_VALUE}{@code 0x0.0000000000001p-1022}
+ * @param d the {@code double} to be converted. + * @return a hex string representation of the argument. + * @since 1.5 + * @author Joseph D. Darcy + */ + public static String toHexString(double d) { + throw new UnsupportedOperationException(); +// /* +// * Modeled after the "a" conversion specifier in C99, section +// * 7.19.6.1; however, the output of this method is more +// * tightly specified. +// */ +// if (!FpUtils.isFinite(d) ) +// // For infinity and NaN, use the decimal output. +// return Double.toString(d); +// else { +// // Initialized to maximum size of output. +// StringBuffer answer = new StringBuffer(24); +// +// if (FpUtils.rawCopySign(1.0, d) == -1.0) // value is negative, +// answer.append("-"); // so append sign info +// +// answer.append("0x"); +// +// d = Math.abs(d); +// +// if(d == 0.0) { +// answer.append("0.0p0"); +// } +// else { +// boolean subnormal = (d < DoubleConsts.MIN_NORMAL); +// +// // Isolate significand bits and OR in a high-order bit +// // so that the string representation has a known +// // length. +// long signifBits = (Double.doubleToLongBits(d) +// & DoubleConsts.SIGNIF_BIT_MASK) | +// 0x1000000000000000L; +// +// // Subnormal values have a 0 implicit bit; normal +// // values have a 1 implicit bit. +// answer.append(subnormal ? "0." : "1."); +// +// // Isolate the low-order 13 digits of the hex +// // representation. If all the digits are zero, +// // replace with a single 0; otherwise, remove all +// // trailing zeros. +// String signif = Long.toHexString(signifBits).substring(3,16); +// answer.append(signif.equals("0000000000000") ? // 13 zeros +// "0": +// signif.replaceFirst("0{1,12}$", "")); +// +// // If the value is subnormal, use the E_min exponent +// // value for double; otherwise, extract and report d's +// // exponent (the representation of a subnormal uses +// // E_min -1). +// answer.append("p" + (subnormal ? +// DoubleConsts.MIN_EXPONENT: +// FpUtils.getExponent(d) )); +// } +// return answer.toString(); +// } + } + + /** + * Returns a {@code Double} object holding the + * {@code double} value represented by the argument string + * {@code s}. + * + *

If {@code s} is {@code null}, then a + * {@code NullPointerException} is thrown. + * + *

Leading and trailing whitespace characters in {@code s} + * are ignored. Whitespace is removed as if by the {@link + * String#trim} method; that is, both ASCII space and control + * characters are removed. The rest of {@code s} should + * constitute a FloatValue as described by the lexical + * syntax rules: + * + *

+ *
+ *
FloatValue: + *
Signopt {@code NaN} + *
Signopt {@code Infinity} + *
Signopt FloatingPointLiteral + *
Signopt HexFloatingPointLiteral + *
SignedInteger + *
+ * + *

+ * + *

+ *
HexFloatingPointLiteral: + *
HexSignificand BinaryExponent FloatTypeSuffixopt + *
+ * + *

+ * + *

+ *
HexSignificand: + *
HexNumeral + *
HexNumeral {@code .} + *
{@code 0x} HexDigitsopt + * {@code .} HexDigits + *
{@code 0X} HexDigitsopt + * {@code .} HexDigits + *
+ * + *

+ * + *

+ *
BinaryExponent: + *
BinaryExponentIndicator SignedInteger + *
+ * + *

+ * + *

+ *
BinaryExponentIndicator: + *
{@code p} + *
{@code P} + *
+ * + *
+ * + * where Sign, FloatingPointLiteral, + * HexNumeral, HexDigits, SignedInteger and + * FloatTypeSuffix are as defined in the lexical structure + * sections of + * The Java™ Language Specification, + * except that underscores are not accepted between digits. + * If {@code s} does not have the form of + * a FloatValue, then a {@code NumberFormatException} + * is thrown. Otherwise, {@code s} is regarded as + * representing an exact decimal value in the usual + * "computerized scientific notation" or as an exact + * hexadecimal value; this exact numerical value is then + * conceptually converted to an "infinitely precise" + * binary value that is then rounded to type {@code double} + * by the usual round-to-nearest rule of IEEE 754 floating-point + * arithmetic, which includes preserving the sign of a zero + * value. + * + * Note that the round-to-nearest rule also implies overflow and + * underflow behaviour; if the exact value of {@code s} is large + * enough in magnitude (greater than or equal to ({@link + * #MAX_VALUE} + {@link Math#ulp(double) ulp(MAX_VALUE)}/2), + * rounding to {@code double} will result in an infinity and if the + * exact value of {@code s} is small enough in magnitude (less + * than or equal to {@link #MIN_VALUE}/2), rounding to float will + * result in a zero. + * + * Finally, after rounding a {@code Double} object representing + * this {@code double} value is returned. + * + *

To interpret localized string representations of a + * floating-point value, use subclasses of {@link + * java.text.NumberFormat}. + * + *

Note that trailing format specifiers, specifiers that + * determine the type of a floating-point literal + * ({@code 1.0f} is a {@code float} value; + * {@code 1.0d} is a {@code double} value), do + * not influence the results of this method. In other + * words, the numerical value of the input string is converted + * directly to the target floating-point type. The two-step + * sequence of conversions, string to {@code float} followed + * by {@code float} to {@code double}, is not + * equivalent to converting a string directly to + * {@code double}. For example, the {@code float} + * literal {@code 0.1f} is equal to the {@code double} + * value {@code 0.10000000149011612}; the {@code float} + * literal {@code 0.1f} represents a different numerical + * value than the {@code double} literal + * {@code 0.1}. (The numerical value 0.1 cannot be exactly + * represented in a binary floating-point number.) + * + *

To avoid calling this method on an invalid string and having + * a {@code NumberFormatException} be thrown, the regular + * expression below can be used to screen the input string: + * + * + *

+     *  final String Digits     = "(\\p{Digit}+)";
+     *  final String HexDigits  = "(\\p{XDigit}+)";
+     *  // an exponent is 'e' or 'E' followed by an optionally
+     *  // signed decimal integer.
+     *  final String Exp        = "[eE][+-]?"+Digits;
+     *  final String fpRegex    =
+     *      ("[\\x00-\\x20]*"+  // Optional leading "whitespace"
+     *       "[+-]?(" + // Optional sign character
+     *       "NaN|" +           // "NaN" string
+     *       "Infinity|" +      // "Infinity" string
+     *
+     *       // A decimal floating-point string representing a finite positive
+     *       // number without a leading sign has at most five basic pieces:
+     *       // Digits . Digits ExponentPart FloatTypeSuffix
+     *       //
+     *       // Since this method allows integer-only strings as input
+     *       // in addition to strings of floating-point literals, the
+     *       // two sub-patterns below are simplifications of the grammar
+     *       // productions from section 3.10.2 of
+     *       // The Java™ Language Specification.
+     *
+     *       // Digits ._opt Digits_opt ExponentPart_opt FloatTypeSuffix_opt
+     *       "((("+Digits+"(\\.)?("+Digits+"?)("+Exp+")?)|"+
+     *
+     *       // . Digits ExponentPart_opt FloatTypeSuffix_opt
+     *       "(\\.("+Digits+")("+Exp+")?)|"+
+     *
+     *       // Hexadecimal strings
+     *       "((" +
+     *        // 0[xX] HexDigits ._opt BinaryExponent FloatTypeSuffix_opt
+     *        "(0[xX]" + HexDigits + "(\\.)?)|" +
+     *
+     *        // 0[xX] HexDigits_opt . HexDigits BinaryExponent FloatTypeSuffix_opt
+     *        "(0[xX]" + HexDigits + "?(\\.)" + HexDigits + ")" +
+     *
+     *        ")[pP][+-]?" + Digits + "))" +
+     *       "[fFdD]?))" +
+     *       "[\\x00-\\x20]*");// Optional trailing "whitespace"
+     *
+     *  if (Pattern.matches(fpRegex, myString))
+     *      Double.valueOf(myString); // Will not throw NumberFormatException
+     *  else {
+     *      // Perform suitable alternative action
+     *  }
+     * 
+ * + * + * @param s the string to be parsed. + * @return a {@code Double} object holding the value + * represented by the {@code String} argument. + * @throws NumberFormatException if the string does not contain a + * parsable number. + */ + @JavaScriptBody(args="s", body="return parseFloat(s);") + public static Double valueOf(String s) throws NumberFormatException { + throw new UnsupportedOperationException(); +// return new Double(FloatingDecimal.readJavaFormatString(s).doubleValue()); + } + + /** + * Returns a {@code Double} instance representing the specified + * {@code double} value. + * If a new {@code Double} instance is not required, this method + * should generally be used in preference to the constructor + * {@link #Double(double)}, as this method is likely to yield + * significantly better space and time performance by caching + * frequently requested values. + * + * @param d a double value. + * @return a {@code Double} instance representing {@code d}. + * @since 1.5 + */ + public static Double valueOf(double d) { + return new Double(d); + } + + /** + * Returns a new {@code double} initialized to the value + * represented by the specified {@code String}, as performed + * by the {@code valueOf} method of class + * {@code Double}. + * + * @param s the string to be parsed. + * @return the {@code double} value represented by the string + * argument. + * @throws NullPointerException if the string is null + * @throws NumberFormatException if the string does not contain + * a parsable {@code double}. + * @see java.lang.Double#valueOf(String) + * @since 1.2 + */ + @JavaScriptBody(args="s", body="return parseFloat(s);") + public static double parseDouble(String s) throws NumberFormatException { + throw new UnsupportedOperationException(); +// return FloatingDecimal.readJavaFormatString(s).doubleValue(); + } + + /** + * Returns {@code true} if the specified number is a + * Not-a-Number (NaN) value, {@code false} otherwise. + * + * @param v the value to be tested. + * @return {@code true} if the value of the argument is NaN; + * {@code false} otherwise. + */ + static public boolean isNaN(double v) { + return (v != v); + } + + /** + * Returns {@code true} if the specified number is infinitely + * large in magnitude, {@code false} otherwise. + * + * @param v the value to be tested. + * @return {@code true} if the value of the argument is positive + * infinity or negative infinity; {@code false} otherwise. + */ + static public boolean isInfinite(double v) { + return (v == POSITIVE_INFINITY) || (v == NEGATIVE_INFINITY); + } + + /** + * The value of the Double. + * + * @serial + */ + private final double value; + + /** + * Constructs a newly allocated {@code Double} object that + * represents the primitive {@code double} argument. + * + * @param value the value to be represented by the {@code Double}. + */ + public Double(double value) { + this.value = value; + } + + /** + * Constructs a newly allocated {@code Double} object that + * represents the floating-point value of type {@code double} + * represented by the string. The string is converted to a + * {@code double} value as if by the {@code valueOf} method. + * + * @param s a string to be converted to a {@code Double}. + * @throws NumberFormatException if the string does not contain a + * parsable number. + * @see java.lang.Double#valueOf(java.lang.String) + */ + public Double(String s) throws NumberFormatException { + // REMIND: this is inefficient + this(valueOf(s).doubleValue()); + } + + /** + * Returns {@code true} if this {@code Double} value is + * a Not-a-Number (NaN), {@code false} otherwise. + * + * @return {@code true} if the value represented by this object is + * NaN; {@code false} otherwise. + */ + public boolean isNaN() { + return isNaN(value); + } + + /** + * Returns {@code true} if this {@code Double} value is + * infinitely large in magnitude, {@code false} otherwise. + * + * @return {@code true} if the value represented by this object is + * positive infinity or negative infinity; + * {@code false} otherwise. + */ + public boolean isInfinite() { + return isInfinite(value); + } + + /** + * Returns a string representation of this {@code Double} object. + * The primitive {@code double} value represented by this + * object is converted to a string exactly as if by the method + * {@code toString} of one argument. + * + * @return a {@code String} representation of this object. + * @see java.lang.Double#toString(double) + */ + public String toString() { + return toString(value); + } + + /** + * Returns the value of this {@code Double} as a {@code byte} (by + * casting to a {@code byte}). + * + * @return the {@code double} value represented by this object + * converted to type {@code byte} + * @since JDK1.1 + */ + public byte byteValue() { + return (byte)value; + } + + /** + * Returns the value of this {@code Double} as a + * {@code short} (by casting to a {@code short}). + * + * @return the {@code double} value represented by this object + * converted to type {@code short} + * @since JDK1.1 + */ + public short shortValue() { + return (short)value; + } + + /** + * Returns the value of this {@code Double} as an + * {@code int} (by casting to type {@code int}). + * + * @return the {@code double} value represented by this object + * converted to type {@code int} + */ + public int intValue() { + return (int)value; + } + + /** + * Returns the value of this {@code Double} as a + * {@code long} (by casting to type {@code long}). + * + * @return the {@code double} value represented by this object + * converted to type {@code long} + */ + public long longValue() { + return (long)value; + } + + /** + * Returns the {@code float} value of this + * {@code Double} object. + * + * @return the {@code double} value represented by this object + * converted to type {@code float} + * @since JDK1.0 + */ + public float floatValue() { + return (float)value; + } + + /** + * Returns the {@code double} value of this + * {@code Double} object. + * + * @return the {@code double} value represented by this object + */ + public double doubleValue() { + return (double)value; + } + + /** + * Returns a hash code for this {@code Double} object. The + * result is the exclusive OR of the two halves of the + * {@code long} integer bit representation, exactly as + * produced by the method {@link #doubleToLongBits(double)}, of + * the primitive {@code double} value represented by this + * {@code Double} object. That is, the hash code is the value + * of the expression: + * + *
+ * {@code (int)(v^(v>>>32))} + *
+ * + * where {@code v} is defined by: + * + *
+ * {@code long v = Double.doubleToLongBits(this.doubleValue());} + *
+ * + * @return a {@code hash code} value for this object. + */ + public int hashCode() { + long bits = doubleToLongBits(value); + return (int)(bits ^ (bits >>> 32)); + } + + /** + * Compares this object against the specified object. The result + * is {@code true} if and only if the argument is not + * {@code null} and is a {@code Double} object that + * represents a {@code double} that has the same value as the + * {@code double} represented by this object. For this + * purpose, two {@code double} values are considered to be + * the same if and only if the method {@link + * #doubleToLongBits(double)} returns the identical + * {@code long} value when applied to each. + * + *

Note that in most cases, for two instances of class + * {@code Double}, {@code d1} and {@code d2}, the + * value of {@code d1.equals(d2)} is {@code true} if and + * only if + * + *

+ * {@code d1.doubleValue() == d2.doubleValue()} + *
+ * + *

also has the value {@code true}. However, there are two + * exceptions: + *

    + *
  • If {@code d1} and {@code d2} both represent + * {@code Double.NaN}, then the {@code equals} method + * returns {@code true}, even though + * {@code Double.NaN==Double.NaN} has the value + * {@code false}. + *
  • If {@code d1} represents {@code +0.0} while + * {@code d2} represents {@code -0.0}, or vice versa, + * the {@code equal} test has the value {@code false}, + * even though {@code +0.0==-0.0} has the value {@code true}. + *
+ * This definition allows hash tables to operate properly. + * @param obj the object to compare with. + * @return {@code true} if the objects are the same; + * {@code false} otherwise. + * @see java.lang.Double#doubleToLongBits(double) + */ + public boolean equals(Object obj) { + return (obj instanceof Double) + && (((Double)obj).value) == value; + } + + /** + * Returns a representation of the specified floating-point value + * according to the IEEE 754 floating-point "double + * format" bit layout. + * + *

Bit 63 (the bit that is selected by the mask + * {@code 0x8000000000000000L}) represents the sign of the + * floating-point number. Bits + * 62-52 (the bits that are selected by the mask + * {@code 0x7ff0000000000000L}) represent the exponent. Bits 51-0 + * (the bits that are selected by the mask + * {@code 0x000fffffffffffffL}) represent the significand + * (sometimes called the mantissa) of the floating-point number. + * + *

If the argument is positive infinity, the result is + * {@code 0x7ff0000000000000L}. + * + *

If the argument is negative infinity, the result is + * {@code 0xfff0000000000000L}. + * + *

If the argument is NaN, the result is + * {@code 0x7ff8000000000000L}. + * + *

In all cases, the result is a {@code long} integer that, when + * given to the {@link #longBitsToDouble(long)} method, will produce a + * floating-point value the same as the argument to + * {@code doubleToLongBits} (except all NaN values are + * collapsed to a single "canonical" NaN value). + * + * @param value a {@code double} precision floating-point number. + * @return the bits that represent the floating-point number. + */ + public static long doubleToLongBits(double value) { + throw new UnsupportedOperationException(); +// long result = doubleToRawLongBits(value); +// // Check for NaN based on values of bit fields, maximum +// // exponent and nonzero significand. +// if ( ((result & DoubleConsts.EXP_BIT_MASK) == +// DoubleConsts.EXP_BIT_MASK) && +// (result & DoubleConsts.SIGNIF_BIT_MASK) != 0L) +// result = 0x7ff8000000000000L; +// return result; + } + + /** + * Returns a representation of the specified floating-point value + * according to the IEEE 754 floating-point "double + * format" bit layout, preserving Not-a-Number (NaN) values. + * + *

Bit 63 (the bit that is selected by the mask + * {@code 0x8000000000000000L}) represents the sign of the + * floating-point number. Bits + * 62-52 (the bits that are selected by the mask + * {@code 0x7ff0000000000000L}) represent the exponent. Bits 51-0 + * (the bits that are selected by the mask + * {@code 0x000fffffffffffffL}) represent the significand + * (sometimes called the mantissa) of the floating-point number. + * + *

If the argument is positive infinity, the result is + * {@code 0x7ff0000000000000L}. + * + *

If the argument is negative infinity, the result is + * {@code 0xfff0000000000000L}. + * + *

If the argument is NaN, the result is the {@code long} + * integer representing the actual NaN value. Unlike the + * {@code doubleToLongBits} method, + * {@code doubleToRawLongBits} does not collapse all the bit + * patterns encoding a NaN to a single "canonical" NaN + * value. + * + *

In all cases, the result is a {@code long} integer that, + * when given to the {@link #longBitsToDouble(long)} method, will + * produce a floating-point value the same as the argument to + * {@code doubleToRawLongBits}. + * + * @param value a {@code double} precision floating-point number. + * @return the bits that represent the floating-point number. + * @since 1.3 + */ + public static native long doubleToRawLongBits(double value); + + /** + * Returns the {@code double} value corresponding to a given + * bit representation. + * The argument is considered to be a representation of a + * floating-point value according to the IEEE 754 floating-point + * "double format" bit layout. + * + *

If the argument is {@code 0x7ff0000000000000L}, the result + * is positive infinity. + * + *

If the argument is {@code 0xfff0000000000000L}, the result + * is negative infinity. + * + *

If the argument is any value in the range + * {@code 0x7ff0000000000001L} through + * {@code 0x7fffffffffffffffL} or in the range + * {@code 0xfff0000000000001L} through + * {@code 0xffffffffffffffffL}, the result is a NaN. No IEEE + * 754 floating-point operation provided by Java can distinguish + * between two NaN values of the same type with different bit + * patterns. Distinct values of NaN are only distinguishable by + * use of the {@code Double.doubleToRawLongBits} method. + * + *

In all other cases, let s, e, and m be three + * values that can be computed from the argument: + * + *

+     * int s = ((bits >> 63) == 0) ? 1 : -1;
+     * int e = (int)((bits >> 52) & 0x7ffL);
+     * long m = (e == 0) ?
+     *                 (bits & 0xfffffffffffffL) << 1 :
+     *                 (bits & 0xfffffffffffffL) | 0x10000000000000L;
+     * 
+ * + * Then the floating-point result equals the value of the mathematical + * expression s·m·2e-1075. + * + *

Note that this method may not be able to return a + * {@code double} NaN with exactly same bit pattern as the + * {@code long} argument. IEEE 754 distinguishes between two + * kinds of NaNs, quiet NaNs and signaling NaNs. The + * differences between the two kinds of NaN are generally not + * visible in Java. Arithmetic operations on signaling NaNs turn + * them into quiet NaNs with a different, but often similar, bit + * pattern. However, on some processors merely copying a + * signaling NaN also performs that conversion. In particular, + * copying a signaling NaN to return it to the calling method + * may perform this conversion. So {@code longBitsToDouble} + * may not be able to return a {@code double} with a + * signaling NaN bit pattern. Consequently, for some + * {@code long} values, + * {@code doubleToRawLongBits(longBitsToDouble(start))} may + * not equal {@code start}. Moreover, which + * particular bit patterns represent signaling NaNs is platform + * dependent; although all NaN bit patterns, quiet or signaling, + * must be in the NaN range identified above. + * + * @param bits any {@code long} integer. + * @return the {@code double} floating-point value with the same + * bit pattern. + */ + public static native double longBitsToDouble(long bits); + + /** + * Compares two {@code Double} objects numerically. There + * are two ways in which comparisons performed by this method + * differ from those performed by the Java language numerical + * comparison operators ({@code <, <=, ==, >=, >}) + * when applied to primitive {@code double} values: + *

  • + * {@code Double.NaN} is considered by this method + * to be equal to itself and greater than all other + * {@code double} values (including + * {@code Double.POSITIVE_INFINITY}). + *
  • + * {@code 0.0d} is considered by this method to be greater + * than {@code -0.0d}. + *
+ * This ensures that the natural ordering of + * {@code Double} objects imposed by this method is consistent + * with equals. + * + * @param anotherDouble the {@code Double} to be compared. + * @return the value {@code 0} if {@code anotherDouble} is + * numerically equal to this {@code Double}; a value + * less than {@code 0} if this {@code Double} + * is numerically less than {@code anotherDouble}; + * and a value greater than {@code 0} if this + * {@code Double} is numerically greater than + * {@code anotherDouble}. + * + * @since 1.2 + */ + public int compareTo(Double anotherDouble) { + return Double.compare(value, anotherDouble.value); + } + + /** + * Compares the two specified {@code double} values. The sign + * of the integer value returned is the same as that of the + * integer that would be returned by the call: + *
+     *    new Double(d1).compareTo(new Double(d2))
+     * 
+ * + * @param d1 the first {@code double} to compare + * @param d2 the second {@code double} to compare + * @return the value {@code 0} if {@code d1} is + * numerically equal to {@code d2}; a value less than + * {@code 0} if {@code d1} is numerically less than + * {@code d2}; and a value greater than {@code 0} + * if {@code d1} is numerically greater than + * {@code d2}. + * @since 1.4 + */ + public static int compare(double d1, double d2) { + if (d1 < d2) + return -1; // Neither val is NaN, thisVal is smaller + if (d1 > d2) + return 1; // Neither val is NaN, thisVal is larger + + // Cannot use doubleToRawLongBits because of possibility of NaNs. + long thisBits = Double.doubleToLongBits(d1); + long anotherBits = Double.doubleToLongBits(d2); + + return (thisBits == anotherBits ? 0 : // Values are equal + (thisBits < anotherBits ? -1 : // (-0.0, 0.0) or (!NaN, NaN) + 1)); // (0.0, -0.0) or (NaN, !NaN) + } + + /** use serialVersionUID from JDK 1.0.2 for interoperability */ + private static final long serialVersionUID = -9172774392245257468L; +} diff -r 388e48c0a37a -r 05224402145d emul/mini/src/main/java/java/lang/Enum.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/emul/mini/src/main/java/java/lang/Enum.java Wed Jan 23 20:39:23 2013 +0100 @@ -0,0 +1,254 @@ +/* + * Copyright (c) 2003, 2009, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code 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 + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package java.lang; + +import java.io.Serializable; +import java.io.IOException; + +/** + * This is the common base class of all Java language enumeration types. + * + * More information about enums, including descriptions of the + * implicitly declared methods synthesized by the compiler, can be + * found in section 8.9 of + * The Java™ Language Specification. + * + *

Note that when using an enumeration type as the type of a set + * or as the type of the keys in a map, specialized and efficient + * {@linkplain java.util.EnumSet set} and {@linkplain + * java.util.EnumMap map} implementations are available. + * + * @param The enum type subclass + * @author Josh Bloch + * @author Neal Gafter + * @see Class#getEnumConstants() + * @see java.util.EnumSet + * @see java.util.EnumMap + * @since 1.5 + */ +public abstract class Enum> + implements Comparable, Serializable { + /** + * The name of this enum constant, as declared in the enum declaration. + * Most programmers should use the {@link #toString} method rather than + * accessing this field. + */ + private final String name; + + /** + * Returns the name of this enum constant, exactly as declared in its + * enum declaration. + * + * Most programmers should use the {@link #toString} method in + * preference to this one, as the toString method may return + * a more user-friendly name. This method is designed primarily for + * use in specialized situations where correctness depends on getting the + * exact name, which will not vary from release to release. + * + * @return the name of this enum constant + */ + public final String name() { + return name; + } + + /** + * The ordinal of this enumeration constant (its position + * in the enum declaration, where the initial constant is assigned + * an ordinal of zero). + * + * Most programmers will have no use for this field. It is designed + * for use by sophisticated enum-based data structures, such as + * {@link java.util.EnumSet} and {@link java.util.EnumMap}. + */ + private final int ordinal; + + /** + * Returns the ordinal of this enumeration constant (its position + * in its enum declaration, where the initial constant is assigned + * an ordinal of zero). + * + * Most programmers will have no use for this method. It is + * designed for use by sophisticated enum-based data structures, such + * as {@link java.util.EnumSet} and {@link java.util.EnumMap}. + * + * @return the ordinal of this enumeration constant + */ + public final int ordinal() { + return ordinal; + } + + /** + * Sole constructor. Programmers cannot invoke this constructor. + * It is for use by code emitted by the compiler in response to + * enum type declarations. + * + * @param name - The name of this enum constant, which is the identifier + * used to declare it. + * @param ordinal - The ordinal of this enumeration constant (its position + * in the enum declaration, where the initial constant is assigned + * an ordinal of zero). + */ + protected Enum(String name, int ordinal) { + this.name = name; + this.ordinal = ordinal; + } + + /** + * Returns the name of this enum constant, as contained in the + * declaration. This method may be overridden, though it typically + * isn't necessary or desirable. An enum type should override this + * method when a more "programmer-friendly" string form exists. + * + * @return the name of this enum constant + */ + public String toString() { + return name; + } + + /** + * Returns true if the specified object is equal to this + * enum constant. + * + * @param other the object to be compared for equality with this object. + * @return true if the specified object is equal to this + * enum constant. + */ + public final boolean equals(Object other) { + return this==other; + } + + /** + * Returns a hash code for this enum constant. + * + * @return a hash code for this enum constant. + */ + public final int hashCode() { + return super.hashCode(); + } + + /** + * Throws CloneNotSupportedException. This guarantees that enums + * are never cloned, which is necessary to preserve their "singleton" + * status. + * + * @return (never returns) + */ + protected final Object clone() throws CloneNotSupportedException { + throw new CloneNotSupportedException(); + } + + /** + * Compares this enum with the specified object for order. Returns a + * negative integer, zero, or a positive integer as this object is less + * than, equal to, or greater than the specified object. + * + * Enum constants are only comparable to other enum constants of the + * same enum type. The natural order implemented by this + * method is the order in which the constants are declared. + */ + public final int compareTo(E o) { + Enum other = (Enum)o; + Enum self = this; + if (self.getClass() != other.getClass() && // optimization + self.getDeclaringClass() != other.getDeclaringClass()) + throw new ClassCastException(); + return self.ordinal - other.ordinal; + } + + /** + * Returns the Class object corresponding to this enum constant's + * enum type. Two enum constants e1 and e2 are of the + * same enum type if and only if + * e1.getDeclaringClass() == e2.getDeclaringClass(). + * (The value returned by this method may differ from the one returned + * by the {@link Object#getClass} method for enum constants with + * constant-specific class bodies.) + * + * @return the Class object corresponding to this enum constant's + * enum type + */ + public final Class getDeclaringClass() { + Class clazz = getClass(); + Class zuper = clazz.getSuperclass(); + return (zuper == Enum.class) ? clazz : zuper; + } + + /** + * Returns the enum constant of the specified enum type with the + * specified name. The name must match exactly an identifier used + * to declare an enum constant in this type. (Extraneous whitespace + * characters are not permitted.) + * + *

Note that for a particular enum type {@code T}, the + * implicitly declared {@code public static T valueOf(String)} + * method on that enum may be used instead of this method to map + * from a name to the corresponding enum constant. All the + * constants of an enum type can be obtained by calling the + * implicit {@code public static T[] values()} method of that + * type. + * + * @param The enum type whose constant is to be returned + * @param enumType the {@code Class} object of the enum type from which + * to return a constant + * @param name the name of the constant to return + * @return the enum constant of the specified enum type with the + * specified name + * @throws IllegalArgumentException if the specified enum type has + * no constant with the specified name, or the specified + * class object does not represent an enum type + * @throws NullPointerException if {@code enumType} or {@code name} + * is null + * @since 1.5 + */ + public static > T valueOf(Class enumType, + String name) { + throw new UnsupportedOperationException(); +// T result = enumType.enumConstantDirectory().get(name); +// if (result != null) +// return result; +// if (name == null) +// throw new NullPointerException("Name is null"); +// throw new IllegalArgumentException( +// "No enum constant " + enumType.getCanonicalName() + "." + name); + } + + /** + * enum classes cannot have finalize methods. + */ + protected final void finalize() { } + + /** + * prevent default deserialization + */ +// private void readObject(ObjectInputStream in) throws IOException, +// ClassNotFoundException { +// throw new InvalidObjectException("can't deserialize enum"); +// } +// +// private void readObjectNoData() throws ObjectStreamException { +// throw new InvalidObjectException("can't deserialize enum"); +// } +} diff -r 388e48c0a37a -r 05224402145d emul/mini/src/main/java/java/lang/Error.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/emul/mini/src/main/java/java/lang/Error.java Wed Jan 23 20:39:23 2013 +0100 @@ -0,0 +1,128 @@ +/* + * Copyright (c) 1995, 2011, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code 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 + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package java.lang; + +/** + * An {@code Error} is a subclass of {@code Throwable} + * that indicates serious problems that a reasonable application + * should not try to catch. Most such errors are abnormal conditions. + * The {@code ThreadDeath} error, though a "normal" condition, + * is also a subclass of {@code Error} because most applications + * should not try to catch it. + *

+ * A method is not required to declare in its {@code throws} + * clause any subclasses of {@code Error} that might be thrown + * during the execution of the method but not caught, since these + * errors are abnormal conditions that should never occur. + * + * That is, {@code Error} and its subclasses are regarded as unchecked + * exceptions for the purposes of compile-time checking of exceptions. + * + * @author Frank Yellin + * @see java.lang.ThreadDeath + * @jls 11.2 Compile-Time Checking of Exceptions + * @since JDK1.0 + */ +public class Error extends Throwable { + static final long serialVersionUID = 4980196508277280342L; + + /** + * Constructs a new error with {@code null} as its detail message. + * The cause is not initialized, and may subsequently be initialized by a + * call to {@link #initCause}. + */ + public Error() { + super(); + } + + /** + * Constructs a new error with the specified detail message. The + * cause is not initialized, and may subsequently be initialized by + * a call to {@link #initCause}. + * + * @param message the detail message. The detail message is saved for + * later retrieval by the {@link #getMessage()} method. + */ + public Error(String message) { + super(message); + } + + /** + * Constructs a new error with the specified detail message and + * cause.

Note that the detail message associated with + * {@code cause} is not automatically incorporated in + * this error's detail message. + * + * @param message the detail message (which is saved for later retrieval + * by the {@link #getMessage()} method). + * @param cause the cause (which is saved for later retrieval by the + * {@link #getCause()} method). (A {@code null} value is + * permitted, and indicates that the cause is nonexistent or + * unknown.) + * @since 1.4 + */ + public Error(String message, Throwable cause) { + super(message, cause); + } + + /** + * Constructs a new error with the specified cause and a detail + * message of {@code (cause==null ? null : cause.toString())} (which + * typically contains the class and detail message of {@code cause}). + * This constructor is useful for errors that are little more than + * wrappers for other throwables. + * + * @param cause the cause (which is saved for later retrieval by the + * {@link #getCause()} method). (A {@code null} value is + * permitted, and indicates that the cause is nonexistent or + * unknown.) + * @since 1.4 + */ + public Error(Throwable cause) { + super(cause); + } + + /** + * Constructs a new error with the specified detail message, + * cause, suppression enabled or disabled, and writable stack + * trace enabled or disabled. + * + * @param message the detail message. + * @param cause the cause. (A {@code null} value is permitted, + * and indicates that the cause is nonexistent or unknown.) + * @param enableSuppression whether or not suppression is enabled + * or disabled + * @param writableStackTrace whether or not the stack trace should + * be writable + * + * @since 1.7 + */ + protected Error(String message, Throwable cause, + boolean enableSuppression, + boolean writableStackTrace) { + super(message, cause, enableSuppression, writableStackTrace); + } +} diff -r 388e48c0a37a -r 05224402145d emul/mini/src/main/java/java/lang/Exception.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/emul/mini/src/main/java/java/lang/Exception.java Wed Jan 23 20:39:23 2013 +0100 @@ -0,0 +1,124 @@ +/* + * Copyright (c) 1994, 2011, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code 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 + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package java.lang; + +/** + * The class {@code Exception} and its subclasses are a form of + * {@code Throwable} that indicates conditions that a reasonable + * application might want to catch. + * + *

The class {@code Exception} and any subclasses that are not also + * subclasses of {@link RuntimeException} are checked + * exceptions. Checked exceptions need to be declared in a + * method or constructor's {@code throws} clause if they can be thrown + * by the execution of the method or constructor and propagate outside + * the method or constructor boundary. + * + * @author Frank Yellin + * @see java.lang.Error + * @jls 11.2 Compile-Time Checking of Exceptions + * @since JDK1.0 + */ +public class Exception extends Throwable { + static final long serialVersionUID = -3387516993124229948L; + + /** + * Constructs a new exception with {@code null} as its detail message. + * The cause is not initialized, and may subsequently be initialized by a + * call to {@link #initCause}. + */ + public Exception() { + super(); + } + + /** + * Constructs a new exception with the specified detail message. The + * cause is not initialized, and may subsequently be initialized by + * a call to {@link #initCause}. + * + * @param message the detail message. The detail message is saved for + * later retrieval by the {@link #getMessage()} method. + */ + public Exception(String message) { + super(message); + } + + /** + * Constructs a new exception with the specified detail message and + * cause.

Note that the detail message associated with + * {@code cause} is not automatically incorporated in + * this exception's detail message. + * + * @param message the detail message (which is saved for later retrieval + * by the {@link #getMessage()} method). + * @param cause the cause (which is saved for later retrieval by the + * {@link #getCause()} method). (A null value is + * permitted, and indicates that the cause is nonexistent or + * unknown.) + * @since 1.4 + */ + public Exception(String message, Throwable cause) { + super(message, cause); + } + + /** + * Constructs a new exception with the specified cause and a detail + * message of (cause==null ? null : cause.toString()) (which + * typically contains the class and detail message of cause). + * This constructor is useful for exceptions that are little more than + * wrappers for other throwables (for example, {@link + * java.security.PrivilegedActionException}). + * + * @param cause the cause (which is saved for later retrieval by the + * {@link #getCause()} method). (A null value is + * permitted, and indicates that the cause is nonexistent or + * unknown.) + * @since 1.4 + */ + public Exception(Throwable cause) { + super(cause); + } + + /** + * Constructs a new exception with the specified detail message, + * cause, suppression enabled or disabled, and writable stack + * trace enabled or disabled. + * + * @param message the detail message. + * @param cause the cause. (A {@code null} value is permitted, + * and indicates that the cause is nonexistent or unknown.) + * @param enableSuppression whether or not suppression is enabled + * or disabled + * @param writableStackTrace whether or not the stack trace should + * be writable + * @since 1.7 + */ + protected Exception(String message, Throwable cause, + boolean enableSuppression, + boolean writableStackTrace) { + super(message, cause, enableSuppression, writableStackTrace); + } +} diff -r 388e48c0a37a -r 05224402145d emul/mini/src/main/java/java/lang/Float.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/emul/mini/src/main/java/java/lang/Float.java Wed Jan 23 20:39:23 2013 +0100 @@ -0,0 +1,905 @@ +/* + * Copyright (c) 1994, 2010, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code 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 + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package java.lang; + +import org.apidesign.bck2brwsr.core.JavaScriptBody; + +/** + * The {@code Float} class wraps a value of primitive type + * {@code float} in an object. An object of type + * {@code Float} contains a single field whose type is + * {@code float}. + * + *

In addition, this class provides several methods for converting a + * {@code float} to a {@code String} and a + * {@code String} to a {@code float}, as well as other + * constants and methods useful when dealing with a + * {@code float}. + * + * @author Lee Boynton + * @author Arthur van Hoff + * @author Joseph D. Darcy + * @since JDK1.0 + */ +public final class Float extends Number implements Comparable { + /** + * A constant holding the positive infinity of type + * {@code float}. It is equal to the value returned by + * {@code Float.intBitsToFloat(0x7f800000)}. + */ + public static final float POSITIVE_INFINITY = 1.0f / 0.0f; + + /** + * A constant holding the negative infinity of type + * {@code float}. It is equal to the value returned by + * {@code Float.intBitsToFloat(0xff800000)}. + */ + public static final float NEGATIVE_INFINITY = -1.0f / 0.0f; + + /** + * A constant holding a Not-a-Number (NaN) value of type + * {@code float}. It is equivalent to the value returned by + * {@code Float.intBitsToFloat(0x7fc00000)}. + */ + public static final float NaN = 0.0f / 0.0f; + + /** + * A constant holding the largest positive finite value of type + * {@code float}, (2-2-23)·2127. + * It is equal to the hexadecimal floating-point literal + * {@code 0x1.fffffeP+127f} and also equal to + * {@code Float.intBitsToFloat(0x7f7fffff)}. + */ + public static final float MAX_VALUE = 0x1.fffffeP+127f; // 3.4028235e+38f + + /** + * A constant holding the smallest positive normal value of type + * {@code float}, 2-126. It is equal to the + * hexadecimal floating-point literal {@code 0x1.0p-126f} and also + * equal to {@code Float.intBitsToFloat(0x00800000)}. + * + * @since 1.6 + */ + public static final float MIN_NORMAL = 0x1.0p-126f; // 1.17549435E-38f + + /** + * A constant holding the smallest positive nonzero value of type + * {@code float}, 2-149. It is equal to the + * hexadecimal floating-point literal {@code 0x0.000002P-126f} + * and also equal to {@code Float.intBitsToFloat(0x1)}. + */ + public static final float MIN_VALUE = 0x0.000002P-126f; // 1.4e-45f + + /** + * Maximum exponent a finite {@code float} variable may have. It + * is equal to the value returned by {@code + * Math.getExponent(Float.MAX_VALUE)}. + * + * @since 1.6 + */ + public static final int MAX_EXPONENT = 127; + + /** + * Minimum exponent a normalized {@code float} variable may have. + * It is equal to the value returned by {@code + * Math.getExponent(Float.MIN_NORMAL)}. + * + * @since 1.6 + */ + public static final int MIN_EXPONENT = -126; + + /** + * The number of bits used to represent a {@code float} value. + * + * @since 1.5 + */ + public static final int SIZE = 32; + + /** + * The {@code Class} instance representing the primitive type + * {@code float}. + * + * @since JDK1.1 + */ + public static final Class TYPE = Class.getPrimitiveClass("float"); + + /** + * Returns a string representation of the {@code float} + * argument. All characters mentioned below are ASCII characters. + *

    + *
  • If the argument is NaN, the result is the string + * "{@code NaN}". + *
  • Otherwise, the result is a string that represents the sign and + * magnitude (absolute value) of the argument. If the sign is + * negative, the first character of the result is + * '{@code -}' ('\u002D'); if the sign is + * positive, no sign character appears in the result. As for + * the magnitude m: + *
      + *
    • If m is infinity, it is represented by the characters + * {@code "Infinity"}; thus, positive infinity produces + * the result {@code "Infinity"} and negative infinity + * produces the result {@code "-Infinity"}. + *
    • If m is zero, it is represented by the characters + * {@code "0.0"}; thus, negative zero produces the result + * {@code "-0.0"} and positive zero produces the result + * {@code "0.0"}. + *
    • If m is greater than or equal to 10-3 but + * less than 107, then it is represented as the + * integer part of m, in decimal form with no leading + * zeroes, followed by '{@code .}' + * ('\u002E'), followed by one or more + * decimal digits representing the fractional part of + * m. + *
    • If m is less than 10-3 or greater than or + * equal to 107, then it is represented in + * so-called "computerized scientific notation." Let n + * be the unique integer such that 10n ≤ + * m {@literal <} 10n+1; then let a + * be the mathematically exact quotient of m and + * 10n so that 1 ≤ a {@literal <} 10. + * The magnitude is then represented as the integer part of + * a, as a single decimal digit, followed by + * '{@code .}' ('\u002E'), followed by + * decimal digits representing the fractional part of + * a, followed by the letter '{@code E}' + * ('\u0045'), followed by a representation + * of n as a decimal integer, as produced by the + * method {@link java.lang.Integer#toString(int)}. + * + *
    + *
+ * How many digits must be printed for the fractional part of + * m or a? There must be at least one digit + * to represent the fractional part, and beyond that as many, but + * only as many, more digits as are needed to uniquely distinguish + * the argument value from adjacent values of type + * {@code float}. That is, suppose that x is the + * exact mathematical value represented by the decimal + * representation produced by this method for a finite nonzero + * argument f. Then f must be the {@code float} + * value nearest to x; or, if two {@code float} values are + * equally close to x, then f must be one of + * them and the least significant bit of the significand of + * f must be {@code 0}. + * + *

To create localized string representations of a floating-point + * value, use subclasses of {@link java.text.NumberFormat}. + * + * @param f the float to be converted. + * @return a string representation of the argument. + */ + public static String toString(float f) { + return Double.toString(f); + } + + /** + * Returns a hexadecimal string representation of the + * {@code float} argument. All characters mentioned below are + * ASCII characters. + * + *

    + *
  • If the argument is NaN, the result is the string + * "{@code NaN}". + *
  • Otherwise, the result is a string that represents the sign and + * magnitude (absolute value) of the argument. If the sign is negative, + * the first character of the result is '{@code -}' + * ('\u002D'); if the sign is positive, no sign character + * appears in the result. As for the magnitude m: + * + *
      + *
    • If m is infinity, it is represented by the string + * {@code "Infinity"}; thus, positive infinity produces the + * result {@code "Infinity"} and negative infinity produces + * the result {@code "-Infinity"}. + * + *
    • If m is zero, it is represented by the string + * {@code "0x0.0p0"}; thus, negative zero produces the result + * {@code "-0x0.0p0"} and positive zero produces the result + * {@code "0x0.0p0"}. + * + *
    • If m is a {@code float} value with a + * normalized representation, substrings are used to represent the + * significand and exponent fields. The significand is + * represented by the characters {@code "0x1."} + * followed by a lowercase hexadecimal representation of the rest + * of the significand as a fraction. Trailing zeros in the + * hexadecimal representation are removed unless all the digits + * are zero, in which case a single zero is used. Next, the + * exponent is represented by {@code "p"} followed + * by a decimal string of the unbiased exponent as if produced by + * a call to {@link Integer#toString(int) Integer.toString} on the + * exponent value. + * + *
    • If m is a {@code float} value with a subnormal + * representation, the significand is represented by the + * characters {@code "0x0."} followed by a + * hexadecimal representation of the rest of the significand as a + * fraction. Trailing zeros in the hexadecimal representation are + * removed. Next, the exponent is represented by + * {@code "p-126"}. Note that there must be at + * least one nonzero digit in a subnormal significand. + * + *
    + * + *
+ * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *

Examples

Floating-point ValueHexadecimal String
{@code 1.0} {@code 0x1.0p0}
{@code -1.0} {@code -0x1.0p0}
{@code 2.0} {@code 0x1.0p1}
{@code 3.0} {@code 0x1.8p1}
{@code 0.5} {@code 0x1.0p-1}
{@code 0.25} {@code 0x1.0p-2}
{@code Float.MAX_VALUE}{@code 0x1.fffffep127}
{@code Minimum Normal Value}{@code 0x1.0p-126}
{@code Maximum Subnormal Value}{@code 0x0.fffffep-126}
{@code Float.MIN_VALUE}{@code 0x0.000002p-126}
+ * @param f the {@code float} to be converted. + * @return a hex string representation of the argument. + * @since 1.5 + * @author Joseph D. Darcy + */ + public static String toHexString(float f) { + throw new UnsupportedOperationException(); +// if (Math.abs(f) < FloatConsts.MIN_NORMAL +// && f != 0.0f ) {// float subnormal +// // Adjust exponent to create subnormal double, then +// // replace subnormal double exponent with subnormal float +// // exponent +// String s = Double.toHexString(FpUtils.scalb((double)f, +// /* -1022+126 */ +// DoubleConsts.MIN_EXPONENT- +// FloatConsts.MIN_EXPONENT)); +// return s.replaceFirst("p-1022$", "p-126"); +// } +// else // double string will be the same as float string +// return Double.toHexString(f); + } + + /** + * Returns a {@code Float} object holding the + * {@code float} value represented by the argument string + * {@code s}. + * + *

If {@code s} is {@code null}, then a + * {@code NullPointerException} is thrown. + * + *

Leading and trailing whitespace characters in {@code s} + * are ignored. Whitespace is removed as if by the {@link + * String#trim} method; that is, both ASCII space and control + * characters are removed. The rest of {@code s} should + * constitute a FloatValue as described by the lexical + * syntax rules: + * + *

+ *
+ *
FloatValue: + *
Signopt {@code NaN} + *
Signopt {@code Infinity} + *
Signopt FloatingPointLiteral + *
Signopt HexFloatingPointLiteral + *
SignedInteger + *
+ * + *

+ * + *

+ *
HexFloatingPointLiteral: + *
HexSignificand BinaryExponent FloatTypeSuffixopt + *
+ * + *

+ * + *

+ *
HexSignificand: + *
HexNumeral + *
HexNumeral {@code .} + *
{@code 0x} HexDigitsopt + * {@code .} HexDigits + *
{@code 0X} HexDigitsopt + * {@code .} HexDigits + *
+ * + *

+ * + *

+ *
BinaryExponent: + *
BinaryExponentIndicator SignedInteger + *
+ * + *

+ * + *

+ *
BinaryExponentIndicator: + *
{@code p} + *
{@code P} + *
+ * + *
+ * + * where Sign, FloatingPointLiteral, + * HexNumeral, HexDigits, SignedInteger and + * FloatTypeSuffix are as defined in the lexical structure + * sections of + * The Java™ Language Specification, + * except that underscores are not accepted between digits. + * If {@code s} does not have the form of + * a FloatValue, then a {@code NumberFormatException} + * is thrown. Otherwise, {@code s} is regarded as + * representing an exact decimal value in the usual + * "computerized scientific notation" or as an exact + * hexadecimal value; this exact numerical value is then + * conceptually converted to an "infinitely precise" + * binary value that is then rounded to type {@code float} + * by the usual round-to-nearest rule of IEEE 754 floating-point + * arithmetic, which includes preserving the sign of a zero + * value. + * + * Note that the round-to-nearest rule also implies overflow and + * underflow behaviour; if the exact value of {@code s} is large + * enough in magnitude (greater than or equal to ({@link + * #MAX_VALUE} + {@link Math#ulp(float) ulp(MAX_VALUE)}/2), + * rounding to {@code float} will result in an infinity and if the + * exact value of {@code s} is small enough in magnitude (less + * than or equal to {@link #MIN_VALUE}/2), rounding to float will + * result in a zero. + * + * Finally, after rounding a {@code Float} object representing + * this {@code float} value is returned. + * + *

To interpret localized string representations of a + * floating-point value, use subclasses of {@link + * java.text.NumberFormat}. + * + *

Note that trailing format specifiers, specifiers that + * determine the type of a floating-point literal + * ({@code 1.0f} is a {@code float} value; + * {@code 1.0d} is a {@code double} value), do + * not influence the results of this method. In other + * words, the numerical value of the input string is converted + * directly to the target floating-point type. In general, the + * two-step sequence of conversions, string to {@code double} + * followed by {@code double} to {@code float}, is + * not equivalent to converting a string directly to + * {@code float}. For example, if first converted to an + * intermediate {@code double} and then to + * {@code float}, the string
+ * {@code "1.00000017881393421514957253748434595763683319091796875001d"}
+ * results in the {@code float} value + * {@code 1.0000002f}; if the string is converted directly to + * {@code float}, 1.0000001f results. + * + *

To avoid calling this method on an invalid string and having + * a {@code NumberFormatException} be thrown, the documentation + * for {@link Double#valueOf Double.valueOf} lists a regular + * expression which can be used to screen the input. + * + * @param s the string to be parsed. + * @return a {@code Float} object holding the value + * represented by the {@code String} argument. + * @throws NumberFormatException if the string does not contain a + * parsable number. + */ + public static Float valueOf(String s) throws NumberFormatException { + throw new UnsupportedOperationException(); +// return new Float(FloatingDecimal.readJavaFormatString(s).floatValue()); + } + + /** + * Returns a {@code Float} instance representing the specified + * {@code float} value. + * If a new {@code Float} instance is not required, this method + * should generally be used in preference to the constructor + * {@link #Float(float)}, as this method is likely to yield + * significantly better space and time performance by caching + * frequently requested values. + * + * @param f a float value. + * @return a {@code Float} instance representing {@code f}. + * @since 1.5 + */ + public static Float valueOf(float f) { + return new Float(f); + } + + /** + * Returns a new {@code float} initialized to the value + * represented by the specified {@code String}, as performed + * by the {@code valueOf} method of class {@code Float}. + * + * @param s the string to be parsed. + * @return the {@code float} value represented by the string + * argument. + * @throws NullPointerException if the string is null + * @throws NumberFormatException if the string does not contain a + * parsable {@code float}. + * @see java.lang.Float#valueOf(String) + * @since 1.2 + */ + public static float parseFloat(String s) throws NumberFormatException { + throw new UnsupportedOperationException(); +// return FloatingDecimal.readJavaFormatString(s).floatValue(); + } + + /** + * Returns {@code true} if the specified number is a + * Not-a-Number (NaN) value, {@code false} otherwise. + * + * @param v the value to be tested. + * @return {@code true} if the argument is NaN; + * {@code false} otherwise. + */ + static public boolean isNaN(float v) { + return (v != v); + } + + /** + * Returns {@code true} if the specified number is infinitely + * large in magnitude, {@code false} otherwise. + * + * @param v the value to be tested. + * @return {@code true} if the argument is positive infinity or + * negative infinity; {@code false} otherwise. + */ + static public boolean isInfinite(float v) { + return (v == POSITIVE_INFINITY) || (v == NEGATIVE_INFINITY); + } + + /** + * The value of the Float. + * + * @serial + */ + private final float value; + + /** + * Constructs a newly allocated {@code Float} object that + * represents the primitive {@code float} argument. + * + * @param value the value to be represented by the {@code Float}. + */ + public Float(float value) { + this.value = value; + } + + /** + * Constructs a newly allocated {@code Float} object that + * represents the argument converted to type {@code float}. + * + * @param value the value to be represented by the {@code Float}. + */ + public Float(double value) { + this.value = (float)value; + } + + /** + * Constructs a newly allocated {@code Float} object that + * represents the floating-point value of type {@code float} + * represented by the string. The string is converted to a + * {@code float} value as if by the {@code valueOf} method. + * + * @param s a string to be converted to a {@code Float}. + * @throws NumberFormatException if the string does not contain a + * parsable number. + * @see java.lang.Float#valueOf(java.lang.String) + */ + public Float(String s) throws NumberFormatException { + // REMIND: this is inefficient + this(valueOf(s).floatValue()); + } + + /** + * Returns {@code true} if this {@code Float} value is a + * Not-a-Number (NaN), {@code false} otherwise. + * + * @return {@code true} if the value represented by this object is + * NaN; {@code false} otherwise. + */ + public boolean isNaN() { + return isNaN(value); + } + + /** + * Returns {@code true} if this {@code Float} value is + * infinitely large in magnitude, {@code false} otherwise. + * + * @return {@code true} if the value represented by this object is + * positive infinity or negative infinity; + * {@code false} otherwise. + */ + public boolean isInfinite() { + return isInfinite(value); + } + + /** + * Returns a string representation of this {@code Float} object. + * The primitive {@code float} value represented by this object + * is converted to a {@code String} exactly as if by the method + * {@code toString} of one argument. + * + * @return a {@code String} representation of this object. + * @see java.lang.Float#toString(float) + */ + public String toString() { + return Float.toString(value); + } + + /** + * Returns the value of this {@code Float} as a {@code byte} (by + * casting to a {@code byte}). + * + * @return the {@code float} value represented by this object + * converted to type {@code byte} + */ + public byte byteValue() { + return (byte)value; + } + + /** + * Returns the value of this {@code Float} as a {@code short} (by + * casting to a {@code short}). + * + * @return the {@code float} value represented by this object + * converted to type {@code short} + * @since JDK1.1 + */ + public short shortValue() { + return (short)value; + } + + /** + * Returns the value of this {@code Float} as an {@code int} (by + * casting to type {@code int}). + * + * @return the {@code float} value represented by this object + * converted to type {@code int} + */ + public int intValue() { + return (int)value; + } + + /** + * Returns value of this {@code Float} as a {@code long} (by + * casting to type {@code long}). + * + * @return the {@code float} value represented by this object + * converted to type {@code long} + */ + public long longValue() { + return (long)value; + } + + /** + * Returns the {@code float} value of this {@code Float} object. + * + * @return the {@code float} value represented by this object + */ + public float floatValue() { + return value; + } + + /** + * Returns the {@code double} value of this {@code Float} object. + * + * @return the {@code float} value represented by this + * object is converted to type {@code double} and the + * result of the conversion is returned. + */ + public double doubleValue() { + return (double)value; + } + + /** + * Returns a hash code for this {@code Float} object. The + * result is the integer bit representation, exactly as produced + * by the method {@link #floatToIntBits(float)}, of the primitive + * {@code float} value represented by this {@code Float} + * object. + * + * @return a hash code value for this object. + */ + public int hashCode() { + return floatToIntBits(value); + } + + /** + + * Compares this object against the specified object. The result + * is {@code true} if and only if the argument is not + * {@code null} and is a {@code Float} object that + * represents a {@code float} with the same value as the + * {@code float} represented by this object. For this + * purpose, two {@code float} values are considered to be the + * same if and only if the method {@link #floatToIntBits(float)} + * returns the identical {@code int} value when applied to + * each. + * + *

Note that in most cases, for two instances of class + * {@code Float}, {@code f1} and {@code f2}, the value + * of {@code f1.equals(f2)} is {@code true} if and only if + * + *

+     *   f1.floatValue() == f2.floatValue()
+     * 
+ * + *

also has the value {@code true}. However, there are two exceptions: + *

    + *
  • If {@code f1} and {@code f2} both represent + * {@code Float.NaN}, then the {@code equals} method returns + * {@code true}, even though {@code Float.NaN==Float.NaN} + * has the value {@code false}. + *
  • If {@code f1} represents {@code +0.0f} while + * {@code f2} represents {@code -0.0f}, or vice + * versa, the {@code equal} test has the value + * {@code false}, even though {@code 0.0f==-0.0f} + * has the value {@code true}. + *
+ * + * This definition allows hash tables to operate properly. + * + * @param obj the object to be compared + * @return {@code true} if the objects are the same; + * {@code false} otherwise. + * @see java.lang.Float#floatToIntBits(float) + */ + public boolean equals(Object obj) { + return (obj instanceof Float) + && (floatToIntBits(((Float)obj).value) == floatToIntBits(value)); + } + + /** + * Returns a representation of the specified floating-point value + * according to the IEEE 754 floating-point "single format" bit + * layout. + * + *

Bit 31 (the bit that is selected by the mask + * {@code 0x80000000}) represents the sign of the floating-point + * number. + * Bits 30-23 (the bits that are selected by the mask + * {@code 0x7f800000}) represent the exponent. + * Bits 22-0 (the bits that are selected by the mask + * {@code 0x007fffff}) represent the significand (sometimes called + * the mantissa) of the floating-point number. + * + *

If the argument is positive infinity, the result is + * {@code 0x7f800000}. + * + *

If the argument is negative infinity, the result is + * {@code 0xff800000}. + * + *

If the argument is NaN, the result is {@code 0x7fc00000}. + * + *

In all cases, the result is an integer that, when given to the + * {@link #intBitsToFloat(int)} method, will produce a floating-point + * value the same as the argument to {@code floatToIntBits} + * (except all NaN values are collapsed to a single + * "canonical" NaN value). + * + * @param value a floating-point number. + * @return the bits that represent the floating-point number. + */ + public static int floatToIntBits(float value) { + throw new UnsupportedOperationException(); +// int result = floatToRawIntBits(value); +// // Check for NaN based on values of bit fields, maximum +// // exponent and nonzero significand. +// if ( ((result & FloatConsts.EXP_BIT_MASK) == +// FloatConsts.EXP_BIT_MASK) && +// (result & FloatConsts.SIGNIF_BIT_MASK) != 0) +// result = 0x7fc00000; +// return result; + } + + /** + * Returns a representation of the specified floating-point value + * according to the IEEE 754 floating-point "single format" bit + * layout, preserving Not-a-Number (NaN) values. + * + *

Bit 31 (the bit that is selected by the mask + * {@code 0x80000000}) represents the sign of the floating-point + * number. + * Bits 30-23 (the bits that are selected by the mask + * {@code 0x7f800000}) represent the exponent. + * Bits 22-0 (the bits that are selected by the mask + * {@code 0x007fffff}) represent the significand (sometimes called + * the mantissa) of the floating-point number. + * + *

If the argument is positive infinity, the result is + * {@code 0x7f800000}. + * + *

If the argument is negative infinity, the result is + * {@code 0xff800000}. + * + *

If the argument is NaN, the result is the integer representing + * the actual NaN value. Unlike the {@code floatToIntBits} + * method, {@code floatToRawIntBits} does not collapse all the + * bit patterns encoding a NaN to a single "canonical" + * NaN value. + * + *

In all cases, the result is an integer that, when given to the + * {@link #intBitsToFloat(int)} method, will produce a + * floating-point value the same as the argument to + * {@code floatToRawIntBits}. + * + * @param value a floating-point number. + * @return the bits that represent the floating-point number. + * @since 1.3 + */ + public static native int floatToRawIntBits(float value); + + /** + * Returns the {@code float} value corresponding to a given + * bit representation. + * The argument is considered to be a representation of a + * floating-point value according to the IEEE 754 floating-point + * "single format" bit layout. + * + *

If the argument is {@code 0x7f800000}, the result is positive + * infinity. + * + *

If the argument is {@code 0xff800000}, the result is negative + * infinity. + * + *

If the argument is any value in the range + * {@code 0x7f800001} through {@code 0x7fffffff} or in + * the range {@code 0xff800001} through + * {@code 0xffffffff}, the result is a NaN. No IEEE 754 + * floating-point operation provided by Java can distinguish + * between two NaN values of the same type with different bit + * patterns. Distinct values of NaN are only distinguishable by + * use of the {@code Float.floatToRawIntBits} method. + * + *

In all other cases, let s, e, and m be three + * values that can be computed from the argument: + * + *

+     * int s = ((bits >> 31) == 0) ? 1 : -1;
+     * int e = ((bits >> 23) & 0xff);
+     * int m = (e == 0) ?
+     *                 (bits & 0x7fffff) << 1 :
+     *                 (bits & 0x7fffff) | 0x800000;
+     * 
+ * + * Then the floating-point result equals the value of the mathematical + * expression s·m·2e-150. + * + *

Note that this method may not be able to return a + * {@code float} NaN with exactly same bit pattern as the + * {@code int} argument. IEEE 754 distinguishes between two + * kinds of NaNs, quiet NaNs and signaling NaNs. The + * differences between the two kinds of NaN are generally not + * visible in Java. Arithmetic operations on signaling NaNs turn + * them into quiet NaNs with a different, but often similar, bit + * pattern. However, on some processors merely copying a + * signaling NaN also performs that conversion. In particular, + * copying a signaling NaN to return it to the calling method may + * perform this conversion. So {@code intBitsToFloat} may + * not be able to return a {@code float} with a signaling NaN + * bit pattern. Consequently, for some {@code int} values, + * {@code floatToRawIntBits(intBitsToFloat(start))} may + * not equal {@code start}. Moreover, which + * particular bit patterns represent signaling NaNs is platform + * dependent; although all NaN bit patterns, quiet or signaling, + * must be in the NaN range identified above. + * + * @param bits an integer. + * @return the {@code float} floating-point value with the same bit + * pattern. + */ + @JavaScriptBody(args = "bits", + body = + "if (bits === 0x7f800000) return Number.POSITIVE_INFINITY;\n" + + "if (bits === 0xff800000) return Number.NEGATIVE_INFINITY;\n" + + "if (bits >= 0x7f800001 && bits <= 0xffffffff) return Number.NaN;\n" + + "var s = ((bits >> 31) == 0) ? 1 : -1;\n" + + "var e = ((bits >> 23) & 0xff);\n" + + "var m = (e == 0) ?\n" + + " (bits & 0x7fffff) << 1 :\n" + + " (bits & 0x7fffff) | 0x800000;\n" + + "return s * m * Math.pow(2.0, e - 150);\n" + ) + public static native float intBitsToFloat(int bits); + + /** + * Compares two {@code Float} objects numerically. There are + * two ways in which comparisons performed by this method differ + * from those performed by the Java language numerical comparison + * operators ({@code <, <=, ==, >=, >}) when + * applied to primitive {@code float} values: + * + *

  • + * {@code Float.NaN} is considered by this method to + * be equal to itself and greater than all other + * {@code float} values + * (including {@code Float.POSITIVE_INFINITY}). + *
  • + * {@code 0.0f} is considered by this method to be greater + * than {@code -0.0f}. + *
+ * + * This ensures that the natural ordering of {@code Float} + * objects imposed by this method is consistent with equals. + * + * @param anotherFloat the {@code Float} to be compared. + * @return the value {@code 0} if {@code anotherFloat} is + * numerically equal to this {@code Float}; a value + * less than {@code 0} if this {@code Float} + * is numerically less than {@code anotherFloat}; + * and a value greater than {@code 0} if this + * {@code Float} is numerically greater than + * {@code anotherFloat}. + * + * @since 1.2 + * @see Comparable#compareTo(Object) + */ + public int compareTo(Float anotherFloat) { + return Float.compare(value, anotherFloat.value); + } + + /** + * Compares the two specified {@code float} values. The sign + * of the integer value returned is the same as that of the + * integer that would be returned by the call: + *
+     *    new Float(f1).compareTo(new Float(f2))
+     * 
+ * + * @param f1 the first {@code float} to compare. + * @param f2 the second {@code float} to compare. + * @return the value {@code 0} if {@code f1} is + * numerically equal to {@code f2}; a value less than + * {@code 0} if {@code f1} is numerically less than + * {@code f2}; and a value greater than {@code 0} + * if {@code f1} is numerically greater than + * {@code f2}. + * @since 1.4 + */ + public static int compare(float f1, float f2) { + if (f1 < f2) + return -1; // Neither val is NaN, thisVal is smaller + if (f1 > f2) + return 1; // Neither val is NaN, thisVal is larger + + // Cannot use floatToRawIntBits because of possibility of NaNs. + int thisBits = Float.floatToIntBits(f1); + int anotherBits = Float.floatToIntBits(f2); + + return (thisBits == anotherBits ? 0 : // Values are equal + (thisBits < anotherBits ? -1 : // (-0.0, 0.0) or (!NaN, NaN) + 1)); // (0.0, -0.0) or (NaN, !NaN) + } + + /** use serialVersionUID from JDK 1.0.2 for interoperability */ + private static final long serialVersionUID = -2671257302660747028L; +} diff -r 388e48c0a37a -r 05224402145d emul/mini/src/main/java/java/lang/IllegalAccessException.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/emul/mini/src/main/java/java/lang/IllegalAccessException.java Wed Jan 23 20:39:23 2013 +0100 @@ -0,0 +1,78 @@ +/* + * Copyright (c) 1995, 2008, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code 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 + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package java.lang; + +/** + * An IllegalAccessException is thrown when an application tries + * to reflectively create an instance (other than an array), + * set or get a field, or invoke a method, but the currently + * executing method does not have access to the definition of + * the specified class, field, method or constructor. + * + * @author unascribed + * @see Class#newInstance() + * @see java.lang.reflect.Field#set(Object, Object) + * @see java.lang.reflect.Field#setBoolean(Object, boolean) + * @see java.lang.reflect.Field#setByte(Object, byte) + * @see java.lang.reflect.Field#setShort(Object, short) + * @see java.lang.reflect.Field#setChar(Object, char) + * @see java.lang.reflect.Field#setInt(Object, int) + * @see java.lang.reflect.Field#setLong(Object, long) + * @see java.lang.reflect.Field#setFloat(Object, float) + * @see java.lang.reflect.Field#setDouble(Object, double) + * @see java.lang.reflect.Field#get(Object) + * @see java.lang.reflect.Field#getBoolean(Object) + * @see java.lang.reflect.Field#getByte(Object) + * @see java.lang.reflect.Field#getShort(Object) + * @see java.lang.reflect.Field#getChar(Object) + * @see java.lang.reflect.Field#getInt(Object) + * @see java.lang.reflect.Field#getLong(Object) + * @see java.lang.reflect.Field#getFloat(Object) + * @see java.lang.reflect.Field#getDouble(Object) + * @see java.lang.reflect.Method#invoke(Object, Object[]) + * @see java.lang.reflect.Constructor#newInstance(Object[]) + * @since JDK1.0 + */ +public class IllegalAccessException extends ReflectiveOperationException { + private static final long serialVersionUID = 6616958222490762034L; + + /** + * Constructs an IllegalAccessException without a + * detail message. + */ + public IllegalAccessException() { + super(); + } + + /** + * Constructs an IllegalAccessException with a detail message. + * + * @param s the detail message. + */ + public IllegalAccessException(String s) { + super(s); + } +} diff -r 388e48c0a37a -r 05224402145d emul/mini/src/main/java/java/lang/IllegalArgumentException.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/emul/mini/src/main/java/java/lang/IllegalArgumentException.java Wed Jan 23 20:39:23 2013 +0100 @@ -0,0 +1,95 @@ +/* + * Copyright (c) 1994, 2003, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code 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 + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package java.lang; + +/** + * Thrown to indicate that a method has been passed an illegal or + * inappropriate argument. + * + * @author unascribed + * @see java.lang.Thread#setPriority(int) + * @since JDK1.0 + */ +public +class IllegalArgumentException extends RuntimeException { + /** + * Constructs an IllegalArgumentException with no + * detail message. + */ + public IllegalArgumentException() { + super(); + } + + /** + * Constructs an IllegalArgumentException with the + * specified detail message. + * + * @param s the detail message. + */ + public IllegalArgumentException(String s) { + super(s); + } + + /** + * Constructs a new exception with the specified detail message and + * cause. + * + *

Note that the detail message associated with cause is + * not automatically incorporated in this exception's detail + * message. + * + * @param message the detail message (which is saved for later retrieval + * by the {@link Throwable#getMessage()} method). + * @param cause the cause (which is saved for later retrieval by the + * {@link Throwable#getCause()} method). (A null value + * is permitted, and indicates that the cause is nonexistent or + * unknown.) + * @since 1.5 + */ + public IllegalArgumentException(String message, Throwable cause) { + super(message, cause); + } + + /** + * Constructs a new exception with the specified cause and a detail + * message of (cause==null ? null : cause.toString()) (which + * typically contains the class and detail message of cause). + * This constructor is useful for exceptions that are little more than + * wrappers for other throwables (for example, {@link + * java.security.PrivilegedActionException}). + * + * @param cause the cause (which is saved for later retrieval by the + * {@link Throwable#getCause()} method). (A null value is + * permitted, and indicates that the cause is nonexistent or + * unknown.) + * @since 1.5 + */ + public IllegalArgumentException(Throwable cause) { + super(cause); + } + + private static final long serialVersionUID = -5365630128856068164L; +} diff -r 388e48c0a37a -r 05224402145d emul/mini/src/main/java/java/lang/IllegalStateException.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/emul/mini/src/main/java/java/lang/IllegalStateException.java Wed Jan 23 20:39:23 2013 +0100 @@ -0,0 +1,97 @@ +/* + * Copyright (c) 1996, 2003, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code 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 + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package java.lang; + +/** + * Signals that a method has been invoked at an illegal or + * inappropriate time. In other words, the Java environment or + * Java application is not in an appropriate state for the requested + * operation. + * + * @author Jonni Kanerva + * @since JDK1.1 + */ +public +class IllegalStateException extends RuntimeException { + /** + * Constructs an IllegalStateException with no detail message. + * A detail message is a String that describes this particular exception. + */ + public IllegalStateException() { + super(); + } + + /** + * Constructs an IllegalStateException with the specified detail + * message. A detail message is a String that describes this particular + * exception. + * + * @param s the String that contains a detailed message + */ + public IllegalStateException(String s) { + super(s); + } + + /** + * Constructs a new exception with the specified detail message and + * cause. + * + *

Note that the detail message associated with cause is + * not automatically incorporated in this exception's detail + * message. + * + * @param message the detail message (which is saved for later retrieval + * by the {@link Throwable#getMessage()} method). + * @param cause the cause (which is saved for later retrieval by the + * {@link Throwable#getCause()} method). (A null value + * is permitted, and indicates that the cause is nonexistent or + * unknown.) + * @since 1.5 + */ + public IllegalStateException(String message, Throwable cause) { + super(message, cause); + } + + /** + * Constructs a new exception with the specified cause and a detail + * message of (cause==null ? null : cause.toString()) (which + * typically contains the class and detail message of cause). + * This constructor is useful for exceptions that are little more than + * wrappers for other throwables (for example, {@link + * java.security.PrivilegedActionException}). + * + * @param cause the cause (which is saved for later retrieval by the + * {@link Throwable#getCause()} method). (A null value is + * permitted, and indicates that the cause is nonexistent or + * unknown.) + * @since 1.5 + */ + public IllegalStateException(Throwable cause) { + super(cause); + } + + static final long serialVersionUID = -1848914673093119416L; +} diff -r 388e48c0a37a -r 05224402145d emul/mini/src/main/java/java/lang/IndexOutOfBoundsException.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/emul/mini/src/main/java/java/lang/IndexOutOfBoundsException.java Wed Jan 23 20:39:23 2013 +0100 @@ -0,0 +1,58 @@ +/* + * Copyright (c) 1995, 2008, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code 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 + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package java.lang; + +/** + * Thrown to indicate that an index of some sort (such as to an array, to a + * string, or to a vector) is out of range. + *

+ * Applications can subclass this class to indicate similar exceptions. + * + * @author Frank Yellin + * @since JDK1.0 + */ +public +class IndexOutOfBoundsException extends RuntimeException { + private static final long serialVersionUID = 234122996006267687L; + + /** + * Constructs an IndexOutOfBoundsException with no + * detail message. + */ + public IndexOutOfBoundsException() { + super(); + } + + /** + * Constructs an IndexOutOfBoundsException with the + * specified detail message. + * + * @param s the detail message. + */ + public IndexOutOfBoundsException(String s) { + super(s); + } +} diff -r 388e48c0a37a -r 05224402145d emul/mini/src/main/java/java/lang/InstantiationException.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/emul/mini/src/main/java/java/lang/InstantiationException.java Wed Jan 23 20:39:23 2013 +0100 @@ -0,0 +1,65 @@ +/* + * Copyright (c) 1995, 2008, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code 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 + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package java.lang; + +/** + * Thrown when an application tries to create an instance of a class + * using the {@code newInstance} method in class + * {@code Class}, but the specified class object cannot be + * instantiated. The instantiation can fail for a variety of + * reasons including but not limited to: + * + *

    + *
  • the class object represents an abstract class, an interface, + * an array class, a primitive type, or {@code void} + *
  • the class has no nullary constructor + *
+ * + * @author unascribed + * @see java.lang.Class#newInstance() + * @since JDK1.0 + */ +public +class InstantiationException extends ReflectiveOperationException { + private static final long serialVersionUID = -8441929162975509110L; + + /** + * Constructs an {@code InstantiationException} with no detail message. + */ + public InstantiationException() { + super(); + } + + /** + * Constructs an {@code InstantiationException} with the + * specified detail message. + * + * @param s the detail message. + */ + public InstantiationException(String s) { + super(s); + } +} diff -r 388e48c0a37a -r 05224402145d emul/mini/src/main/java/java/lang/Integer.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/emul/mini/src/main/java/java/lang/Integer.java Wed Jan 23 20:39:23 2013 +0100 @@ -0,0 +1,1246 @@ +/* + * Copyright (c) 1994, 2010, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code 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 + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package java.lang; + +import org.apidesign.bck2brwsr.core.JavaScriptBody; + +/** + * The {@code Integer} class wraps a value of the primitive type + * {@code int} in an object. An object of type {@code Integer} + * contains a single field whose type is {@code int}. + * + *

In addition, this class provides several methods for converting + * an {@code int} to a {@code String} and a {@code String} to an + * {@code int}, as well as other constants and methods useful when + * dealing with an {@code int}. + * + *

Implementation note: The implementations of the "bit twiddling" + * methods (such as {@link #highestOneBit(int) highestOneBit} and + * {@link #numberOfTrailingZeros(int) numberOfTrailingZeros}) are + * based on material from Henry S. Warren, Jr.'s Hacker's + * Delight, (Addison Wesley, 2002). + * + * @author Lee Boynton + * @author Arthur van Hoff + * @author Josh Bloch + * @author Joseph D. Darcy + * @since JDK1.0 + */ +public final class Integer extends Number implements Comparable { + /** + * A constant holding the minimum value an {@code int} can + * have, -231. + */ + public static final int MIN_VALUE = 0x80000000; + + /** + * A constant holding the maximum value an {@code int} can + * have, 231-1. + */ + public static final int MAX_VALUE = 0x7fffffff; + + /** + * The {@code Class} instance representing the primitive type + * {@code int}. + * + * @since JDK1.1 + */ + public static final Class TYPE = (Class) Class.getPrimitiveClass("int"); + + /** + * All possible chars for representing a number as a String + */ + final static char[] digits = { + '0' , '1' , '2' , '3' , '4' , '5' , + '6' , '7' , '8' , '9' , 'a' , 'b' , + 'c' , 'd' , 'e' , 'f' , 'g' , 'h' , + 'i' , 'j' , 'k' , 'l' , 'm' , 'n' , + 'o' , 'p' , 'q' , 'r' , 's' , 't' , + 'u' , 'v' , 'w' , 'x' , 'y' , 'z' + }; + + /** + * Returns a string representation of the first argument in the + * radix specified by the second argument. + * + *

If the radix is smaller than {@code Character.MIN_RADIX} + * or larger than {@code Character.MAX_RADIX}, then the radix + * {@code 10} is used instead. + * + *

If the first argument is negative, the first element of the + * result is the ASCII minus character {@code '-'} + * ('\u002D'). If the first argument is not + * negative, no sign character appears in the result. + * + *

The remaining characters of the result represent the magnitude + * of the first argument. If the magnitude is zero, it is + * represented by a single zero character {@code '0'} + * ('\u0030'); otherwise, the first character of + * the representation of the magnitude will not be the zero + * character. The following ASCII characters are used as digits: + * + *

+ * {@code 0123456789abcdefghijklmnopqrstuvwxyz} + *
+ * + * These are '\u0030' through + * '\u0039' and '\u0061' through + * '\u007A'. If {@code radix} is + * N, then the first N of these characters + * are used as radix-N digits in the order shown. Thus, + * the digits for hexadecimal (radix 16) are + * {@code 0123456789abcdef}. If uppercase letters are + * desired, the {@link java.lang.String#toUpperCase()} method may + * be called on the result: + * + *
+ * {@code Integer.toString(n, 16).toUpperCase()} + *
+ * + * @param i an integer to be converted to a string. + * @param radix the radix to use in the string representation. + * @return a string representation of the argument in the specified radix. + * @see java.lang.Character#MAX_RADIX + * @see java.lang.Character#MIN_RADIX + */ + public static String toString(int i, int radix) { + + if (radix < Character.MIN_RADIX || radix > Character.MAX_RADIX) + radix = 10; + + /* Use the faster version */ + if (radix == 10) { + return toString(i); + } + + char buf[] = new char[33]; + boolean negative = (i < 0); + int charPos = 32; + + if (!negative) { + i = -i; + } + + while (i <= -radix) { + buf[charPos--] = digits[-(i % radix)]; + i = i / radix; + } + buf[charPos] = digits[-i]; + + if (negative) { + buf[--charPos] = '-'; + } + + return new String(buf, charPos, (33 - charPos)); + } + + /** + * Returns a string representation of the integer argument as an + * unsigned integer in base 16. + * + *

The unsigned integer value is the argument plus 232 + * if the argument is negative; otherwise, it is equal to the + * argument. This value is converted to a string of ASCII digits + * in hexadecimal (base 16) with no extra leading + * {@code 0}s. If the unsigned magnitude is zero, it is + * represented by a single zero character {@code '0'} + * ('\u0030'); otherwise, the first character of + * the representation of the unsigned magnitude will not be the + * zero character. The following characters are used as + * hexadecimal digits: + * + *

+ * {@code 0123456789abcdef} + *
+ * + * These are the characters '\u0030' through + * '\u0039' and '\u0061' through + * '\u0066'. If uppercase letters are + * desired, the {@link java.lang.String#toUpperCase()} method may + * be called on the result: + * + *
+ * {@code Integer.toHexString(n).toUpperCase()} + *
+ * + * @param i an integer to be converted to a string. + * @return the string representation of the unsigned integer value + * represented by the argument in hexadecimal (base 16). + * @since JDK1.0.2 + */ + public static String toHexString(int i) { + return toUnsignedString(i, 4); + } + + /** + * Returns a string representation of the integer argument as an + * unsigned integer in base 8. + * + *

The unsigned integer value is the argument plus 232 + * if the argument is negative; otherwise, it is equal to the + * argument. This value is converted to a string of ASCII digits + * in octal (base 8) with no extra leading {@code 0}s. + * + *

If the unsigned magnitude is zero, it is represented by a + * single zero character {@code '0'} + * ('\u0030'); otherwise, the first character of + * the representation of the unsigned magnitude will not be the + * zero character. The following characters are used as octal + * digits: + * + *

+ * {@code 01234567} + *
+ * + * These are the characters '\u0030' through + * '\u0037'. + * + * @param i an integer to be converted to a string. + * @return the string representation of the unsigned integer value + * represented by the argument in octal (base 8). + * @since JDK1.0.2 + */ + public static String toOctalString(int i) { + return toUnsignedString(i, 3); + } + + /** + * Returns a string representation of the integer argument as an + * unsigned integer in base 2. + * + *

The unsigned integer value is the argument plus 232 + * if the argument is negative; otherwise it is equal to the + * argument. This value is converted to a string of ASCII digits + * in binary (base 2) with no extra leading {@code 0}s. + * If the unsigned magnitude is zero, it is represented by a + * single zero character {@code '0'} + * ('\u0030'); otherwise, the first character of + * the representation of the unsigned magnitude will not be the + * zero character. The characters {@code '0'} + * ('\u0030') and {@code '1'} + * ('\u0031') are used as binary digits. + * + * @param i an integer to be converted to a string. + * @return the string representation of the unsigned integer value + * represented by the argument in binary (base 2). + * @since JDK1.0.2 + */ + public static String toBinaryString(int i) { + return toUnsignedString(i, 1); + } + + /** + * Convert the integer to an unsigned number. + */ + private static String toUnsignedString(int i, int shift) { + char[] buf = new char[32]; + int charPos = 32; + int radix = 1 << shift; + int mask = radix - 1; + do { + buf[--charPos] = digits[i & mask]; + i >>>= shift; + } while (i != 0); + + return new String(buf, charPos, (32 - charPos)); + } + + + final static char [] DigitTens = { + '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', + '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', + '2', '2', '2', '2', '2', '2', '2', '2', '2', '2', + '3', '3', '3', '3', '3', '3', '3', '3', '3', '3', + '4', '4', '4', '4', '4', '4', '4', '4', '4', '4', + '5', '5', '5', '5', '5', '5', '5', '5', '5', '5', + '6', '6', '6', '6', '6', '6', '6', '6', '6', '6', + '7', '7', '7', '7', '7', '7', '7', '7', '7', '7', + '8', '8', '8', '8', '8', '8', '8', '8', '8', '8', + '9', '9', '9', '9', '9', '9', '9', '9', '9', '9', + } ; + + final static char [] DigitOnes = { + '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', + '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', + '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', + '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', + '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', + '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', + '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', + '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', + '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', + '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', + } ; + + // I use the "invariant division by multiplication" trick to + // accelerate Integer.toString. In particular we want to + // avoid division by 10. + // + // The "trick" has roughly the same performance characteristics + // as the "classic" Integer.toString code on a non-JIT VM. + // The trick avoids .rem and .div calls but has a longer code + // path and is thus dominated by dispatch overhead. In the + // JIT case the dispatch overhead doesn't exist and the + // "trick" is considerably faster than the classic code. + // + // TODO-FIXME: convert (x * 52429) into the equiv shift-add + // sequence. + // + // RE: Division by Invariant Integers using Multiplication + // T Gralund, P Montgomery + // ACM PLDI 1994 + // + + /** + * Returns a {@code String} object representing the + * specified integer. The argument is converted to signed decimal + * representation and returned as a string, exactly as if the + * argument and radix 10 were given as arguments to the {@link + * #toString(int, int)} method. + * + * @param i an integer to be converted. + * @return a string representation of the argument in base 10. + */ + @JavaScriptBody(args = "i", body = "return i.toString();") + public static String toString(int i) { + if (i == Integer.MIN_VALUE) + return "-2147483648"; + int size = (i < 0) ? stringSize(-i) + 1 : stringSize(i); + char[] buf = new char[size]; + getChars(i, size, buf); + return new String(buf, 0, size); + } + + /** + * Places characters representing the integer i into the + * character array buf. The characters are placed into + * the buffer backwards starting with the least significant + * digit at the specified index (exclusive), and working + * backwards from there. + * + * Will fail if i == Integer.MIN_VALUE + */ + static void getChars(int i, int index, char[] buf) { + int q, r; + int charPos = index; + char sign = 0; + + if (i < 0) { + sign = '-'; + i = -i; + } + + // Generate two digits per iteration + while (i >= 65536) { + q = i / 100; + // really: r = i - (q * 100); + r = i - ((q << 6) + (q << 5) + (q << 2)); + i = q; + buf [--charPos] = DigitOnes[r]; + buf [--charPos] = DigitTens[r]; + } + + // Fall thru to fast mode for smaller numbers + // assert(i <= 65536, i); + for (;;) { + q = (i * 52429) >>> (16+3); + r = i - ((q << 3) + (q << 1)); // r = i-(q*10) ... + buf [--charPos] = digits [r]; + i = q; + if (i == 0) break; + } + if (sign != 0) { + buf [--charPos] = sign; + } + } + + final static int [] sizeTable = { 9, 99, 999, 9999, 99999, 999999, 9999999, + 99999999, 999999999, Integer.MAX_VALUE }; + + // Requires positive x + static int stringSize(int x) { + for (int i=0; ; i++) + if (x <= sizeTable[i]) + return i+1; + } + + /** + * Parses the string argument as a signed integer in the radix + * specified by the second argument. The characters in the string + * must all be digits of the specified radix (as determined by + * whether {@link java.lang.Character#digit(char, int)} returns a + * nonnegative value), except that the first character may be an + * ASCII minus sign {@code '-'} ('\u002D') to + * indicate a negative value or an ASCII plus sign {@code '+'} + * ('\u002B') to indicate a positive value. The + * resulting integer value is returned. + * + *

An exception of type {@code NumberFormatException} is + * thrown if any of the following situations occurs: + *

    + *
  • The first argument is {@code null} or is a string of + * length zero. + * + *
  • The radix is either smaller than + * {@link java.lang.Character#MIN_RADIX} or + * larger than {@link java.lang.Character#MAX_RADIX}. + * + *
  • Any character of the string is not a digit of the specified + * radix, except that the first character may be a minus sign + * {@code '-'} ('\u002D') or plus sign + * {@code '+'} ('\u002B') provided that the + * string is longer than length 1. + * + *
  • The value represented by the string is not a value of type + * {@code int}. + *
+ * + *

Examples: + *

+     * parseInt("0", 10) returns 0
+     * parseInt("473", 10) returns 473
+     * parseInt("+42", 10) returns 42
+     * parseInt("-0", 10) returns 0
+     * parseInt("-FF", 16) returns -255
+     * parseInt("1100110", 2) returns 102
+     * parseInt("2147483647", 10) returns 2147483647
+     * parseInt("-2147483648", 10) returns -2147483648
+     * parseInt("2147483648", 10) throws a NumberFormatException
+     * parseInt("99", 8) throws a NumberFormatException
+     * parseInt("Kona", 10) throws a NumberFormatException
+     * parseInt("Kona", 27) returns 411787
+     * 
+ * + * @param s the {@code String} containing the integer + * representation to be parsed + * @param radix the radix to be used while parsing {@code s}. + * @return the integer represented by the string argument in the + * specified radix. + * @exception NumberFormatException if the {@code String} + * does not contain a parsable {@code int}. + */ + @JavaScriptBody(args={"s", "radix"}, body="return parseInt(s,radix);") + public static int parseInt(String s, int radix) + throws NumberFormatException + { + /* + * WARNING: This method may be invoked early during VM initialization + * before IntegerCache is initialized. Care must be taken to not use + * the valueOf method. + */ + + if (s == null) { + throw new NumberFormatException("null"); + } + + if (radix < Character.MIN_RADIX) { + throw new NumberFormatException("radix " + radix + + " less than Character.MIN_RADIX"); + } + + if (radix > Character.MAX_RADIX) { + throw new NumberFormatException("radix " + radix + + " greater than Character.MAX_RADIX"); + } + + int result = 0; + boolean negative = false; + int i = 0, len = s.length(); + int limit = -Integer.MAX_VALUE; + int multmin; + int digit; + + if (len > 0) { + char firstChar = s.charAt(0); + if (firstChar < '0') { // Possible leading "+" or "-" + if (firstChar == '-') { + negative = true; + limit = Integer.MIN_VALUE; + } else if (firstChar != '+') + throw NumberFormatException.forInputString(s); + + if (len == 1) // Cannot have lone "+" or "-" + throw NumberFormatException.forInputString(s); + i++; + } + multmin = limit / radix; + while (i < len) { + // Accumulating negatively avoids surprises near MAX_VALUE + digit = Character.digit(s.charAt(i++),radix); + if (digit < 0) { + throw NumberFormatException.forInputString(s); + } + if (result < multmin) { + throw NumberFormatException.forInputString(s); + } + result *= radix; + if (result < limit + digit) { + throw NumberFormatException.forInputString(s); + } + result -= digit; + } + } else { + throw NumberFormatException.forInputString(s); + } + return negative ? result : -result; + } + + /** + * Parses the string argument as a signed decimal integer. The + * characters in the string must all be decimal digits, except + * that the first character may be an ASCII minus sign {@code '-'} + * ('\u002D') to indicate a negative value or an + * ASCII plus sign {@code '+'} ('\u002B') to + * indicate a positive value. The resulting integer value is + * returned, exactly as if the argument and the radix 10 were + * given as arguments to the {@link #parseInt(java.lang.String, + * int)} method. + * + * @param s a {@code String} containing the {@code int} + * representation to be parsed + * @return the integer value represented by the argument in decimal. + * @exception NumberFormatException if the string does not contain a + * parsable integer. + */ + public static int parseInt(String s) throws NumberFormatException { + return parseInt(s,10); + } + + /** + * Returns an {@code Integer} object holding the value + * extracted from the specified {@code String} when parsed + * with the radix given by the second argument. The first argument + * is interpreted as representing a signed integer in the radix + * specified by the second argument, exactly as if the arguments + * were given to the {@link #parseInt(java.lang.String, int)} + * method. The result is an {@code Integer} object that + * represents the integer value specified by the string. + * + *

In other words, this method returns an {@code Integer} + * object equal to the value of: + * + *

+ * {@code new Integer(Integer.parseInt(s, radix))} + *
+ * + * @param s the string to be parsed. + * @param radix the radix to be used in interpreting {@code s} + * @return an {@code Integer} object holding the value + * represented by the string argument in the specified + * radix. + * @exception NumberFormatException if the {@code String} + * does not contain a parsable {@code int}. + */ + public static Integer valueOf(String s, int radix) throws NumberFormatException { + return Integer.valueOf(parseInt(s,radix)); + } + + /** + * Returns an {@code Integer} object holding the + * value of the specified {@code String}. The argument is + * interpreted as representing a signed decimal integer, exactly + * as if the argument were given to the {@link + * #parseInt(java.lang.String)} method. The result is an + * {@code Integer} object that represents the integer value + * specified by the string. + * + *

In other words, this method returns an {@code Integer} + * object equal to the value of: + * + *

+ * {@code new Integer(Integer.parseInt(s))} + *
+ * + * @param s the string to be parsed. + * @return an {@code Integer} object holding the value + * represented by the string argument. + * @exception NumberFormatException if the string cannot be parsed + * as an integer. + */ + public static Integer valueOf(String s) throws NumberFormatException { + return Integer.valueOf(parseInt(s, 10)); + } + + /** + * Cache to support the object identity semantics of autoboxing for values between + * -128 and 127 (inclusive) as required by JLS. + * + * The cache is initialized on first usage. The size of the cache + * may be controlled by the -XX:AutoBoxCacheMax= option. + * During VM initialization, java.lang.Integer.IntegerCache.high property + * may be set and saved in the private system properties in the + * sun.misc.VM class. + */ + + private static class IntegerCache { + static final int low = -128; + static final int high; + static final Integer cache[]; + + static { + // high value may be configured by property + int h = 127; + String integerCacheHighPropValue = + AbstractStringBuilder.getProperty("java.lang.Integer.IntegerCache.high"); + if (integerCacheHighPropValue != null) { + int i = parseInt(integerCacheHighPropValue); + i = Math.max(i, 127); + // Maximum array size is Integer.MAX_VALUE + h = Math.min(i, Integer.MAX_VALUE - (-low)); + } + high = h; + + cache = new Integer[(high - low) + 1]; + int j = low; + for(int k = 0; k < cache.length; k++) + cache[k] = new Integer(j++); + } + + private IntegerCache() {} + } + + /** + * Returns an {@code Integer} instance representing the specified + * {@code int} value. If a new {@code Integer} instance is not + * required, this method should generally be used in preference to + * the constructor {@link #Integer(int)}, as this method is likely + * to yield significantly better space and time performance by + * caching frequently requested values. + * + * This method will always cache values in the range -128 to 127, + * inclusive, and may cache other values outside of this range. + * + * @param i an {@code int} value. + * @return an {@code Integer} instance representing {@code i}. + * @since 1.5 + */ + public static Integer valueOf(int i) { + //assert IntegerCache.high >= 127; + if (i >= IntegerCache.low && i <= IntegerCache.high) + return IntegerCache.cache[i + (-IntegerCache.low)]; + return new Integer(i); + } + + /** + * The value of the {@code Integer}. + * + * @serial + */ + private final int value; + + /** + * Constructs a newly allocated {@code Integer} object that + * represents the specified {@code int} value. + * + * @param value the value to be represented by the + * {@code Integer} object. + */ + public Integer(int value) { + this.value = value; + } + + /** + * Constructs a newly allocated {@code Integer} object that + * represents the {@code int} value indicated by the + * {@code String} parameter. The string is converted to an + * {@code int} value in exactly the manner used by the + * {@code parseInt} method for radix 10. + * + * @param s the {@code String} to be converted to an + * {@code Integer}. + * @exception NumberFormatException if the {@code String} does not + * contain a parsable integer. + * @see java.lang.Integer#parseInt(java.lang.String, int) + */ + public Integer(String s) throws NumberFormatException { + this.value = parseInt(s, 10); + } + + /** + * Returns the value of this {@code Integer} as a + * {@code byte}. + */ + public byte byteValue() { + return (byte)value; + } + + /** + * Returns the value of this {@code Integer} as a + * {@code short}. + */ + public short shortValue() { + return (short)value; + } + + /** + * Returns the value of this {@code Integer} as an + * {@code int}. + */ + public int intValue() { + return value; + } + + /** + * Returns the value of this {@code Integer} as a + * {@code long}. + */ + public long longValue() { + return (long)value; + } + + /** + * Returns the value of this {@code Integer} as a + * {@code float}. + */ + public float floatValue() { + return (float)value; + } + + /** + * Returns the value of this {@code Integer} as a + * {@code double}. + */ + public double doubleValue() { + return (double)value; + } + + /** + * Returns a {@code String} object representing this + * {@code Integer}'s value. The value is converted to signed + * decimal representation and returned as a string, exactly as if + * the integer value were given as an argument to the {@link + * java.lang.Integer#toString(int)} method. + * + * @return a string representation of the value of this object in + * base 10. + */ + public String toString() { + return toString(value); + } + + /** + * Returns a hash code for this {@code Integer}. + * + * @return a hash code value for this object, equal to the + * primitive {@code int} value represented by this + * {@code Integer} object. + */ + public int hashCode() { + return value; + } + + /** + * Compares this object to the specified object. The result is + * {@code true} if and only if the argument is not + * {@code null} and is an {@code Integer} object that + * contains the same {@code int} value as this object. + * + * @param obj the object to compare with. + * @return {@code true} if the objects are the same; + * {@code false} otherwise. + */ + public boolean equals(Object obj) { + if (obj instanceof Integer) { + return value == ((Integer)obj).intValue(); + } + return false; + } + + /** + * Determines the integer value of the system property with the + * specified name. + * + *

The first argument is treated as the name of a system property. + * System properties are accessible through the + * {@link java.lang.System#getProperty(java.lang.String)} method. The + * string value of this property is then interpreted as an integer + * value and an {@code Integer} object representing this value is + * returned. Details of possible numeric formats can be found with + * the definition of {@code getProperty}. + * + *

If there is no property with the specified name, if the specified name + * is empty or {@code null}, or if the property does not have + * the correct numeric format, then {@code null} is returned. + * + *

In other words, this method returns an {@code Integer} + * object equal to the value of: + * + *

+ * {@code getInteger(nm, null)} + *
+ * + * @param nm property name. + * @return the {@code Integer} value of the property. + * @see java.lang.System#getProperty(java.lang.String) + * @see java.lang.System#getProperty(java.lang.String, java.lang.String) + */ + public static Integer getInteger(String nm) { + return getInteger(nm, null); + } + + /** + * Determines the integer value of the system property with the + * specified name. + * + *

The first argument is treated as the name of a system property. + * System properties are accessible through the {@link + * java.lang.System#getProperty(java.lang.String)} method. The + * string value of this property is then interpreted as an integer + * value and an {@code Integer} object representing this value is + * returned. Details of possible numeric formats can be found with + * the definition of {@code getProperty}. + * + *

The second argument is the default value. An {@code Integer} object + * that represents the value of the second argument is returned if there + * is no property of the specified name, if the property does not have + * the correct numeric format, or if the specified name is empty or + * {@code null}. + * + *

In other words, this method returns an {@code Integer} object + * equal to the value of: + * + *

+ * {@code getInteger(nm, new Integer(val))} + *
+ * + * but in practice it may be implemented in a manner such as: + * + *
+     * Integer result = getInteger(nm, null);
+     * return (result == null) ? new Integer(val) : result;
+     * 
+ * + * to avoid the unnecessary allocation of an {@code Integer} + * object when the default value is not needed. + * + * @param nm property name. + * @param val default value. + * @return the {@code Integer} value of the property. + * @see java.lang.System#getProperty(java.lang.String) + * @see java.lang.System#getProperty(java.lang.String, java.lang.String) + */ + public static Integer getInteger(String nm, int val) { + Integer result = getInteger(nm, null); + return (result == null) ? Integer.valueOf(val) : result; + } + + /** + * Returns the integer value of the system property with the + * specified name. The first argument is treated as the name of a + * system property. System properties are accessible through the + * {@link java.lang.System#getProperty(java.lang.String)} method. + * The string value of this property is then interpreted as an + * integer value, as per the {@code Integer.decode} method, + * and an {@code Integer} object representing this value is + * returned. + * + *
  • If the property value begins with the two ASCII characters + * {@code 0x} or the ASCII character {@code #}, not + * followed by a minus sign, then the rest of it is parsed as a + * hexadecimal integer exactly as by the method + * {@link #valueOf(java.lang.String, int)} with radix 16. + *
  • If the property value begins with the ASCII character + * {@code 0} followed by another character, it is parsed as an + * octal integer exactly as by the method + * {@link #valueOf(java.lang.String, int)} with radix 8. + *
  • Otherwise, the property value is parsed as a decimal integer + * exactly as by the method {@link #valueOf(java.lang.String, int)} + * with radix 10. + *
+ * + *

The second argument is the default value. The default value is + * returned if there is no property of the specified name, if the + * property does not have the correct numeric format, or if the + * specified name is empty or {@code null}. + * + * @param nm property name. + * @param val default value. + * @return the {@code Integer} value of the property. + * @see java.lang.System#getProperty(java.lang.String) + * @see java.lang.System#getProperty(java.lang.String, java.lang.String) + * @see java.lang.Integer#decode + */ + public static Integer getInteger(String nm, Integer val) { + String v = null; + try { + v = AbstractStringBuilder.getProperty(nm); + } catch (IllegalArgumentException e) { + } catch (NullPointerException e) { + } + if (v != null) { + try { + return Integer.decode(v); + } catch (NumberFormatException e) { + } + } + return val; + } + + /** + * Decodes a {@code String} into an {@code Integer}. + * Accepts decimal, hexadecimal, and octal numbers given + * by the following grammar: + * + *

+ *
+ *
DecodableString: + *
Signopt DecimalNumeral + *
Signopt {@code 0x} HexDigits + *
Signopt {@code 0X} HexDigits + *
Signopt {@code #} HexDigits + *
Signopt {@code 0} OctalDigits + *

+ *

Sign: + *
{@code -} + *
{@code +} + *
+ *
+ * + * DecimalNumeral, HexDigits, and OctalDigits + * are as defined in section 3.10.1 of + * The Java™ Language Specification, + * except that underscores are not accepted between digits. + * + *

The sequence of characters following an optional + * sign and/or radix specifier ("{@code 0x}", "{@code 0X}", + * "{@code #}", or leading zero) is parsed as by the {@code + * Integer.parseInt} method with the indicated radix (10, 16, or + * 8). This sequence of characters must represent a positive + * value or a {@link NumberFormatException} will be thrown. The + * result is negated if first character of the specified {@code + * String} is the minus sign. No whitespace characters are + * permitted in the {@code String}. + * + * @param nm the {@code String} to decode. + * @return an {@code Integer} object holding the {@code int} + * value represented by {@code nm} + * @exception NumberFormatException if the {@code String} does not + * contain a parsable integer. + * @see java.lang.Integer#parseInt(java.lang.String, int) + */ + public static Integer decode(String nm) throws NumberFormatException { + int radix = 10; + int index = 0; + boolean negative = false; + Integer result; + + if (nm.length() == 0) + throw new NumberFormatException("Zero length string"); + char firstChar = nm.charAt(0); + // Handle sign, if present + if (firstChar == '-') { + negative = true; + index++; + } else if (firstChar == '+') + index++; + + // Handle radix specifier, if present + if (nm.startsWith("0x", index) || nm.startsWith("0X", index)) { + index += 2; + radix = 16; + } + else if (nm.startsWith("#", index)) { + index ++; + radix = 16; + } + else if (nm.startsWith("0", index) && nm.length() > 1 + index) { + index ++; + radix = 8; + } + + if (nm.startsWith("-", index) || nm.startsWith("+", index)) + throw new NumberFormatException("Sign character in wrong position"); + + try { + result = Integer.valueOf(nm.substring(index), radix); + result = negative ? Integer.valueOf(-result.intValue()) : result; + } catch (NumberFormatException e) { + // If number is Integer.MIN_VALUE, we'll end up here. The next line + // handles this case, and causes any genuine format error to be + // rethrown. + String constant = negative ? ("-" + nm.substring(index)) + : nm.substring(index); + result = Integer.valueOf(constant, radix); + } + return result; + } + + /** + * Compares two {@code Integer} objects numerically. + * + * @param anotherInteger the {@code Integer} to be compared. + * @return the value {@code 0} if this {@code Integer} is + * equal to the argument {@code Integer}; a value less than + * {@code 0} if this {@code Integer} is numerically less + * than the argument {@code Integer}; and a value greater + * than {@code 0} if this {@code Integer} is numerically + * greater than the argument {@code Integer} (signed + * comparison). + * @since 1.2 + */ + public int compareTo(Integer anotherInteger) { + return compare(this.value, anotherInteger.value); + } + + /** + * Compares two {@code int} values numerically. + * The value returned is identical to what would be returned by: + *

+     *    Integer.valueOf(x).compareTo(Integer.valueOf(y))
+     * 
+ * + * @param x the first {@code int} to compare + * @param y the second {@code int} to compare + * @return the value {@code 0} if {@code x == y}; + * a value less than {@code 0} if {@code x < y}; and + * a value greater than {@code 0} if {@code x > y} + * @since 1.7 + */ + public static int compare(int x, int y) { + return (x < y) ? -1 : ((x == y) ? 0 : 1); + } + + + // Bit twiddling + + /** + * The number of bits used to represent an {@code int} value in two's + * complement binary form. + * + * @since 1.5 + */ + public static final int SIZE = 32; + + /** + * Returns an {@code int} value with at most a single one-bit, in the + * position of the highest-order ("leftmost") one-bit in the specified + * {@code int} value. Returns zero if the specified value has no + * one-bits in its two's complement binary representation, that is, if it + * is equal to zero. + * + * @return an {@code int} value with a single one-bit, in the position + * of the highest-order one-bit in the specified value, or zero if + * the specified value is itself equal to zero. + * @since 1.5 + */ + public static int highestOneBit(int i) { + // HD, Figure 3-1 + i |= (i >> 1); + i |= (i >> 2); + i |= (i >> 4); + i |= (i >> 8); + i |= (i >> 16); + return i - (i >>> 1); + } + + /** + * Returns an {@code int} value with at most a single one-bit, in the + * position of the lowest-order ("rightmost") one-bit in the specified + * {@code int} value. Returns zero if the specified value has no + * one-bits in its two's complement binary representation, that is, if it + * is equal to zero. + * + * @return an {@code int} value with a single one-bit, in the position + * of the lowest-order one-bit in the specified value, or zero if + * the specified value is itself equal to zero. + * @since 1.5 + */ + public static int lowestOneBit(int i) { + // HD, Section 2-1 + return i & -i; + } + + /** + * Returns the number of zero bits preceding the highest-order + * ("leftmost") one-bit in the two's complement binary representation + * of the specified {@code int} value. Returns 32 if the + * specified value has no one-bits in its two's complement representation, + * in other words if it is equal to zero. + * + *

Note that this method is closely related to the logarithm base 2. + * For all positive {@code int} values x: + *

    + *
  • floor(log2(x)) = {@code 31 - numberOfLeadingZeros(x)} + *
  • ceil(log2(x)) = {@code 32 - numberOfLeadingZeros(x - 1)} + *
+ * + * @return the number of zero bits preceding the highest-order + * ("leftmost") one-bit in the two's complement binary representation + * of the specified {@code int} value, or 32 if the value + * is equal to zero. + * @since 1.5 + */ + public static int numberOfLeadingZeros(int i) { + // HD, Figure 5-6 + if (i == 0) + return 32; + int n = 1; + if (i >>> 16 == 0) { n += 16; i <<= 16; } + if (i >>> 24 == 0) { n += 8; i <<= 8; } + if (i >>> 28 == 0) { n += 4; i <<= 4; } + if (i >>> 30 == 0) { n += 2; i <<= 2; } + n -= i >>> 31; + return n; + } + + /** + * Returns the number of zero bits following the lowest-order ("rightmost") + * one-bit in the two's complement binary representation of the specified + * {@code int} value. Returns 32 if the specified value has no + * one-bits in its two's complement representation, in other words if it is + * equal to zero. + * + * @return the number of zero bits following the lowest-order ("rightmost") + * one-bit in the two's complement binary representation of the + * specified {@code int} value, or 32 if the value is equal + * to zero. + * @since 1.5 + */ + public static int numberOfTrailingZeros(int i) { + // HD, Figure 5-14 + int y; + if (i == 0) return 32; + int n = 31; + y = i <<16; if (y != 0) { n = n -16; i = y; } + y = i << 8; if (y != 0) { n = n - 8; i = y; } + y = i << 4; if (y != 0) { n = n - 4; i = y; } + y = i << 2; if (y != 0) { n = n - 2; i = y; } + return n - ((i << 1) >>> 31); + } + + /** + * Returns the number of one-bits in the two's complement binary + * representation of the specified {@code int} value. This function is + * sometimes referred to as the population count. + * + * @return the number of one-bits in the two's complement binary + * representation of the specified {@code int} value. + * @since 1.5 + */ + public static int bitCount(int i) { + // HD, Figure 5-2 + i = i - ((i >>> 1) & 0x55555555); + i = (i & 0x33333333) + ((i >>> 2) & 0x33333333); + i = (i + (i >>> 4)) & 0x0f0f0f0f; + i = i + (i >>> 8); + i = i + (i >>> 16); + return i & 0x3f; + } + + /** + * Returns the value obtained by rotating the two's complement binary + * representation of the specified {@code int} value left by the + * specified number of bits. (Bits shifted out of the left hand, or + * high-order, side reenter on the right, or low-order.) + * + *

Note that left rotation with a negative distance is equivalent to + * right rotation: {@code rotateLeft(val, -distance) == rotateRight(val, + * distance)}. Note also that rotation by any multiple of 32 is a + * no-op, so all but the last five bits of the rotation distance can be + * ignored, even if the distance is negative: {@code rotateLeft(val, + * distance) == rotateLeft(val, distance & 0x1F)}. + * + * @return the value obtained by rotating the two's complement binary + * representation of the specified {@code int} value left by the + * specified number of bits. + * @since 1.5 + */ + public static int rotateLeft(int i, int distance) { + return (i << distance) | (i >>> -distance); + } + + /** + * Returns the value obtained by rotating the two's complement binary + * representation of the specified {@code int} value right by the + * specified number of bits. (Bits shifted out of the right hand, or + * low-order, side reenter on the left, or high-order.) + * + *

Note that right rotation with a negative distance is equivalent to + * left rotation: {@code rotateRight(val, -distance) == rotateLeft(val, + * distance)}. Note also that rotation by any multiple of 32 is a + * no-op, so all but the last five bits of the rotation distance can be + * ignored, even if the distance is negative: {@code rotateRight(val, + * distance) == rotateRight(val, distance & 0x1F)}. + * + * @return the value obtained by rotating the two's complement binary + * representation of the specified {@code int} value right by the + * specified number of bits. + * @since 1.5 + */ + public static int rotateRight(int i, int distance) { + return (i >>> distance) | (i << -distance); + } + + /** + * Returns the value obtained by reversing the order of the bits in the + * two's complement binary representation of the specified {@code int} + * value. + * + * @return the value obtained by reversing order of the bits in the + * specified {@code int} value. + * @since 1.5 + */ + public static int reverse(int i) { + // HD, Figure 7-1 + i = (i & 0x55555555) << 1 | (i >>> 1) & 0x55555555; + i = (i & 0x33333333) << 2 | (i >>> 2) & 0x33333333; + i = (i & 0x0f0f0f0f) << 4 | (i >>> 4) & 0x0f0f0f0f; + i = (i << 24) | ((i & 0xff00) << 8) | + ((i >>> 8) & 0xff00) | (i >>> 24); + return i; + } + + /** + * Returns the signum function of the specified {@code int} value. (The + * return value is -1 if the specified value is negative; 0 if the + * specified value is zero; and 1 if the specified value is positive.) + * + * @return the signum function of the specified {@code int} value. + * @since 1.5 + */ + public static int signum(int i) { + // HD, Section 2-7 + return (i >> 31) | (-i >>> 31); + } + + /** + * Returns the value obtained by reversing the order of the bytes in the + * two's complement representation of the specified {@code int} value. + * + * @return the value obtained by reversing the bytes in the specified + * {@code int} value. + * @since 1.5 + */ + public static int reverseBytes(int i) { + return ((i >>> 24) ) | + ((i >> 8) & 0xFF00) | + ((i << 8) & 0xFF0000) | + ((i << 24)); + } + + /** use serialVersionUID from JDK 1.0.2 for interoperability */ + private static final long serialVersionUID = 1360826667806852920L; +} diff -r 388e48c0a37a -r 05224402145d emul/mini/src/main/java/java/lang/InterruptedException.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/emul/mini/src/main/java/java/lang/InterruptedException.java Wed Jan 23 20:39:23 2013 +0100 @@ -0,0 +1,69 @@ +/* + * Copyright (c) 1995, 2008, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code 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 + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package java.lang; + +/** + * Thrown when a thread is waiting, sleeping, or otherwise occupied, + * and the thread is interrupted, either before or during the activity. + * Occasionally a method may wish to test whether the current + * thread has been interrupted, and if so, to immediately throw + * this exception. The following code can be used to achieve + * this effect: + *

+ *  if (Thread.interrupted())  // Clears interrupted status!
+ *      throw new InterruptedException();
+ * 
+ * + * @author Frank Yellin + * @see java.lang.Object#wait() + * @see java.lang.Object#wait(long) + * @see java.lang.Object#wait(long, int) + * @see java.lang.Thread#sleep(long) + * @see java.lang.Thread#interrupt() + * @see java.lang.Thread#interrupted() + * @since JDK1.0 + */ +public +class InterruptedException extends Exception { + private static final long serialVersionUID = 6700697376100628473L; + + /** + * Constructs an InterruptedException with no detail message. + */ + public InterruptedException() { + super(); + } + + /** + * Constructs an InterruptedException with the + * specified detail message. + * + * @param s the detail message. + */ + public InterruptedException(String s) { + super(s); + } +} diff -r 388e48c0a37a -r 05224402145d emul/mini/src/main/java/java/lang/LinkageError.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/emul/mini/src/main/java/java/lang/LinkageError.java Wed Jan 23 20:39:23 2013 +0100 @@ -0,0 +1,69 @@ +/* + * Copyright (c) 1995, 2010, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code 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 + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package java.lang; + +/** + * Subclasses of {@code LinkageError} indicate that a class has + * some dependency on another class; however, the latter class has + * incompatibly changed after the compilation of the former class. + * + * + * @author Frank Yellin + * @since JDK1.0 + */ +public +class LinkageError extends Error { + private static final long serialVersionUID = 3579600108157160122L; + + /** + * Constructs a {@code LinkageError} with no detail message. + */ + public LinkageError() { + super(); + } + + /** + * Constructs a {@code LinkageError} with the specified detail + * message. + * + * @param s the detail message. + */ + public LinkageError(String s) { + super(s); + } + + /** + * Constructs a {@code LinkageError} with the specified detail + * message and cause. + * + * @param s the detail message. + * @param cause the cause, may be {@code null} + * @since 1.7 + */ + public LinkageError(String s, Throwable cause) { + super(s, cause); + } +} diff -r 388e48c0a37a -r 05224402145d emul/mini/src/main/java/java/lang/Long.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/emul/mini/src/main/java/java/lang/Long.java Wed Jan 23 20:39:23 2013 +0100 @@ -0,0 +1,1202 @@ +/* + * Copyright (c) 1994, 2009, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code 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 + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package java.lang; + +import org.apidesign.bck2brwsr.core.JavaScriptBody; + +/** + * The {@code Long} class wraps a value of the primitive type {@code + * long} in an object. An object of type {@code Long} contains a + * single field whose type is {@code long}. + * + *

In addition, this class provides several methods for converting + * a {@code long} to a {@code String} and a {@code String} to a {@code + * long}, as well as other constants and methods useful when dealing + * with a {@code long}. + * + *

Implementation note: The implementations of the "bit twiddling" + * methods (such as {@link #highestOneBit(long) highestOneBit} and + * {@link #numberOfTrailingZeros(long) numberOfTrailingZeros}) are + * based on material from Henry S. Warren, Jr.'s Hacker's + * Delight, (Addison Wesley, 2002). + * + * @author Lee Boynton + * @author Arthur van Hoff + * @author Josh Bloch + * @author Joseph D. Darcy + * @since JDK1.0 + */ +public final class Long extends Number implements Comparable { + /** + * A constant holding the minimum value a {@code long} can + * have, -263. + */ + public static final long MIN_VALUE = 0x8000000000000000L; + + /** + * A constant holding the maximum value a {@code long} can + * have, 263-1. + */ + public static final long MAX_VALUE = 0x7fffffffffffffffL; + + /** + * The {@code Class} instance representing the primitive type + * {@code long}. + * + * @since JDK1.1 + */ + public static final Class TYPE = (Class) Class.getPrimitiveClass("long"); + + /** + * Returns a string representation of the first argument in the + * radix specified by the second argument. + * + *

If the radix is smaller than {@code Character.MIN_RADIX} + * or larger than {@code Character.MAX_RADIX}, then the radix + * {@code 10} is used instead. + * + *

If the first argument is negative, the first element of the + * result is the ASCII minus sign {@code '-'} + * ('\u002d'). If the first argument is not + * negative, no sign character appears in the result. + * + *

The remaining characters of the result represent the magnitude + * of the first argument. If the magnitude is zero, it is + * represented by a single zero character {@code '0'} + * ('\u0030'); otherwise, the first character of + * the representation of the magnitude will not be the zero + * character. The following ASCII characters are used as digits: + * + *

+ * {@code 0123456789abcdefghijklmnopqrstuvwxyz} + *
+ * + * These are '\u0030' through + * '\u0039' and '\u0061' through + * '\u007a'. If {@code radix} is + * N, then the first N of these characters + * are used as radix-N digits in the order shown. Thus, + * the digits for hexadecimal (radix 16) are + * {@code 0123456789abcdef}. If uppercase letters are + * desired, the {@link java.lang.String#toUpperCase()} method may + * be called on the result: + * + *
+ * {@code Long.toString(n, 16).toUpperCase()} + *
+ * + * @param i a {@code long} to be converted to a string. + * @param radix the radix to use in the string representation. + * @return a string representation of the argument in the specified radix. + * @see java.lang.Character#MAX_RADIX + * @see java.lang.Character#MIN_RADIX + */ + public static String toString(long i, int radix) { + if (radix < Character.MIN_RADIX || radix > Character.MAX_RADIX) + radix = 10; + if (radix == 10) + return toString(i); + char[] buf = new char[65]; + int charPos = 64; + boolean negative = (i < 0); + + if (!negative) { + i = -i; + } + + while (i <= -radix) { + buf[charPos--] = Integer.digits[(int)(-(i % radix))]; + i = i / radix; + } + buf[charPos] = Integer.digits[(int)(-i)]; + + if (negative) { + buf[--charPos] = '-'; + } + + return new String(buf, charPos, (65 - charPos)); + } + + /** + * Returns a string representation of the {@code long} + * argument as an unsigned integer in base 16. + * + *

The unsigned {@code long} value is the argument plus + * 264 if the argument is negative; otherwise, it is + * equal to the argument. This value is converted to a string of + * ASCII digits in hexadecimal (base 16) with no extra + * leading {@code 0}s. If the unsigned magnitude is zero, it + * is represented by a single zero character {@code '0'} + * ('\u0030'); otherwise, the first character of + * the representation of the unsigned magnitude will not be the + * zero character. The following characters are used as + * hexadecimal digits: + * + *

+ * {@code 0123456789abcdef} + *
+ * + * These are the characters '\u0030' through + * '\u0039' and '\u0061' through + * '\u0066'. If uppercase letters are desired, + * the {@link java.lang.String#toUpperCase()} method may be called + * on the result: + * + *
+ * {@code Long.toHexString(n).toUpperCase()} + *
+ * + * @param i a {@code long} to be converted to a string. + * @return the string representation of the unsigned {@code long} + * value represented by the argument in hexadecimal + * (base 16). + * @since JDK 1.0.2 + */ + public static String toHexString(long i) { + return toUnsignedString(i, 4); + } + + /** + * Returns a string representation of the {@code long} + * argument as an unsigned integer in base 8. + * + *

The unsigned {@code long} value is the argument plus + * 264 if the argument is negative; otherwise, it is + * equal to the argument. This value is converted to a string of + * ASCII digits in octal (base 8) with no extra leading + * {@code 0}s. + * + *

If the unsigned magnitude is zero, it is represented by a + * single zero character {@code '0'} + * ('\u0030'); otherwise, the first character of + * the representation of the unsigned magnitude will not be the + * zero character. The following characters are used as octal + * digits: + * + *

+ * {@code 01234567} + *
+ * + * These are the characters '\u0030' through + * '\u0037'. + * + * @param i a {@code long} to be converted to a string. + * @return the string representation of the unsigned {@code long} + * value represented by the argument in octal (base 8). + * @since JDK 1.0.2 + */ + public static String toOctalString(long i) { + return toUnsignedString(i, 3); + } + + /** + * Returns a string representation of the {@code long} + * argument as an unsigned integer in base 2. + * + *

The unsigned {@code long} value is the argument plus + * 264 if the argument is negative; otherwise, it is + * equal to the argument. This value is converted to a string of + * ASCII digits in binary (base 2) with no extra leading + * {@code 0}s. If the unsigned magnitude is zero, it is + * represented by a single zero character {@code '0'} + * ('\u0030'); otherwise, the first character of + * the representation of the unsigned magnitude will not be the + * zero character. The characters {@code '0'} + * ('\u0030') and {@code '1'} + * ('\u0031') are used as binary digits. + * + * @param i a {@code long} to be converted to a string. + * @return the string representation of the unsigned {@code long} + * value represented by the argument in binary (base 2). + * @since JDK 1.0.2 + */ + public static String toBinaryString(long i) { + return toUnsignedString(i, 1); + } + + /** + * Convert the integer to an unsigned number. + */ + private static String toUnsignedString(long i, int shift) { + char[] buf = new char[64]; + int charPos = 64; + int radix = 1 << shift; + long mask = radix - 1; + do { + buf[--charPos] = Integer.digits[(int)(i & mask)]; + i >>>= shift; + } while (i != 0); + return new String(buf, charPos, (64 - charPos)); + } + + /** + * Returns a {@code String} object representing the specified + * {@code long}. The argument is converted to signed decimal + * representation and returned as a string, exactly as if the + * argument and the radix 10 were given as arguments to the {@link + * #toString(long, int)} method. + * + * @param i a {@code long} to be converted. + * @return a string representation of the argument in base 10. + */ + @JavaScriptBody(args = "i", body = "return i.toString();") + public static String toString(long i) { + if (i == Long.MIN_VALUE) + return "-9223372036854775808"; + int size = (i < 0) ? stringSize(-i) + 1 : stringSize(i); + char[] buf = new char[size]; + getChars(i, size, buf); + return new String(buf, 0, size); + } + + /** + * Places characters representing the integer i into the + * character array buf. The characters are placed into + * the buffer backwards starting with the least significant + * digit at the specified index (exclusive), and working + * backwards from there. + * + * Will fail if i == Long.MIN_VALUE + */ + static void getChars(long i, int index, char[] buf) { + long q; + int r; + int charPos = index; + char sign = 0; + + if (i < 0) { + sign = '-'; + i = -i; + } + + // Get 2 digits/iteration using longs until quotient fits into an int + while (i > Integer.MAX_VALUE) { + q = i / 100; + // really: r = i - (q * 100); + r = (int)(i - ((q << 6) + (q << 5) + (q << 2))); + i = q; + buf[--charPos] = Integer.DigitOnes[r]; + buf[--charPos] = Integer.DigitTens[r]; + } + + // Get 2 digits/iteration using ints + int q2; + int i2 = (int)i; + while (i2 >= 65536) { + q2 = i2 / 100; + // really: r = i2 - (q * 100); + r = i2 - ((q2 << 6) + (q2 << 5) + (q2 << 2)); + i2 = q2; + buf[--charPos] = Integer.DigitOnes[r]; + buf[--charPos] = Integer.DigitTens[r]; + } + + // Fall thru to fast mode for smaller numbers + // assert(i2 <= 65536, i2); + for (;;) { + q2 = (i2 * 52429) >>> (16+3); + r = i2 - ((q2 << 3) + (q2 << 1)); // r = i2-(q2*10) ... + buf[--charPos] = Integer.digits[r]; + i2 = q2; + if (i2 == 0) break; + } + if (sign != 0) { + buf[--charPos] = sign; + } + } + + // Requires positive x + static int stringSize(long x) { + long p = 10; + for (int i=1; i<19; i++) { + if (x < p) + return i; + p = 10*p; + } + return 19; + } + + /** + * Parses the string argument as a signed {@code long} in the + * radix specified by the second argument. The characters in the + * string must all be digits of the specified radix (as determined + * by whether {@link java.lang.Character#digit(char, int)} returns + * a nonnegative value), except that the first character may be an + * ASCII minus sign {@code '-'} ('\u002D') to + * indicate a negative value or an ASCII plus sign {@code '+'} + * ('\u002B') to indicate a positive value. The + * resulting {@code long} value is returned. + * + *

Note that neither the character {@code L} + * ('\u004C') nor {@code l} + * ('\u006C') is permitted to appear at the end + * of the string as a type indicator, as would be permitted in + * Java programming language source code - except that either + * {@code L} or {@code l} may appear as a digit for a + * radix greater than 22. + * + *

An exception of type {@code NumberFormatException} is + * thrown if any of the following situations occurs: + *

    + * + *
  • The first argument is {@code null} or is a string of + * length zero. + * + *
  • The {@code radix} is either smaller than {@link + * java.lang.Character#MIN_RADIX} or larger than {@link + * java.lang.Character#MAX_RADIX}. + * + *
  • Any character of the string is not a digit of the specified + * radix, except that the first character may be a minus sign + * {@code '-'} ('\u002d') or plus sign {@code + * '+'} ('\u002B') provided that the string is + * longer than length 1. + * + *
  • The value represented by the string is not a value of type + * {@code long}. + *
+ * + *

Examples: + *

+     * parseLong("0", 10) returns 0L
+     * parseLong("473", 10) returns 473L
+     * parseLong("+42", 10) returns 42L
+     * parseLong("-0", 10) returns 0L
+     * parseLong("-FF", 16) returns -255L
+     * parseLong("1100110", 2) returns 102L
+     * parseLong("99", 8) throws a NumberFormatException
+     * parseLong("Hazelnut", 10) throws a NumberFormatException
+     * parseLong("Hazelnut", 36) returns 1356099454469L
+     * 
+ * + * @param s the {@code String} containing the + * {@code long} representation to be parsed. + * @param radix the radix to be used while parsing {@code s}. + * @return the {@code long} represented by the string argument in + * the specified radix. + * @throws NumberFormatException if the string does not contain a + * parsable {@code long}. + */ + public static long parseLong(String s, int radix) + throws NumberFormatException + { + if (s == null) { + throw new NumberFormatException("null"); + } + + if (radix < Character.MIN_RADIX) { + throw new NumberFormatException("radix " + radix + + " less than Character.MIN_RADIX"); + } + if (radix > Character.MAX_RADIX) { + throw new NumberFormatException("radix " + radix + + " greater than Character.MAX_RADIX"); + } + + long result = 0; + boolean negative = false; + int i = 0, len = s.length(); + long limit = -Long.MAX_VALUE; + long multmin; + int digit; + + if (len > 0) { + char firstChar = s.charAt(0); + if (firstChar < '0') { // Possible leading "+" or "-" + if (firstChar == '-') { + negative = true; + limit = Long.MIN_VALUE; + } else if (firstChar != '+') + throw NumberFormatException.forInputString(s); + + if (len == 1) // Cannot have lone "+" or "-" + throw NumberFormatException.forInputString(s); + i++; + } + multmin = limit / radix; + while (i < len) { + // Accumulating negatively avoids surprises near MAX_VALUE + digit = Character.digit(s.charAt(i++),radix); + if (digit < 0) { + throw NumberFormatException.forInputString(s); + } + if (result < multmin) { + throw NumberFormatException.forInputString(s); + } + result *= radix; + if (result < limit + digit) { + throw NumberFormatException.forInputString(s); + } + result -= digit; + } + } else { + throw NumberFormatException.forInputString(s); + } + return negative ? result : -result; + } + + /** + * Parses the string argument as a signed decimal {@code long}. + * The characters in the string must all be decimal digits, except + * that the first character may be an ASCII minus sign {@code '-'} + * (\u002D') to indicate a negative value or an + * ASCII plus sign {@code '+'} ('\u002B') to + * indicate a positive value. The resulting {@code long} value is + * returned, exactly as if the argument and the radix {@code 10} + * were given as arguments to the {@link + * #parseLong(java.lang.String, int)} method. + * + *

Note that neither the character {@code L} + * ('\u004C') nor {@code l} + * ('\u006C') is permitted to appear at the end + * of the string as a type indicator, as would be permitted in + * Java programming language source code. + * + * @param s a {@code String} containing the {@code long} + * representation to be parsed + * @return the {@code long} represented by the argument in + * decimal. + * @throws NumberFormatException if the string does not contain a + * parsable {@code long}. + */ + public static long parseLong(String s) throws NumberFormatException { + return parseLong(s, 10); + } + + /** + * Returns a {@code Long} object holding the value + * extracted from the specified {@code String} when parsed + * with the radix given by the second argument. The first + * argument is interpreted as representing a signed + * {@code long} in the radix specified by the second + * argument, exactly as if the arguments were given to the {@link + * #parseLong(java.lang.String, int)} method. The result is a + * {@code Long} object that represents the {@code long} + * value specified by the string. + * + *

In other words, this method returns a {@code Long} object equal + * to the value of: + * + *

+ * {@code new Long(Long.parseLong(s, radix))} + *
+ * + * @param s the string to be parsed + * @param radix the radix to be used in interpreting {@code s} + * @return a {@code Long} object holding the value + * represented by the string argument in the specified + * radix. + * @throws NumberFormatException If the {@code String} does not + * contain a parsable {@code long}. + */ + public static Long valueOf(String s, int radix) throws NumberFormatException { + return Long.valueOf(parseLong(s, radix)); + } + + /** + * Returns a {@code Long} object holding the value + * of the specified {@code String}. The argument is + * interpreted as representing a signed decimal {@code long}, + * exactly as if the argument were given to the {@link + * #parseLong(java.lang.String)} method. The result is a + * {@code Long} object that represents the integer value + * specified by the string. + * + *

In other words, this method returns a {@code Long} object + * equal to the value of: + * + *

+ * {@code new Long(Long.parseLong(s))} + *
+ * + * @param s the string to be parsed. + * @return a {@code Long} object holding the value + * represented by the string argument. + * @throws NumberFormatException If the string cannot be parsed + * as a {@code long}. + */ + public static Long valueOf(String s) throws NumberFormatException + { + return Long.valueOf(parseLong(s, 10)); + } + + private static class LongCache { + private LongCache(){} + + static final Long cache[] = new Long[-(-128) + 127 + 1]; + + static { + for(int i = 0; i < cache.length; i++) + cache[i] = new Long(i - 128); + } + } + + /** + * Returns a {@code Long} instance representing the specified + * {@code long} value. + * If a new {@code Long} instance is not required, this method + * should generally be used in preference to the constructor + * {@link #Long(long)}, as this method is likely to yield + * significantly better space and time performance by caching + * frequently requested values. + * + * Note that unlike the {@linkplain Integer#valueOf(int) + * corresponding method} in the {@code Integer} class, this method + * is not required to cache values within a particular + * range. + * + * @param l a long value. + * @return a {@code Long} instance representing {@code l}. + * @since 1.5 + */ + public static Long valueOf(long l) { + final int offset = 128; + if (l >= -128 && l <= 127) { // will cache + return LongCache.cache[(int)l + offset]; + } + return new Long(l); + } + + /** + * Decodes a {@code String} into a {@code Long}. + * Accepts decimal, hexadecimal, and octal numbers given by the + * following grammar: + * + *
+ *
+ *
DecodableString: + *
Signopt DecimalNumeral + *
Signopt {@code 0x} HexDigits + *
Signopt {@code 0X} HexDigits + *
Signopt {@code #} HexDigits + *
Signopt {@code 0} OctalDigits + *

+ *

Sign: + *
{@code -} + *
{@code +} + *
+ *
+ * + * DecimalNumeral, HexDigits, and OctalDigits + * are as defined in section 3.10.1 of + * The Java™ Language Specification, + * except that underscores are not accepted between digits. + * + *

The sequence of characters following an optional + * sign and/or radix specifier ("{@code 0x}", "{@code 0X}", + * "{@code #}", or leading zero) is parsed as by the {@code + * Long.parseLong} method with the indicated radix (10, 16, or 8). + * This sequence of characters must represent a positive value or + * a {@link NumberFormatException} will be thrown. The result is + * negated if first character of the specified {@code String} is + * the minus sign. No whitespace characters are permitted in the + * {@code String}. + * + * @param nm the {@code String} to decode. + * @return a {@code Long} object holding the {@code long} + * value represented by {@code nm} + * @throws NumberFormatException if the {@code String} does not + * contain a parsable {@code long}. + * @see java.lang.Long#parseLong(String, int) + * @since 1.2 + */ + public static Long decode(String nm) throws NumberFormatException { + int radix = 10; + int index = 0; + boolean negative = false; + Long result; + + if (nm.length() == 0) + throw new NumberFormatException("Zero length string"); + char firstChar = nm.charAt(0); + // Handle sign, if present + if (firstChar == '-') { + negative = true; + index++; + } else if (firstChar == '+') + index++; + + // Handle radix specifier, if present + if (nm.startsWith("0x", index) || nm.startsWith("0X", index)) { + index += 2; + radix = 16; + } + else if (nm.startsWith("#", index)) { + index ++; + radix = 16; + } + else if (nm.startsWith("0", index) && nm.length() > 1 + index) { + index ++; + radix = 8; + } + + if (nm.startsWith("-", index) || nm.startsWith("+", index)) + throw new NumberFormatException("Sign character in wrong position"); + + try { + result = Long.valueOf(nm.substring(index), radix); + result = negative ? Long.valueOf(-result.longValue()) : result; + } catch (NumberFormatException e) { + // If number is Long.MIN_VALUE, we'll end up here. The next line + // handles this case, and causes any genuine format error to be + // rethrown. + String constant = negative ? ("-" + nm.substring(index)) + : nm.substring(index); + result = Long.valueOf(constant, radix); + } + return result; + } + + /** + * The value of the {@code Long}. + * + * @serial + */ + private final long value; + + /** + * Constructs a newly allocated {@code Long} object that + * represents the specified {@code long} argument. + * + * @param value the value to be represented by the + * {@code Long} object. + */ + public Long(long value) { + this.value = value; + } + + /** + * Constructs a newly allocated {@code Long} object that + * represents the {@code long} value indicated by the + * {@code String} parameter. The string is converted to a + * {@code long} value in exactly the manner used by the + * {@code parseLong} method for radix 10. + * + * @param s the {@code String} to be converted to a + * {@code Long}. + * @throws NumberFormatException if the {@code String} does not + * contain a parsable {@code long}. + * @see java.lang.Long#parseLong(java.lang.String, int) + */ + public Long(String s) throws NumberFormatException { + this.value = parseLong(s, 10); + } + + /** + * Returns the value of this {@code Long} as a + * {@code byte}. + */ + public byte byteValue() { + return (byte)value; + } + + /** + * Returns the value of this {@code Long} as a + * {@code short}. + */ + public short shortValue() { + return (short)value; + } + + /** + * Returns the value of this {@code Long} as an + * {@code int}. + */ + public int intValue() { + return (int)value; + } + + /** + * Returns the value of this {@code Long} as a + * {@code long} value. + */ + public long longValue() { + return (long)value; + } + + /** + * Returns the value of this {@code Long} as a + * {@code float}. + */ + public float floatValue() { + return (float)value; + } + + /** + * Returns the value of this {@code Long} as a + * {@code double}. + */ + public double doubleValue() { + return (double)value; + } + + /** + * Returns a {@code String} object representing this + * {@code Long}'s value. The value is converted to signed + * decimal representation and returned as a string, exactly as if + * the {@code long} value were given as an argument to the + * {@link java.lang.Long#toString(long)} method. + * + * @return a string representation of the value of this object in + * base 10. + */ + public String toString() { + return toString(value); + } + + /** + * Returns a hash code for this {@code Long}. The result is + * the exclusive OR of the two halves of the primitive + * {@code long} value held by this {@code Long} + * object. That is, the hashcode is the value of the expression: + * + *

+ * {@code (int)(this.longValue()^(this.longValue()>>>32))} + *
+ * + * @return a hash code value for this object. + */ + public int hashCode() { + return (int)(value ^ (value >>> 32)); + } + + /** + * Compares this object to the specified object. The result is + * {@code true} if and only if the argument is not + * {@code null} and is a {@code Long} object that + * contains the same {@code long} value as this object. + * + * @param obj the object to compare with. + * @return {@code true} if the objects are the same; + * {@code false} otherwise. + */ + public boolean equals(Object obj) { + if (obj instanceof Long) { + return value == ((Long)obj).longValue(); + } + return false; + } + + /** + * Determines the {@code long} value of the system property + * with the specified name. + * + *

The first argument is treated as the name of a system property. + * System properties are accessible through the {@link + * java.lang.System#getProperty(java.lang.String)} method. The + * string value of this property is then interpreted as a + * {@code long} value and a {@code Long} object + * representing this value is returned. Details of possible + * numeric formats can be found with the definition of + * {@code getProperty}. + * + *

If there is no property with the specified name, if the + * specified name is empty or {@code null}, or if the + * property does not have the correct numeric format, then + * {@code null} is returned. + * + *

In other words, this method returns a {@code Long} object equal to + * the value of: + * + *

+ * {@code getLong(nm, null)} + *
+ * + * @param nm property name. + * @return the {@code Long} value of the property. + * @see java.lang.System#getProperty(java.lang.String) + * @see java.lang.System#getProperty(java.lang.String, java.lang.String) + */ + public static Long getLong(String nm) { + return getLong(nm, null); + } + + /** + * Determines the {@code long} value of the system property + * with the specified name. + * + *

The first argument is treated as the name of a system property. + * System properties are accessible through the {@link + * java.lang.System#getProperty(java.lang.String)} method. The + * string value of this property is then interpreted as a + * {@code long} value and a {@code Long} object + * representing this value is returned. Details of possible + * numeric formats can be found with the definition of + * {@code getProperty}. + * + *

The second argument is the default value. A {@code Long} object + * that represents the value of the second argument is returned if there + * is no property of the specified name, if the property does not have + * the correct numeric format, or if the specified name is empty or null. + * + *

In other words, this method returns a {@code Long} object equal + * to the value of: + * + *

+ * {@code getLong(nm, new Long(val))} + *
+ * + * but in practice it may be implemented in a manner such as: + * + *
+     * Long result = getLong(nm, null);
+     * return (result == null) ? new Long(val) : result;
+     * 
+ * + * to avoid the unnecessary allocation of a {@code Long} object when + * the default value is not needed. + * + * @param nm property name. + * @param val default value. + * @return the {@code Long} value of the property. + * @see java.lang.System#getProperty(java.lang.String) + * @see java.lang.System#getProperty(java.lang.String, java.lang.String) + */ + public static Long getLong(String nm, long val) { + Long result = Long.getLong(nm, null); + return (result == null) ? Long.valueOf(val) : result; + } + + /** + * Returns the {@code long} value of the system property with + * the specified name. The first argument is treated as the name + * of a system property. System properties are accessible through + * the {@link java.lang.System#getProperty(java.lang.String)} + * method. The string value of this property is then interpreted + * as a {@code long} value, as per the + * {@code Long.decode} method, and a {@code Long} object + * representing this value is returned. + * + *
    + *
  • If the property value begins with the two ASCII characters + * {@code 0x} or the ASCII character {@code #}, not followed by + * a minus sign, then the rest of it is parsed as a hexadecimal integer + * exactly as for the method {@link #valueOf(java.lang.String, int)} + * with radix 16. + *
  • If the property value begins with the ASCII character + * {@code 0} followed by another character, it is parsed as + * an octal integer exactly as by the method {@link + * #valueOf(java.lang.String, int)} with radix 8. + *
  • Otherwise the property value is parsed as a decimal + * integer exactly as by the method + * {@link #valueOf(java.lang.String, int)} with radix 10. + *
+ * + *

Note that, in every case, neither {@code L} + * ('\u004C') nor {@code l} + * ('\u006C') is permitted to appear at the end + * of the property value as a type indicator, as would be + * permitted in Java programming language source code. + * + *

The second argument is the default value. The default value is + * returned if there is no property of the specified name, if the + * property does not have the correct numeric format, or if the + * specified name is empty or {@code null}. + * + * @param nm property name. + * @param val default value. + * @return the {@code Long} value of the property. + * @see java.lang.System#getProperty(java.lang.String) + * @see java.lang.System#getProperty(java.lang.String, java.lang.String) + * @see java.lang.Long#decode + */ + public static Long getLong(String nm, Long val) { + String v = null; + try { + v = AbstractStringBuilder.getProperty(nm); + } catch (IllegalArgumentException e) { + } catch (NullPointerException e) { + } + if (v != null) { + try { + return Long.decode(v); + } catch (NumberFormatException e) { + } + } + return val; + } + + /** + * Compares two {@code Long} objects numerically. + * + * @param anotherLong the {@code Long} to be compared. + * @return the value {@code 0} if this {@code Long} is + * equal to the argument {@code Long}; a value less than + * {@code 0} if this {@code Long} is numerically less + * than the argument {@code Long}; and a value greater + * than {@code 0} if this {@code Long} is numerically + * greater than the argument {@code Long} (signed + * comparison). + * @since 1.2 + */ + public int compareTo(Long anotherLong) { + return compare(this.value, anotherLong.value); + } + + /** + * Compares two {@code long} values numerically. + * The value returned is identical to what would be returned by: + *

+     *    Long.valueOf(x).compareTo(Long.valueOf(y))
+     * 
+ * + * @param x the first {@code long} to compare + * @param y the second {@code long} to compare + * @return the value {@code 0} if {@code x == y}; + * a value less than {@code 0} if {@code x < y}; and + * a value greater than {@code 0} if {@code x > y} + * @since 1.7 + */ + public static int compare(long x, long y) { + return (x < y) ? -1 : ((x == y) ? 0 : 1); + } + + + // Bit Twiddling + + /** + * The number of bits used to represent a {@code long} value in two's + * complement binary form. + * + * @since 1.5 + */ + public static final int SIZE = 64; + + /** + * Returns a {@code long} value with at most a single one-bit, in the + * position of the highest-order ("leftmost") one-bit in the specified + * {@code long} value. Returns zero if the specified value has no + * one-bits in its two's complement binary representation, that is, if it + * is equal to zero. + * + * @return a {@code long} value with a single one-bit, in the position + * of the highest-order one-bit in the specified value, or zero if + * the specified value is itself equal to zero. + * @since 1.5 + */ + public static long highestOneBit(long i) { + // HD, Figure 3-1 + i |= (i >> 1); + i |= (i >> 2); + i |= (i >> 4); + i |= (i >> 8); + i |= (i >> 16); + i |= (i >> 32); + return i - (i >>> 1); + } + + /** + * Returns a {@code long} value with at most a single one-bit, in the + * position of the lowest-order ("rightmost") one-bit in the specified + * {@code long} value. Returns zero if the specified value has no + * one-bits in its two's complement binary representation, that is, if it + * is equal to zero. + * + * @return a {@code long} value with a single one-bit, in the position + * of the lowest-order one-bit in the specified value, or zero if + * the specified value is itself equal to zero. + * @since 1.5 + */ + public static long lowestOneBit(long i) { + // HD, Section 2-1 + return i & -i; + } + + /** + * Returns the number of zero bits preceding the highest-order + * ("leftmost") one-bit in the two's complement binary representation + * of the specified {@code long} value. Returns 64 if the + * specified value has no one-bits in its two's complement representation, + * in other words if it is equal to zero. + * + *

Note that this method is closely related to the logarithm base 2. + * For all positive {@code long} values x: + *

    + *
  • floor(log2(x)) = {@code 63 - numberOfLeadingZeros(x)} + *
  • ceil(log2(x)) = {@code 64 - numberOfLeadingZeros(x - 1)} + *
+ * + * @return the number of zero bits preceding the highest-order + * ("leftmost") one-bit in the two's complement binary representation + * of the specified {@code long} value, or 64 if the value + * is equal to zero. + * @since 1.5 + */ + public static int numberOfLeadingZeros(long i) { + // HD, Figure 5-6 + if (i == 0) + return 64; + int n = 1; + int x = (int)(i >>> 32); + if (x == 0) { n += 32; x = (int)i; } + if (x >>> 16 == 0) { n += 16; x <<= 16; } + if (x >>> 24 == 0) { n += 8; x <<= 8; } + if (x >>> 28 == 0) { n += 4; x <<= 4; } + if (x >>> 30 == 0) { n += 2; x <<= 2; } + n -= x >>> 31; + return n; + } + + /** + * Returns the number of zero bits following the lowest-order ("rightmost") + * one-bit in the two's complement binary representation of the specified + * {@code long} value. Returns 64 if the specified value has no + * one-bits in its two's complement representation, in other words if it is + * equal to zero. + * + * @return the number of zero bits following the lowest-order ("rightmost") + * one-bit in the two's complement binary representation of the + * specified {@code long} value, or 64 if the value is equal + * to zero. + * @since 1.5 + */ + public static int numberOfTrailingZeros(long i) { + // HD, Figure 5-14 + int x, y; + if (i == 0) return 64; + int n = 63; + y = (int)i; if (y != 0) { n = n -32; x = y; } else x = (int)(i>>>32); + y = x <<16; if (y != 0) { n = n -16; x = y; } + y = x << 8; if (y != 0) { n = n - 8; x = y; } + y = x << 4; if (y != 0) { n = n - 4; x = y; } + y = x << 2; if (y != 0) { n = n - 2; x = y; } + return n - ((x << 1) >>> 31); + } + + /** + * Returns the number of one-bits in the two's complement binary + * representation of the specified {@code long} value. This function is + * sometimes referred to as the population count. + * + * @return the number of one-bits in the two's complement binary + * representation of the specified {@code long} value. + * @since 1.5 + */ + public static int bitCount(long i) { + // HD, Figure 5-14 + i = i - ((i >>> 1) & 0x5555555555555555L); + i = (i & 0x3333333333333333L) + ((i >>> 2) & 0x3333333333333333L); + i = (i + (i >>> 4)) & 0x0f0f0f0f0f0f0f0fL; + i = i + (i >>> 8); + i = i + (i >>> 16); + i = i + (i >>> 32); + return (int)i & 0x7f; + } + + /** + * Returns the value obtained by rotating the two's complement binary + * representation of the specified {@code long} value left by the + * specified number of bits. (Bits shifted out of the left hand, or + * high-order, side reenter on the right, or low-order.) + * + *

Note that left rotation with a negative distance is equivalent to + * right rotation: {@code rotateLeft(val, -distance) == rotateRight(val, + * distance)}. Note also that rotation by any multiple of 64 is a + * no-op, so all but the last six bits of the rotation distance can be + * ignored, even if the distance is negative: {@code rotateLeft(val, + * distance) == rotateLeft(val, distance & 0x3F)}. + * + * @return the value obtained by rotating the two's complement binary + * representation of the specified {@code long} value left by the + * specified number of bits. + * @since 1.5 + */ + public static long rotateLeft(long i, int distance) { + return (i << distance) | (i >>> -distance); + } + + /** + * Returns the value obtained by rotating the two's complement binary + * representation of the specified {@code long} value right by the + * specified number of bits. (Bits shifted out of the right hand, or + * low-order, side reenter on the left, or high-order.) + * + *

Note that right rotation with a negative distance is equivalent to + * left rotation: {@code rotateRight(val, -distance) == rotateLeft(val, + * distance)}. Note also that rotation by any multiple of 64 is a + * no-op, so all but the last six bits of the rotation distance can be + * ignored, even if the distance is negative: {@code rotateRight(val, + * distance) == rotateRight(val, distance & 0x3F)}. + * + * @return the value obtained by rotating the two's complement binary + * representation of the specified {@code long} value right by the + * specified number of bits. + * @since 1.5 + */ + public static long rotateRight(long i, int distance) { + return (i >>> distance) | (i << -distance); + } + + /** + * Returns the value obtained by reversing the order of the bits in the + * two's complement binary representation of the specified {@code long} + * value. + * + * @return the value obtained by reversing order of the bits in the + * specified {@code long} value. + * @since 1.5 + */ + public static long reverse(long i) { + // HD, Figure 7-1 + i = (i & 0x5555555555555555L) << 1 | (i >>> 1) & 0x5555555555555555L; + i = (i & 0x3333333333333333L) << 2 | (i >>> 2) & 0x3333333333333333L; + i = (i & 0x0f0f0f0f0f0f0f0fL) << 4 | (i >>> 4) & 0x0f0f0f0f0f0f0f0fL; + i = (i & 0x00ff00ff00ff00ffL) << 8 | (i >>> 8) & 0x00ff00ff00ff00ffL; + i = (i << 48) | ((i & 0xffff0000L) << 16) | + ((i >>> 16) & 0xffff0000L) | (i >>> 48); + return i; + } + + /** + * Returns the signum function of the specified {@code long} value. (The + * return value is -1 if the specified value is negative; 0 if the + * specified value is zero; and 1 if the specified value is positive.) + * + * @return the signum function of the specified {@code long} value. + * @since 1.5 + */ + public static int signum(long i) { + // HD, Section 2-7 + return (int) ((i >> 63) | (-i >>> 63)); + } + + /** + * Returns the value obtained by reversing the order of the bytes in the + * two's complement representation of the specified {@code long} value. + * + * @return the value obtained by reversing the bytes in the specified + * {@code long} value. + * @since 1.5 + */ + public static long reverseBytes(long i) { + i = (i & 0x00ff00ff00ff00ffL) << 8 | (i >>> 8) & 0x00ff00ff00ff00ffL; + return (i << 48) | ((i & 0xffff0000L) << 16) | + ((i >>> 16) & 0xffff0000L) | (i >>> 48); + } + + /** use serialVersionUID from JDK 1.0.2 for interoperability */ + private static final long serialVersionUID = 4290774380558885855L; +} diff -r 388e48c0a37a -r 05224402145d emul/mini/src/main/java/java/lang/Math.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/emul/mini/src/main/java/java/lang/Math.java Wed Jan 23 20:39:23 2013 +0100 @@ -0,0 +1,1244 @@ +/* + * Copyright (c) 1994, 2011, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code 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 + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package java.lang; + +import org.apidesign.bck2brwsr.core.JavaScriptBody; + + +/** + * The class {@code Math} contains methods for performing basic + * numeric operations such as the elementary exponential, logarithm, + * square root, and trigonometric functions. + * + *

Unlike some of the numeric methods of class + * {@code StrictMath}, all implementations of the equivalent + * functions of class {@code Math} are not defined to return the + * bit-for-bit same results. This relaxation permits + * better-performing implementations where strict reproducibility is + * not required. + * + *

By default many of the {@code Math} methods simply call + * the equivalent method in {@code StrictMath} for their + * implementation. Code generators are encouraged to use + * platform-specific native libraries or microprocessor instructions, + * where available, to provide higher-performance implementations of + * {@code Math} methods. Such higher-performance + * implementations still must conform to the specification for + * {@code Math}. + * + *

The quality of implementation specifications concern two + * properties, accuracy of the returned result and monotonicity of the + * method. Accuracy of the floating-point {@code Math} methods + * is measured in terms of ulps, units in the last place. For + * a given floating-point format, an ulp of a specific real number + * value is the distance between the two floating-point values + * bracketing that numerical value. When discussing the accuracy of a + * method as a whole rather than at a specific argument, the number of + * ulps cited is for the worst-case error at any argument. If a + * method always has an error less than 0.5 ulps, the method always + * returns the floating-point number nearest the exact result; such a + * method is correctly rounded. A correctly rounded method is + * generally the best a floating-point approximation can be; however, + * it is impractical for many floating-point methods to be correctly + * rounded. Instead, for the {@code Math} class, a larger error + * bound of 1 or 2 ulps is allowed for certain methods. Informally, + * with a 1 ulp error bound, when the exact result is a representable + * number, the exact result should be returned as the computed result; + * otherwise, either of the two floating-point values which bracket + * the exact result may be returned. For exact results large in + * magnitude, one of the endpoints of the bracket may be infinite. + * Besides accuracy at individual arguments, maintaining proper + * relations between the method at different arguments is also + * important. Therefore, most methods with more than 0.5 ulp errors + * are required to be semi-monotonic: whenever the mathematical + * function is non-decreasing, so is the floating-point approximation, + * likewise, whenever the mathematical function is non-increasing, so + * is the floating-point approximation. Not all approximations that + * have 1 ulp accuracy will automatically meet the monotonicity + * requirements. + * + * @author unascribed + * @author Joseph D. Darcy + * @since JDK1.0 + */ + +public final class Math { + + /** + * Don't let anyone instantiate this class. + */ + private Math() {} + + /** + * The {@code double} value that is closer than any other to + * e, the base of the natural logarithms. + */ + public static final double E = 2.7182818284590452354; + + /** + * The {@code double} value that is closer than any other to + * pi, the ratio of the circumference of a circle to its + * diameter. + */ + public static final double PI = 3.14159265358979323846; + + /** + * Returns the trigonometric sine of an angle. Special cases: + *

  • If the argument is NaN or an infinity, then the + * result is NaN. + *
  • If the argument is zero, then the result is a zero with the + * same sign as the argument.
+ * + *

The computed result must be within 1 ulp of the exact result. + * Results must be semi-monotonic. + * + * @param a an angle, in radians. + * @return the sine of the argument. + */ + @JavaScriptBody(args="a", body="return Math.sin(a);") + public static double sin(double a) { + throw new UnsupportedOperationException(); + } + + /** + * Returns the trigonometric cosine of an angle. Special cases: + *

  • If the argument is NaN or an infinity, then the + * result is NaN.
+ * + *

The computed result must be within 1 ulp of the exact result. + * Results must be semi-monotonic. + * + * @param a an angle, in radians. + * @return the cosine of the argument. + */ + @JavaScriptBody(args="a", body="return Math.cos(a);") + public static double cos(double a) { + throw new UnsupportedOperationException(); + } + + /** + * Returns the trigonometric tangent of an angle. Special cases: + *

  • If the argument is NaN or an infinity, then the result + * is NaN. + *
  • If the argument is zero, then the result is a zero with the + * same sign as the argument.
+ * + *

The computed result must be within 1 ulp of the exact result. + * Results must be semi-monotonic. + * + * @param a an angle, in radians. + * @return the tangent of the argument. + */ + @JavaScriptBody(args="a", body="return Math.tan(a);") + public static double tan(double a) { + throw new UnsupportedOperationException(); + } + + /** + * Returns the arc sine of a value; the returned angle is in the + * range -pi/2 through pi/2. Special cases: + *

  • If the argument is NaN or its absolute value is greater + * than 1, then the result is NaN. + *
  • If the argument is zero, then the result is a zero with the + * same sign as the argument.
+ * + *

The computed result must be within 1 ulp of the exact result. + * Results must be semi-monotonic. + * + * @param a the value whose arc sine is to be returned. + * @return the arc sine of the argument. + */ + @JavaScriptBody(args="a", body="return Math.asin(a);") + public static double asin(double a) { + throw new UnsupportedOperationException(); + } + + /** + * Returns the arc cosine of a value; the returned angle is in the + * range 0.0 through pi. Special case: + *

  • If the argument is NaN or its absolute value is greater + * than 1, then the result is NaN.
+ * + *

The computed result must be within 1 ulp of the exact result. + * Results must be semi-monotonic. + * + * @param a the value whose arc cosine is to be returned. + * @return the arc cosine of the argument. + */ + @JavaScriptBody(args="a", body="return Math.acos(a);") + public static double acos(double a) { + throw new UnsupportedOperationException(); + } + + /** + * Returns the arc tangent of a value; the returned angle is in the + * range -pi/2 through pi/2. Special cases: + *

  • If the argument is NaN, then the result is NaN. + *
  • If the argument is zero, then the result is a zero with the + * same sign as the argument.
+ * + *

The computed result must be within 1 ulp of the exact result. + * Results must be semi-monotonic. + * + * @param a the value whose arc tangent is to be returned. + * @return the arc tangent of the argument. + */ + @JavaScriptBody(args="a", body="return Math.atan(a);") + public static double atan(double a) { + throw new UnsupportedOperationException(); + } + + /** + * Converts an angle measured in degrees to an approximately + * equivalent angle measured in radians. The conversion from + * degrees to radians is generally inexact. + * + * @param angdeg an angle, in degrees + * @return the measurement of the angle {@code angdeg} + * in radians. + * @since 1.2 + */ + public static double toRadians(double angdeg) { + return angdeg / 180.0 * PI; + } + + /** + * Converts an angle measured in radians to an approximately + * equivalent angle measured in degrees. The conversion from + * radians to degrees is generally inexact; users should + * not expect {@code cos(toRadians(90.0))} to exactly + * equal {@code 0.0}. + * + * @param angrad an angle, in radians + * @return the measurement of the angle {@code angrad} + * in degrees. + * @since 1.2 + */ + public static double toDegrees(double angrad) { + return angrad * 180.0 / PI; + } + + /** + * Returns Euler's number e raised to the power of a + * {@code double} value. Special cases: + *

  • If the argument is NaN, the result is NaN. + *
  • If the argument is positive infinity, then the result is + * positive infinity. + *
  • If the argument is negative infinity, then the result is + * positive zero.
+ * + *

The computed result must be within 1 ulp of the exact result. + * Results must be semi-monotonic. + * + * @param a the exponent to raise e to. + * @return the value e{@code a}, + * where e is the base of the natural logarithms. + */ + @JavaScriptBody(args="a", body="return Math.exp(a);") + public static double exp(double a) { + throw new UnsupportedOperationException(); + } + + /** + * Returns the natural logarithm (base e) of a {@code double} + * value. Special cases: + *

  • If the argument is NaN or less than zero, then the result + * is NaN. + *
  • If the argument is positive infinity, then the result is + * positive infinity. + *
  • If the argument is positive zero or negative zero, then the + * result is negative infinity.
+ * + *

The computed result must be within 1 ulp of the exact result. + * Results must be semi-monotonic. + * + * @param a a value + * @return the value ln {@code a}, the natural logarithm of + * {@code a}. + */ + @JavaScriptBody(args="a", body="return Math.log(a);") + public static double log(double a) { + throw new UnsupportedOperationException(); + } + + /** + * Returns the base 10 logarithm of a {@code double} value. + * Special cases: + * + *

  • If the argument is NaN or less than zero, then the result + * is NaN. + *
  • If the argument is positive infinity, then the result is + * positive infinity. + *
  • If the argument is positive zero or negative zero, then the + * result is negative infinity. + *
  • If the argument is equal to 10n for + * integer n, then the result is n. + *
+ * + *

The computed result must be within 1 ulp of the exact result. + * Results must be semi-monotonic. + * + * @param a a value + * @return the base 10 logarithm of {@code a}. + * @since 1.5 + */ + @JavaScriptBody(args="a", body="return Math.log(a) / Math.LN10;") + public static double log10(double a) { + throw new UnsupportedOperationException(); + } + + /** + * Returns the correctly rounded positive square root of a + * {@code double} value. + * Special cases: + *

  • If the argument is NaN or less than zero, then the result + * is NaN. + *
  • If the argument is positive infinity, then the result is positive + * infinity. + *
  • If the argument is positive zero or negative zero, then the + * result is the same as the argument.
+ * Otherwise, the result is the {@code double} value closest to + * the true mathematical square root of the argument value. + * + * @param a a value. + * @return the positive square root of {@code a}. + * If the argument is NaN or less than zero, the result is NaN. + */ + @JavaScriptBody(args="a", body="return Math.sqrt(a);") + public static double sqrt(double a) { + throw new UnsupportedOperationException(); + } + + /** + * Returns the smallest (closest to negative infinity) + * {@code double} value that is greater than or equal to the + * argument and is equal to a mathematical integer. Special cases: + *
  • If the argument value is already equal to a + * mathematical integer, then the result is the same as the + * argument.
  • If the argument is NaN or an infinity or + * positive zero or negative zero, then the result is the same as + * the argument.
  • If the argument value is less than zero but + * greater than -1.0, then the result is negative zero.
Note + * that the value of {@code Math.ceil(x)} is exactly the + * value of {@code -Math.floor(-x)}. + * + * + * @param a a value. + * @return the smallest (closest to negative infinity) + * floating-point value that is greater than or equal to + * the argument and is equal to a mathematical integer. + */ + @JavaScriptBody(args="a", body="return Math.ceil(a);") + public static double ceil(double a) { + throw new UnsupportedOperationException(); + } + + /** + * Returns the largest (closest to positive infinity) + * {@code double} value that is less than or equal to the + * argument and is equal to a mathematical integer. Special cases: + *
  • If the argument value is already equal to a + * mathematical integer, then the result is the same as the + * argument.
  • If the argument is NaN or an infinity or + * positive zero or negative zero, then the result is the same as + * the argument.
+ * + * @param a a value. + * @return the largest (closest to positive infinity) + * floating-point value that less than or equal to the argument + * and is equal to a mathematical integer. + */ + @JavaScriptBody(args="a", body="return Math.floor(a);") + public static double floor(double a) { + throw new UnsupportedOperationException(); + } + + /** + * Returns the angle theta from the conversion of rectangular + * coordinates ({@code x}, {@code y}) to polar + * coordinates (r, theta). + * This method computes the phase theta by computing an arc tangent + * of {@code y/x} in the range of -pi to pi. Special + * cases: + *
  • If either argument is NaN, then the result is NaN. + *
  • If the first argument is positive zero and the second argument + * is positive, or the first argument is positive and finite and the + * second argument is positive infinity, then the result is positive + * zero. + *
  • If the first argument is negative zero and the second argument + * is positive, or the first argument is negative and finite and the + * second argument is positive infinity, then the result is negative zero. + *
  • If the first argument is positive zero and the second argument + * is negative, or the first argument is positive and finite and the + * second argument is negative infinity, then the result is the + * {@code double} value closest to pi. + *
  • If the first argument is negative zero and the second argument + * is negative, or the first argument is negative and finite and the + * second argument is negative infinity, then the result is the + * {@code double} value closest to -pi. + *
  • If the first argument is positive and the second argument is + * positive zero or negative zero, or the first argument is positive + * infinity and the second argument is finite, then the result is the + * {@code double} value closest to pi/2. + *
  • If the first argument is negative and the second argument is + * positive zero or negative zero, or the first argument is negative + * infinity and the second argument is finite, then the result is the + * {@code double} value closest to -pi/2. + *
  • If both arguments are positive infinity, then the result is the + * {@code double} value closest to pi/4. + *
  • If the first argument is positive infinity and the second argument + * is negative infinity, then the result is the {@code double} + * value closest to 3*pi/4. + *
  • If the first argument is negative infinity and the second argument + * is positive infinity, then the result is the {@code double} value + * closest to -pi/4. + *
  • If both arguments are negative infinity, then the result is the + * {@code double} value closest to -3*pi/4.
+ * + *

The computed result must be within 2 ulps of the exact result. + * Results must be semi-monotonic. + * + * @param y the ordinate coordinate + * @param x the abscissa coordinate + * @return the theta component of the point + * (rtheta) + * in polar coordinates that corresponds to the point + * (xy) in Cartesian coordinates. + */ + @JavaScriptBody(args={"y", "x"}, body="return Math.atan2(y, x);") + public static double atan2(double y, double x) { + throw new UnsupportedOperationException(); + } + + /** + * Returns the value of the first argument raised to the power of the + * second argument. Special cases: + * + *

  • If the second argument is positive or negative zero, then the + * result is 1.0. + *
  • If the second argument is 1.0, then the result is the same as the + * first argument. + *
  • If the second argument is NaN, then the result is NaN. + *
  • If the first argument is NaN and the second argument is nonzero, + * then the result is NaN. + * + *
  • If + *
      + *
    • the absolute value of the first argument is greater than 1 + * and the second argument is positive infinity, or + *
    • the absolute value of the first argument is less than 1 and + * the second argument is negative infinity, + *
    + * then the result is positive infinity. + * + *
  • If + *
      + *
    • the absolute value of the first argument is greater than 1 and + * the second argument is negative infinity, or + *
    • the absolute value of the + * first argument is less than 1 and the second argument is positive + * infinity, + *
    + * then the result is positive zero. + * + *
  • If the absolute value of the first argument equals 1 and the + * second argument is infinite, then the result is NaN. + * + *
  • If + *
      + *
    • the first argument is positive zero and the second argument + * is greater than zero, or + *
    • the first argument is positive infinity and the second + * argument is less than zero, + *
    + * then the result is positive zero. + * + *
  • If + *
      + *
    • the first argument is positive zero and the second argument + * is less than zero, or + *
    • the first argument is positive infinity and the second + * argument is greater than zero, + *
    + * then the result is positive infinity. + * + *
  • If + *
      + *
    • the first argument is negative zero and the second argument + * is greater than zero but not a finite odd integer, or + *
    • the first argument is negative infinity and the second + * argument is less than zero but not a finite odd integer, + *
    + * then the result is positive zero. + * + *
  • If + *
      + *
    • the first argument is negative zero and the second argument + * is a positive finite odd integer, or + *
    • the first argument is negative infinity and the second + * argument is a negative finite odd integer, + *
    + * then the result is negative zero. + * + *
  • If + *
      + *
    • the first argument is negative zero and the second argument + * is less than zero but not a finite odd integer, or + *
    • the first argument is negative infinity and the second + * argument is greater than zero but not a finite odd integer, + *
    + * then the result is positive infinity. + * + *
  • If + *
      + *
    • the first argument is negative zero and the second argument + * is a negative finite odd integer, or + *
    • the first argument is negative infinity and the second + * argument is a positive finite odd integer, + *
    + * then the result is negative infinity. + * + *
  • If the first argument is finite and less than zero + *
      + *
    • if the second argument is a finite even integer, the + * result is equal to the result of raising the absolute value of + * the first argument to the power of the second argument + * + *
    • if the second argument is a finite odd integer, the result + * is equal to the negative of the result of raising the absolute + * value of the first argument to the power of the second + * argument + * + *
    • if the second argument is finite and not an integer, then + * the result is NaN. + *
    + * + *
  • If both arguments are integers, then the result is exactly equal + * to the mathematical result of raising the first argument to the power + * of the second argument if that result can in fact be represented + * exactly as a {@code double} value.
+ * + *

(In the foregoing descriptions, a floating-point value is + * considered to be an integer if and only if it is finite and a + * fixed point of the method {@link #ceil ceil} or, + * equivalently, a fixed point of the method {@link #floor + * floor}. A value is a fixed point of a one-argument + * method if and only if the result of applying the method to the + * value is equal to the value.) + * + *

The computed result must be within 1 ulp of the exact result. + * Results must be semi-monotonic. + * + * @param a the base. + * @param b the exponent. + * @return the value {@code a}{@code b}. + */ + @JavaScriptBody(args={"a", "b"}, body="return Math.pow(a, b);") + public static double pow(double a, double b) { + throw new UnsupportedOperationException(); + } + + /** + * Returns the closest {@code int} to the argument, with ties + * rounding up. + * + *

+ * Special cases: + *

  • If the argument is NaN, the result is 0. + *
  • If the argument is negative infinity or any value less than or + * equal to the value of {@code Integer.MIN_VALUE}, the result is + * equal to the value of {@code Integer.MIN_VALUE}. + *
  • If the argument is positive infinity or any value greater than or + * equal to the value of {@code Integer.MAX_VALUE}, the result is + * equal to the value of {@code Integer.MAX_VALUE}.
+ * + * @param a a floating-point value to be rounded to an integer. + * @return the value of the argument rounded to the nearest + * {@code int} value. + * @see java.lang.Integer#MAX_VALUE + * @see java.lang.Integer#MIN_VALUE + */ + @JavaScriptBody(args="a", body="return Math.round(a);") + public static int round(float a) { + throw new UnsupportedOperationException(); + } + + /** + * Returns the closest {@code long} to the argument, with ties + * rounding up. + * + *

Special cases: + *

  • If the argument is NaN, the result is 0. + *
  • If the argument is negative infinity or any value less than or + * equal to the value of {@code Long.MIN_VALUE}, the result is + * equal to the value of {@code Long.MIN_VALUE}. + *
  • If the argument is positive infinity or any value greater than or + * equal to the value of {@code Long.MAX_VALUE}, the result is + * equal to the value of {@code Long.MAX_VALUE}.
+ * + * @param a a floating-point value to be rounded to a + * {@code long}. + * @return the value of the argument rounded to the nearest + * {@code long} value. + * @see java.lang.Long#MAX_VALUE + * @see java.lang.Long#MIN_VALUE + */ + @JavaScriptBody(args="a", body="return Math.round(a);") + public static long round(double a) { + throw new UnsupportedOperationException(); + } + +// private static Random randomNumberGenerator; +// +// private static synchronized Random initRNG() { +// Random rnd = randomNumberGenerator; +// return (rnd == null) ? (randomNumberGenerator = new Random()) : rnd; +// } + + /** + * Returns a {@code double} value with a positive sign, greater + * than or equal to {@code 0.0} and less than {@code 1.0}. + * Returned values are chosen pseudorandomly with (approximately) + * uniform distribution from that range. + * + *

When this method is first called, it creates a single new + * pseudorandom-number generator, exactly as if by the expression + * + *

{@code new java.util.Random()}
+ * + * This new pseudorandom-number generator is used thereafter for + * all calls to this method and is used nowhere else. + * + *

This method is properly synchronized to allow correct use by + * more than one thread. However, if many threads need to generate + * pseudorandom numbers at a great rate, it may reduce contention + * for each thread to have its own pseudorandom-number generator. + * + * @return a pseudorandom {@code double} greater than or equal + * to {@code 0.0} and less than {@code 1.0}. + * @see Random#nextDouble() + */ + @JavaScriptBody(args={}, body="return Math.random();") + public static double random() { + throw new UnsupportedOperationException(); + } + + /** + * Returns the absolute value of an {@code int} value. + * If the argument is not negative, the argument is returned. + * If the argument is negative, the negation of the argument is returned. + * + *

Note that if the argument is equal to the value of + * {@link Integer#MIN_VALUE}, the most negative representable + * {@code int} value, the result is that same value, which is + * negative. + * + * @param a the argument whose absolute value is to be determined + * @return the absolute value of the argument. + */ + public static int abs(int a) { + return (a < 0) ? -a : a; + } + + /** + * Returns the absolute value of a {@code long} value. + * If the argument is not negative, the argument is returned. + * If the argument is negative, the negation of the argument is returned. + * + *

Note that if the argument is equal to the value of + * {@link Long#MIN_VALUE}, the most negative representable + * {@code long} value, the result is that same value, which + * is negative. + * + * @param a the argument whose absolute value is to be determined + * @return the absolute value of the argument. + */ + public static long abs(long a) { + return (a < 0) ? -a : a; + } + + /** + * Returns the absolute value of a {@code float} value. + * If the argument is not negative, the argument is returned. + * If the argument is negative, the negation of the argument is returned. + * Special cases: + *

  • If the argument is positive zero or negative zero, the + * result is positive zero. + *
  • If the argument is infinite, the result is positive infinity. + *
  • If the argument is NaN, the result is NaN.
+ * In other words, the result is the same as the value of the expression: + *

{@code Float.intBitsToFloat(0x7fffffff & Float.floatToIntBits(a))} + * + * @param a the argument whose absolute value is to be determined + * @return the absolute value of the argument. + */ + public static float abs(float a) { + return (a <= 0.0F) ? 0.0F - a : a; + } + + /** + * Returns the absolute value of a {@code double} value. + * If the argument is not negative, the argument is returned. + * If the argument is negative, the negation of the argument is returned. + * Special cases: + *

  • If the argument is positive zero or negative zero, the result + * is positive zero. + *
  • If the argument is infinite, the result is positive infinity. + *
  • If the argument is NaN, the result is NaN.
+ * In other words, the result is the same as the value of the expression: + *

{@code Double.longBitsToDouble((Double.doubleToLongBits(a)<<1)>>>1)} + * + * @param a the argument whose absolute value is to be determined + * @return the absolute value of the argument. + */ + public static double abs(double a) { + return (a <= 0.0D) ? 0.0D - a : a; + } + + /** + * Returns the greater of two {@code int} values. That is, the + * result is the argument closer to the value of + * {@link Integer#MAX_VALUE}. If the arguments have the same value, + * the result is that same value. + * + * @param a an argument. + * @param b another argument. + * @return the larger of {@code a} and {@code b}. + */ + public static int max(int a, int b) { + return (a >= b) ? a : b; + } + + /** + * Returns the greater of two {@code long} values. That is, the + * result is the argument closer to the value of + * {@link Long#MAX_VALUE}. If the arguments have the same value, + * the result is that same value. + * + * @param a an argument. + * @param b another argument. + * @return the larger of {@code a} and {@code b}. + */ + public static long max(long a, long b) { + return (a >= b) ? a : b; + } + + /** + * Returns the greater of two {@code float} values. That is, + * the result is the argument closer to positive infinity. If the + * arguments have the same value, the result is that same + * value. If either value is NaN, then the result is NaN. Unlike + * the numerical comparison operators, this method considers + * negative zero to be strictly smaller than positive zero. If one + * argument is positive zero and the other negative zero, the + * result is positive zero. + * + * @param a an argument. + * @param b another argument. + * @return the larger of {@code a} and {@code b}. + */ + @JavaScriptBody(args={"a", "b"}, + body="return Math.max(a,b);" + ) + public static float max(float a, float b) { + throw new UnsupportedOperationException(); + } + + /** + * Returns the greater of two {@code double} values. That + * is, the result is the argument closer to positive infinity. If + * the arguments have the same value, the result is that same + * value. If either value is NaN, then the result is NaN. Unlike + * the numerical comparison operators, this method considers + * negative zero to be strictly smaller than positive zero. If one + * argument is positive zero and the other negative zero, the + * result is positive zero. + * + * @param a an argument. + * @param b another argument. + * @return the larger of {@code a} and {@code b}. + */ + @JavaScriptBody(args={"a", "b"}, + body="return Math.max(a,b);" + ) + public static double max(double a, double b) { + throw new UnsupportedOperationException(); + } + + /** + * Returns the smaller of two {@code int} values. That is, + * the result the argument closer to the value of + * {@link Integer#MIN_VALUE}. If the arguments have the same + * value, the result is that same value. + * + * @param a an argument. + * @param b another argument. + * @return the smaller of {@code a} and {@code b}. + */ + public static int min(int a, int b) { + return (a <= b) ? a : b; + } + + /** + * Returns the smaller of two {@code long} values. That is, + * the result is the argument closer to the value of + * {@link Long#MIN_VALUE}. If the arguments have the same + * value, the result is that same value. + * + * @param a an argument. + * @param b another argument. + * @return the smaller of {@code a} and {@code b}. + */ + public static long min(long a, long b) { + return (a <= b) ? a : b; + } + + /** + * Returns the smaller of two {@code float} values. That is, + * the result is the value closer to negative infinity. If the + * arguments have the same value, the result is that same + * value. If either value is NaN, then the result is NaN. Unlike + * the numerical comparison operators, this method considers + * negative zero to be strictly smaller than positive zero. If + * one argument is positive zero and the other is negative zero, + * the result is negative zero. + * + * @param a an argument. + * @param b another argument. + * @return the smaller of {@code a} and {@code b}. + */ + @JavaScriptBody(args={"a", "b"}, + body="return Math.min(a,b);" + ) + public static float min(float a, float b) { + throw new UnsupportedOperationException(); + } + + /** + * Returns the smaller of two {@code double} values. That + * is, the result is the value closer to negative infinity. If the + * arguments have the same value, the result is that same + * value. If either value is NaN, then the result is NaN. Unlike + * the numerical comparison operators, this method considers + * negative zero to be strictly smaller than positive zero. If one + * argument is positive zero and the other is negative zero, the + * result is negative zero. + * + * @param a an argument. + * @param b another argument. + * @return the smaller of {@code a} and {@code b}. + */ + @JavaScriptBody(args={"a", "b"}, + body="return Math.min(a,b);" + ) + public static double min(double a, double b) { + throw new UnsupportedOperationException(); + } + + /** + * Returns the size of an ulp of the argument. An ulp of a + * {@code double} value is the positive distance between this + * floating-point value and the {@code double} value next + * larger in magnitude. Note that for non-NaN x, + * ulp(-x) == ulp(x). + * + *

Special Cases: + *

    + *
  • If the argument is NaN, then the result is NaN. + *
  • If the argument is positive or negative infinity, then the + * result is positive infinity. + *
  • If the argument is positive or negative zero, then the result is + * {@code Double.MIN_VALUE}. + *
  • If the argument is ±{@code Double.MAX_VALUE}, then + * the result is equal to 2971. + *
+ * + * @param d the floating-point value whose ulp is to be returned + * @return the size of an ulp of the argument + * @author Joseph D. Darcy + * @since 1.5 + */ +// public static double ulp(double d) { +// return sun.misc.FpUtils.ulp(d); +// } + + /** + * Returns the size of an ulp of the argument. An ulp of a + * {@code float} value is the positive distance between this + * floating-point value and the {@code float} value next + * larger in magnitude. Note that for non-NaN x, + * ulp(-x) == ulp(x). + * + *

Special Cases: + *

    + *
  • If the argument is NaN, then the result is NaN. + *
  • If the argument is positive or negative infinity, then the + * result is positive infinity. + *
  • If the argument is positive or negative zero, then the result is + * {@code Float.MIN_VALUE}. + *
  • If the argument is ±{@code Float.MAX_VALUE}, then + * the result is equal to 2104. + *
+ * + * @param f the floating-point value whose ulp is to be returned + * @return the size of an ulp of the argument + * @author Joseph D. Darcy + * @since 1.5 + */ +// public static float ulp(float f) { +// return sun.misc.FpUtils.ulp(f); +// } + + /** + * Returns the signum function of the argument; zero if the argument + * is zero, 1.0 if the argument is greater than zero, -1.0 if the + * argument is less than zero. + * + *

Special Cases: + *

    + *
  • If the argument is NaN, then the result is NaN. + *
  • If the argument is positive zero or negative zero, then the + * result is the same as the argument. + *
+ * + * @param d the floating-point value whose signum is to be returned + * @return the signum function of the argument + * @author Joseph D. Darcy + * @since 1.5 + */ +// public static double signum(double d) { +// return sun.misc.FpUtils.signum(d); +// } + + /** + * Returns the signum function of the argument; zero if the argument + * is zero, 1.0f if the argument is greater than zero, -1.0f if the + * argument is less than zero. + * + *

Special Cases: + *

    + *
  • If the argument is NaN, then the result is NaN. + *
  • If the argument is positive zero or negative zero, then the + * result is the same as the argument. + *
+ * + * @param f the floating-point value whose signum is to be returned + * @return the signum function of the argument + * @author Joseph D. Darcy + * @since 1.5 + */ +// public static float signum(float f) { +// return sun.misc.FpUtils.signum(f); +// } + + /** + * Returns the first floating-point argument with the sign of the + * second floating-point argument. Note that unlike the {@link + * StrictMath#copySign(double, double) StrictMath.copySign} + * method, this method does not require NaN {@code sign} + * arguments to be treated as positive values; implementations are + * permitted to treat some NaN arguments as positive and other NaN + * arguments as negative to allow greater performance. + * + * @param magnitude the parameter providing the magnitude of the result + * @param sign the parameter providing the sign of the result + * @return a value with the magnitude of {@code magnitude} + * and the sign of {@code sign}. + * @since 1.6 + */ +// public static double copySign(double magnitude, double sign) { +// return sun.misc.FpUtils.rawCopySign(magnitude, sign); +// } + + /** + * Returns the first floating-point argument with the sign of the + * second floating-point argument. Note that unlike the {@link + * StrictMath#copySign(float, float) StrictMath.copySign} + * method, this method does not require NaN {@code sign} + * arguments to be treated as positive values; implementations are + * permitted to treat some NaN arguments as positive and other NaN + * arguments as negative to allow greater performance. + * + * @param magnitude the parameter providing the magnitude of the result + * @param sign the parameter providing the sign of the result + * @return a value with the magnitude of {@code magnitude} + * and the sign of {@code sign}. + * @since 1.6 + */ +// public static float copySign(float magnitude, float sign) { +// return sun.misc.FpUtils.rawCopySign(magnitude, sign); +// } + + /** + * Returns the unbiased exponent used in the representation of a + * {@code float}. Special cases: + * + *
    + *
  • If the argument is NaN or infinite, then the result is + * {@link Float#MAX_EXPONENT} + 1. + *
  • If the argument is zero or subnormal, then the result is + * {@link Float#MIN_EXPONENT} -1. + *
+ * @param f a {@code float} value + * @return the unbiased exponent of the argument + * @since 1.6 + */ +// public static int getExponent(float f) { +// return sun.misc.FpUtils.getExponent(f); +// } + + /** + * Returns the unbiased exponent used in the representation of a + * {@code double}. Special cases: + * + *
    + *
  • If the argument is NaN or infinite, then the result is + * {@link Double#MAX_EXPONENT} + 1. + *
  • If the argument is zero or subnormal, then the result is + * {@link Double#MIN_EXPONENT} -1. + *
+ * @param d a {@code double} value + * @return the unbiased exponent of the argument + * @since 1.6 + */ +// public static int getExponent(double d) { +// return sun.misc.FpUtils.getExponent(d); +// } + + /** + * Returns the floating-point number adjacent to the first + * argument in the direction of the second argument. If both + * arguments compare as equal the second argument is returned. + * + *

+ * Special cases: + *

    + *
  • If either argument is a NaN, then NaN is returned. + * + *
  • If both arguments are signed zeros, {@code direction} + * is returned unchanged (as implied by the requirement of + * returning the second argument if the arguments compare as + * equal). + * + *
  • If {@code start} is + * ±{@link Double#MIN_VALUE} and {@code direction} + * has a value such that the result should have a smaller + * magnitude, then a zero with the same sign as {@code start} + * is returned. + * + *
  • If {@code start} is infinite and + * {@code direction} has a value such that the result should + * have a smaller magnitude, {@link Double#MAX_VALUE} with the + * same sign as {@code start} is returned. + * + *
  • If {@code start} is equal to ± + * {@link Double#MAX_VALUE} and {@code direction} has a + * value such that the result should have a larger magnitude, an + * infinity with same sign as {@code start} is returned. + *
+ * + * @param start starting floating-point value + * @param direction value indicating which of + * {@code start}'s neighbors or {@code start} should + * be returned + * @return The floating-point number adjacent to {@code start} in the + * direction of {@code direction}. + * @since 1.6 + */ +// public static double nextAfter(double start, double direction) { +// return sun.misc.FpUtils.nextAfter(start, direction); +// } + + /** + * Returns the floating-point number adjacent to the first + * argument in the direction of the second argument. If both + * arguments compare as equal a value equivalent to the second argument + * is returned. + * + *

+ * Special cases: + *

    + *
  • If either argument is a NaN, then NaN is returned. + * + *
  • If both arguments are signed zeros, a value equivalent + * to {@code direction} is returned. + * + *
  • If {@code start} is + * ±{@link Float#MIN_VALUE} and {@code direction} + * has a value such that the result should have a smaller + * magnitude, then a zero with the same sign as {@code start} + * is returned. + * + *
  • If {@code start} is infinite and + * {@code direction} has a value such that the result should + * have a smaller magnitude, {@link Float#MAX_VALUE} with the + * same sign as {@code start} is returned. + * + *
  • If {@code start} is equal to ± + * {@link Float#MAX_VALUE} and {@code direction} has a + * value such that the result should have a larger magnitude, an + * infinity with same sign as {@code start} is returned. + *
+ * + * @param start starting floating-point value + * @param direction value indicating which of + * {@code start}'s neighbors or {@code start} should + * be returned + * @return The floating-point number adjacent to {@code start} in the + * direction of {@code direction}. + * @since 1.6 + */ +// public static float nextAfter(float start, double direction) { +// return sun.misc.FpUtils.nextAfter(start, direction); +// } + + /** + * Returns the floating-point value adjacent to {@code d} in + * the direction of positive infinity. This method is + * semantically equivalent to {@code nextAfter(d, + * Double.POSITIVE_INFINITY)}; however, a {@code nextUp} + * implementation may run faster than its equivalent + * {@code nextAfter} call. + * + *

Special Cases: + *

    + *
  • If the argument is NaN, the result is NaN. + * + *
  • If the argument is positive infinity, the result is + * positive infinity. + * + *
  • If the argument is zero, the result is + * {@link Double#MIN_VALUE} + * + *
+ * + * @param d starting floating-point value + * @return The adjacent floating-point value closer to positive + * infinity. + * @since 1.6 + */ +// public static double nextUp(double d) { +// return sun.misc.FpUtils.nextUp(d); +// } + + /** + * Returns the floating-point value adjacent to {@code f} in + * the direction of positive infinity. This method is + * semantically equivalent to {@code nextAfter(f, + * Float.POSITIVE_INFINITY)}; however, a {@code nextUp} + * implementation may run faster than its equivalent + * {@code nextAfter} call. + * + *

Special Cases: + *

    + *
  • If the argument is NaN, the result is NaN. + * + *
  • If the argument is positive infinity, the result is + * positive infinity. + * + *
  • If the argument is zero, the result is + * {@link Float#MIN_VALUE} + * + *
+ * + * @param f starting floating-point value + * @return The adjacent floating-point value closer to positive + * infinity. + * @since 1.6 + */ +// public static float nextUp(float f) { +// return sun.misc.FpUtils.nextUp(f); +// } + + + /** + * Return {@code d} × + * 2{@code scaleFactor} rounded as if performed + * by a single correctly rounded floating-point multiply to a + * member of the double value set. See the Java + * Language Specification for a discussion of floating-point + * value sets. If the exponent of the result is between {@link + * Double#MIN_EXPONENT} and {@link Double#MAX_EXPONENT}, the + * answer is calculated exactly. If the exponent of the result + * would be larger than {@code Double.MAX_EXPONENT}, an + * infinity is returned. Note that if the result is subnormal, + * precision may be lost; that is, when {@code scalb(x, n)} + * is subnormal, {@code scalb(scalb(x, n), -n)} may not equal + * x. When the result is non-NaN, the result has the same + * sign as {@code d}. + * + *

Special cases: + *

    + *
  • If the first argument is NaN, NaN is returned. + *
  • If the first argument is infinite, then an infinity of the + * same sign is returned. + *
  • If the first argument is zero, then a zero of the same + * sign is returned. + *
+ * + * @param d number to be scaled by a power of two. + * @param scaleFactor power of 2 used to scale {@code d} + * @return {@code d} × 2{@code scaleFactor} + * @since 1.6 + */ +// public static double scalb(double d, int scaleFactor) { +// return sun.misc.FpUtils.scalb(d, scaleFactor); +// } + + /** + * Return {@code f} × + * 2{@code scaleFactor} rounded as if performed + * by a single correctly rounded floating-point multiply to a + * member of the float value set. See the Java + * Language Specification for a discussion of floating-point + * value sets. If the exponent of the result is between {@link + * Float#MIN_EXPONENT} and {@link Float#MAX_EXPONENT}, the + * answer is calculated exactly. If the exponent of the result + * would be larger than {@code Float.MAX_EXPONENT}, an + * infinity is returned. Note that if the result is subnormal, + * precision may be lost; that is, when {@code scalb(x, n)} + * is subnormal, {@code scalb(scalb(x, n), -n)} may not equal + * x. When the result is non-NaN, the result has the same + * sign as {@code f}. + * + *

Special cases: + *

    + *
  • If the first argument is NaN, NaN is returned. + *
  • If the first argument is infinite, then an infinity of the + * same sign is returned. + *
  • If the first argument is zero, then a zero of the same + * sign is returned. + *
+ * + * @param f number to be scaled by a power of two. + * @param scaleFactor power of 2 used to scale {@code f} + * @return {@code f} × 2{@code scaleFactor} + * @since 1.6 + */ +// public static float scalb(float f, int scaleFactor) { +// return sun.misc.FpUtils.scalb(f, scaleFactor); +// } +} diff -r 388e48c0a37a -r 05224402145d emul/mini/src/main/java/java/lang/NegativeArraySizeException.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/emul/mini/src/main/java/java/lang/NegativeArraySizeException.java Wed Jan 23 20:39:23 2013 +0100 @@ -0,0 +1,55 @@ +/* + * Copyright (c) 1994, 2008, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code 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 + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package java.lang; + +/** + * Thrown if an application tries to create an array with negative size. + * + * @author unascribed + * @since JDK1.0 + */ +public +class NegativeArraySizeException extends RuntimeException { + private static final long serialVersionUID = -8960118058596991861L; + + /** + * Constructs a NegativeArraySizeException with no + * detail message. + */ + public NegativeArraySizeException() { + super(); + } + + /** + * Constructs a NegativeArraySizeException with the + * specified detail message. + * + * @param s the detail message. + */ + public NegativeArraySizeException(String s) { + super(s); + } +} diff -r 388e48c0a37a -r 05224402145d emul/mini/src/main/java/java/lang/NoSuchMethodException.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/emul/mini/src/main/java/java/lang/NoSuchMethodException.java Wed Jan 23 20:39:23 2013 +0100 @@ -0,0 +1,53 @@ +/* + * Copyright (c) 1995, 2008, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code 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 + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package java.lang; + +/** + * Thrown when a particular method cannot be found. + * + * @author unascribed + * @since JDK1.0 + */ +public +class NoSuchMethodException extends ReflectiveOperationException { + private static final long serialVersionUID = 5034388446362600923L; + + /** + * Constructs a NoSuchMethodException without a detail message. + */ + public NoSuchMethodException() { + super(); + } + + /** + * Constructs a NoSuchMethodException with a detail message. + * + * @param s the detail message. + */ + public NoSuchMethodException(String s) { + super(s); + } +} diff -r 388e48c0a37a -r 05224402145d emul/mini/src/main/java/java/lang/NullPointerException.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/emul/mini/src/main/java/java/lang/NullPointerException.java Wed Jan 23 20:39:23 2013 +0100 @@ -0,0 +1,72 @@ +/* + * Copyright (c) 1994, 2011, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code 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 + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package java.lang; + +/** + * Thrown when an application attempts to use {@code null} in a + * case where an object is required. These include: + *
    + *
  • Calling the instance method of a {@code null} object. + *
  • Accessing or modifying the field of a {@code null} object. + *
  • Taking the length of {@code null} as if it were an array. + *
  • Accessing or modifying the slots of {@code null} as if it + * were an array. + *
  • Throwing {@code null} as if it were a {@code Throwable} + * value. + *
+ *

+ * Applications should throw instances of this class to indicate + * other illegal uses of the {@code null} object. + * + * {@code NullPointerException} objects may be constructed by the + * virtual machine as if {@linkplain Throwable#Throwable(String, + * Throwable, boolean, boolean) suppression were disabled and/or the + * stack trace was not writable}. + * + * @author unascribed + * @since JDK1.0 + */ +public +class NullPointerException extends RuntimeException { + private static final long serialVersionUID = 5162710183389028792L; + + /** + * Constructs a {@code NullPointerException} with no detail message. + */ + public NullPointerException() { + super(); + } + + /** + * Constructs a {@code NullPointerException} with the specified + * detail message. + * + * @param s the detail message. + */ + public NullPointerException(String s) { + super(s); + } +} diff -r 388e48c0a37a -r 05224402145d emul/mini/src/main/java/java/lang/Number.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/emul/mini/src/main/java/java/lang/Number.java Wed Jan 23 20:39:23 2013 +0100 @@ -0,0 +1,118 @@ +/* + * Copyright (c) 1994, 2001, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code 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 + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package java.lang; + +import org.apidesign.bck2brwsr.core.ExtraJavaScript; + +/** + * The abstract class Number is the superclass of classes + * BigDecimal, BigInteger, + * Byte, Double, Float, + * Integer, Long, and Short. + *

+ * Subclasses of Number must provide methods to convert + * the represented numeric value to byte, double, + * float, int, long, and + * short. + * + * @author Lee Boynton + * @author Arthur van Hoff + * @see java.lang.Byte + * @see java.lang.Double + * @see java.lang.Float + * @see java.lang.Integer + * @see java.lang.Long + * @see java.lang.Short + * @since JDK1.0 + */ +@ExtraJavaScript( + resource="/org/apidesign/vm4brwsr/emul/java_lang_Number.js", + processByteCode=true +) +public abstract class Number implements java.io.Serializable { + /** + * Returns the value of the specified number as an int. + * This may involve rounding or truncation. + * + * @return the numeric value represented by this object after conversion + * to type int. + */ + public abstract int intValue(); + + /** + * Returns the value of the specified number as a long. + * This may involve rounding or truncation. + * + * @return the numeric value represented by this object after conversion + * to type long. + */ + public abstract long longValue(); + + /** + * Returns the value of the specified number as a float. + * This may involve rounding. + * + * @return the numeric value represented by this object after conversion + * to type float. + */ + public abstract float floatValue(); + + /** + * Returns the value of the specified number as a double. + * This may involve rounding. + * + * @return the numeric value represented by this object after conversion + * to type double. + */ + public abstract double doubleValue(); + + /** + * Returns the value of the specified number as a byte. + * This may involve rounding or truncation. + * + * @return the numeric value represented by this object after conversion + * to type byte. + * @since JDK1.1 + */ + public byte byteValue() { + return (byte)intValue(); + } + + /** + * Returns the value of the specified number as a short. + * This may involve rounding or truncation. + * + * @return the numeric value represented by this object after conversion + * to type short. + * @since JDK1.1 + */ + public short shortValue() { + return (short)intValue(); + } + + /** use serialVersionUID from JDK 1.0.2 for interoperability */ + private static final long serialVersionUID = -8742448824652078965L; +} diff -r 388e48c0a37a -r 05224402145d emul/mini/src/main/java/java/lang/NumberFormatException.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/emul/mini/src/main/java/java/lang/NumberFormatException.java Wed Jan 23 20:39:23 2013 +0100 @@ -0,0 +1,67 @@ +/* + * Copyright (c) 1994, 2001, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code 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 + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package java.lang; + +/** + * Thrown to indicate that the application has attempted to convert + * a string to one of the numeric types, but that the string does not + * have the appropriate format. + * + * @author unascribed + * @see java.lang.Integer#toString() + * @since JDK1.0 + */ +public +class NumberFormatException extends IllegalArgumentException { + static final long serialVersionUID = -2848938806368998894L; + + /** + * Constructs a NumberFormatException with no detail message. + */ + public NumberFormatException () { + super(); + } + + /** + * Constructs a NumberFormatException with the + * specified detail message. + * + * @param s the detail message. + */ + public NumberFormatException (String s) { + super (s); + } + + /** + * Factory method for making a NumberFormatException + * given the specified input which caused the error. + * + * @param s the input causing the error + */ + static NumberFormatException forInputString(String s) { + return new NumberFormatException("For input string: \"" + s + "\""); + } +} diff -r 388e48c0a37a -r 05224402145d emul/mini/src/main/java/java/lang/Object.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/emul/mini/src/main/java/java/lang/Object.java Wed Jan 23 20:39:23 2013 +0100 @@ -0,0 +1,595 @@ +/* + * Copyright (c) 1994, 2010, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code 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 + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package java.lang; + +import java.lang.reflect.Array; +import org.apidesign.bck2brwsr.core.JavaScriptBody; +import org.apidesign.bck2brwsr.core.JavaScriptPrototype; + +/** + * Class {@code Object} is the root of the class hierarchy. + * Every class has {@code Object} as a superclass. All objects, + * including arrays, implement the methods of this class. + * + * @author unascribed + * @see java.lang.Class + * @since JDK1.0 + */ +@JavaScriptPrototype(container = "Object.prototype", prototype = "new Object") +public class Object { + + private static void registerNatives() { + try { + Array.get(null, 0); + } catch (Throwable ex) { + // ignore + } + } + static { + registerNatives(); + } + + /** + * Returns the runtime class of this {@code Object}. The returned + * {@code Class} object is the object that is locked by {@code + * static synchronized} methods of the represented class. + * + *

The actual result type is {@code Class} + * where {@code |X|} is the erasure of the static type of the + * expression on which {@code getClass} is called. For + * example, no cast is required in this code fragment:

+ * + *

+ * {@code Number n = 0; }
+ * {@code Class c = n.getClass(); } + *

+ * + * @return The {@code Class} object that represents the runtime + * class of this object. + * @see Class Literals, section 15.8.2 of + * The Java™ Language Specification. + */ + @JavaScriptBody(args={}, body="return this.constructor.$class;") + public final native Class getClass(); + + /** + * Returns a hash code value for the object. This method is + * supported for the benefit of hash tables such as those provided by + * {@link java.util.HashMap}. + *

+ * The general contract of {@code hashCode} is: + *

    + *
  • Whenever it is invoked on the same object more than once during + * an execution of a Java application, the {@code hashCode} method + * must consistently return the same integer, provided no information + * used in {@code equals} comparisons on the object is modified. + * This integer need not remain consistent from one execution of an + * application to another execution of the same application. + *
  • If two objects are equal according to the {@code equals(Object)} + * method, then calling the {@code hashCode} method on each of + * the two objects must produce the same integer result. + *
  • It is not required that if two objects are unequal + * according to the {@link java.lang.Object#equals(java.lang.Object)} + * method, then calling the {@code hashCode} method on each of the + * two objects must produce distinct integer results. However, the + * programmer should be aware that producing distinct integer results + * for unequal objects may improve the performance of hash tables. + *
+ *

+ * As much as is reasonably practical, the hashCode method defined by + * class {@code Object} does return distinct integers for distinct + * objects. (This is typically implemented by converting the internal + * address of the object into an integer, but this implementation + * technique is not required by the + * JavaTM programming language.) + * + * @return a hash code value for this object. + * @see java.lang.Object#equals(java.lang.Object) + * @see java.lang.System#identityHashCode + */ + @JavaScriptBody(args = {}, body = + "if (this.$hashCode) return this.$hashCode;\n" + + "var h = this.computeHashCode__I();\n" + + "return this.$hashCode = h & h;" + ) + public native int hashCode(); + + @JavaScriptBody(args = {}, body = "Math.random() * Math.pow(2, 32);") + native int computeHashCode(); + + /** + * Indicates whether some other object is "equal to" this one. + *

+ * The {@code equals} method implements an equivalence relation + * on non-null object references: + *

    + *
  • It is reflexive: for any non-null reference value + * {@code x}, {@code x.equals(x)} should return + * {@code true}. + *
  • It is symmetric: for any non-null reference values + * {@code x} and {@code y}, {@code x.equals(y)} + * should return {@code true} if and only if + * {@code y.equals(x)} returns {@code true}. + *
  • It is transitive: for any non-null reference values + * {@code x}, {@code y}, and {@code z}, if + * {@code x.equals(y)} returns {@code true} and + * {@code y.equals(z)} returns {@code true}, then + * {@code x.equals(z)} should return {@code true}. + *
  • It is consistent: for any non-null reference values + * {@code x} and {@code y}, multiple invocations of + * {@code x.equals(y)} consistently return {@code true} + * or consistently return {@code false}, provided no + * information used in {@code equals} comparisons on the + * objects is modified. + *
  • For any non-null reference value {@code x}, + * {@code x.equals(null)} should return {@code false}. + *
+ *

+ * The {@code equals} method for class {@code Object} implements + * the most discriminating possible equivalence relation on objects; + * that is, for any non-null reference values {@code x} and + * {@code y}, this method returns {@code true} if and only + * if {@code x} and {@code y} refer to the same object + * ({@code x == y} has the value {@code true}). + *

+ * Note that it is generally necessary to override the {@code hashCode} + * method whenever this method is overridden, so as to maintain the + * general contract for the {@code hashCode} method, which states + * that equal objects must have equal hash codes. + * + * @param obj the reference object with which to compare. + * @return {@code true} if this object is the same as the obj + * argument; {@code false} otherwise. + * @see #hashCode() + * @see java.util.HashMap + */ + public boolean equals(Object obj) { + return (this == obj); + } + + /** + * Creates and returns a copy of this object. The precise meaning + * of "copy" may depend on the class of the object. The general + * intent is that, for any object {@code x}, the expression: + *

+ *
+     * x.clone() != x
+ * will be true, and that the expression: + *
+ *
+     * x.clone().getClass() == x.getClass()
+ * will be {@code true}, but these are not absolute requirements. + * While it is typically the case that: + *
+ *
+     * x.clone().equals(x)
+ * will be {@code true}, this is not an absolute requirement. + *

+ * By convention, the returned object should be obtained by calling + * {@code super.clone}. If a class and all of its superclasses (except + * {@code Object}) obey this convention, it will be the case that + * {@code x.clone().getClass() == x.getClass()}. + *

+ * By convention, the object returned by this method should be independent + * of this object (which is being cloned). To achieve this independence, + * it may be necessary to modify one or more fields of the object returned + * by {@code super.clone} before returning it. Typically, this means + * copying any mutable objects that comprise the internal "deep structure" + * of the object being cloned and replacing the references to these + * objects with references to the copies. If a class contains only + * primitive fields or references to immutable objects, then it is usually + * the case that no fields in the object returned by {@code super.clone} + * need to be modified. + *

+ * The method {@code clone} for class {@code Object} performs a + * specific cloning operation. First, if the class of this object does + * not implement the interface {@code Cloneable}, then a + * {@code CloneNotSupportedException} is thrown. Note that all arrays + * are considered to implement the interface {@code Cloneable} and that + * the return type of the {@code clone} method of an array type {@code T[]} + * is {@code T[]} where T is any reference or primitive type. + * Otherwise, this method creates a new instance of the class of this + * object and initializes all its fields with exactly the contents of + * the corresponding fields of this object, as if by assignment; the + * contents of the fields are not themselves cloned. Thus, this method + * performs a "shallow copy" of this object, not a "deep copy" operation. + *

+ * The class {@code Object} does not itself implement the interface + * {@code Cloneable}, so calling the {@code clone} method on an object + * whose class is {@code Object} will result in throwing an + * exception at run time. + * + * @return a clone of this instance. + * @exception CloneNotSupportedException if the object's class does not + * support the {@code Cloneable} interface. Subclasses + * that override the {@code clone} method can also + * throw this exception to indicate that an instance cannot + * be cloned. + * @see java.lang.Cloneable + */ + protected Object clone() throws CloneNotSupportedException { + Object ret = clone(this); + if (ret == null) { + throw new CloneNotSupportedException(getClass().getName()); + } + return ret; + } + + @JavaScriptBody(args = "self", body = + "\nif (!self.$instOf_java_lang_Cloneable) {" + + "\n return null;" + + "\n} else {" + + "\n var clone = self.constructor(true);" + + "\n var props = Object.getOwnPropertyNames(self);" + + "\n for (var i = 0; i < props.length; i++) {" + + "\n var p = props[i];" + + "\n clone[p] = self[p];" + + "\n };" + + "\n return clone;" + + "\n}" + ) + private static native Object clone(Object self) throws CloneNotSupportedException; + + /** + * Returns a string representation of the object. In general, the + * {@code toString} method returns a string that + * "textually represents" this object. The result should + * be a concise but informative representation that is easy for a + * person to read. + * It is recommended that all subclasses override this method. + *

+ * The {@code toString} method for class {@code Object} + * returns a string consisting of the name of the class of which the + * object is an instance, the at-sign character `{@code @}', and + * the unsigned hexadecimal representation of the hash code of the + * object. In other words, this method returns a string equal to the + * value of: + *

+ *
+     * getClass().getName() + '@' + Integer.toHexString(hashCode())
+     * 
+ * + * @return a string representation of the object. + */ + public String toString() { + return getClass().getName() + "@" + Integer.toHexString(hashCode()); + } + + /** + * Wakes up a single thread that is waiting on this object's + * monitor. If any threads are waiting on this object, one of them + * is chosen to be awakened. The choice is arbitrary and occurs at + * the discretion of the implementation. A thread waits on an object's + * monitor by calling one of the {@code wait} methods. + *

+ * The awakened thread will not be able to proceed until the current + * thread relinquishes the lock on this object. The awakened thread will + * compete in the usual manner with any other threads that might be + * actively competing to synchronize on this object; for example, the + * awakened thread enjoys no reliable privilege or disadvantage in being + * the next thread to lock this object. + *

+ * This method should only be called by a thread that is the owner + * of this object's monitor. A thread becomes the owner of the + * object's monitor in one of three ways: + *

    + *
  • By executing a synchronized instance method of that object. + *
  • By executing the body of a {@code synchronized} statement + * that synchronizes on the object. + *
  • For objects of type {@code Class,} by executing a + * synchronized static method of that class. + *
+ *

+ * Only one thread at a time can own an object's monitor. + * + * @exception IllegalMonitorStateException if the current thread is not + * the owner of this object's monitor. + * @see java.lang.Object#notifyAll() + * @see java.lang.Object#wait() + */ + public final native void notify(); + + /** + * Wakes up all threads that are waiting on this object's monitor. A + * thread waits on an object's monitor by calling one of the + * {@code wait} methods. + *

+ * The awakened threads will not be able to proceed until the current + * thread relinquishes the lock on this object. The awakened threads + * will compete in the usual manner with any other threads that might + * be actively competing to synchronize on this object; for example, + * the awakened threads enjoy no reliable privilege or disadvantage in + * being the next thread to lock this object. + *

+ * This method should only be called by a thread that is the owner + * of this object's monitor. See the {@code notify} method for a + * description of the ways in which a thread can become the owner of + * a monitor. + * + * @exception IllegalMonitorStateException if the current thread is not + * the owner of this object's monitor. + * @see java.lang.Object#notify() + * @see java.lang.Object#wait() + */ + public final native void notifyAll(); + + /** + * Causes the current thread to wait until either another thread invokes the + * {@link java.lang.Object#notify()} method or the + * {@link java.lang.Object#notifyAll()} method for this object, or a + * specified amount of time has elapsed. + *

+ * The current thread must own this object's monitor. + *

+ * This method causes the current thread (call it T) to + * place itself in the wait set for this object and then to relinquish + * any and all synchronization claims on this object. Thread T + * becomes disabled for thread scheduling purposes and lies dormant + * until one of four things happens: + *

    + *
  • Some other thread invokes the {@code notify} method for this + * object and thread T happens to be arbitrarily chosen as + * the thread to be awakened. + *
  • Some other thread invokes the {@code notifyAll} method for this + * object. + *
  • Some other thread {@linkplain Thread#interrupt() interrupts} + * thread T. + *
  • The specified amount of real time has elapsed, more or less. If + * {@code timeout} is zero, however, then real time is not taken into + * consideration and the thread simply waits until notified. + *
+ * The thread T is then removed from the wait set for this + * object and re-enabled for thread scheduling. It then competes in the + * usual manner with other threads for the right to synchronize on the + * object; once it has gained control of the object, all its + * synchronization claims on the object are restored to the status quo + * ante - that is, to the situation as of the time that the {@code wait} + * method was invoked. Thread T then returns from the + * invocation of the {@code wait} method. Thus, on return from the + * {@code wait} method, the synchronization state of the object and of + * thread {@code T} is exactly as it was when the {@code wait} method + * was invoked. + *

+ * A thread can also wake up without being notified, interrupted, or + * timing out, a so-called spurious wakeup. While this will rarely + * occur in practice, applications must guard against it by testing for + * the condition that should have caused the thread to be awakened, and + * continuing to wait if the condition is not satisfied. In other words, + * waits should always occur in loops, like this one: + *

+     *     synchronized (obj) {
+     *         while (<condition does not hold>)
+     *             obj.wait(timeout);
+     *         ... // Perform action appropriate to condition
+     *     }
+     * 
+ * (For more information on this topic, see Section 3.2.3 in Doug Lea's + * "Concurrent Programming in Java (Second Edition)" (Addison-Wesley, + * 2000), or Item 50 in Joshua Bloch's "Effective Java Programming + * Language Guide" (Addison-Wesley, 2001). + * + *

If the current thread is {@linkplain java.lang.Thread#interrupt() + * interrupted} by any thread before or while it is waiting, then an + * {@code InterruptedException} is thrown. This exception is not + * thrown until the lock status of this object has been restored as + * described above. + * + *

+ * Note that the {@code wait} method, as it places the current thread + * into the wait set for this object, unlocks only this object; any + * other objects on which the current thread may be synchronized remain + * locked while the thread waits. + *

+ * This method should only be called by a thread that is the owner + * of this object's monitor. See the {@code notify} method for a + * description of the ways in which a thread can become the owner of + * a monitor. + * + * @param timeout the maximum time to wait in milliseconds. + * @exception IllegalArgumentException if the value of timeout is + * negative. + * @exception IllegalMonitorStateException if the current thread is not + * the owner of the object's monitor. + * @exception InterruptedException if any thread interrupted the + * current thread before or while the current thread + * was waiting for a notification. The interrupted + * status of the current thread is cleared when + * this exception is thrown. + * @see java.lang.Object#notify() + * @see java.lang.Object#notifyAll() + */ + public final native void wait(long timeout) throws InterruptedException; + + /** + * Causes the current thread to wait until another thread invokes the + * {@link java.lang.Object#notify()} method or the + * {@link java.lang.Object#notifyAll()} method for this object, or + * some other thread interrupts the current thread, or a certain + * amount of real time has elapsed. + *

+ * This method is similar to the {@code wait} method of one + * argument, but it allows finer control over the amount of time to + * wait for a notification before giving up. The amount of real time, + * measured in nanoseconds, is given by: + *

+ *
+     * 1000000*timeout+nanos
+ *

+ * In all other respects, this method does the same thing as the + * method {@link #wait(long)} of one argument. In particular, + * {@code wait(0, 0)} means the same thing as {@code wait(0)}. + *

+ * The current thread must own this object's monitor. The thread + * releases ownership of this monitor and waits until either of the + * following two conditions has occurred: + *

    + *
  • Another thread notifies threads waiting on this object's monitor + * to wake up either through a call to the {@code notify} method + * or the {@code notifyAll} method. + *
  • The timeout period, specified by {@code timeout} + * milliseconds plus {@code nanos} nanoseconds arguments, has + * elapsed. + *
+ *

+ * The thread then waits until it can re-obtain ownership of the + * monitor and resumes execution. + *

+ * As in the one argument version, interrupts and spurious wakeups are + * possible, and this method should always be used in a loop: + *

+     *     synchronized (obj) {
+     *         while (<condition does not hold>)
+     *             obj.wait(timeout, nanos);
+     *         ... // Perform action appropriate to condition
+     *     }
+     * 
+ * This method should only be called by a thread that is the owner + * of this object's monitor. See the {@code notify} method for a + * description of the ways in which a thread can become the owner of + * a monitor. + * + * @param timeout the maximum time to wait in milliseconds. + * @param nanos additional time, in nanoseconds range + * 0-999999. + * @exception IllegalArgumentException if the value of timeout is + * negative or the value of nanos is + * not in the range 0-999999. + * @exception IllegalMonitorStateException if the current thread is not + * the owner of this object's monitor. + * @exception InterruptedException if any thread interrupted the + * current thread before or while the current thread + * was waiting for a notification. The interrupted + * status of the current thread is cleared when + * this exception is thrown. + */ + public final void wait(long timeout, int nanos) throws InterruptedException { + if (timeout < 0) { + throw new IllegalArgumentException("timeout value is negative"); + } + + if (nanos < 0 || nanos > 999999) { + throw new IllegalArgumentException( + "nanosecond timeout value out of range"); + } + + if (nanos >= 500000 || (nanos != 0 && timeout == 0)) { + timeout++; + } + + wait(timeout); + } + + /** + * Causes the current thread to wait until another thread invokes the + * {@link java.lang.Object#notify()} method or the + * {@link java.lang.Object#notifyAll()} method for this object. + * In other words, this method behaves exactly as if it simply + * performs the call {@code wait(0)}. + *

+ * The current thread must own this object's monitor. The thread + * releases ownership of this monitor and waits until another thread + * notifies threads waiting on this object's monitor to wake up + * either through a call to the {@code notify} method or the + * {@code notifyAll} method. The thread then waits until it can + * re-obtain ownership of the monitor and resumes execution. + *

+ * As in the one argument version, interrupts and spurious wakeups are + * possible, and this method should always be used in a loop: + *

+     *     synchronized (obj) {
+     *         while (<condition does not hold>)
+     *             obj.wait();
+     *         ... // Perform action appropriate to condition
+     *     }
+     * 
+ * This method should only be called by a thread that is the owner + * of this object's monitor. See the {@code notify} method for a + * description of the ways in which a thread can become the owner of + * a monitor. + * + * @exception IllegalMonitorStateException if the current thread is not + * the owner of the object's monitor. + * @exception InterruptedException if any thread interrupted the + * current thread before or while the current thread + * was waiting for a notification. The interrupted + * status of the current thread is cleared when + * this exception is thrown. + * @see java.lang.Object#notify() + * @see java.lang.Object#notifyAll() + */ + public final void wait() throws InterruptedException { + wait(0); + } + + /** + * Called by the garbage collector on an object when garbage collection + * determines that there are no more references to the object. + * A subclass overrides the {@code finalize} method to dispose of + * system resources or to perform other cleanup. + *

+ * The general contract of {@code finalize} is that it is invoked + * if and when the JavaTM virtual + * machine has determined that there is no longer any + * means by which this object can be accessed by any thread that has + * not yet died, except as a result of an action taken by the + * finalization of some other object or class which is ready to be + * finalized. The {@code finalize} method may take any action, including + * making this object available again to other threads; the usual purpose + * of {@code finalize}, however, is to perform cleanup actions before + * the object is irrevocably discarded. For example, the finalize method + * for an object that represents an input/output connection might perform + * explicit I/O transactions to break the connection before the object is + * permanently discarded. + *

+ * The {@code finalize} method of class {@code Object} performs no + * special action; it simply returns normally. Subclasses of + * {@code Object} may override this definition. + *

+ * The Java programming language does not guarantee which thread will + * invoke the {@code finalize} method for any given object. It is + * guaranteed, however, that the thread that invokes finalize will not + * be holding any user-visible synchronization locks when finalize is + * invoked. If an uncaught exception is thrown by the finalize method, + * the exception is ignored and finalization of that object terminates. + *

+ * After the {@code finalize} method has been invoked for an object, no + * further action is taken until the Java virtual machine has again + * determined that there is no longer any means by which this object can + * be accessed by any thread that has not yet died, including possible + * actions by other objects or classes which are ready to be finalized, + * at which point the object may be discarded. + *

+ * The {@code finalize} method is never invoked more than once by a Java + * virtual machine for any given object. + *

+ * Any exception thrown by the {@code finalize} method causes + * the finalization of this object to be halted, but is otherwise + * ignored. + * + * @throws Throwable the {@code Exception} raised by this method + */ + protected void finalize() throws Throwable { } +} diff -r 388e48c0a37a -r 05224402145d emul/mini/src/main/java/java/lang/OutOfMemoryError.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/emul/mini/src/main/java/java/lang/OutOfMemoryError.java Wed Jan 23 20:39:23 2013 +0100 @@ -0,0 +1,60 @@ +/* + * Copyright (c) 1994, 2011, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code 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 + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package java.lang; + +/** + * Thrown when the Java Virtual Machine cannot allocate an object + * because it is out of memory, and no more memory could be made + * available by the garbage collector. + * + * {@code OutOfMemoryError} objects may be constructed by the virtual + * machine as if {@linkplain Throwable#Throwable(String, Throwable, + * boolean, boolean) suppression were disabled and/or the stack trace was not + * writable}. + * + * @author unascribed + * @since JDK1.0 + */ +public class OutOfMemoryError extends VirtualMachineError { + private static final long serialVersionUID = 8228564086184010517L; + + /** + * Constructs an {@code OutOfMemoryError} with no detail message. + */ + public OutOfMemoryError() { + super(); + } + + /** + * Constructs an {@code OutOfMemoryError} with the specified + * detail message. + * + * @param s the detail message. + */ + public OutOfMemoryError(String s) { + super(s); + } +} diff -r 388e48c0a37a -r 05224402145d emul/mini/src/main/java/java/lang/ReflectiveOperationException.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/emul/mini/src/main/java/java/lang/ReflectiveOperationException.java Wed Jan 23 20:39:23 2013 +0100 @@ -0,0 +1,91 @@ +/* + * Copyright (c) 2009, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code 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 + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package java.lang; + +/** + * Common superclass of exceptions thrown by reflective operations in + * core reflection. + * + * @see LinkageError + * @since 1.7 + */ +public class ReflectiveOperationException extends Exception { + static final long serialVersionUID = 123456789L; + + /** + * Constructs a new exception with {@code null} as its detail + * message. The cause is not initialized, and may subsequently be + * initialized by a call to {@link #initCause}. + */ + public ReflectiveOperationException() { + super(); + } + + /** + * Constructs a new exception with the specified detail message. + * The cause is not initialized, and may subsequently be + * initialized by a call to {@link #initCause}. + * + * @param message the detail message. The detail message is saved for + * later retrieval by the {@link #getMessage()} method. + */ + public ReflectiveOperationException(String message) { + super(message); + } + + /** + * Constructs a new exception with the specified detail message + * and cause. + * + *

Note that the detail message associated with + * {@code cause} is not automatically incorporated in + * this exception's detail message. + * + * @param message the detail message (which is saved for later retrieval + * by the {@link #getMessage()} method). + * @param cause the cause (which is saved for later retrieval by the + * {@link #getCause()} method). (A {@code null} value is + * permitted, and indicates that the cause is nonexistent or + * unknown.) + */ + public ReflectiveOperationException(String message, Throwable cause) { + super(message, cause); + } + + /** + * Constructs a new exception with the specified cause and a detail + * message of {@code (cause==null ? null : cause.toString())} (which + * typically contains the class and detail message of {@code cause}). + * + * @param cause the cause (which is saved for later retrieval by the + * {@link #getCause()} method). (A {@code null} value is + * permitted, and indicates that the cause is nonexistent or + * unknown.) + */ + public ReflectiveOperationException(Throwable cause) { + super(cause); + } +} diff -r 388e48c0a37a -r 05224402145d emul/mini/src/main/java/java/lang/Runnable.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/emul/mini/src/main/java/java/lang/Runnable.java Wed Jan 23 20:39:23 2013 +0100 @@ -0,0 +1,69 @@ +/* + * Copyright (c) 1994, 2005, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code 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 + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package java.lang; + +/** + * The Runnable interface should be implemented by any + * class whose instances are intended to be executed by a thread. The + * class must define a method of no arguments called run. + *

+ * This interface is designed to provide a common protocol for objects that + * wish to execute code while they are active. For example, + * Runnable is implemented by class Thread. + * Being active simply means that a thread has been started and has not + * yet been stopped. + *

+ * In addition, Runnable provides the means for a class to be + * active while not subclassing Thread. A class that implements + * Runnable can run without subclassing Thread + * by instantiating a Thread instance and passing itself in + * as the target. In most cases, the Runnable interface should + * be used if you are only planning to override the run() + * method and no other Thread methods. + * This is important because classes should not be subclassed + * unless the programmer intends on modifying or enhancing the fundamental + * behavior of the class. + * + * @author Arthur van Hoff + * @see java.lang.Thread + * @see java.util.concurrent.Callable + * @since JDK1.0 + */ +public +interface Runnable { + /** + * When an object implementing interface Runnable is used + * to create a thread, starting the thread causes the object's + * run method to be called in that separately executing + * thread. + *

+ * The general contract of the method run is that it may + * take any action whatsoever. + * + * @see java.lang.Thread#run() + */ + public abstract void run(); +} diff -r 388e48c0a37a -r 05224402145d emul/mini/src/main/java/java/lang/RuntimeException.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/emul/mini/src/main/java/java/lang/RuntimeException.java Wed Jan 23 20:39:23 2013 +0100 @@ -0,0 +1,119 @@ +/* + * Copyright (c) 1995, 2011, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code 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 + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package java.lang; + +/** + * {@code RuntimeException} is the superclass of those + * exceptions that can be thrown during the normal operation of the + * Java Virtual Machine. + * + *

{@code RuntimeException} and its subclasses are unchecked + * exceptions. Unchecked exceptions do not need to be + * declared in a method or constructor's {@code throws} clause if they + * can be thrown by the execution of the method or constructor and + * propagate outside the method or constructor boundary. + * + * @author Frank Yellin + * @jls 11.2 Compile-Time Checking of Exceptions + * @since JDK1.0 + */ +public class RuntimeException extends Exception { + static final long serialVersionUID = -7034897190745766939L; + + /** Constructs a new runtime exception with {@code null} as its + * detail message. The cause is not initialized, and may subsequently be + * initialized by a call to {@link #initCause}. + */ + public RuntimeException() { + super(); + } + + /** Constructs a new runtime exception with the specified detail message. + * The cause is not initialized, and may subsequently be initialized by a + * call to {@link #initCause}. + * + * @param message the detail message. The detail message is saved for + * later retrieval by the {@link #getMessage()} method. + */ + public RuntimeException(String message) { + super(message); + } + + /** + * Constructs a new runtime exception with the specified detail message and + * cause.

Note that the detail message associated with + * {@code cause} is not automatically incorporated in + * this runtime exception's detail message. + * + * @param message the detail message (which is saved for later retrieval + * by the {@link #getMessage()} method). + * @param cause the cause (which is saved for later retrieval by the + * {@link #getCause()} method). (A null value is + * permitted, and indicates that the cause is nonexistent or + * unknown.) + * @since 1.4 + */ + public RuntimeException(String message, Throwable cause) { + super(message, cause); + } + + /** Constructs a new runtime exception with the specified cause and a + * detail message of (cause==null ? null : cause.toString()) + * (which typically contains the class and detail message of + * cause). This constructor is useful for runtime exceptions + * that are little more than wrappers for other throwables. + * + * @param cause the cause (which is saved for later retrieval by the + * {@link #getCause()} method). (A null value is + * permitted, and indicates that the cause is nonexistent or + * unknown.) + * @since 1.4 + */ + public RuntimeException(Throwable cause) { + super(cause); + } + + /** + * Constructs a new runtime exception with the specified detail + * message, cause, suppression enabled or disabled, and writable + * stack trace enabled or disabled. + * + * @param message the detail message. + * @param cause the cause. (A {@code null} value is permitted, + * and indicates that the cause is nonexistent or unknown.) + * @param enableSuppression whether or not suppression is enabled + * or disabled + * @param writableStackTrace whether or not the stack trace should + * be writable + * + * @since 1.7 + */ + protected RuntimeException(String message, Throwable cause, + boolean enableSuppression, + boolean writableStackTrace) { + super(message, cause, enableSuppression, writableStackTrace); + } +} diff -r 388e48c0a37a -r 05224402145d emul/mini/src/main/java/java/lang/SecurityException.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/emul/mini/src/main/java/java/lang/SecurityException.java Wed Jan 23 20:39:23 2013 +0100 @@ -0,0 +1,84 @@ +/* + * Copyright (c) 1995, 2003, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code 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 + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +package java.lang; + +/** + * Thrown by the security manager to indicate a security violation. + * + * @author unascribed + * @see java.lang.SecurityManager + * @since JDK1.0 + */ +public class SecurityException extends RuntimeException { + + private static final long serialVersionUID = 6878364983674394167L; + + /** + * Constructs a SecurityException with no detail message. + */ + public SecurityException() { + super(); + } + + /** + * Constructs a SecurityException with the specified + * detail message. + * + * @param s the detail message. + */ + public SecurityException(String s) { + super(s); + } + + /** + * Creates a SecurityException with the specified + * detail message and cause. + * + * @param message the detail message (which is saved for later retrieval + * by the {@link #getMessage()} method). + * @param cause the cause (which is saved for later retrieval by the + * {@link #getCause()} method). (A null value is permitted, + * and indicates that the cause is nonexistent or unknown.) + * @since 1.5 + */ + public SecurityException(String message, Throwable cause) { + super(message, cause); + } + + /** + * Creates a SecurityException with the specified cause + * and a detail message of (cause==null ? null : cause.toString()) + * (which typically contains the class and detail message of + * cause). + * + * @param cause the cause (which is saved for later retrieval by the + * {@link #getCause()} method). (A null value is permitted, + * and indicates that the cause is nonexistent or unknown.) + * @since 1.5 + */ + public SecurityException(Throwable cause) { + super(cause); + } +} diff -r 388e48c0a37a -r 05224402145d emul/mini/src/main/java/java/lang/Short.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/emul/mini/src/main/java/java/lang/Short.java Wed Jan 23 20:39:23 2013 +0100 @@ -0,0 +1,468 @@ +/* + * Copyright (c) 1996, 2009, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code 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 + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package java.lang; + +/** + * The {@code Short} class wraps a value of primitive type {@code + * short} in an object. An object of type {@code Short} contains a + * single field whose type is {@code short}. + * + *

In addition, this class provides several methods for converting + * a {@code short} to a {@code String} and a {@code String} to a + * {@code short}, as well as other constants and methods useful when + * dealing with a {@code short}. + * + * @author Nakul Saraiya + * @author Joseph D. Darcy + * @see java.lang.Number + * @since JDK1.1 + */ +public final class Short extends Number implements Comparable { + + /** + * A constant holding the minimum value a {@code short} can + * have, -215. + */ + public static final short MIN_VALUE = -32768; + + /** + * A constant holding the maximum value a {@code short} can + * have, 215-1. + */ + public static final short MAX_VALUE = 32767; + + /** + * The {@code Class} instance representing the primitive type + * {@code short}. + */ + public static final Class TYPE = (Class) Class.getPrimitiveClass("short"); + + /** + * Returns a new {@code String} object representing the + * specified {@code short}. The radix is assumed to be 10. + * + * @param s the {@code short} to be converted + * @return the string representation of the specified {@code short} + * @see java.lang.Integer#toString(int) + */ + public static String toString(short s) { + return Integer.toString((int)s, 10); + } + + /** + * Parses the string argument as a signed {@code short} in the + * radix specified by the second argument. The characters in the + * string must all be digits, of the specified radix (as + * determined by whether {@link java.lang.Character#digit(char, + * int)} returns a nonnegative value) except that the first + * character may be an ASCII minus sign {@code '-'} + * ('\u002D') to indicate a negative value or an + * ASCII plus sign {@code '+'} ('\u002B') to + * indicate a positive value. The resulting {@code short} value + * is returned. + * + *

An exception of type {@code NumberFormatException} is + * thrown if any of the following situations occurs: + *

    + *
  • The first argument is {@code null} or is a string of + * length zero. + * + *
  • The radix is either smaller than {@link + * java.lang.Character#MIN_RADIX} or larger than {@link + * java.lang.Character#MAX_RADIX}. + * + *
  • Any character of the string is not a digit of the + * specified radix, except that the first character may be a minus + * sign {@code '-'} ('\u002D') or plus sign + * {@code '+'} ('\u002B') provided that the + * string is longer than length 1. + * + *
  • The value represented by the string is not a value of type + * {@code short}. + *
+ * + * @param s the {@code String} containing the + * {@code short} representation to be parsed + * @param radix the radix to be used while parsing {@code s} + * @return the {@code short} represented by the string + * argument in the specified radix. + * @throws NumberFormatException If the {@code String} + * does not contain a parsable {@code short}. + */ + public static short parseShort(String s, int radix) + throws NumberFormatException { + int i = Integer.parseInt(s, radix); + if (i < MIN_VALUE || i > MAX_VALUE) + throw new NumberFormatException( + "Value out of range. Value:\"" + s + "\" Radix:" + radix); + return (short)i; + } + + /** + * Parses the string argument as a signed decimal {@code + * short}. The characters in the string must all be decimal + * digits, except that the first character may be an ASCII minus + * sign {@code '-'} ('\u002D') to indicate a + * negative value or an ASCII plus sign {@code '+'} + * ('\u002B') to indicate a positive value. The + * resulting {@code short} value is returned, exactly as if the + * argument and the radix 10 were given as arguments to the {@link + * #parseShort(java.lang.String, int)} method. + * + * @param s a {@code String} containing the {@code short} + * representation to be parsed + * @return the {@code short} value represented by the + * argument in decimal. + * @throws NumberFormatException If the string does not + * contain a parsable {@code short}. + */ + public static short parseShort(String s) throws NumberFormatException { + return parseShort(s, 10); + } + + /** + * Returns a {@code Short} object holding the value + * extracted from the specified {@code String} when parsed + * with the radix given by the second argument. The first argument + * is interpreted as representing a signed {@code short} in + * the radix specified by the second argument, exactly as if the + * argument were given to the {@link #parseShort(java.lang.String, + * int)} method. The result is a {@code Short} object that + * represents the {@code short} value specified by the string. + * + *

In other words, this method returns a {@code Short} object + * equal to the value of: + * + *

+ * {@code new Short(Short.parseShort(s, radix))} + *
+ * + * @param s the string to be parsed + * @param radix the radix to be used in interpreting {@code s} + * @return a {@code Short} object holding the value + * represented by the string argument in the + * specified radix. + * @throws NumberFormatException If the {@code String} does + * not contain a parsable {@code short}. + */ + public static Short valueOf(String s, int radix) + throws NumberFormatException { + return valueOf(parseShort(s, radix)); + } + + /** + * Returns a {@code Short} object holding the + * value given by the specified {@code String}. The argument + * is interpreted as representing a signed decimal + * {@code short}, exactly as if the argument were given to + * the {@link #parseShort(java.lang.String)} method. The result is + * a {@code Short} object that represents the + * {@code short} value specified by the string. + * + *

In other words, this method returns a {@code Short} object + * equal to the value of: + * + *

+ * {@code new Short(Short.parseShort(s))} + *
+ * + * @param s the string to be parsed + * @return a {@code Short} object holding the value + * represented by the string argument + * @throws NumberFormatException If the {@code String} does + * not contain a parsable {@code short}. + */ + public static Short valueOf(String s) throws NumberFormatException { + return valueOf(s, 10); + } + + private static class ShortCache { + private ShortCache(){} + + static final Short cache[] = new Short[-(-128) + 127 + 1]; + + static { + for(int i = 0; i < cache.length; i++) + cache[i] = new Short((short)(i - 128)); + } + } + + /** + * Returns a {@code Short} instance representing the specified + * {@code short} value. + * If a new {@code Short} instance is not required, this method + * should generally be used in preference to the constructor + * {@link #Short(short)}, as this method is likely to yield + * significantly better space and time performance by caching + * frequently requested values. + * + * This method will always cache values in the range -128 to 127, + * inclusive, and may cache other values outside of this range. + * + * @param s a short value. + * @return a {@code Short} instance representing {@code s}. + * @since 1.5 + */ + public static Short valueOf(short s) { + final int offset = 128; + int sAsInt = s; + if (sAsInt >= -128 && sAsInt <= 127) { // must cache + return ShortCache.cache[sAsInt + offset]; + } + return new Short(s); + } + + /** + * Decodes a {@code String} into a {@code Short}. + * Accepts decimal, hexadecimal, and octal numbers given by + * the following grammar: + * + *
+ *
+ *
DecodableString: + *
Signopt DecimalNumeral + *
Signopt {@code 0x} HexDigits + *
Signopt {@code 0X} HexDigits + *
Signopt {@code #} HexDigits + *
Signopt {@code 0} OctalDigits + *

+ *

Sign: + *
{@code -} + *
{@code +} + *
+ *
+ * + * DecimalNumeral, HexDigits, and OctalDigits + * are as defined in section 3.10.1 of + * The Java™ Language Specification, + * except that underscores are not accepted between digits. + * + *

The sequence of characters following an optional + * sign and/or radix specifier ("{@code 0x}", "{@code 0X}", + * "{@code #}", or leading zero) is parsed as by the {@code + * Short.parseShort} method with the indicated radix (10, 16, or + * 8). This sequence of characters must represent a positive + * value or a {@link NumberFormatException} will be thrown. The + * result is negated if first character of the specified {@code + * String} is the minus sign. No whitespace characters are + * permitted in the {@code String}. + * + * @param nm the {@code String} to decode. + * @return a {@code Short} object holding the {@code short} + * value represented by {@code nm} + * @throws NumberFormatException if the {@code String} does not + * contain a parsable {@code short}. + * @see java.lang.Short#parseShort(java.lang.String, int) + */ + public static Short decode(String nm) throws NumberFormatException { + int i = Integer.decode(nm); + if (i < MIN_VALUE || i > MAX_VALUE) + throw new NumberFormatException( + "Value " + i + " out of range from input " + nm); + return valueOf((short)i); + } + + /** + * The value of the {@code Short}. + * + * @serial + */ + private final short value; + + /** + * Constructs a newly allocated {@code Short} object that + * represents the specified {@code short} value. + * + * @param value the value to be represented by the + * {@code Short}. + */ + public Short(short value) { + this.value = value; + } + + /** + * Constructs a newly allocated {@code Short} object that + * represents the {@code short} value indicated by the + * {@code String} parameter. The string is converted to a + * {@code short} value in exactly the manner used by the + * {@code parseShort} method for radix 10. + * + * @param s the {@code String} to be converted to a + * {@code Short} + * @throws NumberFormatException If the {@code String} + * does not contain a parsable {@code short}. + * @see java.lang.Short#parseShort(java.lang.String, int) + */ + public Short(String s) throws NumberFormatException { + this.value = parseShort(s, 10); + } + + /** + * Returns the value of this {@code Short} as a + * {@code byte}. + */ + public byte byteValue() { + return (byte)value; + } + + /** + * Returns the value of this {@code Short} as a + * {@code short}. + */ + public short shortValue() { + return value; + } + + /** + * Returns the value of this {@code Short} as an + * {@code int}. + */ + public int intValue() { + return (int)value; + } + + /** + * Returns the value of this {@code Short} as a + * {@code long}. + */ + public long longValue() { + return (long)value; + } + + /** + * Returns the value of this {@code Short} as a + * {@code float}. + */ + public float floatValue() { + return (float)value; + } + + /** + * Returns the value of this {@code Short} as a + * {@code double}. + */ + public double doubleValue() { + return (double)value; + } + + /** + * Returns a {@code String} object representing this + * {@code Short}'s value. The value is converted to signed + * decimal representation and returned as a string, exactly as if + * the {@code short} value were given as an argument to the + * {@link java.lang.Short#toString(short)} method. + * + * @return a string representation of the value of this object in + * base 10. + */ + public String toString() { + return Integer.toString((int)value); + } + + /** + * Returns a hash code for this {@code Short}; equal to the result + * of invoking {@code intValue()}. + * + * @return a hash code value for this {@code Short} + */ + public int hashCode() { + return (int)value; + } + + /** + * Compares this object to the specified object. The result is + * {@code true} if and only if the argument is not + * {@code null} and is a {@code Short} object that + * contains the same {@code short} value as this object. + * + * @param obj the object to compare with + * @return {@code true} if the objects are the same; + * {@code false} otherwise. + */ + public boolean equals(Object obj) { + if (obj instanceof Short) { + return value == ((Short)obj).shortValue(); + } + return false; + } + + /** + * Compares two {@code Short} objects numerically. + * + * @param anotherShort the {@code Short} to be compared. + * @return the value {@code 0} if this {@code Short} is + * equal to the argument {@code Short}; a value less than + * {@code 0} if this {@code Short} is numerically less + * than the argument {@code Short}; and a value greater than + * {@code 0} if this {@code Short} is numerically + * greater than the argument {@code Short} (signed + * comparison). + * @since 1.2 + */ + public int compareTo(Short anotherShort) { + return compare(this.value, anotherShort.value); + } + + /** + * Compares two {@code short} values numerically. + * The value returned is identical to what would be returned by: + *

+     *    Short.valueOf(x).compareTo(Short.valueOf(y))
+     * 
+ * + * @param x the first {@code short} to compare + * @param y the second {@code short} to compare + * @return the value {@code 0} if {@code x == y}; + * a value less than {@code 0} if {@code x < y}; and + * a value greater than {@code 0} if {@code x > y} + * @since 1.7 + */ + public static int compare(short x, short y) { + return x - y; + } + + /** + * The number of bits used to represent a {@code short} value in two's + * complement binary form. + * @since 1.5 + */ + public static final int SIZE = 16; + + /** + * Returns the value obtained by reversing the order of the bytes in the + * two's complement representation of the specified {@code short} value. + * + * @return the value obtained by reversing (or, equivalently, swapping) + * the bytes in the specified {@code short} value. + * @since 1.5 + */ + public static short reverseBytes(short i) { + return (short) (((i & 0xFF00) >> 8) | (i << 8)); + } + + /** use serialVersionUID from JDK 1.1. for interoperability */ + private static final long serialVersionUID = 7515723908773894738L; +} diff -r 388e48c0a37a -r 05224402145d emul/mini/src/main/java/java/lang/StackTraceElement.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/emul/mini/src/main/java/java/lang/StackTraceElement.java Wed Jan 23 20:39:23 2013 +0100 @@ -0,0 +1,223 @@ +/* + * Copyright (c) 2000, 2011, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code 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 + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package java.lang; + +/** + * An element in a stack trace, as returned by {@link + * Throwable#getStackTrace()}. Each element represents a single stack frame. + * All stack frames except for the one at the top of the stack represent + * a method invocation. The frame at the top of the stack represents the + * execution point at which the stack trace was generated. Typically, + * this is the point at which the throwable corresponding to the stack trace + * was created. + * + * @since 1.4 + * @author Josh Bloch + */ +public final class StackTraceElement implements java.io.Serializable { + // Normally initialized by VM (public constructor added in 1.5) + private String declaringClass; + private String methodName; + private String fileName; + private int lineNumber; + + /** + * Creates a stack trace element representing the specified execution + * point. + * + * @param declaringClass the fully qualified name of the class containing + * the execution point represented by the stack trace element + * @param methodName the name of the method containing the execution point + * represented by the stack trace element + * @param fileName the name of the file containing the execution point + * represented by the stack trace element, or {@code null} if + * this information is unavailable + * @param lineNumber the line number of the source line containing the + * execution point represented by this stack trace element, or + * a negative number if this information is unavailable. A value + * of -2 indicates that the method containing the execution point + * is a native method + * @throws NullPointerException if {@code declaringClass} or + * {@code methodName} is null + * @since 1.5 + */ + public StackTraceElement(String declaringClass, String methodName, + String fileName, int lineNumber) { + this.declaringClass = declaringClass; + this.methodName = methodName; + this.fileName = fileName; + this.lineNumber = lineNumber; + } + + /** + * Returns the name of the source file containing the execution point + * represented by this stack trace element. Generally, this corresponds + * to the {@code SourceFile} attribute of the relevant {@code class} + * file (as per The Java Virtual Machine Specification, Section + * 4.7.7). In some systems, the name may refer to some source code unit + * other than a file, such as an entry in source repository. + * + * @return the name of the file containing the execution point + * represented by this stack trace element, or {@code null} if + * this information is unavailable. + */ + public String getFileName() { + return fileName; + } + + /** + * Returns the line number of the source line containing the execution + * point represented by this stack trace element. Generally, this is + * derived from the {@code LineNumberTable} attribute of the relevant + * {@code class} file (as per The Java Virtual Machine + * Specification, Section 4.7.8). + * + * @return the line number of the source line containing the execution + * point represented by this stack trace element, or a negative + * number if this information is unavailable. + */ + public int getLineNumber() { + return lineNumber; + } + + /** + * Returns the fully qualified name of the class containing the + * execution point represented by this stack trace element. + * + * @return the fully qualified name of the {@code Class} containing + * the execution point represented by this stack trace element. + */ + public String getClassName() { + return declaringClass; + } + + /** + * Returns the name of the method containing the execution point + * represented by this stack trace element. If the execution point is + * contained in an instance or class initializer, this method will return + * the appropriate special method name, {@code } or + * {@code }, as per Section 3.9 of The Java Virtual + * Machine Specification. + * + * @return the name of the method containing the execution point + * represented by this stack trace element. + */ + public String getMethodName() { + return methodName; + } + + /** + * Returns true if the method containing the execution point + * represented by this stack trace element is a native method. + * + * @return {@code true} if the method containing the execution point + * represented by this stack trace element is a native method. + */ + public boolean isNativeMethod() { + return lineNumber == -2; + } + + /** + * Returns a string representation of this stack trace element. The + * format of this string depends on the implementation, but the following + * examples may be regarded as typical: + *
    + *
  • + * {@code "MyClass.mash(MyClass.java:9)"} - Here, {@code "MyClass"} + * is the fully-qualified name of the class containing the + * execution point represented by this stack trace element, + * {@code "mash"} is the name of the method containing the execution + * point, {@code "MyClass.java"} is the source file containing the + * execution point, and {@code "9"} is the line number of the source + * line containing the execution point. + *
  • + * {@code "MyClass.mash(MyClass.java)"} - As above, but the line + * number is unavailable. + *
  • + * {@code "MyClass.mash(Unknown Source)"} - As above, but neither + * the file name nor the line number are available. + *
  • + * {@code "MyClass.mash(Native Method)"} - As above, but neither + * the file name nor the line number are available, and the method + * containing the execution point is known to be a native method. + *
+ * @see Throwable#printStackTrace() + */ + public String toString() { + return getClassName() + "." + methodName + + (isNativeMethod() ? "(Native Method)" : + (fileName != null && lineNumber >= 0 ? + "(" + fileName + ":" + lineNumber + ")" : + (fileName != null ? "("+fileName+")" : "(Unknown Source)"))); + } + + /** + * Returns true if the specified object is another + * {@code StackTraceElement} instance representing the same execution + * point as this instance. Two stack trace elements {@code a} and + * {@code b} are equal if and only if: + *
+     *     equals(a.getFileName(), b.getFileName()) &&
+     *     a.getLineNumber() == b.getLineNumber()) &&
+     *     equals(a.getClassName(), b.getClassName()) &&
+     *     equals(a.getMethodName(), b.getMethodName())
+     * 
+ * where {@code equals} has the semantics of {@link + * java.util.Objects#equals(Object, Object) Objects.equals}. + * + * @param obj the object to be compared with this stack trace element. + * @return true if the specified object is another + * {@code StackTraceElement} instance representing the same + * execution point as this instance. + */ + public boolean equals(Object obj) { + if (obj==this) + return true; + if (!(obj instanceof StackTraceElement)) + return false; + StackTraceElement e = (StackTraceElement)obj; + return e.declaringClass.equals(declaringClass) && + e.lineNumber == lineNumber && + equals(methodName, e.methodName) && + equals(fileName, e.fileName); + } + + /** + * Returns a hash code value for this stack trace element. + */ + public int hashCode() { + int result = 31*declaringClass.hashCode() + methodName.hashCode(); + result = 31*result + (fileName == null ? 0 : fileName.hashCode()); + result = 31*result + lineNumber; + return result; + } + + private static boolean equals(Object a, Object b) { + return (a == b) || (a != null && a.equals(b)); + } + + private static final long serialVersionUID = 6992337162326171013L; +} diff -r 388e48c0a37a -r 05224402145d emul/mini/src/main/java/java/lang/String.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/emul/mini/src/main/java/java/lang/String.java Wed Jan 23 20:39:23 2013 +0100 @@ -0,0 +1,3009 @@ +/* + * Copyright (c) 1994, 2010, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code 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 + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package java.lang; + +import java.util.Comparator; +import org.apidesign.bck2brwsr.core.ExtraJavaScript; +import org.apidesign.bck2brwsr.core.JavaScriptBody; +import org.apidesign.bck2brwsr.core.JavaScriptOnly; +import org.apidesign.bck2brwsr.core.JavaScriptPrototype; + +/** + * The String class represents character strings. All + * string literals in Java programs, such as "abc", are + * implemented as instances of this class. + *

+ * Strings are constant; their values cannot be changed after they + * are created. String buffers support mutable strings. + * Because String objects are immutable they can be shared. For example: + *

+ *     String str = "abc";
+ * 

+ * is equivalent to: + *

+ *     char data[] = {'a', 'b', 'c'};
+ *     String str = new String(data);
+ * 

+ * Here are some more examples of how strings can be used: + *

+ *     System.out.println("abc");
+ *     String cde = "cde";
+ *     System.out.println("abc" + cde);
+ *     String c = "abc".substring(2,3);
+ *     String d = cde.substring(1, 2);
+ * 
+ *

+ * The class String includes methods for examining + * individual characters of the sequence, for comparing strings, for + * searching strings, for extracting substrings, and for creating a + * copy of a string with all characters translated to uppercase or to + * lowercase. Case mapping is based on the Unicode Standard version + * specified by the {@link java.lang.Character Character} class. + *

+ * The Java language provides special support for the string + * concatenation operator ( + ), and for conversion of + * other objects to strings. String concatenation is implemented + * through the StringBuilder(or StringBuffer) + * class and its append method. + * String conversions are implemented through the method + * toString, defined by Object and + * inherited by all classes in Java. For additional information on + * string concatenation and conversion, see Gosling, Joy, and Steele, + * The Java Language Specification. + * + *

Unless otherwise noted, passing a null argument to a constructor + * or method in this class will cause a {@link NullPointerException} to be + * thrown. + * + *

A String represents a string in the UTF-16 format + * in which supplementary characters are represented by surrogate + * pairs (see the section Unicode + * Character Representations in the Character class for + * more information). + * Index values refer to char code units, so a supplementary + * character uses two positions in a String. + *

The String class provides methods for dealing with + * Unicode code points (i.e., characters), in addition to those for + * dealing with Unicode code units (i.e., char values). + * + * @author Lee Boynton + * @author Arthur van Hoff + * @author Martin Buchholz + * @author Ulf Zibis + * @see java.lang.Object#toString() + * @see java.lang.StringBuffer + * @see java.lang.StringBuilder + * @see java.nio.charset.Charset + * @since JDK1.0 + */ + +@ExtraJavaScript( + resource="/org/apidesign/vm4brwsr/emul/java_lang_String.js", + processByteCode=true +) +@JavaScriptPrototype(container = "String.prototype", prototype = "new String") +public final class String + implements java.io.Serializable, Comparable, CharSequence +{ + /** real string to delegate to */ + private Object r; + + /** use serialVersionUID from JDK 1.0.2 for interoperability */ + private static final long serialVersionUID = -6849794470754667710L; + + @JavaScriptOnly(name="toString", value="function() { return this.fld_r; }") + private static void jsToString() { + } + + @JavaScriptOnly(name="valueOf", value="function() { return this.toString().valueOf(); }") + private static void jsValudOf() { + } + + /** + * Class String is special cased within the Serialization Stream Protocol. + * + * A String instance is written initially into an ObjectOutputStream in the + * following format: + *

+     *      TC_STRING (utf String)
+     * 
+ * The String is written by method DataOutput.writeUTF. + * A new handle is generated to refer to all future references to the + * string instance within the stream. + */ +// private static final ObjectStreamField[] serialPersistentFields = +// new ObjectStreamField[0]; + + /** + * Initializes a newly created {@code String} object so that it represents + * an empty character sequence. Note that use of this constructor is + * unnecessary since Strings are immutable. + */ + public String() { + this.r = ""; + } + + /** + * Initializes a newly created {@code String} object so that it represents + * the same sequence of characters as the argument; in other words, the + * newly created string is a copy of the argument string. Unless an + * explicit copy of {@code original} is needed, use of this constructor is + * unnecessary since Strings are immutable. + * + * @param original + * A {@code String} + */ + public String(String original) { + this.r = original.toString(); + } + + /** + * Allocates a new {@code String} so that it represents the sequence of + * characters currently contained in the character array argument. The + * contents of the character array are copied; subsequent modification of + * the character array does not affect the newly created string. + * + * @param value + * The initial value of the string + */ + @JavaScriptBody(args = { "charArr" }, body= + "for (var i = 0; i < charArr.length; i++) {\n" + + " if (typeof charArr[i] === 'number') charArr[i] = String.fromCharCode(charArr[i]);\n" + + "}\n" + + "this.fld_r = charArr.join('');\n" + ) + public String(char value[]) { + } + + /** + * Allocates a new {@code String} that contains characters from a subarray + * of the character array argument. The {@code offset} argument is the + * index of the first character of the subarray and the {@code count} + * argument specifies the length of the subarray. The contents of the + * subarray are copied; subsequent modification of the character array does + * not affect the newly created string. + * + * @param value + * Array that is the source of characters + * + * @param offset + * The initial offset + * + * @param count + * The length + * + * @throws IndexOutOfBoundsException + * If the {@code offset} and {@code count} arguments index + * characters outside the bounds of the {@code value} array + */ + @JavaScriptBody(args = { "charArr", "off", "cnt" }, body = + "var up = off + cnt;\n" + + "for (var i = off; i < up; i++) {\n" + + " if (typeof charArr[i] === 'number') charArr[i] = String.fromCharCode(charArr[i]);\n" + + "}\n" + + "this.fld_r = charArr.slice(off, up).join(\"\");\n" + ) + public String(char value[], int offset, int count) { + } + + /** + * Allocates a new {@code String} that contains characters from a subarray + * of the Unicode code point array + * argument. The {@code offset} argument is the index of the first code + * point of the subarray and the {@code count} argument specifies the + * length of the subarray. The contents of the subarray are converted to + * {@code char}s; subsequent modification of the {@code int} array does not + * affect the newly created string. + * + * @param codePoints + * Array that is the source of Unicode code points + * + * @param offset + * The initial offset + * + * @param count + * The length + * + * @throws IllegalArgumentException + * If any invalid Unicode code point is found in {@code + * codePoints} + * + * @throws IndexOutOfBoundsException + * If the {@code offset} and {@code count} arguments index + * characters outside the bounds of the {@code codePoints} array + * + * @since 1.5 + */ + public String(int[] codePoints, int offset, int count) { + if (offset < 0) { + throw new StringIndexOutOfBoundsException(offset); + } + if (count < 0) { + throw new StringIndexOutOfBoundsException(count); + } + // Note: offset or count might be near -1>>>1. + if (offset > codePoints.length - count) { + throw new StringIndexOutOfBoundsException(offset + count); + } + + final int end = offset + count; + + // Pass 1: Compute precise size of char[] + int n = count; + for (int i = offset; i < end; i++) { + int c = codePoints[i]; + if (Character.isBmpCodePoint(c)) + continue; + else if (Character.isValidCodePoint(c)) + n++; + else throw new IllegalArgumentException(Integer.toString(c)); + } + + // Pass 2: Allocate and fill in char[] + final char[] v = new char[n]; + + for (int i = offset, j = 0; i < end; i++, j++) { + int c = codePoints[i]; + if (Character.isBmpCodePoint(c)) + v[j] = (char) c; + else + Character.toSurrogates(c, v, j++); + } + + this.r = new String(v, 0, n); + } + + /** + * Allocates a new {@code String} constructed from a subarray of an array + * of 8-bit integer values. + * + *

The {@code offset} argument is the index of the first byte of the + * subarray, and the {@code count} argument specifies the length of the + * subarray. + * + *

Each {@code byte} in the subarray is converted to a {@code char} as + * specified in the method above. + * + * @deprecated This method does not properly convert bytes into characters. + * As of JDK 1.1, the preferred way to do this is via the + * {@code String} constructors that take a {@link + * java.nio.charset.Charset}, charset name, or that use the platform's + * default charset. + * + * @param ascii + * The bytes to be converted to characters + * + * @param hibyte + * The top 8 bits of each 16-bit Unicode code unit + * + * @param offset + * The initial offset + * @param count + * The length + * + * @throws IndexOutOfBoundsException + * If the {@code offset} or {@code count} argument is invalid + * + * @see #String(byte[], int) + * @see #String(byte[], int, int, java.lang.String) + * @see #String(byte[], int, int, java.nio.charset.Charset) + * @see #String(byte[], int, int) + * @see #String(byte[], java.lang.String) + * @see #String(byte[], java.nio.charset.Charset) + * @see #String(byte[]) + */ + @Deprecated + public String(byte ascii[], int hibyte, int offset, int count) { + checkBounds(ascii, offset, count); + char value[] = new char[count]; + + if (hibyte == 0) { + for (int i = count ; i-- > 0 ;) { + value[i] = (char) (ascii[i + offset] & 0xff); + } + } else { + hibyte <<= 8; + for (int i = count ; i-- > 0 ;) { + value[i] = (char) (hibyte | (ascii[i + offset] & 0xff)); + } + } + this.r = new String(value, 0, count); + } + + /** + * Allocates a new {@code String} containing characters constructed from + * an array of 8-bit integer values. Each character cin the + * resulting string is constructed from the corresponding component + * b in the byte array such that: + * + *

+     *     c == (char)(((hibyte & 0xff) << 8)
+     *                         | (b & 0xff))
+     * 
+ * + * @deprecated This method does not properly convert bytes into + * characters. As of JDK 1.1, the preferred way to do this is via the + * {@code String} constructors that take a {@link + * java.nio.charset.Charset}, charset name, or that use the platform's + * default charset. + * + * @param ascii + * The bytes to be converted to characters + * + * @param hibyte + * The top 8 bits of each 16-bit Unicode code unit + * + * @see #String(byte[], int, int, java.lang.String) + * @see #String(byte[], int, int, java.nio.charset.Charset) + * @see #String(byte[], int, int) + * @see #String(byte[], java.lang.String) + * @see #String(byte[], java.nio.charset.Charset) + * @see #String(byte[]) + */ + @Deprecated + public String(byte ascii[], int hibyte) { + this(ascii, hibyte, 0, ascii.length); + } + + /* Common private utility method used to bounds check the byte array + * and requested offset & length values used by the String(byte[],..) + * constructors. + */ + private static void checkBounds(byte[] bytes, int offset, int length) { + if (length < 0) + throw new StringIndexOutOfBoundsException(length); + if (offset < 0) + throw new StringIndexOutOfBoundsException(offset); + if (offset > bytes.length - length) + throw new StringIndexOutOfBoundsException(offset + length); + } + + /** + * Constructs a new {@code String} by decoding the specified subarray of + * bytes using the specified charset. The length of the new {@code String} + * is a function of the charset, and hence may not be equal to the length + * of the subarray. + * + *

The behavior of this constructor when the given bytes are not valid + * in the given charset is unspecified. The {@link + * java.nio.charset.CharsetDecoder} class should be used when more control + * over the decoding process is required. + * + * @param bytes + * The bytes to be decoded into characters + * + * @param offset + * The index of the first byte to decode + * + * @param length + * The number of bytes to decode + + * @param charsetName + * The name of a supported {@linkplain java.nio.charset.Charset + * charset} + * + * @throws UnsupportedEncodingException + * If the named charset is not supported + * + * @throws IndexOutOfBoundsException + * If the {@code offset} and {@code length} arguments index + * characters outside the bounds of the {@code bytes} array + * + * @since JDK1.1 + */ +// public String(byte bytes[], int offset, int length, String charsetName) +// throws UnsupportedEncodingException +// { +// if (charsetName == null) +// throw new NullPointerException("charsetName"); +// checkBounds(bytes, offset, length); +// char[] v = StringCoding.decode(charsetName, bytes, offset, length); +// this.offset = 0; +// this.count = v.length; +// this.value = v; +// } + + /** + * Constructs a new {@code String} by decoding the specified subarray of + * bytes using the specified {@linkplain java.nio.charset.Charset charset}. + * The length of the new {@code String} is a function of the charset, and + * hence may not be equal to the length of the subarray. + * + *

This method always replaces malformed-input and unmappable-character + * sequences with this charset's default replacement string. The {@link + * java.nio.charset.CharsetDecoder} class should be used when more control + * over the decoding process is required. + * + * @param bytes + * The bytes to be decoded into characters + * + * @param offset + * The index of the first byte to decode + * + * @param length + * The number of bytes to decode + * + * @param charset + * The {@linkplain java.nio.charset.Charset charset} to be used to + * decode the {@code bytes} + * + * @throws IndexOutOfBoundsException + * If the {@code offset} and {@code length} arguments index + * characters outside the bounds of the {@code bytes} array + * + * @since 1.6 + */ + /* don't want dependnecy on Charset + public String(byte bytes[], int offset, int length, Charset charset) { + if (charset == null) + throw new NullPointerException("charset"); + checkBounds(bytes, offset, length); + char[] v = StringCoding.decode(charset, bytes, offset, length); + this.offset = 0; + this.count = v.length; + this.value = v; + } + */ + + /** + * Constructs a new {@code String} by decoding the specified array of bytes + * using the specified {@linkplain java.nio.charset.Charset charset}. The + * length of the new {@code String} is a function of the charset, and hence + * may not be equal to the length of the byte array. + * + *

The behavior of this constructor when the given bytes are not valid + * in the given charset is unspecified. The {@link + * java.nio.charset.CharsetDecoder} class should be used when more control + * over the decoding process is required. + * + * @param bytes + * The bytes to be decoded into characters + * + * @param charsetName + * The name of a supported {@linkplain java.nio.charset.Charset + * charset} + * + * @throws UnsupportedEncodingException + * If the named charset is not supported + * + * @since JDK1.1 + */ +// public String(byte bytes[], String charsetName) +// throws UnsupportedEncodingException +// { +// this(bytes, 0, bytes.length, charsetName); +// } + + /** + * Constructs a new {@code String} by decoding the specified array of + * bytes using the specified {@linkplain java.nio.charset.Charset charset}. + * The length of the new {@code String} is a function of the charset, and + * hence may not be equal to the length of the byte array. + * + *

This method always replaces malformed-input and unmappable-character + * sequences with this charset's default replacement string. The {@link + * java.nio.charset.CharsetDecoder} class should be used when more control + * over the decoding process is required. + * + * @param bytes + * The bytes to be decoded into characters + * + * @param charset + * The {@linkplain java.nio.charset.Charset charset} to be used to + * decode the {@code bytes} + * + * @since 1.6 + */ + /* don't want dep on Charset + public String(byte bytes[], Charset charset) { + this(bytes, 0, bytes.length, charset); + } + */ + + /** + * Constructs a new {@code String} by decoding the specified subarray of + * bytes using the platform's default charset. The length of the new + * {@code String} is a function of the charset, and hence may not be equal + * to the length of the subarray. + * + *

The behavior of this constructor when the given bytes are not valid + * in the default charset is unspecified. The {@link + * java.nio.charset.CharsetDecoder} class should be used when more control + * over the decoding process is required. + * + * @param bytes + * The bytes to be decoded into characters + * + * @param offset + * The index of the first byte to decode + * + * @param length + * The number of bytes to decode + * + * @throws IndexOutOfBoundsException + * If the {@code offset} and the {@code length} arguments index + * characters outside the bounds of the {@code bytes} array + * + * @since JDK1.1 + */ + public String(byte bytes[], int offset, int length) { + checkBounds(bytes, offset, length); + char[] v = new char[length]; + for (int i = 0; i < length; i++) { + v[i] = (char)bytes[offset++]; + } + this.r = new String(v, 0, v.length); + } + + /** + * Constructs a new {@code String} by decoding the specified array of bytes + * using the platform's default charset. The length of the new {@code + * String} is a function of the charset, and hence may not be equal to the + * length of the byte array. + * + *

The behavior of this constructor when the given bytes are not valid + * in the default charset is unspecified. The {@link + * java.nio.charset.CharsetDecoder} class should be used when more control + * over the decoding process is required. + * + * @param bytes + * The bytes to be decoded into characters + * + * @since JDK1.1 + */ + public String(byte bytes[]) { + this(bytes, 0, bytes.length); + } + + /** + * Allocates a new string that contains the sequence of characters + * currently contained in the string buffer argument. The contents of the + * string buffer are copied; subsequent modification of the string buffer + * does not affect the newly created string. + * + * @param buffer + * A {@code StringBuffer} + */ + public String(StringBuffer buffer) { + this.r = buffer.toString(); + } + + /** + * Allocates a new string that contains the sequence of characters + * currently contained in the string builder argument. The contents of the + * string builder are copied; subsequent modification of the string builder + * does not affect the newly created string. + * + *

This constructor is provided to ease migration to {@code + * StringBuilder}. Obtaining a string from a string builder via the {@code + * toString} method is likely to run faster and is generally preferred. + * + * @param builder + * A {@code StringBuilder} + * + * @since 1.5 + */ + public String(StringBuilder builder) { + this.r = builder.toString(); + } + + /** + * Returns the length of this string. + * The length is equal to the number of Unicode + * code units in the string. + * + * @return the length of the sequence of characters represented by this + * object. + */ + @JavaScriptBody(args = {}, body = "return this.toString().length;") + public int length() { + throw new UnsupportedOperationException(); + } + + /** + * Returns true if, and only if, {@link #length()} is 0. + * + * @return true if {@link #length()} is 0, otherwise + * false + * + * @since 1.6 + */ + @JavaScriptBody(args = {}, body="return this.toString().length === 0;") + public boolean isEmpty() { + return length() == 0; + } + + /** + * Returns the char value at the + * specified index. An index ranges from 0 to + * length() - 1. The first char value of the sequence + * is at index 0, the next at index 1, + * and so on, as for array indexing. + * + *

If the char value specified by the index is a + * surrogate, the surrogate + * value is returned. + * + * @param index the index of the char value. + * @return the char value at the specified index of this string. + * The first char value is at index 0. + * @exception IndexOutOfBoundsException if the index + * argument is negative or not less than the length of this + * string. + */ + @JavaScriptBody(args = { "index" }, + body = "return this.toString().charCodeAt(index);" + ) + public char charAt(int index) { + throw new UnsupportedOperationException(); + } + + /** + * Returns the character (Unicode code point) at the specified + * index. The index refers to char values + * (Unicode code units) and ranges from 0 to + * {@link #length()} - 1. + * + *

If the char value specified at the given index + * is in the high-surrogate range, the following index is less + * than the length of this String, and the + * char value at the following index is in the + * low-surrogate range, then the supplementary code point + * corresponding to this surrogate pair is returned. Otherwise, + * the char value at the given index is returned. + * + * @param index the index to the char values + * @return the code point value of the character at the + * index + * @exception IndexOutOfBoundsException if the index + * argument is negative or not less than the length of this + * string. + * @since 1.5 + */ + public int codePointAt(int index) { + if ((index < 0) || (index >= length())) { + throw new StringIndexOutOfBoundsException(index); + } + return Character.codePointAtImpl(toCharArray(), offset() + index, offset() + length()); + } + + /** + * Returns the character (Unicode code point) before the specified + * index. The index refers to char values + * (Unicode code units) and ranges from 1 to {@link + * CharSequence#length() length}. + * + *

If the char value at (index - 1) + * is in the low-surrogate range, (index - 2) is not + * negative, and the char value at (index - + * 2) is in the high-surrogate range, then the + * supplementary code point value of the surrogate pair is + * returned. If the char value at index - + * 1 is an unpaired low-surrogate or a high-surrogate, the + * surrogate value is returned. + * + * @param index the index following the code point that should be returned + * @return the Unicode code point value before the given index. + * @exception IndexOutOfBoundsException if the index + * argument is less than 1 or greater than the length + * of this string. + * @since 1.5 + */ + public int codePointBefore(int index) { + int i = index - 1; + if ((i < 0) || (i >= length())) { + throw new StringIndexOutOfBoundsException(index); + } + return Character.codePointBeforeImpl(toCharArray(), offset() + index, offset()); + } + + /** + * Returns the number of Unicode code points in the specified text + * range of this String. The text range begins at the + * specified beginIndex and extends to the + * char at index endIndex - 1. Thus the + * length (in chars) of the text range is + * endIndex-beginIndex. Unpaired surrogates within + * the text range count as one code point each. + * + * @param beginIndex the index to the first char of + * the text range. + * @param endIndex the index after the last char of + * the text range. + * @return the number of Unicode code points in the specified text + * range + * @exception IndexOutOfBoundsException if the + * beginIndex is negative, or endIndex + * is larger than the length of this String, or + * beginIndex is larger than endIndex. + * @since 1.5 + */ + public int codePointCount(int beginIndex, int endIndex) { + if (beginIndex < 0 || endIndex > length() || beginIndex > endIndex) { + throw new IndexOutOfBoundsException(); + } + return Character.codePointCountImpl(toCharArray(), offset()+beginIndex, endIndex-beginIndex); + } + + /** + * Returns the index within this String that is + * offset from the given index by + * codePointOffset code points. Unpaired surrogates + * within the text range given by index and + * codePointOffset count as one code point each. + * + * @param index the index to be offset + * @param codePointOffset the offset in code points + * @return the index within this String + * @exception IndexOutOfBoundsException if index + * is negative or larger then the length of this + * String, or if codePointOffset is positive + * and the substring starting with index has fewer + * than codePointOffset code points, + * or if codePointOffset is negative and the substring + * before index has fewer than the absolute value + * of codePointOffset code points. + * @since 1.5 + */ + public int offsetByCodePoints(int index, int codePointOffset) { + if (index < 0 || index > length()) { + throw new IndexOutOfBoundsException(); + } + return Character.offsetByCodePointsImpl(toCharArray(), offset(), length(), + offset()+index, codePointOffset) - offset(); + } + + /** + * Copy characters from this string into dst starting at dstBegin. + * This method doesn't perform any range checking. + */ + @JavaScriptBody(args = { "arr", "to" }, body = + "var s = this.toString();\n" + + "for (var i = 0; i < s.length; i++) {\n" + + " arr[to++] = s[i];\n" + + "}" + ) + void getChars(char dst[], int dstBegin) { + AbstractStringBuilder.arraycopy(toCharArray(), offset(), dst, dstBegin, length()); + } + + /** + * Copies characters from this string into the destination character + * array. + *

+ * The first character to be copied is at index srcBegin; + * the last character to be copied is at index srcEnd-1 + * (thus the total number of characters to be copied is + * srcEnd-srcBegin). The characters are copied into the + * subarray of dst starting at index dstBegin + * and ending at index: + *

+     *     dstbegin + (srcEnd-srcBegin) - 1
+     * 
+ * + * @param srcBegin index of the first character in the string + * to copy. + * @param srcEnd index after the last character in the string + * to copy. + * @param dst the destination array. + * @param dstBegin the start offset in the destination array. + * @exception IndexOutOfBoundsException If any of the following + * is true: + *
  • srcBegin is negative. + *
  • srcBegin is greater than srcEnd + *
  • srcEnd is greater than the length of this + * string + *
  • dstBegin is negative + *
  • dstBegin+(srcEnd-srcBegin) is larger than + * dst.length
+ */ + @JavaScriptBody(args = { "beg", "end", "arr", "dst" }, body= + "var s = this.toString();\n" + + "while (beg < end) {\n" + + " arr[dst++] = s[beg++];\n" + + "}\n" + ) + public void getChars(int srcBegin, int srcEnd, char dst[], int dstBegin) { + if (srcBegin < 0) { + throw new StringIndexOutOfBoundsException(srcBegin); + } + if (srcEnd > length()) { + throw new StringIndexOutOfBoundsException(srcEnd); + } + if (srcBegin > srcEnd) { + throw new StringIndexOutOfBoundsException(srcEnd - srcBegin); + } + AbstractStringBuilder.arraycopy(toCharArray(), offset() + srcBegin, dst, dstBegin, + srcEnd - srcBegin); + } + + /** + * Copies characters from this string into the destination byte array. Each + * byte receives the 8 low-order bits of the corresponding character. The + * eight high-order bits of each character are not copied and do not + * participate in the transfer in any way. + * + *

The first character to be copied is at index {@code srcBegin}; the + * last character to be copied is at index {@code srcEnd-1}. The total + * number of characters to be copied is {@code srcEnd-srcBegin}. The + * characters, converted to bytes, are copied into the subarray of {@code + * dst} starting at index {@code dstBegin} and ending at index: + * + *

+     *     dstbegin + (srcEnd-srcBegin) - 1
+     * 
+ * + * @deprecated This method does not properly convert characters into + * bytes. As of JDK 1.1, the preferred way to do this is via the + * {@link #getBytes()} method, which uses the platform's default charset. + * + * @param srcBegin + * Index of the first character in the string to copy + * + * @param srcEnd + * Index after the last character in the string to copy + * + * @param dst + * The destination array + * + * @param dstBegin + * The start offset in the destination array + * + * @throws IndexOutOfBoundsException + * If any of the following is true: + *
    + *
  • {@code srcBegin} is negative + *
  • {@code srcBegin} is greater than {@code srcEnd} + *
  • {@code srcEnd} is greater than the length of this String + *
  • {@code dstBegin} is negative + *
  • {@code dstBegin+(srcEnd-srcBegin)} is larger than {@code + * dst.length} + *
+ */ + @Deprecated + public void getBytes(int srcBegin, int srcEnd, byte dst[], int dstBegin) { + if (srcBegin < 0) { + throw new StringIndexOutOfBoundsException(srcBegin); + } + if (srcEnd > length()) { + throw new StringIndexOutOfBoundsException(srcEnd); + } + if (srcBegin > srcEnd) { + throw new StringIndexOutOfBoundsException(srcEnd - srcBegin); + } + int j = dstBegin; + int n = offset() + srcEnd; + int i = offset() + srcBegin; + char[] val = toCharArray(); /* avoid getfield opcode */ + + while (i < n) { + dst[j++] = (byte)val[i++]; + } + } + + /** + * Encodes this {@code String} into a sequence of bytes using the named + * charset, storing the result into a new byte array. + * + *

The behavior of this method when this string cannot be encoded in + * the given charset is unspecified. The {@link + * java.nio.charset.CharsetEncoder} class should be used when more control + * over the encoding process is required. + * + * @param charsetName + * The name of a supported {@linkplain java.nio.charset.Charset + * charset} + * + * @return The resultant byte array + * + * @throws UnsupportedEncodingException + * If the named charset is not supported + * + * @since JDK1.1 + */ +// public byte[] getBytes(String charsetName) +// throws UnsupportedEncodingException +// { +// if (charsetName == null) throw new NullPointerException(); +// return StringCoding.encode(charsetName, value, offset, count); +// } + + /** + * Encodes this {@code String} into a sequence of bytes using the given + * {@linkplain java.nio.charset.Charset charset}, storing the result into a + * new byte array. + * + *

This method always replaces malformed-input and unmappable-character + * sequences with this charset's default replacement byte array. The + * {@link java.nio.charset.CharsetEncoder} class should be used when more + * control over the encoding process is required. + * + * @param charset + * The {@linkplain java.nio.charset.Charset} to be used to encode + * the {@code String} + * + * @return The resultant byte array + * + * @since 1.6 + */ + /* don't want dep on Charset + public byte[] getBytes(Charset charset) { + if (charset == null) throw new NullPointerException(); + return StringCoding.encode(charset, value, offset, count); + } + */ + + /** + * Encodes this {@code String} into a sequence of bytes using the + * platform's default charset, storing the result into a new byte array. + * + *

The behavior of this method when this string cannot be encoded in + * the default charset is unspecified. The {@link + * java.nio.charset.CharsetEncoder} class should be used when more control + * over the encoding process is required. + * + * @return The resultant byte array + * + * @since JDK1.1 + */ + public byte[] getBytes() { + byte[] arr = new byte[length()]; + for (int i = 0; i < arr.length; i++) { + final char v = charAt(i); + arr[i] = (byte)v; + } + return arr; + } + + /** + * Compares this string to the specified object. The result is {@code + * true} if and only if the argument is not {@code null} and is a {@code + * String} object that represents the same sequence of characters as this + * object. + * + * @param anObject + * The object to compare this {@code String} against + * + * @return {@code true} if the given object represents a {@code String} + * equivalent to this string, {@code false} otherwise + * + * @see #compareTo(String) + * @see #equalsIgnoreCase(String) + */ + @JavaScriptBody(args = { "obj" }, body = + "return obj != null && obj.$instOf_java_lang_String && " + + "this.toString() === obj.toString();" + ) + public boolean equals(Object anObject) { + if (this == anObject) { + return true; + } + if (anObject instanceof String) { + String anotherString = (String)anObject; + int n = length(); + if (n == anotherString.length()) { + char v1[] = toCharArray(); + char v2[] = anotherString.toCharArray(); + int i = offset(); + int j = anotherString.offset(); + while (n-- != 0) { + if (v1[i++] != v2[j++]) + return false; + } + return true; + } + } + return false; + } + + /** + * Compares this string to the specified {@code StringBuffer}. The result + * is {@code true} if and only if this {@code String} represents the same + * sequence of characters as the specified {@code StringBuffer}. + * + * @param sb + * The {@code StringBuffer} to compare this {@code String} against + * + * @return {@code true} if this {@code String} represents the same + * sequence of characters as the specified {@code StringBuffer}, + * {@code false} otherwise + * + * @since 1.4 + */ + public boolean contentEquals(StringBuffer sb) { + synchronized(sb) { + return contentEquals((CharSequence)sb); + } + } + + /** + * Compares this string to the specified {@code CharSequence}. The result + * is {@code true} if and only if this {@code String} represents the same + * sequence of char values as the specified sequence. + * + * @param cs + * The sequence to compare this {@code String} against + * + * @return {@code true} if this {@code String} represents the same + * sequence of char values as the specified sequence, {@code + * false} otherwise + * + * @since 1.5 + */ + public boolean contentEquals(CharSequence cs) { + if (length() != cs.length()) + return false; + // Argument is a StringBuffer, StringBuilder + if (cs instanceof AbstractStringBuilder) { + char v1[] = toCharArray(); + char v2[] = ((AbstractStringBuilder)cs).getValue(); + int i = offset(); + int j = 0; + int n = length(); + while (n-- != 0) { + if (v1[i++] != v2[j++]) + return false; + } + return true; + } + // Argument is a String + if (cs.equals(this)) + return true; + // Argument is a generic CharSequence + char v1[] = toCharArray(); + int i = offset(); + int j = 0; + int n = length(); + while (n-- != 0) { + if (v1[i++] != cs.charAt(j++)) + return false; + } + return true; + } + + /** + * Compares this {@code String} to another {@code String}, ignoring case + * considerations. Two strings are considered equal ignoring case if they + * are of the same length and corresponding characters in the two strings + * are equal ignoring case. + * + *

Two characters {@code c1} and {@code c2} are considered the same + * ignoring case if at least one of the following is true: + *

    + *
  • The two characters are the same (as compared by the + * {@code ==} operator) + *
  • Applying the method {@link + * java.lang.Character#toUpperCase(char)} to each character + * produces the same result + *
  • Applying the method {@link + * java.lang.Character#toLowerCase(char)} to each character + * produces the same result + *
+ * + * @param anotherString + * The {@code String} to compare this {@code String} against + * + * @return {@code true} if the argument is not {@code null} and it + * represents an equivalent {@code String} ignoring case; {@code + * false} otherwise + * + * @see #equals(Object) + */ + public boolean equalsIgnoreCase(String anotherString) { + return (this == anotherString) ? true : + (anotherString != null) && (anotherString.length() == length()) && + regionMatches(true, 0, anotherString, 0, length()); + } + + /** + * Compares two strings lexicographically. + * The comparison is based on the Unicode value of each character in + * the strings. The character sequence represented by this + * String object is compared lexicographically to the + * character sequence represented by the argument string. The result is + * a negative integer if this String object + * lexicographically precedes the argument string. The result is a + * positive integer if this String object lexicographically + * follows the argument string. The result is zero if the strings + * are equal; compareTo returns 0 exactly when + * the {@link #equals(Object)} method would return true. + *

+ * This is the definition of lexicographic ordering. If two strings are + * different, then either they have different characters at some index + * that is a valid index for both strings, or their lengths are different, + * or both. If they have different characters at one or more index + * positions, let k be the smallest such index; then the string + * whose character at position k has the smaller value, as + * determined by using the < operator, lexicographically precedes the + * other string. In this case, compareTo returns the + * difference of the two character values at position k in + * the two string -- that is, the value: + *

+     * this.charAt(k)-anotherString.charAt(k)
+     * 
+ * If there is no index position at which they differ, then the shorter + * string lexicographically precedes the longer string. In this case, + * compareTo returns the difference of the lengths of the + * strings -- that is, the value: + *
+     * this.length()-anotherString.length()
+     * 
+ * + * @param anotherString the String to be compared. + * @return the value 0 if the argument string is equal to + * this string; a value less than 0 if this string + * is lexicographically less than the string argument; and a + * value greater than 0 if this string is + * lexicographically greater than the string argument. + */ + public int compareTo(String anotherString) { + int len1 = length(); + int len2 = anotherString.length(); + int n = Math.min(len1, len2); + char v1[] = toCharArray(); + char v2[] = anotherString.toCharArray(); + int i = offset(); + int j = anotherString.offset(); + + if (i == j) { + int k = i; + int lim = n + i; + while (k < lim) { + char c1 = v1[k]; + char c2 = v2[k]; + if (c1 != c2) { + return c1 - c2; + } + k++; + } + } else { + while (n-- != 0) { + char c1 = v1[i++]; + char c2 = v2[j++]; + if (c1 != c2) { + return c1 - c2; + } + } + } + return len1 - len2; + } + + /** + * A Comparator that orders String objects as by + * compareToIgnoreCase. This comparator is serializable. + *

+ * Note that this Comparator does not take locale into account, + * and will result in an unsatisfactory ordering for certain locales. + * The java.text package provides Collators to allow + * locale-sensitive ordering. + * + * @see java.text.Collator#compare(String, String) + * @since 1.2 + */ + public static final Comparator CASE_INSENSITIVE_ORDER + = new CaseInsensitiveComparator(); + + private static int offset() { + return 0; + } + + private static class CaseInsensitiveComparator + implements Comparator, java.io.Serializable { + // use serialVersionUID from JDK 1.2.2 for interoperability + private static final long serialVersionUID = 8575799808933029326L; + + public int compare(String s1, String s2) { + int n1 = s1.length(); + int n2 = s2.length(); + int min = Math.min(n1, n2); + for (int i = 0; i < min; i++) { + char c1 = s1.charAt(i); + char c2 = s2.charAt(i); + if (c1 != c2) { + c1 = Character.toUpperCase(c1); + c2 = Character.toUpperCase(c2); + if (c1 != c2) { + c1 = Character.toLowerCase(c1); + c2 = Character.toLowerCase(c2); + if (c1 != c2) { + // No overflow because of numeric promotion + return c1 - c2; + } + } + } + } + return n1 - n2; + } + } + + /** + * Compares two strings lexicographically, ignoring case + * differences. This method returns an integer whose sign is that of + * calling compareTo with normalized versions of the strings + * where case differences have been eliminated by calling + * Character.toLowerCase(Character.toUpperCase(character)) on + * each character. + *

+ * Note that this method does not take locale into account, + * and will result in an unsatisfactory ordering for certain locales. + * The java.text package provides collators to allow + * locale-sensitive ordering. + * + * @param str the String to be compared. + * @return a negative integer, zero, or a positive integer as the + * specified String is greater than, equal to, or less + * than this String, ignoring case considerations. + * @see java.text.Collator#compare(String, String) + * @since 1.2 + */ + public int compareToIgnoreCase(String str) { + return CASE_INSENSITIVE_ORDER.compare(this, str); + } + + /** + * Tests if two string regions are equal. + *

+ * A substring of this String object is compared to a substring + * of the argument other. The result is true if these substrings + * represent identical character sequences. The substring of this + * String object to be compared begins at index toffset + * and has length len. The substring of other to be compared + * begins at index ooffset and has length len. The + * result is false if and only if at least one of the following + * is true: + *

  • toffset is negative. + *
  • ooffset is negative. + *
  • toffset+len is greater than the length of this + * String object. + *
  • ooffset+len is greater than the length of the other + * argument. + *
  • There is some nonnegative integer k less than len + * such that: + * this.charAt(toffset+k) != other.charAt(ooffset+k) + *
+ * + * @param toffset the starting offset of the subregion in this string. + * @param other the string argument. + * @param ooffset the starting offset of the subregion in the string + * argument. + * @param len the number of characters to compare. + * @return true if the specified subregion of this string + * exactly matches the specified subregion of the string argument; + * false otherwise. + */ + public boolean regionMatches(int toffset, String other, int ooffset, + int len) { + char ta[] = toCharArray(); + int to = offset() + toffset; + char pa[] = other.toCharArray(); + int po = other.offset() + ooffset; + // Note: toffset, ooffset, or len might be near -1>>>1. + if ((ooffset < 0) || (toffset < 0) || (toffset > (long)length() - len) + || (ooffset > (long)other.length() - len)) { + return false; + } + while (len-- > 0) { + if (ta[to++] != pa[po++]) { + return false; + } + } + return true; + } + + /** + * Tests if two string regions are equal. + *

+ * A substring of this String object is compared to a substring + * of the argument other. The result is true if these + * substrings represent character sequences that are the same, ignoring + * case if and only if ignoreCase is true. The substring of + * this String object to be compared begins at index + * toffset and has length len. The substring of + * other to be compared begins at index ooffset and + * has length len. The result is false if and only if + * at least one of the following is true: + *

  • toffset is negative. + *
  • ooffset is negative. + *
  • toffset+len is greater than the length of this + * String object. + *
  • ooffset+len is greater than the length of the other + * argument. + *
  • ignoreCase is false and there is some nonnegative + * integer k less than len such that: + *
    +     * this.charAt(toffset+k) != other.charAt(ooffset+k)
    +     * 
    + *
  • ignoreCase is true and there is some nonnegative + * integer k less than len such that: + *
    +     * Character.toLowerCase(this.charAt(toffset+k)) !=
    +               Character.toLowerCase(other.charAt(ooffset+k))
    +     * 
    + * and: + *
    +     * Character.toUpperCase(this.charAt(toffset+k)) !=
    +     *         Character.toUpperCase(other.charAt(ooffset+k))
    +     * 
    + *
+ * + * @param ignoreCase if true, ignore case when comparing + * characters. + * @param toffset the starting offset of the subregion in this + * string. + * @param other the string argument. + * @param ooffset the starting offset of the subregion in the string + * argument. + * @param len the number of characters to compare. + * @return true if the specified subregion of this string + * matches the specified subregion of the string argument; + * false otherwise. Whether the matching is exact + * or case insensitive depends on the ignoreCase + * argument. + */ + public boolean regionMatches(boolean ignoreCase, int toffset, + String other, int ooffset, int len) { + char ta[] = toCharArray(); + int to = offset() + toffset; + char pa[] = other.toCharArray(); + int po = other.offset() + ooffset; + // Note: toffset, ooffset, or len might be near -1>>>1. + if ((ooffset < 0) || (toffset < 0) || (toffset > (long)length() - len) || + (ooffset > (long)other.length() - len)) { + return false; + } + while (len-- > 0) { + char c1 = ta[to++]; + char c2 = pa[po++]; + if (c1 == c2) { + continue; + } + if (ignoreCase) { + // If characters don't match but case may be ignored, + // try converting both characters to uppercase. + // If the results match, then the comparison scan should + // continue. + char u1 = Character.toUpperCase(c1); + char u2 = Character.toUpperCase(c2); + if (u1 == u2) { + continue; + } + // Unfortunately, conversion to uppercase does not work properly + // for the Georgian alphabet, which has strange rules about case + // conversion. So we need to make one last check before + // exiting. + if (Character.toLowerCase(u1) == Character.toLowerCase(u2)) { + continue; + } + } + return false; + } + return true; + } + + /** + * Tests if the substring of this string beginning at the + * specified index starts with the specified prefix. + * + * @param prefix the prefix. + * @param toffset where to begin looking in this string. + * @return true if the character sequence represented by the + * argument is a prefix of the substring of this object starting + * at index toffset; false otherwise. + * The result is false if toffset is + * negative or greater than the length of this + * String object; otherwise the result is the same + * as the result of the expression + *
+     *          this.substring(toffset).startsWith(prefix)
+     *          
+ */ + @JavaScriptBody(args = { "find", "from" }, body= + "find = find.toString();\n" + + "return this.toString().substring(from, from + find.length) === find;\n" + ) + public boolean startsWith(String prefix, int toffset) { + char ta[] = toCharArray(); + int to = offset() + toffset; + char pa[] = prefix.toCharArray(); + int po = prefix.offset(); + int pc = prefix.length(); + // Note: toffset might be near -1>>>1. + if ((toffset < 0) || (toffset > length() - pc)) { + return false; + } + while (--pc >= 0) { + if (ta[to++] != pa[po++]) { + return false; + } + } + return true; + } + + /** + * Tests if this string starts with the specified prefix. + * + * @param prefix the prefix. + * @return true if the character sequence represented by the + * argument is a prefix of the character sequence represented by + * this string; false otherwise. + * Note also that true will be returned if the + * argument is an empty string or is equal to this + * String object as determined by the + * {@link #equals(Object)} method. + * @since 1. 0 + */ + public boolean startsWith(String prefix) { + return startsWith(prefix, 0); + } + + /** + * Tests if this string ends with the specified suffix. + * + * @param suffix the suffix. + * @return true if the character sequence represented by the + * argument is a suffix of the character sequence represented by + * this object; false otherwise. Note that the + * result will be true if the argument is the + * empty string or is equal to this String object + * as determined by the {@link #equals(Object)} method. + */ + public boolean endsWith(String suffix) { + return startsWith(suffix, length() - suffix.length()); + } + + /** + * Returns a hash code for this string. The hash code for a + * String object is computed as + *
+     * s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1]
+     * 
+ * using int arithmetic, where s[i] is the + * ith character of the string, n is the length of + * the string, and ^ indicates exponentiation. + * (The hash value of the empty string is zero.) + * + * @return a hash code value for this object. + */ + public int hashCode() { + return super.hashCode(); + } + int computeHashCode() { + int h = 0; + if (h == 0 && length() > 0) { + int off = offset(); + int len = length(); + + for (int i = 0; i < len; i++) { + h = 31*h + charAt(off++); + } + } + return h; + } + + /** + * Returns the index within this string of the first occurrence of + * the specified character. If a character with value + * ch occurs in the character sequence represented by + * this String object, then the index (in Unicode + * code units) of the first such occurrence is returned. For + * values of ch in the range from 0 to 0xFFFF + * (inclusive), this is the smallest value k such that: + *
+     * this.charAt(k) == ch
+     * 
+ * is true. For other values of ch, it is the + * smallest value k such that: + *
+     * this.codePointAt(k) == ch
+     * 
+ * is true. In either case, if no such character occurs in this + * string, then -1 is returned. + * + * @param ch a character (Unicode code point). + * @return the index of the first occurrence of the character in the + * character sequence represented by this object, or + * -1 if the character does not occur. + */ + public int indexOf(int ch) { + return indexOf(ch, 0); + } + + /** + * Returns the index within this string of the first occurrence of the + * specified character, starting the search at the specified index. + *

+ * If a character with value ch occurs in the + * character sequence represented by this String + * object at an index no smaller than fromIndex, then + * the index of the first such occurrence is returned. For values + * of ch in the range from 0 to 0xFFFF (inclusive), + * this is the smallest value k such that: + *

+     * (this.charAt(k) == ch) && (k >= fromIndex)
+     * 
+ * is true. For other values of ch, it is the + * smallest value k such that: + *
+     * (this.codePointAt(k) == ch) && (k >= fromIndex)
+     * 
+ * is true. In either case, if no such character occurs in this + * string at or after position fromIndex, then + * -1 is returned. + * + *

+ * There is no restriction on the value of fromIndex. If it + * is negative, it has the same effect as if it were zero: this entire + * string may be searched. If it is greater than the length of this + * string, it has the same effect as if it were equal to the length of + * this string: -1 is returned. + * + *

All indices are specified in char values + * (Unicode code units). + * + * @param ch a character (Unicode code point). + * @param fromIndex the index to start the search from. + * @return the index of the first occurrence of the character in the + * character sequence represented by this object that is greater + * than or equal to fromIndex, or -1 + * if the character does not occur. + */ + @JavaScriptBody(args = { "ch", "from" }, body = + "if (typeof ch === 'number') ch = String.fromCharCode(ch);\n" + + "return this.toString().indexOf(ch, from);\n" + ) + public int indexOf(int ch, int fromIndex) { + if (fromIndex < 0) { + fromIndex = 0; + } else if (fromIndex >= length()) { + // Note: fromIndex might be near -1>>>1. + return -1; + } + + if (ch < Character.MIN_SUPPLEMENTARY_CODE_POINT) { + // handle most cases here (ch is a BMP code point or a + // negative value (invalid code point)) + final char[] value = this.toCharArray(); + final int offset = this.offset(); + final int max = offset + length(); + for (int i = offset + fromIndex; i < max ; i++) { + if (value[i] == ch) { + return i - offset; + } + } + return -1; + } else { + return indexOfSupplementary(ch, fromIndex); + } + } + + /** + * Handles (rare) calls of indexOf with a supplementary character. + */ + private int indexOfSupplementary(int ch, int fromIndex) { + if (Character.isValidCodePoint(ch)) { + final char[] value = this.toCharArray(); + final int offset = this.offset(); + final char hi = Character.highSurrogate(ch); + final char lo = Character.lowSurrogate(ch); + final int max = offset + length() - 1; + for (int i = offset + fromIndex; i < max; i++) { + if (value[i] == hi && value[i+1] == lo) { + return i - offset; + } + } + } + return -1; + } + + /** + * Returns the index within this string of the last occurrence of + * the specified character. For values of ch in the + * range from 0 to 0xFFFF (inclusive), the index (in Unicode code + * units) returned is the largest value k such that: + *

+     * this.charAt(k) == ch
+     * 
+ * is true. For other values of ch, it is the + * largest value k such that: + *
+     * this.codePointAt(k) == ch
+     * 
+ * is true. In either case, if no such character occurs in this + * string, then -1 is returned. The + * String is searched backwards starting at the last + * character. + * + * @param ch a character (Unicode code point). + * @return the index of the last occurrence of the character in the + * character sequence represented by this object, or + * -1 if the character does not occur. + */ + public int lastIndexOf(int ch) { + return lastIndexOf(ch, length() - 1); + } + + /** + * Returns the index within this string of the last occurrence of + * the specified character, searching backward starting at the + * specified index. For values of ch in the range + * from 0 to 0xFFFF (inclusive), the index returned is the largest + * value k such that: + *
+     * (this.charAt(k) == ch) && (k <= fromIndex)
+     * 
+ * is true. For other values of ch, it is the + * largest value k such that: + *
+     * (this.codePointAt(k) == ch) && (k <= fromIndex)
+     * 
+ * is true. In either case, if no such character occurs in this + * string at or before position fromIndex, then + * -1 is returned. + * + *

All indices are specified in char values + * (Unicode code units). + * + * @param ch a character (Unicode code point). + * @param fromIndex the index to start the search from. There is no + * restriction on the value of fromIndex. If it is + * greater than or equal to the length of this string, it has + * the same effect as if it were equal to one less than the + * length of this string: this entire string may be searched. + * If it is negative, it has the same effect as if it were -1: + * -1 is returned. + * @return the index of the last occurrence of the character in the + * character sequence represented by this object that is less + * than or equal to fromIndex, or -1 + * if the character does not occur before that point. + */ + @JavaScriptBody(args = { "ch", "from" }, body = + "if (typeof ch === 'number') ch = String.fromCharCode(ch);\n" + + "return this.toString().lastIndexOf(ch, from);" + ) + public int lastIndexOf(int ch, int fromIndex) { + if (ch < Character.MIN_SUPPLEMENTARY_CODE_POINT) { + // handle most cases here (ch is a BMP code point or a + // negative value (invalid code point)) + final char[] value = this.toCharArray(); + final int offset = this.offset(); + int i = offset + Math.min(fromIndex, length() - 1); + for (; i >= offset ; i--) { + if (value[i] == ch) { + return i - offset; + } + } + return -1; + } else { + return lastIndexOfSupplementary(ch, fromIndex); + } + } + + /** + * Handles (rare) calls of lastIndexOf with a supplementary character. + */ + private int lastIndexOfSupplementary(int ch, int fromIndex) { + if (Character.isValidCodePoint(ch)) { + final char[] value = this.toCharArray(); + final int offset = this.offset(); + char hi = Character.highSurrogate(ch); + char lo = Character.lowSurrogate(ch); + int i = offset + Math.min(fromIndex, length() - 2); + for (; i >= offset; i--) { + if (value[i] == hi && value[i+1] == lo) { + return i - offset; + } + } + } + return -1; + } + + /** + * Returns the index within this string of the first occurrence of the + * specified substring. + * + *

The returned index is the smallest value k for which: + *

+     * this.startsWith(str, k)
+     * 
+ * If no such value of k exists, then {@code -1} is returned. + * + * @param str the substring to search for. + * @return the index of the first occurrence of the specified substring, + * or {@code -1} if there is no such occurrence. + */ + public int indexOf(String str) { + return indexOf(str, 0); + } + + /** + * Returns the index within this string of the first occurrence of the + * specified substring, starting at the specified index. + * + *

The returned index is the smallest value k for which: + *

+     * k >= fromIndex && this.startsWith(str, k)
+     * 
+ * If no such value of k exists, then {@code -1} is returned. + * + * @param str the substring to search for. + * @param fromIndex the index from which to start the search. + * @return the index of the first occurrence of the specified substring, + * starting at the specified index, + * or {@code -1} if there is no such occurrence. + */ + @JavaScriptBody(args = { "str", "fromIndex" }, body = + "return this.toString().indexOf(str.toString(), fromIndex);" + ) + public native int indexOf(String str, int fromIndex); + + /** + * Returns the index within this string of the last occurrence of the + * specified substring. The last occurrence of the empty string "" + * is considered to occur at the index value {@code this.length()}. + * + *

The returned index is the largest value k for which: + *

+     * this.startsWith(str, k)
+     * 
+ * If no such value of k exists, then {@code -1} is returned. + * + * @param str the substring to search for. + * @return the index of the last occurrence of the specified substring, + * or {@code -1} if there is no such occurrence. + */ + public int lastIndexOf(String str) { + return lastIndexOf(str, length()); + } + + /** + * Returns the index within this string of the last occurrence of the + * specified substring, searching backward starting at the specified index. + * + *

The returned index is the largest value k for which: + *

+     * k <= fromIndex && this.startsWith(str, k)
+     * 
+ * If no such value of k exists, then {@code -1} is returned. + * + * @param str the substring to search for. + * @param fromIndex the index to start the search from. + * @return the index of the last occurrence of the specified substring, + * searching backward from the specified index, + * or {@code -1} if there is no such occurrence. + */ + @JavaScriptBody(args = { "s", "from" }, body = + "return this.toString().lastIndexOf(s.toString(), from);" + ) + public int lastIndexOf(String str, int fromIndex) { + return lastIndexOf(toCharArray(), offset(), length(), str.toCharArray(), str.offset(), str.length(), fromIndex); + } + + /** + * Code shared by String and StringBuffer to do searches. The + * source is the character array being searched, and the target + * is the string being searched for. + * + * @param source the characters being searched. + * @param sourceOffset offset of the source string. + * @param sourceCount count of the source string. + * @param target the characters being searched for. + * @param targetOffset offset of the target string. + * @param targetCount count of the target string. + * @param fromIndex the index to begin searching from. + */ + static int lastIndexOf(char[] source, int sourceOffset, int sourceCount, + char[] target, int targetOffset, int targetCount, + int fromIndex) { + /* + * Check arguments; return immediately where possible. For + * consistency, don't check for null str. + */ + int rightIndex = sourceCount - targetCount; + if (fromIndex < 0) { + return -1; + } + if (fromIndex > rightIndex) { + fromIndex = rightIndex; + } + /* Empty string always matches. */ + if (targetCount == 0) { + return fromIndex; + } + + int strLastIndex = targetOffset + targetCount - 1; + char strLastChar = target[strLastIndex]; + int min = sourceOffset + targetCount - 1; + int i = min + fromIndex; + + startSearchForLastChar: + while (true) { + while (i >= min && source[i] != strLastChar) { + i--; + } + if (i < min) { + return -1; + } + int j = i - 1; + int start = j - (targetCount - 1); + int k = strLastIndex - 1; + + while (j > start) { + if (source[j--] != target[k--]) { + i--; + continue startSearchForLastChar; + } + } + return start - sourceOffset + 1; + } + } + + /** + * Returns a new string that is a substring of this string. The + * substring begins with the character at the specified index and + * extends to the end of this string.

+ * Examples: + *

+     * "unhappy".substring(2) returns "happy"
+     * "Harbison".substring(3) returns "bison"
+     * "emptiness".substring(9) returns "" (an empty string)
+     * 
+ * + * @param beginIndex the beginning index, inclusive. + * @return the specified substring. + * @exception IndexOutOfBoundsException if + * beginIndex is negative or larger than the + * length of this String object. + */ + public String substring(int beginIndex) { + return substring(beginIndex, length()); + } + + /** + * Returns a new string that is a substring of this string. The + * substring begins at the specified beginIndex and + * extends to the character at index endIndex - 1. + * Thus the length of the substring is endIndex-beginIndex. + *

+ * Examples: + *

+     * "hamburger".substring(4, 8) returns "urge"
+     * "smiles".substring(1, 5) returns "mile"
+     * 
+ * + * @param beginIndex the beginning index, inclusive. + * @param endIndex the ending index, exclusive. + * @return the specified substring. + * @exception IndexOutOfBoundsException if the + * beginIndex is negative, or + * endIndex is larger than the length of + * this String object, or + * beginIndex is larger than + * endIndex. + */ + @JavaScriptBody(args = { "beginIndex", "endIndex" }, body = + "return this.toString().substring(beginIndex, endIndex);" + ) + public String substring(int beginIndex, int endIndex) { + if (beginIndex < 0) { + throw new StringIndexOutOfBoundsException(beginIndex); + } + if (endIndex > length()) { + throw new StringIndexOutOfBoundsException(endIndex); + } + if (beginIndex > endIndex) { + throw new StringIndexOutOfBoundsException(endIndex - beginIndex); + } + return ((beginIndex == 0) && (endIndex == length())) ? this : + new String(toCharArray(), offset() + beginIndex, endIndex - beginIndex); + } + + /** + * Returns a new character sequence that is a subsequence of this sequence. + * + *

An invocation of this method of the form + * + *

+     * str.subSequence(begin, end)
+ * + * behaves in exactly the same way as the invocation + * + *
+     * str.substring(begin, end)
+ * + * This method is defined so that the String class can implement + * the {@link CharSequence} interface.

+ * + * @param beginIndex the begin index, inclusive. + * @param endIndex the end index, exclusive. + * @return the specified subsequence. + * + * @throws IndexOutOfBoundsException + * if beginIndex or endIndex are negative, + * if endIndex is greater than length(), + * or if beginIndex is greater than startIndex + * + * @since 1.4 + * @spec JSR-51 + */ + public CharSequence subSequence(int beginIndex, int endIndex) { + return this.substring(beginIndex, endIndex); + } + + /** + * Concatenates the specified string to the end of this string. + *

+ * If the length of the argument string is 0, then this + * String object is returned. Otherwise, a new + * String object is created, representing a character + * sequence that is the concatenation of the character sequence + * represented by this String object and the character + * sequence represented by the argument string.

+ * Examples: + *

+     * "cares".concat("s") returns "caress"
+     * "to".concat("get").concat("her") returns "together"
+     * 
+ * + * @param str the String that is concatenated to the end + * of this String. + * @return a string that represents the concatenation of this object's + * characters followed by the string argument's characters. + */ + public String concat(String str) { + int otherLen = str.length(); + if (otherLen == 0) { + return this; + } + char buf[] = new char[length() + otherLen]; + getChars(0, length(), buf, 0); + str.getChars(0, otherLen, buf, length()); + return new String(buf, 0, length() + otherLen); + } + + /** + * Returns a new string resulting from replacing all occurrences of + * oldChar in this string with newChar. + *

+ * If the character oldChar does not occur in the + * character sequence represented by this String object, + * then a reference to this String object is returned. + * Otherwise, a new String object is created that + * represents a character sequence identical to the character sequence + * represented by this String object, except that every + * occurrence of oldChar is replaced by an occurrence + * of newChar. + *

+ * Examples: + *

+     * "mesquite in your cellar".replace('e', 'o')
+     *         returns "mosquito in your collar"
+     * "the war of baronets".replace('r', 'y')
+     *         returns "the way of bayonets"
+     * "sparring with a purple porpoise".replace('p', 't')
+     *         returns "starring with a turtle tortoise"
+     * "JonL".replace('q', 'x') returns "JonL" (no change)
+     * 
+ * + * @param oldChar the old character. + * @param newChar the new character. + * @return a string derived from this string by replacing every + * occurrence of oldChar with newChar. + */ + @JavaScriptBody(args = { "arg1", "arg2" }, body = + "if (typeof arg1 === 'number') arg1 = String.fromCharCode(arg1);\n" + + "if (typeof arg2 === 'number') arg2 = String.fromCharCode(arg2);\n" + + "var s = this.toString();\n" + + "for (;;) {\n" + + " var ret = s.replace(arg1, arg2);\n" + + " if (ret === s) {\n" + + " return ret;\n" + + " }\n" + + " s = ret;\n" + + "}" + ) + public String replace(char oldChar, char newChar) { + if (oldChar != newChar) { + int len = length(); + int i = -1; + char[] val = toCharArray(); /* avoid getfield opcode */ + int off = offset(); /* avoid getfield opcode */ + + while (++i < len) { + if (val[off + i] == oldChar) { + break; + } + } + if (i < len) { + char buf[] = new char[len]; + for (int j = 0 ; j < i ; j++) { + buf[j] = val[off+j]; + } + while (i < len) { + char c = val[off + i]; + buf[i] = (c == oldChar) ? newChar : c; + i++; + } + return new String(buf, 0, len); + } + } + return this; + } + + /** + * Tells whether or not this string matches the given regular expression. + * + *

An invocation of this method of the form + * str.matches(regex) yields exactly the + * same result as the expression + * + *

{@link java.util.regex.Pattern}.{@link + * java.util.regex.Pattern#matches(String,CharSequence) + * matches}(regex, str)
+ * + * @param regex + * the regular expression to which this string is to be matched + * + * @return true if, and only if, this string matches the + * given regular expression + * + * @throws PatternSyntaxException + * if the regular expression's syntax is invalid + * + * @see java.util.regex.Pattern + * + * @since 1.4 + * @spec JSR-51 + */ + @JavaScriptBody(args = { "regex" }, body = + "var self = this.toString();\n" + + "var re = new RegExp(regex.toString());\n" + + "var r = re.exec(self);\n" + + "return r != null && r.length > 0 && self.length == r[0].length;" + ) + public boolean matches(String regex) { + throw new UnsupportedOperationException(); + } + + /** + * Returns true if and only if this string contains the specified + * sequence of char values. + * + * @param s the sequence to search for + * @return true if this string contains s, false otherwise + * @throws NullPointerException if s is null + * @since 1.5 + */ + public boolean contains(CharSequence s) { + return indexOf(s.toString()) > -1; + } + + /** + * Replaces the first substring of this string that matches the given regular expression with the + * given replacement. + * + *

An invocation of this method of the form + * str.replaceFirst(regex, repl) + * yields exactly the same result as the expression + * + *

+ * {@link java.util.regex.Pattern}.{@link java.util.regex.Pattern#compile + * compile}(regex).{@link + * java.util.regex.Pattern#matcher(java.lang.CharSequence) + * matcher}(str).{@link java.util.regex.Matcher#replaceFirst + * replaceFirst}(repl)
+ * + *

+ * Note that backslashes (\) and dollar signs ($) in the + * replacement string may cause the results to be different than if it were + * being treated as a literal replacement string; see + * {@link java.util.regex.Matcher#replaceFirst}. + * Use {@link java.util.regex.Matcher#quoteReplacement} to suppress the special + * meaning of these characters, if desired. + * + * @param regex + * the regular expression to which this string is to be matched + * @param replacement + * the string to be substituted for the first match + * + * @return The resulting String + * + * @throws PatternSyntaxException + * if the regular expression's syntax is invalid + * + * @see java.util.regex.Pattern + * + * @since 1.4 + * @spec JSR-51 + */ + public String replaceFirst(String regex, String replacement) { + throw new UnsupportedOperationException(); + } + + /** + * Replaces each substring of this string that matches the given regular expression with the + * given replacement. + * + *

An invocation of this method of the form + * str.replaceAll(regex, repl) + * yields exactly the same result as the expression + * + *

+ * {@link java.util.regex.Pattern}.{@link java.util.regex.Pattern#compile + * compile}(regex).{@link + * java.util.regex.Pattern#matcher(java.lang.CharSequence) + * matcher}(str).{@link java.util.regex.Matcher#replaceAll + * replaceAll}(repl)
+ * + *

+ * Note that backslashes (\) and dollar signs ($) in the + * replacement string may cause the results to be different than if it were + * being treated as a literal replacement string; see + * {@link java.util.regex.Matcher#replaceAll Matcher.replaceAll}. + * Use {@link java.util.regex.Matcher#quoteReplacement} to suppress the special + * meaning of these characters, if desired. + * + * @param regex + * the regular expression to which this string is to be matched + * @param replacement + * the string to be substituted for each match + * + * @return The resulting String + * + * @throws PatternSyntaxException + * if the regular expression's syntax is invalid + * + * @see java.util.regex.Pattern + * + * @since 1.4 + * @spec JSR-51 + */ + public String replaceAll(String regex, String replacement) { + throw new UnsupportedOperationException(); + } + + /** + * Replaces each substring of this string that matches the literal target + * sequence with the specified literal replacement sequence. The + * replacement proceeds from the beginning of the string to the end, for + * example, replacing "aa" with "b" in the string "aaa" will result in + * "ba" rather than "ab". + * + * @param target The sequence of char values to be replaced + * @param replacement The replacement sequence of char values + * @return The resulting string + * @throws NullPointerException if target or + * replacement is null. + * @since 1.5 + */ + public String replace(CharSequence target, CharSequence replacement) { + throw new UnsupportedOperationException("This one should be supported, but without dep on rest of regexp"); + } + + /** + * Splits this string around matches of the given + * regular expression. + * + *

The array returned by this method contains each substring of this + * string that is terminated by another substring that matches the given + * expression or is terminated by the end of the string. The substrings in + * the array are in the order in which they occur in this string. If the + * expression does not match any part of the input then the resulting array + * has just one element, namely this string. + * + *

The limit parameter controls the number of times the + * pattern is applied and therefore affects the length of the resulting + * array. If the limit n is greater than zero then the pattern + * will be applied at most n - 1 times, the array's + * length will be no greater than n, and the array's last entry + * will contain all input beyond the last matched delimiter. If n + * is non-positive then the pattern will be applied as many times as + * possible and the array can have any length. If n is zero then + * the pattern will be applied as many times as possible, the array can + * have any length, and trailing empty strings will be discarded. + * + *

The string "boo:and:foo", for example, yields the + * following results with these parameters: + * + *

+ * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
RegexLimitResult
:2{ "boo", "and:foo" }
:5{ "boo", "and", "foo" }
:-2{ "boo", "and", "foo" }
o5{ "b", "", ":and:f", "", "" }
o-2{ "b", "", ":and:f", "", "" }
o0{ "b", "", ":and:f" }
+ * + *

An invocation of this method of the form + * str.split(regex, n) + * yields the same result as the expression + * + *

+ * {@link java.util.regex.Pattern}.{@link java.util.regex.Pattern#compile + * compile}(regex).{@link + * java.util.regex.Pattern#split(java.lang.CharSequence,int) + * split}(str, n) + *
+ * + * + * @param regex + * the delimiting regular expression + * + * @param limit + * the result threshold, as described above + * + * @return the array of strings computed by splitting this string + * around matches of the given regular expression + * + * @throws PatternSyntaxException + * if the regular expression's syntax is invalid + * + * @see java.util.regex.Pattern + * + * @since 1.4 + * @spec JSR-51 + */ + public String[] split(String regex, int limit) { + throw new UnsupportedOperationException("Needs regexp"); + } + + /** + * Splits this string around matches of the given regular expression. + * + *

This method works as if by invoking the two-argument {@link + * #split(String, int) split} method with the given expression and a limit + * argument of zero. Trailing empty strings are therefore not included in + * the resulting array. + * + *

The string "boo:and:foo", for example, yields the following + * results with these expressions: + * + *

+ * + * + * + * + * + * + * + * + *
RegexResult
:{ "boo", "and", "foo" }
o{ "b", "", ":and:f" }
+ * + * + * @param regex + * the delimiting regular expression + * + * @return the array of strings computed by splitting this string + * around matches of the given regular expression + * + * @throws PatternSyntaxException + * if the regular expression's syntax is invalid + * + * @see java.util.regex.Pattern + * + * @since 1.4 + * @spec JSR-51 + */ + public String[] split(String regex) { + return split(regex, 0); + } + + /** + * Converts all of the characters in this String to lower + * case using the rules of the given Locale. Case mapping is based + * on the Unicode Standard version specified by the {@link java.lang.Character Character} + * class. Since case mappings are not always 1:1 char mappings, the resulting + * String may be a different length than the original String. + *

+ * Examples of lowercase mappings are in the following table: + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
Language Code of LocaleUpper CaseLower CaseDescription
tr (Turkish)\u0130\u0069capital letter I with dot above -> small letter i
tr (Turkish)\u0049\u0131capital letter I -> small letter dotless i
(all)French Friesfrench frieslowercased all chars in String
(all)capiotacapchi + * capthetacapupsil + * capsigmaiotachi + * thetaupsilon + * sigmalowercased all chars in String
+ * + * @param locale use the case transformation rules for this locale + * @return the String, converted to lowercase. + * @see java.lang.String#toLowerCase() + * @see java.lang.String#toUpperCase() + * @see java.lang.String#toUpperCase(Locale) + * @since 1.1 + */ +// public String toLowerCase(Locale locale) { +// if (locale == null) { +// throw new NullPointerException(); +// } +// +// int firstUpper; +// +// /* Now check if there are any characters that need to be changed. */ +// scan: { +// for (firstUpper = 0 ; firstUpper < count; ) { +// char c = value[offset+firstUpper]; +// if ((c >= Character.MIN_HIGH_SURROGATE) && +// (c <= Character.MAX_HIGH_SURROGATE)) { +// int supplChar = codePointAt(firstUpper); +// if (supplChar != Character.toLowerCase(supplChar)) { +// break scan; +// } +// firstUpper += Character.charCount(supplChar); +// } else { +// if (c != Character.toLowerCase(c)) { +// break scan; +// } +// firstUpper++; +// } +// } +// return this; +// } +// +// char[] result = new char[count]; +// int resultOffset = 0; /* result may grow, so i+resultOffset +// * is the write location in result */ +// +// /* Just copy the first few lowerCase characters. */ +// arraycopy(value, offset, result, 0, firstUpper); +// +// String lang = locale.getLanguage(); +// boolean localeDependent = +// (lang == "tr" || lang == "az" || lang == "lt"); +// char[] lowerCharArray; +// int lowerChar; +// int srcChar; +// int srcCount; +// for (int i = firstUpper; i < count; i += srcCount) { +// srcChar = (int)value[offset+i]; +// if ((char)srcChar >= Character.MIN_HIGH_SURROGATE && +// (char)srcChar <= Character.MAX_HIGH_SURROGATE) { +// srcChar = codePointAt(i); +// srcCount = Character.charCount(srcChar); +// } else { +// srcCount = 1; +// } +// if (localeDependent || srcChar == '\u03A3') { // GREEK CAPITAL LETTER SIGMA +// lowerChar = ConditionalSpecialCasing.toLowerCaseEx(this, i, locale); +// } else if (srcChar == '\u0130') { // LATIN CAPITAL LETTER I DOT +// lowerChar = Character.ERROR; +// } else { +// lowerChar = Character.toLowerCase(srcChar); +// } +// if ((lowerChar == Character.ERROR) || +// (lowerChar >= Character.MIN_SUPPLEMENTARY_CODE_POINT)) { +// if (lowerChar == Character.ERROR) { +// if (!localeDependent && srcChar == '\u0130') { +// lowerCharArray = +// ConditionalSpecialCasing.toLowerCaseCharArray(this, i, Locale.ENGLISH); +// } else { +// lowerCharArray = +// ConditionalSpecialCasing.toLowerCaseCharArray(this, i, locale); +// } +// } else if (srcCount == 2) { +// resultOffset += Character.toChars(lowerChar, result, i + resultOffset) - srcCount; +// continue; +// } else { +// lowerCharArray = Character.toChars(lowerChar); +// } +// +// /* Grow result if needed */ +// int mapLen = lowerCharArray.length; +// if (mapLen > srcCount) { +// char[] result2 = new char[result.length + mapLen - srcCount]; +// arraycopy(result, 0, result2, 0, +// i + resultOffset); +// result = result2; +// } +// for (int x=0; xString to lower + * case using the rules of the default locale. This is equivalent to calling + * toLowerCase(Locale.getDefault()). + *

+ * Note: This method is locale sensitive, and may produce unexpected + * results if used for strings that are intended to be interpreted locale + * independently. + * Examples are programming language identifiers, protocol keys, and HTML + * tags. + * For instance, "TITLE".toLowerCase() in a Turkish locale + * returns "t\u005Cu0131tle", where '\u005Cu0131' is the + * LATIN SMALL LETTER DOTLESS I character. + * To obtain correct results for locale insensitive strings, use + * toLowerCase(Locale.ENGLISH). + *

+ * @return the String, converted to lowercase. + * @see java.lang.String#toLowerCase(Locale) + */ + @JavaScriptBody(args = {}, body = "return this.toLowerCase();") + public String toLowerCase() { + throw new UnsupportedOperationException("Should be supported but without connection to locale"); + } + + /** + * Converts all of the characters in this String to upper + * case using the rules of the given Locale. Case mapping is based + * on the Unicode Standard version specified by the {@link java.lang.Character Character} + * class. Since case mappings are not always 1:1 char mappings, the resulting + * String may be a different length than the original String. + *

+ * Examples of locale-sensitive and 1:M case mappings are in the following table. + *

+ * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
Language Code of LocaleLower CaseUpper CaseDescription
tr (Turkish)\u0069\u0130small letter i -> capital letter I with dot above
tr (Turkish)\u0131\u0049small letter dotless i -> capital letter I
(all)\u00df\u0053 \u0053small letter sharp s -> two letters: SS
(all)FahrvergnügenFAHRVERGNÜGEN
+ * @param locale use the case transformation rules for this locale + * @return the String, converted to uppercase. + * @see java.lang.String#toUpperCase() + * @see java.lang.String#toLowerCase() + * @see java.lang.String#toLowerCase(Locale) + * @since 1.1 + */ + /* not for javascript + public String toUpperCase(Locale locale) { + if (locale == null) { + throw new NullPointerException(); + } + + int firstLower; + + // Now check if there are any characters that need to be changed. + scan: { + for (firstLower = 0 ; firstLower < count; ) { + int c = (int)value[offset+firstLower]; + int srcCount; + if ((c >= Character.MIN_HIGH_SURROGATE) && + (c <= Character.MAX_HIGH_SURROGATE)) { + c = codePointAt(firstLower); + srcCount = Character.charCount(c); + } else { + srcCount = 1; + } + int upperCaseChar = Character.toUpperCaseEx(c); + if ((upperCaseChar == Character.ERROR) || + (c != upperCaseChar)) { + break scan; + } + firstLower += srcCount; + } + return this; + } + + char[] result = new char[count]; /* may grow * + int resultOffset = 0; /* result may grow, so i+resultOffset + * is the write location in result * + + /* Just copy the first few upperCase characters. * + arraycopy(value, offset, result, 0, firstLower); + + String lang = locale.getLanguage(); + boolean localeDependent = + (lang == "tr" || lang == "az" || lang == "lt"); + char[] upperCharArray; + int upperChar; + int srcChar; + int srcCount; + for (int i = firstLower; i < count; i += srcCount) { + srcChar = (int)value[offset+i]; + if ((char)srcChar >= Character.MIN_HIGH_SURROGATE && + (char)srcChar <= Character.MAX_HIGH_SURROGATE) { + srcChar = codePointAt(i); + srcCount = Character.charCount(srcChar); + } else { + srcCount = 1; + } + if (localeDependent) { + upperChar = ConditionalSpecialCasing.toUpperCaseEx(this, i, locale); + } else { + upperChar = Character.toUpperCaseEx(srcChar); + } + if ((upperChar == Character.ERROR) || + (upperChar >= Character.MIN_SUPPLEMENTARY_CODE_POINT)) { + if (upperChar == Character.ERROR) { + if (localeDependent) { + upperCharArray = + ConditionalSpecialCasing.toUpperCaseCharArray(this, i, locale); + } else { + upperCharArray = Character.toUpperCaseCharArray(srcChar); + } + } else if (srcCount == 2) { + resultOffset += Character.toChars(upperChar, result, i + resultOffset) - srcCount; + continue; + } else { + upperCharArray = Character.toChars(upperChar); + } + + /* Grow result if needed * + int mapLen = upperCharArray.length; + if (mapLen > srcCount) { + char[] result2 = new char[result.length + mapLen - srcCount]; + arraycopy(result, 0, result2, 0, + i + resultOffset); + result = result2; + } + for (int x=0; xString to upper + * case using the rules of the default locale. This method is equivalent to + * toUpperCase(Locale.getDefault()). + *

+ * Note: This method is locale sensitive, and may produce unexpected + * results if used for strings that are intended to be interpreted locale + * independently. + * Examples are programming language identifiers, protocol keys, and HTML + * tags. + * For instance, "title".toUpperCase() in a Turkish locale + * returns "T\u005Cu0130TLE", where '\u005Cu0130' is the + * LATIN CAPITAL LETTER I WITH DOT ABOVE character. + * To obtain correct results for locale insensitive strings, use + * toUpperCase(Locale.ENGLISH). + *

+ * @return the String, converted to uppercase. + * @see java.lang.String#toUpperCase(Locale) + */ + @JavaScriptBody(args = {}, body = "return this.toUpperCase();") + public String toUpperCase() { + throw new UnsupportedOperationException(); + } + + /** + * Returns a copy of the string, with leading and trailing whitespace + * omitted. + *

+ * If this String object represents an empty character + * sequence, or the first and last characters of character sequence + * represented by this String object both have codes + * greater than '\u0020' (the space character), then a + * reference to this String object is returned. + *

+ * Otherwise, if there is no character with a code greater than + * '\u0020' in the string, then a new + * String object representing an empty string is created + * and returned. + *

+ * Otherwise, let k be the index of the first character in the + * string whose code is greater than '\u0020', and let + * m be the index of the last character in the string whose code + * is greater than '\u0020'. A new String + * object is created, representing the substring of this string that + * begins with the character at index k and ends with the + * character at index m-that is, the result of + * this.substring(km+1). + *

+ * This method may be used to trim whitespace (as defined above) from + * the beginning and end of a string. + * + * @return A copy of this string with leading and trailing white + * space removed, or this string if it has no leading or + * trailing white space. + */ + public String trim() { + int len = length(); + int st = 0; + int off = offset(); /* avoid getfield opcode */ + char[] val = toCharArray(); /* avoid getfield opcode */ + + while ((st < len) && (val[off + st] <= ' ')) { + st++; + } + while ((st < len) && (val[off + len - 1] <= ' ')) { + len--; + } + return ((st > 0) || (len < length())) ? substring(st, len) : this; + } + + /** + * This object (which is already a string!) is itself returned. + * + * @return the string itself. + */ + @JavaScriptBody(args = {}, body = "return this.toString();") + public String toString() { + return this; + } + + /** + * Converts this string to a new character array. + * + * @return a newly allocated character array whose length is the length + * of this string and whose contents are initialized to contain + * the character sequence represented by this string. + */ + public char[] toCharArray() { + char result[] = new char[length()]; + getChars(0, length(), result, 0); + return result; + } + + /** + * Returns a formatted string using the specified format string and + * arguments. + * + *

The locale always used is the one returned by {@link + * java.util.Locale#getDefault() Locale.getDefault()}. + * + * @param format + * A format string + * + * @param args + * Arguments referenced by the format specifiers in the format + * string. If there are more arguments than format specifiers, the + * extra arguments are ignored. The number of arguments is + * variable and may be zero. The maximum number of arguments is + * limited by the maximum dimension of a Java array as defined by + * The Java™ Virtual Machine Specification. + * The behaviour on a + * null argument depends on the conversion. + * + * @throws IllegalFormatException + * If a format string contains an illegal syntax, a format + * specifier that is incompatible with the given arguments, + * insufficient arguments given the format string, or other + * illegal conditions. For specification of all possible + * formatting errors, see the Details section of the + * formatter class specification. + * + * @throws NullPointerException + * If the format is null + * + * @return A formatted string + * + * @see java.util.Formatter + * @since 1.5 + */ + public static String format(String format, Object ... args) { + throw new UnsupportedOperationException(); + } + + /** + * Returns a formatted string using the specified locale, format string, + * and arguments. + * + * @param l + * The {@linkplain java.util.Locale locale} to apply during + * formatting. If l is null then no localization + * is applied. + * + * @param format + * A format string + * + * @param args + * Arguments referenced by the format specifiers in the format + * string. If there are more arguments than format specifiers, the + * extra arguments are ignored. The number of arguments is + * variable and may be zero. The maximum number of arguments is + * limited by the maximum dimension of a Java array as defined by + * The Java™ Virtual Machine Specification. + * The behaviour on a + * null argument depends on the conversion. + * + * @throws IllegalFormatException + * If a format string contains an illegal syntax, a format + * specifier that is incompatible with the given arguments, + * insufficient arguments given the format string, or other + * illegal conditions. For specification of all possible + * formatting errors, see the Details section of the + * formatter class specification + * + * @throws NullPointerException + * If the format is null + * + * @return A formatted string + * + * @see java.util.Formatter + * @since 1.5 + */ +// public static String format(Locale l, String format, Object ... args) { +// return new Formatter(l).format(format, args).toString(); +// } + + /** + * Returns the string representation of the Object argument. + * + * @param obj an Object. + * @return if the argument is null, then a string equal to + * "null"; otherwise, the value of + * obj.toString() is returned. + * @see java.lang.Object#toString() + */ + public static String valueOf(Object obj) { + return (obj == null) ? "null" : obj.toString(); + } + + /** + * Returns the string representation of the char array + * argument. The contents of the character array are copied; subsequent + * modification of the character array does not affect the newly + * created string. + * + * @param data a char array. + * @return a newly allocated string representing the same sequence of + * characters contained in the character array argument. + */ + public static String valueOf(char data[]) { + return new String(data); + } + + /** + * Returns the string representation of a specific subarray of the + * char array argument. + *

+ * The offset argument is the index of the first + * character of the subarray. The count argument + * specifies the length of the subarray. The contents of the subarray + * are copied; subsequent modification of the character array does not + * affect the newly created string. + * + * @param data the character array. + * @param offset the initial offset into the value of the + * String. + * @param count the length of the value of the String. + * @return a string representing the sequence of characters contained + * in the subarray of the character array argument. + * @exception IndexOutOfBoundsException if offset is + * negative, or count is negative, or + * offset+count is larger than + * data.length. + */ + public static String valueOf(char data[], int offset, int count) { + return new String(data, offset, count); + } + + /** + * Returns a String that represents the character sequence in the + * array specified. + * + * @param data the character array. + * @param offset initial offset of the subarray. + * @param count length of the subarray. + * @return a String that contains the characters of the + * specified subarray of the character array. + */ + public static String copyValueOf(char data[], int offset, int count) { + // All public String constructors now copy the data. + return new String(data, offset, count); + } + + /** + * Returns a String that represents the character sequence in the + * array specified. + * + * @param data the character array. + * @return a String that contains the characters of the + * character array. + */ + public static String copyValueOf(char data[]) { + return copyValueOf(data, 0, data.length); + } + + /** + * Returns the string representation of the boolean argument. + * + * @param b a boolean. + * @return if the argument is true, a string equal to + * "true" is returned; otherwise, a string equal to + * "false" is returned. + */ + public static String valueOf(boolean b) { + return b ? "true" : "false"; + } + + /** + * Returns the string representation of the char + * argument. + * + * @param c a char. + * @return a string of length 1 containing + * as its single character the argument c. + */ + public static String valueOf(char c) { + char data[] = {c}; + return new String(data, 0, 1); + } + + /** + * Returns the string representation of the int argument. + *

+ * The representation is exactly the one returned by the + * Integer.toString method of one argument. + * + * @param i an int. + * @return a string representation of the int argument. + * @see java.lang.Integer#toString(int, int) + */ + public static String valueOf(int i) { + return Integer.toString(i); + } + + /** + * Returns the string representation of the long argument. + *

+ * The representation is exactly the one returned by the + * Long.toString method of one argument. + * + * @param l a long. + * @return a string representation of the long argument. + * @see java.lang.Long#toString(long) + */ + public static String valueOf(long l) { + return Long.toString(l); + } + + /** + * Returns the string representation of the float argument. + *

+ * The representation is exactly the one returned by the + * Float.toString method of one argument. + * + * @param f a float. + * @return a string representation of the float argument. + * @see java.lang.Float#toString(float) + */ + public static String valueOf(float f) { + return Float.toString(f); + } + + /** + * Returns the string representation of the double argument. + *

+ * The representation is exactly the one returned by the + * Double.toString method of one argument. + * + * @param d a double. + * @return a string representation of the double argument. + * @see java.lang.Double#toString(double) + */ + public static String valueOf(double d) { + return Double.toString(d); + } + + /** + * Returns a canonical representation for the string object. + *

+ * A pool of strings, initially empty, is maintained privately by the + * class String. + *

+ * When the intern method is invoked, if the pool already contains a + * string equal to this String object as determined by + * the {@link #equals(Object)} method, then the string from the pool is + * returned. Otherwise, this String object is added to the + * pool and a reference to this String object is returned. + *

+ * It follows that for any two strings s and t, + * s.intern() == t.intern() is true + * if and only if s.equals(t) is true. + *

+ * All literal strings and string-valued constant expressions are + * interned. String literals are defined in section 3.10.5 of the + * The Java™ Language Specification. + * + * @return a string that has the same contents as this string, but is + * guaranteed to be from a pool of unique strings. + */ + public native String intern(); +} diff -r 388e48c0a37a -r 05224402145d emul/mini/src/main/java/java/lang/StringBuffer.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/emul/mini/src/main/java/java/lang/StringBuffer.java Wed Jan 23 20:39:23 2013 +0100 @@ -0,0 +1,604 @@ +/* + * Copyright (c) 1994, 2008, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code 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 + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package java.lang; + + +/** + * A thread-safe, mutable sequence of characters. + * A string buffer is like a {@link String}, but can be modified. At any + * point in time it contains some particular sequence of characters, but + * the length and content of the sequence can be changed through certain + * method calls. + *

+ * String buffers are safe for use by multiple threads. The methods + * are synchronized where necessary so that all the operations on any + * particular instance behave as if they occur in some serial order + * that is consistent with the order of the method calls made by each of + * the individual threads involved. + *

+ * The principal operations on a StringBuffer are the + * append and insert methods, which are + * overloaded so as to accept data of any type. Each effectively + * converts a given datum to a string and then appends or inserts the + * characters of that string to the string buffer. The + * append method always adds these characters at the end + * of the buffer; the insert method adds the characters at + * a specified point. + *

+ * For example, if z refers to a string buffer object + * whose current contents are "start", then + * the method call z.append("le") would cause the string + * buffer to contain "startle", whereas + * z.insert(4, "le") would alter the string buffer to + * contain "starlet". + *

+ * In general, if sb refers to an instance of a StringBuffer, + * then sb.append(x) has the same effect as + * sb.insert(sb.length(), x). + *

+ * Whenever an operation occurs involving a source sequence (such as + * appending or inserting from a source sequence) this class synchronizes + * only on the string buffer performing the operation, not on the source. + *

+ * Every string buffer has a capacity. As long as the length of the + * character sequence contained in the string buffer does not exceed + * the capacity, it is not necessary to allocate a new internal + * buffer array. If the internal buffer overflows, it is + * automatically made larger. + * + * As of release JDK 5, this class has been supplemented with an equivalent + * class designed for use by a single thread, {@link StringBuilder}. The + * StringBuilder class should generally be used in preference to + * this one, as it supports all of the same operations but it is faster, as + * it performs no synchronization. + * + * @author Arthur van Hoff + * @see java.lang.StringBuilder + * @see java.lang.String + * @since JDK1.0 + */ + public final class StringBuffer + extends AbstractStringBuilder + implements java.io.Serializable, CharSequence +{ + + /** use serialVersionUID from JDK 1.0.2 for interoperability */ + static final long serialVersionUID = 3388685877147921107L; + + /** + * Constructs a string buffer with no characters in it and an + * initial capacity of 16 characters. + */ + public StringBuffer() { + super(16); + } + + /** + * Constructs a string buffer with no characters in it and + * the specified initial capacity. + * + * @param capacity the initial capacity. + * @exception NegativeArraySizeException if the capacity + * argument is less than 0. + */ + public StringBuffer(int capacity) { + super(capacity); + } + + /** + * Constructs a string buffer initialized to the contents of the + * specified string. The initial capacity of the string buffer is + * 16 plus the length of the string argument. + * + * @param str the initial contents of the buffer. + * @exception NullPointerException if str is null + */ + public StringBuffer(String str) { + super(str.length() + 16); + append(str); + } + + /** + * Constructs a string buffer that contains the same characters + * as the specified CharSequence. The initial capacity of + * the string buffer is 16 plus the length of the + * CharSequence argument. + *

+ * If the length of the specified CharSequence is + * less than or equal to zero, then an empty buffer of capacity + * 16 is returned. + * + * @param seq the sequence to copy. + * @exception NullPointerException if seq is null + * @since 1.5 + */ + public StringBuffer(CharSequence seq) { + this(seq.length() + 16); + append(seq); + } + + public synchronized int length() { + return count; + } + + public synchronized int capacity() { + return value.length; + } + + + public synchronized void ensureCapacity(int minimumCapacity) { + if (minimumCapacity > value.length) { + expandCapacity(minimumCapacity); + } + } + + /** + * @since 1.5 + */ + public synchronized void trimToSize() { + super.trimToSize(); + } + + /** + * @throws IndexOutOfBoundsException {@inheritDoc} + * @see #length() + */ + public synchronized void setLength(int newLength) { + super.setLength(newLength); + } + + /** + * @throws IndexOutOfBoundsException {@inheritDoc} + * @see #length() + */ + public synchronized char charAt(int index) { + if ((index < 0) || (index >= count)) + throw new StringIndexOutOfBoundsException(index); + return value[index]; + } + + /** + * @since 1.5 + */ + public synchronized int codePointAt(int index) { + return super.codePointAt(index); + } + + /** + * @since 1.5 + */ + public synchronized int codePointBefore(int index) { + return super.codePointBefore(index); + } + + /** + * @since 1.5 + */ + public synchronized int codePointCount(int beginIndex, int endIndex) { + return super.codePointCount(beginIndex, endIndex); + } + + /** + * @since 1.5 + */ + public synchronized int offsetByCodePoints(int index, int codePointOffset) { + return super.offsetByCodePoints(index, codePointOffset); + } + + /** + * @throws NullPointerException {@inheritDoc} + * @throws IndexOutOfBoundsException {@inheritDoc} + */ + public synchronized void getChars(int srcBegin, int srcEnd, char[] dst, + int dstBegin) + { + super.getChars(srcBegin, srcEnd, dst, dstBegin); + } + + /** + * @throws IndexOutOfBoundsException {@inheritDoc} + * @see #length() + */ + public synchronized void setCharAt(int index, char ch) { + if ((index < 0) || (index >= count)) + throw new StringIndexOutOfBoundsException(index); + value[index] = ch; + } + + public synchronized StringBuffer append(Object obj) { + super.append(String.valueOf(obj)); + return this; + } + + public synchronized StringBuffer append(String str) { + super.append(str); + return this; + } + + /** + * Appends the specified StringBuffer to this sequence. + *

+ * The characters of the StringBuffer argument are appended, + * in order, to the contents of this StringBuffer, increasing the + * length of this StringBuffer by the length of the argument. + * If sb is null, then the four characters + * "null" are appended to this StringBuffer. + *

+ * Let n be the length of the old character sequence, the one + * contained in the StringBuffer just prior to execution of the + * append method. Then the character at index k in + * the new character sequence is equal to the character at index k + * in the old character sequence, if k is less than n; + * otherwise, it is equal to the character at index k-n in the + * argument sb. + *

+ * This method synchronizes on this (the destination) + * object but does not synchronize on the source (sb). + * + * @param sb the StringBuffer to append. + * @return a reference to this object. + * @since 1.4 + */ + public synchronized StringBuffer append(StringBuffer sb) { + super.append(sb); + return this; + } + + + /** + * Appends the specified CharSequence to this + * sequence. + *

+ * The characters of the CharSequence argument are appended, + * in order, increasing the length of this sequence by the length of the + * argument. + * + *

The result of this method is exactly the same as if it were an + * invocation of this.append(s, 0, s.length()); + * + *

This method synchronizes on this (the destination) + * object but does not synchronize on the source (s). + * + *

If s is null, then the four characters + * "null" are appended. + * + * @param s the CharSequence to append. + * @return a reference to this object. + * @since 1.5 + */ + public StringBuffer append(CharSequence s) { + // Note, synchronization achieved via other invocations + if (s == null) + s = "null"; + if (s instanceof String) + return this.append((String)s); + if (s instanceof StringBuffer) + return this.append((StringBuffer)s); + return this.append(s, 0, s.length()); + } + + /** + * @throws IndexOutOfBoundsException {@inheritDoc} + * @since 1.5 + */ + public synchronized StringBuffer append(CharSequence s, int start, int end) + { + super.append(s, start, end); + return this; + } + + public synchronized StringBuffer append(char[] str) { + super.append(str); + return this; + } + + /** + * @throws IndexOutOfBoundsException {@inheritDoc} + */ + public synchronized StringBuffer append(char[] str, int offset, int len) { + super.append(str, offset, len); + return this; + } + + public synchronized StringBuffer append(boolean b) { + super.append(b); + return this; + } + + public synchronized StringBuffer append(char c) { + super.append(c); + return this; + } + + public synchronized StringBuffer append(int i) { + super.append(i); + return this; + } + + /** + * @since 1.5 + */ + public synchronized StringBuffer appendCodePoint(int codePoint) { + super.appendCodePoint(codePoint); + return this; + } + + public synchronized StringBuffer append(long lng) { + super.append(lng); + return this; + } + + public synchronized StringBuffer append(float f) { + super.append(f); + return this; + } + + public synchronized StringBuffer append(double d) { + super.append(d); + return this; + } + + /** + * @throws StringIndexOutOfBoundsException {@inheritDoc} + * @since 1.2 + */ + public synchronized StringBuffer delete(int start, int end) { + super.delete(start, end); + return this; + } + + /** + * @throws StringIndexOutOfBoundsException {@inheritDoc} + * @since 1.2 + */ + public synchronized StringBuffer deleteCharAt(int index) { + super.deleteCharAt(index); + return this; + } + + /** + * @throws StringIndexOutOfBoundsException {@inheritDoc} + * @since 1.2 + */ + public synchronized StringBuffer replace(int start, int end, String str) { + super.replace(start, end, str); + return this; + } + + /** + * @throws StringIndexOutOfBoundsException {@inheritDoc} + * @since 1.2 + */ + public synchronized String substring(int start) { + return substring(start, count); + } + + /** + * @throws IndexOutOfBoundsException {@inheritDoc} + * @since 1.4 + */ + public synchronized CharSequence subSequence(int start, int end) { + return super.substring(start, end); + } + + /** + * @throws StringIndexOutOfBoundsException {@inheritDoc} + * @since 1.2 + */ + public synchronized String substring(int start, int end) { + return super.substring(start, end); + } + + /** + * @throws StringIndexOutOfBoundsException {@inheritDoc} + * @since 1.2 + */ + public synchronized StringBuffer insert(int index, char[] str, int offset, + int len) + { + super.insert(index, str, offset, len); + return this; + } + + /** + * @throws StringIndexOutOfBoundsException {@inheritDoc} + */ + public synchronized StringBuffer insert(int offset, Object obj) { + super.insert(offset, String.valueOf(obj)); + return this; + } + + /** + * @throws StringIndexOutOfBoundsException {@inheritDoc} + */ + public synchronized StringBuffer insert(int offset, String str) { + super.insert(offset, str); + return this; + } + + /** + * @throws StringIndexOutOfBoundsException {@inheritDoc} + */ + public synchronized StringBuffer insert(int offset, char[] str) { + super.insert(offset, str); + return this; + } + + /** + * @throws IndexOutOfBoundsException {@inheritDoc} + * @since 1.5 + */ + public StringBuffer insert(int dstOffset, CharSequence s) { + // Note, synchronization achieved via other invocations + if (s == null) + s = "null"; + if (s instanceof String) + return this.insert(dstOffset, (String)s); + return this.insert(dstOffset, s, 0, s.length()); + } + + /** + * @throws IndexOutOfBoundsException {@inheritDoc} + * @since 1.5 + */ + public synchronized StringBuffer insert(int dstOffset, CharSequence s, + int start, int end) + { + super.insert(dstOffset, s, start, end); + return this; + } + + /** + * @throws StringIndexOutOfBoundsException {@inheritDoc} + */ + public StringBuffer insert(int offset, boolean b) { + return insert(offset, String.valueOf(b)); + } + + /** + * @throws IndexOutOfBoundsException {@inheritDoc} + */ + public synchronized StringBuffer insert(int offset, char c) { + super.insert(offset, c); + return this; + } + + /** + * @throws StringIndexOutOfBoundsException {@inheritDoc} + */ + public StringBuffer insert(int offset, int i) { + return insert(offset, String.valueOf(i)); + } + + /** + * @throws StringIndexOutOfBoundsException {@inheritDoc} + */ + public StringBuffer insert(int offset, long l) { + return insert(offset, String.valueOf(l)); + } + + /** + * @throws StringIndexOutOfBoundsException {@inheritDoc} + */ + public StringBuffer insert(int offset, float f) { + return insert(offset, String.valueOf(f)); + } + + /** + * @throws StringIndexOutOfBoundsException {@inheritDoc} + */ + public StringBuffer insert(int offset, double d) { + return insert(offset, String.valueOf(d)); + } + + /** + * @throws NullPointerException {@inheritDoc} + * @since 1.4 + */ + public int indexOf(String str) { + return indexOf(str, 0); + } + + /** + * @throws NullPointerException {@inheritDoc} + * @since 1.4 + */ + public synchronized int indexOf(String str, int fromIndex) { + return super.indexOf(str, fromIndex); + } + + /** + * @throws NullPointerException {@inheritDoc} + * @since 1.4 + */ + public int lastIndexOf(String str) { + // Note, synchronization achieved via other invocations + return lastIndexOf(str, count); + } + + /** + * @throws NullPointerException {@inheritDoc} + * @since 1.4 + */ + public synchronized int lastIndexOf(String str, int fromIndex) { + return String.lastIndexOf(value, 0, count, + str.toCharArray(), 0, str.length(), fromIndex); + } + + /** + * @since JDK1.0.2 + */ + public synchronized StringBuffer reverse() { + super.reverse(); + return this; + } + + public synchronized String toString() { + return new String(value, 0, count); + } + +// /** +// * Serializable fields for StringBuffer. +// * +// * @serialField value char[] +// * The backing character array of this StringBuffer. +// * @serialField count int +// * The number of characters in this StringBuffer. +// * @serialField shared boolean +// * A flag indicating whether the backing array is shared. +// * The value is ignored upon deserialization. +// */ +// private static final java.io.ObjectStreamField[] serialPersistentFields = +// { +// new java.io.ObjectStreamField("value", char[].class), +// new java.io.ObjectStreamField("count", Integer.TYPE), +// new java.io.ObjectStreamField("shared", Boolean.TYPE), +// }; +// +// /** +// * readObject is called to restore the state of the StringBuffer from +// * a stream. +// */ +// private synchronized void writeObject(java.io.ObjectOutputStream s) +// throws java.io.IOException { +// java.io.ObjectOutputStream.PutField fields = s.putFields(); +// fields.put("value", value); +// fields.put("count", count); +// fields.put("shared", false); +// s.writeFields(); +// } +// +// /** +// * readObject is called to restore the state of the StringBuffer from +// * a stream. +// */ +// private void readObject(java.io.ObjectInputStream s) +// throws java.io.IOException, ClassNotFoundException { +// java.io.ObjectInputStream.GetField fields = s.readFields(); +// value = (char[])fields.get("value", null); +// count = fields.get("count", 0); +// } +} diff -r 388e48c0a37a -r 05224402145d emul/mini/src/main/java/java/lang/StringBuilder.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/emul/mini/src/main/java/java/lang/StringBuilder.java Wed Jan 23 20:39:23 2013 +0100 @@ -0,0 +1,436 @@ +/* + * Copyright (c) 2003, 2008, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code 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 + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package java.lang; + + +/** + * A mutable sequence of characters. This class provides an API compatible + * with StringBuffer, but with no guarantee of synchronization. + * This class is designed for use as a drop-in replacement for + * StringBuffer in places where the string buffer was being + * used by a single thread (as is generally the case). Where possible, + * it is recommended that this class be used in preference to + * StringBuffer as it will be faster under most implementations. + * + *

The principal operations on a StringBuilder are the + * append and insert methods, which are + * overloaded so as to accept data of any type. Each effectively + * converts a given datum to a string and then appends or inserts the + * characters of that string to the string builder. The + * append method always adds these characters at the end + * of the builder; the insert method adds the characters at + * a specified point. + *

+ * For example, if z refers to a string builder object + * whose current contents are "start", then + * the method call z.append("le") would cause the string + * builder to contain "startle", whereas + * z.insert(4, "le") would alter the string builder to + * contain "starlet". + *

+ * In general, if sb refers to an instance of a StringBuilder, + * then sb.append(x) has the same effect as + * sb.insert(sb.length(), x). + * + * Every string builder has a capacity. As long as the length of the + * character sequence contained in the string builder does not exceed + * the capacity, it is not necessary to allocate a new internal + * buffer. If the internal buffer overflows, it is automatically made larger. + * + *

Instances of StringBuilder are not safe for + * use by multiple threads. If such synchronization is required then it is + * recommended that {@link java.lang.StringBuffer} be used. + * + * @author Michael McCloskey + * @see java.lang.StringBuffer + * @see java.lang.String + * @since 1.5 + */ +public final class StringBuilder + extends AbstractStringBuilder + implements java.io.Serializable, CharSequence +{ + + /** use serialVersionUID for interoperability */ + static final long serialVersionUID = 4383685877147921099L; + + /** + * Constructs a string builder with no characters in it and an + * initial capacity of 16 characters. + */ + public StringBuilder() { + super(16); + } + + /** + * Constructs a string builder with no characters in it and an + * initial capacity specified by the capacity argument. + * + * @param capacity the initial capacity. + * @throws NegativeArraySizeException if the capacity + * argument is less than 0. + */ + public StringBuilder(int capacity) { + super(capacity); + } + + /** + * Constructs a string builder initialized to the contents of the + * specified string. The initial capacity of the string builder is + * 16 plus the length of the string argument. + * + * @param str the initial contents of the buffer. + * @throws NullPointerException if str is null + */ + public StringBuilder(String str) { + super(str.length() + 16); + append(str); + } + + /** + * Constructs a string builder that contains the same characters + * as the specified CharSequence. The initial capacity of + * the string builder is 16 plus the length of the + * CharSequence argument. + * + * @param seq the sequence to copy. + * @throws NullPointerException if seq is null + */ + public StringBuilder(CharSequence seq) { + this(seq.length() + 16); + append(seq); + } + + public StringBuilder append(Object obj) { + return append(String.valueOf(obj)); + } + + public StringBuilder append(String str) { + super.append(str); + return this; + } + + // Appends the specified string builder to this sequence. + private StringBuilder append(StringBuilder sb) { + if (sb == null) + return append("null"); + int len = sb.length(); + int newcount = count + len; + if (newcount > value.length) + expandCapacity(newcount); + sb.getChars(0, len, value, count); + count = newcount; + return this; + } + + /** + * Appends the specified StringBuffer to this sequence. + *

+ * The characters of the StringBuffer argument are appended, + * in order, to this sequence, increasing the + * length of this sequence by the length of the argument. + * If sb is null, then the four characters + * "null" are appended to this sequence. + *

+ * Let n be the length of this character sequence just prior to + * execution of the append method. Then the character at index + * k in the new character sequence is equal to the character at + * index k in the old character sequence, if k is less than + * n; otherwise, it is equal to the character at index k-n + * in the argument sb. + * + * @param sb the StringBuffer to append. + * @return a reference to this object. + */ + public StringBuilder append(StringBuffer sb) { + super.append(sb); + return this; + } + + /** + */ + public StringBuilder append(CharSequence s) { + if (s == null) + s = "null"; + if (s instanceof String) + return this.append((String)s); + if (s instanceof StringBuffer) + return this.append((StringBuffer)s); + if (s instanceof StringBuilder) + return this.append((StringBuilder)s); + return this.append(s, 0, s.length()); + } + + /** + * @throws IndexOutOfBoundsException {@inheritDoc} + */ + public StringBuilder append(CharSequence s, int start, int end) { + super.append(s, start, end); + return this; + } + + public StringBuilder append(char[] str) { + super.append(str); + return this; + } + + /** + * @throws IndexOutOfBoundsException {@inheritDoc} + */ + public StringBuilder append(char[] str, int offset, int len) { + super.append(str, offset, len); + return this; + } + + public StringBuilder append(boolean b) { + super.append(b); + return this; + } + + public StringBuilder append(char c) { + super.append(c); + return this; + } + + public StringBuilder append(int i) { + super.append(i); + return this; + } + + public StringBuilder append(long lng) { + super.append(lng); + return this; + } + + public StringBuilder append(float f) { + super.append(f); + return this; + } + + public StringBuilder append(double d) { + super.append(d); + return this; + } + + /** + * @since 1.5 + */ + public StringBuilder appendCodePoint(int codePoint) { + super.appendCodePoint(codePoint); + return this; + } + + /** + * @throws StringIndexOutOfBoundsException {@inheritDoc} + */ + public StringBuilder delete(int start, int end) { + super.delete(start, end); + return this; + } + + /** + * @throws StringIndexOutOfBoundsException {@inheritDoc} + */ + public StringBuilder deleteCharAt(int index) { + super.deleteCharAt(index); + return this; + } + + /** + * @throws StringIndexOutOfBoundsException {@inheritDoc} + */ + public StringBuilder replace(int start, int end, String str) { + super.replace(start, end, str); + return this; + } + + /** + * @throws StringIndexOutOfBoundsException {@inheritDoc} + */ + public StringBuilder insert(int index, char[] str, int offset, + int len) + { + super.insert(index, str, offset, len); + return this; + } + + /** + * @throws StringIndexOutOfBoundsException {@inheritDoc} + */ + public StringBuilder insert(int offset, Object obj) { + return insert(offset, String.valueOf(obj)); + } + + /** + * @throws StringIndexOutOfBoundsException {@inheritDoc} + */ + public StringBuilder insert(int offset, String str) { + super.insert(offset, str); + return this; + } + + /** + * @throws StringIndexOutOfBoundsException {@inheritDoc} + */ + public StringBuilder insert(int offset, char[] str) { + super.insert(offset, str); + return this; + } + + /** + * @throws IndexOutOfBoundsException {@inheritDoc} + */ + public StringBuilder insert(int dstOffset, CharSequence s) { + if (s == null) + s = "null"; + if (s instanceof String) + return this.insert(dstOffset, (String)s); + return this.insert(dstOffset, s, 0, s.length()); + } + + /** + * @throws IndexOutOfBoundsException {@inheritDoc} + */ + public StringBuilder insert(int dstOffset, CharSequence s, + int start, int end) + { + super.insert(dstOffset, s, start, end); + return this; + } + + /** + * @throws StringIndexOutOfBoundsException {@inheritDoc} + */ + public StringBuilder insert(int offset, boolean b) { + super.insert(offset, b); + return this; + } + + /** + * @throws IndexOutOfBoundsException {@inheritDoc} + */ + public StringBuilder insert(int offset, char c) { + super.insert(offset, c); + return this; + } + + /** + * @throws StringIndexOutOfBoundsException {@inheritDoc} + */ + public StringBuilder insert(int offset, int i) { + return insert(offset, String.valueOf(i)); + } + + /** + * @throws StringIndexOutOfBoundsException {@inheritDoc} + */ + public StringBuilder insert(int offset, long l) { + return insert(offset, String.valueOf(l)); + } + + /** + * @throws StringIndexOutOfBoundsException {@inheritDoc} + */ + public StringBuilder insert(int offset, float f) { + return insert(offset, String.valueOf(f)); + } + + /** + * @throws StringIndexOutOfBoundsException {@inheritDoc} + */ + public StringBuilder insert(int offset, double d) { + return insert(offset, String.valueOf(d)); + } + + /** + * @throws NullPointerException {@inheritDoc} + */ + public int indexOf(String str) { + return indexOf(str, 0); + } + + /** + * @throws NullPointerException {@inheritDoc} + */ + public int indexOf(String str, int fromIndex) { + return super.indexOf(str, fromIndex); + } + + /** + * @throws NullPointerException {@inheritDoc} + */ + public int lastIndexOf(String str) { + return lastIndexOf(str, count); + } + + /** + * @throws NullPointerException {@inheritDoc} + */ + public int lastIndexOf(String str, int fromIndex) { + return String.lastIndexOf(value, 0, count, + str.toCharArray(), 0, str.length(), fromIndex); + } + + public StringBuilder reverse() { + super.reverse(); + return this; + } + + public String toString() { + // Create a copy, don't share the array + return new String(value, 0, count); + } + + /** + * Save the state of the StringBuilder instance to a stream + * (that is, serialize it). + * + * @serialData the number of characters currently stored in the string + * builder (int), followed by the characters in the + * string builder (char[]). The length of the + * char array may be greater than the number of + * characters currently stored in the string builder, in which + * case extra characters are ignored. + */ +// private void writeObject(java.io.ObjectOutputStream s) +// throws java.io.IOException { +// s.defaultWriteObject(); +// s.writeInt(count); +// s.writeObject(value); +// } + + /** + * readObject is called to restore the state of the StringBuffer from + * a stream. + */ +// private void readObject(java.io.ObjectInputStream s) +// throws java.io.IOException, ClassNotFoundException { +// s.defaultReadObject(); +// count = s.readInt(); +// value = (char[]) s.readObject(); +// } + +} diff -r 388e48c0a37a -r 05224402145d emul/mini/src/main/java/java/lang/StringIndexOutOfBoundsException.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/emul/mini/src/main/java/java/lang/StringIndexOutOfBoundsException.java Wed Jan 23 20:39:23 2013 +0100 @@ -0,0 +1,71 @@ +/* + * Copyright (c) 1994, 2008, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code 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 + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package java.lang; + +/** + * Thrown by String methods to indicate that an index + * is either negative or greater than the size of the string. For + * some methods such as the charAt method, this exception also is + * thrown when the index is equal to the size of the string. + * + * @author unascribed + * @see java.lang.String#charAt(int) + * @since JDK1.0 + */ +public +class StringIndexOutOfBoundsException extends IndexOutOfBoundsException { + private static final long serialVersionUID = -6762910422159637258L; + + /** + * Constructs a StringIndexOutOfBoundsException with no + * detail message. + * + * @since JDK1.0. + */ + public StringIndexOutOfBoundsException() { + super(); + } + + /** + * Constructs a StringIndexOutOfBoundsException with + * the specified detail message. + * + * @param s the detail message. + */ + public StringIndexOutOfBoundsException(String s) { + super(s); + } + + /** + * Constructs a new StringIndexOutOfBoundsException + * class with an argument indicating the illegal index. + * + * @param index the illegal index. + */ + public StringIndexOutOfBoundsException(int index) { + super("String index out of range: " + index); + } +} diff -r 388e48c0a37a -r 05224402145d emul/mini/src/main/java/java/lang/Throwable.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/emul/mini/src/main/java/java/lang/Throwable.java Wed Jan 23 20:39:23 2013 +0100 @@ -0,0 +1,1088 @@ +/* + * Copyright (c) 1994, 2011, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code 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 + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package java.lang; +import java.io.*; +import org.apidesign.bck2brwsr.core.JavaScriptBody; +import org.apidesign.bck2brwsr.core.JavaScriptOnly; + +/** + * The {@code Throwable} class is the superclass of all errors and + * exceptions in the Java language. Only objects that are instances of this + * class (or one of its subclasses) are thrown by the Java Virtual Machine or + * can be thrown by the Java {@code throw} statement. Similarly, only + * this class or one of its subclasses can be the argument type in a + * {@code catch} clause. + * + * For the purposes of compile-time checking of exceptions, {@code + * Throwable} and any subclass of {@code Throwable} that is not also a + * subclass of either {@link RuntimeException} or {@link Error} are + * regarded as checked exceptions. + * + *

Instances of two subclasses, {@link java.lang.Error} and + * {@link java.lang.Exception}, are conventionally used to indicate + * that exceptional situations have occurred. Typically, these instances + * are freshly created in the context of the exceptional situation so + * as to include relevant information (such as stack trace data). + * + *

A throwable contains a snapshot of the execution stack of its + * thread at the time it was created. It can also contain a message + * string that gives more information about the error. Over time, a + * throwable can {@linkplain Throwable#addSuppressed suppress} other + * throwables from being propagated. Finally, the throwable can also + * contain a cause: another throwable that caused this + * throwable to be constructed. The recording of this causal information + * is referred to as the chained exception facility, as the + * cause can, itself, have a cause, and so on, leading to a "chain" of + * exceptions, each caused by another. + * + *

One reason that a throwable may have a cause is that the class that + * throws it is built atop a lower layered abstraction, and an operation on + * the upper layer fails due to a failure in the lower layer. It would be bad + * design to let the throwable thrown by the lower layer propagate outward, as + * it is generally unrelated to the abstraction provided by the upper layer. + * Further, doing so would tie the API of the upper layer to the details of + * its implementation, assuming the lower layer's exception was a checked + * exception. Throwing a "wrapped exception" (i.e., an exception containing a + * cause) allows the upper layer to communicate the details of the failure to + * its caller without incurring either of these shortcomings. It preserves + * the flexibility to change the implementation of the upper layer without + * changing its API (in particular, the set of exceptions thrown by its + * methods). + * + *

A second reason that a throwable may have a cause is that the method + * that throws it must conform to a general-purpose interface that does not + * permit the method to throw the cause directly. For example, suppose + * a persistent collection conforms to the {@link java.util.Collection + * Collection} interface, and that its persistence is implemented atop + * {@code java.io}. Suppose the internals of the {@code add} method + * can throw an {@link java.io.IOException IOException}. The implementation + * can communicate the details of the {@code IOException} to its caller + * while conforming to the {@code Collection} interface by wrapping the + * {@code IOException} in an appropriate unchecked exception. (The + * specification for the persistent collection should indicate that it is + * capable of throwing such exceptions.) + * + *

A cause can be associated with a throwable in two ways: via a + * constructor that takes the cause as an argument, or via the + * {@link #initCause(Throwable)} method. New throwable classes that + * wish to allow causes to be associated with them should provide constructors + * that take a cause and delegate (perhaps indirectly) to one of the + * {@code Throwable} constructors that takes a cause. + * + * Because the {@code initCause} method is public, it allows a cause to be + * associated with any throwable, even a "legacy throwable" whose + * implementation predates the addition of the exception chaining mechanism to + * {@code Throwable}. + * + *

By convention, class {@code Throwable} and its subclasses have two + * constructors, one that takes no arguments and one that takes a + * {@code String} argument that can be used to produce a detail message. + * Further, those subclasses that might likely have a cause associated with + * them should have two more constructors, one that takes a + * {@code Throwable} (the cause), and one that takes a + * {@code String} (the detail message) and a {@code Throwable} (the + * cause). + * + * @author unascribed + * @author Josh Bloch (Added exception chaining and programmatic access to + * stack trace in 1.4.) + * @jls 11.2 Compile-Time Checking of Exceptions + * @since JDK1.0 + */ +public class Throwable implements Serializable { + /** use serialVersionUID from JDK 1.0.2 for interoperability */ + private static final long serialVersionUID = -3042686055658047285L; + + /** + * Native code saves some indication of the stack backtrace in this slot. + */ + private transient Object backtrace; + + /** + * Specific details about the Throwable. For example, for + * {@code FileNotFoundException}, this contains the name of + * the file that could not be found. + * + * @serial + */ + private String detailMessage; + + + /** + * Holder class to defer initializing sentinel objects only used + * for serialization. + */ + private static class SentinelHolder { + /** + * {@linkplain #setStackTrace(StackTraceElement[]) Setting the + * stack trace} to a one-element array containing this sentinel + * value indicates future attempts to set the stack trace will be + * ignored. The sentinal is equal to the result of calling:
+ * {@code new StackTraceElement("", "", null, Integer.MIN_VALUE)} + */ + public static final StackTraceElement STACK_TRACE_ELEMENT_SENTINEL = + new StackTraceElement("", "", null, Integer.MIN_VALUE); + + /** + * Sentinel value used in the serial form to indicate an immutable + * stack trace. + */ + public static final StackTraceElement[] STACK_TRACE_SENTINEL = + new StackTraceElement[] {STACK_TRACE_ELEMENT_SENTINEL}; + } + + /** + * A shared value for an empty stack. + */ + private static final StackTraceElement[] UNASSIGNED_STACK = new StackTraceElement[0]; + + /* + * To allow Throwable objects to be made immutable and safely + * reused by the JVM, such as OutOfMemoryErrors, fields of + * Throwable that are writable in response to user actions, cause, + * stackTrace, and suppressedExceptions obey the following + * protocol: + * + * 1) The fields are initialized to a non-null sentinel value + * which indicates the value has logically not been set. + * + * 2) Writing a null to the field indicates further writes + * are forbidden + * + * 3) The sentinel value may be replaced with another non-null + * value. + * + * For example, implementations of the HotSpot JVM have + * preallocated OutOfMemoryError objects to provide for better + * diagnosability of that situation. These objects are created + * without calling the constructor for that class and the fields + * in question are initialized to null. To support this + * capability, any new fields added to Throwable that require + * being initialized to a non-null value require a coordinated JVM + * change. + */ + + /** + * The throwable that caused this throwable to get thrown, or null if this + * throwable was not caused by another throwable, or if the causative + * throwable is unknown. If this field is equal to this throwable itself, + * it indicates that the cause of this throwable has not yet been + * initialized. + * + * @serial + * @since 1.4 + */ + private Throwable cause = this; + + /** + * The stack trace, as returned by {@link #getStackTrace()}. + * + * The field is initialized to a zero-length array. A {@code + * null} value of this field indicates subsequent calls to {@link + * #setStackTrace(StackTraceElement[])} and {@link + * #fillInStackTrace()} will be be no-ops. + * + * @serial + * @since 1.4 + */ + private StackTraceElement[] stackTrace = UNASSIGNED_STACK; + + // Setting this static field introduces an acceptable + // initialization dependency on a few java.util classes. +// I don't think this dependency is acceptable +// private static final List SUPPRESSED_SENTINEL = +// Collections.unmodifiableList(new ArrayList(0)); + + /** + * The list of suppressed exceptions, as returned by {@link + * #getSuppressed()}. The list is initialized to a zero-element + * unmodifiable sentinel list. When a serialized Throwable is + * read in, if the {@code suppressedExceptions} field points to a + * zero-element list, the field is reset to the sentinel value. + * + * @serial + * @since 1.7 + */ +// private List suppressedExceptions = SUPPRESSED_SENTINEL; + + /** Message for trying to suppress a null exception. */ + private static final String NULL_CAUSE_MESSAGE = "Cannot suppress a null exception."; + + /** Message for trying to suppress oneself. */ + private static final String SELF_SUPPRESSION_MESSAGE = "Self-suppression not permitted"; + + /** Caption for labeling causative exception stack traces */ + @JavaScriptOnly(name="toString", value="function() { return this.toString__Ljava_lang_String_2().toString(); }") + private static void jsToString() { + } + + @JavaScriptOnly(name="valueOf", value="function() { return this.toString().valueOf(); }") + private static void jsValudOf() { + } + private static final String CAUSE_CAPTION = "Caused by: "; + + /** Caption for labeling suppressed exception stack traces */ + private static final String SUPPRESSED_CAPTION = "Suppressed: "; + + /** + * Constructs a new throwable with {@code null} as its detail message. + * The cause is not initialized, and may subsequently be initialized by a + * call to {@link #initCause}. + * + *

The {@link #fillInStackTrace()} method is called to initialize + * the stack trace data in the newly created throwable. + */ + public Throwable() { + fillInStackTrace(); + } + + /** + * Constructs a new throwable with the specified detail message. The + * cause is not initialized, and may subsequently be initialized by + * a call to {@link #initCause}. + * + *

The {@link #fillInStackTrace()} method is called to initialize + * the stack trace data in the newly created throwable. + * + * @param message the detail message. The detail message is saved for + * later retrieval by the {@link #getMessage()} method. + */ + public Throwable(String message) { + fillInStackTrace(); + detailMessage = message; + } + + /** + * Constructs a new throwable with the specified detail message and + * cause.

Note that the detail message associated with + * {@code cause} is not automatically incorporated in + * this throwable's detail message. + * + *

The {@link #fillInStackTrace()} method is called to initialize + * the stack trace data in the newly created throwable. + * + * @param message the detail message (which is saved for later retrieval + * by the {@link #getMessage()} method). + * @param cause the cause (which is saved for later retrieval by the + * {@link #getCause()} method). (A {@code null} value is + * permitted, and indicates that the cause is nonexistent or + * unknown.) + * @since 1.4 + */ + public Throwable(String message, Throwable cause) { + fillInStackTrace(); + detailMessage = message; + this.cause = cause; + } + + /** + * Constructs a new throwable with the specified cause and a detail + * message of {@code (cause==null ? null : cause.toString())} (which + * typically contains the class and detail message of {@code cause}). + * This constructor is useful for throwables that are little more than + * wrappers for other throwables (for example, {@link + * java.security.PrivilegedActionException}). + * + *

The {@link #fillInStackTrace()} method is called to initialize + * the stack trace data in the newly created throwable. + * + * @param cause the cause (which is saved for later retrieval by the + * {@link #getCause()} method). (A {@code null} value is + * permitted, and indicates that the cause is nonexistent or + * unknown.) + * @since 1.4 + */ + public Throwable(Throwable cause) { + fillInStackTrace(); + detailMessage = (cause==null ? null : cause.toString()); + this.cause = cause; + } + + /** + * Constructs a new throwable with the specified detail message, + * cause, {@linkplain #addSuppressed suppression} enabled or + * disabled, and writable stack trace enabled or disabled. If + * suppression is disabled, {@link #getSuppressed} for this object + * will return a zero-length array and calls to {@link + * #addSuppressed} that would otherwise append an exception to the + * suppressed list will have no effect. If the writable stack + * trace is false, this constructor will not call {@link + * #fillInStackTrace()}, a {@code null} will be written to the + * {@code stackTrace} field, and subsequent calls to {@code + * fillInStackTrace} and {@link + * #setStackTrace(StackTraceElement[])} will not set the stack + * trace. If the writable stack trace is false, {@link + * #getStackTrace} will return a zero length array. + * + *

Note that the other constructors of {@code Throwable} treat + * suppression as being enabled and the stack trace as being + * writable. Subclasses of {@code Throwable} should document any + * conditions under which suppression is disabled and document + * conditions under which the stack trace is not writable. + * Disabling of suppression should only occur in exceptional + * circumstances where special requirements exist, such as a + * virtual machine reusing exception objects under low-memory + * situations. Circumstances where a given exception object is + * repeatedly caught and rethrown, such as to implement control + * flow between two sub-systems, is another situation where + * immutable throwable objects would be appropriate. + * + * @param message the detail message. + * @param cause the cause. (A {@code null} value is permitted, + * and indicates that the cause is nonexistent or unknown.) + * @param enableSuppression whether or not suppression is enabled or disabled + * @param writableStackTrace whether or not the stack trace should be + * writable + * + * @see OutOfMemoryError + * @see NullPointerException + * @see ArithmeticException + * @since 1.7 + */ + protected Throwable(String message, Throwable cause, + boolean enableSuppression, + boolean writableStackTrace) { + if (writableStackTrace) { + fillInStackTrace(); + } else { + stackTrace = null; + } + detailMessage = message; + this.cause = cause; +// if (!enableSuppression) +// suppressedExceptions = null; + } + + /** + * Returns the detail message string of this throwable. + * + * @return the detail message string of this {@code Throwable} instance + * (which may be {@code null}). + */ + public String getMessage() { + return detailMessage; + } + + /** + * Creates a localized description of this throwable. + * Subclasses may override this method in order to produce a + * locale-specific message. For subclasses that do not override this + * method, the default implementation returns the same result as + * {@code getMessage()}. + * + * @return The localized description of this throwable. + * @since JDK1.1 + */ + public String getLocalizedMessage() { + return getMessage(); + } + + /** + * Returns the cause of this throwable or {@code null} if the + * cause is nonexistent or unknown. (The cause is the throwable that + * caused this throwable to get thrown.) + * + *

This implementation returns the cause that was supplied via one of + * the constructors requiring a {@code Throwable}, or that was set after + * creation with the {@link #initCause(Throwable)} method. While it is + * typically unnecessary to override this method, a subclass can override + * it to return a cause set by some other means. This is appropriate for + * a "legacy chained throwable" that predates the addition of chained + * exceptions to {@code Throwable}. Note that it is not + * necessary to override any of the {@code PrintStackTrace} methods, + * all of which invoke the {@code getCause} method to determine the + * cause of a throwable. + * + * @return the cause of this throwable or {@code null} if the + * cause is nonexistent or unknown. + * @since 1.4 + */ + public synchronized Throwable getCause() { + return (cause==this ? null : cause); + } + + /** + * Initializes the cause of this throwable to the specified value. + * (The cause is the throwable that caused this throwable to get thrown.) + * + *

This method can be called at most once. It is generally called from + * within the constructor, or immediately after creating the + * throwable. If this throwable was created + * with {@link #Throwable(Throwable)} or + * {@link #Throwable(String,Throwable)}, this method cannot be called + * even once. + * + *

An example of using this method on a legacy throwable type + * without other support for setting the cause is: + * + *

+     * try {
+     *     lowLevelOp();
+     * } catch (LowLevelException le) {
+     *     throw (HighLevelException)
+     *           new HighLevelException().initCause(le); // Legacy constructor
+     * }
+     * 
+ * + * @param cause the cause (which is saved for later retrieval by the + * {@link #getCause()} method). (A {@code null} value is + * permitted, and indicates that the cause is nonexistent or + * unknown.) + * @return a reference to this {@code Throwable} instance. + * @throws IllegalArgumentException if {@code cause} is this + * throwable. (A throwable cannot be its own cause.) + * @throws IllegalStateException if this throwable was + * created with {@link #Throwable(Throwable)} or + * {@link #Throwable(String,Throwable)}, or this method has already + * been called on this throwable. + * @since 1.4 + */ + public synchronized Throwable initCause(Throwable cause) { + if (this.cause != this) + throw new IllegalStateException("Can't overwrite cause"); + if (cause == this) + throw new IllegalArgumentException("Self-causation not permitted"); + this.cause = cause; + return this; + } + + /** + * Returns a short description of this throwable. + * The result is the concatenation of: + *
    + *
  • the {@linkplain Class#getName() name} of the class of this object + *
  • ": " (a colon and a space) + *
  • the result of invoking this object's {@link #getLocalizedMessage} + * method + *
+ * If {@code getLocalizedMessage} returns {@code null}, then just + * the class name is returned. + * + * @return a string representation of this throwable. + */ + public String toString() { + String s = getClass().getName(); + String message = getLocalizedMessage(); + return (message != null) ? (s + ": " + message) : s; + } + + /** + * Prints this throwable and its backtrace to the + * standard error stream. This method prints a stack trace for this + * {@code Throwable} object on the error output stream that is + * the value of the field {@code System.err}. The first line of + * output contains the result of the {@link #toString()} method for + * this object. Remaining lines represent data previously recorded by + * the method {@link #fillInStackTrace()}. The format of this + * information depends on the implementation, but the following + * example may be regarded as typical: + *
+     * java.lang.NullPointerException
+     *         at MyClass.mash(MyClass.java:9)
+     *         at MyClass.crunch(MyClass.java:6)
+     *         at MyClass.main(MyClass.java:3)
+     * 
+ * This example was produced by running the program: + *
+     * class MyClass {
+     *     public static void main(String[] args) {
+     *         crunch(null);
+     *     }
+     *     static void crunch(int[] a) {
+     *         mash(a);
+     *     }
+     *     static void mash(int[] b) {
+     *         System.out.println(b[0]);
+     *     }
+     * }
+     * 
+ * The backtrace for a throwable with an initialized, non-null cause + * should generally include the backtrace for the cause. The format + * of this information depends on the implementation, but the following + * example may be regarded as typical: + *
+     * HighLevelException: MidLevelException: LowLevelException
+     *         at Junk.a(Junk.java:13)
+     *         at Junk.main(Junk.java:4)
+     * Caused by: MidLevelException: LowLevelException
+     *         at Junk.c(Junk.java:23)
+     *         at Junk.b(Junk.java:17)
+     *         at Junk.a(Junk.java:11)
+     *         ... 1 more
+     * Caused by: LowLevelException
+     *         at Junk.e(Junk.java:30)
+     *         at Junk.d(Junk.java:27)
+     *         at Junk.c(Junk.java:21)
+     *         ... 3 more
+     * 
+ * Note the presence of lines containing the characters {@code "..."}. + * These lines indicate that the remainder of the stack trace for this + * exception matches the indicated number of frames from the bottom of the + * stack trace of the exception that was caused by this exception (the + * "enclosing" exception). This shorthand can greatly reduce the length + * of the output in the common case where a wrapped exception is thrown + * from same method as the "causative exception" is caught. The above + * example was produced by running the program: + *
+     * public class Junk {
+     *     public static void main(String args[]) {
+     *         try {
+     *             a();
+     *         } catch(HighLevelException e) {
+     *             e.printStackTrace();
+     *         }
+     *     }
+     *     static void a() throws HighLevelException {
+     *         try {
+     *             b();
+     *         } catch(MidLevelException e) {
+     *             throw new HighLevelException(e);
+     *         }
+     *     }
+     *     static void b() throws MidLevelException {
+     *         c();
+     *     }
+     *     static void c() throws MidLevelException {
+     *         try {
+     *             d();
+     *         } catch(LowLevelException e) {
+     *             throw new MidLevelException(e);
+     *         }
+     *     }
+     *     static void d() throws LowLevelException {
+     *        e();
+     *     }
+     *     static void e() throws LowLevelException {
+     *         throw new LowLevelException();
+     *     }
+     * }
+     *
+     * class HighLevelException extends Exception {
+     *     HighLevelException(Throwable cause) { super(cause); }
+     * }
+     *
+     * class MidLevelException extends Exception {
+     *     MidLevelException(Throwable cause)  { super(cause); }
+     * }
+     *
+     * class LowLevelException extends Exception {
+     * }
+     * 
+ * As of release 7, the platform supports the notion of + * suppressed exceptions (in conjunction with the {@code + * try}-with-resources statement). Any exceptions that were + * suppressed in order to deliver an exception are printed out + * beneath the stack trace. The format of this information + * depends on the implementation, but the following example may be + * regarded as typical: + * + *
+     * Exception in thread "main" java.lang.Exception: Something happened
+     *  at Foo.bar(Foo.java:10)
+     *  at Foo.main(Foo.java:5)
+     *  Suppressed: Resource$CloseFailException: Resource ID = 0
+     *          at Resource.close(Resource.java:26)
+     *          at Foo.bar(Foo.java:9)
+     *          ... 1 more
+     * 
+ * Note that the "... n more" notation is used on suppressed exceptions + * just at it is used on causes. Unlike causes, suppressed exceptions are + * indented beyond their "containing exceptions." + * + *

An exception can have both a cause and one or more suppressed + * exceptions: + *

+     * Exception in thread "main" java.lang.Exception: Main block
+     *  at Foo3.main(Foo3.java:7)
+     *  Suppressed: Resource$CloseFailException: Resource ID = 2
+     *          at Resource.close(Resource.java:26)
+     *          at Foo3.main(Foo3.java:5)
+     *  Suppressed: Resource$CloseFailException: Resource ID = 1
+     *          at Resource.close(Resource.java:26)
+     *          at Foo3.main(Foo3.java:5)
+     * Caused by: java.lang.Exception: I did it
+     *  at Foo3.main(Foo3.java:8)
+     * 
+ * Likewise, a suppressed exception can have a cause: + *
+     * Exception in thread "main" java.lang.Exception: Main block
+     *  at Foo4.main(Foo4.java:6)
+     *  Suppressed: Resource2$CloseFailException: Resource ID = 1
+     *          at Resource2.close(Resource2.java:20)
+     *          at Foo4.main(Foo4.java:5)
+     *  Caused by: java.lang.Exception: Rats, you caught me
+     *          at Resource2$CloseFailException.(Resource2.java:45)
+     *          ... 2 more
+     * 
+ */ +// public void printStackTrace() { +// printStackTrace(System.err); +// } +// +// /** +// * Prints this throwable and its backtrace to the specified print stream. +// * +// * @param s {@code PrintStream} to use for output +// */ +// public void printStackTrace(PrintStream s) { +// printStackTrace(new WrappedPrintStream(s)); +// } +// +// private void printStackTrace(PrintStreamOrWriter s) { +// // Guard against malicious overrides of Throwable.equals by +// // using a Set with identity equality semantics. +//// Set dejaVu = +//// Collections.newSetFromMap(new IdentityHashMap()); +//// dejaVu.add(this); +// +// synchronized (s.lock()) { +// // Print our stack trace +// s.println(this); +// StackTraceElement[] trace = getOurStackTrace(); +// for (StackTraceElement traceElement : trace) +// s.println("\tat " + traceElement); +// +// // Print suppressed exceptions, if any +//// for (Throwable se : getSuppressed()) +//// se.printEnclosedStackTrace(s, trace, SUPPRESSED_CAPTION, "\t", dejaVu); +// +// // Print cause, if any +// Throwable ourCause = getCause(); +//// if (ourCause != null) +//// ourCause.printEnclosedStackTrace(s, trace, CAUSE_CAPTION, "", dejaVu); +// } +// } +// +// /** +// * Print our stack trace as an enclosed exception for the specified +// * stack trace. +// */ +// private void printEnclosedStackTrace(PrintStreamOrWriter s, +// StackTraceElement[] enclosingTrace, +// String caption, +// String prefix, +// Object dejaVu) { +// assert Thread.holdsLock(s.lock()); +// { +// // Compute number of frames in common between this and enclosing trace +// StackTraceElement[] trace = getOurStackTrace(); +// int m = trace.length - 1; +// int n = enclosingTrace.length - 1; +// while (m >= 0 && n >=0 && trace[m].equals(enclosingTrace[n])) { +// m--; n--; +// } +// int framesInCommon = trace.length - 1 - m; +// +// // Print our stack trace +// s.println(prefix + caption + this); +// for (int i = 0; i <= m; i++) +// s.println(prefix + "\tat " + trace[i]); +// if (framesInCommon != 0) +// s.println(prefix + "\t... " + framesInCommon + " more"); +// +// // Print suppressed exceptions, if any +// for (Throwable se : getSuppressed()) +// se.printEnclosedStackTrace(s, trace, SUPPRESSED_CAPTION, +// prefix +"\t", dejaVu); +// +// // Print cause, if any +// Throwable ourCause = getCause(); +// if (ourCause != null) +// ourCause.printEnclosedStackTrace(s, trace, CAUSE_CAPTION, prefix, dejaVu); +// } +// } +// +// /** +// * Prints this throwable and its backtrace to the specified +// * print writer. +// * +// * @param s {@code PrintWriter} to use for output +// * @since JDK1.1 +// */ +// public void printStackTrace(PrintWriter s) { +// printStackTrace(new WrappedPrintWriter(s)); +// } +// +// /** +// * Wrapper class for PrintStream and PrintWriter to enable a single +// * implementation of printStackTrace. +// */ +// private abstract static class PrintStreamOrWriter { +// /** Returns the object to be locked when using this StreamOrWriter */ +// abstract Object lock(); +// +// /** Prints the specified string as a line on this StreamOrWriter */ +// abstract void println(Object o); +// } +// +// private static class WrappedPrintStream extends PrintStreamOrWriter { +// private final PrintStream printStream; +// +// WrappedPrintStream(PrintStream printStream) { +// this.printStream = printStream; +// } +// +// Object lock() { +// return printStream; +// } +// +// void println(Object o) { +// printStream.println(o); +// } +// } +// +// private static class WrappedPrintWriter extends PrintStreamOrWriter { +// private final PrintWriter printWriter; +// +// WrappedPrintWriter(PrintWriter printWriter) { +// this.printWriter = printWriter; +// } +// +// Object lock() { +// return printWriter; +// } +// +// void println(Object o) { +// printWriter.println(o); +// } +// } + + /** + * Fills in the execution stack trace. This method records within this + * {@code Throwable} object information about the current state of + * the stack frames for the current thread. + * + *

If the stack trace of this {@code Throwable} {@linkplain + * Throwable#Throwable(String, Throwable, boolean, boolean) is not + * writable}, calling this method has no effect. + * + * @return a reference to this {@code Throwable} instance. + * @see java.lang.Throwable#printStackTrace() + */ + public synchronized Throwable fillInStackTrace() { + if (stackTrace != null || + backtrace != null /* Out of protocol state */ ) { + fillInStackTrace(0); + stackTrace = UNASSIGNED_STACK; + } + return this; + } + + @JavaScriptBody(args = { "dummy" }, body = "") + private native Throwable fillInStackTrace(int dummy); + + /** + * Provides programmatic access to the stack trace information printed by + * {@link #printStackTrace()}. Returns an array of stack trace elements, + * each representing one stack frame. The zeroth element of the array + * (assuming the array's length is non-zero) represents the top of the + * stack, which is the last method invocation in the sequence. Typically, + * this is the point at which this throwable was created and thrown. + * The last element of the array (assuming the array's length is non-zero) + * represents the bottom of the stack, which is the first method invocation + * in the sequence. + * + *

Some virtual machines may, under some circumstances, omit one + * or more stack frames from the stack trace. In the extreme case, + * a virtual machine that has no stack trace information concerning + * this throwable is permitted to return a zero-length array from this + * method. Generally speaking, the array returned by this method will + * contain one element for every frame that would be printed by + * {@code printStackTrace}. Writes to the returned array do not + * affect future calls to this method. + * + * @return an array of stack trace elements representing the stack trace + * pertaining to this throwable. + * @since 1.4 + */ + public StackTraceElement[] getStackTrace() { + return getOurStackTrace().clone(); + } + + private synchronized StackTraceElement[] getOurStackTrace() { + // Initialize stack trace field with information from + // backtrace if this is the first call to this method + if (stackTrace == UNASSIGNED_STACK || + (stackTrace == null && backtrace != null) /* Out of protocol state */) { + int depth = getStackTraceDepth(); + stackTrace = new StackTraceElement[depth]; + for (int i=0; i < depth; i++) + stackTrace[i] = getStackTraceElement(i); + } else if (stackTrace == null) { + return UNASSIGNED_STACK; + } + return stackTrace; + } + + /** + * Sets the stack trace elements that will be returned by + * {@link #getStackTrace()} and printed by {@link #printStackTrace()} + * and related methods. + * + * This method, which is designed for use by RPC frameworks and other + * advanced systems, allows the client to override the default + * stack trace that is either generated by {@link #fillInStackTrace()} + * when a throwable is constructed or deserialized when a throwable is + * read from a serialization stream. + * + *

If the stack trace of this {@code Throwable} {@linkplain + * Throwable#Throwable(String, Throwable, boolean, boolean) is not + * writable}, calling this method has no effect other than + * validating its argument. + * + * @param stackTrace the stack trace elements to be associated with + * this {@code Throwable}. The specified array is copied by this + * call; changes in the specified array after the method invocation + * returns will have no affect on this {@code Throwable}'s stack + * trace. + * + * @throws NullPointerException if {@code stackTrace} is + * {@code null} or if any of the elements of + * {@code stackTrace} are {@code null} + * + * @since 1.4 + */ + public void setStackTrace(StackTraceElement[] stackTrace) { + // Validate argument + StackTraceElement[] defensiveCopy = stackTrace.clone(); + for (int i = 0; i < defensiveCopy.length; i++) { + if (defensiveCopy[i] == null) + throw new NullPointerException("stackTrace[" + i + "]"); + } + + synchronized (this) { + if (this.stackTrace == null && // Immutable stack + backtrace == null) // Test for out of protocol state + return; + this.stackTrace = defensiveCopy; + } + } + + /** + * Returns the number of elements in the stack trace (or 0 if the stack + * trace is unavailable). + * + * package-protection for use by SharedSecrets. + */ + native int getStackTraceDepth(); + + /** + * Returns the specified element of the stack trace. + * + * package-protection for use by SharedSecrets. + * + * @param index index of the element to return. + * @throws IndexOutOfBoundsException if {@code index < 0 || + * index >= getStackTraceDepth() } + */ + native StackTraceElement getStackTraceElement(int index); + + /** + * Reads a {@code Throwable} from a stream, enforcing + * well-formedness constraints on fields. Null entries and + * self-pointers are not allowed in the list of {@code + * suppressedExceptions}. Null entries are not allowed for stack + * trace elements. A null stack trace in the serial form results + * in a zero-length stack element array. A single-element stack + * trace whose entry is equal to {@code new StackTraceElement("", + * "", null, Integer.MIN_VALUE)} results in a {@code null} {@code + * stackTrace} field. + * + * Note that there are no constraints on the value the {@code + * cause} field can hold; both {@code null} and {@code this} are + * valid values for the field. + */ +// private void readObject(ObjectInputStream s) +// throws IOException, ClassNotFoundException { +// s.defaultReadObject(); // read in all fields +// if (suppressedExceptions != null) { +// List suppressed = null; +// if (suppressedExceptions.isEmpty()) { +// // Use the sentinel for a zero-length list +// suppressed = SUPPRESSED_SENTINEL; +// } else { // Copy Throwables to new list +// suppressed = new ArrayList(1); +// for (Throwable t : suppressedExceptions) { +// // Enforce constraints on suppressed exceptions in +// // case of corrupt or malicious stream. +// if (t == null) +// throw new NullPointerException(NULL_CAUSE_MESSAGE); +// if (t == this) +// throw new IllegalArgumentException(SELF_SUPPRESSION_MESSAGE); +// suppressed.add(t); +// } +// } +// suppressedExceptions = suppressed; +// } // else a null suppressedExceptions field remains null +// +// /* +// * For zero-length stack traces, use a clone of +// * UNASSIGNED_STACK rather than UNASSIGNED_STACK itself to +// * allow identity comparison against UNASSIGNED_STACK in +// * getOurStackTrace. The identity of UNASSIGNED_STACK in +// * stackTrace indicates to the getOurStackTrace method that +// * the stackTrace needs to be constructed from the information +// * in backtrace. +// */ +// if (stackTrace != null) { +// if (stackTrace.length == 0) { +// stackTrace = UNASSIGNED_STACK.clone(); +// } else if (stackTrace.length == 1 && +// // Check for the marker of an immutable stack trace +// SentinelHolder.STACK_TRACE_ELEMENT_SENTINEL.equals(stackTrace[0])) { +// stackTrace = null; +// } else { // Verify stack trace elements are non-null. +// for(StackTraceElement ste : stackTrace) { +// if (ste == null) +// throw new NullPointerException("null StackTraceElement in serial stream. "); +// } +// } +// } else { +// // A null stackTrace field in the serial form can result +// // from an exception serialized without that field in +// // older JDK releases; treat such exceptions as having +// // empty stack traces. +// stackTrace = UNASSIGNED_STACK.clone(); +// } +// } + + /** + * Write a {@code Throwable} object to a stream. + * + * A {@code null} stack trace field is represented in the serial + * form as a one-element array whose element is equal to {@code + * new StackTraceElement("", "", null, Integer.MIN_VALUE)}. + */ +// private synchronized void writeObject(ObjectOutputStream s) +// throws IOException { +// // Ensure that the stackTrace field is initialized to a +// // non-null value, if appropriate. As of JDK 7, a null stack +// // trace field is a valid value indicating the stack trace +// // should not be set. +// getOurStackTrace(); +// +// StackTraceElement[] oldStackTrace = stackTrace; +// try { +// if (stackTrace == null) +// stackTrace = SentinelHolder.STACK_TRACE_SENTINEL; +// s.defaultWriteObject(); +// } finally { +// stackTrace = oldStackTrace; +// } +// } + + /** + * Appends the specified exception to the exceptions that were + * suppressed in order to deliver this exception. This method is + * thread-safe and typically called (automatically and implicitly) + * by the {@code try}-with-resources statement. + * + *

The suppression behavior is enabled unless disabled + * {@linkplain #Throwable(String, Throwable, boolean, boolean) via + * a constructor}. When suppression is disabled, this method does + * nothing other than to validate its argument. + * + *

Note that when one exception {@linkplain + * #initCause(Throwable) causes} another exception, the first + * exception is usually caught and then the second exception is + * thrown in response. In other words, there is a causal + * connection between the two exceptions. + * + * In contrast, there are situations where two independent + * exceptions can be thrown in sibling code blocks, in particular + * in the {@code try} block of a {@code try}-with-resources + * statement and the compiler-generated {@code finally} block + * which closes the resource. + * + * In these situations, only one of the thrown exceptions can be + * propagated. In the {@code try}-with-resources statement, when + * there are two such exceptions, the exception originating from + * the {@code try} block is propagated and the exception from the + * {@code finally} block is added to the list of exceptions + * suppressed by the exception from the {@code try} block. As an + * exception unwinds the stack, it can accumulate multiple + * suppressed exceptions. + * + *

An exception may have suppressed exceptions while also being + * caused by another exception. Whether or not an exception has a + * cause is semantically known at the time of its creation, unlike + * whether or not an exception will suppress other exceptions + * which is typically only determined after an exception is + * thrown. + * + *

Note that programmer written code is also able to take + * advantage of calling this method in situations where there are + * multiple sibling exceptions and only one can be propagated. + * + * @param exception the exception to be added to the list of + * suppressed exceptions + * @throws IllegalArgumentException if {@code exception} is this + * throwable; a throwable cannot suppress itself. + * @throws NullPointerException if {@code exception} is {@code null} + * @since 1.7 + */ + public final synchronized void addSuppressed(Throwable exception) { + if (exception == this) + throw new IllegalArgumentException(SELF_SUPPRESSION_MESSAGE); + + if (exception == null) + throw new NullPointerException(NULL_CAUSE_MESSAGE); + +// if (suppressedExceptions == null) // Suppressed exceptions not recorded +// return; +// +// if (suppressedExceptions == SUPPRESSED_SENTINEL) +// suppressedExceptions = new ArrayList(1); +// +// suppressedExceptions.add(exception); + } + + private static final Throwable[] EMPTY_THROWABLE_ARRAY = new Throwable[0]; + + /** + * Returns an array containing all of the exceptions that were + * suppressed, typically by the {@code try}-with-resources + * statement, in order to deliver this exception. + * + * If no exceptions were suppressed or {@linkplain + * #Throwable(String, Throwable, boolean, boolean) suppression is + * disabled}, an empty array is returned. This method is + * thread-safe. Writes to the returned array do not affect future + * calls to this method. + * + * @return an array containing all of the exceptions that were + * suppressed to deliver this exception. + * @since 1.7 + */ + public final synchronized Throwable[] getSuppressed() { + return new Throwable[0]; +// if (suppressedExceptions == SUPPRESSED_SENTINEL || +// suppressedExceptions == null) +// return EMPTY_THROWABLE_ARRAY; +// else +// return suppressedExceptions.toArray(EMPTY_THROWABLE_ARRAY); + } +} diff -r 388e48c0a37a -r 05224402145d emul/mini/src/main/java/java/lang/VirtualMachineError.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/emul/mini/src/main/java/java/lang/VirtualMachineError.java Wed Jan 23 20:39:23 2013 +0100 @@ -0,0 +1,54 @@ +/* + * Copyright (c) 1995, 1997, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code 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 + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package java.lang; + +/** + * Thrown to indicate that the Java Virtual Machine is broken or has + * run out of resources necessary for it to continue operating. + * + * + * @author Frank Yellin + * @since JDK1.0 + */ +abstract public +class VirtualMachineError extends Error { + /** + * Constructs a VirtualMachineError with no detail message. + */ + public VirtualMachineError() { + super(); + } + + /** + * Constructs a VirtualMachineError with the specified + * detail message. + * + * @param s the detail message. + */ + public VirtualMachineError(String s) { + super(s); + } +} diff -r 388e48c0a37a -r 05224402145d emul/mini/src/main/java/java/lang/Void.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/emul/mini/src/main/java/java/lang/Void.java Wed Jan 23 20:39:23 2013 +0100 @@ -0,0 +1,49 @@ +/* + * Copyright (c) 1996, 2006, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code 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 + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package java.lang; + +/** + * The {@code Void} class is an uninstantiable placeholder class to hold a + * reference to the {@code Class} object representing the Java keyword + * void. + * + * @author unascribed + * @since JDK1.1 + */ +public final +class Void { + + /** + * The {@code Class} object representing the pseudo-type corresponding to + * the keyword {@code void}. + */ + public static final Class TYPE = Class.getPrimitiveClass("void"); + + /* + * The Void class cannot be instantiated. + */ + private Void() {} +} diff -r 388e48c0a37a -r 05224402145d emul/mini/src/main/java/java/lang/annotation/Annotation.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/emul/mini/src/main/java/java/lang/annotation/Annotation.java Wed Jan 23 20:39:23 2013 +0100 @@ -0,0 +1,131 @@ +/* + * Copyright (c) 2003, 2009, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code 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 + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package java.lang.annotation; + +/** + * The common interface extended by all annotation types. Note that an + * interface that manually extends this one does not define + * an annotation type. Also note that this interface does not itself + * define an annotation type. + * + * More information about annotation types can be found in section 9.6 of + * The Java™ Language Specification. + * + * @author Josh Bloch + * @since 1.5 + */ +public interface Annotation { + /** + * Returns true if the specified object represents an annotation + * that is logically equivalent to this one. In other words, + * returns true if the specified object is an instance of the same + * annotation type as this instance, all of whose members are equal + * to the corresponding member of this annotation, as defined below: + *

    + *
  • Two corresponding primitive typed members whose values are + * x and y are considered equal if x == y, + * unless their type is float or double. + * + *
  • Two corresponding float members whose values + * are x and y are considered equal if + * Float.valueOf(x).equals(Float.valueOf(y)). + * (Unlike the == operator, NaN is considered equal + * to itself, and 0.0f unequal to -0.0f.) + * + *
  • Two corresponding double members whose values + * are x and y are considered equal if + * Double.valueOf(x).equals(Double.valueOf(y)). + * (Unlike the == operator, NaN is considered equal + * to itself, and 0.0 unequal to -0.0.) + * + *
  • Two corresponding String, Class, enum, or + * annotation typed members whose values are x and y + * are considered equal if x.equals(y). (Note that this + * definition is recursive for annotation typed members.) + * + *
  • Two corresponding array typed members x and y + * are considered equal if Arrays.equals(x, y), for the + * appropriate overloading of {@link java.util.Arrays#equals}. + *
+ * + * @return true if the specified object represents an annotation + * that is logically equivalent to this one, otherwise false + */ + boolean equals(Object obj); + + /** + * Returns the hash code of this annotation, as defined below: + * + *

The hash code of an annotation is the sum of the hash codes + * of its members (including those with default values), as defined + * below: + * + * The hash code of an annotation member is (127 times the hash code + * of the member-name as computed by {@link String#hashCode()}) XOR + * the hash code of the member-value, as defined below: + * + *

The hash code of a member-value depends on its type: + *

    + *
  • The hash code of a primitive value v is equal to + * WrapperType.valueOf(v).hashCode(), where + * WrapperType is the wrapper type corresponding + * to the primitive type of v ({@link Byte}, + * {@link Character}, {@link Double}, {@link Float}, {@link Integer}, + * {@link Long}, {@link Short}, or {@link Boolean}). + * + *
  • The hash code of a string, enum, class, or annotation member-value + I v is computed as by calling + * v.hashCode(). (In the case of annotation + * member values, this is a recursive definition.) + * + *
  • The hash code of an array member-value is computed by calling + * the appropriate overloading of + * {@link java.util.Arrays#hashCode(long[]) Arrays.hashCode} + * on the value. (There is one overloading for each primitive + * type, and one for object reference types.) + *
+ * + * @return the hash code of this annotation + */ + int hashCode(); + + /** + * Returns a string representation of this annotation. The details + * of the representation are implementation-dependent, but the following + * may be regarded as typical: + *
+     *   @com.acme.util.Name(first=Alfred, middle=E., last=Neuman)
+     * 
+ * + * @return a string representation of this annotation + */ + String toString(); + + /** + * Returns the annotation type of this annotation. + */ + Class annotationType(); +} diff -r 388e48c0a37a -r 05224402145d emul/mini/src/main/java/java/lang/annotation/Documented.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/emul/mini/src/main/java/java/lang/annotation/Documented.java Wed Jan 23 20:39:23 2013 +0100 @@ -0,0 +1,43 @@ +/* + * Copyright (c) 2003, 2004, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code 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 + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package java.lang.annotation; + +/** + * Indicates that annotations with a type are to be documented by javadoc + * and similar tools by default. This type should be used to annotate the + * declarations of types whose annotations affect the use of annotated + * elements by their clients. If a type declaration is annotated with + * Documented, its annotations become part of the public API + * of the annotated elements. + * + * @author Joshua Bloch + * @since 1.5 + */ +@Documented +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.ANNOTATION_TYPE) +public @interface Documented { +} diff -r 388e48c0a37a -r 05224402145d emul/mini/src/main/java/java/lang/annotation/ElementType.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/emul/mini/src/main/java/java/lang/annotation/ElementType.java Wed Jan 23 20:39:23 2013 +0100 @@ -0,0 +1,63 @@ +/* + * Copyright (c) 2003, 2011, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code 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 + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package java.lang.annotation; + +/** + * A program element type. The constants of this enumerated type + * provide a simple classification of the declared elements in a + * Java program. + * + *

These constants are used with the {@link Target} meta-annotation type + * to specify where it is legal to use an annotation type. + * + * @author Joshua Bloch + * @since 1.5 + */ +public enum ElementType { + /** Class, interface (including annotation type), or enum declaration */ + TYPE, + + /** Field declaration (includes enum constants) */ + FIELD, + + /** Method declaration */ + METHOD, + + /** Parameter declaration */ + PARAMETER, + + /** Constructor declaration */ + CONSTRUCTOR, + + /** Local variable declaration */ + LOCAL_VARIABLE, + + /** Annotation type declaration */ + ANNOTATION_TYPE, + + /** Package declaration */ + PACKAGE +} diff -r 388e48c0a37a -r 05224402145d emul/mini/src/main/java/java/lang/annotation/Retention.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/emul/mini/src/main/java/java/lang/annotation/Retention.java Wed Jan 23 20:39:23 2013 +0100 @@ -0,0 +1,47 @@ +/* + * Copyright (c) 2003, 2006, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code 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 + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package java.lang.annotation; + +/** + * Indicates how long annotations with the annotated type are to + * be retained. If no Retention annotation is present on + * an annotation type declaration, the retention policy defaults to + * {@code RetentionPolicy.CLASS}. + * + *

A Retention meta-annotation has effect only if the + * meta-annotated type is used directly for annotation. It has no + * effect if the meta-annotated type is used as a member type in + * another annotation type. + * + * @author Joshua Bloch + * @since 1.5 + */ +@Documented +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.ANNOTATION_TYPE) +public @interface Retention { + RetentionPolicy value(); +} diff -r 388e48c0a37a -r 05224402145d emul/mini/src/main/java/java/lang/annotation/RetentionPolicy.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/emul/mini/src/main/java/java/lang/annotation/RetentionPolicy.java Wed Jan 23 20:39:23 2013 +0100 @@ -0,0 +1,57 @@ +/* + * Copyright (c) 2003, 2004, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code 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 + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package java.lang.annotation; + +/** + * Annotation retention policy. The constants of this enumerated type + * describe the various policies for retaining annotations. They are used + * in conjunction with the {@link Retention} meta-annotation type to specify + * how long annotations are to be retained. + * + * @author Joshua Bloch + * @since 1.5 + */ +public enum RetentionPolicy { + /** + * Annotations are to be discarded by the compiler. + */ + SOURCE, + + /** + * Annotations are to be recorded in the class file by the compiler + * but need not be retained by the VM at run time. This is the default + * behavior. + */ + CLASS, + + /** + * Annotations are to be recorded in the class file by the compiler and + * retained by the VM at run time, so they may be read reflectively. + * + * @see java.lang.reflect.AnnotatedElement + */ + RUNTIME +} diff -r 388e48c0a37a -r 05224402145d emul/mini/src/main/java/java/lang/annotation/Target.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/emul/mini/src/main/java/java/lang/annotation/Target.java Wed Jan 23 20:39:23 2013 +0100 @@ -0,0 +1,68 @@ +/* + * Copyright (c) 2003, 2004, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code 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 + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package java.lang.annotation; + +/** + * Indicates the kinds of program element to which an annotation type + * is applicable. If a Target meta-annotation is not present on an + * annotation type declaration, the declared type may be used on any + * program element. If such a meta-annotation is present, the compiler + * will enforce the specified usage restriction. + * + * For example, this meta-annotation indicates that the declared type is + * itself a meta-annotation type. It can only be used on annotation type + * declarations: + *

+ *    @Target(ElementType.ANNOTATION_TYPE)
+ *    public @interface MetaAnnotationType {
+ *        ...
+ *    }
+ * 
+ * This meta-annotation indicates that the declared type is intended solely + * for use as a member type in complex annotation type declarations. It + * cannot be used to annotate anything directly: + *
+ *    @Target({})
+ *    public @interface MemberType {
+ *        ...
+ *    }
+ * 
+ * It is a compile-time error for a single ElementType constant to + * appear more than once in a Target annotation. For example, the + * following meta-annotation is illegal: + *
+ *    @Target({ElementType.FIELD, ElementType.METHOD, ElementType.FIELD})
+ *    public @interface Bogus {
+ *        ...
+ *    }
+ * 
+ */ +@Documented +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.ANNOTATION_TYPE) +public @interface Target { + ElementType[] value(); +} diff -r 388e48c0a37a -r 05224402145d emul/mini/src/main/java/java/lang/annotation/UnsupportedOperationException.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/emul/mini/src/main/java/java/lang/annotation/UnsupportedOperationException.java Wed Jan 23 20:39:23 2013 +0100 @@ -0,0 +1,94 @@ +/* + * Copyright (c) 1997, 2006, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code 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 + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package java.lang; + +/** + * Thrown to indicate that the requested operation is not supported.

+ * + * This class is a member of the + * + * Java Collections Framework. + * + * @author Josh Bloch + * @since 1.2 + */ +public class UnsupportedOperationException extends RuntimeException { + /** + * Constructs an UnsupportedOperationException with no detail message. + */ + public UnsupportedOperationException() { + } + + /** + * Constructs an UnsupportedOperationException with the specified + * detail message. + * + * @param message the detail message + */ + public UnsupportedOperationException(String message) { + super(message); + } + + /** + * Constructs a new exception with the specified detail message and + * cause. + * + *

Note that the detail message associated with cause is + * not automatically incorporated in this exception's detail + * message. + * + * @param message the detail message (which is saved for later retrieval + * by the {@link Throwable#getMessage()} method). + * @param cause the cause (which is saved for later retrieval by the + * {@link Throwable#getCause()} method). (A null value + * is permitted, and indicates that the cause is nonexistent or + * unknown.) + * @since 1.5 + */ + public UnsupportedOperationException(String message, Throwable cause) { + super(message, cause); + } + + /** + * Constructs a new exception with the specified cause and a detail + * message of (cause==null ? null : cause.toString()) (which + * typically contains the class and detail message of cause). + * This constructor is useful for exceptions that are little more than + * wrappers for other throwables (for example, {@link + * java.security.PrivilegedActionException}). + * + * @param cause the cause (which is saved for later retrieval by the + * {@link Throwable#getCause()} method). (A null value is + * permitted, and indicates that the cause is nonexistent or + * unknown.) + * @since 1.5 + */ + public UnsupportedOperationException(Throwable cause) { + super(cause); + } + + static final long serialVersionUID = -1242599979055084673L; +} diff -r 388e48c0a37a -r 05224402145d emul/mini/src/main/java/java/lang/reflect/AccessibleObject.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/emul/mini/src/main/java/java/lang/reflect/AccessibleObject.java Wed Jan 23 20:39:23 2013 +0100 @@ -0,0 +1,167 @@ +/* + * Copyright (c) 1997, 2008, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code 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 + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package java.lang.reflect; + +import java.lang.annotation.Annotation; + +/** + * The AccessibleObject class is the base class for Field, Method and + * Constructor objects. It provides the ability to flag a reflected + * object as suppressing default Java language access control checks + * when it is used. The access checks--for public, default (package) + * access, protected, and private members--are performed when Fields, + * Methods or Constructors are used to set or get fields, to invoke + * methods, or to create and initialize new instances of classes, + * respectively. + * + *

Setting the {@code accessible} flag in a reflected object + * permits sophisticated applications with sufficient privilege, such + * as Java Object Serialization or other persistence mechanisms, to + * manipulate objects in a manner that would normally be prohibited. + * + *

By default, a reflected object is not accessible. + * + * @see Field + * @see Method + * @see Constructor + * @see ReflectPermission + * + * @since 1.2 + */ +public class AccessibleObject implements AnnotatedElement { + + /** + * Convenience method to set the {@code accessible} flag for an + * array of objects with a single security check (for efficiency). + * + *

First, if there is a security manager, its + * {@code checkPermission} method is called with a + * {@code ReflectPermission("suppressAccessChecks")} permission. + * + *

A {@code SecurityException} is raised if {@code flag} is + * {@code true} but accessibility of any of the elements of the input + * {@code array} may not be changed (for example, if the element + * object is a {@link Constructor} object for the class {@link + * java.lang.Class}). In the event of such a SecurityException, the + * accessibility of objects is set to {@code flag} for array elements + * upto (and excluding) the element for which the exception occurred; the + * accessibility of elements beyond (and including) the element for which + * the exception occurred is unchanged. + * + * @param array the array of AccessibleObjects + * @param flag the new value for the {@code accessible} flag + * in each object + * @throws SecurityException if the request is denied. + * @see SecurityManager#checkPermission + * @see java.lang.RuntimePermission + */ + public static void setAccessible(AccessibleObject[] array, boolean flag) + throws SecurityException { + throw new SecurityException(); + } + + /** + * Set the {@code accessible} flag for this object to + * the indicated boolean value. A value of {@code true} indicates that + * the reflected object should suppress Java language access + * checking when it is used. A value of {@code false} indicates + * that the reflected object should enforce Java language access checks. + * + *

First, if there is a security manager, its + * {@code checkPermission} method is called with a + * {@code ReflectPermission("suppressAccessChecks")} permission. + * + *

A {@code SecurityException} is raised if {@code flag} is + * {@code true} but accessibility of this object may not be changed + * (for example, if this element object is a {@link Constructor} object for + * the class {@link java.lang.Class}). + * + *

A {@code SecurityException} is raised if this object is a {@link + * java.lang.reflect.Constructor} object for the class + * {@code java.lang.Class}, and {@code flag} is true. + * + * @param flag the new value for the {@code accessible} flag + * @throws SecurityException if the request is denied. + * @see SecurityManager#checkPermission + * @see java.lang.RuntimePermission + */ + public void setAccessible(boolean flag) throws SecurityException { + throw new SecurityException(); + } + + /** + * Get the value of the {@code accessible} flag for this object. + * + * @return the value of the object's {@code accessible} flag + */ + public boolean isAccessible() { + return override; + } + + /** + * Constructor: only used by the Java Virtual Machine. + */ + protected AccessibleObject() {} + + // Indicates whether language-level access checks are overridden + // by this object. Initializes to "false". This field is used by + // Field, Method, and Constructor. + // + // NOTE: for security purposes, this field must not be visible + // outside this package. + boolean override; + + /** + * @throws NullPointerException {@inheritDoc} + * @since 1.5 + */ + public T getAnnotation(Class annotationClass) { + throw new AssertionError("All subclasses should override this method"); + } + + /** + * @throws NullPointerException {@inheritDoc} + * @since 1.5 + */ + public boolean isAnnotationPresent( + Class annotationClass) { + return getAnnotation(annotationClass) != null; + } + + /** + * @since 1.5 + */ + public Annotation[] getAnnotations() { + return getDeclaredAnnotations(); + } + + /** + * @since 1.5 + */ + public Annotation[] getDeclaredAnnotations() { + throw new AssertionError("All subclasses should override this method"); + } +} diff -r 388e48c0a37a -r 05224402145d emul/mini/src/main/java/java/lang/reflect/AnnotatedElement.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/emul/mini/src/main/java/java/lang/reflect/AnnotatedElement.java Wed Jan 23 20:39:23 2013 +0100 @@ -0,0 +1,112 @@ +/* + * Copyright (c) 2003, 2005, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code 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 + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package java.lang.reflect; + +import java.lang.annotation.Annotation; + +/** + * Represents an annotated element of the program currently running in this + * VM. This interface allows annotations to be read reflectively. All + * annotations returned by methods in this interface are immutable and + * serializable. It is permissible for the caller to modify the + * arrays returned by accessors for array-valued enum members; it will + * have no affect on the arrays returned to other callers. + * + *

If an annotation returned by a method in this interface contains + * (directly or indirectly) a {@link Class}-valued member referring to + * a class that is not accessible in this VM, attempting to read the class + * by calling the relevant Class-returning method on the returned annotation + * will result in a {@link TypeNotPresentException}. + * + *

Similarly, attempting to read an enum-valued member will result in + * a {@link EnumConstantNotPresentException} if the enum constant in the + * annotation is no longer present in the enum type. + * + *

Finally, Attempting to read a member whose definition has evolved + * incompatibly will result in a {@link + * java.lang.annotation.AnnotationTypeMismatchException} or an + * {@link java.lang.annotation.IncompleteAnnotationException}. + * + * @see java.lang.EnumConstantNotPresentException + * @see java.lang.TypeNotPresentException + * @see java.lang.annotation.AnnotationFormatError + * @see java.lang.annotation.AnnotationTypeMismatchException + * @see java.lang.annotation.IncompleteAnnotationException + * @since 1.5 + * @author Josh Bloch + */ +public interface AnnotatedElement { + /** + * Returns true if an annotation for the specified type + * is present on this element, else false. This method + * is designed primarily for convenient access to marker annotations. + * + * @param annotationClass the Class object corresponding to the + * annotation type + * @return true if an annotation for the specified annotation + * type is present on this element, else false + * @throws NullPointerException if the given annotation class is null + * @since 1.5 + */ + boolean isAnnotationPresent(Class annotationClass); + + /** + * Returns this element's annotation for the specified type if + * such an annotation is present, else null. + * + * @param annotationClass the Class object corresponding to the + * annotation type + * @return this element's annotation for the specified annotation type if + * present on this element, else null + * @throws NullPointerException if the given annotation class is null + * @since 1.5 + */ + T getAnnotation(Class annotationClass); + + /** + * Returns all annotations present on this element. (Returns an array + * of length zero if this element has no annotations.) The caller of + * this method is free to modify the returned array; it will have no + * effect on the arrays returned to other callers. + * + * @return all annotations present on this element + * @since 1.5 + */ + Annotation[] getAnnotations(); + + /** + * Returns all annotations that are directly present on this + * element. Unlike the other methods in this interface, this method + * ignores inherited annotations. (Returns an array of length zero if + * no annotations are directly present on this element.) The caller of + * this method is free to modify the returned array; it will have no + * effect on the arrays returned to other callers. + * + * @return All annotations directly present on this element + * @since 1.5 + */ + Annotation[] getDeclaredAnnotations(); +} diff -r 388e48c0a37a -r 05224402145d emul/mini/src/main/java/java/lang/reflect/Array.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/emul/mini/src/main/java/java/lang/reflect/Array.java Wed Jan 23 20:39:23 2013 +0100 @@ -0,0 +1,659 @@ +/* + * Copyright (c) 1996, 2006, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code 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 + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package java.lang.reflect; + +import org.apidesign.bck2brwsr.core.JavaScriptBody; +import org.apidesign.bck2brwsr.core.JavaScriptPrototype; + +/** + * The {@code Array} class provides static methods to dynamically create and + * access Java arrays. + * + *

{@code Array} permits widening conversions to occur during a get or set + * operation, but throws an {@code IllegalArgumentException} if a narrowing + * conversion would occur. + * + * @author Nakul Saraiya + */ +@JavaScriptPrototype(prototype = "new Array", container = "Array.prototype") +public final +class Array { + + /** + * Constructor. Class Array is not instantiable. + */ + private Array() {} + + /** + * Creates a new array with the specified component type and + * length. + * Invoking this method is equivalent to creating an array + * as follows: + *

+ *
+     * int[] x = {length};
+     * Array.newInstance(componentType, x);
+     * 
+ *
+ * + * @param componentType the {@code Class} object representing the + * component type of the new array + * @param length the length of the new array + * @return the new array + * @exception NullPointerException if the specified + * {@code componentType} parameter is null + * @exception IllegalArgumentException if componentType is {@link Void#TYPE} + * @exception NegativeArraySizeException if the specified {@code length} + * is negative + */ + public static Object newInstance(Class componentType, int length) + throws NegativeArraySizeException { + if (length < 0) { + throw new NegativeArraySizeException(); + } + String sig = findSignature(componentType); + return newArray(componentType.isPrimitive(), sig, length); + } + + private static String findSignature(Class type) { + if (type == Integer.TYPE) { + return "[I"; + } + if (type == Long.TYPE) { + return "[J"; + } + if (type == Double.TYPE) { + return "[D"; + } + if (type == Float.TYPE) { + return "[F"; + } + if (type == Byte.TYPE) { + return "[B"; + } + if (type == Boolean.TYPE) { + return "[Z"; + } + if (type == Short.TYPE) { + return "[S"; + } + if (type == Character.TYPE) { + return "[C"; + } + if (type.getName().equals("void")) { + throw new IllegalStateException("Can't create array for " + type); + } + return "[L" + type.getName() + ";"; + } + /** + * Creates a new array + * with the specified component type and dimensions. + * If {@code componentType} + * represents a non-array class or interface, the new array + * has {@code dimensions.length} dimensions and + * {@code componentType} as its component type. If + * {@code componentType} represents an array class, the + * number of dimensions of the new array is equal to the sum + * of {@code dimensions.length} and the number of + * dimensions of {@code componentType}. In this case, the + * component type of the new array is the component type of + * {@code componentType}. + * + *

The number of dimensions of the new array must not + * exceed the number of array dimensions supported by the + * implementation (typically 255). + * + * @param componentType the {@code Class} object representing the component + * type of the new array + * @param dimensions an array of {@code int} representing the dimensions of + * the new array + * @return the new array + * @exception NullPointerException if the specified + * {@code componentType} argument is null + * @exception IllegalArgumentException if the specified {@code dimensions} + * argument is a zero-dimensional array, or if the number of + * requested dimensions exceeds the limit on the number of array dimensions + * supported by the implementation (typically 255), or if componentType + * is {@link Void#TYPE}. + * @exception NegativeArraySizeException if any of the components in + * the specified {@code dimensions} argument is negative. + */ + public static Object newInstance(Class componentType, int... dimensions) + throws IllegalArgumentException, NegativeArraySizeException { + StringBuilder sig = new StringBuilder(); + for (int i = 1; i < dimensions.length; i++) { + sig.append('['); + } + sig.append(findSignature(componentType)); + return multiNewArray(sig.toString(), dimensions, 0); + } + + /** + * Returns the length of the specified array object, as an {@code int}. + * + * @param array the array + * @return the length of the array + * @exception IllegalArgumentException if the object argument is not + * an array + */ + public static int getLength(Object array) + throws IllegalArgumentException { + if (!array.getClass().isArray()) { + throw new IllegalArgumentException("Argument is not an array"); + } + return length(array); + } + + @JavaScriptBody(args = { "arr" }, body = "return arr.length;") + private static native int length(Object arr); + + /** + * Returns the value of the indexed component in the specified + * array object. The value is automatically wrapped in an object + * if it has a primitive type. + * + * @param array the array + * @param index the index + * @return the (possibly wrapped) value of the indexed component in + * the specified array + * @exception NullPointerException If the specified object is null + * @exception IllegalArgumentException If the specified object is not + * an array + * @exception ArrayIndexOutOfBoundsException If the specified {@code index} + * argument is negative, or if it is greater than or equal to the + * length of the specified array + */ + public static Object get(Object array, int index) + throws IllegalArgumentException, ArrayIndexOutOfBoundsException { + final Class t = array.getClass().getComponentType(); + if (t.isPrimitive()) { + return Array.fromPrimitive(t, array, index); + } else { + return ((Object[])array)[index]; + } + } + + /** + * Returns the value of the indexed component in the specified + * array object, as a {@code boolean}. + * + * @param array the array + * @param index the index + * @return the value of the indexed component in the specified array + * @exception NullPointerException If the specified object is null + * @exception IllegalArgumentException If the specified object is not + * an array, or if the indexed element cannot be converted to the + * return type by an identity or widening conversion + * @exception ArrayIndexOutOfBoundsException If the specified {@code index} + * argument is negative, or if it is greater than or equal to the + * length of the specified array + * @see Array#get + */ + public static native boolean getBoolean(Object array, int index) + throws IllegalArgumentException, ArrayIndexOutOfBoundsException; + + /** + * Returns the value of the indexed component in the specified + * array object, as a {@code byte}. + * + * @param array the array + * @param index the index + * @return the value of the indexed component in the specified array + * @exception NullPointerException If the specified object is null + * @exception IllegalArgumentException If the specified object is not + * an array, or if the indexed element cannot be converted to the + * return type by an identity or widening conversion + * @exception ArrayIndexOutOfBoundsException If the specified {@code index} + * argument is negative, or if it is greater than or equal to the + * length of the specified array + * @see Array#get + */ + public static byte getByte(Object array, int index) + throws IllegalArgumentException, ArrayIndexOutOfBoundsException { + if (array.getClass().getComponentType() != Byte.TYPE) { + throw new IllegalArgumentException(); + } + byte[] arr = (byte[]) array; + return arr[index]; + } + + /** + * Returns the value of the indexed component in the specified + * array object, as a {@code char}. + * + * @param array the array + * @param index the index + * @return the value of the indexed component in the specified array + * @exception NullPointerException If the specified object is null + * @exception IllegalArgumentException If the specified object is not + * an array, or if the indexed element cannot be converted to the + * return type by an identity or widening conversion + * @exception ArrayIndexOutOfBoundsException If the specified {@code index} + * argument is negative, or if it is greater than or equal to the + * length of the specified array + * @see Array#get + */ + public static native char getChar(Object array, int index) + throws IllegalArgumentException, ArrayIndexOutOfBoundsException; + + /** + * Returns the value of the indexed component in the specified + * array object, as a {@code short}. + * + * @param array the array + * @param index the index + * @return the value of the indexed component in the specified array + * @exception NullPointerException If the specified object is null + * @exception IllegalArgumentException If the specified object is not + * an array, or if the indexed element cannot be converted to the + * return type by an identity or widening conversion + * @exception ArrayIndexOutOfBoundsException If the specified {@code index} + * argument is negative, or if it is greater than or equal to the + * length of the specified array + * @see Array#get + */ + public static short getShort(Object array, int index) + throws IllegalArgumentException, ArrayIndexOutOfBoundsException { + final Class t = array.getClass().getComponentType(); + if (t == Short.TYPE) { + short[] arr = (short[]) array; + return arr[index]; + } + return getByte(array, index); + } + + /** + * Returns the value of the indexed component in the specified + * array object, as an {@code int}. + * + * @param array the array + * @param index the index + * @return the value of the indexed component in the specified array + * @exception NullPointerException If the specified object is null + * @exception IllegalArgumentException If the specified object is not + * an array, or if the indexed element cannot be converted to the + * return type by an identity or widening conversion + * @exception ArrayIndexOutOfBoundsException If the specified {@code index} + * argument is negative, or if it is greater than or equal to the + * length of the specified array + * @see Array#get + */ + public static int getInt(Object array, int index) + throws IllegalArgumentException, ArrayIndexOutOfBoundsException { + final Class t = array.getClass().getComponentType(); + if (t == Integer.TYPE) { + int[] arr = (int[]) array; + return arr[index]; + } + return getShort(array, index); + } + + /** + * Returns the value of the indexed component in the specified + * array object, as a {@code long}. + * + * @param array the array + * @param index the index + * @return the value of the indexed component in the specified array + * @exception NullPointerException If the specified object is null + * @exception IllegalArgumentException If the specified object is not + * an array, or if the indexed element cannot be converted to the + * return type by an identity or widening conversion + * @exception ArrayIndexOutOfBoundsException If the specified {@code index} + * argument is negative, or if it is greater than or equal to the + * length of the specified array + * @see Array#get + */ + public static long getLong(Object array, int index) + throws IllegalArgumentException, ArrayIndexOutOfBoundsException { + final Class t = array.getClass().getComponentType(); + if (t == Long.TYPE) { + long[] arr = (long[]) array; + return arr[index]; + } + return getInt(array, index); + } + + /** + * Returns the value of the indexed component in the specified + * array object, as a {@code float}. + * + * @param array the array + * @param index the index + * @return the value of the indexed component in the specified array + * @exception NullPointerException If the specified object is null + * @exception IllegalArgumentException If the specified object is not + * an array, or if the indexed element cannot be converted to the + * return type by an identity or widening conversion + * @exception ArrayIndexOutOfBoundsException If the specified {@code index} + * argument is negative, or if it is greater than or equal to the + * length of the specified array + * @see Array#get + */ + public static float getFloat(Object array, int index) + throws IllegalArgumentException, ArrayIndexOutOfBoundsException { + final Class t = array.getClass().getComponentType(); + if (t == Float.TYPE) { + float[] arr = (float[]) array; + return arr[index]; + } + return getLong(array, index); + } + + /** + * Returns the value of the indexed component in the specified + * array object, as a {@code double}. + * + * @param array the array + * @param index the index + * @return the value of the indexed component in the specified array + * @exception NullPointerException If the specified object is null + * @exception IllegalArgumentException If the specified object is not + * an array, or if the indexed element cannot be converted to the + * return type by an identity or widening conversion + * @exception ArrayIndexOutOfBoundsException If the specified {@code index} + * argument is negative, or if it is greater than or equal to the + * length of the specified array + * @see Array#get + */ + public static double getDouble(Object array, int index) + throws IllegalArgumentException, ArrayIndexOutOfBoundsException { + final Class t = array.getClass().getComponentType(); + if (t == Double.TYPE) { + double[] arr = (double[]) array; + return arr[index]; + } + return getFloat(array, index); + } + + /** + * Sets the value of the indexed component of the specified array + * object to the specified new value. The new value is first + * automatically unwrapped if the array has a primitive component + * type. + * @param array the array + * @param index the index into the array + * @param value the new value of the indexed component + * @exception NullPointerException If the specified object argument + * is null + * @exception IllegalArgumentException If the specified object argument + * is not an array, or if the array component type is primitive and + * an unwrapping conversion fails + * @exception ArrayIndexOutOfBoundsException If the specified {@code index} + * argument is negative, or if it is greater than or equal to + * the length of the specified array + */ + public static void set(Object array, int index, Object value) + throws IllegalArgumentException, ArrayIndexOutOfBoundsException { + if (array.getClass().getComponentType().isPrimitive()) { + throw new IllegalArgumentException(); + } else { + Object[] arr = (Object[])array; + arr[index] = value; + } + } + + /** + * Sets the value of the indexed component of the specified array + * object to the specified {@code boolean} value. + * @param array the array + * @param index the index into the array + * @param z the new value of the indexed component + * @exception NullPointerException If the specified object argument + * is null + * @exception IllegalArgumentException If the specified object argument + * is not an array, or if the specified value cannot be converted + * to the underlying array's component type by an identity or a + * primitive widening conversion + * @exception ArrayIndexOutOfBoundsException If the specified {@code index} + * argument is negative, or if it is greater than or equal to + * the length of the specified array + * @see Array#set + */ + public static native void setBoolean(Object array, int index, boolean z) + throws IllegalArgumentException, ArrayIndexOutOfBoundsException; + + /** + * Sets the value of the indexed component of the specified array + * object to the specified {@code byte} value. + * @param array the array + * @param index the index into the array + * @param b the new value of the indexed component + * @exception NullPointerException If the specified object argument + * is null + * @exception IllegalArgumentException If the specified object argument + * is not an array, or if the specified value cannot be converted + * to the underlying array's component type by an identity or a + * primitive widening conversion + * @exception ArrayIndexOutOfBoundsException If the specified {@code index} + * argument is negative, or if it is greater than or equal to + * the length of the specified array + * @see Array#set + */ + public static void setByte(Object array, int index, byte b) + throws IllegalArgumentException, ArrayIndexOutOfBoundsException { + Class t = array.getClass().getComponentType(); + if (t == Byte.TYPE) { + byte[] arr = (byte[]) array; + arr[index] = b; + } else { + setShort(array, index, b); + } + } + + /** + * Sets the value of the indexed component of the specified array + * object to the specified {@code char} value. + * @param array the array + * @param index the index into the array + * @param c the new value of the indexed component + * @exception NullPointerException If the specified object argument + * is null + * @exception IllegalArgumentException If the specified object argument + * is not an array, or if the specified value cannot be converted + * to the underlying array's component type by an identity or a + * primitive widening conversion + * @exception ArrayIndexOutOfBoundsException If the specified {@code index} + * argument is negative, or if it is greater than or equal to + * the length of the specified array + * @see Array#set + */ + public static native void setChar(Object array, int index, char c) + throws IllegalArgumentException, ArrayIndexOutOfBoundsException; + + /** + * Sets the value of the indexed component of the specified array + * object to the specified {@code short} value. + * @param array the array + * @param index the index into the array + * @param s the new value of the indexed component + * @exception NullPointerException If the specified object argument + * is null + * @exception IllegalArgumentException If the specified object argument + * is not an array, or if the specified value cannot be converted + * to the underlying array's component type by an identity or a + * primitive widening conversion + * @exception ArrayIndexOutOfBoundsException If the specified {@code index} + * argument is negative, or if it is greater than or equal to + * the length of the specified array + * @see Array#set + */ + public static void setShort(Object array, int index, short s) + throws IllegalArgumentException, ArrayIndexOutOfBoundsException { + Class t = array.getClass().getComponentType(); + if (t == Short.TYPE) { + short[] arr = (short[]) array; + arr[index] = s; + } else { + setInt(array, index, s); + } + + } + + /** + * Sets the value of the indexed component of the specified array + * object to the specified {@code int} value. + * @param array the array + * @param index the index into the array + * @param i the new value of the indexed component + * @exception NullPointerException If the specified object argument + * is null + * @exception IllegalArgumentException If the specified object argument + * is not an array, or if the specified value cannot be converted + * to the underlying array's component type by an identity or a + * primitive widening conversion + * @exception ArrayIndexOutOfBoundsException If the specified {@code index} + * argument is negative, or if it is greater than or equal to + * the length of the specified array + * @see Array#set + */ + public static void setInt(Object array, int index, int i) + throws IllegalArgumentException, ArrayIndexOutOfBoundsException { + Class t = array.getClass().getComponentType(); + if (t == Integer.TYPE) { + long[] arr = (long[]) array; + arr[index] = i; + } else { + setLong(array, index, i); + } + } + + /** + * Sets the value of the indexed component of the specified array + * object to the specified {@code long} value. + * @param array the array + * @param index the index into the array + * @param l the new value of the indexed component + * @exception NullPointerException If the specified object argument + * is null + * @exception IllegalArgumentException If the specified object argument + * is not an array, or if the specified value cannot be converted + * to the underlying array's component type by an identity or a + * primitive widening conversion + * @exception ArrayIndexOutOfBoundsException If the specified {@code index} + * argument is negative, or if it is greater than or equal to + * the length of the specified array + * @see Array#set + */ + public static void setLong(Object array, int index, long l) + throws IllegalArgumentException, ArrayIndexOutOfBoundsException { + Class t = array.getClass().getComponentType(); + if (t == Long.TYPE) { + long[] arr = (long[]) array; + arr[index] = l; + } else { + setFloat(array, index, l); + } + } + + /** + * Sets the value of the indexed component of the specified array + * object to the specified {@code float} value. + * @param array the array + * @param index the index into the array + * @param f the new value of the indexed component + * @exception NullPointerException If the specified object argument + * is null + * @exception IllegalArgumentException If the specified object argument + * is not an array, or if the specified value cannot be converted + * to the underlying array's component type by an identity or a + * primitive widening conversion + * @exception ArrayIndexOutOfBoundsException If the specified {@code index} + * argument is negative, or if it is greater than or equal to + * the length of the specified array + * @see Array#set + */ + public static void setFloat(Object array, int index, float f) + throws IllegalArgumentException, ArrayIndexOutOfBoundsException { + Class t = array.getClass().getComponentType(); + if (t == Float.TYPE) { + float[] arr = (float[])array; + arr[index] = f; + } else { + setDouble(array, index, f); + } + } + + /** + * Sets the value of the indexed component of the specified array + * object to the specified {@code double} value. + * @param array the array + * @param index the index into the array + * @param d the new value of the indexed component + * @exception NullPointerException If the specified object argument + * is null + * @exception IllegalArgumentException If the specified object argument + * is not an array, or if the specified value cannot be converted + * to the underlying array's component type by an identity or a + * primitive widening conversion + * @exception ArrayIndexOutOfBoundsException If the specified {@code index} + * argument is negative, or if it is greater than or equal to + * the length of the specified array + * @see Array#set + */ + public static void setDouble(Object array, int index, double d) + throws IllegalArgumentException, ArrayIndexOutOfBoundsException { + Class t = array.getClass().getComponentType(); + if (t == Double.TYPE) { + double[] arr = (double[])array; + arr[index] = d; + } else { + throw new IllegalArgumentException("argument type mismatch"); + } + } + + /* + * Private + */ + + @JavaScriptBody(args = { "primitive", "sig", "length" }, body = + "var arr = new Array(length);\n" + + "var value = primitive ? 0 : null;\n" + + "for(var i = 0; i < length; i++) arr[i] = value;\n" + + "arr.jvmName = sig;\n" + + "return arr;" + ) + private static native Object newArray(boolean primitive, String sig, int length); + + private static Object multiNewArray(String sig, int[] dims, int index) + throws IllegalArgumentException, NegativeArraySizeException { + if (dims.length == index + 1) { + return newArray(sig.length() == 2, sig, dims[index]); + } + Object[] arr = (Object[]) newArray(false, sig, dims[index]); + String compsig = sig.substring(1); + for (int i = 0; i < arr.length; i++) { + arr[i] = multiNewArray(compsig, dims, index + 1); + } + return arr; + } + private static Object fromPrimitive(Class t, Object array, int index) { + return Method.fromPrimitive(t, atArray(array, index)); + } + + @JavaScriptBody(args = { "array", "index" }, body = "return array[index]") + private static native Object atArray(Object array, int index); +} diff -r 388e48c0a37a -r 05224402145d emul/mini/src/main/java/java/lang/reflect/Field.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/emul/mini/src/main/java/java/lang/reflect/Field.java Wed Jan 23 20:39:23 2013 +0100 @@ -0,0 +1,953 @@ +/* + * Copyright (c) 1996, 2006, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code 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 + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package java.lang.reflect; + +import java.lang.annotation.Annotation; + + +/** + * A {@code Field} provides information about, and dynamic access to, a + * single field of a class or an interface. The reflected field may + * be a class (static) field or an instance field. + * + *

A {@code Field} permits widening conversions to occur during a get or + * set access operation, but throws an {@code IllegalArgumentException} if a + * narrowing conversion would occur. + * + * @see Member + * @see java.lang.Class + * @see java.lang.Class#getFields() + * @see java.lang.Class#getField(String) + * @see java.lang.Class#getDeclaredFields() + * @see java.lang.Class#getDeclaredField(String) + * + * @author Kenneth Russell + * @author Nakul Saraiya + */ +public final +class Field extends AccessibleObject implements Member { + + private Class clazz; + private int slot; + // This is guaranteed to be interned by the VM in the 1.4 + // reflection implementation + private String name; + private Class type; + private int modifiers; + // Generics and annotations support + private transient String signature; + private byte[] annotations; + // For sharing of FieldAccessors. This branching structure is + // currently only two levels deep (i.e., one root Field and + // potentially many Field objects pointing to it.) + private Field root; + + // Generics infrastructure + + private String getGenericSignature() {return signature;} + + + /** + * Package-private constructor used by ReflectAccess to enable + * instantiation of these objects in Java code from the java.lang + * package via sun.reflect.LangReflectAccess. + */ + Field(Class declaringClass, + String name, + Class type, + int modifiers, + int slot, + String signature, + byte[] annotations) + { + this.clazz = declaringClass; + this.name = name; + this.type = type; + this.modifiers = modifiers; + this.slot = slot; + this.signature = signature; + this.annotations = annotations; + } + + /** + * Package-private routine (exposed to java.lang.Class via + * ReflectAccess) which returns a copy of this Field. The copy's + * "root" field points to this Field. + */ + Field copy() { + // This routine enables sharing of FieldAccessor objects + // among Field objects which refer to the same underlying + // method in the VM. (All of this contortion is only necessary + // because of the "accessibility" bit in AccessibleObject, + // which implicitly requires that new java.lang.reflect + // objects be fabricated for each reflective call on Class + // objects.) + Field res = new Field(clazz, name, type, modifiers, slot, signature, annotations); + res.root = this; + return res; + } + + /** + * Returns the {@code Class} object representing the class or interface + * that declares the field represented by this {@code Field} object. + */ + public Class getDeclaringClass() { + return clazz; + } + + /** + * Returns the name of the field represented by this {@code Field} object. + */ + public String getName() { + return name; + } + + /** + * Returns the Java language modifiers for the field represented + * by this {@code Field} object, as an integer. The {@code Modifier} class should + * be used to decode the modifiers. + * + * @see Modifier + */ + public int getModifiers() { + return modifiers; + } + + /** + * Returns {@code true} if this field represents an element of + * an enumerated type; returns {@code false} otherwise. + * + * @return {@code true} if and only if this field represents an element of + * an enumerated type. + * @since 1.5 + */ + public boolean isEnumConstant() { + return (getModifiers() & Modifier.ENUM) != 0; + } + + /** + * Returns {@code true} if this field is a synthetic + * field; returns {@code false} otherwise. + * + * @return true if and only if this field is a synthetic + * field as defined by the Java Language Specification. + * @since 1.5 + */ + public boolean isSynthetic() { + return Modifier.isSynthetic(getModifiers()); + } + + /** + * Returns a {@code Class} object that identifies the + * declared type for the field represented by this + * {@code Field} object. + * + * @return a {@code Class} object identifying the declared + * type of the field represented by this object + */ + public Class getType() { + return type; + } + + /** + * Returns a {@code Type} object that represents the declared type for + * the field represented by this {@code Field} object. + * + *

If the {@code Type} is a parameterized type, the + * {@code Type} object returned must accurately reflect the + * actual type parameters used in the source code. + * + *

If the type of the underlying field is a type variable or a + * parameterized type, it is created. Otherwise, it is resolved. + * + * @return a {@code Type} object that represents the declared type for + * the field represented by this {@code Field} object + * @throws GenericSignatureFormatError if the generic field + * signature does not conform to the format specified in + * The Java™ Virtual Machine Specification + * @throws TypeNotPresentException if the generic type + * signature of the underlying field refers to a non-existent + * type declaration + * @throws MalformedParameterizedTypeException if the generic + * signature of the underlying field refers to a parameterized type + * that cannot be instantiated for any reason + * @since 1.5 + */ + public Type getGenericType() { + throw new UnsupportedOperationException(); + } + + + /** + * Compares this {@code Field} against the specified object. Returns + * true if the objects are the same. Two {@code Field} objects are the same if + * they were declared by the same class and have the same name + * and type. + */ + public boolean equals(Object obj) { + if (obj != null && obj instanceof Field) { + Field other = (Field)obj; + return (getDeclaringClass() == other.getDeclaringClass()) + && (getName() == other.getName()) + && (getType() == other.getType()); + } + return false; + } + + /** + * Returns a hashcode for this {@code Field}. This is computed as the + * exclusive-or of the hashcodes for the underlying field's + * declaring class name and its name. + */ + public int hashCode() { + return getDeclaringClass().getName().hashCode() ^ getName().hashCode(); + } + + /** + * Returns a string describing this {@code Field}. The format is + * the access modifiers for the field, if any, followed + * by the field type, followed by a space, followed by + * the fully-qualified name of the class declaring the field, + * followed by a period, followed by the name of the field. + * For example: + *

+     *    public static final int java.lang.Thread.MIN_PRIORITY
+     *    private int java.io.FileDescriptor.fd
+     * 
+ * + *

The modifiers are placed in canonical order as specified by + * "The Java Language Specification". This is {@code public}, + * {@code protected} or {@code private} first, and then other + * modifiers in the following order: {@code static}, {@code final}, + * {@code transient}, {@code volatile}. + */ + public String toString() { + int mod = getModifiers(); + return (((mod == 0) ? "" : (Modifier.toString(mod) + " ")) + + getTypeName(getType()) + " " + + getTypeName(getDeclaringClass()) + "." + + getName()); + } + + /** + * Returns a string describing this {@code Field}, including + * its generic type. The format is the access modifiers for the + * field, if any, followed by the generic field type, followed by + * a space, followed by the fully-qualified name of the class + * declaring the field, followed by a period, followed by the name + * of the field. + * + *

The modifiers are placed in canonical order as specified by + * "The Java Language Specification". This is {@code public}, + * {@code protected} or {@code private} first, and then other + * modifiers in the following order: {@code static}, {@code final}, + * {@code transient}, {@code volatile}. + * + * @return a string describing this {@code Field}, including + * its generic type + * + * @since 1.5 + */ + public String toGenericString() { + int mod = getModifiers(); + Type fieldType = getGenericType(); + return (((mod == 0) ? "" : (Modifier.toString(mod) + " ")) + + ((fieldType instanceof Class) ? + getTypeName((Class)fieldType): fieldType.toString())+ " " + + getTypeName(getDeclaringClass()) + "." + + getName()); + } + + /** + * Returns the value of the field represented by this {@code Field}, on + * the specified object. The value is automatically wrapped in an + * object if it has a primitive type. + * + *

The underlying field's value is obtained as follows: + * + *

If the underlying field is a static field, the {@code obj} argument + * is ignored; it may be null. + * + *

Otherwise, the underlying field is an instance field. If the + * specified {@code obj} argument is null, the method throws a + * {@code NullPointerException}. If the specified object is not an + * instance of the class or interface declaring the underlying + * field, the method throws an {@code IllegalArgumentException}. + * + *

If this {@code Field} object is enforcing Java language access control, and + * the underlying field is inaccessible, the method throws an + * {@code IllegalAccessException}. + * If the underlying field is static, the class that declared the + * field is initialized if it has not already been initialized. + * + *

Otherwise, the value is retrieved from the underlying instance + * or static field. If the field has a primitive type, the value + * is wrapped in an object before being returned, otherwise it is + * returned as is. + * + *

If the field is hidden in the type of {@code obj}, + * the field's value is obtained according to the preceding rules. + * + * @param obj object from which the represented field's value is + * to be extracted + * @return the value of the represented field in object + * {@code obj}; primitive values are wrapped in an appropriate + * object before being returned + * + * @exception IllegalAccessException if this {@code Field} object + * is enforcing Java language access control and the underlying + * field is inaccessible. + * @exception IllegalArgumentException if the specified object is not an + * instance of the class or interface declaring the underlying + * field (or a subclass or implementor thereof). + * @exception NullPointerException if the specified object is null + * and the field is an instance field. + * @exception ExceptionInInitializerError if the initialization provoked + * by this method fails. + */ + public Object get(Object obj) + throws IllegalArgumentException, IllegalAccessException + { + return getFieldAccessor(obj).get(obj); + } + + /** + * Gets the value of a static or instance {@code boolean} field. + * + * @param obj the object to extract the {@code boolean} value + * from + * @return the value of the {@code boolean} field + * + * @exception IllegalAccessException if this {@code Field} object + * is enforcing Java language access control and the underlying + * field is inaccessible. + * @exception IllegalArgumentException if the specified object is not + * an instance of the class or interface declaring the + * underlying field (or a subclass or implementor + * thereof), or if the field value cannot be + * converted to the type {@code boolean} by a + * widening conversion. + * @exception NullPointerException if the specified object is null + * and the field is an instance field. + * @exception ExceptionInInitializerError if the initialization provoked + * by this method fails. + * @see Field#get + */ + public boolean getBoolean(Object obj) + throws IllegalArgumentException, IllegalAccessException + { + return getFieldAccessor(obj).getBoolean(obj); + } + + /** + * Gets the value of a static or instance {@code byte} field. + * + * @param obj the object to extract the {@code byte} value + * from + * @return the value of the {@code byte} field + * + * @exception IllegalAccessException if this {@code Field} object + * is enforcing Java language access control and the underlying + * field is inaccessible. + * @exception IllegalArgumentException if the specified object is not + * an instance of the class or interface declaring the + * underlying field (or a subclass or implementor + * thereof), or if the field value cannot be + * converted to the type {@code byte} by a + * widening conversion. + * @exception NullPointerException if the specified object is null + * and the field is an instance field. + * @exception ExceptionInInitializerError if the initialization provoked + * by this method fails. + * @see Field#get + */ + public byte getByte(Object obj) + throws IllegalArgumentException, IllegalAccessException + { + return getFieldAccessor(obj).getByte(obj); + } + + /** + * Gets the value of a static or instance field of type + * {@code char} or of another primitive type convertible to + * type {@code char} via a widening conversion. + * + * @param obj the object to extract the {@code char} value + * from + * @return the value of the field converted to type {@code char} + * + * @exception IllegalAccessException if this {@code Field} object + * is enforcing Java language access control and the underlying + * field is inaccessible. + * @exception IllegalArgumentException if the specified object is not + * an instance of the class or interface declaring the + * underlying field (or a subclass or implementor + * thereof), or if the field value cannot be + * converted to the type {@code char} by a + * widening conversion. + * @exception NullPointerException if the specified object is null + * and the field is an instance field. + * @exception ExceptionInInitializerError if the initialization provoked + * by this method fails. + * @see Field#get + */ + public char getChar(Object obj) + throws IllegalArgumentException, IllegalAccessException + { + return getFieldAccessor(obj).getChar(obj); + } + + /** + * Gets the value of a static or instance field of type + * {@code short} or of another primitive type convertible to + * type {@code short} via a widening conversion. + * + * @param obj the object to extract the {@code short} value + * from + * @return the value of the field converted to type {@code short} + * + * @exception IllegalAccessException if this {@code Field} object + * is enforcing Java language access control and the underlying + * field is inaccessible. + * @exception IllegalArgumentException if the specified object is not + * an instance of the class or interface declaring the + * underlying field (or a subclass or implementor + * thereof), or if the field value cannot be + * converted to the type {@code short} by a + * widening conversion. + * @exception NullPointerException if the specified object is null + * and the field is an instance field. + * @exception ExceptionInInitializerError if the initialization provoked + * by this method fails. + * @see Field#get + */ + public short getShort(Object obj) + throws IllegalArgumentException, IllegalAccessException + { + return getFieldAccessor(obj).getShort(obj); + } + + /** + * Gets the value of a static or instance field of type + * {@code int} or of another primitive type convertible to + * type {@code int} via a widening conversion. + * + * @param obj the object to extract the {@code int} value + * from + * @return the value of the field converted to type {@code int} + * + * @exception IllegalAccessException if this {@code Field} object + * is enforcing Java language access control and the underlying + * field is inaccessible. + * @exception IllegalArgumentException if the specified object is not + * an instance of the class or interface declaring the + * underlying field (or a subclass or implementor + * thereof), or if the field value cannot be + * converted to the type {@code int} by a + * widening conversion. + * @exception NullPointerException if the specified object is null + * and the field is an instance field. + * @exception ExceptionInInitializerError if the initialization provoked + * by this method fails. + * @see Field#get + */ + public int getInt(Object obj) + throws IllegalArgumentException, IllegalAccessException + { + return getFieldAccessor(obj).getInt(obj); + } + + /** + * Gets the value of a static or instance field of type + * {@code long} or of another primitive type convertible to + * type {@code long} via a widening conversion. + * + * @param obj the object to extract the {@code long} value + * from + * @return the value of the field converted to type {@code long} + * + * @exception IllegalAccessException if this {@code Field} object + * is enforcing Java language access control and the underlying + * field is inaccessible. + * @exception IllegalArgumentException if the specified object is not + * an instance of the class or interface declaring the + * underlying field (or a subclass or implementor + * thereof), or if the field value cannot be + * converted to the type {@code long} by a + * widening conversion. + * @exception NullPointerException if the specified object is null + * and the field is an instance field. + * @exception ExceptionInInitializerError if the initialization provoked + * by this method fails. + * @see Field#get + */ + public long getLong(Object obj) + throws IllegalArgumentException, IllegalAccessException + { + return getFieldAccessor(obj).getLong(obj); + } + + /** + * Gets the value of a static or instance field of type + * {@code float} or of another primitive type convertible to + * type {@code float} via a widening conversion. + * + * @param obj the object to extract the {@code float} value + * from + * @return the value of the field converted to type {@code float} + * + * @exception IllegalAccessException if this {@code Field} object + * is enforcing Java language access control and the underlying + * field is inaccessible. + * @exception IllegalArgumentException if the specified object is not + * an instance of the class or interface declaring the + * underlying field (or a subclass or implementor + * thereof), or if the field value cannot be + * converted to the type {@code float} by a + * widening conversion. + * @exception NullPointerException if the specified object is null + * and the field is an instance field. + * @exception ExceptionInInitializerError if the initialization provoked + * by this method fails. + * @see Field#get + */ + public float getFloat(Object obj) + throws IllegalArgumentException, IllegalAccessException + { + return getFieldAccessor(obj).getFloat(obj); + } + + /** + * Gets the value of a static or instance field of type + * {@code double} or of another primitive type convertible to + * type {@code double} via a widening conversion. + * + * @param obj the object to extract the {@code double} value + * from + * @return the value of the field converted to type {@code double} + * + * @exception IllegalAccessException if this {@code Field} object + * is enforcing Java language access control and the underlying + * field is inaccessible. + * @exception IllegalArgumentException if the specified object is not + * an instance of the class or interface declaring the + * underlying field (or a subclass or implementor + * thereof), or if the field value cannot be + * converted to the type {@code double} by a + * widening conversion. + * @exception NullPointerException if the specified object is null + * and the field is an instance field. + * @exception ExceptionInInitializerError if the initialization provoked + * by this method fails. + * @see Field#get + */ + public double getDouble(Object obj) + throws IllegalArgumentException, IllegalAccessException + { + return getFieldAccessor(obj).getDouble(obj); + } + + /** + * Sets the field represented by this {@code Field} object on the + * specified object argument to the specified new value. The new + * value is automatically unwrapped if the underlying field has a + * primitive type. + * + *

The operation proceeds as follows: + * + *

If the underlying field is static, the {@code obj} argument is + * ignored; it may be null. + * + *

Otherwise the underlying field is an instance field. If the + * specified object argument is null, the method throws a + * {@code NullPointerException}. If the specified object argument is not + * an instance of the class or interface declaring the underlying + * field, the method throws an {@code IllegalArgumentException}. + * + *

If this {@code Field} object is enforcing Java language access control, and + * the underlying field is inaccessible, the method throws an + * {@code IllegalAccessException}. + * + *

If the underlying field is final, the method throws an + * {@code IllegalAccessException} unless {@code setAccessible(true)} + * has succeeded for this {@code Field} object + * and the field is non-static. Setting a final field in this way + * is meaningful only during deserialization or reconstruction of + * instances of classes with blank final fields, before they are + * made available for access by other parts of a program. Use in + * any other context may have unpredictable effects, including cases + * in which other parts of a program continue to use the original + * value of this field. + * + *

If the underlying field is of a primitive type, an unwrapping + * conversion is attempted to convert the new value to a value of + * a primitive type. If this attempt fails, the method throws an + * {@code IllegalArgumentException}. + * + *

If, after possible unwrapping, the new value cannot be + * converted to the type of the underlying field by an identity or + * widening conversion, the method throws an + * {@code IllegalArgumentException}. + * + *

If the underlying field is static, the class that declared the + * field is initialized if it has not already been initialized. + * + *

The field is set to the possibly unwrapped and widened new value. + * + *

If the field is hidden in the type of {@code obj}, + * the field's value is set according to the preceding rules. + * + * @param obj the object whose field should be modified + * @param value the new value for the field of {@code obj} + * being modified + * + * @exception IllegalAccessException if this {@code Field} object + * is enforcing Java language access control and the underlying + * field is either inaccessible or final. + * @exception IllegalArgumentException if the specified object is not an + * instance of the class or interface declaring the underlying + * field (or a subclass or implementor thereof), + * or if an unwrapping conversion fails. + * @exception NullPointerException if the specified object is null + * and the field is an instance field. + * @exception ExceptionInInitializerError if the initialization provoked + * by this method fails. + */ + public void set(Object obj, Object value) + throws IllegalArgumentException, IllegalAccessException + { + getFieldAccessor(obj).set(obj, value); + } + + /** + * Sets the value of a field as a {@code boolean} on the specified object. + * This method is equivalent to + * {@code set(obj, zObj)}, + * where {@code zObj} is a {@code Boolean} object and + * {@code zObj.booleanValue() == z}. + * + * @param obj the object whose field should be modified + * @param z the new value for the field of {@code obj} + * being modified + * + * @exception IllegalAccessException if this {@code Field} object + * is enforcing Java language access control and the underlying + * field is either inaccessible or final. + * @exception IllegalArgumentException if the specified object is not an + * instance of the class or interface declaring the underlying + * field (or a subclass or implementor thereof), + * or if an unwrapping conversion fails. + * @exception NullPointerException if the specified object is null + * and the field is an instance field. + * @exception ExceptionInInitializerError if the initialization provoked + * by this method fails. + * @see Field#set + */ + public void setBoolean(Object obj, boolean z) + throws IllegalArgumentException, IllegalAccessException + { + getFieldAccessor(obj).setBoolean(obj, z); + } + + /** + * Sets the value of a field as a {@code byte} on the specified object. + * This method is equivalent to + * {@code set(obj, bObj)}, + * where {@code bObj} is a {@code Byte} object and + * {@code bObj.byteValue() == b}. + * + * @param obj the object whose field should be modified + * @param b the new value for the field of {@code obj} + * being modified + * + * @exception IllegalAccessException if this {@code Field} object + * is enforcing Java language access control and the underlying + * field is either inaccessible or final. + * @exception IllegalArgumentException if the specified object is not an + * instance of the class or interface declaring the underlying + * field (or a subclass or implementor thereof), + * or if an unwrapping conversion fails. + * @exception NullPointerException if the specified object is null + * and the field is an instance field. + * @exception ExceptionInInitializerError if the initialization provoked + * by this method fails. + * @see Field#set + */ + public void setByte(Object obj, byte b) + throws IllegalArgumentException, IllegalAccessException + { + getFieldAccessor(obj).setByte(obj, b); + } + + /** + * Sets the value of a field as a {@code char} on the specified object. + * This method is equivalent to + * {@code set(obj, cObj)}, + * where {@code cObj} is a {@code Character} object and + * {@code cObj.charValue() == c}. + * + * @param obj the object whose field should be modified + * @param c the new value for the field of {@code obj} + * being modified + * + * @exception IllegalAccessException if this {@code Field} object + * is enforcing Java language access control and the underlying + * field is either inaccessible or final. + * @exception IllegalArgumentException if the specified object is not an + * instance of the class or interface declaring the underlying + * field (or a subclass or implementor thereof), + * or if an unwrapping conversion fails. + * @exception NullPointerException if the specified object is null + * and the field is an instance field. + * @exception ExceptionInInitializerError if the initialization provoked + * by this method fails. + * @see Field#set + */ + public void setChar(Object obj, char c) + throws IllegalArgumentException, IllegalAccessException + { + getFieldAccessor(obj).setChar(obj, c); + } + + /** + * Sets the value of a field as a {@code short} on the specified object. + * This method is equivalent to + * {@code set(obj, sObj)}, + * where {@code sObj} is a {@code Short} object and + * {@code sObj.shortValue() == s}. + * + * @param obj the object whose field should be modified + * @param s the new value for the field of {@code obj} + * being modified + * + * @exception IllegalAccessException if this {@code Field} object + * is enforcing Java language access control and the underlying + * field is either inaccessible or final. + * @exception IllegalArgumentException if the specified object is not an + * instance of the class or interface declaring the underlying + * field (or a subclass or implementor thereof), + * or if an unwrapping conversion fails. + * @exception NullPointerException if the specified object is null + * and the field is an instance field. + * @exception ExceptionInInitializerError if the initialization provoked + * by this method fails. + * @see Field#set + */ + public void setShort(Object obj, short s) + throws IllegalArgumentException, IllegalAccessException + { + getFieldAccessor(obj).setShort(obj, s); + } + + /** + * Sets the value of a field as an {@code int} on the specified object. + * This method is equivalent to + * {@code set(obj, iObj)}, + * where {@code iObj} is a {@code Integer} object and + * {@code iObj.intValue() == i}. + * + * @param obj the object whose field should be modified + * @param i the new value for the field of {@code obj} + * being modified + * + * @exception IllegalAccessException if this {@code Field} object + * is enforcing Java language access control and the underlying + * field is either inaccessible or final. + * @exception IllegalArgumentException if the specified object is not an + * instance of the class or interface declaring the underlying + * field (or a subclass or implementor thereof), + * or if an unwrapping conversion fails. + * @exception NullPointerException if the specified object is null + * and the field is an instance field. + * @exception ExceptionInInitializerError if the initialization provoked + * by this method fails. + * @see Field#set + */ + public void setInt(Object obj, int i) + throws IllegalArgumentException, IllegalAccessException + { + getFieldAccessor(obj).setInt(obj, i); + } + + /** + * Sets the value of a field as a {@code long} on the specified object. + * This method is equivalent to + * {@code set(obj, lObj)}, + * where {@code lObj} is a {@code Long} object and + * {@code lObj.longValue() == l}. + * + * @param obj the object whose field should be modified + * @param l the new value for the field of {@code obj} + * being modified + * + * @exception IllegalAccessException if this {@code Field} object + * is enforcing Java language access control and the underlying + * field is either inaccessible or final. + * @exception IllegalArgumentException if the specified object is not an + * instance of the class or interface declaring the underlying + * field (or a subclass or implementor thereof), + * or if an unwrapping conversion fails. + * @exception NullPointerException if the specified object is null + * and the field is an instance field. + * @exception ExceptionInInitializerError if the initialization provoked + * by this method fails. + * @see Field#set + */ + public void setLong(Object obj, long l) + throws IllegalArgumentException, IllegalAccessException + { + getFieldAccessor(obj).setLong(obj, l); + } + + /** + * Sets the value of a field as a {@code float} on the specified object. + * This method is equivalent to + * {@code set(obj, fObj)}, + * where {@code fObj} is a {@code Float} object and + * {@code fObj.floatValue() == f}. + * + * @param obj the object whose field should be modified + * @param f the new value for the field of {@code obj} + * being modified + * + * @exception IllegalAccessException if this {@code Field} object + * is enforcing Java language access control and the underlying + * field is either inaccessible or final. + * @exception IllegalArgumentException if the specified object is not an + * instance of the class or interface declaring the underlying + * field (or a subclass or implementor thereof), + * or if an unwrapping conversion fails. + * @exception NullPointerException if the specified object is null + * and the field is an instance field. + * @exception ExceptionInInitializerError if the initialization provoked + * by this method fails. + * @see Field#set + */ + public void setFloat(Object obj, float f) + throws IllegalArgumentException, IllegalAccessException + { + getFieldAccessor(obj).setFloat(obj, f); + } + + /** + * Sets the value of a field as a {@code double} on the specified object. + * This method is equivalent to + * {@code set(obj, dObj)}, + * where {@code dObj} is a {@code Double} object and + * {@code dObj.doubleValue() == d}. + * + * @param obj the object whose field should be modified + * @param d the new value for the field of {@code obj} + * being modified + * + * @exception IllegalAccessException if this {@code Field} object + * is enforcing Java language access control and the underlying + * field is either inaccessible or final. + * @exception IllegalArgumentException if the specified object is not an + * instance of the class or interface declaring the underlying + * field (or a subclass or implementor thereof), + * or if an unwrapping conversion fails. + * @exception NullPointerException if the specified object is null + * and the field is an instance field. + * @exception ExceptionInInitializerError if the initialization provoked + * by this method fails. + * @see Field#set + */ + public void setDouble(Object obj, double d) + throws IllegalArgumentException, IllegalAccessException + { + getFieldAccessor(obj).setDouble(obj, d); + } + + // Convenience routine which performs security checks + private FieldAccessor getFieldAccessor(Object obj) + throws IllegalAccessException + { + throw new SecurityException(); + } + + private static abstract class FieldAccessor { + abstract void setShort(Object obj, short s); + abstract void setInt(Object obj, int i); + abstract void setChar(Object obj, char c); + abstract void setByte(Object obj, byte b); + abstract void setBoolean(Object obj, boolean z); + abstract void set(Object obj, Object value); + abstract double getDouble(Object obj); + abstract void setLong(Object obj, long l); + abstract void setFloat(Object obj, float f); + abstract void setDouble(Object obj, double d); + abstract long getLong(Object obj); + abstract int getInt(Object obj); + abstract short getShort(Object obj); + abstract char getChar(Object obj); + abstract byte getByte(Object obj); + abstract boolean getBoolean(Object obj); + abstract Object get(Object obj); + abstract float getFloat(Object obj); + } + + /* + * Utility routine to paper over array type names + */ + static String getTypeName(Class type) { + if (type.isArray()) { + try { + Class cl = type; + int dimensions = 0; + while (cl.isArray()) { + dimensions++; + cl = cl.getComponentType(); + } + StringBuffer sb = new StringBuffer(); + sb.append(cl.getName()); + for (int i = 0; i < dimensions; i++) { + sb.append("[]"); + } + return sb.toString(); + } catch (Throwable e) { /*FALLTHRU*/ } + } + return type.getName(); + } + + /** + * @throws NullPointerException {@inheritDoc} + * @since 1.5 + */ + public T getAnnotation(Class annotationClass) { + if (annotationClass == null) + throw new NullPointerException(); + + throw new UnsupportedOperationException(); + } + + /** + * @since 1.5 + */ + public Annotation[] getDeclaredAnnotations() { + throw new UnsupportedOperationException(); + } +} diff -r 388e48c0a37a -r 05224402145d emul/mini/src/main/java/java/lang/reflect/GenericDeclaration.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/emul/mini/src/main/java/java/lang/reflect/GenericDeclaration.java Wed Jan 23 20:39:23 2013 +0100 @@ -0,0 +1,49 @@ +/* + * Copyright (c) 2003, 2004, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code 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 + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package java.lang.reflect; + +/** + * A common interface for all entities that declare type variables. + * + * @since 1.5 + */ +public interface GenericDeclaration { + /** + * Returns an array of {@code TypeVariable} objects that + * represent the type variables declared by the generic + * declaration represented by this {@code GenericDeclaration} + * object, in declaration order. Returns an array of length 0 if + * the underlying generic declaration declares no type variables. + * + * @return an array of {@code TypeVariable} objects that represent + * the type variables declared by this generic declaration + * @throws GenericSignatureFormatError if the generic + * signature of this generic declaration does not conform to + * the format specified in + * The Java™ Virtual Machine Specification + */ + public TypeVariable[] getTypeParameters(); +} diff -r 388e48c0a37a -r 05224402145d emul/mini/src/main/java/java/lang/reflect/InvocationTargetException.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/emul/mini/src/main/java/java/lang/reflect/InvocationTargetException.java Wed Jan 23 20:39:23 2013 +0100 @@ -0,0 +1,111 @@ +/* + * Copyright (c) 1996, 2004, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code 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 + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package java.lang.reflect; + +/** + * InvocationTargetException is a checked exception that wraps + * an exception thrown by an invoked method or constructor. + * + *

As of release 1.4, this exception has been retrofitted to conform to + * the general purpose exception-chaining mechanism. The "target exception" + * that is provided at construction time and accessed via the + * {@link #getTargetException()} method is now known as the cause, + * and may be accessed via the {@link Throwable#getCause()} method, + * as well as the aforementioned "legacy method." + * + * @see Method + * @see Constructor + */ +public class InvocationTargetException extends ReflectiveOperationException { + /** + * Use serialVersionUID from JDK 1.1.X for interoperability + */ + private static final long serialVersionUID = 4085088731926701167L; + + /** + * This field holds the target if the + * InvocationTargetException(Throwable target) constructor was + * used to instantiate the object + * + * @serial + * + */ + private Throwable target; + + /** + * Constructs an {@code InvocationTargetException} with + * {@code null} as the target exception. + */ + protected InvocationTargetException() { + super((Throwable)null); // Disallow initCause + } + + /** + * Constructs a InvocationTargetException with a target exception. + * + * @param target the target exception + */ + public InvocationTargetException(Throwable target) { + super((Throwable)null); // Disallow initCause + this.target = target; + } + + /** + * Constructs a InvocationTargetException with a target exception + * and a detail message. + * + * @param target the target exception + * @param s the detail message + */ + public InvocationTargetException(Throwable target, String s) { + super(s, null); // Disallow initCause + this.target = target; + } + + /** + * Get the thrown target exception. + * + *

This method predates the general-purpose exception chaining facility. + * The {@link Throwable#getCause()} method is now the preferred means of + * obtaining this information. + * + * @return the thrown target exception (cause of this exception). + */ + public Throwable getTargetException() { + return target; + } + + /** + * Returns the cause of this exception (the thrown target exception, + * which may be {@code null}). + * + * @return the cause of this exception. + * @since 1.4 + */ + public Throwable getCause() { + return target; + } +} diff -r 388e48c0a37a -r 05224402145d emul/mini/src/main/java/java/lang/reflect/Member.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/emul/mini/src/main/java/java/lang/reflect/Member.java Wed Jan 23 20:39:23 2013 +0100 @@ -0,0 +1,93 @@ +/* + * Copyright (c) 1996, 2006, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code 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 + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package java.lang.reflect; + +/** + * Member is an interface that reflects identifying information about + * a single member (a field or a method) or a constructor. + * + * @see java.lang.Class + * @see Field + * @see Method + * @see Constructor + * + * @author Nakul Saraiya + */ +public +interface Member { + + /** + * Identifies the set of all public members of a class or interface, + * including inherited members. + * @see java.lang.SecurityManager#checkMemberAccess + */ + public static final int PUBLIC = 0; + + /** + * Identifies the set of declared members of a class or interface. + * Inherited members are not included. + * @see java.lang.SecurityManager#checkMemberAccess + */ + public static final int DECLARED = 1; + + /** + * Returns the Class object representing the class or interface + * that declares the member or constructor represented by this Member. + * + * @return an object representing the declaring class of the + * underlying member + */ + public Class getDeclaringClass(); + + /** + * Returns the simple name of the underlying member or constructor + * represented by this Member. + * + * @return the simple name of the underlying member + */ + public String getName(); + + /** + * Returns the Java language modifiers for the member or + * constructor represented by this Member, as an integer. The + * Modifier class should be used to decode the modifiers in + * the integer. + * + * @return the Java language modifiers for the underlying member + * @see Modifier + */ + public int getModifiers(); + + /** + * Returns {@code true} if this member was introduced by + * the compiler; returns {@code false} otherwise. + * + * @return true if and only if this member was introduced by + * the compiler. + * @since 1.5 + */ + public boolean isSynthetic(); +} diff -r 388e48c0a37a -r 05224402145d emul/mini/src/main/java/java/lang/reflect/Method.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/emul/mini/src/main/java/java/lang/reflect/Method.java Wed Jan 23 20:39:23 2013 +0100 @@ -0,0 +1,720 @@ +/* + * Copyright (c) 1996, 2006, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code 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 + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package java.lang.reflect; + +import java.lang.annotation.Annotation; +import java.util.Enumeration; +import org.apidesign.bck2brwsr.core.JavaScriptBody; +import org.apidesign.bck2brwsr.emul.AnnotationImpl; +import org.apidesign.bck2brwsr.emul.MethodImpl; + +/** + * A {@code Method} provides information about, and access to, a single method + * on a class or interface. The reflected method may be a class method + * or an instance method (including an abstract method). + * + *

A {@code Method} permits widening conversions to occur when matching the + * actual parameters to invoke with the underlying method's formal + * parameters, but it throws an {@code IllegalArgumentException} if a + * narrowing conversion would occur. + * + * @see Member + * @see java.lang.Class + * @see java.lang.Class#getMethods() + * @see java.lang.Class#getMethod(String, Class[]) + * @see java.lang.Class#getDeclaredMethods() + * @see java.lang.Class#getDeclaredMethod(String, Class[]) + * + * @author Kenneth Russell + * @author Nakul Saraiya + */ +public final + class Method extends AccessibleObject implements GenericDeclaration, + Member { + private final Class clazz; + private final String name; + private final Object data; + private final String sig; + + // Generics infrastructure + + private String getGenericSignature() {return null;} + + /** + * Package-private constructor used by ReflectAccess to enable + * instantiation of these objects in Java code from the java.lang + * package via sun.reflect.LangReflectAccess. + */ + Method(Class declaringClass, String name, Object data, String sig) + { + this.clazz = declaringClass; + this.name = name; + this.data = data; + this.sig = sig; + } + + /** + * Package-private routine (exposed to java.lang.Class via + * ReflectAccess) which returns a copy of this Method. The copy's + * "root" field points to this Method. + */ + Method copy() { + return this; + } + + /** + * Returns the {@code Class} object representing the class or interface + * that declares the method represented by this {@code Method} object. + */ + public Class getDeclaringClass() { + return clazz; + } + + /** + * Returns the name of the method represented by this {@code Method} + * object, as a {@code String}. + */ + public String getName() { + return name; + } + + /** + * Returns the Java language modifiers for the method represented + * by this {@code Method} object, as an integer. The {@code Modifier} class should + * be used to decode the modifiers. + * + * @see Modifier + */ + public int getModifiers() { + return getAccess(data); + } + + @JavaScriptBody(args = "self", body = "return self.access;") + private static native int getAccess(Object self); + + /** + * Returns an array of {@code TypeVariable} objects that represent the + * type variables declared by the generic declaration represented by this + * {@code GenericDeclaration} object, in declaration order. Returns an + * array of length 0 if the underlying generic declaration declares no type + * variables. + * + * @return an array of {@code TypeVariable} objects that represent + * the type variables declared by this generic declaration + * @throws GenericSignatureFormatError if the generic + * signature of this generic declaration does not conform to + * the format specified in + * The Java™ Virtual Machine Specification + * @since 1.5 + */ + public TypeVariable[] getTypeParameters() { + throw new UnsupportedOperationException(); + } + + /** + * Returns a {@code Class} object that represents the formal return type + * of the method represented by this {@code Method} object. + * + * @return the return type for the method this object represents + */ + public Class getReturnType() { + return MethodImpl.signatureParser(sig).nextElement(); + } + + /** + * Returns a {@code Type} object that represents the formal return + * type of the method represented by this {@code Method} object. + * + *

If the return type is a parameterized type, + * the {@code Type} object returned must accurately reflect + * the actual type parameters used in the source code. + * + *

If the return type is a type variable or a parameterized type, it + * is created. Otherwise, it is resolved. + * + * @return a {@code Type} object that represents the formal return + * type of the underlying method + * @throws GenericSignatureFormatError + * if the generic method signature does not conform to the format + * specified in + * The Java™ Virtual Machine Specification + * @throws TypeNotPresentException if the underlying method's + * return type refers to a non-existent type declaration + * @throws MalformedParameterizedTypeException if the + * underlying method's return typed refers to a parameterized + * type that cannot be instantiated for any reason + * @since 1.5 + */ + public Type getGenericReturnType() { + throw new UnsupportedOperationException(); + } + + + /** + * Returns an array of {@code Class} objects that represent the formal + * parameter types, in declaration order, of the method + * represented by this {@code Method} object. Returns an array of length + * 0 if the underlying method takes no parameters. + * + * @return the parameter types for the method this object + * represents + */ + public Class[] getParameterTypes() { + Class[] arr = new Class[MethodImpl.signatureElements(sig) - 1]; + Enumeration en = MethodImpl.signatureParser(sig); + en.nextElement(); // return type + for (int i = 0; i < arr.length; i++) { + arr[i] = en.nextElement(); + } + return arr; + } + + /** + * Returns an array of {@code Type} objects that represent the formal + * parameter types, in declaration order, of the method represented by + * this {@code Method} object. Returns an array of length 0 if the + * underlying method takes no parameters. + * + *

If a formal parameter type is a parameterized type, + * the {@code Type} object returned for it must accurately reflect + * the actual type parameters used in the source code. + * + *

If a formal parameter type is a type variable or a parameterized + * type, it is created. Otherwise, it is resolved. + * + * @return an array of Types that represent the formal + * parameter types of the underlying method, in declaration order + * @throws GenericSignatureFormatError + * if the generic method signature does not conform to the format + * specified in + * The Java™ Virtual Machine Specification + * @throws TypeNotPresentException if any of the parameter + * types of the underlying method refers to a non-existent type + * declaration + * @throws MalformedParameterizedTypeException if any of + * the underlying method's parameter types refer to a parameterized + * type that cannot be instantiated for any reason + * @since 1.5 + */ + public Type[] getGenericParameterTypes() { + throw new UnsupportedOperationException(); + } + + + /** + * Returns an array of {@code Class} objects that represent + * the types of the exceptions declared to be thrown + * by the underlying method + * represented by this {@code Method} object. Returns an array of length + * 0 if the method declares no exceptions in its {@code throws} clause. + * + * @return the exception types declared as being thrown by the + * method this object represents + */ + public Class[] getExceptionTypes() { + throw new UnsupportedOperationException(); + //return (Class[]) exceptionTypes.clone(); + } + + /** + * Returns an array of {@code Type} objects that represent the + * exceptions declared to be thrown by this {@code Method} object. + * Returns an array of length 0 if the underlying method declares + * no exceptions in its {@code throws} clause. + * + *

If an exception type is a type variable or a parameterized + * type, it is created. Otherwise, it is resolved. + * + * @return an array of Types that represent the exception types + * thrown by the underlying method + * @throws GenericSignatureFormatError + * if the generic method signature does not conform to the format + * specified in + * The Java™ Virtual Machine Specification + * @throws TypeNotPresentException if the underlying method's + * {@code throws} clause refers to a non-existent type declaration + * @throws MalformedParameterizedTypeException if + * the underlying method's {@code throws} clause refers to a + * parameterized type that cannot be instantiated for any reason + * @since 1.5 + */ + public Type[] getGenericExceptionTypes() { + throw new UnsupportedOperationException(); + } + + /** + * Compares this {@code Method} against the specified object. Returns + * true if the objects are the same. Two {@code Methods} are the same if + * they were declared by the same class and have the same name + * and formal parameter types and return type. + */ + public boolean equals(Object obj) { + if (obj != null && obj instanceof Method) { + Method other = (Method)obj; + return data == other.data; + } + return false; + } + + /** + * Returns a hashcode for this {@code Method}. The hashcode is computed + * as the exclusive-or of the hashcodes for the underlying + * method's declaring class name and the method's name. + */ + public int hashCode() { + return getDeclaringClass().getName().hashCode() ^ getName().hashCode(); + } + + /** + * Returns a string describing this {@code Method}. The string is + * formatted as the method access modifiers, if any, followed by + * the method return type, followed by a space, followed by the + * class declaring the method, followed by a period, followed by + * the method name, followed by a parenthesized, comma-separated + * list of the method's formal parameter types. If the method + * throws checked exceptions, the parameter list is followed by a + * space, followed by the word throws followed by a + * comma-separated list of the thrown exception types. + * For example: + *

+     *    public boolean java.lang.Object.equals(java.lang.Object)
+     * 
+ * + *

The access modifiers are placed in canonical order as + * specified by "The Java Language Specification". This is + * {@code public}, {@code protected} or {@code private} first, + * and then other modifiers in the following order: + * {@code abstract}, {@code static}, {@code final}, + * {@code synchronized}, {@code native}, {@code strictfp}. + */ + public String toString() { + try { + StringBuilder sb = new StringBuilder(); + int mod = getModifiers() & Modifier.methodModifiers(); + if (mod != 0) { + sb.append(Modifier.toString(mod)).append(' '); + } + sb.append(Field.getTypeName(getReturnType())).append(' '); + sb.append(Field.getTypeName(getDeclaringClass())).append('.'); + sb.append(getName()).append('('); + Class[] params = getParameterTypes(); // avoid clone + for (int j = 0; j < params.length; j++) { + sb.append(Field.getTypeName(params[j])); + if (j < (params.length - 1)) + sb.append(','); + } + sb.append(')'); + /* + Class[] exceptions = exceptionTypes; // avoid clone + if (exceptions.length > 0) { + sb.append(" throws "); + for (int k = 0; k < exceptions.length; k++) { + sb.append(exceptions[k].getName()); + if (k < (exceptions.length - 1)) + sb.append(','); + } + } + */ + return sb.toString(); + } catch (Exception e) { + return "<" + e + ">"; + } + } + + /** + * Returns a string describing this {@code Method}, including + * type parameters. The string is formatted as the method access + * modifiers, if any, followed by an angle-bracketed + * comma-separated list of the method's type parameters, if any, + * followed by the method's generic return type, followed by a + * space, followed by the class declaring the method, followed by + * a period, followed by the method name, followed by a + * parenthesized, comma-separated list of the method's generic + * formal parameter types. + * + * If this method was declared to take a variable number of + * arguments, instead of denoting the last parameter as + * "Type[]", it is denoted as + * "Type...". + * + * A space is used to separate access modifiers from one another + * and from the type parameters or return type. If there are no + * type parameters, the type parameter list is elided; if the type + * parameter list is present, a space separates the list from the + * class name. If the method is declared to throw exceptions, the + * parameter list is followed by a space, followed by the word + * throws followed by a comma-separated list of the generic thrown + * exception types. If there are no type parameters, the type + * parameter list is elided. + * + *

The access modifiers are placed in canonical order as + * specified by "The Java Language Specification". This is + * {@code public}, {@code protected} or {@code private} first, + * and then other modifiers in the following order: + * {@code abstract}, {@code static}, {@code final}, + * {@code synchronized}, {@code native}, {@code strictfp}. + * + * @return a string describing this {@code Method}, + * include type parameters + * + * @since 1.5 + */ + public String toGenericString() { + try { + StringBuilder sb = new StringBuilder(); + int mod = getModifiers() & Modifier.methodModifiers(); + if (mod != 0) { + sb.append(Modifier.toString(mod)).append(' '); + } + TypeVariable[] typeparms = getTypeParameters(); + if (typeparms.length > 0) { + boolean first = true; + sb.append('<'); + for(TypeVariable typeparm: typeparms) { + if (!first) + sb.append(','); + // Class objects can't occur here; no need to test + // and call Class.getName(). + sb.append(typeparm.toString()); + first = false; + } + sb.append("> "); + } + + Type genRetType = getGenericReturnType(); + sb.append( ((genRetType instanceof Class)? + Field.getTypeName((Class)genRetType):genRetType.toString())) + .append(' '); + + sb.append(Field.getTypeName(getDeclaringClass())).append('.'); + sb.append(getName()).append('('); + Type[] params = getGenericParameterTypes(); + for (int j = 0; j < params.length; j++) { + String param = (params[j] instanceof Class)? + Field.getTypeName((Class)params[j]): + (params[j].toString()); + if (isVarArgs() && (j == params.length - 1)) // replace T[] with T... + param = param.replaceFirst("\\[\\]$", "..."); + sb.append(param); + if (j < (params.length - 1)) + sb.append(','); + } + sb.append(')'); + Type[] exceptions = getGenericExceptionTypes(); + if (exceptions.length > 0) { + sb.append(" throws "); + for (int k = 0; k < exceptions.length; k++) { + sb.append((exceptions[k] instanceof Class)? + ((Class)exceptions[k]).getName(): + exceptions[k].toString()); + if (k < (exceptions.length - 1)) + sb.append(','); + } + } + return sb.toString(); + } catch (Exception e) { + return "<" + e + ">"; + } + } + + /** + * Invokes the underlying method represented by this {@code Method} + * object, on the specified object with the specified parameters. + * Individual parameters are automatically unwrapped to match + * primitive formal parameters, and both primitive and reference + * parameters are subject to method invocation conversions as + * necessary. + * + *

If the underlying method is static, then the specified {@code obj} + * argument is ignored. It may be null. + * + *

If the number of formal parameters required by the underlying method is + * 0, the supplied {@code args} array may be of length 0 or null. + * + *

If the underlying method is an instance method, it is invoked + * using dynamic method lookup as documented in The Java Language + * Specification, Second Edition, section 15.12.4.4; in particular, + * overriding based on the runtime type of the target object will occur. + * + *

If the underlying method is static, the class that declared + * the method is initialized if it has not already been initialized. + * + *

If the method completes normally, the value it returns is + * returned to the caller of invoke; if the value has a primitive + * type, it is first appropriately wrapped in an object. However, + * if the value has the type of an array of a primitive type, the + * elements of the array are not wrapped in objects; in + * other words, an array of primitive type is returned. If the + * underlying method return type is void, the invocation returns + * null. + * + * @param obj the object the underlying method is invoked from + * @param args the arguments used for the method call + * @return the result of dispatching the method represented by + * this object on {@code obj} with parameters + * {@code args} + * + * @exception IllegalAccessException if this {@code Method} object + * is enforcing Java language access control and the underlying + * method is inaccessible. + * @exception IllegalArgumentException if the method is an + * instance method and the specified object argument + * is not an instance of the class or interface + * declaring the underlying method (or of a subclass + * or implementor thereof); if the number of actual + * and formal parameters differ; if an unwrapping + * conversion for primitive arguments fails; or if, + * after possible unwrapping, a parameter value + * cannot be converted to the corresponding formal + * parameter type by a method invocation conversion. + * @exception InvocationTargetException if the underlying method + * throws an exception. + * @exception NullPointerException if the specified object is null + * and the method is an instance method. + * @exception ExceptionInInitializerError if the initialization + * provoked by this method fails. + */ + public Object invoke(Object obj, Object... args) + throws IllegalAccessException, IllegalArgumentException, + InvocationTargetException + { + final boolean isStatic = (getModifiers() & Modifier.STATIC) == 0; + if (isStatic && obj == null) { + throw new NullPointerException(); + } + Class[] types = getParameterTypes(); + if (types.length != args.length) { + throw new IllegalArgumentException("Types len " + types.length + " args: " + args.length); + } else { + args = args.clone(); + for (int i = 0; i < types.length; i++) { + Class c = types[i]; + if (c.isPrimitive()) { + args[i] = toPrimitive(c, args[i]); + } + } + } + Object res = invoke0(isStatic, this, obj, args); + if (getReturnType().isPrimitive()) { + res = fromPrimitive(getReturnType(), res); + } + return res; + } + + @JavaScriptBody(args = { "st", "method", "self", "args" }, body = + "var p;\n" + + "if (st) {\n" + + " p = new Array(1);\n" + + " p[0] = self;\n" + + " p = p.concat(args);\n" + + "} else {\n" + + " p = args;\n" + + "}\n" + + "return method.fld_data.apply(self, p);\n" + ) + private static native Object invoke0(boolean isStatic, Method m, Object self, Object[] args); + + static Object fromPrimitive(Class type, Object o) { + if (type == Integer.TYPE) { + return fromRaw(Integer.class, "valueOf__Ljava_lang_Integer_2I", o); + } + if (type == Long.TYPE) { + return fromRaw(Long.class, "valueOf__Ljava_lang_Long_2J", o); + } + if (type == Double.TYPE) { + return fromRaw(Double.class, "valueOf__Ljava_lang_Double_2D", o); + } + if (type == Float.TYPE) { + return fromRaw(Float.class, "valueOf__Ljava_lang_Float_2F", o); + } + if (type == Byte.TYPE) { + return fromRaw(Byte.class, "valueOf__Ljava_lang_Byte_2B", o); + } + if (type == Boolean.TYPE) { + return fromRaw(Boolean.class, "valueOf__Ljava_lang_Boolean_2Z", o); + } + if (type == Short.TYPE) { + return fromRaw(Short.class, "valueOf__Ljava_lang_Short_2S", o); + } + if (type == Character.TYPE) { + return fromRaw(Character.class, "valueOf__Ljava_lang_Character_2C", o); + } + if (type.getName().equals("void")) { + return null; + } + throw new IllegalStateException("Can't convert " + o); + } + + @JavaScriptBody(args = { "cls", "m", "o" }, + body = "return cls.cnstr(false)[m](o);" + ) + private static native Integer fromRaw(Class cls, String m, Object o); + + private static Object toPrimitive(Class type, Object o) { + if (type == Integer.TYPE) { + return toRaw("intValue__I", o); + } + if (type == Long.TYPE) { + return toRaw("longValue__J", o); + } + if (type == Double.TYPE) { + return toRaw("doubleValue__D", o); + } + if (type == Float.TYPE) { + return toRaw("floatValue__F", o); + } + if (type == Byte.TYPE) { + return toRaw("byteValue__B", o); + } + if (type == Boolean.TYPE) { + return toRaw("booleanValue__Z", o); + } + if (type == Short.TYPE) { + return toRaw("shortValue__S", o); + } + if (type == Character.TYPE) { + return toRaw("charValue__C", o); + } + if (type.getName().equals("void")) { + return o; + } + throw new IllegalStateException("Can't convert " + o); + } + + @JavaScriptBody(args = { "m", "o" }, + body = "return o[m](o);" + ) + private static native Object toRaw(String m, Object o); + + /** + * Returns {@code true} if this method is a bridge + * method; returns {@code false} otherwise. + * + * @return true if and only if this method is a bridge + * method as defined by the Java Language Specification. + * @since 1.5 + */ + public boolean isBridge() { + return (getModifiers() & Modifier.BRIDGE) != 0; + } + + /** + * Returns {@code true} if this method was declared to take + * a variable number of arguments; returns {@code false} + * otherwise. + * + * @return {@code true} if an only if this method was declared to + * take a variable number of arguments. + * @since 1.5 + */ + public boolean isVarArgs() { + return (getModifiers() & Modifier.VARARGS) != 0; + } + + /** + * Returns {@code true} if this method is a synthetic + * method; returns {@code false} otherwise. + * + * @return true if and only if this method is a synthetic + * method as defined by the Java Language Specification. + * @since 1.5 + */ + public boolean isSynthetic() { + return Modifier.isSynthetic(getModifiers()); + } + + @JavaScriptBody(args = { "ac" }, + body = + "if (this.fld_data.anno) {" + + " return this.fld_data.anno['L' + ac.jvmName + ';'];" + + "} else return null;" + ) + private Object getAnnotationData(Class annotationClass) { + throw new UnsupportedOperationException(); + } + + /** + * @throws NullPointerException {@inheritDoc} + * @since 1.5 + */ + public T getAnnotation(Class annotationClass) { + Object data = getAnnotationData(annotationClass); + return data == null ? null : AnnotationImpl.create(annotationClass, data); + } + + /** + * @since 1.5 + */ + public Annotation[] getDeclaredAnnotations() { + throw new UnsupportedOperationException(); + } + + /** + * Returns the default value for the annotation member represented by + * this {@code Method} instance. If the member is of a primitive type, + * an instance of the corresponding wrapper type is returned. Returns + * null if no default is associated with the member, or if the method + * instance does not represent a declared member of an annotation type. + * + * @return the default value for the annotation member represented + * by this {@code Method} instance. + * @throws TypeNotPresentException if the annotation is of type + * {@link Class} and no definition can be found for the + * default class value. + * @since 1.5 + */ + public Object getDefaultValue() { + throw new UnsupportedOperationException(); + } + + /** + * Returns an array of arrays that represent the annotations on the formal + * parameters, in declaration order, of the method represented by + * this {@code Method} object. (Returns an array of length zero if the + * underlying method is parameterless. If the method has one or more + * parameters, a nested array of length zero is returned for each parameter + * with no annotations.) The annotation objects contained in the returned + * arrays are serializable. The caller of this method is free to modify + * the returned arrays; it will have no effect on the arrays returned to + * other callers. + * + * @return an array of arrays that represent the annotations on the formal + * parameters, in declaration order, of the method represented by this + * Method object + * @since 1.5 + */ + public Annotation[][] getParameterAnnotations() { + throw new UnsupportedOperationException(); + } + + static { + MethodImpl.INSTANCE = new MethodImpl() { + protected Method create(Class declaringClass, String name, Object data, String sig) { + return new Method(declaringClass, name, data, sig); + } + }; + } +} diff -r 388e48c0a37a -r 05224402145d emul/mini/src/main/java/java/lang/reflect/Modifier.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/emul/mini/src/main/java/java/lang/reflect/Modifier.java Wed Jan 23 20:39:23 2013 +0100 @@ -0,0 +1,437 @@ +/* + * Copyright (c) 1996, 2008, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code 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 + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package java.lang.reflect; + +/** + * The Modifier class provides {@code static} methods and + * constants to decode class and member access modifiers. The sets of + * modifiers are represented as integers with distinct bit positions + * representing different modifiers. The values for the constants + * representing the modifiers are taken from the tables in sections 4.1, 4.4, 4.5, and 4.7 of + * The Java™ Virtual Machine Specification. + * + * @see Class#getModifiers() + * @see Member#getModifiers() + * + * @author Nakul Saraiya + * @author Kenneth Russell + */ +public +class Modifier { + + /** + * Return {@code true} if the integer argument includes the + * {@code public} modifier, {@code false} otherwise. + * + * @param mod a set of modifiers + * @return {@code true} if {@code mod} includes the + * {@code public} modifier; {@code false} otherwise. + */ + public static boolean isPublic(int mod) { + return (mod & PUBLIC) != 0; + } + + /** + * Return {@code true} if the integer argument includes the + * {@code private} modifier, {@code false} otherwise. + * + * @param mod a set of modifiers + * @return {@code true} if {@code mod} includes the + * {@code private} modifier; {@code false} otherwise. + */ + public static boolean isPrivate(int mod) { + return (mod & PRIVATE) != 0; + } + + /** + * Return {@code true} if the integer argument includes the + * {@code protected} modifier, {@code false} otherwise. + * + * @param mod a set of modifiers + * @return {@code true} if {@code mod} includes the + * {@code protected} modifier; {@code false} otherwise. + */ + public static boolean isProtected(int mod) { + return (mod & PROTECTED) != 0; + } + + /** + * Return {@code true} if the integer argument includes the + * {@code static} modifier, {@code false} otherwise. + * + * @param mod a set of modifiers + * @return {@code true} if {@code mod} includes the + * {@code static} modifier; {@code false} otherwise. + */ + public static boolean isStatic(int mod) { + return (mod & STATIC) != 0; + } + + /** + * Return {@code true} if the integer argument includes the + * {@code final} modifier, {@code false} otherwise. + * + * @param mod a set of modifiers + * @return {@code true} if {@code mod} includes the + * {@code final} modifier; {@code false} otherwise. + */ + public static boolean isFinal(int mod) { + return (mod & FINAL) != 0; + } + + /** + * Return {@code true} if the integer argument includes the + * {@code synchronized} modifier, {@code false} otherwise. + * + * @param mod a set of modifiers + * @return {@code true} if {@code mod} includes the + * {@code synchronized} modifier; {@code false} otherwise. + */ + public static boolean isSynchronized(int mod) { + return (mod & SYNCHRONIZED) != 0; + } + + /** + * Return {@code true} if the integer argument includes the + * {@code volatile} modifier, {@code false} otherwise. + * + * @param mod a set of modifiers + * @return {@code true} if {@code mod} includes the + * {@code volatile} modifier; {@code false} otherwise. + */ + public static boolean isVolatile(int mod) { + return (mod & VOLATILE) != 0; + } + + /** + * Return {@code true} if the integer argument includes the + * {@code transient} modifier, {@code false} otherwise. + * + * @param mod a set of modifiers + * @return {@code true} if {@code mod} includes the + * {@code transient} modifier; {@code false} otherwise. + */ + public static boolean isTransient(int mod) { + return (mod & TRANSIENT) != 0; + } + + /** + * Return {@code true} if the integer argument includes the + * {@code native} modifier, {@code false} otherwise. + * + * @param mod a set of modifiers + * @return {@code true} if {@code mod} includes the + * {@code native} modifier; {@code false} otherwise. + */ + public static boolean isNative(int mod) { + return (mod & NATIVE) != 0; + } + + /** + * Return {@code true} if the integer argument includes the + * {@code interface} modifier, {@code false} otherwise. + * + * @param mod a set of modifiers + * @return {@code true} if {@code mod} includes the + * {@code interface} modifier; {@code false} otherwise. + */ + public static boolean isInterface(int mod) { + return (mod & INTERFACE) != 0; + } + + /** + * Return {@code true} if the integer argument includes the + * {@code abstract} modifier, {@code false} otherwise. + * + * @param mod a set of modifiers + * @return {@code true} if {@code mod} includes the + * {@code abstract} modifier; {@code false} otherwise. + */ + public static boolean isAbstract(int mod) { + return (mod & ABSTRACT) != 0; + } + + /** + * Return {@code true} if the integer argument includes the + * {@code strictfp} modifier, {@code false} otherwise. + * + * @param mod a set of modifiers + * @return {@code true} if {@code mod} includes the + * {@code strictfp} modifier; {@code false} otherwise. + */ + public static boolean isStrict(int mod) { + return (mod & STRICT) != 0; + } + + /** + * Return a string describing the access modifier flags in + * the specified modifier. For example: + *

+     *    public final synchronized strictfp
+     * 
+ * The modifier names are returned in an order consistent with the + * suggested modifier orderings given in sections 8.1.1, 8.3.1, 8.4.3, 8.8.3, and 9.1.1 of + * The Java™ Language Specification. + * The full modifier ordering used by this method is: + *
{@code + * public protected private abstract static final transient + * volatile synchronized native strictfp + * interface }
+ * The {@code interface} modifier discussed in this class is + * not a true modifier in the Java language and it appears after + * all other modifiers listed by this method. This method may + * return a string of modifiers that are not valid modifiers of a + * Java entity; in other words, no checking is done on the + * possible validity of the combination of modifiers represented + * by the input. + * + * Note that to perform such checking for a known kind of entity, + * such as a constructor or method, first AND the argument of + * {@code toString} with the appropriate mask from a method like + * {@link #constructorModifiers} or {@link #methodModifiers}. + * + * @param mod a set of modifiers + * @return a string representation of the set of modifiers + * represented by {@code mod} + */ + public static String toString(int mod) { + StringBuffer sb = new StringBuffer(); + int len; + + if ((mod & PUBLIC) != 0) sb.append("public "); + if ((mod & PROTECTED) != 0) sb.append("protected "); + if ((mod & PRIVATE) != 0) sb.append("private "); + + /* Canonical order */ + if ((mod & ABSTRACT) != 0) sb.append("abstract "); + if ((mod & STATIC) != 0) sb.append("static "); + if ((mod & FINAL) != 0) sb.append("final "); + if ((mod & TRANSIENT) != 0) sb.append("transient "); + if ((mod & VOLATILE) != 0) sb.append("volatile "); + if ((mod & SYNCHRONIZED) != 0) sb.append("synchronized "); + if ((mod & NATIVE) != 0) sb.append("native "); + if ((mod & STRICT) != 0) sb.append("strictfp "); + if ((mod & INTERFACE) != 0) sb.append("interface "); + + if ((len = sb.length()) > 0) /* trim trailing space */ + return sb.toString().substring(0, len-1); + return ""; + } + + /* + * Access modifier flag constants from tables 4.1, 4.4, 4.5, and 4.7 of + * The Java™ Virtual Machine Specification + */ + + /** + * The {@code int} value representing the {@code public} + * modifier. + */ + public static final int PUBLIC = 0x00000001; + + /** + * The {@code int} value representing the {@code private} + * modifier. + */ + public static final int PRIVATE = 0x00000002; + + /** + * The {@code int} value representing the {@code protected} + * modifier. + */ + public static final int PROTECTED = 0x00000004; + + /** + * The {@code int} value representing the {@code static} + * modifier. + */ + public static final int STATIC = 0x00000008; + + /** + * The {@code int} value representing the {@code final} + * modifier. + */ + public static final int FINAL = 0x00000010; + + /** + * The {@code int} value representing the {@code synchronized} + * modifier. + */ + public static final int SYNCHRONIZED = 0x00000020; + + /** + * The {@code int} value representing the {@code volatile} + * modifier. + */ + public static final int VOLATILE = 0x00000040; + + /** + * The {@code int} value representing the {@code transient} + * modifier. + */ + public static final int TRANSIENT = 0x00000080; + + /** + * The {@code int} value representing the {@code native} + * modifier. + */ + public static final int NATIVE = 0x00000100; + + /** + * The {@code int} value representing the {@code interface} + * modifier. + */ + public static final int INTERFACE = 0x00000200; + + /** + * The {@code int} value representing the {@code abstract} + * modifier. + */ + public static final int ABSTRACT = 0x00000400; + + /** + * The {@code int} value representing the {@code strictfp} + * modifier. + */ + public static final int STRICT = 0x00000800; + + // Bits not (yet) exposed in the public API either because they + // have different meanings for fields and methods and there is no + // way to distinguish between the two in this class, or because + // they are not Java programming language keywords + static final int BRIDGE = 0x00000040; + static final int VARARGS = 0x00000080; + static final int SYNTHETIC = 0x00001000; + static final int ANNOTATION= 0x00002000; + static final int ENUM = 0x00004000; + static boolean isSynthetic(int mod) { + return (mod & SYNTHETIC) != 0; + } + + /** + * See JLSv3 section 8.1.1. + */ + private static final int CLASS_MODIFIERS = + Modifier.PUBLIC | Modifier.PROTECTED | Modifier.PRIVATE | + Modifier.ABSTRACT | Modifier.STATIC | Modifier.FINAL | + Modifier.STRICT; + + /** + * See JLSv3 section 9.1.1. + */ + private static final int INTERFACE_MODIFIERS = + Modifier.PUBLIC | Modifier.PROTECTED | Modifier.PRIVATE | + Modifier.ABSTRACT | Modifier.STATIC | Modifier.STRICT; + + + /** + * See JLSv3 section 8.8.3. + */ + private static final int CONSTRUCTOR_MODIFIERS = + Modifier.PUBLIC | Modifier.PROTECTED | Modifier.PRIVATE; + + /** + * See JLSv3 section 8.4.3. + */ + private static final int METHOD_MODIFIERS = + Modifier.PUBLIC | Modifier.PROTECTED | Modifier.PRIVATE | + Modifier.ABSTRACT | Modifier.STATIC | Modifier.FINAL | + Modifier.SYNCHRONIZED | Modifier.NATIVE | Modifier.STRICT; + + /** + * See JLSv3 section 8.3.1. + */ + private static final int FIELD_MODIFIERS = + Modifier.PUBLIC | Modifier.PROTECTED | Modifier.PRIVATE | + Modifier.STATIC | Modifier.FINAL | Modifier.TRANSIENT | + Modifier.VOLATILE; + + /** + * Return an {@code int} value OR-ing together the source language + * modifiers that can be applied to a class. + * @return an {@code int} value OR-ing together the source language + * modifiers that can be applied to a class. + * + * @jls 8.1.1 Class Modifiers + * @since 1.7 + */ + public static int classModifiers() { + return CLASS_MODIFIERS; + } + + /** + * Return an {@code int} value OR-ing together the source language + * modifiers that can be applied to an interface. + * @return an {@code int} value OR-ing together the source language + * modifiers that can be applied to an inteface. + * + * @jls 9.1.1 Interface Modifiers + * @since 1.7 + */ + public static int interfaceModifiers() { + return INTERFACE_MODIFIERS; + } + + /** + * Return an {@code int} value OR-ing together the source language + * modifiers that can be applied to a constructor. + * @return an {@code int} value OR-ing together the source language + * modifiers that can be applied to a constructor. + * + * @jls 8.8.3 Constructor Modifiers + * @since 1.7 + */ + public static int constructorModifiers() { + return CONSTRUCTOR_MODIFIERS; + } + + /** + * Return an {@code int} value OR-ing together the source language + * modifiers that can be applied to a method. + * @return an {@code int} value OR-ing together the source language + * modifiers that can be applied to a method. + * + * @jls 8.4.3 Method Modifiers + * @since 1.7 + */ + public static int methodModifiers() { + return METHOD_MODIFIERS; + } + + + /** + * Return an {@code int} value OR-ing together the source language + * modifiers that can be applied to a field. + * @return an {@code int} value OR-ing together the source language + * modifiers that can be applied to a field. + * + * @jls 8.3.1 Field Modifiers + * @since 1.7 + */ + public static int fieldModifiers() { + return FIELD_MODIFIERS; + } +} diff -r 388e48c0a37a -r 05224402145d emul/mini/src/main/java/java/lang/reflect/Type.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/emul/mini/src/main/java/java/lang/reflect/Type.java Wed Jan 23 20:39:23 2013 +0100 @@ -0,0 +1,37 @@ +/* + * Copyright (c) 2003, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code 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 + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package java.lang.reflect; + +/** + * Type is the common superinterface for all types in the Java + * programming language. These include raw types, parameterized types, + * array types, type variables and primitive types. + * + * @since 1.5 + */ + +public interface Type { +} diff -r 388e48c0a37a -r 05224402145d emul/mini/src/main/java/java/lang/reflect/TypeVariable.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/emul/mini/src/main/java/java/lang/reflect/TypeVariable.java Wed Jan 23 20:39:23 2013 +0100 @@ -0,0 +1,89 @@ +/* + * Copyright (c) 2003, 2005, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code 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 + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package java.lang.reflect; + +/** + * TypeVariable is the common superinterface for type variables of kinds. + * A type variable is created the first time it is needed by a reflective + * method, as specified in this package. If a type variable t is referenced + * by a type (i.e, class, interface or annotation type) T, and T is declared + * by the nth enclosing class of T (see JLS 8.1.2), then the creation of t + * requires the resolution (see JVMS 5) of the ith enclosing class of T, + * for i = 0 to n, inclusive. Creating a type variable must not cause the + * creation of its bounds. Repeated creation of a type variable has no effect. + * + *

Multiple objects may be instantiated at run-time to + * represent a given type variable. Even though a type variable is + * created only once, this does not imply any requirement to cache + * instances representing the type variable. However, all instances + * representing a type variable must be equal() to each other. + * As a consequence, users of type variables must not rely on the identity + * of instances of classes implementing this interface. + * + * @param the type of generic declaration that declared the + * underlying type variable. + * + * @since 1.5 + */ +public interface TypeVariable extends Type { + /** + * Returns an array of {@code Type} objects representing the + * upper bound(s) of this type variable. Note that if no upper bound is + * explicitly declared, the upper bound is {@code Object}. + * + *

For each upper bound B:

  • if B is a parameterized + * type or a type variable, it is created, (see {@link + * java.lang.reflect.ParameterizedType ParameterizedType} for the + * details of the creation process for parameterized types). + *
  • Otherwise, B is resolved.
+ * + * @throws TypeNotPresentException if any of the + * bounds refers to a non-existent type declaration + * @throws MalformedParameterizedTypeException if any of the + * bounds refer to a parameterized type that cannot be instantiated + * for any reason + * @return an array of {@code Type}s representing the upper + * bound(s) of this type variable + */ + Type[] getBounds(); + + /** + * Returns the {@code GenericDeclaration} object representing the + * generic declaration declared this type variable. + * + * @return the generic declaration declared for this type variable. + * + * @since 1.5 + */ + D getGenericDeclaration(); + + /** + * Returns the name of this type variable, as it occurs in the source code. + * + * @return the name of this type variable, as it appears in the source code + */ + String getName(); +} diff -r 388e48c0a37a -r 05224402145d emul/mini/src/main/java/java/lang/reflect/package-info.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/emul/mini/src/main/java/java/lang/reflect/package-info.java Wed Jan 23 20:39:23 2013 +0100 @@ -0,0 +1,49 @@ +/* + * Copyright (c) 1998, 2006, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code 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 + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/** + * Provides classes and interfaces for obtaining reflective + * information about classes and objects. Reflection allows + * programmatic access to information about the fields, methods and + * constructors of loaded classes, and the use of reflected fields, + * methods, and constructors to operate on their underlying + * counterparts, within security restrictions. + * + *

{@code AccessibleObject} allows suppression of access checks if + * the necessary {@code ReflectPermission} is available. + * + *

{@code Array} provides static methods to dynamically create and + * access arrays. + * + *

Classes in this package, along with {@code java.lang.Class} + * accommodate applications such as debuggers, interpreters, object + * inspectors, class browsers, and services such as Object + * Serialization and JavaBeans that need access to either the public + * members of a target object (based on its runtime class) or the + * members declared by a given class. + * + * @since JDK1.1 + */ +package java.lang.reflect; diff -r 388e48c0a37a -r 05224402145d emul/mini/src/main/java/java/net/MalformedURLException.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/emul/mini/src/main/java/java/net/MalformedURLException.java Wed Jan 23 20:39:23 2013 +0100 @@ -0,0 +1,56 @@ +/* + * Copyright (c) 1995, 2008, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code 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 + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package java.net; + +import java.io.IOException; + +/** + * Thrown to indicate that a malformed URL has occurred. Either no + * legal protocol could be found in a specification string or the + * string could not be parsed. + * + * @author Arthur van Hoff + * @since JDK1.0 + */ +public class MalformedURLException extends IOException { + private static final long serialVersionUID = -182787522200415866L; + + /** + * Constructs a MalformedURLException with no detail message. + */ + public MalformedURLException() { + } + + /** + * Constructs a MalformedURLException with the + * specified detail message. + * + * @param msg the detail message. + */ + public MalformedURLException(String msg) { + super(msg); + } +} diff -r 388e48c0a37a -r 05224402145d emul/mini/src/main/java/java/net/URL.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/emul/mini/src/main/java/java/net/URL.java Wed Jan 23 20:39:23 2013 +0100 @@ -0,0 +1,1037 @@ +/* + * Copyright (c) 1995, 2008, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code 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 + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package java.net; + +import java.io.IOException; +import java.io.InputStream; +import org.apidesign.bck2brwsr.core.JavaScriptBody; + +/** + * Class URL represents a Uniform Resource + * Locator, a pointer to a "resource" on the World + * Wide Web. A resource can be something as simple as a file or a + * directory, or it can be a reference to a more complicated object, + * such as a query to a database or to a search engine. More + * information on the types of URLs and their formats can be found at: + *

+ * + * http://www.socs.uts.edu.au/MosaicDocs-old/url-primer.html + *
+ *

+ * In general, a URL can be broken into several parts. The previous + * example of a URL indicates that the protocol to use is + * http (HyperText Transfer Protocol) and that the + * information resides on a host machine named + * www.socs.uts.edu.au. The information on that host + * machine is named /MosaicDocs-old/url-primer.html. The exact + * meaning of this name on the host machine is both protocol + * dependent and host dependent. The information normally resides in + * a file, but it could be generated on the fly. This component of + * the URL is called the path component. + *

+ * A URL can optionally specify a "port", which is the + * port number to which the TCP connection is made on the remote host + * machine. If the port is not specified, the default port for + * the protocol is used instead. For example, the default port for + * http is 80. An alternative port could be + * specified as: + *

+ *     http://www.socs.uts.edu.au:80/MosaicDocs-old/url-primer.html
+ * 
+ *

+ * The syntax of URL is defined by RFC 2396: Uniform + * Resource Identifiers (URI): Generic Syntax, amended by RFC 2732: Format for + * Literal IPv6 Addresses in URLs. The Literal IPv6 address format + * also supports scope_ids. The syntax and usage of scope_ids is described + * here. + *

+ * A URL may have appended to it a "fragment", also known + * as a "ref" or a "reference". The fragment is indicated by the sharp + * sign character "#" followed by more characters. For example, + *

+ *     http://java.sun.com/index.html#chapter1
+ * 
+ *

+ * This fragment is not technically part of the URL. Rather, it + * indicates that after the specified resource is retrieved, the + * application is specifically interested in that part of the + * document that has the tag chapter1 attached to it. The + * meaning of a tag is resource specific. + *

+ * An application can also specify a "relative URL", + * which contains only enough information to reach the resource + * relative to another URL. Relative URLs are frequently used within + * HTML pages. For example, if the contents of the URL: + *

+ *     http://java.sun.com/index.html
+ * 
+ * contained within it the relative URL: + *
+ *     FAQ.html
+ * 
+ * it would be a shorthand for: + *
+ *     http://java.sun.com/FAQ.html
+ * 
+ *

+ * The relative URL need not specify all the components of a URL. If + * the protocol, host name, or port number is missing, the value is + * inherited from the fully specified URL. The file component must be + * specified. The optional fragment is not inherited. + *

+ * The URL class does not itself encode or decode any URL components + * according to the escaping mechanism defined in RFC2396. It is the + * responsibility of the caller to encode any fields, which need to be + * escaped prior to calling URL, and also to decode any escaped fields, + * that are returned from URL. Furthermore, because URL has no knowledge + * of URL escaping, it does not recognise equivalence between the encoded + * or decoded form of the same URL. For example, the two URLs:
+ *

    http://foo.com/hello world/ and http://foo.com/hello%20world
+ * would be considered not equal to each other. + *

+ * Note, the {@link java.net.URI} class does perform escaping of its + * component fields in certain circumstances. The recommended way + * to manage the encoding and decoding of URLs is to use {@link java.net.URI}, + * and to convert between these two classes using {@link #toURI()} and + * {@link URI#toURL()}. + *

+ * The {@link URLEncoder} and {@link URLDecoder} classes can also be + * used, but only for HTML form encoding, which is not the same + * as the encoding scheme defined in RFC2396. + * + * @author James Gosling + * @since JDK1.0 + */ +public final class URL implements java.io.Serializable { + + static final long serialVersionUID = -7627629688361524110L; + + /** + * The property which specifies the package prefix list to be scanned + * for protocol handlers. The value of this property (if any) should + * be a vertical bar delimited list of package names to search through + * for a protocol handler to load. The policy of this class is that + * all protocol handlers will be in a class called .Handler, + * and each package in the list is examined in turn for a matching + * handler. If none are found (or the property is not specified), the + * default package prefix, sun.net.www.protocol, is used. The search + * proceeds from the first package in the list to the last and stops + * when a match is found. + */ + private static final String protocolPathProp = "java.protocol.handler.pkgs"; + + /** + * The protocol to use (ftp, http, nntp, ... etc.) . + * @serial + */ + private String protocol; + + /** + * The host name to connect to. + * @serial + */ + private String host; + + /** + * The protocol port to connect to. + * @serial + */ + private int port = -1; + + /** + * The specified file name on that host. file is + * defined as path[?query] + * @serial + */ + private String file; + + /** + * The query part of this URL. + */ + private transient String query; + + /** + * The authority part of this URL. + * @serial + */ + private String authority; + + /** + * The path part of this URL. + */ + private transient String path; + + /** + * The userinfo part of this URL. + */ + private transient String userInfo; + + /** + * # reference. + * @serial + */ + private String ref; + + /** + * The host's IP address, used in equals and hashCode. + * Computed on demand. An uninitialized or unknown hostAddress is null. + */ + transient Object hostAddress; + + /** + * The URLStreamHandler for this URL. + */ + transient URLStreamHandler handler; + + /* Our hash code. + * @serial + */ + private int hashCode = -1; + + /** + * Creates a URL object from the specified + * protocol, host, port + * number, and file.

+ * + * host can be expressed as a host name or a literal + * IP address. If IPv6 literal address is used, it should be + * enclosed in square brackets ('[' and ']'), as + * specified by RFC 2732; + * However, the literal IPv6 address format defined in RFC 2373: IP + * Version 6 Addressing Architecture is also accepted.

+ * + * Specifying a port number of -1 + * indicates that the URL should use the default port for the + * protocol.

+ * + * If this is the first URL object being created with the specified + * protocol, a stream protocol handler object, an instance of + * class URLStreamHandler, is created for that protocol: + *

    + *
  1. If the application has previously set up an instance of + * URLStreamHandlerFactory as the stream handler factory, + * then the createURLStreamHandler method of that instance + * is called with the protocol string as an argument to create the + * stream protocol handler. + *
  2. If no URLStreamHandlerFactory has yet been set up, + * or if the factory's createURLStreamHandler method + * returns null, then the constructor finds the + * value of the system property: + *
    +     *         java.protocol.handler.pkgs
    +     *     
    + * If the value of that system property is not null, + * it is interpreted as a list of packages separated by a vertical + * slash character '|'. The constructor tries to load + * the class named: + *
    +     *         <package>.<protocol>.Handler
    +     *     
    + * where <package> is replaced by the name of the package + * and <protocol> is replaced by the name of the protocol. + * If this class does not exist, or if the class exists but it is not + * a subclass of URLStreamHandler, then the next package + * in the list is tried. + *
  3. If the previous step fails to find a protocol handler, then the + * constructor tries to load from a system default package. + *
    +     *         <system default package>.<protocol>.Handler
    +     *     
    + * If this class does not exist, or if the class exists but it is not a + * subclass of URLStreamHandler, then a + * MalformedURLException is thrown. + *
+ * + *

Protocol handlers for the following protocols are guaranteed + * to exist on the search path :- + *

+     *     http, https, ftp, file, and jar
+     * 
+ * Protocol handlers for additional protocols may also be + * available. + * + *

No validation of the inputs is performed by this constructor. + * + * @param protocol the name of the protocol to use. + * @param host the name of the host. + * @param port the port number on the host. + * @param file the file on the host + * @exception MalformedURLException if an unknown protocol is specified. + * @see java.lang.System#getProperty(java.lang.String) + * @see java.net.URL#setURLStreamHandlerFactory( + * java.net.URLStreamHandlerFactory) + * @see java.net.URLStreamHandler + * @see java.net.URLStreamHandlerFactory#createURLStreamHandler( + * java.lang.String) + */ + public URL(String protocol, String host, int port, String file) + throws MalformedURLException + { + this(protocol, host, port, file, null); + } + + /** + * Creates a URL from the specified protocol + * name, host name, and file name. The + * default port for the specified protocol is used. + *

+ * This method is equivalent to calling the four-argument + * constructor with the arguments being protocol, + * host, -1, and file. + * + * No validation of the inputs is performed by this constructor. + * + * @param protocol the name of the protocol to use. + * @param host the name of the host. + * @param file the file on the host. + * @exception MalformedURLException if an unknown protocol is specified. + * @see java.net.URL#URL(java.lang.String, java.lang.String, + * int, java.lang.String) + */ + public URL(String protocol, String host, String file) + throws MalformedURLException { + this(protocol, host, -1, file); + } + + /** + * Creates a URL object from the specified + * protocol, host, port + * number, file, and handler. Specifying + * a port number of -1 indicates that + * the URL should use the default port for the protocol. Specifying + * a handler of null indicates that the URL + * should use a default stream handler for the protocol, as outlined + * for: + * java.net.URL#URL(java.lang.String, java.lang.String, int, + * java.lang.String) + * + *

If the handler is not null and there is a security manager, + * the security manager's checkPermission + * method is called with a + * NetPermission("specifyStreamHandler") permission. + * This may result in a SecurityException. + * + * No validation of the inputs is performed by this constructor. + * + * @param protocol the name of the protocol to use. + * @param host the name of the host. + * @param port the port number on the host. + * @param file the file on the host + * @param handler the stream handler for the URL. + * @exception MalformedURLException if an unknown protocol is specified. + * @exception SecurityException + * if a security manager exists and its + * checkPermission method doesn't allow + * specifying a stream handler explicitly. + * @see java.lang.System#getProperty(java.lang.String) + * @see java.net.URL#setURLStreamHandlerFactory( + * java.net.URLStreamHandlerFactory) + * @see java.net.URLStreamHandler + * @see java.net.URLStreamHandlerFactory#createURLStreamHandler( + * java.lang.String) + * @see SecurityManager#checkPermission + * @see java.net.NetPermission + */ + public URL(String protocol, String host, int port, String file, + URLStreamHandler handler) throws MalformedURLException { + if (handler != null) { + throw new SecurityException(); + } + + protocol = protocol.toLowerCase(); + this.protocol = protocol; + if (host != null) { + + /** + * if host is a literal IPv6 address, + * we will make it conform to RFC 2732 + */ + if (host.indexOf(':') >= 0 && !host.startsWith("[")) { + host = "["+host+"]"; + } + this.host = host; + + if (port < -1) { + throw new MalformedURLException("Invalid port number :" + + port); + } + this.port = port; + authority = (port == -1) ? host : host + ":" + port; + } + + Parts parts = new Parts(file); + path = parts.getPath(); + query = parts.getQuery(); + + if (query != null) { + this.file = path + "?" + query; + } else { + this.file = path; + } + ref = parts.getRef(); + + // Note: we don't do validation of the URL here. Too risky to change + // right now, but worth considering for future reference. -br + if (handler == null && + (handler = getURLStreamHandler(protocol)) == null) { + throw new MalformedURLException("unknown protocol: " + protocol); + } + this.handler = handler; + } + + /** + * Creates a URL object from the String + * representation. + *

+ * This constructor is equivalent to a call to the two-argument + * constructor with a null first argument. + * + * @param spec the String to parse as a URL. + * @exception MalformedURLException if no protocol is specified, or an + * unknown protocol is found, or spec is null. + * @see java.net.URL#URL(java.net.URL, java.lang.String) + */ + public URL(String spec) throws MalformedURLException { + this(null, spec); + } + + /** + * Creates a URL by parsing the given spec within a specified context. + * + * The new URL is created from the given context URL and the spec + * argument as described in + * RFC2396 "Uniform Resource Identifiers : Generic * Syntax" : + *

+     *          <scheme>://<authority><path>?<query>#<fragment>
+     * 
+ * The reference is parsed into the scheme, authority, path, query and + * fragment parts. If the path component is empty and the scheme, + * authority, and query components are undefined, then the new URL is a + * reference to the current document. Otherwise, the fragment and query + * parts present in the spec are used in the new URL. + *

+ * If the scheme component is defined in the given spec and does not match + * the scheme of the context, then the new URL is created as an absolute + * URL based on the spec alone. Otherwise the scheme component is inherited + * from the context URL. + *

+ * If the authority component is present in the spec then the spec is + * treated as absolute and the spec authority and path will replace the + * context authority and path. If the authority component is absent in the + * spec then the authority of the new URL will be inherited from the + * context. + *

+ * If the spec's path component begins with a slash character + * "/" then the + * path is treated as absolute and the spec path replaces the context path. + *

+ * Otherwise, the path is treated as a relative path and is appended to the + * context path, as described in RFC2396. Also, in this case, + * the path is canonicalized through the removal of directory + * changes made by occurences of ".." and ".". + *

+ * For a more detailed description of URL parsing, refer to RFC2396. + * + * @param context the context in which to parse the specification. + * @param spec the String to parse as a URL. + * @exception MalformedURLException if no protocol is specified, or an + * unknown protocol is found, or spec is null. + * @see java.net.URL#URL(java.lang.String, java.lang.String, + * int, java.lang.String) + * @see java.net.URLStreamHandler + * @see java.net.URLStreamHandler#parseURL(java.net.URL, + * java.lang.String, int, int) + */ + public URL(URL context, String spec) throws MalformedURLException { + this(context, spec, null); + } + + /** + * Creates a URL by parsing the given spec with the specified handler + * within a specified context. If the handler is null, the parsing + * occurs as with the two argument constructor. + * + * @param context the context in which to parse the specification. + * @param spec the String to parse as a URL. + * @param handler the stream handler for the URL. + * @exception MalformedURLException if no protocol is specified, or an + * unknown protocol is found, or spec is null. + * @exception SecurityException + * if a security manager exists and its + * checkPermission method doesn't allow + * specifying a stream handler. + * @see java.net.URL#URL(java.lang.String, java.lang.String, + * int, java.lang.String) + * @see java.net.URLStreamHandler + * @see java.net.URLStreamHandler#parseURL(java.net.URL, + * java.lang.String, int, int) + */ + public URL(URL context, String spec, URLStreamHandler handler) + throws MalformedURLException + { + String original = spec; + int i, limit, c; + int start = 0; + String newProtocol = null; + boolean aRef=false; + boolean isRelative = false; + + // Check for permission to specify a handler + if (handler != null) { + throw new SecurityException(); + } + + try { + limit = spec.length(); + while ((limit > 0) && (spec.charAt(limit - 1) <= ' ')) { + limit--; //eliminate trailing whitespace + } + while ((start < limit) && (spec.charAt(start) <= ' ')) { + start++; // eliminate leading whitespace + } + + if (spec.regionMatches(true, start, "url:", 0, 4)) { + start += 4; + } + if (start < spec.length() && spec.charAt(start) == '#') { + /* we're assuming this is a ref relative to the context URL. + * This means protocols cannot start w/ '#', but we must parse + * ref URL's like: "hello:there" w/ a ':' in them. + */ + aRef=true; + } + for (i = start ; !aRef && (i < limit) && + ((c = spec.charAt(i)) != '/') ; i++) { + if (c == ':') { + + String s = spec.substring(start, i).toLowerCase(); + if (isValidProtocol(s)) { + newProtocol = s; + start = i + 1; + } + break; + } + } + + // Only use our context if the protocols match. + protocol = newProtocol; + if ((context != null) && ((newProtocol == null) || + newProtocol.equalsIgnoreCase(context.protocol))) { + // inherit the protocol handler from the context + // if not specified to the constructor + if (handler == null) { + handler = context.handler; + } + + // If the context is a hierarchical URL scheme and the spec + // contains a matching scheme then maintain backwards + // compatibility and treat it as if the spec didn't contain + // the scheme; see 5.2.3 of RFC2396 + if (context.path != null && context.path.startsWith("/")) + newProtocol = null; + + if (newProtocol == null) { + protocol = context.protocol; + authority = context.authority; + userInfo = context.userInfo; + host = context.host; + port = context.port; + file = context.file; + path = context.path; + isRelative = true; + } + } + + if (protocol == null) { + throw new MalformedURLException("no protocol: "+original); + } + + // Get the protocol handler if not specified or the protocol + // of the context could not be used + if (handler == null && + (handler = getURLStreamHandler(protocol)) == null) { + throw new MalformedURLException("unknown protocol: "+protocol); + } + this.handler = handler; + + i = spec.indexOf('#', start); + if (i >= 0) { +//thrw(protocol + " hnd: " + handler.getClass().getName() + " i: " + i); + ref = spec.substring(i + 1, limit); + limit = i; + } + + /* + * Handle special case inheritance of query and fragment + * implied by RFC2396 section 5.2.2. + */ + if (isRelative && start == limit) { + query = context.query; + if (ref == null) { + ref = context.ref; + } + } + + handler.parseURL(this, spec, start, limit); + + } catch(MalformedURLException e) { + throw e; + } catch(Exception e) { + MalformedURLException exception = new MalformedURLException(e.getMessage()); + exception.initCause(e); + throw exception; + } + } + + /* + * Returns true if specified string is a valid protocol name. + */ + private boolean isValidProtocol(String protocol) { + int len = protocol.length(); + if (len < 1) + return false; + char c = protocol.charAt(0); + if (!Character.isLetter(c)) + return false; + for (int i = 1; i < len; i++) { + c = protocol.charAt(i); + if (!Character.isLetterOrDigit(c) && c != '.' && c != '+' && + c != '-') { + return false; + } + } + return true; + } + + /** + * Sets the fields of the URL. This is not a public method so that + * only URLStreamHandlers can modify URL fields. URLs are + * otherwise constant. + * + * @param protocol the name of the protocol to use + * @param host the name of the host + @param port the port number on the host + * @param file the file on the host + * @param ref the internal reference in the URL + */ + protected void set(String protocol, String host, + int port, String file, String ref) { + synchronized (this) { + this.protocol = protocol; + this.host = host; + authority = port == -1 ? host : host + ":" + port; + this.port = port; + this.file = file; + this.ref = ref; + /* This is very important. We must recompute this after the + * URL has been changed. */ + hashCode = -1; + hostAddress = null; + int q = file.lastIndexOf('?'); + if (q != -1) { + query = file.substring(q+1); + path = file.substring(0, q); + } else + path = file; + } + } + + /** + * Sets the specified 8 fields of the URL. This is not a public method so + * that only URLStreamHandlers can modify URL fields. URLs are otherwise + * constant. + * + * @param protocol the name of the protocol to use + * @param host the name of the host + * @param port the port number on the host + * @param authority the authority part for the url + * @param userInfo the username and password + * @param path the file on the host + * @param ref the internal reference in the URL + * @param query the query part of this URL + * @since 1.3 + */ + protected void set(String protocol, String host, int port, + String authority, String userInfo, String path, + String query, String ref) { + synchronized (this) { + this.protocol = protocol; + this.host = host; + this.port = port; + this.file = query == null ? path : path + "?" + query; + this.userInfo = userInfo; + this.path = path; + this.ref = ref; + /* This is very important. We must recompute this after the + * URL has been changed. */ + hashCode = -1; + hostAddress = null; + this.query = query; + this.authority = authority; + } + } + + /** + * Gets the query part of this URL. + * + * @return the query part of this URL, + * or null if one does not exist + * @since 1.3 + */ + public String getQuery() { + return query; + } + + /** + * Gets the path part of this URL. + * + * @return the path part of this URL, or an + * empty string if one does not exist + * @since 1.3 + */ + public String getPath() { + return path; + } + + /** + * Gets the userInfo part of this URL. + * + * @return the userInfo part of this URL, or + * null if one does not exist + * @since 1.3 + */ + public String getUserInfo() { + return userInfo; + } + + /** + * Gets the authority part of this URL. + * + * @return the authority part of this URL + * @since 1.3 + */ + public String getAuthority() { + return authority; + } + + /** + * Gets the port number of this URL. + * + * @return the port number, or -1 if the port is not set + */ + public int getPort() { + return port; + } + + /** + * Gets the default port number of the protocol associated + * with this URL. If the URL scheme or the URLStreamHandler + * for the URL do not define a default port number, + * then -1 is returned. + * + * @return the port number + * @since 1.4 + */ + public int getDefaultPort() { + return handler.getDefaultPort(); + } + + /** + * Gets the protocol name of this URL. + * + * @return the protocol of this URL. + */ + public String getProtocol() { + return protocol; + } + + /** + * Gets the host name of this URL, if applicable. + * The format of the host conforms to RFC 2732, i.e. for a + * literal IPv6 address, this method will return the IPv6 address + * enclosed in square brackets ('[' and ']'). + * + * @return the host name of this URL. + */ + public String getHost() { + return host; + } + + /** + * Gets the file name of this URL. + * The returned file portion will be + * the same as getPath(), plus the concatenation of + * the value of getQuery(), if any. If there is + * no query portion, this method and getPath() will + * return identical results. + * + * @return the file name of this URL, + * or an empty string if one does not exist + */ + public String getFile() { + return file; + } + + /** + * Gets the anchor (also known as the "reference") of this + * URL. + * + * @return the anchor (also known as the "reference") of this + * URL, or null if one does not exist + */ + public String getRef() { + return ref; + } + + /** + * Compares this URL for equality with another object.

+ * + * If the given object is not a URL then this method immediately returns + * false.

+ * + * Two URL objects are equal if they have the same protocol, reference + * equivalent hosts, have the same port number on the host, and the same + * file and fragment of the file.

+ * + * Two hosts are considered equivalent if both host names can be resolved + * into the same IP addresses; else if either host name can't be + * resolved, the host names must be equal without regard to case; or both + * host names equal to null.

+ * + * Since hosts comparison requires name resolution, this operation is a + * blocking operation.

+ * + * Note: The defined behavior for equals is known to + * be inconsistent with virtual hosting in HTTP. + * + * @param obj the URL to compare against. + * @return true if the objects are the same; + * false otherwise. + */ + public boolean equals(Object obj) { + if (!(obj instanceof URL)) + return false; + URL u2 = (URL)obj; + + return handler.equals(this, u2); + } + + /** + * Creates an integer suitable for hash table indexing.

+ * + * The hash code is based upon all the URL components relevant for URL + * comparison. As such, this operation is a blocking operation.

+ * + * @return a hash code for this URL. + */ + public synchronized int hashCode() { + if (hashCode != -1) + return hashCode; + + hashCode = handler.hashCode(this); + return hashCode; + } + + /** + * Compares two URLs, excluding the fragment component.

+ * + * Returns true if this URL and the + * other argument are equal without taking the + * fragment component into consideration. + * + * @param other the URL to compare against. + * @return true if they reference the same remote object; + * false otherwise. + */ + public boolean sameFile(URL other) { + return handler.sameFile(this, other); + } + + /** + * Constructs a string representation of this URL. The + * string is created by calling the toExternalForm + * method of the stream protocol handler for this object. + * + * @return a string representation of this object. + * @see java.net.URL#URL(java.lang.String, java.lang.String, int, + * java.lang.String) + * @see java.net.URLStreamHandler#toExternalForm(java.net.URL) + */ + public String toString() { + return toExternalForm(); + } + + /** + * Constructs a string representation of this URL. The + * string is created by calling the toExternalForm + * method of the stream protocol handler for this object. + * + * @return a string representation of this object. + * @see java.net.URL#URL(java.lang.String, java.lang.String, + * int, java.lang.String) + * @see java.net.URLStreamHandler#toExternalForm(java.net.URL) + */ + public String toExternalForm() { + return handler.toExternalForm(this); + } + + /** + * Returns a {@link java.net.URLConnection URLConnection} instance that + * represents a connection to the remote object referred to by the + * {@code URL}. + * + *

A new instance of {@linkplain java.net.URLConnection URLConnection} is + * created every time when invoking the + * {@linkplain java.net.URLStreamHandler#openConnection(URL) + * URLStreamHandler.openConnection(URL)} method of the protocol handler for + * this URL.

+ * + *

It should be noted that a URLConnection instance does not establish + * the actual network connection on creation. This will happen only when + * calling {@linkplain java.net.URLConnection#connect() URLConnection.connect()}.

+ * + *

If for the URL's protocol (such as HTTP or JAR), there + * exists a public, specialized URLConnection subclass belonging + * to one of the following packages or one of their subpackages: + * java.lang, java.io, java.util, java.net, the connection + * returned will be of that subclass. For example, for HTTP an + * HttpURLConnection will be returned, and for JAR a + * JarURLConnection will be returned.

+ * + * @return a {@link java.net.URLConnection URLConnection} linking + * to the URL. + * @exception IOException if an I/O exception occurs. + * @see java.net.URL#URL(java.lang.String, java.lang.String, + * int, java.lang.String) + */ +// public URLConnection openConnection() throws java.io.IOException { +// return handler.openConnection(this); +// } + + + /** + * Opens a connection to this URL and returns an + * InputStream for reading from that connection. This + * method is a shorthand for: + *
+     *     openConnection().getInputStream()
+     * 
+ * + * @return an input stream for reading from the URL connection. + * @exception IOException if an I/O exception occurs. + * @see java.net.URL#openConnection() + * @see java.net.URLConnection#getInputStream() + */ + public final InputStream openStream() throws java.io.IOException { + throw new IOException(); +// return openConnection().getInputStream(); + } + + /** + * Gets the contents of this URL. This method is a shorthand for: + *
+     *     openConnection().getContent()
+     * 
+ * + * @return the contents of this URL. + * @exception IOException if an I/O exception occurs. + * @see java.net.URLConnection#getContent() + */ + public final Object getContent() throws java.io.IOException { + return loadText(toExternalForm()); + } + + @JavaScriptBody(args = "url", body = "" + + "var request = new XMLHttpRequest();\n" + + "request.open('GET', url, false);\n" + + "request.send();\n" + + "return request.responseText;\n" + ) + private static native String loadText(String url) throws IOException; + + /** + * Gets the contents of this URL. This method is a shorthand for: + *
+     *     openConnection().getContent(Class[])
+     * 
+ * + * @param classes an array of Java types + * @return the content object of this URL that is the first match of + * the types specified in the classes array. + * null if none of the requested types are supported. + * @exception IOException if an I/O exception occurs. + * @see java.net.URLConnection#getContent(Class[]) + * @since 1.3 + */ + public final Object getContent(Class[] classes) + throws java.io.IOException { + for (Class c : classes) { + if (c == String.class) { + return getContent(); + } + } + return null; + } + + static URLStreamHandler getURLStreamHandler(String protocol) { + URLStreamHandler universal = new URLStreamHandler() {}; + return universal; + } + +} + +class Parts { + String path, query, ref; + + Parts(String file) { + int ind = file.indexOf('#'); + ref = ind < 0 ? null: file.substring(ind + 1); + file = ind < 0 ? file: file.substring(0, ind); + int q = file.lastIndexOf('?'); + if (q != -1) { + query = file.substring(q+1); + path = file.substring(0, q); + } else { + path = file; + } + } + + String getPath() { + return path; + } + + String getQuery() { + return query; + } + + String getRef() { + return ref; + } +} diff -r 388e48c0a37a -r 05224402145d emul/mini/src/main/java/java/net/URLStreamHandler.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/emul/mini/src/main/java/java/net/URLStreamHandler.java Wed Jan 23 20:39:23 2013 +0100 @@ -0,0 +1,568 @@ +/* + * Copyright (c) 1995, 2006, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code 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 + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package java.net; + + +/** + * The abstract class URLStreamHandler is the common + * superclass for all stream protocol handlers. A stream protocol + * handler knows how to make a connection for a particular protocol + * type, such as http, ftp, or + * gopher. + *

+ * In most cases, an instance of a URLStreamHandler + * subclass is not created directly by an application. Rather, the + * first time a protocol name is encountered when constructing a + * URL, the appropriate stream protocol handler is + * automatically loaded. + * + * @author James Gosling + * @see java.net.URL#URL(java.lang.String, java.lang.String, int, java.lang.String) + * @since JDK1.0 + */ +public abstract class URLStreamHandler { + /** + * Opens a connection to the object referenced by the + * URL argument. + * This method should be overridden by a subclass. + * + *

If for the handler's protocol (such as HTTP or JAR), there + * exists a public, specialized URLConnection subclass belonging + * to one of the following packages or one of their subpackages: + * java.lang, java.io, java.util, java.net, the connection + * returned will be of that subclass. For example, for HTTP an + * HttpURLConnection will be returned, and for JAR a + * JarURLConnection will be returned. + * + * @param u the URL that this connects to. + * @return a URLConnection object for the URL. + * @exception IOException if an I/O error occurs while opening the + * connection. + */ +// abstract protected URLConnection openConnection(URL u) throws IOException; + + /** + * Same as openConnection(URL), except that the connection will be + * made through the specified proxy; Protocol handlers that do not + * support proxying will ignore the proxy parameter and make a + * normal connection. + * + * Calling this method preempts the system's default ProxySelector + * settings. + * + * @param u the URL that this connects to. + * @param p the proxy through which the connection will be made. + * If direct connection is desired, Proxy.NO_PROXY + * should be specified. + * @return a URLConnection object for the URL. + * @exception IOException if an I/O error occurs while opening the + * connection. + * @exception IllegalArgumentException if either u or p is null, + * or p has the wrong type. + * @exception UnsupportedOperationException if the subclass that + * implements the protocol doesn't support this method. + * @since 1.5 + */ +// protected URLConnection openConnection(URL u, Proxy p) throws IOException { +// throw new UnsupportedOperationException("Method not implemented."); +// } + + /** + * Parses the string representation of a URL into a + * URL object. + *

+ * If there is any inherited context, then it has already been + * copied into the URL argument. + *

+ * The parseURL method of URLStreamHandler + * parses the string representation as if it were an + * http specification. Most URL protocol families have a + * similar parsing. A stream protocol handler for a protocol that has + * a different syntax must override this routine. + * + * @param u the URL to receive the result of parsing + * the spec. + * @param spec the String representing the URL that + * must be parsed. + * @param start the character index at which to begin parsing. This is + * just past the ':' (if there is one) that + * specifies the determination of the protocol name. + * @param limit the character position to stop parsing at. This is the + * end of the string or the position of the + * "#" character, if present. All information + * after the sharp sign indicates an anchor. + */ + protected void parseURL(URL u, String spec, int start, int limit) { + // These fields may receive context content if this was relative URL + String protocol = u.getProtocol(); + String authority = u.getAuthority(); + String userInfo = u.getUserInfo(); + String host = u.getHost(); + int port = u.getPort(); + String path = u.getPath(); + String query = u.getQuery(); + + // This field has already been parsed + String ref = u.getRef(); + + boolean isRelPath = false; + boolean queryOnly = false; + +// FIX: should not assume query if opaque + // Strip off the query part + if (start < limit) { + int queryStart = spec.indexOf('?'); + queryOnly = queryStart == start; + if ((queryStart != -1) && (queryStart < limit)) { + query = spec.substring(queryStart+1, limit); + if (limit > queryStart) + limit = queryStart; + spec = spec.substring(0, queryStart); + } + } + + int i = 0; + // Parse the authority part if any + boolean isUNCName = (start <= limit - 4) && + (spec.charAt(start) == '/') && + (spec.charAt(start + 1) == '/') && + (spec.charAt(start + 2) == '/') && + (spec.charAt(start + 3) == '/'); + if (!isUNCName && (start <= limit - 2) && (spec.charAt(start) == '/') && + (spec.charAt(start + 1) == '/')) { + start += 2; + i = spec.indexOf('/', start); + if (i < 0) { + i = spec.indexOf('?', start); + if (i < 0) + i = limit; + } + + host = authority = spec.substring(start, i); + + int ind = authority.indexOf('@'); + if (ind != -1) { + userInfo = authority.substring(0, ind); + host = authority.substring(ind+1); + } else { + userInfo = null; + } + if (host != null) { + // If the host is surrounded by [ and ] then its an IPv6 + // literal address as specified in RFC2732 + if (host.length()>0 && (host.charAt(0) == '[')) { + if ((ind = host.indexOf(']')) > 2) { + + String nhost = host ; + host = nhost.substring(0,ind+1); +// if (!IPAddressUtil. +// isIPv6LiteralAddress(host.substring(1, ind))) { +// throw new IllegalArgumentException( +// "Invalid host: "+ host); +// } + + port = -1 ; + if (nhost.length() > ind+1) { + if (nhost.charAt(ind+1) == ':') { + ++ind ; + // port can be null according to RFC2396 + if (nhost.length() > (ind + 1)) { + port = Integer.parseInt(nhost.substring(ind+1)); + } + } else { + throw new IllegalArgumentException( + "Invalid authority field: " + authority); + } + } + } else { + throw new IllegalArgumentException( + "Invalid authority field: " + authority); + } + } else { + ind = host.indexOf(':'); + port = -1; + if (ind >= 0) { + // port can be null according to RFC2396 + if (host.length() > (ind + 1)) { + port = Integer.parseInt(host.substring(ind + 1)); + } + host = host.substring(0, ind); + } + } + } else { + host = ""; + } + if (port < -1) + throw new IllegalArgumentException("Invalid port number :" + + port); + start = i; + // If the authority is defined then the path is defined by the + // spec only; See RFC 2396 Section 5.2.4. + if (authority != null && authority.length() > 0) + path = ""; + } + + if (host == null) { + host = ""; + } + + // Parse the file path if any + if (start < limit) { + if (spec.charAt(start) == '/') { + path = spec.substring(start, limit); + } else if (path != null && path.length() > 0) { + isRelPath = true; + int ind = path.lastIndexOf('/'); + String seperator = ""; + if (ind == -1 && authority != null) + seperator = "/"; + path = path.substring(0, ind + 1) + seperator + + spec.substring(start, limit); + + } else { + String seperator = (authority != null) ? "/" : ""; + path = seperator + spec.substring(start, limit); + } + } else if (queryOnly && path != null) { + int ind = path.lastIndexOf('/'); + if (ind < 0) + ind = 0; + path = path.substring(0, ind) + "/"; + } + if (path == null) + path = ""; + + if (isRelPath) { + // Remove embedded /./ + while ((i = path.indexOf("/./")) >= 0) { + path = path.substring(0, i) + path.substring(i + 2); + } + // Remove embedded /../ if possible + i = 0; + while ((i = path.indexOf("/../", i)) >= 0) { + /* + * A "/../" will cancel the previous segment and itself, + * unless that segment is a "/../" itself + * i.e. "/a/b/../c" becomes "/a/c" + * but "/../../a" should stay unchanged + */ + if (i > 0 && (limit = path.lastIndexOf('/', i - 1)) >= 0 && + (path.indexOf("/../", limit) != 0)) { + path = path.substring(0, limit) + path.substring(i + 3); + i = 0; + } else { + i = i + 3; + } + } + // Remove trailing .. if possible + while (path.endsWith("/..")) { + i = path.indexOf("/.."); + if ((limit = path.lastIndexOf('/', i - 1)) >= 0) { + path = path.substring(0, limit+1); + } else { + break; + } + } + // Remove starting . + if (path.startsWith("./") && path.length() > 2) + path = path.substring(2); + + // Remove trailing . + if (path.endsWith("/.")) + path = path.substring(0, path.length() -1); + } + + setURL(u, protocol, host, port, authority, userInfo, path, query, ref); + } + + /** + * Returns the default port for a URL parsed by this handler. This method + * is meant to be overidden by handlers with default port numbers. + * @return the default port for a URL parsed by this handler. + * @since 1.3 + */ + protected int getDefaultPort() { + return -1; + } + + /** + * Provides the default equals calculation. May be overidden by handlers + * for other protocols that have different requirements for equals(). + * This method requires that none of its arguments is null. This is + * guaranteed by the fact that it is only called by java.net.URL class. + * @param u1 a URL object + * @param u2 a URL object + * @return true if the two urls are + * considered equal, ie. they refer to the same + * fragment in the same file. + * @since 1.3 + */ + protected boolean equals(URL u1, URL u2) { + String ref1 = u1.getRef(); + String ref2 = u2.getRef(); + return (ref1 == ref2 || (ref1 != null && ref1.equals(ref2))) && + sameFile(u1, u2); + } + + /** + * Provides the default hash calculation. May be overidden by handlers for + * other protocols that have different requirements for hashCode + * calculation. + * @param u a URL object + * @return an int suitable for hash table indexing + * @since 1.3 + */ + protected int hashCode(URL u) { + int h = 0; + + // Generate the protocol part. + String protocol = u.getProtocol(); + if (protocol != null) + h += protocol.hashCode(); + + // Generate the host part. + Object addr = getHostAddress(u); + if (addr != null) { + h += addr.hashCode(); + } else { + String host = u.getHost(); + if (host != null) + h += host.toLowerCase().hashCode(); + } + + // Generate the file part. + String file = u.getFile(); + if (file != null) + h += file.hashCode(); + + // Generate the port part. + if (u.getPort() == -1) + h += getDefaultPort(); + else + h += u.getPort(); + + // Generate the ref part. + String ref = u.getRef(); + if (ref != null) + h += ref.hashCode(); + + return h; + } + + /** + * Compare two urls to see whether they refer to the same file, + * i.e., having the same protocol, host, port, and path. + * This method requires that none of its arguments is null. This is + * guaranteed by the fact that it is only called indirectly + * by java.net.URL class. + * @param u1 a URL object + * @param u2 a URL object + * @return true if u1 and u2 refer to the same file + * @since 1.3 + */ + protected boolean sameFile(URL u1, URL u2) { + // Compare the protocols. + if (!((u1.getProtocol() == u2.getProtocol()) || + (u1.getProtocol() != null && + u1.getProtocol().equalsIgnoreCase(u2.getProtocol())))) + return false; + + // Compare the files. + if (!(u1.getFile() == u2.getFile() || + (u1.getFile() != null && u1.getFile().equals(u2.getFile())))) + return false; + + // Compare the ports. + int port1, port2; + port1 = (u1.getPort() != -1) ? u1.getPort() : u1.handler.getDefaultPort(); + port2 = (u2.getPort() != -1) ? u2.getPort() : u2.handler.getDefaultPort(); + if (port1 != port2) + return false; + + // Compare the hosts. + if (!hostsEqual(u1, u2)) + return false; + + return true; + } + + /** + * Get the IP address of our host. An empty host field or a DNS failure + * will result in a null return. + * + * @param u a URL object + * @return an InetAddress representing the host + * IP address. + * @since 1.3 + */ + private synchronized Object getHostAddress(URL u) { + return u.hostAddress; + } + + /** + * Compares the host components of two URLs. + * @param u1 the URL of the first host to compare + * @param u2 the URL of the second host to compare + * @return true if and only if they + * are equal, false otherwise. + * @since 1.3 + */ + protected boolean hostsEqual(URL u1, URL u2) { + Object a1 = getHostAddress(u1); + Object a2 = getHostAddress(u2); + // if we have internet address for both, compare them + if (a1 != null && a2 != null) { + return a1.equals(a2); + // else, if both have host names, compare them + } else if (u1.getHost() != null && u2.getHost() != null) + return u1.getHost().equalsIgnoreCase(u2.getHost()); + else + return u1.getHost() == null && u2.getHost() == null; + } + + /** + * Converts a URL of a specific protocol to a + * String. + * + * @param u the URL. + * @return a string representation of the URL argument. + */ + protected String toExternalForm(URL u) { + + // pre-compute length of StringBuffer + int len = u.getProtocol().length() + 1; + if (u.getAuthority() != null && u.getAuthority().length() > 0) + len += 2 + u.getAuthority().length(); + if (u.getPath() != null) { + len += u.getPath().length(); + } + if (u.getQuery() != null) { + len += 1 + u.getQuery().length(); + } + if (u.getRef() != null) + len += 1 + u.getRef().length(); + + StringBuffer result = new StringBuffer(len); + result.append(u.getProtocol()); + result.append(":"); + if (u.getAuthority() != null && u.getAuthority().length() > 0) { + result.append("//"); + result.append(u.getAuthority()); + } + if (u.getPath() != null) { + result.append(u.getPath()); + } + if (u.getQuery() != null) { + result.append('?'); + result.append(u.getQuery()); + } + if (u.getRef() != null) { + result.append("#"); + result.append(u.getRef()); + } + return result.toString(); + } + + /** + * Sets the fields of the URL argument to the indicated values. + * Only classes derived from URLStreamHandler are supposed to be able + * to call the set method on a URL. + * + * @param u the URL to modify. + * @param protocol the protocol name. + * @param host the remote host value for the URL. + * @param port the port on the remote machine. + * @param authority the authority part for the URL. + * @param userInfo the userInfo part of the URL. + * @param path the path component of the URL. + * @param query the query part for the URL. + * @param ref the reference. + * @exception SecurityException if the protocol handler of the URL is + * different from this one + * @see java.net.URL#set(java.lang.String, java.lang.String, int, java.lang.String, java.lang.String) + * @since 1.3 + */ + protected void setURL(URL u, String protocol, String host, int port, + String authority, String userInfo, String path, + String query, String ref) { + if (this != u.handler) { + throw new SecurityException("handler for url different from " + + "this handler"); + } + // ensure that no one can reset the protocol on a given URL. + u.set(u.getProtocol(), host, port, authority, userInfo, path, query, ref); + } + + /** + * Sets the fields of the URL argument to the indicated values. + * Only classes derived from URLStreamHandler are supposed to be able + * to call the set method on a URL. + * + * @param u the URL to modify. + * @param protocol the protocol name. This value is ignored since 1.2. + * @param host the remote host value for the URL. + * @param port the port on the remote machine. + * @param file the file. + * @param ref the reference. + * @exception SecurityException if the protocol handler of the URL is + * different from this one + * @deprecated Use setURL(URL, String, String, int, String, String, String, + * String); + */ + @Deprecated + protected void setURL(URL u, String protocol, String host, int port, + String file, String ref) { + /* + * Only old URL handlers call this, so assume that the host + * field might contain "user:passwd@host". Fix as necessary. + */ + String authority = null; + String userInfo = null; + if (host != null && host.length() != 0) { + authority = (port == -1) ? host : host + ":" + port; + int at = host.lastIndexOf('@'); + if (at != -1) { + userInfo = host.substring(0, at); + host = host.substring(at+1); + } + } + + /* + * Assume file might contain query part. Fix as necessary. + */ + String path = null; + String query = null; + if (file != null) { + int q = file.lastIndexOf('?'); + if (q != -1) { + query = file.substring(q+1); + path = file.substring(0, q); + } else + path = file; + } + setURL(u, protocol, host, port, authority, userInfo, path, query, ref); + } +} diff -r 388e48c0a37a -r 05224402145d emul/mini/src/main/java/java/util/Comparator.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/emul/mini/src/main/java/java/util/Comparator.java Wed Jan 23 20:39:23 2013 +0100 @@ -0,0 +1,168 @@ +/* + * Copyright (c) 1997, 2007, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code 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 + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package java.util; + +/** + * A comparison function, which imposes a total ordering on some + * collection of objects. Comparators can be passed to a sort method (such + * as {@link Collections#sort(List,Comparator) Collections.sort} or {@link + * Arrays#sort(Object[],Comparator) Arrays.sort}) to allow precise control + * over the sort order. Comparators can also be used to control the order of + * certain data structures (such as {@link SortedSet sorted sets} or {@link + * SortedMap sorted maps}), or to provide an ordering for collections of + * objects that don't have a {@link Comparable natural ordering}.

+ * + * The ordering imposed by a comparator c on a set of elements + * S is said to be consistent with equals if and only if + * c.compare(e1, e2)==0 has the same boolean value as + * e1.equals(e2) for every e1 and e2 in + * S.

+ * + * Caution should be exercised when using a comparator capable of imposing an + * ordering inconsistent with equals to order a sorted set (or sorted map). + * Suppose a sorted set (or sorted map) with an explicit comparator c + * is used with elements (or keys) drawn from a set S. If the + * ordering imposed by c on S is inconsistent with equals, + * the sorted set (or sorted map) will behave "strangely." In particular the + * sorted set (or sorted map) will violate the general contract for set (or + * map), which is defined in terms of equals.

+ * + * For example, suppose one adds two elements {@code a} and {@code b} such that + * {@code (a.equals(b) && c.compare(a, b) != 0)} + * to an empty {@code TreeSet} with comparator {@code c}. + * The second {@code add} operation will return + * true (and the size of the tree set will increase) because {@code a} and + * {@code b} are not equivalent from the tree set's perspective, even though + * this is contrary to the specification of the + * {@link Set#add Set.add} method.

+ * + * Note: It is generally a good idea for comparators to also implement + * java.io.Serializable, as they may be used as ordering methods in + * serializable data structures (like {@link TreeSet}, {@link TreeMap}). In + * order for the data structure to serialize successfully, the comparator (if + * provided) must implement Serializable.

+ * + * For the mathematically inclined, the relation that defines the + * imposed ordering that a given comparator c imposes on a + * given set of objects S is:

+ *       {(x, y) such that c.compare(x, y) <= 0}.
+ * 
The quotient for this total order is:
+ *       {(x, y) such that c.compare(x, y) == 0}.
+ * 
+ * + * It follows immediately from the contract for compare that the + * quotient is an equivalence relation on S, and that the + * imposed ordering is a total order on S. When we say that + * the ordering imposed by c on S is consistent with + * equals, we mean that the quotient for the ordering is the equivalence + * relation defined by the objects' {@link Object#equals(Object) + * equals(Object)} method(s):
+ *     {(x, y) such that x.equals(y)}. 
+ * + *

Unlike {@code Comparable}, a comparator may optionally permit + * comparison of null arguments, while maintaining the requirements for + * an equivalence relation. + * + *

This interface is a member of the + * + * Java Collections Framework. + * + * @param the type of objects that may be compared by this comparator + * + * @author Josh Bloch + * @author Neal Gafter + * @see Comparable + * @see java.io.Serializable + * @since 1.2 + */ + +public interface Comparator { + /** + * Compares its two arguments for order. Returns a negative integer, + * zero, or a positive integer as the first argument is less than, equal + * to, or greater than the second.

+ * + * In the foregoing description, the notation + * sgn(expression) designates the mathematical + * signum function, which is defined to return one of -1, + * 0, or 1 according to whether the value of + * expression is negative, zero or positive.

+ * + * The implementor must ensure that sgn(compare(x, y)) == + * -sgn(compare(y, x)) for all x and y. (This + * implies that compare(x, y) must throw an exception if and only + * if compare(y, x) throws an exception.)

+ * + * The implementor must also ensure that the relation is transitive: + * ((compare(x, y)>0) && (compare(y, z)>0)) implies + * compare(x, z)>0.

+ * + * Finally, the implementor must ensure that compare(x, y)==0 + * implies that sgn(compare(x, z))==sgn(compare(y, z)) for all + * z.

+ * + * It is generally the case, but not strictly required that + * (compare(x, y)==0) == (x.equals(y)). Generally speaking, + * any comparator that violates this condition should clearly indicate + * this fact. The recommended language is "Note: this comparator + * imposes orderings that are inconsistent with equals." + * + * @param o1 the first object to be compared. + * @param o2 the second object to be compared. + * @return a negative integer, zero, or a positive integer as the + * first argument is less than, equal to, or greater than the + * second. + * @throws NullPointerException if an argument is null and this + * comparator does not permit null arguments + * @throws ClassCastException if the arguments' types prevent them from + * being compared by this comparator. + */ + int compare(T o1, T o2); + + /** + * Indicates whether some other object is "equal to" this + * comparator. This method must obey the general contract of + * {@link Object#equals(Object)}. Additionally, this method can return + * true only if the specified object is also a comparator + * and it imposes the same ordering as this comparator. Thus, + * comp1.equals(comp2) implies that sgn(comp1.compare(o1, + * o2))==sgn(comp2.compare(o1, o2)) for every object reference + * o1 and o2.

+ * + * Note that it is always safe not to override + * Object.equals(Object). However, overriding this method may, + * in some cases, improve performance by allowing programs to determine + * that two distinct comparators impose the same order. + * + * @param obj the reference object with which to compare. + * @return true only if the specified object is also + * a comparator and it imposes the same ordering as this + * comparator. + * @see Object#equals(Object) + * @see Object#hashCode() + */ + boolean equals(Object obj); +} diff -r 388e48c0a37a -r 05224402145d emul/mini/src/main/java/java/util/Enumeration.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/emul/mini/src/main/java/java/util/Enumeration.java Wed Jan 23 20:39:23 2013 +0100 @@ -0,0 +1,79 @@ +/* + * Copyright (c) 1994, 2005, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code 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 + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package java.util; + +/** + * An object that implements the Enumeration interface generates a + * series of elements, one at a time. Successive calls to the + * nextElement method return successive elements of the + * series. + *

+ * For example, to print all elements of a Vector<E> v: + *

+ *   for (Enumeration<E> e = v.elements(); e.hasMoreElements();)
+ *       System.out.println(e.nextElement());
+ *

+ * Methods are provided to enumerate through the elements of a + * vector, the keys of a hashtable, and the values in a hashtable. + * Enumerations are also used to specify the input streams to a + * SequenceInputStream. + *

+ * NOTE: The functionality of this interface is duplicated by the Iterator + * interface. In addition, Iterator adds an optional remove operation, and + * has shorter method names. New implementations should consider using + * Iterator in preference to Enumeration. + * + * @see java.util.Iterator + * @see java.io.SequenceInputStream + * @see java.util.Enumeration#nextElement() + * @see java.util.Hashtable + * @see java.util.Hashtable#elements() + * @see java.util.Hashtable#keys() + * @see java.util.Vector + * @see java.util.Vector#elements() + * + * @author Lee Boynton + * @since JDK1.0 + */ +public interface Enumeration { + /** + * Tests if this enumeration contains more elements. + * + * @return true if and only if this enumeration object + * contains at least one more element to provide; + * false otherwise. + */ + boolean hasMoreElements(); + + /** + * Returns the next element of this enumeration if this enumeration + * object has at least one more element to provide. + * + * @return the next element of this enumeration. + * @exception NoSuchElementException if no more elements exist. + */ + E nextElement(); +} diff -r 388e48c0a37a -r 05224402145d emul/mini/src/main/java/java/util/NoSuchElementException.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/emul/mini/src/main/java/java/util/NoSuchElementException.java Wed Jan 23 20:39:23 2013 +0100 @@ -0,0 +1,60 @@ +/* + * Copyright (c) 1994, 2008, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code 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 + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package java.util; + +/** + * Thrown by the nextElement method of an + * Enumeration to indicate that there are no more + * elements in the enumeration. + * + * @author unascribed + * @see java.util.Enumeration + * @see java.util.Enumeration#nextElement() + * @since JDK1.0 + */ +public +class NoSuchElementException extends RuntimeException { + private static final long serialVersionUID = 6769829250639411880L; + + /** + * Constructs a NoSuchElementException with null + * as its error message string. + */ + public NoSuchElementException() { + super(); + } + + /** + * Constructs a NoSuchElementException, saving a reference + * to the error message string s for later retrieval by the + * getMessage method. + * + * @param s the detail message. + */ + public NoSuchElementException(String s) { + super(s); + } +} diff -r 388e48c0a37a -r 05224402145d emul/mini/src/main/java/org/apidesign/bck2brwsr/emul/AnnotationImpl.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/emul/mini/src/main/java/org/apidesign/bck2brwsr/emul/AnnotationImpl.java Wed Jan 23 20:39:23 2013 +0100 @@ -0,0 +1,81 @@ +/** + * Back 2 Browser Bytecode Translator + * Copyright (C) 2012 Jaroslav Tulach + * + * This program 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, version 2 of the License. + * + * This program 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 this program. Look for COPYING file in the top folder. + * If not, see http://opensource.org/licenses/GPL-2.0. + */ +package org.apidesign.bck2brwsr.emul; + +import java.lang.annotation.Annotation; +import org.apidesign.bck2brwsr.core.JavaScriptBody; + +/** + * + * @author Jaroslav Tulach + */ +public final class AnnotationImpl implements Annotation { + public Class annotationType() { + return getClass(); + } + + @JavaScriptBody(args = { "a", "n", "values" }, body = "" + + "function f(v, p) {\n" + + " var val = v;\n" + + " var prop = p;\n" + + " return function() {\n" + + " return val[prop];\n" + + " };\n" + + "}\n" + + "var props = Object.getOwnPropertyNames(values);\n" + + "for (var i = 0; i < props.length; i++) {\n" + + " var p = props[i];\n" + + " a[p] = new f(values, p);\n" + + "}\n" + + "a['$instOf_' + n] = true;\n" + + "return a;" + ) + private static T create(AnnotationImpl a, String n, Object values) { + return null; + } + public static T create(Class annoClass, Object values) { + return create(new AnnotationImpl(), annoClass.getName().replace('.', '_'), values); + } + + public static Annotation[] create(Object anno) { + String[] names = findNames(anno); + Annotation[] ret = new Annotation[names.length]; + for (int i = 0; i < names.length; i++) { + String n = names[i].substring(1, names[i].length() - 1).replace('/', '_'); + ret[i] = create(new AnnotationImpl(), n, findData(anno, names[i])); + } + return ret; + } + @JavaScriptBody(args = "anno", body = + "var arr = new Array();" + + "var props = Object.getOwnPropertyNames(anno);\n" + + "for (var i = 0; i < props.length; i++) {\n" + + " var p = props[i];\n" + + " arr.push(p);" + + "}" + + "return arr;" + ) + private static String[] findNames(Object anno) { + throw new UnsupportedOperationException(); + } + + @JavaScriptBody(args={ "anno", "p"}, body="return anno[p];") + private static Object findData(Object anno, String p) { + throw new UnsupportedOperationException(); + } +} diff -r 388e48c0a37a -r 05224402145d emul/mini/src/main/java/org/apidesign/bck2brwsr/emul/MethodImpl.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/emul/mini/src/main/java/org/apidesign/bck2brwsr/emul/MethodImpl.java Wed Jan 23 20:39:23 2013 +0100 @@ -0,0 +1,164 @@ +/* + * Copyright (c) 1996, 2006, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code 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 + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +package org.apidesign.bck2brwsr.emul; + +import java.lang.reflect.Method; +import java.util.Enumeration; +import org.apidesign.bck2brwsr.core.JavaScriptBody; + +/** Utilities to work on methods. + * + * @author Jaroslav Tulach + */ +public abstract class MethodImpl { + public static MethodImpl INSTANCE; + static { + try { + Class.forName(Method.class.getName()); + } catch (ClassNotFoundException ex) { + throw new IllegalStateException(ex); + } + } + + protected abstract Method create(Class declaringClass, String name, Object data, String sig); + + + // + // bck2brwsr implementation + // + + @JavaScriptBody(args = {"clazz", "prefix"}, + body = "" + + "var c = clazz.cnstr.prototype;" + + "var arr = new Array();\n" + + "for (m in c) {\n" + + " if (m.indexOf(prefix) === 0) {\n" + + " arr.push(m);\n" + + " arr.push(c[m]);\n" + + " }" + + "}\n" + + "return arr;") + private static native Object[] findMethodData( + Class clazz, String prefix); + + public static Method findMethod( + Class clazz, String name, Class... parameterTypes) { + Object[] data = findMethodData(clazz, name + "__"); + BIG: for (int i = 0; i < data.length; i += 2) { + String sig = ((String) data[0]).substring(name.length() + 2); + Method tmp = INSTANCE.create(clazz, name, data[1], sig); + Class[] tmpParms = tmp.getParameterTypes(); + if (parameterTypes.length != tmpParms.length) { + continue; + } + for (int j = 0; j < tmpParms.length; j++) { + if (!parameterTypes[j].equals(tmpParms[j])) { + continue BIG; + } + } + return tmp; + } + return null; + } + + public static Method[] findMethods(Class clazz, int mask) { + Object[] namesAndData = findMethodData(clazz, ""); + int cnt = 0; + for (int i = 0; i < namesAndData.length; i += 2) { + String sig = (String) namesAndData[i]; + Object data = namesAndData[i + 1]; + int middle = sig.indexOf("__"); + if (middle == -1) { + continue; + } + String name = sig.substring(0, middle); + sig = sig.substring(middle + 2); + final Method m = INSTANCE.create(clazz, name, data, sig); + if ((m.getModifiers() & mask) == 0) { + continue; + } + namesAndData[cnt++] = m; + } + Method[] arr = new Method[cnt]; + for (int i = 0; i < cnt; i++) { + arr[i] = (Method) namesAndData[i]; + } + return arr; + } + + public static int signatureElements(String sig) { + Enumeration en = signatureParser(sig); + int cnt = 0; + while (en.hasMoreElements()) { + en.nextElement(); + cnt++; + } + return cnt; + } + + public static Enumeration signatureParser(final String sig) { + class E implements Enumeration { + int pos; + + public boolean hasMoreElements() { + return pos < sig.length(); + } + + public Class nextElement() { + switch (sig.charAt(pos++)) { + case 'I': + return Integer.TYPE; + case 'J': + return Long.TYPE; + case 'D': + return Double.TYPE; + case 'F': + return Float.TYPE; + case 'B': + return Byte.TYPE; + case 'Z': + return Boolean.TYPE; + case 'S': + return Short.TYPE; + case 'V': + return Void.TYPE; + case 'C': + return Character.TYPE; + case 'L': + try { + int up = sig.indexOf("_2"); + String type = sig.substring(1, up); + pos = up + 2; + return Class.forName(type); + } catch (ClassNotFoundException ex) { + // should not happen + } + } + throw new UnsupportedOperationException(sig + " at " + pos); + } + } + return new E(); + } +} diff -r 388e48c0a37a -r 05224402145d emul/mini/src/main/resources/org/apidesign/vm4brwsr/emul/java_lang_Number.js --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/emul/mini/src/main/resources/org/apidesign/vm4brwsr/emul/java_lang_Number.js Wed Jan 23 20:39:23 2013 +0100 @@ -0,0 +1,9 @@ +// empty line needed here +Number.prototype.add32 = function(x) { return (this + x) | 0; }; +Number.prototype.sub32 = function(x) { return (this - x) | 0; }; +Number.prototype.mul32 = function(x) { + return (((this * (x >> 16)) << 16) + this * (x & 0xFFFF)) | 0; +}; + +Number.prototype.toInt8 = function() { return (this << 24) >> 24; }; +Number.prototype.toInt16 = function() { return (this << 16) >> 16; }; \ No newline at end of file diff -r 388e48c0a37a -r 05224402145d emul/mini/src/main/resources/org/apidesign/vm4brwsr/emul/java_lang_String.js --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/emul/mini/src/main/resources/org/apidesign/vm4brwsr/emul/java_lang_String.js Wed Jan 23 20:39:23 2013 +0100 @@ -0,0 +1,26 @@ +// initialize methods on arrays and String constants +vm.java_lang_reflect_Array(false); +vm.java_lang_String(false); + +Array.prototype.at = function(indx, value) { + if (indx < 0 || indx > this.length) { + var e = vm.java_lang_ArrayIndexOutOfBoundsException(true); + e.constructor.cons__VLjava_lang_String_2.call(e, indx.toString()); + throw e; + } + if (arguments.length === 2) { + this[indx] = value; + } + return this[indx]; +}; +Array.prototype.getClass__Ljava_lang_Class_2 = function() { + return vm.java_lang_Class(false).defineArray__Ljava_lang_Class_2Ljava_lang_String_2(this.jvmName); +}; +Array.prototype.clone__Ljava_lang_Object_2 = function() { + var s = this.length; + var ret = new Array(s); + for (var i = 0; i < s; i++) { + ret[i] = this[i]; + } + return ret; +}; diff -r 388e48c0a37a -r 05224402145d emul/pom.xml --- a/emul/pom.xml Wed Jan 23 20:16:48 2013 +0100 +++ b/emul/pom.xml Wed Jan 23 20:39:23 2013 +0100 @@ -1,42 +1,17 @@ - - + + 4.0.0 - org.apidesign bck2brwsr + org.apidesign. 0.3-SNAPSHOT org.apidesign.bck2brwsr - emul + emul.pom 0.3-SNAPSHOT - Java API Emulation - http://maven.apache.org - - UTF-8 - - - - org.apidesign.bck2brwsr - core - 0.3-SNAPSHOT - jar - - - - - - org.apache.maven.plugins - maven-compiler-plugin - 2.5.1 - - - non-existing - - 1.7 - 1.7 - - - - + pom + Emulation of Core Libraries + + mini + diff -r 388e48c0a37a -r 05224402145d emul/src/main/java/java/io/ByteArrayInputStream.java --- a/emul/src/main/java/java/io/ByteArrayInputStream.java Wed Jan 23 20:16:48 2013 +0100 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,283 +0,0 @@ -/* - * Copyright (c) 1994, 2010, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code 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 - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package java.io; - -/** - * A ByteArrayInputStream contains - * an internal buffer that contains bytes that - * may be read from the stream. An internal - * counter keeps track of the next byte to - * be supplied by the read method. - *

- * Closing a ByteArrayInputStream has no effect. The methods in - * this class can be called after the stream has been closed without - * generating an IOException. - * - * @author Arthur van Hoff - * @see java.io.StringBufferInputStream - * @since JDK1.0 - */ -public -class ByteArrayInputStream extends InputStream { - - /** - * An array of bytes that was provided - * by the creator of the stream. Elements buf[0] - * through buf[count-1] are the - * only bytes that can ever be read from the - * stream; element buf[pos] is - * the next byte to be read. - */ - protected byte buf[]; - - /** - * The index of the next character to read from the input stream buffer. - * This value should always be nonnegative - * and not larger than the value of count. - * The next byte to be read from the input stream buffer - * will be buf[pos]. - */ - protected int pos; - - /** - * The currently marked position in the stream. - * ByteArrayInputStream objects are marked at position zero by - * default when constructed. They may be marked at another - * position within the buffer by the mark() method. - * The current buffer position is set to this point by the - * reset() method. - *

- * If no mark has been set, then the value of mark is the offset - * passed to the constructor (or 0 if the offset was not supplied). - * - * @since JDK1.1 - */ - protected int mark = 0; - - /** - * The index one greater than the last valid character in the input - * stream buffer. - * This value should always be nonnegative - * and not larger than the length of buf. - * It is one greater than the position of - * the last byte within buf that - * can ever be read from the input stream buffer. - */ - protected int count; - - /** - * Creates a ByteArrayInputStream - * so that it uses buf as its - * buffer array. - * The buffer array is not copied. - * The initial value of pos - * is 0 and the initial value - * of count is the length of - * buf. - * - * @param buf the input buffer. - */ - public ByteArrayInputStream(byte buf[]) { - this.buf = buf; - this.pos = 0; - this.count = buf.length; - } - - /** - * Creates ByteArrayInputStream - * that uses buf as its - * buffer array. The initial value of pos - * is offset and the initial value - * of count is the minimum of offset+length - * and buf.length. - * The buffer array is not copied. The buffer's mark is - * set to the specified offset. - * - * @param buf the input buffer. - * @param offset the offset in the buffer of the first byte to read. - * @param length the maximum number of bytes to read from the buffer. - */ - public ByteArrayInputStream(byte buf[], int offset, int length) { - this.buf = buf; - this.pos = offset; - this.count = Math.min(offset + length, buf.length); - this.mark = offset; - } - - /** - * Reads the next byte of data from this input stream. The value - * byte is returned as an int in the range - * 0 to 255. If no byte is available - * because the end of the stream has been reached, the value - * -1 is returned. - *

- * This read method - * cannot block. - * - * @return the next byte of data, or -1 if the end of the - * stream has been reached. - */ - public synchronized int read() { - return (pos < count) ? (buf[pos++] & 0xff) : -1; - } - - /** - * Reads up to len bytes of data into an array of bytes - * from this input stream. - * If pos equals count, - * then -1 is returned to indicate - * end of file. Otherwise, the number k - * of bytes read is equal to the smaller of - * len and count-pos. - * If k is positive, then bytes - * buf[pos] through buf[pos+k-1] - * are copied into b[off] through - * b[off+k-1] in the manner performed - * by System.arraycopy. The - * value k is added into pos - * and k is returned. - *

- * This read method cannot block. - * - * @param b the buffer into which the data is read. - * @param off the start offset in the destination array b - * @param len the maximum number of bytes read. - * @return the total number of bytes read into the buffer, or - * -1 if there is no more data because the end of - * the stream has been reached. - * @exception NullPointerException If b is null. - * @exception IndexOutOfBoundsException If off is negative, - * len is negative, or len is greater than - * b.length - off - */ - public synchronized int read(byte b[], int off, int len) { - if (b == null) { - throw new NullPointerException(); - } else if (off < 0 || len < 0 || len > b.length - off) { - throw new IndexOutOfBoundsException(); - } - - if (pos >= count) { - return -1; - } - - int avail = count - pos; - if (len > avail) { - len = avail; - } - if (len <= 0) { - return 0; - } - PushbackInputStream.arraycopy(buf, pos, b, off, len); - pos += len; - return len; - } - - /** - * Skips n bytes of input from this input stream. Fewer - * bytes might be skipped if the end of the input stream is reached. - * The actual number k - * of bytes to be skipped is equal to the smaller - * of n and count-pos. - * The value k is added into pos - * and k is returned. - * - * @param n the number of bytes to be skipped. - * @return the actual number of bytes skipped. - */ - public synchronized long skip(long n) { - long k = count - pos; - if (n < k) { - k = n < 0 ? 0 : n; - } - - pos += k; - return k; - } - - /** - * Returns the number of remaining bytes that can be read (or skipped over) - * from this input stream. - *

- * The value returned is count - pos, - * which is the number of bytes remaining to be read from the input buffer. - * - * @return the number of remaining bytes that can be read (or skipped - * over) from this input stream without blocking. - */ - public synchronized int available() { - return count - pos; - } - - /** - * Tests if this InputStream supports mark/reset. The - * markSupported method of ByteArrayInputStream - * always returns true. - * - * @since JDK1.1 - */ - public boolean markSupported() { - return true; - } - - /** - * Set the current marked position in the stream. - * ByteArrayInputStream objects are marked at position zero by - * default when constructed. They may be marked at another - * position within the buffer by this method. - *

- * If no mark has been set, then the value of the mark is the - * offset passed to the constructor (or 0 if the offset was not - * supplied). - * - *

Note: The readAheadLimit for this class - * has no meaning. - * - * @since JDK1.1 - */ - public void mark(int readAheadLimit) { - mark = pos; - } - - /** - * Resets the buffer to the marked position. The marked position - * is 0 unless another position was marked or an offset was specified - * in the constructor. - */ - public synchronized void reset() { - pos = mark; - } - - /** - * Closing a ByteArrayInputStream has no effect. The methods in - * this class can be called after the stream has been closed without - * generating an IOException. - *

- */ - public void close() throws IOException { - } - -} diff -r 388e48c0a37a -r 05224402145d emul/src/main/java/java/io/Closeable.java --- a/emul/src/main/java/java/io/Closeable.java Wed Jan 23 20:16:48 2013 +0100 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,48 +0,0 @@ -/* - * Copyright (c) 2003, 2010, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code 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 - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package java.io; - -import java.io.IOException; - -/** - * A {@code Closeable} is a source or destination of data that can be closed. - * The close method is invoked to release resources that the object is - * holding (such as open files). - * - * @since 1.5 - */ - -public interface Closeable extends AutoCloseable { - - /** - * Closes this stream and releases any system resources associated - * with it. If the stream is already closed then invoking this - * method has no effect. - * - * @throws IOException if an I/O error occurs - */ - public void close() throws IOException; -} diff -r 388e48c0a37a -r 05224402145d emul/src/main/java/java/io/DataInput.java --- a/emul/src/main/java/java/io/DataInput.java Wed Jan 23 20:16:48 2013 +0100 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,635 +0,0 @@ -/* - * Copyright (c) 1995, 2006, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code 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 - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package java.io; - -/** - * The DataInput interface provides - * for reading bytes from a binary stream and - * reconstructing from them data in any of - * the Java primitive types. There is also - * a - * facility for reconstructing a String - * from data in - * modified UTF-8 - * format. - *

- * It is generally true of all the reading - * routines in this interface that if end of - * file is reached before the desired number - * of bytes has been read, an EOFException - * (which is a kind of IOException) - * is thrown. If any byte cannot be read for - * any reason other than end of file, an IOException - * other than EOFException is - * thrown. In particular, an IOException - * may be thrown if the input stream has been - * closed. - * - *

Modified UTF-8

- *

- * Implementations of the DataInput and DataOutput interfaces represent - * Unicode strings in a format that is a slight modification of UTF-8. - * (For information regarding the standard UTF-8 format, see section - * 3.9 Unicode Encoding Forms of The Unicode Standard, Version - * 4.0). - * Note that in the following tables, the most significant bit appears in the - * far left-hand column. - *

- * All characters in the range '\u0001' to - * '\u007F' are represented by a single byte: - * - *

- * - * - * - * - * - * - * - * - * - *
Bit Values
Byte 1 - * - * - * - *
0
- *
bits 6-0
- *
- *
- *
- * - *

- * The null character '\u0000' and characters in the - * range '\u0080' to '\u07FF' are - * represented by a pair of bytes: - * - *

- * - * - * - * - * - * - * - * - * - * - * - * - * - *
Bit Values
Byte 1 - * - * - * - *
1
- *
1
- *
0
- *
bits 10-6
- *
- *
Byte 2 - * - * - * - *
1
- *
0
- *
bits 5-0
- *
- *
- *
- * - *
- * char values in the range '\u0800' to - * '\uFFFF' are represented by three bytes: - * - *
- * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - *
Bit Values
Byte 1 - * - * - * - *
1
- *
1
- *
1
- *
0
- *
bits 15-12
- *
- *
Byte 2 - * - * - * - *
1
- *
0
- *
bits 11-6
- *
- *
Byte 3 - * - * - * - *
1
- *
0
- *
bits 5-0
- *
- *
- *
- * - *

- * The differences between this format and the - * standard UTF-8 format are the following: - *

    - *
  • The null byte '\u0000' is encoded in 2-byte format - * rather than 1-byte, so that the encoded strings never have - * embedded nulls. - *
  • Only the 1-byte, 2-byte, and 3-byte formats are used. - *
  • Supplementary characters - * are represented in the form of surrogate pairs. - *
- * @author Frank Yellin - * @see java.io.DataInputStream - * @see java.io.DataOutput - * @since JDK1.0 - */ -public -interface DataInput { - /** - * Reads some bytes from an input - * stream and stores them into the buffer - * array b. The number of bytes - * read is equal - * to the length of b. - *

- * This method blocks until one of the - * following conditions occurs:

- *

    - *
  • b.length - * bytes of input data are available, in which - * case a normal return is made. - * - *
  • End of - * file is detected, in which case an EOFException - * is thrown. - * - *
  • An I/O error occurs, in - * which case an IOException other - * than EOFException is thrown. - *
- *

- * If b is null, - * a NullPointerException is thrown. - * If b.length is zero, then - * no bytes are read. Otherwise, the first - * byte read is stored into element b[0], - * the next one into b[1], and - * so on. - * If an exception is thrown from - * this method, then it may be that some but - * not all bytes of b have been - * updated with data from the input stream. - * - * @param b the buffer into which the data is read. - * @exception EOFException if this stream reaches the end before reading - * all the bytes. - * @exception IOException if an I/O error occurs. - */ - void readFully(byte b[]) throws IOException; - - /** - * - * Reads len - * bytes from - * an input stream. - *

- * This method - * blocks until one of the following conditions - * occurs:

- *

    - *
  • len bytes - * of input data are available, in which case - * a normal return is made. - * - *
  • End of file - * is detected, in which case an EOFException - * is thrown. - * - *
  • An I/O error occurs, in - * which case an IOException other - * than EOFException is thrown. - *
- *

- * If b is null, - * a NullPointerException is thrown. - * If off is negative, or len - * is negative, or off+len is - * greater than the length of the array b, - * then an IndexOutOfBoundsException - * is thrown. - * If len is zero, - * then no bytes are read. Otherwise, the first - * byte read is stored into element b[off], - * the next one into b[off+1], - * and so on. The number of bytes read is, - * at most, equal to len. - * - * @param b the buffer into which the data is read. - * @param off an int specifying the offset into the data. - * @param len an int specifying the number of bytes to read. - * @exception EOFException if this stream reaches the end before reading - * all the bytes. - * @exception IOException if an I/O error occurs. - */ - void readFully(byte b[], int off, int len) throws IOException; - - /** - * Makes an attempt to skip over - * n bytes - * of data from the input - * stream, discarding the skipped bytes. However, - * it may skip - * over some smaller number of - * bytes, possibly zero. This may result from - * any of a - * number of conditions; reaching - * end of file before n bytes - * have been skipped is - * only one possibility. - * This method never throws an EOFException. - * The actual - * number of bytes skipped is returned. - * - * @param n the number of bytes to be skipped. - * @return the number of bytes actually skipped. - * @exception IOException if an I/O error occurs. - */ - int skipBytes(int n) throws IOException; - - /** - * Reads one input byte and returns - * true if that byte is nonzero, - * false if that byte is zero. - * This method is suitable for reading - * the byte written by the writeBoolean - * method of interface DataOutput. - * - * @return the boolean value read. - * @exception EOFException if this stream reaches the end before reading - * all the bytes. - * @exception IOException if an I/O error occurs. - */ - boolean readBoolean() throws IOException; - - /** - * Reads and returns one input byte. - * The byte is treated as a signed value in - * the range -128 through 127, - * inclusive. - * This method is suitable for - * reading the byte written by the writeByte - * method of interface DataOutput. - * - * @return the 8-bit value read. - * @exception EOFException if this stream reaches the end before reading - * all the bytes. - * @exception IOException if an I/O error occurs. - */ - byte readByte() throws IOException; - - /** - * Reads one input byte, zero-extends - * it to type int, and returns - * the result, which is therefore in the range - * 0 - * through 255. - * This method is suitable for reading - * the byte written by the writeByte - * method of interface DataOutput - * if the argument to writeByte - * was intended to be a value in the range - * 0 through 255. - * - * @return the unsigned 8-bit value read. - * @exception EOFException if this stream reaches the end before reading - * all the bytes. - * @exception IOException if an I/O error occurs. - */ - int readUnsignedByte() throws IOException; - - /** - * Reads two input bytes and returns - * a short value. Let a - * be the first byte read and b - * be the second byte. The value - * returned - * is: - *

(short)((a << 8) | (b & 0xff))
-     * 
- * This method - * is suitable for reading the bytes written - * by the writeShort method of - * interface DataOutput. - * - * @return the 16-bit value read. - * @exception EOFException if this stream reaches the end before reading - * all the bytes. - * @exception IOException if an I/O error occurs. - */ - short readShort() throws IOException; - - /** - * Reads two input bytes and returns - * an int value in the range 0 - * through 65535. Let a - * be the first byte read and - * b - * be the second byte. The value returned is: - *

(((a & 0xff) << 8) | (b & 0xff))
-     * 
- * This method is suitable for reading the bytes - * written by the writeShort method - * of interface DataOutput if - * the argument to writeShort - * was intended to be a value in the range - * 0 through 65535. - * - * @return the unsigned 16-bit value read. - * @exception EOFException if this stream reaches the end before reading - * all the bytes. - * @exception IOException if an I/O error occurs. - */ - int readUnsignedShort() throws IOException; - - /** - * Reads two input bytes and returns a char value. - * Let a - * be the first byte read and b - * be the second byte. The value - * returned is: - *

(char)((a << 8) | (b & 0xff))
-     * 
- * This method - * is suitable for reading bytes written by - * the writeChar method of interface - * DataOutput. - * - * @return the char value read. - * @exception EOFException if this stream reaches the end before reading - * all the bytes. - * @exception IOException if an I/O error occurs. - */ - char readChar() throws IOException; - - /** - * Reads four input bytes and returns an - * int value. Let a-d - * be the first through fourth bytes read. The value returned is: - *

-     * 
-     * (((a & 0xff) << 24) | ((b & 0xff) << 16) |
-     *  ((c & 0xff) << 8) | (d & 0xff))
-     * 
- * This method is suitable - * for reading bytes written by the writeInt - * method of interface DataOutput. - * - * @return the int value read. - * @exception EOFException if this stream reaches the end before reading - * all the bytes. - * @exception IOException if an I/O error occurs. - */ - int readInt() throws IOException; - - /** - * Reads eight input bytes and returns - * a long value. Let a-h - * be the first through eighth bytes read. - * The value returned is: - *

 
-     * (((long)(a & 0xff) << 56) |
-     *  ((long)(b & 0xff) << 48) |
-     *  ((long)(c & 0xff) << 40) |
-     *  ((long)(d & 0xff) << 32) |
-     *  ((long)(e & 0xff) << 24) |
-     *  ((long)(f & 0xff) << 16) |
-     *  ((long)(g & 0xff) <<  8) |
-     *  ((long)(h & 0xff)))
-     * 
- *

- * This method is suitable - * for reading bytes written by the writeLong - * method of interface DataOutput. - * - * @return the long value read. - * @exception EOFException if this stream reaches the end before reading - * all the bytes. - * @exception IOException if an I/O error occurs. - */ - long readLong() throws IOException; - - /** - * Reads four input bytes and returns - * a float value. It does this - * by first constructing an int - * value in exactly the manner - * of the readInt - * method, then converting this int - * value to a float in - * exactly the manner of the method Float.intBitsToFloat. - * This method is suitable for reading - * bytes written by the writeFloat - * method of interface DataOutput. - * - * @return the float value read. - * @exception EOFException if this stream reaches the end before reading - * all the bytes. - * @exception IOException if an I/O error occurs. - */ - float readFloat() throws IOException; - - /** - * Reads eight input bytes and returns - * a double value. It does this - * by first constructing a long - * value in exactly the manner - * of the readlong - * method, then converting this long - * value to a double in exactly - * the manner of the method Double.longBitsToDouble. - * This method is suitable for reading - * bytes written by the writeDouble - * method of interface DataOutput. - * - * @return the double value read. - * @exception EOFException if this stream reaches the end before reading - * all the bytes. - * @exception IOException if an I/O error occurs. - */ - double readDouble() throws IOException; - - /** - * Reads the next line of text from the input stream. - * It reads successive bytes, converting - * each byte separately into a character, - * until it encounters a line terminator or - * end of - * file; the characters read are then - * returned as a String. Note - * that because this - * method processes bytes, - * it does not support input of the full Unicode - * character set. - *

- * If end of file is encountered - * before even one byte can be read, then null - * is returned. Otherwise, each byte that is - * read is converted to type char - * by zero-extension. If the character '\n' - * is encountered, it is discarded and reading - * ceases. If the character '\r' - * is encountered, it is discarded and, if - * the following byte converts to the - * character '\n', then that is - * discarded also; reading then ceases. If - * end of file is encountered before either - * of the characters '\n' and - * '\r' is encountered, reading - * ceases. Once reading has ceased, a String - * is returned that contains all the characters - * read and not discarded, taken in order. - * Note that every character in this string - * will have a value less than \u0100, - * that is, (char)256. - * - * @return the next line of text from the input stream, - * or null if the end of file is - * encountered before a byte can be read. - * @exception IOException if an I/O error occurs. - */ - String readLine() throws IOException; - - /** - * Reads in a string that has been encoded using a - * modified UTF-8 - * format. - * The general contract of readUTF - * is that it reads a representation of a Unicode - * character string encoded in modified - * UTF-8 format; this string of characters - * is then returned as a String. - *

- * First, two bytes are read and used to - * construct an unsigned 16-bit integer in - * exactly the manner of the readUnsignedShort - * method . This integer value is called the - * UTF length and specifies the number - * of additional bytes to be read. These bytes - * are then converted to characters by considering - * them in groups. The length of each group - * is computed from the value of the first - * byte of the group. The byte following a - * group, if any, is the first byte of the - * next group. - *

- * If the first byte of a group - * matches the bit pattern 0xxxxxxx - * (where x means "may be 0 - * or 1"), then the group consists - * of just that byte. The byte is zero-extended - * to form a character. - *

- * If the first byte - * of a group matches the bit pattern 110xxxxx, - * then the group consists of that byte a - * and a second byte b. If there - * is no byte b (because byte - * a was the last of the bytes - * to be read), or if byte b does - * not match the bit pattern 10xxxxxx, - * then a UTFDataFormatException - * is thrown. Otherwise, the group is converted - * to the character:

- *

(char)(((a& 0x1F) << 6) | (b & 0x3F))
-     * 
- * If the first byte of a group - * matches the bit pattern 1110xxxx, - * then the group consists of that byte a - * and two more bytes b and c. - * If there is no byte c (because - * byte a was one of the last - * two of the bytes to be read), or either - * byte b or byte c - * does not match the bit pattern 10xxxxxx, - * then a UTFDataFormatException - * is thrown. Otherwise, the group is converted - * to the character:

- *


-     * (char)(((a & 0x0F) << 12) | ((b & 0x3F) << 6) | (c & 0x3F))
-     * 
- * If the first byte of a group matches the - * pattern 1111xxxx or the pattern - * 10xxxxxx, then a UTFDataFormatException - * is thrown. - *

- * If end of file is encountered - * at any time during this entire process, - * then an EOFException is thrown. - *

- * After every group has been converted to - * a character by this process, the characters - * are gathered, in the same order in which - * their corresponding groups were read from - * the input stream, to form a String, - * which is returned. - *

- * The writeUTF - * method of interface DataOutput - * may be used to write data that is suitable - * for reading by this method. - * @return a Unicode string. - * @exception EOFException if this stream reaches the end - * before reading all the bytes. - * @exception IOException if an I/O error occurs. - * @exception UTFDataFormatException if the bytes do not represent a - * valid modified UTF-8 encoding of a string. - */ - String readUTF() throws IOException; -} diff -r 388e48c0a37a -r 05224402145d emul/src/main/java/java/io/DataInputStream.java --- a/emul/src/main/java/java/io/DataInputStream.java Wed Jan 23 20:16:48 2013 +0100 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,704 +0,0 @@ -/* - * Copyright (c) 1994, 2006, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code 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 - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package java.io; - -import org.apidesign.bck2brwsr.core.JavaScriptBody; - -/** - * A data input stream lets an application read primitive Java data - * types from an underlying input stream in a machine-independent - * way. An application uses a data output stream to write data that - * can later be read by a data input stream. - *

- * DataInputStream is not necessarily safe for multithreaded access. - * Thread safety is optional and is the responsibility of users of - * methods in this class. - * - * @author Arthur van Hoff - * @see java.io.DataOutputStream - * @since JDK1.0 - */ -public -class DataInputStream extends FilterInputStream implements DataInput { - - /** - * Creates a DataInputStream that uses the specified - * underlying InputStream. - * - * @param in the specified input stream - */ - public DataInputStream(InputStream in) { - super(in); - } - - /** - * working arrays initialized on demand by readUTF - */ - private byte bytearr[] = new byte[80]; - private char chararr[] = new char[80]; - - /** - * Reads some number of bytes from the contained input stream and - * stores them into the buffer array b. The number of - * bytes actually read is returned as an integer. This method blocks - * until input data is available, end of file is detected, or an - * exception is thrown. - * - *

If b is null, a NullPointerException is - * thrown. If the length of b is zero, then no bytes are - * read and 0 is returned; otherwise, there is an attempt - * to read at least one byte. If no byte is available because the - * stream is at end of file, the value -1 is returned; - * otherwise, at least one byte is read and stored into b. - * - *

The first byte read is stored into element b[0], the - * next one into b[1], and so on. The number of bytes read - * is, at most, equal to the length of b. Let k - * be the number of bytes actually read; these bytes will be stored in - * elements b[0] through b[k-1], leaving - * elements b[k] through b[b.length-1] - * unaffected. - * - *

The read(b) method has the same effect as: - *

-     * read(b, 0, b.length)
-     * 
- * - * @param b the buffer into which the data is read. - * @return the total number of bytes read into the buffer, or - * -1 if there is no more data because the end - * of the stream has been reached. - * @exception IOException if the first byte cannot be read for any reason - * other than end of file, the stream has been closed and the underlying - * input stream does not support reading after close, or another I/O - * error occurs. - * @see java.io.FilterInputStream#in - * @see java.io.InputStream#read(byte[], int, int) - */ - public final int read(byte b[]) throws IOException { - return in.read(b, 0, b.length); - } - - /** - * Reads up to len bytes of data from the contained - * input stream into an array of bytes. An attempt is made to read - * as many as len bytes, but a smaller number may be read, - * possibly zero. The number of bytes actually read is returned as an - * integer. - * - *

This method blocks until input data is available, end of file is - * detected, or an exception is thrown. - * - *

If len is zero, then no bytes are read and - * 0 is returned; otherwise, there is an attempt to read at - * least one byte. If no byte is available because the stream is at end of - * file, the value -1 is returned; otherwise, at least one - * byte is read and stored into b. - * - *

The first byte read is stored into element b[off], the - * next one into b[off+1], and so on. The number of bytes read - * is, at most, equal to len. Let k be the number of - * bytes actually read; these bytes will be stored in elements - * b[off] through b[off+k-1], - * leaving elements b[off+k] through - * b[off+len-1] unaffected. - * - *

In every case, elements b[0] through - * b[off] and elements b[off+len] through - * b[b.length-1] are unaffected. - * - * @param b the buffer into which the data is read. - * @param off the start offset in the destination array b - * @param len the maximum number of bytes read. - * @return the total number of bytes read into the buffer, or - * -1 if there is no more data because the end - * of the stream has been reached. - * @exception NullPointerException If b is null. - * @exception IndexOutOfBoundsException If off is negative, - * len is negative, or len is greater than - * b.length - off - * @exception IOException if the first byte cannot be read for any reason - * other than end of file, the stream has been closed and the underlying - * input stream does not support reading after close, or another I/O - * error occurs. - * @see java.io.FilterInputStream#in - * @see java.io.InputStream#read(byte[], int, int) - */ - public final int read(byte b[], int off, int len) throws IOException { - return in.read(b, off, len); - } - - /** - * See the general contract of the readFully - * method of DataInput. - *

- * Bytes - * for this operation are read from the contained - * input stream. - * - * @param b the buffer into which the data is read. - * @exception EOFException if this input stream reaches the end before - * reading all the bytes. - * @exception IOException the stream has been closed and the contained - * input stream does not support reading after close, or - * another I/O error occurs. - * @see java.io.FilterInputStream#in - */ - public final void readFully(byte b[]) throws IOException { - readFully(b, 0, b.length); - } - - /** - * See the general contract of the readFully - * method of DataInput. - *

- * Bytes - * for this operation are read from the contained - * input stream. - * - * @param b the buffer into which the data is read. - * @param off the start offset of the data. - * @param len the number of bytes to read. - * @exception EOFException if this input stream reaches the end before - * reading all the bytes. - * @exception IOException the stream has been closed and the contained - * input stream does not support reading after close, or - * another I/O error occurs. - * @see java.io.FilterInputStream#in - */ - public final void readFully(byte b[], int off, int len) throws IOException { - if (len < 0) - throw new IndexOutOfBoundsException(); - int n = 0; - while (n < len) { - int count = in.read(b, off + n, len - n); - if (count < 0) - throw new EOFException(); - n += count; - } - } - - /** - * See the general contract of the skipBytes - * method of DataInput. - *

- * Bytes for this operation are read from the contained - * input stream. - * - * @param n the number of bytes to be skipped. - * @return the actual number of bytes skipped. - * @exception IOException if the contained input stream does not support - * seek, or the stream has been closed and - * the contained input stream does not support - * reading after close, or another I/O error occurs. - */ - public final int skipBytes(int n) throws IOException { - int total = 0; - int cur = 0; - - while ((total 0)) { - total += cur; - } - - return total; - } - - /** - * See the general contract of the readBoolean - * method of DataInput. - *

- * Bytes for this operation are read from the contained - * input stream. - * - * @return the boolean value read. - * @exception EOFException if this input stream has reached the end. - * @exception IOException the stream has been closed and the contained - * input stream does not support reading after close, or - * another I/O error occurs. - * @see java.io.FilterInputStream#in - */ - public final boolean readBoolean() throws IOException { - int ch = in.read(); - if (ch < 0) - throw new EOFException(); - return (ch != 0); - } - - /** - * See the general contract of the readByte - * method of DataInput. - *

- * Bytes - * for this operation are read from the contained - * input stream. - * - * @return the next byte of this input stream as a signed 8-bit - * byte. - * @exception EOFException if this input stream has reached the end. - * @exception IOException the stream has been closed and the contained - * input stream does not support reading after close, or - * another I/O error occurs. - * @see java.io.FilterInputStream#in - */ - public final byte readByte() throws IOException { - int ch = in.read(); - if (ch < 0) - throw new EOFException(); - return (byte)(ch); - } - - /** - * See the general contract of the readUnsignedByte - * method of DataInput. - *

- * Bytes - * for this operation are read from the contained - * input stream. - * - * @return the next byte of this input stream, interpreted as an - * unsigned 8-bit number. - * @exception EOFException if this input stream has reached the end. - * @exception IOException the stream has been closed and the contained - * input stream does not support reading after close, or - * another I/O error occurs. - * @see java.io.FilterInputStream#in - */ - public final int readUnsignedByte() throws IOException { - int ch = in.read(); - if (ch < 0) - throw new EOFException(); - return ch; - } - - /** - * See the general contract of the readShort - * method of DataInput. - *

- * Bytes - * for this operation are read from the contained - * input stream. - * - * @return the next two bytes of this input stream, interpreted as a - * signed 16-bit number. - * @exception EOFException if this input stream reaches the end before - * reading two bytes. - * @exception IOException the stream has been closed and the contained - * input stream does not support reading after close, or - * another I/O error occurs. - * @see java.io.FilterInputStream#in - */ - public final short readShort() throws IOException { - int ch1 = in.read(); - int ch2 = in.read(); - if ((ch1 | ch2) < 0) - throw new EOFException(); - return (short)((ch1 << 8) + (ch2 << 0)); - } - - /** - * See the general contract of the readUnsignedShort - * method of DataInput. - *

- * Bytes - * for this operation are read from the contained - * input stream. - * - * @return the next two bytes of this input stream, interpreted as an - * unsigned 16-bit integer. - * @exception EOFException if this input stream reaches the end before - * reading two bytes. - * @exception IOException the stream has been closed and the contained - * input stream does not support reading after close, or - * another I/O error occurs. - * @see java.io.FilterInputStream#in - */ - public final int readUnsignedShort() throws IOException { - int ch1 = in.read(); - int ch2 = in.read(); - if ((ch1 | ch2) < 0) - throw new EOFException(); - return (ch1 << 8) + (ch2 << 0); - } - - /** - * See the general contract of the readChar - * method of DataInput. - *

- * Bytes - * for this operation are read from the contained - * input stream. - * - * @return the next two bytes of this input stream, interpreted as a - * char. - * @exception EOFException if this input stream reaches the end before - * reading two bytes. - * @exception IOException the stream has been closed and the contained - * input stream does not support reading after close, or - * another I/O error occurs. - * @see java.io.FilterInputStream#in - */ - public final char readChar() throws IOException { - int ch1 = in.read(); - int ch2 = in.read(); - if ((ch1 | ch2) < 0) - throw new EOFException(); - return (char)((ch1 << 8) + (ch2 << 0)); - } - - /** - * See the general contract of the readInt - * method of DataInput. - *

- * Bytes - * for this operation are read from the contained - * input stream. - * - * @return the next four bytes of this input stream, interpreted as an - * int. - * @exception EOFException if this input stream reaches the end before - * reading four bytes. - * @exception IOException the stream has been closed and the contained - * input stream does not support reading after close, or - * another I/O error occurs. - * @see java.io.FilterInputStream#in - */ - public final int readInt() throws IOException { - int ch1 = in.read(); - int ch2 = in.read(); - int ch3 = in.read(); - int ch4 = in.read(); - if ((ch1 | ch2 | ch3 | ch4) < 0) - throw new EOFException(); - return ((ch1 << 24) + (ch2 << 16) + (ch3 << 8) + (ch4 << 0)); - } - - private byte readBuffer[] = new byte[8]; - - /** - * See the general contract of the readLong - * method of DataInput. - *

- * Bytes - * for this operation are read from the contained - * input stream. - * - * @return the next eight bytes of this input stream, interpreted as a - * long. - * @exception EOFException if this input stream reaches the end before - * reading eight bytes. - * @exception IOException the stream has been closed and the contained - * input stream does not support reading after close, or - * another I/O error occurs. - * @see java.io.FilterInputStream#in - */ - public final long readLong() throws IOException { - readFully(readBuffer, 0, 8); - return (((long)readBuffer[0] << 56) + - ((long)(readBuffer[1] & 255) << 48) + - ((long)(readBuffer[2] & 255) << 40) + - ((long)(readBuffer[3] & 255) << 32) + - ((long)(readBuffer[4] & 255) << 24) + - ((readBuffer[5] & 255) << 16) + - ((readBuffer[6] & 255) << 8) + - ((readBuffer[7] & 255) << 0)); - } - - /** - * See the general contract of the readFloat - * method of DataInput. - *

- * Bytes - * for this operation are read from the contained - * input stream. - * - * @return the next four bytes of this input stream, interpreted as a - * float. - * @exception EOFException if this input stream reaches the end before - * reading four bytes. - * @exception IOException the stream has been closed and the contained - * input stream does not support reading after close, or - * another I/O error occurs. - * @see java.io.DataInputStream#readInt() - * @see java.lang.Float#intBitsToFloat(int) - */ - public final float readFloat() throws IOException { - return Float.intBitsToFloat(readInt()); - } - - /** - * See the general contract of the readDouble - * method of DataInput. - *

- * Bytes - * for this operation are read from the contained - * input stream. - * - * @return the next eight bytes of this input stream, interpreted as a - * double. - * @exception EOFException if this input stream reaches the end before - * reading eight bytes. - * @exception IOException the stream has been closed and the contained - * input stream does not support reading after close, or - * another I/O error occurs. - * @see java.io.DataInputStream#readLong() - * @see java.lang.Double#longBitsToDouble(long) - */ - public final double readDouble() throws IOException { - int hi = readInt(); - int low = readInt(); - return toDouble(hi, low); - } - - @JavaScriptBody(args={ "hi", "low" }, - body= - "if (low == 0) {\n" - + " if (hi === 0x7ff00000) return Number.POSITIVE_INFINITY;\n" - + " if (hi === 0xfff00000) return Number.NEGATIVE_INFINITY;\n" - + "}\n" - + "if (hi >= 0x7ff00000 && hi <= 0x7fffffff) return Number.NaN;\n" - + "if (hi >= 0xfff00000 && hi <= 0xffffffff) return Number.NaN;\n" - + "var s = (hi & 0x80000000) === 0 ? 1 : -1;\n" - + "var e = (hi >> 20) & 0x7ff;\n" - + "var to32 = low >> 0;\n" - + "if (e === 0) {\n" - + " if (to32 & 0x80000000) {\n" - + " hi = hi << 1 + 1; low = low << 1;\n" - + " } else {\n" - + " hi = hi << 1; low = low << 1;\n" - + " }\n" - + "} else {\n" - + " hi = (hi & 0xfffff) | 0x100000;\n" - + "}\n" - + "to32 = low >> 0;\n" - + "var m = Math.pow(2.0, 32) * hi + to32;\n" - + "var r = s * m * Math.pow(2.0, e - 1075);\n" - + "//throw 'exp: ' + e + ' sign: ' + s + ' hi:' + hi + ' low: ' + low + ' m: ' + m + ' r: ' + r;\n" - + "return r;\n" - ) - private static double toDouble(int hi, int low) { - long both = hi; - both = (both << 32) & low; - return Double.doubleToLongBits(both); - } - - private char lineBuffer[]; - - /** - * See the general contract of the readLine - * method of DataInput. - *

- * Bytes - * for this operation are read from the contained - * input stream. - * - * @deprecated This method does not properly convert bytes to characters. - * As of JDK 1.1, the preferred way to read lines of text is via the - * BufferedReader.readLine() method. Programs that use the - * DataInputStream class to read lines can be converted to use - * the BufferedReader class by replacing code of the form: - *

-     *     DataInputStream d = new DataInputStream(in);
-     * 
- * with: - *
-     *     BufferedReader d
-     *          = new BufferedReader(new InputStreamReader(in));
-     * 
- * - * @return the next line of text from this input stream. - * @exception IOException if an I/O error occurs. - * @see java.io.BufferedReader#readLine() - * @see java.io.FilterInputStream#in - */ - @Deprecated - public final String readLine() throws IOException { - char buf[] = lineBuffer; - - if (buf == null) { - buf = lineBuffer = new char[128]; - } - - int room = buf.length; - int offset = 0; - int c; - -loop: while (true) { - switch (c = in.read()) { - case -1: - case '\n': - break loop; - - case '\r': - int c2 = in.read(); - if ((c2 != '\n') && (c2 != -1)) { - if (!(in instanceof PushbackInputStream)) { - this.in = new PushbackInputStream(in); - } - ((PushbackInputStream)in).unread(c2); - } - break loop; - - default: - if (--room < 0) { - buf = new char[offset + 128]; - room = buf.length - offset - 1; - arraycopy(lineBuffer, 0, buf, 0, offset); - lineBuffer = buf; - } - buf[offset++] = (char) c; - break; - } - } - if ((c == -1) && (offset == 0)) { - return null; - } - return String.copyValueOf(buf, 0, offset); - } - - /** - * See the general contract of the readUTF - * method of DataInput. - *

- * Bytes - * for this operation are read from the contained - * input stream. - * - * @return a Unicode string. - * @exception EOFException if this input stream reaches the end before - * reading all the bytes. - * @exception IOException the stream has been closed and the contained - * input stream does not support reading after close, or - * another I/O error occurs. - * @exception UTFDataFormatException if the bytes do not represent a valid - * modified UTF-8 encoding of a string. - * @see java.io.DataInputStream#readUTF(java.io.DataInput) - */ - public final String readUTF() throws IOException { - return readUTF(this); - } - - /** - * Reads from the - * stream in a representation - * of a Unicode character string encoded in - * modified UTF-8 format; - * this string of characters is then returned as a String. - * The details of the modified UTF-8 representation - * are exactly the same as for the readUTF - * method of DataInput. - * - * @param in a data input stream. - * @return a Unicode string. - * @exception EOFException if the input stream reaches the end - * before all the bytes. - * @exception IOException the stream has been closed and the contained - * input stream does not support reading after close, or - * another I/O error occurs. - * @exception UTFDataFormatException if the bytes do not represent a - * valid modified UTF-8 encoding of a Unicode string. - * @see java.io.DataInputStream#readUnsignedShort() - */ - public final static String readUTF(DataInput in) throws IOException { - int utflen = in.readUnsignedShort(); - byte[] bytearr = null; - char[] chararr = null; - if (in instanceof DataInputStream) { - DataInputStream dis = (DataInputStream)in; - if (dis.bytearr.length < utflen){ - dis.bytearr = new byte[utflen*2]; - dis.chararr = new char[utflen*2]; - } - chararr = dis.chararr; - bytearr = dis.bytearr; - } else { - bytearr = new byte[utflen]; - chararr = new char[utflen]; - } - - int c, char2, char3; - int count = 0; - int chararr_count=0; - - in.readFully(bytearr, 0, utflen); - - while (count < utflen) { - c = (int) bytearr[count] & 0xff; - if (c > 127) break; - count++; - chararr[chararr_count++]=(char)c; - } - - while (count < utflen) { - c = (int) bytearr[count] & 0xff; - switch (c >> 4) { - case 0: case 1: case 2: case 3: case 4: case 5: case 6: case 7: - /* 0xxxxxxx*/ - count++; - chararr[chararr_count++]=(char)c; - break; - case 12: case 13: - /* 110x xxxx 10xx xxxx*/ - count += 2; - if (count > utflen) - throw new UTFDataFormatException( - "malformed input: partial character at end"); - char2 = (int) bytearr[count-1]; - if ((char2 & 0xC0) != 0x80) - throw new UTFDataFormatException( - "malformed input around byte " + count); - chararr[chararr_count++]=(char)(((c & 0x1F) << 6) | - (char2 & 0x3F)); - break; - case 14: - /* 1110 xxxx 10xx xxxx 10xx xxxx */ - count += 3; - if (count > utflen) - throw new UTFDataFormatException( - "malformed input: partial character at end"); - char2 = (int) bytearr[count-2]; - char3 = (int) bytearr[count-1]; - if (((char2 & 0xC0) != 0x80) || ((char3 & 0xC0) != 0x80)) - throw new UTFDataFormatException( - "malformed input around byte " + (count-1)); - chararr[chararr_count++]=(char)(((c & 0x0F) << 12) | - ((char2 & 0x3F) << 6) | - ((char3 & 0x3F) << 0)); - break; - default: - /* 10xx xxxx, 1111 xxxx */ - throw new UTFDataFormatException( - "malformed input around byte " + count); - } - } - // The number of chars produced may be less than utflen - return new String(chararr, 0, chararr_count); - } - static void arraycopy(char[] value, int srcBegin, char[] dst, int dstBegin, int count) { - while (count-- > 0) { - dst[dstBegin++] = value[srcBegin++]; - } - } -} diff -r 388e48c0a37a -r 05224402145d emul/src/main/java/java/io/EOFException.java --- a/emul/src/main/java/java/io/EOFException.java Wed Jan 23 20:16:48 2013 +0100 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,65 +0,0 @@ -/* - * Copyright (c) 1995, 2008, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code 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 - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package java.io; - -/** - * Signals that an end of file or end of stream has been reached - * unexpectedly during input. - *

- * This exception is mainly used by data input streams to signal end of - * stream. Note that many other input operations return a special value on - * end of stream rather than throwing an exception. - *

- * - * @author Frank Yellin - * @see java.io.DataInputStream - * @see java.io.IOException - * @since JDK1.0 - */ -public -class EOFException extends IOException { - private static final long serialVersionUID = 6433858223774886977L; - - /** - * Constructs an EOFException with null - * as its error detail message. - */ - public EOFException() { - super(); - } - - /** - * Constructs an EOFException with the specified detail - * message. The string s may later be retrieved by the - * {@link java.lang.Throwable#getMessage} method of class - * java.lang.Throwable. - * - * @param s the detail message. - */ - public EOFException(String s) { - super(s); - } -} diff -r 388e48c0a37a -r 05224402145d emul/src/main/java/java/io/FilterInputStream.java --- a/emul/src/main/java/java/io/FilterInputStream.java Wed Jan 23 20:16:48 2013 +0100 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,245 +0,0 @@ -/* - * Copyright (c) 1994, 2010, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code 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 - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package java.io; - -/** - * A FilterInputStream contains - * some other input stream, which it uses as - * its basic source of data, possibly transforming - * the data along the way or providing additional - * functionality. The class FilterInputStream - * itself simply overrides all methods of - * InputStream with versions that - * pass all requests to the contained input - * stream. Subclasses of FilterInputStream - * may further override some of these methods - * and may also provide additional methods - * and fields. - * - * @author Jonathan Payne - * @since JDK1.0 - */ -public -class FilterInputStream extends InputStream { - /** - * The input stream to be filtered. - */ - protected volatile InputStream in; - - /** - * Creates a FilterInputStream - * by assigning the argument in - * to the field this.in so as - * to remember it for later use. - * - * @param in the underlying input stream, or null if - * this instance is to be created without an underlying stream. - */ - protected FilterInputStream(InputStream in) { - this.in = in; - } - - /** - * Reads the next byte of data from this input stream. The value - * byte is returned as an int in the range - * 0 to 255. If no byte is available - * because the end of the stream has been reached, the value - * -1 is returned. This method blocks until input data - * is available, the end of the stream is detected, or an exception - * is thrown. - *

- * This method - * simply performs in.read() and returns the result. - * - * @return the next byte of data, or -1 if the end of the - * stream is reached. - * @exception IOException if an I/O error occurs. - * @see java.io.FilterInputStream#in - */ - public int read() throws IOException { - return in.read(); - } - - /** - * Reads up to byte.length bytes of data from this - * input stream into an array of bytes. This method blocks until some - * input is available. - *

- * This method simply performs the call - * read(b, 0, b.length) and returns - * the result. It is important that it does - * not do in.read(b) instead; - * certain subclasses of FilterInputStream - * depend on the implementation strategy actually - * used. - * - * @param b the buffer into which the data is read. - * @return the total number of bytes read into the buffer, or - * -1 if there is no more data because the end of - * the stream has been reached. - * @exception IOException if an I/O error occurs. - * @see java.io.FilterInputStream#read(byte[], int, int) - */ - public int read(byte b[]) throws IOException { - return read(b, 0, b.length); - } - - /** - * Reads up to len bytes of data from this input stream - * into an array of bytes. If len is not zero, the method - * blocks until some input is available; otherwise, no - * bytes are read and 0 is returned. - *

- * This method simply performs in.read(b, off, len) - * and returns the result. - * - * @param b the buffer into which the data is read. - * @param off the start offset in the destination array b - * @param len the maximum number of bytes read. - * @return the total number of bytes read into the buffer, or - * -1 if there is no more data because the end of - * the stream has been reached. - * @exception NullPointerException If b is null. - * @exception IndexOutOfBoundsException If off is negative, - * len is negative, or len is greater than - * b.length - off - * @exception IOException if an I/O error occurs. - * @see java.io.FilterInputStream#in - */ - public int read(byte b[], int off, int len) throws IOException { - return in.read(b, off, len); - } - - /** - * Skips over and discards n bytes of data from the - * input stream. The skip method may, for a variety of - * reasons, end up skipping over some smaller number of bytes, - * possibly 0. The actual number of bytes skipped is - * returned. - *

- * This method simply performs in.skip(n). - * - * @param n the number of bytes to be skipped. - * @return the actual number of bytes skipped. - * @exception IOException if the stream does not support seek, - * or if some other I/O error occurs. - */ - public long skip(long n) throws IOException { - return in.skip(n); - } - - /** - * Returns an estimate of the number of bytes that can be read (or - * skipped over) from this input stream without blocking by the next - * caller of a method for this input stream. The next caller might be - * the same thread or another thread. A single read or skip of this - * many bytes will not block, but may read or skip fewer bytes. - *

- * This method returns the result of {@link #in in}.available(). - * - * @return an estimate of the number of bytes that can be read (or skipped - * over) from this input stream without blocking. - * @exception IOException if an I/O error occurs. - */ - public int available() throws IOException { - return in.available(); - } - - /** - * Closes this input stream and releases any system resources - * associated with the stream. - * This - * method simply performs in.close(). - * - * @exception IOException if an I/O error occurs. - * @see java.io.FilterInputStream#in - */ - public void close() throws IOException { - in.close(); - } - - /** - * Marks the current position in this input stream. A subsequent - * call to the reset method repositions this stream at - * the last marked position so that subsequent reads re-read the same bytes. - *

- * The readlimit argument tells this input stream to - * allow that many bytes to be read before the mark position gets - * invalidated. - *

- * This method simply performs in.mark(readlimit). - * - * @param readlimit the maximum limit of bytes that can be read before - * the mark position becomes invalid. - * @see java.io.FilterInputStream#in - * @see java.io.FilterInputStream#reset() - */ - public synchronized void mark(int readlimit) { - in.mark(readlimit); - } - - /** - * Repositions this stream to the position at the time the - * mark method was last called on this input stream. - *

- * This method - * simply performs in.reset(). - *

- * Stream marks are intended to be used in - * situations where you need to read ahead a little to see what's in - * the stream. Often this is most easily done by invoking some - * general parser. If the stream is of the type handled by the - * parse, it just chugs along happily. If the stream is not of - * that type, the parser should toss an exception when it fails. - * If this happens within readlimit bytes, it allows the outer - * code to reset the stream and try another parser. - * - * @exception IOException if the stream has not been marked or if the - * mark has been invalidated. - * @see java.io.FilterInputStream#in - * @see java.io.FilterInputStream#mark(int) - */ - public synchronized void reset() throws IOException { - in.reset(); - } - - /** - * Tests if this input stream supports the mark - * and reset methods. - * This method - * simply performs in.markSupported(). - * - * @return true if this stream type supports the - * mark and reset method; - * false otherwise. - * @see java.io.FilterInputStream#in - * @see java.io.InputStream#mark(int) - * @see java.io.InputStream#reset() - */ - public boolean markSupported() { - return in.markSupported(); - } -} diff -r 388e48c0a37a -r 05224402145d emul/src/main/java/java/io/IOException.java --- a/emul/src/main/java/java/io/IOException.java Wed Jan 23 20:16:48 2013 +0100 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,101 +0,0 @@ -/* - * Copyright (c) 1994, 2006, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code 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 - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package java.io; - -/** - * Signals that an I/O exception of some sort has occurred. This - * class is the general class of exceptions produced by failed or - * interrupted I/O operations. - * - * @author unascribed - * @see java.io.InputStream - * @see java.io.OutputStream - * @since JDK1.0 - */ -public -class IOException extends Exception { - static final long serialVersionUID = 7818375828146090155L; - - /** - * Constructs an {@code IOException} with {@code null} - * as its error detail message. - */ - public IOException() { - super(); - } - - /** - * Constructs an {@code IOException} with the specified detail message. - * - * @param message - * The detail message (which is saved for later retrieval - * by the {@link #getMessage()} method) - */ - public IOException(String message) { - super(message); - } - - /** - * Constructs an {@code IOException} with the specified detail message - * and cause. - * - *

Note that the detail message associated with {@code cause} is - * not automatically incorporated into this exception's detail - * message. - * - * @param message - * The detail message (which is saved for later retrieval - * by the {@link #getMessage()} method) - * - * @param cause - * The cause (which is saved for later retrieval by the - * {@link #getCause()} method). (A null value is permitted, - * and indicates that the cause is nonexistent or unknown.) - * - * @since 1.6 - */ - public IOException(String message, Throwable cause) { - super(message, cause); - } - - /** - * Constructs an {@code IOException} with the specified cause and a - * detail message of {@code (cause==null ? null : cause.toString())} - * (which typically contains the class and detail message of {@code cause}). - * This constructor is useful for IO exceptions that are little more - * than wrappers for other throwables. - * - * @param cause - * The cause (which is saved for later retrieval by the - * {@link #getCause()} method). (A null value is permitted, - * and indicates that the cause is nonexistent or unknown.) - * - * @since 1.6 - */ - public IOException(Throwable cause) { - super(cause); - } -} diff -r 388e48c0a37a -r 05224402145d emul/src/main/java/java/io/InputStream.java --- a/emul/src/main/java/java/io/InputStream.java Wed Jan 23 20:16:48 2013 +0100 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,370 +0,0 @@ -/* - * Copyright (c) 1994, 2006, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code 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 - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package java.io; - -/** - * This abstract class is the superclass of all classes representing - * an input stream of bytes. - * - *

Applications that need to define a subclass of InputStream - * must always provide a method that returns the next byte of input. - * - * @author Arthur van Hoff - * @see java.io.BufferedInputStream - * @see java.io.ByteArrayInputStream - * @see java.io.DataInputStream - * @see java.io.FilterInputStream - * @see java.io.InputStream#read() - * @see java.io.OutputStream - * @see java.io.PushbackInputStream - * @since JDK1.0 - */ -public abstract class InputStream implements Closeable { - - // SKIP_BUFFER_SIZE is used to determine the size of skipBuffer - private static final int SKIP_BUFFER_SIZE = 2048; - // skipBuffer is initialized in skip(long), if needed. - private static byte[] skipBuffer; - - /** - * Reads the next byte of data from the input stream. The value byte is - * returned as an int in the range 0 to - * 255. If no byte is available because the end of the stream - * has been reached, the value -1 is returned. This method - * blocks until input data is available, the end of the stream is detected, - * or an exception is thrown. - * - *

A subclass must provide an implementation of this method. - * - * @return the next byte of data, or -1 if the end of the - * stream is reached. - * @exception IOException if an I/O error occurs. - */ - public abstract int read() throws IOException; - - /** - * Reads some number of bytes from the input stream and stores them into - * the buffer array b. The number of bytes actually read is - * returned as an integer. This method blocks until input data is - * available, end of file is detected, or an exception is thrown. - * - *

If the length of b is zero, then no bytes are read and - * 0 is returned; otherwise, there is an attempt to read at - * least one byte. If no byte is available because the stream is at the - * end of the file, the value -1 is returned; otherwise, at - * least one byte is read and stored into b. - * - *

The first byte read is stored into element b[0], the - * next one into b[1], and so on. The number of bytes read is, - * at most, equal to the length of b. Let k be the - * number of bytes actually read; these bytes will be stored in elements - * b[0] through b[k-1], - * leaving elements b[k] through - * b[b.length-1] unaffected. - * - *

The read(b) method for class InputStream - * has the same effect as:

 read(b, 0, b.length) 
- * - * @param b the buffer into which the data is read. - * @return the total number of bytes read into the buffer, or - * -1 if there is no more data because the end of - * the stream has been reached. - * @exception IOException If the first byte cannot be read for any reason - * other than the end of the file, if the input stream has been closed, or - * if some other I/O error occurs. - * @exception NullPointerException if b is null. - * @see java.io.InputStream#read(byte[], int, int) - */ - public int read(byte b[]) throws IOException { - return read(b, 0, b.length); - } - - /** - * Reads up to len bytes of data from the input stream into - * an array of bytes. An attempt is made to read as many as - * len bytes, but a smaller number may be read. - * The number of bytes actually read is returned as an integer. - * - *

This method blocks until input data is available, end of file is - * detected, or an exception is thrown. - * - *

If len is zero, then no bytes are read and - * 0 is returned; otherwise, there is an attempt to read at - * least one byte. If no byte is available because the stream is at end of - * file, the value -1 is returned; otherwise, at least one - * byte is read and stored into b. - * - *

The first byte read is stored into element b[off], the - * next one into b[off+1], and so on. The number of bytes read - * is, at most, equal to len. Let k be the number of - * bytes actually read; these bytes will be stored in elements - * b[off] through b[off+k-1], - * leaving elements b[off+k] through - * b[off+len-1] unaffected. - * - *

In every case, elements b[0] through - * b[off] and elements b[off+len] through - * b[b.length-1] are unaffected. - * - *

The read(b, off, len) method - * for class InputStream simply calls the method - * read() repeatedly. If the first such call results in an - * IOException, that exception is returned from the call to - * the read(b, off, len) method. If - * any subsequent call to read() results in a - * IOException, the exception is caught and treated as if it - * were end of file; the bytes read up to that point are stored into - * b and the number of bytes read before the exception - * occurred is returned. The default implementation of this method blocks - * until the requested amount of input data len has been read, - * end of file is detected, or an exception is thrown. Subclasses are encouraged - * to provide a more efficient implementation of this method. - * - * @param b the buffer into which the data is read. - * @param off the start offset in array b - * at which the data is written. - * @param len the maximum number of bytes to read. - * @return the total number of bytes read into the buffer, or - * -1 if there is no more data because the end of - * the stream has been reached. - * @exception IOException If the first byte cannot be read for any reason - * other than end of file, or if the input stream has been closed, or if - * some other I/O error occurs. - * @exception NullPointerException If b is null. - * @exception IndexOutOfBoundsException If off is negative, - * len is negative, or len is greater than - * b.length - off - * @see java.io.InputStream#read() - */ - public int read(byte b[], int off, int len) throws IOException { - if (b == null) { - throw new NullPointerException(); - } else if (off < 0 || len < 0 || len > b.length - off) { - throw new IndexOutOfBoundsException(); - } else if (len == 0) { - return 0; - } - - int c = read(); - if (c == -1) { - return -1; - } - b[off] = (byte)c; - - int i = 1; - try { - for (; i < len ; i++) { - c = read(); - if (c == -1) { - break; - } - b[off + i] = (byte)c; - } - } catch (IOException ee) { - } - return i; - } - - /** - * Skips over and discards n bytes of data from this input - * stream. The skip method may, for a variety of reasons, end - * up skipping over some smaller number of bytes, possibly 0. - * This may result from any of a number of conditions; reaching end of file - * before n bytes have been skipped is only one possibility. - * The actual number of bytes skipped is returned. If n is - * negative, no bytes are skipped. - * - *

The skip method of this class creates a - * byte array and then repeatedly reads into it until n bytes - * have been read or the end of the stream has been reached. Subclasses are - * encouraged to provide a more efficient implementation of this method. - * For instance, the implementation may depend on the ability to seek. - * - * @param n the number of bytes to be skipped. - * @return the actual number of bytes skipped. - * @exception IOException if the stream does not support seek, - * or if some other I/O error occurs. - */ - public long skip(long n) throws IOException { - - long remaining = n; - int nr; - if (skipBuffer == null) - skipBuffer = new byte[SKIP_BUFFER_SIZE]; - - byte[] localSkipBuffer = skipBuffer; - - if (n <= 0) { - return 0; - } - - while (remaining > 0) { - nr = read(localSkipBuffer, 0, - (int) Math.min(SKIP_BUFFER_SIZE, remaining)); - if (nr < 0) { - break; - } - remaining -= nr; - } - - return n - remaining; - } - - /** - * Returns an estimate of the number of bytes that can be read (or - * skipped over) from this input stream without blocking by the next - * invocation of a method for this input stream. The next invocation - * might be the same thread or another thread. A single read or skip of this - * many bytes will not block, but may read or skip fewer bytes. - * - *

Note that while some implementations of {@code InputStream} will return - * the total number of bytes in the stream, many will not. It is - * never correct to use the return value of this method to allocate - * a buffer intended to hold all data in this stream. - * - *

A subclass' implementation of this method may choose to throw an - * {@link IOException} if this input stream has been closed by - * invoking the {@link #close()} method. - * - *

The {@code available} method for class {@code InputStream} always - * returns {@code 0}. - * - *

This method should be overridden by subclasses. - * - * @return an estimate of the number of bytes that can be read (or skipped - * over) from this input stream without blocking or {@code 0} when - * it reaches the end of the input stream. - * @exception IOException if an I/O error occurs. - */ - public int available() throws IOException { - return 0; - } - - /** - * Closes this input stream and releases any system resources associated - * with the stream. - * - *

The close method of InputStream does - * nothing. - * - * @exception IOException if an I/O error occurs. - */ - public void close() throws IOException {} - - /** - * Marks the current position in this input stream. A subsequent call to - * the reset method repositions this stream at the last marked - * position so that subsequent reads re-read the same bytes. - * - *

The readlimit arguments tells this input stream to - * allow that many bytes to be read before the mark position gets - * invalidated. - * - *

The general contract of mark is that, if the method - * markSupported returns true, the stream somehow - * remembers all the bytes read after the call to mark and - * stands ready to supply those same bytes again if and whenever the method - * reset is called. However, the stream is not required to - * remember any data at all if more than readlimit bytes are - * read from the stream before reset is called. - * - *

Marking a closed stream should not have any effect on the stream. - * - *

The mark method of InputStream does - * nothing. - * - * @param readlimit the maximum limit of bytes that can be read before - * the mark position becomes invalid. - * @see java.io.InputStream#reset() - */ - public synchronized void mark(int readlimit) {} - - /** - * Repositions this stream to the position at the time the - * mark method was last called on this input stream. - * - *

The general contract of reset is: - * - *

    - * - *
  • If the method markSupported returns - * true, then: - * - *
    • If the method mark has not been called since - * the stream was created, or the number of bytes read from the stream - * since mark was last called is larger than the argument - * to mark at that last call, then an - * IOException might be thrown. - * - *
    • If such an IOException is not thrown, then the - * stream is reset to a state such that all the bytes read since the - * most recent call to mark (or since the start of the - * file, if mark has not been called) will be resupplied - * to subsequent callers of the read method, followed by - * any bytes that otherwise would have been the next input data as of - * the time of the call to reset.
    - * - *
  • If the method markSupported returns - * false, then: - * - *
    • The call to reset may throw an - * IOException. - * - *
    • If an IOException is not thrown, then the stream - * is reset to a fixed state that depends on the particular type of the - * input stream and how it was created. The bytes that will be supplied - * to subsequent callers of the read method depend on the - * particular type of the input stream.
- * - *

The method reset for class InputStream - * does nothing except throw an IOException. - * - * @exception IOException if this stream has not been marked or if the - * mark has been invalidated. - * @see java.io.InputStream#mark(int) - * @see java.io.IOException - */ - public synchronized void reset() throws IOException { - throw new IOException("mark/reset not supported"); - } - - /** - * Tests if this input stream supports the mark and - * reset methods. Whether or not mark and - * reset are supported is an invariant property of a - * particular input stream instance. The markSupported method - * of InputStream returns false. - * - * @return true if this stream instance supports the mark - * and reset methods; false otherwise. - * @see java.io.InputStream#mark(int) - * @see java.io.InputStream#reset() - */ - public boolean markSupported() { - return false; - } - -} diff -r 388e48c0a37a -r 05224402145d emul/src/main/java/java/io/PushbackInputStream.java --- a/emul/src/main/java/java/io/PushbackInputStream.java Wed Jan 23 20:16:48 2013 +0100 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,388 +0,0 @@ -/* - * Copyright (c) 1994, 2011, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code 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 - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package java.io; - -/** - * A PushbackInputStream adds - * functionality to another input stream, namely - * the ability to "push back" or "unread" - * one byte. This is useful in situations where - * it is convenient for a fragment of code - * to read an indefinite number of data bytes - * that are delimited by a particular byte - * value; after reading the terminating byte, - * the code fragment can "unread" it, so that - * the next read operation on the input stream - * will reread the byte that was pushed back. - * For example, bytes representing the characters - * constituting an identifier might be terminated - * by a byte representing an operator character; - * a method whose job is to read just an identifier - * can read until it sees the operator and - * then push the operator back to be re-read. - * - * @author David Connelly - * @author Jonathan Payne - * @since JDK1.0 - */ -public -class PushbackInputStream extends FilterInputStream { - /** - * The pushback buffer. - * @since JDK1.1 - */ - protected byte[] buf; - - /** - * The position within the pushback buffer from which the next byte will - * be read. When the buffer is empty, pos is equal to - * buf.length; when the buffer is full, pos is - * equal to zero. - * - * @since JDK1.1 - */ - protected int pos; - - /** - * Check to make sure that this stream has not been closed - */ - private void ensureOpen() throws IOException { - if (in == null) - throw new IOException("Stream closed"); - } - - /** - * Creates a PushbackInputStream - * with a pushback buffer of the specified size, - * and saves its argument, the input stream - * in, for later use. Initially, - * there is no pushed-back byte (the field - * pushBack is initialized to - * -1). - * - * @param in the input stream from which bytes will be read. - * @param size the size of the pushback buffer. - * @exception IllegalArgumentException if size is <= 0 - * @since JDK1.1 - */ - public PushbackInputStream(InputStream in, int size) { - super(in); - if (size <= 0) { - throw new IllegalArgumentException("size <= 0"); - } - this.buf = new byte[size]; - this.pos = size; - } - - /** - * Creates a PushbackInputStream - * and saves its argument, the input stream - * in, for later use. Initially, - * there is no pushed-back byte (the field - * pushBack is initialized to - * -1). - * - * @param in the input stream from which bytes will be read. - */ - public PushbackInputStream(InputStream in) { - this(in, 1); - } - - /** - * Reads the next byte of data from this input stream. The value - * byte is returned as an int in the range - * 0 to 255. If no byte is available - * because the end of the stream has been reached, the value - * -1 is returned. This method blocks until input data - * is available, the end of the stream is detected, or an exception - * is thrown. - * - *

This method returns the most recently pushed-back byte, if there is - * one, and otherwise calls the read method of its underlying - * input stream and returns whatever value that method returns. - * - * @return the next byte of data, or -1 if the end of the - * stream has been reached. - * @exception IOException if this input stream has been closed by - * invoking its {@link #close()} method, - * or an I/O error occurs. - * @see java.io.InputStream#read() - */ - public int read() throws IOException { - ensureOpen(); - if (pos < buf.length) { - return buf[pos++] & 0xff; - } - return super.read(); - } - - /** - * Reads up to len bytes of data from this input stream into - * an array of bytes. This method first reads any pushed-back bytes; after - * that, if fewer than len bytes have been read then it - * reads from the underlying input stream. If len is not zero, the method - * blocks until at least 1 byte of input is available; otherwise, no - * bytes are read and 0 is returned. - * - * @param b the buffer into which the data is read. - * @param off the start offset in the destination array b - * @param len the maximum number of bytes read. - * @return the total number of bytes read into the buffer, or - * -1 if there is no more data because the end of - * the stream has been reached. - * @exception NullPointerException If b is null. - * @exception IndexOutOfBoundsException If off is negative, - * len is negative, or len is greater than - * b.length - off - * @exception IOException if this input stream has been closed by - * invoking its {@link #close()} method, - * or an I/O error occurs. - * @see java.io.InputStream#read(byte[], int, int) - */ - public int read(byte[] b, int off, int len) throws IOException { - ensureOpen(); - if (b == null) { - throw new NullPointerException(); - } else if (off < 0 || len < 0 || len > b.length - off) { - throw new IndexOutOfBoundsException(); - } else if (len == 0) { - return 0; - } - - int avail = buf.length - pos; - if (avail > 0) { - if (len < avail) { - avail = len; - } - arraycopy(buf, pos, b, off, avail); - pos += avail; - off += avail; - len -= avail; - } - if (len > 0) { - len = super.read(b, off, len); - if (len == -1) { - return avail == 0 ? -1 : avail; - } - return avail + len; - } - return avail; - } - - /** - * Pushes back a byte by copying it to the front of the pushback buffer. - * After this method returns, the next byte to be read will have the value - * (byte)b. - * - * @param b the int value whose low-order - * byte is to be pushed back. - * @exception IOException If there is not enough room in the pushback - * buffer for the byte, or this input stream has been closed by - * invoking its {@link #close()} method. - */ - public void unread(int b) throws IOException { - ensureOpen(); - if (pos == 0) { - throw new IOException("Push back buffer is full"); - } - buf[--pos] = (byte)b; - } - - /** - * Pushes back a portion of an array of bytes by copying it to the front - * of the pushback buffer. After this method returns, the next byte to be - * read will have the value b[off], the byte after that will - * have the value b[off+1], and so forth. - * - * @param b the byte array to push back. - * @param off the start offset of the data. - * @param len the number of bytes to push back. - * @exception IOException If there is not enough room in the pushback - * buffer for the specified number of bytes, - * or this input stream has been closed by - * invoking its {@link #close()} method. - * @since JDK1.1 - */ - public void unread(byte[] b, int off, int len) throws IOException { - ensureOpen(); - if (len > pos) { - throw new IOException("Push back buffer is full"); - } - pos -= len; - arraycopy(b, off, buf, pos, len); - } - - /** - * Pushes back an array of bytes by copying it to the front of the - * pushback buffer. After this method returns, the next byte to be read - * will have the value b[0], the byte after that will have the - * value b[1], and so forth. - * - * @param b the byte array to push back - * @exception IOException If there is not enough room in the pushback - * buffer for the specified number of bytes, - * or this input stream has been closed by - * invoking its {@link #close()} method. - * @since JDK1.1 - */ - public void unread(byte[] b) throws IOException { - unread(b, 0, b.length); - } - - /** - * Returns an estimate of the number of bytes that can be read (or - * skipped over) from this input stream without blocking by the next - * invocation of a method for this input stream. The next invocation might be - * the same thread or another thread. A single read or skip of this - * many bytes will not block, but may read or skip fewer bytes. - * - *

The method returns the sum of the number of bytes that have been - * pushed back and the value returned by {@link - * java.io.FilterInputStream#available available}. - * - * @return the number of bytes that can be read (or skipped over) from - * the input stream without blocking. - * @exception IOException if this input stream has been closed by - * invoking its {@link #close()} method, - * or an I/O error occurs. - * @see java.io.FilterInputStream#in - * @see java.io.InputStream#available() - */ - public int available() throws IOException { - ensureOpen(); - int n = buf.length - pos; - int avail = super.available(); - return n > (Integer.MAX_VALUE - avail) - ? Integer.MAX_VALUE - : n + avail; - } - - /** - * Skips over and discards n bytes of data from this - * input stream. The skip method may, for a variety of - * reasons, end up skipping over some smaller number of bytes, - * possibly zero. If n is negative, no bytes are skipped. - * - *

The skip method of PushbackInputStream - * first skips over the bytes in the pushback buffer, if any. It then - * calls the skip method of the underlying input stream if - * more bytes need to be skipped. The actual number of bytes skipped - * is returned. - * - * @param n {@inheritDoc} - * @return {@inheritDoc} - * @exception IOException if the stream does not support seek, - * or the stream has been closed by - * invoking its {@link #close()} method, - * or an I/O error occurs. - * @see java.io.FilterInputStream#in - * @see java.io.InputStream#skip(long n) - * @since 1.2 - */ - public long skip(long n) throws IOException { - ensureOpen(); - if (n <= 0) { - return 0; - } - - long pskip = buf.length - pos; - if (pskip > 0) { - if (n < pskip) { - pskip = n; - } - pos += pskip; - n -= pskip; - } - if (n > 0) { - pskip += super.skip(n); - } - return pskip; - } - - /** - * Tests if this input stream supports the mark and - * reset methods, which it does not. - * - * @return false, since this class does not support the - * mark and reset methods. - * @see java.io.InputStream#mark(int) - * @see java.io.InputStream#reset() - */ - public boolean markSupported() { - return false; - } - - /** - * Marks the current position in this input stream. - * - *

The mark method of PushbackInputStream - * does nothing. - * - * @param readlimit the maximum limit of bytes that can be read before - * the mark position becomes invalid. - * @see java.io.InputStream#reset() - */ - public synchronized void mark(int readlimit) { - } - - /** - * Repositions this stream to the position at the time the - * mark method was last called on this input stream. - * - *

The method reset for class - * PushbackInputStream does nothing except throw an - * IOException. - * - * @exception IOException if this method is invoked. - * @see java.io.InputStream#mark(int) - * @see java.io.IOException - */ - public synchronized void reset() throws IOException { - throw new IOException("mark/reset not supported"); - } - - /** - * Closes this input stream and releases any system resources - * associated with the stream. - * Once the stream has been closed, further read(), unread(), - * available(), reset(), or skip() invocations will throw an IOException. - * Closing a previously closed stream has no effect. - * - * @exception IOException if an I/O error occurs. - */ - public synchronized void close() throws IOException { - if (in == null) - return; - in.close(); - in = null; - buf = null; - } - static void arraycopy(byte[] value, int srcBegin, byte[] dst, int dstBegin, int count) { - while (count-- > 0) { - dst[dstBegin++] = value[srcBegin++]; - } - } -} diff -r 388e48c0a37a -r 05224402145d emul/src/main/java/java/io/Serializable.java --- a/emul/src/main/java/java/io/Serializable.java Wed Jan 23 20:16:48 2013 +0100 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,170 +0,0 @@ -/* - * Copyright (c) 1996, 2005, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code 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 - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package java.io; - -/** - * Serializability of a class is enabled by the class implementing the - * java.io.Serializable interface. Classes that do not implement this - * interface will not have any of their state serialized or - * deserialized. All subtypes of a serializable class are themselves - * serializable. The serialization interface has no methods or fields - * and serves only to identify the semantics of being serializable.

- * - * To allow subtypes of non-serializable classes to be serialized, the - * subtype may assume responsibility for saving and restoring the - * state of the supertype's public, protected, and (if accessible) - * package fields. The subtype may assume this responsibility only if - * the class it extends has an accessible no-arg constructor to - * initialize the class's state. It is an error to declare a class - * Serializable if this is not the case. The error will be detected at - * runtime.

- * - * During deserialization, the fields of non-serializable classes will - * be initialized using the public or protected no-arg constructor of - * the class. A no-arg constructor must be accessible to the subclass - * that is serializable. The fields of serializable subclasses will - * be restored from the stream.

- * - * When traversing a graph, an object may be encountered that does not - * support the Serializable interface. In this case the - * NotSerializableException will be thrown and will identify the class - * of the non-serializable object.

- * - * Classes that require special handling during the serialization and - * deserialization process must implement special methods with these exact - * signatures:

- * - *

- * private void writeObject(java.io.ObjectOutputStream out)
- *     throws IOException
- * private void readObject(java.io.ObjectInputStream in)
- *     throws IOException, ClassNotFoundException;
- * private void readObjectNoData()
- *     throws ObjectStreamException;
- * 
- * - *

The writeObject method is responsible for writing the state of the - * object for its particular class so that the corresponding - * readObject method can restore it. The default mechanism for saving - * the Object's fields can be invoked by calling - * out.defaultWriteObject. The method does not need to concern - * itself with the state belonging to its superclasses or subclasses. - * State is saved by writing the individual fields to the - * ObjectOutputStream using the writeObject method or by using the - * methods for primitive data types supported by DataOutput. - * - *

The readObject method is responsible for reading from the stream and - * restoring the classes fields. It may call in.defaultReadObject to invoke - * the default mechanism for restoring the object's non-static and - * non-transient fields. The defaultReadObject method uses information in - * the stream to assign the fields of the object saved in the stream with the - * correspondingly named fields in the current object. This handles the case - * when the class has evolved to add new fields. The method does not need to - * concern itself with the state belonging to its superclasses or subclasses. - * State is saved by writing the individual fields to the - * ObjectOutputStream using the writeObject method or by using the - * methods for primitive data types supported by DataOutput. - * - *

The readObjectNoData method is responsible for initializing the state of - * the object for its particular class in the event that the serialization - * stream does not list the given class as a superclass of the object being - * deserialized. This may occur in cases where the receiving party uses a - * different version of the deserialized instance's class than the sending - * party, and the receiver's version extends classes that are not extended by - * the sender's version. This may also occur if the serialization stream has - * been tampered; hence, readObjectNoData is useful for initializing - * deserialized objects properly despite a "hostile" or incomplete source - * stream. - * - *

Serializable classes that need to designate an alternative object to be - * used when writing an object to the stream should implement this - * special method with the exact signature:

- * - *

- * ANY-ACCESS-MODIFIER Object writeReplace() throws ObjectStreamException;
- * 

- * - * This writeReplace method is invoked by serialization if the method - * exists and it would be accessible from a method defined within the - * class of the object being serialized. Thus, the method can have private, - * protected and package-private access. Subclass access to this method - * follows java accessibility rules.

- * - * Classes that need to designate a replacement when an instance of it - * is read from the stream should implement this special method with the - * exact signature.

- * - *

- * ANY-ACCESS-MODIFIER Object readResolve() throws ObjectStreamException;
- * 

- * - * This readResolve method follows the same invocation rules and - * accessibility rules as writeReplace.

- * - * The serialization runtime associates with each serializable class a version - * number, called a serialVersionUID, which is used during deserialization to - * verify that the sender and receiver of a serialized object have loaded - * classes for that object that are compatible with respect to serialization. - * If the receiver has loaded a class for the object that has a different - * serialVersionUID than that of the corresponding sender's class, then - * deserialization will result in an {@link InvalidClassException}. A - * serializable class can declare its own serialVersionUID explicitly by - * declaring a field named "serialVersionUID" that must be static, - * final, and of type long:

- * - *

- * ANY-ACCESS-MODIFIER static final long serialVersionUID = 42L;
- * 
- * - * If a serializable class does not explicitly declare a serialVersionUID, then - * the serialization runtime will calculate a default serialVersionUID value - * for that class based on various aspects of the class, as described in the - * Java(TM) Object Serialization Specification. However, it is strongly - * recommended that all serializable classes explicitly declare - * serialVersionUID values, since the default serialVersionUID computation is - * highly sensitive to class details that may vary depending on compiler - * implementations, and can thus result in unexpected - * InvalidClassExceptions during deserialization. Therefore, to - * guarantee a consistent serialVersionUID value across different java compiler - * implementations, a serializable class must declare an explicit - * serialVersionUID value. It is also strongly advised that explicit - * serialVersionUID declarations use the private modifier where - * possible, since such declarations apply only to the immediately declaring - * class--serialVersionUID fields are not useful as inherited members. Array - * classes cannot declare an explicit serialVersionUID, so they always have - * the default computed value, but the requirement for matching - * serialVersionUID values is waived for array classes. - * - * @author unascribed - * @see java.io.ObjectOutputStream - * @see java.io.ObjectInputStream - * @see java.io.ObjectOutput - * @see java.io.ObjectInput - * @see java.io.Externalizable - * @since JDK1.1 - */ -public interface Serializable { -} diff -r 388e48c0a37a -r 05224402145d emul/src/main/java/java/io/UTFDataFormatException.java --- a/emul/src/main/java/java/io/UTFDataFormatException.java Wed Jan 23 20:16:48 2013 +0100 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,69 +0,0 @@ -/* - * Copyright (c) 1995, 2008, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code 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 - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package java.io; - -/** - * Signals that a malformed string in - * modified UTF-8 - * format has been read in a data - * input stream or by any class that implements the data input - * interface. - * See the - * DataInput - * class description for the format in - * which modified UTF-8 strings are read and written. - * - * @author Frank Yellin - * @see java.io.DataInput - * @see java.io.DataInputStream#readUTF(java.io.DataInput) - * @see java.io.IOException - * @since JDK1.0 - */ -public -class UTFDataFormatException extends IOException { - private static final long serialVersionUID = 420743449228280612L; - - /** - * Constructs a UTFDataFormatException with - * null as its error detail message. - */ - public UTFDataFormatException() { - super(); - } - - /** - * Constructs a UTFDataFormatException with the - * specified detail message. The string s can be - * retrieved later by the - * {@link java.lang.Throwable#getMessage} - * method of class java.lang.Throwable. - * - * @param s the detail message. - */ - public UTFDataFormatException(String s) { - super(s); - } -} diff -r 388e48c0a37a -r 05224402145d emul/src/main/java/java/io/UnsupportedEncodingException.java --- a/emul/src/main/java/java/io/UnsupportedEncodingException.java Wed Jan 23 20:16:48 2013 +0100 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,52 +0,0 @@ -/* - * Copyright (c) 1996, 2008, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code 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 - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ -package java.io; - -/** - * The Character Encoding is not supported. - * - * @author Asmus Freytag - * @since JDK1.1 - */ -public class UnsupportedEncodingException - extends IOException -{ - private static final long serialVersionUID = -4274276298326136670L; - - /** - * Constructs an UnsupportedEncodingException without a detail message. - */ - public UnsupportedEncodingException() { - super(); - } - - /** - * Constructs an UnsupportedEncodingException with a detail message. - * @param s Describes the reason for the exception. - */ - public UnsupportedEncodingException(String s) { - super(s); - } -} diff -r 388e48c0a37a -r 05224402145d emul/src/main/java/java/lang/AbstractStringBuilder.java --- a/emul/src/main/java/java/lang/AbstractStringBuilder.java Wed Jan 23 20:16:48 2013 +0100 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,1424 +0,0 @@ -/* - * Copyright (c) 2003, 2010, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code 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 - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package java.lang; - -/** - * A mutable sequence of characters. - *

- * Implements a modifiable string. At any point in time it contains some - * particular sequence of characters, but the length and content of the - * sequence can be changed through certain method calls. - * - * @author Michael McCloskey - * @author Martin Buchholz - * @author Ulf Zibis - * @since 1.5 - */ -abstract class AbstractStringBuilder implements Appendable, CharSequence { - /** - * The value is used for character storage. - */ - char[] value; - - /** - * The count is the number of characters used. - */ - int count; - - /** - * This no-arg constructor is necessary for serialization of subclasses. - */ - AbstractStringBuilder() { - } - - /** - * Creates an AbstractStringBuilder of the specified capacity. - */ - AbstractStringBuilder(int capacity) { - value = new char[capacity]; - } - - /** - * Returns the length (character count). - * - * @return the length of the sequence of characters currently - * represented by this object - */ - public int length() { - return count; - } - - /** - * Returns the current capacity. The capacity is the amount of storage - * available for newly inserted characters, beyond which an allocation - * will occur. - * - * @return the current capacity - */ - public int capacity() { - return value.length; - } - - /** - * Ensures that the capacity is at least equal to the specified minimum. - * If the current capacity is less than the argument, then a new internal - * array is allocated with greater capacity. The new capacity is the - * larger of: - *

    - *
  • The minimumCapacity argument. - *
  • Twice the old capacity, plus 2. - *
- * If the minimumCapacity argument is nonpositive, this - * method takes no action and simply returns. - * - * @param minimumCapacity the minimum desired capacity. - */ - public void ensureCapacity(int minimumCapacity) { - if (minimumCapacity > 0) - ensureCapacityInternal(minimumCapacity); - } - - /** - * This method has the same contract as ensureCapacity, but is - * never synchronized. - */ - private void ensureCapacityInternal(int minimumCapacity) { - // overflow-conscious code - if (minimumCapacity - value.length > 0) - expandCapacity(minimumCapacity); - } - - /** - * This implements the expansion semantics of ensureCapacity with no - * size check or synchronization. - */ - void expandCapacity(int minimumCapacity) { - int newCapacity = value.length * 2 + 2; - if (newCapacity - minimumCapacity < 0) - newCapacity = minimumCapacity; - if (newCapacity < 0) { - if (minimumCapacity < 0) // overflow - throw new OutOfMemoryError(); - newCapacity = Integer.MAX_VALUE; - } - value = copyOf(value, newCapacity); - } - - /** - * Attempts to reduce storage used for the character sequence. - * If the buffer is larger than necessary to hold its current sequence of - * characters, then it may be resized to become more space efficient. - * Calling this method may, but is not required to, affect the value - * returned by a subsequent call to the {@link #capacity()} method. - */ - public void trimToSize() { - if (count < value.length) { - value = copyOf(value, count); - } - } - - /** - * Sets the length of the character sequence. - * The sequence is changed to a new character sequence - * whose length is specified by the argument. For every nonnegative - * index k less than newLength, the character at - * index k in the new character sequence is the same as the - * character at index k in the old sequence if k is less - * than the length of the old character sequence; otherwise, it is the - * null character '\u0000'. - * - * In other words, if the newLength argument is less than - * the current length, the length is changed to the specified length. - *

- * If the newLength argument is greater than or equal - * to the current length, sufficient null characters - * ('\u0000') are appended so that - * length becomes the newLength argument. - *

- * The newLength argument must be greater than or equal - * to 0. - * - * @param newLength the new length - * @throws IndexOutOfBoundsException if the - * newLength argument is negative. - */ - public void setLength(int newLength) { - if (newLength < 0) - throw new StringIndexOutOfBoundsException(newLength); - ensureCapacityInternal(newLength); - - if (count < newLength) { - for (; count < newLength; count++) - value[count] = '\0'; - } else { - count = newLength; - } - } - - /** - * Returns the char value in this sequence at the specified index. - * The first char value is at index 0, the next at index - * 1, and so on, as in array indexing. - *

- * The index argument must be greater than or equal to - * 0, and less than the length of this sequence. - * - *

If the char value specified by the index is a - * surrogate, the surrogate - * value is returned. - * - * @param index the index of the desired char value. - * @return the char value at the specified index. - * @throws IndexOutOfBoundsException if index is - * negative or greater than or equal to length(). - */ - public char charAt(int index) { - if ((index < 0) || (index >= count)) - throw new StringIndexOutOfBoundsException(index); - return value[index]; - } - - /** - * Returns the character (Unicode code point) at the specified - * index. The index refers to char values - * (Unicode code units) and ranges from 0 to - * {@link #length()} - 1. - * - *

If the char value specified at the given index - * is in the high-surrogate range, the following index is less - * than the length of this sequence, and the - * char value at the following index is in the - * low-surrogate range, then the supplementary code point - * corresponding to this surrogate pair is returned. Otherwise, - * the char value at the given index is returned. - * - * @param index the index to the char values - * @return the code point value of the character at the - * index - * @exception IndexOutOfBoundsException if the index - * argument is negative or not less than the length of this - * sequence. - */ - public int codePointAt(int index) { - if ((index < 0) || (index >= count)) { - throw new StringIndexOutOfBoundsException(index); - } - return Character.codePointAt(value, index); - } - - /** - * Returns the character (Unicode code point) before the specified - * index. The index refers to char values - * (Unicode code units) and ranges from 1 to {@link - * #length()}. - * - *

If the char value at (index - 1) - * is in the low-surrogate range, (index - 2) is not - * negative, and the char value at (index - - * 2) is in the high-surrogate range, then the - * supplementary code point value of the surrogate pair is - * returned. If the char value at index - - * 1 is an unpaired low-surrogate or a high-surrogate, the - * surrogate value is returned. - * - * @param index the index following the code point that should be returned - * @return the Unicode code point value before the given index. - * @exception IndexOutOfBoundsException if the index - * argument is less than 1 or greater than the length - * of this sequence. - */ - public int codePointBefore(int index) { - int i = index - 1; - if ((i < 0) || (i >= count)) { - throw new StringIndexOutOfBoundsException(index); - } - return Character.codePointBefore(value, index); - } - - /** - * Returns the number of Unicode code points in the specified text - * range of this sequence. The text range begins at the specified - * beginIndex and extends to the char at - * index endIndex - 1. Thus the length (in - * chars) of the text range is - * endIndex-beginIndex. Unpaired surrogates within - * this sequence count as one code point each. - * - * @param beginIndex the index to the first char of - * the text range. - * @param endIndex the index after the last char of - * the text range. - * @return the number of Unicode code points in the specified text - * range - * @exception IndexOutOfBoundsException if the - * beginIndex is negative, or endIndex - * is larger than the length of this sequence, or - * beginIndex is larger than endIndex. - */ - public int codePointCount(int beginIndex, int endIndex) { - if (beginIndex < 0 || endIndex > count || beginIndex > endIndex) { - throw new IndexOutOfBoundsException(); - } - return Character.codePointCountImpl(value, beginIndex, endIndex-beginIndex); - } - - /** - * Returns the index within this sequence that is offset from the - * given index by codePointOffset code - * points. Unpaired surrogates within the text range given by - * index and codePointOffset count as - * one code point each. - * - * @param index the index to be offset - * @param codePointOffset the offset in code points - * @return the index within this sequence - * @exception IndexOutOfBoundsException if index - * is negative or larger then the length of this sequence, - * or if codePointOffset is positive and the subsequence - * starting with index has fewer than - * codePointOffset code points, - * or if codePointOffset is negative and the subsequence - * before index has fewer than the absolute value of - * codePointOffset code points. - */ - public int offsetByCodePoints(int index, int codePointOffset) { - if (index < 0 || index > count) { - throw new IndexOutOfBoundsException(); - } - return Character.offsetByCodePointsImpl(value, 0, count, - index, codePointOffset); - } - - /** - * Characters are copied from this sequence into the - * destination character array dst. The first character to - * be copied is at index srcBegin; the last character to - * be copied is at index srcEnd-1. The total number of - * characters to be copied is srcEnd-srcBegin. The - * characters are copied into the subarray of dst starting - * at index dstBegin and ending at index: - *

-     * dstbegin + (srcEnd-srcBegin) - 1
-     * 
- * - * @param srcBegin start copying at this offset. - * @param srcEnd stop copying at this offset. - * @param dst the array to copy the data into. - * @param dstBegin offset into dst. - * @throws NullPointerException if dst is - * null. - * @throws IndexOutOfBoundsException if any of the following is true: - *
    - *
  • srcBegin is negative - *
  • dstBegin is negative - *
  • the srcBegin argument is greater than - * the srcEnd argument. - *
  • srcEnd is greater than - * this.length(). - *
  • dstBegin+srcEnd-srcBegin is greater than - * dst.length - *
- */ - public void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin) - { - if (srcBegin < 0) - throw new StringIndexOutOfBoundsException(srcBegin); - if ((srcEnd < 0) || (srcEnd > count)) - throw new StringIndexOutOfBoundsException(srcEnd); - if (srcBegin > srcEnd) - throw new StringIndexOutOfBoundsException("srcBegin > srcEnd"); - arraycopy(value, srcBegin, dst, dstBegin, srcEnd - srcBegin); - } - - /** - * The character at the specified index is set to ch. This - * sequence is altered to represent a new character sequence that is - * identical to the old character sequence, except that it contains the - * character ch at position index. - *

- * The index argument must be greater than or equal to - * 0, and less than the length of this sequence. - * - * @param index the index of the character to modify. - * @param ch the new character. - * @throws IndexOutOfBoundsException if index is - * negative or greater than or equal to length(). - */ - public void setCharAt(int index, char ch) { - if ((index < 0) || (index >= count)) - throw new StringIndexOutOfBoundsException(index); - value[index] = ch; - } - - /** - * Appends the string representation of the {@code Object} argument. - *

- * The overall effect is exactly as if the argument were converted - * to a string by the method {@link String#valueOf(Object)}, - * and the characters of that string were then - * {@link #append(String) appended} to this character sequence. - * - * @param obj an {@code Object}. - * @return a reference to this object. - */ - public AbstractStringBuilder append(Object obj) { - return append(String.valueOf(obj)); - } - - /** - * Appends the specified string to this character sequence. - *

- * The characters of the {@code String} argument are appended, in - * order, increasing the length of this sequence by the length of the - * argument. If {@code str} is {@code null}, then the four - * characters {@code "null"} are appended. - *

- * Let n be the length of this character sequence just prior to - * execution of the {@code append} method. Then the character at - * index k in the new character sequence is equal to the character - * at index k in the old character sequence, if k is less - * than n; otherwise, it is equal to the character at index - * k-n in the argument {@code str}. - * - * @param str a string. - * @return a reference to this object. - */ - public AbstractStringBuilder append(String str) { - if (str == null) str = "null"; - int len = str.length(); - ensureCapacityInternal(count + len); - str.getChars(0, len, value, count); - count += len; - return this; - } - - // Documentation in subclasses because of synchro difference - public AbstractStringBuilder append(StringBuffer sb) { - if (sb == null) - return append("null"); - int len = sb.length(); - ensureCapacityInternal(count + len); - sb.getChars(0, len, value, count); - count += len; - return this; - } - - // Documentation in subclasses because of synchro difference - public AbstractStringBuilder append(CharSequence s) { - if (s == null) - s = "null"; - if (s instanceof String) - return this.append((String)s); - if (s instanceof StringBuffer) - return this.append((StringBuffer)s); - return this.append(s, 0, s.length()); - } - - /** - * Appends a subsequence of the specified {@code CharSequence} to this - * sequence. - *

- * Characters of the argument {@code s}, starting at - * index {@code start}, are appended, in order, to the contents of - * this sequence up to the (exclusive) index {@code end}. The length - * of this sequence is increased by the value of {@code end - start}. - *

- * Let n be the length of this character sequence just prior to - * execution of the {@code append} method. Then the character at - * index k in this character sequence becomes equal to the - * character at index k in this sequence, if k is less than - * n; otherwise, it is equal to the character at index - * k+start-n in the argument {@code s}. - *

- * If {@code s} is {@code null}, then this method appends - * characters as if the s parameter was a sequence containing the four - * characters {@code "null"}. - * - * @param s the sequence to append. - * @param start the starting index of the subsequence to be appended. - * @param end the end index of the subsequence to be appended. - * @return a reference to this object. - * @throws IndexOutOfBoundsException if - * {@code start} is negative, or - * {@code start} is greater than {@code end} or - * {@code end} is greater than {@code s.length()} - */ - public AbstractStringBuilder append(CharSequence s, int start, int end) { - if (s == null) - s = "null"; - if ((start < 0) || (start > end) || (end > s.length())) - throw new IndexOutOfBoundsException( - "start " + start + ", end " + end + ", s.length() " - + s.length()); - int len = end - start; - ensureCapacityInternal(count + len); - for (int i = start, j = count; i < end; i++, j++) - value[j] = s.charAt(i); - count += len; - return this; - } - - /** - * Appends the string representation of the {@code char} array - * argument to this sequence. - *

- * The characters of the array argument are appended, in order, to - * the contents of this sequence. The length of this sequence - * increases by the length of the argument. - *

- * The overall effect is exactly as if the argument were converted - * to a string by the method {@link String#valueOf(char[])}, - * and the characters of that string were then - * {@link #append(String) appended} to this character sequence. - * - * @param str the characters to be appended. - * @return a reference to this object. - */ - public AbstractStringBuilder append(char[] str) { - int len = str.length; - ensureCapacityInternal(count + len); - arraycopy(str, 0, value, count, len); - count += len; - return this; - } - - /** - * Appends the string representation of a subarray of the - * {@code char} array argument to this sequence. - *

- * Characters of the {@code char} array {@code str}, starting at - * index {@code offset}, are appended, in order, to the contents - * of this sequence. The length of this sequence increases - * by the value of {@code len}. - *

- * The overall effect is exactly as if the arguments were converted - * to a string by the method {@link String#valueOf(char[],int,int)}, - * and the characters of that string were then - * {@link #append(String) appended} to this character sequence. - * - * @param str the characters to be appended. - * @param offset the index of the first {@code char} to append. - * @param len the number of {@code char}s to append. - * @return a reference to this object. - * @throws IndexOutOfBoundsException - * if {@code offset < 0} or {@code len < 0} - * or {@code offset+len > str.length} - */ - public AbstractStringBuilder append(char str[], int offset, int len) { - if (len > 0) // let arraycopy report AIOOBE for len < 0 - ensureCapacityInternal(count + len); - arraycopy(str, offset, value, count, len); - count += len; - return this; - } - - /** - * Appends the string representation of the {@code boolean} - * argument to the sequence. - *

- * The overall effect is exactly as if the argument were converted - * to a string by the method {@link String#valueOf(boolean)}, - * and the characters of that string were then - * {@link #append(String) appended} to this character sequence. - * - * @param b a {@code boolean}. - * @return a reference to this object. - */ - public AbstractStringBuilder append(boolean b) { - if (b) { - ensureCapacityInternal(count + 4); - value[count++] = 't'; - value[count++] = 'r'; - value[count++] = 'u'; - value[count++] = 'e'; - } else { - ensureCapacityInternal(count + 5); - value[count++] = 'f'; - value[count++] = 'a'; - value[count++] = 'l'; - value[count++] = 's'; - value[count++] = 'e'; - } - return this; - } - - /** - * Appends the string representation of the {@code char} - * argument to this sequence. - *

- * The argument is appended to the contents of this sequence. - * The length of this sequence increases by {@code 1}. - *

- * The overall effect is exactly as if the argument were converted - * to a string by the method {@link String#valueOf(char)}, - * and the character in that string were then - * {@link #append(String) appended} to this character sequence. - * - * @param c a {@code char}. - * @return a reference to this object. - */ - public AbstractStringBuilder append(char c) { - ensureCapacityInternal(count + 1); - value[count++] = c; - return this; - } - - /** - * Appends the string representation of the {@code int} - * argument to this sequence. - *

- * The overall effect is exactly as if the argument were converted - * to a string by the method {@link String#valueOf(int)}, - * and the characters of that string were then - * {@link #append(String) appended} to this character sequence. - * - * @param i an {@code int}. - * @return a reference to this object. - */ - public AbstractStringBuilder append(int i) { - return append(Integer.toString(i)); - } - - /** - * Appends the string representation of the {@code long} - * argument to this sequence. - *

- * The overall effect is exactly as if the argument were converted - * to a string by the method {@link String#valueOf(long)}, - * and the characters of that string were then - * {@link #append(String) appended} to this character sequence. - * - * @param l a {@code long}. - * @return a reference to this object. - */ - public AbstractStringBuilder append(long l) { - if (l == Long.MIN_VALUE) { - append("-9223372036854775808"); - return this; - } - int appendedLength = (l < 0) ? Long.stringSize(-l) + 1 - : Long.stringSize(l); - int spaceNeeded = count + appendedLength; - ensureCapacityInternal(spaceNeeded); - Long.getChars(l, spaceNeeded, value); - count = spaceNeeded; - return this; - } - - /** - * Appends the string representation of the {@code float} - * argument to this sequence. - *

- * The overall effect is exactly as if the argument were converted - * to a string by the method {@link String#valueOf(float)}, - * and the characters of that string were then - * {@link #append(String) appended} to this character sequence. - * - * @param f a {@code float}. - * @return a reference to this object. - */ - public AbstractStringBuilder append(float f) { - return append(Float.toString(f)); - } - - /** - * Appends the string representation of the {@code double} - * argument to this sequence. - *

- * The overall effect is exactly as if the argument were converted - * to a string by the method {@link String#valueOf(double)}, - * and the characters of that string were then - * {@link #append(String) appended} to this character sequence. - * - * @param d a {@code double}. - * @return a reference to this object. - */ - public AbstractStringBuilder append(double d) { - return append(Double.toString(d)); - } - - /** - * Removes the characters in a substring of this sequence. - * The substring begins at the specified {@code start} and extends to - * the character at index {@code end - 1} or to the end of the - * sequence if no such character exists. If - * {@code start} is equal to {@code end}, no changes are made. - * - * @param start The beginning index, inclusive. - * @param end The ending index, exclusive. - * @return This object. - * @throws StringIndexOutOfBoundsException if {@code start} - * is negative, greater than {@code length()}, or - * greater than {@code end}. - */ - public AbstractStringBuilder delete(int start, int end) { - if (start < 0) - throw new StringIndexOutOfBoundsException(start); - if (end > count) - end = count; - if (start > end) - throw new StringIndexOutOfBoundsException(); - int len = end - start; - if (len > 0) { - arraycopy(value, start+len, value, start, count-end); - count -= len; - } - return this; - } - - /** - * Appends the string representation of the {@code codePoint} - * argument to this sequence. - * - *

The argument is appended to the contents of this sequence. - * The length of this sequence increases by - * {@link Character#charCount(int) Character.charCount(codePoint)}. - * - *

The overall effect is exactly as if the argument were - * converted to a {@code char} array by the method - * {@link Character#toChars(int)} and the character in that array - * were then {@link #append(char[]) appended} to this character - * sequence. - * - * @param codePoint a Unicode code point - * @return a reference to this object. - * @exception IllegalArgumentException if the specified - * {@code codePoint} isn't a valid Unicode code point - */ - public AbstractStringBuilder appendCodePoint(int codePoint) { - final int count = this.count; - - if (Character.isBmpCodePoint(codePoint)) { - ensureCapacityInternal(count + 1); - value[count] = (char) codePoint; - this.count = count + 1; - } else if (Character.isValidCodePoint(codePoint)) { - ensureCapacityInternal(count + 2); - Character.toSurrogates(codePoint, value, count); - this.count = count + 2; - } else { - throw new IllegalArgumentException(); - } - return this; - } - - /** - * Removes the char at the specified position in this - * sequence. This sequence is shortened by one char. - * - *

Note: If the character at the given index is a supplementary - * character, this method does not remove the entire character. If - * correct handling of supplementary characters is required, - * determine the number of chars to remove by calling - * Character.charCount(thisSequence.codePointAt(index)), - * where thisSequence is this sequence. - * - * @param index Index of char to remove - * @return This object. - * @throws StringIndexOutOfBoundsException if the index - * is negative or greater than or equal to - * length(). - */ - public AbstractStringBuilder deleteCharAt(int index) { - if ((index < 0) || (index >= count)) - throw new StringIndexOutOfBoundsException(index); - arraycopy(value, index+1, value, index, count-index-1); - count--; - return this; - } - - /** - * Replaces the characters in a substring of this sequence - * with characters in the specified String. The substring - * begins at the specified start and extends to the character - * at index end - 1 or to the end of the - * sequence if no such character exists. First the - * characters in the substring are removed and then the specified - * String is inserted at start. (This - * sequence will be lengthened to accommodate the - * specified String if necessary.) - * - * @param start The beginning index, inclusive. - * @param end The ending index, exclusive. - * @param str String that will replace previous contents. - * @return This object. - * @throws StringIndexOutOfBoundsException if start - * is negative, greater than length(), or - * greater than end. - */ - public AbstractStringBuilder replace(int start, int end, String str) { - if (start < 0) - throw new StringIndexOutOfBoundsException(start); - if (start > count) - throw new StringIndexOutOfBoundsException("start > length()"); - if (start > end) - throw new StringIndexOutOfBoundsException("start > end"); - - if (end > count) - end = count; - int len = str.length(); - int newCount = count + len - (end - start); - ensureCapacityInternal(newCount); - - arraycopy(value, end, value, start + len, count - end); - str.getChars(value, start); - count = newCount; - return this; - } - - /** - * Returns a new String that contains a subsequence of - * characters currently contained in this character sequence. The - * substring begins at the specified index and extends to the end of - * this sequence. - * - * @param start The beginning index, inclusive. - * @return The new string. - * @throws StringIndexOutOfBoundsException if start is - * less than zero, or greater than the length of this object. - */ - public String substring(int start) { - return substring(start, count); - } - - /** - * Returns a new character sequence that is a subsequence of this sequence. - * - *

An invocation of this method of the form - * - *

-     * sb.subSequence(begin, end)
- * - * behaves in exactly the same way as the invocation - * - *
-     * sb.substring(begin, end)
- * - * This method is provided so that this class can - * implement the {@link CharSequence} interface.

- * - * @param start the start index, inclusive. - * @param end the end index, exclusive. - * @return the specified subsequence. - * - * @throws IndexOutOfBoundsException - * if start or end are negative, - * if end is greater than length(), - * or if start is greater than end - * @spec JSR-51 - */ - public CharSequence subSequence(int start, int end) { - return substring(start, end); - } - - /** - * Returns a new String that contains a subsequence of - * characters currently contained in this sequence. The - * substring begins at the specified start and - * extends to the character at index end - 1. - * - * @param start The beginning index, inclusive. - * @param end The ending index, exclusive. - * @return The new string. - * @throws StringIndexOutOfBoundsException if start - * or end are negative or greater than - * length(), or start is - * greater than end. - */ - public String substring(int start, int end) { - if (start < 0) - throw new StringIndexOutOfBoundsException(start); - if (end > count) - throw new StringIndexOutOfBoundsException(end); - if (start > end) - throw new StringIndexOutOfBoundsException(end - start); - return new String(value, start, end - start); - } - - /** - * Inserts the string representation of a subarray of the {@code str} - * array argument into this sequence. The subarray begins at the - * specified {@code offset} and extends {@code len} {@code char}s. - * The characters of the subarray are inserted into this sequence at - * the position indicated by {@code index}. The length of this - * sequence increases by {@code len} {@code char}s. - * - * @param index position at which to insert subarray. - * @param str A {@code char} array. - * @param offset the index of the first {@code char} in subarray to - * be inserted. - * @param len the number of {@code char}s in the subarray to - * be inserted. - * @return This object - * @throws StringIndexOutOfBoundsException if {@code index} - * is negative or greater than {@code length()}, or - * {@code offset} or {@code len} are negative, or - * {@code (offset+len)} is greater than - * {@code str.length}. - */ - public AbstractStringBuilder insert(int index, char[] str, int offset, - int len) - { - if ((index < 0) || (index > length())) - throw new StringIndexOutOfBoundsException(index); - if ((offset < 0) || (len < 0) || (offset > str.length - len)) - throw new StringIndexOutOfBoundsException( - "offset " + offset + ", len " + len + ", str.length " - + str.length); - ensureCapacityInternal(count + len); - arraycopy(value, index, value, index + len, count - index); - arraycopy(str, offset, value, index, len); - count += len; - return this; - } - - /** - * Inserts the string representation of the {@code Object} - * argument into this character sequence. - *

- * The overall effect is exactly as if the second argument were - * converted to a string by the method {@link String#valueOf(Object)}, - * and the characters of that string were then - * {@link #insert(int,String) inserted} into this character - * sequence at the indicated offset. - *

- * The {@code offset} argument must be greater than or equal to - * {@code 0}, and less than or equal to the {@linkplain #length() length} - * of this sequence. - * - * @param offset the offset. - * @param obj an {@code Object}. - * @return a reference to this object. - * @throws StringIndexOutOfBoundsException if the offset is invalid. - */ - public AbstractStringBuilder insert(int offset, Object obj) { - return insert(offset, String.valueOf(obj)); - } - - /** - * Inserts the string into this character sequence. - *

- * The characters of the {@code String} argument are inserted, in - * order, into this sequence at the indicated offset, moving up any - * characters originally above that position and increasing the length - * of this sequence by the length of the argument. If - * {@code str} is {@code null}, then the four characters - * {@code "null"} are inserted into this sequence. - *

- * The character at index k in the new character sequence is - * equal to: - *

    - *
  • the character at index k in the old character sequence, if - * k is less than {@code offset} - *
  • the character at index k{@code -offset} in the - * argument {@code str}, if k is not less than - * {@code offset} but is less than {@code offset+str.length()} - *
  • the character at index k{@code -str.length()} in the - * old character sequence, if k is not less than - * {@code offset+str.length()} - *

- * The {@code offset} argument must be greater than or equal to - * {@code 0}, and less than or equal to the {@linkplain #length() length} - * of this sequence. - * - * @param offset the offset. - * @param str a string. - * @return a reference to this object. - * @throws StringIndexOutOfBoundsException if the offset is invalid. - */ - public AbstractStringBuilder insert(int offset, String str) { - if ((offset < 0) || (offset > length())) - throw new StringIndexOutOfBoundsException(offset); - if (str == null) - str = "null"; - int len = str.length(); - ensureCapacityInternal(count + len); - arraycopy(value, offset, value, offset + len, count - offset); - str.getChars(value, offset); - count += len; - return this; - } - - /** - * Inserts the string representation of the {@code char} array - * argument into this sequence. - *

- * The characters of the array argument are inserted into the - * contents of this sequence at the position indicated by - * {@code offset}. The length of this sequence increases by - * the length of the argument. - *

- * The overall effect is exactly as if the second argument were - * converted to a string by the method {@link String#valueOf(char[])}, - * and the characters of that string were then - * {@link #insert(int,String) inserted} into this character - * sequence at the indicated offset. - *

- * The {@code offset} argument must be greater than or equal to - * {@code 0}, and less than or equal to the {@linkplain #length() length} - * of this sequence. - * - * @param offset the offset. - * @param str a character array. - * @return a reference to this object. - * @throws StringIndexOutOfBoundsException if the offset is invalid. - */ - public AbstractStringBuilder insert(int offset, char[] str) { - if ((offset < 0) || (offset > length())) - throw new StringIndexOutOfBoundsException(offset); - int len = str.length; - ensureCapacityInternal(count + len); - arraycopy(value, offset, value, offset + len, count - offset); - arraycopy(str, 0, value, offset, len); - count += len; - return this; - } - - /** - * Inserts the specified {@code CharSequence} into this sequence. - *

- * The characters of the {@code CharSequence} argument are inserted, - * in order, into this sequence at the indicated offset, moving up - * any characters originally above that position and increasing the length - * of this sequence by the length of the argument s. - *

- * The result of this method is exactly the same as if it were an - * invocation of this object's - * {@link #insert(int,CharSequence,int,int) insert}(dstOffset, s, 0, s.length()) - * method. - * - *

If {@code s} is {@code null}, then the four characters - * {@code "null"} are inserted into this sequence. - * - * @param dstOffset the offset. - * @param s the sequence to be inserted - * @return a reference to this object. - * @throws IndexOutOfBoundsException if the offset is invalid. - */ - public AbstractStringBuilder insert(int dstOffset, CharSequence s) { - if (s == null) - s = "null"; - if (s instanceof String) - return this.insert(dstOffset, (String)s); - return this.insert(dstOffset, s, 0, s.length()); - } - - /** - * Inserts a subsequence of the specified {@code CharSequence} into - * this sequence. - *

- * The subsequence of the argument {@code s} specified by - * {@code start} and {@code end} are inserted, - * in order, into this sequence at the specified destination offset, moving - * up any characters originally above that position. The length of this - * sequence is increased by {@code end - start}. - *

- * The character at index k in this sequence becomes equal to: - *

    - *
  • the character at index k in this sequence, if - * k is less than {@code dstOffset} - *
  • the character at index k{@code +start-dstOffset} in - * the argument {@code s}, if k is greater than or equal to - * {@code dstOffset} but is less than {@code dstOffset+end-start} - *
  • the character at index k{@code -(end-start)} in this - * sequence, if k is greater than or equal to - * {@code dstOffset+end-start} - *

- * The {@code dstOffset} argument must be greater than or equal to - * {@code 0}, and less than or equal to the {@linkplain #length() length} - * of this sequence. - *

The start argument must be nonnegative, and not greater than - * {@code end}. - *

The end argument must be greater than or equal to - * {@code start}, and less than or equal to the length of s. - * - *

If {@code s} is {@code null}, then this method inserts - * characters as if the s parameter was a sequence containing the four - * characters {@code "null"}. - * - * @param dstOffset the offset in this sequence. - * @param s the sequence to be inserted. - * @param start the starting index of the subsequence to be inserted. - * @param end the end index of the subsequence to be inserted. - * @return a reference to this object. - * @throws IndexOutOfBoundsException if {@code dstOffset} - * is negative or greater than {@code this.length()}, or - * {@code start} or {@code end} are negative, or - * {@code start} is greater than {@code end} or - * {@code end} is greater than {@code s.length()} - */ - public AbstractStringBuilder insert(int dstOffset, CharSequence s, - int start, int end) { - if (s == null) - s = "null"; - if ((dstOffset < 0) || (dstOffset > this.length())) - throw new IndexOutOfBoundsException("dstOffset "+dstOffset); - if ((start < 0) || (end < 0) || (start > end) || (end > s.length())) - throw new IndexOutOfBoundsException( - "start " + start + ", end " + end + ", s.length() " - + s.length()); - int len = end - start; - ensureCapacityInternal(count + len); - arraycopy(value, dstOffset, value, dstOffset + len, - count - dstOffset); - for (int i=start; i - * The overall effect is exactly as if the second argument were - * converted to a string by the method {@link String#valueOf(boolean)}, - * and the characters of that string were then - * {@link #insert(int,String) inserted} into this character - * sequence at the indicated offset. - *

- * The {@code offset} argument must be greater than or equal to - * {@code 0}, and less than or equal to the {@linkplain #length() length} - * of this sequence. - * - * @param offset the offset. - * @param b a {@code boolean}. - * @return a reference to this object. - * @throws StringIndexOutOfBoundsException if the offset is invalid. - */ - public AbstractStringBuilder insert(int offset, boolean b) { - return insert(offset, String.valueOf(b)); - } - - /** - * Inserts the string representation of the {@code char} - * argument into this sequence. - *

- * The overall effect is exactly as if the second argument were - * converted to a string by the method {@link String#valueOf(char)}, - * and the character in that string were then - * {@link #insert(int,String) inserted} into this character - * sequence at the indicated offset. - *

- * The {@code offset} argument must be greater than or equal to - * {@code 0}, and less than or equal to the {@linkplain #length() length} - * of this sequence. - * - * @param offset the offset. - * @param c a {@code char}. - * @return a reference to this object. - * @throws IndexOutOfBoundsException if the offset is invalid. - */ - public AbstractStringBuilder insert(int offset, char c) { - ensureCapacityInternal(count + 1); - arraycopy(value, offset, value, offset + 1, count - offset); - value[offset] = c; - count += 1; - return this; - } - - /** - * Inserts the string representation of the second {@code int} - * argument into this sequence. - *

- * The overall effect is exactly as if the second argument were - * converted to a string by the method {@link String#valueOf(int)}, - * and the characters of that string were then - * {@link #insert(int,String) inserted} into this character - * sequence at the indicated offset. - *

- * The {@code offset} argument must be greater than or equal to - * {@code 0}, and less than or equal to the {@linkplain #length() length} - * of this sequence. - * - * @param offset the offset. - * @param i an {@code int}. - * @return a reference to this object. - * @throws StringIndexOutOfBoundsException if the offset is invalid. - */ - public AbstractStringBuilder insert(int offset, int i) { - return insert(offset, String.valueOf(i)); - } - - /** - * Inserts the string representation of the {@code long} - * argument into this sequence. - *

- * The overall effect is exactly as if the second argument were - * converted to a string by the method {@link String#valueOf(long)}, - * and the characters of that string were then - * {@link #insert(int,String) inserted} into this character - * sequence at the indicated offset. - *

- * The {@code offset} argument must be greater than or equal to - * {@code 0}, and less than or equal to the {@linkplain #length() length} - * of this sequence. - * - * @param offset the offset. - * @param l a {@code long}. - * @return a reference to this object. - * @throws StringIndexOutOfBoundsException if the offset is invalid. - */ - public AbstractStringBuilder insert(int offset, long l) { - return insert(offset, String.valueOf(l)); - } - - /** - * Inserts the string representation of the {@code float} - * argument into this sequence. - *

- * The overall effect is exactly as if the second argument were - * converted to a string by the method {@link String#valueOf(float)}, - * and the characters of that string were then - * {@link #insert(int,String) inserted} into this character - * sequence at the indicated offset. - *

- * The {@code offset} argument must be greater than or equal to - * {@code 0}, and less than or equal to the {@linkplain #length() length} - * of this sequence. - * - * @param offset the offset. - * @param f a {@code float}. - * @return a reference to this object. - * @throws StringIndexOutOfBoundsException if the offset is invalid. - */ - public AbstractStringBuilder insert(int offset, float f) { - return insert(offset, String.valueOf(f)); - } - - /** - * Inserts the string representation of the {@code double} - * argument into this sequence. - *

- * The overall effect is exactly as if the second argument were - * converted to a string by the method {@link String#valueOf(double)}, - * and the characters of that string were then - * {@link #insert(int,String) inserted} into this character - * sequence at the indicated offset. - *

- * The {@code offset} argument must be greater than or equal to - * {@code 0}, and less than or equal to the {@linkplain #length() length} - * of this sequence. - * - * @param offset the offset. - * @param d a {@code double}. - * @return a reference to this object. - * @throws StringIndexOutOfBoundsException if the offset is invalid. - */ - public AbstractStringBuilder insert(int offset, double d) { - return insert(offset, String.valueOf(d)); - } - - /** - * Returns the index within this string of the first occurrence of the - * specified substring. The integer returned is the smallest value - * k such that: - *

-     * this.toString().startsWith(str, k)
-     * 
- * is true. - * - * @param str any string. - * @return if the string argument occurs as a substring within this - * object, then the index of the first character of the first - * such substring is returned; if it does not occur as a - * substring, -1 is returned. - * @throws java.lang.NullPointerException if str is - * null. - */ - public int indexOf(String str) { - return indexOf(str, 0); - } - - /** - * Returns the index within this string of the first occurrence of the - * specified substring, starting at the specified index. The integer - * returned is the smallest value k for which: - *
-     *     k >= Math.min(fromIndex, str.length()) &&
-     *                   this.toString().startsWith(str, k)
-     * 
- * If no such value of k exists, then -1 is returned. - * - * @param str the substring for which to search. - * @param fromIndex the index from which to start the search. - * @return the index within this string of the first occurrence of the - * specified substring, starting at the specified index. - * @throws java.lang.NullPointerException if str is - * null. - */ - public int indexOf(String str, int fromIndex) { - return toString().indexOf(str, fromIndex); - } - - /** - * Returns the index within this string of the rightmost occurrence - * of the specified substring. The rightmost empty string "" is - * considered to occur at the index value this.length(). - * The returned index is the largest value k such that - *
-     * this.toString().startsWith(str, k)
-     * 
- * is true. - * - * @param str the substring to search for. - * @return if the string argument occurs one or more times as a substring - * within this object, then the index of the first character of - * the last such substring is returned. If it does not occur as - * a substring, -1 is returned. - * @throws java.lang.NullPointerException if str is - * null. - */ - public int lastIndexOf(String str) { - return lastIndexOf(str, count); - } - - /** - * Returns the index within this string of the last occurrence of the - * specified substring. The integer returned is the largest value k - * such that: - *
-     *     k <= Math.min(fromIndex, str.length()) &&
-     *                   this.toString().startsWith(str, k)
-     * 
- * If no such value of k exists, then -1 is returned. - * - * @param str the substring to search for. - * @param fromIndex the index to start the search from. - * @return the index within this sequence of the last occurrence of the - * specified substring. - * @throws java.lang.NullPointerException if str is - * null. - */ - public int lastIndexOf(String str, int fromIndex) { - return String.lastIndexOf(value, 0, count, - str.toCharArray(), 0, str.length(), fromIndex); - } - - /** - * Causes this character sequence to be replaced by the reverse of - * the sequence. If there are any surrogate pairs included in the - * sequence, these are treated as single characters for the - * reverse operation. Thus, the order of the high-low surrogates - * is never reversed. - * - * Let n be the character length of this character sequence - * (not the length in char values) just prior to - * execution of the reverse method. Then the - * character at index k in the new character sequence is - * equal to the character at index n-k-1 in the old - * character sequence. - * - *

Note that the reverse operation may result in producing - * surrogate pairs that were unpaired low-surrogates and - * high-surrogates before the operation. For example, reversing - * "\uDC00\uD800" produces "\uD800\uDC00" which is - * a valid surrogate pair. - * - * @return a reference to this object. - */ - public AbstractStringBuilder reverse() { - boolean hasSurrogate = false; - int n = count - 1; - for (int j = (n-1) >> 1; j >= 0; --j) { - char temp = value[j]; - char temp2 = value[n - j]; - if (!hasSurrogate) { - hasSurrogate = (temp >= Character.MIN_SURROGATE && temp <= Character.MAX_SURROGATE) - || (temp2 >= Character.MIN_SURROGATE && temp2 <= Character.MAX_SURROGATE); - } - value[j] = temp2; - value[n - j] = temp; - } - if (hasSurrogate) { - // Reverse back all valid surrogate pairs - for (int i = 0; i < count - 1; i++) { - char c2 = value[i]; - if (Character.isLowSurrogate(c2)) { - char c1 = value[i + 1]; - if (Character.isHighSurrogate(c1)) { - value[i++] = c1; - value[i] = c2; - } - } - } - } - return this; - } - - /** - * Returns a string representing the data in this sequence. - * A new String object is allocated and initialized to - * contain the character sequence currently represented by this - * object. This String is then returned. Subsequent - * changes to this sequence do not affect the contents of the - * String. - * - * @return a string representation of this sequence of characters. - */ - public abstract String toString(); - - /** - * Needed by String for the contentEquals method. - */ - final char[] getValue() { - return value; - } - - static char[] copyOfRange(char[] original, int from, int to) { - int newLength = to - from; - if (newLength < 0) { - throw new IllegalArgumentException(from + " > " + to); - } - char[] copy = new char[newLength]; - arraycopy(original, from, copy, 0, Math.min(original.length - from, newLength)); - return copy; - } - - static void arraycopy(char[] value, int srcBegin, char[] dst, int dstBegin, int count) { - if (srcBegin < dstBegin) { - while (count-- > 0) { - dst[dstBegin + count] = value[srcBegin + count]; - } - } else { - while (count-- > 0) { - dst[dstBegin++] = value[srcBegin++]; - } - } - } - - // access system property - static String getProperty(String nm) { - return null; - } - - static char[] copyOf(char[] original, int newLength) { - char[] copy = new char[newLength]; - arraycopy(original, 0, copy, 0, Math.min(original.length, newLength)); - return copy; - } - -} diff -r 388e48c0a37a -r 05224402145d emul/src/main/java/java/lang/Appendable.java --- a/emul/src/main/java/java/lang/Appendable.java Wed Jan 23 20:16:48 2013 +0100 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,121 +0,0 @@ -/* - * Copyright (c) 2003, 2004, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code 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 - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package java.lang; - -import java.io.IOException; - -/** - * An object to which char sequences and values can be appended. The - * Appendable interface must be implemented by any class whose - * instances are intended to receive formatted output from a {@link - * java.util.Formatter}. - * - *

The characters to be appended should be valid Unicode characters as - * described in Unicode Character - * Representation. Note that supplementary characters may be composed of - * multiple 16-bit char values. - * - *

Appendables are not necessarily safe for multithreaded access. Thread - * safety is the responsibility of classes that extend and implement this - * interface. - * - *

Since this interface may be implemented by existing classes - * with different styles of error handling there is no guarantee that - * errors will be propagated to the invoker. - * - * @since 1.5 - */ -public interface Appendable { - - /** - * Appends the specified character sequence to this Appendable. - * - *

Depending on which class implements the character sequence - * csq, the entire sequence may not be appended. For - * instance, if csq is a {@link java.nio.CharBuffer} then - * the subsequence to append is defined by the buffer's position and limit. - * - * @param csq - * The character sequence to append. If csq is - * null, then the four characters "null" are - * appended to this Appendable. - * - * @return A reference to this Appendable - * - * @throws IOException - * If an I/O error occurs - */ - Appendable append(CharSequence csq) throws IOException; - - /** - * Appends a subsequence of the specified character sequence to this - * Appendable. - * - *

An invocation of this method of the form out.append(csq, start, - * end) when csq is not null, behaves in - * exactly the same way as the invocation - * - *

-     *     out.append(csq.subSequence(start, end)) 
- * - * @param csq - * The character sequence from which a subsequence will be - * appended. If csq is null, then characters - * will be appended as if csq contained the four - * characters "null". - * - * @param start - * The index of the first character in the subsequence - * - * @param end - * The index of the character following the last character in the - * subsequence - * - * @return A reference to this Appendable - * - * @throws IndexOutOfBoundsException - * If start or end are negative, start - * is greater than end, or end is greater than - * csq.length() - * - * @throws IOException - * If an I/O error occurs - */ - Appendable append(CharSequence csq, int start, int end) throws IOException; - - /** - * Appends the specified character to this Appendable. - * - * @param c - * The character to append - * - * @return A reference to this Appendable - * - * @throws IOException - * If an I/O error occurs - */ - Appendable append(char c) throws IOException; -} diff -r 388e48c0a37a -r 05224402145d emul/src/main/java/java/lang/ArrayIndexOutOfBoundsException.java --- a/emul/src/main/java/java/lang/ArrayIndexOutOfBoundsException.java Wed Jan 23 20:16:48 2013 +0100 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,67 +0,0 @@ -/* - * Copyright (c) 1994, 2008, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code 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 - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package java.lang; - -/** - * Thrown to indicate that an array has been accessed with an - * illegal index. The index is either negative or greater than or - * equal to the size of the array. - * - * @author unascribed - * @since JDK1.0 - */ -public -class ArrayIndexOutOfBoundsException extends IndexOutOfBoundsException { - private static final long serialVersionUID = -5116101128118950844L; - - /** - * Constructs an ArrayIndexOutOfBoundsException with no - * detail message. - */ - public ArrayIndexOutOfBoundsException() { - super(); - } - - /** - * Constructs a new ArrayIndexOutOfBoundsException - * class with an argument indicating the illegal index. - * - * @param index the illegal index. - */ - public ArrayIndexOutOfBoundsException(int index) { - super("Array index out of range: " + index); - } - - /** - * Constructs an ArrayIndexOutOfBoundsException class - * with the specified detail message. - * - * @param s the detail message. - */ - public ArrayIndexOutOfBoundsException(String s) { - super(s); - } -} diff -r 388e48c0a37a -r 05224402145d emul/src/main/java/java/lang/AssertionError.java --- a/emul/src/main/java/java/lang/AssertionError.java Wed Jan 23 20:16:48 2013 +0100 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,167 +0,0 @@ -/* - * Copyright (c) 2000, 2010, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code 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 - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package java.lang; - -/** - * Thrown to indicate that an assertion has failed. - * - *

The seven one-argument public constructors provided by this - * class ensure that the assertion error returned by the invocation: - *

- *     new AssertionError(expression)
- * 
- * has as its detail message the string conversion of - * expression (as defined in section 15.18.1.1 of - * The Java™ Language Specification), - * regardless of the type of expression. - * - * @since 1.4 - */ -public class AssertionError extends Error { - private static final long serialVersionUID = -5013299493970297370L; - - /** - * Constructs an AssertionError with no detail message. - */ - public AssertionError() { - } - - /** - * This internal constructor does no processing on its string argument, - * even if it is a null reference. The public constructors will - * never call this constructor with a null argument. - */ - private AssertionError(String detailMessage) { - super(detailMessage); - } - - /** - * Constructs an AssertionError with its detail message derived - * from the specified object, which is converted to a string as - * defined in section 15.18.1.1 of - * The Java™ Language Specification. - *

- * If the specified object is an instance of {@code Throwable}, it - * becomes the cause of the newly constructed assertion error. - * - * @param detailMessage value to be used in constructing detail message - * @see Throwable#getCause() - */ - public AssertionError(Object detailMessage) { - this("" + detailMessage); - if (detailMessage instanceof Throwable) - initCause((Throwable) detailMessage); - } - - /** - * Constructs an AssertionError with its detail message derived - * from the specified boolean, which is converted to - * a string as defined in section 15.18.1.1 of - * The Java™ Language Specification. - * - * @param detailMessage value to be used in constructing detail message - */ - public AssertionError(boolean detailMessage) { - this("" + detailMessage); - } - - /** - * Constructs an AssertionError with its detail message derived - * from the specified char, which is converted to a - * string as defined in section 15.18.1.1 of - * The Java™ Language Specification. - * - * @param detailMessage value to be used in constructing detail message - */ - public AssertionError(char detailMessage) { - this("" + detailMessage); - } - - /** - * Constructs an AssertionError with its detail message derived - * from the specified int, which is converted to a - * string as defined in section 15.18.1.1 of - * The Java™ Language Specification. - * - * @param detailMessage value to be used in constructing detail message - */ - public AssertionError(int detailMessage) { - this("" + detailMessage); - } - - /** - * Constructs an AssertionError with its detail message derived - * from the specified long, which is converted to a - * string as defined in section 15.18.1.1 of - * The Java™ Language Specification. - * - * @param detailMessage value to be used in constructing detail message - */ - public AssertionError(long detailMessage) { - this("" + detailMessage); - } - - /** - * Constructs an AssertionError with its detail message derived - * from the specified float, which is converted to a - * string as defined in section 15.18.1.1 of - * The Java™ Language Specification. - * - * @param detailMessage value to be used in constructing detail message - */ - public AssertionError(float detailMessage) { - this("" + detailMessage); - } - - /** - * Constructs an AssertionError with its detail message derived - * from the specified double, which is converted to a - * string as defined in section 15.18.1.1 of - * The Java™ Language Specification. - * - * @param detailMessage value to be used in constructing detail message - */ - public AssertionError(double detailMessage) { - this("" + detailMessage); - } - - /** - * Constructs a new {@code AssertionError} with the specified - * detail message and cause. - * - *

Note that the detail message associated with - * {@code cause} is not automatically incorporated in - * this error's detail message. - * - * @param message the detail message, may be {@code null} - * @param cause the cause, may be {@code null} - * - * @since 1.7 - */ - public AssertionError(String message, Throwable cause) { - super(message, cause); - } -} diff -r 388e48c0a37a -r 05224402145d emul/src/main/java/java/lang/AutoCloseable.java --- a/emul/src/main/java/java/lang/AutoCloseable.java Wed Jan 23 20:16:48 2013 +0100 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,72 +0,0 @@ -/* - * Copyright (c) 2009, 2011, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code 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 - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package java.lang; - -/** - * A resource that must be closed when it is no longer needed. - * - * @author Josh Bloch - * @since 1.7 - */ -public interface AutoCloseable { - /** - * Closes this resource, relinquishing any underlying resources. - * This method is invoked automatically on objects managed by the - * {@code try}-with-resources statement. - * - *

While this interface method is declared to throw {@code - * Exception}, implementers are strongly encouraged to - * declare concrete implementations of the {@code close} method to - * throw more specific exceptions, or to throw no exception at all - * if the close operation cannot fail. - * - *

Implementers of this interface are also strongly advised - * to not have the {@code close} method throw {@link - * InterruptedException}. - * - * This exception interacts with a thread's interrupted status, - * and runtime misbehavior is likely to occur if an {@code - * InterruptedException} is {@linkplain Throwable#addSuppressed - * suppressed}. - * - * More generally, if it would cause problems for an - * exception to be suppressed, the {@code AutoCloseable.close} - * method should not throw it. - * - *

Note that unlike the {@link java.io.Closeable#close close} - * method of {@link java.io.Closeable}, this {@code close} method - * is not required to be idempotent. In other words, - * calling this {@code close} method more than once may have some - * visible side effect, unlike {@code Closeable.close} which is - * required to have no effect if called more than once. - * - * However, implementers of this interface are strongly encouraged - * to make their {@code close} methods idempotent. - * - * @throws Exception if this resource cannot be closed - */ - void close() throws Exception; -} diff -r 388e48c0a37a -r 05224402145d emul/src/main/java/java/lang/Boolean.java --- a/emul/src/main/java/java/lang/Boolean.java Wed Jan 23 20:16:48 2013 +0100 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,282 +0,0 @@ -/* - * Copyright (c) 1994, 2006, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code 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 - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package java.lang; - -/** - * The Boolean class wraps a value of the primitive type - * {@code boolean} in an object. An object of type - * {@code Boolean} contains a single field whose type is - * {@code boolean}. - *

- * In addition, this class provides many methods for - * converting a {@code boolean} to a {@code String} and a - * {@code String} to a {@code boolean}, as well as other - * constants and methods useful when dealing with a - * {@code boolean}. - * - * @author Arthur van Hoff - * @since JDK1.0 - */ -public final class Boolean implements java.io.Serializable, - Comparable -{ - /** - * The {@code Boolean} object corresponding to the primitive - * value {@code true}. - */ - public static final Boolean TRUE = new Boolean(true); - - /** - * The {@code Boolean} object corresponding to the primitive - * value {@code false}. - */ - public static final Boolean FALSE = new Boolean(false); - - /** - * The Class object representing the primitive type boolean. - * - * @since JDK1.1 - */ - public static final Class TYPE = Class.getPrimitiveClass("boolean"); - - /** - * The value of the Boolean. - * - * @serial - */ - private final boolean value; - - /** use serialVersionUID from JDK 1.0.2 for interoperability */ - private static final long serialVersionUID = -3665804199014368530L; - - /** - * Allocates a {@code Boolean} object representing the - * {@code value} argument. - * - *

Note: It is rarely appropriate to use this constructor. - * Unless a new instance is required, the static factory - * {@link #valueOf(boolean)} is generally a better choice. It is - * likely to yield significantly better space and time performance. - * - * @param value the value of the {@code Boolean}. - */ - public Boolean(boolean value) { - this.value = value; - } - - /** - * Allocates a {@code Boolean} object representing the value - * {@code true} if the string argument is not {@code null} - * and is equal, ignoring case, to the string {@code "true"}. - * Otherwise, allocate a {@code Boolean} object representing the - * value {@code false}. Examples:

- * {@code new Boolean("True")} produces a {@code Boolean} object - * that represents {@code true}.
- * {@code new Boolean("yes")} produces a {@code Boolean} object - * that represents {@code false}. - * - * @param s the string to be converted to a {@code Boolean}. - */ - public Boolean(String s) { - this(toBoolean(s)); - } - - /** - * Parses the string argument as a boolean. The {@code boolean} - * returned represents the value {@code true} if the string argument - * is not {@code null} and is equal, ignoring case, to the string - * {@code "true"}.

- * Example: {@code Boolean.parseBoolean("True")} returns {@code true}.
- * Example: {@code Boolean.parseBoolean("yes")} returns {@code false}. - * - * @param s the {@code String} containing the boolean - * representation to be parsed - * @return the boolean represented by the string argument - * @since 1.5 - */ - public static boolean parseBoolean(String s) { - return toBoolean(s); - } - - /** - * Returns the value of this {@code Boolean} object as a boolean - * primitive. - * - * @return the primitive {@code boolean} value of this object. - */ - public boolean booleanValue() { - return value; - } - - /** - * Returns a {@code Boolean} instance representing the specified - * {@code boolean} value. If the specified {@code boolean} value - * is {@code true}, this method returns {@code Boolean.TRUE}; - * if it is {@code false}, this method returns {@code Boolean.FALSE}. - * If a new {@code Boolean} instance is not required, this method - * should generally be used in preference to the constructor - * {@link #Boolean(boolean)}, as this method is likely to yield - * significantly better space and time performance. - * - * @param b a boolean value. - * @return a {@code Boolean} instance representing {@code b}. - * @since 1.4 - */ - public static Boolean valueOf(boolean b) { - return (b ? TRUE : FALSE); - } - - /** - * Returns a {@code Boolean} with a value represented by the - * specified string. The {@code Boolean} returned represents a - * true value if the string argument is not {@code null} - * and is equal, ignoring case, to the string {@code "true"}. - * - * @param s a string. - * @return the {@code Boolean} value represented by the string. - */ - public static Boolean valueOf(String s) { - return toBoolean(s) ? TRUE : FALSE; - } - - /** - * Returns a {@code String} object representing the specified - * boolean. If the specified boolean is {@code true}, then - * the string {@code "true"} will be returned, otherwise the - * string {@code "false"} will be returned. - * - * @param b the boolean to be converted - * @return the string representation of the specified {@code boolean} - * @since 1.4 - */ - public static String toString(boolean b) { - return b ? "true" : "false"; - } - - /** - * Returns a {@code String} object representing this Boolean's - * value. If this object represents the value {@code true}, - * a string equal to {@code "true"} is returned. Otherwise, a - * string equal to {@code "false"} is returned. - * - * @return a string representation of this object. - */ - public String toString() { - return value ? "true" : "false"; - } - - /** - * Returns a hash code for this {@code Boolean} object. - * - * @return the integer {@code 1231} if this object represents - * {@code true}; returns the integer {@code 1237} if this - * object represents {@code false}. - */ - public int hashCode() { - return value ? 1231 : 1237; - } - - /** - * Returns {@code true} if and only if the argument is not - * {@code null} and is a {@code Boolean} object that - * represents the same {@code boolean} value as this object. - * - * @param obj the object to compare with. - * @return {@code true} if the Boolean objects represent the - * same value; {@code false} otherwise. - */ - public boolean equals(Object obj) { - if (obj instanceof Boolean) { - return value == ((Boolean)obj).booleanValue(); - } - return false; - } - - /** - * Returns {@code true} if and only if the system property - * named by the argument exists and is equal to the string - * {@code "true"}. (Beginning with version 1.0.2 of the - * JavaTM platform, the test of - * this string is case insensitive.) A system property is accessible - * through {@code getProperty}, a method defined by the - * {@code System} class. - *

- * If there is no property with the specified name, or if the specified - * name is empty or null, then {@code false} is returned. - * - * @param name the system property name. - * @return the {@code boolean} value of the system property. - * @see java.lang.System#getProperty(java.lang.String) - * @see java.lang.System#getProperty(java.lang.String, java.lang.String) - */ - public static boolean getBoolean(String name) { - boolean result = false; - try { - result = toBoolean(AbstractStringBuilder.getProperty(name)); - } catch (IllegalArgumentException e) { - } catch (NullPointerException e) { - } - return result; - } - - /** - * Compares this {@code Boolean} instance with another. - * - * @param b the {@code Boolean} instance to be compared - * @return zero if this object represents the same boolean value as the - * argument; a positive value if this object represents true - * and the argument represents false; and a negative value if - * this object represents false and the argument represents true - * @throws NullPointerException if the argument is {@code null} - * @see Comparable - * @since 1.5 - */ - public int compareTo(Boolean b) { - return compare(this.value, b.value); - } - - /** - * Compares two {@code boolean} values. - * The value returned is identical to what would be returned by: - *

-     *    Boolean.valueOf(x).compareTo(Boolean.valueOf(y))
-     * 
- * - * @param x the first {@code boolean} to compare - * @param y the second {@code boolean} to compare - * @return the value {@code 0} if {@code x == y}; - * a value less than {@code 0} if {@code !x && y}; and - * a value greater than {@code 0} if {@code x && !y} - * @since 1.7 - */ - public static int compare(boolean x, boolean y) { - return (x == y) ? 0 : (x ? 1 : -1); - } - - private static boolean toBoolean(String name) { - return ((name != null) && name.equalsIgnoreCase("true")); - } -} diff -r 388e48c0a37a -r 05224402145d emul/src/main/java/java/lang/Byte.java --- a/emul/src/main/java/java/lang/Byte.java Wed Jan 23 20:16:48 2013 +0100 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,452 +0,0 @@ -/* - * Copyright (c) 1996, 2009, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code 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 - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package java.lang; - -/** - * - * The {@code Byte} class wraps a value of primitive type {@code byte} - * in an object. An object of type {@code Byte} contains a single - * field whose type is {@code byte}. - * - *

In addition, this class provides several methods for converting - * a {@code byte} to a {@code String} and a {@code String} to a {@code - * byte}, as well as other constants and methods useful when dealing - * with a {@code byte}. - * - * @author Nakul Saraiya - * @author Joseph D. Darcy - * @see java.lang.Number - * @since JDK1.1 - */ -public final class Byte extends Number implements Comparable { - - /** - * A constant holding the minimum value a {@code byte} can - * have, -27. - */ - public static final byte MIN_VALUE = -128; - - /** - * A constant holding the maximum value a {@code byte} can - * have, 27-1. - */ - public static final byte MAX_VALUE = 127; - - /** - * The {@code Class} instance representing the primitive type - * {@code byte}. - */ - public static final Class TYPE = (Class) Class.getPrimitiveClass("byte"); - - /** - * Returns a new {@code String} object representing the - * specified {@code byte}. The radix is assumed to be 10. - * - * @param b the {@code byte} to be converted - * @return the string representation of the specified {@code byte} - * @see java.lang.Integer#toString(int) - */ - public static String toString(byte b) { - return Integer.toString((int)b, 10); - } - - private static class ByteCache { - private ByteCache(){} - - static final Byte cache[] = new Byte[-(-128) + 127 + 1]; - - static { - for(int i = 0; i < cache.length; i++) - cache[i] = new Byte((byte)(i - 128)); - } - } - - /** - * Returns a {@code Byte} instance representing the specified - * {@code byte} value. - * If a new {@code Byte} instance is not required, this method - * should generally be used in preference to the constructor - * {@link #Byte(byte)}, as this method is likely to yield - * significantly better space and time performance since - * all byte values are cached. - * - * @param b a byte value. - * @return a {@code Byte} instance representing {@code b}. - * @since 1.5 - */ - public static Byte valueOf(byte b) { - final int offset = 128; - return ByteCache.cache[(int)b + offset]; - } - - /** - * Parses the string argument as a signed {@code byte} in the - * radix specified by the second argument. The characters in the - * string must all be digits, of the specified radix (as - * determined by whether {@link java.lang.Character#digit(char, - * int)} returns a nonnegative value) except that the first - * character may be an ASCII minus sign {@code '-'} - * ('\u002D') to indicate a negative value or an - * ASCII plus sign {@code '+'} ('\u002B') to - * indicate a positive value. The resulting {@code byte} value is - * returned. - * - *

An exception of type {@code NumberFormatException} is - * thrown if any of the following situations occurs: - *

    - *
  • The first argument is {@code null} or is a string of - * length zero. - * - *
  • The radix is either smaller than {@link - * java.lang.Character#MIN_RADIX} or larger than {@link - * java.lang.Character#MAX_RADIX}. - * - *
  • Any character of the string is not a digit of the - * specified radix, except that the first character may be a minus - * sign {@code '-'} ('\u002D') or plus sign - * {@code '+'} ('\u002B') provided that the - * string is longer than length 1. - * - *
  • The value represented by the string is not a value of type - * {@code byte}. - *
- * - * @param s the {@code String} containing the - * {@code byte} - * representation to be parsed - * @param radix the radix to be used while parsing {@code s} - * @return the {@code byte} value represented by the string - * argument in the specified radix - * @throws NumberFormatException If the string does - * not contain a parsable {@code byte}. - */ - public static byte parseByte(String s, int radix) - throws NumberFormatException { - int i = Integer.parseInt(s, radix); - if (i < MIN_VALUE || i > MAX_VALUE) - throw new NumberFormatException( - "Value out of range. Value:\"" + s + "\" Radix:" + radix); - return (byte)i; - } - - /** - * Parses the string argument as a signed decimal {@code - * byte}. The characters in the string must all be decimal digits, - * except that the first character may be an ASCII minus sign - * {@code '-'} ('\u002D') to indicate a negative - * value or an ASCII plus sign {@code '+'} - * ('\u002B') to indicate a positive value. The - * resulting {@code byte} value is returned, exactly as if the - * argument and the radix 10 were given as arguments to the {@link - * #parseByte(java.lang.String, int)} method. - * - * @param s a {@code String} containing the - * {@code byte} representation to be parsed - * @return the {@code byte} value represented by the - * argument in decimal - * @throws NumberFormatException if the string does not - * contain a parsable {@code byte}. - */ - public static byte parseByte(String s) throws NumberFormatException { - return parseByte(s, 10); - } - - /** - * Returns a {@code Byte} object holding the value - * extracted from the specified {@code String} when parsed - * with the radix given by the second argument. The first argument - * is interpreted as representing a signed {@code byte} in - * the radix specified by the second argument, exactly as if the - * argument were given to the {@link #parseByte(java.lang.String, - * int)} method. The result is a {@code Byte} object that - * represents the {@code byte} value specified by the string. - * - *

In other words, this method returns a {@code Byte} object - * equal to the value of: - * - *

- * {@code new Byte(Byte.parseByte(s, radix))} - *
- * - * @param s the string to be parsed - * @param radix the radix to be used in interpreting {@code s} - * @return a {@code Byte} object holding the value - * represented by the string argument in the - * specified radix. - * @throws NumberFormatException If the {@code String} does - * not contain a parsable {@code byte}. - */ - public static Byte valueOf(String s, int radix) - throws NumberFormatException { - return valueOf(parseByte(s, radix)); - } - - /** - * Returns a {@code Byte} object holding the value - * given by the specified {@code String}. The argument is - * interpreted as representing a signed decimal {@code byte}, - * exactly as if the argument were given to the {@link - * #parseByte(java.lang.String)} method. The result is a - * {@code Byte} object that represents the {@code byte} - * value specified by the string. - * - *

In other words, this method returns a {@code Byte} object - * equal to the value of: - * - *

- * {@code new Byte(Byte.parseByte(s))} - *
- * - * @param s the string to be parsed - * @return a {@code Byte} object holding the value - * represented by the string argument - * @throws NumberFormatException If the {@code String} does - * not contain a parsable {@code byte}. - */ - public static Byte valueOf(String s) throws NumberFormatException { - return valueOf(s, 10); - } - - /** - * Decodes a {@code String} into a {@code Byte}. - * Accepts decimal, hexadecimal, and octal numbers given by - * the following grammar: - * - *
- *
- *
DecodableString: - *
Signopt DecimalNumeral - *
Signopt {@code 0x} HexDigits - *
Signopt {@code 0X} HexDigits - *
Signopt {@code #} HexDigits - *
Signopt {@code 0} OctalDigits - *

- *

Sign: - *
{@code -} - *
{@code +} - *
- *
- * - * DecimalNumeral, HexDigits, and OctalDigits - * are as defined in section 3.10.1 of - * The Java™ Language Specification, - * except that underscores are not accepted between digits. - * - *

The sequence of characters following an optional - * sign and/or radix specifier ("{@code 0x}", "{@code 0X}", - * "{@code #}", or leading zero) is parsed as by the {@code - * Byte.parseByte} method with the indicated radix (10, 16, or 8). - * This sequence of characters must represent a positive value or - * a {@link NumberFormatException} will be thrown. The result is - * negated if first character of the specified {@code String} is - * the minus sign. No whitespace characters are permitted in the - * {@code String}. - * - * @param nm the {@code String} to decode. - * @return a {@code Byte} object holding the {@code byte} - * value represented by {@code nm} - * @throws NumberFormatException if the {@code String} does not - * contain a parsable {@code byte}. - * @see java.lang.Byte#parseByte(java.lang.String, int) - */ - public static Byte decode(String nm) throws NumberFormatException { - int i = Integer.decode(nm); - if (i < MIN_VALUE || i > MAX_VALUE) - throw new NumberFormatException( - "Value " + i + " out of range from input " + nm); - return valueOf((byte)i); - } - - /** - * The value of the {@code Byte}. - * - * @serial - */ - private final byte value; - - /** - * Constructs a newly allocated {@code Byte} object that - * represents the specified {@code byte} value. - * - * @param value the value to be represented by the - * {@code Byte}. - */ - public Byte(byte value) { - this.value = value; - } - - /** - * Constructs a newly allocated {@code Byte} object that - * represents the {@code byte} value indicated by the - * {@code String} parameter. The string is converted to a - * {@code byte} value in exactly the manner used by the - * {@code parseByte} method for radix 10. - * - * @param s the {@code String} to be converted to a - * {@code Byte} - * @throws NumberFormatException If the {@code String} - * does not contain a parsable {@code byte}. - * @see java.lang.Byte#parseByte(java.lang.String, int) - */ - public Byte(String s) throws NumberFormatException { - this.value = parseByte(s, 10); - } - - /** - * Returns the value of this {@code Byte} as a - * {@code byte}. - */ - public byte byteValue() { - return value; - } - - /** - * Returns the value of this {@code Byte} as a - * {@code short}. - */ - public short shortValue() { - return (short)value; - } - - /** - * Returns the value of this {@code Byte} as an - * {@code int}. - */ - public int intValue() { - return (int)value; - } - - /** - * Returns the value of this {@code Byte} as a - * {@code long}. - */ - public long longValue() { - return (long)value; - } - - /** - * Returns the value of this {@code Byte} as a - * {@code float}. - */ - public float floatValue() { - return (float)value; - } - - /** - * Returns the value of this {@code Byte} as a - * {@code double}. - */ - public double doubleValue() { - return (double)value; - } - - /** - * Returns a {@code String} object representing this - * {@code Byte}'s value. The value is converted to signed - * decimal representation and returned as a string, exactly as if - * the {@code byte} value were given as an argument to the - * {@link java.lang.Byte#toString(byte)} method. - * - * @return a string representation of the value of this object in - * base 10. - */ - public String toString() { - return Integer.toString((int)value); - } - - /** - * Returns a hash code for this {@code Byte}; equal to the result - * of invoking {@code intValue()}. - * - * @return a hash code value for this {@code Byte} - */ - public int hashCode() { - return (int)value; - } - - /** - * Compares this object to the specified object. The result is - * {@code true} if and only if the argument is not - * {@code null} and is a {@code Byte} object that - * contains the same {@code byte} value as this object. - * - * @param obj the object to compare with - * @return {@code true} if the objects are the same; - * {@code false} otherwise. - */ - public boolean equals(Object obj) { - if (obj instanceof Byte) { - return value == ((Byte)obj).byteValue(); - } - return false; - } - - /** - * Compares two {@code Byte} objects numerically. - * - * @param anotherByte the {@code Byte} to be compared. - * @return the value {@code 0} if this {@code Byte} is - * equal to the argument {@code Byte}; a value less than - * {@code 0} if this {@code Byte} is numerically less - * than the argument {@code Byte}; and a value greater than - * {@code 0} if this {@code Byte} is numerically - * greater than the argument {@code Byte} (signed - * comparison). - * @since 1.2 - */ - public int compareTo(Byte anotherByte) { - return compare(this.value, anotherByte.value); - } - - /** - * Compares two {@code byte} values numerically. - * The value returned is identical to what would be returned by: - *

-     *    Byte.valueOf(x).compareTo(Byte.valueOf(y))
-     * 
- * - * @param x the first {@code byte} to compare - * @param y the second {@code byte} to compare - * @return the value {@code 0} if {@code x == y}; - * a value less than {@code 0} if {@code x < y}; and - * a value greater than {@code 0} if {@code x > y} - * @since 1.7 - */ - public static int compare(byte x, byte y) { - return x - y; - } - - /** - * The number of bits used to represent a {@code byte} value in two's - * complement binary form. - * - * @since 1.5 - */ - public static final int SIZE = 8; - - /** use serialVersionUID from JDK 1.1. for interoperability */ - private static final long serialVersionUID = -7183698231559129828L; -} diff -r 388e48c0a37a -r 05224402145d emul/src/main/java/java/lang/CharSequence.java --- a/emul/src/main/java/java/lang/CharSequence.java Wed Jan 23 20:16:48 2013 +0100 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,111 +0,0 @@ -/* - * Copyright (c) 2000, 2003, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code 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 - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package java.lang; - - -/** - * A CharSequence is a readable sequence of char values. This - * interface provides uniform, read-only access to many different kinds of - * char sequences. - * A char value represents a character in the Basic - * Multilingual Plane (BMP) or a surrogate. Refer to Unicode Character Representation for details. - * - *

This interface does not refine the general contracts of the {@link - * java.lang.Object#equals(java.lang.Object) equals} and {@link - * java.lang.Object#hashCode() hashCode} methods. The result of comparing two - * objects that implement CharSequence is therefore, in general, - * undefined. Each object may be implemented by a different class, and there - * is no guarantee that each class will be capable of testing its instances - * for equality with those of the other. It is therefore inappropriate to use - * arbitrary CharSequence instances as elements in a set or as keys in - * a map.

- * - * @author Mike McCloskey - * @since 1.4 - * @spec JSR-51 - */ - -public interface CharSequence { - - /** - * Returns the length of this character sequence. The length is the number - * of 16-bit chars in the sequence.

- * - * @return the number of chars in this sequence - */ - int length(); - - /** - * Returns the char value at the specified index. An index ranges from zero - * to length() - 1. The first char value of the sequence is at - * index zero, the next at index one, and so on, as for array - * indexing.

- * - *

If the char value specified by the index is a - * surrogate, the surrogate - * value is returned. - * - * @param index the index of the char value to be returned - * - * @return the specified char value - * - * @throws IndexOutOfBoundsException - * if the index argument is negative or not less than - * length() - */ - char charAt(int index); - - /** - * Returns a new CharSequence that is a subsequence of this sequence. - * The subsequence starts with the char value at the specified index and - * ends with the char value at index end - 1. The length - * (in chars) of the - * returned sequence is end - start, so if start == end - * then an empty sequence is returned.

- * - * @param start the start index, inclusive - * @param end the end index, exclusive - * - * @return the specified subsequence - * - * @throws IndexOutOfBoundsException - * if start or end are negative, - * if end is greater than length(), - * or if start is greater than end - */ - CharSequence subSequence(int start, int end); - - /** - * Returns a string containing the characters in this sequence in the same - * order as this sequence. The length of the string will be the length of - * this sequence.

- * - * @return a string consisting of exactly this sequence of characters - */ - public String toString(); - -} diff -r 388e48c0a37a -r 05224402145d emul/src/main/java/java/lang/Character.java --- a/emul/src/main/java/java/lang/Character.java Wed Jan 23 20:16:48 2013 +0100 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,2382 +0,0 @@ -/* - * Copyright (c) 2002, 2010, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code 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 - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package java.lang; - -import org.apidesign.bck2brwsr.core.JavaScriptBody; - -/** - * The {@code Character} class wraps a value of the primitive - * type {@code char} in an object. An object of type - * {@code Character} contains a single field whose type is - * {@code char}. - *

- * In addition, this class provides several methods for determining - * a character's category (lowercase letter, digit, etc.) and for converting - * characters from uppercase to lowercase and vice versa. - *

- * Character information is based on the Unicode Standard, version 6.0.0. - *

- * The methods and data of class {@code Character} are defined by - * the information in the UnicodeData file that is part of the - * Unicode Character Database maintained by the Unicode - * Consortium. This file specifies various properties including name - * and general category for every defined Unicode code point or - * character range. - *

- * The file and its description are available from the Unicode Consortium at: - *

- * - *

Unicode Character Representations

- * - *

The {@code char} data type (and therefore the value that a - * {@code Character} object encapsulates) are based on the - * original Unicode specification, which defined characters as - * fixed-width 16-bit entities. The Unicode Standard has since been - * changed to allow for characters whose representation requires more - * than 16 bits. The range of legal code points is now - * U+0000 to U+10FFFF, known as Unicode scalar value. - * (Refer to the - * definition of the U+n notation in the Unicode - * Standard.) - * - *

The set of characters from U+0000 to U+FFFF is - * sometimes referred to as the Basic Multilingual Plane (BMP). - * Characters whose code points are greater - * than U+FFFF are called supplementary characters. The Java - * platform uses the UTF-16 representation in {@code char} arrays and - * in the {@code String} and {@code StringBuffer} classes. In - * this representation, supplementary characters are represented as a pair - * of {@code char} values, the first from the high-surrogates - * range, (\uD800-\uDBFF), the second from the - * low-surrogates range (\uDC00-\uDFFF). - * - *

A {@code char} value, therefore, represents Basic - * Multilingual Plane (BMP) code points, including the surrogate - * code points, or code units of the UTF-16 encoding. An - * {@code int} value represents all Unicode code points, - * including supplementary code points. The lower (least significant) - * 21 bits of {@code int} are used to represent Unicode code - * points and the upper (most significant) 11 bits must be zero. - * Unless otherwise specified, the behavior with respect to - * supplementary characters and surrogate {@code char} values is - * as follows: - * - *

    - *
  • The methods that only accept a {@code char} value cannot support - * supplementary characters. They treat {@code char} values from the - * surrogate ranges as undefined characters. For example, - * {@code Character.isLetter('\u005CuD840')} returns {@code false}, even though - * this specific value if followed by any low-surrogate value in a string - * would represent a letter. - * - *
  • The methods that accept an {@code int} value support all - * Unicode characters, including supplementary characters. For - * example, {@code Character.isLetter(0x2F81A)} returns - * {@code true} because the code point value represents a letter - * (a CJK ideograph). - *
- * - *

In the Java SE API documentation, Unicode code point is - * used for character values in the range between U+0000 and U+10FFFF, - * and Unicode code unit is used for 16-bit - * {@code char} values that are code units of the UTF-16 - * encoding. For more information on Unicode terminology, refer to the - * Unicode Glossary. - * - * @author Lee Boynton - * @author Guy Steele - * @author Akira Tanaka - * @author Martin Buchholz - * @author Ulf Zibis - * @since 1.0 - */ -public final -class Character implements java.io.Serializable, Comparable { - /** - * The minimum radix available for conversion to and from strings. - * The constant value of this field is the smallest value permitted - * for the radix argument in radix-conversion methods such as the - * {@code digit} method, the {@code forDigit} method, and the - * {@code toString} method of class {@code Integer}. - * - * @see Character#digit(char, int) - * @see Character#forDigit(int, int) - * @see Integer#toString(int, int) - * @see Integer#valueOf(String) - */ - public static final int MIN_RADIX = 2; - - /** - * The maximum radix available for conversion to and from strings. - * The constant value of this field is the largest value permitted - * for the radix argument in radix-conversion methods such as the - * {@code digit} method, the {@code forDigit} method, and the - * {@code toString} method of class {@code Integer}. - * - * @see Character#digit(char, int) - * @see Character#forDigit(int, int) - * @see Integer#toString(int, int) - * @see Integer#valueOf(String) - */ - public static final int MAX_RADIX = 36; - - /** - * The constant value of this field is the smallest value of type - * {@code char}, {@code '\u005Cu0000'}. - * - * @since 1.0.2 - */ - public static final char MIN_VALUE = '\u0000'; - - /** - * The constant value of this field is the largest value of type - * {@code char}, {@code '\u005CuFFFF'}. - * - * @since 1.0.2 - */ - public static final char MAX_VALUE = '\uFFFF'; - - /** - * The {@code Class} instance representing the primitive type - * {@code char}. - * - * @since 1.1 - */ - public static final Class TYPE = Class.getPrimitiveClass("char"); - - /* - * Normative general types - */ - - /* - * General character types - */ - - /** - * General category "Cn" in the Unicode specification. - * @since 1.1 - */ - public static final byte UNASSIGNED = 0; - - /** - * General category "Lu" in the Unicode specification. - * @since 1.1 - */ - public static final byte UPPERCASE_LETTER = 1; - - /** - * General category "Ll" in the Unicode specification. - * @since 1.1 - */ - public static final byte LOWERCASE_LETTER = 2; - - /** - * General category "Lt" in the Unicode specification. - * @since 1.1 - */ - public static final byte TITLECASE_LETTER = 3; - - /** - * General category "Lm" in the Unicode specification. - * @since 1.1 - */ - public static final byte MODIFIER_LETTER = 4; - - /** - * General category "Lo" in the Unicode specification. - * @since 1.1 - */ - public static final byte OTHER_LETTER = 5; - - /** - * General category "Mn" in the Unicode specification. - * @since 1.1 - */ - public static final byte NON_SPACING_MARK = 6; - - /** - * General category "Me" in the Unicode specification. - * @since 1.1 - */ - public static final byte ENCLOSING_MARK = 7; - - /** - * General category "Mc" in the Unicode specification. - * @since 1.1 - */ - public static final byte COMBINING_SPACING_MARK = 8; - - /** - * General category "Nd" in the Unicode specification. - * @since 1.1 - */ - public static final byte DECIMAL_DIGIT_NUMBER = 9; - - /** - * General category "Nl" in the Unicode specification. - * @since 1.1 - */ - public static final byte LETTER_NUMBER = 10; - - /** - * General category "No" in the Unicode specification. - * @since 1.1 - */ - public static final byte OTHER_NUMBER = 11; - - /** - * General category "Zs" in the Unicode specification. - * @since 1.1 - */ - public static final byte SPACE_SEPARATOR = 12; - - /** - * General category "Zl" in the Unicode specification. - * @since 1.1 - */ - public static final byte LINE_SEPARATOR = 13; - - /** - * General category "Zp" in the Unicode specification. - * @since 1.1 - */ - public static final byte PARAGRAPH_SEPARATOR = 14; - - /** - * General category "Cc" in the Unicode specification. - * @since 1.1 - */ - public static final byte CONTROL = 15; - - /** - * General category "Cf" in the Unicode specification. - * @since 1.1 - */ - public static final byte FORMAT = 16; - - /** - * General category "Co" in the Unicode specification. - * @since 1.1 - */ - public static final byte PRIVATE_USE = 18; - - /** - * General category "Cs" in the Unicode specification. - * @since 1.1 - */ - public static final byte SURROGATE = 19; - - /** - * General category "Pd" in the Unicode specification. - * @since 1.1 - */ - public static final byte DASH_PUNCTUATION = 20; - - /** - * General category "Ps" in the Unicode specification. - * @since 1.1 - */ - public static final byte START_PUNCTUATION = 21; - - /** - * General category "Pe" in the Unicode specification. - * @since 1.1 - */ - public static final byte END_PUNCTUATION = 22; - - /** - * General category "Pc" in the Unicode specification. - * @since 1.1 - */ - public static final byte CONNECTOR_PUNCTUATION = 23; - - /** - * General category "Po" in the Unicode specification. - * @since 1.1 - */ - public static final byte OTHER_PUNCTUATION = 24; - - /** - * General category "Sm" in the Unicode specification. - * @since 1.1 - */ - public static final byte MATH_SYMBOL = 25; - - /** - * General category "Sc" in the Unicode specification. - * @since 1.1 - */ - public static final byte CURRENCY_SYMBOL = 26; - - /** - * General category "Sk" in the Unicode specification. - * @since 1.1 - */ - public static final byte MODIFIER_SYMBOL = 27; - - /** - * General category "So" in the Unicode specification. - * @since 1.1 - */ - public static final byte OTHER_SYMBOL = 28; - - /** - * General category "Pi" in the Unicode specification. - * @since 1.4 - */ - public static final byte INITIAL_QUOTE_PUNCTUATION = 29; - - /** - * General category "Pf" in the Unicode specification. - * @since 1.4 - */ - public static final byte FINAL_QUOTE_PUNCTUATION = 30; - - /** - * Error flag. Use int (code point) to avoid confusion with U+FFFF. - */ - static final int ERROR = 0xFFFFFFFF; - - - /** - * Undefined bidirectional character type. Undefined {@code char} - * values have undefined directionality in the Unicode specification. - * @since 1.4 - */ - public static final byte DIRECTIONALITY_UNDEFINED = -1; - - /** - * Strong bidirectional character type "L" in the Unicode specification. - * @since 1.4 - */ - public static final byte DIRECTIONALITY_LEFT_TO_RIGHT = 0; - - /** - * Strong bidirectional character type "R" in the Unicode specification. - * @since 1.4 - */ - public static final byte DIRECTIONALITY_RIGHT_TO_LEFT = 1; - - /** - * Strong bidirectional character type "AL" in the Unicode specification. - * @since 1.4 - */ - public static final byte DIRECTIONALITY_RIGHT_TO_LEFT_ARABIC = 2; - - /** - * Weak bidirectional character type "EN" in the Unicode specification. - * @since 1.4 - */ - public static final byte DIRECTIONALITY_EUROPEAN_NUMBER = 3; - - /** - * Weak bidirectional character type "ES" in the Unicode specification. - * @since 1.4 - */ - public static final byte DIRECTIONALITY_EUROPEAN_NUMBER_SEPARATOR = 4; - - /** - * Weak bidirectional character type "ET" in the Unicode specification. - * @since 1.4 - */ - public static final byte DIRECTIONALITY_EUROPEAN_NUMBER_TERMINATOR = 5; - - /** - * Weak bidirectional character type "AN" in the Unicode specification. - * @since 1.4 - */ - public static final byte DIRECTIONALITY_ARABIC_NUMBER = 6; - - /** - * Weak bidirectional character type "CS" in the Unicode specification. - * @since 1.4 - */ - public static final byte DIRECTIONALITY_COMMON_NUMBER_SEPARATOR = 7; - - /** - * Weak bidirectional character type "NSM" in the Unicode specification. - * @since 1.4 - */ - public static final byte DIRECTIONALITY_NONSPACING_MARK = 8; - - /** - * Weak bidirectional character type "BN" in the Unicode specification. - * @since 1.4 - */ - public static final byte DIRECTIONALITY_BOUNDARY_NEUTRAL = 9; - - /** - * Neutral bidirectional character type "B" in the Unicode specification. - * @since 1.4 - */ - public static final byte DIRECTIONALITY_PARAGRAPH_SEPARATOR = 10; - - /** - * Neutral bidirectional character type "S" in the Unicode specification. - * @since 1.4 - */ - public static final byte DIRECTIONALITY_SEGMENT_SEPARATOR = 11; - - /** - * Neutral bidirectional character type "WS" in the Unicode specification. - * @since 1.4 - */ - public static final byte DIRECTIONALITY_WHITESPACE = 12; - - /** - * Neutral bidirectional character type "ON" in the Unicode specification. - * @since 1.4 - */ - public static final byte DIRECTIONALITY_OTHER_NEUTRALS = 13; - - /** - * Strong bidirectional character type "LRE" in the Unicode specification. - * @since 1.4 - */ - public static final byte DIRECTIONALITY_LEFT_TO_RIGHT_EMBEDDING = 14; - - /** - * Strong bidirectional character type "LRO" in the Unicode specification. - * @since 1.4 - */ - public static final byte DIRECTIONALITY_LEFT_TO_RIGHT_OVERRIDE = 15; - - /** - * Strong bidirectional character type "RLE" in the Unicode specification. - * @since 1.4 - */ - public static final byte DIRECTIONALITY_RIGHT_TO_LEFT_EMBEDDING = 16; - - /** - * Strong bidirectional character type "RLO" in the Unicode specification. - * @since 1.4 - */ - public static final byte DIRECTIONALITY_RIGHT_TO_LEFT_OVERRIDE = 17; - - /** - * Weak bidirectional character type "PDF" in the Unicode specification. - * @since 1.4 - */ - public static final byte DIRECTIONALITY_POP_DIRECTIONAL_FORMAT = 18; - - /** - * The minimum value of a - * - * Unicode high-surrogate code unit - * in the UTF-16 encoding, constant {@code '\u005CuD800'}. - * A high-surrogate is also known as a leading-surrogate. - * - * @since 1.5 - */ - public static final char MIN_HIGH_SURROGATE = '\uD800'; - - /** - * The maximum value of a - * - * Unicode high-surrogate code unit - * in the UTF-16 encoding, constant {@code '\u005CuDBFF'}. - * A high-surrogate is also known as a leading-surrogate. - * - * @since 1.5 - */ - public static final char MAX_HIGH_SURROGATE = '\uDBFF'; - - /** - * The minimum value of a - * - * Unicode low-surrogate code unit - * in the UTF-16 encoding, constant {@code '\u005CuDC00'}. - * A low-surrogate is also known as a trailing-surrogate. - * - * @since 1.5 - */ - public static final char MIN_LOW_SURROGATE = '\uDC00'; - - /** - * The maximum value of a - * - * Unicode low-surrogate code unit - * in the UTF-16 encoding, constant {@code '\u005CuDFFF'}. - * A low-surrogate is also known as a trailing-surrogate. - * - * @since 1.5 - */ - public static final char MAX_LOW_SURROGATE = '\uDFFF'; - - /** - * The minimum value of a Unicode surrogate code unit in the - * UTF-16 encoding, constant {@code '\u005CuD800'}. - * - * @since 1.5 - */ - public static final char MIN_SURROGATE = MIN_HIGH_SURROGATE; - - /** - * The maximum value of a Unicode surrogate code unit in the - * UTF-16 encoding, constant {@code '\u005CuDFFF'}. - * - * @since 1.5 - */ - public static final char MAX_SURROGATE = MAX_LOW_SURROGATE; - - /** - * The minimum value of a - * - * Unicode supplementary code point, constant {@code U+10000}. - * - * @since 1.5 - */ - public static final int MIN_SUPPLEMENTARY_CODE_POINT = 0x010000; - - /** - * The minimum value of a - * - * Unicode code point, constant {@code U+0000}. - * - * @since 1.5 - */ - public static final int MIN_CODE_POINT = 0x000000; - - /** - * The maximum value of a - * - * Unicode code point, constant {@code U+10FFFF}. - * - * @since 1.5 - */ - public static final int MAX_CODE_POINT = 0X10FFFF; - - - /** - * Instances of this class represent particular subsets of the Unicode - * character set. The only family of subsets defined in the - * {@code Character} class is {@link Character.UnicodeBlock}. - * Other portions of the Java API may define other subsets for their - * own purposes. - * - * @since 1.2 - */ - public static class Subset { - - private String name; - - /** - * Constructs a new {@code Subset} instance. - * - * @param name The name of this subset - * @exception NullPointerException if name is {@code null} - */ - protected Subset(String name) { - if (name == null) { - throw new NullPointerException("name"); - } - this.name = name; - } - - /** - * Compares two {@code Subset} objects for equality. - * This method returns {@code true} if and only if - * {@code this} and the argument refer to the same - * object; since this method is {@code final}, this - * guarantee holds for all subclasses. - */ - public final boolean equals(Object obj) { - return (this == obj); - } - - /** - * Returns the standard hash code as defined by the - * {@link Object#hashCode} method. This method - * is {@code final} in order to ensure that the - * {@code equals} and {@code hashCode} methods will - * be consistent in all subclasses. - */ - public final int hashCode() { - return super.hashCode(); - } - - /** - * Returns the name of this subset. - */ - public final String toString() { - return name; - } - } - - // See http://www.unicode.org/Public/UNIDATA/Blocks.txt - // for the latest specification of Unicode Blocks. - - - /** - * The value of the {@code Character}. - * - * @serial - */ - private final char value; - - /** use serialVersionUID from JDK 1.0.2 for interoperability */ - private static final long serialVersionUID = 3786198910865385080L; - - /** - * Constructs a newly allocated {@code Character} object that - * represents the specified {@code char} value. - * - * @param value the value to be represented by the - * {@code Character} object. - */ - public Character(char value) { - this.value = value; - } - - private static class CharacterCache { - private CharacterCache(){} - - static final Character cache[] = new Character[127 + 1]; - - static { - for (int i = 0; i < cache.length; i++) - cache[i] = new Character((char)i); - } - } - - /** - * Returns a Character instance representing the specified - * char value. - * If a new Character instance is not required, this method - * should generally be used in preference to the constructor - * {@link #Character(char)}, as this method is likely to yield - * significantly better space and time performance by caching - * frequently requested values. - * - * This method will always cache values in the range {@code - * '\u005Cu0000'} to {@code '\u005Cu007F'}, inclusive, and may - * cache other values outside of this range. - * - * @param c a char value. - * @return a Character instance representing c. - * @since 1.5 - */ - public static Character valueOf(char c) { - if (c <= 127) { // must cache - return CharacterCache.cache[(int)c]; - } - return new Character(c); - } - - /** - * Returns the value of this {@code Character} object. - * @return the primitive {@code char} value represented by - * this object. - */ - public char charValue() { - return value; - } - - /** - * Returns a hash code for this {@code Character}; equal to the result - * of invoking {@code charValue()}. - * - * @return a hash code value for this {@code Character} - */ - public int hashCode() { - return (int)value; - } - - /** - * Compares this object against the specified object. - * The result is {@code true} if and only if the argument is not - * {@code null} and is a {@code Character} object that - * represents the same {@code char} value as this object. - * - * @param obj the object to compare with. - * @return {@code true} if the objects are the same; - * {@code false} otherwise. - */ - public boolean equals(Object obj) { - if (obj instanceof Character) { - return value == ((Character)obj).charValue(); - } - return false; - } - - /** - * Returns a {@code String} object representing this - * {@code Character}'s value. The result is a string of - * length 1 whose sole component is the primitive - * {@code char} value represented by this - * {@code Character} object. - * - * @return a string representation of this object. - */ - public String toString() { - char buf[] = {value}; - return String.valueOf(buf); - } - - /** - * Returns a {@code String} object representing the - * specified {@code char}. The result is a string of length - * 1 consisting solely of the specified {@code char}. - * - * @param c the {@code char} to be converted - * @return the string representation of the specified {@code char} - * @since 1.4 - */ - public static String toString(char c) { - return String.valueOf(c); - } - - /** - * Determines whether the specified code point is a valid - * - * Unicode code point value. - * - * @param codePoint the Unicode code point to be tested - * @return {@code true} if the specified code point value is between - * {@link #MIN_CODE_POINT} and - * {@link #MAX_CODE_POINT} inclusive; - * {@code false} otherwise. - * @since 1.5 - */ - public static boolean isValidCodePoint(int codePoint) { - // Optimized form of: - // codePoint >= MIN_CODE_POINT && codePoint <= MAX_CODE_POINT - int plane = codePoint >>> 16; - return plane < ((MAX_CODE_POINT + 1) >>> 16); - } - - /** - * Determines whether the specified character (Unicode code point) - * is in the Basic Multilingual Plane (BMP). - * Such code points can be represented using a single {@code char}. - * - * @param codePoint the character (Unicode code point) to be tested - * @return {@code true} if the specified code point is between - * {@link #MIN_VALUE} and {@link #MAX_VALUE} inclusive; - * {@code false} otherwise. - * @since 1.7 - */ - public static boolean isBmpCodePoint(int codePoint) { - return codePoint >>> 16 == 0; - // Optimized form of: - // codePoint >= MIN_VALUE && codePoint <= MAX_VALUE - // We consistently use logical shift (>>>) to facilitate - // additional runtime optimizations. - } - - /** - * Determines whether the specified character (Unicode code point) - * is in the supplementary character range. - * - * @param codePoint the character (Unicode code point) to be tested - * @return {@code true} if the specified code point is between - * {@link #MIN_SUPPLEMENTARY_CODE_POINT} and - * {@link #MAX_CODE_POINT} inclusive; - * {@code false} otherwise. - * @since 1.5 - */ - public static boolean isSupplementaryCodePoint(int codePoint) { - return codePoint >= MIN_SUPPLEMENTARY_CODE_POINT - && codePoint < MAX_CODE_POINT + 1; - } - - /** - * Determines if the given {@code char} value is a - * - * Unicode high-surrogate code unit - * (also known as leading-surrogate code unit). - * - *

Such values do not represent characters by themselves, - * but are used in the representation of - * supplementary characters - * in the UTF-16 encoding. - * - * @param ch the {@code char} value to be tested. - * @return {@code true} if the {@code char} value is between - * {@link #MIN_HIGH_SURROGATE} and - * {@link #MAX_HIGH_SURROGATE} inclusive; - * {@code false} otherwise. - * @see Character#isLowSurrogate(char) - * @see Character.UnicodeBlock#of(int) - * @since 1.5 - */ - public static boolean isHighSurrogate(char ch) { - // Help VM constant-fold; MAX_HIGH_SURROGATE + 1 == MIN_LOW_SURROGATE - return ch >= MIN_HIGH_SURROGATE && ch < (MAX_HIGH_SURROGATE + 1); - } - - /** - * Determines if the given {@code char} value is a - * - * Unicode low-surrogate code unit - * (also known as trailing-surrogate code unit). - * - *

Such values do not represent characters by themselves, - * but are used in the representation of - * supplementary characters - * in the UTF-16 encoding. - * - * @param ch the {@code char} value to be tested. - * @return {@code true} if the {@code char} value is between - * {@link #MIN_LOW_SURROGATE} and - * {@link #MAX_LOW_SURROGATE} inclusive; - * {@code false} otherwise. - * @see Character#isHighSurrogate(char) - * @since 1.5 - */ - public static boolean isLowSurrogate(char ch) { - return ch >= MIN_LOW_SURROGATE && ch < (MAX_LOW_SURROGATE + 1); - } - - /** - * Determines if the given {@code char} value is a Unicode - * surrogate code unit. - * - *

Such values do not represent characters by themselves, - * but are used in the representation of - * supplementary characters - * in the UTF-16 encoding. - * - *

A char value is a surrogate code unit if and only if it is either - * a {@linkplain #isLowSurrogate(char) low-surrogate code unit} or - * a {@linkplain #isHighSurrogate(char) high-surrogate code unit}. - * - * @param ch the {@code char} value to be tested. - * @return {@code true} if the {@code char} value is between - * {@link #MIN_SURROGATE} and - * {@link #MAX_SURROGATE} inclusive; - * {@code false} otherwise. - * @since 1.7 - */ - public static boolean isSurrogate(char ch) { - return ch >= MIN_SURROGATE && ch < (MAX_SURROGATE + 1); - } - - /** - * Determines whether the specified pair of {@code char} - * values is a valid - * - * Unicode surrogate pair. - - *

This method is equivalent to the expression: - *

-     * isHighSurrogate(high) && isLowSurrogate(low)
-     * 
- * - * @param high the high-surrogate code value to be tested - * @param low the low-surrogate code value to be tested - * @return {@code true} if the specified high and - * low-surrogate code values represent a valid surrogate pair; - * {@code false} otherwise. - * @since 1.5 - */ - public static boolean isSurrogatePair(char high, char low) { - return isHighSurrogate(high) && isLowSurrogate(low); - } - - /** - * Determines the number of {@code char} values needed to - * represent the specified character (Unicode code point). If the - * specified character is equal to or greater than 0x10000, then - * the method returns 2. Otherwise, the method returns 1. - * - *

This method doesn't validate the specified character to be a - * valid Unicode code point. The caller must validate the - * character value using {@link #isValidCodePoint(int) isValidCodePoint} - * if necessary. - * - * @param codePoint the character (Unicode code point) to be tested. - * @return 2 if the character is a valid supplementary character; 1 otherwise. - * @see Character#isSupplementaryCodePoint(int) - * @since 1.5 - */ - public static int charCount(int codePoint) { - return codePoint >= MIN_SUPPLEMENTARY_CODE_POINT ? 2 : 1; - } - - /** - * Converts the specified surrogate pair to its supplementary code - * point value. This method does not validate the specified - * surrogate pair. The caller must validate it using {@link - * #isSurrogatePair(char, char) isSurrogatePair} if necessary. - * - * @param high the high-surrogate code unit - * @param low the low-surrogate code unit - * @return the supplementary code point composed from the - * specified surrogate pair. - * @since 1.5 - */ - public static int toCodePoint(char high, char low) { - // Optimized form of: - // return ((high - MIN_HIGH_SURROGATE) << 10) - // + (low - MIN_LOW_SURROGATE) - // + MIN_SUPPLEMENTARY_CODE_POINT; - return ((high << 10) + low) + (MIN_SUPPLEMENTARY_CODE_POINT - - (MIN_HIGH_SURROGATE << 10) - - MIN_LOW_SURROGATE); - } - - /** - * Returns the code point at the given index of the - * {@code CharSequence}. If the {@code char} value at - * the given index in the {@code CharSequence} is in the - * high-surrogate range, the following index is less than the - * length of the {@code CharSequence}, and the - * {@code char} value at the following index is in the - * low-surrogate range, then the supplementary code point - * corresponding to this surrogate pair is returned. Otherwise, - * the {@code char} value at the given index is returned. - * - * @param seq a sequence of {@code char} values (Unicode code - * units) - * @param index the index to the {@code char} values (Unicode - * code units) in {@code seq} to be converted - * @return the Unicode code point at the given index - * @exception NullPointerException if {@code seq} is null. - * @exception IndexOutOfBoundsException if the value - * {@code index} is negative or not less than - * {@link CharSequence#length() seq.length()}. - * @since 1.5 - */ - public static int codePointAt(CharSequence seq, int index) { - char c1 = seq.charAt(index++); - if (isHighSurrogate(c1)) { - if (index < seq.length()) { - char c2 = seq.charAt(index); - if (isLowSurrogate(c2)) { - return toCodePoint(c1, c2); - } - } - } - return c1; - } - - /** - * Returns the code point at the given index of the - * {@code char} array. If the {@code char} value at - * the given index in the {@code char} array is in the - * high-surrogate range, the following index is less than the - * length of the {@code char} array, and the - * {@code char} value at the following index is in the - * low-surrogate range, then the supplementary code point - * corresponding to this surrogate pair is returned. Otherwise, - * the {@code char} value at the given index is returned. - * - * @param a the {@code char} array - * @param index the index to the {@code char} values (Unicode - * code units) in the {@code char} array to be converted - * @return the Unicode code point at the given index - * @exception NullPointerException if {@code a} is null. - * @exception IndexOutOfBoundsException if the value - * {@code index} is negative or not less than - * the length of the {@code char} array. - * @since 1.5 - */ - public static int codePointAt(char[] a, int index) { - return codePointAtImpl(a, index, a.length); - } - - /** - * Returns the code point at the given index of the - * {@code char} array, where only array elements with - * {@code index} less than {@code limit} can be used. If - * the {@code char} value at the given index in the - * {@code char} array is in the high-surrogate range, the - * following index is less than the {@code limit}, and the - * {@code char} value at the following index is in the - * low-surrogate range, then the supplementary code point - * corresponding to this surrogate pair is returned. Otherwise, - * the {@code char} value at the given index is returned. - * - * @param a the {@code char} array - * @param index the index to the {@code char} values (Unicode - * code units) in the {@code char} array to be converted - * @param limit the index after the last array element that - * can be used in the {@code char} array - * @return the Unicode code point at the given index - * @exception NullPointerException if {@code a} is null. - * @exception IndexOutOfBoundsException if the {@code index} - * argument is negative or not less than the {@code limit} - * argument, or if the {@code limit} argument is negative or - * greater than the length of the {@code char} array. - * @since 1.5 - */ - public static int codePointAt(char[] a, int index, int limit) { - if (index >= limit || limit < 0 || limit > a.length) { - throw new IndexOutOfBoundsException(); - } - return codePointAtImpl(a, index, limit); - } - - // throws ArrayIndexOutofBoundsException if index out of bounds - static int codePointAtImpl(char[] a, int index, int limit) { - char c1 = a[index++]; - if (isHighSurrogate(c1)) { - if (index < limit) { - char c2 = a[index]; - if (isLowSurrogate(c2)) { - return toCodePoint(c1, c2); - } - } - } - return c1; - } - - /** - * Returns the code point preceding the given index of the - * {@code CharSequence}. If the {@code char} value at - * {@code (index - 1)} in the {@code CharSequence} is in - * the low-surrogate range, {@code (index - 2)} is not - * negative, and the {@code char} value at {@code (index - 2)} - * in the {@code CharSequence} is in the - * high-surrogate range, then the supplementary code point - * corresponding to this surrogate pair is returned. Otherwise, - * the {@code char} value at {@code (index - 1)} is - * returned. - * - * @param seq the {@code CharSequence} instance - * @param index the index following the code point that should be returned - * @return the Unicode code point value before the given index. - * @exception NullPointerException if {@code seq} is null. - * @exception IndexOutOfBoundsException if the {@code index} - * argument is less than 1 or greater than {@link - * CharSequence#length() seq.length()}. - * @since 1.5 - */ - public static int codePointBefore(CharSequence seq, int index) { - char c2 = seq.charAt(--index); - if (isLowSurrogate(c2)) { - if (index > 0) { - char c1 = seq.charAt(--index); - if (isHighSurrogate(c1)) { - return toCodePoint(c1, c2); - } - } - } - return c2; - } - - /** - * Returns the code point preceding the given index of the - * {@code char} array. If the {@code char} value at - * {@code (index - 1)} in the {@code char} array is in - * the low-surrogate range, {@code (index - 2)} is not - * negative, and the {@code char} value at {@code (index - 2)} - * in the {@code char} array is in the - * high-surrogate range, then the supplementary code point - * corresponding to this surrogate pair is returned. Otherwise, - * the {@code char} value at {@code (index - 1)} is - * returned. - * - * @param a the {@code char} array - * @param index the index following the code point that should be returned - * @return the Unicode code point value before the given index. - * @exception NullPointerException if {@code a} is null. - * @exception IndexOutOfBoundsException if the {@code index} - * argument is less than 1 or greater than the length of the - * {@code char} array - * @since 1.5 - */ - public static int codePointBefore(char[] a, int index) { - return codePointBeforeImpl(a, index, 0); - } - - /** - * Returns the code point preceding the given index of the - * {@code char} array, where only array elements with - * {@code index} greater than or equal to {@code start} - * can be used. If the {@code char} value at {@code (index - 1)} - * in the {@code char} array is in the - * low-surrogate range, {@code (index - 2)} is not less than - * {@code start}, and the {@code char} value at - * {@code (index - 2)} in the {@code char} array is in - * the high-surrogate range, then the supplementary code point - * corresponding to this surrogate pair is returned. Otherwise, - * the {@code char} value at {@code (index - 1)} is - * returned. - * - * @param a the {@code char} array - * @param index the index following the code point that should be returned - * @param start the index of the first array element in the - * {@code char} array - * @return the Unicode code point value before the given index. - * @exception NullPointerException if {@code a} is null. - * @exception IndexOutOfBoundsException if the {@code index} - * argument is not greater than the {@code start} argument or - * is greater than the length of the {@code char} array, or - * if the {@code start} argument is negative or not less than - * the length of the {@code char} array. - * @since 1.5 - */ - public static int codePointBefore(char[] a, int index, int start) { - if (index <= start || start < 0 || start >= a.length) { - throw new IndexOutOfBoundsException(); - } - return codePointBeforeImpl(a, index, start); - } - - // throws ArrayIndexOutofBoundsException if index-1 out of bounds - static int codePointBeforeImpl(char[] a, int index, int start) { - char c2 = a[--index]; - if (isLowSurrogate(c2)) { - if (index > start) { - char c1 = a[--index]; - if (isHighSurrogate(c1)) { - return toCodePoint(c1, c2); - } - } - } - return c2; - } - - /** - * Returns the leading surrogate (a - * - * high surrogate code unit) of the - * - * surrogate pair - * representing the specified supplementary character (Unicode - * code point) in the UTF-16 encoding. If the specified character - * is not a - * supplementary character, - * an unspecified {@code char} is returned. - * - *

If - * {@link #isSupplementaryCodePoint isSupplementaryCodePoint(x)} - * is {@code true}, then - * {@link #isHighSurrogate isHighSurrogate}{@code (highSurrogate(x))} and - * {@link #toCodePoint toCodePoint}{@code (highSurrogate(x), }{@link #lowSurrogate lowSurrogate}{@code (x)) == x} - * are also always {@code true}. - * - * @param codePoint a supplementary character (Unicode code point) - * @return the leading surrogate code unit used to represent the - * character in the UTF-16 encoding - * @since 1.7 - */ - public static char highSurrogate(int codePoint) { - return (char) ((codePoint >>> 10) - + (MIN_HIGH_SURROGATE - (MIN_SUPPLEMENTARY_CODE_POINT >>> 10))); - } - - /** - * Returns the trailing surrogate (a - * - * low surrogate code unit) of the - * - * surrogate pair - * representing the specified supplementary character (Unicode - * code point) in the UTF-16 encoding. If the specified character - * is not a - * supplementary character, - * an unspecified {@code char} is returned. - * - *

If - * {@link #isSupplementaryCodePoint isSupplementaryCodePoint(x)} - * is {@code true}, then - * {@link #isLowSurrogate isLowSurrogate}{@code (lowSurrogate(x))} and - * {@link #toCodePoint toCodePoint}{@code (}{@link #highSurrogate highSurrogate}{@code (x), lowSurrogate(x)) == x} - * are also always {@code true}. - * - * @param codePoint a supplementary character (Unicode code point) - * @return the trailing surrogate code unit used to represent the - * character in the UTF-16 encoding - * @since 1.7 - */ - public static char lowSurrogate(int codePoint) { - return (char) ((codePoint & 0x3ff) + MIN_LOW_SURROGATE); - } - - /** - * Converts the specified character (Unicode code point) to its - * UTF-16 representation. If the specified code point is a BMP - * (Basic Multilingual Plane or Plane 0) value, the same value is - * stored in {@code dst[dstIndex]}, and 1 is returned. If the - * specified code point is a supplementary character, its - * surrogate values are stored in {@code dst[dstIndex]} - * (high-surrogate) and {@code dst[dstIndex+1]} - * (low-surrogate), and 2 is returned. - * - * @param codePoint the character (Unicode code point) to be converted. - * @param dst an array of {@code char} in which the - * {@code codePoint}'s UTF-16 value is stored. - * @param dstIndex the start index into the {@code dst} - * array where the converted value is stored. - * @return 1 if the code point is a BMP code point, 2 if the - * code point is a supplementary code point. - * @exception IllegalArgumentException if the specified - * {@code codePoint} is not a valid Unicode code point. - * @exception NullPointerException if the specified {@code dst} is null. - * @exception IndexOutOfBoundsException if {@code dstIndex} - * is negative or not less than {@code dst.length}, or if - * {@code dst} at {@code dstIndex} doesn't have enough - * array element(s) to store the resulting {@code char} - * value(s). (If {@code dstIndex} is equal to - * {@code dst.length-1} and the specified - * {@code codePoint} is a supplementary character, the - * high-surrogate value is not stored in - * {@code dst[dstIndex]}.) - * @since 1.5 - */ - public static int toChars(int codePoint, char[] dst, int dstIndex) { - if (isBmpCodePoint(codePoint)) { - dst[dstIndex] = (char) codePoint; - return 1; - } else if (isValidCodePoint(codePoint)) { - toSurrogates(codePoint, dst, dstIndex); - return 2; - } else { - throw new IllegalArgumentException(); - } - } - - /** - * Converts the specified character (Unicode code point) to its - * UTF-16 representation stored in a {@code char} array. If - * the specified code point is a BMP (Basic Multilingual Plane or - * Plane 0) value, the resulting {@code char} array has - * the same value as {@code codePoint}. If the specified code - * point is a supplementary code point, the resulting - * {@code char} array has the corresponding surrogate pair. - * - * @param codePoint a Unicode code point - * @return a {@code char} array having - * {@code codePoint}'s UTF-16 representation. - * @exception IllegalArgumentException if the specified - * {@code codePoint} is not a valid Unicode code point. - * @since 1.5 - */ - public static char[] toChars(int codePoint) { - if (isBmpCodePoint(codePoint)) { - return new char[] { (char) codePoint }; - } else if (isValidCodePoint(codePoint)) { - char[] result = new char[2]; - toSurrogates(codePoint, result, 0); - return result; - } else { - throw new IllegalArgumentException(); - } - } - - static void toSurrogates(int codePoint, char[] dst, int index) { - // We write elements "backwards" to guarantee all-or-nothing - dst[index+1] = lowSurrogate(codePoint); - dst[index] = highSurrogate(codePoint); - } - - /** - * Returns the number of Unicode code points in the text range of - * the specified char sequence. The text range begins at the - * specified {@code beginIndex} and extends to the - * {@code char} at index {@code endIndex - 1}. Thus the - * length (in {@code char}s) of the text range is - * {@code endIndex-beginIndex}. Unpaired surrogates within - * the text range count as one code point each. - * - * @param seq the char sequence - * @param beginIndex the index to the first {@code char} of - * the text range. - * @param endIndex the index after the last {@code char} of - * the text range. - * @return the number of Unicode code points in the specified text - * range - * @exception NullPointerException if {@code seq} is null. - * @exception IndexOutOfBoundsException if the - * {@code beginIndex} is negative, or {@code endIndex} - * is larger than the length of the given sequence, or - * {@code beginIndex} is larger than {@code endIndex}. - * @since 1.5 - */ - public static int codePointCount(CharSequence seq, int beginIndex, int endIndex) { - int length = seq.length(); - if (beginIndex < 0 || endIndex > length || beginIndex > endIndex) { - throw new IndexOutOfBoundsException(); - } - int n = endIndex - beginIndex; - for (int i = beginIndex; i < endIndex; ) { - if (isHighSurrogate(seq.charAt(i++)) && i < endIndex && - isLowSurrogate(seq.charAt(i))) { - n--; - i++; - } - } - return n; - } - - /** - * Returns the number of Unicode code points in a subarray of the - * {@code char} array argument. The {@code offset} - * argument is the index of the first {@code char} of the - * subarray and the {@code count} argument specifies the - * length of the subarray in {@code char}s. Unpaired - * surrogates within the subarray count as one code point each. - * - * @param a the {@code char} array - * @param offset the index of the first {@code char} in the - * given {@code char} array - * @param count the length of the subarray in {@code char}s - * @return the number of Unicode code points in the specified subarray - * @exception NullPointerException if {@code a} is null. - * @exception IndexOutOfBoundsException if {@code offset} or - * {@code count} is negative, or if {@code offset + - * count} is larger than the length of the given array. - * @since 1.5 - */ - public static int codePointCount(char[] a, int offset, int count) { - if (count > a.length - offset || offset < 0 || count < 0) { - throw new IndexOutOfBoundsException(); - } - return codePointCountImpl(a, offset, count); - } - - static int codePointCountImpl(char[] a, int offset, int count) { - int endIndex = offset + count; - int n = count; - for (int i = offset; i < endIndex; ) { - if (isHighSurrogate(a[i++]) && i < endIndex && - isLowSurrogate(a[i])) { - n--; - i++; - } - } - return n; - } - - /** - * Returns the index within the given char sequence that is offset - * from the given {@code index} by {@code codePointOffset} - * code points. Unpaired surrogates within the text range given by - * {@code index} and {@code codePointOffset} count as - * one code point each. - * - * @param seq the char sequence - * @param index the index to be offset - * @param codePointOffset the offset in code points - * @return the index within the char sequence - * @exception NullPointerException if {@code seq} is null. - * @exception IndexOutOfBoundsException if {@code index} - * is negative or larger then the length of the char sequence, - * or if {@code codePointOffset} is positive and the - * subsequence starting with {@code index} has fewer than - * {@code codePointOffset} code points, or if - * {@code codePointOffset} is negative and the subsequence - * before {@code index} has fewer than the absolute value - * of {@code codePointOffset} code points. - * @since 1.5 - */ - public static int offsetByCodePoints(CharSequence seq, int index, - int codePointOffset) { - int length = seq.length(); - if (index < 0 || index > length) { - throw new IndexOutOfBoundsException(); - } - - int x = index; - if (codePointOffset >= 0) { - int i; - for (i = 0; x < length && i < codePointOffset; i++) { - if (isHighSurrogate(seq.charAt(x++)) && x < length && - isLowSurrogate(seq.charAt(x))) { - x++; - } - } - if (i < codePointOffset) { - throw new IndexOutOfBoundsException(); - } - } else { - int i; - for (i = codePointOffset; x > 0 && i < 0; i++) { - if (isLowSurrogate(seq.charAt(--x)) && x > 0 && - isHighSurrogate(seq.charAt(x-1))) { - x--; - } - } - if (i < 0) { - throw new IndexOutOfBoundsException(); - } - } - return x; - } - - /** - * Returns the index within the given {@code char} subarray - * that is offset from the given {@code index} by - * {@code codePointOffset} code points. The - * {@code start} and {@code count} arguments specify a - * subarray of the {@code char} array. Unpaired surrogates - * within the text range given by {@code index} and - * {@code codePointOffset} count as one code point each. - * - * @param a the {@code char} array - * @param start the index of the first {@code char} of the - * subarray - * @param count the length of the subarray in {@code char}s - * @param index the index to be offset - * @param codePointOffset the offset in code points - * @return the index within the subarray - * @exception NullPointerException if {@code a} is null. - * @exception IndexOutOfBoundsException - * if {@code start} or {@code count} is negative, - * or if {@code start + count} is larger than the length of - * the given array, - * or if {@code index} is less than {@code start} or - * larger then {@code start + count}, - * or if {@code codePointOffset} is positive and the text range - * starting with {@code index} and ending with {@code start + count - 1} - * has fewer than {@code codePointOffset} code - * points, - * or if {@code codePointOffset} is negative and the text range - * starting with {@code start} and ending with {@code index - 1} - * has fewer than the absolute value of - * {@code codePointOffset} code points. - * @since 1.5 - */ - public static int offsetByCodePoints(char[] a, int start, int count, - int index, int codePointOffset) { - if (count > a.length-start || start < 0 || count < 0 - || index < start || index > start+count) { - throw new IndexOutOfBoundsException(); - } - return offsetByCodePointsImpl(a, start, count, index, codePointOffset); - } - - static int offsetByCodePointsImpl(char[]a, int start, int count, - int index, int codePointOffset) { - int x = index; - if (codePointOffset >= 0) { - int limit = start + count; - int i; - for (i = 0; x < limit && i < codePointOffset; i++) { - if (isHighSurrogate(a[x++]) && x < limit && - isLowSurrogate(a[x])) { - x++; - } - } - if (i < codePointOffset) { - throw new IndexOutOfBoundsException(); - } - } else { - int i; - for (i = codePointOffset; x > start && i < 0; i++) { - if (isLowSurrogate(a[--x]) && x > start && - isHighSurrogate(a[x-1])) { - x--; - } - } - if (i < 0) { - throw new IndexOutOfBoundsException(); - } - } - return x; - } - - /** - * Determines if the specified character is a lowercase character. - *

- * A character is lowercase if its general category type, provided - * by {@code Character.getType(ch)}, is - * {@code LOWERCASE_LETTER}, or it has contributory property - * Other_Lowercase as defined by the Unicode Standard. - *

- * The following are examples of lowercase characters: - *

-     * a b c d e f g h i j k l m n o p q r s t u v w x y z
-     * '\u00DF' '\u00E0' '\u00E1' '\u00E2' '\u00E3' '\u00E4' '\u00E5' '\u00E6'
-     * '\u00E7' '\u00E8' '\u00E9' '\u00EA' '\u00EB' '\u00EC' '\u00ED' '\u00EE'
-     * '\u00EF' '\u00F0' '\u00F1' '\u00F2' '\u00F3' '\u00F4' '\u00F5' '\u00F6'
-     * '\u00F8' '\u00F9' '\u00FA' '\u00FB' '\u00FC' '\u00FD' '\u00FE' '\u00FF'
-     * 
- *

Many other Unicode characters are lowercase too. - * - *

Note: This method cannot handle supplementary characters. To support - * all Unicode characters, including supplementary characters, use - * the {@link #isLowerCase(int)} method. - * - * @param ch the character to be tested. - * @return {@code true} if the character is lowercase; - * {@code false} otherwise. - * @see Character#isLowerCase(char) - * @see Character#isTitleCase(char) - * @see Character#toLowerCase(char) - * @see Character#getType(char) - */ - public static boolean isLowerCase(char ch) { - return ch == toLowerCase(ch); - } - - /** - * Determines if the specified character is an uppercase character. - *

- * A character is uppercase if its general category type, provided by - * {@code Character.getType(ch)}, is {@code UPPERCASE_LETTER}. - * or it has contributory property Other_Uppercase as defined by the Unicode Standard. - *

- * The following are examples of uppercase characters: - *

-     * A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
-     * '\u00C0' '\u00C1' '\u00C2' '\u00C3' '\u00C4' '\u00C5' '\u00C6' '\u00C7'
-     * '\u00C8' '\u00C9' '\u00CA' '\u00CB' '\u00CC' '\u00CD' '\u00CE' '\u00CF'
-     * '\u00D0' '\u00D1' '\u00D2' '\u00D3' '\u00D4' '\u00D5' '\u00D6' '\u00D8'
-     * '\u00D9' '\u00DA' '\u00DB' '\u00DC' '\u00DD' '\u00DE'
-     * 
- *

Many other Unicode characters are uppercase too.

- * - *

Note: This method cannot handle supplementary characters. To support - * all Unicode characters, including supplementary characters, use - * the {@link #isUpperCase(int)} method. - * - * @param ch the character to be tested. - * @return {@code true} if the character is uppercase; - * {@code false} otherwise. - * @see Character#isLowerCase(char) - * @see Character#isTitleCase(char) - * @see Character#toUpperCase(char) - * @see Character#getType(char) - * @since 1.0 - */ - public static boolean isUpperCase(char ch) { - return ch == toUpperCase(ch); - } - - /** - * Determines if the specified character is a titlecase character. - *

- * A character is a titlecase character if its general - * category type, provided by {@code Character.getType(ch)}, - * is {@code TITLECASE_LETTER}. - *

- * Some characters look like pairs of Latin letters. For example, there - * is an uppercase letter that looks like "LJ" and has a corresponding - * lowercase letter that looks like "lj". A third form, which looks like "Lj", - * is the appropriate form to use when rendering a word in lowercase - * with initial capitals, as for a book title. - *

- * These are some of the Unicode characters for which this method returns - * {@code true}: - *

    - *
  • {@code LATIN CAPITAL LETTER D WITH SMALL LETTER Z WITH CARON} - *
  • {@code LATIN CAPITAL LETTER L WITH SMALL LETTER J} - *
  • {@code LATIN CAPITAL LETTER N WITH SMALL LETTER J} - *
  • {@code LATIN CAPITAL LETTER D WITH SMALL LETTER Z} - *
- *

Many other Unicode characters are titlecase too.

- * - *

Note: This method cannot handle supplementary characters. To support - * all Unicode characters, including supplementary characters, use - * the {@link #isTitleCase(int)} method. - * - * @param ch the character to be tested. - * @return {@code true} if the character is titlecase; - * {@code false} otherwise. - * @see Character#isLowerCase(char) - * @see Character#isUpperCase(char) - * @see Character#toTitleCase(char) - * @see Character#getType(char) - * @since 1.0.2 - */ - public static boolean isTitleCase(char ch) { - return isTitleCase((int)ch); - } - - /** - * Determines if the specified character (Unicode code point) is a titlecase character. - *

- * A character is a titlecase character if its general - * category type, provided by {@link Character#getType(int) getType(codePoint)}, - * is {@code TITLECASE_LETTER}. - *

- * Some characters look like pairs of Latin letters. For example, there - * is an uppercase letter that looks like "LJ" and has a corresponding - * lowercase letter that looks like "lj". A third form, which looks like "Lj", - * is the appropriate form to use when rendering a word in lowercase - * with initial capitals, as for a book title. - *

- * These are some of the Unicode characters for which this method returns - * {@code true}: - *

    - *
  • {@code LATIN CAPITAL LETTER D WITH SMALL LETTER Z WITH CARON} - *
  • {@code LATIN CAPITAL LETTER L WITH SMALL LETTER J} - *
  • {@code LATIN CAPITAL LETTER N WITH SMALL LETTER J} - *
  • {@code LATIN CAPITAL LETTER D WITH SMALL LETTER Z} - *
- *

Many other Unicode characters are titlecase too.

- * - * @param codePoint the character (Unicode code point) to be tested. - * @return {@code true} if the character is titlecase; - * {@code false} otherwise. - * @see Character#isLowerCase(int) - * @see Character#isUpperCase(int) - * @see Character#toTitleCase(int) - * @see Character#getType(int) - * @since 1.5 - */ - public static boolean isTitleCase(int codePoint) { - return getType(codePoint) == Character.TITLECASE_LETTER; - } - - /** - * Determines if the specified character is a digit. - *

- * A character is a digit if its general category type, provided - * by {@code Character.getType(ch)}, is - * {@code DECIMAL_DIGIT_NUMBER}. - *

- * Some Unicode character ranges that contain digits: - *

    - *
  • {@code '\u005Cu0030'} through {@code '\u005Cu0039'}, - * ISO-LATIN-1 digits ({@code '0'} through {@code '9'}) - *
  • {@code '\u005Cu0660'} through {@code '\u005Cu0669'}, - * Arabic-Indic digits - *
  • {@code '\u005Cu06F0'} through {@code '\u005Cu06F9'}, - * Extended Arabic-Indic digits - *
  • {@code '\u005Cu0966'} through {@code '\u005Cu096F'}, - * Devanagari digits - *
  • {@code '\u005CuFF10'} through {@code '\u005CuFF19'}, - * Fullwidth digits - *
- * - * Many other character ranges contain digits as well. - * - *

Note: This method cannot handle supplementary characters. To support - * all Unicode characters, including supplementary characters, use - * the {@link #isDigit(int)} method. - * - * @param ch the character to be tested. - * @return {@code true} if the character is a digit; - * {@code false} otherwise. - * @see Character#digit(char, int) - * @see Character#forDigit(int, int) - * @see Character#getType(char) - */ - public static boolean isDigit(char ch) { - return String.valueOf(ch).matches("\\d"); - } - - /** - * Determines if the specified character (Unicode code point) is a digit. - *

- * A character is a digit if its general category type, provided - * by {@link Character#getType(int) getType(codePoint)}, is - * {@code DECIMAL_DIGIT_NUMBER}. - *

- * Some Unicode character ranges that contain digits: - *

    - *
  • {@code '\u005Cu0030'} through {@code '\u005Cu0039'}, - * ISO-LATIN-1 digits ({@code '0'} through {@code '9'}) - *
  • {@code '\u005Cu0660'} through {@code '\u005Cu0669'}, - * Arabic-Indic digits - *
  • {@code '\u005Cu06F0'} through {@code '\u005Cu06F9'}, - * Extended Arabic-Indic digits - *
  • {@code '\u005Cu0966'} through {@code '\u005Cu096F'}, - * Devanagari digits - *
  • {@code '\u005CuFF10'} through {@code '\u005CuFF19'}, - * Fullwidth digits - *
- * - * Many other character ranges contain digits as well. - * - * @param codePoint the character (Unicode code point) to be tested. - * @return {@code true} if the character is a digit; - * {@code false} otherwise. - * @see Character#forDigit(int, int) - * @see Character#getType(int) - * @since 1.5 - */ - public static boolean isDigit(int codePoint) { - return fromCodeChars(codePoint).matches("\\d"); - } - - @JavaScriptBody(args = "c", body = "return String.fromCharCode(c);") - private native static String fromCodeChars(int codePoint); - - /** - * Determines if a character is defined in Unicode. - *

- * A character is defined if at least one of the following is true: - *

    - *
  • It has an entry in the UnicodeData file. - *
  • It has a value in a range defined by the UnicodeData file. - *
- * - *

Note: This method cannot handle supplementary characters. To support - * all Unicode characters, including supplementary characters, use - * the {@link #isDefined(int)} method. - * - * @param ch the character to be tested - * @return {@code true} if the character has a defined meaning - * in Unicode; {@code false} otherwise. - * @see Character#isDigit(char) - * @see Character#isLetter(char) - * @see Character#isLetterOrDigit(char) - * @see Character#isLowerCase(char) - * @see Character#isTitleCase(char) - * @see Character#isUpperCase(char) - * @since 1.0.2 - */ - public static boolean isDefined(char ch) { - return isDefined((int)ch); - } - - /** - * Determines if a character (Unicode code point) is defined in Unicode. - *

- * A character is defined if at least one of the following is true: - *

    - *
  • It has an entry in the UnicodeData file. - *
  • It has a value in a range defined by the UnicodeData file. - *
- * - * @param codePoint the character (Unicode code point) to be tested. - * @return {@code true} if the character has a defined meaning - * in Unicode; {@code false} otherwise. - * @see Character#isDigit(int) - * @see Character#isLetter(int) - * @see Character#isLetterOrDigit(int) - * @see Character#isLowerCase(int) - * @see Character#isTitleCase(int) - * @see Character#isUpperCase(int) - * @since 1.5 - */ - public static boolean isDefined(int codePoint) { - return getType(codePoint) != Character.UNASSIGNED; - } - - /** - * Determines if the specified character is a letter. - *

- * A character is considered to be a letter if its general - * category type, provided by {@code Character.getType(ch)}, - * is any of the following: - *

    - *
  • {@code UPPERCASE_LETTER} - *
  • {@code LOWERCASE_LETTER} - *
  • {@code TITLECASE_LETTER} - *
  • {@code MODIFIER_LETTER} - *
  • {@code OTHER_LETTER} - *
- * - * Not all letters have case. Many characters are - * letters but are neither uppercase nor lowercase nor titlecase. - * - *

Note: This method cannot handle supplementary characters. To support - * all Unicode characters, including supplementary characters, use - * the {@link #isLetter(int)} method. - * - * @param ch the character to be tested. - * @return {@code true} if the character is a letter; - * {@code false} otherwise. - * @see Character#isDigit(char) - * @see Character#isJavaIdentifierStart(char) - * @see Character#isJavaLetter(char) - * @see Character#isJavaLetterOrDigit(char) - * @see Character#isLetterOrDigit(char) - * @see Character#isLowerCase(char) - * @see Character#isTitleCase(char) - * @see Character#isUnicodeIdentifierStart(char) - * @see Character#isUpperCase(char) - */ - public static boolean isLetter(char ch) { - return String.valueOf(ch).matches("\\w") && !isDigit(ch); - } - - /** - * Determines if the specified character (Unicode code point) is a letter. - *

- * A character is considered to be a letter if its general - * category type, provided by {@link Character#getType(int) getType(codePoint)}, - * is any of the following: - *

    - *
  • {@code UPPERCASE_LETTER} - *
  • {@code LOWERCASE_LETTER} - *
  • {@code TITLECASE_LETTER} - *
  • {@code MODIFIER_LETTER} - *
  • {@code OTHER_LETTER} - *
- * - * Not all letters have case. Many characters are - * letters but are neither uppercase nor lowercase nor titlecase. - * - * @param codePoint the character (Unicode code point) to be tested. - * @return {@code true} if the character is a letter; - * {@code false} otherwise. - * @see Character#isDigit(int) - * @see Character#isJavaIdentifierStart(int) - * @see Character#isLetterOrDigit(int) - * @see Character#isLowerCase(int) - * @see Character#isTitleCase(int) - * @see Character#isUnicodeIdentifierStart(int) - * @see Character#isUpperCase(int) - * @since 1.5 - */ - public static boolean isLetter(int codePoint) { - return fromCodeChars(codePoint).matches("\\w") && !isDigit(codePoint); - } - - /** - * Determines if the specified character is a letter or digit. - *

- * A character is considered to be a letter or digit if either - * {@code Character.isLetter(char ch)} or - * {@code Character.isDigit(char ch)} returns - * {@code true} for the character. - * - *

Note: This method cannot handle supplementary characters. To support - * all Unicode characters, including supplementary characters, use - * the {@link #isLetterOrDigit(int)} method. - * - * @param ch the character to be tested. - * @return {@code true} if the character is a letter or digit; - * {@code false} otherwise. - * @see Character#isDigit(char) - * @see Character#isJavaIdentifierPart(char) - * @see Character#isJavaLetter(char) - * @see Character#isJavaLetterOrDigit(char) - * @see Character#isLetter(char) - * @see Character#isUnicodeIdentifierPart(char) - * @since 1.0.2 - */ - public static boolean isLetterOrDigit(char ch) { - return String.valueOf(ch).matches("\\w"); - } - - /** - * Determines if the specified character (Unicode code point) is a letter or digit. - *

- * A character is considered to be a letter or digit if either - * {@link #isLetter(int) isLetter(codePoint)} or - * {@link #isDigit(int) isDigit(codePoint)} returns - * {@code true} for the character. - * - * @param codePoint the character (Unicode code point) to be tested. - * @return {@code true} if the character is a letter or digit; - * {@code false} otherwise. - * @see Character#isDigit(int) - * @see Character#isJavaIdentifierPart(int) - * @see Character#isLetter(int) - * @see Character#isUnicodeIdentifierPart(int) - * @since 1.5 - */ - public static boolean isLetterOrDigit(int codePoint) { - return fromCodeChars(codePoint).matches("\\w"); - } - - static int getType(int x) { - throw new UnsupportedOperationException(); - } - - /** - * Converts the character argument to lowercase using case - * mapping information from the UnicodeData file. - *

- * Note that - * {@code Character.isLowerCase(Character.toLowerCase(ch))} - * does not always return {@code true} for some ranges of - * characters, particularly those that are symbols or ideographs. - * - *

In general, {@link String#toLowerCase()} should be used to map - * characters to lowercase. {@code String} case mapping methods - * have several benefits over {@code Character} case mapping methods. - * {@code String} case mapping methods can perform locale-sensitive - * mappings, context-sensitive mappings, and 1:M character mappings, whereas - * the {@code Character} case mapping methods cannot. - * - *

Note: This method cannot handle supplementary characters. To support - * all Unicode characters, including supplementary characters, use - * the {@link #toLowerCase(int)} method. - * - * @param ch the character to be converted. - * @return the lowercase equivalent of the character, if any; - * otherwise, the character itself. - * @see Character#isLowerCase(char) - * @see String#toLowerCase() - */ - public static char toLowerCase(char ch) { - return String.valueOf(ch).toLowerCase().charAt(0); - } - - /** - * Converts the character argument to uppercase using case mapping - * information from the UnicodeData file. - *

- * Note that - * {@code Character.isUpperCase(Character.toUpperCase(ch))} - * does not always return {@code true} for some ranges of - * characters, particularly those that are symbols or ideographs. - * - *

In general, {@link String#toUpperCase()} should be used to map - * characters to uppercase. {@code String} case mapping methods - * have several benefits over {@code Character} case mapping methods. - * {@code String} case mapping methods can perform locale-sensitive - * mappings, context-sensitive mappings, and 1:M character mappings, whereas - * the {@code Character} case mapping methods cannot. - * - *

Note: This method cannot handle supplementary characters. To support - * all Unicode characters, including supplementary characters, use - * the {@link #toUpperCase(int)} method. - * - * @param ch the character to be converted. - * @return the uppercase equivalent of the character, if any; - * otherwise, the character itself. - * @see Character#isUpperCase(char) - * @see String#toUpperCase() - */ - public static char toUpperCase(char ch) { - return String.valueOf(ch).toUpperCase().charAt(0); - } - - /** - * Returns the numeric value of the character {@code ch} in the - * specified radix. - *

- * If the radix is not in the range {@code MIN_RADIX} ≤ - * {@code radix} ≤ {@code MAX_RADIX} or if the - * value of {@code ch} is not a valid digit in the specified - * radix, {@code -1} is returned. A character is a valid digit - * if at least one of the following is true: - *

    - *
  • The method {@code isDigit} is {@code true} of the character - * and the Unicode decimal digit value of the character (or its - * single-character decomposition) is less than the specified radix. - * In this case the decimal digit value is returned. - *
  • The character is one of the uppercase Latin letters - * {@code 'A'} through {@code 'Z'} and its code is less than - * {@code radix + 'A' - 10}. - * In this case, {@code ch - 'A' + 10} - * is returned. - *
  • The character is one of the lowercase Latin letters - * {@code 'a'} through {@code 'z'} and its code is less than - * {@code radix + 'a' - 10}. - * In this case, {@code ch - 'a' + 10} - * is returned. - *
  • The character is one of the fullwidth uppercase Latin letters A - * ({@code '\u005CuFF21'}) through Z ({@code '\u005CuFF3A'}) - * and its code is less than - * {@code radix + '\u005CuFF21' - 10}. - * In this case, {@code ch - '\u005CuFF21' + 10} - * is returned. - *
  • The character is one of the fullwidth lowercase Latin letters a - * ({@code '\u005CuFF41'}) through z ({@code '\u005CuFF5A'}) - * and its code is less than - * {@code radix + '\u005CuFF41' - 10}. - * In this case, {@code ch - '\u005CuFF41' + 10} - * is returned. - *
- * - *

Note: This method cannot handle supplementary characters. To support - * all Unicode characters, including supplementary characters, use - * the {@link #digit(int, int)} method. - * - * @param ch the character to be converted. - * @param radix the radix. - * @return the numeric value represented by the character in the - * specified radix. - * @see Character#forDigit(int, int) - * @see Character#isDigit(char) - */ - public static int digit(char ch, int radix) { - return digit((int)ch, radix); - } - - /** - * Returns the numeric value of the specified character (Unicode - * code point) in the specified radix. - * - *

If the radix is not in the range {@code MIN_RADIX} ≤ - * {@code radix} ≤ {@code MAX_RADIX} or if the - * character is not a valid digit in the specified - * radix, {@code -1} is returned. A character is a valid digit - * if at least one of the following is true: - *

    - *
  • The method {@link #isDigit(int) isDigit(codePoint)} is {@code true} of the character - * and the Unicode decimal digit value of the character (or its - * single-character decomposition) is less than the specified radix. - * In this case the decimal digit value is returned. - *
  • The character is one of the uppercase Latin letters - * {@code 'A'} through {@code 'Z'} and its code is less than - * {@code radix + 'A' - 10}. - * In this case, {@code codePoint - 'A' + 10} - * is returned. - *
  • The character is one of the lowercase Latin letters - * {@code 'a'} through {@code 'z'} and its code is less than - * {@code radix + 'a' - 10}. - * In this case, {@code codePoint - 'a' + 10} - * is returned. - *
  • The character is one of the fullwidth uppercase Latin letters A - * ({@code '\u005CuFF21'}) through Z ({@code '\u005CuFF3A'}) - * and its code is less than - * {@code radix + '\u005CuFF21' - 10}. - * In this case, - * {@code codePoint - '\u005CuFF21' + 10} - * is returned. - *
  • The character is one of the fullwidth lowercase Latin letters a - * ({@code '\u005CuFF41'}) through z ({@code '\u005CuFF5A'}) - * and its code is less than - * {@code radix + '\u005CuFF41'- 10}. - * In this case, - * {@code codePoint - '\u005CuFF41' + 10} - * is returned. - *
- * - * @param codePoint the character (Unicode code point) to be converted. - * @param radix the radix. - * @return the numeric value represented by the character in the - * specified radix. - * @see Character#forDigit(int, int) - * @see Character#isDigit(int) - * @since 1.5 - */ - public static int digit(int codePoint, int radix) { - throw new UnsupportedOperationException(); - } - - /** - * Returns the {@code int} value that the specified Unicode - * character represents. For example, the character - * {@code '\u005Cu216C'} (the roman numeral fifty) will return - * an int with a value of 50. - *

- * The letters A-Z in their uppercase ({@code '\u005Cu0041'} through - * {@code '\u005Cu005A'}), lowercase - * ({@code '\u005Cu0061'} through {@code '\u005Cu007A'}), and - * full width variant ({@code '\u005CuFF21'} through - * {@code '\u005CuFF3A'} and {@code '\u005CuFF41'} through - * {@code '\u005CuFF5A'}) forms have numeric values from 10 - * through 35. This is independent of the Unicode specification, - * which does not assign numeric values to these {@code char} - * values. - *

- * If the character does not have a numeric value, then -1 is returned. - * If the character has a numeric value that cannot be represented as a - * nonnegative integer (for example, a fractional value), then -2 - * is returned. - * - *

Note: This method cannot handle supplementary characters. To support - * all Unicode characters, including supplementary characters, use - * the {@link #getNumericValue(int)} method. - * - * @param ch the character to be converted. - * @return the numeric value of the character, as a nonnegative {@code int} - * value; -2 if the character has a numeric value that is not a - * nonnegative integer; -1 if the character has no numeric value. - * @see Character#forDigit(int, int) - * @see Character#isDigit(char) - * @since 1.1 - */ - public static int getNumericValue(char ch) { - return getNumericValue((int)ch); - } - - /** - * Returns the {@code int} value that the specified - * character (Unicode code point) represents. For example, the character - * {@code '\u005Cu216C'} (the Roman numeral fifty) will return - * an {@code int} with a value of 50. - *

- * The letters A-Z in their uppercase ({@code '\u005Cu0041'} through - * {@code '\u005Cu005A'}), lowercase - * ({@code '\u005Cu0061'} through {@code '\u005Cu007A'}), and - * full width variant ({@code '\u005CuFF21'} through - * {@code '\u005CuFF3A'} and {@code '\u005CuFF41'} through - * {@code '\u005CuFF5A'}) forms have numeric values from 10 - * through 35. This is independent of the Unicode specification, - * which does not assign numeric values to these {@code char} - * values. - *

- * If the character does not have a numeric value, then -1 is returned. - * If the character has a numeric value that cannot be represented as a - * nonnegative integer (for example, a fractional value), then -2 - * is returned. - * - * @param codePoint the character (Unicode code point) to be converted. - * @return the numeric value of the character, as a nonnegative {@code int} - * value; -2 if the character has a numeric value that is not a - * nonnegative integer; -1 if the character has no numeric value. - * @see Character#forDigit(int, int) - * @see Character#isDigit(int) - * @since 1.5 - */ - public static int getNumericValue(int codePoint) { - throw new UnsupportedOperationException(); - } - - /** - * Determines if the specified character is ISO-LATIN-1 white space. - * This method returns {@code true} for the following five - * characters only: - * - * - * - * - * - * - * - * - * - * - * - *
{@code '\t'} {@code U+0009}{@code HORIZONTAL TABULATION}
{@code '\n'} {@code U+000A}{@code NEW LINE}
{@code '\f'} {@code U+000C}{@code FORM FEED}
{@code '\r'} {@code U+000D}{@code CARRIAGE RETURN}
{@code ' '} {@code U+0020}{@code SPACE}
- * - * @param ch the character to be tested. - * @return {@code true} if the character is ISO-LATIN-1 white - * space; {@code false} otherwise. - * @see Character#isSpaceChar(char) - * @see Character#isWhitespace(char) - * @deprecated Replaced by isWhitespace(char). - */ - @Deprecated - public static boolean isSpace(char ch) { - return (ch <= 0x0020) && - (((((1L << 0x0009) | - (1L << 0x000A) | - (1L << 0x000C) | - (1L << 0x000D) | - (1L << 0x0020)) >> ch) & 1L) != 0); - } - - - - /** - * Determines if the specified character is white space according to Java. - * A character is a Java whitespace character if and only if it satisfies - * one of the following criteria: - *

    - *
  • It is a Unicode space character ({@code SPACE_SEPARATOR}, - * {@code LINE_SEPARATOR}, or {@code PARAGRAPH_SEPARATOR}) - * but is not also a non-breaking space ({@code '\u005Cu00A0'}, - * {@code '\u005Cu2007'}, {@code '\u005Cu202F'}). - *
  • It is {@code '\u005Ct'}, U+0009 HORIZONTAL TABULATION. - *
  • It is {@code '\u005Cn'}, U+000A LINE FEED. - *
  • It is {@code '\u005Cu000B'}, U+000B VERTICAL TABULATION. - *
  • It is {@code '\u005Cf'}, U+000C FORM FEED. - *
  • It is {@code '\u005Cr'}, U+000D CARRIAGE RETURN. - *
  • It is {@code '\u005Cu001C'}, U+001C FILE SEPARATOR. - *
  • It is {@code '\u005Cu001D'}, U+001D GROUP SEPARATOR. - *
  • It is {@code '\u005Cu001E'}, U+001E RECORD SEPARATOR. - *
  • It is {@code '\u005Cu001F'}, U+001F UNIT SEPARATOR. - *
- * - *

Note: This method cannot handle supplementary characters. To support - * all Unicode characters, including supplementary characters, use - * the {@link #isWhitespace(int)} method. - * - * @param ch the character to be tested. - * @return {@code true} if the character is a Java whitespace - * character; {@code false} otherwise. - * @see Character#isSpaceChar(char) - * @since 1.1 - */ - public static boolean isWhitespace(char ch) { - return isWhitespace((int)ch); - } - - /** - * Determines if the specified character (Unicode code point) is - * white space according to Java. A character is a Java - * whitespace character if and only if it satisfies one of the - * following criteria: - *

    - *
  • It is a Unicode space character ({@link #SPACE_SEPARATOR}, - * {@link #LINE_SEPARATOR}, or {@link #PARAGRAPH_SEPARATOR}) - * but is not also a non-breaking space ({@code '\u005Cu00A0'}, - * {@code '\u005Cu2007'}, {@code '\u005Cu202F'}). - *
  • It is {@code '\u005Ct'}, U+0009 HORIZONTAL TABULATION. - *
  • It is {@code '\u005Cn'}, U+000A LINE FEED. - *
  • It is {@code '\u005Cu000B'}, U+000B VERTICAL TABULATION. - *
  • It is {@code '\u005Cf'}, U+000C FORM FEED. - *
  • It is {@code '\u005Cr'}, U+000D CARRIAGE RETURN. - *
  • It is {@code '\u005Cu001C'}, U+001C FILE SEPARATOR. - *
  • It is {@code '\u005Cu001D'}, U+001D GROUP SEPARATOR. - *
  • It is {@code '\u005Cu001E'}, U+001E RECORD SEPARATOR. - *
  • It is {@code '\u005Cu001F'}, U+001F UNIT SEPARATOR. - *
- *

- * - * @param codePoint the character (Unicode code point) to be tested. - * @return {@code true} if the character is a Java whitespace - * character; {@code false} otherwise. - * @see Character#isSpaceChar(int) - * @since 1.5 - */ - public static boolean isWhitespace(int codePoint) { - throw new UnsupportedOperationException(); - } - - /** - * Determines if the specified character is an ISO control - * character. A character is considered to be an ISO control - * character if its code is in the range {@code '\u005Cu0000'} - * through {@code '\u005Cu001F'} or in the range - * {@code '\u005Cu007F'} through {@code '\u005Cu009F'}. - * - *

Note: This method cannot handle supplementary characters. To support - * all Unicode characters, including supplementary characters, use - * the {@link #isISOControl(int)} method. - * - * @param ch the character to be tested. - * @return {@code true} if the character is an ISO control character; - * {@code false} otherwise. - * - * @see Character#isSpaceChar(char) - * @see Character#isWhitespace(char) - * @since 1.1 - */ - public static boolean isISOControl(char ch) { - return isISOControl((int)ch); - } - - /** - * Determines if the referenced character (Unicode code point) is an ISO control - * character. A character is considered to be an ISO control - * character if its code is in the range {@code '\u005Cu0000'} - * through {@code '\u005Cu001F'} or in the range - * {@code '\u005Cu007F'} through {@code '\u005Cu009F'}. - * - * @param codePoint the character (Unicode code point) to be tested. - * @return {@code true} if the character is an ISO control character; - * {@code false} otherwise. - * @see Character#isSpaceChar(int) - * @see Character#isWhitespace(int) - * @since 1.5 - */ - public static boolean isISOControl(int codePoint) { - // Optimized form of: - // (codePoint >= 0x00 && codePoint <= 0x1F) || - // (codePoint >= 0x7F && codePoint <= 0x9F); - return codePoint <= 0x9F && - (codePoint >= 0x7F || (codePoint >>> 5 == 0)); - } - - /** - * Determines the character representation for a specific digit in - * the specified radix. If the value of {@code radix} is not a - * valid radix, or the value of {@code digit} is not a valid - * digit in the specified radix, the null character - * ({@code '\u005Cu0000'}) is returned. - *

- * The {@code radix} argument is valid if it is greater than or - * equal to {@code MIN_RADIX} and less than or equal to - * {@code MAX_RADIX}. The {@code digit} argument is valid if - * {@code 0 <= digit < radix}. - *

- * If the digit is less than 10, then - * {@code '0' + digit} is returned. Otherwise, the value - * {@code 'a' + digit - 10} is returned. - * - * @param digit the number to convert to a character. - * @param radix the radix. - * @return the {@code char} representation of the specified digit - * in the specified radix. - * @see Character#MIN_RADIX - * @see Character#MAX_RADIX - * @see Character#digit(char, int) - */ - public static char forDigit(int digit, int radix) { - if ((digit >= radix) || (digit < 0)) { - return '\0'; - } - if ((radix < Character.MIN_RADIX) || (radix > Character.MAX_RADIX)) { - return '\0'; - } - if (digit < 10) { - return (char)('0' + digit); - } - return (char)('a' - 10 + digit); - } - - /** - * Compares two {@code Character} objects numerically. - * - * @param anotherCharacter the {@code Character} to be compared. - - * @return the value {@code 0} if the argument {@code Character} - * is equal to this {@code Character}; a value less than - * {@code 0} if this {@code Character} is numerically less - * than the {@code Character} argument; and a value greater than - * {@code 0} if this {@code Character} is numerically greater - * than the {@code Character} argument (unsigned comparison). - * Note that this is strictly a numerical comparison; it is not - * locale-dependent. - * @since 1.2 - */ - public int compareTo(Character anotherCharacter) { - return compare(this.value, anotherCharacter.value); - } - - /** - * Compares two {@code char} values numerically. - * The value returned is identical to what would be returned by: - *

-     *    Character.valueOf(x).compareTo(Character.valueOf(y))
-     * 
- * - * @param x the first {@code char} to compare - * @param y the second {@code char} to compare - * @return the value {@code 0} if {@code x == y}; - * a value less than {@code 0} if {@code x < y}; and - * a value greater than {@code 0} if {@code x > y} - * @since 1.7 - */ - public static int compare(char x, char y) { - return x - y; - } - - - /** - * The number of bits used to represent a char value in unsigned - * binary form, constant {@code 16}. - * - * @since 1.5 - */ - public static final int SIZE = 16; - - /** - * Returns the value obtained by reversing the order of the bytes in the - * specified char value. - * - * @return the value obtained by reversing (or, equivalently, swapping) - * the bytes in the specified char value. - * @since 1.5 - */ - public static char reverseBytes(char ch) { - return (char) (((ch & 0xFF00) >> 8) | (ch << 8)); - } - -} diff -r 388e48c0a37a -r 05224402145d emul/src/main/java/java/lang/Class.java --- a/emul/src/main/java/java/lang/Class.java Wed Jan 23 20:16:48 2013 +0100 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,1205 +0,0 @@ -/* - * Copyright (c) 1994, 2010, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code 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 - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package java.lang; - -import java.io.ByteArrayInputStream; -import org.apidesign.bck2brwsr.emul.AnnotationImpl; -import java.io.InputStream; -import java.lang.annotation.Annotation; -import java.lang.reflect.Field; -import java.lang.reflect.Method; -import java.lang.reflect.TypeVariable; -import org.apidesign.bck2brwsr.core.JavaScriptBody; -import org.apidesign.bck2brwsr.emul.MethodImpl; - -/** - * Instances of the class {@code Class} represent classes and - * interfaces in a running Java application. An enum is a kind of - * class and an annotation is a kind of interface. Every array also - * belongs to a class that is reflected as a {@code Class} object - * that is shared by all arrays with the same element type and number - * of dimensions. The primitive Java types ({@code boolean}, - * {@code byte}, {@code char}, {@code short}, - * {@code int}, {@code long}, {@code float}, and - * {@code double}), and the keyword {@code void} are also - * represented as {@code Class} objects. - * - *

{@code Class} has no public constructor. Instead {@code Class} - * objects are constructed automatically by the Java Virtual Machine as classes - * are loaded and by calls to the {@code defineClass} method in the class - * loader. - * - *

The following example uses a {@code Class} object to print the - * class name of an object: - * - *

- *     void printClassName(Object obj) {
- *         System.out.println("The class of " + obj +
- *                            " is " + obj.getClass().getName());
- *     }
- * 
- * - *

It is also possible to get the {@code Class} object for a named - * type (or for void) using a class literal. See Section 15.8.2 of - * The Java™ Language Specification. - * For example: - * - *

- * {@code System.out.println("The name of class Foo is: "+Foo.class.getName());} - *
- * - * @param the type of the class modeled by this {@code Class} - * object. For example, the type of {@code String.class} is {@code - * Class}. Use {@code Class} if the class being modeled is - * unknown. - * - * @author unascribed - * @see java.lang.ClassLoader#defineClass(byte[], int, int) - * @since JDK1.0 - */ -public final - class Class implements java.io.Serializable, - java.lang.reflect.GenericDeclaration, - java.lang.reflect.Type, - java.lang.reflect.AnnotatedElement { - private static final int ANNOTATION= 0x00002000; - private static final int ENUM = 0x00004000; - private static final int SYNTHETIC = 0x00001000; - - /* - * Constructor. Only the Java Virtual Machine creates Class - * objects. - */ - private Class() {} - - - /** - * Converts the object to a string. The string representation is the - * string "class" or "interface", followed by a space, and then by the - * fully qualified name of the class in the format returned by - * {@code getName}. If this {@code Class} object represents a - * primitive type, this method returns the name of the primitive type. If - * this {@code Class} object represents void this method returns - * "void". - * - * @return a string representation of this class object. - */ - public String toString() { - return (isInterface() ? "interface " : (isPrimitive() ? "" : "class ")) - + getName(); - } - - - /** - * Returns the {@code Class} object associated with the class or - * interface with the given string name. Invoking this method is - * equivalent to: - * - *
- * {@code Class.forName(className, true, currentLoader)} - *
- * - * where {@code currentLoader} denotes the defining class loader of - * the current class. - * - *

For example, the following code fragment returns the - * runtime {@code Class} descriptor for the class named - * {@code java.lang.Thread}: - * - *

- * {@code Class t = Class.forName("java.lang.Thread")} - *
- *

- * A call to {@code forName("X")} causes the class named - * {@code X} to be initialized. - * - * @param className the fully qualified name of the desired class. - * @return the {@code Class} object for the class with the - * specified name. - * @exception LinkageError if the linkage fails - * @exception ExceptionInInitializerError if the initialization provoked - * by this method fails - * @exception ClassNotFoundException if the class cannot be located - */ - public static Class forName(String className) - throws ClassNotFoundException { - if (className.startsWith("[")) { - Class arrType = defineArray(className); - Class c = arrType; - while (c != null && c.isArray()) { - c = c.getComponentType0(); // verify component type is sane - } - return arrType; - } - Class c = loadCls(className, className.replace('.', '_')); - if (c == null) { - throw new ClassNotFoundException(className); - } - return c; - } - - @JavaScriptBody(args = {"n", "c" }, body = - "if (vm[c]) return vm[c].$class;\n" - + "if (vm.loadClass) {\n" - + " vm.loadClass(n);\n" - + " if (vm[c]) return vm[c].$class;\n" - + "}\n" - + "return null;" - ) - private static native Class loadCls(String n, String c); - - - /** - * Creates a new instance of the class represented by this {@code Class} - * object. The class is instantiated as if by a {@code new} - * expression with an empty argument list. The class is initialized if it - * has not already been initialized. - * - *

Note that this method propagates any exception thrown by the - * nullary constructor, including a checked exception. Use of - * this method effectively bypasses the compile-time exception - * checking that would otherwise be performed by the compiler. - * The {@link - * java.lang.reflect.Constructor#newInstance(java.lang.Object...) - * Constructor.newInstance} method avoids this problem by wrapping - * any exception thrown by the constructor in a (checked) {@link - * java.lang.reflect.InvocationTargetException}. - * - * @return a newly allocated instance of the class represented by this - * object. - * @exception IllegalAccessException if the class or its nullary - * constructor is not accessible. - * @exception InstantiationException - * if this {@code Class} represents an abstract class, - * an interface, an array class, a primitive type, or void; - * or if the class has no nullary constructor; - * or if the instantiation fails for some other reason. - * @exception ExceptionInInitializerError if the initialization - * provoked by this method fails. - * @exception SecurityException - * If a security manager, s, is present and any of the - * following conditions is met: - * - *

    - * - *
  • invocation of - * {@link SecurityManager#checkMemberAccess - * s.checkMemberAccess(this, Member.PUBLIC)} denies - * creation of new instances of this class - * - *
  • the caller's class loader is not the same as or an - * ancestor of the class loader for the current class and - * invocation of {@link SecurityManager#checkPackageAccess - * s.checkPackageAccess()} denies access to the package - * of this class - * - *
- * - */ - @JavaScriptBody(args = { "self", "illegal" }, body = - "\nvar c = self.cnstr;" - + "\nif (c['cons__V']) {" - + "\n if ((c.cons__V.access & 0x1) != 0) {" - + "\n var inst = c();" - + "\n c.cons__V.call(inst);" - + "\n return inst;" - + "\n }" - + "\n return illegal;" - + "\n}" - + "\nreturn null;" - ) - private static native Object newInstance0(Class self, Object illegal); - - public T newInstance() - throws InstantiationException, IllegalAccessException - { - Object illegal = new Object(); - Object inst = newInstance0(this, illegal); - if (inst == null) { - throw new InstantiationException(getName()); - } - if (inst == illegal) { - throw new IllegalAccessException(); - } - return (T)inst; - } - - /** - * Determines if the specified {@code Object} is assignment-compatible - * with the object represented by this {@code Class}. This method is - * the dynamic equivalent of the Java language {@code instanceof} - * operator. The method returns {@code true} if the specified - * {@code Object} argument is non-null and can be cast to the - * reference type represented by this {@code Class} object without - * raising a {@code ClassCastException.} It returns {@code false} - * otherwise. - * - *

Specifically, if this {@code Class} object represents a - * declared class, this method returns {@code true} if the specified - * {@code Object} argument is an instance of the represented class (or - * of any of its subclasses); it returns {@code false} otherwise. If - * this {@code Class} object represents an array class, this method - * returns {@code true} if the specified {@code Object} argument - * can be converted to an object of the array class by an identity - * conversion or by a widening reference conversion; it returns - * {@code false} otherwise. If this {@code Class} object - * represents an interface, this method returns {@code true} if the - * class or any superclass of the specified {@code Object} argument - * implements this interface; it returns {@code false} otherwise. If - * this {@code Class} object represents a primitive type, this method - * returns {@code false}. - * - * @param obj the object to check - * @return true if {@code obj} is an instance of this class - * - * @since JDK1.1 - */ - public boolean isInstance(Object obj) { - String prop = "$instOf_" + getName().replace('.', '_'); - return hasProperty(obj, prop); - } - - @JavaScriptBody(args = { "who", "prop" }, body = - "if (who[prop]) return true; else return false;" - ) - private static native boolean hasProperty(Object who, String prop); - - - /** - * Determines if the class or interface represented by this - * {@code Class} object is either the same as, or is a superclass or - * superinterface of, the class or interface represented by the specified - * {@code Class} parameter. It returns {@code true} if so; - * otherwise it returns {@code false}. If this {@code Class} - * object represents a primitive type, this method returns - * {@code true} if the specified {@code Class} parameter is - * exactly this {@code Class} object; otherwise it returns - * {@code false}. - * - *

Specifically, this method tests whether the type represented by the - * specified {@code Class} parameter can be converted to the type - * represented by this {@code Class} object via an identity conversion - * or via a widening reference conversion. See The Java Language - * Specification, sections 5.1.1 and 5.1.4 , for details. - * - * @param cls the {@code Class} object to be checked - * @return the {@code boolean} value indicating whether objects of the - * type {@code cls} can be assigned to objects of this class - * @exception NullPointerException if the specified Class parameter is - * null. - * @since JDK1.1 - */ - public native boolean isAssignableFrom(Class cls); - - - /** - * Determines if the specified {@code Class} object represents an - * interface type. - * - * @return {@code true} if this object represents an interface; - * {@code false} otherwise. - */ - public boolean isInterface() { - return (getAccess() & 0x200) != 0; - } - - @JavaScriptBody(args = {}, body = "return this.access;") - private native int getAccess(); - - - /** - * Determines if this {@code Class} object represents an array class. - * - * @return {@code true} if this object represents an array class; - * {@code false} otherwise. - * @since JDK1.1 - */ - public boolean isArray() { - return hasProperty(this, "array"); // NOI18N - } - - - /** - * Determines if the specified {@code Class} object represents a - * primitive type. - * - *

There are nine predefined {@code Class} objects to represent - * the eight primitive types and void. These are created by the Java - * Virtual Machine, and have the same names as the primitive types that - * they represent, namely {@code boolean}, {@code byte}, - * {@code char}, {@code short}, {@code int}, - * {@code long}, {@code float}, and {@code double}. - * - *

These objects may only be accessed via the following public static - * final variables, and are the only {@code Class} objects for which - * this method returns {@code true}. - * - * @return true if and only if this class represents a primitive type - * - * @see java.lang.Boolean#TYPE - * @see java.lang.Character#TYPE - * @see java.lang.Byte#TYPE - * @see java.lang.Short#TYPE - * @see java.lang.Integer#TYPE - * @see java.lang.Long#TYPE - * @see java.lang.Float#TYPE - * @see java.lang.Double#TYPE - * @see java.lang.Void#TYPE - * @since JDK1.1 - */ - @JavaScriptBody(args = {}, body = - "if (this.primitive) return true;" - + "else return false;" - ) - public native boolean isPrimitive(); - - /** - * Returns true if this {@code Class} object represents an annotation - * type. Note that if this method returns true, {@link #isInterface()} - * would also return true, as all annotation types are also interfaces. - * - * @return {@code true} if this class object represents an annotation - * type; {@code false} otherwise - * @since 1.5 - */ - public boolean isAnnotation() { - return (getModifiers() & ANNOTATION) != 0; - } - - /** - * Returns {@code true} if this class is a synthetic class; - * returns {@code false} otherwise. - * @return {@code true} if and only if this class is a synthetic class as - * defined by the Java Language Specification. - * @since 1.5 - */ - public boolean isSynthetic() { - return (getModifiers() & SYNTHETIC) != 0; - } - - /** - * Returns the name of the entity (class, interface, array class, - * primitive type, or void) represented by this {@code Class} object, - * as a {@code String}. - * - *

If this class object represents a reference type that is not an - * array type then the binary name of the class is returned, as specified - * by - * The Java™ Language Specification. - * - *

If this class object represents a primitive type or void, then the - * name returned is a {@code String} equal to the Java language - * keyword corresponding to the primitive type or void. - * - *

If this class object represents a class of arrays, then the internal - * form of the name consists of the name of the element type preceded by - * one or more '{@code [}' characters representing the depth of the array - * nesting. The encoding of element type names is as follows: - * - *

- *
Element Type     Encoding - *
boolean     Z - *
byte     B - *
char     C - *
class or interface - *     Lclassname; - *
double     D - *
float     F - *
int     I - *
long     J - *
short     S - *
- * - *

The class or interface name classname is the binary name of - * the class specified above. - * - *

Examples: - *

-     * String.class.getName()
-     *     returns "java.lang.String"
-     * byte.class.getName()
-     *     returns "byte"
-     * (new Object[3]).getClass().getName()
-     *     returns "[Ljava.lang.Object;"
-     * (new int[3][4][5][6][7][8][9]).getClass().getName()
-     *     returns "[[[[[[[I"
-     * 
- * - * @return the name of the class or interface - * represented by this object. - */ - public String getName() { - return jvmName().replace('/', '.'); - } - - @JavaScriptBody(args = {}, body = "return this.jvmName;") - private native String jvmName(); - - - /** - * Returns an array of {@code TypeVariable} objects that represent the - * type variables declared by the generic declaration represented by this - * {@code GenericDeclaration} object, in declaration order. Returns an - * array of length 0 if the underlying generic declaration declares no type - * variables. - * - * @return an array of {@code TypeVariable} objects that represent - * the type variables declared by this generic declaration - * @throws java.lang.reflect.GenericSignatureFormatError if the generic - * signature of this generic declaration does not conform to - * the format specified in - * The Java™ Virtual Machine Specification - * @since 1.5 - */ - public TypeVariable>[] getTypeParameters() { - throw new UnsupportedOperationException(); - } - - /** - * Returns the {@code Class} representing the superclass of the entity - * (class, interface, primitive type or void) represented by this - * {@code Class}. If this {@code Class} represents either the - * {@code Object} class, an interface, a primitive type, or void, then - * null is returned. If this object represents an array class then the - * {@code Class} object representing the {@code Object} class is - * returned. - * - * @return the superclass of the class represented by this object. - */ - @JavaScriptBody(args = {}, body = "return this.superclass;") - public native Class getSuperclass(); - - /** - * Returns the Java language modifiers for this class or interface, encoded - * in an integer. The modifiers consist of the Java Virtual Machine's - * constants for {@code public}, {@code protected}, - * {@code private}, {@code final}, {@code static}, - * {@code abstract} and {@code interface}; they should be decoded - * using the methods of class {@code Modifier}. - * - *

If the underlying class is an array class, then its - * {@code public}, {@code private} and {@code protected} - * modifiers are the same as those of its component type. If this - * {@code Class} represents a primitive type or void, its - * {@code public} modifier is always {@code true}, and its - * {@code protected} and {@code private} modifiers are always - * {@code false}. If this object represents an array class, a - * primitive type or void, then its {@code final} modifier is always - * {@code true} and its interface modifier is always - * {@code false}. The values of its other modifiers are not determined - * by this specification. - * - *

The modifier encodings are defined in The Java Virtual Machine - * Specification, table 4.1. - * - * @return the {@code int} representing the modifiers for this class - * @see java.lang.reflect.Modifier - * @since JDK1.1 - */ - public native int getModifiers(); - - - /** - * Returns the simple name of the underlying class as given in the - * source code. Returns an empty string if the underlying class is - * anonymous. - * - *

The simple name of an array is the simple name of the - * component type with "[]" appended. In particular the simple - * name of an array whose component type is anonymous is "[]". - * - * @return the simple name of the underlying class - * @since 1.5 - */ - public String getSimpleName() { - if (isArray()) - return getComponentType().getSimpleName()+"[]"; - - String simpleName = getSimpleBinaryName(); - if (simpleName == null) { // top level class - simpleName = getName(); - return simpleName.substring(simpleName.lastIndexOf(".")+1); // strip the package name - } - // According to JLS3 "Binary Compatibility" (13.1) the binary - // name of non-package classes (not top level) is the binary - // name of the immediately enclosing class followed by a '$' followed by: - // (for nested and inner classes): the simple name. - // (for local classes): 1 or more digits followed by the simple name. - // (for anonymous classes): 1 or more digits. - - // Since getSimpleBinaryName() will strip the binary name of - // the immediatly enclosing class, we are now looking at a - // string that matches the regular expression "\$[0-9]*" - // followed by a simple name (considering the simple of an - // anonymous class to be the empty string). - - // Remove leading "\$[0-9]*" from the name - int length = simpleName.length(); - if (length < 1 || simpleName.charAt(0) != '$') - throw new IllegalStateException("Malformed class name"); - int index = 1; - while (index < length && isAsciiDigit(simpleName.charAt(index))) - index++; - // Eventually, this is the empty string iff this is an anonymous class - return simpleName.substring(index); - } - - /** - * Returns the "simple binary name" of the underlying class, i.e., - * the binary name without the leading enclosing class name. - * Returns {@code null} if the underlying class is a top level - * class. - */ - private String getSimpleBinaryName() { - Class enclosingClass = null; // XXX getEnclosingClass(); - if (enclosingClass == null) // top level class - return null; - // Otherwise, strip the enclosing class' name - try { - return getName().substring(enclosingClass.getName().length()); - } catch (IndexOutOfBoundsException ex) { - throw new IllegalStateException("Malformed class name"); - } - } - - /** - * Returns an array containing {@code Field} objects reflecting all - * the accessible public fields of the class or interface represented by - * this {@code Class} object. The elements in the array returned are - * not sorted and are not in any particular order. This method returns an - * array of length 0 if the class or interface has no accessible public - * fields, or if it represents an array class, a primitive type, or void. - * - *

Specifically, if this {@code Class} object represents a class, - * this method returns the public fields of this class and of all its - * superclasses. If this {@code Class} object represents an - * interface, this method returns the fields of this interface and of all - * its superinterfaces. - * - *

The implicit length field for array class is not reflected by this - * method. User code should use the methods of class {@code Array} to - * manipulate arrays. - * - *

See The Java Language Specification, sections 8.2 and 8.3. - * - * @return the array of {@code Field} objects representing the - * public fields - * @exception SecurityException - * If a security manager, s, is present and any of the - * following conditions is met: - * - *

    - * - *
  • invocation of - * {@link SecurityManager#checkMemberAccess - * s.checkMemberAccess(this, Member.PUBLIC)} denies - * access to the fields within this class - * - *
  • the caller's class loader is not the same as or an - * ancestor of the class loader for the current class and - * invocation of {@link SecurityManager#checkPackageAccess - * s.checkPackageAccess()} denies access to the package - * of this class - * - *
- * - * @since JDK1.1 - */ - public Field[] getFields() throws SecurityException { - throw new SecurityException(); - } - - /** - * Returns an array containing {@code Method} objects reflecting all - * the public member methods of the class or interface represented - * by this {@code Class} object, including those declared by the class - * or interface and those inherited from superclasses and - * superinterfaces. Array classes return all the (public) member methods - * inherited from the {@code Object} class. The elements in the array - * returned are not sorted and are not in any particular order. This - * method returns an array of length 0 if this {@code Class} object - * represents a class or interface that has no public member methods, or if - * this {@code Class} object represents a primitive type or void. - * - *

The class initialization method {@code } is not - * included in the returned array. If the class declares multiple public - * member methods with the same parameter types, they are all included in - * the returned array. - * - *

See The Java Language Specification, sections 8.2 and 8.4. - * - * @return the array of {@code Method} objects representing the - * public methods of this class - * @exception SecurityException - * If a security manager, s, is present and any of the - * following conditions is met: - * - *

    - * - *
  • invocation of - * {@link SecurityManager#checkMemberAccess - * s.checkMemberAccess(this, Member.PUBLIC)} denies - * access to the methods within this class - * - *
  • the caller's class loader is not the same as or an - * ancestor of the class loader for the current class and - * invocation of {@link SecurityManager#checkPackageAccess - * s.checkPackageAccess()} denies access to the package - * of this class - * - *
- * - * @since JDK1.1 - */ - public Method[] getMethods() throws SecurityException { - return MethodImpl.findMethods(this, 0x01); - } - - /** - * Returns a {@code Field} object that reflects the specified public - * member field of the class or interface represented by this - * {@code Class} object. The {@code name} parameter is a - * {@code String} specifying the simple name of the desired field. - * - *

The field to be reflected is determined by the algorithm that - * follows. Let C be the class represented by this object: - *

    - *
  1. If C declares a public field with the name specified, that is the - * field to be reflected.
  2. - *
  3. If no field was found in step 1 above, this algorithm is applied - * recursively to each direct superinterface of C. The direct - * superinterfaces are searched in the order they were declared.
  4. - *
  5. If no field was found in steps 1 and 2 above, and C has a - * superclass S, then this algorithm is invoked recursively upon S. - * If C has no superclass, then a {@code NoSuchFieldException} - * is thrown.
  6. - *
- * - *

See The Java Language Specification, sections 8.2 and 8.3. - * - * @param name the field name - * @return the {@code Field} object of this class specified by - * {@code name} - * @exception NoSuchFieldException if a field with the specified name is - * not found. - * @exception NullPointerException if {@code name} is {@code null} - * @exception SecurityException - * If a security manager, s, is present and any of the - * following conditions is met: - * - *

    - * - *
  • invocation of - * {@link SecurityManager#checkMemberAccess - * s.checkMemberAccess(this, Member.PUBLIC)} denies - * access to the field - * - *
  • the caller's class loader is not the same as or an - * ancestor of the class loader for the current class and - * invocation of {@link SecurityManager#checkPackageAccess - * s.checkPackageAccess()} denies access to the package - * of this class - * - *
- * - * @since JDK1.1 - */ - public Field getField(String name) - throws SecurityException { - throw new SecurityException(); - } - - - /** - * Returns a {@code Method} object that reflects the specified public - * member method of the class or interface represented by this - * {@code Class} object. The {@code name} parameter is a - * {@code String} specifying the simple name of the desired method. The - * {@code parameterTypes} parameter is an array of {@code Class} - * objects that identify the method's formal parameter types, in declared - * order. If {@code parameterTypes} is {@code null}, it is - * treated as if it were an empty array. - * - *

If the {@code name} is "{@code };"or "{@code }" a - * {@code NoSuchMethodException} is raised. Otherwise, the method to - * be reflected is determined by the algorithm that follows. Let C be the - * class represented by this object: - *

    - *
  1. C is searched for any matching methods. If no matching - * method is found, the algorithm of step 1 is invoked recursively on - * the superclass of C.
  2. - *
  3. If no method was found in step 1 above, the superinterfaces of C - * are searched for a matching method. If any such method is found, it - * is reflected.
  4. - *
- * - * To find a matching method in a class C:  If C declares exactly one - * public method with the specified name and exactly the same formal - * parameter types, that is the method reflected. If more than one such - * method is found in C, and one of these methods has a return type that is - * more specific than any of the others, that method is reflected; - * otherwise one of the methods is chosen arbitrarily. - * - *

Note that there may be more than one matching method in a - * class because while the Java language forbids a class to - * declare multiple methods with the same signature but different - * return types, the Java virtual machine does not. This - * increased flexibility in the virtual machine can be used to - * implement various language features. For example, covariant - * returns can be implemented with {@linkplain - * java.lang.reflect.Method#isBridge bridge methods}; the bridge - * method and the method being overridden would have the same - * signature but different return types. - * - *

See The Java Language Specification, sections 8.2 and 8.4. - * - * @param name the name of the method - * @param parameterTypes the list of parameters - * @return the {@code Method} object that matches the specified - * {@code name} and {@code parameterTypes} - * @exception NoSuchMethodException if a matching method is not found - * or if the name is "<init>"or "<clinit>". - * @exception NullPointerException if {@code name} is {@code null} - * @exception SecurityException - * If a security manager, s, is present and any of the - * following conditions is met: - * - *

    - * - *
  • invocation of - * {@link SecurityManager#checkMemberAccess - * s.checkMemberAccess(this, Member.PUBLIC)} denies - * access to the method - * - *
  • the caller's class loader is not the same as or an - * ancestor of the class loader for the current class and - * invocation of {@link SecurityManager#checkPackageAccess - * s.checkPackageAccess()} denies access to the package - * of this class - * - *
- * - * @since JDK1.1 - */ - public Method getMethod(String name, Class... parameterTypes) - throws SecurityException, NoSuchMethodException { - Method m = MethodImpl.findMethod(this, name, parameterTypes); - if (m == null) { - StringBuilder sb = new StringBuilder(); - sb.append(getName()).append('.').append(name).append('('); - String sep = ""; - for (int i = 0; i < parameterTypes.length; i++) { - sb.append(sep).append(parameterTypes[i].getName()); - sep = ", "; - } - sb.append(')'); - throw new NoSuchMethodException(sb.toString()); - } - return m; - } - - /** - * Character.isDigit answers {@code true} to some non-ascii - * digits. This one does not. - */ - private static boolean isAsciiDigit(char c) { - return '0' <= c && c <= '9'; - } - - /** - * Returns the canonical name of the underlying class as - * defined by the Java Language Specification. Returns null if - * the underlying class does not have a canonical name (i.e., if - * it is a local or anonymous class or an array whose component - * type does not have a canonical name). - * @return the canonical name of the underlying class if it exists, and - * {@code null} otherwise. - * @since 1.5 - */ - public String getCanonicalName() { - if (isArray()) { - String canonicalName = getComponentType().getCanonicalName(); - if (canonicalName != null) - return canonicalName + "[]"; - else - return null; - } -// if (isLocalOrAnonymousClass()) -// return null; -// Class enclosingClass = getEnclosingClass(); - Class enclosingClass = null; - if (enclosingClass == null) { // top level class - return getName(); - } else { - String enclosingName = enclosingClass.getCanonicalName(); - if (enclosingName == null) - return null; - return enclosingName + "." + getSimpleName(); - } - } - - /** - * Finds a resource with a given name. The rules for searching resources - * associated with a given class are implemented by the defining - * {@linkplain ClassLoader class loader} of the class. This method - * delegates to this object's class loader. If this object was loaded by - * the bootstrap class loader, the method delegates to {@link - * ClassLoader#getSystemResourceAsStream}. - * - *

Before delegation, an absolute resource name is constructed from the - * given resource name using this algorithm: - * - *

    - * - *
  • If the {@code name} begins with a {@code '/'} - * ('\u002f'), then the absolute name of the resource is the - * portion of the {@code name} following the {@code '/'}. - * - *
  • Otherwise, the absolute name is of the following form: - * - *
    - * {@code modified_package_name/name} - *
    - * - *

    Where the {@code modified_package_name} is the package name of this - * object with {@code '/'} substituted for {@code '.'} - * ('\u002e'). - * - *

- * - * @param name name of the desired resource - * @return A {@link java.io.InputStream} object or {@code null} if - * no resource with this name is found - * @throws NullPointerException If {@code name} is {@code null} - * @since JDK1.1 - */ - public InputStream getResourceAsStream(String name) { - name = resolveName(name); - byte[] arr = getResourceAsStream0(name); - return arr == null ? null : new ByteArrayInputStream(arr); - } - - @JavaScriptBody(args = "name", body = - "return (vm.loadBytes) ? vm.loadBytes(name) : null;" - ) - private static native byte[] getResourceAsStream0(String name); - - /** - * Finds a resource with a given name. The rules for searching resources - * associated with a given class are implemented by the defining - * {@linkplain ClassLoader class loader} of the class. This method - * delegates to this object's class loader. If this object was loaded by - * the bootstrap class loader, the method delegates to {@link - * ClassLoader#getSystemResource}. - * - *

Before delegation, an absolute resource name is constructed from the - * given resource name using this algorithm: - * - *

    - * - *
  • If the {@code name} begins with a {@code '/'} - * ('\u002f'), then the absolute name of the resource is the - * portion of the {@code name} following the {@code '/'}. - * - *
  • Otherwise, the absolute name is of the following form: - * - *
    - * {@code modified_package_name/name} - *
    - * - *

    Where the {@code modified_package_name} is the package name of this - * object with {@code '/'} substituted for {@code '.'} - * ('\u002e'). - * - *

- * - * @param name name of the desired resource - * @return A {@link java.net.URL} object or {@code null} if no - * resource with this name is found - * @since JDK1.1 - */ - public java.net.URL getResource(String name) { - name = resolveName(name); - ClassLoader cl = null; - if (cl==null) { - // A system class. - return ClassLoader.getSystemResource(name); - } - return cl.getResource(name); - } - - - /** - * Add a package name prefix if the name is not absolute Remove leading "/" - * if name is absolute - */ - private String resolveName(String name) { - if (name == null) { - return name; - } - if (!name.startsWith("/")) { - Class c = this; - while (c.isArray()) { - c = c.getComponentType(); - } - String baseName = c.getName(); - int index = baseName.lastIndexOf('.'); - if (index != -1) { - name = baseName.substring(0, index).replace('.', '/') - +"/"+name; - } - } else { - name = name.substring(1); - } - return name; - } - - /** - * Returns the class loader for the class. Some implementations may use - * null to represent the bootstrap class loader. This method will return - * null in such implementations if this class was loaded by the bootstrap - * class loader. - * - *

If a security manager is present, and the caller's class loader is - * not null and the caller's class loader is not the same as or an ancestor of - * the class loader for the class whose class loader is requested, then - * this method calls the security manager's {@code checkPermission} - * method with a {@code RuntimePermission("getClassLoader")} - * permission to ensure it's ok to access the class loader for the class. - * - *

If this object - * represents a primitive type or void, null is returned. - * - * @return the class loader that loaded the class or interface - * represented by this object. - * @throws SecurityException - * if a security manager exists and its - * {@code checkPermission} method denies - * access to the class loader for the class. - * @see java.lang.ClassLoader - * @see SecurityManager#checkPermission - * @see java.lang.RuntimePermission - */ - public ClassLoader getClassLoader() { - throw new SecurityException(); - } - - /** - * Returns the {@code Class} representing the component type of an - * array. If this class does not represent an array class this method - * returns null. - * - * @return the {@code Class} representing the component type of this - * class if this class is an array - * @see java.lang.reflect.Array - * @since JDK1.1 - */ - public Class getComponentType() { - if (isArray()) { - try { - return getComponentType0(); - } catch (ClassNotFoundException cnfe) { - throw new IllegalStateException(cnfe); - } - } - return null; - } - - private Class getComponentType0() throws ClassNotFoundException { - String n = getName().substring(1); - switch (n.charAt(0)) { - case 'L': - n = n.substring(1, n.length() - 1); - return Class.forName(n); - case 'I': - return Integer.TYPE; - case 'J': - return Long.TYPE; - case 'D': - return Double.TYPE; - case 'F': - return Float.TYPE; - case 'B': - return Byte.TYPE; - case 'Z': - return Boolean.TYPE; - case 'S': - return Short.TYPE; - case 'V': - return Void.TYPE; - case 'C': - return Character.TYPE; - case '[': - return defineArray(n); - default: - throw new ClassNotFoundException("Unknown component type of " + getName()); - } - } - - @JavaScriptBody(args = { "sig" }, body = - "var c = Array[sig];\n" + - "if (c) return c;\n" + - "c = vm.java_lang_Class(true);\n" + - "c.jvmName = sig;\n" + - "c.superclass = vm.java_lang_Object(false).$class;\n" + - "c.array = true;\n" + - "Array[sig] = c;\n" + - "return c;" - ) - private static native Class defineArray(String sig); - - /** - * Returns true if and only if this class was declared as an enum in the - * source code. - * - * @return true if and only if this class was declared as an enum in the - * source code - * @since 1.5 - */ - public boolean isEnum() { - // An enum must both directly extend java.lang.Enum and have - // the ENUM bit set; classes for specialized enum constants - // don't do the former. - return (this.getModifiers() & ENUM) != 0 && - this.getSuperclass() == java.lang.Enum.class; - } - - /** - * Casts an object to the class or interface represented - * by this {@code Class} object. - * - * @param obj the object to be cast - * @return the object after casting, or null if obj is null - * - * @throws ClassCastException if the object is not - * null and is not assignable to the type T. - * - * @since 1.5 - */ - public T cast(Object obj) { - if (obj != null && !isInstance(obj)) - throw new ClassCastException(cannotCastMsg(obj)); - return (T) obj; - } - - private String cannotCastMsg(Object obj) { - return "Cannot cast " + obj.getClass().getName() + " to " + getName(); - } - - /** - * Casts this {@code Class} object to represent a subclass of the class - * represented by the specified class object. Checks that that the cast - * is valid, and throws a {@code ClassCastException} if it is not. If - * this method succeeds, it always returns a reference to this class object. - * - *

This method is useful when a client needs to "narrow" the type of - * a {@code Class} object to pass it to an API that restricts the - * {@code Class} objects that it is willing to accept. A cast would - * generate a compile-time warning, as the correctness of the cast - * could not be checked at runtime (because generic types are implemented - * by erasure). - * - * @return this {@code Class} object, cast to represent a subclass of - * the specified class object. - * @throws ClassCastException if this {@code Class} object does not - * represent a subclass of the specified class (here "subclass" includes - * the class itself). - * @since 1.5 - */ - public Class asSubclass(Class clazz) { - if (clazz.isAssignableFrom(this)) - return (Class) this; - else - throw new ClassCastException(this.toString()); - } - - @JavaScriptBody(args = { "ac" }, - body = - "if (this.anno) {" - + " return this.anno['L' + ac.jvmName + ';'];" - + "} else return null;" - ) - private Object getAnnotationData(Class annotationClass) { - throw new UnsupportedOperationException(); - } - /** - * @throws NullPointerException {@inheritDoc} - * @since 1.5 - */ - public A getAnnotation(Class annotationClass) { - Object data = getAnnotationData(annotationClass); - return data == null ? null : AnnotationImpl.create(annotationClass, data); - } - - /** - * @throws NullPointerException {@inheritDoc} - * @since 1.5 - */ - @JavaScriptBody(args = { "ac" }, - body = "if (this.anno && this.anno['L' + ac.jvmName + ';']) { return true; }" - + "else return false;" - ) - public boolean isAnnotationPresent( - Class annotationClass) { - if (annotationClass == null) - throw new NullPointerException(); - - return getAnnotation(annotationClass) != null; - } - - @JavaScriptBody(args = {}, body = "return this.anno;") - private Object getAnnotationData() { - throw new UnsupportedOperationException(); - } - - /** - * @since 1.5 - */ - public Annotation[] getAnnotations() { - Object data = getAnnotationData(); - return data == null ? new Annotation[0] : AnnotationImpl.create(data); - } - - /** - * @since 1.5 - */ - public Annotation[] getDeclaredAnnotations() { - throw new UnsupportedOperationException(); - } - - @JavaScriptBody(args = "type", body = "" - + "var c = vm.java_lang_Class(true);" - + "c.jvmName = type;" - + "c.primitive = true;" - + "return c;" - ) - native static Class getPrimitiveClass(String type); - - @JavaScriptBody(args = {}, body = - "return vm.desiredAssertionStatus ? vm.desiredAssertionStatus : false;" - ) - public native boolean desiredAssertionStatus(); -} diff -r 388e48c0a37a -r 05224402145d emul/src/main/java/java/lang/ClassCastException.java --- a/emul/src/main/java/java/lang/ClassCastException.java Wed Jan 23 20:16:48 2013 +0100 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,60 +0,0 @@ -/* - * Copyright (c) 1994, 2008, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code 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 - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package java.lang; - -/** - * Thrown to indicate that the code has attempted to cast an object - * to a subclass of which it is not an instance. For example, the - * following code generates a ClassCastException: - *

- *     Object x = new Integer(0);
- *     System.out.println((String)x);
- * 
- * - * @author unascribed - * @since JDK1.0 - */ -public -class ClassCastException extends RuntimeException { - private static final long serialVersionUID = -9223365651070458532L; - - /** - * Constructs a ClassCastException with no detail message. - */ - public ClassCastException() { - super(); - } - - /** - * Constructs a ClassCastException with the specified - * detail message. - * - * @param s the detail message. - */ - public ClassCastException(String s) { - super(s); - } -} diff -r 388e48c0a37a -r 05224402145d emul/src/main/java/java/lang/ClassFormatError.java --- a/emul/src/main/java/java/lang/ClassFormatError.java Wed Jan 23 20:16:48 2013 +0100 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,56 +0,0 @@ -/* - * Copyright (c) 1994, 2008, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code 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 - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package java.lang; - -/** - * Thrown when the Java Virtual Machine attempts to read a class - * file and determines that the file is malformed or otherwise cannot - * be interpreted as a class file. - * - * @author unascribed - * @since JDK1.0 - */ -public -class ClassFormatError extends LinkageError { - private static final long serialVersionUID = -8420114879011949195L; - - /** - * Constructs a ClassFormatError with no detail message. - */ - public ClassFormatError() { - super(); - } - - /** - * Constructs a ClassFormatError with the specified - * detail message. - * - * @param s the detail message. - */ - public ClassFormatError(String s) { - super(s); - } -} diff -r 388e48c0a37a -r 05224402145d emul/src/main/java/java/lang/ClassLoader.java --- a/emul/src/main/java/java/lang/ClassLoader.java Wed Jan 23 20:16:48 2013 +0100 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,914 +0,0 @@ -/* - * Copyright (c) 1994, 2011, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code 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 - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ -package java.lang; - -import java.io.InputStream; -import java.io.IOException; -import java.net.URL; -import java.util.Enumeration; -import java.util.NoSuchElementException; -import org.apidesign.bck2brwsr.core.JavaScriptBody; - -/** - * A class loader is an object that is responsible for loading classes. The - * class ClassLoader is an abstract class. Given the binary name of a class, a class loader should attempt to - * locate or generate data that constitutes a definition for the class. A - * typical strategy is to transform the name into a file name and then read a - * "class file" of that name from a file system. - * - *

Every {@link Class Class} object contains a {@link - * Class#getClassLoader() reference} to the ClassLoader that defined - * it. - * - *

Class objects for array classes are not created by class - * loaders, but are created automatically as required by the Java runtime. - * The class loader for an array class, as returned by {@link - * Class#getClassLoader()} is the same as the class loader for its element - * type; if the element type is a primitive type, then the array class has no - * class loader. - * - *

Applications implement subclasses of ClassLoader in order to - * extend the manner in which the Java virtual machine dynamically loads - * classes. - * - *

Class loaders may typically be used by security managers to indicate - * security domains. - * - *

The ClassLoader class uses a delegation model to search for - * classes and resources. Each instance of ClassLoader has an - * associated parent class loader. When requested to find a class or - * resource, a ClassLoader instance will delegate the search for the - * class or resource to its parent class loader before attempting to find the - * class or resource itself. The virtual machine's built-in class loader, - * called the "bootstrap class loader", does not itself have a parent but may - * serve as the parent of a ClassLoader instance. - * - *

Class loaders that support concurrent loading of classes are known as - * parallel capable class loaders and are required to register - * themselves at their class initialization time by invoking the - * {@link - * #registerAsParallelCapable ClassLoader.registerAsParallelCapable} - * method. Note that the ClassLoader class is registered as parallel - * capable by default. However, its subclasses still need to register themselves - * if they are parallel capable.
- * In environments in which the delegation model is not strictly - * hierarchical, class loaders need to be parallel capable, otherwise class - * loading can lead to deadlocks because the loader lock is held for the - * duration of the class loading process (see {@link #loadClass - * loadClass} methods). - * - *

Normally, the Java virtual machine loads classes from the local file - * system in a platform-dependent manner. For example, on UNIX systems, the - * virtual machine loads classes from the directory defined by the - * CLASSPATH environment variable. - * - *

However, some classes may not originate from a file; they may originate - * from other sources, such as the network, or they could be constructed by an - * application. The method {@link #defineClass(String, byte[], int, int) - * defineClass} converts an array of bytes into an instance of class - * Class. Instances of this newly defined class can be created using - * {@link Class#newInstance Class.newInstance}. - * - *

The methods and constructors of objects created by a class loader may - * reference other classes. To determine the class(es) referred to, the Java - * virtual machine invokes the {@link #loadClass loadClass} method of - * the class loader that originally created the class. - * - *

For example, an application could create a network class loader to - * download class files from a server. Sample code might look like: - * - *

- *   ClassLoader loader = new NetworkClassLoader(host, port);
- *   Object main = loader.loadClass("Main", true).newInstance();
- *        . . .
- * 
- * - *

The network class loader subclass must define the methods {@link - * #findClass findClass} and loadClassData to load a class - * from the network. Once it has downloaded the bytes that make up the class, - * it should use the method {@link #defineClass defineClass} to - * create a class instance. A sample implementation is: - * - *

- *     class NetworkClassLoader extends ClassLoader {
- *         String host;
- *         int port;
- *
- *         public Class findClass(String name) {
- *             byte[] b = loadClassData(name);
- *             return defineClass(name, b, 0, b.length);
- *         }
- *
- *         private byte[] loadClassData(String name) {
- *             // load the class data from the connection
- *              . . .
- *         }
- *     }
- * 
- * - *

Binary names

- * - *

Any class name provided as a {@link String} parameter to methods in - * ClassLoader must be a binary name as defined by - * The Java™ Language Specification. - * - *

Examples of valid class names include: - *

- *   "java.lang.String"
- *   "javax.swing.JSpinner$DefaultEditor"
- *   "java.security.KeyStore$Builder$FileBuilder$1"
- *   "java.net.URLClassLoader$3$1"
- * 
- * - * @see #resolveClass(Class) - * @since 1.0 - */ -public abstract class ClassLoader { - - @JavaScriptBody(args = {}, body = "") - private static native void registerNatives(); - static { - registerNatives(); - } - - // The parent class loader for delegation - // Note: VM hardcoded the offset of this field, thus all new fields - // must be added *after* it. - private final ClassLoader parent; - - - /** - * Creates a new class loader using the specified parent class loader for - * delegation. - * - *

If there is a security manager, its {@link - * SecurityManager#checkCreateClassLoader() - * checkCreateClassLoader} method is invoked. This may result in - * a security exception.

- * - * @param parent - * The parent class loader - * - * @throws SecurityException - * If a security manager exists and its - * checkCreateClassLoader method doesn't allow creation - * of a new class loader. - * - * @since 1.2 - */ - protected ClassLoader(ClassLoader parent) { - throw new SecurityException(); - } - - /** - * Creates a new class loader using the ClassLoader returned by - * the method {@link #getSystemClassLoader() - * getSystemClassLoader()} as the parent class loader. - * - *

If there is a security manager, its {@link - * SecurityManager#checkCreateClassLoader() - * checkCreateClassLoader} method is invoked. This may result in - * a security exception.

- * - * @throws SecurityException - * If a security manager exists and its - * checkCreateClassLoader method doesn't allow creation - * of a new class loader. - */ - protected ClassLoader() { - throw new SecurityException(); - } - - // -- Class -- - - /** - * Loads the class with the specified binary name. - * This method searches for classes in the same manner as the {@link - * #loadClass(String, boolean)} method. It is invoked by the Java virtual - * machine to resolve class references. Invoking this method is equivalent - * to invoking {@link #loadClass(String, boolean) loadClass(name, - * false)}.

- * - * @param name - * The binary name of the class - * - * @return The resulting Class object - * - * @throws ClassNotFoundException - * If the class was not found - */ - public Class loadClass(String name) throws ClassNotFoundException { - return loadClass(name, false); - } - - /** - * Loads the class with the specified binary name. The - * default implementation of this method searches for classes in the - * following order: - * - *

    - * - *
  1. Invoke {@link #findLoadedClass(String)} to check if the class - * has already been loaded.

  2. - * - *
  3. Invoke the {@link #loadClass(String) loadClass} method - * on the parent class loader. If the parent is null the class - * loader built-in to the virtual machine is used, instead.

  4. - * - *
  5. Invoke the {@link #findClass(String)} method to find the - * class.

  6. - * - *
- * - *

If the class was found using the above steps, and the - * resolve flag is true, this method will then invoke the {@link - * #resolveClass(Class)} method on the resulting Class object. - * - *

Subclasses of ClassLoader are encouraged to override {@link - * #findClass(String)}, rather than this method.

- * - *

Unless overridden, this method synchronizes on the result of - * {@link #getClassLoadingLock getClassLoadingLock} method - * during the entire class loading process. - * - * @param name - * The binary name of the class - * - * @param resolve - * If true then resolve the class - * - * @return The resulting Class object - * - * @throws ClassNotFoundException - * If the class could not be found - */ - protected Class loadClass(String name, boolean resolve) - throws ClassNotFoundException - { - synchronized (getClassLoadingLock(name)) { - // First, check if the class has already been loaded - Class c = findLoadedClass(name); - if (c == null) { - try { - if (parent != null) { - c = parent.loadClass(name, false); - } else { - c = findBootstrapClassOrNull(name); - } - } catch (ClassNotFoundException e) { - // ClassNotFoundException thrown if class not found - // from the non-null parent class loader - } - - if (c == null) { - // If still not found, then invoke findClass in order - // to find the class. - c = findClass(name); - -// // this is the defining class loader; record the stats -// sun.misc.PerfCounter.getParentDelegationTime().addTime(t1 - t0); -// sun.misc.PerfCounter.getFindClassTime().addElapsedTimeFrom(t1); -// sun.misc.PerfCounter.getFindClasses().increment(); - } - } - if (resolve) { - resolveClass(c); - } - return c; - } - } - - /** - * Returns the lock object for class loading operations. - * For backward compatibility, the default implementation of this method - * behaves as follows. If this ClassLoader object is registered as - * parallel capable, the method returns a dedicated object associated - * with the specified class name. Otherwise, the method returns this - * ClassLoader object.

- * - * @param className - * The name of the to-be-loaded class - * - * @return the lock for class loading operations - * - * @throws NullPointerException - * If registered as parallel capable and className is null - * - * @see #loadClass(String, boolean) - * - * @since 1.7 - */ - protected Object getClassLoadingLock(String className) { - Object lock = this; - return lock; - } - - /** - * Finds the class with the specified binary name. - * This method should be overridden by class loader implementations that - * follow the delegation model for loading classes, and will be invoked by - * the {@link #loadClass loadClass} method after checking the - * parent class loader for the requested class. The default implementation - * throws a ClassNotFoundException.

- * - * @param name - * The binary name of the class - * - * @return The resulting Class object - * - * @throws ClassNotFoundException - * If the class could not be found - * - * @since 1.2 - */ - protected Class findClass(String name) throws ClassNotFoundException { - throw new ClassNotFoundException(name); - } - - /** - * Converts an array of bytes into an instance of class Class. - * Before the Class can be used it must be resolved. This method - * is deprecated in favor of the version that takes a binary name as its first argument, and is more secure. - * - * @param b - * The bytes that make up the class data. The bytes in positions - * off through off+len-1 should have the format - * of a valid class file as defined by - * The Java™ Virtual Machine Specification. - * - * @param off - * The start offset in b of the class data - * - * @param len - * The length of the class data - * - * @return The Class object that was created from the specified - * class data - * - * @throws ClassFormatError - * If the data did not contain a valid class - * - * @throws IndexOutOfBoundsException - * If either off or len is negative, or if - * off+len is greater than b.length. - * - * @throws SecurityException - * If an attempt is made to add this class to a package that - * contains classes that were signed by a different set of - * certificates than this class, or if an attempt is made - * to define a class in a package with a fully-qualified name - * that starts with "{@code java.}". - * - * @see #loadClass(String, boolean) - * @see #resolveClass(Class) - * - * @deprecated Replaced by {@link #defineClass(String, byte[], int, int) - * defineClass(String, byte[], int, int)} - */ - @Deprecated - protected final Class defineClass(byte[] b, int off, int len) - throws ClassFormatError - { - throw new SecurityException(); - } - - /** - * Converts an array of bytes into an instance of class Class. - * Before the Class can be used it must be resolved. - * - *

This method assigns a default {@link java.security.ProtectionDomain - * ProtectionDomain} to the newly defined class. The - * ProtectionDomain is effectively granted the same set of - * permissions returned when {@link - * java.security.Policy#getPermissions(java.security.CodeSource) - * Policy.getPolicy().getPermissions(new CodeSource(null, null))} - * is invoked. The default domain is created on the first invocation of - * {@link #defineClass(String, byte[], int, int) defineClass}, - * and re-used on subsequent invocations. - * - *

To assign a specific ProtectionDomain to the class, use - * the {@link #defineClass(String, byte[], int, int, - * java.security.ProtectionDomain) defineClass} method that takes a - * ProtectionDomain as one of its arguments.

- * - * @param name - * The expected binary name of the class, or - * null if not known - * - * @param b - * The bytes that make up the class data. The bytes in positions - * off through off+len-1 should have the format - * of a valid class file as defined by - * The Java™ Virtual Machine Specification. - * - * @param off - * The start offset in b of the class data - * - * @param len - * The length of the class data - * - * @return The Class object that was created from the specified - * class data. - * - * @throws ClassFormatError - * If the data did not contain a valid class - * - * @throws IndexOutOfBoundsException - * If either off or len is negative, or if - * off+len is greater than b.length. - * - * @throws SecurityException - * If an attempt is made to add this class to a package that - * contains classes that were signed by a different set of - * certificates than this class (which is unsigned), or if - * name begins with "java.". - * - * @see #loadClass(String, boolean) - * @see #resolveClass(Class) - * @see java.security.CodeSource - * @see java.security.SecureClassLoader - * - * @since 1.1 - */ - protected final Class defineClass(String name, byte[] b, int off, int len) - throws ClassFormatError - { - throw new SecurityException(); - } - - /** - * Links the specified class. This (misleadingly named) method may be - * used by a class loader to link a class. If the class c has - * already been linked, then this method simply returns. Otherwise, the - * class is linked as described in the "Execution" chapter of - * The Java™ Language Specification. - *

- * - * @param c - * The class to link - * - * @throws NullPointerException - * If c is null. - * - * @see #defineClass(String, byte[], int, int) - */ - protected final void resolveClass(Class c) { - resolveClass0(c); - } - - private native void resolveClass0(Class c); - - - /** - * Returns the class with the given binary name if this - * loader has been recorded by the Java virtual machine as an initiating - * loader of a class with that binary name. Otherwise - * null is returned.

- * - * @param name - * The binary name of the class - * - * @return The Class object, or null if the class has - * not been loaded - * - * @since 1.1 - */ - protected final Class findLoadedClass(String name) { - if (!checkName(name)) - return null; - return findLoadedClass0(name); - } - - private native final Class findLoadedClass0(String name); - - /** - * Sets the signers of a class. This should be invoked after defining a - * class.

- * - * @param c - * The Class object - * - * @param signers - * The signers for the class - * - * @since 1.1 - */ - protected final void setSigners(Class c, Object[] signers) { - //c.setSigners(signers); - throw new UnsupportedOperationException(); - } - - - // -- Resource -- - - /** - * Finds the resource with the given name. A resource is some data - * (images, audio, text, etc) that can be accessed by class code in a way - * that is independent of the location of the code. - * - *

The name of a resource is a '/'-separated path name that - * identifies the resource. - * - *

This method will first search the parent class loader for the - * resource; if the parent is null the path of the class loader - * built-in to the virtual machine is searched. That failing, this method - * will invoke {@link #findResource(String)} to find the resource.

- * - * @param name - * The resource name - * - * @return A URL object for reading the resource, or - * null if the resource could not be found or the invoker - * doesn't have adequate privileges to get the resource. - * - * @since 1.1 - */ - public URL getResource(String name) { - URL url; - if (parent != null) { - url = parent.getResource(name); - } else { - url = getBootstrapResource(name); - } - if (url == null) { - url = findResource(name); - } - return url; - } - - /** - * Finds all the resources with the given name. A resource is some data - * (images, audio, text, etc) that can be accessed by class code in a way - * that is independent of the location of the code. - * - *

The name of a resource is a /-separated path name that - * identifies the resource. - * - *

The search order is described in the documentation for {@link - * #getResource(String)}.

- * - * @param name - * The resource name - * - * @return An enumeration of {@link java.net.URL URL} objects for - * the resource. If no resources could be found, the enumeration - * will be empty. Resources that the class loader doesn't have - * access to will not be in the enumeration. - * - * @throws IOException - * If I/O errors occur - * - * @see #findResources(String) - * - * @since 1.2 - */ - public Enumeration getResources(String name) throws IOException { - Enumeration[] tmp = new Enumeration[2]; - if (parent != null) { - tmp[0] = parent.getResources(name); - } else { - tmp[0] = getBootstrapResources(name); - } - tmp[1] = findResources(name); - - return new CompoundEnumeration(tmp); - } - - /** - * Finds the resource with the given name. Class loader implementations - * should override this method to specify where to find resources.

- * - * @param name - * The resource name - * - * @return A URL object for reading the resource, or - * null if the resource could not be found - * - * @since 1.2 - */ - protected URL findResource(String name) { - return null; - } - - /** - * Returns an enumeration of {@link java.net.URL URL} objects - * representing all the resources with the given name. Class loader - * implementations should override this method to specify where to load - * resources from.

- * - * @param name - * The resource name - * - * @return An enumeration of {@link java.net.URL URL} objects for - * the resources - * - * @throws IOException - * If I/O errors occur - * - * @since 1.2 - */ - protected Enumeration findResources(String name) throws IOException { - return new CompoundEnumeration(new Enumeration[0]); - } - - // index 0: java.lang.ClassLoader.class - // index 1: the immediate caller of index 0. - // index 2: the immediate caller of index 1. - private static native Class getCaller(int index); - - /** - * Registers the caller as parallel capable.

- * The registration succeeds if and only if all of the following - * conditions are met:
- * 1. no instance of the caller has been created

- * 2. all of the super classes (except class Object) of the caller are - * registered as parallel capable

- * Note that once a class loader is registered as parallel capable, there - * is no way to change it back.

- * - * @return true if the caller is successfully registered as - * parallel capable and false if otherwise. - * - * @since 1.7 - */ -// protected static boolean registerAsParallelCapable() { -// return false; -// } - - /** - * Find a resource of the specified name from the search path used to load - * classes. This method locates the resource through the system class - * loader (see {@link #getSystemClassLoader()}).

- * - * @param name - * The resource name - * - * @return A {@link java.net.URL URL} object for reading the - * resource, or null if the resource could not be found - * - * @since 1.1 - */ - public static URL getSystemResource(String name) { - ClassLoader system = getSystemClassLoader(); - if (system == null) { - return getBootstrapResource(name); - } - return system.getResource(name); - } - - /** - * Finds all resources of the specified name from the search path used to - * load classes. The resources thus found are returned as an - * {@link java.util.Enumeration Enumeration} of {@link - * java.net.URL URL} objects. - * - *

The search order is described in the documentation for {@link - * #getSystemResource(String)}.

- * - * @param name - * The resource name - * - * @return An enumeration of resource {@link java.net.URL URL} - * objects - * - * @throws IOException - * If I/O errors occur - - * @since 1.2 - */ - public static Enumeration getSystemResources(String name) - throws IOException - { - ClassLoader system = getSystemClassLoader(); - if (system == null) { - return getBootstrapResources(name); - } - return system.getResources(name); - } - - - - /** - * Returns an input stream for reading the specified resource. - * - *

The search order is described in the documentation for {@link - * #getResource(String)}.

- * - * @param name - * The resource name - * - * @return An input stream for reading the resource, or null - * if the resource could not be found - * - * @since 1.1 - */ - public InputStream getResourceAsStream(String name) { - URL url = getResource(name); - try { - return url != null ? url.openStream() : null; - } catch (IOException e) { - return null; - } - } - - /** - * Open for reading, a resource of the specified name from the search path - * used to load classes. This method locates the resource through the - * system class loader (see {@link #getSystemClassLoader()}).

- * - * @param name - * The resource name - * - * @return An input stream for reading the resource, or null - * if the resource could not be found - * - * @since 1.1 - */ - public static InputStream getSystemResourceAsStream(String name) { - URL url = getSystemResource(name); - try { - return url != null ? url.openStream() : null; - } catch (IOException e) { - return null; - } - } - - - // -- Hierarchy -- - - /** - * Returns the parent class loader for delegation. Some implementations may - * use null to represent the bootstrap class loader. This method - * will return null in such implementations if this class loader's - * parent is the bootstrap class loader. - * - *

If a security manager is present, and the invoker's class loader is - * not null and is not an ancestor of this class loader, then this - * method invokes the security manager's {@link - * SecurityManager#checkPermission(java.security.Permission) - * checkPermission} method with a {@link - * RuntimePermission#RuntimePermission(String) - * RuntimePermission("getClassLoader")} permission to verify - * access to the parent class loader is permitted. If not, a - * SecurityException will be thrown.

- * - * @return The parent ClassLoader - * - * @throws SecurityException - * If a security manager exists and its checkPermission - * method doesn't allow access to this class loader's parent class - * loader. - * - * @since 1.2 - */ - public final ClassLoader getParent() { - throw new SecurityException(); - } - - /** - * Returns the system class loader for delegation. This is the default - * delegation parent for new ClassLoader instances, and is - * typically the class loader used to start the application. - * - *

This method is first invoked early in the runtime's startup - * sequence, at which point it creates the system class loader and sets it - * as the context class loader of the invoking Thread. - * - *

The default system class loader is an implementation-dependent - * instance of this class. - * - *

If the system property "java.system.class.loader" is defined - * when this method is first invoked then the value of that property is - * taken to be the name of a class that will be returned as the system - * class loader. The class is loaded using the default system class loader - * and must define a public constructor that takes a single parameter of - * type ClassLoader which is used as the delegation parent. An - * instance is then created using this constructor with the default system - * class loader as the parameter. The resulting class loader is defined - * to be the system class loader. - * - *

If a security manager is present, and the invoker's class loader is - * not null and the invoker's class loader is not the same as or - * an ancestor of the system class loader, then this method invokes the - * security manager's {@link - * SecurityManager#checkPermission(java.security.Permission) - * checkPermission} method with a {@link - * RuntimePermission#RuntimePermission(String) - * RuntimePermission("getClassLoader")} permission to verify - * access to the system class loader. If not, a - * SecurityException will be thrown.

- * - * @return The system ClassLoader for delegation, or - * null if none - * - * @throws SecurityException - * If a security manager exists and its checkPermission - * method doesn't allow access to the system class loader. - * - * @throws IllegalStateException - * If invoked recursively during the construction of the class - * loader specified by the "java.system.class.loader" - * property. - * - * @throws Error - * If the system property "java.system.class.loader" - * is defined but the named class could not be loaded, the - * provider class does not define the required constructor, or an - * exception is thrown by that constructor when it is invoked. The - * underlying cause of the error can be retrieved via the - * {@link Throwable#getCause()} method. - * - * @revised 1.4 - */ - public static ClassLoader getSystemClassLoader() { - throw new SecurityException(); - } - - // Returns true if the specified class loader can be found in this class - // loader's delegation chain. - boolean isAncestor(ClassLoader cl) { - ClassLoader acl = this; - do { - acl = acl.parent; - if (cl == acl) { - return true; - } - } while (acl != null); - return false; - } - - private boolean checkName(String name) { - throw new UnsupportedOperationException(); - } - - private Class findBootstrapClassOrNull(String name) { - throw new UnsupportedOperationException(); - } - - private static URL getBootstrapResource(String name) { - throw new UnsupportedOperationException(); - } - - private static Enumeration getBootstrapResources(String name) { - throw new UnsupportedOperationException(); - } - - private static class CompoundEnumeration implements Enumeration { - private URL next; - private int index; - private final Enumeration[] arr; - - public CompoundEnumeration(Enumeration[] arr) { - this.arr = arr; - this.index = 0; - } - - public boolean hasMoreElements() { - if (next == null) { - if (arr[index].hasMoreElements()) { - next = (URL) arr[index].nextElement(); - } else { - if (index < arr.length) { - index++; - return hasMoreElements(); - } - } - } - return next != null; - } - - public URL nextElement() { - if (!hasMoreElements()) { - throw new NoSuchElementException(); - } - URL r = next; - next = null; - return r; - } - - } -} diff -r 388e48c0a37a -r 05224402145d emul/src/main/java/java/lang/ClassNotFoundException.java --- a/emul/src/main/java/java/lang/ClassNotFoundException.java Wed Jan 23 20:16:48 2013 +0100 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,125 +0,0 @@ -/* - * Copyright (c) 1995, 2004, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code 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 - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package java.lang; - -/** - * Thrown when an application tries to load in a class through its - * string name using: - *
    - *
  • The forName method in class Class. - *
  • The findSystemClass method in class - * ClassLoader . - *
  • The loadClass method in class ClassLoader. - *
- *

- * but no definition for the class with the specified name could be found. - * - *

As of release 1.4, this exception has been retrofitted to conform to - * the general purpose exception-chaining mechanism. The "optional exception - * that was raised while loading the class" that may be provided at - * construction time and accessed via the {@link #getException()} method is - * now known as the cause, and may be accessed via the {@link - * Throwable#getCause()} method, as well as the aforementioned "legacy method." - * - * @author unascribed - * @see java.lang.Class#forName(java.lang.String) - * @see java.lang.ClassLoader#findSystemClass(java.lang.String) - * @see java.lang.ClassLoader#loadClass(java.lang.String, boolean) - * @since JDK1.0 - */ -public class ClassNotFoundException extends ReflectiveOperationException { - /** - * use serialVersionUID from JDK 1.1.X for interoperability - */ - private static final long serialVersionUID = 9176873029745254542L; - - /** - * This field holds the exception ex if the - * ClassNotFoundException(String s, Throwable ex) constructor was - * used to instantiate the object - * @serial - * @since 1.2 - */ - private Throwable ex; - - /** - * Constructs a ClassNotFoundException with no detail message. - */ - public ClassNotFoundException() { - super((Throwable)null); // Disallow initCause - } - - /** - * Constructs a ClassNotFoundException with the - * specified detail message. - * - * @param s the detail message. - */ - public ClassNotFoundException(String s) { - super(s, null); // Disallow initCause - } - - /** - * Constructs a ClassNotFoundException with the - * specified detail message and optional exception that was - * raised while loading the class. - * - * @param s the detail message - * @param ex the exception that was raised while loading the class - * @since 1.2 - */ - public ClassNotFoundException(String s, Throwable ex) { - super(s, null); // Disallow initCause - this.ex = ex; - } - - /** - * Returns the exception that was raised if an error occurred while - * attempting to load the class. Otherwise, returns null. - * - *

This method predates the general-purpose exception chaining facility. - * The {@link Throwable#getCause()} method is now the preferred means of - * obtaining this information. - * - * @return the Exception that was raised while loading a class - * @since 1.2 - */ - public Throwable getException() { - return ex; - } - - /** - * Returns the cause of this exception (the exception that was raised - * if an error occurred while attempting to load the class; otherwise - * null). - * - * @return the cause of this exception. - * @since 1.4 - */ - public Throwable getCause() { - return ex; - } -} diff -r 388e48c0a37a -r 05224402145d emul/src/main/java/java/lang/CloneNotSupportedException.java --- a/emul/src/main/java/java/lang/CloneNotSupportedException.java Wed Jan 23 20:16:48 2013 +0100 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,65 +0,0 @@ -/* - * Copyright (c) 1995, 2008, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code 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 - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package java.lang; - -/** - * Thrown to indicate that the clone method in class - * Object has been called to clone an object, but that - * the object's class does not implement the Cloneable - * interface. - *

- * Applications that override the clone method can also - * throw this exception to indicate that an object could not or - * should not be cloned. - * - * @author unascribed - * @see java.lang.Cloneable - * @see java.lang.Object#clone() - * @since JDK1.0 - */ - -public -class CloneNotSupportedException extends Exception { - private static final long serialVersionUID = 5195511250079656443L; - - /** - * Constructs a CloneNotSupportedException with no - * detail message. - */ - public CloneNotSupportedException() { - super(); - } - - /** - * Constructs a CloneNotSupportedException with the - * specified detail message. - * - * @param s the detail message. - */ - public CloneNotSupportedException(String s) { - super(s); - } -} diff -r 388e48c0a37a -r 05224402145d emul/src/main/java/java/lang/Comparable.java --- a/emul/src/main/java/java/lang/Comparable.java Wed Jan 23 20:16:48 2013 +0100 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,137 +0,0 @@ -/* - * Copyright (c) 1997, 2007, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code 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 - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package java.lang; - -/** - * This interface imposes a total ordering on the objects of each class that - * implements it. This ordering is referred to as the class's natural - * ordering, and the class's compareTo method is referred to as - * its natural comparison method.

- * - * Lists (and arrays) of objects that implement this interface can be sorted - * automatically by {@link Collections#sort(List) Collections.sort} (and - * {@link Arrays#sort(Object[]) Arrays.sort}). Objects that implement this - * interface can be used as keys in a {@linkplain SortedMap sorted map} or as - * elements in a {@linkplain SortedSet sorted set}, without the need to - * specify a {@linkplain Comparator comparator}.

- * - * The natural ordering for a class C is said to be consistent - * with equals if and only if e1.compareTo(e2) == 0 has - * the same boolean value as e1.equals(e2) for every - * e1 and e2 of class C. Note that null - * is not an instance of any class, and e.compareTo(null) should - * throw a NullPointerException even though e.equals(null) - * returns false.

- * - * It is strongly recommended (though not required) that natural orderings be - * consistent with equals. This is so because sorted sets (and sorted maps) - * without explicit comparators behave "strangely" when they are used with - * elements (or keys) whose natural ordering is inconsistent with equals. In - * particular, such a sorted set (or sorted map) violates the general contract - * for set (or map), which is defined in terms of the equals - * method.

- * - * For example, if one adds two keys a and b such that - * (!a.equals(b) && a.compareTo(b) == 0) to a sorted - * set that does not use an explicit comparator, the second add - * operation returns false (and the size of the sorted set does not increase) - * because a and b are equivalent from the sorted set's - * perspective.

- * - * Virtually all Java core classes that implement Comparable have natural - * orderings that are consistent with equals. One exception is - * java.math.BigDecimal, whose natural ordering equates - * BigDecimal objects with equal values and different precisions - * (such as 4.0 and 4.00).

- * - * For the mathematically inclined, the relation that defines - * the natural ordering on a given class C is:

- *       {(x, y) such that x.compareTo(y) <= 0}.
- * 
The quotient for this total order is:
- *       {(x, y) such that x.compareTo(y) == 0}.
- * 
- * - * It follows immediately from the contract for compareTo that the - * quotient is an equivalence relation on C, and that the - * natural ordering is a total order on C. When we say that a - * class's natural ordering is consistent with equals, we mean that the - * quotient for the natural ordering is the equivalence relation defined by - * the class's {@link Object#equals(Object) equals(Object)} method:
- *     {(x, y) such that x.equals(y)}. 

- * - * This interface is a member of the - * - * Java Collections Framework. - * - * @param the type of objects that this object may be compared to - * - * @author Josh Bloch - * @see java.util.Comparator - * @since 1.2 - */ - -public interface Comparable { - /** - * Compares this object with the specified object for order. Returns a - * negative integer, zero, or a positive integer as this object is less - * than, equal to, or greater than the specified object. - * - *

The implementor must ensure sgn(x.compareTo(y)) == - * -sgn(y.compareTo(x)) for all x and y. (This - * implies that x.compareTo(y) must throw an exception iff - * y.compareTo(x) throws an exception.) - * - *

The implementor must also ensure that the relation is transitive: - * (x.compareTo(y)>0 && y.compareTo(z)>0) implies - * x.compareTo(z)>0. - * - *

Finally, the implementor must ensure that x.compareTo(y)==0 - * implies that sgn(x.compareTo(z)) == sgn(y.compareTo(z)), for - * all z. - * - *

It is strongly recommended, but not strictly required that - * (x.compareTo(y)==0) == (x.equals(y)). Generally speaking, any - * class that implements the Comparable interface and violates - * this condition should clearly indicate this fact. The recommended - * language is "Note: this class has a natural ordering that is - * inconsistent with equals." - * - *

In the foregoing description, the notation - * sgn(expression) designates the mathematical - * signum function, which is defined to return one of -1, - * 0, or 1 according to whether the value of - * expression is negative, zero or positive. - * - * @param o the object to be compared. - * @return a negative integer, zero, or a positive integer as this object - * is less than, equal to, or greater than the specified object. - * - * @throws NullPointerException if the specified object is null - * @throws ClassCastException if the specified object's type prevents it - * from being compared to this object. - */ - public int compareTo(T o); -} diff -r 388e48c0a37a -r 05224402145d emul/src/main/java/java/lang/Deprecated.java --- a/emul/src/main/java/java/lang/Deprecated.java Wed Jan 23 20:16:48 2013 +0100 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,44 +0,0 @@ -/* - * Copyright (c) 2003, 2010, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code 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 - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package java.lang; - -import java.lang.annotation.*; -import static java.lang.annotation.ElementType.*; - -/** - * A program element annotated @Deprecated is one that programmers - * are discouraged from using, typically because it is dangerous, - * or because a better alternative exists. Compilers warn when a - * deprecated program element is used or overridden in non-deprecated code. - * - * @author Neal Gafter - * @since 1.5 - */ -@Documented -@Retention(RetentionPolicy.RUNTIME) -@Target(value={CONSTRUCTOR, FIELD, LOCAL_VARIABLE, METHOD, PACKAGE, PARAMETER, TYPE}) -public @interface Deprecated { -} diff -r 388e48c0a37a -r 05224402145d emul/src/main/java/java/lang/Double.java --- a/emul/src/main/java/java/lang/Double.java Wed Jan 23 20:16:48 2013 +0100 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,994 +0,0 @@ -/* - * Copyright (c) 1994, 2010, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code 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 - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package java.lang; - -import org.apidesign.bck2brwsr.core.JavaScriptBody; - -/** - * The {@code Double} class wraps a value of the primitive type - * {@code double} in an object. An object of type - * {@code Double} contains a single field whose type is - * {@code double}. - * - *

In addition, this class provides several methods for converting a - * {@code double} to a {@code String} and a - * {@code String} to a {@code double}, as well as other - * constants and methods useful when dealing with a - * {@code double}. - * - * @author Lee Boynton - * @author Arthur van Hoff - * @author Joseph D. Darcy - * @since JDK1.0 - */ -public final class Double extends Number implements Comparable { - /** - * A constant holding the positive infinity of type - * {@code double}. It is equal to the value returned by - * {@code Double.longBitsToDouble(0x7ff0000000000000L)}. - */ - public static final double POSITIVE_INFINITY = 1.0 / 0.0; - - /** - * A constant holding the negative infinity of type - * {@code double}. It is equal to the value returned by - * {@code Double.longBitsToDouble(0xfff0000000000000L)}. - */ - public static final double NEGATIVE_INFINITY = -1.0 / 0.0; - - /** - * A constant holding a Not-a-Number (NaN) value of type - * {@code double}. It is equivalent to the value returned by - * {@code Double.longBitsToDouble(0x7ff8000000000000L)}. - */ - public static final double NaN = 0.0d / 0.0; - - /** - * A constant holding the largest positive finite value of type - * {@code double}, - * (2-2-52)·21023. It is equal to - * the hexadecimal floating-point literal - * {@code 0x1.fffffffffffffP+1023} and also equal to - * {@code Double.longBitsToDouble(0x7fefffffffffffffL)}. - */ - public static final double MAX_VALUE = 0x1.fffffffffffffP+1023; // 1.7976931348623157e+308 - - /** - * A constant holding the smallest positive normal value of type - * {@code double}, 2-1022. It is equal to the - * hexadecimal floating-point literal {@code 0x1.0p-1022} and also - * equal to {@code Double.longBitsToDouble(0x0010000000000000L)}. - * - * @since 1.6 - */ - public static final double MIN_NORMAL = 0x1.0p-1022; // 2.2250738585072014E-308 - - /** - * A constant holding the smallest positive nonzero value of type - * {@code double}, 2-1074. It is equal to the - * hexadecimal floating-point literal - * {@code 0x0.0000000000001P-1022} and also equal to - * {@code Double.longBitsToDouble(0x1L)}. - */ - public static final double MIN_VALUE = 0x0.0000000000001P-1022; // 4.9e-324 - - /** - * Maximum exponent a finite {@code double} variable may have. - * It is equal to the value returned by - * {@code Math.getExponent(Double.MAX_VALUE)}. - * - * @since 1.6 - */ - public static final int MAX_EXPONENT = 1023; - - /** - * Minimum exponent a normalized {@code double} variable may - * have. It is equal to the value returned by - * {@code Math.getExponent(Double.MIN_NORMAL)}. - * - * @since 1.6 - */ - public static final int MIN_EXPONENT = -1022; - - /** - * The number of bits used to represent a {@code double} value. - * - * @since 1.5 - */ - public static final int SIZE = 64; - - /** - * The {@code Class} instance representing the primitive type - * {@code double}. - * - * @since JDK1.1 - */ - public static final Class TYPE = (Class) Class.getPrimitiveClass("double"); - - /** - * Returns a string representation of the {@code double} - * argument. All characters mentioned below are ASCII characters. - *

    - *
  • If the argument is NaN, the result is the string - * "{@code NaN}". - *
  • Otherwise, the result is a string that represents the sign and - * magnitude (absolute value) of the argument. If the sign is negative, - * the first character of the result is '{@code -}' - * ('\u002D'); if the sign is positive, no sign character - * appears in the result. As for the magnitude m: - *
      - *
    • If m is infinity, it is represented by the characters - * {@code "Infinity"}; thus, positive infinity produces the result - * {@code "Infinity"} and negative infinity produces the result - * {@code "-Infinity"}. - * - *
    • If m is zero, it is represented by the characters - * {@code "0.0"}; thus, negative zero produces the result - * {@code "-0.0"} and positive zero produces the result - * {@code "0.0"}. - * - *
    • If m is greater than or equal to 10-3 but less - * than 107, then it is represented as the integer part of - * m, in decimal form with no leading zeroes, followed by - * '{@code .}' ('\u002E'), followed by one or - * more decimal digits representing the fractional part of m. - * - *
    • If m is less than 10-3 or greater than or - * equal to 107, then it is represented in so-called - * "computerized scientific notation." Let n be the unique - * integer such that 10nm {@literal <} - * 10n+1; then let a be the - * mathematically exact quotient of m and - * 10n so that 1 ≤ a {@literal <} 10. The - * magnitude is then represented as the integer part of a, - * as a single decimal digit, followed by '{@code .}' - * ('\u002E'), followed by decimal digits - * representing the fractional part of a, followed by the - * letter '{@code E}' ('\u0045'), followed - * by a representation of n as a decimal integer, as - * produced by the method {@link Integer#toString(int)}. - *
    - *
- * How many digits must be printed for the fractional part of - * m or a? There must be at least one digit to represent - * the fractional part, and beyond that as many, but only as many, more - * digits as are needed to uniquely distinguish the argument value from - * adjacent values of type {@code double}. That is, suppose that - * x is the exact mathematical value represented by the decimal - * representation produced by this method for a finite nonzero argument - * d. Then d must be the {@code double} value nearest - * to x; or if two {@code double} values are equally close - * to x, then d must be one of them and the least - * significant bit of the significand of d must be {@code 0}. - * - *

To create localized string representations of a floating-point - * value, use subclasses of {@link java.text.NumberFormat}. - * - * @param d the {@code double} to be converted. - * @return a string representation of the argument. - */ - @JavaScriptBody(args="d", body="var r = d.toString();" - + "if (r.indexOf('.') === -1) r = r + '.0';" - + "return r;") - public static String toString(double d) { - throw new UnsupportedOperationException(); - } - - /** - * Returns a hexadecimal string representation of the - * {@code double} argument. All characters mentioned below - * are ASCII characters. - * - *

    - *
  • If the argument is NaN, the result is the string - * "{@code NaN}". - *
  • Otherwise, the result is a string that represents the sign - * and magnitude of the argument. If the sign is negative, the - * first character of the result is '{@code -}' - * ('\u002D'); if the sign is positive, no sign - * character appears in the result. As for the magnitude m: - * - *
      - *
    • If m is infinity, it is represented by the string - * {@code "Infinity"}; thus, positive infinity produces the - * result {@code "Infinity"} and negative infinity produces - * the result {@code "-Infinity"}. - * - *
    • If m is zero, it is represented by the string - * {@code "0x0.0p0"}; thus, negative zero produces the result - * {@code "-0x0.0p0"} and positive zero produces the result - * {@code "0x0.0p0"}. - * - *
    • If m is a {@code double} value with a - * normalized representation, substrings are used to represent the - * significand and exponent fields. The significand is - * represented by the characters {@code "0x1."} - * followed by a lowercase hexadecimal representation of the rest - * of the significand as a fraction. Trailing zeros in the - * hexadecimal representation are removed unless all the digits - * are zero, in which case a single zero is used. Next, the - * exponent is represented by {@code "p"} followed - * by a decimal string of the unbiased exponent as if produced by - * a call to {@link Integer#toString(int) Integer.toString} on the - * exponent value. - * - *
    • If m is a {@code double} value with a subnormal - * representation, the significand is represented by the - * characters {@code "0x0."} followed by a - * hexadecimal representation of the rest of the significand as a - * fraction. Trailing zeros in the hexadecimal representation are - * removed. Next, the exponent is represented by - * {@code "p-1022"}. Note that there must be at - * least one nonzero digit in a subnormal significand. - * - *
    - * - *
- * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - *

Examples

Floating-point ValueHexadecimal String
{@code 1.0} {@code 0x1.0p0}
{@code -1.0} {@code -0x1.0p0}
{@code 2.0} {@code 0x1.0p1}
{@code 3.0} {@code 0x1.8p1}
{@code 0.5} {@code 0x1.0p-1}
{@code 0.25} {@code 0x1.0p-2}
{@code Double.MAX_VALUE}{@code 0x1.fffffffffffffp1023}
{@code Minimum Normal Value}{@code 0x1.0p-1022}
{@code Maximum Subnormal Value}{@code 0x0.fffffffffffffp-1022}
{@code Double.MIN_VALUE}{@code 0x0.0000000000001p-1022}
- * @param d the {@code double} to be converted. - * @return a hex string representation of the argument. - * @since 1.5 - * @author Joseph D. Darcy - */ - public static String toHexString(double d) { - throw new UnsupportedOperationException(); -// /* -// * Modeled after the "a" conversion specifier in C99, section -// * 7.19.6.1; however, the output of this method is more -// * tightly specified. -// */ -// if (!FpUtils.isFinite(d) ) -// // For infinity and NaN, use the decimal output. -// return Double.toString(d); -// else { -// // Initialized to maximum size of output. -// StringBuffer answer = new StringBuffer(24); -// -// if (FpUtils.rawCopySign(1.0, d) == -1.0) // value is negative, -// answer.append("-"); // so append sign info -// -// answer.append("0x"); -// -// d = Math.abs(d); -// -// if(d == 0.0) { -// answer.append("0.0p0"); -// } -// else { -// boolean subnormal = (d < DoubleConsts.MIN_NORMAL); -// -// // Isolate significand bits and OR in a high-order bit -// // so that the string representation has a known -// // length. -// long signifBits = (Double.doubleToLongBits(d) -// & DoubleConsts.SIGNIF_BIT_MASK) | -// 0x1000000000000000L; -// -// // Subnormal values have a 0 implicit bit; normal -// // values have a 1 implicit bit. -// answer.append(subnormal ? "0." : "1."); -// -// // Isolate the low-order 13 digits of the hex -// // representation. If all the digits are zero, -// // replace with a single 0; otherwise, remove all -// // trailing zeros. -// String signif = Long.toHexString(signifBits).substring(3,16); -// answer.append(signif.equals("0000000000000") ? // 13 zeros -// "0": -// signif.replaceFirst("0{1,12}$", "")); -// -// // If the value is subnormal, use the E_min exponent -// // value for double; otherwise, extract and report d's -// // exponent (the representation of a subnormal uses -// // E_min -1). -// answer.append("p" + (subnormal ? -// DoubleConsts.MIN_EXPONENT: -// FpUtils.getExponent(d) )); -// } -// return answer.toString(); -// } - } - - /** - * Returns a {@code Double} object holding the - * {@code double} value represented by the argument string - * {@code s}. - * - *

If {@code s} is {@code null}, then a - * {@code NullPointerException} is thrown. - * - *

Leading and trailing whitespace characters in {@code s} - * are ignored. Whitespace is removed as if by the {@link - * String#trim} method; that is, both ASCII space and control - * characters are removed. The rest of {@code s} should - * constitute a FloatValue as described by the lexical - * syntax rules: - * - *

- *
- *
FloatValue: - *
Signopt {@code NaN} - *
Signopt {@code Infinity} - *
Signopt FloatingPointLiteral - *
Signopt HexFloatingPointLiteral - *
SignedInteger - *
- * - *

- * - *

- *
HexFloatingPointLiteral: - *
HexSignificand BinaryExponent FloatTypeSuffixopt - *
- * - *

- * - *

- *
HexSignificand: - *
HexNumeral - *
HexNumeral {@code .} - *
{@code 0x} HexDigitsopt - * {@code .} HexDigits - *
{@code 0X} HexDigitsopt - * {@code .} HexDigits - *
- * - *

- * - *

- *
BinaryExponent: - *
BinaryExponentIndicator SignedInteger - *
- * - *

- * - *

- *
BinaryExponentIndicator: - *
{@code p} - *
{@code P} - *
- * - *
- * - * where Sign, FloatingPointLiteral, - * HexNumeral, HexDigits, SignedInteger and - * FloatTypeSuffix are as defined in the lexical structure - * sections of - * The Java™ Language Specification, - * except that underscores are not accepted between digits. - * If {@code s} does not have the form of - * a FloatValue, then a {@code NumberFormatException} - * is thrown. Otherwise, {@code s} is regarded as - * representing an exact decimal value in the usual - * "computerized scientific notation" or as an exact - * hexadecimal value; this exact numerical value is then - * conceptually converted to an "infinitely precise" - * binary value that is then rounded to type {@code double} - * by the usual round-to-nearest rule of IEEE 754 floating-point - * arithmetic, which includes preserving the sign of a zero - * value. - * - * Note that the round-to-nearest rule also implies overflow and - * underflow behaviour; if the exact value of {@code s} is large - * enough in magnitude (greater than or equal to ({@link - * #MAX_VALUE} + {@link Math#ulp(double) ulp(MAX_VALUE)}/2), - * rounding to {@code double} will result in an infinity and if the - * exact value of {@code s} is small enough in magnitude (less - * than or equal to {@link #MIN_VALUE}/2), rounding to float will - * result in a zero. - * - * Finally, after rounding a {@code Double} object representing - * this {@code double} value is returned. - * - *

To interpret localized string representations of a - * floating-point value, use subclasses of {@link - * java.text.NumberFormat}. - * - *

Note that trailing format specifiers, specifiers that - * determine the type of a floating-point literal - * ({@code 1.0f} is a {@code float} value; - * {@code 1.0d} is a {@code double} value), do - * not influence the results of this method. In other - * words, the numerical value of the input string is converted - * directly to the target floating-point type. The two-step - * sequence of conversions, string to {@code float} followed - * by {@code float} to {@code double}, is not - * equivalent to converting a string directly to - * {@code double}. For example, the {@code float} - * literal {@code 0.1f} is equal to the {@code double} - * value {@code 0.10000000149011612}; the {@code float} - * literal {@code 0.1f} represents a different numerical - * value than the {@code double} literal - * {@code 0.1}. (The numerical value 0.1 cannot be exactly - * represented in a binary floating-point number.) - * - *

To avoid calling this method on an invalid string and having - * a {@code NumberFormatException} be thrown, the regular - * expression below can be used to screen the input string: - * - * - *

-     *  final String Digits     = "(\\p{Digit}+)";
-     *  final String HexDigits  = "(\\p{XDigit}+)";
-     *  // an exponent is 'e' or 'E' followed by an optionally
-     *  // signed decimal integer.
-     *  final String Exp        = "[eE][+-]?"+Digits;
-     *  final String fpRegex    =
-     *      ("[\\x00-\\x20]*"+  // Optional leading "whitespace"
-     *       "[+-]?(" + // Optional sign character
-     *       "NaN|" +           // "NaN" string
-     *       "Infinity|" +      // "Infinity" string
-     *
-     *       // A decimal floating-point string representing a finite positive
-     *       // number without a leading sign has at most five basic pieces:
-     *       // Digits . Digits ExponentPart FloatTypeSuffix
-     *       //
-     *       // Since this method allows integer-only strings as input
-     *       // in addition to strings of floating-point literals, the
-     *       // two sub-patterns below are simplifications of the grammar
-     *       // productions from section 3.10.2 of
-     *       // The Java™ Language Specification.
-     *
-     *       // Digits ._opt Digits_opt ExponentPart_opt FloatTypeSuffix_opt
-     *       "((("+Digits+"(\\.)?("+Digits+"?)("+Exp+")?)|"+
-     *
-     *       // . Digits ExponentPart_opt FloatTypeSuffix_opt
-     *       "(\\.("+Digits+")("+Exp+")?)|"+
-     *
-     *       // Hexadecimal strings
-     *       "((" +
-     *        // 0[xX] HexDigits ._opt BinaryExponent FloatTypeSuffix_opt
-     *        "(0[xX]" + HexDigits + "(\\.)?)|" +
-     *
-     *        // 0[xX] HexDigits_opt . HexDigits BinaryExponent FloatTypeSuffix_opt
-     *        "(0[xX]" + HexDigits + "?(\\.)" + HexDigits + ")" +
-     *
-     *        ")[pP][+-]?" + Digits + "))" +
-     *       "[fFdD]?))" +
-     *       "[\\x00-\\x20]*");// Optional trailing "whitespace"
-     *
-     *  if (Pattern.matches(fpRegex, myString))
-     *      Double.valueOf(myString); // Will not throw NumberFormatException
-     *  else {
-     *      // Perform suitable alternative action
-     *  }
-     * 
- * - * - * @param s the string to be parsed. - * @return a {@code Double} object holding the value - * represented by the {@code String} argument. - * @throws NumberFormatException if the string does not contain a - * parsable number. - */ - @JavaScriptBody(args="s", body="return parseFloat(s);") - public static Double valueOf(String s) throws NumberFormatException { - throw new UnsupportedOperationException(); -// return new Double(FloatingDecimal.readJavaFormatString(s).doubleValue()); - } - - /** - * Returns a {@code Double} instance representing the specified - * {@code double} value. - * If a new {@code Double} instance is not required, this method - * should generally be used in preference to the constructor - * {@link #Double(double)}, as this method is likely to yield - * significantly better space and time performance by caching - * frequently requested values. - * - * @param d a double value. - * @return a {@code Double} instance representing {@code d}. - * @since 1.5 - */ - public static Double valueOf(double d) { - return new Double(d); - } - - /** - * Returns a new {@code double} initialized to the value - * represented by the specified {@code String}, as performed - * by the {@code valueOf} method of class - * {@code Double}. - * - * @param s the string to be parsed. - * @return the {@code double} value represented by the string - * argument. - * @throws NullPointerException if the string is null - * @throws NumberFormatException if the string does not contain - * a parsable {@code double}. - * @see java.lang.Double#valueOf(String) - * @since 1.2 - */ - @JavaScriptBody(args="s", body="return parseFloat(s);") - public static double parseDouble(String s) throws NumberFormatException { - throw new UnsupportedOperationException(); -// return FloatingDecimal.readJavaFormatString(s).doubleValue(); - } - - /** - * Returns {@code true} if the specified number is a - * Not-a-Number (NaN) value, {@code false} otherwise. - * - * @param v the value to be tested. - * @return {@code true} if the value of the argument is NaN; - * {@code false} otherwise. - */ - static public boolean isNaN(double v) { - return (v != v); - } - - /** - * Returns {@code true} if the specified number is infinitely - * large in magnitude, {@code false} otherwise. - * - * @param v the value to be tested. - * @return {@code true} if the value of the argument is positive - * infinity or negative infinity; {@code false} otherwise. - */ - static public boolean isInfinite(double v) { - return (v == POSITIVE_INFINITY) || (v == NEGATIVE_INFINITY); - } - - /** - * The value of the Double. - * - * @serial - */ - private final double value; - - /** - * Constructs a newly allocated {@code Double} object that - * represents the primitive {@code double} argument. - * - * @param value the value to be represented by the {@code Double}. - */ - public Double(double value) { - this.value = value; - } - - /** - * Constructs a newly allocated {@code Double} object that - * represents the floating-point value of type {@code double} - * represented by the string. The string is converted to a - * {@code double} value as if by the {@code valueOf} method. - * - * @param s a string to be converted to a {@code Double}. - * @throws NumberFormatException if the string does not contain a - * parsable number. - * @see java.lang.Double#valueOf(java.lang.String) - */ - public Double(String s) throws NumberFormatException { - // REMIND: this is inefficient - this(valueOf(s).doubleValue()); - } - - /** - * Returns {@code true} if this {@code Double} value is - * a Not-a-Number (NaN), {@code false} otherwise. - * - * @return {@code true} if the value represented by this object is - * NaN; {@code false} otherwise. - */ - public boolean isNaN() { - return isNaN(value); - } - - /** - * Returns {@code true} if this {@code Double} value is - * infinitely large in magnitude, {@code false} otherwise. - * - * @return {@code true} if the value represented by this object is - * positive infinity or negative infinity; - * {@code false} otherwise. - */ - public boolean isInfinite() { - return isInfinite(value); - } - - /** - * Returns a string representation of this {@code Double} object. - * The primitive {@code double} value represented by this - * object is converted to a string exactly as if by the method - * {@code toString} of one argument. - * - * @return a {@code String} representation of this object. - * @see java.lang.Double#toString(double) - */ - public String toString() { - return toString(value); - } - - /** - * Returns the value of this {@code Double} as a {@code byte} (by - * casting to a {@code byte}). - * - * @return the {@code double} value represented by this object - * converted to type {@code byte} - * @since JDK1.1 - */ - public byte byteValue() { - return (byte)value; - } - - /** - * Returns the value of this {@code Double} as a - * {@code short} (by casting to a {@code short}). - * - * @return the {@code double} value represented by this object - * converted to type {@code short} - * @since JDK1.1 - */ - public short shortValue() { - return (short)value; - } - - /** - * Returns the value of this {@code Double} as an - * {@code int} (by casting to type {@code int}). - * - * @return the {@code double} value represented by this object - * converted to type {@code int} - */ - public int intValue() { - return (int)value; - } - - /** - * Returns the value of this {@code Double} as a - * {@code long} (by casting to type {@code long}). - * - * @return the {@code double} value represented by this object - * converted to type {@code long} - */ - public long longValue() { - return (long)value; - } - - /** - * Returns the {@code float} value of this - * {@code Double} object. - * - * @return the {@code double} value represented by this object - * converted to type {@code float} - * @since JDK1.0 - */ - public float floatValue() { - return (float)value; - } - - /** - * Returns the {@code double} value of this - * {@code Double} object. - * - * @return the {@code double} value represented by this object - */ - public double doubleValue() { - return (double)value; - } - - /** - * Returns a hash code for this {@code Double} object. The - * result is the exclusive OR of the two halves of the - * {@code long} integer bit representation, exactly as - * produced by the method {@link #doubleToLongBits(double)}, of - * the primitive {@code double} value represented by this - * {@code Double} object. That is, the hash code is the value - * of the expression: - * - *
- * {@code (int)(v^(v>>>32))} - *
- * - * where {@code v} is defined by: - * - *
- * {@code long v = Double.doubleToLongBits(this.doubleValue());} - *
- * - * @return a {@code hash code} value for this object. - */ - public int hashCode() { - long bits = doubleToLongBits(value); - return (int)(bits ^ (bits >>> 32)); - } - - /** - * Compares this object against the specified object. The result - * is {@code true} if and only if the argument is not - * {@code null} and is a {@code Double} object that - * represents a {@code double} that has the same value as the - * {@code double} represented by this object. For this - * purpose, two {@code double} values are considered to be - * the same if and only if the method {@link - * #doubleToLongBits(double)} returns the identical - * {@code long} value when applied to each. - * - *

Note that in most cases, for two instances of class - * {@code Double}, {@code d1} and {@code d2}, the - * value of {@code d1.equals(d2)} is {@code true} if and - * only if - * - *

- * {@code d1.doubleValue() == d2.doubleValue()} - *
- * - *

also has the value {@code true}. However, there are two - * exceptions: - *

    - *
  • If {@code d1} and {@code d2} both represent - * {@code Double.NaN}, then the {@code equals} method - * returns {@code true}, even though - * {@code Double.NaN==Double.NaN} has the value - * {@code false}. - *
  • If {@code d1} represents {@code +0.0} while - * {@code d2} represents {@code -0.0}, or vice versa, - * the {@code equal} test has the value {@code false}, - * even though {@code +0.0==-0.0} has the value {@code true}. - *
- * This definition allows hash tables to operate properly. - * @param obj the object to compare with. - * @return {@code true} if the objects are the same; - * {@code false} otherwise. - * @see java.lang.Double#doubleToLongBits(double) - */ - public boolean equals(Object obj) { - return (obj instanceof Double) - && (((Double)obj).value) == value; - } - - /** - * Returns a representation of the specified floating-point value - * according to the IEEE 754 floating-point "double - * format" bit layout. - * - *

Bit 63 (the bit that is selected by the mask - * {@code 0x8000000000000000L}) represents the sign of the - * floating-point number. Bits - * 62-52 (the bits that are selected by the mask - * {@code 0x7ff0000000000000L}) represent the exponent. Bits 51-0 - * (the bits that are selected by the mask - * {@code 0x000fffffffffffffL}) represent the significand - * (sometimes called the mantissa) of the floating-point number. - * - *

If the argument is positive infinity, the result is - * {@code 0x7ff0000000000000L}. - * - *

If the argument is negative infinity, the result is - * {@code 0xfff0000000000000L}. - * - *

If the argument is NaN, the result is - * {@code 0x7ff8000000000000L}. - * - *

In all cases, the result is a {@code long} integer that, when - * given to the {@link #longBitsToDouble(long)} method, will produce a - * floating-point value the same as the argument to - * {@code doubleToLongBits} (except all NaN values are - * collapsed to a single "canonical" NaN value). - * - * @param value a {@code double} precision floating-point number. - * @return the bits that represent the floating-point number. - */ - public static long doubleToLongBits(double value) { - throw new UnsupportedOperationException(); -// long result = doubleToRawLongBits(value); -// // Check for NaN based on values of bit fields, maximum -// // exponent and nonzero significand. -// if ( ((result & DoubleConsts.EXP_BIT_MASK) == -// DoubleConsts.EXP_BIT_MASK) && -// (result & DoubleConsts.SIGNIF_BIT_MASK) != 0L) -// result = 0x7ff8000000000000L; -// return result; - } - - /** - * Returns a representation of the specified floating-point value - * according to the IEEE 754 floating-point "double - * format" bit layout, preserving Not-a-Number (NaN) values. - * - *

Bit 63 (the bit that is selected by the mask - * {@code 0x8000000000000000L}) represents the sign of the - * floating-point number. Bits - * 62-52 (the bits that are selected by the mask - * {@code 0x7ff0000000000000L}) represent the exponent. Bits 51-0 - * (the bits that are selected by the mask - * {@code 0x000fffffffffffffL}) represent the significand - * (sometimes called the mantissa) of the floating-point number. - * - *

If the argument is positive infinity, the result is - * {@code 0x7ff0000000000000L}. - * - *

If the argument is negative infinity, the result is - * {@code 0xfff0000000000000L}. - * - *

If the argument is NaN, the result is the {@code long} - * integer representing the actual NaN value. Unlike the - * {@code doubleToLongBits} method, - * {@code doubleToRawLongBits} does not collapse all the bit - * patterns encoding a NaN to a single "canonical" NaN - * value. - * - *

In all cases, the result is a {@code long} integer that, - * when given to the {@link #longBitsToDouble(long)} method, will - * produce a floating-point value the same as the argument to - * {@code doubleToRawLongBits}. - * - * @param value a {@code double} precision floating-point number. - * @return the bits that represent the floating-point number. - * @since 1.3 - */ - public static native long doubleToRawLongBits(double value); - - /** - * Returns the {@code double} value corresponding to a given - * bit representation. - * The argument is considered to be a representation of a - * floating-point value according to the IEEE 754 floating-point - * "double format" bit layout. - * - *

If the argument is {@code 0x7ff0000000000000L}, the result - * is positive infinity. - * - *

If the argument is {@code 0xfff0000000000000L}, the result - * is negative infinity. - * - *

If the argument is any value in the range - * {@code 0x7ff0000000000001L} through - * {@code 0x7fffffffffffffffL} or in the range - * {@code 0xfff0000000000001L} through - * {@code 0xffffffffffffffffL}, the result is a NaN. No IEEE - * 754 floating-point operation provided by Java can distinguish - * between two NaN values of the same type with different bit - * patterns. Distinct values of NaN are only distinguishable by - * use of the {@code Double.doubleToRawLongBits} method. - * - *

In all other cases, let s, e, and m be three - * values that can be computed from the argument: - * - *

-     * int s = ((bits >> 63) == 0) ? 1 : -1;
-     * int e = (int)((bits >> 52) & 0x7ffL);
-     * long m = (e == 0) ?
-     *                 (bits & 0xfffffffffffffL) << 1 :
-     *                 (bits & 0xfffffffffffffL) | 0x10000000000000L;
-     * 
- * - * Then the floating-point result equals the value of the mathematical - * expression s·m·2e-1075. - * - *

Note that this method may not be able to return a - * {@code double} NaN with exactly same bit pattern as the - * {@code long} argument. IEEE 754 distinguishes between two - * kinds of NaNs, quiet NaNs and signaling NaNs. The - * differences between the two kinds of NaN are generally not - * visible in Java. Arithmetic operations on signaling NaNs turn - * them into quiet NaNs with a different, but often similar, bit - * pattern. However, on some processors merely copying a - * signaling NaN also performs that conversion. In particular, - * copying a signaling NaN to return it to the calling method - * may perform this conversion. So {@code longBitsToDouble} - * may not be able to return a {@code double} with a - * signaling NaN bit pattern. Consequently, for some - * {@code long} values, - * {@code doubleToRawLongBits(longBitsToDouble(start))} may - * not equal {@code start}. Moreover, which - * particular bit patterns represent signaling NaNs is platform - * dependent; although all NaN bit patterns, quiet or signaling, - * must be in the NaN range identified above. - * - * @param bits any {@code long} integer. - * @return the {@code double} floating-point value with the same - * bit pattern. - */ - public static native double longBitsToDouble(long bits); - - /** - * Compares two {@code Double} objects numerically. There - * are two ways in which comparisons performed by this method - * differ from those performed by the Java language numerical - * comparison operators ({@code <, <=, ==, >=, >}) - * when applied to primitive {@code double} values: - *

  • - * {@code Double.NaN} is considered by this method - * to be equal to itself and greater than all other - * {@code double} values (including - * {@code Double.POSITIVE_INFINITY}). - *
  • - * {@code 0.0d} is considered by this method to be greater - * than {@code -0.0d}. - *
- * This ensures that the natural ordering of - * {@code Double} objects imposed by this method is consistent - * with equals. - * - * @param anotherDouble the {@code Double} to be compared. - * @return the value {@code 0} if {@code anotherDouble} is - * numerically equal to this {@code Double}; a value - * less than {@code 0} if this {@code Double} - * is numerically less than {@code anotherDouble}; - * and a value greater than {@code 0} if this - * {@code Double} is numerically greater than - * {@code anotherDouble}. - * - * @since 1.2 - */ - public int compareTo(Double anotherDouble) { - return Double.compare(value, anotherDouble.value); - } - - /** - * Compares the two specified {@code double} values. The sign - * of the integer value returned is the same as that of the - * integer that would be returned by the call: - *
-     *    new Double(d1).compareTo(new Double(d2))
-     * 
- * - * @param d1 the first {@code double} to compare - * @param d2 the second {@code double} to compare - * @return the value {@code 0} if {@code d1} is - * numerically equal to {@code d2}; a value less than - * {@code 0} if {@code d1} is numerically less than - * {@code d2}; and a value greater than {@code 0} - * if {@code d1} is numerically greater than - * {@code d2}. - * @since 1.4 - */ - public static int compare(double d1, double d2) { - if (d1 < d2) - return -1; // Neither val is NaN, thisVal is smaller - if (d1 > d2) - return 1; // Neither val is NaN, thisVal is larger - - // Cannot use doubleToRawLongBits because of possibility of NaNs. - long thisBits = Double.doubleToLongBits(d1); - long anotherBits = Double.doubleToLongBits(d2); - - return (thisBits == anotherBits ? 0 : // Values are equal - (thisBits < anotherBits ? -1 : // (-0.0, 0.0) or (!NaN, NaN) - 1)); // (0.0, -0.0) or (NaN, !NaN) - } - - /** use serialVersionUID from JDK 1.0.2 for interoperability */ - private static final long serialVersionUID = -9172774392245257468L; -} diff -r 388e48c0a37a -r 05224402145d emul/src/main/java/java/lang/Enum.java --- a/emul/src/main/java/java/lang/Enum.java Wed Jan 23 20:16:48 2013 +0100 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,254 +0,0 @@ -/* - * Copyright (c) 2003, 2009, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code 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 - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package java.lang; - -import java.io.Serializable; -import java.io.IOException; - -/** - * This is the common base class of all Java language enumeration types. - * - * More information about enums, including descriptions of the - * implicitly declared methods synthesized by the compiler, can be - * found in section 8.9 of - * The Java™ Language Specification. - * - *

Note that when using an enumeration type as the type of a set - * or as the type of the keys in a map, specialized and efficient - * {@linkplain java.util.EnumSet set} and {@linkplain - * java.util.EnumMap map} implementations are available. - * - * @param The enum type subclass - * @author Josh Bloch - * @author Neal Gafter - * @see Class#getEnumConstants() - * @see java.util.EnumSet - * @see java.util.EnumMap - * @since 1.5 - */ -public abstract class Enum> - implements Comparable, Serializable { - /** - * The name of this enum constant, as declared in the enum declaration. - * Most programmers should use the {@link #toString} method rather than - * accessing this field. - */ - private final String name; - - /** - * Returns the name of this enum constant, exactly as declared in its - * enum declaration. - * - * Most programmers should use the {@link #toString} method in - * preference to this one, as the toString method may return - * a more user-friendly name. This method is designed primarily for - * use in specialized situations where correctness depends on getting the - * exact name, which will not vary from release to release. - * - * @return the name of this enum constant - */ - public final String name() { - return name; - } - - /** - * The ordinal of this enumeration constant (its position - * in the enum declaration, where the initial constant is assigned - * an ordinal of zero). - * - * Most programmers will have no use for this field. It is designed - * for use by sophisticated enum-based data structures, such as - * {@link java.util.EnumSet} and {@link java.util.EnumMap}. - */ - private final int ordinal; - - /** - * Returns the ordinal of this enumeration constant (its position - * in its enum declaration, where the initial constant is assigned - * an ordinal of zero). - * - * Most programmers will have no use for this method. It is - * designed for use by sophisticated enum-based data structures, such - * as {@link java.util.EnumSet} and {@link java.util.EnumMap}. - * - * @return the ordinal of this enumeration constant - */ - public final int ordinal() { - return ordinal; - } - - /** - * Sole constructor. Programmers cannot invoke this constructor. - * It is for use by code emitted by the compiler in response to - * enum type declarations. - * - * @param name - The name of this enum constant, which is the identifier - * used to declare it. - * @param ordinal - The ordinal of this enumeration constant (its position - * in the enum declaration, where the initial constant is assigned - * an ordinal of zero). - */ - protected Enum(String name, int ordinal) { - this.name = name; - this.ordinal = ordinal; - } - - /** - * Returns the name of this enum constant, as contained in the - * declaration. This method may be overridden, though it typically - * isn't necessary or desirable. An enum type should override this - * method when a more "programmer-friendly" string form exists. - * - * @return the name of this enum constant - */ - public String toString() { - return name; - } - - /** - * Returns true if the specified object is equal to this - * enum constant. - * - * @param other the object to be compared for equality with this object. - * @return true if the specified object is equal to this - * enum constant. - */ - public final boolean equals(Object other) { - return this==other; - } - - /** - * Returns a hash code for this enum constant. - * - * @return a hash code for this enum constant. - */ - public final int hashCode() { - return super.hashCode(); - } - - /** - * Throws CloneNotSupportedException. This guarantees that enums - * are never cloned, which is necessary to preserve their "singleton" - * status. - * - * @return (never returns) - */ - protected final Object clone() throws CloneNotSupportedException { - throw new CloneNotSupportedException(); - } - - /** - * Compares this enum with the specified object for order. Returns a - * negative integer, zero, or a positive integer as this object is less - * than, equal to, or greater than the specified object. - * - * Enum constants are only comparable to other enum constants of the - * same enum type. The natural order implemented by this - * method is the order in which the constants are declared. - */ - public final int compareTo(E o) { - Enum other = (Enum)o; - Enum self = this; - if (self.getClass() != other.getClass() && // optimization - self.getDeclaringClass() != other.getDeclaringClass()) - throw new ClassCastException(); - return self.ordinal - other.ordinal; - } - - /** - * Returns the Class object corresponding to this enum constant's - * enum type. Two enum constants e1 and e2 are of the - * same enum type if and only if - * e1.getDeclaringClass() == e2.getDeclaringClass(). - * (The value returned by this method may differ from the one returned - * by the {@link Object#getClass} method for enum constants with - * constant-specific class bodies.) - * - * @return the Class object corresponding to this enum constant's - * enum type - */ - public final Class getDeclaringClass() { - Class clazz = getClass(); - Class zuper = clazz.getSuperclass(); - return (zuper == Enum.class) ? clazz : zuper; - } - - /** - * Returns the enum constant of the specified enum type with the - * specified name. The name must match exactly an identifier used - * to declare an enum constant in this type. (Extraneous whitespace - * characters are not permitted.) - * - *

Note that for a particular enum type {@code T}, the - * implicitly declared {@code public static T valueOf(String)} - * method on that enum may be used instead of this method to map - * from a name to the corresponding enum constant. All the - * constants of an enum type can be obtained by calling the - * implicit {@code public static T[] values()} method of that - * type. - * - * @param The enum type whose constant is to be returned - * @param enumType the {@code Class} object of the enum type from which - * to return a constant - * @param name the name of the constant to return - * @return the enum constant of the specified enum type with the - * specified name - * @throws IllegalArgumentException if the specified enum type has - * no constant with the specified name, or the specified - * class object does not represent an enum type - * @throws NullPointerException if {@code enumType} or {@code name} - * is null - * @since 1.5 - */ - public static > T valueOf(Class enumType, - String name) { - throw new UnsupportedOperationException(); -// T result = enumType.enumConstantDirectory().get(name); -// if (result != null) -// return result; -// if (name == null) -// throw new NullPointerException("Name is null"); -// throw new IllegalArgumentException( -// "No enum constant " + enumType.getCanonicalName() + "." + name); - } - - /** - * enum classes cannot have finalize methods. - */ - protected final void finalize() { } - - /** - * prevent default deserialization - */ -// private void readObject(ObjectInputStream in) throws IOException, -// ClassNotFoundException { -// throw new InvalidObjectException("can't deserialize enum"); -// } -// -// private void readObjectNoData() throws ObjectStreamException { -// throw new InvalidObjectException("can't deserialize enum"); -// } -} diff -r 388e48c0a37a -r 05224402145d emul/src/main/java/java/lang/Error.java --- a/emul/src/main/java/java/lang/Error.java Wed Jan 23 20:16:48 2013 +0100 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,128 +0,0 @@ -/* - * Copyright (c) 1995, 2011, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code 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 - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package java.lang; - -/** - * An {@code Error} is a subclass of {@code Throwable} - * that indicates serious problems that a reasonable application - * should not try to catch. Most such errors are abnormal conditions. - * The {@code ThreadDeath} error, though a "normal" condition, - * is also a subclass of {@code Error} because most applications - * should not try to catch it. - *

- * A method is not required to declare in its {@code throws} - * clause any subclasses of {@code Error} that might be thrown - * during the execution of the method but not caught, since these - * errors are abnormal conditions that should never occur. - * - * That is, {@code Error} and its subclasses are regarded as unchecked - * exceptions for the purposes of compile-time checking of exceptions. - * - * @author Frank Yellin - * @see java.lang.ThreadDeath - * @jls 11.2 Compile-Time Checking of Exceptions - * @since JDK1.0 - */ -public class Error extends Throwable { - static final long serialVersionUID = 4980196508277280342L; - - /** - * Constructs a new error with {@code null} as its detail message. - * The cause is not initialized, and may subsequently be initialized by a - * call to {@link #initCause}. - */ - public Error() { - super(); - } - - /** - * Constructs a new error with the specified detail message. The - * cause is not initialized, and may subsequently be initialized by - * a call to {@link #initCause}. - * - * @param message the detail message. The detail message is saved for - * later retrieval by the {@link #getMessage()} method. - */ - public Error(String message) { - super(message); - } - - /** - * Constructs a new error with the specified detail message and - * cause.

Note that the detail message associated with - * {@code cause} is not automatically incorporated in - * this error's detail message. - * - * @param message the detail message (which is saved for later retrieval - * by the {@link #getMessage()} method). - * @param cause the cause (which is saved for later retrieval by the - * {@link #getCause()} method). (A {@code null} value is - * permitted, and indicates that the cause is nonexistent or - * unknown.) - * @since 1.4 - */ - public Error(String message, Throwable cause) { - super(message, cause); - } - - /** - * Constructs a new error with the specified cause and a detail - * message of {@code (cause==null ? null : cause.toString())} (which - * typically contains the class and detail message of {@code cause}). - * This constructor is useful for errors that are little more than - * wrappers for other throwables. - * - * @param cause the cause (which is saved for later retrieval by the - * {@link #getCause()} method). (A {@code null} value is - * permitted, and indicates that the cause is nonexistent or - * unknown.) - * @since 1.4 - */ - public Error(Throwable cause) { - super(cause); - } - - /** - * Constructs a new error with the specified detail message, - * cause, suppression enabled or disabled, and writable stack - * trace enabled or disabled. - * - * @param message the detail message. - * @param cause the cause. (A {@code null} value is permitted, - * and indicates that the cause is nonexistent or unknown.) - * @param enableSuppression whether or not suppression is enabled - * or disabled - * @param writableStackTrace whether or not the stack trace should - * be writable - * - * @since 1.7 - */ - protected Error(String message, Throwable cause, - boolean enableSuppression, - boolean writableStackTrace) { - super(message, cause, enableSuppression, writableStackTrace); - } -} diff -r 388e48c0a37a -r 05224402145d emul/src/main/java/java/lang/Exception.java --- a/emul/src/main/java/java/lang/Exception.java Wed Jan 23 20:16:48 2013 +0100 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,124 +0,0 @@ -/* - * Copyright (c) 1994, 2011, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code 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 - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package java.lang; - -/** - * The class {@code Exception} and its subclasses are a form of - * {@code Throwable} that indicates conditions that a reasonable - * application might want to catch. - * - *

The class {@code Exception} and any subclasses that are not also - * subclasses of {@link RuntimeException} are checked - * exceptions. Checked exceptions need to be declared in a - * method or constructor's {@code throws} clause if they can be thrown - * by the execution of the method or constructor and propagate outside - * the method or constructor boundary. - * - * @author Frank Yellin - * @see java.lang.Error - * @jls 11.2 Compile-Time Checking of Exceptions - * @since JDK1.0 - */ -public class Exception extends Throwable { - static final long serialVersionUID = -3387516993124229948L; - - /** - * Constructs a new exception with {@code null} as its detail message. - * The cause is not initialized, and may subsequently be initialized by a - * call to {@link #initCause}. - */ - public Exception() { - super(); - } - - /** - * Constructs a new exception with the specified detail message. The - * cause is not initialized, and may subsequently be initialized by - * a call to {@link #initCause}. - * - * @param message the detail message. The detail message is saved for - * later retrieval by the {@link #getMessage()} method. - */ - public Exception(String message) { - super(message); - } - - /** - * Constructs a new exception with the specified detail message and - * cause.

Note that the detail message associated with - * {@code cause} is not automatically incorporated in - * this exception's detail message. - * - * @param message the detail message (which is saved for later retrieval - * by the {@link #getMessage()} method). - * @param cause the cause (which is saved for later retrieval by the - * {@link #getCause()} method). (A null value is - * permitted, and indicates that the cause is nonexistent or - * unknown.) - * @since 1.4 - */ - public Exception(String message, Throwable cause) { - super(message, cause); - } - - /** - * Constructs a new exception with the specified cause and a detail - * message of (cause==null ? null : cause.toString()) (which - * typically contains the class and detail message of cause). - * This constructor is useful for exceptions that are little more than - * wrappers for other throwables (for example, {@link - * java.security.PrivilegedActionException}). - * - * @param cause the cause (which is saved for later retrieval by the - * {@link #getCause()} method). (A null value is - * permitted, and indicates that the cause is nonexistent or - * unknown.) - * @since 1.4 - */ - public Exception(Throwable cause) { - super(cause); - } - - /** - * Constructs a new exception with the specified detail message, - * cause, suppression enabled or disabled, and writable stack - * trace enabled or disabled. - * - * @param message the detail message. - * @param cause the cause. (A {@code null} value is permitted, - * and indicates that the cause is nonexistent or unknown.) - * @param enableSuppression whether or not suppression is enabled - * or disabled - * @param writableStackTrace whether or not the stack trace should - * be writable - * @since 1.7 - */ - protected Exception(String message, Throwable cause, - boolean enableSuppression, - boolean writableStackTrace) { - super(message, cause, enableSuppression, writableStackTrace); - } -} diff -r 388e48c0a37a -r 05224402145d emul/src/main/java/java/lang/Float.java --- a/emul/src/main/java/java/lang/Float.java Wed Jan 23 20:16:48 2013 +0100 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,905 +0,0 @@ -/* - * Copyright (c) 1994, 2010, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code 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 - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package java.lang; - -import org.apidesign.bck2brwsr.core.JavaScriptBody; - -/** - * The {@code Float} class wraps a value of primitive type - * {@code float} in an object. An object of type - * {@code Float} contains a single field whose type is - * {@code float}. - * - *

In addition, this class provides several methods for converting a - * {@code float} to a {@code String} and a - * {@code String} to a {@code float}, as well as other - * constants and methods useful when dealing with a - * {@code float}. - * - * @author Lee Boynton - * @author Arthur van Hoff - * @author Joseph D. Darcy - * @since JDK1.0 - */ -public final class Float extends Number implements Comparable { - /** - * A constant holding the positive infinity of type - * {@code float}. It is equal to the value returned by - * {@code Float.intBitsToFloat(0x7f800000)}. - */ - public static final float POSITIVE_INFINITY = 1.0f / 0.0f; - - /** - * A constant holding the negative infinity of type - * {@code float}. It is equal to the value returned by - * {@code Float.intBitsToFloat(0xff800000)}. - */ - public static final float NEGATIVE_INFINITY = -1.0f / 0.0f; - - /** - * A constant holding a Not-a-Number (NaN) value of type - * {@code float}. It is equivalent to the value returned by - * {@code Float.intBitsToFloat(0x7fc00000)}. - */ - public static final float NaN = 0.0f / 0.0f; - - /** - * A constant holding the largest positive finite value of type - * {@code float}, (2-2-23)·2127. - * It is equal to the hexadecimal floating-point literal - * {@code 0x1.fffffeP+127f} and also equal to - * {@code Float.intBitsToFloat(0x7f7fffff)}. - */ - public static final float MAX_VALUE = 0x1.fffffeP+127f; // 3.4028235e+38f - - /** - * A constant holding the smallest positive normal value of type - * {@code float}, 2-126. It is equal to the - * hexadecimal floating-point literal {@code 0x1.0p-126f} and also - * equal to {@code Float.intBitsToFloat(0x00800000)}. - * - * @since 1.6 - */ - public static final float MIN_NORMAL = 0x1.0p-126f; // 1.17549435E-38f - - /** - * A constant holding the smallest positive nonzero value of type - * {@code float}, 2-149. It is equal to the - * hexadecimal floating-point literal {@code 0x0.000002P-126f} - * and also equal to {@code Float.intBitsToFloat(0x1)}. - */ - public static final float MIN_VALUE = 0x0.000002P-126f; // 1.4e-45f - - /** - * Maximum exponent a finite {@code float} variable may have. It - * is equal to the value returned by {@code - * Math.getExponent(Float.MAX_VALUE)}. - * - * @since 1.6 - */ - public static final int MAX_EXPONENT = 127; - - /** - * Minimum exponent a normalized {@code float} variable may have. - * It is equal to the value returned by {@code - * Math.getExponent(Float.MIN_NORMAL)}. - * - * @since 1.6 - */ - public static final int MIN_EXPONENT = -126; - - /** - * The number of bits used to represent a {@code float} value. - * - * @since 1.5 - */ - public static final int SIZE = 32; - - /** - * The {@code Class} instance representing the primitive type - * {@code float}. - * - * @since JDK1.1 - */ - public static final Class TYPE = Class.getPrimitiveClass("float"); - - /** - * Returns a string representation of the {@code float} - * argument. All characters mentioned below are ASCII characters. - *

    - *
  • If the argument is NaN, the result is the string - * "{@code NaN}". - *
  • Otherwise, the result is a string that represents the sign and - * magnitude (absolute value) of the argument. If the sign is - * negative, the first character of the result is - * '{@code -}' ('\u002D'); if the sign is - * positive, no sign character appears in the result. As for - * the magnitude m: - *
      - *
    • If m is infinity, it is represented by the characters - * {@code "Infinity"}; thus, positive infinity produces - * the result {@code "Infinity"} and negative infinity - * produces the result {@code "-Infinity"}. - *
    • If m is zero, it is represented by the characters - * {@code "0.0"}; thus, negative zero produces the result - * {@code "-0.0"} and positive zero produces the result - * {@code "0.0"}. - *
    • If m is greater than or equal to 10-3 but - * less than 107, then it is represented as the - * integer part of m, in decimal form with no leading - * zeroes, followed by '{@code .}' - * ('\u002E'), followed by one or more - * decimal digits representing the fractional part of - * m. - *
    • If m is less than 10-3 or greater than or - * equal to 107, then it is represented in - * so-called "computerized scientific notation." Let n - * be the unique integer such that 10n ≤ - * m {@literal <} 10n+1; then let a - * be the mathematically exact quotient of m and - * 10n so that 1 ≤ a {@literal <} 10. - * The magnitude is then represented as the integer part of - * a, as a single decimal digit, followed by - * '{@code .}' ('\u002E'), followed by - * decimal digits representing the fractional part of - * a, followed by the letter '{@code E}' - * ('\u0045'), followed by a representation - * of n as a decimal integer, as produced by the - * method {@link java.lang.Integer#toString(int)}. - * - *
    - *
- * How many digits must be printed for the fractional part of - * m or a? There must be at least one digit - * to represent the fractional part, and beyond that as many, but - * only as many, more digits as are needed to uniquely distinguish - * the argument value from adjacent values of type - * {@code float}. That is, suppose that x is the - * exact mathematical value represented by the decimal - * representation produced by this method for a finite nonzero - * argument f. Then f must be the {@code float} - * value nearest to x; or, if two {@code float} values are - * equally close to x, then f must be one of - * them and the least significant bit of the significand of - * f must be {@code 0}. - * - *

To create localized string representations of a floating-point - * value, use subclasses of {@link java.text.NumberFormat}. - * - * @param f the float to be converted. - * @return a string representation of the argument. - */ - public static String toString(float f) { - return Double.toString(f); - } - - /** - * Returns a hexadecimal string representation of the - * {@code float} argument. All characters mentioned below are - * ASCII characters. - * - *

    - *
  • If the argument is NaN, the result is the string - * "{@code NaN}". - *
  • Otherwise, the result is a string that represents the sign and - * magnitude (absolute value) of the argument. If the sign is negative, - * the first character of the result is '{@code -}' - * ('\u002D'); if the sign is positive, no sign character - * appears in the result. As for the magnitude m: - * - *
      - *
    • If m is infinity, it is represented by the string - * {@code "Infinity"}; thus, positive infinity produces the - * result {@code "Infinity"} and negative infinity produces - * the result {@code "-Infinity"}. - * - *
    • If m is zero, it is represented by the string - * {@code "0x0.0p0"}; thus, negative zero produces the result - * {@code "-0x0.0p0"} and positive zero produces the result - * {@code "0x0.0p0"}. - * - *
    • If m is a {@code float} value with a - * normalized representation, substrings are used to represent the - * significand and exponent fields. The significand is - * represented by the characters {@code "0x1."} - * followed by a lowercase hexadecimal representation of the rest - * of the significand as a fraction. Trailing zeros in the - * hexadecimal representation are removed unless all the digits - * are zero, in which case a single zero is used. Next, the - * exponent is represented by {@code "p"} followed - * by a decimal string of the unbiased exponent as if produced by - * a call to {@link Integer#toString(int) Integer.toString} on the - * exponent value. - * - *
    • If m is a {@code float} value with a subnormal - * representation, the significand is represented by the - * characters {@code "0x0."} followed by a - * hexadecimal representation of the rest of the significand as a - * fraction. Trailing zeros in the hexadecimal representation are - * removed. Next, the exponent is represented by - * {@code "p-126"}. Note that there must be at - * least one nonzero digit in a subnormal significand. - * - *
    - * - *
- * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - *

Examples

Floating-point ValueHexadecimal String
{@code 1.0} {@code 0x1.0p0}
{@code -1.0} {@code -0x1.0p0}
{@code 2.0} {@code 0x1.0p1}
{@code 3.0} {@code 0x1.8p1}
{@code 0.5} {@code 0x1.0p-1}
{@code 0.25} {@code 0x1.0p-2}
{@code Float.MAX_VALUE}{@code 0x1.fffffep127}
{@code Minimum Normal Value}{@code 0x1.0p-126}
{@code Maximum Subnormal Value}{@code 0x0.fffffep-126}
{@code Float.MIN_VALUE}{@code 0x0.000002p-126}
- * @param f the {@code float} to be converted. - * @return a hex string representation of the argument. - * @since 1.5 - * @author Joseph D. Darcy - */ - public static String toHexString(float f) { - throw new UnsupportedOperationException(); -// if (Math.abs(f) < FloatConsts.MIN_NORMAL -// && f != 0.0f ) {// float subnormal -// // Adjust exponent to create subnormal double, then -// // replace subnormal double exponent with subnormal float -// // exponent -// String s = Double.toHexString(FpUtils.scalb((double)f, -// /* -1022+126 */ -// DoubleConsts.MIN_EXPONENT- -// FloatConsts.MIN_EXPONENT)); -// return s.replaceFirst("p-1022$", "p-126"); -// } -// else // double string will be the same as float string -// return Double.toHexString(f); - } - - /** - * Returns a {@code Float} object holding the - * {@code float} value represented by the argument string - * {@code s}. - * - *

If {@code s} is {@code null}, then a - * {@code NullPointerException} is thrown. - * - *

Leading and trailing whitespace characters in {@code s} - * are ignored. Whitespace is removed as if by the {@link - * String#trim} method; that is, both ASCII space and control - * characters are removed. The rest of {@code s} should - * constitute a FloatValue as described by the lexical - * syntax rules: - * - *

- *
- *
FloatValue: - *
Signopt {@code NaN} - *
Signopt {@code Infinity} - *
Signopt FloatingPointLiteral - *
Signopt HexFloatingPointLiteral - *
SignedInteger - *
- * - *

- * - *

- *
HexFloatingPointLiteral: - *
HexSignificand BinaryExponent FloatTypeSuffixopt - *
- * - *

- * - *

- *
HexSignificand: - *
HexNumeral - *
HexNumeral {@code .} - *
{@code 0x} HexDigitsopt - * {@code .} HexDigits - *
{@code 0X} HexDigitsopt - * {@code .} HexDigits - *
- * - *

- * - *

- *
BinaryExponent: - *
BinaryExponentIndicator SignedInteger - *
- * - *

- * - *

- *
BinaryExponentIndicator: - *
{@code p} - *
{@code P} - *
- * - *
- * - * where Sign, FloatingPointLiteral, - * HexNumeral, HexDigits, SignedInteger and - * FloatTypeSuffix are as defined in the lexical structure - * sections of - * The Java™ Language Specification, - * except that underscores are not accepted between digits. - * If {@code s} does not have the form of - * a FloatValue, then a {@code NumberFormatException} - * is thrown. Otherwise, {@code s} is regarded as - * representing an exact decimal value in the usual - * "computerized scientific notation" or as an exact - * hexadecimal value; this exact numerical value is then - * conceptually converted to an "infinitely precise" - * binary value that is then rounded to type {@code float} - * by the usual round-to-nearest rule of IEEE 754 floating-point - * arithmetic, which includes preserving the sign of a zero - * value. - * - * Note that the round-to-nearest rule also implies overflow and - * underflow behaviour; if the exact value of {@code s} is large - * enough in magnitude (greater than or equal to ({@link - * #MAX_VALUE} + {@link Math#ulp(float) ulp(MAX_VALUE)}/2), - * rounding to {@code float} will result in an infinity and if the - * exact value of {@code s} is small enough in magnitude (less - * than or equal to {@link #MIN_VALUE}/2), rounding to float will - * result in a zero. - * - * Finally, after rounding a {@code Float} object representing - * this {@code float} value is returned. - * - *

To interpret localized string representations of a - * floating-point value, use subclasses of {@link - * java.text.NumberFormat}. - * - *

Note that trailing format specifiers, specifiers that - * determine the type of a floating-point literal - * ({@code 1.0f} is a {@code float} value; - * {@code 1.0d} is a {@code double} value), do - * not influence the results of this method. In other - * words, the numerical value of the input string is converted - * directly to the target floating-point type. In general, the - * two-step sequence of conversions, string to {@code double} - * followed by {@code double} to {@code float}, is - * not equivalent to converting a string directly to - * {@code float}. For example, if first converted to an - * intermediate {@code double} and then to - * {@code float}, the string
- * {@code "1.00000017881393421514957253748434595763683319091796875001d"}
- * results in the {@code float} value - * {@code 1.0000002f}; if the string is converted directly to - * {@code float}, 1.0000001f results. - * - *

To avoid calling this method on an invalid string and having - * a {@code NumberFormatException} be thrown, the documentation - * for {@link Double#valueOf Double.valueOf} lists a regular - * expression which can be used to screen the input. - * - * @param s the string to be parsed. - * @return a {@code Float} object holding the value - * represented by the {@code String} argument. - * @throws NumberFormatException if the string does not contain a - * parsable number. - */ - public static Float valueOf(String s) throws NumberFormatException { - throw new UnsupportedOperationException(); -// return new Float(FloatingDecimal.readJavaFormatString(s).floatValue()); - } - - /** - * Returns a {@code Float} instance representing the specified - * {@code float} value. - * If a new {@code Float} instance is not required, this method - * should generally be used in preference to the constructor - * {@link #Float(float)}, as this method is likely to yield - * significantly better space and time performance by caching - * frequently requested values. - * - * @param f a float value. - * @return a {@code Float} instance representing {@code f}. - * @since 1.5 - */ - public static Float valueOf(float f) { - return new Float(f); - } - - /** - * Returns a new {@code float} initialized to the value - * represented by the specified {@code String}, as performed - * by the {@code valueOf} method of class {@code Float}. - * - * @param s the string to be parsed. - * @return the {@code float} value represented by the string - * argument. - * @throws NullPointerException if the string is null - * @throws NumberFormatException if the string does not contain a - * parsable {@code float}. - * @see java.lang.Float#valueOf(String) - * @since 1.2 - */ - public static float parseFloat(String s) throws NumberFormatException { - throw new UnsupportedOperationException(); -// return FloatingDecimal.readJavaFormatString(s).floatValue(); - } - - /** - * Returns {@code true} if the specified number is a - * Not-a-Number (NaN) value, {@code false} otherwise. - * - * @param v the value to be tested. - * @return {@code true} if the argument is NaN; - * {@code false} otherwise. - */ - static public boolean isNaN(float v) { - return (v != v); - } - - /** - * Returns {@code true} if the specified number is infinitely - * large in magnitude, {@code false} otherwise. - * - * @param v the value to be tested. - * @return {@code true} if the argument is positive infinity or - * negative infinity; {@code false} otherwise. - */ - static public boolean isInfinite(float v) { - return (v == POSITIVE_INFINITY) || (v == NEGATIVE_INFINITY); - } - - /** - * The value of the Float. - * - * @serial - */ - private final float value; - - /** - * Constructs a newly allocated {@code Float} object that - * represents the primitive {@code float} argument. - * - * @param value the value to be represented by the {@code Float}. - */ - public Float(float value) { - this.value = value; - } - - /** - * Constructs a newly allocated {@code Float} object that - * represents the argument converted to type {@code float}. - * - * @param value the value to be represented by the {@code Float}. - */ - public Float(double value) { - this.value = (float)value; - } - - /** - * Constructs a newly allocated {@code Float} object that - * represents the floating-point value of type {@code float} - * represented by the string. The string is converted to a - * {@code float} value as if by the {@code valueOf} method. - * - * @param s a string to be converted to a {@code Float}. - * @throws NumberFormatException if the string does not contain a - * parsable number. - * @see java.lang.Float#valueOf(java.lang.String) - */ - public Float(String s) throws NumberFormatException { - // REMIND: this is inefficient - this(valueOf(s).floatValue()); - } - - /** - * Returns {@code true} if this {@code Float} value is a - * Not-a-Number (NaN), {@code false} otherwise. - * - * @return {@code true} if the value represented by this object is - * NaN; {@code false} otherwise. - */ - public boolean isNaN() { - return isNaN(value); - } - - /** - * Returns {@code true} if this {@code Float} value is - * infinitely large in magnitude, {@code false} otherwise. - * - * @return {@code true} if the value represented by this object is - * positive infinity or negative infinity; - * {@code false} otherwise. - */ - public boolean isInfinite() { - return isInfinite(value); - } - - /** - * Returns a string representation of this {@code Float} object. - * The primitive {@code float} value represented by this object - * is converted to a {@code String} exactly as if by the method - * {@code toString} of one argument. - * - * @return a {@code String} representation of this object. - * @see java.lang.Float#toString(float) - */ - public String toString() { - return Float.toString(value); - } - - /** - * Returns the value of this {@code Float} as a {@code byte} (by - * casting to a {@code byte}). - * - * @return the {@code float} value represented by this object - * converted to type {@code byte} - */ - public byte byteValue() { - return (byte)value; - } - - /** - * Returns the value of this {@code Float} as a {@code short} (by - * casting to a {@code short}). - * - * @return the {@code float} value represented by this object - * converted to type {@code short} - * @since JDK1.1 - */ - public short shortValue() { - return (short)value; - } - - /** - * Returns the value of this {@code Float} as an {@code int} (by - * casting to type {@code int}). - * - * @return the {@code float} value represented by this object - * converted to type {@code int} - */ - public int intValue() { - return (int)value; - } - - /** - * Returns value of this {@code Float} as a {@code long} (by - * casting to type {@code long}). - * - * @return the {@code float} value represented by this object - * converted to type {@code long} - */ - public long longValue() { - return (long)value; - } - - /** - * Returns the {@code float} value of this {@code Float} object. - * - * @return the {@code float} value represented by this object - */ - public float floatValue() { - return value; - } - - /** - * Returns the {@code double} value of this {@code Float} object. - * - * @return the {@code float} value represented by this - * object is converted to type {@code double} and the - * result of the conversion is returned. - */ - public double doubleValue() { - return (double)value; - } - - /** - * Returns a hash code for this {@code Float} object. The - * result is the integer bit representation, exactly as produced - * by the method {@link #floatToIntBits(float)}, of the primitive - * {@code float} value represented by this {@code Float} - * object. - * - * @return a hash code value for this object. - */ - public int hashCode() { - return floatToIntBits(value); - } - - /** - - * Compares this object against the specified object. The result - * is {@code true} if and only if the argument is not - * {@code null} and is a {@code Float} object that - * represents a {@code float} with the same value as the - * {@code float} represented by this object. For this - * purpose, two {@code float} values are considered to be the - * same if and only if the method {@link #floatToIntBits(float)} - * returns the identical {@code int} value when applied to - * each. - * - *

Note that in most cases, for two instances of class - * {@code Float}, {@code f1} and {@code f2}, the value - * of {@code f1.equals(f2)} is {@code true} if and only if - * - *

-     *   f1.floatValue() == f2.floatValue()
-     * 
- * - *

also has the value {@code true}. However, there are two exceptions: - *

    - *
  • If {@code f1} and {@code f2} both represent - * {@code Float.NaN}, then the {@code equals} method returns - * {@code true}, even though {@code Float.NaN==Float.NaN} - * has the value {@code false}. - *
  • If {@code f1} represents {@code +0.0f} while - * {@code f2} represents {@code -0.0f}, or vice - * versa, the {@code equal} test has the value - * {@code false}, even though {@code 0.0f==-0.0f} - * has the value {@code true}. - *
- * - * This definition allows hash tables to operate properly. - * - * @param obj the object to be compared - * @return {@code true} if the objects are the same; - * {@code false} otherwise. - * @see java.lang.Float#floatToIntBits(float) - */ - public boolean equals(Object obj) { - return (obj instanceof Float) - && (floatToIntBits(((Float)obj).value) == floatToIntBits(value)); - } - - /** - * Returns a representation of the specified floating-point value - * according to the IEEE 754 floating-point "single format" bit - * layout. - * - *

Bit 31 (the bit that is selected by the mask - * {@code 0x80000000}) represents the sign of the floating-point - * number. - * Bits 30-23 (the bits that are selected by the mask - * {@code 0x7f800000}) represent the exponent. - * Bits 22-0 (the bits that are selected by the mask - * {@code 0x007fffff}) represent the significand (sometimes called - * the mantissa) of the floating-point number. - * - *

If the argument is positive infinity, the result is - * {@code 0x7f800000}. - * - *

If the argument is negative infinity, the result is - * {@code 0xff800000}. - * - *

If the argument is NaN, the result is {@code 0x7fc00000}. - * - *

In all cases, the result is an integer that, when given to the - * {@link #intBitsToFloat(int)} method, will produce a floating-point - * value the same as the argument to {@code floatToIntBits} - * (except all NaN values are collapsed to a single - * "canonical" NaN value). - * - * @param value a floating-point number. - * @return the bits that represent the floating-point number. - */ - public static int floatToIntBits(float value) { - throw new UnsupportedOperationException(); -// int result = floatToRawIntBits(value); -// // Check for NaN based on values of bit fields, maximum -// // exponent and nonzero significand. -// if ( ((result & FloatConsts.EXP_BIT_MASK) == -// FloatConsts.EXP_BIT_MASK) && -// (result & FloatConsts.SIGNIF_BIT_MASK) != 0) -// result = 0x7fc00000; -// return result; - } - - /** - * Returns a representation of the specified floating-point value - * according to the IEEE 754 floating-point "single format" bit - * layout, preserving Not-a-Number (NaN) values. - * - *

Bit 31 (the bit that is selected by the mask - * {@code 0x80000000}) represents the sign of the floating-point - * number. - * Bits 30-23 (the bits that are selected by the mask - * {@code 0x7f800000}) represent the exponent. - * Bits 22-0 (the bits that are selected by the mask - * {@code 0x007fffff}) represent the significand (sometimes called - * the mantissa) of the floating-point number. - * - *

If the argument is positive infinity, the result is - * {@code 0x7f800000}. - * - *

If the argument is negative infinity, the result is - * {@code 0xff800000}. - * - *

If the argument is NaN, the result is the integer representing - * the actual NaN value. Unlike the {@code floatToIntBits} - * method, {@code floatToRawIntBits} does not collapse all the - * bit patterns encoding a NaN to a single "canonical" - * NaN value. - * - *

In all cases, the result is an integer that, when given to the - * {@link #intBitsToFloat(int)} method, will produce a - * floating-point value the same as the argument to - * {@code floatToRawIntBits}. - * - * @param value a floating-point number. - * @return the bits that represent the floating-point number. - * @since 1.3 - */ - public static native int floatToRawIntBits(float value); - - /** - * Returns the {@code float} value corresponding to a given - * bit representation. - * The argument is considered to be a representation of a - * floating-point value according to the IEEE 754 floating-point - * "single format" bit layout. - * - *

If the argument is {@code 0x7f800000}, the result is positive - * infinity. - * - *

If the argument is {@code 0xff800000}, the result is negative - * infinity. - * - *

If the argument is any value in the range - * {@code 0x7f800001} through {@code 0x7fffffff} or in - * the range {@code 0xff800001} through - * {@code 0xffffffff}, the result is a NaN. No IEEE 754 - * floating-point operation provided by Java can distinguish - * between two NaN values of the same type with different bit - * patterns. Distinct values of NaN are only distinguishable by - * use of the {@code Float.floatToRawIntBits} method. - * - *

In all other cases, let s, e, and m be three - * values that can be computed from the argument: - * - *

-     * int s = ((bits >> 31) == 0) ? 1 : -1;
-     * int e = ((bits >> 23) & 0xff);
-     * int m = (e == 0) ?
-     *                 (bits & 0x7fffff) << 1 :
-     *                 (bits & 0x7fffff) | 0x800000;
-     * 
- * - * Then the floating-point result equals the value of the mathematical - * expression s·m·2e-150. - * - *

Note that this method may not be able to return a - * {@code float} NaN with exactly same bit pattern as the - * {@code int} argument. IEEE 754 distinguishes between two - * kinds of NaNs, quiet NaNs and signaling NaNs. The - * differences between the two kinds of NaN are generally not - * visible in Java. Arithmetic operations on signaling NaNs turn - * them into quiet NaNs with a different, but often similar, bit - * pattern. However, on some processors merely copying a - * signaling NaN also performs that conversion. In particular, - * copying a signaling NaN to return it to the calling method may - * perform this conversion. So {@code intBitsToFloat} may - * not be able to return a {@code float} with a signaling NaN - * bit pattern. Consequently, for some {@code int} values, - * {@code floatToRawIntBits(intBitsToFloat(start))} may - * not equal {@code start}. Moreover, which - * particular bit patterns represent signaling NaNs is platform - * dependent; although all NaN bit patterns, quiet or signaling, - * must be in the NaN range identified above. - * - * @param bits an integer. - * @return the {@code float} floating-point value with the same bit - * pattern. - */ - @JavaScriptBody(args = "bits", - body = - "if (bits === 0x7f800000) return Number.POSITIVE_INFINITY;\n" - + "if (bits === 0xff800000) return Number.NEGATIVE_INFINITY;\n" - + "if (bits >= 0x7f800001 && bits <= 0xffffffff) return Number.NaN;\n" - + "var s = ((bits >> 31) == 0) ? 1 : -1;\n" - + "var e = ((bits >> 23) & 0xff);\n" - + "var m = (e == 0) ?\n" - + " (bits & 0x7fffff) << 1 :\n" - + " (bits & 0x7fffff) | 0x800000;\n" - + "return s * m * Math.pow(2.0, e - 150);\n" - ) - public static native float intBitsToFloat(int bits); - - /** - * Compares two {@code Float} objects numerically. There are - * two ways in which comparisons performed by this method differ - * from those performed by the Java language numerical comparison - * operators ({@code <, <=, ==, >=, >}) when - * applied to primitive {@code float} values: - * - *

  • - * {@code Float.NaN} is considered by this method to - * be equal to itself and greater than all other - * {@code float} values - * (including {@code Float.POSITIVE_INFINITY}). - *
  • - * {@code 0.0f} is considered by this method to be greater - * than {@code -0.0f}. - *
- * - * This ensures that the natural ordering of {@code Float} - * objects imposed by this method is consistent with equals. - * - * @param anotherFloat the {@code Float} to be compared. - * @return the value {@code 0} if {@code anotherFloat} is - * numerically equal to this {@code Float}; a value - * less than {@code 0} if this {@code Float} - * is numerically less than {@code anotherFloat}; - * and a value greater than {@code 0} if this - * {@code Float} is numerically greater than - * {@code anotherFloat}. - * - * @since 1.2 - * @see Comparable#compareTo(Object) - */ - public int compareTo(Float anotherFloat) { - return Float.compare(value, anotherFloat.value); - } - - /** - * Compares the two specified {@code float} values. The sign - * of the integer value returned is the same as that of the - * integer that would be returned by the call: - *
-     *    new Float(f1).compareTo(new Float(f2))
-     * 
- * - * @param f1 the first {@code float} to compare. - * @param f2 the second {@code float} to compare. - * @return the value {@code 0} if {@code f1} is - * numerically equal to {@code f2}; a value less than - * {@code 0} if {@code f1} is numerically less than - * {@code f2}; and a value greater than {@code 0} - * if {@code f1} is numerically greater than - * {@code f2}. - * @since 1.4 - */ - public static int compare(float f1, float f2) { - if (f1 < f2) - return -1; // Neither val is NaN, thisVal is smaller - if (f1 > f2) - return 1; // Neither val is NaN, thisVal is larger - - // Cannot use floatToRawIntBits because of possibility of NaNs. - int thisBits = Float.floatToIntBits(f1); - int anotherBits = Float.floatToIntBits(f2); - - return (thisBits == anotherBits ? 0 : // Values are equal - (thisBits < anotherBits ? -1 : // (-0.0, 0.0) or (!NaN, NaN) - 1)); // (0.0, -0.0) or (NaN, !NaN) - } - - /** use serialVersionUID from JDK 1.0.2 for interoperability */ - private static final long serialVersionUID = -2671257302660747028L; -} diff -r 388e48c0a37a -r 05224402145d emul/src/main/java/java/lang/IllegalAccessException.java --- a/emul/src/main/java/java/lang/IllegalAccessException.java Wed Jan 23 20:16:48 2013 +0100 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,78 +0,0 @@ -/* - * Copyright (c) 1995, 2008, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code 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 - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package java.lang; - -/** - * An IllegalAccessException is thrown when an application tries - * to reflectively create an instance (other than an array), - * set or get a field, or invoke a method, but the currently - * executing method does not have access to the definition of - * the specified class, field, method or constructor. - * - * @author unascribed - * @see Class#newInstance() - * @see java.lang.reflect.Field#set(Object, Object) - * @see java.lang.reflect.Field#setBoolean(Object, boolean) - * @see java.lang.reflect.Field#setByte(Object, byte) - * @see java.lang.reflect.Field#setShort(Object, short) - * @see java.lang.reflect.Field#setChar(Object, char) - * @see java.lang.reflect.Field#setInt(Object, int) - * @see java.lang.reflect.Field#setLong(Object, long) - * @see java.lang.reflect.Field#setFloat(Object, float) - * @see java.lang.reflect.Field#setDouble(Object, double) - * @see java.lang.reflect.Field#get(Object) - * @see java.lang.reflect.Field#getBoolean(Object) - * @see java.lang.reflect.Field#getByte(Object) - * @see java.lang.reflect.Field#getShort(Object) - * @see java.lang.reflect.Field#getChar(Object) - * @see java.lang.reflect.Field#getInt(Object) - * @see java.lang.reflect.Field#getLong(Object) - * @see java.lang.reflect.Field#getFloat(Object) - * @see java.lang.reflect.Field#getDouble(Object) - * @see java.lang.reflect.Method#invoke(Object, Object[]) - * @see java.lang.reflect.Constructor#newInstance(Object[]) - * @since JDK1.0 - */ -public class IllegalAccessException extends ReflectiveOperationException { - private static final long serialVersionUID = 6616958222490762034L; - - /** - * Constructs an IllegalAccessException without a - * detail message. - */ - public IllegalAccessException() { - super(); - } - - /** - * Constructs an IllegalAccessException with a detail message. - * - * @param s the detail message. - */ - public IllegalAccessException(String s) { - super(s); - } -} diff -r 388e48c0a37a -r 05224402145d emul/src/main/java/java/lang/IllegalArgumentException.java --- a/emul/src/main/java/java/lang/IllegalArgumentException.java Wed Jan 23 20:16:48 2013 +0100 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,95 +0,0 @@ -/* - * Copyright (c) 1994, 2003, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code 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 - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package java.lang; - -/** - * Thrown to indicate that a method has been passed an illegal or - * inappropriate argument. - * - * @author unascribed - * @see java.lang.Thread#setPriority(int) - * @since JDK1.0 - */ -public -class IllegalArgumentException extends RuntimeException { - /** - * Constructs an IllegalArgumentException with no - * detail message. - */ - public IllegalArgumentException() { - super(); - } - - /** - * Constructs an IllegalArgumentException with the - * specified detail message. - * - * @param s the detail message. - */ - public IllegalArgumentException(String s) { - super(s); - } - - /** - * Constructs a new exception with the specified detail message and - * cause. - * - *

Note that the detail message associated with cause is - * not automatically incorporated in this exception's detail - * message. - * - * @param message the detail message (which is saved for later retrieval - * by the {@link Throwable#getMessage()} method). - * @param cause the cause (which is saved for later retrieval by the - * {@link Throwable#getCause()} method). (A null value - * is permitted, and indicates that the cause is nonexistent or - * unknown.) - * @since 1.5 - */ - public IllegalArgumentException(String message, Throwable cause) { - super(message, cause); - } - - /** - * Constructs a new exception with the specified cause and a detail - * message of (cause==null ? null : cause.toString()) (which - * typically contains the class and detail message of cause). - * This constructor is useful for exceptions that are little more than - * wrappers for other throwables (for example, {@link - * java.security.PrivilegedActionException}). - * - * @param cause the cause (which is saved for later retrieval by the - * {@link Throwable#getCause()} method). (A null value is - * permitted, and indicates that the cause is nonexistent or - * unknown.) - * @since 1.5 - */ - public IllegalArgumentException(Throwable cause) { - super(cause); - } - - private static final long serialVersionUID = -5365630128856068164L; -} diff -r 388e48c0a37a -r 05224402145d emul/src/main/java/java/lang/IllegalStateException.java --- a/emul/src/main/java/java/lang/IllegalStateException.java Wed Jan 23 20:16:48 2013 +0100 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,97 +0,0 @@ -/* - * Copyright (c) 1996, 2003, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code 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 - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package java.lang; - -/** - * Signals that a method has been invoked at an illegal or - * inappropriate time. In other words, the Java environment or - * Java application is not in an appropriate state for the requested - * operation. - * - * @author Jonni Kanerva - * @since JDK1.1 - */ -public -class IllegalStateException extends RuntimeException { - /** - * Constructs an IllegalStateException with no detail message. - * A detail message is a String that describes this particular exception. - */ - public IllegalStateException() { - super(); - } - - /** - * Constructs an IllegalStateException with the specified detail - * message. A detail message is a String that describes this particular - * exception. - * - * @param s the String that contains a detailed message - */ - public IllegalStateException(String s) { - super(s); - } - - /** - * Constructs a new exception with the specified detail message and - * cause. - * - *

Note that the detail message associated with cause is - * not automatically incorporated in this exception's detail - * message. - * - * @param message the detail message (which is saved for later retrieval - * by the {@link Throwable#getMessage()} method). - * @param cause the cause (which is saved for later retrieval by the - * {@link Throwable#getCause()} method). (A null value - * is permitted, and indicates that the cause is nonexistent or - * unknown.) - * @since 1.5 - */ - public IllegalStateException(String message, Throwable cause) { - super(message, cause); - } - - /** - * Constructs a new exception with the specified cause and a detail - * message of (cause==null ? null : cause.toString()) (which - * typically contains the class and detail message of cause). - * This constructor is useful for exceptions that are little more than - * wrappers for other throwables (for example, {@link - * java.security.PrivilegedActionException}). - * - * @param cause the cause (which is saved for later retrieval by the - * {@link Throwable#getCause()} method). (A null value is - * permitted, and indicates that the cause is nonexistent or - * unknown.) - * @since 1.5 - */ - public IllegalStateException(Throwable cause) { - super(cause); - } - - static final long serialVersionUID = -1848914673093119416L; -} diff -r 388e48c0a37a -r 05224402145d emul/src/main/java/java/lang/IndexOutOfBoundsException.java --- a/emul/src/main/java/java/lang/IndexOutOfBoundsException.java Wed Jan 23 20:16:48 2013 +0100 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,58 +0,0 @@ -/* - * Copyright (c) 1995, 2008, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code 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 - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package java.lang; - -/** - * Thrown to indicate that an index of some sort (such as to an array, to a - * string, or to a vector) is out of range. - *

- * Applications can subclass this class to indicate similar exceptions. - * - * @author Frank Yellin - * @since JDK1.0 - */ -public -class IndexOutOfBoundsException extends RuntimeException { - private static final long serialVersionUID = 234122996006267687L; - - /** - * Constructs an IndexOutOfBoundsException with no - * detail message. - */ - public IndexOutOfBoundsException() { - super(); - } - - /** - * Constructs an IndexOutOfBoundsException with the - * specified detail message. - * - * @param s the detail message. - */ - public IndexOutOfBoundsException(String s) { - super(s); - } -} diff -r 388e48c0a37a -r 05224402145d emul/src/main/java/java/lang/InstantiationException.java --- a/emul/src/main/java/java/lang/InstantiationException.java Wed Jan 23 20:16:48 2013 +0100 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,65 +0,0 @@ -/* - * Copyright (c) 1995, 2008, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code 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 - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package java.lang; - -/** - * Thrown when an application tries to create an instance of a class - * using the {@code newInstance} method in class - * {@code Class}, but the specified class object cannot be - * instantiated. The instantiation can fail for a variety of - * reasons including but not limited to: - * - *

    - *
  • the class object represents an abstract class, an interface, - * an array class, a primitive type, or {@code void} - *
  • the class has no nullary constructor - *
- * - * @author unascribed - * @see java.lang.Class#newInstance() - * @since JDK1.0 - */ -public -class InstantiationException extends ReflectiveOperationException { - private static final long serialVersionUID = -8441929162975509110L; - - /** - * Constructs an {@code InstantiationException} with no detail message. - */ - public InstantiationException() { - super(); - } - - /** - * Constructs an {@code InstantiationException} with the - * specified detail message. - * - * @param s the detail message. - */ - public InstantiationException(String s) { - super(s); - } -} diff -r 388e48c0a37a -r 05224402145d emul/src/main/java/java/lang/Integer.java --- a/emul/src/main/java/java/lang/Integer.java Wed Jan 23 20:16:48 2013 +0100 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,1246 +0,0 @@ -/* - * Copyright (c) 1994, 2010, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code 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 - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package java.lang; - -import org.apidesign.bck2brwsr.core.JavaScriptBody; - -/** - * The {@code Integer} class wraps a value of the primitive type - * {@code int} in an object. An object of type {@code Integer} - * contains a single field whose type is {@code int}. - * - *

In addition, this class provides several methods for converting - * an {@code int} to a {@code String} and a {@code String} to an - * {@code int}, as well as other constants and methods useful when - * dealing with an {@code int}. - * - *

Implementation note: The implementations of the "bit twiddling" - * methods (such as {@link #highestOneBit(int) highestOneBit} and - * {@link #numberOfTrailingZeros(int) numberOfTrailingZeros}) are - * based on material from Henry S. Warren, Jr.'s Hacker's - * Delight, (Addison Wesley, 2002). - * - * @author Lee Boynton - * @author Arthur van Hoff - * @author Josh Bloch - * @author Joseph D. Darcy - * @since JDK1.0 - */ -public final class Integer extends Number implements Comparable { - /** - * A constant holding the minimum value an {@code int} can - * have, -231. - */ - public static final int MIN_VALUE = 0x80000000; - - /** - * A constant holding the maximum value an {@code int} can - * have, 231-1. - */ - public static final int MAX_VALUE = 0x7fffffff; - - /** - * The {@code Class} instance representing the primitive type - * {@code int}. - * - * @since JDK1.1 - */ - public static final Class TYPE = (Class) Class.getPrimitiveClass("int"); - - /** - * All possible chars for representing a number as a String - */ - final static char[] digits = { - '0' , '1' , '2' , '3' , '4' , '5' , - '6' , '7' , '8' , '9' , 'a' , 'b' , - 'c' , 'd' , 'e' , 'f' , 'g' , 'h' , - 'i' , 'j' , 'k' , 'l' , 'm' , 'n' , - 'o' , 'p' , 'q' , 'r' , 's' , 't' , - 'u' , 'v' , 'w' , 'x' , 'y' , 'z' - }; - - /** - * Returns a string representation of the first argument in the - * radix specified by the second argument. - * - *

If the radix is smaller than {@code Character.MIN_RADIX} - * or larger than {@code Character.MAX_RADIX}, then the radix - * {@code 10} is used instead. - * - *

If the first argument is negative, the first element of the - * result is the ASCII minus character {@code '-'} - * ('\u002D'). If the first argument is not - * negative, no sign character appears in the result. - * - *

The remaining characters of the result represent the magnitude - * of the first argument. If the magnitude is zero, it is - * represented by a single zero character {@code '0'} - * ('\u0030'); otherwise, the first character of - * the representation of the magnitude will not be the zero - * character. The following ASCII characters are used as digits: - * - *

- * {@code 0123456789abcdefghijklmnopqrstuvwxyz} - *
- * - * These are '\u0030' through - * '\u0039' and '\u0061' through - * '\u007A'. If {@code radix} is - * N, then the first N of these characters - * are used as radix-N digits in the order shown. Thus, - * the digits for hexadecimal (radix 16) are - * {@code 0123456789abcdef}. If uppercase letters are - * desired, the {@link java.lang.String#toUpperCase()} method may - * be called on the result: - * - *
- * {@code Integer.toString(n, 16).toUpperCase()} - *
- * - * @param i an integer to be converted to a string. - * @param radix the radix to use in the string representation. - * @return a string representation of the argument in the specified radix. - * @see java.lang.Character#MAX_RADIX - * @see java.lang.Character#MIN_RADIX - */ - public static String toString(int i, int radix) { - - if (radix < Character.MIN_RADIX || radix > Character.MAX_RADIX) - radix = 10; - - /* Use the faster version */ - if (radix == 10) { - return toString(i); - } - - char buf[] = new char[33]; - boolean negative = (i < 0); - int charPos = 32; - - if (!negative) { - i = -i; - } - - while (i <= -radix) { - buf[charPos--] = digits[-(i % radix)]; - i = i / radix; - } - buf[charPos] = digits[-i]; - - if (negative) { - buf[--charPos] = '-'; - } - - return new String(buf, charPos, (33 - charPos)); - } - - /** - * Returns a string representation of the integer argument as an - * unsigned integer in base 16. - * - *

The unsigned integer value is the argument plus 232 - * if the argument is negative; otherwise, it is equal to the - * argument. This value is converted to a string of ASCII digits - * in hexadecimal (base 16) with no extra leading - * {@code 0}s. If the unsigned magnitude is zero, it is - * represented by a single zero character {@code '0'} - * ('\u0030'); otherwise, the first character of - * the representation of the unsigned magnitude will not be the - * zero character. The following characters are used as - * hexadecimal digits: - * - *

- * {@code 0123456789abcdef} - *
- * - * These are the characters '\u0030' through - * '\u0039' and '\u0061' through - * '\u0066'. If uppercase letters are - * desired, the {@link java.lang.String#toUpperCase()} method may - * be called on the result: - * - *
- * {@code Integer.toHexString(n).toUpperCase()} - *
- * - * @param i an integer to be converted to a string. - * @return the string representation of the unsigned integer value - * represented by the argument in hexadecimal (base 16). - * @since JDK1.0.2 - */ - public static String toHexString(int i) { - return toUnsignedString(i, 4); - } - - /** - * Returns a string representation of the integer argument as an - * unsigned integer in base 8. - * - *

The unsigned integer value is the argument plus 232 - * if the argument is negative; otherwise, it is equal to the - * argument. This value is converted to a string of ASCII digits - * in octal (base 8) with no extra leading {@code 0}s. - * - *

If the unsigned magnitude is zero, it is represented by a - * single zero character {@code '0'} - * ('\u0030'); otherwise, the first character of - * the representation of the unsigned magnitude will not be the - * zero character. The following characters are used as octal - * digits: - * - *

- * {@code 01234567} - *
- * - * These are the characters '\u0030' through - * '\u0037'. - * - * @param i an integer to be converted to a string. - * @return the string representation of the unsigned integer value - * represented by the argument in octal (base 8). - * @since JDK1.0.2 - */ - public static String toOctalString(int i) { - return toUnsignedString(i, 3); - } - - /** - * Returns a string representation of the integer argument as an - * unsigned integer in base 2. - * - *

The unsigned integer value is the argument plus 232 - * if the argument is negative; otherwise it is equal to the - * argument. This value is converted to a string of ASCII digits - * in binary (base 2) with no extra leading {@code 0}s. - * If the unsigned magnitude is zero, it is represented by a - * single zero character {@code '0'} - * ('\u0030'); otherwise, the first character of - * the representation of the unsigned magnitude will not be the - * zero character. The characters {@code '0'} - * ('\u0030') and {@code '1'} - * ('\u0031') are used as binary digits. - * - * @param i an integer to be converted to a string. - * @return the string representation of the unsigned integer value - * represented by the argument in binary (base 2). - * @since JDK1.0.2 - */ - public static String toBinaryString(int i) { - return toUnsignedString(i, 1); - } - - /** - * Convert the integer to an unsigned number. - */ - private static String toUnsignedString(int i, int shift) { - char[] buf = new char[32]; - int charPos = 32; - int radix = 1 << shift; - int mask = radix - 1; - do { - buf[--charPos] = digits[i & mask]; - i >>>= shift; - } while (i != 0); - - return new String(buf, charPos, (32 - charPos)); - } - - - final static char [] DigitTens = { - '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', - '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', - '2', '2', '2', '2', '2', '2', '2', '2', '2', '2', - '3', '3', '3', '3', '3', '3', '3', '3', '3', '3', - '4', '4', '4', '4', '4', '4', '4', '4', '4', '4', - '5', '5', '5', '5', '5', '5', '5', '5', '5', '5', - '6', '6', '6', '6', '6', '6', '6', '6', '6', '6', - '7', '7', '7', '7', '7', '7', '7', '7', '7', '7', - '8', '8', '8', '8', '8', '8', '8', '8', '8', '8', - '9', '9', '9', '9', '9', '9', '9', '9', '9', '9', - } ; - - final static char [] DigitOnes = { - '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', - '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', - '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', - '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', - '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', - '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', - '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', - '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', - '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', - '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', - } ; - - // I use the "invariant division by multiplication" trick to - // accelerate Integer.toString. In particular we want to - // avoid division by 10. - // - // The "trick" has roughly the same performance characteristics - // as the "classic" Integer.toString code on a non-JIT VM. - // The trick avoids .rem and .div calls but has a longer code - // path and is thus dominated by dispatch overhead. In the - // JIT case the dispatch overhead doesn't exist and the - // "trick" is considerably faster than the classic code. - // - // TODO-FIXME: convert (x * 52429) into the equiv shift-add - // sequence. - // - // RE: Division by Invariant Integers using Multiplication - // T Gralund, P Montgomery - // ACM PLDI 1994 - // - - /** - * Returns a {@code String} object representing the - * specified integer. The argument is converted to signed decimal - * representation and returned as a string, exactly as if the - * argument and radix 10 were given as arguments to the {@link - * #toString(int, int)} method. - * - * @param i an integer to be converted. - * @return a string representation of the argument in base 10. - */ - @JavaScriptBody(args = "i", body = "return i.toString();") - public static String toString(int i) { - if (i == Integer.MIN_VALUE) - return "-2147483648"; - int size = (i < 0) ? stringSize(-i) + 1 : stringSize(i); - char[] buf = new char[size]; - getChars(i, size, buf); - return new String(buf, 0, size); - } - - /** - * Places characters representing the integer i into the - * character array buf. The characters are placed into - * the buffer backwards starting with the least significant - * digit at the specified index (exclusive), and working - * backwards from there. - * - * Will fail if i == Integer.MIN_VALUE - */ - static void getChars(int i, int index, char[] buf) { - int q, r; - int charPos = index; - char sign = 0; - - if (i < 0) { - sign = '-'; - i = -i; - } - - // Generate two digits per iteration - while (i >= 65536) { - q = i / 100; - // really: r = i - (q * 100); - r = i - ((q << 6) + (q << 5) + (q << 2)); - i = q; - buf [--charPos] = DigitOnes[r]; - buf [--charPos] = DigitTens[r]; - } - - // Fall thru to fast mode for smaller numbers - // assert(i <= 65536, i); - for (;;) { - q = (i * 52429) >>> (16+3); - r = i - ((q << 3) + (q << 1)); // r = i-(q*10) ... - buf [--charPos] = digits [r]; - i = q; - if (i == 0) break; - } - if (sign != 0) { - buf [--charPos] = sign; - } - } - - final static int [] sizeTable = { 9, 99, 999, 9999, 99999, 999999, 9999999, - 99999999, 999999999, Integer.MAX_VALUE }; - - // Requires positive x - static int stringSize(int x) { - for (int i=0; ; i++) - if (x <= sizeTable[i]) - return i+1; - } - - /** - * Parses the string argument as a signed integer in the radix - * specified by the second argument. The characters in the string - * must all be digits of the specified radix (as determined by - * whether {@link java.lang.Character#digit(char, int)} returns a - * nonnegative value), except that the first character may be an - * ASCII minus sign {@code '-'} ('\u002D') to - * indicate a negative value or an ASCII plus sign {@code '+'} - * ('\u002B') to indicate a positive value. The - * resulting integer value is returned. - * - *

An exception of type {@code NumberFormatException} is - * thrown if any of the following situations occurs: - *

    - *
  • The first argument is {@code null} or is a string of - * length zero. - * - *
  • The radix is either smaller than - * {@link java.lang.Character#MIN_RADIX} or - * larger than {@link java.lang.Character#MAX_RADIX}. - * - *
  • Any character of the string is not a digit of the specified - * radix, except that the first character may be a minus sign - * {@code '-'} ('\u002D') or plus sign - * {@code '+'} ('\u002B') provided that the - * string is longer than length 1. - * - *
  • The value represented by the string is not a value of type - * {@code int}. - *
- * - *

Examples: - *

-     * parseInt("0", 10) returns 0
-     * parseInt("473", 10) returns 473
-     * parseInt("+42", 10) returns 42
-     * parseInt("-0", 10) returns 0
-     * parseInt("-FF", 16) returns -255
-     * parseInt("1100110", 2) returns 102
-     * parseInt("2147483647", 10) returns 2147483647
-     * parseInt("-2147483648", 10) returns -2147483648
-     * parseInt("2147483648", 10) throws a NumberFormatException
-     * parseInt("99", 8) throws a NumberFormatException
-     * parseInt("Kona", 10) throws a NumberFormatException
-     * parseInt("Kona", 27) returns 411787
-     * 
- * - * @param s the {@code String} containing the integer - * representation to be parsed - * @param radix the radix to be used while parsing {@code s}. - * @return the integer represented by the string argument in the - * specified radix. - * @exception NumberFormatException if the {@code String} - * does not contain a parsable {@code int}. - */ - @JavaScriptBody(args={"s", "radix"}, body="return parseInt(s,radix);") - public static int parseInt(String s, int radix) - throws NumberFormatException - { - /* - * WARNING: This method may be invoked early during VM initialization - * before IntegerCache is initialized. Care must be taken to not use - * the valueOf method. - */ - - if (s == null) { - throw new NumberFormatException("null"); - } - - if (radix < Character.MIN_RADIX) { - throw new NumberFormatException("radix " + radix + - " less than Character.MIN_RADIX"); - } - - if (radix > Character.MAX_RADIX) { - throw new NumberFormatException("radix " + radix + - " greater than Character.MAX_RADIX"); - } - - int result = 0; - boolean negative = false; - int i = 0, len = s.length(); - int limit = -Integer.MAX_VALUE; - int multmin; - int digit; - - if (len > 0) { - char firstChar = s.charAt(0); - if (firstChar < '0') { // Possible leading "+" or "-" - if (firstChar == '-') { - negative = true; - limit = Integer.MIN_VALUE; - } else if (firstChar != '+') - throw NumberFormatException.forInputString(s); - - if (len == 1) // Cannot have lone "+" or "-" - throw NumberFormatException.forInputString(s); - i++; - } - multmin = limit / radix; - while (i < len) { - // Accumulating negatively avoids surprises near MAX_VALUE - digit = Character.digit(s.charAt(i++),radix); - if (digit < 0) { - throw NumberFormatException.forInputString(s); - } - if (result < multmin) { - throw NumberFormatException.forInputString(s); - } - result *= radix; - if (result < limit + digit) { - throw NumberFormatException.forInputString(s); - } - result -= digit; - } - } else { - throw NumberFormatException.forInputString(s); - } - return negative ? result : -result; - } - - /** - * Parses the string argument as a signed decimal integer. The - * characters in the string must all be decimal digits, except - * that the first character may be an ASCII minus sign {@code '-'} - * ('\u002D') to indicate a negative value or an - * ASCII plus sign {@code '+'} ('\u002B') to - * indicate a positive value. The resulting integer value is - * returned, exactly as if the argument and the radix 10 were - * given as arguments to the {@link #parseInt(java.lang.String, - * int)} method. - * - * @param s a {@code String} containing the {@code int} - * representation to be parsed - * @return the integer value represented by the argument in decimal. - * @exception NumberFormatException if the string does not contain a - * parsable integer. - */ - public static int parseInt(String s) throws NumberFormatException { - return parseInt(s,10); - } - - /** - * Returns an {@code Integer} object holding the value - * extracted from the specified {@code String} when parsed - * with the radix given by the second argument. The first argument - * is interpreted as representing a signed integer in the radix - * specified by the second argument, exactly as if the arguments - * were given to the {@link #parseInt(java.lang.String, int)} - * method. The result is an {@code Integer} object that - * represents the integer value specified by the string. - * - *

In other words, this method returns an {@code Integer} - * object equal to the value of: - * - *

- * {@code new Integer(Integer.parseInt(s, radix))} - *
- * - * @param s the string to be parsed. - * @param radix the radix to be used in interpreting {@code s} - * @return an {@code Integer} object holding the value - * represented by the string argument in the specified - * radix. - * @exception NumberFormatException if the {@code String} - * does not contain a parsable {@code int}. - */ - public static Integer valueOf(String s, int radix) throws NumberFormatException { - return Integer.valueOf(parseInt(s,radix)); - } - - /** - * Returns an {@code Integer} object holding the - * value of the specified {@code String}. The argument is - * interpreted as representing a signed decimal integer, exactly - * as if the argument were given to the {@link - * #parseInt(java.lang.String)} method. The result is an - * {@code Integer} object that represents the integer value - * specified by the string. - * - *

In other words, this method returns an {@code Integer} - * object equal to the value of: - * - *

- * {@code new Integer(Integer.parseInt(s))} - *
- * - * @param s the string to be parsed. - * @return an {@code Integer} object holding the value - * represented by the string argument. - * @exception NumberFormatException if the string cannot be parsed - * as an integer. - */ - public static Integer valueOf(String s) throws NumberFormatException { - return Integer.valueOf(parseInt(s, 10)); - } - - /** - * Cache to support the object identity semantics of autoboxing for values between - * -128 and 127 (inclusive) as required by JLS. - * - * The cache is initialized on first usage. The size of the cache - * may be controlled by the -XX:AutoBoxCacheMax= option. - * During VM initialization, java.lang.Integer.IntegerCache.high property - * may be set and saved in the private system properties in the - * sun.misc.VM class. - */ - - private static class IntegerCache { - static final int low = -128; - static final int high; - static final Integer cache[]; - - static { - // high value may be configured by property - int h = 127; - String integerCacheHighPropValue = - AbstractStringBuilder.getProperty("java.lang.Integer.IntegerCache.high"); - if (integerCacheHighPropValue != null) { - int i = parseInt(integerCacheHighPropValue); - i = Math.max(i, 127); - // Maximum array size is Integer.MAX_VALUE - h = Math.min(i, Integer.MAX_VALUE - (-low)); - } - high = h; - - cache = new Integer[(high - low) + 1]; - int j = low; - for(int k = 0; k < cache.length; k++) - cache[k] = new Integer(j++); - } - - private IntegerCache() {} - } - - /** - * Returns an {@code Integer} instance representing the specified - * {@code int} value. If a new {@code Integer} instance is not - * required, this method should generally be used in preference to - * the constructor {@link #Integer(int)}, as this method is likely - * to yield significantly better space and time performance by - * caching frequently requested values. - * - * This method will always cache values in the range -128 to 127, - * inclusive, and may cache other values outside of this range. - * - * @param i an {@code int} value. - * @return an {@code Integer} instance representing {@code i}. - * @since 1.5 - */ - public static Integer valueOf(int i) { - //assert IntegerCache.high >= 127; - if (i >= IntegerCache.low && i <= IntegerCache.high) - return IntegerCache.cache[i + (-IntegerCache.low)]; - return new Integer(i); - } - - /** - * The value of the {@code Integer}. - * - * @serial - */ - private final int value; - - /** - * Constructs a newly allocated {@code Integer} object that - * represents the specified {@code int} value. - * - * @param value the value to be represented by the - * {@code Integer} object. - */ - public Integer(int value) { - this.value = value; - } - - /** - * Constructs a newly allocated {@code Integer} object that - * represents the {@code int} value indicated by the - * {@code String} parameter. The string is converted to an - * {@code int} value in exactly the manner used by the - * {@code parseInt} method for radix 10. - * - * @param s the {@code String} to be converted to an - * {@code Integer}. - * @exception NumberFormatException if the {@code String} does not - * contain a parsable integer. - * @see java.lang.Integer#parseInt(java.lang.String, int) - */ - public Integer(String s) throws NumberFormatException { - this.value = parseInt(s, 10); - } - - /** - * Returns the value of this {@code Integer} as a - * {@code byte}. - */ - public byte byteValue() { - return (byte)value; - } - - /** - * Returns the value of this {@code Integer} as a - * {@code short}. - */ - public short shortValue() { - return (short)value; - } - - /** - * Returns the value of this {@code Integer} as an - * {@code int}. - */ - public int intValue() { - return value; - } - - /** - * Returns the value of this {@code Integer} as a - * {@code long}. - */ - public long longValue() { - return (long)value; - } - - /** - * Returns the value of this {@code Integer} as a - * {@code float}. - */ - public float floatValue() { - return (float)value; - } - - /** - * Returns the value of this {@code Integer} as a - * {@code double}. - */ - public double doubleValue() { - return (double)value; - } - - /** - * Returns a {@code String} object representing this - * {@code Integer}'s value. The value is converted to signed - * decimal representation and returned as a string, exactly as if - * the integer value were given as an argument to the {@link - * java.lang.Integer#toString(int)} method. - * - * @return a string representation of the value of this object in - * base 10. - */ - public String toString() { - return toString(value); - } - - /** - * Returns a hash code for this {@code Integer}. - * - * @return a hash code value for this object, equal to the - * primitive {@code int} value represented by this - * {@code Integer} object. - */ - public int hashCode() { - return value; - } - - /** - * Compares this object to the specified object. The result is - * {@code true} if and only if the argument is not - * {@code null} and is an {@code Integer} object that - * contains the same {@code int} value as this object. - * - * @param obj the object to compare with. - * @return {@code true} if the objects are the same; - * {@code false} otherwise. - */ - public boolean equals(Object obj) { - if (obj instanceof Integer) { - return value == ((Integer)obj).intValue(); - } - return false; - } - - /** - * Determines the integer value of the system property with the - * specified name. - * - *

The first argument is treated as the name of a system property. - * System properties are accessible through the - * {@link java.lang.System#getProperty(java.lang.String)} method. The - * string value of this property is then interpreted as an integer - * value and an {@code Integer} object representing this value is - * returned. Details of possible numeric formats can be found with - * the definition of {@code getProperty}. - * - *

If there is no property with the specified name, if the specified name - * is empty or {@code null}, or if the property does not have - * the correct numeric format, then {@code null} is returned. - * - *

In other words, this method returns an {@code Integer} - * object equal to the value of: - * - *

- * {@code getInteger(nm, null)} - *
- * - * @param nm property name. - * @return the {@code Integer} value of the property. - * @see java.lang.System#getProperty(java.lang.String) - * @see java.lang.System#getProperty(java.lang.String, java.lang.String) - */ - public static Integer getInteger(String nm) { - return getInteger(nm, null); - } - - /** - * Determines the integer value of the system property with the - * specified name. - * - *

The first argument is treated as the name of a system property. - * System properties are accessible through the {@link - * java.lang.System#getProperty(java.lang.String)} method. The - * string value of this property is then interpreted as an integer - * value and an {@code Integer} object representing this value is - * returned. Details of possible numeric formats can be found with - * the definition of {@code getProperty}. - * - *

The second argument is the default value. An {@code Integer} object - * that represents the value of the second argument is returned if there - * is no property of the specified name, if the property does not have - * the correct numeric format, or if the specified name is empty or - * {@code null}. - * - *

In other words, this method returns an {@code Integer} object - * equal to the value of: - * - *

- * {@code getInteger(nm, new Integer(val))} - *
- * - * but in practice it may be implemented in a manner such as: - * - *
-     * Integer result = getInteger(nm, null);
-     * return (result == null) ? new Integer(val) : result;
-     * 
- * - * to avoid the unnecessary allocation of an {@code Integer} - * object when the default value is not needed. - * - * @param nm property name. - * @param val default value. - * @return the {@code Integer} value of the property. - * @see java.lang.System#getProperty(java.lang.String) - * @see java.lang.System#getProperty(java.lang.String, java.lang.String) - */ - public static Integer getInteger(String nm, int val) { - Integer result = getInteger(nm, null); - return (result == null) ? Integer.valueOf(val) : result; - } - - /** - * Returns the integer value of the system property with the - * specified name. The first argument is treated as the name of a - * system property. System properties are accessible through the - * {@link java.lang.System#getProperty(java.lang.String)} method. - * The string value of this property is then interpreted as an - * integer value, as per the {@code Integer.decode} method, - * and an {@code Integer} object representing this value is - * returned. - * - *
  • If the property value begins with the two ASCII characters - * {@code 0x} or the ASCII character {@code #}, not - * followed by a minus sign, then the rest of it is parsed as a - * hexadecimal integer exactly as by the method - * {@link #valueOf(java.lang.String, int)} with radix 16. - *
  • If the property value begins with the ASCII character - * {@code 0} followed by another character, it is parsed as an - * octal integer exactly as by the method - * {@link #valueOf(java.lang.String, int)} with radix 8. - *
  • Otherwise, the property value is parsed as a decimal integer - * exactly as by the method {@link #valueOf(java.lang.String, int)} - * with radix 10. - *
- * - *

The second argument is the default value. The default value is - * returned if there is no property of the specified name, if the - * property does not have the correct numeric format, or if the - * specified name is empty or {@code null}. - * - * @param nm property name. - * @param val default value. - * @return the {@code Integer} value of the property. - * @see java.lang.System#getProperty(java.lang.String) - * @see java.lang.System#getProperty(java.lang.String, java.lang.String) - * @see java.lang.Integer#decode - */ - public static Integer getInteger(String nm, Integer val) { - String v = null; - try { - v = AbstractStringBuilder.getProperty(nm); - } catch (IllegalArgumentException e) { - } catch (NullPointerException e) { - } - if (v != null) { - try { - return Integer.decode(v); - } catch (NumberFormatException e) { - } - } - return val; - } - - /** - * Decodes a {@code String} into an {@code Integer}. - * Accepts decimal, hexadecimal, and octal numbers given - * by the following grammar: - * - *

- *
- *
DecodableString: - *
Signopt DecimalNumeral - *
Signopt {@code 0x} HexDigits - *
Signopt {@code 0X} HexDigits - *
Signopt {@code #} HexDigits - *
Signopt {@code 0} OctalDigits - *

- *

Sign: - *
{@code -} - *
{@code +} - *
- *
- * - * DecimalNumeral, HexDigits, and OctalDigits - * are as defined in section 3.10.1 of - * The Java™ Language Specification, - * except that underscores are not accepted between digits. - * - *

The sequence of characters following an optional - * sign and/or radix specifier ("{@code 0x}", "{@code 0X}", - * "{@code #}", or leading zero) is parsed as by the {@code - * Integer.parseInt} method with the indicated radix (10, 16, or - * 8). This sequence of characters must represent a positive - * value or a {@link NumberFormatException} will be thrown. The - * result is negated if first character of the specified {@code - * String} is the minus sign. No whitespace characters are - * permitted in the {@code String}. - * - * @param nm the {@code String} to decode. - * @return an {@code Integer} object holding the {@code int} - * value represented by {@code nm} - * @exception NumberFormatException if the {@code String} does not - * contain a parsable integer. - * @see java.lang.Integer#parseInt(java.lang.String, int) - */ - public static Integer decode(String nm) throws NumberFormatException { - int radix = 10; - int index = 0; - boolean negative = false; - Integer result; - - if (nm.length() == 0) - throw new NumberFormatException("Zero length string"); - char firstChar = nm.charAt(0); - // Handle sign, if present - if (firstChar == '-') { - negative = true; - index++; - } else if (firstChar == '+') - index++; - - // Handle radix specifier, if present - if (nm.startsWith("0x", index) || nm.startsWith("0X", index)) { - index += 2; - radix = 16; - } - else if (nm.startsWith("#", index)) { - index ++; - radix = 16; - } - else if (nm.startsWith("0", index) && nm.length() > 1 + index) { - index ++; - radix = 8; - } - - if (nm.startsWith("-", index) || nm.startsWith("+", index)) - throw new NumberFormatException("Sign character in wrong position"); - - try { - result = Integer.valueOf(nm.substring(index), radix); - result = negative ? Integer.valueOf(-result.intValue()) : result; - } catch (NumberFormatException e) { - // If number is Integer.MIN_VALUE, we'll end up here. The next line - // handles this case, and causes any genuine format error to be - // rethrown. - String constant = negative ? ("-" + nm.substring(index)) - : nm.substring(index); - result = Integer.valueOf(constant, radix); - } - return result; - } - - /** - * Compares two {@code Integer} objects numerically. - * - * @param anotherInteger the {@code Integer} to be compared. - * @return the value {@code 0} if this {@code Integer} is - * equal to the argument {@code Integer}; a value less than - * {@code 0} if this {@code Integer} is numerically less - * than the argument {@code Integer}; and a value greater - * than {@code 0} if this {@code Integer} is numerically - * greater than the argument {@code Integer} (signed - * comparison). - * @since 1.2 - */ - public int compareTo(Integer anotherInteger) { - return compare(this.value, anotherInteger.value); - } - - /** - * Compares two {@code int} values numerically. - * The value returned is identical to what would be returned by: - *

-     *    Integer.valueOf(x).compareTo(Integer.valueOf(y))
-     * 
- * - * @param x the first {@code int} to compare - * @param y the second {@code int} to compare - * @return the value {@code 0} if {@code x == y}; - * a value less than {@code 0} if {@code x < y}; and - * a value greater than {@code 0} if {@code x > y} - * @since 1.7 - */ - public static int compare(int x, int y) { - return (x < y) ? -1 : ((x == y) ? 0 : 1); - } - - - // Bit twiddling - - /** - * The number of bits used to represent an {@code int} value in two's - * complement binary form. - * - * @since 1.5 - */ - public static final int SIZE = 32; - - /** - * Returns an {@code int} value with at most a single one-bit, in the - * position of the highest-order ("leftmost") one-bit in the specified - * {@code int} value. Returns zero if the specified value has no - * one-bits in its two's complement binary representation, that is, if it - * is equal to zero. - * - * @return an {@code int} value with a single one-bit, in the position - * of the highest-order one-bit in the specified value, or zero if - * the specified value is itself equal to zero. - * @since 1.5 - */ - public static int highestOneBit(int i) { - // HD, Figure 3-1 - i |= (i >> 1); - i |= (i >> 2); - i |= (i >> 4); - i |= (i >> 8); - i |= (i >> 16); - return i - (i >>> 1); - } - - /** - * Returns an {@code int} value with at most a single one-bit, in the - * position of the lowest-order ("rightmost") one-bit in the specified - * {@code int} value. Returns zero if the specified value has no - * one-bits in its two's complement binary representation, that is, if it - * is equal to zero. - * - * @return an {@code int} value with a single one-bit, in the position - * of the lowest-order one-bit in the specified value, or zero if - * the specified value is itself equal to zero. - * @since 1.5 - */ - public static int lowestOneBit(int i) { - // HD, Section 2-1 - return i & -i; - } - - /** - * Returns the number of zero bits preceding the highest-order - * ("leftmost") one-bit in the two's complement binary representation - * of the specified {@code int} value. Returns 32 if the - * specified value has no one-bits in its two's complement representation, - * in other words if it is equal to zero. - * - *

Note that this method is closely related to the logarithm base 2. - * For all positive {@code int} values x: - *

    - *
  • floor(log2(x)) = {@code 31 - numberOfLeadingZeros(x)} - *
  • ceil(log2(x)) = {@code 32 - numberOfLeadingZeros(x - 1)} - *
- * - * @return the number of zero bits preceding the highest-order - * ("leftmost") one-bit in the two's complement binary representation - * of the specified {@code int} value, or 32 if the value - * is equal to zero. - * @since 1.5 - */ - public static int numberOfLeadingZeros(int i) { - // HD, Figure 5-6 - if (i == 0) - return 32; - int n = 1; - if (i >>> 16 == 0) { n += 16; i <<= 16; } - if (i >>> 24 == 0) { n += 8; i <<= 8; } - if (i >>> 28 == 0) { n += 4; i <<= 4; } - if (i >>> 30 == 0) { n += 2; i <<= 2; } - n -= i >>> 31; - return n; - } - - /** - * Returns the number of zero bits following the lowest-order ("rightmost") - * one-bit in the two's complement binary representation of the specified - * {@code int} value. Returns 32 if the specified value has no - * one-bits in its two's complement representation, in other words if it is - * equal to zero. - * - * @return the number of zero bits following the lowest-order ("rightmost") - * one-bit in the two's complement binary representation of the - * specified {@code int} value, or 32 if the value is equal - * to zero. - * @since 1.5 - */ - public static int numberOfTrailingZeros(int i) { - // HD, Figure 5-14 - int y; - if (i == 0) return 32; - int n = 31; - y = i <<16; if (y != 0) { n = n -16; i = y; } - y = i << 8; if (y != 0) { n = n - 8; i = y; } - y = i << 4; if (y != 0) { n = n - 4; i = y; } - y = i << 2; if (y != 0) { n = n - 2; i = y; } - return n - ((i << 1) >>> 31); - } - - /** - * Returns the number of one-bits in the two's complement binary - * representation of the specified {@code int} value. This function is - * sometimes referred to as the population count. - * - * @return the number of one-bits in the two's complement binary - * representation of the specified {@code int} value. - * @since 1.5 - */ - public static int bitCount(int i) { - // HD, Figure 5-2 - i = i - ((i >>> 1) & 0x55555555); - i = (i & 0x33333333) + ((i >>> 2) & 0x33333333); - i = (i + (i >>> 4)) & 0x0f0f0f0f; - i = i + (i >>> 8); - i = i + (i >>> 16); - return i & 0x3f; - } - - /** - * Returns the value obtained by rotating the two's complement binary - * representation of the specified {@code int} value left by the - * specified number of bits. (Bits shifted out of the left hand, or - * high-order, side reenter on the right, or low-order.) - * - *

Note that left rotation with a negative distance is equivalent to - * right rotation: {@code rotateLeft(val, -distance) == rotateRight(val, - * distance)}. Note also that rotation by any multiple of 32 is a - * no-op, so all but the last five bits of the rotation distance can be - * ignored, even if the distance is negative: {@code rotateLeft(val, - * distance) == rotateLeft(val, distance & 0x1F)}. - * - * @return the value obtained by rotating the two's complement binary - * representation of the specified {@code int} value left by the - * specified number of bits. - * @since 1.5 - */ - public static int rotateLeft(int i, int distance) { - return (i << distance) | (i >>> -distance); - } - - /** - * Returns the value obtained by rotating the two's complement binary - * representation of the specified {@code int} value right by the - * specified number of bits. (Bits shifted out of the right hand, or - * low-order, side reenter on the left, or high-order.) - * - *

Note that right rotation with a negative distance is equivalent to - * left rotation: {@code rotateRight(val, -distance) == rotateLeft(val, - * distance)}. Note also that rotation by any multiple of 32 is a - * no-op, so all but the last five bits of the rotation distance can be - * ignored, even if the distance is negative: {@code rotateRight(val, - * distance) == rotateRight(val, distance & 0x1F)}. - * - * @return the value obtained by rotating the two's complement binary - * representation of the specified {@code int} value right by the - * specified number of bits. - * @since 1.5 - */ - public static int rotateRight(int i, int distance) { - return (i >>> distance) | (i << -distance); - } - - /** - * Returns the value obtained by reversing the order of the bits in the - * two's complement binary representation of the specified {@code int} - * value. - * - * @return the value obtained by reversing order of the bits in the - * specified {@code int} value. - * @since 1.5 - */ - public static int reverse(int i) { - // HD, Figure 7-1 - i = (i & 0x55555555) << 1 | (i >>> 1) & 0x55555555; - i = (i & 0x33333333) << 2 | (i >>> 2) & 0x33333333; - i = (i & 0x0f0f0f0f) << 4 | (i >>> 4) & 0x0f0f0f0f; - i = (i << 24) | ((i & 0xff00) << 8) | - ((i >>> 8) & 0xff00) | (i >>> 24); - return i; - } - - /** - * Returns the signum function of the specified {@code int} value. (The - * return value is -1 if the specified value is negative; 0 if the - * specified value is zero; and 1 if the specified value is positive.) - * - * @return the signum function of the specified {@code int} value. - * @since 1.5 - */ - public static int signum(int i) { - // HD, Section 2-7 - return (i >> 31) | (-i >>> 31); - } - - /** - * Returns the value obtained by reversing the order of the bytes in the - * two's complement representation of the specified {@code int} value. - * - * @return the value obtained by reversing the bytes in the specified - * {@code int} value. - * @since 1.5 - */ - public static int reverseBytes(int i) { - return ((i >>> 24) ) | - ((i >> 8) & 0xFF00) | - ((i << 8) & 0xFF0000) | - ((i << 24)); - } - - /** use serialVersionUID from JDK 1.0.2 for interoperability */ - private static final long serialVersionUID = 1360826667806852920L; -} diff -r 388e48c0a37a -r 05224402145d emul/src/main/java/java/lang/InterruptedException.java --- a/emul/src/main/java/java/lang/InterruptedException.java Wed Jan 23 20:16:48 2013 +0100 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,69 +0,0 @@ -/* - * Copyright (c) 1995, 2008, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code 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 - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package java.lang; - -/** - * Thrown when a thread is waiting, sleeping, or otherwise occupied, - * and the thread is interrupted, either before or during the activity. - * Occasionally a method may wish to test whether the current - * thread has been interrupted, and if so, to immediately throw - * this exception. The following code can be used to achieve - * this effect: - *

- *  if (Thread.interrupted())  // Clears interrupted status!
- *      throw new InterruptedException();
- * 
- * - * @author Frank Yellin - * @see java.lang.Object#wait() - * @see java.lang.Object#wait(long) - * @see java.lang.Object#wait(long, int) - * @see java.lang.Thread#sleep(long) - * @see java.lang.Thread#interrupt() - * @see java.lang.Thread#interrupted() - * @since JDK1.0 - */ -public -class InterruptedException extends Exception { - private static final long serialVersionUID = 6700697376100628473L; - - /** - * Constructs an InterruptedException with no detail message. - */ - public InterruptedException() { - super(); - } - - /** - * Constructs an InterruptedException with the - * specified detail message. - * - * @param s the detail message. - */ - public InterruptedException(String s) { - super(s); - } -} diff -r 388e48c0a37a -r 05224402145d emul/src/main/java/java/lang/LinkageError.java --- a/emul/src/main/java/java/lang/LinkageError.java Wed Jan 23 20:16:48 2013 +0100 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,69 +0,0 @@ -/* - * Copyright (c) 1995, 2010, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code 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 - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package java.lang; - -/** - * Subclasses of {@code LinkageError} indicate that a class has - * some dependency on another class; however, the latter class has - * incompatibly changed after the compilation of the former class. - * - * - * @author Frank Yellin - * @since JDK1.0 - */ -public -class LinkageError extends Error { - private static final long serialVersionUID = 3579600108157160122L; - - /** - * Constructs a {@code LinkageError} with no detail message. - */ - public LinkageError() { - super(); - } - - /** - * Constructs a {@code LinkageError} with the specified detail - * message. - * - * @param s the detail message. - */ - public LinkageError(String s) { - super(s); - } - - /** - * Constructs a {@code LinkageError} with the specified detail - * message and cause. - * - * @param s the detail message. - * @param cause the cause, may be {@code null} - * @since 1.7 - */ - public LinkageError(String s, Throwable cause) { - super(s, cause); - } -} diff -r 388e48c0a37a -r 05224402145d emul/src/main/java/java/lang/Long.java --- a/emul/src/main/java/java/lang/Long.java Wed Jan 23 20:16:48 2013 +0100 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,1202 +0,0 @@ -/* - * Copyright (c) 1994, 2009, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code 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 - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package java.lang; - -import org.apidesign.bck2brwsr.core.JavaScriptBody; - -/** - * The {@code Long} class wraps a value of the primitive type {@code - * long} in an object. An object of type {@code Long} contains a - * single field whose type is {@code long}. - * - *

In addition, this class provides several methods for converting - * a {@code long} to a {@code String} and a {@code String} to a {@code - * long}, as well as other constants and methods useful when dealing - * with a {@code long}. - * - *

Implementation note: The implementations of the "bit twiddling" - * methods (such as {@link #highestOneBit(long) highestOneBit} and - * {@link #numberOfTrailingZeros(long) numberOfTrailingZeros}) are - * based on material from Henry S. Warren, Jr.'s Hacker's - * Delight, (Addison Wesley, 2002). - * - * @author Lee Boynton - * @author Arthur van Hoff - * @author Josh Bloch - * @author Joseph D. Darcy - * @since JDK1.0 - */ -public final class Long extends Number implements Comparable { - /** - * A constant holding the minimum value a {@code long} can - * have, -263. - */ - public static final long MIN_VALUE = 0x8000000000000000L; - - /** - * A constant holding the maximum value a {@code long} can - * have, 263-1. - */ - public static final long MAX_VALUE = 0x7fffffffffffffffL; - - /** - * The {@code Class} instance representing the primitive type - * {@code long}. - * - * @since JDK1.1 - */ - public static final Class TYPE = (Class) Class.getPrimitiveClass("long"); - - /** - * Returns a string representation of the first argument in the - * radix specified by the second argument. - * - *

If the radix is smaller than {@code Character.MIN_RADIX} - * or larger than {@code Character.MAX_RADIX}, then the radix - * {@code 10} is used instead. - * - *

If the first argument is negative, the first element of the - * result is the ASCII minus sign {@code '-'} - * ('\u002d'). If the first argument is not - * negative, no sign character appears in the result. - * - *

The remaining characters of the result represent the magnitude - * of the first argument. If the magnitude is zero, it is - * represented by a single zero character {@code '0'} - * ('\u0030'); otherwise, the first character of - * the representation of the magnitude will not be the zero - * character. The following ASCII characters are used as digits: - * - *

- * {@code 0123456789abcdefghijklmnopqrstuvwxyz} - *
- * - * These are '\u0030' through - * '\u0039' and '\u0061' through - * '\u007a'. If {@code radix} is - * N, then the first N of these characters - * are used as radix-N digits in the order shown. Thus, - * the digits for hexadecimal (radix 16) are - * {@code 0123456789abcdef}. If uppercase letters are - * desired, the {@link java.lang.String#toUpperCase()} method may - * be called on the result: - * - *
- * {@code Long.toString(n, 16).toUpperCase()} - *
- * - * @param i a {@code long} to be converted to a string. - * @param radix the radix to use in the string representation. - * @return a string representation of the argument in the specified radix. - * @see java.lang.Character#MAX_RADIX - * @see java.lang.Character#MIN_RADIX - */ - public static String toString(long i, int radix) { - if (radix < Character.MIN_RADIX || radix > Character.MAX_RADIX) - radix = 10; - if (radix == 10) - return toString(i); - char[] buf = new char[65]; - int charPos = 64; - boolean negative = (i < 0); - - if (!negative) { - i = -i; - } - - while (i <= -radix) { - buf[charPos--] = Integer.digits[(int)(-(i % radix))]; - i = i / radix; - } - buf[charPos] = Integer.digits[(int)(-i)]; - - if (negative) { - buf[--charPos] = '-'; - } - - return new String(buf, charPos, (65 - charPos)); - } - - /** - * Returns a string representation of the {@code long} - * argument as an unsigned integer in base 16. - * - *

The unsigned {@code long} value is the argument plus - * 264 if the argument is negative; otherwise, it is - * equal to the argument. This value is converted to a string of - * ASCII digits in hexadecimal (base 16) with no extra - * leading {@code 0}s. If the unsigned magnitude is zero, it - * is represented by a single zero character {@code '0'} - * ('\u0030'); otherwise, the first character of - * the representation of the unsigned magnitude will not be the - * zero character. The following characters are used as - * hexadecimal digits: - * - *

- * {@code 0123456789abcdef} - *
- * - * These are the characters '\u0030' through - * '\u0039' and '\u0061' through - * '\u0066'. If uppercase letters are desired, - * the {@link java.lang.String#toUpperCase()} method may be called - * on the result: - * - *
- * {@code Long.toHexString(n).toUpperCase()} - *
- * - * @param i a {@code long} to be converted to a string. - * @return the string representation of the unsigned {@code long} - * value represented by the argument in hexadecimal - * (base 16). - * @since JDK 1.0.2 - */ - public static String toHexString(long i) { - return toUnsignedString(i, 4); - } - - /** - * Returns a string representation of the {@code long} - * argument as an unsigned integer in base 8. - * - *

The unsigned {@code long} value is the argument plus - * 264 if the argument is negative; otherwise, it is - * equal to the argument. This value is converted to a string of - * ASCII digits in octal (base 8) with no extra leading - * {@code 0}s. - * - *

If the unsigned magnitude is zero, it is represented by a - * single zero character {@code '0'} - * ('\u0030'); otherwise, the first character of - * the representation of the unsigned magnitude will not be the - * zero character. The following characters are used as octal - * digits: - * - *

- * {@code 01234567} - *
- * - * These are the characters '\u0030' through - * '\u0037'. - * - * @param i a {@code long} to be converted to a string. - * @return the string representation of the unsigned {@code long} - * value represented by the argument in octal (base 8). - * @since JDK 1.0.2 - */ - public static String toOctalString(long i) { - return toUnsignedString(i, 3); - } - - /** - * Returns a string representation of the {@code long} - * argument as an unsigned integer in base 2. - * - *

The unsigned {@code long} value is the argument plus - * 264 if the argument is negative; otherwise, it is - * equal to the argument. This value is converted to a string of - * ASCII digits in binary (base 2) with no extra leading - * {@code 0}s. If the unsigned magnitude is zero, it is - * represented by a single zero character {@code '0'} - * ('\u0030'); otherwise, the first character of - * the representation of the unsigned magnitude will not be the - * zero character. The characters {@code '0'} - * ('\u0030') and {@code '1'} - * ('\u0031') are used as binary digits. - * - * @param i a {@code long} to be converted to a string. - * @return the string representation of the unsigned {@code long} - * value represented by the argument in binary (base 2). - * @since JDK 1.0.2 - */ - public static String toBinaryString(long i) { - return toUnsignedString(i, 1); - } - - /** - * Convert the integer to an unsigned number. - */ - private static String toUnsignedString(long i, int shift) { - char[] buf = new char[64]; - int charPos = 64; - int radix = 1 << shift; - long mask = radix - 1; - do { - buf[--charPos] = Integer.digits[(int)(i & mask)]; - i >>>= shift; - } while (i != 0); - return new String(buf, charPos, (64 - charPos)); - } - - /** - * Returns a {@code String} object representing the specified - * {@code long}. The argument is converted to signed decimal - * representation and returned as a string, exactly as if the - * argument and the radix 10 were given as arguments to the {@link - * #toString(long, int)} method. - * - * @param i a {@code long} to be converted. - * @return a string representation of the argument in base 10. - */ - @JavaScriptBody(args = "i", body = "return i.toString();") - public static String toString(long i) { - if (i == Long.MIN_VALUE) - return "-9223372036854775808"; - int size = (i < 0) ? stringSize(-i) + 1 : stringSize(i); - char[] buf = new char[size]; - getChars(i, size, buf); - return new String(buf, 0, size); - } - - /** - * Places characters representing the integer i into the - * character array buf. The characters are placed into - * the buffer backwards starting with the least significant - * digit at the specified index (exclusive), and working - * backwards from there. - * - * Will fail if i == Long.MIN_VALUE - */ - static void getChars(long i, int index, char[] buf) { - long q; - int r; - int charPos = index; - char sign = 0; - - if (i < 0) { - sign = '-'; - i = -i; - } - - // Get 2 digits/iteration using longs until quotient fits into an int - while (i > Integer.MAX_VALUE) { - q = i / 100; - // really: r = i - (q * 100); - r = (int)(i - ((q << 6) + (q << 5) + (q << 2))); - i = q; - buf[--charPos] = Integer.DigitOnes[r]; - buf[--charPos] = Integer.DigitTens[r]; - } - - // Get 2 digits/iteration using ints - int q2; - int i2 = (int)i; - while (i2 >= 65536) { - q2 = i2 / 100; - // really: r = i2 - (q * 100); - r = i2 - ((q2 << 6) + (q2 << 5) + (q2 << 2)); - i2 = q2; - buf[--charPos] = Integer.DigitOnes[r]; - buf[--charPos] = Integer.DigitTens[r]; - } - - // Fall thru to fast mode for smaller numbers - // assert(i2 <= 65536, i2); - for (;;) { - q2 = (i2 * 52429) >>> (16+3); - r = i2 - ((q2 << 3) + (q2 << 1)); // r = i2-(q2*10) ... - buf[--charPos] = Integer.digits[r]; - i2 = q2; - if (i2 == 0) break; - } - if (sign != 0) { - buf[--charPos] = sign; - } - } - - // Requires positive x - static int stringSize(long x) { - long p = 10; - for (int i=1; i<19; i++) { - if (x < p) - return i; - p = 10*p; - } - return 19; - } - - /** - * Parses the string argument as a signed {@code long} in the - * radix specified by the second argument. The characters in the - * string must all be digits of the specified radix (as determined - * by whether {@link java.lang.Character#digit(char, int)} returns - * a nonnegative value), except that the first character may be an - * ASCII minus sign {@code '-'} ('\u002D') to - * indicate a negative value or an ASCII plus sign {@code '+'} - * ('\u002B') to indicate a positive value. The - * resulting {@code long} value is returned. - * - *

Note that neither the character {@code L} - * ('\u004C') nor {@code l} - * ('\u006C') is permitted to appear at the end - * of the string as a type indicator, as would be permitted in - * Java programming language source code - except that either - * {@code L} or {@code l} may appear as a digit for a - * radix greater than 22. - * - *

An exception of type {@code NumberFormatException} is - * thrown if any of the following situations occurs: - *

    - * - *
  • The first argument is {@code null} or is a string of - * length zero. - * - *
  • The {@code radix} is either smaller than {@link - * java.lang.Character#MIN_RADIX} or larger than {@link - * java.lang.Character#MAX_RADIX}. - * - *
  • Any character of the string is not a digit of the specified - * radix, except that the first character may be a minus sign - * {@code '-'} ('\u002d') or plus sign {@code - * '+'} ('\u002B') provided that the string is - * longer than length 1. - * - *
  • The value represented by the string is not a value of type - * {@code long}. - *
- * - *

Examples: - *

-     * parseLong("0", 10) returns 0L
-     * parseLong("473", 10) returns 473L
-     * parseLong("+42", 10) returns 42L
-     * parseLong("-0", 10) returns 0L
-     * parseLong("-FF", 16) returns -255L
-     * parseLong("1100110", 2) returns 102L
-     * parseLong("99", 8) throws a NumberFormatException
-     * parseLong("Hazelnut", 10) throws a NumberFormatException
-     * parseLong("Hazelnut", 36) returns 1356099454469L
-     * 
- * - * @param s the {@code String} containing the - * {@code long} representation to be parsed. - * @param radix the radix to be used while parsing {@code s}. - * @return the {@code long} represented by the string argument in - * the specified radix. - * @throws NumberFormatException if the string does not contain a - * parsable {@code long}. - */ - public static long parseLong(String s, int radix) - throws NumberFormatException - { - if (s == null) { - throw new NumberFormatException("null"); - } - - if (radix < Character.MIN_RADIX) { - throw new NumberFormatException("radix " + radix + - " less than Character.MIN_RADIX"); - } - if (radix > Character.MAX_RADIX) { - throw new NumberFormatException("radix " + radix + - " greater than Character.MAX_RADIX"); - } - - long result = 0; - boolean negative = false; - int i = 0, len = s.length(); - long limit = -Long.MAX_VALUE; - long multmin; - int digit; - - if (len > 0) { - char firstChar = s.charAt(0); - if (firstChar < '0') { // Possible leading "+" or "-" - if (firstChar == '-') { - negative = true; - limit = Long.MIN_VALUE; - } else if (firstChar != '+') - throw NumberFormatException.forInputString(s); - - if (len == 1) // Cannot have lone "+" or "-" - throw NumberFormatException.forInputString(s); - i++; - } - multmin = limit / radix; - while (i < len) { - // Accumulating negatively avoids surprises near MAX_VALUE - digit = Character.digit(s.charAt(i++),radix); - if (digit < 0) { - throw NumberFormatException.forInputString(s); - } - if (result < multmin) { - throw NumberFormatException.forInputString(s); - } - result *= radix; - if (result < limit + digit) { - throw NumberFormatException.forInputString(s); - } - result -= digit; - } - } else { - throw NumberFormatException.forInputString(s); - } - return negative ? result : -result; - } - - /** - * Parses the string argument as a signed decimal {@code long}. - * The characters in the string must all be decimal digits, except - * that the first character may be an ASCII minus sign {@code '-'} - * (\u002D') to indicate a negative value or an - * ASCII plus sign {@code '+'} ('\u002B') to - * indicate a positive value. The resulting {@code long} value is - * returned, exactly as if the argument and the radix {@code 10} - * were given as arguments to the {@link - * #parseLong(java.lang.String, int)} method. - * - *

Note that neither the character {@code L} - * ('\u004C') nor {@code l} - * ('\u006C') is permitted to appear at the end - * of the string as a type indicator, as would be permitted in - * Java programming language source code. - * - * @param s a {@code String} containing the {@code long} - * representation to be parsed - * @return the {@code long} represented by the argument in - * decimal. - * @throws NumberFormatException if the string does not contain a - * parsable {@code long}. - */ - public static long parseLong(String s) throws NumberFormatException { - return parseLong(s, 10); - } - - /** - * Returns a {@code Long} object holding the value - * extracted from the specified {@code String} when parsed - * with the radix given by the second argument. The first - * argument is interpreted as representing a signed - * {@code long} in the radix specified by the second - * argument, exactly as if the arguments were given to the {@link - * #parseLong(java.lang.String, int)} method. The result is a - * {@code Long} object that represents the {@code long} - * value specified by the string. - * - *

In other words, this method returns a {@code Long} object equal - * to the value of: - * - *

- * {@code new Long(Long.parseLong(s, radix))} - *
- * - * @param s the string to be parsed - * @param radix the radix to be used in interpreting {@code s} - * @return a {@code Long} object holding the value - * represented by the string argument in the specified - * radix. - * @throws NumberFormatException If the {@code String} does not - * contain a parsable {@code long}. - */ - public static Long valueOf(String s, int radix) throws NumberFormatException { - return Long.valueOf(parseLong(s, radix)); - } - - /** - * Returns a {@code Long} object holding the value - * of the specified {@code String}. The argument is - * interpreted as representing a signed decimal {@code long}, - * exactly as if the argument were given to the {@link - * #parseLong(java.lang.String)} method. The result is a - * {@code Long} object that represents the integer value - * specified by the string. - * - *

In other words, this method returns a {@code Long} object - * equal to the value of: - * - *

- * {@code new Long(Long.parseLong(s))} - *
- * - * @param s the string to be parsed. - * @return a {@code Long} object holding the value - * represented by the string argument. - * @throws NumberFormatException If the string cannot be parsed - * as a {@code long}. - */ - public static Long valueOf(String s) throws NumberFormatException - { - return Long.valueOf(parseLong(s, 10)); - } - - private static class LongCache { - private LongCache(){} - - static final Long cache[] = new Long[-(-128) + 127 + 1]; - - static { - for(int i = 0; i < cache.length; i++) - cache[i] = new Long(i - 128); - } - } - - /** - * Returns a {@code Long} instance representing the specified - * {@code long} value. - * If a new {@code Long} instance is not required, this method - * should generally be used in preference to the constructor - * {@link #Long(long)}, as this method is likely to yield - * significantly better space and time performance by caching - * frequently requested values. - * - * Note that unlike the {@linkplain Integer#valueOf(int) - * corresponding method} in the {@code Integer} class, this method - * is not required to cache values within a particular - * range. - * - * @param l a long value. - * @return a {@code Long} instance representing {@code l}. - * @since 1.5 - */ - public static Long valueOf(long l) { - final int offset = 128; - if (l >= -128 && l <= 127) { // will cache - return LongCache.cache[(int)l + offset]; - } - return new Long(l); - } - - /** - * Decodes a {@code String} into a {@code Long}. - * Accepts decimal, hexadecimal, and octal numbers given by the - * following grammar: - * - *
- *
- *
DecodableString: - *
Signopt DecimalNumeral - *
Signopt {@code 0x} HexDigits - *
Signopt {@code 0X} HexDigits - *
Signopt {@code #} HexDigits - *
Signopt {@code 0} OctalDigits - *

- *

Sign: - *
{@code -} - *
{@code +} - *
- *
- * - * DecimalNumeral, HexDigits, and OctalDigits - * are as defined in section 3.10.1 of - * The Java™ Language Specification, - * except that underscores are not accepted between digits. - * - *

The sequence of characters following an optional - * sign and/or radix specifier ("{@code 0x}", "{@code 0X}", - * "{@code #}", or leading zero) is parsed as by the {@code - * Long.parseLong} method with the indicated radix (10, 16, or 8). - * This sequence of characters must represent a positive value or - * a {@link NumberFormatException} will be thrown. The result is - * negated if first character of the specified {@code String} is - * the minus sign. No whitespace characters are permitted in the - * {@code String}. - * - * @param nm the {@code String} to decode. - * @return a {@code Long} object holding the {@code long} - * value represented by {@code nm} - * @throws NumberFormatException if the {@code String} does not - * contain a parsable {@code long}. - * @see java.lang.Long#parseLong(String, int) - * @since 1.2 - */ - public static Long decode(String nm) throws NumberFormatException { - int radix = 10; - int index = 0; - boolean negative = false; - Long result; - - if (nm.length() == 0) - throw new NumberFormatException("Zero length string"); - char firstChar = nm.charAt(0); - // Handle sign, if present - if (firstChar == '-') { - negative = true; - index++; - } else if (firstChar == '+') - index++; - - // Handle radix specifier, if present - if (nm.startsWith("0x", index) || nm.startsWith("0X", index)) { - index += 2; - radix = 16; - } - else if (nm.startsWith("#", index)) { - index ++; - radix = 16; - } - else if (nm.startsWith("0", index) && nm.length() > 1 + index) { - index ++; - radix = 8; - } - - if (nm.startsWith("-", index) || nm.startsWith("+", index)) - throw new NumberFormatException("Sign character in wrong position"); - - try { - result = Long.valueOf(nm.substring(index), radix); - result = negative ? Long.valueOf(-result.longValue()) : result; - } catch (NumberFormatException e) { - // If number is Long.MIN_VALUE, we'll end up here. The next line - // handles this case, and causes any genuine format error to be - // rethrown. - String constant = negative ? ("-" + nm.substring(index)) - : nm.substring(index); - result = Long.valueOf(constant, radix); - } - return result; - } - - /** - * The value of the {@code Long}. - * - * @serial - */ - private final long value; - - /** - * Constructs a newly allocated {@code Long} object that - * represents the specified {@code long} argument. - * - * @param value the value to be represented by the - * {@code Long} object. - */ - public Long(long value) { - this.value = value; - } - - /** - * Constructs a newly allocated {@code Long} object that - * represents the {@code long} value indicated by the - * {@code String} parameter. The string is converted to a - * {@code long} value in exactly the manner used by the - * {@code parseLong} method for radix 10. - * - * @param s the {@code String} to be converted to a - * {@code Long}. - * @throws NumberFormatException if the {@code String} does not - * contain a parsable {@code long}. - * @see java.lang.Long#parseLong(java.lang.String, int) - */ - public Long(String s) throws NumberFormatException { - this.value = parseLong(s, 10); - } - - /** - * Returns the value of this {@code Long} as a - * {@code byte}. - */ - public byte byteValue() { - return (byte)value; - } - - /** - * Returns the value of this {@code Long} as a - * {@code short}. - */ - public short shortValue() { - return (short)value; - } - - /** - * Returns the value of this {@code Long} as an - * {@code int}. - */ - public int intValue() { - return (int)value; - } - - /** - * Returns the value of this {@code Long} as a - * {@code long} value. - */ - public long longValue() { - return (long)value; - } - - /** - * Returns the value of this {@code Long} as a - * {@code float}. - */ - public float floatValue() { - return (float)value; - } - - /** - * Returns the value of this {@code Long} as a - * {@code double}. - */ - public double doubleValue() { - return (double)value; - } - - /** - * Returns a {@code String} object representing this - * {@code Long}'s value. The value is converted to signed - * decimal representation and returned as a string, exactly as if - * the {@code long} value were given as an argument to the - * {@link java.lang.Long#toString(long)} method. - * - * @return a string representation of the value of this object in - * base 10. - */ - public String toString() { - return toString(value); - } - - /** - * Returns a hash code for this {@code Long}. The result is - * the exclusive OR of the two halves of the primitive - * {@code long} value held by this {@code Long} - * object. That is, the hashcode is the value of the expression: - * - *

- * {@code (int)(this.longValue()^(this.longValue()>>>32))} - *
- * - * @return a hash code value for this object. - */ - public int hashCode() { - return (int)(value ^ (value >>> 32)); - } - - /** - * Compares this object to the specified object. The result is - * {@code true} if and only if the argument is not - * {@code null} and is a {@code Long} object that - * contains the same {@code long} value as this object. - * - * @param obj the object to compare with. - * @return {@code true} if the objects are the same; - * {@code false} otherwise. - */ - public boolean equals(Object obj) { - if (obj instanceof Long) { - return value == ((Long)obj).longValue(); - } - return false; - } - - /** - * Determines the {@code long} value of the system property - * with the specified name. - * - *

The first argument is treated as the name of a system property. - * System properties are accessible through the {@link - * java.lang.System#getProperty(java.lang.String)} method. The - * string value of this property is then interpreted as a - * {@code long} value and a {@code Long} object - * representing this value is returned. Details of possible - * numeric formats can be found with the definition of - * {@code getProperty}. - * - *

If there is no property with the specified name, if the - * specified name is empty or {@code null}, or if the - * property does not have the correct numeric format, then - * {@code null} is returned. - * - *

In other words, this method returns a {@code Long} object equal to - * the value of: - * - *

- * {@code getLong(nm, null)} - *
- * - * @param nm property name. - * @return the {@code Long} value of the property. - * @see java.lang.System#getProperty(java.lang.String) - * @see java.lang.System#getProperty(java.lang.String, java.lang.String) - */ - public static Long getLong(String nm) { - return getLong(nm, null); - } - - /** - * Determines the {@code long} value of the system property - * with the specified name. - * - *

The first argument is treated as the name of a system property. - * System properties are accessible through the {@link - * java.lang.System#getProperty(java.lang.String)} method. The - * string value of this property is then interpreted as a - * {@code long} value and a {@code Long} object - * representing this value is returned. Details of possible - * numeric formats can be found with the definition of - * {@code getProperty}. - * - *

The second argument is the default value. A {@code Long} object - * that represents the value of the second argument is returned if there - * is no property of the specified name, if the property does not have - * the correct numeric format, or if the specified name is empty or null. - * - *

In other words, this method returns a {@code Long} object equal - * to the value of: - * - *

- * {@code getLong(nm, new Long(val))} - *
- * - * but in practice it may be implemented in a manner such as: - * - *
-     * Long result = getLong(nm, null);
-     * return (result == null) ? new Long(val) : result;
-     * 
- * - * to avoid the unnecessary allocation of a {@code Long} object when - * the default value is not needed. - * - * @param nm property name. - * @param val default value. - * @return the {@code Long} value of the property. - * @see java.lang.System#getProperty(java.lang.String) - * @see java.lang.System#getProperty(java.lang.String, java.lang.String) - */ - public static Long getLong(String nm, long val) { - Long result = Long.getLong(nm, null); - return (result == null) ? Long.valueOf(val) : result; - } - - /** - * Returns the {@code long} value of the system property with - * the specified name. The first argument is treated as the name - * of a system property. System properties are accessible through - * the {@link java.lang.System#getProperty(java.lang.String)} - * method. The string value of this property is then interpreted - * as a {@code long} value, as per the - * {@code Long.decode} method, and a {@code Long} object - * representing this value is returned. - * - *
    - *
  • If the property value begins with the two ASCII characters - * {@code 0x} or the ASCII character {@code #}, not followed by - * a minus sign, then the rest of it is parsed as a hexadecimal integer - * exactly as for the method {@link #valueOf(java.lang.String, int)} - * with radix 16. - *
  • If the property value begins with the ASCII character - * {@code 0} followed by another character, it is parsed as - * an octal integer exactly as by the method {@link - * #valueOf(java.lang.String, int)} with radix 8. - *
  • Otherwise the property value is parsed as a decimal - * integer exactly as by the method - * {@link #valueOf(java.lang.String, int)} with radix 10. - *
- * - *

Note that, in every case, neither {@code L} - * ('\u004C') nor {@code l} - * ('\u006C') is permitted to appear at the end - * of the property value as a type indicator, as would be - * permitted in Java programming language source code. - * - *

The second argument is the default value. The default value is - * returned if there is no property of the specified name, if the - * property does not have the correct numeric format, or if the - * specified name is empty or {@code null}. - * - * @param nm property name. - * @param val default value. - * @return the {@code Long} value of the property. - * @see java.lang.System#getProperty(java.lang.String) - * @see java.lang.System#getProperty(java.lang.String, java.lang.String) - * @see java.lang.Long#decode - */ - public static Long getLong(String nm, Long val) { - String v = null; - try { - v = AbstractStringBuilder.getProperty(nm); - } catch (IllegalArgumentException e) { - } catch (NullPointerException e) { - } - if (v != null) { - try { - return Long.decode(v); - } catch (NumberFormatException e) { - } - } - return val; - } - - /** - * Compares two {@code Long} objects numerically. - * - * @param anotherLong the {@code Long} to be compared. - * @return the value {@code 0} if this {@code Long} is - * equal to the argument {@code Long}; a value less than - * {@code 0} if this {@code Long} is numerically less - * than the argument {@code Long}; and a value greater - * than {@code 0} if this {@code Long} is numerically - * greater than the argument {@code Long} (signed - * comparison). - * @since 1.2 - */ - public int compareTo(Long anotherLong) { - return compare(this.value, anotherLong.value); - } - - /** - * Compares two {@code long} values numerically. - * The value returned is identical to what would be returned by: - *

-     *    Long.valueOf(x).compareTo(Long.valueOf(y))
-     * 
- * - * @param x the first {@code long} to compare - * @param y the second {@code long} to compare - * @return the value {@code 0} if {@code x == y}; - * a value less than {@code 0} if {@code x < y}; and - * a value greater than {@code 0} if {@code x > y} - * @since 1.7 - */ - public static int compare(long x, long y) { - return (x < y) ? -1 : ((x == y) ? 0 : 1); - } - - - // Bit Twiddling - - /** - * The number of bits used to represent a {@code long} value in two's - * complement binary form. - * - * @since 1.5 - */ - public static final int SIZE = 64; - - /** - * Returns a {@code long} value with at most a single one-bit, in the - * position of the highest-order ("leftmost") one-bit in the specified - * {@code long} value. Returns zero if the specified value has no - * one-bits in its two's complement binary representation, that is, if it - * is equal to zero. - * - * @return a {@code long} value with a single one-bit, in the position - * of the highest-order one-bit in the specified value, or zero if - * the specified value is itself equal to zero. - * @since 1.5 - */ - public static long highestOneBit(long i) { - // HD, Figure 3-1 - i |= (i >> 1); - i |= (i >> 2); - i |= (i >> 4); - i |= (i >> 8); - i |= (i >> 16); - i |= (i >> 32); - return i - (i >>> 1); - } - - /** - * Returns a {@code long} value with at most a single one-bit, in the - * position of the lowest-order ("rightmost") one-bit in the specified - * {@code long} value. Returns zero if the specified value has no - * one-bits in its two's complement binary representation, that is, if it - * is equal to zero. - * - * @return a {@code long} value with a single one-bit, in the position - * of the lowest-order one-bit in the specified value, or zero if - * the specified value is itself equal to zero. - * @since 1.5 - */ - public static long lowestOneBit(long i) { - // HD, Section 2-1 - return i & -i; - } - - /** - * Returns the number of zero bits preceding the highest-order - * ("leftmost") one-bit in the two's complement binary representation - * of the specified {@code long} value. Returns 64 if the - * specified value has no one-bits in its two's complement representation, - * in other words if it is equal to zero. - * - *

Note that this method is closely related to the logarithm base 2. - * For all positive {@code long} values x: - *

    - *
  • floor(log2(x)) = {@code 63 - numberOfLeadingZeros(x)} - *
  • ceil(log2(x)) = {@code 64 - numberOfLeadingZeros(x - 1)} - *
- * - * @return the number of zero bits preceding the highest-order - * ("leftmost") one-bit in the two's complement binary representation - * of the specified {@code long} value, or 64 if the value - * is equal to zero. - * @since 1.5 - */ - public static int numberOfLeadingZeros(long i) { - // HD, Figure 5-6 - if (i == 0) - return 64; - int n = 1; - int x = (int)(i >>> 32); - if (x == 0) { n += 32; x = (int)i; } - if (x >>> 16 == 0) { n += 16; x <<= 16; } - if (x >>> 24 == 0) { n += 8; x <<= 8; } - if (x >>> 28 == 0) { n += 4; x <<= 4; } - if (x >>> 30 == 0) { n += 2; x <<= 2; } - n -= x >>> 31; - return n; - } - - /** - * Returns the number of zero bits following the lowest-order ("rightmost") - * one-bit in the two's complement binary representation of the specified - * {@code long} value. Returns 64 if the specified value has no - * one-bits in its two's complement representation, in other words if it is - * equal to zero. - * - * @return the number of zero bits following the lowest-order ("rightmost") - * one-bit in the two's complement binary representation of the - * specified {@code long} value, or 64 if the value is equal - * to zero. - * @since 1.5 - */ - public static int numberOfTrailingZeros(long i) { - // HD, Figure 5-14 - int x, y; - if (i == 0) return 64; - int n = 63; - y = (int)i; if (y != 0) { n = n -32; x = y; } else x = (int)(i>>>32); - y = x <<16; if (y != 0) { n = n -16; x = y; } - y = x << 8; if (y != 0) { n = n - 8; x = y; } - y = x << 4; if (y != 0) { n = n - 4; x = y; } - y = x << 2; if (y != 0) { n = n - 2; x = y; } - return n - ((x << 1) >>> 31); - } - - /** - * Returns the number of one-bits in the two's complement binary - * representation of the specified {@code long} value. This function is - * sometimes referred to as the population count. - * - * @return the number of one-bits in the two's complement binary - * representation of the specified {@code long} value. - * @since 1.5 - */ - public static int bitCount(long i) { - // HD, Figure 5-14 - i = i - ((i >>> 1) & 0x5555555555555555L); - i = (i & 0x3333333333333333L) + ((i >>> 2) & 0x3333333333333333L); - i = (i + (i >>> 4)) & 0x0f0f0f0f0f0f0f0fL; - i = i + (i >>> 8); - i = i + (i >>> 16); - i = i + (i >>> 32); - return (int)i & 0x7f; - } - - /** - * Returns the value obtained by rotating the two's complement binary - * representation of the specified {@code long} value left by the - * specified number of bits. (Bits shifted out of the left hand, or - * high-order, side reenter on the right, or low-order.) - * - *

Note that left rotation with a negative distance is equivalent to - * right rotation: {@code rotateLeft(val, -distance) == rotateRight(val, - * distance)}. Note also that rotation by any multiple of 64 is a - * no-op, so all but the last six bits of the rotation distance can be - * ignored, even if the distance is negative: {@code rotateLeft(val, - * distance) == rotateLeft(val, distance & 0x3F)}. - * - * @return the value obtained by rotating the two's complement binary - * representation of the specified {@code long} value left by the - * specified number of bits. - * @since 1.5 - */ - public static long rotateLeft(long i, int distance) { - return (i << distance) | (i >>> -distance); - } - - /** - * Returns the value obtained by rotating the two's complement binary - * representation of the specified {@code long} value right by the - * specified number of bits. (Bits shifted out of the right hand, or - * low-order, side reenter on the left, or high-order.) - * - *

Note that right rotation with a negative distance is equivalent to - * left rotation: {@code rotateRight(val, -distance) == rotateLeft(val, - * distance)}. Note also that rotation by any multiple of 64 is a - * no-op, so all but the last six bits of the rotation distance can be - * ignored, even if the distance is negative: {@code rotateRight(val, - * distance) == rotateRight(val, distance & 0x3F)}. - * - * @return the value obtained by rotating the two's complement binary - * representation of the specified {@code long} value right by the - * specified number of bits. - * @since 1.5 - */ - public static long rotateRight(long i, int distance) { - return (i >>> distance) | (i << -distance); - } - - /** - * Returns the value obtained by reversing the order of the bits in the - * two's complement binary representation of the specified {@code long} - * value. - * - * @return the value obtained by reversing order of the bits in the - * specified {@code long} value. - * @since 1.5 - */ - public static long reverse(long i) { - // HD, Figure 7-1 - i = (i & 0x5555555555555555L) << 1 | (i >>> 1) & 0x5555555555555555L; - i = (i & 0x3333333333333333L) << 2 | (i >>> 2) & 0x3333333333333333L; - i = (i & 0x0f0f0f0f0f0f0f0fL) << 4 | (i >>> 4) & 0x0f0f0f0f0f0f0f0fL; - i = (i & 0x00ff00ff00ff00ffL) << 8 | (i >>> 8) & 0x00ff00ff00ff00ffL; - i = (i << 48) | ((i & 0xffff0000L) << 16) | - ((i >>> 16) & 0xffff0000L) | (i >>> 48); - return i; - } - - /** - * Returns the signum function of the specified {@code long} value. (The - * return value is -1 if the specified value is negative; 0 if the - * specified value is zero; and 1 if the specified value is positive.) - * - * @return the signum function of the specified {@code long} value. - * @since 1.5 - */ - public static int signum(long i) { - // HD, Section 2-7 - return (int) ((i >> 63) | (-i >>> 63)); - } - - /** - * Returns the value obtained by reversing the order of the bytes in the - * two's complement representation of the specified {@code long} value. - * - * @return the value obtained by reversing the bytes in the specified - * {@code long} value. - * @since 1.5 - */ - public static long reverseBytes(long i) { - i = (i & 0x00ff00ff00ff00ffL) << 8 | (i >>> 8) & 0x00ff00ff00ff00ffL; - return (i << 48) | ((i & 0xffff0000L) << 16) | - ((i >>> 16) & 0xffff0000L) | (i >>> 48); - } - - /** use serialVersionUID from JDK 1.0.2 for interoperability */ - private static final long serialVersionUID = 4290774380558885855L; -} diff -r 388e48c0a37a -r 05224402145d emul/src/main/java/java/lang/Math.java --- a/emul/src/main/java/java/lang/Math.java Wed Jan 23 20:16:48 2013 +0100 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,1244 +0,0 @@ -/* - * Copyright (c) 1994, 2011, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code 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 - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package java.lang; - -import org.apidesign.bck2brwsr.core.JavaScriptBody; - - -/** - * The class {@code Math} contains methods for performing basic - * numeric operations such as the elementary exponential, logarithm, - * square root, and trigonometric functions. - * - *

Unlike some of the numeric methods of class - * {@code StrictMath}, all implementations of the equivalent - * functions of class {@code Math} are not defined to return the - * bit-for-bit same results. This relaxation permits - * better-performing implementations where strict reproducibility is - * not required. - * - *

By default many of the {@code Math} methods simply call - * the equivalent method in {@code StrictMath} for their - * implementation. Code generators are encouraged to use - * platform-specific native libraries or microprocessor instructions, - * where available, to provide higher-performance implementations of - * {@code Math} methods. Such higher-performance - * implementations still must conform to the specification for - * {@code Math}. - * - *

The quality of implementation specifications concern two - * properties, accuracy of the returned result and monotonicity of the - * method. Accuracy of the floating-point {@code Math} methods - * is measured in terms of ulps, units in the last place. For - * a given floating-point format, an ulp of a specific real number - * value is the distance between the two floating-point values - * bracketing that numerical value. When discussing the accuracy of a - * method as a whole rather than at a specific argument, the number of - * ulps cited is for the worst-case error at any argument. If a - * method always has an error less than 0.5 ulps, the method always - * returns the floating-point number nearest the exact result; such a - * method is correctly rounded. A correctly rounded method is - * generally the best a floating-point approximation can be; however, - * it is impractical for many floating-point methods to be correctly - * rounded. Instead, for the {@code Math} class, a larger error - * bound of 1 or 2 ulps is allowed for certain methods. Informally, - * with a 1 ulp error bound, when the exact result is a representable - * number, the exact result should be returned as the computed result; - * otherwise, either of the two floating-point values which bracket - * the exact result may be returned. For exact results large in - * magnitude, one of the endpoints of the bracket may be infinite. - * Besides accuracy at individual arguments, maintaining proper - * relations between the method at different arguments is also - * important. Therefore, most methods with more than 0.5 ulp errors - * are required to be semi-monotonic: whenever the mathematical - * function is non-decreasing, so is the floating-point approximation, - * likewise, whenever the mathematical function is non-increasing, so - * is the floating-point approximation. Not all approximations that - * have 1 ulp accuracy will automatically meet the monotonicity - * requirements. - * - * @author unascribed - * @author Joseph D. Darcy - * @since JDK1.0 - */ - -public final class Math { - - /** - * Don't let anyone instantiate this class. - */ - private Math() {} - - /** - * The {@code double} value that is closer than any other to - * e, the base of the natural logarithms. - */ - public static final double E = 2.7182818284590452354; - - /** - * The {@code double} value that is closer than any other to - * pi, the ratio of the circumference of a circle to its - * diameter. - */ - public static final double PI = 3.14159265358979323846; - - /** - * Returns the trigonometric sine of an angle. Special cases: - *

  • If the argument is NaN or an infinity, then the - * result is NaN. - *
  • If the argument is zero, then the result is a zero with the - * same sign as the argument.
- * - *

The computed result must be within 1 ulp of the exact result. - * Results must be semi-monotonic. - * - * @param a an angle, in radians. - * @return the sine of the argument. - */ - @JavaScriptBody(args="a", body="return Math.sin(a);") - public static double sin(double a) { - throw new UnsupportedOperationException(); - } - - /** - * Returns the trigonometric cosine of an angle. Special cases: - *

  • If the argument is NaN or an infinity, then the - * result is NaN.
- * - *

The computed result must be within 1 ulp of the exact result. - * Results must be semi-monotonic. - * - * @param a an angle, in radians. - * @return the cosine of the argument. - */ - @JavaScriptBody(args="a", body="return Math.cos(a);") - public static double cos(double a) { - throw new UnsupportedOperationException(); - } - - /** - * Returns the trigonometric tangent of an angle. Special cases: - *

  • If the argument is NaN or an infinity, then the result - * is NaN. - *
  • If the argument is zero, then the result is a zero with the - * same sign as the argument.
- * - *

The computed result must be within 1 ulp of the exact result. - * Results must be semi-monotonic. - * - * @param a an angle, in radians. - * @return the tangent of the argument. - */ - @JavaScriptBody(args="a", body="return Math.tan(a);") - public static double tan(double a) { - throw new UnsupportedOperationException(); - } - - /** - * Returns the arc sine of a value; the returned angle is in the - * range -pi/2 through pi/2. Special cases: - *

  • If the argument is NaN or its absolute value is greater - * than 1, then the result is NaN. - *
  • If the argument is zero, then the result is a zero with the - * same sign as the argument.
- * - *

The computed result must be within 1 ulp of the exact result. - * Results must be semi-monotonic. - * - * @param a the value whose arc sine is to be returned. - * @return the arc sine of the argument. - */ - @JavaScriptBody(args="a", body="return Math.asin(a);") - public static double asin(double a) { - throw new UnsupportedOperationException(); - } - - /** - * Returns the arc cosine of a value; the returned angle is in the - * range 0.0 through pi. Special case: - *

  • If the argument is NaN or its absolute value is greater - * than 1, then the result is NaN.
- * - *

The computed result must be within 1 ulp of the exact result. - * Results must be semi-monotonic. - * - * @param a the value whose arc cosine is to be returned. - * @return the arc cosine of the argument. - */ - @JavaScriptBody(args="a", body="return Math.acos(a);") - public static double acos(double a) { - throw new UnsupportedOperationException(); - } - - /** - * Returns the arc tangent of a value; the returned angle is in the - * range -pi/2 through pi/2. Special cases: - *

  • If the argument is NaN, then the result is NaN. - *
  • If the argument is zero, then the result is a zero with the - * same sign as the argument.
- * - *

The computed result must be within 1 ulp of the exact result. - * Results must be semi-monotonic. - * - * @param a the value whose arc tangent is to be returned. - * @return the arc tangent of the argument. - */ - @JavaScriptBody(args="a", body="return Math.atan(a);") - public static double atan(double a) { - throw new UnsupportedOperationException(); - } - - /** - * Converts an angle measured in degrees to an approximately - * equivalent angle measured in radians. The conversion from - * degrees to radians is generally inexact. - * - * @param angdeg an angle, in degrees - * @return the measurement of the angle {@code angdeg} - * in radians. - * @since 1.2 - */ - public static double toRadians(double angdeg) { - return angdeg / 180.0 * PI; - } - - /** - * Converts an angle measured in radians to an approximately - * equivalent angle measured in degrees. The conversion from - * radians to degrees is generally inexact; users should - * not expect {@code cos(toRadians(90.0))} to exactly - * equal {@code 0.0}. - * - * @param angrad an angle, in radians - * @return the measurement of the angle {@code angrad} - * in degrees. - * @since 1.2 - */ - public static double toDegrees(double angrad) { - return angrad * 180.0 / PI; - } - - /** - * Returns Euler's number e raised to the power of a - * {@code double} value. Special cases: - *

  • If the argument is NaN, the result is NaN. - *
  • If the argument is positive infinity, then the result is - * positive infinity. - *
  • If the argument is negative infinity, then the result is - * positive zero.
- * - *

The computed result must be within 1 ulp of the exact result. - * Results must be semi-monotonic. - * - * @param a the exponent to raise e to. - * @return the value e{@code a}, - * where e is the base of the natural logarithms. - */ - @JavaScriptBody(args="a", body="return Math.exp(a);") - public static double exp(double a) { - throw new UnsupportedOperationException(); - } - - /** - * Returns the natural logarithm (base e) of a {@code double} - * value. Special cases: - *

  • If the argument is NaN or less than zero, then the result - * is NaN. - *
  • If the argument is positive infinity, then the result is - * positive infinity. - *
  • If the argument is positive zero or negative zero, then the - * result is negative infinity.
- * - *

The computed result must be within 1 ulp of the exact result. - * Results must be semi-monotonic. - * - * @param a a value - * @return the value ln {@code a}, the natural logarithm of - * {@code a}. - */ - @JavaScriptBody(args="a", body="return Math.log(a);") - public static double log(double a) { - throw new UnsupportedOperationException(); - } - - /** - * Returns the base 10 logarithm of a {@code double} value. - * Special cases: - * - *

  • If the argument is NaN or less than zero, then the result - * is NaN. - *
  • If the argument is positive infinity, then the result is - * positive infinity. - *
  • If the argument is positive zero or negative zero, then the - * result is negative infinity. - *
  • If the argument is equal to 10n for - * integer n, then the result is n. - *
- * - *

The computed result must be within 1 ulp of the exact result. - * Results must be semi-monotonic. - * - * @param a a value - * @return the base 10 logarithm of {@code a}. - * @since 1.5 - */ - @JavaScriptBody(args="a", body="return Math.log(a) / Math.LN10;") - public static double log10(double a) { - throw new UnsupportedOperationException(); - } - - /** - * Returns the correctly rounded positive square root of a - * {@code double} value. - * Special cases: - *

  • If the argument is NaN or less than zero, then the result - * is NaN. - *
  • If the argument is positive infinity, then the result is positive - * infinity. - *
  • If the argument is positive zero or negative zero, then the - * result is the same as the argument.
- * Otherwise, the result is the {@code double} value closest to - * the true mathematical square root of the argument value. - * - * @param a a value. - * @return the positive square root of {@code a}. - * If the argument is NaN or less than zero, the result is NaN. - */ - @JavaScriptBody(args="a", body="return Math.sqrt(a);") - public static double sqrt(double a) { - throw new UnsupportedOperationException(); - } - - /** - * Returns the smallest (closest to negative infinity) - * {@code double} value that is greater than or equal to the - * argument and is equal to a mathematical integer. Special cases: - *
  • If the argument value is already equal to a - * mathematical integer, then the result is the same as the - * argument.
  • If the argument is NaN or an infinity or - * positive zero or negative zero, then the result is the same as - * the argument.
  • If the argument value is less than zero but - * greater than -1.0, then the result is negative zero.
Note - * that the value of {@code Math.ceil(x)} is exactly the - * value of {@code -Math.floor(-x)}. - * - * - * @param a a value. - * @return the smallest (closest to negative infinity) - * floating-point value that is greater than or equal to - * the argument and is equal to a mathematical integer. - */ - @JavaScriptBody(args="a", body="return Math.ceil(a);") - public static double ceil(double a) { - throw new UnsupportedOperationException(); - } - - /** - * Returns the largest (closest to positive infinity) - * {@code double} value that is less than or equal to the - * argument and is equal to a mathematical integer. Special cases: - *
  • If the argument value is already equal to a - * mathematical integer, then the result is the same as the - * argument.
  • If the argument is NaN or an infinity or - * positive zero or negative zero, then the result is the same as - * the argument.
- * - * @param a a value. - * @return the largest (closest to positive infinity) - * floating-point value that less than or equal to the argument - * and is equal to a mathematical integer. - */ - @JavaScriptBody(args="a", body="return Math.floor(a);") - public static double floor(double a) { - throw new UnsupportedOperationException(); - } - - /** - * Returns the angle theta from the conversion of rectangular - * coordinates ({@code x}, {@code y}) to polar - * coordinates (r, theta). - * This method computes the phase theta by computing an arc tangent - * of {@code y/x} in the range of -pi to pi. Special - * cases: - *
  • If either argument is NaN, then the result is NaN. - *
  • If the first argument is positive zero and the second argument - * is positive, or the first argument is positive and finite and the - * second argument is positive infinity, then the result is positive - * zero. - *
  • If the first argument is negative zero and the second argument - * is positive, or the first argument is negative and finite and the - * second argument is positive infinity, then the result is negative zero. - *
  • If the first argument is positive zero and the second argument - * is negative, or the first argument is positive and finite and the - * second argument is negative infinity, then the result is the - * {@code double} value closest to pi. - *
  • If the first argument is negative zero and the second argument - * is negative, or the first argument is negative and finite and the - * second argument is negative infinity, then the result is the - * {@code double} value closest to -pi. - *
  • If the first argument is positive and the second argument is - * positive zero or negative zero, or the first argument is positive - * infinity and the second argument is finite, then the result is the - * {@code double} value closest to pi/2. - *
  • If the first argument is negative and the second argument is - * positive zero or negative zero, or the first argument is negative - * infinity and the second argument is finite, then the result is the - * {@code double} value closest to -pi/2. - *
  • If both arguments are positive infinity, then the result is the - * {@code double} value closest to pi/4. - *
  • If the first argument is positive infinity and the second argument - * is negative infinity, then the result is the {@code double} - * value closest to 3*pi/4. - *
  • If the first argument is negative infinity and the second argument - * is positive infinity, then the result is the {@code double} value - * closest to -pi/4. - *
  • If both arguments are negative infinity, then the result is the - * {@code double} value closest to -3*pi/4.
- * - *

The computed result must be within 2 ulps of the exact result. - * Results must be semi-monotonic. - * - * @param y the ordinate coordinate - * @param x the abscissa coordinate - * @return the theta component of the point - * (rtheta) - * in polar coordinates that corresponds to the point - * (xy) in Cartesian coordinates. - */ - @JavaScriptBody(args={"y", "x"}, body="return Math.atan2(y, x);") - public static double atan2(double y, double x) { - throw new UnsupportedOperationException(); - } - - /** - * Returns the value of the first argument raised to the power of the - * second argument. Special cases: - * - *

  • If the second argument is positive or negative zero, then the - * result is 1.0. - *
  • If the second argument is 1.0, then the result is the same as the - * first argument. - *
  • If the second argument is NaN, then the result is NaN. - *
  • If the first argument is NaN and the second argument is nonzero, - * then the result is NaN. - * - *
  • If - *
      - *
    • the absolute value of the first argument is greater than 1 - * and the second argument is positive infinity, or - *
    • the absolute value of the first argument is less than 1 and - * the second argument is negative infinity, - *
    - * then the result is positive infinity. - * - *
  • If - *
      - *
    • the absolute value of the first argument is greater than 1 and - * the second argument is negative infinity, or - *
    • the absolute value of the - * first argument is less than 1 and the second argument is positive - * infinity, - *
    - * then the result is positive zero. - * - *
  • If the absolute value of the first argument equals 1 and the - * second argument is infinite, then the result is NaN. - * - *
  • If - *
      - *
    • the first argument is positive zero and the second argument - * is greater than zero, or - *
    • the first argument is positive infinity and the second - * argument is less than zero, - *
    - * then the result is positive zero. - * - *
  • If - *
      - *
    • the first argument is positive zero and the second argument - * is less than zero, or - *
    • the first argument is positive infinity and the second - * argument is greater than zero, - *
    - * then the result is positive infinity. - * - *
  • If - *
      - *
    • the first argument is negative zero and the second argument - * is greater than zero but not a finite odd integer, or - *
    • the first argument is negative infinity and the second - * argument is less than zero but not a finite odd integer, - *
    - * then the result is positive zero. - * - *
  • If - *
      - *
    • the first argument is negative zero and the second argument - * is a positive finite odd integer, or - *
    • the first argument is negative infinity and the second - * argument is a negative finite odd integer, - *
    - * then the result is negative zero. - * - *
  • If - *
      - *
    • the first argument is negative zero and the second argument - * is less than zero but not a finite odd integer, or - *
    • the first argument is negative infinity and the second - * argument is greater than zero but not a finite odd integer, - *
    - * then the result is positive infinity. - * - *
  • If - *
      - *
    • the first argument is negative zero and the second argument - * is a negative finite odd integer, or - *
    • the first argument is negative infinity and the second - * argument is a positive finite odd integer, - *
    - * then the result is negative infinity. - * - *
  • If the first argument is finite and less than zero - *
      - *
    • if the second argument is a finite even integer, the - * result is equal to the result of raising the absolute value of - * the first argument to the power of the second argument - * - *
    • if the second argument is a finite odd integer, the result - * is equal to the negative of the result of raising the absolute - * value of the first argument to the power of the second - * argument - * - *
    • if the second argument is finite and not an integer, then - * the result is NaN. - *
    - * - *
  • If both arguments are integers, then the result is exactly equal - * to the mathematical result of raising the first argument to the power - * of the second argument if that result can in fact be represented - * exactly as a {@code double} value.
- * - *

(In the foregoing descriptions, a floating-point value is - * considered to be an integer if and only if it is finite and a - * fixed point of the method {@link #ceil ceil} or, - * equivalently, a fixed point of the method {@link #floor - * floor}. A value is a fixed point of a one-argument - * method if and only if the result of applying the method to the - * value is equal to the value.) - * - *

The computed result must be within 1 ulp of the exact result. - * Results must be semi-monotonic. - * - * @param a the base. - * @param b the exponent. - * @return the value {@code a}{@code b}. - */ - @JavaScriptBody(args={"a", "b"}, body="return Math.pow(a, b);") - public static double pow(double a, double b) { - throw new UnsupportedOperationException(); - } - - /** - * Returns the closest {@code int} to the argument, with ties - * rounding up. - * - *

- * Special cases: - *

  • If the argument is NaN, the result is 0. - *
  • If the argument is negative infinity or any value less than or - * equal to the value of {@code Integer.MIN_VALUE}, the result is - * equal to the value of {@code Integer.MIN_VALUE}. - *
  • If the argument is positive infinity or any value greater than or - * equal to the value of {@code Integer.MAX_VALUE}, the result is - * equal to the value of {@code Integer.MAX_VALUE}.
- * - * @param a a floating-point value to be rounded to an integer. - * @return the value of the argument rounded to the nearest - * {@code int} value. - * @see java.lang.Integer#MAX_VALUE - * @see java.lang.Integer#MIN_VALUE - */ - @JavaScriptBody(args="a", body="return Math.round(a);") - public static int round(float a) { - throw new UnsupportedOperationException(); - } - - /** - * Returns the closest {@code long} to the argument, with ties - * rounding up. - * - *

Special cases: - *

  • If the argument is NaN, the result is 0. - *
  • If the argument is negative infinity or any value less than or - * equal to the value of {@code Long.MIN_VALUE}, the result is - * equal to the value of {@code Long.MIN_VALUE}. - *
  • If the argument is positive infinity or any value greater than or - * equal to the value of {@code Long.MAX_VALUE}, the result is - * equal to the value of {@code Long.MAX_VALUE}.
- * - * @param a a floating-point value to be rounded to a - * {@code long}. - * @return the value of the argument rounded to the nearest - * {@code long} value. - * @see java.lang.Long#MAX_VALUE - * @see java.lang.Long#MIN_VALUE - */ - @JavaScriptBody(args="a", body="return Math.round(a);") - public static long round(double a) { - throw new UnsupportedOperationException(); - } - -// private static Random randomNumberGenerator; -// -// private static synchronized Random initRNG() { -// Random rnd = randomNumberGenerator; -// return (rnd == null) ? (randomNumberGenerator = new Random()) : rnd; -// } - - /** - * Returns a {@code double} value with a positive sign, greater - * than or equal to {@code 0.0} and less than {@code 1.0}. - * Returned values are chosen pseudorandomly with (approximately) - * uniform distribution from that range. - * - *

When this method is first called, it creates a single new - * pseudorandom-number generator, exactly as if by the expression - * - *

{@code new java.util.Random()}
- * - * This new pseudorandom-number generator is used thereafter for - * all calls to this method and is used nowhere else. - * - *

This method is properly synchronized to allow correct use by - * more than one thread. However, if many threads need to generate - * pseudorandom numbers at a great rate, it may reduce contention - * for each thread to have its own pseudorandom-number generator. - * - * @return a pseudorandom {@code double} greater than or equal - * to {@code 0.0} and less than {@code 1.0}. - * @see Random#nextDouble() - */ - @JavaScriptBody(args={}, body="return Math.random();") - public static double random() { - throw new UnsupportedOperationException(); - } - - /** - * Returns the absolute value of an {@code int} value. - * If the argument is not negative, the argument is returned. - * If the argument is negative, the negation of the argument is returned. - * - *

Note that if the argument is equal to the value of - * {@link Integer#MIN_VALUE}, the most negative representable - * {@code int} value, the result is that same value, which is - * negative. - * - * @param a the argument whose absolute value is to be determined - * @return the absolute value of the argument. - */ - public static int abs(int a) { - return (a < 0) ? -a : a; - } - - /** - * Returns the absolute value of a {@code long} value. - * If the argument is not negative, the argument is returned. - * If the argument is negative, the negation of the argument is returned. - * - *

Note that if the argument is equal to the value of - * {@link Long#MIN_VALUE}, the most negative representable - * {@code long} value, the result is that same value, which - * is negative. - * - * @param a the argument whose absolute value is to be determined - * @return the absolute value of the argument. - */ - public static long abs(long a) { - return (a < 0) ? -a : a; - } - - /** - * Returns the absolute value of a {@code float} value. - * If the argument is not negative, the argument is returned. - * If the argument is negative, the negation of the argument is returned. - * Special cases: - *

  • If the argument is positive zero or negative zero, the - * result is positive zero. - *
  • If the argument is infinite, the result is positive infinity. - *
  • If the argument is NaN, the result is NaN.
- * In other words, the result is the same as the value of the expression: - *

{@code Float.intBitsToFloat(0x7fffffff & Float.floatToIntBits(a))} - * - * @param a the argument whose absolute value is to be determined - * @return the absolute value of the argument. - */ - public static float abs(float a) { - return (a <= 0.0F) ? 0.0F - a : a; - } - - /** - * Returns the absolute value of a {@code double} value. - * If the argument is not negative, the argument is returned. - * If the argument is negative, the negation of the argument is returned. - * Special cases: - *

  • If the argument is positive zero or negative zero, the result - * is positive zero. - *
  • If the argument is infinite, the result is positive infinity. - *
  • If the argument is NaN, the result is NaN.
- * In other words, the result is the same as the value of the expression: - *

{@code Double.longBitsToDouble((Double.doubleToLongBits(a)<<1)>>>1)} - * - * @param a the argument whose absolute value is to be determined - * @return the absolute value of the argument. - */ - public static double abs(double a) { - return (a <= 0.0D) ? 0.0D - a : a; - } - - /** - * Returns the greater of two {@code int} values. That is, the - * result is the argument closer to the value of - * {@link Integer#MAX_VALUE}. If the arguments have the same value, - * the result is that same value. - * - * @param a an argument. - * @param b another argument. - * @return the larger of {@code a} and {@code b}. - */ - public static int max(int a, int b) { - return (a >= b) ? a : b; - } - - /** - * Returns the greater of two {@code long} values. That is, the - * result is the argument closer to the value of - * {@link Long#MAX_VALUE}. If the arguments have the same value, - * the result is that same value. - * - * @param a an argument. - * @param b another argument. - * @return the larger of {@code a} and {@code b}. - */ - public static long max(long a, long b) { - return (a >= b) ? a : b; - } - - /** - * Returns the greater of two {@code float} values. That is, - * the result is the argument closer to positive infinity. If the - * arguments have the same value, the result is that same - * value. If either value is NaN, then the result is NaN. Unlike - * the numerical comparison operators, this method considers - * negative zero to be strictly smaller than positive zero. If one - * argument is positive zero and the other negative zero, the - * result is positive zero. - * - * @param a an argument. - * @param b another argument. - * @return the larger of {@code a} and {@code b}. - */ - @JavaScriptBody(args={"a", "b"}, - body="return Math.max(a,b);" - ) - public static float max(float a, float b) { - throw new UnsupportedOperationException(); - } - - /** - * Returns the greater of two {@code double} values. That - * is, the result is the argument closer to positive infinity. If - * the arguments have the same value, the result is that same - * value. If either value is NaN, then the result is NaN. Unlike - * the numerical comparison operators, this method considers - * negative zero to be strictly smaller than positive zero. If one - * argument is positive zero and the other negative zero, the - * result is positive zero. - * - * @param a an argument. - * @param b another argument. - * @return the larger of {@code a} and {@code b}. - */ - @JavaScriptBody(args={"a", "b"}, - body="return Math.max(a,b);" - ) - public static double max(double a, double b) { - throw new UnsupportedOperationException(); - } - - /** - * Returns the smaller of two {@code int} values. That is, - * the result the argument closer to the value of - * {@link Integer#MIN_VALUE}. If the arguments have the same - * value, the result is that same value. - * - * @param a an argument. - * @param b another argument. - * @return the smaller of {@code a} and {@code b}. - */ - public static int min(int a, int b) { - return (a <= b) ? a : b; - } - - /** - * Returns the smaller of two {@code long} values. That is, - * the result is the argument closer to the value of - * {@link Long#MIN_VALUE}. If the arguments have the same - * value, the result is that same value. - * - * @param a an argument. - * @param b another argument. - * @return the smaller of {@code a} and {@code b}. - */ - public static long min(long a, long b) { - return (a <= b) ? a : b; - } - - /** - * Returns the smaller of two {@code float} values. That is, - * the result is the value closer to negative infinity. If the - * arguments have the same value, the result is that same - * value. If either value is NaN, then the result is NaN. Unlike - * the numerical comparison operators, this method considers - * negative zero to be strictly smaller than positive zero. If - * one argument is positive zero and the other is negative zero, - * the result is negative zero. - * - * @param a an argument. - * @param b another argument. - * @return the smaller of {@code a} and {@code b}. - */ - @JavaScriptBody(args={"a", "b"}, - body="return Math.min(a,b);" - ) - public static float min(float a, float b) { - throw new UnsupportedOperationException(); - } - - /** - * Returns the smaller of two {@code double} values. That - * is, the result is the value closer to negative infinity. If the - * arguments have the same value, the result is that same - * value. If either value is NaN, then the result is NaN. Unlike - * the numerical comparison operators, this method considers - * negative zero to be strictly smaller than positive zero. If one - * argument is positive zero and the other is negative zero, the - * result is negative zero. - * - * @param a an argument. - * @param b another argument. - * @return the smaller of {@code a} and {@code b}. - */ - @JavaScriptBody(args={"a", "b"}, - body="return Math.min(a,b);" - ) - public static double min(double a, double b) { - throw new UnsupportedOperationException(); - } - - /** - * Returns the size of an ulp of the argument. An ulp of a - * {@code double} value is the positive distance between this - * floating-point value and the {@code double} value next - * larger in magnitude. Note that for non-NaN x, - * ulp(-x) == ulp(x). - * - *

Special Cases: - *

    - *
  • If the argument is NaN, then the result is NaN. - *
  • If the argument is positive or negative infinity, then the - * result is positive infinity. - *
  • If the argument is positive or negative zero, then the result is - * {@code Double.MIN_VALUE}. - *
  • If the argument is ±{@code Double.MAX_VALUE}, then - * the result is equal to 2971. - *
- * - * @param d the floating-point value whose ulp is to be returned - * @return the size of an ulp of the argument - * @author Joseph D. Darcy - * @since 1.5 - */ -// public static double ulp(double d) { -// return sun.misc.FpUtils.ulp(d); -// } - - /** - * Returns the size of an ulp of the argument. An ulp of a - * {@code float} value is the positive distance between this - * floating-point value and the {@code float} value next - * larger in magnitude. Note that for non-NaN x, - * ulp(-x) == ulp(x). - * - *

Special Cases: - *

    - *
  • If the argument is NaN, then the result is NaN. - *
  • If the argument is positive or negative infinity, then the - * result is positive infinity. - *
  • If the argument is positive or negative zero, then the result is - * {@code Float.MIN_VALUE}. - *
  • If the argument is ±{@code Float.MAX_VALUE}, then - * the result is equal to 2104. - *
- * - * @param f the floating-point value whose ulp is to be returned - * @return the size of an ulp of the argument - * @author Joseph D. Darcy - * @since 1.5 - */ -// public static float ulp(float f) { -// return sun.misc.FpUtils.ulp(f); -// } - - /** - * Returns the signum function of the argument; zero if the argument - * is zero, 1.0 if the argument is greater than zero, -1.0 if the - * argument is less than zero. - * - *

Special Cases: - *

    - *
  • If the argument is NaN, then the result is NaN. - *
  • If the argument is positive zero or negative zero, then the - * result is the same as the argument. - *
- * - * @param d the floating-point value whose signum is to be returned - * @return the signum function of the argument - * @author Joseph D. Darcy - * @since 1.5 - */ -// public static double signum(double d) { -// return sun.misc.FpUtils.signum(d); -// } - - /** - * Returns the signum function of the argument; zero if the argument - * is zero, 1.0f if the argument is greater than zero, -1.0f if the - * argument is less than zero. - * - *

Special Cases: - *

    - *
  • If the argument is NaN, then the result is NaN. - *
  • If the argument is positive zero or negative zero, then the - * result is the same as the argument. - *
- * - * @param f the floating-point value whose signum is to be returned - * @return the signum function of the argument - * @author Joseph D. Darcy - * @since 1.5 - */ -// public static float signum(float f) { -// return sun.misc.FpUtils.signum(f); -// } - - /** - * Returns the first floating-point argument with the sign of the - * second floating-point argument. Note that unlike the {@link - * StrictMath#copySign(double, double) StrictMath.copySign} - * method, this method does not require NaN {@code sign} - * arguments to be treated as positive values; implementations are - * permitted to treat some NaN arguments as positive and other NaN - * arguments as negative to allow greater performance. - * - * @param magnitude the parameter providing the magnitude of the result - * @param sign the parameter providing the sign of the result - * @return a value with the magnitude of {@code magnitude} - * and the sign of {@code sign}. - * @since 1.6 - */ -// public static double copySign(double magnitude, double sign) { -// return sun.misc.FpUtils.rawCopySign(magnitude, sign); -// } - - /** - * Returns the first floating-point argument with the sign of the - * second floating-point argument. Note that unlike the {@link - * StrictMath#copySign(float, float) StrictMath.copySign} - * method, this method does not require NaN {@code sign} - * arguments to be treated as positive values; implementations are - * permitted to treat some NaN arguments as positive and other NaN - * arguments as negative to allow greater performance. - * - * @param magnitude the parameter providing the magnitude of the result - * @param sign the parameter providing the sign of the result - * @return a value with the magnitude of {@code magnitude} - * and the sign of {@code sign}. - * @since 1.6 - */ -// public static float copySign(float magnitude, float sign) { -// return sun.misc.FpUtils.rawCopySign(magnitude, sign); -// } - - /** - * Returns the unbiased exponent used in the representation of a - * {@code float}. Special cases: - * - *
    - *
  • If the argument is NaN or infinite, then the result is - * {@link Float#MAX_EXPONENT} + 1. - *
  • If the argument is zero or subnormal, then the result is - * {@link Float#MIN_EXPONENT} -1. - *
- * @param f a {@code float} value - * @return the unbiased exponent of the argument - * @since 1.6 - */ -// public static int getExponent(float f) { -// return sun.misc.FpUtils.getExponent(f); -// } - - /** - * Returns the unbiased exponent used in the representation of a - * {@code double}. Special cases: - * - *
    - *
  • If the argument is NaN or infinite, then the result is - * {@link Double#MAX_EXPONENT} + 1. - *
  • If the argument is zero or subnormal, then the result is - * {@link Double#MIN_EXPONENT} -1. - *
- * @param d a {@code double} value - * @return the unbiased exponent of the argument - * @since 1.6 - */ -// public static int getExponent(double d) { -// return sun.misc.FpUtils.getExponent(d); -// } - - /** - * Returns the floating-point number adjacent to the first - * argument in the direction of the second argument. If both - * arguments compare as equal the second argument is returned. - * - *

- * Special cases: - *

    - *
  • If either argument is a NaN, then NaN is returned. - * - *
  • If both arguments are signed zeros, {@code direction} - * is returned unchanged (as implied by the requirement of - * returning the second argument if the arguments compare as - * equal). - * - *
  • If {@code start} is - * ±{@link Double#MIN_VALUE} and {@code direction} - * has a value such that the result should have a smaller - * magnitude, then a zero with the same sign as {@code start} - * is returned. - * - *
  • If {@code start} is infinite and - * {@code direction} has a value such that the result should - * have a smaller magnitude, {@link Double#MAX_VALUE} with the - * same sign as {@code start} is returned. - * - *
  • If {@code start} is equal to ± - * {@link Double#MAX_VALUE} and {@code direction} has a - * value such that the result should have a larger magnitude, an - * infinity with same sign as {@code start} is returned. - *
- * - * @param start starting floating-point value - * @param direction value indicating which of - * {@code start}'s neighbors or {@code start} should - * be returned - * @return The floating-point number adjacent to {@code start} in the - * direction of {@code direction}. - * @since 1.6 - */ -// public static double nextAfter(double start, double direction) { -// return sun.misc.FpUtils.nextAfter(start, direction); -// } - - /** - * Returns the floating-point number adjacent to the first - * argument in the direction of the second argument. If both - * arguments compare as equal a value equivalent to the second argument - * is returned. - * - *

- * Special cases: - *

    - *
  • If either argument is a NaN, then NaN is returned. - * - *
  • If both arguments are signed zeros, a value equivalent - * to {@code direction} is returned. - * - *
  • If {@code start} is - * ±{@link Float#MIN_VALUE} and {@code direction} - * has a value such that the result should have a smaller - * magnitude, then a zero with the same sign as {@code start} - * is returned. - * - *
  • If {@code start} is infinite and - * {@code direction} has a value such that the result should - * have a smaller magnitude, {@link Float#MAX_VALUE} with the - * same sign as {@code start} is returned. - * - *
  • If {@code start} is equal to ± - * {@link Float#MAX_VALUE} and {@code direction} has a - * value such that the result should have a larger magnitude, an - * infinity with same sign as {@code start} is returned. - *
- * - * @param start starting floating-point value - * @param direction value indicating which of - * {@code start}'s neighbors or {@code start} should - * be returned - * @return The floating-point number adjacent to {@code start} in the - * direction of {@code direction}. - * @since 1.6 - */ -// public static float nextAfter(float start, double direction) { -// return sun.misc.FpUtils.nextAfter(start, direction); -// } - - /** - * Returns the floating-point value adjacent to {@code d} in - * the direction of positive infinity. This method is - * semantically equivalent to {@code nextAfter(d, - * Double.POSITIVE_INFINITY)}; however, a {@code nextUp} - * implementation may run faster than its equivalent - * {@code nextAfter} call. - * - *

Special Cases: - *

    - *
  • If the argument is NaN, the result is NaN. - * - *
  • If the argument is positive infinity, the result is - * positive infinity. - * - *
  • If the argument is zero, the result is - * {@link Double#MIN_VALUE} - * - *
- * - * @param d starting floating-point value - * @return The adjacent floating-point value closer to positive - * infinity. - * @since 1.6 - */ -// public static double nextUp(double d) { -// return sun.misc.FpUtils.nextUp(d); -// } - - /** - * Returns the floating-point value adjacent to {@code f} in - * the direction of positive infinity. This method is - * semantically equivalent to {@code nextAfter(f, - * Float.POSITIVE_INFINITY)}; however, a {@code nextUp} - * implementation may run faster than its equivalent - * {@code nextAfter} call. - * - *

Special Cases: - *

    - *
  • If the argument is NaN, the result is NaN. - * - *
  • If the argument is positive infinity, the result is - * positive infinity. - * - *
  • If the argument is zero, the result is - * {@link Float#MIN_VALUE} - * - *
- * - * @param f starting floating-point value - * @return The adjacent floating-point value closer to positive - * infinity. - * @since 1.6 - */ -// public static float nextUp(float f) { -// return sun.misc.FpUtils.nextUp(f); -// } - - - /** - * Return {@code d} × - * 2{@code scaleFactor} rounded as if performed - * by a single correctly rounded floating-point multiply to a - * member of the double value set. See the Java - * Language Specification for a discussion of floating-point - * value sets. If the exponent of the result is between {@link - * Double#MIN_EXPONENT} and {@link Double#MAX_EXPONENT}, the - * answer is calculated exactly. If the exponent of the result - * would be larger than {@code Double.MAX_EXPONENT}, an - * infinity is returned. Note that if the result is subnormal, - * precision may be lost; that is, when {@code scalb(x, n)} - * is subnormal, {@code scalb(scalb(x, n), -n)} may not equal - * x. When the result is non-NaN, the result has the same - * sign as {@code d}. - * - *

Special cases: - *

    - *
  • If the first argument is NaN, NaN is returned. - *
  • If the first argument is infinite, then an infinity of the - * same sign is returned. - *
  • If the first argument is zero, then a zero of the same - * sign is returned. - *
- * - * @param d number to be scaled by a power of two. - * @param scaleFactor power of 2 used to scale {@code d} - * @return {@code d} × 2{@code scaleFactor} - * @since 1.6 - */ -// public static double scalb(double d, int scaleFactor) { -// return sun.misc.FpUtils.scalb(d, scaleFactor); -// } - - /** - * Return {@code f} × - * 2{@code scaleFactor} rounded as if performed - * by a single correctly rounded floating-point multiply to a - * member of the float value set. See the Java - * Language Specification for a discussion of floating-point - * value sets. If the exponent of the result is between {@link - * Float#MIN_EXPONENT} and {@link Float#MAX_EXPONENT}, the - * answer is calculated exactly. If the exponent of the result - * would be larger than {@code Float.MAX_EXPONENT}, an - * infinity is returned. Note that if the result is subnormal, - * precision may be lost; that is, when {@code scalb(x, n)} - * is subnormal, {@code scalb(scalb(x, n), -n)} may not equal - * x. When the result is non-NaN, the result has the same - * sign as {@code f}. - * - *

Special cases: - *

    - *
  • If the first argument is NaN, NaN is returned. - *
  • If the first argument is infinite, then an infinity of the - * same sign is returned. - *
  • If the first argument is zero, then a zero of the same - * sign is returned. - *
- * - * @param f number to be scaled by a power of two. - * @param scaleFactor power of 2 used to scale {@code f} - * @return {@code f} × 2{@code scaleFactor} - * @since 1.6 - */ -// public static float scalb(float f, int scaleFactor) { -// return sun.misc.FpUtils.scalb(f, scaleFactor); -// } -} diff -r 388e48c0a37a -r 05224402145d emul/src/main/java/java/lang/NegativeArraySizeException.java --- a/emul/src/main/java/java/lang/NegativeArraySizeException.java Wed Jan 23 20:16:48 2013 +0100 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,55 +0,0 @@ -/* - * Copyright (c) 1994, 2008, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code 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 - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package java.lang; - -/** - * Thrown if an application tries to create an array with negative size. - * - * @author unascribed - * @since JDK1.0 - */ -public -class NegativeArraySizeException extends RuntimeException { - private static final long serialVersionUID = -8960118058596991861L; - - /** - * Constructs a NegativeArraySizeException with no - * detail message. - */ - public NegativeArraySizeException() { - super(); - } - - /** - * Constructs a NegativeArraySizeException with the - * specified detail message. - * - * @param s the detail message. - */ - public NegativeArraySizeException(String s) { - super(s); - } -} diff -r 388e48c0a37a -r 05224402145d emul/src/main/java/java/lang/NoSuchMethodException.java --- a/emul/src/main/java/java/lang/NoSuchMethodException.java Wed Jan 23 20:16:48 2013 +0100 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,53 +0,0 @@ -/* - * Copyright (c) 1995, 2008, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code 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 - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package java.lang; - -/** - * Thrown when a particular method cannot be found. - * - * @author unascribed - * @since JDK1.0 - */ -public -class NoSuchMethodException extends ReflectiveOperationException { - private static final long serialVersionUID = 5034388446362600923L; - - /** - * Constructs a NoSuchMethodException without a detail message. - */ - public NoSuchMethodException() { - super(); - } - - /** - * Constructs a NoSuchMethodException with a detail message. - * - * @param s the detail message. - */ - public NoSuchMethodException(String s) { - super(s); - } -} diff -r 388e48c0a37a -r 05224402145d emul/src/main/java/java/lang/NullPointerException.java --- a/emul/src/main/java/java/lang/NullPointerException.java Wed Jan 23 20:16:48 2013 +0100 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,72 +0,0 @@ -/* - * Copyright (c) 1994, 2011, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code 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 - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package java.lang; - -/** - * Thrown when an application attempts to use {@code null} in a - * case where an object is required. These include: - *
    - *
  • Calling the instance method of a {@code null} object. - *
  • Accessing or modifying the field of a {@code null} object. - *
  • Taking the length of {@code null} as if it were an array. - *
  • Accessing or modifying the slots of {@code null} as if it - * were an array. - *
  • Throwing {@code null} as if it were a {@code Throwable} - * value. - *
- *

- * Applications should throw instances of this class to indicate - * other illegal uses of the {@code null} object. - * - * {@code NullPointerException} objects may be constructed by the - * virtual machine as if {@linkplain Throwable#Throwable(String, - * Throwable, boolean, boolean) suppression were disabled and/or the - * stack trace was not writable}. - * - * @author unascribed - * @since JDK1.0 - */ -public -class NullPointerException extends RuntimeException { - private static final long serialVersionUID = 5162710183389028792L; - - /** - * Constructs a {@code NullPointerException} with no detail message. - */ - public NullPointerException() { - super(); - } - - /** - * Constructs a {@code NullPointerException} with the specified - * detail message. - * - * @param s the detail message. - */ - public NullPointerException(String s) { - super(s); - } -} diff -r 388e48c0a37a -r 05224402145d emul/src/main/java/java/lang/Number.java --- a/emul/src/main/java/java/lang/Number.java Wed Jan 23 20:16:48 2013 +0100 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,118 +0,0 @@ -/* - * Copyright (c) 1994, 2001, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code 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 - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package java.lang; - -import org.apidesign.bck2brwsr.core.ExtraJavaScript; - -/** - * The abstract class Number is the superclass of classes - * BigDecimal, BigInteger, - * Byte, Double, Float, - * Integer, Long, and Short. - *

- * Subclasses of Number must provide methods to convert - * the represented numeric value to byte, double, - * float, int, long, and - * short. - * - * @author Lee Boynton - * @author Arthur van Hoff - * @see java.lang.Byte - * @see java.lang.Double - * @see java.lang.Float - * @see java.lang.Integer - * @see java.lang.Long - * @see java.lang.Short - * @since JDK1.0 - */ -@ExtraJavaScript( - resource="/org/apidesign/vm4brwsr/emul/java_lang_Number.js", - processByteCode=true -) -public abstract class Number implements java.io.Serializable { - /** - * Returns the value of the specified number as an int. - * This may involve rounding or truncation. - * - * @return the numeric value represented by this object after conversion - * to type int. - */ - public abstract int intValue(); - - /** - * Returns the value of the specified number as a long. - * This may involve rounding or truncation. - * - * @return the numeric value represented by this object after conversion - * to type long. - */ - public abstract long longValue(); - - /** - * Returns the value of the specified number as a float. - * This may involve rounding. - * - * @return the numeric value represented by this object after conversion - * to type float. - */ - public abstract float floatValue(); - - /** - * Returns the value of the specified number as a double. - * This may involve rounding. - * - * @return the numeric value represented by this object after conversion - * to type double. - */ - public abstract double doubleValue(); - - /** - * Returns the value of the specified number as a byte. - * This may involve rounding or truncation. - * - * @return the numeric value represented by this object after conversion - * to type byte. - * @since JDK1.1 - */ - public byte byteValue() { - return (byte)intValue(); - } - - /** - * Returns the value of the specified number as a short. - * This may involve rounding or truncation. - * - * @return the numeric value represented by this object after conversion - * to type short. - * @since JDK1.1 - */ - public short shortValue() { - return (short)intValue(); - } - - /** use serialVersionUID from JDK 1.0.2 for interoperability */ - private static final long serialVersionUID = -8742448824652078965L; -} diff -r 388e48c0a37a -r 05224402145d emul/src/main/java/java/lang/NumberFormatException.java --- a/emul/src/main/java/java/lang/NumberFormatException.java Wed Jan 23 20:16:48 2013 +0100 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,67 +0,0 @@ -/* - * Copyright (c) 1994, 2001, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code 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 - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package java.lang; - -/** - * Thrown to indicate that the application has attempted to convert - * a string to one of the numeric types, but that the string does not - * have the appropriate format. - * - * @author unascribed - * @see java.lang.Integer#toString() - * @since JDK1.0 - */ -public -class NumberFormatException extends IllegalArgumentException { - static final long serialVersionUID = -2848938806368998894L; - - /** - * Constructs a NumberFormatException with no detail message. - */ - public NumberFormatException () { - super(); - } - - /** - * Constructs a NumberFormatException with the - * specified detail message. - * - * @param s the detail message. - */ - public NumberFormatException (String s) { - super (s); - } - - /** - * Factory method for making a NumberFormatException - * given the specified input which caused the error. - * - * @param s the input causing the error - */ - static NumberFormatException forInputString(String s) { - return new NumberFormatException("For input string: \"" + s + "\""); - } -} diff -r 388e48c0a37a -r 05224402145d emul/src/main/java/java/lang/Object.java --- a/emul/src/main/java/java/lang/Object.java Wed Jan 23 20:16:48 2013 +0100 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,595 +0,0 @@ -/* - * Copyright (c) 1994, 2010, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code 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 - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package java.lang; - -import java.lang.reflect.Array; -import org.apidesign.bck2brwsr.core.JavaScriptBody; -import org.apidesign.bck2brwsr.core.JavaScriptPrototype; - -/** - * Class {@code Object} is the root of the class hierarchy. - * Every class has {@code Object} as a superclass. All objects, - * including arrays, implement the methods of this class. - * - * @author unascribed - * @see java.lang.Class - * @since JDK1.0 - */ -@JavaScriptPrototype(container = "Object.prototype", prototype = "new Object") -public class Object { - - private static void registerNatives() { - try { - Array.get(null, 0); - } catch (Throwable ex) { - // ignore - } - } - static { - registerNatives(); - } - - /** - * Returns the runtime class of this {@code Object}. The returned - * {@code Class} object is the object that is locked by {@code - * static synchronized} methods of the represented class. - * - *

The actual result type is {@code Class} - * where {@code |X|} is the erasure of the static type of the - * expression on which {@code getClass} is called. For - * example, no cast is required in this code fragment:

- * - *

- * {@code Number n = 0; }
- * {@code Class c = n.getClass(); } - *

- * - * @return The {@code Class} object that represents the runtime - * class of this object. - * @see Class Literals, section 15.8.2 of - * The Java™ Language Specification. - */ - @JavaScriptBody(args={}, body="return this.constructor.$class;") - public final native Class getClass(); - - /** - * Returns a hash code value for the object. This method is - * supported for the benefit of hash tables such as those provided by - * {@link java.util.HashMap}. - *

- * The general contract of {@code hashCode} is: - *

    - *
  • Whenever it is invoked on the same object more than once during - * an execution of a Java application, the {@code hashCode} method - * must consistently return the same integer, provided no information - * used in {@code equals} comparisons on the object is modified. - * This integer need not remain consistent from one execution of an - * application to another execution of the same application. - *
  • If two objects are equal according to the {@code equals(Object)} - * method, then calling the {@code hashCode} method on each of - * the two objects must produce the same integer result. - *
  • It is not required that if two objects are unequal - * according to the {@link java.lang.Object#equals(java.lang.Object)} - * method, then calling the {@code hashCode} method on each of the - * two objects must produce distinct integer results. However, the - * programmer should be aware that producing distinct integer results - * for unequal objects may improve the performance of hash tables. - *
- *

- * As much as is reasonably practical, the hashCode method defined by - * class {@code Object} does return distinct integers for distinct - * objects. (This is typically implemented by converting the internal - * address of the object into an integer, but this implementation - * technique is not required by the - * JavaTM programming language.) - * - * @return a hash code value for this object. - * @see java.lang.Object#equals(java.lang.Object) - * @see java.lang.System#identityHashCode - */ - @JavaScriptBody(args = {}, body = - "if (this.$hashCode) return this.$hashCode;\n" - + "var h = this.computeHashCode__I();\n" - + "return this.$hashCode = h & h;" - ) - public native int hashCode(); - - @JavaScriptBody(args = {}, body = "Math.random() * Math.pow(2, 32);") - native int computeHashCode(); - - /** - * Indicates whether some other object is "equal to" this one. - *

- * The {@code equals} method implements an equivalence relation - * on non-null object references: - *

    - *
  • It is reflexive: for any non-null reference value - * {@code x}, {@code x.equals(x)} should return - * {@code true}. - *
  • It is symmetric: for any non-null reference values - * {@code x} and {@code y}, {@code x.equals(y)} - * should return {@code true} if and only if - * {@code y.equals(x)} returns {@code true}. - *
  • It is transitive: for any non-null reference values - * {@code x}, {@code y}, and {@code z}, if - * {@code x.equals(y)} returns {@code true} and - * {@code y.equals(z)} returns {@code true}, then - * {@code x.equals(z)} should return {@code true}. - *
  • It is consistent: for any non-null reference values - * {@code x} and {@code y}, multiple invocations of - * {@code x.equals(y)} consistently return {@code true} - * or consistently return {@code false}, provided no - * information used in {@code equals} comparisons on the - * objects is modified. - *
  • For any non-null reference value {@code x}, - * {@code x.equals(null)} should return {@code false}. - *
- *

- * The {@code equals} method for class {@code Object} implements - * the most discriminating possible equivalence relation on objects; - * that is, for any non-null reference values {@code x} and - * {@code y}, this method returns {@code true} if and only - * if {@code x} and {@code y} refer to the same object - * ({@code x == y} has the value {@code true}). - *

- * Note that it is generally necessary to override the {@code hashCode} - * method whenever this method is overridden, so as to maintain the - * general contract for the {@code hashCode} method, which states - * that equal objects must have equal hash codes. - * - * @param obj the reference object with which to compare. - * @return {@code true} if this object is the same as the obj - * argument; {@code false} otherwise. - * @see #hashCode() - * @see java.util.HashMap - */ - public boolean equals(Object obj) { - return (this == obj); - } - - /** - * Creates and returns a copy of this object. The precise meaning - * of "copy" may depend on the class of the object. The general - * intent is that, for any object {@code x}, the expression: - *

- *
-     * x.clone() != x
- * will be true, and that the expression: - *
- *
-     * x.clone().getClass() == x.getClass()
- * will be {@code true}, but these are not absolute requirements. - * While it is typically the case that: - *
- *
-     * x.clone().equals(x)
- * will be {@code true}, this is not an absolute requirement. - *

- * By convention, the returned object should be obtained by calling - * {@code super.clone}. If a class and all of its superclasses (except - * {@code Object}) obey this convention, it will be the case that - * {@code x.clone().getClass() == x.getClass()}. - *

- * By convention, the object returned by this method should be independent - * of this object (which is being cloned). To achieve this independence, - * it may be necessary to modify one or more fields of the object returned - * by {@code super.clone} before returning it. Typically, this means - * copying any mutable objects that comprise the internal "deep structure" - * of the object being cloned and replacing the references to these - * objects with references to the copies. If a class contains only - * primitive fields or references to immutable objects, then it is usually - * the case that no fields in the object returned by {@code super.clone} - * need to be modified. - *

- * The method {@code clone} for class {@code Object} performs a - * specific cloning operation. First, if the class of this object does - * not implement the interface {@code Cloneable}, then a - * {@code CloneNotSupportedException} is thrown. Note that all arrays - * are considered to implement the interface {@code Cloneable} and that - * the return type of the {@code clone} method of an array type {@code T[]} - * is {@code T[]} where T is any reference or primitive type. - * Otherwise, this method creates a new instance of the class of this - * object and initializes all its fields with exactly the contents of - * the corresponding fields of this object, as if by assignment; the - * contents of the fields are not themselves cloned. Thus, this method - * performs a "shallow copy" of this object, not a "deep copy" operation. - *

- * The class {@code Object} does not itself implement the interface - * {@code Cloneable}, so calling the {@code clone} method on an object - * whose class is {@code Object} will result in throwing an - * exception at run time. - * - * @return a clone of this instance. - * @exception CloneNotSupportedException if the object's class does not - * support the {@code Cloneable} interface. Subclasses - * that override the {@code clone} method can also - * throw this exception to indicate that an instance cannot - * be cloned. - * @see java.lang.Cloneable - */ - protected Object clone() throws CloneNotSupportedException { - Object ret = clone(this); - if (ret == null) { - throw new CloneNotSupportedException(getClass().getName()); - } - return ret; - } - - @JavaScriptBody(args = "self", body = - "\nif (!self.$instOf_java_lang_Cloneable) {" - + "\n return null;" - + "\n} else {" - + "\n var clone = self.constructor(true);" - + "\n var props = Object.getOwnPropertyNames(self);" - + "\n for (var i = 0; i < props.length; i++) {" - + "\n var p = props[i];" - + "\n clone[p] = self[p];" - + "\n };" - + "\n return clone;" - + "\n}" - ) - private static native Object clone(Object self) throws CloneNotSupportedException; - - /** - * Returns a string representation of the object. In general, the - * {@code toString} method returns a string that - * "textually represents" this object. The result should - * be a concise but informative representation that is easy for a - * person to read. - * It is recommended that all subclasses override this method. - *

- * The {@code toString} method for class {@code Object} - * returns a string consisting of the name of the class of which the - * object is an instance, the at-sign character `{@code @}', and - * the unsigned hexadecimal representation of the hash code of the - * object. In other words, this method returns a string equal to the - * value of: - *

- *
-     * getClass().getName() + '@' + Integer.toHexString(hashCode())
-     * 
- * - * @return a string representation of the object. - */ - public String toString() { - return getClass().getName() + "@" + Integer.toHexString(hashCode()); - } - - /** - * Wakes up a single thread that is waiting on this object's - * monitor. If any threads are waiting on this object, one of them - * is chosen to be awakened. The choice is arbitrary and occurs at - * the discretion of the implementation. A thread waits on an object's - * monitor by calling one of the {@code wait} methods. - *

- * The awakened thread will not be able to proceed until the current - * thread relinquishes the lock on this object. The awakened thread will - * compete in the usual manner with any other threads that might be - * actively competing to synchronize on this object; for example, the - * awakened thread enjoys no reliable privilege or disadvantage in being - * the next thread to lock this object. - *

- * This method should only be called by a thread that is the owner - * of this object's monitor. A thread becomes the owner of the - * object's monitor in one of three ways: - *

    - *
  • By executing a synchronized instance method of that object. - *
  • By executing the body of a {@code synchronized} statement - * that synchronizes on the object. - *
  • For objects of type {@code Class,} by executing a - * synchronized static method of that class. - *
- *

- * Only one thread at a time can own an object's monitor. - * - * @exception IllegalMonitorStateException if the current thread is not - * the owner of this object's monitor. - * @see java.lang.Object#notifyAll() - * @see java.lang.Object#wait() - */ - public final native void notify(); - - /** - * Wakes up all threads that are waiting on this object's monitor. A - * thread waits on an object's monitor by calling one of the - * {@code wait} methods. - *

- * The awakened threads will not be able to proceed until the current - * thread relinquishes the lock on this object. The awakened threads - * will compete in the usual manner with any other threads that might - * be actively competing to synchronize on this object; for example, - * the awakened threads enjoy no reliable privilege or disadvantage in - * being the next thread to lock this object. - *

- * This method should only be called by a thread that is the owner - * of this object's monitor. See the {@code notify} method for a - * description of the ways in which a thread can become the owner of - * a monitor. - * - * @exception IllegalMonitorStateException if the current thread is not - * the owner of this object's monitor. - * @see java.lang.Object#notify() - * @see java.lang.Object#wait() - */ - public final native void notifyAll(); - - /** - * Causes the current thread to wait until either another thread invokes the - * {@link java.lang.Object#notify()} method or the - * {@link java.lang.Object#notifyAll()} method for this object, or a - * specified amount of time has elapsed. - *

- * The current thread must own this object's monitor. - *

- * This method causes the current thread (call it T) to - * place itself in the wait set for this object and then to relinquish - * any and all synchronization claims on this object. Thread T - * becomes disabled for thread scheduling purposes and lies dormant - * until one of four things happens: - *

    - *
  • Some other thread invokes the {@code notify} method for this - * object and thread T happens to be arbitrarily chosen as - * the thread to be awakened. - *
  • Some other thread invokes the {@code notifyAll} method for this - * object. - *
  • Some other thread {@linkplain Thread#interrupt() interrupts} - * thread T. - *
  • The specified amount of real time has elapsed, more or less. If - * {@code timeout} is zero, however, then real time is not taken into - * consideration and the thread simply waits until notified. - *
- * The thread T is then removed from the wait set for this - * object and re-enabled for thread scheduling. It then competes in the - * usual manner with other threads for the right to synchronize on the - * object; once it has gained control of the object, all its - * synchronization claims on the object are restored to the status quo - * ante - that is, to the situation as of the time that the {@code wait} - * method was invoked. Thread T then returns from the - * invocation of the {@code wait} method. Thus, on return from the - * {@code wait} method, the synchronization state of the object and of - * thread {@code T} is exactly as it was when the {@code wait} method - * was invoked. - *

- * A thread can also wake up without being notified, interrupted, or - * timing out, a so-called spurious wakeup. While this will rarely - * occur in practice, applications must guard against it by testing for - * the condition that should have caused the thread to be awakened, and - * continuing to wait if the condition is not satisfied. In other words, - * waits should always occur in loops, like this one: - *

-     *     synchronized (obj) {
-     *         while (<condition does not hold>)
-     *             obj.wait(timeout);
-     *         ... // Perform action appropriate to condition
-     *     }
-     * 
- * (For more information on this topic, see Section 3.2.3 in Doug Lea's - * "Concurrent Programming in Java (Second Edition)" (Addison-Wesley, - * 2000), or Item 50 in Joshua Bloch's "Effective Java Programming - * Language Guide" (Addison-Wesley, 2001). - * - *

If the current thread is {@linkplain java.lang.Thread#interrupt() - * interrupted} by any thread before or while it is waiting, then an - * {@code InterruptedException} is thrown. This exception is not - * thrown until the lock status of this object has been restored as - * described above. - * - *

- * Note that the {@code wait} method, as it places the current thread - * into the wait set for this object, unlocks only this object; any - * other objects on which the current thread may be synchronized remain - * locked while the thread waits. - *

- * This method should only be called by a thread that is the owner - * of this object's monitor. See the {@code notify} method for a - * description of the ways in which a thread can become the owner of - * a monitor. - * - * @param timeout the maximum time to wait in milliseconds. - * @exception IllegalArgumentException if the value of timeout is - * negative. - * @exception IllegalMonitorStateException if the current thread is not - * the owner of the object's monitor. - * @exception InterruptedException if any thread interrupted the - * current thread before or while the current thread - * was waiting for a notification. The interrupted - * status of the current thread is cleared when - * this exception is thrown. - * @see java.lang.Object#notify() - * @see java.lang.Object#notifyAll() - */ - public final native void wait(long timeout) throws InterruptedException; - - /** - * Causes the current thread to wait until another thread invokes the - * {@link java.lang.Object#notify()} method or the - * {@link java.lang.Object#notifyAll()} method for this object, or - * some other thread interrupts the current thread, or a certain - * amount of real time has elapsed. - *

- * This method is similar to the {@code wait} method of one - * argument, but it allows finer control over the amount of time to - * wait for a notification before giving up. The amount of real time, - * measured in nanoseconds, is given by: - *

- *
-     * 1000000*timeout+nanos
- *

- * In all other respects, this method does the same thing as the - * method {@link #wait(long)} of one argument. In particular, - * {@code wait(0, 0)} means the same thing as {@code wait(0)}. - *

- * The current thread must own this object's monitor. The thread - * releases ownership of this monitor and waits until either of the - * following two conditions has occurred: - *

    - *
  • Another thread notifies threads waiting on this object's monitor - * to wake up either through a call to the {@code notify} method - * or the {@code notifyAll} method. - *
  • The timeout period, specified by {@code timeout} - * milliseconds plus {@code nanos} nanoseconds arguments, has - * elapsed. - *
- *

- * The thread then waits until it can re-obtain ownership of the - * monitor and resumes execution. - *

- * As in the one argument version, interrupts and spurious wakeups are - * possible, and this method should always be used in a loop: - *

-     *     synchronized (obj) {
-     *         while (<condition does not hold>)
-     *             obj.wait(timeout, nanos);
-     *         ... // Perform action appropriate to condition
-     *     }
-     * 
- * This method should only be called by a thread that is the owner - * of this object's monitor. See the {@code notify} method for a - * description of the ways in which a thread can become the owner of - * a monitor. - * - * @param timeout the maximum time to wait in milliseconds. - * @param nanos additional time, in nanoseconds range - * 0-999999. - * @exception IllegalArgumentException if the value of timeout is - * negative or the value of nanos is - * not in the range 0-999999. - * @exception IllegalMonitorStateException if the current thread is not - * the owner of this object's monitor. - * @exception InterruptedException if any thread interrupted the - * current thread before or while the current thread - * was waiting for a notification. The interrupted - * status of the current thread is cleared when - * this exception is thrown. - */ - public final void wait(long timeout, int nanos) throws InterruptedException { - if (timeout < 0) { - throw new IllegalArgumentException("timeout value is negative"); - } - - if (nanos < 0 || nanos > 999999) { - throw new IllegalArgumentException( - "nanosecond timeout value out of range"); - } - - if (nanos >= 500000 || (nanos != 0 && timeout == 0)) { - timeout++; - } - - wait(timeout); - } - - /** - * Causes the current thread to wait until another thread invokes the - * {@link java.lang.Object#notify()} method or the - * {@link java.lang.Object#notifyAll()} method for this object. - * In other words, this method behaves exactly as if it simply - * performs the call {@code wait(0)}. - *

- * The current thread must own this object's monitor. The thread - * releases ownership of this monitor and waits until another thread - * notifies threads waiting on this object's monitor to wake up - * either through a call to the {@code notify} method or the - * {@code notifyAll} method. The thread then waits until it can - * re-obtain ownership of the monitor and resumes execution. - *

- * As in the one argument version, interrupts and spurious wakeups are - * possible, and this method should always be used in a loop: - *

-     *     synchronized (obj) {
-     *         while (<condition does not hold>)
-     *             obj.wait();
-     *         ... // Perform action appropriate to condition
-     *     }
-     * 
- * This method should only be called by a thread that is the owner - * of this object's monitor. See the {@code notify} method for a - * description of the ways in which a thread can become the owner of - * a monitor. - * - * @exception IllegalMonitorStateException if the current thread is not - * the owner of the object's monitor. - * @exception InterruptedException if any thread interrupted the - * current thread before or while the current thread - * was waiting for a notification. The interrupted - * status of the current thread is cleared when - * this exception is thrown. - * @see java.lang.Object#notify() - * @see java.lang.Object#notifyAll() - */ - public final void wait() throws InterruptedException { - wait(0); - } - - /** - * Called by the garbage collector on an object when garbage collection - * determines that there are no more references to the object. - * A subclass overrides the {@code finalize} method to dispose of - * system resources or to perform other cleanup. - *

- * The general contract of {@code finalize} is that it is invoked - * if and when the JavaTM virtual - * machine has determined that there is no longer any - * means by which this object can be accessed by any thread that has - * not yet died, except as a result of an action taken by the - * finalization of some other object or class which is ready to be - * finalized. The {@code finalize} method may take any action, including - * making this object available again to other threads; the usual purpose - * of {@code finalize}, however, is to perform cleanup actions before - * the object is irrevocably discarded. For example, the finalize method - * for an object that represents an input/output connection might perform - * explicit I/O transactions to break the connection before the object is - * permanently discarded. - *

- * The {@code finalize} method of class {@code Object} performs no - * special action; it simply returns normally. Subclasses of - * {@code Object} may override this definition. - *

- * The Java programming language does not guarantee which thread will - * invoke the {@code finalize} method for any given object. It is - * guaranteed, however, that the thread that invokes finalize will not - * be holding any user-visible synchronization locks when finalize is - * invoked. If an uncaught exception is thrown by the finalize method, - * the exception is ignored and finalization of that object terminates. - *

- * After the {@code finalize} method has been invoked for an object, no - * further action is taken until the Java virtual machine has again - * determined that there is no longer any means by which this object can - * be accessed by any thread that has not yet died, including possible - * actions by other objects or classes which are ready to be finalized, - * at which point the object may be discarded. - *

- * The {@code finalize} method is never invoked more than once by a Java - * virtual machine for any given object. - *

- * Any exception thrown by the {@code finalize} method causes - * the finalization of this object to be halted, but is otherwise - * ignored. - * - * @throws Throwable the {@code Exception} raised by this method - */ - protected void finalize() throws Throwable { } -} diff -r 388e48c0a37a -r 05224402145d emul/src/main/java/java/lang/OutOfMemoryError.java --- a/emul/src/main/java/java/lang/OutOfMemoryError.java Wed Jan 23 20:16:48 2013 +0100 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,60 +0,0 @@ -/* - * Copyright (c) 1994, 2011, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code 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 - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package java.lang; - -/** - * Thrown when the Java Virtual Machine cannot allocate an object - * because it is out of memory, and no more memory could be made - * available by the garbage collector. - * - * {@code OutOfMemoryError} objects may be constructed by the virtual - * machine as if {@linkplain Throwable#Throwable(String, Throwable, - * boolean, boolean) suppression were disabled and/or the stack trace was not - * writable}. - * - * @author unascribed - * @since JDK1.0 - */ -public class OutOfMemoryError extends VirtualMachineError { - private static final long serialVersionUID = 8228564086184010517L; - - /** - * Constructs an {@code OutOfMemoryError} with no detail message. - */ - public OutOfMemoryError() { - super(); - } - - /** - * Constructs an {@code OutOfMemoryError} with the specified - * detail message. - * - * @param s the detail message. - */ - public OutOfMemoryError(String s) { - super(s); - } -} diff -r 388e48c0a37a -r 05224402145d emul/src/main/java/java/lang/ReflectiveOperationException.java --- a/emul/src/main/java/java/lang/ReflectiveOperationException.java Wed Jan 23 20:16:48 2013 +0100 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,91 +0,0 @@ -/* - * Copyright (c) 2009, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code 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 - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package java.lang; - -/** - * Common superclass of exceptions thrown by reflective operations in - * core reflection. - * - * @see LinkageError - * @since 1.7 - */ -public class ReflectiveOperationException extends Exception { - static final long serialVersionUID = 123456789L; - - /** - * Constructs a new exception with {@code null} as its detail - * message. The cause is not initialized, and may subsequently be - * initialized by a call to {@link #initCause}. - */ - public ReflectiveOperationException() { - super(); - } - - /** - * Constructs a new exception with the specified detail message. - * The cause is not initialized, and may subsequently be - * initialized by a call to {@link #initCause}. - * - * @param message the detail message. The detail message is saved for - * later retrieval by the {@link #getMessage()} method. - */ - public ReflectiveOperationException(String message) { - super(message); - } - - /** - * Constructs a new exception with the specified detail message - * and cause. - * - *

Note that the detail message associated with - * {@code cause} is not automatically incorporated in - * this exception's detail message. - * - * @param message the detail message (which is saved for later retrieval - * by the {@link #getMessage()} method). - * @param cause the cause (which is saved for later retrieval by the - * {@link #getCause()} method). (A {@code null} value is - * permitted, and indicates that the cause is nonexistent or - * unknown.) - */ - public ReflectiveOperationException(String message, Throwable cause) { - super(message, cause); - } - - /** - * Constructs a new exception with the specified cause and a detail - * message of {@code (cause==null ? null : cause.toString())} (which - * typically contains the class and detail message of {@code cause}). - * - * @param cause the cause (which is saved for later retrieval by the - * {@link #getCause()} method). (A {@code null} value is - * permitted, and indicates that the cause is nonexistent or - * unknown.) - */ - public ReflectiveOperationException(Throwable cause) { - super(cause); - } -} diff -r 388e48c0a37a -r 05224402145d emul/src/main/java/java/lang/Runnable.java --- a/emul/src/main/java/java/lang/Runnable.java Wed Jan 23 20:16:48 2013 +0100 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,69 +0,0 @@ -/* - * Copyright (c) 1994, 2005, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code 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 - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package java.lang; - -/** - * The Runnable interface should be implemented by any - * class whose instances are intended to be executed by a thread. The - * class must define a method of no arguments called run. - *

- * This interface is designed to provide a common protocol for objects that - * wish to execute code while they are active. For example, - * Runnable is implemented by class Thread. - * Being active simply means that a thread has been started and has not - * yet been stopped. - *

- * In addition, Runnable provides the means for a class to be - * active while not subclassing Thread. A class that implements - * Runnable can run without subclassing Thread - * by instantiating a Thread instance and passing itself in - * as the target. In most cases, the Runnable interface should - * be used if you are only planning to override the run() - * method and no other Thread methods. - * This is important because classes should not be subclassed - * unless the programmer intends on modifying or enhancing the fundamental - * behavior of the class. - * - * @author Arthur van Hoff - * @see java.lang.Thread - * @see java.util.concurrent.Callable - * @since JDK1.0 - */ -public -interface Runnable { - /** - * When an object implementing interface Runnable is used - * to create a thread, starting the thread causes the object's - * run method to be called in that separately executing - * thread. - *

- * The general contract of the method run is that it may - * take any action whatsoever. - * - * @see java.lang.Thread#run() - */ - public abstract void run(); -} diff -r 388e48c0a37a -r 05224402145d emul/src/main/java/java/lang/RuntimeException.java --- a/emul/src/main/java/java/lang/RuntimeException.java Wed Jan 23 20:16:48 2013 +0100 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,119 +0,0 @@ -/* - * Copyright (c) 1995, 2011, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code 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 - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package java.lang; - -/** - * {@code RuntimeException} is the superclass of those - * exceptions that can be thrown during the normal operation of the - * Java Virtual Machine. - * - *

{@code RuntimeException} and its subclasses are unchecked - * exceptions. Unchecked exceptions do not need to be - * declared in a method or constructor's {@code throws} clause if they - * can be thrown by the execution of the method or constructor and - * propagate outside the method or constructor boundary. - * - * @author Frank Yellin - * @jls 11.2 Compile-Time Checking of Exceptions - * @since JDK1.0 - */ -public class RuntimeException extends Exception { - static final long serialVersionUID = -7034897190745766939L; - - /** Constructs a new runtime exception with {@code null} as its - * detail message. The cause is not initialized, and may subsequently be - * initialized by a call to {@link #initCause}. - */ - public RuntimeException() { - super(); - } - - /** Constructs a new runtime exception with the specified detail message. - * The cause is not initialized, and may subsequently be initialized by a - * call to {@link #initCause}. - * - * @param message the detail message. The detail message is saved for - * later retrieval by the {@link #getMessage()} method. - */ - public RuntimeException(String message) { - super(message); - } - - /** - * Constructs a new runtime exception with the specified detail message and - * cause.

Note that the detail message associated with - * {@code cause} is not automatically incorporated in - * this runtime exception's detail message. - * - * @param message the detail message (which is saved for later retrieval - * by the {@link #getMessage()} method). - * @param cause the cause (which is saved for later retrieval by the - * {@link #getCause()} method). (A null value is - * permitted, and indicates that the cause is nonexistent or - * unknown.) - * @since 1.4 - */ - public RuntimeException(String message, Throwable cause) { - super(message, cause); - } - - /** Constructs a new runtime exception with the specified cause and a - * detail message of (cause==null ? null : cause.toString()) - * (which typically contains the class and detail message of - * cause). This constructor is useful for runtime exceptions - * that are little more than wrappers for other throwables. - * - * @param cause the cause (which is saved for later retrieval by the - * {@link #getCause()} method). (A null value is - * permitted, and indicates that the cause is nonexistent or - * unknown.) - * @since 1.4 - */ - public RuntimeException(Throwable cause) { - super(cause); - } - - /** - * Constructs a new runtime exception with the specified detail - * message, cause, suppression enabled or disabled, and writable - * stack trace enabled or disabled. - * - * @param message the detail message. - * @param cause the cause. (A {@code null} value is permitted, - * and indicates that the cause is nonexistent or unknown.) - * @param enableSuppression whether or not suppression is enabled - * or disabled - * @param writableStackTrace whether or not the stack trace should - * be writable - * - * @since 1.7 - */ - protected RuntimeException(String message, Throwable cause, - boolean enableSuppression, - boolean writableStackTrace) { - super(message, cause, enableSuppression, writableStackTrace); - } -} diff -r 388e48c0a37a -r 05224402145d emul/src/main/java/java/lang/SecurityException.java --- a/emul/src/main/java/java/lang/SecurityException.java Wed Jan 23 20:16:48 2013 +0100 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,84 +0,0 @@ -/* - * Copyright (c) 1995, 2003, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code 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 - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ -package java.lang; - -/** - * Thrown by the security manager to indicate a security violation. - * - * @author unascribed - * @see java.lang.SecurityManager - * @since JDK1.0 - */ -public class SecurityException extends RuntimeException { - - private static final long serialVersionUID = 6878364983674394167L; - - /** - * Constructs a SecurityException with no detail message. - */ - public SecurityException() { - super(); - } - - /** - * Constructs a SecurityException with the specified - * detail message. - * - * @param s the detail message. - */ - public SecurityException(String s) { - super(s); - } - - /** - * Creates a SecurityException with the specified - * detail message and cause. - * - * @param message the detail message (which is saved for later retrieval - * by the {@link #getMessage()} method). - * @param cause the cause (which is saved for later retrieval by the - * {@link #getCause()} method). (A null value is permitted, - * and indicates that the cause is nonexistent or unknown.) - * @since 1.5 - */ - public SecurityException(String message, Throwable cause) { - super(message, cause); - } - - /** - * Creates a SecurityException with the specified cause - * and a detail message of (cause==null ? null : cause.toString()) - * (which typically contains the class and detail message of - * cause). - * - * @param cause the cause (which is saved for later retrieval by the - * {@link #getCause()} method). (A null value is permitted, - * and indicates that the cause is nonexistent or unknown.) - * @since 1.5 - */ - public SecurityException(Throwable cause) { - super(cause); - } -} diff -r 388e48c0a37a -r 05224402145d emul/src/main/java/java/lang/Short.java --- a/emul/src/main/java/java/lang/Short.java Wed Jan 23 20:16:48 2013 +0100 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,468 +0,0 @@ -/* - * Copyright (c) 1996, 2009, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code 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 - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package java.lang; - -/** - * The {@code Short} class wraps a value of primitive type {@code - * short} in an object. An object of type {@code Short} contains a - * single field whose type is {@code short}. - * - *

In addition, this class provides several methods for converting - * a {@code short} to a {@code String} and a {@code String} to a - * {@code short}, as well as other constants and methods useful when - * dealing with a {@code short}. - * - * @author Nakul Saraiya - * @author Joseph D. Darcy - * @see java.lang.Number - * @since JDK1.1 - */ -public final class Short extends Number implements Comparable { - - /** - * A constant holding the minimum value a {@code short} can - * have, -215. - */ - public static final short MIN_VALUE = -32768; - - /** - * A constant holding the maximum value a {@code short} can - * have, 215-1. - */ - public static final short MAX_VALUE = 32767; - - /** - * The {@code Class} instance representing the primitive type - * {@code short}. - */ - public static final Class TYPE = (Class) Class.getPrimitiveClass("short"); - - /** - * Returns a new {@code String} object representing the - * specified {@code short}. The radix is assumed to be 10. - * - * @param s the {@code short} to be converted - * @return the string representation of the specified {@code short} - * @see java.lang.Integer#toString(int) - */ - public static String toString(short s) { - return Integer.toString((int)s, 10); - } - - /** - * Parses the string argument as a signed {@code short} in the - * radix specified by the second argument. The characters in the - * string must all be digits, of the specified radix (as - * determined by whether {@link java.lang.Character#digit(char, - * int)} returns a nonnegative value) except that the first - * character may be an ASCII minus sign {@code '-'} - * ('\u002D') to indicate a negative value or an - * ASCII plus sign {@code '+'} ('\u002B') to - * indicate a positive value. The resulting {@code short} value - * is returned. - * - *

An exception of type {@code NumberFormatException} is - * thrown if any of the following situations occurs: - *

    - *
  • The first argument is {@code null} or is a string of - * length zero. - * - *
  • The radix is either smaller than {@link - * java.lang.Character#MIN_RADIX} or larger than {@link - * java.lang.Character#MAX_RADIX}. - * - *
  • Any character of the string is not a digit of the - * specified radix, except that the first character may be a minus - * sign {@code '-'} ('\u002D') or plus sign - * {@code '+'} ('\u002B') provided that the - * string is longer than length 1. - * - *
  • The value represented by the string is not a value of type - * {@code short}. - *
- * - * @param s the {@code String} containing the - * {@code short} representation to be parsed - * @param radix the radix to be used while parsing {@code s} - * @return the {@code short} represented by the string - * argument in the specified radix. - * @throws NumberFormatException If the {@code String} - * does not contain a parsable {@code short}. - */ - public static short parseShort(String s, int radix) - throws NumberFormatException { - int i = Integer.parseInt(s, radix); - if (i < MIN_VALUE || i > MAX_VALUE) - throw new NumberFormatException( - "Value out of range. Value:\"" + s + "\" Radix:" + radix); - return (short)i; - } - - /** - * Parses the string argument as a signed decimal {@code - * short}. The characters in the string must all be decimal - * digits, except that the first character may be an ASCII minus - * sign {@code '-'} ('\u002D') to indicate a - * negative value or an ASCII plus sign {@code '+'} - * ('\u002B') to indicate a positive value. The - * resulting {@code short} value is returned, exactly as if the - * argument and the radix 10 were given as arguments to the {@link - * #parseShort(java.lang.String, int)} method. - * - * @param s a {@code String} containing the {@code short} - * representation to be parsed - * @return the {@code short} value represented by the - * argument in decimal. - * @throws NumberFormatException If the string does not - * contain a parsable {@code short}. - */ - public static short parseShort(String s) throws NumberFormatException { - return parseShort(s, 10); - } - - /** - * Returns a {@code Short} object holding the value - * extracted from the specified {@code String} when parsed - * with the radix given by the second argument. The first argument - * is interpreted as representing a signed {@code short} in - * the radix specified by the second argument, exactly as if the - * argument were given to the {@link #parseShort(java.lang.String, - * int)} method. The result is a {@code Short} object that - * represents the {@code short} value specified by the string. - * - *

In other words, this method returns a {@code Short} object - * equal to the value of: - * - *

- * {@code new Short(Short.parseShort(s, radix))} - *
- * - * @param s the string to be parsed - * @param radix the radix to be used in interpreting {@code s} - * @return a {@code Short} object holding the value - * represented by the string argument in the - * specified radix. - * @throws NumberFormatException If the {@code String} does - * not contain a parsable {@code short}. - */ - public static Short valueOf(String s, int radix) - throws NumberFormatException { - return valueOf(parseShort(s, radix)); - } - - /** - * Returns a {@code Short} object holding the - * value given by the specified {@code String}. The argument - * is interpreted as representing a signed decimal - * {@code short}, exactly as if the argument were given to - * the {@link #parseShort(java.lang.String)} method. The result is - * a {@code Short} object that represents the - * {@code short} value specified by the string. - * - *

In other words, this method returns a {@code Short} object - * equal to the value of: - * - *

- * {@code new Short(Short.parseShort(s))} - *
- * - * @param s the string to be parsed - * @return a {@code Short} object holding the value - * represented by the string argument - * @throws NumberFormatException If the {@code String} does - * not contain a parsable {@code short}. - */ - public static Short valueOf(String s) throws NumberFormatException { - return valueOf(s, 10); - } - - private static class ShortCache { - private ShortCache(){} - - static final Short cache[] = new Short[-(-128) + 127 + 1]; - - static { - for(int i = 0; i < cache.length; i++) - cache[i] = new Short((short)(i - 128)); - } - } - - /** - * Returns a {@code Short} instance representing the specified - * {@code short} value. - * If a new {@code Short} instance is not required, this method - * should generally be used in preference to the constructor - * {@link #Short(short)}, as this method is likely to yield - * significantly better space and time performance by caching - * frequently requested values. - * - * This method will always cache values in the range -128 to 127, - * inclusive, and may cache other values outside of this range. - * - * @param s a short value. - * @return a {@code Short} instance representing {@code s}. - * @since 1.5 - */ - public static Short valueOf(short s) { - final int offset = 128; - int sAsInt = s; - if (sAsInt >= -128 && sAsInt <= 127) { // must cache - return ShortCache.cache[sAsInt + offset]; - } - return new Short(s); - } - - /** - * Decodes a {@code String} into a {@code Short}. - * Accepts decimal, hexadecimal, and octal numbers given by - * the following grammar: - * - *
- *
- *
DecodableString: - *
Signopt DecimalNumeral - *
Signopt {@code 0x} HexDigits - *
Signopt {@code 0X} HexDigits - *
Signopt {@code #} HexDigits - *
Signopt {@code 0} OctalDigits - *

- *

Sign: - *
{@code -} - *
{@code +} - *
- *
- * - * DecimalNumeral, HexDigits, and OctalDigits - * are as defined in section 3.10.1 of - * The Java™ Language Specification, - * except that underscores are not accepted between digits. - * - *

The sequence of characters following an optional - * sign and/or radix specifier ("{@code 0x}", "{@code 0X}", - * "{@code #}", or leading zero) is parsed as by the {@code - * Short.parseShort} method with the indicated radix (10, 16, or - * 8). This sequence of characters must represent a positive - * value or a {@link NumberFormatException} will be thrown. The - * result is negated if first character of the specified {@code - * String} is the minus sign. No whitespace characters are - * permitted in the {@code String}. - * - * @param nm the {@code String} to decode. - * @return a {@code Short} object holding the {@code short} - * value represented by {@code nm} - * @throws NumberFormatException if the {@code String} does not - * contain a parsable {@code short}. - * @see java.lang.Short#parseShort(java.lang.String, int) - */ - public static Short decode(String nm) throws NumberFormatException { - int i = Integer.decode(nm); - if (i < MIN_VALUE || i > MAX_VALUE) - throw new NumberFormatException( - "Value " + i + " out of range from input " + nm); - return valueOf((short)i); - } - - /** - * The value of the {@code Short}. - * - * @serial - */ - private final short value; - - /** - * Constructs a newly allocated {@code Short} object that - * represents the specified {@code short} value. - * - * @param value the value to be represented by the - * {@code Short}. - */ - public Short(short value) { - this.value = value; - } - - /** - * Constructs a newly allocated {@code Short} object that - * represents the {@code short} value indicated by the - * {@code String} parameter. The string is converted to a - * {@code short} value in exactly the manner used by the - * {@code parseShort} method for radix 10. - * - * @param s the {@code String} to be converted to a - * {@code Short} - * @throws NumberFormatException If the {@code String} - * does not contain a parsable {@code short}. - * @see java.lang.Short#parseShort(java.lang.String, int) - */ - public Short(String s) throws NumberFormatException { - this.value = parseShort(s, 10); - } - - /** - * Returns the value of this {@code Short} as a - * {@code byte}. - */ - public byte byteValue() { - return (byte)value; - } - - /** - * Returns the value of this {@code Short} as a - * {@code short}. - */ - public short shortValue() { - return value; - } - - /** - * Returns the value of this {@code Short} as an - * {@code int}. - */ - public int intValue() { - return (int)value; - } - - /** - * Returns the value of this {@code Short} as a - * {@code long}. - */ - public long longValue() { - return (long)value; - } - - /** - * Returns the value of this {@code Short} as a - * {@code float}. - */ - public float floatValue() { - return (float)value; - } - - /** - * Returns the value of this {@code Short} as a - * {@code double}. - */ - public double doubleValue() { - return (double)value; - } - - /** - * Returns a {@code String} object representing this - * {@code Short}'s value. The value is converted to signed - * decimal representation and returned as a string, exactly as if - * the {@code short} value were given as an argument to the - * {@link java.lang.Short#toString(short)} method. - * - * @return a string representation of the value of this object in - * base 10. - */ - public String toString() { - return Integer.toString((int)value); - } - - /** - * Returns a hash code for this {@code Short}; equal to the result - * of invoking {@code intValue()}. - * - * @return a hash code value for this {@code Short} - */ - public int hashCode() { - return (int)value; - } - - /** - * Compares this object to the specified object. The result is - * {@code true} if and only if the argument is not - * {@code null} and is a {@code Short} object that - * contains the same {@code short} value as this object. - * - * @param obj the object to compare with - * @return {@code true} if the objects are the same; - * {@code false} otherwise. - */ - public boolean equals(Object obj) { - if (obj instanceof Short) { - return value == ((Short)obj).shortValue(); - } - return false; - } - - /** - * Compares two {@code Short} objects numerically. - * - * @param anotherShort the {@code Short} to be compared. - * @return the value {@code 0} if this {@code Short} is - * equal to the argument {@code Short}; a value less than - * {@code 0} if this {@code Short} is numerically less - * than the argument {@code Short}; and a value greater than - * {@code 0} if this {@code Short} is numerically - * greater than the argument {@code Short} (signed - * comparison). - * @since 1.2 - */ - public int compareTo(Short anotherShort) { - return compare(this.value, anotherShort.value); - } - - /** - * Compares two {@code short} values numerically. - * The value returned is identical to what would be returned by: - *

-     *    Short.valueOf(x).compareTo(Short.valueOf(y))
-     * 
- * - * @param x the first {@code short} to compare - * @param y the second {@code short} to compare - * @return the value {@code 0} if {@code x == y}; - * a value less than {@code 0} if {@code x < y}; and - * a value greater than {@code 0} if {@code x > y} - * @since 1.7 - */ - public static int compare(short x, short y) { - return x - y; - } - - /** - * The number of bits used to represent a {@code short} value in two's - * complement binary form. - * @since 1.5 - */ - public static final int SIZE = 16; - - /** - * Returns the value obtained by reversing the order of the bytes in the - * two's complement representation of the specified {@code short} value. - * - * @return the value obtained by reversing (or, equivalently, swapping) - * the bytes in the specified {@code short} value. - * @since 1.5 - */ - public static short reverseBytes(short i) { - return (short) (((i & 0xFF00) >> 8) | (i << 8)); - } - - /** use serialVersionUID from JDK 1.1. for interoperability */ - private static final long serialVersionUID = 7515723908773894738L; -} diff -r 388e48c0a37a -r 05224402145d emul/src/main/java/java/lang/StackTraceElement.java --- a/emul/src/main/java/java/lang/StackTraceElement.java Wed Jan 23 20:16:48 2013 +0100 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,223 +0,0 @@ -/* - * Copyright (c) 2000, 2011, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code 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 - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package java.lang; - -/** - * An element in a stack trace, as returned by {@link - * Throwable#getStackTrace()}. Each element represents a single stack frame. - * All stack frames except for the one at the top of the stack represent - * a method invocation. The frame at the top of the stack represents the - * execution point at which the stack trace was generated. Typically, - * this is the point at which the throwable corresponding to the stack trace - * was created. - * - * @since 1.4 - * @author Josh Bloch - */ -public final class StackTraceElement implements java.io.Serializable { - // Normally initialized by VM (public constructor added in 1.5) - private String declaringClass; - private String methodName; - private String fileName; - private int lineNumber; - - /** - * Creates a stack trace element representing the specified execution - * point. - * - * @param declaringClass the fully qualified name of the class containing - * the execution point represented by the stack trace element - * @param methodName the name of the method containing the execution point - * represented by the stack trace element - * @param fileName the name of the file containing the execution point - * represented by the stack trace element, or {@code null} if - * this information is unavailable - * @param lineNumber the line number of the source line containing the - * execution point represented by this stack trace element, or - * a negative number if this information is unavailable. A value - * of -2 indicates that the method containing the execution point - * is a native method - * @throws NullPointerException if {@code declaringClass} or - * {@code methodName} is null - * @since 1.5 - */ - public StackTraceElement(String declaringClass, String methodName, - String fileName, int lineNumber) { - this.declaringClass = declaringClass; - this.methodName = methodName; - this.fileName = fileName; - this.lineNumber = lineNumber; - } - - /** - * Returns the name of the source file containing the execution point - * represented by this stack trace element. Generally, this corresponds - * to the {@code SourceFile} attribute of the relevant {@code class} - * file (as per The Java Virtual Machine Specification, Section - * 4.7.7). In some systems, the name may refer to some source code unit - * other than a file, such as an entry in source repository. - * - * @return the name of the file containing the execution point - * represented by this stack trace element, or {@code null} if - * this information is unavailable. - */ - public String getFileName() { - return fileName; - } - - /** - * Returns the line number of the source line containing the execution - * point represented by this stack trace element. Generally, this is - * derived from the {@code LineNumberTable} attribute of the relevant - * {@code class} file (as per The Java Virtual Machine - * Specification, Section 4.7.8). - * - * @return the line number of the source line containing the execution - * point represented by this stack trace element, or a negative - * number if this information is unavailable. - */ - public int getLineNumber() { - return lineNumber; - } - - /** - * Returns the fully qualified name of the class containing the - * execution point represented by this stack trace element. - * - * @return the fully qualified name of the {@code Class} containing - * the execution point represented by this stack trace element. - */ - public String getClassName() { - return declaringClass; - } - - /** - * Returns the name of the method containing the execution point - * represented by this stack trace element. If the execution point is - * contained in an instance or class initializer, this method will return - * the appropriate special method name, {@code } or - * {@code }, as per Section 3.9 of The Java Virtual - * Machine Specification. - * - * @return the name of the method containing the execution point - * represented by this stack trace element. - */ - public String getMethodName() { - return methodName; - } - - /** - * Returns true if the method containing the execution point - * represented by this stack trace element is a native method. - * - * @return {@code true} if the method containing the execution point - * represented by this stack trace element is a native method. - */ - public boolean isNativeMethod() { - return lineNumber == -2; - } - - /** - * Returns a string representation of this stack trace element. The - * format of this string depends on the implementation, but the following - * examples may be regarded as typical: - *
    - *
  • - * {@code "MyClass.mash(MyClass.java:9)"} - Here, {@code "MyClass"} - * is the fully-qualified name of the class containing the - * execution point represented by this stack trace element, - * {@code "mash"} is the name of the method containing the execution - * point, {@code "MyClass.java"} is the source file containing the - * execution point, and {@code "9"} is the line number of the source - * line containing the execution point. - *
  • - * {@code "MyClass.mash(MyClass.java)"} - As above, but the line - * number is unavailable. - *
  • - * {@code "MyClass.mash(Unknown Source)"} - As above, but neither - * the file name nor the line number are available. - *
  • - * {@code "MyClass.mash(Native Method)"} - As above, but neither - * the file name nor the line number are available, and the method - * containing the execution point is known to be a native method. - *
- * @see Throwable#printStackTrace() - */ - public String toString() { - return getClassName() + "." + methodName + - (isNativeMethod() ? "(Native Method)" : - (fileName != null && lineNumber >= 0 ? - "(" + fileName + ":" + lineNumber + ")" : - (fileName != null ? "("+fileName+")" : "(Unknown Source)"))); - } - - /** - * Returns true if the specified object is another - * {@code StackTraceElement} instance representing the same execution - * point as this instance. Two stack trace elements {@code a} and - * {@code b} are equal if and only if: - *
-     *     equals(a.getFileName(), b.getFileName()) &&
-     *     a.getLineNumber() == b.getLineNumber()) &&
-     *     equals(a.getClassName(), b.getClassName()) &&
-     *     equals(a.getMethodName(), b.getMethodName())
-     * 
- * where {@code equals} has the semantics of {@link - * java.util.Objects#equals(Object, Object) Objects.equals}. - * - * @param obj the object to be compared with this stack trace element. - * @return true if the specified object is another - * {@code StackTraceElement} instance representing the same - * execution point as this instance. - */ - public boolean equals(Object obj) { - if (obj==this) - return true; - if (!(obj instanceof StackTraceElement)) - return false; - StackTraceElement e = (StackTraceElement)obj; - return e.declaringClass.equals(declaringClass) && - e.lineNumber == lineNumber && - equals(methodName, e.methodName) && - equals(fileName, e.fileName); - } - - /** - * Returns a hash code value for this stack trace element. - */ - public int hashCode() { - int result = 31*declaringClass.hashCode() + methodName.hashCode(); - result = 31*result + (fileName == null ? 0 : fileName.hashCode()); - result = 31*result + lineNumber; - return result; - } - - private static boolean equals(Object a, Object b) { - return (a == b) || (a != null && a.equals(b)); - } - - private static final long serialVersionUID = 6992337162326171013L; -} diff -r 388e48c0a37a -r 05224402145d emul/src/main/java/java/lang/String.java --- a/emul/src/main/java/java/lang/String.java Wed Jan 23 20:16:48 2013 +0100 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,3009 +0,0 @@ -/* - * Copyright (c) 1994, 2010, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code 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 - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package java.lang; - -import java.util.Comparator; -import org.apidesign.bck2brwsr.core.ExtraJavaScript; -import org.apidesign.bck2brwsr.core.JavaScriptBody; -import org.apidesign.bck2brwsr.core.JavaScriptOnly; -import org.apidesign.bck2brwsr.core.JavaScriptPrototype; - -/** - * The String class represents character strings. All - * string literals in Java programs, such as "abc", are - * implemented as instances of this class. - *

- * Strings are constant; their values cannot be changed after they - * are created. String buffers support mutable strings. - * Because String objects are immutable they can be shared. For example: - *

- *     String str = "abc";
- * 

- * is equivalent to: - *

- *     char data[] = {'a', 'b', 'c'};
- *     String str = new String(data);
- * 

- * Here are some more examples of how strings can be used: - *

- *     System.out.println("abc");
- *     String cde = "cde";
- *     System.out.println("abc" + cde);
- *     String c = "abc".substring(2,3);
- *     String d = cde.substring(1, 2);
- * 
- *

- * The class String includes methods for examining - * individual characters of the sequence, for comparing strings, for - * searching strings, for extracting substrings, and for creating a - * copy of a string with all characters translated to uppercase or to - * lowercase. Case mapping is based on the Unicode Standard version - * specified by the {@link java.lang.Character Character} class. - *

- * The Java language provides special support for the string - * concatenation operator ( + ), and for conversion of - * other objects to strings. String concatenation is implemented - * through the StringBuilder(or StringBuffer) - * class and its append method. - * String conversions are implemented through the method - * toString, defined by Object and - * inherited by all classes in Java. For additional information on - * string concatenation and conversion, see Gosling, Joy, and Steele, - * The Java Language Specification. - * - *

Unless otherwise noted, passing a null argument to a constructor - * or method in this class will cause a {@link NullPointerException} to be - * thrown. - * - *

A String represents a string in the UTF-16 format - * in which supplementary characters are represented by surrogate - * pairs (see the section Unicode - * Character Representations in the Character class for - * more information). - * Index values refer to char code units, so a supplementary - * character uses two positions in a String. - *

The String class provides methods for dealing with - * Unicode code points (i.e., characters), in addition to those for - * dealing with Unicode code units (i.e., char values). - * - * @author Lee Boynton - * @author Arthur van Hoff - * @author Martin Buchholz - * @author Ulf Zibis - * @see java.lang.Object#toString() - * @see java.lang.StringBuffer - * @see java.lang.StringBuilder - * @see java.nio.charset.Charset - * @since JDK1.0 - */ - -@ExtraJavaScript( - resource="/org/apidesign/vm4brwsr/emul/java_lang_String.js", - processByteCode=true -) -@JavaScriptPrototype(container = "String.prototype", prototype = "new String") -public final class String - implements java.io.Serializable, Comparable, CharSequence -{ - /** real string to delegate to */ - private Object r; - - /** use serialVersionUID from JDK 1.0.2 for interoperability */ - private static final long serialVersionUID = -6849794470754667710L; - - @JavaScriptOnly(name="toString", value="function() { return this.fld_r; }") - private static void jsToString() { - } - - @JavaScriptOnly(name="valueOf", value="function() { return this.toString().valueOf(); }") - private static void jsValudOf() { - } - - /** - * Class String is special cased within the Serialization Stream Protocol. - * - * A String instance is written initially into an ObjectOutputStream in the - * following format: - *

-     *      TC_STRING (utf String)
-     * 
- * The String is written by method DataOutput.writeUTF. - * A new handle is generated to refer to all future references to the - * string instance within the stream. - */ -// private static final ObjectStreamField[] serialPersistentFields = -// new ObjectStreamField[0]; - - /** - * Initializes a newly created {@code String} object so that it represents - * an empty character sequence. Note that use of this constructor is - * unnecessary since Strings are immutable. - */ - public String() { - this.r = ""; - } - - /** - * Initializes a newly created {@code String} object so that it represents - * the same sequence of characters as the argument; in other words, the - * newly created string is a copy of the argument string. Unless an - * explicit copy of {@code original} is needed, use of this constructor is - * unnecessary since Strings are immutable. - * - * @param original - * A {@code String} - */ - public String(String original) { - this.r = original.toString(); - } - - /** - * Allocates a new {@code String} so that it represents the sequence of - * characters currently contained in the character array argument. The - * contents of the character array are copied; subsequent modification of - * the character array does not affect the newly created string. - * - * @param value - * The initial value of the string - */ - @JavaScriptBody(args = { "charArr" }, body= - "for (var i = 0; i < charArr.length; i++) {\n" - + " if (typeof charArr[i] === 'number') charArr[i] = String.fromCharCode(charArr[i]);\n" - + "}\n" - + "this.fld_r = charArr.join('');\n" - ) - public String(char value[]) { - } - - /** - * Allocates a new {@code String} that contains characters from a subarray - * of the character array argument. The {@code offset} argument is the - * index of the first character of the subarray and the {@code count} - * argument specifies the length of the subarray. The contents of the - * subarray are copied; subsequent modification of the character array does - * not affect the newly created string. - * - * @param value - * Array that is the source of characters - * - * @param offset - * The initial offset - * - * @param count - * The length - * - * @throws IndexOutOfBoundsException - * If the {@code offset} and {@code count} arguments index - * characters outside the bounds of the {@code value} array - */ - @JavaScriptBody(args = { "charArr", "off", "cnt" }, body = - "var up = off + cnt;\n" + - "for (var i = off; i < up; i++) {\n" + - " if (typeof charArr[i] === 'number') charArr[i] = String.fromCharCode(charArr[i]);\n" + - "}\n" + - "this.fld_r = charArr.slice(off, up).join(\"\");\n" - ) - public String(char value[], int offset, int count) { - } - - /** - * Allocates a new {@code String} that contains characters from a subarray - * of the Unicode code point array - * argument. The {@code offset} argument is the index of the first code - * point of the subarray and the {@code count} argument specifies the - * length of the subarray. The contents of the subarray are converted to - * {@code char}s; subsequent modification of the {@code int} array does not - * affect the newly created string. - * - * @param codePoints - * Array that is the source of Unicode code points - * - * @param offset - * The initial offset - * - * @param count - * The length - * - * @throws IllegalArgumentException - * If any invalid Unicode code point is found in {@code - * codePoints} - * - * @throws IndexOutOfBoundsException - * If the {@code offset} and {@code count} arguments index - * characters outside the bounds of the {@code codePoints} array - * - * @since 1.5 - */ - public String(int[] codePoints, int offset, int count) { - if (offset < 0) { - throw new StringIndexOutOfBoundsException(offset); - } - if (count < 0) { - throw new StringIndexOutOfBoundsException(count); - } - // Note: offset or count might be near -1>>>1. - if (offset > codePoints.length - count) { - throw new StringIndexOutOfBoundsException(offset + count); - } - - final int end = offset + count; - - // Pass 1: Compute precise size of char[] - int n = count; - for (int i = offset; i < end; i++) { - int c = codePoints[i]; - if (Character.isBmpCodePoint(c)) - continue; - else if (Character.isValidCodePoint(c)) - n++; - else throw new IllegalArgumentException(Integer.toString(c)); - } - - // Pass 2: Allocate and fill in char[] - final char[] v = new char[n]; - - for (int i = offset, j = 0; i < end; i++, j++) { - int c = codePoints[i]; - if (Character.isBmpCodePoint(c)) - v[j] = (char) c; - else - Character.toSurrogates(c, v, j++); - } - - this.r = new String(v, 0, n); - } - - /** - * Allocates a new {@code String} constructed from a subarray of an array - * of 8-bit integer values. - * - *

The {@code offset} argument is the index of the first byte of the - * subarray, and the {@code count} argument specifies the length of the - * subarray. - * - *

Each {@code byte} in the subarray is converted to a {@code char} as - * specified in the method above. - * - * @deprecated This method does not properly convert bytes into characters. - * As of JDK 1.1, the preferred way to do this is via the - * {@code String} constructors that take a {@link - * java.nio.charset.Charset}, charset name, or that use the platform's - * default charset. - * - * @param ascii - * The bytes to be converted to characters - * - * @param hibyte - * The top 8 bits of each 16-bit Unicode code unit - * - * @param offset - * The initial offset - * @param count - * The length - * - * @throws IndexOutOfBoundsException - * If the {@code offset} or {@code count} argument is invalid - * - * @see #String(byte[], int) - * @see #String(byte[], int, int, java.lang.String) - * @see #String(byte[], int, int, java.nio.charset.Charset) - * @see #String(byte[], int, int) - * @see #String(byte[], java.lang.String) - * @see #String(byte[], java.nio.charset.Charset) - * @see #String(byte[]) - */ - @Deprecated - public String(byte ascii[], int hibyte, int offset, int count) { - checkBounds(ascii, offset, count); - char value[] = new char[count]; - - if (hibyte == 0) { - for (int i = count ; i-- > 0 ;) { - value[i] = (char) (ascii[i + offset] & 0xff); - } - } else { - hibyte <<= 8; - for (int i = count ; i-- > 0 ;) { - value[i] = (char) (hibyte | (ascii[i + offset] & 0xff)); - } - } - this.r = new String(value, 0, count); - } - - /** - * Allocates a new {@code String} containing characters constructed from - * an array of 8-bit integer values. Each character cin the - * resulting string is constructed from the corresponding component - * b in the byte array such that: - * - *

-     *     c == (char)(((hibyte & 0xff) << 8)
-     *                         | (b & 0xff))
-     * 
- * - * @deprecated This method does not properly convert bytes into - * characters. As of JDK 1.1, the preferred way to do this is via the - * {@code String} constructors that take a {@link - * java.nio.charset.Charset}, charset name, or that use the platform's - * default charset. - * - * @param ascii - * The bytes to be converted to characters - * - * @param hibyte - * The top 8 bits of each 16-bit Unicode code unit - * - * @see #String(byte[], int, int, java.lang.String) - * @see #String(byte[], int, int, java.nio.charset.Charset) - * @see #String(byte[], int, int) - * @see #String(byte[], java.lang.String) - * @see #String(byte[], java.nio.charset.Charset) - * @see #String(byte[]) - */ - @Deprecated - public String(byte ascii[], int hibyte) { - this(ascii, hibyte, 0, ascii.length); - } - - /* Common private utility method used to bounds check the byte array - * and requested offset & length values used by the String(byte[],..) - * constructors. - */ - private static void checkBounds(byte[] bytes, int offset, int length) { - if (length < 0) - throw new StringIndexOutOfBoundsException(length); - if (offset < 0) - throw new StringIndexOutOfBoundsException(offset); - if (offset > bytes.length - length) - throw new StringIndexOutOfBoundsException(offset + length); - } - - /** - * Constructs a new {@code String} by decoding the specified subarray of - * bytes using the specified charset. The length of the new {@code String} - * is a function of the charset, and hence may not be equal to the length - * of the subarray. - * - *

The behavior of this constructor when the given bytes are not valid - * in the given charset is unspecified. The {@link - * java.nio.charset.CharsetDecoder} class should be used when more control - * over the decoding process is required. - * - * @param bytes - * The bytes to be decoded into characters - * - * @param offset - * The index of the first byte to decode - * - * @param length - * The number of bytes to decode - - * @param charsetName - * The name of a supported {@linkplain java.nio.charset.Charset - * charset} - * - * @throws UnsupportedEncodingException - * If the named charset is not supported - * - * @throws IndexOutOfBoundsException - * If the {@code offset} and {@code length} arguments index - * characters outside the bounds of the {@code bytes} array - * - * @since JDK1.1 - */ -// public String(byte bytes[], int offset, int length, String charsetName) -// throws UnsupportedEncodingException -// { -// if (charsetName == null) -// throw new NullPointerException("charsetName"); -// checkBounds(bytes, offset, length); -// char[] v = StringCoding.decode(charsetName, bytes, offset, length); -// this.offset = 0; -// this.count = v.length; -// this.value = v; -// } - - /** - * Constructs a new {@code String} by decoding the specified subarray of - * bytes using the specified {@linkplain java.nio.charset.Charset charset}. - * The length of the new {@code String} is a function of the charset, and - * hence may not be equal to the length of the subarray. - * - *

This method always replaces malformed-input and unmappable-character - * sequences with this charset's default replacement string. The {@link - * java.nio.charset.CharsetDecoder} class should be used when more control - * over the decoding process is required. - * - * @param bytes - * The bytes to be decoded into characters - * - * @param offset - * The index of the first byte to decode - * - * @param length - * The number of bytes to decode - * - * @param charset - * The {@linkplain java.nio.charset.Charset charset} to be used to - * decode the {@code bytes} - * - * @throws IndexOutOfBoundsException - * If the {@code offset} and {@code length} arguments index - * characters outside the bounds of the {@code bytes} array - * - * @since 1.6 - */ - /* don't want dependnecy on Charset - public String(byte bytes[], int offset, int length, Charset charset) { - if (charset == null) - throw new NullPointerException("charset"); - checkBounds(bytes, offset, length); - char[] v = StringCoding.decode(charset, bytes, offset, length); - this.offset = 0; - this.count = v.length; - this.value = v; - } - */ - - /** - * Constructs a new {@code String} by decoding the specified array of bytes - * using the specified {@linkplain java.nio.charset.Charset charset}. The - * length of the new {@code String} is a function of the charset, and hence - * may not be equal to the length of the byte array. - * - *

The behavior of this constructor when the given bytes are not valid - * in the given charset is unspecified. The {@link - * java.nio.charset.CharsetDecoder} class should be used when more control - * over the decoding process is required. - * - * @param bytes - * The bytes to be decoded into characters - * - * @param charsetName - * The name of a supported {@linkplain java.nio.charset.Charset - * charset} - * - * @throws UnsupportedEncodingException - * If the named charset is not supported - * - * @since JDK1.1 - */ -// public String(byte bytes[], String charsetName) -// throws UnsupportedEncodingException -// { -// this(bytes, 0, bytes.length, charsetName); -// } - - /** - * Constructs a new {@code String} by decoding the specified array of - * bytes using the specified {@linkplain java.nio.charset.Charset charset}. - * The length of the new {@code String} is a function of the charset, and - * hence may not be equal to the length of the byte array. - * - *

This method always replaces malformed-input and unmappable-character - * sequences with this charset's default replacement string. The {@link - * java.nio.charset.CharsetDecoder} class should be used when more control - * over the decoding process is required. - * - * @param bytes - * The bytes to be decoded into characters - * - * @param charset - * The {@linkplain java.nio.charset.Charset charset} to be used to - * decode the {@code bytes} - * - * @since 1.6 - */ - /* don't want dep on Charset - public String(byte bytes[], Charset charset) { - this(bytes, 0, bytes.length, charset); - } - */ - - /** - * Constructs a new {@code String} by decoding the specified subarray of - * bytes using the platform's default charset. The length of the new - * {@code String} is a function of the charset, and hence may not be equal - * to the length of the subarray. - * - *

The behavior of this constructor when the given bytes are not valid - * in the default charset is unspecified. The {@link - * java.nio.charset.CharsetDecoder} class should be used when more control - * over the decoding process is required. - * - * @param bytes - * The bytes to be decoded into characters - * - * @param offset - * The index of the first byte to decode - * - * @param length - * The number of bytes to decode - * - * @throws IndexOutOfBoundsException - * If the {@code offset} and the {@code length} arguments index - * characters outside the bounds of the {@code bytes} array - * - * @since JDK1.1 - */ - public String(byte bytes[], int offset, int length) { - checkBounds(bytes, offset, length); - char[] v = new char[length]; - for (int i = 0; i < length; i++) { - v[i] = (char)bytes[offset++]; - } - this.r = new String(v, 0, v.length); - } - - /** - * Constructs a new {@code String} by decoding the specified array of bytes - * using the platform's default charset. The length of the new {@code - * String} is a function of the charset, and hence may not be equal to the - * length of the byte array. - * - *

The behavior of this constructor when the given bytes are not valid - * in the default charset is unspecified. The {@link - * java.nio.charset.CharsetDecoder} class should be used when more control - * over the decoding process is required. - * - * @param bytes - * The bytes to be decoded into characters - * - * @since JDK1.1 - */ - public String(byte bytes[]) { - this(bytes, 0, bytes.length); - } - - /** - * Allocates a new string that contains the sequence of characters - * currently contained in the string buffer argument. The contents of the - * string buffer are copied; subsequent modification of the string buffer - * does not affect the newly created string. - * - * @param buffer - * A {@code StringBuffer} - */ - public String(StringBuffer buffer) { - this.r = buffer.toString(); - } - - /** - * Allocates a new string that contains the sequence of characters - * currently contained in the string builder argument. The contents of the - * string builder are copied; subsequent modification of the string builder - * does not affect the newly created string. - * - *

This constructor is provided to ease migration to {@code - * StringBuilder}. Obtaining a string from a string builder via the {@code - * toString} method is likely to run faster and is generally preferred. - * - * @param builder - * A {@code StringBuilder} - * - * @since 1.5 - */ - public String(StringBuilder builder) { - this.r = builder.toString(); - } - - /** - * Returns the length of this string. - * The length is equal to the number of Unicode - * code units in the string. - * - * @return the length of the sequence of characters represented by this - * object. - */ - @JavaScriptBody(args = {}, body = "return this.toString().length;") - public int length() { - throw new UnsupportedOperationException(); - } - - /** - * Returns true if, and only if, {@link #length()} is 0. - * - * @return true if {@link #length()} is 0, otherwise - * false - * - * @since 1.6 - */ - @JavaScriptBody(args = {}, body="return this.toString().length === 0;") - public boolean isEmpty() { - return length() == 0; - } - - /** - * Returns the char value at the - * specified index. An index ranges from 0 to - * length() - 1. The first char value of the sequence - * is at index 0, the next at index 1, - * and so on, as for array indexing. - * - *

If the char value specified by the index is a - * surrogate, the surrogate - * value is returned. - * - * @param index the index of the char value. - * @return the char value at the specified index of this string. - * The first char value is at index 0. - * @exception IndexOutOfBoundsException if the index - * argument is negative or not less than the length of this - * string. - */ - @JavaScriptBody(args = { "index" }, - body = "return this.toString().charCodeAt(index);" - ) - public char charAt(int index) { - throw new UnsupportedOperationException(); - } - - /** - * Returns the character (Unicode code point) at the specified - * index. The index refers to char values - * (Unicode code units) and ranges from 0 to - * {@link #length()} - 1. - * - *

If the char value specified at the given index - * is in the high-surrogate range, the following index is less - * than the length of this String, and the - * char value at the following index is in the - * low-surrogate range, then the supplementary code point - * corresponding to this surrogate pair is returned. Otherwise, - * the char value at the given index is returned. - * - * @param index the index to the char values - * @return the code point value of the character at the - * index - * @exception IndexOutOfBoundsException if the index - * argument is negative or not less than the length of this - * string. - * @since 1.5 - */ - public int codePointAt(int index) { - if ((index < 0) || (index >= length())) { - throw new StringIndexOutOfBoundsException(index); - } - return Character.codePointAtImpl(toCharArray(), offset() + index, offset() + length()); - } - - /** - * Returns the character (Unicode code point) before the specified - * index. The index refers to char values - * (Unicode code units) and ranges from 1 to {@link - * CharSequence#length() length}. - * - *

If the char value at (index - 1) - * is in the low-surrogate range, (index - 2) is not - * negative, and the char value at (index - - * 2) is in the high-surrogate range, then the - * supplementary code point value of the surrogate pair is - * returned. If the char value at index - - * 1 is an unpaired low-surrogate or a high-surrogate, the - * surrogate value is returned. - * - * @param index the index following the code point that should be returned - * @return the Unicode code point value before the given index. - * @exception IndexOutOfBoundsException if the index - * argument is less than 1 or greater than the length - * of this string. - * @since 1.5 - */ - public int codePointBefore(int index) { - int i = index - 1; - if ((i < 0) || (i >= length())) { - throw new StringIndexOutOfBoundsException(index); - } - return Character.codePointBeforeImpl(toCharArray(), offset() + index, offset()); - } - - /** - * Returns the number of Unicode code points in the specified text - * range of this String. The text range begins at the - * specified beginIndex and extends to the - * char at index endIndex - 1. Thus the - * length (in chars) of the text range is - * endIndex-beginIndex. Unpaired surrogates within - * the text range count as one code point each. - * - * @param beginIndex the index to the first char of - * the text range. - * @param endIndex the index after the last char of - * the text range. - * @return the number of Unicode code points in the specified text - * range - * @exception IndexOutOfBoundsException if the - * beginIndex is negative, or endIndex - * is larger than the length of this String, or - * beginIndex is larger than endIndex. - * @since 1.5 - */ - public int codePointCount(int beginIndex, int endIndex) { - if (beginIndex < 0 || endIndex > length() || beginIndex > endIndex) { - throw new IndexOutOfBoundsException(); - } - return Character.codePointCountImpl(toCharArray(), offset()+beginIndex, endIndex-beginIndex); - } - - /** - * Returns the index within this String that is - * offset from the given index by - * codePointOffset code points. Unpaired surrogates - * within the text range given by index and - * codePointOffset count as one code point each. - * - * @param index the index to be offset - * @param codePointOffset the offset in code points - * @return the index within this String - * @exception IndexOutOfBoundsException if index - * is negative or larger then the length of this - * String, or if codePointOffset is positive - * and the substring starting with index has fewer - * than codePointOffset code points, - * or if codePointOffset is negative and the substring - * before index has fewer than the absolute value - * of codePointOffset code points. - * @since 1.5 - */ - public int offsetByCodePoints(int index, int codePointOffset) { - if (index < 0 || index > length()) { - throw new IndexOutOfBoundsException(); - } - return Character.offsetByCodePointsImpl(toCharArray(), offset(), length(), - offset()+index, codePointOffset) - offset(); - } - - /** - * Copy characters from this string into dst starting at dstBegin. - * This method doesn't perform any range checking. - */ - @JavaScriptBody(args = { "arr", "to" }, body = - "var s = this.toString();\n" + - "for (var i = 0; i < s.length; i++) {\n" + - " arr[to++] = s[i];\n" + - "}" - ) - void getChars(char dst[], int dstBegin) { - AbstractStringBuilder.arraycopy(toCharArray(), offset(), dst, dstBegin, length()); - } - - /** - * Copies characters from this string into the destination character - * array. - *

- * The first character to be copied is at index srcBegin; - * the last character to be copied is at index srcEnd-1 - * (thus the total number of characters to be copied is - * srcEnd-srcBegin). The characters are copied into the - * subarray of dst starting at index dstBegin - * and ending at index: - *

-     *     dstbegin + (srcEnd-srcBegin) - 1
-     * 
- * - * @param srcBegin index of the first character in the string - * to copy. - * @param srcEnd index after the last character in the string - * to copy. - * @param dst the destination array. - * @param dstBegin the start offset in the destination array. - * @exception IndexOutOfBoundsException If any of the following - * is true: - *
  • srcBegin is negative. - *
  • srcBegin is greater than srcEnd - *
  • srcEnd is greater than the length of this - * string - *
  • dstBegin is negative - *
  • dstBegin+(srcEnd-srcBegin) is larger than - * dst.length
- */ - @JavaScriptBody(args = { "beg", "end", "arr", "dst" }, body= - "var s = this.toString();\n" + - "while (beg < end) {\n" + - " arr[dst++] = s[beg++];\n" + - "}\n" - ) - public void getChars(int srcBegin, int srcEnd, char dst[], int dstBegin) { - if (srcBegin < 0) { - throw new StringIndexOutOfBoundsException(srcBegin); - } - if (srcEnd > length()) { - throw new StringIndexOutOfBoundsException(srcEnd); - } - if (srcBegin > srcEnd) { - throw new StringIndexOutOfBoundsException(srcEnd - srcBegin); - } - AbstractStringBuilder.arraycopy(toCharArray(), offset() + srcBegin, dst, dstBegin, - srcEnd - srcBegin); - } - - /** - * Copies characters from this string into the destination byte array. Each - * byte receives the 8 low-order bits of the corresponding character. The - * eight high-order bits of each character are not copied and do not - * participate in the transfer in any way. - * - *

The first character to be copied is at index {@code srcBegin}; the - * last character to be copied is at index {@code srcEnd-1}. The total - * number of characters to be copied is {@code srcEnd-srcBegin}. The - * characters, converted to bytes, are copied into the subarray of {@code - * dst} starting at index {@code dstBegin} and ending at index: - * - *

-     *     dstbegin + (srcEnd-srcBegin) - 1
-     * 
- * - * @deprecated This method does not properly convert characters into - * bytes. As of JDK 1.1, the preferred way to do this is via the - * {@link #getBytes()} method, which uses the platform's default charset. - * - * @param srcBegin - * Index of the first character in the string to copy - * - * @param srcEnd - * Index after the last character in the string to copy - * - * @param dst - * The destination array - * - * @param dstBegin - * The start offset in the destination array - * - * @throws IndexOutOfBoundsException - * If any of the following is true: - *
    - *
  • {@code srcBegin} is negative - *
  • {@code srcBegin} is greater than {@code srcEnd} - *
  • {@code srcEnd} is greater than the length of this String - *
  • {@code dstBegin} is negative - *
  • {@code dstBegin+(srcEnd-srcBegin)} is larger than {@code - * dst.length} - *
- */ - @Deprecated - public void getBytes(int srcBegin, int srcEnd, byte dst[], int dstBegin) { - if (srcBegin < 0) { - throw new StringIndexOutOfBoundsException(srcBegin); - } - if (srcEnd > length()) { - throw new StringIndexOutOfBoundsException(srcEnd); - } - if (srcBegin > srcEnd) { - throw new StringIndexOutOfBoundsException(srcEnd - srcBegin); - } - int j = dstBegin; - int n = offset() + srcEnd; - int i = offset() + srcBegin; - char[] val = toCharArray(); /* avoid getfield opcode */ - - while (i < n) { - dst[j++] = (byte)val[i++]; - } - } - - /** - * Encodes this {@code String} into a sequence of bytes using the named - * charset, storing the result into a new byte array. - * - *

The behavior of this method when this string cannot be encoded in - * the given charset is unspecified. The {@link - * java.nio.charset.CharsetEncoder} class should be used when more control - * over the encoding process is required. - * - * @param charsetName - * The name of a supported {@linkplain java.nio.charset.Charset - * charset} - * - * @return The resultant byte array - * - * @throws UnsupportedEncodingException - * If the named charset is not supported - * - * @since JDK1.1 - */ -// public byte[] getBytes(String charsetName) -// throws UnsupportedEncodingException -// { -// if (charsetName == null) throw new NullPointerException(); -// return StringCoding.encode(charsetName, value, offset, count); -// } - - /** - * Encodes this {@code String} into a sequence of bytes using the given - * {@linkplain java.nio.charset.Charset charset}, storing the result into a - * new byte array. - * - *

This method always replaces malformed-input and unmappable-character - * sequences with this charset's default replacement byte array. The - * {@link java.nio.charset.CharsetEncoder} class should be used when more - * control over the encoding process is required. - * - * @param charset - * The {@linkplain java.nio.charset.Charset} to be used to encode - * the {@code String} - * - * @return The resultant byte array - * - * @since 1.6 - */ - /* don't want dep on Charset - public byte[] getBytes(Charset charset) { - if (charset == null) throw new NullPointerException(); - return StringCoding.encode(charset, value, offset, count); - } - */ - - /** - * Encodes this {@code String} into a sequence of bytes using the - * platform's default charset, storing the result into a new byte array. - * - *

The behavior of this method when this string cannot be encoded in - * the default charset is unspecified. The {@link - * java.nio.charset.CharsetEncoder} class should be used when more control - * over the encoding process is required. - * - * @return The resultant byte array - * - * @since JDK1.1 - */ - public byte[] getBytes() { - byte[] arr = new byte[length()]; - for (int i = 0; i < arr.length; i++) { - final char v = charAt(i); - arr[i] = (byte)v; - } - return arr; - } - - /** - * Compares this string to the specified object. The result is {@code - * true} if and only if the argument is not {@code null} and is a {@code - * String} object that represents the same sequence of characters as this - * object. - * - * @param anObject - * The object to compare this {@code String} against - * - * @return {@code true} if the given object represents a {@code String} - * equivalent to this string, {@code false} otherwise - * - * @see #compareTo(String) - * @see #equalsIgnoreCase(String) - */ - @JavaScriptBody(args = { "obj" }, body = - "return obj != null && obj.$instOf_java_lang_String && " - + "this.toString() === obj.toString();" - ) - public boolean equals(Object anObject) { - if (this == anObject) { - return true; - } - if (anObject instanceof String) { - String anotherString = (String)anObject; - int n = length(); - if (n == anotherString.length()) { - char v1[] = toCharArray(); - char v2[] = anotherString.toCharArray(); - int i = offset(); - int j = anotherString.offset(); - while (n-- != 0) { - if (v1[i++] != v2[j++]) - return false; - } - return true; - } - } - return false; - } - - /** - * Compares this string to the specified {@code StringBuffer}. The result - * is {@code true} if and only if this {@code String} represents the same - * sequence of characters as the specified {@code StringBuffer}. - * - * @param sb - * The {@code StringBuffer} to compare this {@code String} against - * - * @return {@code true} if this {@code String} represents the same - * sequence of characters as the specified {@code StringBuffer}, - * {@code false} otherwise - * - * @since 1.4 - */ - public boolean contentEquals(StringBuffer sb) { - synchronized(sb) { - return contentEquals((CharSequence)sb); - } - } - - /** - * Compares this string to the specified {@code CharSequence}. The result - * is {@code true} if and only if this {@code String} represents the same - * sequence of char values as the specified sequence. - * - * @param cs - * The sequence to compare this {@code String} against - * - * @return {@code true} if this {@code String} represents the same - * sequence of char values as the specified sequence, {@code - * false} otherwise - * - * @since 1.5 - */ - public boolean contentEquals(CharSequence cs) { - if (length() != cs.length()) - return false; - // Argument is a StringBuffer, StringBuilder - if (cs instanceof AbstractStringBuilder) { - char v1[] = toCharArray(); - char v2[] = ((AbstractStringBuilder)cs).getValue(); - int i = offset(); - int j = 0; - int n = length(); - while (n-- != 0) { - if (v1[i++] != v2[j++]) - return false; - } - return true; - } - // Argument is a String - if (cs.equals(this)) - return true; - // Argument is a generic CharSequence - char v1[] = toCharArray(); - int i = offset(); - int j = 0; - int n = length(); - while (n-- != 0) { - if (v1[i++] != cs.charAt(j++)) - return false; - } - return true; - } - - /** - * Compares this {@code String} to another {@code String}, ignoring case - * considerations. Two strings are considered equal ignoring case if they - * are of the same length and corresponding characters in the two strings - * are equal ignoring case. - * - *

Two characters {@code c1} and {@code c2} are considered the same - * ignoring case if at least one of the following is true: - *

    - *
  • The two characters are the same (as compared by the - * {@code ==} operator) - *
  • Applying the method {@link - * java.lang.Character#toUpperCase(char)} to each character - * produces the same result - *
  • Applying the method {@link - * java.lang.Character#toLowerCase(char)} to each character - * produces the same result - *
- * - * @param anotherString - * The {@code String} to compare this {@code String} against - * - * @return {@code true} if the argument is not {@code null} and it - * represents an equivalent {@code String} ignoring case; {@code - * false} otherwise - * - * @see #equals(Object) - */ - public boolean equalsIgnoreCase(String anotherString) { - return (this == anotherString) ? true : - (anotherString != null) && (anotherString.length() == length()) && - regionMatches(true, 0, anotherString, 0, length()); - } - - /** - * Compares two strings lexicographically. - * The comparison is based on the Unicode value of each character in - * the strings. The character sequence represented by this - * String object is compared lexicographically to the - * character sequence represented by the argument string. The result is - * a negative integer if this String object - * lexicographically precedes the argument string. The result is a - * positive integer if this String object lexicographically - * follows the argument string. The result is zero if the strings - * are equal; compareTo returns 0 exactly when - * the {@link #equals(Object)} method would return true. - *

- * This is the definition of lexicographic ordering. If two strings are - * different, then either they have different characters at some index - * that is a valid index for both strings, or their lengths are different, - * or both. If they have different characters at one or more index - * positions, let k be the smallest such index; then the string - * whose character at position k has the smaller value, as - * determined by using the < operator, lexicographically precedes the - * other string. In this case, compareTo returns the - * difference of the two character values at position k in - * the two string -- that is, the value: - *

-     * this.charAt(k)-anotherString.charAt(k)
-     * 
- * If there is no index position at which they differ, then the shorter - * string lexicographically precedes the longer string. In this case, - * compareTo returns the difference of the lengths of the - * strings -- that is, the value: - *
-     * this.length()-anotherString.length()
-     * 
- * - * @param anotherString the String to be compared. - * @return the value 0 if the argument string is equal to - * this string; a value less than 0 if this string - * is lexicographically less than the string argument; and a - * value greater than 0 if this string is - * lexicographically greater than the string argument. - */ - public int compareTo(String anotherString) { - int len1 = length(); - int len2 = anotherString.length(); - int n = Math.min(len1, len2); - char v1[] = toCharArray(); - char v2[] = anotherString.toCharArray(); - int i = offset(); - int j = anotherString.offset(); - - if (i == j) { - int k = i; - int lim = n + i; - while (k < lim) { - char c1 = v1[k]; - char c2 = v2[k]; - if (c1 != c2) { - return c1 - c2; - } - k++; - } - } else { - while (n-- != 0) { - char c1 = v1[i++]; - char c2 = v2[j++]; - if (c1 != c2) { - return c1 - c2; - } - } - } - return len1 - len2; - } - - /** - * A Comparator that orders String objects as by - * compareToIgnoreCase. This comparator is serializable. - *

- * Note that this Comparator does not take locale into account, - * and will result in an unsatisfactory ordering for certain locales. - * The java.text package provides Collators to allow - * locale-sensitive ordering. - * - * @see java.text.Collator#compare(String, String) - * @since 1.2 - */ - public static final Comparator CASE_INSENSITIVE_ORDER - = new CaseInsensitiveComparator(); - - private static int offset() { - return 0; - } - - private static class CaseInsensitiveComparator - implements Comparator, java.io.Serializable { - // use serialVersionUID from JDK 1.2.2 for interoperability - private static final long serialVersionUID = 8575799808933029326L; - - public int compare(String s1, String s2) { - int n1 = s1.length(); - int n2 = s2.length(); - int min = Math.min(n1, n2); - for (int i = 0; i < min; i++) { - char c1 = s1.charAt(i); - char c2 = s2.charAt(i); - if (c1 != c2) { - c1 = Character.toUpperCase(c1); - c2 = Character.toUpperCase(c2); - if (c1 != c2) { - c1 = Character.toLowerCase(c1); - c2 = Character.toLowerCase(c2); - if (c1 != c2) { - // No overflow because of numeric promotion - return c1 - c2; - } - } - } - } - return n1 - n2; - } - } - - /** - * Compares two strings lexicographically, ignoring case - * differences. This method returns an integer whose sign is that of - * calling compareTo with normalized versions of the strings - * where case differences have been eliminated by calling - * Character.toLowerCase(Character.toUpperCase(character)) on - * each character. - *

- * Note that this method does not take locale into account, - * and will result in an unsatisfactory ordering for certain locales. - * The java.text package provides collators to allow - * locale-sensitive ordering. - * - * @param str the String to be compared. - * @return a negative integer, zero, or a positive integer as the - * specified String is greater than, equal to, or less - * than this String, ignoring case considerations. - * @see java.text.Collator#compare(String, String) - * @since 1.2 - */ - public int compareToIgnoreCase(String str) { - return CASE_INSENSITIVE_ORDER.compare(this, str); - } - - /** - * Tests if two string regions are equal. - *

- * A substring of this String object is compared to a substring - * of the argument other. The result is true if these substrings - * represent identical character sequences. The substring of this - * String object to be compared begins at index toffset - * and has length len. The substring of other to be compared - * begins at index ooffset and has length len. The - * result is false if and only if at least one of the following - * is true: - *

  • toffset is negative. - *
  • ooffset is negative. - *
  • toffset+len is greater than the length of this - * String object. - *
  • ooffset+len is greater than the length of the other - * argument. - *
  • There is some nonnegative integer k less than len - * such that: - * this.charAt(toffset+k) != other.charAt(ooffset+k) - *
- * - * @param toffset the starting offset of the subregion in this string. - * @param other the string argument. - * @param ooffset the starting offset of the subregion in the string - * argument. - * @param len the number of characters to compare. - * @return true if the specified subregion of this string - * exactly matches the specified subregion of the string argument; - * false otherwise. - */ - public boolean regionMatches(int toffset, String other, int ooffset, - int len) { - char ta[] = toCharArray(); - int to = offset() + toffset; - char pa[] = other.toCharArray(); - int po = other.offset() + ooffset; - // Note: toffset, ooffset, or len might be near -1>>>1. - if ((ooffset < 0) || (toffset < 0) || (toffset > (long)length() - len) - || (ooffset > (long)other.length() - len)) { - return false; - } - while (len-- > 0) { - if (ta[to++] != pa[po++]) { - return false; - } - } - return true; - } - - /** - * Tests if two string regions are equal. - *

- * A substring of this String object is compared to a substring - * of the argument other. The result is true if these - * substrings represent character sequences that are the same, ignoring - * case if and only if ignoreCase is true. The substring of - * this String object to be compared begins at index - * toffset and has length len. The substring of - * other to be compared begins at index ooffset and - * has length len. The result is false if and only if - * at least one of the following is true: - *

  • toffset is negative. - *
  • ooffset is negative. - *
  • toffset+len is greater than the length of this - * String object. - *
  • ooffset+len is greater than the length of the other - * argument. - *
  • ignoreCase is false and there is some nonnegative - * integer k less than len such that: - *
    -     * this.charAt(toffset+k) != other.charAt(ooffset+k)
    -     * 
    - *
  • ignoreCase is true and there is some nonnegative - * integer k less than len such that: - *
    -     * Character.toLowerCase(this.charAt(toffset+k)) !=
    -               Character.toLowerCase(other.charAt(ooffset+k))
    -     * 
    - * and: - *
    -     * Character.toUpperCase(this.charAt(toffset+k)) !=
    -     *         Character.toUpperCase(other.charAt(ooffset+k))
    -     * 
    - *
- * - * @param ignoreCase if true, ignore case when comparing - * characters. - * @param toffset the starting offset of the subregion in this - * string. - * @param other the string argument. - * @param ooffset the starting offset of the subregion in the string - * argument. - * @param len the number of characters to compare. - * @return true if the specified subregion of this string - * matches the specified subregion of the string argument; - * false otherwise. Whether the matching is exact - * or case insensitive depends on the ignoreCase - * argument. - */ - public boolean regionMatches(boolean ignoreCase, int toffset, - String other, int ooffset, int len) { - char ta[] = toCharArray(); - int to = offset() + toffset; - char pa[] = other.toCharArray(); - int po = other.offset() + ooffset; - // Note: toffset, ooffset, or len might be near -1>>>1. - if ((ooffset < 0) || (toffset < 0) || (toffset > (long)length() - len) || - (ooffset > (long)other.length() - len)) { - return false; - } - while (len-- > 0) { - char c1 = ta[to++]; - char c2 = pa[po++]; - if (c1 == c2) { - continue; - } - if (ignoreCase) { - // If characters don't match but case may be ignored, - // try converting both characters to uppercase. - // If the results match, then the comparison scan should - // continue. - char u1 = Character.toUpperCase(c1); - char u2 = Character.toUpperCase(c2); - if (u1 == u2) { - continue; - } - // Unfortunately, conversion to uppercase does not work properly - // for the Georgian alphabet, which has strange rules about case - // conversion. So we need to make one last check before - // exiting. - if (Character.toLowerCase(u1) == Character.toLowerCase(u2)) { - continue; - } - } - return false; - } - return true; - } - - /** - * Tests if the substring of this string beginning at the - * specified index starts with the specified prefix. - * - * @param prefix the prefix. - * @param toffset where to begin looking in this string. - * @return true if the character sequence represented by the - * argument is a prefix of the substring of this object starting - * at index toffset; false otherwise. - * The result is false if toffset is - * negative or greater than the length of this - * String object; otherwise the result is the same - * as the result of the expression - *
-     *          this.substring(toffset).startsWith(prefix)
-     *          
- */ - @JavaScriptBody(args = { "find", "from" }, body= - "find = find.toString();\n" + - "return this.toString().substring(from, from + find.length) === find;\n" - ) - public boolean startsWith(String prefix, int toffset) { - char ta[] = toCharArray(); - int to = offset() + toffset; - char pa[] = prefix.toCharArray(); - int po = prefix.offset(); - int pc = prefix.length(); - // Note: toffset might be near -1>>>1. - if ((toffset < 0) || (toffset > length() - pc)) { - return false; - } - while (--pc >= 0) { - if (ta[to++] != pa[po++]) { - return false; - } - } - return true; - } - - /** - * Tests if this string starts with the specified prefix. - * - * @param prefix the prefix. - * @return true if the character sequence represented by the - * argument is a prefix of the character sequence represented by - * this string; false otherwise. - * Note also that true will be returned if the - * argument is an empty string or is equal to this - * String object as determined by the - * {@link #equals(Object)} method. - * @since 1. 0 - */ - public boolean startsWith(String prefix) { - return startsWith(prefix, 0); - } - - /** - * Tests if this string ends with the specified suffix. - * - * @param suffix the suffix. - * @return true if the character sequence represented by the - * argument is a suffix of the character sequence represented by - * this object; false otherwise. Note that the - * result will be true if the argument is the - * empty string or is equal to this String object - * as determined by the {@link #equals(Object)} method. - */ - public boolean endsWith(String suffix) { - return startsWith(suffix, length() - suffix.length()); - } - - /** - * Returns a hash code for this string. The hash code for a - * String object is computed as - *
-     * s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1]
-     * 
- * using int arithmetic, where s[i] is the - * ith character of the string, n is the length of - * the string, and ^ indicates exponentiation. - * (The hash value of the empty string is zero.) - * - * @return a hash code value for this object. - */ - public int hashCode() { - return super.hashCode(); - } - int computeHashCode() { - int h = 0; - if (h == 0 && length() > 0) { - int off = offset(); - int len = length(); - - for (int i = 0; i < len; i++) { - h = 31*h + charAt(off++); - } - } - return h; - } - - /** - * Returns the index within this string of the first occurrence of - * the specified character. If a character with value - * ch occurs in the character sequence represented by - * this String object, then the index (in Unicode - * code units) of the first such occurrence is returned. For - * values of ch in the range from 0 to 0xFFFF - * (inclusive), this is the smallest value k such that: - *
-     * this.charAt(k) == ch
-     * 
- * is true. For other values of ch, it is the - * smallest value k such that: - *
-     * this.codePointAt(k) == ch
-     * 
- * is true. In either case, if no such character occurs in this - * string, then -1 is returned. - * - * @param ch a character (Unicode code point). - * @return the index of the first occurrence of the character in the - * character sequence represented by this object, or - * -1 if the character does not occur. - */ - public int indexOf(int ch) { - return indexOf(ch, 0); - } - - /** - * Returns the index within this string of the first occurrence of the - * specified character, starting the search at the specified index. - *

- * If a character with value ch occurs in the - * character sequence represented by this String - * object at an index no smaller than fromIndex, then - * the index of the first such occurrence is returned. For values - * of ch in the range from 0 to 0xFFFF (inclusive), - * this is the smallest value k such that: - *

-     * (this.charAt(k) == ch) && (k >= fromIndex)
-     * 
- * is true. For other values of ch, it is the - * smallest value k such that: - *
-     * (this.codePointAt(k) == ch) && (k >= fromIndex)
-     * 
- * is true. In either case, if no such character occurs in this - * string at or after position fromIndex, then - * -1 is returned. - * - *

- * There is no restriction on the value of fromIndex. If it - * is negative, it has the same effect as if it were zero: this entire - * string may be searched. If it is greater than the length of this - * string, it has the same effect as if it were equal to the length of - * this string: -1 is returned. - * - *

All indices are specified in char values - * (Unicode code units). - * - * @param ch a character (Unicode code point). - * @param fromIndex the index to start the search from. - * @return the index of the first occurrence of the character in the - * character sequence represented by this object that is greater - * than or equal to fromIndex, or -1 - * if the character does not occur. - */ - @JavaScriptBody(args = { "ch", "from" }, body = - "if (typeof ch === 'number') ch = String.fromCharCode(ch);\n" + - "return this.toString().indexOf(ch, from);\n" - ) - public int indexOf(int ch, int fromIndex) { - if (fromIndex < 0) { - fromIndex = 0; - } else if (fromIndex >= length()) { - // Note: fromIndex might be near -1>>>1. - return -1; - } - - if (ch < Character.MIN_SUPPLEMENTARY_CODE_POINT) { - // handle most cases here (ch is a BMP code point or a - // negative value (invalid code point)) - final char[] value = this.toCharArray(); - final int offset = this.offset(); - final int max = offset + length(); - for (int i = offset + fromIndex; i < max ; i++) { - if (value[i] == ch) { - return i - offset; - } - } - return -1; - } else { - return indexOfSupplementary(ch, fromIndex); - } - } - - /** - * Handles (rare) calls of indexOf with a supplementary character. - */ - private int indexOfSupplementary(int ch, int fromIndex) { - if (Character.isValidCodePoint(ch)) { - final char[] value = this.toCharArray(); - final int offset = this.offset(); - final char hi = Character.highSurrogate(ch); - final char lo = Character.lowSurrogate(ch); - final int max = offset + length() - 1; - for (int i = offset + fromIndex; i < max; i++) { - if (value[i] == hi && value[i+1] == lo) { - return i - offset; - } - } - } - return -1; - } - - /** - * Returns the index within this string of the last occurrence of - * the specified character. For values of ch in the - * range from 0 to 0xFFFF (inclusive), the index (in Unicode code - * units) returned is the largest value k such that: - *

-     * this.charAt(k) == ch
-     * 
- * is true. For other values of ch, it is the - * largest value k such that: - *
-     * this.codePointAt(k) == ch
-     * 
- * is true. In either case, if no such character occurs in this - * string, then -1 is returned. The - * String is searched backwards starting at the last - * character. - * - * @param ch a character (Unicode code point). - * @return the index of the last occurrence of the character in the - * character sequence represented by this object, or - * -1 if the character does not occur. - */ - public int lastIndexOf(int ch) { - return lastIndexOf(ch, length() - 1); - } - - /** - * Returns the index within this string of the last occurrence of - * the specified character, searching backward starting at the - * specified index. For values of ch in the range - * from 0 to 0xFFFF (inclusive), the index returned is the largest - * value k such that: - *
-     * (this.charAt(k) == ch) && (k <= fromIndex)
-     * 
- * is true. For other values of ch, it is the - * largest value k such that: - *
-     * (this.codePointAt(k) == ch) && (k <= fromIndex)
-     * 
- * is true. In either case, if no such character occurs in this - * string at or before position fromIndex, then - * -1 is returned. - * - *

All indices are specified in char values - * (Unicode code units). - * - * @param ch a character (Unicode code point). - * @param fromIndex the index to start the search from. There is no - * restriction on the value of fromIndex. If it is - * greater than or equal to the length of this string, it has - * the same effect as if it were equal to one less than the - * length of this string: this entire string may be searched. - * If it is negative, it has the same effect as if it were -1: - * -1 is returned. - * @return the index of the last occurrence of the character in the - * character sequence represented by this object that is less - * than or equal to fromIndex, or -1 - * if the character does not occur before that point. - */ - @JavaScriptBody(args = { "ch", "from" }, body = - "if (typeof ch === 'number') ch = String.fromCharCode(ch);\n" + - "return this.toString().lastIndexOf(ch, from);" - ) - public int lastIndexOf(int ch, int fromIndex) { - if (ch < Character.MIN_SUPPLEMENTARY_CODE_POINT) { - // handle most cases here (ch is a BMP code point or a - // negative value (invalid code point)) - final char[] value = this.toCharArray(); - final int offset = this.offset(); - int i = offset + Math.min(fromIndex, length() - 1); - for (; i >= offset ; i--) { - if (value[i] == ch) { - return i - offset; - } - } - return -1; - } else { - return lastIndexOfSupplementary(ch, fromIndex); - } - } - - /** - * Handles (rare) calls of lastIndexOf with a supplementary character. - */ - private int lastIndexOfSupplementary(int ch, int fromIndex) { - if (Character.isValidCodePoint(ch)) { - final char[] value = this.toCharArray(); - final int offset = this.offset(); - char hi = Character.highSurrogate(ch); - char lo = Character.lowSurrogate(ch); - int i = offset + Math.min(fromIndex, length() - 2); - for (; i >= offset; i--) { - if (value[i] == hi && value[i+1] == lo) { - return i - offset; - } - } - } - return -1; - } - - /** - * Returns the index within this string of the first occurrence of the - * specified substring. - * - *

The returned index is the smallest value k for which: - *

-     * this.startsWith(str, k)
-     * 
- * If no such value of k exists, then {@code -1} is returned. - * - * @param str the substring to search for. - * @return the index of the first occurrence of the specified substring, - * or {@code -1} if there is no such occurrence. - */ - public int indexOf(String str) { - return indexOf(str, 0); - } - - /** - * Returns the index within this string of the first occurrence of the - * specified substring, starting at the specified index. - * - *

The returned index is the smallest value k for which: - *

-     * k >= fromIndex && this.startsWith(str, k)
-     * 
- * If no such value of k exists, then {@code -1} is returned. - * - * @param str the substring to search for. - * @param fromIndex the index from which to start the search. - * @return the index of the first occurrence of the specified substring, - * starting at the specified index, - * or {@code -1} if there is no such occurrence. - */ - @JavaScriptBody(args = { "str", "fromIndex" }, body = - "return this.toString().indexOf(str.toString(), fromIndex);" - ) - public native int indexOf(String str, int fromIndex); - - /** - * Returns the index within this string of the last occurrence of the - * specified substring. The last occurrence of the empty string "" - * is considered to occur at the index value {@code this.length()}. - * - *

The returned index is the largest value k for which: - *

-     * this.startsWith(str, k)
-     * 
- * If no such value of k exists, then {@code -1} is returned. - * - * @param str the substring to search for. - * @return the index of the last occurrence of the specified substring, - * or {@code -1} if there is no such occurrence. - */ - public int lastIndexOf(String str) { - return lastIndexOf(str, length()); - } - - /** - * Returns the index within this string of the last occurrence of the - * specified substring, searching backward starting at the specified index. - * - *

The returned index is the largest value k for which: - *

-     * k <= fromIndex && this.startsWith(str, k)
-     * 
- * If no such value of k exists, then {@code -1} is returned. - * - * @param str the substring to search for. - * @param fromIndex the index to start the search from. - * @return the index of the last occurrence of the specified substring, - * searching backward from the specified index, - * or {@code -1} if there is no such occurrence. - */ - @JavaScriptBody(args = { "s", "from" }, body = - "return this.toString().lastIndexOf(s.toString(), from);" - ) - public int lastIndexOf(String str, int fromIndex) { - return lastIndexOf(toCharArray(), offset(), length(), str.toCharArray(), str.offset(), str.length(), fromIndex); - } - - /** - * Code shared by String and StringBuffer to do searches. The - * source is the character array being searched, and the target - * is the string being searched for. - * - * @param source the characters being searched. - * @param sourceOffset offset of the source string. - * @param sourceCount count of the source string. - * @param target the characters being searched for. - * @param targetOffset offset of the target string. - * @param targetCount count of the target string. - * @param fromIndex the index to begin searching from. - */ - static int lastIndexOf(char[] source, int sourceOffset, int sourceCount, - char[] target, int targetOffset, int targetCount, - int fromIndex) { - /* - * Check arguments; return immediately where possible. For - * consistency, don't check for null str. - */ - int rightIndex = sourceCount - targetCount; - if (fromIndex < 0) { - return -1; - } - if (fromIndex > rightIndex) { - fromIndex = rightIndex; - } - /* Empty string always matches. */ - if (targetCount == 0) { - return fromIndex; - } - - int strLastIndex = targetOffset + targetCount - 1; - char strLastChar = target[strLastIndex]; - int min = sourceOffset + targetCount - 1; - int i = min + fromIndex; - - startSearchForLastChar: - while (true) { - while (i >= min && source[i] != strLastChar) { - i--; - } - if (i < min) { - return -1; - } - int j = i - 1; - int start = j - (targetCount - 1); - int k = strLastIndex - 1; - - while (j > start) { - if (source[j--] != target[k--]) { - i--; - continue startSearchForLastChar; - } - } - return start - sourceOffset + 1; - } - } - - /** - * Returns a new string that is a substring of this string. The - * substring begins with the character at the specified index and - * extends to the end of this string.

- * Examples: - *

-     * "unhappy".substring(2) returns "happy"
-     * "Harbison".substring(3) returns "bison"
-     * "emptiness".substring(9) returns "" (an empty string)
-     * 
- * - * @param beginIndex the beginning index, inclusive. - * @return the specified substring. - * @exception IndexOutOfBoundsException if - * beginIndex is negative or larger than the - * length of this String object. - */ - public String substring(int beginIndex) { - return substring(beginIndex, length()); - } - - /** - * Returns a new string that is a substring of this string. The - * substring begins at the specified beginIndex and - * extends to the character at index endIndex - 1. - * Thus the length of the substring is endIndex-beginIndex. - *

- * Examples: - *

-     * "hamburger".substring(4, 8) returns "urge"
-     * "smiles".substring(1, 5) returns "mile"
-     * 
- * - * @param beginIndex the beginning index, inclusive. - * @param endIndex the ending index, exclusive. - * @return the specified substring. - * @exception IndexOutOfBoundsException if the - * beginIndex is negative, or - * endIndex is larger than the length of - * this String object, or - * beginIndex is larger than - * endIndex. - */ - @JavaScriptBody(args = { "beginIndex", "endIndex" }, body = - "return this.toString().substring(beginIndex, endIndex);" - ) - public String substring(int beginIndex, int endIndex) { - if (beginIndex < 0) { - throw new StringIndexOutOfBoundsException(beginIndex); - } - if (endIndex > length()) { - throw new StringIndexOutOfBoundsException(endIndex); - } - if (beginIndex > endIndex) { - throw new StringIndexOutOfBoundsException(endIndex - beginIndex); - } - return ((beginIndex == 0) && (endIndex == length())) ? this : - new String(toCharArray(), offset() + beginIndex, endIndex - beginIndex); - } - - /** - * Returns a new character sequence that is a subsequence of this sequence. - * - *

An invocation of this method of the form - * - *

-     * str.subSequence(begin, end)
- * - * behaves in exactly the same way as the invocation - * - *
-     * str.substring(begin, end)
- * - * This method is defined so that the String class can implement - * the {@link CharSequence} interface.

- * - * @param beginIndex the begin index, inclusive. - * @param endIndex the end index, exclusive. - * @return the specified subsequence. - * - * @throws IndexOutOfBoundsException - * if beginIndex or endIndex are negative, - * if endIndex is greater than length(), - * or if beginIndex is greater than startIndex - * - * @since 1.4 - * @spec JSR-51 - */ - public CharSequence subSequence(int beginIndex, int endIndex) { - return this.substring(beginIndex, endIndex); - } - - /** - * Concatenates the specified string to the end of this string. - *

- * If the length of the argument string is 0, then this - * String object is returned. Otherwise, a new - * String object is created, representing a character - * sequence that is the concatenation of the character sequence - * represented by this String object and the character - * sequence represented by the argument string.

- * Examples: - *

-     * "cares".concat("s") returns "caress"
-     * "to".concat("get").concat("her") returns "together"
-     * 
- * - * @param str the String that is concatenated to the end - * of this String. - * @return a string that represents the concatenation of this object's - * characters followed by the string argument's characters. - */ - public String concat(String str) { - int otherLen = str.length(); - if (otherLen == 0) { - return this; - } - char buf[] = new char[length() + otherLen]; - getChars(0, length(), buf, 0); - str.getChars(0, otherLen, buf, length()); - return new String(buf, 0, length() + otherLen); - } - - /** - * Returns a new string resulting from replacing all occurrences of - * oldChar in this string with newChar. - *

- * If the character oldChar does not occur in the - * character sequence represented by this String object, - * then a reference to this String object is returned. - * Otherwise, a new String object is created that - * represents a character sequence identical to the character sequence - * represented by this String object, except that every - * occurrence of oldChar is replaced by an occurrence - * of newChar. - *

- * Examples: - *

-     * "mesquite in your cellar".replace('e', 'o')
-     *         returns "mosquito in your collar"
-     * "the war of baronets".replace('r', 'y')
-     *         returns "the way of bayonets"
-     * "sparring with a purple porpoise".replace('p', 't')
-     *         returns "starring with a turtle tortoise"
-     * "JonL".replace('q', 'x') returns "JonL" (no change)
-     * 
- * - * @param oldChar the old character. - * @param newChar the new character. - * @return a string derived from this string by replacing every - * occurrence of oldChar with newChar. - */ - @JavaScriptBody(args = { "arg1", "arg2" }, body = - "if (typeof arg1 === 'number') arg1 = String.fromCharCode(arg1);\n" + - "if (typeof arg2 === 'number') arg2 = String.fromCharCode(arg2);\n" + - "var s = this.toString();\n" + - "for (;;) {\n" + - " var ret = s.replace(arg1, arg2);\n" + - " if (ret === s) {\n" + - " return ret;\n" + - " }\n" + - " s = ret;\n" + - "}" - ) - public String replace(char oldChar, char newChar) { - if (oldChar != newChar) { - int len = length(); - int i = -1; - char[] val = toCharArray(); /* avoid getfield opcode */ - int off = offset(); /* avoid getfield opcode */ - - while (++i < len) { - if (val[off + i] == oldChar) { - break; - } - } - if (i < len) { - char buf[] = new char[len]; - for (int j = 0 ; j < i ; j++) { - buf[j] = val[off+j]; - } - while (i < len) { - char c = val[off + i]; - buf[i] = (c == oldChar) ? newChar : c; - i++; - } - return new String(buf, 0, len); - } - } - return this; - } - - /** - * Tells whether or not this string matches the given regular expression. - * - *

An invocation of this method of the form - * str.matches(regex) yields exactly the - * same result as the expression - * - *

{@link java.util.regex.Pattern}.{@link - * java.util.regex.Pattern#matches(String,CharSequence) - * matches}(regex, str)
- * - * @param regex - * the regular expression to which this string is to be matched - * - * @return true if, and only if, this string matches the - * given regular expression - * - * @throws PatternSyntaxException - * if the regular expression's syntax is invalid - * - * @see java.util.regex.Pattern - * - * @since 1.4 - * @spec JSR-51 - */ - @JavaScriptBody(args = { "regex" }, body = - "var self = this.toString();\n" - + "var re = new RegExp(regex.toString());\n" - + "var r = re.exec(self);\n" - + "return r != null && r.length > 0 && self.length == r[0].length;" - ) - public boolean matches(String regex) { - throw new UnsupportedOperationException(); - } - - /** - * Returns true if and only if this string contains the specified - * sequence of char values. - * - * @param s the sequence to search for - * @return true if this string contains s, false otherwise - * @throws NullPointerException if s is null - * @since 1.5 - */ - public boolean contains(CharSequence s) { - return indexOf(s.toString()) > -1; - } - - /** - * Replaces the first substring of this string that matches the given regular expression with the - * given replacement. - * - *

An invocation of this method of the form - * str.replaceFirst(regex, repl) - * yields exactly the same result as the expression - * - *

- * {@link java.util.regex.Pattern}.{@link java.util.regex.Pattern#compile - * compile}(regex).{@link - * java.util.regex.Pattern#matcher(java.lang.CharSequence) - * matcher}(str).{@link java.util.regex.Matcher#replaceFirst - * replaceFirst}(repl)
- * - *

- * Note that backslashes (\) and dollar signs ($) in the - * replacement string may cause the results to be different than if it were - * being treated as a literal replacement string; see - * {@link java.util.regex.Matcher#replaceFirst}. - * Use {@link java.util.regex.Matcher#quoteReplacement} to suppress the special - * meaning of these characters, if desired. - * - * @param regex - * the regular expression to which this string is to be matched - * @param replacement - * the string to be substituted for the first match - * - * @return The resulting String - * - * @throws PatternSyntaxException - * if the regular expression's syntax is invalid - * - * @see java.util.regex.Pattern - * - * @since 1.4 - * @spec JSR-51 - */ - public String replaceFirst(String regex, String replacement) { - throw new UnsupportedOperationException(); - } - - /** - * Replaces each substring of this string that matches the given regular expression with the - * given replacement. - * - *

An invocation of this method of the form - * str.replaceAll(regex, repl) - * yields exactly the same result as the expression - * - *

- * {@link java.util.regex.Pattern}.{@link java.util.regex.Pattern#compile - * compile}(regex).{@link - * java.util.regex.Pattern#matcher(java.lang.CharSequence) - * matcher}(str).{@link java.util.regex.Matcher#replaceAll - * replaceAll}(repl)
- * - *

- * Note that backslashes (\) and dollar signs ($) in the - * replacement string may cause the results to be different than if it were - * being treated as a literal replacement string; see - * {@link java.util.regex.Matcher#replaceAll Matcher.replaceAll}. - * Use {@link java.util.regex.Matcher#quoteReplacement} to suppress the special - * meaning of these characters, if desired. - * - * @param regex - * the regular expression to which this string is to be matched - * @param replacement - * the string to be substituted for each match - * - * @return The resulting String - * - * @throws PatternSyntaxException - * if the regular expression's syntax is invalid - * - * @see java.util.regex.Pattern - * - * @since 1.4 - * @spec JSR-51 - */ - public String replaceAll(String regex, String replacement) { - throw new UnsupportedOperationException(); - } - - /** - * Replaces each substring of this string that matches the literal target - * sequence with the specified literal replacement sequence. The - * replacement proceeds from the beginning of the string to the end, for - * example, replacing "aa" with "b" in the string "aaa" will result in - * "ba" rather than "ab". - * - * @param target The sequence of char values to be replaced - * @param replacement The replacement sequence of char values - * @return The resulting string - * @throws NullPointerException if target or - * replacement is null. - * @since 1.5 - */ - public String replace(CharSequence target, CharSequence replacement) { - throw new UnsupportedOperationException("This one should be supported, but without dep on rest of regexp"); - } - - /** - * Splits this string around matches of the given - * regular expression. - * - *

The array returned by this method contains each substring of this - * string that is terminated by another substring that matches the given - * expression or is terminated by the end of the string. The substrings in - * the array are in the order in which they occur in this string. If the - * expression does not match any part of the input then the resulting array - * has just one element, namely this string. - * - *

The limit parameter controls the number of times the - * pattern is applied and therefore affects the length of the resulting - * array. If the limit n is greater than zero then the pattern - * will be applied at most n - 1 times, the array's - * length will be no greater than n, and the array's last entry - * will contain all input beyond the last matched delimiter. If n - * is non-positive then the pattern will be applied as many times as - * possible and the array can have any length. If n is zero then - * the pattern will be applied as many times as possible, the array can - * have any length, and trailing empty strings will be discarded. - * - *

The string "boo:and:foo", for example, yields the - * following results with these parameters: - * - *

- * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - *
RegexLimitResult
:2{ "boo", "and:foo" }
:5{ "boo", "and", "foo" }
:-2{ "boo", "and", "foo" }
o5{ "b", "", ":and:f", "", "" }
o-2{ "b", "", ":and:f", "", "" }
o0{ "b", "", ":and:f" }
- * - *

An invocation of this method of the form - * str.split(regex, n) - * yields the same result as the expression - * - *

- * {@link java.util.regex.Pattern}.{@link java.util.regex.Pattern#compile - * compile}(regex).{@link - * java.util.regex.Pattern#split(java.lang.CharSequence,int) - * split}(str, n) - *
- * - * - * @param regex - * the delimiting regular expression - * - * @param limit - * the result threshold, as described above - * - * @return the array of strings computed by splitting this string - * around matches of the given regular expression - * - * @throws PatternSyntaxException - * if the regular expression's syntax is invalid - * - * @see java.util.regex.Pattern - * - * @since 1.4 - * @spec JSR-51 - */ - public String[] split(String regex, int limit) { - throw new UnsupportedOperationException("Needs regexp"); - } - - /** - * Splits this string around matches of the given regular expression. - * - *

This method works as if by invoking the two-argument {@link - * #split(String, int) split} method with the given expression and a limit - * argument of zero. Trailing empty strings are therefore not included in - * the resulting array. - * - *

The string "boo:and:foo", for example, yields the following - * results with these expressions: - * - *

- * - * - * - * - * - * - * - * - *
RegexResult
:{ "boo", "and", "foo" }
o{ "b", "", ":and:f" }
- * - * - * @param regex - * the delimiting regular expression - * - * @return the array of strings computed by splitting this string - * around matches of the given regular expression - * - * @throws PatternSyntaxException - * if the regular expression's syntax is invalid - * - * @see java.util.regex.Pattern - * - * @since 1.4 - * @spec JSR-51 - */ - public String[] split(String regex) { - return split(regex, 0); - } - - /** - * Converts all of the characters in this String to lower - * case using the rules of the given Locale. Case mapping is based - * on the Unicode Standard version specified by the {@link java.lang.Character Character} - * class. Since case mappings are not always 1:1 char mappings, the resulting - * String may be a different length than the original String. - *

- * Examples of lowercase mappings are in the following table: - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - *
Language Code of LocaleUpper CaseLower CaseDescription
tr (Turkish)\u0130\u0069capital letter I with dot above -> small letter i
tr (Turkish)\u0049\u0131capital letter I -> small letter dotless i
(all)French Friesfrench frieslowercased all chars in String
(all)capiotacapchi - * capthetacapupsil - * capsigmaiotachi - * thetaupsilon - * sigmalowercased all chars in String
- * - * @param locale use the case transformation rules for this locale - * @return the String, converted to lowercase. - * @see java.lang.String#toLowerCase() - * @see java.lang.String#toUpperCase() - * @see java.lang.String#toUpperCase(Locale) - * @since 1.1 - */ -// public String toLowerCase(Locale locale) { -// if (locale == null) { -// throw new NullPointerException(); -// } -// -// int firstUpper; -// -// /* Now check if there are any characters that need to be changed. */ -// scan: { -// for (firstUpper = 0 ; firstUpper < count; ) { -// char c = value[offset+firstUpper]; -// if ((c >= Character.MIN_HIGH_SURROGATE) && -// (c <= Character.MAX_HIGH_SURROGATE)) { -// int supplChar = codePointAt(firstUpper); -// if (supplChar != Character.toLowerCase(supplChar)) { -// break scan; -// } -// firstUpper += Character.charCount(supplChar); -// } else { -// if (c != Character.toLowerCase(c)) { -// break scan; -// } -// firstUpper++; -// } -// } -// return this; -// } -// -// char[] result = new char[count]; -// int resultOffset = 0; /* result may grow, so i+resultOffset -// * is the write location in result */ -// -// /* Just copy the first few lowerCase characters. */ -// arraycopy(value, offset, result, 0, firstUpper); -// -// String lang = locale.getLanguage(); -// boolean localeDependent = -// (lang == "tr" || lang == "az" || lang == "lt"); -// char[] lowerCharArray; -// int lowerChar; -// int srcChar; -// int srcCount; -// for (int i = firstUpper; i < count; i += srcCount) { -// srcChar = (int)value[offset+i]; -// if ((char)srcChar >= Character.MIN_HIGH_SURROGATE && -// (char)srcChar <= Character.MAX_HIGH_SURROGATE) { -// srcChar = codePointAt(i); -// srcCount = Character.charCount(srcChar); -// } else { -// srcCount = 1; -// } -// if (localeDependent || srcChar == '\u03A3') { // GREEK CAPITAL LETTER SIGMA -// lowerChar = ConditionalSpecialCasing.toLowerCaseEx(this, i, locale); -// } else if (srcChar == '\u0130') { // LATIN CAPITAL LETTER I DOT -// lowerChar = Character.ERROR; -// } else { -// lowerChar = Character.toLowerCase(srcChar); -// } -// if ((lowerChar == Character.ERROR) || -// (lowerChar >= Character.MIN_SUPPLEMENTARY_CODE_POINT)) { -// if (lowerChar == Character.ERROR) { -// if (!localeDependent && srcChar == '\u0130') { -// lowerCharArray = -// ConditionalSpecialCasing.toLowerCaseCharArray(this, i, Locale.ENGLISH); -// } else { -// lowerCharArray = -// ConditionalSpecialCasing.toLowerCaseCharArray(this, i, locale); -// } -// } else if (srcCount == 2) { -// resultOffset += Character.toChars(lowerChar, result, i + resultOffset) - srcCount; -// continue; -// } else { -// lowerCharArray = Character.toChars(lowerChar); -// } -// -// /* Grow result if needed */ -// int mapLen = lowerCharArray.length; -// if (mapLen > srcCount) { -// char[] result2 = new char[result.length + mapLen - srcCount]; -// arraycopy(result, 0, result2, 0, -// i + resultOffset); -// result = result2; -// } -// for (int x=0; xString to lower - * case using the rules of the default locale. This is equivalent to calling - * toLowerCase(Locale.getDefault()). - *

- * Note: This method is locale sensitive, and may produce unexpected - * results if used for strings that are intended to be interpreted locale - * independently. - * Examples are programming language identifiers, protocol keys, and HTML - * tags. - * For instance, "TITLE".toLowerCase() in a Turkish locale - * returns "t\u005Cu0131tle", where '\u005Cu0131' is the - * LATIN SMALL LETTER DOTLESS I character. - * To obtain correct results for locale insensitive strings, use - * toLowerCase(Locale.ENGLISH). - *

- * @return the String, converted to lowercase. - * @see java.lang.String#toLowerCase(Locale) - */ - @JavaScriptBody(args = {}, body = "return this.toLowerCase();") - public String toLowerCase() { - throw new UnsupportedOperationException("Should be supported but without connection to locale"); - } - - /** - * Converts all of the characters in this String to upper - * case using the rules of the given Locale. Case mapping is based - * on the Unicode Standard version specified by the {@link java.lang.Character Character} - * class. Since case mappings are not always 1:1 char mappings, the resulting - * String may be a different length than the original String. - *

- * Examples of locale-sensitive and 1:M case mappings are in the following table. - *

- * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - *
Language Code of LocaleLower CaseUpper CaseDescription
tr (Turkish)\u0069\u0130small letter i -> capital letter I with dot above
tr (Turkish)\u0131\u0049small letter dotless i -> capital letter I
(all)\u00df\u0053 \u0053small letter sharp s -> two letters: SS
(all)FahrvergnügenFAHRVERGNÜGEN
- * @param locale use the case transformation rules for this locale - * @return the String, converted to uppercase. - * @see java.lang.String#toUpperCase() - * @see java.lang.String#toLowerCase() - * @see java.lang.String#toLowerCase(Locale) - * @since 1.1 - */ - /* not for javascript - public String toUpperCase(Locale locale) { - if (locale == null) { - throw new NullPointerException(); - } - - int firstLower; - - // Now check if there are any characters that need to be changed. - scan: { - for (firstLower = 0 ; firstLower < count; ) { - int c = (int)value[offset+firstLower]; - int srcCount; - if ((c >= Character.MIN_HIGH_SURROGATE) && - (c <= Character.MAX_HIGH_SURROGATE)) { - c = codePointAt(firstLower); - srcCount = Character.charCount(c); - } else { - srcCount = 1; - } - int upperCaseChar = Character.toUpperCaseEx(c); - if ((upperCaseChar == Character.ERROR) || - (c != upperCaseChar)) { - break scan; - } - firstLower += srcCount; - } - return this; - } - - char[] result = new char[count]; /* may grow * - int resultOffset = 0; /* result may grow, so i+resultOffset - * is the write location in result * - - /* Just copy the first few upperCase characters. * - arraycopy(value, offset, result, 0, firstLower); - - String lang = locale.getLanguage(); - boolean localeDependent = - (lang == "tr" || lang == "az" || lang == "lt"); - char[] upperCharArray; - int upperChar; - int srcChar; - int srcCount; - for (int i = firstLower; i < count; i += srcCount) { - srcChar = (int)value[offset+i]; - if ((char)srcChar >= Character.MIN_HIGH_SURROGATE && - (char)srcChar <= Character.MAX_HIGH_SURROGATE) { - srcChar = codePointAt(i); - srcCount = Character.charCount(srcChar); - } else { - srcCount = 1; - } - if (localeDependent) { - upperChar = ConditionalSpecialCasing.toUpperCaseEx(this, i, locale); - } else { - upperChar = Character.toUpperCaseEx(srcChar); - } - if ((upperChar == Character.ERROR) || - (upperChar >= Character.MIN_SUPPLEMENTARY_CODE_POINT)) { - if (upperChar == Character.ERROR) { - if (localeDependent) { - upperCharArray = - ConditionalSpecialCasing.toUpperCaseCharArray(this, i, locale); - } else { - upperCharArray = Character.toUpperCaseCharArray(srcChar); - } - } else if (srcCount == 2) { - resultOffset += Character.toChars(upperChar, result, i + resultOffset) - srcCount; - continue; - } else { - upperCharArray = Character.toChars(upperChar); - } - - /* Grow result if needed * - int mapLen = upperCharArray.length; - if (mapLen > srcCount) { - char[] result2 = new char[result.length + mapLen - srcCount]; - arraycopy(result, 0, result2, 0, - i + resultOffset); - result = result2; - } - for (int x=0; xString to upper - * case using the rules of the default locale. This method is equivalent to - * toUpperCase(Locale.getDefault()). - *

- * Note: This method is locale sensitive, and may produce unexpected - * results if used for strings that are intended to be interpreted locale - * independently. - * Examples are programming language identifiers, protocol keys, and HTML - * tags. - * For instance, "title".toUpperCase() in a Turkish locale - * returns "T\u005Cu0130TLE", where '\u005Cu0130' is the - * LATIN CAPITAL LETTER I WITH DOT ABOVE character. - * To obtain correct results for locale insensitive strings, use - * toUpperCase(Locale.ENGLISH). - *

- * @return the String, converted to uppercase. - * @see java.lang.String#toUpperCase(Locale) - */ - @JavaScriptBody(args = {}, body = "return this.toUpperCase();") - public String toUpperCase() { - throw new UnsupportedOperationException(); - } - - /** - * Returns a copy of the string, with leading and trailing whitespace - * omitted. - *

- * If this String object represents an empty character - * sequence, or the first and last characters of character sequence - * represented by this String object both have codes - * greater than '\u0020' (the space character), then a - * reference to this String object is returned. - *

- * Otherwise, if there is no character with a code greater than - * '\u0020' in the string, then a new - * String object representing an empty string is created - * and returned. - *

- * Otherwise, let k be the index of the first character in the - * string whose code is greater than '\u0020', and let - * m be the index of the last character in the string whose code - * is greater than '\u0020'. A new String - * object is created, representing the substring of this string that - * begins with the character at index k and ends with the - * character at index m-that is, the result of - * this.substring(km+1). - *

- * This method may be used to trim whitespace (as defined above) from - * the beginning and end of a string. - * - * @return A copy of this string with leading and trailing white - * space removed, or this string if it has no leading or - * trailing white space. - */ - public String trim() { - int len = length(); - int st = 0; - int off = offset(); /* avoid getfield opcode */ - char[] val = toCharArray(); /* avoid getfield opcode */ - - while ((st < len) && (val[off + st] <= ' ')) { - st++; - } - while ((st < len) && (val[off + len - 1] <= ' ')) { - len--; - } - return ((st > 0) || (len < length())) ? substring(st, len) : this; - } - - /** - * This object (which is already a string!) is itself returned. - * - * @return the string itself. - */ - @JavaScriptBody(args = {}, body = "return this.toString();") - public String toString() { - return this; - } - - /** - * Converts this string to a new character array. - * - * @return a newly allocated character array whose length is the length - * of this string and whose contents are initialized to contain - * the character sequence represented by this string. - */ - public char[] toCharArray() { - char result[] = new char[length()]; - getChars(0, length(), result, 0); - return result; - } - - /** - * Returns a formatted string using the specified format string and - * arguments. - * - *

The locale always used is the one returned by {@link - * java.util.Locale#getDefault() Locale.getDefault()}. - * - * @param format - * A format string - * - * @param args - * Arguments referenced by the format specifiers in the format - * string. If there are more arguments than format specifiers, the - * extra arguments are ignored. The number of arguments is - * variable and may be zero. The maximum number of arguments is - * limited by the maximum dimension of a Java array as defined by - * The Java™ Virtual Machine Specification. - * The behaviour on a - * null argument depends on the conversion. - * - * @throws IllegalFormatException - * If a format string contains an illegal syntax, a format - * specifier that is incompatible with the given arguments, - * insufficient arguments given the format string, or other - * illegal conditions. For specification of all possible - * formatting errors, see the Details section of the - * formatter class specification. - * - * @throws NullPointerException - * If the format is null - * - * @return A formatted string - * - * @see java.util.Formatter - * @since 1.5 - */ - public static String format(String format, Object ... args) { - throw new UnsupportedOperationException(); - } - - /** - * Returns a formatted string using the specified locale, format string, - * and arguments. - * - * @param l - * The {@linkplain java.util.Locale locale} to apply during - * formatting. If l is null then no localization - * is applied. - * - * @param format - * A format string - * - * @param args - * Arguments referenced by the format specifiers in the format - * string. If there are more arguments than format specifiers, the - * extra arguments are ignored. The number of arguments is - * variable and may be zero. The maximum number of arguments is - * limited by the maximum dimension of a Java array as defined by - * The Java™ Virtual Machine Specification. - * The behaviour on a - * null argument depends on the conversion. - * - * @throws IllegalFormatException - * If a format string contains an illegal syntax, a format - * specifier that is incompatible with the given arguments, - * insufficient arguments given the format string, or other - * illegal conditions. For specification of all possible - * formatting errors, see the Details section of the - * formatter class specification - * - * @throws NullPointerException - * If the format is null - * - * @return A formatted string - * - * @see java.util.Formatter - * @since 1.5 - */ -// public static String format(Locale l, String format, Object ... args) { -// return new Formatter(l).format(format, args).toString(); -// } - - /** - * Returns the string representation of the Object argument. - * - * @param obj an Object. - * @return if the argument is null, then a string equal to - * "null"; otherwise, the value of - * obj.toString() is returned. - * @see java.lang.Object#toString() - */ - public static String valueOf(Object obj) { - return (obj == null) ? "null" : obj.toString(); - } - - /** - * Returns the string representation of the char array - * argument. The contents of the character array are copied; subsequent - * modification of the character array does not affect the newly - * created string. - * - * @param data a char array. - * @return a newly allocated string representing the same sequence of - * characters contained in the character array argument. - */ - public static String valueOf(char data[]) { - return new String(data); - } - - /** - * Returns the string representation of a specific subarray of the - * char array argument. - *

- * The offset argument is the index of the first - * character of the subarray. The count argument - * specifies the length of the subarray. The contents of the subarray - * are copied; subsequent modification of the character array does not - * affect the newly created string. - * - * @param data the character array. - * @param offset the initial offset into the value of the - * String. - * @param count the length of the value of the String. - * @return a string representing the sequence of characters contained - * in the subarray of the character array argument. - * @exception IndexOutOfBoundsException if offset is - * negative, or count is negative, or - * offset+count is larger than - * data.length. - */ - public static String valueOf(char data[], int offset, int count) { - return new String(data, offset, count); - } - - /** - * Returns a String that represents the character sequence in the - * array specified. - * - * @param data the character array. - * @param offset initial offset of the subarray. - * @param count length of the subarray. - * @return a String that contains the characters of the - * specified subarray of the character array. - */ - public static String copyValueOf(char data[], int offset, int count) { - // All public String constructors now copy the data. - return new String(data, offset, count); - } - - /** - * Returns a String that represents the character sequence in the - * array specified. - * - * @param data the character array. - * @return a String that contains the characters of the - * character array. - */ - public static String copyValueOf(char data[]) { - return copyValueOf(data, 0, data.length); - } - - /** - * Returns the string representation of the boolean argument. - * - * @param b a boolean. - * @return if the argument is true, a string equal to - * "true" is returned; otherwise, a string equal to - * "false" is returned. - */ - public static String valueOf(boolean b) { - return b ? "true" : "false"; - } - - /** - * Returns the string representation of the char - * argument. - * - * @param c a char. - * @return a string of length 1 containing - * as its single character the argument c. - */ - public static String valueOf(char c) { - char data[] = {c}; - return new String(data, 0, 1); - } - - /** - * Returns the string representation of the int argument. - *

- * The representation is exactly the one returned by the - * Integer.toString method of one argument. - * - * @param i an int. - * @return a string representation of the int argument. - * @see java.lang.Integer#toString(int, int) - */ - public static String valueOf(int i) { - return Integer.toString(i); - } - - /** - * Returns the string representation of the long argument. - *

- * The representation is exactly the one returned by the - * Long.toString method of one argument. - * - * @param l a long. - * @return a string representation of the long argument. - * @see java.lang.Long#toString(long) - */ - public static String valueOf(long l) { - return Long.toString(l); - } - - /** - * Returns the string representation of the float argument. - *

- * The representation is exactly the one returned by the - * Float.toString method of one argument. - * - * @param f a float. - * @return a string representation of the float argument. - * @see java.lang.Float#toString(float) - */ - public static String valueOf(float f) { - return Float.toString(f); - } - - /** - * Returns the string representation of the double argument. - *

- * The representation is exactly the one returned by the - * Double.toString method of one argument. - * - * @param d a double. - * @return a string representation of the double argument. - * @see java.lang.Double#toString(double) - */ - public static String valueOf(double d) { - return Double.toString(d); - } - - /** - * Returns a canonical representation for the string object. - *

- * A pool of strings, initially empty, is maintained privately by the - * class String. - *

- * When the intern method is invoked, if the pool already contains a - * string equal to this String object as determined by - * the {@link #equals(Object)} method, then the string from the pool is - * returned. Otherwise, this String object is added to the - * pool and a reference to this String object is returned. - *

- * It follows that for any two strings s and t, - * s.intern() == t.intern() is true - * if and only if s.equals(t) is true. - *

- * All literal strings and string-valued constant expressions are - * interned. String literals are defined in section 3.10.5 of the - * The Java™ Language Specification. - * - * @return a string that has the same contents as this string, but is - * guaranteed to be from a pool of unique strings. - */ - public native String intern(); -} diff -r 388e48c0a37a -r 05224402145d emul/src/main/java/java/lang/StringBuffer.java --- a/emul/src/main/java/java/lang/StringBuffer.java Wed Jan 23 20:16:48 2013 +0100 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,604 +0,0 @@ -/* - * Copyright (c) 1994, 2008, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code 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 - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package java.lang; - - -/** - * A thread-safe, mutable sequence of characters. - * A string buffer is like a {@link String}, but can be modified. At any - * point in time it contains some particular sequence of characters, but - * the length and content of the sequence can be changed through certain - * method calls. - *

- * String buffers are safe for use by multiple threads. The methods - * are synchronized where necessary so that all the operations on any - * particular instance behave as if they occur in some serial order - * that is consistent with the order of the method calls made by each of - * the individual threads involved. - *

- * The principal operations on a StringBuffer are the - * append and insert methods, which are - * overloaded so as to accept data of any type. Each effectively - * converts a given datum to a string and then appends or inserts the - * characters of that string to the string buffer. The - * append method always adds these characters at the end - * of the buffer; the insert method adds the characters at - * a specified point. - *

- * For example, if z refers to a string buffer object - * whose current contents are "start", then - * the method call z.append("le") would cause the string - * buffer to contain "startle", whereas - * z.insert(4, "le") would alter the string buffer to - * contain "starlet". - *

- * In general, if sb refers to an instance of a StringBuffer, - * then sb.append(x) has the same effect as - * sb.insert(sb.length(), x). - *

- * Whenever an operation occurs involving a source sequence (such as - * appending or inserting from a source sequence) this class synchronizes - * only on the string buffer performing the operation, not on the source. - *

- * Every string buffer has a capacity. As long as the length of the - * character sequence contained in the string buffer does not exceed - * the capacity, it is not necessary to allocate a new internal - * buffer array. If the internal buffer overflows, it is - * automatically made larger. - * - * As of release JDK 5, this class has been supplemented with an equivalent - * class designed for use by a single thread, {@link StringBuilder}. The - * StringBuilder class should generally be used in preference to - * this one, as it supports all of the same operations but it is faster, as - * it performs no synchronization. - * - * @author Arthur van Hoff - * @see java.lang.StringBuilder - * @see java.lang.String - * @since JDK1.0 - */ - public final class StringBuffer - extends AbstractStringBuilder - implements java.io.Serializable, CharSequence -{ - - /** use serialVersionUID from JDK 1.0.2 for interoperability */ - static final long serialVersionUID = 3388685877147921107L; - - /** - * Constructs a string buffer with no characters in it and an - * initial capacity of 16 characters. - */ - public StringBuffer() { - super(16); - } - - /** - * Constructs a string buffer with no characters in it and - * the specified initial capacity. - * - * @param capacity the initial capacity. - * @exception NegativeArraySizeException if the capacity - * argument is less than 0. - */ - public StringBuffer(int capacity) { - super(capacity); - } - - /** - * Constructs a string buffer initialized to the contents of the - * specified string. The initial capacity of the string buffer is - * 16 plus the length of the string argument. - * - * @param str the initial contents of the buffer. - * @exception NullPointerException if str is null - */ - public StringBuffer(String str) { - super(str.length() + 16); - append(str); - } - - /** - * Constructs a string buffer that contains the same characters - * as the specified CharSequence. The initial capacity of - * the string buffer is 16 plus the length of the - * CharSequence argument. - *

- * If the length of the specified CharSequence is - * less than or equal to zero, then an empty buffer of capacity - * 16 is returned. - * - * @param seq the sequence to copy. - * @exception NullPointerException if seq is null - * @since 1.5 - */ - public StringBuffer(CharSequence seq) { - this(seq.length() + 16); - append(seq); - } - - public synchronized int length() { - return count; - } - - public synchronized int capacity() { - return value.length; - } - - - public synchronized void ensureCapacity(int minimumCapacity) { - if (minimumCapacity > value.length) { - expandCapacity(minimumCapacity); - } - } - - /** - * @since 1.5 - */ - public synchronized void trimToSize() { - super.trimToSize(); - } - - /** - * @throws IndexOutOfBoundsException {@inheritDoc} - * @see #length() - */ - public synchronized void setLength(int newLength) { - super.setLength(newLength); - } - - /** - * @throws IndexOutOfBoundsException {@inheritDoc} - * @see #length() - */ - public synchronized char charAt(int index) { - if ((index < 0) || (index >= count)) - throw new StringIndexOutOfBoundsException(index); - return value[index]; - } - - /** - * @since 1.5 - */ - public synchronized int codePointAt(int index) { - return super.codePointAt(index); - } - - /** - * @since 1.5 - */ - public synchronized int codePointBefore(int index) { - return super.codePointBefore(index); - } - - /** - * @since 1.5 - */ - public synchronized int codePointCount(int beginIndex, int endIndex) { - return super.codePointCount(beginIndex, endIndex); - } - - /** - * @since 1.5 - */ - public synchronized int offsetByCodePoints(int index, int codePointOffset) { - return super.offsetByCodePoints(index, codePointOffset); - } - - /** - * @throws NullPointerException {@inheritDoc} - * @throws IndexOutOfBoundsException {@inheritDoc} - */ - public synchronized void getChars(int srcBegin, int srcEnd, char[] dst, - int dstBegin) - { - super.getChars(srcBegin, srcEnd, dst, dstBegin); - } - - /** - * @throws IndexOutOfBoundsException {@inheritDoc} - * @see #length() - */ - public synchronized void setCharAt(int index, char ch) { - if ((index < 0) || (index >= count)) - throw new StringIndexOutOfBoundsException(index); - value[index] = ch; - } - - public synchronized StringBuffer append(Object obj) { - super.append(String.valueOf(obj)); - return this; - } - - public synchronized StringBuffer append(String str) { - super.append(str); - return this; - } - - /** - * Appends the specified StringBuffer to this sequence. - *

- * The characters of the StringBuffer argument are appended, - * in order, to the contents of this StringBuffer, increasing the - * length of this StringBuffer by the length of the argument. - * If sb is null, then the four characters - * "null" are appended to this StringBuffer. - *

- * Let n be the length of the old character sequence, the one - * contained in the StringBuffer just prior to execution of the - * append method. Then the character at index k in - * the new character sequence is equal to the character at index k - * in the old character sequence, if k is less than n; - * otherwise, it is equal to the character at index k-n in the - * argument sb. - *

- * This method synchronizes on this (the destination) - * object but does not synchronize on the source (sb). - * - * @param sb the StringBuffer to append. - * @return a reference to this object. - * @since 1.4 - */ - public synchronized StringBuffer append(StringBuffer sb) { - super.append(sb); - return this; - } - - - /** - * Appends the specified CharSequence to this - * sequence. - *

- * The characters of the CharSequence argument are appended, - * in order, increasing the length of this sequence by the length of the - * argument. - * - *

The result of this method is exactly the same as if it were an - * invocation of this.append(s, 0, s.length()); - * - *

This method synchronizes on this (the destination) - * object but does not synchronize on the source (s). - * - *

If s is null, then the four characters - * "null" are appended. - * - * @param s the CharSequence to append. - * @return a reference to this object. - * @since 1.5 - */ - public StringBuffer append(CharSequence s) { - // Note, synchronization achieved via other invocations - if (s == null) - s = "null"; - if (s instanceof String) - return this.append((String)s); - if (s instanceof StringBuffer) - return this.append((StringBuffer)s); - return this.append(s, 0, s.length()); - } - - /** - * @throws IndexOutOfBoundsException {@inheritDoc} - * @since 1.5 - */ - public synchronized StringBuffer append(CharSequence s, int start, int end) - { - super.append(s, start, end); - return this; - } - - public synchronized StringBuffer append(char[] str) { - super.append(str); - return this; - } - - /** - * @throws IndexOutOfBoundsException {@inheritDoc} - */ - public synchronized StringBuffer append(char[] str, int offset, int len) { - super.append(str, offset, len); - return this; - } - - public synchronized StringBuffer append(boolean b) { - super.append(b); - return this; - } - - public synchronized StringBuffer append(char c) { - super.append(c); - return this; - } - - public synchronized StringBuffer append(int i) { - super.append(i); - return this; - } - - /** - * @since 1.5 - */ - public synchronized StringBuffer appendCodePoint(int codePoint) { - super.appendCodePoint(codePoint); - return this; - } - - public synchronized StringBuffer append(long lng) { - super.append(lng); - return this; - } - - public synchronized StringBuffer append(float f) { - super.append(f); - return this; - } - - public synchronized StringBuffer append(double d) { - super.append(d); - return this; - } - - /** - * @throws StringIndexOutOfBoundsException {@inheritDoc} - * @since 1.2 - */ - public synchronized StringBuffer delete(int start, int end) { - super.delete(start, end); - return this; - } - - /** - * @throws StringIndexOutOfBoundsException {@inheritDoc} - * @since 1.2 - */ - public synchronized StringBuffer deleteCharAt(int index) { - super.deleteCharAt(index); - return this; - } - - /** - * @throws StringIndexOutOfBoundsException {@inheritDoc} - * @since 1.2 - */ - public synchronized StringBuffer replace(int start, int end, String str) { - super.replace(start, end, str); - return this; - } - - /** - * @throws StringIndexOutOfBoundsException {@inheritDoc} - * @since 1.2 - */ - public synchronized String substring(int start) { - return substring(start, count); - } - - /** - * @throws IndexOutOfBoundsException {@inheritDoc} - * @since 1.4 - */ - public synchronized CharSequence subSequence(int start, int end) { - return super.substring(start, end); - } - - /** - * @throws StringIndexOutOfBoundsException {@inheritDoc} - * @since 1.2 - */ - public synchronized String substring(int start, int end) { - return super.substring(start, end); - } - - /** - * @throws StringIndexOutOfBoundsException {@inheritDoc} - * @since 1.2 - */ - public synchronized StringBuffer insert(int index, char[] str, int offset, - int len) - { - super.insert(index, str, offset, len); - return this; - } - - /** - * @throws StringIndexOutOfBoundsException {@inheritDoc} - */ - public synchronized StringBuffer insert(int offset, Object obj) { - super.insert(offset, String.valueOf(obj)); - return this; - } - - /** - * @throws StringIndexOutOfBoundsException {@inheritDoc} - */ - public synchronized StringBuffer insert(int offset, String str) { - super.insert(offset, str); - return this; - } - - /** - * @throws StringIndexOutOfBoundsException {@inheritDoc} - */ - public synchronized StringBuffer insert(int offset, char[] str) { - super.insert(offset, str); - return this; - } - - /** - * @throws IndexOutOfBoundsException {@inheritDoc} - * @since 1.5 - */ - public StringBuffer insert(int dstOffset, CharSequence s) { - // Note, synchronization achieved via other invocations - if (s == null) - s = "null"; - if (s instanceof String) - return this.insert(dstOffset, (String)s); - return this.insert(dstOffset, s, 0, s.length()); - } - - /** - * @throws IndexOutOfBoundsException {@inheritDoc} - * @since 1.5 - */ - public synchronized StringBuffer insert(int dstOffset, CharSequence s, - int start, int end) - { - super.insert(dstOffset, s, start, end); - return this; - } - - /** - * @throws StringIndexOutOfBoundsException {@inheritDoc} - */ - public StringBuffer insert(int offset, boolean b) { - return insert(offset, String.valueOf(b)); - } - - /** - * @throws IndexOutOfBoundsException {@inheritDoc} - */ - public synchronized StringBuffer insert(int offset, char c) { - super.insert(offset, c); - return this; - } - - /** - * @throws StringIndexOutOfBoundsException {@inheritDoc} - */ - public StringBuffer insert(int offset, int i) { - return insert(offset, String.valueOf(i)); - } - - /** - * @throws StringIndexOutOfBoundsException {@inheritDoc} - */ - public StringBuffer insert(int offset, long l) { - return insert(offset, String.valueOf(l)); - } - - /** - * @throws StringIndexOutOfBoundsException {@inheritDoc} - */ - public StringBuffer insert(int offset, float f) { - return insert(offset, String.valueOf(f)); - } - - /** - * @throws StringIndexOutOfBoundsException {@inheritDoc} - */ - public StringBuffer insert(int offset, double d) { - return insert(offset, String.valueOf(d)); - } - - /** - * @throws NullPointerException {@inheritDoc} - * @since 1.4 - */ - public int indexOf(String str) { - return indexOf(str, 0); - } - - /** - * @throws NullPointerException {@inheritDoc} - * @since 1.4 - */ - public synchronized int indexOf(String str, int fromIndex) { - return super.indexOf(str, fromIndex); - } - - /** - * @throws NullPointerException {@inheritDoc} - * @since 1.4 - */ - public int lastIndexOf(String str) { - // Note, synchronization achieved via other invocations - return lastIndexOf(str, count); - } - - /** - * @throws NullPointerException {@inheritDoc} - * @since 1.4 - */ - public synchronized int lastIndexOf(String str, int fromIndex) { - return String.lastIndexOf(value, 0, count, - str.toCharArray(), 0, str.length(), fromIndex); - } - - /** - * @since JDK1.0.2 - */ - public synchronized StringBuffer reverse() { - super.reverse(); - return this; - } - - public synchronized String toString() { - return new String(value, 0, count); - } - -// /** -// * Serializable fields for StringBuffer. -// * -// * @serialField value char[] -// * The backing character array of this StringBuffer. -// * @serialField count int -// * The number of characters in this StringBuffer. -// * @serialField shared boolean -// * A flag indicating whether the backing array is shared. -// * The value is ignored upon deserialization. -// */ -// private static final java.io.ObjectStreamField[] serialPersistentFields = -// { -// new java.io.ObjectStreamField("value", char[].class), -// new java.io.ObjectStreamField("count", Integer.TYPE), -// new java.io.ObjectStreamField("shared", Boolean.TYPE), -// }; -// -// /** -// * readObject is called to restore the state of the StringBuffer from -// * a stream. -// */ -// private synchronized void writeObject(java.io.ObjectOutputStream s) -// throws java.io.IOException { -// java.io.ObjectOutputStream.PutField fields = s.putFields(); -// fields.put("value", value); -// fields.put("count", count); -// fields.put("shared", false); -// s.writeFields(); -// } -// -// /** -// * readObject is called to restore the state of the StringBuffer from -// * a stream. -// */ -// private void readObject(java.io.ObjectInputStream s) -// throws java.io.IOException, ClassNotFoundException { -// java.io.ObjectInputStream.GetField fields = s.readFields(); -// value = (char[])fields.get("value", null); -// count = fields.get("count", 0); -// } -} diff -r 388e48c0a37a -r 05224402145d emul/src/main/java/java/lang/StringBuilder.java --- a/emul/src/main/java/java/lang/StringBuilder.java Wed Jan 23 20:16:48 2013 +0100 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,436 +0,0 @@ -/* - * Copyright (c) 2003, 2008, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code 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 - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package java.lang; - - -/** - * A mutable sequence of characters. This class provides an API compatible - * with StringBuffer, but with no guarantee of synchronization. - * This class is designed for use as a drop-in replacement for - * StringBuffer in places where the string buffer was being - * used by a single thread (as is generally the case). Where possible, - * it is recommended that this class be used in preference to - * StringBuffer as it will be faster under most implementations. - * - *

The principal operations on a StringBuilder are the - * append and insert methods, which are - * overloaded so as to accept data of any type. Each effectively - * converts a given datum to a string and then appends or inserts the - * characters of that string to the string builder. The - * append method always adds these characters at the end - * of the builder; the insert method adds the characters at - * a specified point. - *

- * For example, if z refers to a string builder object - * whose current contents are "start", then - * the method call z.append("le") would cause the string - * builder to contain "startle", whereas - * z.insert(4, "le") would alter the string builder to - * contain "starlet". - *

- * In general, if sb refers to an instance of a StringBuilder, - * then sb.append(x) has the same effect as - * sb.insert(sb.length(), x). - * - * Every string builder has a capacity. As long as the length of the - * character sequence contained in the string builder does not exceed - * the capacity, it is not necessary to allocate a new internal - * buffer. If the internal buffer overflows, it is automatically made larger. - * - *

Instances of StringBuilder are not safe for - * use by multiple threads. If such synchronization is required then it is - * recommended that {@link java.lang.StringBuffer} be used. - * - * @author Michael McCloskey - * @see java.lang.StringBuffer - * @see java.lang.String - * @since 1.5 - */ -public final class StringBuilder - extends AbstractStringBuilder - implements java.io.Serializable, CharSequence -{ - - /** use serialVersionUID for interoperability */ - static final long serialVersionUID = 4383685877147921099L; - - /** - * Constructs a string builder with no characters in it and an - * initial capacity of 16 characters. - */ - public StringBuilder() { - super(16); - } - - /** - * Constructs a string builder with no characters in it and an - * initial capacity specified by the capacity argument. - * - * @param capacity the initial capacity. - * @throws NegativeArraySizeException if the capacity - * argument is less than 0. - */ - public StringBuilder(int capacity) { - super(capacity); - } - - /** - * Constructs a string builder initialized to the contents of the - * specified string. The initial capacity of the string builder is - * 16 plus the length of the string argument. - * - * @param str the initial contents of the buffer. - * @throws NullPointerException if str is null - */ - public StringBuilder(String str) { - super(str.length() + 16); - append(str); - } - - /** - * Constructs a string builder that contains the same characters - * as the specified CharSequence. The initial capacity of - * the string builder is 16 plus the length of the - * CharSequence argument. - * - * @param seq the sequence to copy. - * @throws NullPointerException if seq is null - */ - public StringBuilder(CharSequence seq) { - this(seq.length() + 16); - append(seq); - } - - public StringBuilder append(Object obj) { - return append(String.valueOf(obj)); - } - - public StringBuilder append(String str) { - super.append(str); - return this; - } - - // Appends the specified string builder to this sequence. - private StringBuilder append(StringBuilder sb) { - if (sb == null) - return append("null"); - int len = sb.length(); - int newcount = count + len; - if (newcount > value.length) - expandCapacity(newcount); - sb.getChars(0, len, value, count); - count = newcount; - return this; - } - - /** - * Appends the specified StringBuffer to this sequence. - *

- * The characters of the StringBuffer argument are appended, - * in order, to this sequence, increasing the - * length of this sequence by the length of the argument. - * If sb is null, then the four characters - * "null" are appended to this sequence. - *

- * Let n be the length of this character sequence just prior to - * execution of the append method. Then the character at index - * k in the new character sequence is equal to the character at - * index k in the old character sequence, if k is less than - * n; otherwise, it is equal to the character at index k-n - * in the argument sb. - * - * @param sb the StringBuffer to append. - * @return a reference to this object. - */ - public StringBuilder append(StringBuffer sb) { - super.append(sb); - return this; - } - - /** - */ - public StringBuilder append(CharSequence s) { - if (s == null) - s = "null"; - if (s instanceof String) - return this.append((String)s); - if (s instanceof StringBuffer) - return this.append((StringBuffer)s); - if (s instanceof StringBuilder) - return this.append((StringBuilder)s); - return this.append(s, 0, s.length()); - } - - /** - * @throws IndexOutOfBoundsException {@inheritDoc} - */ - public StringBuilder append(CharSequence s, int start, int end) { - super.append(s, start, end); - return this; - } - - public StringBuilder append(char[] str) { - super.append(str); - return this; - } - - /** - * @throws IndexOutOfBoundsException {@inheritDoc} - */ - public StringBuilder append(char[] str, int offset, int len) { - super.append(str, offset, len); - return this; - } - - public StringBuilder append(boolean b) { - super.append(b); - return this; - } - - public StringBuilder append(char c) { - super.append(c); - return this; - } - - public StringBuilder append(int i) { - super.append(i); - return this; - } - - public StringBuilder append(long lng) { - super.append(lng); - return this; - } - - public StringBuilder append(float f) { - super.append(f); - return this; - } - - public StringBuilder append(double d) { - super.append(d); - return this; - } - - /** - * @since 1.5 - */ - public StringBuilder appendCodePoint(int codePoint) { - super.appendCodePoint(codePoint); - return this; - } - - /** - * @throws StringIndexOutOfBoundsException {@inheritDoc} - */ - public StringBuilder delete(int start, int end) { - super.delete(start, end); - return this; - } - - /** - * @throws StringIndexOutOfBoundsException {@inheritDoc} - */ - public StringBuilder deleteCharAt(int index) { - super.deleteCharAt(index); - return this; - } - - /** - * @throws StringIndexOutOfBoundsException {@inheritDoc} - */ - public StringBuilder replace(int start, int end, String str) { - super.replace(start, end, str); - return this; - } - - /** - * @throws StringIndexOutOfBoundsException {@inheritDoc} - */ - public StringBuilder insert(int index, char[] str, int offset, - int len) - { - super.insert(index, str, offset, len); - return this; - } - - /** - * @throws StringIndexOutOfBoundsException {@inheritDoc} - */ - public StringBuilder insert(int offset, Object obj) { - return insert(offset, String.valueOf(obj)); - } - - /** - * @throws StringIndexOutOfBoundsException {@inheritDoc} - */ - public StringBuilder insert(int offset, String str) { - super.insert(offset, str); - return this; - } - - /** - * @throws StringIndexOutOfBoundsException {@inheritDoc} - */ - public StringBuilder insert(int offset, char[] str) { - super.insert(offset, str); - return this; - } - - /** - * @throws IndexOutOfBoundsException {@inheritDoc} - */ - public StringBuilder insert(int dstOffset, CharSequence s) { - if (s == null) - s = "null"; - if (s instanceof String) - return this.insert(dstOffset, (String)s); - return this.insert(dstOffset, s, 0, s.length()); - } - - /** - * @throws IndexOutOfBoundsException {@inheritDoc} - */ - public StringBuilder insert(int dstOffset, CharSequence s, - int start, int end) - { - super.insert(dstOffset, s, start, end); - return this; - } - - /** - * @throws StringIndexOutOfBoundsException {@inheritDoc} - */ - public StringBuilder insert(int offset, boolean b) { - super.insert(offset, b); - return this; - } - - /** - * @throws IndexOutOfBoundsException {@inheritDoc} - */ - public StringBuilder insert(int offset, char c) { - super.insert(offset, c); - return this; - } - - /** - * @throws StringIndexOutOfBoundsException {@inheritDoc} - */ - public StringBuilder insert(int offset, int i) { - return insert(offset, String.valueOf(i)); - } - - /** - * @throws StringIndexOutOfBoundsException {@inheritDoc} - */ - public StringBuilder insert(int offset, long l) { - return insert(offset, String.valueOf(l)); - } - - /** - * @throws StringIndexOutOfBoundsException {@inheritDoc} - */ - public StringBuilder insert(int offset, float f) { - return insert(offset, String.valueOf(f)); - } - - /** - * @throws StringIndexOutOfBoundsException {@inheritDoc} - */ - public StringBuilder insert(int offset, double d) { - return insert(offset, String.valueOf(d)); - } - - /** - * @throws NullPointerException {@inheritDoc} - */ - public int indexOf(String str) { - return indexOf(str, 0); - } - - /** - * @throws NullPointerException {@inheritDoc} - */ - public int indexOf(String str, int fromIndex) { - return super.indexOf(str, fromIndex); - } - - /** - * @throws NullPointerException {@inheritDoc} - */ - public int lastIndexOf(String str) { - return lastIndexOf(str, count); - } - - /** - * @throws NullPointerException {@inheritDoc} - */ - public int lastIndexOf(String str, int fromIndex) { - return String.lastIndexOf(value, 0, count, - str.toCharArray(), 0, str.length(), fromIndex); - } - - public StringBuilder reverse() { - super.reverse(); - return this; - } - - public String toString() { - // Create a copy, don't share the array - return new String(value, 0, count); - } - - /** - * Save the state of the StringBuilder instance to a stream - * (that is, serialize it). - * - * @serialData the number of characters currently stored in the string - * builder (int), followed by the characters in the - * string builder (char[]). The length of the - * char array may be greater than the number of - * characters currently stored in the string builder, in which - * case extra characters are ignored. - */ -// private void writeObject(java.io.ObjectOutputStream s) -// throws java.io.IOException { -// s.defaultWriteObject(); -// s.writeInt(count); -// s.writeObject(value); -// } - - /** - * readObject is called to restore the state of the StringBuffer from - * a stream. - */ -// private void readObject(java.io.ObjectInputStream s) -// throws java.io.IOException, ClassNotFoundException { -// s.defaultReadObject(); -// count = s.readInt(); -// value = (char[]) s.readObject(); -// } - -} diff -r 388e48c0a37a -r 05224402145d emul/src/main/java/java/lang/StringIndexOutOfBoundsException.java --- a/emul/src/main/java/java/lang/StringIndexOutOfBoundsException.java Wed Jan 23 20:16:48 2013 +0100 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,71 +0,0 @@ -/* - * Copyright (c) 1994, 2008, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code 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 - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package java.lang; - -/** - * Thrown by String methods to indicate that an index - * is either negative or greater than the size of the string. For - * some methods such as the charAt method, this exception also is - * thrown when the index is equal to the size of the string. - * - * @author unascribed - * @see java.lang.String#charAt(int) - * @since JDK1.0 - */ -public -class StringIndexOutOfBoundsException extends IndexOutOfBoundsException { - private static final long serialVersionUID = -6762910422159637258L; - - /** - * Constructs a StringIndexOutOfBoundsException with no - * detail message. - * - * @since JDK1.0. - */ - public StringIndexOutOfBoundsException() { - super(); - } - - /** - * Constructs a StringIndexOutOfBoundsException with - * the specified detail message. - * - * @param s the detail message. - */ - public StringIndexOutOfBoundsException(String s) { - super(s); - } - - /** - * Constructs a new StringIndexOutOfBoundsException - * class with an argument indicating the illegal index. - * - * @param index the illegal index. - */ - public StringIndexOutOfBoundsException(int index) { - super("String index out of range: " + index); - } -} diff -r 388e48c0a37a -r 05224402145d emul/src/main/java/java/lang/Throwable.java --- a/emul/src/main/java/java/lang/Throwable.java Wed Jan 23 20:16:48 2013 +0100 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,1088 +0,0 @@ -/* - * Copyright (c) 1994, 2011, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code 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 - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package java.lang; -import java.io.*; -import org.apidesign.bck2brwsr.core.JavaScriptBody; -import org.apidesign.bck2brwsr.core.JavaScriptOnly; - -/** - * The {@code Throwable} class is the superclass of all errors and - * exceptions in the Java language. Only objects that are instances of this - * class (or one of its subclasses) are thrown by the Java Virtual Machine or - * can be thrown by the Java {@code throw} statement. Similarly, only - * this class or one of its subclasses can be the argument type in a - * {@code catch} clause. - * - * For the purposes of compile-time checking of exceptions, {@code - * Throwable} and any subclass of {@code Throwable} that is not also a - * subclass of either {@link RuntimeException} or {@link Error} are - * regarded as checked exceptions. - * - *

Instances of two subclasses, {@link java.lang.Error} and - * {@link java.lang.Exception}, are conventionally used to indicate - * that exceptional situations have occurred. Typically, these instances - * are freshly created in the context of the exceptional situation so - * as to include relevant information (such as stack trace data). - * - *

A throwable contains a snapshot of the execution stack of its - * thread at the time it was created. It can also contain a message - * string that gives more information about the error. Over time, a - * throwable can {@linkplain Throwable#addSuppressed suppress} other - * throwables from being propagated. Finally, the throwable can also - * contain a cause: another throwable that caused this - * throwable to be constructed. The recording of this causal information - * is referred to as the chained exception facility, as the - * cause can, itself, have a cause, and so on, leading to a "chain" of - * exceptions, each caused by another. - * - *

One reason that a throwable may have a cause is that the class that - * throws it is built atop a lower layered abstraction, and an operation on - * the upper layer fails due to a failure in the lower layer. It would be bad - * design to let the throwable thrown by the lower layer propagate outward, as - * it is generally unrelated to the abstraction provided by the upper layer. - * Further, doing so would tie the API of the upper layer to the details of - * its implementation, assuming the lower layer's exception was a checked - * exception. Throwing a "wrapped exception" (i.e., an exception containing a - * cause) allows the upper layer to communicate the details of the failure to - * its caller without incurring either of these shortcomings. It preserves - * the flexibility to change the implementation of the upper layer without - * changing its API (in particular, the set of exceptions thrown by its - * methods). - * - *

A second reason that a throwable may have a cause is that the method - * that throws it must conform to a general-purpose interface that does not - * permit the method to throw the cause directly. For example, suppose - * a persistent collection conforms to the {@link java.util.Collection - * Collection} interface, and that its persistence is implemented atop - * {@code java.io}. Suppose the internals of the {@code add} method - * can throw an {@link java.io.IOException IOException}. The implementation - * can communicate the details of the {@code IOException} to its caller - * while conforming to the {@code Collection} interface by wrapping the - * {@code IOException} in an appropriate unchecked exception. (The - * specification for the persistent collection should indicate that it is - * capable of throwing such exceptions.) - * - *

A cause can be associated with a throwable in two ways: via a - * constructor that takes the cause as an argument, or via the - * {@link #initCause(Throwable)} method. New throwable classes that - * wish to allow causes to be associated with them should provide constructors - * that take a cause and delegate (perhaps indirectly) to one of the - * {@code Throwable} constructors that takes a cause. - * - * Because the {@code initCause} method is public, it allows a cause to be - * associated with any throwable, even a "legacy throwable" whose - * implementation predates the addition of the exception chaining mechanism to - * {@code Throwable}. - * - *

By convention, class {@code Throwable} and its subclasses have two - * constructors, one that takes no arguments and one that takes a - * {@code String} argument that can be used to produce a detail message. - * Further, those subclasses that might likely have a cause associated with - * them should have two more constructors, one that takes a - * {@code Throwable} (the cause), and one that takes a - * {@code String} (the detail message) and a {@code Throwable} (the - * cause). - * - * @author unascribed - * @author Josh Bloch (Added exception chaining and programmatic access to - * stack trace in 1.4.) - * @jls 11.2 Compile-Time Checking of Exceptions - * @since JDK1.0 - */ -public class Throwable implements Serializable { - /** use serialVersionUID from JDK 1.0.2 for interoperability */ - private static final long serialVersionUID = -3042686055658047285L; - - /** - * Native code saves some indication of the stack backtrace in this slot. - */ - private transient Object backtrace; - - /** - * Specific details about the Throwable. For example, for - * {@code FileNotFoundException}, this contains the name of - * the file that could not be found. - * - * @serial - */ - private String detailMessage; - - - /** - * Holder class to defer initializing sentinel objects only used - * for serialization. - */ - private static class SentinelHolder { - /** - * {@linkplain #setStackTrace(StackTraceElement[]) Setting the - * stack trace} to a one-element array containing this sentinel - * value indicates future attempts to set the stack trace will be - * ignored. The sentinal is equal to the result of calling:
- * {@code new StackTraceElement("", "", null, Integer.MIN_VALUE)} - */ - public static final StackTraceElement STACK_TRACE_ELEMENT_SENTINEL = - new StackTraceElement("", "", null, Integer.MIN_VALUE); - - /** - * Sentinel value used in the serial form to indicate an immutable - * stack trace. - */ - public static final StackTraceElement[] STACK_TRACE_SENTINEL = - new StackTraceElement[] {STACK_TRACE_ELEMENT_SENTINEL}; - } - - /** - * A shared value for an empty stack. - */ - private static final StackTraceElement[] UNASSIGNED_STACK = new StackTraceElement[0]; - - /* - * To allow Throwable objects to be made immutable and safely - * reused by the JVM, such as OutOfMemoryErrors, fields of - * Throwable that are writable in response to user actions, cause, - * stackTrace, and suppressedExceptions obey the following - * protocol: - * - * 1) The fields are initialized to a non-null sentinel value - * which indicates the value has logically not been set. - * - * 2) Writing a null to the field indicates further writes - * are forbidden - * - * 3) The sentinel value may be replaced with another non-null - * value. - * - * For example, implementations of the HotSpot JVM have - * preallocated OutOfMemoryError objects to provide for better - * diagnosability of that situation. These objects are created - * without calling the constructor for that class and the fields - * in question are initialized to null. To support this - * capability, any new fields added to Throwable that require - * being initialized to a non-null value require a coordinated JVM - * change. - */ - - /** - * The throwable that caused this throwable to get thrown, or null if this - * throwable was not caused by another throwable, or if the causative - * throwable is unknown. If this field is equal to this throwable itself, - * it indicates that the cause of this throwable has not yet been - * initialized. - * - * @serial - * @since 1.4 - */ - private Throwable cause = this; - - /** - * The stack trace, as returned by {@link #getStackTrace()}. - * - * The field is initialized to a zero-length array. A {@code - * null} value of this field indicates subsequent calls to {@link - * #setStackTrace(StackTraceElement[])} and {@link - * #fillInStackTrace()} will be be no-ops. - * - * @serial - * @since 1.4 - */ - private StackTraceElement[] stackTrace = UNASSIGNED_STACK; - - // Setting this static field introduces an acceptable - // initialization dependency on a few java.util classes. -// I don't think this dependency is acceptable -// private static final List SUPPRESSED_SENTINEL = -// Collections.unmodifiableList(new ArrayList(0)); - - /** - * The list of suppressed exceptions, as returned by {@link - * #getSuppressed()}. The list is initialized to a zero-element - * unmodifiable sentinel list. When a serialized Throwable is - * read in, if the {@code suppressedExceptions} field points to a - * zero-element list, the field is reset to the sentinel value. - * - * @serial - * @since 1.7 - */ -// private List suppressedExceptions = SUPPRESSED_SENTINEL; - - /** Message for trying to suppress a null exception. */ - private static final String NULL_CAUSE_MESSAGE = "Cannot suppress a null exception."; - - /** Message for trying to suppress oneself. */ - private static final String SELF_SUPPRESSION_MESSAGE = "Self-suppression not permitted"; - - /** Caption for labeling causative exception stack traces */ - @JavaScriptOnly(name="toString", value="function() { return this.toString__Ljava_lang_String_2().toString(); }") - private static void jsToString() { - } - - @JavaScriptOnly(name="valueOf", value="function() { return this.toString().valueOf(); }") - private static void jsValudOf() { - } - private static final String CAUSE_CAPTION = "Caused by: "; - - /** Caption for labeling suppressed exception stack traces */ - private static final String SUPPRESSED_CAPTION = "Suppressed: "; - - /** - * Constructs a new throwable with {@code null} as its detail message. - * The cause is not initialized, and may subsequently be initialized by a - * call to {@link #initCause}. - * - *

The {@link #fillInStackTrace()} method is called to initialize - * the stack trace data in the newly created throwable. - */ - public Throwable() { - fillInStackTrace(); - } - - /** - * Constructs a new throwable with the specified detail message. The - * cause is not initialized, and may subsequently be initialized by - * a call to {@link #initCause}. - * - *

The {@link #fillInStackTrace()} method is called to initialize - * the stack trace data in the newly created throwable. - * - * @param message the detail message. The detail message is saved for - * later retrieval by the {@link #getMessage()} method. - */ - public Throwable(String message) { - fillInStackTrace(); - detailMessage = message; - } - - /** - * Constructs a new throwable with the specified detail message and - * cause.

Note that the detail message associated with - * {@code cause} is not automatically incorporated in - * this throwable's detail message. - * - *

The {@link #fillInStackTrace()} method is called to initialize - * the stack trace data in the newly created throwable. - * - * @param message the detail message (which is saved for later retrieval - * by the {@link #getMessage()} method). - * @param cause the cause (which is saved for later retrieval by the - * {@link #getCause()} method). (A {@code null} value is - * permitted, and indicates that the cause is nonexistent or - * unknown.) - * @since 1.4 - */ - public Throwable(String message, Throwable cause) { - fillInStackTrace(); - detailMessage = message; - this.cause = cause; - } - - /** - * Constructs a new throwable with the specified cause and a detail - * message of {@code (cause==null ? null : cause.toString())} (which - * typically contains the class and detail message of {@code cause}). - * This constructor is useful for throwables that are little more than - * wrappers for other throwables (for example, {@link - * java.security.PrivilegedActionException}). - * - *

The {@link #fillInStackTrace()} method is called to initialize - * the stack trace data in the newly created throwable. - * - * @param cause the cause (which is saved for later retrieval by the - * {@link #getCause()} method). (A {@code null} value is - * permitted, and indicates that the cause is nonexistent or - * unknown.) - * @since 1.4 - */ - public Throwable(Throwable cause) { - fillInStackTrace(); - detailMessage = (cause==null ? null : cause.toString()); - this.cause = cause; - } - - /** - * Constructs a new throwable with the specified detail message, - * cause, {@linkplain #addSuppressed suppression} enabled or - * disabled, and writable stack trace enabled or disabled. If - * suppression is disabled, {@link #getSuppressed} for this object - * will return a zero-length array and calls to {@link - * #addSuppressed} that would otherwise append an exception to the - * suppressed list will have no effect. If the writable stack - * trace is false, this constructor will not call {@link - * #fillInStackTrace()}, a {@code null} will be written to the - * {@code stackTrace} field, and subsequent calls to {@code - * fillInStackTrace} and {@link - * #setStackTrace(StackTraceElement[])} will not set the stack - * trace. If the writable stack trace is false, {@link - * #getStackTrace} will return a zero length array. - * - *

Note that the other constructors of {@code Throwable} treat - * suppression as being enabled and the stack trace as being - * writable. Subclasses of {@code Throwable} should document any - * conditions under which suppression is disabled and document - * conditions under which the stack trace is not writable. - * Disabling of suppression should only occur in exceptional - * circumstances where special requirements exist, such as a - * virtual machine reusing exception objects under low-memory - * situations. Circumstances where a given exception object is - * repeatedly caught and rethrown, such as to implement control - * flow between two sub-systems, is another situation where - * immutable throwable objects would be appropriate. - * - * @param message the detail message. - * @param cause the cause. (A {@code null} value is permitted, - * and indicates that the cause is nonexistent or unknown.) - * @param enableSuppression whether or not suppression is enabled or disabled - * @param writableStackTrace whether or not the stack trace should be - * writable - * - * @see OutOfMemoryError - * @see NullPointerException - * @see ArithmeticException - * @since 1.7 - */ - protected Throwable(String message, Throwable cause, - boolean enableSuppression, - boolean writableStackTrace) { - if (writableStackTrace) { - fillInStackTrace(); - } else { - stackTrace = null; - } - detailMessage = message; - this.cause = cause; -// if (!enableSuppression) -// suppressedExceptions = null; - } - - /** - * Returns the detail message string of this throwable. - * - * @return the detail message string of this {@code Throwable} instance - * (which may be {@code null}). - */ - public String getMessage() { - return detailMessage; - } - - /** - * Creates a localized description of this throwable. - * Subclasses may override this method in order to produce a - * locale-specific message. For subclasses that do not override this - * method, the default implementation returns the same result as - * {@code getMessage()}. - * - * @return The localized description of this throwable. - * @since JDK1.1 - */ - public String getLocalizedMessage() { - return getMessage(); - } - - /** - * Returns the cause of this throwable or {@code null} if the - * cause is nonexistent or unknown. (The cause is the throwable that - * caused this throwable to get thrown.) - * - *

This implementation returns the cause that was supplied via one of - * the constructors requiring a {@code Throwable}, or that was set after - * creation with the {@link #initCause(Throwable)} method. While it is - * typically unnecessary to override this method, a subclass can override - * it to return a cause set by some other means. This is appropriate for - * a "legacy chained throwable" that predates the addition of chained - * exceptions to {@code Throwable}. Note that it is not - * necessary to override any of the {@code PrintStackTrace} methods, - * all of which invoke the {@code getCause} method to determine the - * cause of a throwable. - * - * @return the cause of this throwable or {@code null} if the - * cause is nonexistent or unknown. - * @since 1.4 - */ - public synchronized Throwable getCause() { - return (cause==this ? null : cause); - } - - /** - * Initializes the cause of this throwable to the specified value. - * (The cause is the throwable that caused this throwable to get thrown.) - * - *

This method can be called at most once. It is generally called from - * within the constructor, or immediately after creating the - * throwable. If this throwable was created - * with {@link #Throwable(Throwable)} or - * {@link #Throwable(String,Throwable)}, this method cannot be called - * even once. - * - *

An example of using this method on a legacy throwable type - * without other support for setting the cause is: - * - *

-     * try {
-     *     lowLevelOp();
-     * } catch (LowLevelException le) {
-     *     throw (HighLevelException)
-     *           new HighLevelException().initCause(le); // Legacy constructor
-     * }
-     * 
- * - * @param cause the cause (which is saved for later retrieval by the - * {@link #getCause()} method). (A {@code null} value is - * permitted, and indicates that the cause is nonexistent or - * unknown.) - * @return a reference to this {@code Throwable} instance. - * @throws IllegalArgumentException if {@code cause} is this - * throwable. (A throwable cannot be its own cause.) - * @throws IllegalStateException if this throwable was - * created with {@link #Throwable(Throwable)} or - * {@link #Throwable(String,Throwable)}, or this method has already - * been called on this throwable. - * @since 1.4 - */ - public synchronized Throwable initCause(Throwable cause) { - if (this.cause != this) - throw new IllegalStateException("Can't overwrite cause"); - if (cause == this) - throw new IllegalArgumentException("Self-causation not permitted"); - this.cause = cause; - return this; - } - - /** - * Returns a short description of this throwable. - * The result is the concatenation of: - *
    - *
  • the {@linkplain Class#getName() name} of the class of this object - *
  • ": " (a colon and a space) - *
  • the result of invoking this object's {@link #getLocalizedMessage} - * method - *
- * If {@code getLocalizedMessage} returns {@code null}, then just - * the class name is returned. - * - * @return a string representation of this throwable. - */ - public String toString() { - String s = getClass().getName(); - String message = getLocalizedMessage(); - return (message != null) ? (s + ": " + message) : s; - } - - /** - * Prints this throwable and its backtrace to the - * standard error stream. This method prints a stack trace for this - * {@code Throwable} object on the error output stream that is - * the value of the field {@code System.err}. The first line of - * output contains the result of the {@link #toString()} method for - * this object. Remaining lines represent data previously recorded by - * the method {@link #fillInStackTrace()}. The format of this - * information depends on the implementation, but the following - * example may be regarded as typical: - *
-     * java.lang.NullPointerException
-     *         at MyClass.mash(MyClass.java:9)
-     *         at MyClass.crunch(MyClass.java:6)
-     *         at MyClass.main(MyClass.java:3)
-     * 
- * This example was produced by running the program: - *
-     * class MyClass {
-     *     public static void main(String[] args) {
-     *         crunch(null);
-     *     }
-     *     static void crunch(int[] a) {
-     *         mash(a);
-     *     }
-     *     static void mash(int[] b) {
-     *         System.out.println(b[0]);
-     *     }
-     * }
-     * 
- * The backtrace for a throwable with an initialized, non-null cause - * should generally include the backtrace for the cause. The format - * of this information depends on the implementation, but the following - * example may be regarded as typical: - *
-     * HighLevelException: MidLevelException: LowLevelException
-     *         at Junk.a(Junk.java:13)
-     *         at Junk.main(Junk.java:4)
-     * Caused by: MidLevelException: LowLevelException
-     *         at Junk.c(Junk.java:23)
-     *         at Junk.b(Junk.java:17)
-     *         at Junk.a(Junk.java:11)
-     *         ... 1 more
-     * Caused by: LowLevelException
-     *         at Junk.e(Junk.java:30)
-     *         at Junk.d(Junk.java:27)
-     *         at Junk.c(Junk.java:21)
-     *         ... 3 more
-     * 
- * Note the presence of lines containing the characters {@code "..."}. - * These lines indicate that the remainder of the stack trace for this - * exception matches the indicated number of frames from the bottom of the - * stack trace of the exception that was caused by this exception (the - * "enclosing" exception). This shorthand can greatly reduce the length - * of the output in the common case where a wrapped exception is thrown - * from same method as the "causative exception" is caught. The above - * example was produced by running the program: - *
-     * public class Junk {
-     *     public static void main(String args[]) {
-     *         try {
-     *             a();
-     *         } catch(HighLevelException e) {
-     *             e.printStackTrace();
-     *         }
-     *     }
-     *     static void a() throws HighLevelException {
-     *         try {
-     *             b();
-     *         } catch(MidLevelException e) {
-     *             throw new HighLevelException(e);
-     *         }
-     *     }
-     *     static void b() throws MidLevelException {
-     *         c();
-     *     }
-     *     static void c() throws MidLevelException {
-     *         try {
-     *             d();
-     *         } catch(LowLevelException e) {
-     *             throw new MidLevelException(e);
-     *         }
-     *     }
-     *     static void d() throws LowLevelException {
-     *        e();
-     *     }
-     *     static void e() throws LowLevelException {
-     *         throw new LowLevelException();
-     *     }
-     * }
-     *
-     * class HighLevelException extends Exception {
-     *     HighLevelException(Throwable cause) { super(cause); }
-     * }
-     *
-     * class MidLevelException extends Exception {
-     *     MidLevelException(Throwable cause)  { super(cause); }
-     * }
-     *
-     * class LowLevelException extends Exception {
-     * }
-     * 
- * As of release 7, the platform supports the notion of - * suppressed exceptions (in conjunction with the {@code - * try}-with-resources statement). Any exceptions that were - * suppressed in order to deliver an exception are printed out - * beneath the stack trace. The format of this information - * depends on the implementation, but the following example may be - * regarded as typical: - * - *
-     * Exception in thread "main" java.lang.Exception: Something happened
-     *  at Foo.bar(Foo.java:10)
-     *  at Foo.main(Foo.java:5)
-     *  Suppressed: Resource$CloseFailException: Resource ID = 0
-     *          at Resource.close(Resource.java:26)
-     *          at Foo.bar(Foo.java:9)
-     *          ... 1 more
-     * 
- * Note that the "... n more" notation is used on suppressed exceptions - * just at it is used on causes. Unlike causes, suppressed exceptions are - * indented beyond their "containing exceptions." - * - *

An exception can have both a cause and one or more suppressed - * exceptions: - *

-     * Exception in thread "main" java.lang.Exception: Main block
-     *  at Foo3.main(Foo3.java:7)
-     *  Suppressed: Resource$CloseFailException: Resource ID = 2
-     *          at Resource.close(Resource.java:26)
-     *          at Foo3.main(Foo3.java:5)
-     *  Suppressed: Resource$CloseFailException: Resource ID = 1
-     *          at Resource.close(Resource.java:26)
-     *          at Foo3.main(Foo3.java:5)
-     * Caused by: java.lang.Exception: I did it
-     *  at Foo3.main(Foo3.java:8)
-     * 
- * Likewise, a suppressed exception can have a cause: - *
-     * Exception in thread "main" java.lang.Exception: Main block
-     *  at Foo4.main(Foo4.java:6)
-     *  Suppressed: Resource2$CloseFailException: Resource ID = 1
-     *          at Resource2.close(Resource2.java:20)
-     *          at Foo4.main(Foo4.java:5)
-     *  Caused by: java.lang.Exception: Rats, you caught me
-     *          at Resource2$CloseFailException.(Resource2.java:45)
-     *          ... 2 more
-     * 
- */ -// public void printStackTrace() { -// printStackTrace(System.err); -// } -// -// /** -// * Prints this throwable and its backtrace to the specified print stream. -// * -// * @param s {@code PrintStream} to use for output -// */ -// public void printStackTrace(PrintStream s) { -// printStackTrace(new WrappedPrintStream(s)); -// } -// -// private void printStackTrace(PrintStreamOrWriter s) { -// // Guard against malicious overrides of Throwable.equals by -// // using a Set with identity equality semantics. -//// Set dejaVu = -//// Collections.newSetFromMap(new IdentityHashMap()); -//// dejaVu.add(this); -// -// synchronized (s.lock()) { -// // Print our stack trace -// s.println(this); -// StackTraceElement[] trace = getOurStackTrace(); -// for (StackTraceElement traceElement : trace) -// s.println("\tat " + traceElement); -// -// // Print suppressed exceptions, if any -//// for (Throwable se : getSuppressed()) -//// se.printEnclosedStackTrace(s, trace, SUPPRESSED_CAPTION, "\t", dejaVu); -// -// // Print cause, if any -// Throwable ourCause = getCause(); -//// if (ourCause != null) -//// ourCause.printEnclosedStackTrace(s, trace, CAUSE_CAPTION, "", dejaVu); -// } -// } -// -// /** -// * Print our stack trace as an enclosed exception for the specified -// * stack trace. -// */ -// private void printEnclosedStackTrace(PrintStreamOrWriter s, -// StackTraceElement[] enclosingTrace, -// String caption, -// String prefix, -// Object dejaVu) { -// assert Thread.holdsLock(s.lock()); -// { -// // Compute number of frames in common between this and enclosing trace -// StackTraceElement[] trace = getOurStackTrace(); -// int m = trace.length - 1; -// int n = enclosingTrace.length - 1; -// while (m >= 0 && n >=0 && trace[m].equals(enclosingTrace[n])) { -// m--; n--; -// } -// int framesInCommon = trace.length - 1 - m; -// -// // Print our stack trace -// s.println(prefix + caption + this); -// for (int i = 0; i <= m; i++) -// s.println(prefix + "\tat " + trace[i]); -// if (framesInCommon != 0) -// s.println(prefix + "\t... " + framesInCommon + " more"); -// -// // Print suppressed exceptions, if any -// for (Throwable se : getSuppressed()) -// se.printEnclosedStackTrace(s, trace, SUPPRESSED_CAPTION, -// prefix +"\t", dejaVu); -// -// // Print cause, if any -// Throwable ourCause = getCause(); -// if (ourCause != null) -// ourCause.printEnclosedStackTrace(s, trace, CAUSE_CAPTION, prefix, dejaVu); -// } -// } -// -// /** -// * Prints this throwable and its backtrace to the specified -// * print writer. -// * -// * @param s {@code PrintWriter} to use for output -// * @since JDK1.1 -// */ -// public void printStackTrace(PrintWriter s) { -// printStackTrace(new WrappedPrintWriter(s)); -// } -// -// /** -// * Wrapper class for PrintStream and PrintWriter to enable a single -// * implementation of printStackTrace. -// */ -// private abstract static class PrintStreamOrWriter { -// /** Returns the object to be locked when using this StreamOrWriter */ -// abstract Object lock(); -// -// /** Prints the specified string as a line on this StreamOrWriter */ -// abstract void println(Object o); -// } -// -// private static class WrappedPrintStream extends PrintStreamOrWriter { -// private final PrintStream printStream; -// -// WrappedPrintStream(PrintStream printStream) { -// this.printStream = printStream; -// } -// -// Object lock() { -// return printStream; -// } -// -// void println(Object o) { -// printStream.println(o); -// } -// } -// -// private static class WrappedPrintWriter extends PrintStreamOrWriter { -// private final PrintWriter printWriter; -// -// WrappedPrintWriter(PrintWriter printWriter) { -// this.printWriter = printWriter; -// } -// -// Object lock() { -// return printWriter; -// } -// -// void println(Object o) { -// printWriter.println(o); -// } -// } - - /** - * Fills in the execution stack trace. This method records within this - * {@code Throwable} object information about the current state of - * the stack frames for the current thread. - * - *

If the stack trace of this {@code Throwable} {@linkplain - * Throwable#Throwable(String, Throwable, boolean, boolean) is not - * writable}, calling this method has no effect. - * - * @return a reference to this {@code Throwable} instance. - * @see java.lang.Throwable#printStackTrace() - */ - public synchronized Throwable fillInStackTrace() { - if (stackTrace != null || - backtrace != null /* Out of protocol state */ ) { - fillInStackTrace(0); - stackTrace = UNASSIGNED_STACK; - } - return this; - } - - @JavaScriptBody(args = { "dummy" }, body = "") - private native Throwable fillInStackTrace(int dummy); - - /** - * Provides programmatic access to the stack trace information printed by - * {@link #printStackTrace()}. Returns an array of stack trace elements, - * each representing one stack frame. The zeroth element of the array - * (assuming the array's length is non-zero) represents the top of the - * stack, which is the last method invocation in the sequence. Typically, - * this is the point at which this throwable was created and thrown. - * The last element of the array (assuming the array's length is non-zero) - * represents the bottom of the stack, which is the first method invocation - * in the sequence. - * - *

Some virtual machines may, under some circumstances, omit one - * or more stack frames from the stack trace. In the extreme case, - * a virtual machine that has no stack trace information concerning - * this throwable is permitted to return a zero-length array from this - * method. Generally speaking, the array returned by this method will - * contain one element for every frame that would be printed by - * {@code printStackTrace}. Writes to the returned array do not - * affect future calls to this method. - * - * @return an array of stack trace elements representing the stack trace - * pertaining to this throwable. - * @since 1.4 - */ - public StackTraceElement[] getStackTrace() { - return getOurStackTrace().clone(); - } - - private synchronized StackTraceElement[] getOurStackTrace() { - // Initialize stack trace field with information from - // backtrace if this is the first call to this method - if (stackTrace == UNASSIGNED_STACK || - (stackTrace == null && backtrace != null) /* Out of protocol state */) { - int depth = getStackTraceDepth(); - stackTrace = new StackTraceElement[depth]; - for (int i=0; i < depth; i++) - stackTrace[i] = getStackTraceElement(i); - } else if (stackTrace == null) { - return UNASSIGNED_STACK; - } - return stackTrace; - } - - /** - * Sets the stack trace elements that will be returned by - * {@link #getStackTrace()} and printed by {@link #printStackTrace()} - * and related methods. - * - * This method, which is designed for use by RPC frameworks and other - * advanced systems, allows the client to override the default - * stack trace that is either generated by {@link #fillInStackTrace()} - * when a throwable is constructed or deserialized when a throwable is - * read from a serialization stream. - * - *

If the stack trace of this {@code Throwable} {@linkplain - * Throwable#Throwable(String, Throwable, boolean, boolean) is not - * writable}, calling this method has no effect other than - * validating its argument. - * - * @param stackTrace the stack trace elements to be associated with - * this {@code Throwable}. The specified array is copied by this - * call; changes in the specified array after the method invocation - * returns will have no affect on this {@code Throwable}'s stack - * trace. - * - * @throws NullPointerException if {@code stackTrace} is - * {@code null} or if any of the elements of - * {@code stackTrace} are {@code null} - * - * @since 1.4 - */ - public void setStackTrace(StackTraceElement[] stackTrace) { - // Validate argument - StackTraceElement[] defensiveCopy = stackTrace.clone(); - for (int i = 0; i < defensiveCopy.length; i++) { - if (defensiveCopy[i] == null) - throw new NullPointerException("stackTrace[" + i + "]"); - } - - synchronized (this) { - if (this.stackTrace == null && // Immutable stack - backtrace == null) // Test for out of protocol state - return; - this.stackTrace = defensiveCopy; - } - } - - /** - * Returns the number of elements in the stack trace (or 0 if the stack - * trace is unavailable). - * - * package-protection for use by SharedSecrets. - */ - native int getStackTraceDepth(); - - /** - * Returns the specified element of the stack trace. - * - * package-protection for use by SharedSecrets. - * - * @param index index of the element to return. - * @throws IndexOutOfBoundsException if {@code index < 0 || - * index >= getStackTraceDepth() } - */ - native StackTraceElement getStackTraceElement(int index); - - /** - * Reads a {@code Throwable} from a stream, enforcing - * well-formedness constraints on fields. Null entries and - * self-pointers are not allowed in the list of {@code - * suppressedExceptions}. Null entries are not allowed for stack - * trace elements. A null stack trace in the serial form results - * in a zero-length stack element array. A single-element stack - * trace whose entry is equal to {@code new StackTraceElement("", - * "", null, Integer.MIN_VALUE)} results in a {@code null} {@code - * stackTrace} field. - * - * Note that there are no constraints on the value the {@code - * cause} field can hold; both {@code null} and {@code this} are - * valid values for the field. - */ -// private void readObject(ObjectInputStream s) -// throws IOException, ClassNotFoundException { -// s.defaultReadObject(); // read in all fields -// if (suppressedExceptions != null) { -// List suppressed = null; -// if (suppressedExceptions.isEmpty()) { -// // Use the sentinel for a zero-length list -// suppressed = SUPPRESSED_SENTINEL; -// } else { // Copy Throwables to new list -// suppressed = new ArrayList(1); -// for (Throwable t : suppressedExceptions) { -// // Enforce constraints on suppressed exceptions in -// // case of corrupt or malicious stream. -// if (t == null) -// throw new NullPointerException(NULL_CAUSE_MESSAGE); -// if (t == this) -// throw new IllegalArgumentException(SELF_SUPPRESSION_MESSAGE); -// suppressed.add(t); -// } -// } -// suppressedExceptions = suppressed; -// } // else a null suppressedExceptions field remains null -// -// /* -// * For zero-length stack traces, use a clone of -// * UNASSIGNED_STACK rather than UNASSIGNED_STACK itself to -// * allow identity comparison against UNASSIGNED_STACK in -// * getOurStackTrace. The identity of UNASSIGNED_STACK in -// * stackTrace indicates to the getOurStackTrace method that -// * the stackTrace needs to be constructed from the information -// * in backtrace. -// */ -// if (stackTrace != null) { -// if (stackTrace.length == 0) { -// stackTrace = UNASSIGNED_STACK.clone(); -// } else if (stackTrace.length == 1 && -// // Check for the marker of an immutable stack trace -// SentinelHolder.STACK_TRACE_ELEMENT_SENTINEL.equals(stackTrace[0])) { -// stackTrace = null; -// } else { // Verify stack trace elements are non-null. -// for(StackTraceElement ste : stackTrace) { -// if (ste == null) -// throw new NullPointerException("null StackTraceElement in serial stream. "); -// } -// } -// } else { -// // A null stackTrace field in the serial form can result -// // from an exception serialized without that field in -// // older JDK releases; treat such exceptions as having -// // empty stack traces. -// stackTrace = UNASSIGNED_STACK.clone(); -// } -// } - - /** - * Write a {@code Throwable} object to a stream. - * - * A {@code null} stack trace field is represented in the serial - * form as a one-element array whose element is equal to {@code - * new StackTraceElement("", "", null, Integer.MIN_VALUE)}. - */ -// private synchronized void writeObject(ObjectOutputStream s) -// throws IOException { -// // Ensure that the stackTrace field is initialized to a -// // non-null value, if appropriate. As of JDK 7, a null stack -// // trace field is a valid value indicating the stack trace -// // should not be set. -// getOurStackTrace(); -// -// StackTraceElement[] oldStackTrace = stackTrace; -// try { -// if (stackTrace == null) -// stackTrace = SentinelHolder.STACK_TRACE_SENTINEL; -// s.defaultWriteObject(); -// } finally { -// stackTrace = oldStackTrace; -// } -// } - - /** - * Appends the specified exception to the exceptions that were - * suppressed in order to deliver this exception. This method is - * thread-safe and typically called (automatically and implicitly) - * by the {@code try}-with-resources statement. - * - *

The suppression behavior is enabled unless disabled - * {@linkplain #Throwable(String, Throwable, boolean, boolean) via - * a constructor}. When suppression is disabled, this method does - * nothing other than to validate its argument. - * - *

Note that when one exception {@linkplain - * #initCause(Throwable) causes} another exception, the first - * exception is usually caught and then the second exception is - * thrown in response. In other words, there is a causal - * connection between the two exceptions. - * - * In contrast, there are situations where two independent - * exceptions can be thrown in sibling code blocks, in particular - * in the {@code try} block of a {@code try}-with-resources - * statement and the compiler-generated {@code finally} block - * which closes the resource. - * - * In these situations, only one of the thrown exceptions can be - * propagated. In the {@code try}-with-resources statement, when - * there are two such exceptions, the exception originating from - * the {@code try} block is propagated and the exception from the - * {@code finally} block is added to the list of exceptions - * suppressed by the exception from the {@code try} block. As an - * exception unwinds the stack, it can accumulate multiple - * suppressed exceptions. - * - *

An exception may have suppressed exceptions while also being - * caused by another exception. Whether or not an exception has a - * cause is semantically known at the time of its creation, unlike - * whether or not an exception will suppress other exceptions - * which is typically only determined after an exception is - * thrown. - * - *

Note that programmer written code is also able to take - * advantage of calling this method in situations where there are - * multiple sibling exceptions and only one can be propagated. - * - * @param exception the exception to be added to the list of - * suppressed exceptions - * @throws IllegalArgumentException if {@code exception} is this - * throwable; a throwable cannot suppress itself. - * @throws NullPointerException if {@code exception} is {@code null} - * @since 1.7 - */ - public final synchronized void addSuppressed(Throwable exception) { - if (exception == this) - throw new IllegalArgumentException(SELF_SUPPRESSION_MESSAGE); - - if (exception == null) - throw new NullPointerException(NULL_CAUSE_MESSAGE); - -// if (suppressedExceptions == null) // Suppressed exceptions not recorded -// return; -// -// if (suppressedExceptions == SUPPRESSED_SENTINEL) -// suppressedExceptions = new ArrayList(1); -// -// suppressedExceptions.add(exception); - } - - private static final Throwable[] EMPTY_THROWABLE_ARRAY = new Throwable[0]; - - /** - * Returns an array containing all of the exceptions that were - * suppressed, typically by the {@code try}-with-resources - * statement, in order to deliver this exception. - * - * If no exceptions were suppressed or {@linkplain - * #Throwable(String, Throwable, boolean, boolean) suppression is - * disabled}, an empty array is returned. This method is - * thread-safe. Writes to the returned array do not affect future - * calls to this method. - * - * @return an array containing all of the exceptions that were - * suppressed to deliver this exception. - * @since 1.7 - */ - public final synchronized Throwable[] getSuppressed() { - return new Throwable[0]; -// if (suppressedExceptions == SUPPRESSED_SENTINEL || -// suppressedExceptions == null) -// return EMPTY_THROWABLE_ARRAY; -// else -// return suppressedExceptions.toArray(EMPTY_THROWABLE_ARRAY); - } -} diff -r 388e48c0a37a -r 05224402145d emul/src/main/java/java/lang/VirtualMachineError.java --- a/emul/src/main/java/java/lang/VirtualMachineError.java Wed Jan 23 20:16:48 2013 +0100 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,54 +0,0 @@ -/* - * Copyright (c) 1995, 1997, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code 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 - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package java.lang; - -/** - * Thrown to indicate that the Java Virtual Machine is broken or has - * run out of resources necessary for it to continue operating. - * - * - * @author Frank Yellin - * @since JDK1.0 - */ -abstract public -class VirtualMachineError extends Error { - /** - * Constructs a VirtualMachineError with no detail message. - */ - public VirtualMachineError() { - super(); - } - - /** - * Constructs a VirtualMachineError with the specified - * detail message. - * - * @param s the detail message. - */ - public VirtualMachineError(String s) { - super(s); - } -} diff -r 388e48c0a37a -r 05224402145d emul/src/main/java/java/lang/Void.java --- a/emul/src/main/java/java/lang/Void.java Wed Jan 23 20:16:48 2013 +0100 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,49 +0,0 @@ -/* - * Copyright (c) 1996, 2006, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code 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 - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package java.lang; - -/** - * The {@code Void} class is an uninstantiable placeholder class to hold a - * reference to the {@code Class} object representing the Java keyword - * void. - * - * @author unascribed - * @since JDK1.1 - */ -public final -class Void { - - /** - * The {@code Class} object representing the pseudo-type corresponding to - * the keyword {@code void}. - */ - public static final Class TYPE = Class.getPrimitiveClass("void"); - - /* - * The Void class cannot be instantiated. - */ - private Void() {} -} diff -r 388e48c0a37a -r 05224402145d emul/src/main/java/java/lang/annotation/Annotation.java --- a/emul/src/main/java/java/lang/annotation/Annotation.java Wed Jan 23 20:16:48 2013 +0100 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,131 +0,0 @@ -/* - * Copyright (c) 2003, 2009, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code 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 - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package java.lang.annotation; - -/** - * The common interface extended by all annotation types. Note that an - * interface that manually extends this one does not define - * an annotation type. Also note that this interface does not itself - * define an annotation type. - * - * More information about annotation types can be found in section 9.6 of - * The Java™ Language Specification. - * - * @author Josh Bloch - * @since 1.5 - */ -public interface Annotation { - /** - * Returns true if the specified object represents an annotation - * that is logically equivalent to this one. In other words, - * returns true if the specified object is an instance of the same - * annotation type as this instance, all of whose members are equal - * to the corresponding member of this annotation, as defined below: - *

    - *
  • Two corresponding primitive typed members whose values are - * x and y are considered equal if x == y, - * unless their type is float or double. - * - *
  • Two corresponding float members whose values - * are x and y are considered equal if - * Float.valueOf(x).equals(Float.valueOf(y)). - * (Unlike the == operator, NaN is considered equal - * to itself, and 0.0f unequal to -0.0f.) - * - *
  • Two corresponding double members whose values - * are x and y are considered equal if - * Double.valueOf(x).equals(Double.valueOf(y)). - * (Unlike the == operator, NaN is considered equal - * to itself, and 0.0 unequal to -0.0.) - * - *
  • Two corresponding String, Class, enum, or - * annotation typed members whose values are x and y - * are considered equal if x.equals(y). (Note that this - * definition is recursive for annotation typed members.) - * - *
  • Two corresponding array typed members x and y - * are considered equal if Arrays.equals(x, y), for the - * appropriate overloading of {@link java.util.Arrays#equals}. - *
- * - * @return true if the specified object represents an annotation - * that is logically equivalent to this one, otherwise false - */ - boolean equals(Object obj); - - /** - * Returns the hash code of this annotation, as defined below: - * - *

The hash code of an annotation is the sum of the hash codes - * of its members (including those with default values), as defined - * below: - * - * The hash code of an annotation member is (127 times the hash code - * of the member-name as computed by {@link String#hashCode()}) XOR - * the hash code of the member-value, as defined below: - * - *

The hash code of a member-value depends on its type: - *

    - *
  • The hash code of a primitive value v is equal to - * WrapperType.valueOf(v).hashCode(), where - * WrapperType is the wrapper type corresponding - * to the primitive type of v ({@link Byte}, - * {@link Character}, {@link Double}, {@link Float}, {@link Integer}, - * {@link Long}, {@link Short}, or {@link Boolean}). - * - *
  • The hash code of a string, enum, class, or annotation member-value - I v is computed as by calling - * v.hashCode(). (In the case of annotation - * member values, this is a recursive definition.) - * - *
  • The hash code of an array member-value is computed by calling - * the appropriate overloading of - * {@link java.util.Arrays#hashCode(long[]) Arrays.hashCode} - * on the value. (There is one overloading for each primitive - * type, and one for object reference types.) - *
- * - * @return the hash code of this annotation - */ - int hashCode(); - - /** - * Returns a string representation of this annotation. The details - * of the representation are implementation-dependent, but the following - * may be regarded as typical: - *
-     *   @com.acme.util.Name(first=Alfred, middle=E., last=Neuman)
-     * 
- * - * @return a string representation of this annotation - */ - String toString(); - - /** - * Returns the annotation type of this annotation. - */ - Class annotationType(); -} diff -r 388e48c0a37a -r 05224402145d emul/src/main/java/java/lang/annotation/Documented.java --- a/emul/src/main/java/java/lang/annotation/Documented.java Wed Jan 23 20:16:48 2013 +0100 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,43 +0,0 @@ -/* - * Copyright (c) 2003, 2004, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code 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 - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package java.lang.annotation; - -/** - * Indicates that annotations with a type are to be documented by javadoc - * and similar tools by default. This type should be used to annotate the - * declarations of types whose annotations affect the use of annotated - * elements by their clients. If a type declaration is annotated with - * Documented, its annotations become part of the public API - * of the annotated elements. - * - * @author Joshua Bloch - * @since 1.5 - */ -@Documented -@Retention(RetentionPolicy.RUNTIME) -@Target(ElementType.ANNOTATION_TYPE) -public @interface Documented { -} diff -r 388e48c0a37a -r 05224402145d emul/src/main/java/java/lang/annotation/ElementType.java --- a/emul/src/main/java/java/lang/annotation/ElementType.java Wed Jan 23 20:16:48 2013 +0100 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,63 +0,0 @@ -/* - * Copyright (c) 2003, 2011, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code 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 - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package java.lang.annotation; - -/** - * A program element type. The constants of this enumerated type - * provide a simple classification of the declared elements in a - * Java program. - * - *

These constants are used with the {@link Target} meta-annotation type - * to specify where it is legal to use an annotation type. - * - * @author Joshua Bloch - * @since 1.5 - */ -public enum ElementType { - /** Class, interface (including annotation type), or enum declaration */ - TYPE, - - /** Field declaration (includes enum constants) */ - FIELD, - - /** Method declaration */ - METHOD, - - /** Parameter declaration */ - PARAMETER, - - /** Constructor declaration */ - CONSTRUCTOR, - - /** Local variable declaration */ - LOCAL_VARIABLE, - - /** Annotation type declaration */ - ANNOTATION_TYPE, - - /** Package declaration */ - PACKAGE -} diff -r 388e48c0a37a -r 05224402145d emul/src/main/java/java/lang/annotation/Retention.java --- a/emul/src/main/java/java/lang/annotation/Retention.java Wed Jan 23 20:16:48 2013 +0100 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,47 +0,0 @@ -/* - * Copyright (c) 2003, 2006, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code 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 - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package java.lang.annotation; - -/** - * Indicates how long annotations with the annotated type are to - * be retained. If no Retention annotation is present on - * an annotation type declaration, the retention policy defaults to - * {@code RetentionPolicy.CLASS}. - * - *

A Retention meta-annotation has effect only if the - * meta-annotated type is used directly for annotation. It has no - * effect if the meta-annotated type is used as a member type in - * another annotation type. - * - * @author Joshua Bloch - * @since 1.5 - */ -@Documented -@Retention(RetentionPolicy.RUNTIME) -@Target(ElementType.ANNOTATION_TYPE) -public @interface Retention { - RetentionPolicy value(); -} diff -r 388e48c0a37a -r 05224402145d emul/src/main/java/java/lang/annotation/RetentionPolicy.java --- a/emul/src/main/java/java/lang/annotation/RetentionPolicy.java Wed Jan 23 20:16:48 2013 +0100 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,57 +0,0 @@ -/* - * Copyright (c) 2003, 2004, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code 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 - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package java.lang.annotation; - -/** - * Annotation retention policy. The constants of this enumerated type - * describe the various policies for retaining annotations. They are used - * in conjunction with the {@link Retention} meta-annotation type to specify - * how long annotations are to be retained. - * - * @author Joshua Bloch - * @since 1.5 - */ -public enum RetentionPolicy { - /** - * Annotations are to be discarded by the compiler. - */ - SOURCE, - - /** - * Annotations are to be recorded in the class file by the compiler - * but need not be retained by the VM at run time. This is the default - * behavior. - */ - CLASS, - - /** - * Annotations are to be recorded in the class file by the compiler and - * retained by the VM at run time, so they may be read reflectively. - * - * @see java.lang.reflect.AnnotatedElement - */ - RUNTIME -} diff -r 388e48c0a37a -r 05224402145d emul/src/main/java/java/lang/annotation/Target.java --- a/emul/src/main/java/java/lang/annotation/Target.java Wed Jan 23 20:16:48 2013 +0100 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,68 +0,0 @@ -/* - * Copyright (c) 2003, 2004, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code 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 - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package java.lang.annotation; - -/** - * Indicates the kinds of program element to which an annotation type - * is applicable. If a Target meta-annotation is not present on an - * annotation type declaration, the declared type may be used on any - * program element. If such a meta-annotation is present, the compiler - * will enforce the specified usage restriction. - * - * For example, this meta-annotation indicates that the declared type is - * itself a meta-annotation type. It can only be used on annotation type - * declarations: - *

- *    @Target(ElementType.ANNOTATION_TYPE)
- *    public @interface MetaAnnotationType {
- *        ...
- *    }
- * 
- * This meta-annotation indicates that the declared type is intended solely - * for use as a member type in complex annotation type declarations. It - * cannot be used to annotate anything directly: - *
- *    @Target({})
- *    public @interface MemberType {
- *        ...
- *    }
- * 
- * It is a compile-time error for a single ElementType constant to - * appear more than once in a Target annotation. For example, the - * following meta-annotation is illegal: - *
- *    @Target({ElementType.FIELD, ElementType.METHOD, ElementType.FIELD})
- *    public @interface Bogus {
- *        ...
- *    }
- * 
- */ -@Documented -@Retention(RetentionPolicy.RUNTIME) -@Target(ElementType.ANNOTATION_TYPE) -public @interface Target { - ElementType[] value(); -} diff -r 388e48c0a37a -r 05224402145d emul/src/main/java/java/lang/annotation/UnsupportedOperationException.java --- a/emul/src/main/java/java/lang/annotation/UnsupportedOperationException.java Wed Jan 23 20:16:48 2013 +0100 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,94 +0,0 @@ -/* - * Copyright (c) 1997, 2006, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code 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 - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package java.lang; - -/** - * Thrown to indicate that the requested operation is not supported.

- * - * This class is a member of the - * - * Java Collections Framework. - * - * @author Josh Bloch - * @since 1.2 - */ -public class UnsupportedOperationException extends RuntimeException { - /** - * Constructs an UnsupportedOperationException with no detail message. - */ - public UnsupportedOperationException() { - } - - /** - * Constructs an UnsupportedOperationException with the specified - * detail message. - * - * @param message the detail message - */ - public UnsupportedOperationException(String message) { - super(message); - } - - /** - * Constructs a new exception with the specified detail message and - * cause. - * - *

Note that the detail message associated with cause is - * not automatically incorporated in this exception's detail - * message. - * - * @param message the detail message (which is saved for later retrieval - * by the {@link Throwable#getMessage()} method). - * @param cause the cause (which is saved for later retrieval by the - * {@link Throwable#getCause()} method). (A null value - * is permitted, and indicates that the cause is nonexistent or - * unknown.) - * @since 1.5 - */ - public UnsupportedOperationException(String message, Throwable cause) { - super(message, cause); - } - - /** - * Constructs a new exception with the specified cause and a detail - * message of (cause==null ? null : cause.toString()) (which - * typically contains the class and detail message of cause). - * This constructor is useful for exceptions that are little more than - * wrappers for other throwables (for example, {@link - * java.security.PrivilegedActionException}). - * - * @param cause the cause (which is saved for later retrieval by the - * {@link Throwable#getCause()} method). (A null value is - * permitted, and indicates that the cause is nonexistent or - * unknown.) - * @since 1.5 - */ - public UnsupportedOperationException(Throwable cause) { - super(cause); - } - - static final long serialVersionUID = -1242599979055084673L; -} diff -r 388e48c0a37a -r 05224402145d emul/src/main/java/java/lang/reflect/AccessibleObject.java --- a/emul/src/main/java/java/lang/reflect/AccessibleObject.java Wed Jan 23 20:16:48 2013 +0100 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,167 +0,0 @@ -/* - * Copyright (c) 1997, 2008, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code 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 - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package java.lang.reflect; - -import java.lang.annotation.Annotation; - -/** - * The AccessibleObject class is the base class for Field, Method and - * Constructor objects. It provides the ability to flag a reflected - * object as suppressing default Java language access control checks - * when it is used. The access checks--for public, default (package) - * access, protected, and private members--are performed when Fields, - * Methods or Constructors are used to set or get fields, to invoke - * methods, or to create and initialize new instances of classes, - * respectively. - * - *

Setting the {@code accessible} flag in a reflected object - * permits sophisticated applications with sufficient privilege, such - * as Java Object Serialization or other persistence mechanisms, to - * manipulate objects in a manner that would normally be prohibited. - * - *

By default, a reflected object is not accessible. - * - * @see Field - * @see Method - * @see Constructor - * @see ReflectPermission - * - * @since 1.2 - */ -public class AccessibleObject implements AnnotatedElement { - - /** - * Convenience method to set the {@code accessible} flag for an - * array of objects with a single security check (for efficiency). - * - *

First, if there is a security manager, its - * {@code checkPermission} method is called with a - * {@code ReflectPermission("suppressAccessChecks")} permission. - * - *

A {@code SecurityException} is raised if {@code flag} is - * {@code true} but accessibility of any of the elements of the input - * {@code array} may not be changed (for example, if the element - * object is a {@link Constructor} object for the class {@link - * java.lang.Class}). In the event of such a SecurityException, the - * accessibility of objects is set to {@code flag} for array elements - * upto (and excluding) the element for which the exception occurred; the - * accessibility of elements beyond (and including) the element for which - * the exception occurred is unchanged. - * - * @param array the array of AccessibleObjects - * @param flag the new value for the {@code accessible} flag - * in each object - * @throws SecurityException if the request is denied. - * @see SecurityManager#checkPermission - * @see java.lang.RuntimePermission - */ - public static void setAccessible(AccessibleObject[] array, boolean flag) - throws SecurityException { - throw new SecurityException(); - } - - /** - * Set the {@code accessible} flag for this object to - * the indicated boolean value. A value of {@code true} indicates that - * the reflected object should suppress Java language access - * checking when it is used. A value of {@code false} indicates - * that the reflected object should enforce Java language access checks. - * - *

First, if there is a security manager, its - * {@code checkPermission} method is called with a - * {@code ReflectPermission("suppressAccessChecks")} permission. - * - *

A {@code SecurityException} is raised if {@code flag} is - * {@code true} but accessibility of this object may not be changed - * (for example, if this element object is a {@link Constructor} object for - * the class {@link java.lang.Class}). - * - *

A {@code SecurityException} is raised if this object is a {@link - * java.lang.reflect.Constructor} object for the class - * {@code java.lang.Class}, and {@code flag} is true. - * - * @param flag the new value for the {@code accessible} flag - * @throws SecurityException if the request is denied. - * @see SecurityManager#checkPermission - * @see java.lang.RuntimePermission - */ - public void setAccessible(boolean flag) throws SecurityException { - throw new SecurityException(); - } - - /** - * Get the value of the {@code accessible} flag for this object. - * - * @return the value of the object's {@code accessible} flag - */ - public boolean isAccessible() { - return override; - } - - /** - * Constructor: only used by the Java Virtual Machine. - */ - protected AccessibleObject() {} - - // Indicates whether language-level access checks are overridden - // by this object. Initializes to "false". This field is used by - // Field, Method, and Constructor. - // - // NOTE: for security purposes, this field must not be visible - // outside this package. - boolean override; - - /** - * @throws NullPointerException {@inheritDoc} - * @since 1.5 - */ - public T getAnnotation(Class annotationClass) { - throw new AssertionError("All subclasses should override this method"); - } - - /** - * @throws NullPointerException {@inheritDoc} - * @since 1.5 - */ - public boolean isAnnotationPresent( - Class annotationClass) { - return getAnnotation(annotationClass) != null; - } - - /** - * @since 1.5 - */ - public Annotation[] getAnnotations() { - return getDeclaredAnnotations(); - } - - /** - * @since 1.5 - */ - public Annotation[] getDeclaredAnnotations() { - throw new AssertionError("All subclasses should override this method"); - } -} diff -r 388e48c0a37a -r 05224402145d emul/src/main/java/java/lang/reflect/AnnotatedElement.java --- a/emul/src/main/java/java/lang/reflect/AnnotatedElement.java Wed Jan 23 20:16:48 2013 +0100 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,112 +0,0 @@ -/* - * Copyright (c) 2003, 2005, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code 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 - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package java.lang.reflect; - -import java.lang.annotation.Annotation; - -/** - * Represents an annotated element of the program currently running in this - * VM. This interface allows annotations to be read reflectively. All - * annotations returned by methods in this interface are immutable and - * serializable. It is permissible for the caller to modify the - * arrays returned by accessors for array-valued enum members; it will - * have no affect on the arrays returned to other callers. - * - *

If an annotation returned by a method in this interface contains - * (directly or indirectly) a {@link Class}-valued member referring to - * a class that is not accessible in this VM, attempting to read the class - * by calling the relevant Class-returning method on the returned annotation - * will result in a {@link TypeNotPresentException}. - * - *

Similarly, attempting to read an enum-valued member will result in - * a {@link EnumConstantNotPresentException} if the enum constant in the - * annotation is no longer present in the enum type. - * - *

Finally, Attempting to read a member whose definition has evolved - * incompatibly will result in a {@link - * java.lang.annotation.AnnotationTypeMismatchException} or an - * {@link java.lang.annotation.IncompleteAnnotationException}. - * - * @see java.lang.EnumConstantNotPresentException - * @see java.lang.TypeNotPresentException - * @see java.lang.annotation.AnnotationFormatError - * @see java.lang.annotation.AnnotationTypeMismatchException - * @see java.lang.annotation.IncompleteAnnotationException - * @since 1.5 - * @author Josh Bloch - */ -public interface AnnotatedElement { - /** - * Returns true if an annotation for the specified type - * is present on this element, else false. This method - * is designed primarily for convenient access to marker annotations. - * - * @param annotationClass the Class object corresponding to the - * annotation type - * @return true if an annotation for the specified annotation - * type is present on this element, else false - * @throws NullPointerException if the given annotation class is null - * @since 1.5 - */ - boolean isAnnotationPresent(Class annotationClass); - - /** - * Returns this element's annotation for the specified type if - * such an annotation is present, else null. - * - * @param annotationClass the Class object corresponding to the - * annotation type - * @return this element's annotation for the specified annotation type if - * present on this element, else null - * @throws NullPointerException if the given annotation class is null - * @since 1.5 - */ - T getAnnotation(Class annotationClass); - - /** - * Returns all annotations present on this element. (Returns an array - * of length zero if this element has no annotations.) The caller of - * this method is free to modify the returned array; it will have no - * effect on the arrays returned to other callers. - * - * @return all annotations present on this element - * @since 1.5 - */ - Annotation[] getAnnotations(); - - /** - * Returns all annotations that are directly present on this - * element. Unlike the other methods in this interface, this method - * ignores inherited annotations. (Returns an array of length zero if - * no annotations are directly present on this element.) The caller of - * this method is free to modify the returned array; it will have no - * effect on the arrays returned to other callers. - * - * @return All annotations directly present on this element - * @since 1.5 - */ - Annotation[] getDeclaredAnnotations(); -} diff -r 388e48c0a37a -r 05224402145d emul/src/main/java/java/lang/reflect/Array.java --- a/emul/src/main/java/java/lang/reflect/Array.java Wed Jan 23 20:16:48 2013 +0100 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,659 +0,0 @@ -/* - * Copyright (c) 1996, 2006, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code 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 - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package java.lang.reflect; - -import org.apidesign.bck2brwsr.core.JavaScriptBody; -import org.apidesign.bck2brwsr.core.JavaScriptPrototype; - -/** - * The {@code Array} class provides static methods to dynamically create and - * access Java arrays. - * - *

{@code Array} permits widening conversions to occur during a get or set - * operation, but throws an {@code IllegalArgumentException} if a narrowing - * conversion would occur. - * - * @author Nakul Saraiya - */ -@JavaScriptPrototype(prototype = "new Array", container = "Array.prototype") -public final -class Array { - - /** - * Constructor. Class Array is not instantiable. - */ - private Array() {} - - /** - * Creates a new array with the specified component type and - * length. - * Invoking this method is equivalent to creating an array - * as follows: - *

- *
-     * int[] x = {length};
-     * Array.newInstance(componentType, x);
-     * 
- *
- * - * @param componentType the {@code Class} object representing the - * component type of the new array - * @param length the length of the new array - * @return the new array - * @exception NullPointerException if the specified - * {@code componentType} parameter is null - * @exception IllegalArgumentException if componentType is {@link Void#TYPE} - * @exception NegativeArraySizeException if the specified {@code length} - * is negative - */ - public static Object newInstance(Class componentType, int length) - throws NegativeArraySizeException { - if (length < 0) { - throw new NegativeArraySizeException(); - } - String sig = findSignature(componentType); - return newArray(componentType.isPrimitive(), sig, length); - } - - private static String findSignature(Class type) { - if (type == Integer.TYPE) { - return "[I"; - } - if (type == Long.TYPE) { - return "[J"; - } - if (type == Double.TYPE) { - return "[D"; - } - if (type == Float.TYPE) { - return "[F"; - } - if (type == Byte.TYPE) { - return "[B"; - } - if (type == Boolean.TYPE) { - return "[Z"; - } - if (type == Short.TYPE) { - return "[S"; - } - if (type == Character.TYPE) { - return "[C"; - } - if (type.getName().equals("void")) { - throw new IllegalStateException("Can't create array for " + type); - } - return "[L" + type.getName() + ";"; - } - /** - * Creates a new array - * with the specified component type and dimensions. - * If {@code componentType} - * represents a non-array class or interface, the new array - * has {@code dimensions.length} dimensions and - * {@code componentType} as its component type. If - * {@code componentType} represents an array class, the - * number of dimensions of the new array is equal to the sum - * of {@code dimensions.length} and the number of - * dimensions of {@code componentType}. In this case, the - * component type of the new array is the component type of - * {@code componentType}. - * - *

The number of dimensions of the new array must not - * exceed the number of array dimensions supported by the - * implementation (typically 255). - * - * @param componentType the {@code Class} object representing the component - * type of the new array - * @param dimensions an array of {@code int} representing the dimensions of - * the new array - * @return the new array - * @exception NullPointerException if the specified - * {@code componentType} argument is null - * @exception IllegalArgumentException if the specified {@code dimensions} - * argument is a zero-dimensional array, or if the number of - * requested dimensions exceeds the limit on the number of array dimensions - * supported by the implementation (typically 255), or if componentType - * is {@link Void#TYPE}. - * @exception NegativeArraySizeException if any of the components in - * the specified {@code dimensions} argument is negative. - */ - public static Object newInstance(Class componentType, int... dimensions) - throws IllegalArgumentException, NegativeArraySizeException { - StringBuilder sig = new StringBuilder(); - for (int i = 1; i < dimensions.length; i++) { - sig.append('['); - } - sig.append(findSignature(componentType)); - return multiNewArray(sig.toString(), dimensions, 0); - } - - /** - * Returns the length of the specified array object, as an {@code int}. - * - * @param array the array - * @return the length of the array - * @exception IllegalArgumentException if the object argument is not - * an array - */ - public static int getLength(Object array) - throws IllegalArgumentException { - if (!array.getClass().isArray()) { - throw new IllegalArgumentException("Argument is not an array"); - } - return length(array); - } - - @JavaScriptBody(args = { "arr" }, body = "return arr.length;") - private static native int length(Object arr); - - /** - * Returns the value of the indexed component in the specified - * array object. The value is automatically wrapped in an object - * if it has a primitive type. - * - * @param array the array - * @param index the index - * @return the (possibly wrapped) value of the indexed component in - * the specified array - * @exception NullPointerException If the specified object is null - * @exception IllegalArgumentException If the specified object is not - * an array - * @exception ArrayIndexOutOfBoundsException If the specified {@code index} - * argument is negative, or if it is greater than or equal to the - * length of the specified array - */ - public static Object get(Object array, int index) - throws IllegalArgumentException, ArrayIndexOutOfBoundsException { - final Class t = array.getClass().getComponentType(); - if (t.isPrimitive()) { - return Array.fromPrimitive(t, array, index); - } else { - return ((Object[])array)[index]; - } - } - - /** - * Returns the value of the indexed component in the specified - * array object, as a {@code boolean}. - * - * @param array the array - * @param index the index - * @return the value of the indexed component in the specified array - * @exception NullPointerException If the specified object is null - * @exception IllegalArgumentException If the specified object is not - * an array, or if the indexed element cannot be converted to the - * return type by an identity or widening conversion - * @exception ArrayIndexOutOfBoundsException If the specified {@code index} - * argument is negative, or if it is greater than or equal to the - * length of the specified array - * @see Array#get - */ - public static native boolean getBoolean(Object array, int index) - throws IllegalArgumentException, ArrayIndexOutOfBoundsException; - - /** - * Returns the value of the indexed component in the specified - * array object, as a {@code byte}. - * - * @param array the array - * @param index the index - * @return the value of the indexed component in the specified array - * @exception NullPointerException If the specified object is null - * @exception IllegalArgumentException If the specified object is not - * an array, or if the indexed element cannot be converted to the - * return type by an identity or widening conversion - * @exception ArrayIndexOutOfBoundsException If the specified {@code index} - * argument is negative, or if it is greater than or equal to the - * length of the specified array - * @see Array#get - */ - public static byte getByte(Object array, int index) - throws IllegalArgumentException, ArrayIndexOutOfBoundsException { - if (array.getClass().getComponentType() != Byte.TYPE) { - throw new IllegalArgumentException(); - } - byte[] arr = (byte[]) array; - return arr[index]; - } - - /** - * Returns the value of the indexed component in the specified - * array object, as a {@code char}. - * - * @param array the array - * @param index the index - * @return the value of the indexed component in the specified array - * @exception NullPointerException If the specified object is null - * @exception IllegalArgumentException If the specified object is not - * an array, or if the indexed element cannot be converted to the - * return type by an identity or widening conversion - * @exception ArrayIndexOutOfBoundsException If the specified {@code index} - * argument is negative, or if it is greater than or equal to the - * length of the specified array - * @see Array#get - */ - public static native char getChar(Object array, int index) - throws IllegalArgumentException, ArrayIndexOutOfBoundsException; - - /** - * Returns the value of the indexed component in the specified - * array object, as a {@code short}. - * - * @param array the array - * @param index the index - * @return the value of the indexed component in the specified array - * @exception NullPointerException If the specified object is null - * @exception IllegalArgumentException If the specified object is not - * an array, or if the indexed element cannot be converted to the - * return type by an identity or widening conversion - * @exception ArrayIndexOutOfBoundsException If the specified {@code index} - * argument is negative, or if it is greater than or equal to the - * length of the specified array - * @see Array#get - */ - public static short getShort(Object array, int index) - throws IllegalArgumentException, ArrayIndexOutOfBoundsException { - final Class t = array.getClass().getComponentType(); - if (t == Short.TYPE) { - short[] arr = (short[]) array; - return arr[index]; - } - return getByte(array, index); - } - - /** - * Returns the value of the indexed component in the specified - * array object, as an {@code int}. - * - * @param array the array - * @param index the index - * @return the value of the indexed component in the specified array - * @exception NullPointerException If the specified object is null - * @exception IllegalArgumentException If the specified object is not - * an array, or if the indexed element cannot be converted to the - * return type by an identity or widening conversion - * @exception ArrayIndexOutOfBoundsException If the specified {@code index} - * argument is negative, or if it is greater than or equal to the - * length of the specified array - * @see Array#get - */ - public static int getInt(Object array, int index) - throws IllegalArgumentException, ArrayIndexOutOfBoundsException { - final Class t = array.getClass().getComponentType(); - if (t == Integer.TYPE) { - int[] arr = (int[]) array; - return arr[index]; - } - return getShort(array, index); - } - - /** - * Returns the value of the indexed component in the specified - * array object, as a {@code long}. - * - * @param array the array - * @param index the index - * @return the value of the indexed component in the specified array - * @exception NullPointerException If the specified object is null - * @exception IllegalArgumentException If the specified object is not - * an array, or if the indexed element cannot be converted to the - * return type by an identity or widening conversion - * @exception ArrayIndexOutOfBoundsException If the specified {@code index} - * argument is negative, or if it is greater than or equal to the - * length of the specified array - * @see Array#get - */ - public static long getLong(Object array, int index) - throws IllegalArgumentException, ArrayIndexOutOfBoundsException { - final Class t = array.getClass().getComponentType(); - if (t == Long.TYPE) { - long[] arr = (long[]) array; - return arr[index]; - } - return getInt(array, index); - } - - /** - * Returns the value of the indexed component in the specified - * array object, as a {@code float}. - * - * @param array the array - * @param index the index - * @return the value of the indexed component in the specified array - * @exception NullPointerException If the specified object is null - * @exception IllegalArgumentException If the specified object is not - * an array, or if the indexed element cannot be converted to the - * return type by an identity or widening conversion - * @exception ArrayIndexOutOfBoundsException If the specified {@code index} - * argument is negative, or if it is greater than or equal to the - * length of the specified array - * @see Array#get - */ - public static float getFloat(Object array, int index) - throws IllegalArgumentException, ArrayIndexOutOfBoundsException { - final Class t = array.getClass().getComponentType(); - if (t == Float.TYPE) { - float[] arr = (float[]) array; - return arr[index]; - } - return getLong(array, index); - } - - /** - * Returns the value of the indexed component in the specified - * array object, as a {@code double}. - * - * @param array the array - * @param index the index - * @return the value of the indexed component in the specified array - * @exception NullPointerException If the specified object is null - * @exception IllegalArgumentException If the specified object is not - * an array, or if the indexed element cannot be converted to the - * return type by an identity or widening conversion - * @exception ArrayIndexOutOfBoundsException If the specified {@code index} - * argument is negative, or if it is greater than or equal to the - * length of the specified array - * @see Array#get - */ - public static double getDouble(Object array, int index) - throws IllegalArgumentException, ArrayIndexOutOfBoundsException { - final Class t = array.getClass().getComponentType(); - if (t == Double.TYPE) { - double[] arr = (double[]) array; - return arr[index]; - } - return getFloat(array, index); - } - - /** - * Sets the value of the indexed component of the specified array - * object to the specified new value. The new value is first - * automatically unwrapped if the array has a primitive component - * type. - * @param array the array - * @param index the index into the array - * @param value the new value of the indexed component - * @exception NullPointerException If the specified object argument - * is null - * @exception IllegalArgumentException If the specified object argument - * is not an array, or if the array component type is primitive and - * an unwrapping conversion fails - * @exception ArrayIndexOutOfBoundsException If the specified {@code index} - * argument is negative, or if it is greater than or equal to - * the length of the specified array - */ - public static void set(Object array, int index, Object value) - throws IllegalArgumentException, ArrayIndexOutOfBoundsException { - if (array.getClass().getComponentType().isPrimitive()) { - throw new IllegalArgumentException(); - } else { - Object[] arr = (Object[])array; - arr[index] = value; - } - } - - /** - * Sets the value of the indexed component of the specified array - * object to the specified {@code boolean} value. - * @param array the array - * @param index the index into the array - * @param z the new value of the indexed component - * @exception NullPointerException If the specified object argument - * is null - * @exception IllegalArgumentException If the specified object argument - * is not an array, or if the specified value cannot be converted - * to the underlying array's component type by an identity or a - * primitive widening conversion - * @exception ArrayIndexOutOfBoundsException If the specified {@code index} - * argument is negative, or if it is greater than or equal to - * the length of the specified array - * @see Array#set - */ - public static native void setBoolean(Object array, int index, boolean z) - throws IllegalArgumentException, ArrayIndexOutOfBoundsException; - - /** - * Sets the value of the indexed component of the specified array - * object to the specified {@code byte} value. - * @param array the array - * @param index the index into the array - * @param b the new value of the indexed component - * @exception NullPointerException If the specified object argument - * is null - * @exception IllegalArgumentException If the specified object argument - * is not an array, or if the specified value cannot be converted - * to the underlying array's component type by an identity or a - * primitive widening conversion - * @exception ArrayIndexOutOfBoundsException If the specified {@code index} - * argument is negative, or if it is greater than or equal to - * the length of the specified array - * @see Array#set - */ - public static void setByte(Object array, int index, byte b) - throws IllegalArgumentException, ArrayIndexOutOfBoundsException { - Class t = array.getClass().getComponentType(); - if (t == Byte.TYPE) { - byte[] arr = (byte[]) array; - arr[index] = b; - } else { - setShort(array, index, b); - } - } - - /** - * Sets the value of the indexed component of the specified array - * object to the specified {@code char} value. - * @param array the array - * @param index the index into the array - * @param c the new value of the indexed component - * @exception NullPointerException If the specified object argument - * is null - * @exception IllegalArgumentException If the specified object argument - * is not an array, or if the specified value cannot be converted - * to the underlying array's component type by an identity or a - * primitive widening conversion - * @exception ArrayIndexOutOfBoundsException If the specified {@code index} - * argument is negative, or if it is greater than or equal to - * the length of the specified array - * @see Array#set - */ - public static native void setChar(Object array, int index, char c) - throws IllegalArgumentException, ArrayIndexOutOfBoundsException; - - /** - * Sets the value of the indexed component of the specified array - * object to the specified {@code short} value. - * @param array the array - * @param index the index into the array - * @param s the new value of the indexed component - * @exception NullPointerException If the specified object argument - * is null - * @exception IllegalArgumentException If the specified object argument - * is not an array, or if the specified value cannot be converted - * to the underlying array's component type by an identity or a - * primitive widening conversion - * @exception ArrayIndexOutOfBoundsException If the specified {@code index} - * argument is negative, or if it is greater than or equal to - * the length of the specified array - * @see Array#set - */ - public static void setShort(Object array, int index, short s) - throws IllegalArgumentException, ArrayIndexOutOfBoundsException { - Class t = array.getClass().getComponentType(); - if (t == Short.TYPE) { - short[] arr = (short[]) array; - arr[index] = s; - } else { - setInt(array, index, s); - } - - } - - /** - * Sets the value of the indexed component of the specified array - * object to the specified {@code int} value. - * @param array the array - * @param index the index into the array - * @param i the new value of the indexed component - * @exception NullPointerException If the specified object argument - * is null - * @exception IllegalArgumentException If the specified object argument - * is not an array, or if the specified value cannot be converted - * to the underlying array's component type by an identity or a - * primitive widening conversion - * @exception ArrayIndexOutOfBoundsException If the specified {@code index} - * argument is negative, or if it is greater than or equal to - * the length of the specified array - * @see Array#set - */ - public static void setInt(Object array, int index, int i) - throws IllegalArgumentException, ArrayIndexOutOfBoundsException { - Class t = array.getClass().getComponentType(); - if (t == Integer.TYPE) { - long[] arr = (long[]) array; - arr[index] = i; - } else { - setLong(array, index, i); - } - } - - /** - * Sets the value of the indexed component of the specified array - * object to the specified {@code long} value. - * @param array the array - * @param index the index into the array - * @param l the new value of the indexed component - * @exception NullPointerException If the specified object argument - * is null - * @exception IllegalArgumentException If the specified object argument - * is not an array, or if the specified value cannot be converted - * to the underlying array's component type by an identity or a - * primitive widening conversion - * @exception ArrayIndexOutOfBoundsException If the specified {@code index} - * argument is negative, or if it is greater than or equal to - * the length of the specified array - * @see Array#set - */ - public static void setLong(Object array, int index, long l) - throws IllegalArgumentException, ArrayIndexOutOfBoundsException { - Class t = array.getClass().getComponentType(); - if (t == Long.TYPE) { - long[] arr = (long[]) array; - arr[index] = l; - } else { - setFloat(array, index, l); - } - } - - /** - * Sets the value of the indexed component of the specified array - * object to the specified {@code float} value. - * @param array the array - * @param index the index into the array - * @param f the new value of the indexed component - * @exception NullPointerException If the specified object argument - * is null - * @exception IllegalArgumentException If the specified object argument - * is not an array, or if the specified value cannot be converted - * to the underlying array's component type by an identity or a - * primitive widening conversion - * @exception ArrayIndexOutOfBoundsException If the specified {@code index} - * argument is negative, or if it is greater than or equal to - * the length of the specified array - * @see Array#set - */ - public static void setFloat(Object array, int index, float f) - throws IllegalArgumentException, ArrayIndexOutOfBoundsException { - Class t = array.getClass().getComponentType(); - if (t == Float.TYPE) { - float[] arr = (float[])array; - arr[index] = f; - } else { - setDouble(array, index, f); - } - } - - /** - * Sets the value of the indexed component of the specified array - * object to the specified {@code double} value. - * @param array the array - * @param index the index into the array - * @param d the new value of the indexed component - * @exception NullPointerException If the specified object argument - * is null - * @exception IllegalArgumentException If the specified object argument - * is not an array, or if the specified value cannot be converted - * to the underlying array's component type by an identity or a - * primitive widening conversion - * @exception ArrayIndexOutOfBoundsException If the specified {@code index} - * argument is negative, or if it is greater than or equal to - * the length of the specified array - * @see Array#set - */ - public static void setDouble(Object array, int index, double d) - throws IllegalArgumentException, ArrayIndexOutOfBoundsException { - Class t = array.getClass().getComponentType(); - if (t == Double.TYPE) { - double[] arr = (double[])array; - arr[index] = d; - } else { - throw new IllegalArgumentException("argument type mismatch"); - } - } - - /* - * Private - */ - - @JavaScriptBody(args = { "primitive", "sig", "length" }, body = - "var arr = new Array(length);\n" - + "var value = primitive ? 0 : null;\n" - + "for(var i = 0; i < length; i++) arr[i] = value;\n" - + "arr.jvmName = sig;\n" - + "return arr;" - ) - private static native Object newArray(boolean primitive, String sig, int length); - - private static Object multiNewArray(String sig, int[] dims, int index) - throws IllegalArgumentException, NegativeArraySizeException { - if (dims.length == index + 1) { - return newArray(sig.length() == 2, sig, dims[index]); - } - Object[] arr = (Object[]) newArray(false, sig, dims[index]); - String compsig = sig.substring(1); - for (int i = 0; i < arr.length; i++) { - arr[i] = multiNewArray(compsig, dims, index + 1); - } - return arr; - } - private static Object fromPrimitive(Class t, Object array, int index) { - return Method.fromPrimitive(t, atArray(array, index)); - } - - @JavaScriptBody(args = { "array", "index" }, body = "return array[index]") - private static native Object atArray(Object array, int index); -} diff -r 388e48c0a37a -r 05224402145d emul/src/main/java/java/lang/reflect/Field.java --- a/emul/src/main/java/java/lang/reflect/Field.java Wed Jan 23 20:16:48 2013 +0100 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,953 +0,0 @@ -/* - * Copyright (c) 1996, 2006, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code 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 - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package java.lang.reflect; - -import java.lang.annotation.Annotation; - - -/** - * A {@code Field} provides information about, and dynamic access to, a - * single field of a class or an interface. The reflected field may - * be a class (static) field or an instance field. - * - *

A {@code Field} permits widening conversions to occur during a get or - * set access operation, but throws an {@code IllegalArgumentException} if a - * narrowing conversion would occur. - * - * @see Member - * @see java.lang.Class - * @see java.lang.Class#getFields() - * @see java.lang.Class#getField(String) - * @see java.lang.Class#getDeclaredFields() - * @see java.lang.Class#getDeclaredField(String) - * - * @author Kenneth Russell - * @author Nakul Saraiya - */ -public final -class Field extends AccessibleObject implements Member { - - private Class clazz; - private int slot; - // This is guaranteed to be interned by the VM in the 1.4 - // reflection implementation - private String name; - private Class type; - private int modifiers; - // Generics and annotations support - private transient String signature; - private byte[] annotations; - // For sharing of FieldAccessors. This branching structure is - // currently only two levels deep (i.e., one root Field and - // potentially many Field objects pointing to it.) - private Field root; - - // Generics infrastructure - - private String getGenericSignature() {return signature;} - - - /** - * Package-private constructor used by ReflectAccess to enable - * instantiation of these objects in Java code from the java.lang - * package via sun.reflect.LangReflectAccess. - */ - Field(Class declaringClass, - String name, - Class type, - int modifiers, - int slot, - String signature, - byte[] annotations) - { - this.clazz = declaringClass; - this.name = name; - this.type = type; - this.modifiers = modifiers; - this.slot = slot; - this.signature = signature; - this.annotations = annotations; - } - - /** - * Package-private routine (exposed to java.lang.Class via - * ReflectAccess) which returns a copy of this Field. The copy's - * "root" field points to this Field. - */ - Field copy() { - // This routine enables sharing of FieldAccessor objects - // among Field objects which refer to the same underlying - // method in the VM. (All of this contortion is only necessary - // because of the "accessibility" bit in AccessibleObject, - // which implicitly requires that new java.lang.reflect - // objects be fabricated for each reflective call on Class - // objects.) - Field res = new Field(clazz, name, type, modifiers, slot, signature, annotations); - res.root = this; - return res; - } - - /** - * Returns the {@code Class} object representing the class or interface - * that declares the field represented by this {@code Field} object. - */ - public Class getDeclaringClass() { - return clazz; - } - - /** - * Returns the name of the field represented by this {@code Field} object. - */ - public String getName() { - return name; - } - - /** - * Returns the Java language modifiers for the field represented - * by this {@code Field} object, as an integer. The {@code Modifier} class should - * be used to decode the modifiers. - * - * @see Modifier - */ - public int getModifiers() { - return modifiers; - } - - /** - * Returns {@code true} if this field represents an element of - * an enumerated type; returns {@code false} otherwise. - * - * @return {@code true} if and only if this field represents an element of - * an enumerated type. - * @since 1.5 - */ - public boolean isEnumConstant() { - return (getModifiers() & Modifier.ENUM) != 0; - } - - /** - * Returns {@code true} if this field is a synthetic - * field; returns {@code false} otherwise. - * - * @return true if and only if this field is a synthetic - * field as defined by the Java Language Specification. - * @since 1.5 - */ - public boolean isSynthetic() { - return Modifier.isSynthetic(getModifiers()); - } - - /** - * Returns a {@code Class} object that identifies the - * declared type for the field represented by this - * {@code Field} object. - * - * @return a {@code Class} object identifying the declared - * type of the field represented by this object - */ - public Class getType() { - return type; - } - - /** - * Returns a {@code Type} object that represents the declared type for - * the field represented by this {@code Field} object. - * - *

If the {@code Type} is a parameterized type, the - * {@code Type} object returned must accurately reflect the - * actual type parameters used in the source code. - * - *

If the type of the underlying field is a type variable or a - * parameterized type, it is created. Otherwise, it is resolved. - * - * @return a {@code Type} object that represents the declared type for - * the field represented by this {@code Field} object - * @throws GenericSignatureFormatError if the generic field - * signature does not conform to the format specified in - * The Java™ Virtual Machine Specification - * @throws TypeNotPresentException if the generic type - * signature of the underlying field refers to a non-existent - * type declaration - * @throws MalformedParameterizedTypeException if the generic - * signature of the underlying field refers to a parameterized type - * that cannot be instantiated for any reason - * @since 1.5 - */ - public Type getGenericType() { - throw new UnsupportedOperationException(); - } - - - /** - * Compares this {@code Field} against the specified object. Returns - * true if the objects are the same. Two {@code Field} objects are the same if - * they were declared by the same class and have the same name - * and type. - */ - public boolean equals(Object obj) { - if (obj != null && obj instanceof Field) { - Field other = (Field)obj; - return (getDeclaringClass() == other.getDeclaringClass()) - && (getName() == other.getName()) - && (getType() == other.getType()); - } - return false; - } - - /** - * Returns a hashcode for this {@code Field}. This is computed as the - * exclusive-or of the hashcodes for the underlying field's - * declaring class name and its name. - */ - public int hashCode() { - return getDeclaringClass().getName().hashCode() ^ getName().hashCode(); - } - - /** - * Returns a string describing this {@code Field}. The format is - * the access modifiers for the field, if any, followed - * by the field type, followed by a space, followed by - * the fully-qualified name of the class declaring the field, - * followed by a period, followed by the name of the field. - * For example: - *

-     *    public static final int java.lang.Thread.MIN_PRIORITY
-     *    private int java.io.FileDescriptor.fd
-     * 
- * - *

The modifiers are placed in canonical order as specified by - * "The Java Language Specification". This is {@code public}, - * {@code protected} or {@code private} first, and then other - * modifiers in the following order: {@code static}, {@code final}, - * {@code transient}, {@code volatile}. - */ - public String toString() { - int mod = getModifiers(); - return (((mod == 0) ? "" : (Modifier.toString(mod) + " ")) - + getTypeName(getType()) + " " - + getTypeName(getDeclaringClass()) + "." - + getName()); - } - - /** - * Returns a string describing this {@code Field}, including - * its generic type. The format is the access modifiers for the - * field, if any, followed by the generic field type, followed by - * a space, followed by the fully-qualified name of the class - * declaring the field, followed by a period, followed by the name - * of the field. - * - *

The modifiers are placed in canonical order as specified by - * "The Java Language Specification". This is {@code public}, - * {@code protected} or {@code private} first, and then other - * modifiers in the following order: {@code static}, {@code final}, - * {@code transient}, {@code volatile}. - * - * @return a string describing this {@code Field}, including - * its generic type - * - * @since 1.5 - */ - public String toGenericString() { - int mod = getModifiers(); - Type fieldType = getGenericType(); - return (((mod == 0) ? "" : (Modifier.toString(mod) + " ")) - + ((fieldType instanceof Class) ? - getTypeName((Class)fieldType): fieldType.toString())+ " " - + getTypeName(getDeclaringClass()) + "." - + getName()); - } - - /** - * Returns the value of the field represented by this {@code Field}, on - * the specified object. The value is automatically wrapped in an - * object if it has a primitive type. - * - *

The underlying field's value is obtained as follows: - * - *

If the underlying field is a static field, the {@code obj} argument - * is ignored; it may be null. - * - *

Otherwise, the underlying field is an instance field. If the - * specified {@code obj} argument is null, the method throws a - * {@code NullPointerException}. If the specified object is not an - * instance of the class or interface declaring the underlying - * field, the method throws an {@code IllegalArgumentException}. - * - *

If this {@code Field} object is enforcing Java language access control, and - * the underlying field is inaccessible, the method throws an - * {@code IllegalAccessException}. - * If the underlying field is static, the class that declared the - * field is initialized if it has not already been initialized. - * - *

Otherwise, the value is retrieved from the underlying instance - * or static field. If the field has a primitive type, the value - * is wrapped in an object before being returned, otherwise it is - * returned as is. - * - *

If the field is hidden in the type of {@code obj}, - * the field's value is obtained according to the preceding rules. - * - * @param obj object from which the represented field's value is - * to be extracted - * @return the value of the represented field in object - * {@code obj}; primitive values are wrapped in an appropriate - * object before being returned - * - * @exception IllegalAccessException if this {@code Field} object - * is enforcing Java language access control and the underlying - * field is inaccessible. - * @exception IllegalArgumentException if the specified object is not an - * instance of the class or interface declaring the underlying - * field (or a subclass or implementor thereof). - * @exception NullPointerException if the specified object is null - * and the field is an instance field. - * @exception ExceptionInInitializerError if the initialization provoked - * by this method fails. - */ - public Object get(Object obj) - throws IllegalArgumentException, IllegalAccessException - { - return getFieldAccessor(obj).get(obj); - } - - /** - * Gets the value of a static or instance {@code boolean} field. - * - * @param obj the object to extract the {@code boolean} value - * from - * @return the value of the {@code boolean} field - * - * @exception IllegalAccessException if this {@code Field} object - * is enforcing Java language access control and the underlying - * field is inaccessible. - * @exception IllegalArgumentException if the specified object is not - * an instance of the class or interface declaring the - * underlying field (or a subclass or implementor - * thereof), or if the field value cannot be - * converted to the type {@code boolean} by a - * widening conversion. - * @exception NullPointerException if the specified object is null - * and the field is an instance field. - * @exception ExceptionInInitializerError if the initialization provoked - * by this method fails. - * @see Field#get - */ - public boolean getBoolean(Object obj) - throws IllegalArgumentException, IllegalAccessException - { - return getFieldAccessor(obj).getBoolean(obj); - } - - /** - * Gets the value of a static or instance {@code byte} field. - * - * @param obj the object to extract the {@code byte} value - * from - * @return the value of the {@code byte} field - * - * @exception IllegalAccessException if this {@code Field} object - * is enforcing Java language access control and the underlying - * field is inaccessible. - * @exception IllegalArgumentException if the specified object is not - * an instance of the class or interface declaring the - * underlying field (or a subclass or implementor - * thereof), or if the field value cannot be - * converted to the type {@code byte} by a - * widening conversion. - * @exception NullPointerException if the specified object is null - * and the field is an instance field. - * @exception ExceptionInInitializerError if the initialization provoked - * by this method fails. - * @see Field#get - */ - public byte getByte(Object obj) - throws IllegalArgumentException, IllegalAccessException - { - return getFieldAccessor(obj).getByte(obj); - } - - /** - * Gets the value of a static or instance field of type - * {@code char} or of another primitive type convertible to - * type {@code char} via a widening conversion. - * - * @param obj the object to extract the {@code char} value - * from - * @return the value of the field converted to type {@code char} - * - * @exception IllegalAccessException if this {@code Field} object - * is enforcing Java language access control and the underlying - * field is inaccessible. - * @exception IllegalArgumentException if the specified object is not - * an instance of the class or interface declaring the - * underlying field (or a subclass or implementor - * thereof), or if the field value cannot be - * converted to the type {@code char} by a - * widening conversion. - * @exception NullPointerException if the specified object is null - * and the field is an instance field. - * @exception ExceptionInInitializerError if the initialization provoked - * by this method fails. - * @see Field#get - */ - public char getChar(Object obj) - throws IllegalArgumentException, IllegalAccessException - { - return getFieldAccessor(obj).getChar(obj); - } - - /** - * Gets the value of a static or instance field of type - * {@code short} or of another primitive type convertible to - * type {@code short} via a widening conversion. - * - * @param obj the object to extract the {@code short} value - * from - * @return the value of the field converted to type {@code short} - * - * @exception IllegalAccessException if this {@code Field} object - * is enforcing Java language access control and the underlying - * field is inaccessible. - * @exception IllegalArgumentException if the specified object is not - * an instance of the class or interface declaring the - * underlying field (or a subclass or implementor - * thereof), or if the field value cannot be - * converted to the type {@code short} by a - * widening conversion. - * @exception NullPointerException if the specified object is null - * and the field is an instance field. - * @exception ExceptionInInitializerError if the initialization provoked - * by this method fails. - * @see Field#get - */ - public short getShort(Object obj) - throws IllegalArgumentException, IllegalAccessException - { - return getFieldAccessor(obj).getShort(obj); - } - - /** - * Gets the value of a static or instance field of type - * {@code int} or of another primitive type convertible to - * type {@code int} via a widening conversion. - * - * @param obj the object to extract the {@code int} value - * from - * @return the value of the field converted to type {@code int} - * - * @exception IllegalAccessException if this {@code Field} object - * is enforcing Java language access control and the underlying - * field is inaccessible. - * @exception IllegalArgumentException if the specified object is not - * an instance of the class or interface declaring the - * underlying field (or a subclass or implementor - * thereof), or if the field value cannot be - * converted to the type {@code int} by a - * widening conversion. - * @exception NullPointerException if the specified object is null - * and the field is an instance field. - * @exception ExceptionInInitializerError if the initialization provoked - * by this method fails. - * @see Field#get - */ - public int getInt(Object obj) - throws IllegalArgumentException, IllegalAccessException - { - return getFieldAccessor(obj).getInt(obj); - } - - /** - * Gets the value of a static or instance field of type - * {@code long} or of another primitive type convertible to - * type {@code long} via a widening conversion. - * - * @param obj the object to extract the {@code long} value - * from - * @return the value of the field converted to type {@code long} - * - * @exception IllegalAccessException if this {@code Field} object - * is enforcing Java language access control and the underlying - * field is inaccessible. - * @exception IllegalArgumentException if the specified object is not - * an instance of the class or interface declaring the - * underlying field (or a subclass or implementor - * thereof), or if the field value cannot be - * converted to the type {@code long} by a - * widening conversion. - * @exception NullPointerException if the specified object is null - * and the field is an instance field. - * @exception ExceptionInInitializerError if the initialization provoked - * by this method fails. - * @see Field#get - */ - public long getLong(Object obj) - throws IllegalArgumentException, IllegalAccessException - { - return getFieldAccessor(obj).getLong(obj); - } - - /** - * Gets the value of a static or instance field of type - * {@code float} or of another primitive type convertible to - * type {@code float} via a widening conversion. - * - * @param obj the object to extract the {@code float} value - * from - * @return the value of the field converted to type {@code float} - * - * @exception IllegalAccessException if this {@code Field} object - * is enforcing Java language access control and the underlying - * field is inaccessible. - * @exception IllegalArgumentException if the specified object is not - * an instance of the class or interface declaring the - * underlying field (or a subclass or implementor - * thereof), or if the field value cannot be - * converted to the type {@code float} by a - * widening conversion. - * @exception NullPointerException if the specified object is null - * and the field is an instance field. - * @exception ExceptionInInitializerError if the initialization provoked - * by this method fails. - * @see Field#get - */ - public float getFloat(Object obj) - throws IllegalArgumentException, IllegalAccessException - { - return getFieldAccessor(obj).getFloat(obj); - } - - /** - * Gets the value of a static or instance field of type - * {@code double} or of another primitive type convertible to - * type {@code double} via a widening conversion. - * - * @param obj the object to extract the {@code double} value - * from - * @return the value of the field converted to type {@code double} - * - * @exception IllegalAccessException if this {@code Field} object - * is enforcing Java language access control and the underlying - * field is inaccessible. - * @exception IllegalArgumentException if the specified object is not - * an instance of the class or interface declaring the - * underlying field (or a subclass or implementor - * thereof), or if the field value cannot be - * converted to the type {@code double} by a - * widening conversion. - * @exception NullPointerException if the specified object is null - * and the field is an instance field. - * @exception ExceptionInInitializerError if the initialization provoked - * by this method fails. - * @see Field#get - */ - public double getDouble(Object obj) - throws IllegalArgumentException, IllegalAccessException - { - return getFieldAccessor(obj).getDouble(obj); - } - - /** - * Sets the field represented by this {@code Field} object on the - * specified object argument to the specified new value. The new - * value is automatically unwrapped if the underlying field has a - * primitive type. - * - *

The operation proceeds as follows: - * - *

If the underlying field is static, the {@code obj} argument is - * ignored; it may be null. - * - *

Otherwise the underlying field is an instance field. If the - * specified object argument is null, the method throws a - * {@code NullPointerException}. If the specified object argument is not - * an instance of the class or interface declaring the underlying - * field, the method throws an {@code IllegalArgumentException}. - * - *

If this {@code Field} object is enforcing Java language access control, and - * the underlying field is inaccessible, the method throws an - * {@code IllegalAccessException}. - * - *

If the underlying field is final, the method throws an - * {@code IllegalAccessException} unless {@code setAccessible(true)} - * has succeeded for this {@code Field} object - * and the field is non-static. Setting a final field in this way - * is meaningful only during deserialization or reconstruction of - * instances of classes with blank final fields, before they are - * made available for access by other parts of a program. Use in - * any other context may have unpredictable effects, including cases - * in which other parts of a program continue to use the original - * value of this field. - * - *

If the underlying field is of a primitive type, an unwrapping - * conversion is attempted to convert the new value to a value of - * a primitive type. If this attempt fails, the method throws an - * {@code IllegalArgumentException}. - * - *

If, after possible unwrapping, the new value cannot be - * converted to the type of the underlying field by an identity or - * widening conversion, the method throws an - * {@code IllegalArgumentException}. - * - *

If the underlying field is static, the class that declared the - * field is initialized if it has not already been initialized. - * - *

The field is set to the possibly unwrapped and widened new value. - * - *

If the field is hidden in the type of {@code obj}, - * the field's value is set according to the preceding rules. - * - * @param obj the object whose field should be modified - * @param value the new value for the field of {@code obj} - * being modified - * - * @exception IllegalAccessException if this {@code Field} object - * is enforcing Java language access control and the underlying - * field is either inaccessible or final. - * @exception IllegalArgumentException if the specified object is not an - * instance of the class or interface declaring the underlying - * field (or a subclass or implementor thereof), - * or if an unwrapping conversion fails. - * @exception NullPointerException if the specified object is null - * and the field is an instance field. - * @exception ExceptionInInitializerError if the initialization provoked - * by this method fails. - */ - public void set(Object obj, Object value) - throws IllegalArgumentException, IllegalAccessException - { - getFieldAccessor(obj).set(obj, value); - } - - /** - * Sets the value of a field as a {@code boolean} on the specified object. - * This method is equivalent to - * {@code set(obj, zObj)}, - * where {@code zObj} is a {@code Boolean} object and - * {@code zObj.booleanValue() == z}. - * - * @param obj the object whose field should be modified - * @param z the new value for the field of {@code obj} - * being modified - * - * @exception IllegalAccessException if this {@code Field} object - * is enforcing Java language access control and the underlying - * field is either inaccessible or final. - * @exception IllegalArgumentException if the specified object is not an - * instance of the class or interface declaring the underlying - * field (or a subclass or implementor thereof), - * or if an unwrapping conversion fails. - * @exception NullPointerException if the specified object is null - * and the field is an instance field. - * @exception ExceptionInInitializerError if the initialization provoked - * by this method fails. - * @see Field#set - */ - public void setBoolean(Object obj, boolean z) - throws IllegalArgumentException, IllegalAccessException - { - getFieldAccessor(obj).setBoolean(obj, z); - } - - /** - * Sets the value of a field as a {@code byte} on the specified object. - * This method is equivalent to - * {@code set(obj, bObj)}, - * where {@code bObj} is a {@code Byte} object and - * {@code bObj.byteValue() == b}. - * - * @param obj the object whose field should be modified - * @param b the new value for the field of {@code obj} - * being modified - * - * @exception IllegalAccessException if this {@code Field} object - * is enforcing Java language access control and the underlying - * field is either inaccessible or final. - * @exception IllegalArgumentException if the specified object is not an - * instance of the class or interface declaring the underlying - * field (or a subclass or implementor thereof), - * or if an unwrapping conversion fails. - * @exception NullPointerException if the specified object is null - * and the field is an instance field. - * @exception ExceptionInInitializerError if the initialization provoked - * by this method fails. - * @see Field#set - */ - public void setByte(Object obj, byte b) - throws IllegalArgumentException, IllegalAccessException - { - getFieldAccessor(obj).setByte(obj, b); - } - - /** - * Sets the value of a field as a {@code char} on the specified object. - * This method is equivalent to - * {@code set(obj, cObj)}, - * where {@code cObj} is a {@code Character} object and - * {@code cObj.charValue() == c}. - * - * @param obj the object whose field should be modified - * @param c the new value for the field of {@code obj} - * being modified - * - * @exception IllegalAccessException if this {@code Field} object - * is enforcing Java language access control and the underlying - * field is either inaccessible or final. - * @exception IllegalArgumentException if the specified object is not an - * instance of the class or interface declaring the underlying - * field (or a subclass or implementor thereof), - * or if an unwrapping conversion fails. - * @exception NullPointerException if the specified object is null - * and the field is an instance field. - * @exception ExceptionInInitializerError if the initialization provoked - * by this method fails. - * @see Field#set - */ - public void setChar(Object obj, char c) - throws IllegalArgumentException, IllegalAccessException - { - getFieldAccessor(obj).setChar(obj, c); - } - - /** - * Sets the value of a field as a {@code short} on the specified object. - * This method is equivalent to - * {@code set(obj, sObj)}, - * where {@code sObj} is a {@code Short} object and - * {@code sObj.shortValue() == s}. - * - * @param obj the object whose field should be modified - * @param s the new value for the field of {@code obj} - * being modified - * - * @exception IllegalAccessException if this {@code Field} object - * is enforcing Java language access control and the underlying - * field is either inaccessible or final. - * @exception IllegalArgumentException if the specified object is not an - * instance of the class or interface declaring the underlying - * field (or a subclass or implementor thereof), - * or if an unwrapping conversion fails. - * @exception NullPointerException if the specified object is null - * and the field is an instance field. - * @exception ExceptionInInitializerError if the initialization provoked - * by this method fails. - * @see Field#set - */ - public void setShort(Object obj, short s) - throws IllegalArgumentException, IllegalAccessException - { - getFieldAccessor(obj).setShort(obj, s); - } - - /** - * Sets the value of a field as an {@code int} on the specified object. - * This method is equivalent to - * {@code set(obj, iObj)}, - * where {@code iObj} is a {@code Integer} object and - * {@code iObj.intValue() == i}. - * - * @param obj the object whose field should be modified - * @param i the new value for the field of {@code obj} - * being modified - * - * @exception IllegalAccessException if this {@code Field} object - * is enforcing Java language access control and the underlying - * field is either inaccessible or final. - * @exception IllegalArgumentException if the specified object is not an - * instance of the class or interface declaring the underlying - * field (or a subclass or implementor thereof), - * or if an unwrapping conversion fails. - * @exception NullPointerException if the specified object is null - * and the field is an instance field. - * @exception ExceptionInInitializerError if the initialization provoked - * by this method fails. - * @see Field#set - */ - public void setInt(Object obj, int i) - throws IllegalArgumentException, IllegalAccessException - { - getFieldAccessor(obj).setInt(obj, i); - } - - /** - * Sets the value of a field as a {@code long} on the specified object. - * This method is equivalent to - * {@code set(obj, lObj)}, - * where {@code lObj} is a {@code Long} object and - * {@code lObj.longValue() == l}. - * - * @param obj the object whose field should be modified - * @param l the new value for the field of {@code obj} - * being modified - * - * @exception IllegalAccessException if this {@code Field} object - * is enforcing Java language access control and the underlying - * field is either inaccessible or final. - * @exception IllegalArgumentException if the specified object is not an - * instance of the class or interface declaring the underlying - * field (or a subclass or implementor thereof), - * or if an unwrapping conversion fails. - * @exception NullPointerException if the specified object is null - * and the field is an instance field. - * @exception ExceptionInInitializerError if the initialization provoked - * by this method fails. - * @see Field#set - */ - public void setLong(Object obj, long l) - throws IllegalArgumentException, IllegalAccessException - { - getFieldAccessor(obj).setLong(obj, l); - } - - /** - * Sets the value of a field as a {@code float} on the specified object. - * This method is equivalent to - * {@code set(obj, fObj)}, - * where {@code fObj} is a {@code Float} object and - * {@code fObj.floatValue() == f}. - * - * @param obj the object whose field should be modified - * @param f the new value for the field of {@code obj} - * being modified - * - * @exception IllegalAccessException if this {@code Field} object - * is enforcing Java language access control and the underlying - * field is either inaccessible or final. - * @exception IllegalArgumentException if the specified object is not an - * instance of the class or interface declaring the underlying - * field (or a subclass or implementor thereof), - * or if an unwrapping conversion fails. - * @exception NullPointerException if the specified object is null - * and the field is an instance field. - * @exception ExceptionInInitializerError if the initialization provoked - * by this method fails. - * @see Field#set - */ - public void setFloat(Object obj, float f) - throws IllegalArgumentException, IllegalAccessException - { - getFieldAccessor(obj).setFloat(obj, f); - } - - /** - * Sets the value of a field as a {@code double} on the specified object. - * This method is equivalent to - * {@code set(obj, dObj)}, - * where {@code dObj} is a {@code Double} object and - * {@code dObj.doubleValue() == d}. - * - * @param obj the object whose field should be modified - * @param d the new value for the field of {@code obj} - * being modified - * - * @exception IllegalAccessException if this {@code Field} object - * is enforcing Java language access control and the underlying - * field is either inaccessible or final. - * @exception IllegalArgumentException if the specified object is not an - * instance of the class or interface declaring the underlying - * field (or a subclass or implementor thereof), - * or if an unwrapping conversion fails. - * @exception NullPointerException if the specified object is null - * and the field is an instance field. - * @exception ExceptionInInitializerError if the initialization provoked - * by this method fails. - * @see Field#set - */ - public void setDouble(Object obj, double d) - throws IllegalArgumentException, IllegalAccessException - { - getFieldAccessor(obj).setDouble(obj, d); - } - - // Convenience routine which performs security checks - private FieldAccessor getFieldAccessor(Object obj) - throws IllegalAccessException - { - throw new SecurityException(); - } - - private static abstract class FieldAccessor { - abstract void setShort(Object obj, short s); - abstract void setInt(Object obj, int i); - abstract void setChar(Object obj, char c); - abstract void setByte(Object obj, byte b); - abstract void setBoolean(Object obj, boolean z); - abstract void set(Object obj, Object value); - abstract double getDouble(Object obj); - abstract void setLong(Object obj, long l); - abstract void setFloat(Object obj, float f); - abstract void setDouble(Object obj, double d); - abstract long getLong(Object obj); - abstract int getInt(Object obj); - abstract short getShort(Object obj); - abstract char getChar(Object obj); - abstract byte getByte(Object obj); - abstract boolean getBoolean(Object obj); - abstract Object get(Object obj); - abstract float getFloat(Object obj); - } - - /* - * Utility routine to paper over array type names - */ - static String getTypeName(Class type) { - if (type.isArray()) { - try { - Class cl = type; - int dimensions = 0; - while (cl.isArray()) { - dimensions++; - cl = cl.getComponentType(); - } - StringBuffer sb = new StringBuffer(); - sb.append(cl.getName()); - for (int i = 0; i < dimensions; i++) { - sb.append("[]"); - } - return sb.toString(); - } catch (Throwable e) { /*FALLTHRU*/ } - } - return type.getName(); - } - - /** - * @throws NullPointerException {@inheritDoc} - * @since 1.5 - */ - public T getAnnotation(Class annotationClass) { - if (annotationClass == null) - throw new NullPointerException(); - - throw new UnsupportedOperationException(); - } - - /** - * @since 1.5 - */ - public Annotation[] getDeclaredAnnotations() { - throw new UnsupportedOperationException(); - } -} diff -r 388e48c0a37a -r 05224402145d emul/src/main/java/java/lang/reflect/GenericDeclaration.java --- a/emul/src/main/java/java/lang/reflect/GenericDeclaration.java Wed Jan 23 20:16:48 2013 +0100 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,49 +0,0 @@ -/* - * Copyright (c) 2003, 2004, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code 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 - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package java.lang.reflect; - -/** - * A common interface for all entities that declare type variables. - * - * @since 1.5 - */ -public interface GenericDeclaration { - /** - * Returns an array of {@code TypeVariable} objects that - * represent the type variables declared by the generic - * declaration represented by this {@code GenericDeclaration} - * object, in declaration order. Returns an array of length 0 if - * the underlying generic declaration declares no type variables. - * - * @return an array of {@code TypeVariable} objects that represent - * the type variables declared by this generic declaration - * @throws GenericSignatureFormatError if the generic - * signature of this generic declaration does not conform to - * the format specified in - * The Java™ Virtual Machine Specification - */ - public TypeVariable[] getTypeParameters(); -} diff -r 388e48c0a37a -r 05224402145d emul/src/main/java/java/lang/reflect/InvocationTargetException.java --- a/emul/src/main/java/java/lang/reflect/InvocationTargetException.java Wed Jan 23 20:16:48 2013 +0100 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,111 +0,0 @@ -/* - * Copyright (c) 1996, 2004, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code 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 - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package java.lang.reflect; - -/** - * InvocationTargetException is a checked exception that wraps - * an exception thrown by an invoked method or constructor. - * - *

As of release 1.4, this exception has been retrofitted to conform to - * the general purpose exception-chaining mechanism. The "target exception" - * that is provided at construction time and accessed via the - * {@link #getTargetException()} method is now known as the cause, - * and may be accessed via the {@link Throwable#getCause()} method, - * as well as the aforementioned "legacy method." - * - * @see Method - * @see Constructor - */ -public class InvocationTargetException extends ReflectiveOperationException { - /** - * Use serialVersionUID from JDK 1.1.X for interoperability - */ - private static final long serialVersionUID = 4085088731926701167L; - - /** - * This field holds the target if the - * InvocationTargetException(Throwable target) constructor was - * used to instantiate the object - * - * @serial - * - */ - private Throwable target; - - /** - * Constructs an {@code InvocationTargetException} with - * {@code null} as the target exception. - */ - protected InvocationTargetException() { - super((Throwable)null); // Disallow initCause - } - - /** - * Constructs a InvocationTargetException with a target exception. - * - * @param target the target exception - */ - public InvocationTargetException(Throwable target) { - super((Throwable)null); // Disallow initCause - this.target = target; - } - - /** - * Constructs a InvocationTargetException with a target exception - * and a detail message. - * - * @param target the target exception - * @param s the detail message - */ - public InvocationTargetException(Throwable target, String s) { - super(s, null); // Disallow initCause - this.target = target; - } - - /** - * Get the thrown target exception. - * - *

This method predates the general-purpose exception chaining facility. - * The {@link Throwable#getCause()} method is now the preferred means of - * obtaining this information. - * - * @return the thrown target exception (cause of this exception). - */ - public Throwable getTargetException() { - return target; - } - - /** - * Returns the cause of this exception (the thrown target exception, - * which may be {@code null}). - * - * @return the cause of this exception. - * @since 1.4 - */ - public Throwable getCause() { - return target; - } -} diff -r 388e48c0a37a -r 05224402145d emul/src/main/java/java/lang/reflect/Member.java --- a/emul/src/main/java/java/lang/reflect/Member.java Wed Jan 23 20:16:48 2013 +0100 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,93 +0,0 @@ -/* - * Copyright (c) 1996, 2006, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code 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 - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package java.lang.reflect; - -/** - * Member is an interface that reflects identifying information about - * a single member (a field or a method) or a constructor. - * - * @see java.lang.Class - * @see Field - * @see Method - * @see Constructor - * - * @author Nakul Saraiya - */ -public -interface Member { - - /** - * Identifies the set of all public members of a class or interface, - * including inherited members. - * @see java.lang.SecurityManager#checkMemberAccess - */ - public static final int PUBLIC = 0; - - /** - * Identifies the set of declared members of a class or interface. - * Inherited members are not included. - * @see java.lang.SecurityManager#checkMemberAccess - */ - public static final int DECLARED = 1; - - /** - * Returns the Class object representing the class or interface - * that declares the member or constructor represented by this Member. - * - * @return an object representing the declaring class of the - * underlying member - */ - public Class getDeclaringClass(); - - /** - * Returns the simple name of the underlying member or constructor - * represented by this Member. - * - * @return the simple name of the underlying member - */ - public String getName(); - - /** - * Returns the Java language modifiers for the member or - * constructor represented by this Member, as an integer. The - * Modifier class should be used to decode the modifiers in - * the integer. - * - * @return the Java language modifiers for the underlying member - * @see Modifier - */ - public int getModifiers(); - - /** - * Returns {@code true} if this member was introduced by - * the compiler; returns {@code false} otherwise. - * - * @return true if and only if this member was introduced by - * the compiler. - * @since 1.5 - */ - public boolean isSynthetic(); -} diff -r 388e48c0a37a -r 05224402145d emul/src/main/java/java/lang/reflect/Method.java --- a/emul/src/main/java/java/lang/reflect/Method.java Wed Jan 23 20:16:48 2013 +0100 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,720 +0,0 @@ -/* - * Copyright (c) 1996, 2006, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code 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 - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package java.lang.reflect; - -import java.lang.annotation.Annotation; -import java.util.Enumeration; -import org.apidesign.bck2brwsr.core.JavaScriptBody; -import org.apidesign.bck2brwsr.emul.AnnotationImpl; -import org.apidesign.bck2brwsr.emul.MethodImpl; - -/** - * A {@code Method} provides information about, and access to, a single method - * on a class or interface. The reflected method may be a class method - * or an instance method (including an abstract method). - * - *

A {@code Method} permits widening conversions to occur when matching the - * actual parameters to invoke with the underlying method's formal - * parameters, but it throws an {@code IllegalArgumentException} if a - * narrowing conversion would occur. - * - * @see Member - * @see java.lang.Class - * @see java.lang.Class#getMethods() - * @see java.lang.Class#getMethod(String, Class[]) - * @see java.lang.Class#getDeclaredMethods() - * @see java.lang.Class#getDeclaredMethod(String, Class[]) - * - * @author Kenneth Russell - * @author Nakul Saraiya - */ -public final - class Method extends AccessibleObject implements GenericDeclaration, - Member { - private final Class clazz; - private final String name; - private final Object data; - private final String sig; - - // Generics infrastructure - - private String getGenericSignature() {return null;} - - /** - * Package-private constructor used by ReflectAccess to enable - * instantiation of these objects in Java code from the java.lang - * package via sun.reflect.LangReflectAccess. - */ - Method(Class declaringClass, String name, Object data, String sig) - { - this.clazz = declaringClass; - this.name = name; - this.data = data; - this.sig = sig; - } - - /** - * Package-private routine (exposed to java.lang.Class via - * ReflectAccess) which returns a copy of this Method. The copy's - * "root" field points to this Method. - */ - Method copy() { - return this; - } - - /** - * Returns the {@code Class} object representing the class or interface - * that declares the method represented by this {@code Method} object. - */ - public Class getDeclaringClass() { - return clazz; - } - - /** - * Returns the name of the method represented by this {@code Method} - * object, as a {@code String}. - */ - public String getName() { - return name; - } - - /** - * Returns the Java language modifiers for the method represented - * by this {@code Method} object, as an integer. The {@code Modifier} class should - * be used to decode the modifiers. - * - * @see Modifier - */ - public int getModifiers() { - return getAccess(data); - } - - @JavaScriptBody(args = "self", body = "return self.access;") - private static native int getAccess(Object self); - - /** - * Returns an array of {@code TypeVariable} objects that represent the - * type variables declared by the generic declaration represented by this - * {@code GenericDeclaration} object, in declaration order. Returns an - * array of length 0 if the underlying generic declaration declares no type - * variables. - * - * @return an array of {@code TypeVariable} objects that represent - * the type variables declared by this generic declaration - * @throws GenericSignatureFormatError if the generic - * signature of this generic declaration does not conform to - * the format specified in - * The Java™ Virtual Machine Specification - * @since 1.5 - */ - public TypeVariable[] getTypeParameters() { - throw new UnsupportedOperationException(); - } - - /** - * Returns a {@code Class} object that represents the formal return type - * of the method represented by this {@code Method} object. - * - * @return the return type for the method this object represents - */ - public Class getReturnType() { - return MethodImpl.signatureParser(sig).nextElement(); - } - - /** - * Returns a {@code Type} object that represents the formal return - * type of the method represented by this {@code Method} object. - * - *

If the return type is a parameterized type, - * the {@code Type} object returned must accurately reflect - * the actual type parameters used in the source code. - * - *

If the return type is a type variable or a parameterized type, it - * is created. Otherwise, it is resolved. - * - * @return a {@code Type} object that represents the formal return - * type of the underlying method - * @throws GenericSignatureFormatError - * if the generic method signature does not conform to the format - * specified in - * The Java™ Virtual Machine Specification - * @throws TypeNotPresentException if the underlying method's - * return type refers to a non-existent type declaration - * @throws MalformedParameterizedTypeException if the - * underlying method's return typed refers to a parameterized - * type that cannot be instantiated for any reason - * @since 1.5 - */ - public Type getGenericReturnType() { - throw new UnsupportedOperationException(); - } - - - /** - * Returns an array of {@code Class} objects that represent the formal - * parameter types, in declaration order, of the method - * represented by this {@code Method} object. Returns an array of length - * 0 if the underlying method takes no parameters. - * - * @return the parameter types for the method this object - * represents - */ - public Class[] getParameterTypes() { - Class[] arr = new Class[MethodImpl.signatureElements(sig) - 1]; - Enumeration en = MethodImpl.signatureParser(sig); - en.nextElement(); // return type - for (int i = 0; i < arr.length; i++) { - arr[i] = en.nextElement(); - } - return arr; - } - - /** - * Returns an array of {@code Type} objects that represent the formal - * parameter types, in declaration order, of the method represented by - * this {@code Method} object. Returns an array of length 0 if the - * underlying method takes no parameters. - * - *

If a formal parameter type is a parameterized type, - * the {@code Type} object returned for it must accurately reflect - * the actual type parameters used in the source code. - * - *

If a formal parameter type is a type variable or a parameterized - * type, it is created. Otherwise, it is resolved. - * - * @return an array of Types that represent the formal - * parameter types of the underlying method, in declaration order - * @throws GenericSignatureFormatError - * if the generic method signature does not conform to the format - * specified in - * The Java™ Virtual Machine Specification - * @throws TypeNotPresentException if any of the parameter - * types of the underlying method refers to a non-existent type - * declaration - * @throws MalformedParameterizedTypeException if any of - * the underlying method's parameter types refer to a parameterized - * type that cannot be instantiated for any reason - * @since 1.5 - */ - public Type[] getGenericParameterTypes() { - throw new UnsupportedOperationException(); - } - - - /** - * Returns an array of {@code Class} objects that represent - * the types of the exceptions declared to be thrown - * by the underlying method - * represented by this {@code Method} object. Returns an array of length - * 0 if the method declares no exceptions in its {@code throws} clause. - * - * @return the exception types declared as being thrown by the - * method this object represents - */ - public Class[] getExceptionTypes() { - throw new UnsupportedOperationException(); - //return (Class[]) exceptionTypes.clone(); - } - - /** - * Returns an array of {@code Type} objects that represent the - * exceptions declared to be thrown by this {@code Method} object. - * Returns an array of length 0 if the underlying method declares - * no exceptions in its {@code throws} clause. - * - *

If an exception type is a type variable or a parameterized - * type, it is created. Otherwise, it is resolved. - * - * @return an array of Types that represent the exception types - * thrown by the underlying method - * @throws GenericSignatureFormatError - * if the generic method signature does not conform to the format - * specified in - * The Java™ Virtual Machine Specification - * @throws TypeNotPresentException if the underlying method's - * {@code throws} clause refers to a non-existent type declaration - * @throws MalformedParameterizedTypeException if - * the underlying method's {@code throws} clause refers to a - * parameterized type that cannot be instantiated for any reason - * @since 1.5 - */ - public Type[] getGenericExceptionTypes() { - throw new UnsupportedOperationException(); - } - - /** - * Compares this {@code Method} against the specified object. Returns - * true if the objects are the same. Two {@code Methods} are the same if - * they were declared by the same class and have the same name - * and formal parameter types and return type. - */ - public boolean equals(Object obj) { - if (obj != null && obj instanceof Method) { - Method other = (Method)obj; - return data == other.data; - } - return false; - } - - /** - * Returns a hashcode for this {@code Method}. The hashcode is computed - * as the exclusive-or of the hashcodes for the underlying - * method's declaring class name and the method's name. - */ - public int hashCode() { - return getDeclaringClass().getName().hashCode() ^ getName().hashCode(); - } - - /** - * Returns a string describing this {@code Method}. The string is - * formatted as the method access modifiers, if any, followed by - * the method return type, followed by a space, followed by the - * class declaring the method, followed by a period, followed by - * the method name, followed by a parenthesized, comma-separated - * list of the method's formal parameter types. If the method - * throws checked exceptions, the parameter list is followed by a - * space, followed by the word throws followed by a - * comma-separated list of the thrown exception types. - * For example: - *

-     *    public boolean java.lang.Object.equals(java.lang.Object)
-     * 
- * - *

The access modifiers are placed in canonical order as - * specified by "The Java Language Specification". This is - * {@code public}, {@code protected} or {@code private} first, - * and then other modifiers in the following order: - * {@code abstract}, {@code static}, {@code final}, - * {@code synchronized}, {@code native}, {@code strictfp}. - */ - public String toString() { - try { - StringBuilder sb = new StringBuilder(); - int mod = getModifiers() & Modifier.methodModifiers(); - if (mod != 0) { - sb.append(Modifier.toString(mod)).append(' '); - } - sb.append(Field.getTypeName(getReturnType())).append(' '); - sb.append(Field.getTypeName(getDeclaringClass())).append('.'); - sb.append(getName()).append('('); - Class[] params = getParameterTypes(); // avoid clone - for (int j = 0; j < params.length; j++) { - sb.append(Field.getTypeName(params[j])); - if (j < (params.length - 1)) - sb.append(','); - } - sb.append(')'); - /* - Class[] exceptions = exceptionTypes; // avoid clone - if (exceptions.length > 0) { - sb.append(" throws "); - for (int k = 0; k < exceptions.length; k++) { - sb.append(exceptions[k].getName()); - if (k < (exceptions.length - 1)) - sb.append(','); - } - } - */ - return sb.toString(); - } catch (Exception e) { - return "<" + e + ">"; - } - } - - /** - * Returns a string describing this {@code Method}, including - * type parameters. The string is formatted as the method access - * modifiers, if any, followed by an angle-bracketed - * comma-separated list of the method's type parameters, if any, - * followed by the method's generic return type, followed by a - * space, followed by the class declaring the method, followed by - * a period, followed by the method name, followed by a - * parenthesized, comma-separated list of the method's generic - * formal parameter types. - * - * If this method was declared to take a variable number of - * arguments, instead of denoting the last parameter as - * "Type[]", it is denoted as - * "Type...". - * - * A space is used to separate access modifiers from one another - * and from the type parameters or return type. If there are no - * type parameters, the type parameter list is elided; if the type - * parameter list is present, a space separates the list from the - * class name. If the method is declared to throw exceptions, the - * parameter list is followed by a space, followed by the word - * throws followed by a comma-separated list of the generic thrown - * exception types. If there are no type parameters, the type - * parameter list is elided. - * - *

The access modifiers are placed in canonical order as - * specified by "The Java Language Specification". This is - * {@code public}, {@code protected} or {@code private} first, - * and then other modifiers in the following order: - * {@code abstract}, {@code static}, {@code final}, - * {@code synchronized}, {@code native}, {@code strictfp}. - * - * @return a string describing this {@code Method}, - * include type parameters - * - * @since 1.5 - */ - public String toGenericString() { - try { - StringBuilder sb = new StringBuilder(); - int mod = getModifiers() & Modifier.methodModifiers(); - if (mod != 0) { - sb.append(Modifier.toString(mod)).append(' '); - } - TypeVariable[] typeparms = getTypeParameters(); - if (typeparms.length > 0) { - boolean first = true; - sb.append('<'); - for(TypeVariable typeparm: typeparms) { - if (!first) - sb.append(','); - // Class objects can't occur here; no need to test - // and call Class.getName(). - sb.append(typeparm.toString()); - first = false; - } - sb.append("> "); - } - - Type genRetType = getGenericReturnType(); - sb.append( ((genRetType instanceof Class)? - Field.getTypeName((Class)genRetType):genRetType.toString())) - .append(' '); - - sb.append(Field.getTypeName(getDeclaringClass())).append('.'); - sb.append(getName()).append('('); - Type[] params = getGenericParameterTypes(); - for (int j = 0; j < params.length; j++) { - String param = (params[j] instanceof Class)? - Field.getTypeName((Class)params[j]): - (params[j].toString()); - if (isVarArgs() && (j == params.length - 1)) // replace T[] with T... - param = param.replaceFirst("\\[\\]$", "..."); - sb.append(param); - if (j < (params.length - 1)) - sb.append(','); - } - sb.append(')'); - Type[] exceptions = getGenericExceptionTypes(); - if (exceptions.length > 0) { - sb.append(" throws "); - for (int k = 0; k < exceptions.length; k++) { - sb.append((exceptions[k] instanceof Class)? - ((Class)exceptions[k]).getName(): - exceptions[k].toString()); - if (k < (exceptions.length - 1)) - sb.append(','); - } - } - return sb.toString(); - } catch (Exception e) { - return "<" + e + ">"; - } - } - - /** - * Invokes the underlying method represented by this {@code Method} - * object, on the specified object with the specified parameters. - * Individual parameters are automatically unwrapped to match - * primitive formal parameters, and both primitive and reference - * parameters are subject to method invocation conversions as - * necessary. - * - *

If the underlying method is static, then the specified {@code obj} - * argument is ignored. It may be null. - * - *

If the number of formal parameters required by the underlying method is - * 0, the supplied {@code args} array may be of length 0 or null. - * - *

If the underlying method is an instance method, it is invoked - * using dynamic method lookup as documented in The Java Language - * Specification, Second Edition, section 15.12.4.4; in particular, - * overriding based on the runtime type of the target object will occur. - * - *

If the underlying method is static, the class that declared - * the method is initialized if it has not already been initialized. - * - *

If the method completes normally, the value it returns is - * returned to the caller of invoke; if the value has a primitive - * type, it is first appropriately wrapped in an object. However, - * if the value has the type of an array of a primitive type, the - * elements of the array are not wrapped in objects; in - * other words, an array of primitive type is returned. If the - * underlying method return type is void, the invocation returns - * null. - * - * @param obj the object the underlying method is invoked from - * @param args the arguments used for the method call - * @return the result of dispatching the method represented by - * this object on {@code obj} with parameters - * {@code args} - * - * @exception IllegalAccessException if this {@code Method} object - * is enforcing Java language access control and the underlying - * method is inaccessible. - * @exception IllegalArgumentException if the method is an - * instance method and the specified object argument - * is not an instance of the class or interface - * declaring the underlying method (or of a subclass - * or implementor thereof); if the number of actual - * and formal parameters differ; if an unwrapping - * conversion for primitive arguments fails; or if, - * after possible unwrapping, a parameter value - * cannot be converted to the corresponding formal - * parameter type by a method invocation conversion. - * @exception InvocationTargetException if the underlying method - * throws an exception. - * @exception NullPointerException if the specified object is null - * and the method is an instance method. - * @exception ExceptionInInitializerError if the initialization - * provoked by this method fails. - */ - public Object invoke(Object obj, Object... args) - throws IllegalAccessException, IllegalArgumentException, - InvocationTargetException - { - final boolean isStatic = (getModifiers() & Modifier.STATIC) == 0; - if (isStatic && obj == null) { - throw new NullPointerException(); - } - Class[] types = getParameterTypes(); - if (types.length != args.length) { - throw new IllegalArgumentException("Types len " + types.length + " args: " + args.length); - } else { - args = args.clone(); - for (int i = 0; i < types.length; i++) { - Class c = types[i]; - if (c.isPrimitive()) { - args[i] = toPrimitive(c, args[i]); - } - } - } - Object res = invoke0(isStatic, this, obj, args); - if (getReturnType().isPrimitive()) { - res = fromPrimitive(getReturnType(), res); - } - return res; - } - - @JavaScriptBody(args = { "st", "method", "self", "args" }, body = - "var p;\n" - + "if (st) {\n" - + " p = new Array(1);\n" - + " p[0] = self;\n" - + " p = p.concat(args);\n" - + "} else {\n" - + " p = args;\n" - + "}\n" - + "return method.fld_data.apply(self, p);\n" - ) - private static native Object invoke0(boolean isStatic, Method m, Object self, Object[] args); - - static Object fromPrimitive(Class type, Object o) { - if (type == Integer.TYPE) { - return fromRaw(Integer.class, "valueOf__Ljava_lang_Integer_2I", o); - } - if (type == Long.TYPE) { - return fromRaw(Long.class, "valueOf__Ljava_lang_Long_2J", o); - } - if (type == Double.TYPE) { - return fromRaw(Double.class, "valueOf__Ljava_lang_Double_2D", o); - } - if (type == Float.TYPE) { - return fromRaw(Float.class, "valueOf__Ljava_lang_Float_2F", o); - } - if (type == Byte.TYPE) { - return fromRaw(Byte.class, "valueOf__Ljava_lang_Byte_2B", o); - } - if (type == Boolean.TYPE) { - return fromRaw(Boolean.class, "valueOf__Ljava_lang_Boolean_2Z", o); - } - if (type == Short.TYPE) { - return fromRaw(Short.class, "valueOf__Ljava_lang_Short_2S", o); - } - if (type == Character.TYPE) { - return fromRaw(Character.class, "valueOf__Ljava_lang_Character_2C", o); - } - if (type.getName().equals("void")) { - return null; - } - throw new IllegalStateException("Can't convert " + o); - } - - @JavaScriptBody(args = { "cls", "m", "o" }, - body = "return cls.cnstr(false)[m](o);" - ) - private static native Integer fromRaw(Class cls, String m, Object o); - - private static Object toPrimitive(Class type, Object o) { - if (type == Integer.TYPE) { - return toRaw("intValue__I", o); - } - if (type == Long.TYPE) { - return toRaw("longValue__J", o); - } - if (type == Double.TYPE) { - return toRaw("doubleValue__D", o); - } - if (type == Float.TYPE) { - return toRaw("floatValue__F", o); - } - if (type == Byte.TYPE) { - return toRaw("byteValue__B", o); - } - if (type == Boolean.TYPE) { - return toRaw("booleanValue__Z", o); - } - if (type == Short.TYPE) { - return toRaw("shortValue__S", o); - } - if (type == Character.TYPE) { - return toRaw("charValue__C", o); - } - if (type.getName().equals("void")) { - return o; - } - throw new IllegalStateException("Can't convert " + o); - } - - @JavaScriptBody(args = { "m", "o" }, - body = "return o[m](o);" - ) - private static native Object toRaw(String m, Object o); - - /** - * Returns {@code true} if this method is a bridge - * method; returns {@code false} otherwise. - * - * @return true if and only if this method is a bridge - * method as defined by the Java Language Specification. - * @since 1.5 - */ - public boolean isBridge() { - return (getModifiers() & Modifier.BRIDGE) != 0; - } - - /** - * Returns {@code true} if this method was declared to take - * a variable number of arguments; returns {@code false} - * otherwise. - * - * @return {@code true} if an only if this method was declared to - * take a variable number of arguments. - * @since 1.5 - */ - public boolean isVarArgs() { - return (getModifiers() & Modifier.VARARGS) != 0; - } - - /** - * Returns {@code true} if this method is a synthetic - * method; returns {@code false} otherwise. - * - * @return true if and only if this method is a synthetic - * method as defined by the Java Language Specification. - * @since 1.5 - */ - public boolean isSynthetic() { - return Modifier.isSynthetic(getModifiers()); - } - - @JavaScriptBody(args = { "ac" }, - body = - "if (this.fld_data.anno) {" - + " return this.fld_data.anno['L' + ac.jvmName + ';'];" - + "} else return null;" - ) - private Object getAnnotationData(Class annotationClass) { - throw new UnsupportedOperationException(); - } - - /** - * @throws NullPointerException {@inheritDoc} - * @since 1.5 - */ - public T getAnnotation(Class annotationClass) { - Object data = getAnnotationData(annotationClass); - return data == null ? null : AnnotationImpl.create(annotationClass, data); - } - - /** - * @since 1.5 - */ - public Annotation[] getDeclaredAnnotations() { - throw new UnsupportedOperationException(); - } - - /** - * Returns the default value for the annotation member represented by - * this {@code Method} instance. If the member is of a primitive type, - * an instance of the corresponding wrapper type is returned. Returns - * null if no default is associated with the member, or if the method - * instance does not represent a declared member of an annotation type. - * - * @return the default value for the annotation member represented - * by this {@code Method} instance. - * @throws TypeNotPresentException if the annotation is of type - * {@link Class} and no definition can be found for the - * default class value. - * @since 1.5 - */ - public Object getDefaultValue() { - throw new UnsupportedOperationException(); - } - - /** - * Returns an array of arrays that represent the annotations on the formal - * parameters, in declaration order, of the method represented by - * this {@code Method} object. (Returns an array of length zero if the - * underlying method is parameterless. If the method has one or more - * parameters, a nested array of length zero is returned for each parameter - * with no annotations.) The annotation objects contained in the returned - * arrays are serializable. The caller of this method is free to modify - * the returned arrays; it will have no effect on the arrays returned to - * other callers. - * - * @return an array of arrays that represent the annotations on the formal - * parameters, in declaration order, of the method represented by this - * Method object - * @since 1.5 - */ - public Annotation[][] getParameterAnnotations() { - throw new UnsupportedOperationException(); - } - - static { - MethodImpl.INSTANCE = new MethodImpl() { - protected Method create(Class declaringClass, String name, Object data, String sig) { - return new Method(declaringClass, name, data, sig); - } - }; - } -} diff -r 388e48c0a37a -r 05224402145d emul/src/main/java/java/lang/reflect/Modifier.java --- a/emul/src/main/java/java/lang/reflect/Modifier.java Wed Jan 23 20:16:48 2013 +0100 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,437 +0,0 @@ -/* - * Copyright (c) 1996, 2008, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code 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 - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package java.lang.reflect; - -/** - * The Modifier class provides {@code static} methods and - * constants to decode class and member access modifiers. The sets of - * modifiers are represented as integers with distinct bit positions - * representing different modifiers. The values for the constants - * representing the modifiers are taken from the tables in sections 4.1, 4.4, 4.5, and 4.7 of - * The Java™ Virtual Machine Specification. - * - * @see Class#getModifiers() - * @see Member#getModifiers() - * - * @author Nakul Saraiya - * @author Kenneth Russell - */ -public -class Modifier { - - /** - * Return {@code true} if the integer argument includes the - * {@code public} modifier, {@code false} otherwise. - * - * @param mod a set of modifiers - * @return {@code true} if {@code mod} includes the - * {@code public} modifier; {@code false} otherwise. - */ - public static boolean isPublic(int mod) { - return (mod & PUBLIC) != 0; - } - - /** - * Return {@code true} if the integer argument includes the - * {@code private} modifier, {@code false} otherwise. - * - * @param mod a set of modifiers - * @return {@code true} if {@code mod} includes the - * {@code private} modifier; {@code false} otherwise. - */ - public static boolean isPrivate(int mod) { - return (mod & PRIVATE) != 0; - } - - /** - * Return {@code true} if the integer argument includes the - * {@code protected} modifier, {@code false} otherwise. - * - * @param mod a set of modifiers - * @return {@code true} if {@code mod} includes the - * {@code protected} modifier; {@code false} otherwise. - */ - public static boolean isProtected(int mod) { - return (mod & PROTECTED) != 0; - } - - /** - * Return {@code true} if the integer argument includes the - * {@code static} modifier, {@code false} otherwise. - * - * @param mod a set of modifiers - * @return {@code true} if {@code mod} includes the - * {@code static} modifier; {@code false} otherwise. - */ - public static boolean isStatic(int mod) { - return (mod & STATIC) != 0; - } - - /** - * Return {@code true} if the integer argument includes the - * {@code final} modifier, {@code false} otherwise. - * - * @param mod a set of modifiers - * @return {@code true} if {@code mod} includes the - * {@code final} modifier; {@code false} otherwise. - */ - public static boolean isFinal(int mod) { - return (mod & FINAL) != 0; - } - - /** - * Return {@code true} if the integer argument includes the - * {@code synchronized} modifier, {@code false} otherwise. - * - * @param mod a set of modifiers - * @return {@code true} if {@code mod} includes the - * {@code synchronized} modifier; {@code false} otherwise. - */ - public static boolean isSynchronized(int mod) { - return (mod & SYNCHRONIZED) != 0; - } - - /** - * Return {@code true} if the integer argument includes the - * {@code volatile} modifier, {@code false} otherwise. - * - * @param mod a set of modifiers - * @return {@code true} if {@code mod} includes the - * {@code volatile} modifier; {@code false} otherwise. - */ - public static boolean isVolatile(int mod) { - return (mod & VOLATILE) != 0; - } - - /** - * Return {@code true} if the integer argument includes the - * {@code transient} modifier, {@code false} otherwise. - * - * @param mod a set of modifiers - * @return {@code true} if {@code mod} includes the - * {@code transient} modifier; {@code false} otherwise. - */ - public static boolean isTransient(int mod) { - return (mod & TRANSIENT) != 0; - } - - /** - * Return {@code true} if the integer argument includes the - * {@code native} modifier, {@code false} otherwise. - * - * @param mod a set of modifiers - * @return {@code true} if {@code mod} includes the - * {@code native} modifier; {@code false} otherwise. - */ - public static boolean isNative(int mod) { - return (mod & NATIVE) != 0; - } - - /** - * Return {@code true} if the integer argument includes the - * {@code interface} modifier, {@code false} otherwise. - * - * @param mod a set of modifiers - * @return {@code true} if {@code mod} includes the - * {@code interface} modifier; {@code false} otherwise. - */ - public static boolean isInterface(int mod) { - return (mod & INTERFACE) != 0; - } - - /** - * Return {@code true} if the integer argument includes the - * {@code abstract} modifier, {@code false} otherwise. - * - * @param mod a set of modifiers - * @return {@code true} if {@code mod} includes the - * {@code abstract} modifier; {@code false} otherwise. - */ - public static boolean isAbstract(int mod) { - return (mod & ABSTRACT) != 0; - } - - /** - * Return {@code true} if the integer argument includes the - * {@code strictfp} modifier, {@code false} otherwise. - * - * @param mod a set of modifiers - * @return {@code true} if {@code mod} includes the - * {@code strictfp} modifier; {@code false} otherwise. - */ - public static boolean isStrict(int mod) { - return (mod & STRICT) != 0; - } - - /** - * Return a string describing the access modifier flags in - * the specified modifier. For example: - *

-     *    public final synchronized strictfp
-     * 
- * The modifier names are returned in an order consistent with the - * suggested modifier orderings given in sections 8.1.1, 8.3.1, 8.4.3, 8.8.3, and 9.1.1 of - * The Java™ Language Specification. - * The full modifier ordering used by this method is: - *
{@code - * public protected private abstract static final transient - * volatile synchronized native strictfp - * interface }
- * The {@code interface} modifier discussed in this class is - * not a true modifier in the Java language and it appears after - * all other modifiers listed by this method. This method may - * return a string of modifiers that are not valid modifiers of a - * Java entity; in other words, no checking is done on the - * possible validity of the combination of modifiers represented - * by the input. - * - * Note that to perform such checking for a known kind of entity, - * such as a constructor or method, first AND the argument of - * {@code toString} with the appropriate mask from a method like - * {@link #constructorModifiers} or {@link #methodModifiers}. - * - * @param mod a set of modifiers - * @return a string representation of the set of modifiers - * represented by {@code mod} - */ - public static String toString(int mod) { - StringBuffer sb = new StringBuffer(); - int len; - - if ((mod & PUBLIC) != 0) sb.append("public "); - if ((mod & PROTECTED) != 0) sb.append("protected "); - if ((mod & PRIVATE) != 0) sb.append("private "); - - /* Canonical order */ - if ((mod & ABSTRACT) != 0) sb.append("abstract "); - if ((mod & STATIC) != 0) sb.append("static "); - if ((mod & FINAL) != 0) sb.append("final "); - if ((mod & TRANSIENT) != 0) sb.append("transient "); - if ((mod & VOLATILE) != 0) sb.append("volatile "); - if ((mod & SYNCHRONIZED) != 0) sb.append("synchronized "); - if ((mod & NATIVE) != 0) sb.append("native "); - if ((mod & STRICT) != 0) sb.append("strictfp "); - if ((mod & INTERFACE) != 0) sb.append("interface "); - - if ((len = sb.length()) > 0) /* trim trailing space */ - return sb.toString().substring(0, len-1); - return ""; - } - - /* - * Access modifier flag constants from tables 4.1, 4.4, 4.5, and 4.7 of - * The Java™ Virtual Machine Specification - */ - - /** - * The {@code int} value representing the {@code public} - * modifier. - */ - public static final int PUBLIC = 0x00000001; - - /** - * The {@code int} value representing the {@code private} - * modifier. - */ - public static final int PRIVATE = 0x00000002; - - /** - * The {@code int} value representing the {@code protected} - * modifier. - */ - public static final int PROTECTED = 0x00000004; - - /** - * The {@code int} value representing the {@code static} - * modifier. - */ - public static final int STATIC = 0x00000008; - - /** - * The {@code int} value representing the {@code final} - * modifier. - */ - public static final int FINAL = 0x00000010; - - /** - * The {@code int} value representing the {@code synchronized} - * modifier. - */ - public static final int SYNCHRONIZED = 0x00000020; - - /** - * The {@code int} value representing the {@code volatile} - * modifier. - */ - public static final int VOLATILE = 0x00000040; - - /** - * The {@code int} value representing the {@code transient} - * modifier. - */ - public static final int TRANSIENT = 0x00000080; - - /** - * The {@code int} value representing the {@code native} - * modifier. - */ - public static final int NATIVE = 0x00000100; - - /** - * The {@code int} value representing the {@code interface} - * modifier. - */ - public static final int INTERFACE = 0x00000200; - - /** - * The {@code int} value representing the {@code abstract} - * modifier. - */ - public static final int ABSTRACT = 0x00000400; - - /** - * The {@code int} value representing the {@code strictfp} - * modifier. - */ - public static final int STRICT = 0x00000800; - - // Bits not (yet) exposed in the public API either because they - // have different meanings for fields and methods and there is no - // way to distinguish between the two in this class, or because - // they are not Java programming language keywords - static final int BRIDGE = 0x00000040; - static final int VARARGS = 0x00000080; - static final int SYNTHETIC = 0x00001000; - static final int ANNOTATION= 0x00002000; - static final int ENUM = 0x00004000; - static boolean isSynthetic(int mod) { - return (mod & SYNTHETIC) != 0; - } - - /** - * See JLSv3 section 8.1.1. - */ - private static final int CLASS_MODIFIERS = - Modifier.PUBLIC | Modifier.PROTECTED | Modifier.PRIVATE | - Modifier.ABSTRACT | Modifier.STATIC | Modifier.FINAL | - Modifier.STRICT; - - /** - * See JLSv3 section 9.1.1. - */ - private static final int INTERFACE_MODIFIERS = - Modifier.PUBLIC | Modifier.PROTECTED | Modifier.PRIVATE | - Modifier.ABSTRACT | Modifier.STATIC | Modifier.STRICT; - - - /** - * See JLSv3 section 8.8.3. - */ - private static final int CONSTRUCTOR_MODIFIERS = - Modifier.PUBLIC | Modifier.PROTECTED | Modifier.PRIVATE; - - /** - * See JLSv3 section 8.4.3. - */ - private static final int METHOD_MODIFIERS = - Modifier.PUBLIC | Modifier.PROTECTED | Modifier.PRIVATE | - Modifier.ABSTRACT | Modifier.STATIC | Modifier.FINAL | - Modifier.SYNCHRONIZED | Modifier.NATIVE | Modifier.STRICT; - - /** - * See JLSv3 section 8.3.1. - */ - private static final int FIELD_MODIFIERS = - Modifier.PUBLIC | Modifier.PROTECTED | Modifier.PRIVATE | - Modifier.STATIC | Modifier.FINAL | Modifier.TRANSIENT | - Modifier.VOLATILE; - - /** - * Return an {@code int} value OR-ing together the source language - * modifiers that can be applied to a class. - * @return an {@code int} value OR-ing together the source language - * modifiers that can be applied to a class. - * - * @jls 8.1.1 Class Modifiers - * @since 1.7 - */ - public static int classModifiers() { - return CLASS_MODIFIERS; - } - - /** - * Return an {@code int} value OR-ing together the source language - * modifiers that can be applied to an interface. - * @return an {@code int} value OR-ing together the source language - * modifiers that can be applied to an inteface. - * - * @jls 9.1.1 Interface Modifiers - * @since 1.7 - */ - public static int interfaceModifiers() { - return INTERFACE_MODIFIERS; - } - - /** - * Return an {@code int} value OR-ing together the source language - * modifiers that can be applied to a constructor. - * @return an {@code int} value OR-ing together the source language - * modifiers that can be applied to a constructor. - * - * @jls 8.8.3 Constructor Modifiers - * @since 1.7 - */ - public static int constructorModifiers() { - return CONSTRUCTOR_MODIFIERS; - } - - /** - * Return an {@code int} value OR-ing together the source language - * modifiers that can be applied to a method. - * @return an {@code int} value OR-ing together the source language - * modifiers that can be applied to a method. - * - * @jls 8.4.3 Method Modifiers - * @since 1.7 - */ - public static int methodModifiers() { - return METHOD_MODIFIERS; - } - - - /** - * Return an {@code int} value OR-ing together the source language - * modifiers that can be applied to a field. - * @return an {@code int} value OR-ing together the source language - * modifiers that can be applied to a field. - * - * @jls 8.3.1 Field Modifiers - * @since 1.7 - */ - public static int fieldModifiers() { - return FIELD_MODIFIERS; - } -} diff -r 388e48c0a37a -r 05224402145d emul/src/main/java/java/lang/reflect/Type.java --- a/emul/src/main/java/java/lang/reflect/Type.java Wed Jan 23 20:16:48 2013 +0100 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,37 +0,0 @@ -/* - * Copyright (c) 2003, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code 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 - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package java.lang.reflect; - -/** - * Type is the common superinterface for all types in the Java - * programming language. These include raw types, parameterized types, - * array types, type variables and primitive types. - * - * @since 1.5 - */ - -public interface Type { -} diff -r 388e48c0a37a -r 05224402145d emul/src/main/java/java/lang/reflect/TypeVariable.java --- a/emul/src/main/java/java/lang/reflect/TypeVariable.java Wed Jan 23 20:16:48 2013 +0100 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,89 +0,0 @@ -/* - * Copyright (c) 2003, 2005, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code 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 - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package java.lang.reflect; - -/** - * TypeVariable is the common superinterface for type variables of kinds. - * A type variable is created the first time it is needed by a reflective - * method, as specified in this package. If a type variable t is referenced - * by a type (i.e, class, interface or annotation type) T, and T is declared - * by the nth enclosing class of T (see JLS 8.1.2), then the creation of t - * requires the resolution (see JVMS 5) of the ith enclosing class of T, - * for i = 0 to n, inclusive. Creating a type variable must not cause the - * creation of its bounds. Repeated creation of a type variable has no effect. - * - *

Multiple objects may be instantiated at run-time to - * represent a given type variable. Even though a type variable is - * created only once, this does not imply any requirement to cache - * instances representing the type variable. However, all instances - * representing a type variable must be equal() to each other. - * As a consequence, users of type variables must not rely on the identity - * of instances of classes implementing this interface. - * - * @param the type of generic declaration that declared the - * underlying type variable. - * - * @since 1.5 - */ -public interface TypeVariable extends Type { - /** - * Returns an array of {@code Type} objects representing the - * upper bound(s) of this type variable. Note that if no upper bound is - * explicitly declared, the upper bound is {@code Object}. - * - *

For each upper bound B:

  • if B is a parameterized - * type or a type variable, it is created, (see {@link - * java.lang.reflect.ParameterizedType ParameterizedType} for the - * details of the creation process for parameterized types). - *
  • Otherwise, B is resolved.
- * - * @throws TypeNotPresentException if any of the - * bounds refers to a non-existent type declaration - * @throws MalformedParameterizedTypeException if any of the - * bounds refer to a parameterized type that cannot be instantiated - * for any reason - * @return an array of {@code Type}s representing the upper - * bound(s) of this type variable - */ - Type[] getBounds(); - - /** - * Returns the {@code GenericDeclaration} object representing the - * generic declaration declared this type variable. - * - * @return the generic declaration declared for this type variable. - * - * @since 1.5 - */ - D getGenericDeclaration(); - - /** - * Returns the name of this type variable, as it occurs in the source code. - * - * @return the name of this type variable, as it appears in the source code - */ - String getName(); -} diff -r 388e48c0a37a -r 05224402145d emul/src/main/java/java/lang/reflect/package-info.java --- a/emul/src/main/java/java/lang/reflect/package-info.java Wed Jan 23 20:16:48 2013 +0100 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,49 +0,0 @@ -/* - * Copyright (c) 1998, 2006, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code 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 - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -/** - * Provides classes and interfaces for obtaining reflective - * information about classes and objects. Reflection allows - * programmatic access to information about the fields, methods and - * constructors of loaded classes, and the use of reflected fields, - * methods, and constructors to operate on their underlying - * counterparts, within security restrictions. - * - *

{@code AccessibleObject} allows suppression of access checks if - * the necessary {@code ReflectPermission} is available. - * - *

{@code Array} provides static methods to dynamically create and - * access arrays. - * - *

Classes in this package, along with {@code java.lang.Class} - * accommodate applications such as debuggers, interpreters, object - * inspectors, class browsers, and services such as Object - * Serialization and JavaBeans that need access to either the public - * members of a target object (based on its runtime class) or the - * members declared by a given class. - * - * @since JDK1.1 - */ -package java.lang.reflect; diff -r 388e48c0a37a -r 05224402145d emul/src/main/java/java/net/MalformedURLException.java --- a/emul/src/main/java/java/net/MalformedURLException.java Wed Jan 23 20:16:48 2013 +0100 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,56 +0,0 @@ -/* - * Copyright (c) 1995, 2008, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code 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 - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package java.net; - -import java.io.IOException; - -/** - * Thrown to indicate that a malformed URL has occurred. Either no - * legal protocol could be found in a specification string or the - * string could not be parsed. - * - * @author Arthur van Hoff - * @since JDK1.0 - */ -public class MalformedURLException extends IOException { - private static final long serialVersionUID = -182787522200415866L; - - /** - * Constructs a MalformedURLException with no detail message. - */ - public MalformedURLException() { - } - - /** - * Constructs a MalformedURLException with the - * specified detail message. - * - * @param msg the detail message. - */ - public MalformedURLException(String msg) { - super(msg); - } -} diff -r 388e48c0a37a -r 05224402145d emul/src/main/java/java/net/URL.java --- a/emul/src/main/java/java/net/URL.java Wed Jan 23 20:16:48 2013 +0100 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,1037 +0,0 @@ -/* - * Copyright (c) 1995, 2008, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code 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 - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package java.net; - -import java.io.IOException; -import java.io.InputStream; -import org.apidesign.bck2brwsr.core.JavaScriptBody; - -/** - * Class URL represents a Uniform Resource - * Locator, a pointer to a "resource" on the World - * Wide Web. A resource can be something as simple as a file or a - * directory, or it can be a reference to a more complicated object, - * such as a query to a database or to a search engine. More - * information on the types of URLs and their formats can be found at: - *

- * - * http://www.socs.uts.edu.au/MosaicDocs-old/url-primer.html - *
- *

- * In general, a URL can be broken into several parts. The previous - * example of a URL indicates that the protocol to use is - * http (HyperText Transfer Protocol) and that the - * information resides on a host machine named - * www.socs.uts.edu.au. The information on that host - * machine is named /MosaicDocs-old/url-primer.html. The exact - * meaning of this name on the host machine is both protocol - * dependent and host dependent. The information normally resides in - * a file, but it could be generated on the fly. This component of - * the URL is called the path component. - *

- * A URL can optionally specify a "port", which is the - * port number to which the TCP connection is made on the remote host - * machine. If the port is not specified, the default port for - * the protocol is used instead. For example, the default port for - * http is 80. An alternative port could be - * specified as: - *

- *     http://www.socs.uts.edu.au:80/MosaicDocs-old/url-primer.html
- * 
- *

- * The syntax of URL is defined by RFC 2396: Uniform - * Resource Identifiers (URI): Generic Syntax, amended by RFC 2732: Format for - * Literal IPv6 Addresses in URLs. The Literal IPv6 address format - * also supports scope_ids. The syntax and usage of scope_ids is described - * here. - *

- * A URL may have appended to it a "fragment", also known - * as a "ref" or a "reference". The fragment is indicated by the sharp - * sign character "#" followed by more characters. For example, - *

- *     http://java.sun.com/index.html#chapter1
- * 
- *

- * This fragment is not technically part of the URL. Rather, it - * indicates that after the specified resource is retrieved, the - * application is specifically interested in that part of the - * document that has the tag chapter1 attached to it. The - * meaning of a tag is resource specific. - *

- * An application can also specify a "relative URL", - * which contains only enough information to reach the resource - * relative to another URL. Relative URLs are frequently used within - * HTML pages. For example, if the contents of the URL: - *

- *     http://java.sun.com/index.html
- * 
- * contained within it the relative URL: - *
- *     FAQ.html
- * 
- * it would be a shorthand for: - *
- *     http://java.sun.com/FAQ.html
- * 
- *

- * The relative URL need not specify all the components of a URL. If - * the protocol, host name, or port number is missing, the value is - * inherited from the fully specified URL. The file component must be - * specified. The optional fragment is not inherited. - *

- * The URL class does not itself encode or decode any URL components - * according to the escaping mechanism defined in RFC2396. It is the - * responsibility of the caller to encode any fields, which need to be - * escaped prior to calling URL, and also to decode any escaped fields, - * that are returned from URL. Furthermore, because URL has no knowledge - * of URL escaping, it does not recognise equivalence between the encoded - * or decoded form of the same URL. For example, the two URLs:
- *

    http://foo.com/hello world/ and http://foo.com/hello%20world
- * would be considered not equal to each other. - *

- * Note, the {@link java.net.URI} class does perform escaping of its - * component fields in certain circumstances. The recommended way - * to manage the encoding and decoding of URLs is to use {@link java.net.URI}, - * and to convert between these two classes using {@link #toURI()} and - * {@link URI#toURL()}. - *

- * The {@link URLEncoder} and {@link URLDecoder} classes can also be - * used, but only for HTML form encoding, which is not the same - * as the encoding scheme defined in RFC2396. - * - * @author James Gosling - * @since JDK1.0 - */ -public final class URL implements java.io.Serializable { - - static final long serialVersionUID = -7627629688361524110L; - - /** - * The property which specifies the package prefix list to be scanned - * for protocol handlers. The value of this property (if any) should - * be a vertical bar delimited list of package names to search through - * for a protocol handler to load. The policy of this class is that - * all protocol handlers will be in a class called .Handler, - * and each package in the list is examined in turn for a matching - * handler. If none are found (or the property is not specified), the - * default package prefix, sun.net.www.protocol, is used. The search - * proceeds from the first package in the list to the last and stops - * when a match is found. - */ - private static final String protocolPathProp = "java.protocol.handler.pkgs"; - - /** - * The protocol to use (ftp, http, nntp, ... etc.) . - * @serial - */ - private String protocol; - - /** - * The host name to connect to. - * @serial - */ - private String host; - - /** - * The protocol port to connect to. - * @serial - */ - private int port = -1; - - /** - * The specified file name on that host. file is - * defined as path[?query] - * @serial - */ - private String file; - - /** - * The query part of this URL. - */ - private transient String query; - - /** - * The authority part of this URL. - * @serial - */ - private String authority; - - /** - * The path part of this URL. - */ - private transient String path; - - /** - * The userinfo part of this URL. - */ - private transient String userInfo; - - /** - * # reference. - * @serial - */ - private String ref; - - /** - * The host's IP address, used in equals and hashCode. - * Computed on demand. An uninitialized or unknown hostAddress is null. - */ - transient Object hostAddress; - - /** - * The URLStreamHandler for this URL. - */ - transient URLStreamHandler handler; - - /* Our hash code. - * @serial - */ - private int hashCode = -1; - - /** - * Creates a URL object from the specified - * protocol, host, port - * number, and file.

- * - * host can be expressed as a host name or a literal - * IP address. If IPv6 literal address is used, it should be - * enclosed in square brackets ('[' and ']'), as - * specified by RFC 2732; - * However, the literal IPv6 address format defined in RFC 2373: IP - * Version 6 Addressing Architecture is also accepted.

- * - * Specifying a port number of -1 - * indicates that the URL should use the default port for the - * protocol.

- * - * If this is the first URL object being created with the specified - * protocol, a stream protocol handler object, an instance of - * class URLStreamHandler, is created for that protocol: - *

    - *
  1. If the application has previously set up an instance of - * URLStreamHandlerFactory as the stream handler factory, - * then the createURLStreamHandler method of that instance - * is called with the protocol string as an argument to create the - * stream protocol handler. - *
  2. If no URLStreamHandlerFactory has yet been set up, - * or if the factory's createURLStreamHandler method - * returns null, then the constructor finds the - * value of the system property: - *
    -     *         java.protocol.handler.pkgs
    -     *     
    - * If the value of that system property is not null, - * it is interpreted as a list of packages separated by a vertical - * slash character '|'. The constructor tries to load - * the class named: - *
    -     *         <package>.<protocol>.Handler
    -     *     
    - * where <package> is replaced by the name of the package - * and <protocol> is replaced by the name of the protocol. - * If this class does not exist, or if the class exists but it is not - * a subclass of URLStreamHandler, then the next package - * in the list is tried. - *
  3. If the previous step fails to find a protocol handler, then the - * constructor tries to load from a system default package. - *
    -     *         <system default package>.<protocol>.Handler
    -     *     
    - * If this class does not exist, or if the class exists but it is not a - * subclass of URLStreamHandler, then a - * MalformedURLException is thrown. - *
- * - *

Protocol handlers for the following protocols are guaranteed - * to exist on the search path :- - *

-     *     http, https, ftp, file, and jar
-     * 
- * Protocol handlers for additional protocols may also be - * available. - * - *

No validation of the inputs is performed by this constructor. - * - * @param protocol the name of the protocol to use. - * @param host the name of the host. - * @param port the port number on the host. - * @param file the file on the host - * @exception MalformedURLException if an unknown protocol is specified. - * @see java.lang.System#getProperty(java.lang.String) - * @see java.net.URL#setURLStreamHandlerFactory( - * java.net.URLStreamHandlerFactory) - * @see java.net.URLStreamHandler - * @see java.net.URLStreamHandlerFactory#createURLStreamHandler( - * java.lang.String) - */ - public URL(String protocol, String host, int port, String file) - throws MalformedURLException - { - this(protocol, host, port, file, null); - } - - /** - * Creates a URL from the specified protocol - * name, host name, and file name. The - * default port for the specified protocol is used. - *

- * This method is equivalent to calling the four-argument - * constructor with the arguments being protocol, - * host, -1, and file. - * - * No validation of the inputs is performed by this constructor. - * - * @param protocol the name of the protocol to use. - * @param host the name of the host. - * @param file the file on the host. - * @exception MalformedURLException if an unknown protocol is specified. - * @see java.net.URL#URL(java.lang.String, java.lang.String, - * int, java.lang.String) - */ - public URL(String protocol, String host, String file) - throws MalformedURLException { - this(protocol, host, -1, file); - } - - /** - * Creates a URL object from the specified - * protocol, host, port - * number, file, and handler. Specifying - * a port number of -1 indicates that - * the URL should use the default port for the protocol. Specifying - * a handler of null indicates that the URL - * should use a default stream handler for the protocol, as outlined - * for: - * java.net.URL#URL(java.lang.String, java.lang.String, int, - * java.lang.String) - * - *

If the handler is not null and there is a security manager, - * the security manager's checkPermission - * method is called with a - * NetPermission("specifyStreamHandler") permission. - * This may result in a SecurityException. - * - * No validation of the inputs is performed by this constructor. - * - * @param protocol the name of the protocol to use. - * @param host the name of the host. - * @param port the port number on the host. - * @param file the file on the host - * @param handler the stream handler for the URL. - * @exception MalformedURLException if an unknown protocol is specified. - * @exception SecurityException - * if a security manager exists and its - * checkPermission method doesn't allow - * specifying a stream handler explicitly. - * @see java.lang.System#getProperty(java.lang.String) - * @see java.net.URL#setURLStreamHandlerFactory( - * java.net.URLStreamHandlerFactory) - * @see java.net.URLStreamHandler - * @see java.net.URLStreamHandlerFactory#createURLStreamHandler( - * java.lang.String) - * @see SecurityManager#checkPermission - * @see java.net.NetPermission - */ - public URL(String protocol, String host, int port, String file, - URLStreamHandler handler) throws MalformedURLException { - if (handler != null) { - throw new SecurityException(); - } - - protocol = protocol.toLowerCase(); - this.protocol = protocol; - if (host != null) { - - /** - * if host is a literal IPv6 address, - * we will make it conform to RFC 2732 - */ - if (host.indexOf(':') >= 0 && !host.startsWith("[")) { - host = "["+host+"]"; - } - this.host = host; - - if (port < -1) { - throw new MalformedURLException("Invalid port number :" + - port); - } - this.port = port; - authority = (port == -1) ? host : host + ":" + port; - } - - Parts parts = new Parts(file); - path = parts.getPath(); - query = parts.getQuery(); - - if (query != null) { - this.file = path + "?" + query; - } else { - this.file = path; - } - ref = parts.getRef(); - - // Note: we don't do validation of the URL here. Too risky to change - // right now, but worth considering for future reference. -br - if (handler == null && - (handler = getURLStreamHandler(protocol)) == null) { - throw new MalformedURLException("unknown protocol: " + protocol); - } - this.handler = handler; - } - - /** - * Creates a URL object from the String - * representation. - *

- * This constructor is equivalent to a call to the two-argument - * constructor with a null first argument. - * - * @param spec the String to parse as a URL. - * @exception MalformedURLException if no protocol is specified, or an - * unknown protocol is found, or spec is null. - * @see java.net.URL#URL(java.net.URL, java.lang.String) - */ - public URL(String spec) throws MalformedURLException { - this(null, spec); - } - - /** - * Creates a URL by parsing the given spec within a specified context. - * - * The new URL is created from the given context URL and the spec - * argument as described in - * RFC2396 "Uniform Resource Identifiers : Generic * Syntax" : - *

-     *          <scheme>://<authority><path>?<query>#<fragment>
-     * 
- * The reference is parsed into the scheme, authority, path, query and - * fragment parts. If the path component is empty and the scheme, - * authority, and query components are undefined, then the new URL is a - * reference to the current document. Otherwise, the fragment and query - * parts present in the spec are used in the new URL. - *

- * If the scheme component is defined in the given spec and does not match - * the scheme of the context, then the new URL is created as an absolute - * URL based on the spec alone. Otherwise the scheme component is inherited - * from the context URL. - *

- * If the authority component is present in the spec then the spec is - * treated as absolute and the spec authority and path will replace the - * context authority and path. If the authority component is absent in the - * spec then the authority of the new URL will be inherited from the - * context. - *

- * If the spec's path component begins with a slash character - * "/" then the - * path is treated as absolute and the spec path replaces the context path. - *

- * Otherwise, the path is treated as a relative path and is appended to the - * context path, as described in RFC2396. Also, in this case, - * the path is canonicalized through the removal of directory - * changes made by occurences of ".." and ".". - *

- * For a more detailed description of URL parsing, refer to RFC2396. - * - * @param context the context in which to parse the specification. - * @param spec the String to parse as a URL. - * @exception MalformedURLException if no protocol is specified, or an - * unknown protocol is found, or spec is null. - * @see java.net.URL#URL(java.lang.String, java.lang.String, - * int, java.lang.String) - * @see java.net.URLStreamHandler - * @see java.net.URLStreamHandler#parseURL(java.net.URL, - * java.lang.String, int, int) - */ - public URL(URL context, String spec) throws MalformedURLException { - this(context, spec, null); - } - - /** - * Creates a URL by parsing the given spec with the specified handler - * within a specified context. If the handler is null, the parsing - * occurs as with the two argument constructor. - * - * @param context the context in which to parse the specification. - * @param spec the String to parse as a URL. - * @param handler the stream handler for the URL. - * @exception MalformedURLException if no protocol is specified, or an - * unknown protocol is found, or spec is null. - * @exception SecurityException - * if a security manager exists and its - * checkPermission method doesn't allow - * specifying a stream handler. - * @see java.net.URL#URL(java.lang.String, java.lang.String, - * int, java.lang.String) - * @see java.net.URLStreamHandler - * @see java.net.URLStreamHandler#parseURL(java.net.URL, - * java.lang.String, int, int) - */ - public URL(URL context, String spec, URLStreamHandler handler) - throws MalformedURLException - { - String original = spec; - int i, limit, c; - int start = 0; - String newProtocol = null; - boolean aRef=false; - boolean isRelative = false; - - // Check for permission to specify a handler - if (handler != null) { - throw new SecurityException(); - } - - try { - limit = spec.length(); - while ((limit > 0) && (spec.charAt(limit - 1) <= ' ')) { - limit--; //eliminate trailing whitespace - } - while ((start < limit) && (spec.charAt(start) <= ' ')) { - start++; // eliminate leading whitespace - } - - if (spec.regionMatches(true, start, "url:", 0, 4)) { - start += 4; - } - if (start < spec.length() && spec.charAt(start) == '#') { - /* we're assuming this is a ref relative to the context URL. - * This means protocols cannot start w/ '#', but we must parse - * ref URL's like: "hello:there" w/ a ':' in them. - */ - aRef=true; - } - for (i = start ; !aRef && (i < limit) && - ((c = spec.charAt(i)) != '/') ; i++) { - if (c == ':') { - - String s = spec.substring(start, i).toLowerCase(); - if (isValidProtocol(s)) { - newProtocol = s; - start = i + 1; - } - break; - } - } - - // Only use our context if the protocols match. - protocol = newProtocol; - if ((context != null) && ((newProtocol == null) || - newProtocol.equalsIgnoreCase(context.protocol))) { - // inherit the protocol handler from the context - // if not specified to the constructor - if (handler == null) { - handler = context.handler; - } - - // If the context is a hierarchical URL scheme and the spec - // contains a matching scheme then maintain backwards - // compatibility and treat it as if the spec didn't contain - // the scheme; see 5.2.3 of RFC2396 - if (context.path != null && context.path.startsWith("/")) - newProtocol = null; - - if (newProtocol == null) { - protocol = context.protocol; - authority = context.authority; - userInfo = context.userInfo; - host = context.host; - port = context.port; - file = context.file; - path = context.path; - isRelative = true; - } - } - - if (protocol == null) { - throw new MalformedURLException("no protocol: "+original); - } - - // Get the protocol handler if not specified or the protocol - // of the context could not be used - if (handler == null && - (handler = getURLStreamHandler(protocol)) == null) { - throw new MalformedURLException("unknown protocol: "+protocol); - } - this.handler = handler; - - i = spec.indexOf('#', start); - if (i >= 0) { -//thrw(protocol + " hnd: " + handler.getClass().getName() + " i: " + i); - ref = spec.substring(i + 1, limit); - limit = i; - } - - /* - * Handle special case inheritance of query and fragment - * implied by RFC2396 section 5.2.2. - */ - if (isRelative && start == limit) { - query = context.query; - if (ref == null) { - ref = context.ref; - } - } - - handler.parseURL(this, spec, start, limit); - - } catch(MalformedURLException e) { - throw e; - } catch(Exception e) { - MalformedURLException exception = new MalformedURLException(e.getMessage()); - exception.initCause(e); - throw exception; - } - } - - /* - * Returns true if specified string is a valid protocol name. - */ - private boolean isValidProtocol(String protocol) { - int len = protocol.length(); - if (len < 1) - return false; - char c = protocol.charAt(0); - if (!Character.isLetter(c)) - return false; - for (int i = 1; i < len; i++) { - c = protocol.charAt(i); - if (!Character.isLetterOrDigit(c) && c != '.' && c != '+' && - c != '-') { - return false; - } - } - return true; - } - - /** - * Sets the fields of the URL. This is not a public method so that - * only URLStreamHandlers can modify URL fields. URLs are - * otherwise constant. - * - * @param protocol the name of the protocol to use - * @param host the name of the host - @param port the port number on the host - * @param file the file on the host - * @param ref the internal reference in the URL - */ - protected void set(String protocol, String host, - int port, String file, String ref) { - synchronized (this) { - this.protocol = protocol; - this.host = host; - authority = port == -1 ? host : host + ":" + port; - this.port = port; - this.file = file; - this.ref = ref; - /* This is very important. We must recompute this after the - * URL has been changed. */ - hashCode = -1; - hostAddress = null; - int q = file.lastIndexOf('?'); - if (q != -1) { - query = file.substring(q+1); - path = file.substring(0, q); - } else - path = file; - } - } - - /** - * Sets the specified 8 fields of the URL. This is not a public method so - * that only URLStreamHandlers can modify URL fields. URLs are otherwise - * constant. - * - * @param protocol the name of the protocol to use - * @param host the name of the host - * @param port the port number on the host - * @param authority the authority part for the url - * @param userInfo the username and password - * @param path the file on the host - * @param ref the internal reference in the URL - * @param query the query part of this URL - * @since 1.3 - */ - protected void set(String protocol, String host, int port, - String authority, String userInfo, String path, - String query, String ref) { - synchronized (this) { - this.protocol = protocol; - this.host = host; - this.port = port; - this.file = query == null ? path : path + "?" + query; - this.userInfo = userInfo; - this.path = path; - this.ref = ref; - /* This is very important. We must recompute this after the - * URL has been changed. */ - hashCode = -1; - hostAddress = null; - this.query = query; - this.authority = authority; - } - } - - /** - * Gets the query part of this URL. - * - * @return the query part of this URL, - * or null if one does not exist - * @since 1.3 - */ - public String getQuery() { - return query; - } - - /** - * Gets the path part of this URL. - * - * @return the path part of this URL, or an - * empty string if one does not exist - * @since 1.3 - */ - public String getPath() { - return path; - } - - /** - * Gets the userInfo part of this URL. - * - * @return the userInfo part of this URL, or - * null if one does not exist - * @since 1.3 - */ - public String getUserInfo() { - return userInfo; - } - - /** - * Gets the authority part of this URL. - * - * @return the authority part of this URL - * @since 1.3 - */ - public String getAuthority() { - return authority; - } - - /** - * Gets the port number of this URL. - * - * @return the port number, or -1 if the port is not set - */ - public int getPort() { - return port; - } - - /** - * Gets the default port number of the protocol associated - * with this URL. If the URL scheme or the URLStreamHandler - * for the URL do not define a default port number, - * then -1 is returned. - * - * @return the port number - * @since 1.4 - */ - public int getDefaultPort() { - return handler.getDefaultPort(); - } - - /** - * Gets the protocol name of this URL. - * - * @return the protocol of this URL. - */ - public String getProtocol() { - return protocol; - } - - /** - * Gets the host name of this URL, if applicable. - * The format of the host conforms to RFC 2732, i.e. for a - * literal IPv6 address, this method will return the IPv6 address - * enclosed in square brackets ('[' and ']'). - * - * @return the host name of this URL. - */ - public String getHost() { - return host; - } - - /** - * Gets the file name of this URL. - * The returned file portion will be - * the same as getPath(), plus the concatenation of - * the value of getQuery(), if any. If there is - * no query portion, this method and getPath() will - * return identical results. - * - * @return the file name of this URL, - * or an empty string if one does not exist - */ - public String getFile() { - return file; - } - - /** - * Gets the anchor (also known as the "reference") of this - * URL. - * - * @return the anchor (also known as the "reference") of this - * URL, or null if one does not exist - */ - public String getRef() { - return ref; - } - - /** - * Compares this URL for equality with another object.

- * - * If the given object is not a URL then this method immediately returns - * false.

- * - * Two URL objects are equal if they have the same protocol, reference - * equivalent hosts, have the same port number on the host, and the same - * file and fragment of the file.

- * - * Two hosts are considered equivalent if both host names can be resolved - * into the same IP addresses; else if either host name can't be - * resolved, the host names must be equal without regard to case; or both - * host names equal to null.

- * - * Since hosts comparison requires name resolution, this operation is a - * blocking operation.

- * - * Note: The defined behavior for equals is known to - * be inconsistent with virtual hosting in HTTP. - * - * @param obj the URL to compare against. - * @return true if the objects are the same; - * false otherwise. - */ - public boolean equals(Object obj) { - if (!(obj instanceof URL)) - return false; - URL u2 = (URL)obj; - - return handler.equals(this, u2); - } - - /** - * Creates an integer suitable for hash table indexing.

- * - * The hash code is based upon all the URL components relevant for URL - * comparison. As such, this operation is a blocking operation.

- * - * @return a hash code for this URL. - */ - public synchronized int hashCode() { - if (hashCode != -1) - return hashCode; - - hashCode = handler.hashCode(this); - return hashCode; - } - - /** - * Compares two URLs, excluding the fragment component.

- * - * Returns true if this URL and the - * other argument are equal without taking the - * fragment component into consideration. - * - * @param other the URL to compare against. - * @return true if they reference the same remote object; - * false otherwise. - */ - public boolean sameFile(URL other) { - return handler.sameFile(this, other); - } - - /** - * Constructs a string representation of this URL. The - * string is created by calling the toExternalForm - * method of the stream protocol handler for this object. - * - * @return a string representation of this object. - * @see java.net.URL#URL(java.lang.String, java.lang.String, int, - * java.lang.String) - * @see java.net.URLStreamHandler#toExternalForm(java.net.URL) - */ - public String toString() { - return toExternalForm(); - } - - /** - * Constructs a string representation of this URL. The - * string is created by calling the toExternalForm - * method of the stream protocol handler for this object. - * - * @return a string representation of this object. - * @see java.net.URL#URL(java.lang.String, java.lang.String, - * int, java.lang.String) - * @see java.net.URLStreamHandler#toExternalForm(java.net.URL) - */ - public String toExternalForm() { - return handler.toExternalForm(this); - } - - /** - * Returns a {@link java.net.URLConnection URLConnection} instance that - * represents a connection to the remote object referred to by the - * {@code URL}. - * - *

A new instance of {@linkplain java.net.URLConnection URLConnection} is - * created every time when invoking the - * {@linkplain java.net.URLStreamHandler#openConnection(URL) - * URLStreamHandler.openConnection(URL)} method of the protocol handler for - * this URL.

- * - *

It should be noted that a URLConnection instance does not establish - * the actual network connection on creation. This will happen only when - * calling {@linkplain java.net.URLConnection#connect() URLConnection.connect()}.

- * - *

If for the URL's protocol (such as HTTP or JAR), there - * exists a public, specialized URLConnection subclass belonging - * to one of the following packages or one of their subpackages: - * java.lang, java.io, java.util, java.net, the connection - * returned will be of that subclass. For example, for HTTP an - * HttpURLConnection will be returned, and for JAR a - * JarURLConnection will be returned.

- * - * @return a {@link java.net.URLConnection URLConnection} linking - * to the URL. - * @exception IOException if an I/O exception occurs. - * @see java.net.URL#URL(java.lang.String, java.lang.String, - * int, java.lang.String) - */ -// public URLConnection openConnection() throws java.io.IOException { -// return handler.openConnection(this); -// } - - - /** - * Opens a connection to this URL and returns an - * InputStream for reading from that connection. This - * method is a shorthand for: - *
-     *     openConnection().getInputStream()
-     * 
- * - * @return an input stream for reading from the URL connection. - * @exception IOException if an I/O exception occurs. - * @see java.net.URL#openConnection() - * @see java.net.URLConnection#getInputStream() - */ - public final InputStream openStream() throws java.io.IOException { - throw new IOException(); -// return openConnection().getInputStream(); - } - - /** - * Gets the contents of this URL. This method is a shorthand for: - *
-     *     openConnection().getContent()
-     * 
- * - * @return the contents of this URL. - * @exception IOException if an I/O exception occurs. - * @see java.net.URLConnection#getContent() - */ - public final Object getContent() throws java.io.IOException { - return loadText(toExternalForm()); - } - - @JavaScriptBody(args = "url", body = "" - + "var request = new XMLHttpRequest();\n" - + "request.open('GET', url, false);\n" - + "request.send();\n" - + "return request.responseText;\n" - ) - private static native String loadText(String url) throws IOException; - - /** - * Gets the contents of this URL. This method is a shorthand for: - *
-     *     openConnection().getContent(Class[])
-     * 
- * - * @param classes an array of Java types - * @return the content object of this URL that is the first match of - * the types specified in the classes array. - * null if none of the requested types are supported. - * @exception IOException if an I/O exception occurs. - * @see java.net.URLConnection#getContent(Class[]) - * @since 1.3 - */ - public final Object getContent(Class[] classes) - throws java.io.IOException { - for (Class c : classes) { - if (c == String.class) { - return getContent(); - } - } - return null; - } - - static URLStreamHandler getURLStreamHandler(String protocol) { - URLStreamHandler universal = new URLStreamHandler() {}; - return universal; - } - -} - -class Parts { - String path, query, ref; - - Parts(String file) { - int ind = file.indexOf('#'); - ref = ind < 0 ? null: file.substring(ind + 1); - file = ind < 0 ? file: file.substring(0, ind); - int q = file.lastIndexOf('?'); - if (q != -1) { - query = file.substring(q+1); - path = file.substring(0, q); - } else { - path = file; - } - } - - String getPath() { - return path; - } - - String getQuery() { - return query; - } - - String getRef() { - return ref; - } -} diff -r 388e48c0a37a -r 05224402145d emul/src/main/java/java/net/URLStreamHandler.java --- a/emul/src/main/java/java/net/URLStreamHandler.java Wed Jan 23 20:16:48 2013 +0100 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,568 +0,0 @@ -/* - * Copyright (c) 1995, 2006, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code 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 - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package java.net; - - -/** - * The abstract class URLStreamHandler is the common - * superclass for all stream protocol handlers. A stream protocol - * handler knows how to make a connection for a particular protocol - * type, such as http, ftp, or - * gopher. - *

- * In most cases, an instance of a URLStreamHandler - * subclass is not created directly by an application. Rather, the - * first time a protocol name is encountered when constructing a - * URL, the appropriate stream protocol handler is - * automatically loaded. - * - * @author James Gosling - * @see java.net.URL#URL(java.lang.String, java.lang.String, int, java.lang.String) - * @since JDK1.0 - */ -public abstract class URLStreamHandler { - /** - * Opens a connection to the object referenced by the - * URL argument. - * This method should be overridden by a subclass. - * - *

If for the handler's protocol (such as HTTP or JAR), there - * exists a public, specialized URLConnection subclass belonging - * to one of the following packages or one of their subpackages: - * java.lang, java.io, java.util, java.net, the connection - * returned will be of that subclass. For example, for HTTP an - * HttpURLConnection will be returned, and for JAR a - * JarURLConnection will be returned. - * - * @param u the URL that this connects to. - * @return a URLConnection object for the URL. - * @exception IOException if an I/O error occurs while opening the - * connection. - */ -// abstract protected URLConnection openConnection(URL u) throws IOException; - - /** - * Same as openConnection(URL), except that the connection will be - * made through the specified proxy; Protocol handlers that do not - * support proxying will ignore the proxy parameter and make a - * normal connection. - * - * Calling this method preempts the system's default ProxySelector - * settings. - * - * @param u the URL that this connects to. - * @param p the proxy through which the connection will be made. - * If direct connection is desired, Proxy.NO_PROXY - * should be specified. - * @return a URLConnection object for the URL. - * @exception IOException if an I/O error occurs while opening the - * connection. - * @exception IllegalArgumentException if either u or p is null, - * or p has the wrong type. - * @exception UnsupportedOperationException if the subclass that - * implements the protocol doesn't support this method. - * @since 1.5 - */ -// protected URLConnection openConnection(URL u, Proxy p) throws IOException { -// throw new UnsupportedOperationException("Method not implemented."); -// } - - /** - * Parses the string representation of a URL into a - * URL object. - *

- * If there is any inherited context, then it has already been - * copied into the URL argument. - *

- * The parseURL method of URLStreamHandler - * parses the string representation as if it were an - * http specification. Most URL protocol families have a - * similar parsing. A stream protocol handler for a protocol that has - * a different syntax must override this routine. - * - * @param u the URL to receive the result of parsing - * the spec. - * @param spec the String representing the URL that - * must be parsed. - * @param start the character index at which to begin parsing. This is - * just past the ':' (if there is one) that - * specifies the determination of the protocol name. - * @param limit the character position to stop parsing at. This is the - * end of the string or the position of the - * "#" character, if present. All information - * after the sharp sign indicates an anchor. - */ - protected void parseURL(URL u, String spec, int start, int limit) { - // These fields may receive context content if this was relative URL - String protocol = u.getProtocol(); - String authority = u.getAuthority(); - String userInfo = u.getUserInfo(); - String host = u.getHost(); - int port = u.getPort(); - String path = u.getPath(); - String query = u.getQuery(); - - // This field has already been parsed - String ref = u.getRef(); - - boolean isRelPath = false; - boolean queryOnly = false; - -// FIX: should not assume query if opaque - // Strip off the query part - if (start < limit) { - int queryStart = spec.indexOf('?'); - queryOnly = queryStart == start; - if ((queryStart != -1) && (queryStart < limit)) { - query = spec.substring(queryStart+1, limit); - if (limit > queryStart) - limit = queryStart; - spec = spec.substring(0, queryStart); - } - } - - int i = 0; - // Parse the authority part if any - boolean isUNCName = (start <= limit - 4) && - (spec.charAt(start) == '/') && - (spec.charAt(start + 1) == '/') && - (spec.charAt(start + 2) == '/') && - (spec.charAt(start + 3) == '/'); - if (!isUNCName && (start <= limit - 2) && (spec.charAt(start) == '/') && - (spec.charAt(start + 1) == '/')) { - start += 2; - i = spec.indexOf('/', start); - if (i < 0) { - i = spec.indexOf('?', start); - if (i < 0) - i = limit; - } - - host = authority = spec.substring(start, i); - - int ind = authority.indexOf('@'); - if (ind != -1) { - userInfo = authority.substring(0, ind); - host = authority.substring(ind+1); - } else { - userInfo = null; - } - if (host != null) { - // If the host is surrounded by [ and ] then its an IPv6 - // literal address as specified in RFC2732 - if (host.length()>0 && (host.charAt(0) == '[')) { - if ((ind = host.indexOf(']')) > 2) { - - String nhost = host ; - host = nhost.substring(0,ind+1); -// if (!IPAddressUtil. -// isIPv6LiteralAddress(host.substring(1, ind))) { -// throw new IllegalArgumentException( -// "Invalid host: "+ host); -// } - - port = -1 ; - if (nhost.length() > ind+1) { - if (nhost.charAt(ind+1) == ':') { - ++ind ; - // port can be null according to RFC2396 - if (nhost.length() > (ind + 1)) { - port = Integer.parseInt(nhost.substring(ind+1)); - } - } else { - throw new IllegalArgumentException( - "Invalid authority field: " + authority); - } - } - } else { - throw new IllegalArgumentException( - "Invalid authority field: " + authority); - } - } else { - ind = host.indexOf(':'); - port = -1; - if (ind >= 0) { - // port can be null according to RFC2396 - if (host.length() > (ind + 1)) { - port = Integer.parseInt(host.substring(ind + 1)); - } - host = host.substring(0, ind); - } - } - } else { - host = ""; - } - if (port < -1) - throw new IllegalArgumentException("Invalid port number :" + - port); - start = i; - // If the authority is defined then the path is defined by the - // spec only; See RFC 2396 Section 5.2.4. - if (authority != null && authority.length() > 0) - path = ""; - } - - if (host == null) { - host = ""; - } - - // Parse the file path if any - if (start < limit) { - if (spec.charAt(start) == '/') { - path = spec.substring(start, limit); - } else if (path != null && path.length() > 0) { - isRelPath = true; - int ind = path.lastIndexOf('/'); - String seperator = ""; - if (ind == -1 && authority != null) - seperator = "/"; - path = path.substring(0, ind + 1) + seperator + - spec.substring(start, limit); - - } else { - String seperator = (authority != null) ? "/" : ""; - path = seperator + spec.substring(start, limit); - } - } else if (queryOnly && path != null) { - int ind = path.lastIndexOf('/'); - if (ind < 0) - ind = 0; - path = path.substring(0, ind) + "/"; - } - if (path == null) - path = ""; - - if (isRelPath) { - // Remove embedded /./ - while ((i = path.indexOf("/./")) >= 0) { - path = path.substring(0, i) + path.substring(i + 2); - } - // Remove embedded /../ if possible - i = 0; - while ((i = path.indexOf("/../", i)) >= 0) { - /* - * A "/../" will cancel the previous segment and itself, - * unless that segment is a "/../" itself - * i.e. "/a/b/../c" becomes "/a/c" - * but "/../../a" should stay unchanged - */ - if (i > 0 && (limit = path.lastIndexOf('/', i - 1)) >= 0 && - (path.indexOf("/../", limit) != 0)) { - path = path.substring(0, limit) + path.substring(i + 3); - i = 0; - } else { - i = i + 3; - } - } - // Remove trailing .. if possible - while (path.endsWith("/..")) { - i = path.indexOf("/.."); - if ((limit = path.lastIndexOf('/', i - 1)) >= 0) { - path = path.substring(0, limit+1); - } else { - break; - } - } - // Remove starting . - if (path.startsWith("./") && path.length() > 2) - path = path.substring(2); - - // Remove trailing . - if (path.endsWith("/.")) - path = path.substring(0, path.length() -1); - } - - setURL(u, protocol, host, port, authority, userInfo, path, query, ref); - } - - /** - * Returns the default port for a URL parsed by this handler. This method - * is meant to be overidden by handlers with default port numbers. - * @return the default port for a URL parsed by this handler. - * @since 1.3 - */ - protected int getDefaultPort() { - return -1; - } - - /** - * Provides the default equals calculation. May be overidden by handlers - * for other protocols that have different requirements for equals(). - * This method requires that none of its arguments is null. This is - * guaranteed by the fact that it is only called by java.net.URL class. - * @param u1 a URL object - * @param u2 a URL object - * @return true if the two urls are - * considered equal, ie. they refer to the same - * fragment in the same file. - * @since 1.3 - */ - protected boolean equals(URL u1, URL u2) { - String ref1 = u1.getRef(); - String ref2 = u2.getRef(); - return (ref1 == ref2 || (ref1 != null && ref1.equals(ref2))) && - sameFile(u1, u2); - } - - /** - * Provides the default hash calculation. May be overidden by handlers for - * other protocols that have different requirements for hashCode - * calculation. - * @param u a URL object - * @return an int suitable for hash table indexing - * @since 1.3 - */ - protected int hashCode(URL u) { - int h = 0; - - // Generate the protocol part. - String protocol = u.getProtocol(); - if (protocol != null) - h += protocol.hashCode(); - - // Generate the host part. - Object addr = getHostAddress(u); - if (addr != null) { - h += addr.hashCode(); - } else { - String host = u.getHost(); - if (host != null) - h += host.toLowerCase().hashCode(); - } - - // Generate the file part. - String file = u.getFile(); - if (file != null) - h += file.hashCode(); - - // Generate the port part. - if (u.getPort() == -1) - h += getDefaultPort(); - else - h += u.getPort(); - - // Generate the ref part. - String ref = u.getRef(); - if (ref != null) - h += ref.hashCode(); - - return h; - } - - /** - * Compare two urls to see whether they refer to the same file, - * i.e., having the same protocol, host, port, and path. - * This method requires that none of its arguments is null. This is - * guaranteed by the fact that it is only called indirectly - * by java.net.URL class. - * @param u1 a URL object - * @param u2 a URL object - * @return true if u1 and u2 refer to the same file - * @since 1.3 - */ - protected boolean sameFile(URL u1, URL u2) { - // Compare the protocols. - if (!((u1.getProtocol() == u2.getProtocol()) || - (u1.getProtocol() != null && - u1.getProtocol().equalsIgnoreCase(u2.getProtocol())))) - return false; - - // Compare the files. - if (!(u1.getFile() == u2.getFile() || - (u1.getFile() != null && u1.getFile().equals(u2.getFile())))) - return false; - - // Compare the ports. - int port1, port2; - port1 = (u1.getPort() != -1) ? u1.getPort() : u1.handler.getDefaultPort(); - port2 = (u2.getPort() != -1) ? u2.getPort() : u2.handler.getDefaultPort(); - if (port1 != port2) - return false; - - // Compare the hosts. - if (!hostsEqual(u1, u2)) - return false; - - return true; - } - - /** - * Get the IP address of our host. An empty host field or a DNS failure - * will result in a null return. - * - * @param u a URL object - * @return an InetAddress representing the host - * IP address. - * @since 1.3 - */ - private synchronized Object getHostAddress(URL u) { - return u.hostAddress; - } - - /** - * Compares the host components of two URLs. - * @param u1 the URL of the first host to compare - * @param u2 the URL of the second host to compare - * @return true if and only if they - * are equal, false otherwise. - * @since 1.3 - */ - protected boolean hostsEqual(URL u1, URL u2) { - Object a1 = getHostAddress(u1); - Object a2 = getHostAddress(u2); - // if we have internet address for both, compare them - if (a1 != null && a2 != null) { - return a1.equals(a2); - // else, if both have host names, compare them - } else if (u1.getHost() != null && u2.getHost() != null) - return u1.getHost().equalsIgnoreCase(u2.getHost()); - else - return u1.getHost() == null && u2.getHost() == null; - } - - /** - * Converts a URL of a specific protocol to a - * String. - * - * @param u the URL. - * @return a string representation of the URL argument. - */ - protected String toExternalForm(URL u) { - - // pre-compute length of StringBuffer - int len = u.getProtocol().length() + 1; - if (u.getAuthority() != null && u.getAuthority().length() > 0) - len += 2 + u.getAuthority().length(); - if (u.getPath() != null) { - len += u.getPath().length(); - } - if (u.getQuery() != null) { - len += 1 + u.getQuery().length(); - } - if (u.getRef() != null) - len += 1 + u.getRef().length(); - - StringBuffer result = new StringBuffer(len); - result.append(u.getProtocol()); - result.append(":"); - if (u.getAuthority() != null && u.getAuthority().length() > 0) { - result.append("//"); - result.append(u.getAuthority()); - } - if (u.getPath() != null) { - result.append(u.getPath()); - } - if (u.getQuery() != null) { - result.append('?'); - result.append(u.getQuery()); - } - if (u.getRef() != null) { - result.append("#"); - result.append(u.getRef()); - } - return result.toString(); - } - - /** - * Sets the fields of the URL argument to the indicated values. - * Only classes derived from URLStreamHandler are supposed to be able - * to call the set method on a URL. - * - * @param u the URL to modify. - * @param protocol the protocol name. - * @param host the remote host value for the URL. - * @param port the port on the remote machine. - * @param authority the authority part for the URL. - * @param userInfo the userInfo part of the URL. - * @param path the path component of the URL. - * @param query the query part for the URL. - * @param ref the reference. - * @exception SecurityException if the protocol handler of the URL is - * different from this one - * @see java.net.URL#set(java.lang.String, java.lang.String, int, java.lang.String, java.lang.String) - * @since 1.3 - */ - protected void setURL(URL u, String protocol, String host, int port, - String authority, String userInfo, String path, - String query, String ref) { - if (this != u.handler) { - throw new SecurityException("handler for url different from " + - "this handler"); - } - // ensure that no one can reset the protocol on a given URL. - u.set(u.getProtocol(), host, port, authority, userInfo, path, query, ref); - } - - /** - * Sets the fields of the URL argument to the indicated values. - * Only classes derived from URLStreamHandler are supposed to be able - * to call the set method on a URL. - * - * @param u the URL to modify. - * @param protocol the protocol name. This value is ignored since 1.2. - * @param host the remote host value for the URL. - * @param port the port on the remote machine. - * @param file the file. - * @param ref the reference. - * @exception SecurityException if the protocol handler of the URL is - * different from this one - * @deprecated Use setURL(URL, String, String, int, String, String, String, - * String); - */ - @Deprecated - protected void setURL(URL u, String protocol, String host, int port, - String file, String ref) { - /* - * Only old URL handlers call this, so assume that the host - * field might contain "user:passwd@host". Fix as necessary. - */ - String authority = null; - String userInfo = null; - if (host != null && host.length() != 0) { - authority = (port == -1) ? host : host + ":" + port; - int at = host.lastIndexOf('@'); - if (at != -1) { - userInfo = host.substring(0, at); - host = host.substring(at+1); - } - } - - /* - * Assume file might contain query part. Fix as necessary. - */ - String path = null; - String query = null; - if (file != null) { - int q = file.lastIndexOf('?'); - if (q != -1) { - query = file.substring(q+1); - path = file.substring(0, q); - } else - path = file; - } - setURL(u, protocol, host, port, authority, userInfo, path, query, ref); - } -} diff -r 388e48c0a37a -r 05224402145d emul/src/main/java/java/util/Comparator.java --- a/emul/src/main/java/java/util/Comparator.java Wed Jan 23 20:16:48 2013 +0100 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,168 +0,0 @@ -/* - * Copyright (c) 1997, 2007, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code 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 - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package java.util; - -/** - * A comparison function, which imposes a total ordering on some - * collection of objects. Comparators can be passed to a sort method (such - * as {@link Collections#sort(List,Comparator) Collections.sort} or {@link - * Arrays#sort(Object[],Comparator) Arrays.sort}) to allow precise control - * over the sort order. Comparators can also be used to control the order of - * certain data structures (such as {@link SortedSet sorted sets} or {@link - * SortedMap sorted maps}), or to provide an ordering for collections of - * objects that don't have a {@link Comparable natural ordering}.

- * - * The ordering imposed by a comparator c on a set of elements - * S is said to be consistent with equals if and only if - * c.compare(e1, e2)==0 has the same boolean value as - * e1.equals(e2) for every e1 and e2 in - * S.

- * - * Caution should be exercised when using a comparator capable of imposing an - * ordering inconsistent with equals to order a sorted set (or sorted map). - * Suppose a sorted set (or sorted map) with an explicit comparator c - * is used with elements (or keys) drawn from a set S. If the - * ordering imposed by c on S is inconsistent with equals, - * the sorted set (or sorted map) will behave "strangely." In particular the - * sorted set (or sorted map) will violate the general contract for set (or - * map), which is defined in terms of equals.

- * - * For example, suppose one adds two elements {@code a} and {@code b} such that - * {@code (a.equals(b) && c.compare(a, b) != 0)} - * to an empty {@code TreeSet} with comparator {@code c}. - * The second {@code add} operation will return - * true (and the size of the tree set will increase) because {@code a} and - * {@code b} are not equivalent from the tree set's perspective, even though - * this is contrary to the specification of the - * {@link Set#add Set.add} method.

- * - * Note: It is generally a good idea for comparators to also implement - * java.io.Serializable, as they may be used as ordering methods in - * serializable data structures (like {@link TreeSet}, {@link TreeMap}). In - * order for the data structure to serialize successfully, the comparator (if - * provided) must implement Serializable.

- * - * For the mathematically inclined, the relation that defines the - * imposed ordering that a given comparator c imposes on a - * given set of objects S is:

- *       {(x, y) such that c.compare(x, y) <= 0}.
- * 
The quotient for this total order is:
- *       {(x, y) such that c.compare(x, y) == 0}.
- * 
- * - * It follows immediately from the contract for compare that the - * quotient is an equivalence relation on S, and that the - * imposed ordering is a total order on S. When we say that - * the ordering imposed by c on S is consistent with - * equals, we mean that the quotient for the ordering is the equivalence - * relation defined by the objects' {@link Object#equals(Object) - * equals(Object)} method(s):
- *     {(x, y) such that x.equals(y)}. 
- * - *

Unlike {@code Comparable}, a comparator may optionally permit - * comparison of null arguments, while maintaining the requirements for - * an equivalence relation. - * - *

This interface is a member of the - * - * Java Collections Framework. - * - * @param the type of objects that may be compared by this comparator - * - * @author Josh Bloch - * @author Neal Gafter - * @see Comparable - * @see java.io.Serializable - * @since 1.2 - */ - -public interface Comparator { - /** - * Compares its two arguments for order. Returns a negative integer, - * zero, or a positive integer as the first argument is less than, equal - * to, or greater than the second.

- * - * In the foregoing description, the notation - * sgn(expression) designates the mathematical - * signum function, which is defined to return one of -1, - * 0, or 1 according to whether the value of - * expression is negative, zero or positive.

- * - * The implementor must ensure that sgn(compare(x, y)) == - * -sgn(compare(y, x)) for all x and y. (This - * implies that compare(x, y) must throw an exception if and only - * if compare(y, x) throws an exception.)

- * - * The implementor must also ensure that the relation is transitive: - * ((compare(x, y)>0) && (compare(y, z)>0)) implies - * compare(x, z)>0.

- * - * Finally, the implementor must ensure that compare(x, y)==0 - * implies that sgn(compare(x, z))==sgn(compare(y, z)) for all - * z.

- * - * It is generally the case, but not strictly required that - * (compare(x, y)==0) == (x.equals(y)). Generally speaking, - * any comparator that violates this condition should clearly indicate - * this fact. The recommended language is "Note: this comparator - * imposes orderings that are inconsistent with equals." - * - * @param o1 the first object to be compared. - * @param o2 the second object to be compared. - * @return a negative integer, zero, or a positive integer as the - * first argument is less than, equal to, or greater than the - * second. - * @throws NullPointerException if an argument is null and this - * comparator does not permit null arguments - * @throws ClassCastException if the arguments' types prevent them from - * being compared by this comparator. - */ - int compare(T o1, T o2); - - /** - * Indicates whether some other object is "equal to" this - * comparator. This method must obey the general contract of - * {@link Object#equals(Object)}. Additionally, this method can return - * true only if the specified object is also a comparator - * and it imposes the same ordering as this comparator. Thus, - * comp1.equals(comp2) implies that sgn(comp1.compare(o1, - * o2))==sgn(comp2.compare(o1, o2)) for every object reference - * o1 and o2.

- * - * Note that it is always safe not to override - * Object.equals(Object). However, overriding this method may, - * in some cases, improve performance by allowing programs to determine - * that two distinct comparators impose the same order. - * - * @param obj the reference object with which to compare. - * @return true only if the specified object is also - * a comparator and it imposes the same ordering as this - * comparator. - * @see Object#equals(Object) - * @see Object#hashCode() - */ - boolean equals(Object obj); -} diff -r 388e48c0a37a -r 05224402145d emul/src/main/java/java/util/Enumeration.java --- a/emul/src/main/java/java/util/Enumeration.java Wed Jan 23 20:16:48 2013 +0100 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,79 +0,0 @@ -/* - * Copyright (c) 1994, 2005, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code 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 - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package java.util; - -/** - * An object that implements the Enumeration interface generates a - * series of elements, one at a time. Successive calls to the - * nextElement method return successive elements of the - * series. - *

- * For example, to print all elements of a Vector<E> v: - *

- *   for (Enumeration<E> e = v.elements(); e.hasMoreElements();)
- *       System.out.println(e.nextElement());
- *

- * Methods are provided to enumerate through the elements of a - * vector, the keys of a hashtable, and the values in a hashtable. - * Enumerations are also used to specify the input streams to a - * SequenceInputStream. - *

- * NOTE: The functionality of this interface is duplicated by the Iterator - * interface. In addition, Iterator adds an optional remove operation, and - * has shorter method names. New implementations should consider using - * Iterator in preference to Enumeration. - * - * @see java.util.Iterator - * @see java.io.SequenceInputStream - * @see java.util.Enumeration#nextElement() - * @see java.util.Hashtable - * @see java.util.Hashtable#elements() - * @see java.util.Hashtable#keys() - * @see java.util.Vector - * @see java.util.Vector#elements() - * - * @author Lee Boynton - * @since JDK1.0 - */ -public interface Enumeration { - /** - * Tests if this enumeration contains more elements. - * - * @return true if and only if this enumeration object - * contains at least one more element to provide; - * false otherwise. - */ - boolean hasMoreElements(); - - /** - * Returns the next element of this enumeration if this enumeration - * object has at least one more element to provide. - * - * @return the next element of this enumeration. - * @exception NoSuchElementException if no more elements exist. - */ - E nextElement(); -} diff -r 388e48c0a37a -r 05224402145d emul/src/main/java/java/util/NoSuchElementException.java --- a/emul/src/main/java/java/util/NoSuchElementException.java Wed Jan 23 20:16:48 2013 +0100 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,60 +0,0 @@ -/* - * Copyright (c) 1994, 2008, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code 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 - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package java.util; - -/** - * Thrown by the nextElement method of an - * Enumeration to indicate that there are no more - * elements in the enumeration. - * - * @author unascribed - * @see java.util.Enumeration - * @see java.util.Enumeration#nextElement() - * @since JDK1.0 - */ -public -class NoSuchElementException extends RuntimeException { - private static final long serialVersionUID = 6769829250639411880L; - - /** - * Constructs a NoSuchElementException with null - * as its error message string. - */ - public NoSuchElementException() { - super(); - } - - /** - * Constructs a NoSuchElementException, saving a reference - * to the error message string s for later retrieval by the - * getMessage method. - * - * @param s the detail message. - */ - public NoSuchElementException(String s) { - super(s); - } -} diff -r 388e48c0a37a -r 05224402145d emul/src/main/java/org/apidesign/bck2brwsr/emul/AnnotationImpl.java --- a/emul/src/main/java/org/apidesign/bck2brwsr/emul/AnnotationImpl.java Wed Jan 23 20:16:48 2013 +0100 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,81 +0,0 @@ -/** - * Back 2 Browser Bytecode Translator - * Copyright (C) 2012 Jaroslav Tulach - * - * This program 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, version 2 of the License. - * - * This program 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 this program. Look for COPYING file in the top folder. - * If not, see http://opensource.org/licenses/GPL-2.0. - */ -package org.apidesign.bck2brwsr.emul; - -import java.lang.annotation.Annotation; -import org.apidesign.bck2brwsr.core.JavaScriptBody; - -/** - * - * @author Jaroslav Tulach - */ -public final class AnnotationImpl implements Annotation { - public Class annotationType() { - return getClass(); - } - - @JavaScriptBody(args = { "a", "n", "values" }, body = "" - + "function f(v, p) {\n" - + " var val = v;\n" - + " var prop = p;\n" - + " return function() {\n" - + " return val[prop];\n" - + " };\n" - + "}\n" - + "var props = Object.getOwnPropertyNames(values);\n" - + "for (var i = 0; i < props.length; i++) {\n" - + " var p = props[i];\n" - + " a[p] = new f(values, p);\n" - + "}\n" - + "a['$instOf_' + n] = true;\n" - + "return a;" - ) - private static T create(AnnotationImpl a, String n, Object values) { - return null; - } - public static T create(Class annoClass, Object values) { - return create(new AnnotationImpl(), annoClass.getName().replace('.', '_'), values); - } - - public static Annotation[] create(Object anno) { - String[] names = findNames(anno); - Annotation[] ret = new Annotation[names.length]; - for (int i = 0; i < names.length; i++) { - String n = names[i].substring(1, names[i].length() - 1).replace('/', '_'); - ret[i] = create(new AnnotationImpl(), n, findData(anno, names[i])); - } - return ret; - } - @JavaScriptBody(args = "anno", body = - "var arr = new Array();" - + "var props = Object.getOwnPropertyNames(anno);\n" - + "for (var i = 0; i < props.length; i++) {\n" - + " var p = props[i];\n" - + " arr.push(p);" - + "}" - + "return arr;" - ) - private static String[] findNames(Object anno) { - throw new UnsupportedOperationException(); - } - - @JavaScriptBody(args={ "anno", "p"}, body="return anno[p];") - private static Object findData(Object anno, String p) { - throw new UnsupportedOperationException(); - } -} diff -r 388e48c0a37a -r 05224402145d emul/src/main/java/org/apidesign/bck2brwsr/emul/MethodImpl.java --- a/emul/src/main/java/org/apidesign/bck2brwsr/emul/MethodImpl.java Wed Jan 23 20:16:48 2013 +0100 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,164 +0,0 @@ -/* - * Copyright (c) 1996, 2006, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code 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 - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ -package org.apidesign.bck2brwsr.emul; - -import java.lang.reflect.Method; -import java.util.Enumeration; -import org.apidesign.bck2brwsr.core.JavaScriptBody; - -/** Utilities to work on methods. - * - * @author Jaroslav Tulach - */ -public abstract class MethodImpl { - public static MethodImpl INSTANCE; - static { - try { - Class.forName(Method.class.getName()); - } catch (ClassNotFoundException ex) { - throw new IllegalStateException(ex); - } - } - - protected abstract Method create(Class declaringClass, String name, Object data, String sig); - - - // - // bck2brwsr implementation - // - - @JavaScriptBody(args = {"clazz", "prefix"}, - body = "" - + "var c = clazz.cnstr.prototype;" - + "var arr = new Array();\n" - + "for (m in c) {\n" - + " if (m.indexOf(prefix) === 0) {\n" - + " arr.push(m);\n" - + " arr.push(c[m]);\n" - + " }" - + "}\n" - + "return arr;") - private static native Object[] findMethodData( - Class clazz, String prefix); - - public static Method findMethod( - Class clazz, String name, Class... parameterTypes) { - Object[] data = findMethodData(clazz, name + "__"); - BIG: for (int i = 0; i < data.length; i += 2) { - String sig = ((String) data[0]).substring(name.length() + 2); - Method tmp = INSTANCE.create(clazz, name, data[1], sig); - Class[] tmpParms = tmp.getParameterTypes(); - if (parameterTypes.length != tmpParms.length) { - continue; - } - for (int j = 0; j < tmpParms.length; j++) { - if (!parameterTypes[j].equals(tmpParms[j])) { - continue BIG; - } - } - return tmp; - } - return null; - } - - public static Method[] findMethods(Class clazz, int mask) { - Object[] namesAndData = findMethodData(clazz, ""); - int cnt = 0; - for (int i = 0; i < namesAndData.length; i += 2) { - String sig = (String) namesAndData[i]; - Object data = namesAndData[i + 1]; - int middle = sig.indexOf("__"); - if (middle == -1) { - continue; - } - String name = sig.substring(0, middle); - sig = sig.substring(middle + 2); - final Method m = INSTANCE.create(clazz, name, data, sig); - if ((m.getModifiers() & mask) == 0) { - continue; - } - namesAndData[cnt++] = m; - } - Method[] arr = new Method[cnt]; - for (int i = 0; i < cnt; i++) { - arr[i] = (Method) namesAndData[i]; - } - return arr; - } - - public static int signatureElements(String sig) { - Enumeration en = signatureParser(sig); - int cnt = 0; - while (en.hasMoreElements()) { - en.nextElement(); - cnt++; - } - return cnt; - } - - public static Enumeration signatureParser(final String sig) { - class E implements Enumeration { - int pos; - - public boolean hasMoreElements() { - return pos < sig.length(); - } - - public Class nextElement() { - switch (sig.charAt(pos++)) { - case 'I': - return Integer.TYPE; - case 'J': - return Long.TYPE; - case 'D': - return Double.TYPE; - case 'F': - return Float.TYPE; - case 'B': - return Byte.TYPE; - case 'Z': - return Boolean.TYPE; - case 'S': - return Short.TYPE; - case 'V': - return Void.TYPE; - case 'C': - return Character.TYPE; - case 'L': - try { - int up = sig.indexOf("_2"); - String type = sig.substring(1, up); - pos = up + 2; - return Class.forName(type); - } catch (ClassNotFoundException ex) { - // should not happen - } - } - throw new UnsupportedOperationException(sig + " at " + pos); - } - } - return new E(); - } -} diff -r 388e48c0a37a -r 05224402145d emul/src/main/resources/org/apidesign/vm4brwsr/emul/java_lang_Number.js --- a/emul/src/main/resources/org/apidesign/vm4brwsr/emul/java_lang_Number.js Wed Jan 23 20:16:48 2013 +0100 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,9 +0,0 @@ -// empty line needed here -Number.prototype.add32 = function(x) { return (this + x) | 0; }; -Number.prototype.sub32 = function(x) { return (this - x) | 0; }; -Number.prototype.mul32 = function(x) { - return (((this * (x >> 16)) << 16) + this * (x & 0xFFFF)) | 0; -}; - -Number.prototype.toInt8 = function() { return (this << 24) >> 24; }; -Number.prototype.toInt16 = function() { return (this << 16) >> 16; }; \ No newline at end of file diff -r 388e48c0a37a -r 05224402145d emul/src/main/resources/org/apidesign/vm4brwsr/emul/java_lang_String.js --- a/emul/src/main/resources/org/apidesign/vm4brwsr/emul/java_lang_String.js Wed Jan 23 20:16:48 2013 +0100 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,26 +0,0 @@ -// initialize methods on arrays and String constants -vm.java_lang_reflect_Array(false); -vm.java_lang_String(false); - -Array.prototype.at = function(indx, value) { - if (indx < 0 || indx > this.length) { - var e = vm.java_lang_ArrayIndexOutOfBoundsException(true); - e.constructor.cons__VLjava_lang_String_2.call(e, indx.toString()); - throw e; - } - if (arguments.length === 2) { - this[indx] = value; - } - return this[indx]; -}; -Array.prototype.getClass__Ljava_lang_Class_2 = function() { - return vm.java_lang_Class(false).defineArray__Ljava_lang_Class_2Ljava_lang_String_2(this.jvmName); -}; -Array.prototype.clone__Ljava_lang_Object_2 = function() { - var s = this.length; - var ret = new Array(s); - for (var i = 0; i < s; i++) { - ret[i] = this[i]; - } - return ret; -}; diff -r 388e48c0a37a -r 05224402145d javap/pom.xml --- a/javap/pom.xml Wed Jan 23 20:16:48 2013 +0100 +++ b/javap/pom.xml Wed Jan 23 20:39:23 2013 +0100 @@ -34,7 +34,7 @@ org.apidesign.bck2brwsr - emul + emul.mini 0.3-SNAPSHOT diff -r 388e48c0a37a -r 05224402145d javaquery/api/pom.xml --- a/javaquery/api/pom.xml Wed Jan 23 20:16:48 2013 +0100 +++ b/javaquery/api/pom.xml Wed Jan 23 20:39:23 2013 +0100 @@ -52,7 +52,7 @@ org.apidesign.bck2brwsr - emul + emul.mini 0.3-SNAPSHOT jar runtime diff -r 388e48c0a37a -r 05224402145d javaquery/demo-calculator-dynamic/pom.xml --- a/javaquery/demo-calculator-dynamic/pom.xml Wed Jan 23 20:16:48 2013 +0100 +++ b/javaquery/demo-calculator-dynamic/pom.xml Wed Jan 23 20:39:23 2013 +0100 @@ -46,7 +46,7 @@ org.apidesign.bck2brwsr - emul + emul.mini 0.3-SNAPSHOT diff -r 388e48c0a37a -r 05224402145d javaquery/demo-calculator/pom.xml --- a/javaquery/demo-calculator/pom.xml Wed Jan 23 20:16:48 2013 +0100 +++ b/javaquery/demo-calculator/pom.xml Wed Jan 23 20:39:23 2013 +0100 @@ -61,7 +61,7 @@ org.apidesign.bck2brwsr - emul + emul.mini 0.3-SNAPSHOT diff -r 388e48c0a37a -r 05224402145d mojo/pom.xml --- a/mojo/pom.xml Wed Jan 23 20:16:48 2013 +0100 +++ b/mojo/pom.xml Wed Jan 23 20:39:23 2013 +0100 @@ -66,7 +66,7 @@ 0.3-SNAPSHOT - emul + emul.mini org.apidesign.bck2brwsr diff -r 388e48c0a37a -r 05224402145d mojo/src/main/resources/archetype-resources/pom.xml --- a/mojo/src/main/resources/archetype-resources/pom.xml Wed Jan 23 20:16:48 2013 +0100 +++ b/mojo/src/main/resources/archetype-resources/pom.xml Wed Jan 23 20:39:23 2013 +0100 @@ -45,7 +45,7 @@ org.apidesign.bck2brwsr - emul + emul.mini 0.3-SNAPSHOT diff -r 388e48c0a37a -r 05224402145d pom.xml --- a/pom.xml Wed Jan 23 20:16:48 2013 +0100 +++ b/pom.xml Wed Jan 23 20:39:23 2013 +0100 @@ -115,4 +115,4 @@ COPYING - + \ No newline at end of file diff -r 388e48c0a37a -r 05224402145d vm/pom.xml --- a/vm/pom.xml Wed Jan 23 20:16:48 2013 +0100 +++ b/vm/pom.xml Wed Jan 23 20:39:23 2013 +0100 @@ -90,7 +90,7 @@ ${project.groupId} - emul + emul.mini 0.3-SNAPSHOT test diff -r 388e48c0a37a -r 05224402145d vmtest/pom.xml --- a/vmtest/pom.xml Wed Jan 23 20:16:48 2013 +0100 +++ b/vmtest/pom.xml Wed Jan 23 20:39:23 2013 +0100 @@ -49,7 +49,7 @@ ${project.groupId} - emul + emul.mini ${project.version} test