harmony-commits mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From hinde...@apache.org
Subject svn commit: r884518 [4/8] - in /harmony/enhanced/classlib/branches/java6: ./ depends/build/ depends/jars/ make/ modules/accessibility/make/ modules/accessibility/src/main/java/javax/accessibility/ modules/applet/src/main/java/org/apache/harmony/applet/...
Date Thu, 26 Nov 2009 11:12:56 GMT
Modified: harmony/enhanced/classlib/branches/java6/modules/luni/src/main/java/java/io/BufferedReader.java
URL: http://svn.apache.org/viewvc/harmony/enhanced/classlib/branches/java6/modules/luni/src/main/java/java/io/BufferedReader.java?rev=884518&r1=884517&r2=884518&view=diff
==============================================================================
--- harmony/enhanced/classlib/branches/java6/modules/luni/src/main/java/java/io/BufferedReader.java (original)
+++ harmony/enhanced/classlib/branches/java6/modules/luni/src/main/java/java/io/BufferedReader.java Thu Nov 26 11:12:49 2009
@@ -40,15 +40,35 @@
 
     private Reader in;
 
+    /**
+     * The characters that can be read and refilled in bulk. We maintain three
+     * indices into this buffer:<pre>
+     *     { X X X X X X X X X X X X - - }
+     *           ^     ^             ^
+     *           |     |             |
+     *         mark   pos           end</pre>
+     * Pos points to the next readable character. End is one greater than the
+     * last readable character. When {@code pos == end}, the buffer is empty and
+     * must be {@link #fillBuf() filled} before characters can be read.
+     *
+     * <p>Mark is the value pos will be set to on calls to {@link #reset}. Its
+     * value is in the range {@code [0...pos]}. If the mark is {@code -1}, the
+     * buffer cannot be reset.
+     *
+     * <p>MarkLimit limits the distance between the mark and the pos. When this
+     * limit is exceeded, {@link #reset} is permitted (but not required) to
+     * throw an exception. For shorter distances, {@link #reset} shall not throw
+     * (unless the reader is closed).
+     */
     private char[] buf;
 
-    private int marklimit = -1;
+    private int pos;
 
-    private int count;
+    private int end;
 
-    private int markpos = -1;
+    private int mark = -1;
 
-    private int pos;
+    private int markLimit = -1;
 
     /**
      * Constructs a new BufferedReader on the Reader {@code in}. The
@@ -101,36 +121,50 @@
         }
     }
 
-    private int fillbuf() throws IOException {
-        if (markpos == -1 || (pos - markpos >= marklimit)) {
-            /* Mark position not set or exceeded readlimit */
+    /**
+     * Populates the buffer with data. It is an error to call this method when
+     * the buffer still contains data; ie. if {@code pos < end}.
+     *
+     * @return the number of bytes read into the buffer, or -1 if the end of the
+     *      source stream has been reached.
+     */
+    private int fillBuf() throws IOException {
+        // assert(pos == end);
+
+        if (mark == -1 || (pos - mark >= markLimit)) {
+            /* mark isn't set or has exceeded its limit. use the whole buffer */
             int result = in.read(buf, 0, buf.length);
             if (result > 0) {
-                markpos = -1;
+                mark = -1;
                 pos = 0;
-                count = result == -1 ? 0 : result;
+                end = result;
             }
             return result;
         }
-        if (markpos == 0 && marklimit > buf.length) {
-            /* Increase buffer size to accommodate the readlimit */
+
+        if (mark == 0 && markLimit > buf.length) {
+            /* the only way to make room when mark=0 is by growing the buffer */
             int newLength = buf.length * 2;
-            if (newLength > marklimit) {
-                newLength = marklimit;
+            if (newLength > markLimit) {
+                newLength = markLimit;
             }
             char[] newbuf = new char[newLength];
             System.arraycopy(buf, 0, newbuf, 0, buf.length);
             buf = newbuf;
-        } else if (markpos > 0) {
-            System.arraycopy(buf, markpos, buf, 0, buf.length - markpos);
+        } else if (mark > 0) {
+            /* make room by shifting the buffered data to left mark positions */
+            System.arraycopy(buf, mark, buf, 0, buf.length - mark);
+            pos -= mark;
+            end -= mark;
+            mark = 0;
         }
 
         /* Set the new position and mark position */
-        pos -= markpos;
-        count = markpos = 0;
-        int charsread = in.read(buf, pos, buf.length - pos);
-        count = charsread == -1 ? pos : pos + charsread;
-        return charsread;
+        int count = in.read(buf, pos, buf.length - pos);
+        if (count != -1) {
+            end += count;
+        }
+        return count;
     }
 
     /**
@@ -144,32 +178,32 @@
     }
 
     /**
-     * Sets a mark position in this reader. The parameter {@code readlimit}
+     * Sets a mark position in this reader. The parameter {@code markLimit}
      * indicates how many characters can be read before the mark is invalidated.
      * Calling {@code reset()} will reposition the reader back to the marked
-     * position if {@code readlimit} has not been surpassed.
+     * position if {@code markLimit} has not been surpassed.
      * 
-     * @param readlimit
+     * @param markLimit
      *            the number of characters that can be read before the mark is
      *            invalidated.
      * @throws IllegalArgumentException
-     *             if {@code readlimit < 0}.
+     *             if {@code markLimit < 0}.
      * @throws IOException
      *             if an error occurs while setting a mark in this reader.
      * @see #markSupported()
      * @see #reset()
      */
     @Override
-    public void mark(int readlimit) throws IOException {
-        if (readlimit < 0) {
+    public void mark(int markLimit) throws IOException {
+        if (markLimit < 0) {
             throw new IllegalArgumentException();
         }
         synchronized (lock) {
             if (isClosed()) {
                 throw new IOException(Msg.getString("K005b")); //$NON-NLS-1$
             }
-            marklimit = readlimit;
-            markpos = pos;
+            this.markLimit = markLimit;
+            mark = pos;
         }
     }
 
@@ -205,10 +239,9 @@
                 throw new IOException(Msg.getString("K005b")); //$NON-NLS-1$
             }
             /* Are there buffered characters available? */
-            if (pos < count || fillbuf() != -1) {
+            if (pos < end || fillBuf() != -1) {
                 return buf[pos++];
             }
-            markpos = -1;
             return -1;
         }
     }
@@ -248,52 +281,69 @@
             if (offset < 0 || offset > buffer.length - length || length < 0) {
                 throw new IndexOutOfBoundsException();
             }
-            if (length == 0) {
-                return 0;
-            }
-            int required;
-            if (pos < count) {
-                /* There are bytes available in the buffer. */
-                int copylength = count - pos >= length ? length : count - pos;
-                System.arraycopy(buf, pos, buffer, offset, copylength);
-                pos += copylength;
-                if (copylength == length || !in.ready()) {
-                    return copylength;
-                }
-                offset += copylength;
-                required = length - copylength;
-            } else {
-                required = length;
-            }
+            int outstanding = length;
+            while (outstanding > 0) {
 
-            while (true) {
-                int read;
                 /*
-                 * If we're not marked and the required size is greater than the
-                 * buffer, simply read the bytes directly bypassing the buffer.
+                 * If there are bytes in the buffer, grab those first.
                  */
-                if (markpos == -1 && required >= buf.length) {
-                    read = in.read(buffer, offset, required);
-                    if (read == -1) {
-                        return required == length ? -1 : length - required;
-                    }
-                } else {
-                    if (fillbuf() == -1) {
-                        return required == length ? -1 : length - required;
+                int available = end - pos;
+                if (available > 0) {
+                    int count = available >= outstanding ? outstanding : available;
+                    System.arraycopy(buf, pos, buffer, offset, count);
+                    pos += count;
+                    offset += count;
+                    outstanding -= count;
+                }
+
+                /*
+                 * Before attempting to read from the underlying stream, make
+                 * sure we really, really want to. We won't bother if we're
+                 * done, or if we've already got some bytes and reading from the
+                 * underlying stream would block.
+                 */
+                if (outstanding == 0 || (outstanding < length && !in.ready())) {
+                    break;
+                }
+
+                // assert(pos == end);
+
+                /*
+                 * If we're unmarked and the requested size is greater than our
+                 * buffer, read the bytes directly into the caller's buffer. We
+                 * don't read into smaller buffers because that could result in
+                 * a many reads.
+                 */
+                if ((mark == -1 || (pos - mark >= markLimit))
+                        && outstanding >= buf.length) {
+                    int count = in.read(buffer, offset, outstanding);
+                    if (count > 0) {
+                        offset += count;
+                        outstanding -= count;
+                        mark = -1;
                     }
-                    read = count - pos >= required ? required : count - pos;
-                    System.arraycopy(buf, pos, buffer, offset, read);
-                    pos += read;
-                }
-                required -= read;
-                if (required == 0) {
-                    return length;
+
+                    break; // assume the source stream gave us all that it could
                 }
-                if (!in.ready()) {
-                    return length - required;
+
+                if (fillBuf() == -1) {
+                    break; // source is exhausted
                 }
-                offset += read;
             }
+
+            int count = length - outstanding;
+            return (count > 0 || count == length) ? count : -1;
+        }
+    }
+
+    /**
+     * Peeks at the next input character, refilling the buffer if necessary. If
+     * this character is a newline character ("\n"), it is discarded.
+     */
+    final void chompNewline() throws IOException {
+        if ((pos != end || fillBuf() != -1)
+                && buf[pos] == '\n') {
+            pos++;
         }
     }
 
@@ -313,11 +363,11 @@
             if (isClosed()) {
                 throw new IOException(Msg.getString("K005b")); //$NON-NLS-1$
             }
-            /* Are there buffered characters available? */
-            if ((pos >= count) && (fillbuf() == -1)) {
+            /* has the underlying stream been exhausted? */
+            if (pos == end && fillBuf() == -1) {
                 return null;
             }
-            for (int charPos = pos; charPos < count; charPos++) {
+            for (int charPos = pos; charPos < end; charPos++) {
                 char ch = buf[charPos];
                 if (ch > '\r') {
                     continue;
@@ -329,7 +379,7 @@
                 } else if (ch == '\r') {
                     String res = new String(buf, pos, charPos - pos);
                     pos = charPos + 1;
-                    if (((pos < count) || (fillbuf() != -1))
+                    if (((pos < end) || (fillBuf() != -1))
                             && (buf[pos] == '\n')) {
                         pos++;
                     }
@@ -341,27 +391,28 @@
             StringBuilder result = new StringBuilder(80);
             /* Typical Line Length */
 
-            result.append(buf, pos, count - pos);
-            pos = count;
+            result.append(buf, pos, end - pos);
             while (true) {
+                pos = end;
+
                 /* Are there buffered characters available? */
-                if (pos >= count) {
-                    if (eol == '\n') {
-                        return result.toString();
-                    }
-                    // attempt to fill buffer
-                    if (fillbuf() == -1) {
-                        // characters or null.
-                        return result.length() > 0 || eol != '\0' ? result
-                                .toString() : null;
-                    }
+                if (eol == '\n') {
+                    return result.toString();
+                }
+                // attempt to fill buffer
+                if (fillBuf() == -1) {
+                    // characters or null.
+                    return result.length() > 0 || eol != '\0'
+                            ? result.toString()
+                            : null;
                 }
-                for (int charPos = pos; charPos < count; charPos++) {
+                for (int charPos = pos; charPos < end; charPos++) {
+                    char c = buf[charPos];
                     if (eol == '\0') {
-                        if ((buf[charPos] == '\n' || buf[charPos] == '\r')) {
-                            eol = buf[charPos];
+                        if ((c == '\n' || c == '\r')) {
+                            eol = c;
                         }
-                    } else if (eol == '\r' && (buf[charPos] == '\n')) {
+                    } else if (eol == '\r' && c == '\n') {
                         if (charPos > pos) {
                             result.append(buf, pos, charPos - pos - 1);
                         }
@@ -376,11 +427,10 @@
                     }
                 }
                 if (eol == '\0') {
-                    result.append(buf, pos, count - pos);
+                    result.append(buf, pos, end - pos);
                 } else {
-                    result.append(buf, pos, count - pos - 1);
+                    result.append(buf, pos, end - pos - 1);
                 }
-                pos = count;
             }
         }
 
@@ -388,7 +438,7 @@
 
     /**
      * Indicates whether this reader is ready to be read without blocking.
-     * 
+     *
      * @return {@code true} if this reader will not block when {@code read} is
      *         called, {@code false} if unknown or blocking will occur.
      * @throws IOException
@@ -403,7 +453,7 @@
             if (isClosed()) {
                 throw new IOException(Msg.getString("K005b")); //$NON-NLS-1$
             }
-            return ((count - pos) > 0) || in.ready();
+            return ((end - pos) > 0) || in.ready();
         }
     }
 
@@ -423,17 +473,17 @@
             if (isClosed()) {
                 throw new IOException(Msg.getString("K005b")); //$NON-NLS-1$
             }
-            if (markpos == -1) {
+            if (mark == -1) {
                 throw new IOException(Msg.getString("K005c")); //$NON-NLS-1$
             }
-            pos = markpos;
+            pos = mark;
         }
     }
 
     /**
      * Skips {@code amount} characters in this reader. Subsequent
      * {@code read()}s will not return these characters unless {@code reset()}
-     * is used. Skipping characters may invalidate a mark if {@code readlimit}
+     * is used. Skipping characters may invalidate a mark if {@code markLimit}
      * is surpassed.
      * 
      * @param amount
@@ -459,24 +509,24 @@
             if (amount < 1) {
                 return 0;
             }
-            if (count - pos >= amount) {
+            if (end - pos >= amount) {
                 pos += amount;
                 return amount;
             }
 
-            long read = count - pos;
-            pos = count;
+            long read = end - pos;
+            pos = end;
             while (read < amount) {
-                if (fillbuf() == -1) {
+                if (fillBuf() == -1) {
                     return read;
                 }
-                if (count - pos >= amount - read) {
+                if (end - pos >= amount - read) {
                     pos += amount - read;
                     return amount;
                 }
                 // Couldn't get all the characters, skip what we read
-                read += (count - pos);
-                pos = count;
+                read += (end - pos);
+                pos = end;
             }
             return amount;
         }

Modified: harmony/enhanced/classlib/branches/java6/modules/luni/src/main/java/java/io/BufferedWriter.java
URL: http://svn.apache.org/viewvc/harmony/enhanced/classlib/branches/java6/modules/luni/src/main/java/java/io/BufferedWriter.java?rev=884518&r1=884517&r2=884518&view=diff
==============================================================================
--- harmony/enhanced/classlib/branches/java6/modules/luni/src/main/java/java/io/BufferedWriter.java (original)
+++ harmony/enhanced/classlib/branches/java6/modules/luni/src/main/java/java/io/BufferedWriter.java Thu Nov 26 11:12:49 2009
@@ -21,6 +21,7 @@
 
 import org.apache.harmony.luni.util.Msg;
 import org.apache.harmony.luni.util.PriviAction;
+import org.apache.harmony.luni.util.SneakyThrow;
 
 /**
  * Wraps an existing {@link Writer} and <em>buffers</em> the output. Expensive
@@ -95,11 +96,29 @@
     @Override
     public void close() throws IOException {
         synchronized (lock) {
-            if (!isClosed()) {
+            if (isClosed()) {
+                return;
+            }
+
+            Throwable thrown = null;
+            try {
                 flushInternal();
+            } catch (Throwable e) {
+                thrown = e;
+            }
+            buf = null;
+
+            try {
                 out.close();
-                buf = null;
-                out = null;
+            } catch (Throwable e) {
+                if (thrown == null) {
+                    thrown = e;
+                }
+            }
+            out = null;
+
+            if (thrown != null) {
+                SneakyThrow.sneakyThrow(thrown);
             }
         }
     }

Modified: harmony/enhanced/classlib/branches/java6/modules/luni/src/main/java/java/io/CharArrayReader.java
URL: http://svn.apache.org/viewvc/harmony/enhanced/classlib/branches/java6/modules/luni/src/main/java/java/io/CharArrayReader.java?rev=884518&r1=884517&r2=884518&view=diff
==============================================================================
--- harmony/enhanced/classlib/branches/java6/modules/luni/src/main/java/java/io/CharArrayReader.java (original)
+++ harmony/enhanced/classlib/branches/java6/modules/luni/src/main/java/java/io/CharArrayReader.java Thu Nov 26 11:12:49 2009
@@ -54,7 +54,6 @@
      *            the char array from which to read.
      */
     public CharArrayReader(char[] buf) {
-        super(buf);
         this.buf = buf;
         this.count = buf.length;
     }
@@ -75,8 +74,13 @@
      *             {@code offset} is greater than the size of {@code buf} .
      */
     public CharArrayReader(char[] buf, int offset, int length) {
-        super(buf);
-        if (offset < 0 || offset > buf.length || length < 0) {
+        /*
+         * The spec of this constructor is broken. In defining the legal values
+         * of offset and length, it doesn't consider buffer's length. And to be
+         * compatible with the broken spec, we must also test whether
+         * (offset + length) overflows.
+         */
+        if (offset < 0 || offset > buf.length || length < 0 || offset + length < 0) {
             throw new IllegalArgumentException();
         }
         this.buf = buf;
@@ -84,7 +88,8 @@
         this.markedPos = offset;
 
         /* This is according to spec */
-        this.count = this.pos + length < buf.length ? length : buf.length;
+        int bufferLength = buf.length;
+        this.count = offset + length < bufferLength ? length : bufferLength;
     }
 
     /**

Modified: harmony/enhanced/classlib/branches/java6/modules/luni/src/main/java/java/io/FilterOutputStream.java
URL: http://svn.apache.org/viewvc/harmony/enhanced/classlib/branches/java6/modules/luni/src/main/java/java/io/FilterOutputStream.java?rev=884518&r1=884517&r2=884518&view=diff
==============================================================================
--- harmony/enhanced/classlib/branches/java6/modules/luni/src/main/java/java/io/FilterOutputStream.java (original)
+++ harmony/enhanced/classlib/branches/java6/modules/luni/src/main/java/java/io/FilterOutputStream.java Thu Nov 26 11:12:49 2009
@@ -18,6 +18,7 @@
 package java.io;
 
 import org.apache.harmony.luni.util.Msg;
+import org.apache.harmony.luni.util.SneakyThrow;
 
 /**
  * Wraps an existing {@link OutputStream} and performs some transformation on
@@ -55,13 +56,24 @@
      */
     @Override
     public void close() throws IOException {
+        Throwable thrown = null;
         try {
             flush();
-        } catch (IOException e) {
-            // Ignored
+        } catch (Throwable e) {
+            thrown = e;
+        }
+
+        try {
+            out.close();
+        } catch (Throwable e) {
+            if (thrown == null) {
+                thrown = e;
+            }
+        }
+
+        if (thrown != null) {
+            SneakyThrow.sneakyThrow(thrown);
         }
-        /* Make sure we clean up this stream if exception fires */
-        out.close();
     }
 
     /**

Modified: harmony/enhanced/classlib/branches/java6/modules/luni/src/main/java/java/io/InputStreamReader.java
URL: http://svn.apache.org/viewvc/harmony/enhanced/classlib/branches/java6/modules/luni/src/main/java/java/io/InputStreamReader.java?rev=884518&r1=884517&r2=884518&view=diff
==============================================================================
--- harmony/enhanced/classlib/branches/java6/modules/luni/src/main/java/java/io/InputStreamReader.java (original)
+++ harmony/enhanced/classlib/branches/java6/modules/luni/src/main/java/java/io/InputStreamReader.java Thu Nov 26 11:12:49 2009
@@ -246,9 +246,14 @@
             while (out.hasRemaining()) {
                 // fill the buffer if needed
                 if (needInput) {
-                    if ((in.available() == 0) && (out.position() > offset)) {
-                        // we could return the result without blocking read
-                        break;
+                    try {
+                        if ((in.available() == 0) 
+                            && (out.position() > offset)) {
+                            // we could return the result without blocking read
+                            break;
+                        }
+                    } catch (IOException e) {
+                        // available didn't work so just try the read
                     }
 
                     int to_read = bytes.capacity() - bytes.limit();

Modified: harmony/enhanced/classlib/branches/java6/modules/luni/src/main/java/java/io/LineNumberReader.java
URL: http://svn.apache.org/viewvc/harmony/enhanced/classlib/branches/java6/modules/luni/src/main/java/java/io/LineNumberReader.java?rev=884518&r1=884517&r2=884518&view=diff
==============================================================================
--- harmony/enhanced/classlib/branches/java6/modules/luni/src/main/java/java/io/LineNumberReader.java (original)
+++ harmony/enhanced/classlib/branches/java6/modules/luni/src/main/java/java/io/LineNumberReader.java Thu Nov 26 11:12:49 2009
@@ -139,8 +139,7 @@
      * <p>
      * The line number count is incremented if a line terminator is encountered.
      * Recognized line terminator sequences are {@code '\r'}, {@code '\n'} and
-     * {@code "\r\n"}. Line terminator sequences are always translated into
-     * {@code '\n'}.
+     * {@code "\r\n"}.
      *
      * @param buffer
      *            the array in which to store the characters read.
@@ -193,8 +192,15 @@
     @Override
     public String readLine() throws IOException {
         synchronized (lock) {
-            lineNumber++;
-            return super.readLine();
+            if (lastWasCR) {
+                chompNewline();
+                lastWasCR = false;
+            }
+            String result = super.readLine();
+            if (result != null) {
+                lineNumber++;
+            }
+            return result;
         }
     }
 

Modified: harmony/enhanced/classlib/branches/java6/modules/luni/src/main/java/java/io/OutputStream.java
URL: http://svn.apache.org/viewvc/harmony/enhanced/classlib/branches/java6/modules/luni/src/main/java/java/io/OutputStream.java?rev=884518&r1=884517&r2=884518&view=diff
==============================================================================
--- harmony/enhanced/classlib/branches/java6/modules/luni/src/main/java/java/io/OutputStream.java (original)
+++ harmony/enhanced/classlib/branches/java6/modules/luni/src/main/java/java/io/OutputStream.java Thu Nov 26 11:12:49 2009
@@ -118,4 +118,12 @@
      *             if an error occurs while writing to this stream.
      */
     public abstract void write(int oneByte) throws IOException;
+
+    /**
+     * Returns true if this writer has encountered and suppressed an error. Used
+     * by PrintStreams as an alternative to checked exceptions.
+     */
+    boolean checkError() {
+        return false;
+    }
 }

Modified: harmony/enhanced/classlib/branches/java6/modules/luni/src/main/java/java/io/OutputStreamWriter.java
URL: http://svn.apache.org/viewvc/harmony/enhanced/classlib/branches/java6/modules/luni/src/main/java/java/io/OutputStreamWriter.java?rev=884518&r1=884517&r2=884518&view=diff
==============================================================================
--- harmony/enhanced/classlib/branches/java6/modules/luni/src/main/java/java/io/OutputStreamWriter.java (original)
+++ harmony/enhanced/classlib/branches/java6/modules/luni/src/main/java/java/io/OutputStreamWriter.java Thu Nov 26 11:12:49 2009
@@ -302,4 +302,8 @@
             convert(chars);
         }
     }
+
+    @Override boolean checkError() {
+        return out.checkError();
+    }
 }

Modified: harmony/enhanced/classlib/branches/java6/modules/luni/src/main/java/java/io/PrintStream.java
URL: http://svn.apache.org/viewvc/harmony/enhanced/classlib/branches/java6/modules/luni/src/main/java/java/io/PrintStream.java?rev=884518&r1=884517&r2=884518&view=diff
==============================================================================
--- harmony/enhanced/classlib/branches/java6/modules/luni/src/main/java/java/io/PrintStream.java (original)
+++ harmony/enhanced/classlib/branches/java6/modules/luni/src/main/java/java/io/PrintStream.java Thu Nov 26 11:12:49 2009
@@ -232,10 +232,13 @@
      * @see #setError()
      */
     public boolean checkError() {
-        if (out != null) {
-            flush();
+        OutputStream delegate = out;
+        if (delegate == null) {
+            return ioError;
         }
-        return ioError;
+
+        flush();
+        return ioError || delegate.checkError();
     }
     
     /**
@@ -716,7 +719,10 @@
         }
         try {
             out.write(oneByte);
-            if (autoflush && (oneByte & 0xFF) == '\n') {
+            int b = oneByte & 0xFF;
+            // 0x0A is ASCII newline, 0x15 is EBCDIC newline.
+            boolean isNewline = b == 0x0A || b == 0x15; 
+            if (autoflush && isNewline) {
                 flush();
             }
         } catch (IOException e) {

Modified: harmony/enhanced/classlib/branches/java6/modules/luni/src/main/java/java/io/PrintWriter.java
URL: http://svn.apache.org/viewvc/harmony/enhanced/classlib/branches/java6/modules/luni/src/main/java/java/io/PrintWriter.java?rev=884518&r1=884517&r2=884518&view=diff
==============================================================================
--- harmony/enhanced/classlib/branches/java6/modules/luni/src/main/java/java/io/PrintWriter.java (original)
+++ harmony/enhanced/classlib/branches/java6/modules/luni/src/main/java/java/io/PrintWriter.java Thu Nov 26 11:12:49 2009
@@ -223,10 +223,13 @@
      * @see #setError()
      */
     public boolean checkError() {
-        if (out != null) {
-            flush();
+        Writer delegate = out;
+        if (delegate == null) {
+            return ioError;
         }
-        return ioError;
+
+        flush();
+        return ioError || delegate.checkError();
     }
     
     /**
@@ -384,16 +387,6 @@
     }
 
     /**
-     * Print a new line String onto the writer, flushing if autoflush enabled.
-     */
-    private void newline() {
-        print(lineSeparator);
-        if (autoflush) {
-            flush();
-        }
-    }
-
-    /**
      * Prints the string representation of the specified character array
      * to the target.
      * 
@@ -505,7 +498,10 @@
      */
     public void println() {
         synchronized (lock) {
-            newline();
+            print(lineSeparator);
+            if (autoflush) {
+                flush();
+            }
         }
     }
 
@@ -616,7 +612,7 @@
     public void println(String str) {
         synchronized (lock) {
             print(str);
-            newline();
+            println();
         }
     }
 

Modified: harmony/enhanced/classlib/branches/java6/modules/luni/src/main/java/java/io/StringReader.java
URL: http://svn.apache.org/viewvc/harmony/enhanced/classlib/branches/java6/modules/luni/src/main/java/java/io/StringReader.java?rev=884518&r1=884517&r2=884518&view=diff
==============================================================================
--- harmony/enhanced/classlib/branches/java6/modules/luni/src/main/java/java/io/StringReader.java (original)
+++ harmony/enhanced/classlib/branches/java6/modules/luni/src/main/java/java/io/StringReader.java Thu Nov 26 11:12:49 2009
@@ -221,13 +221,19 @@
     }
 
     /**
-     * Skips {@code amount} characters in the source string. Subsequent calls of
-     * {@code read} methods will not return these characters unless {@code
-     * reset()} is used.
-     * 
+     * Moves {@code ns} characters in the source string. Unlike the {@link
+     * Reader#skip(long) overridden method}, this method may skip negative skip
+     * distances: this rewinds the input so that characters may be read again.
+     * When the end of the source string has been reached, the input cannot be
+     * rewound.
+     *
      * @param ns
-     *            the maximum number of characters to skip.
-     * @return the number of characters actually skipped or 0 if {@code ns < 0}.
+     *            the maximum number of characters to skip. Positive values skip
+     *            forward; negative values skip backward.
+     * @return the number of characters actually skipped. This is bounded below
+     *            by the number of characters already read and above by the
+     *            number of characters remaining:<br> {@code -(num chars already
+     *            read) <= distance skipped <= num chars remaining}.
      * @throws IOException
      *             if this reader is closed.
      * @see #mark(int)
@@ -240,18 +246,18 @@
             if (isClosed()) {
                 throw new IOException(Msg.getString("K0083")); //$NON-NLS-1$
             }
-            if (ns <= 0) {
-                return 0;
-            }
-            long skipped = 0;
-            if (ns < this.count - pos) {
-                pos = pos + (int) ns;
-                skipped = ns;
-            } else {
-                skipped = this.count - pos;
-                pos = this.count;
+
+            int minSkip = -pos;
+            int maxSkip = count - pos;
+
+            if (maxSkip == 0 || ns > maxSkip) {
+                ns = maxSkip; // no rewinding if we're at the end
+            } else if (ns < minSkip) {
+                ns = minSkip;
             }
-            return skipped;
+
+            pos += ns;
+            return ns;
         }
     }
 }

Modified: harmony/enhanced/classlib/branches/java6/modules/luni/src/main/java/java/io/Writer.java
URL: http://svn.apache.org/viewvc/harmony/enhanced/classlib/branches/java6/modules/luni/src/main/java/java/io/Writer.java?rev=884518&r1=884517&r2=884518&view=diff
==============================================================================
--- harmony/enhanced/classlib/branches/java6/modules/luni/src/main/java/java/io/Writer.java (original)
+++ harmony/enhanced/classlib/branches/java6/modules/luni/src/main/java/java/io/Writer.java Thu Nov 26 11:12:49 2009
@@ -143,11 +143,7 @@
      *             if this writer is closed or another I/O error occurs.
      */
     public void write(String str) throws IOException {
-        char buf[] = new char[str.length()];
-        str.getChars(0, buf.length, buf, 0);
-        synchronized (lock) {
-            write(buf);
-        }
+        write(str, 0, str.length());
     }
 
     /**
@@ -174,7 +170,7 @@
         str.getChars(offset, offset + count, buf, 0);
 
         synchronized (lock) {
-            write(buf);
+            write(buf, 0, buf.length);
         }
     }
 
@@ -246,4 +242,12 @@
         }
         return this;
     }
+
+    /**
+     * Returns true if this writer has encountered and suppressed an error. Used
+     * by PrintWriters as an alternative to checked exceptions.
+     */
+    boolean checkError() {
+        return false;
+    }
 }

Modified: harmony/enhanced/classlib/branches/java6/modules/luni/src/main/java/java/lang/StrictMath.java
URL: http://svn.apache.org/viewvc/harmony/enhanced/classlib/branches/java6/modules/luni/src/main/java/java/lang/StrictMath.java?rev=884518&r1=884517&r2=884518&view=diff
==============================================================================
--- harmony/enhanced/classlib/branches/java6/modules/luni/src/main/java/java/lang/StrictMath.java (original)
+++ harmony/enhanced/classlib/branches/java6/modules/luni/src/main/java/java/lang/StrictMath.java Thu Nov 26 11:12:49 2009
@@ -37,7 +37,7 @@
  * <a href="http://www.netlib.org/fdlibm/">http://www.netlib.org/fdlibm/</a>
  */
 public final class StrictMath {
-	private static final int FLOAT_EXPONENT_BIAS = 127;
+    private static final int FLOAT_EXPONENT_BIAS = 127;
 
     private static final int FLOAT_EXPONENT_MASK = 0x7F800000;
 
@@ -61,26 +61,26 @@
 
     private static final long DOUBLE_SIGN_MASK = 0x8000000000000000L;
 
-	/**
+    /**
      * The double value closest to e, the base of the natural logarithm.
-	 */
-	public final static double E = Math.E;
+     */
+    public final static double E = Math.E;
 
-	/**
+    /**
      * The double value closest to pi, the ratio of a circle's circumference to
      * its diameter.
-	 */
-	public final static double PI = Math.PI;
+     */
+    public final static double PI = Math.PI;
 
-	private static java.util.Random random;
+    private static java.util.Random random;
 
-	/**
-	 * Prevents this class from being instantiated.
-	 */
-	private StrictMath() {
-	}
+    /**
+     * Prevents this class from being instantiated.
+     */
+    private StrictMath() {
+    }
 
-	/**
+    /**
      * Returns the absolute value of the argument.
      * <p>
      * Special cases:
@@ -95,11 +95,11 @@
      *            the value whose absolute value has to be computed.
      * @return the absolute value of the argument.
      */
-	public static double abs(double d) {
-		long bits = Double.doubleToLongBits(d);
-		bits &= 0x7fffffffffffffffL;
-		return Double.longBitsToDouble(bits);
-	}
+    public static double abs(double d) {
+        long bits = Double.doubleToLongBits(d);
+        bits &= 0x7fffffffffffffffL;
+        return Double.longBitsToDouble(bits);
+    }
 
     /**
      * Returns the absolute value of the argument.
@@ -117,11 +117,11 @@
      * @return the argument if it is positive, otherwise the negation of the
      *         argument.
      */
-	public static float abs(float f) {
-		int bits = Float.floatToIntBits(f);
-		bits &= 0x7fffffff;
-		return Float.intBitsToFloat(bits);
-	}
+    public static float abs(float f) {
+        int bits = Float.floatToIntBits(f);
+        bits &= 0x7fffffff;
+        return Float.intBitsToFloat(bits);
+    }
 
     /**
      * Returns the absolute value of the argument.
@@ -134,9 +134,9 @@
      * @return the argument if it is positive, otherwise the negation of the
      *         argument.
      */
-	public static int abs(int i) {
-		return i >= 0 ? i : -i;
-	}
+    public static int abs(int i) {
+        return i >= 0 ? i : -i;
+    }
 
     /**
      * Returns the absolute value of the argument.
@@ -149,9 +149,9 @@
      * @return the argument if it is positive, otherwise the negation of the
      *         argument.
      */
-	public static long abs(long l) {
-		return l >= 0 ? l : -l;
-	}
+    public static long abs(long l) {
+        return l >= 0 ? l : -l;
+    }
 
     /**
      * Returns the closest double approximation of the arc cosine of the
@@ -168,7 +168,7 @@
      *            the value to compute arc cosine of.
      * @return the arc cosine of the argument.
      */
-	public static native double acos(double d);
+    public static native double acos(double d);
 
     /**
      * Returns the closest double approximation of the arc sine of the argument
@@ -185,7 +185,7 @@
      *            the value whose arc sine has to be computed.
      * @return the arc sine of the argument.
      */
-	public static native double asin(double d);
+    public static native double asin(double d);
 
     /**
      * Returns the closest double approximation of the arc tangent of the
@@ -204,7 +204,7 @@
      *            the value whose arc tangent has to be computed.
      * @return the arc tangent of the argument.
      */
-	public static native double atan(double d);
+    public static native double atan(double d);
 
     /**
      * Returns the closest double approximation of the arc tangent of
@@ -243,7 +243,7 @@
      *            the denominator of the value whose atan has to be computed.
      * @return the arc tangent of {@code y/x}.
      */
-	public static native double atan2(double y, double x);
+    public static native double atan2(double y, double x);
     
     /**
      * Returns the closest double approximation of the cube root of the
@@ -282,7 +282,7 @@
      *            the value whose closest integer value has to be computed.
      * @return the ceiling of the argument.
      */
-	public static native double ceil(double d);
+    public static native double ceil(double d);
     
     
     /**
@@ -425,7 +425,7 @@
      *            the denominator of the operation.
      * @return the IEEE754 floating point reminder of of {@code x/y}.
      */
-	public static native double IEEEremainder(double x, double y);
+    public static native double IEEEremainder(double x, double y);
 
     /**
      * Returns the closest double approximation of the natural logarithm of the
@@ -508,20 +508,20 @@
      *            the second argument.
      * @return the larger of {@code d1} and {@code d2}.
      */
-	public static double max(double d1, double d2) {
-		if (d1 > d2)
-			return d1;
-		if (d1 < d2)
-			return d2;
-		/* if either arg is NaN, return NaN */
-		if (d1 != d2)
-			return Double.NaN;
-		/* max( +0.0,-0.0) == +0.0 */
-		if (d1 == 0.0
-				&& ((Double.doubleToLongBits(d1) & Double.doubleToLongBits(d2)) & 0x8000000000000000L) == 0)
-			return 0.0;
-		return d1;
-	}
+    public static double max(double d1, double d2) {
+        if (d1 > d2)
+            return d1;
+        if (d1 < d2)
+            return d2;
+        /* if either arg is NaN, return NaN */
+        if (d1 != d2)
+            return Double.NaN;
+        /* max( +0.0,-0.0) == +0.0 */
+        if (d1 == 0.0
+                && ((Double.doubleToLongBits(d1) & Double.doubleToLongBits(d2)) & 0x8000000000000000L) == 0)
+            return 0.0;
+        return d1;
+    }
 
     /**
      * Returns the most positive (closest to positive infinity) of the two
@@ -541,20 +541,20 @@
      *            the second argument.
      * @return the larger of {@code f1} and {@code f2}.
      */
-	public static float max(float f1, float f2) {
-		if (f1 > f2)
-			return f1;
-		if (f1 < f2)
-			return f2;
-		/* if either arg is NaN, return NaN */
-		if (f1 != f2)
-			return Float.NaN;
-		/* max( +0.0,-0.0) == +0.0 */
-		if (f1 == 0.0f
-				&& ((Float.floatToIntBits(f1) & Float.floatToIntBits(f2)) & 0x80000000) == 0)
-			return 0.0f;
-		return f1;
-	}
+    public static float max(float f1, float f2) {
+        if (f1 > f2)
+            return f1;
+        if (f1 < f2)
+            return f2;
+        /* if either arg is NaN, return NaN */
+        if (f1 != f2)
+            return Float.NaN;
+        /* max( +0.0,-0.0) == +0.0 */
+        if (f1 == 0.0f
+                && ((Float.floatToIntBits(f1) & Float.floatToIntBits(f2)) & 0x80000000) == 0)
+            return 0.0f;
+        return f1;
+    }
 
     /**
      * Returns the most positive (closest to positive infinity) of the two
@@ -566,9 +566,9 @@
      *            the second argument.
      * @return the larger of {@code i1} and {@code i2}.
      */
-	public static int max(int i1, int i2) {
-		return i1 > i2 ? i1 : i2;
-	}
+    public static int max(int i1, int i2) {
+        return i1 > i2 ? i1 : i2;
+    }
 
     /**
      * Returns the most positive (closest to positive infinity) of the two
@@ -580,9 +580,9 @@
      *            the second argument.
      * @return the larger of {@code l1} and {@code l2}.
      */
-	public static long max(long l1, long l2) {
-		return l1 > l2 ? l1 : l2;
-	}
+    public static long max(long l1, long l2) {
+        return l1 > l2 ? l1 : l2;
+    }
 
     /**
      * Returns the most negative (closest to negative infinity) of the two
@@ -602,20 +602,20 @@
      *            the second argument.
      * @return the smaller of {@code d1} and {@code d2}.
      */
-	public static double min(double d1, double d2) {
-		if (d1 > d2)
-			return d2;
-		if (d1 < d2)
-			return d1;
-		/* if either arg is NaN, return NaN */
-		if (d1 != d2)
-			return Double.NaN;
-		/* min( +0.0,-0.0) == -0.0 */
-		if (d1 == 0.0
-				&& ((Double.doubleToLongBits(d1) | Double.doubleToLongBits(d2)) & 0x8000000000000000l) != 0)
-			return 0.0 * (-1.0);
-		return d1;
-	}
+    public static double min(double d1, double d2) {
+        if (d1 > d2)
+            return d2;
+        if (d1 < d2)
+            return d1;
+        /* if either arg is NaN, return NaN */
+        if (d1 != d2)
+            return Double.NaN;
+        /* min( +0.0,-0.0) == -0.0 */
+        if (d1 == 0.0
+                && ((Double.doubleToLongBits(d1) | Double.doubleToLongBits(d2)) & 0x8000000000000000l) != 0)
+            return 0.0 * (-1.0);
+        return d1;
+    }
 
     /**
      * Returns the most negative (closest to negative infinity) of the two
@@ -635,20 +635,20 @@
      *            the second argument.
      * @return the smaller of {@code f1} and {@code f2}.
      */
-	public static float min(float f1, float f2) {
-		if (f1 > f2)
-			return f2;
-		if (f1 < f2)
-			return f1;
-		/* if either arg is NaN, return NaN */
-		if (f1 != f2)
-			return Float.NaN;
-		/* min( +0.0,-0.0) == -0.0 */
-		if (f1 == 0.0f
-				&& ((Float.floatToIntBits(f1) | Float.floatToIntBits(f2)) & 0x80000000) != 0)
-			return 0.0f * (-1.0f);
-		return f1;
-	}
+    public static float min(float f1, float f2) {
+        if (f1 > f2)
+            return f2;
+        if (f1 < f2)
+            return f1;
+        /* if either arg is NaN, return NaN */
+        if (f1 != f2)
+            return Float.NaN;
+        /* min( +0.0,-0.0) == -0.0 */
+        if (f1 == 0.0f
+                && ((Float.floatToIntBits(f1) | Float.floatToIntBits(f2)) & 0x80000000) != 0)
+            return 0.0f * (-1.0f);
+        return f1;
+    }
 
     /**
      * Returns the most negative (closest to negative infinity) of the two
@@ -660,9 +660,9 @@
      *            the second argument.
      * @return the smaller of {@code i1} and {@code i2}.
      */
-	public static int min(int i1, int i2) {
-		return i1 < i2 ? i1 : i2;
-	}
+    public static int min(int i1, int i2) {
+        return i1 < i2 ? i1 : i2;
+    }
 
     /**
      * Returns the most negative (closest to negative infinity) of the two
@@ -674,9 +674,9 @@
      *            the second argument.
      * @return the smaller of {@code l1} and {@code l2}.
      */
-	public static long min(long l1, long l2) {
-		return l1 < l2 ? l1 : l2;
-	}
+    public static long min(long l1, long l2) {
+        return l1 < l2 ? l1 : l2;
+    }
 
     /**
      * Returns the closest double approximation of the result of raising
@@ -716,7 +716,7 @@
      *            the exponent of the operation.
      * @return {@code x} to the power of {@code y}.
      */
-	public static native double pow(double x, double y);
+    public static native double pow(double x, double y);
 
     /**
      * Returns a pseudo-random number between 0.0 (inclusive) and 1.0
@@ -725,10 +725,10 @@
      * @return a pseudo-random number.
      */
     public static double random() {
-		if (random == null)
-			random = new Random();
-		return random.nextDouble();
-	}
+        if (random == null)
+            random = new Random();
+        return random.nextDouble();
+    }
 
     /**
      * Returns the double conversion of the result of rounding the argument to
@@ -768,12 +768,12 @@
      *            the value to be rounded.
      * @return the closest integer to the argument.
      */
-	public static long round(double d) {
-		// check for NaN
-		if (d != d)
-			return 0L;
-		return (long) Math.floor(d + 0.5d);
-	}
+    public static long round(double d) {
+        // check for NaN
+        if (d != d)
+            return 0L;
+        return (long) Math.floor(d + 0.5d);
+    }
 
     /**
      * Returns the result of rounding the argument to an integer. The result is
@@ -794,12 +794,12 @@
      *            the value to be rounded.
      * @return the closest integer to the argument.
      */
-	public static int round(float f) {
-		// check for NaN
-		if (f != f)
-			return 0;
-		return (int) Math.floor(f + 0.5f);
-	}
+    public static int round(float f) {
+        // check for NaN
+        if (f != f)
+            return 0;
+        return (int) Math.floor(f + 0.5f);
+    }
     
     /**
      * Returns the signum function of the argument. If the argument is less than
@@ -975,9 +975,9 @@
      *            an angle in radians.
      * @return the degree measure of the angle.
      */
-	public static double toDegrees(double angrad) {
-		return angrad * 180d / PI;
-	}
+    public static double toDegrees(double angrad) {
+        return angrad * 180d / PI;
+    }
 
     /**
      * Returns the measure in radians of the supplied degree angle. The result
@@ -996,11 +996,11 @@
      *            an angle in degrees.
      * @return the radian measure of the angle.
      */
-	public static double toRadians(double angdeg) {
-		return angdeg / 180d * PI;
-	}
-	
-	/**
+    public static double toRadians(double angdeg) {
+        return angdeg / 180d * PI;
+    }
+    
+    /**
      * Returns the argument's ulp (unit in the last place). The size of a ulp of
      * a double value is the positive distance between this value and the double
      * value next larger in magnitude. For non-NaN {@code x},

Modified: harmony/enhanced/classlib/branches/java6/modules/luni/src/main/java/java/net/InetAddress.java
URL: http://svn.apache.org/viewvc/harmony/enhanced/classlib/branches/java6/modules/luni/src/main/java/java/net/InetAddress.java?rev=884518&r1=884517&r2=884518&view=diff
==============================================================================
--- harmony/enhanced/classlib/branches/java6/modules/luni/src/main/java/java/net/InetAddress.java (original)
+++ harmony/enhanced/classlib/branches/java6/modules/luni/src/main/java/java/net/InetAddress.java Thu Nov 26 11:12:49 2009
@@ -507,11 +507,17 @@
      */
     static native String getHostNameImpl();
 
-    static String getHostNameInternal(String host) throws UnknownHostException {
+    static String getHostNameInternal(String host, boolean isCheck) throws UnknownHostException {
         if (host == null || 0 == host.length()) {
             return InetAddress.LOOPBACK.getHostAddress();
         }
         if (isHostName(host)) {
+            if (isCheck) {
+                SecurityManager sm = System.getSecurityManager();
+                if (sm != null) {
+                    sm.checkConnect(host, -1);
+                }
+            }
             return lookupHostByName(host).getHostAddress();
         }
         return host;

Modified: harmony/enhanced/classlib/branches/java6/modules/luni/src/main/java/java/net/ServerSocket.java
URL: http://svn.apache.org/viewvc/harmony/enhanced/classlib/branches/java6/modules/luni/src/main/java/java/net/ServerSocket.java?rev=884518&r1=884517&r2=884518&view=diff
==============================================================================
--- harmony/enhanced/classlib/branches/java6/modules/luni/src/main/java/java/net/ServerSocket.java (original)
+++ harmony/enhanced/classlib/branches/java6/modules/luni/src/main/java/java/net/ServerSocket.java Thu Nov 26 11:12:49 2009
@@ -152,14 +152,7 @@
 
         Socket aSocket = new Socket();
         try {
-            synchronized (this) {
-                implAccept(aSocket);
-            }
-            SecurityManager security = System.getSecurityManager();
-            if (security != null) {
-                security.checkAccept(aSocket.getInetAddress().getHostAddress(),
-                        aSocket.getPort());
-            }
+            implAccept(aSocket);
         } catch (SecurityException e) {
             aSocket.close();
             throw e;
@@ -274,8 +267,15 @@
      *             if the connection cannot be accepted.
      */
     protected final void implAccept(Socket aSocket) throws IOException {
-        impl.accept(aSocket.impl);
-        aSocket.accepted();
+        synchronized (this) {
+            impl.accept(aSocket.impl);
+            aSocket.accepted();
+        }
+        SecurityManager security = System.getSecurityManager();
+        if (security != null) {
+            security.checkAccept(aSocket.getInetAddress().getHostAddress(),
+                    aSocket.getPort());
+        }
     }
 
     /**

Modified: harmony/enhanced/classlib/branches/java6/modules/luni/src/main/java/java/net/SocketPermission.java
URL: http://svn.apache.org/viewvc/harmony/enhanced/classlib/branches/java6/modules/luni/src/main/java/java/net/SocketPermission.java?rev=884518&r1=884517&r2=884518&view=diff
==============================================================================
--- harmony/enhanced/classlib/branches/java6/modules/luni/src/main/java/java/net/SocketPermission.java (original)
+++ harmony/enhanced/classlib/branches/java6/modules/luni/src/main/java/java/net/SocketPermission.java Thu Nov 26 11:12:49 2009
@@ -142,7 +142,7 @@
      * Compares the argument {@code o} to this instance and returns {@code true}
      * if they represent the same permission using a class specific comparison.
      *
-     * @param o
+     * @param other
      *            the object to compare with this {@code SocketPermission}
      *            instance.
      * @return {@code true} if they represent the same permission, {@code false}
@@ -150,16 +150,16 @@
      * @see #hashCode
      */
     @Override
-    public boolean equals(Object o) {
-        if (this == o) {
+    public boolean equals(Object other) {
+        if (this == other) {
             return true;
         }
-        if (o == null || this.getClass() != o.getClass()) {
+        if (other == null || this.getClass() != other.getClass()) {
             return false;
         }
-        SocketPermission sp = (SocketPermission) o;
-        if (!hostName.equals(sp.hostName)) {
-            if (getIPString() == null || !ipString.equals(sp.getIPString())) {
+        SocketPermission sp = (SocketPermission) other;
+        if (!hostName.equalsIgnoreCase(sp.hostName)) {
+            if (getIPString(true) == null || !ipString.equalsIgnoreCase(sp.getIPString(true))) {
                 return false;
             }
         }
@@ -379,10 +379,10 @@
         return actions = sb.substring(1, sb.length());
     }
 
-    private String getIPString() {
+    private String getIPString(boolean isCheck) {
         if (!resolved) {
             try {
-                ipString = InetAddress.getHostNameInternal(hostName);
+                ipString = InetAddress.getHostNameInternal(hostName, isCheck);
             } catch (UnknownHostException e) {
                 // ignore
             }
@@ -483,7 +483,7 @@
         }
         // The ipString may not be the same, some hosts resolve to
         // multiple ips
-        return (getIPString() != null && ipString.equals(sp.getIPString()))
+        return (getIPString(false) != null && ipString.equals(sp.getIPString(false)))
                 || hostName.equals(sp.hostName);
     }
 

Modified: harmony/enhanced/classlib/branches/java6/modules/luni/src/main/java/java/net/URL.java
URL: http://svn.apache.org/viewvc/harmony/enhanced/classlib/branches/java6/modules/luni/src/main/java/java/net/URL.java?rev=884518&r1=884517&r2=884518&view=diff
==============================================================================
--- harmony/enhanced/classlib/branches/java6/modules/luni/src/main/java/java/net/URL.java (original)
+++ harmony/enhanced/classlib/branches/java6/modules/luni/src/main/java/java/net/URL.java Thu Nov 26 11:12:49 2009
@@ -697,9 +697,19 @@
      *             through proxies.
      */
     public URLConnection openConnection(Proxy proxy) throws IOException {
-        if (null == proxy) {
+        if (proxy == null) {
+            // K034c=proxy should not be null
             throw new IllegalArgumentException(Msg.getString("K034c")); //$NON-NLS-1$
         }
+
+        SecurityManager sm = System.getSecurityManager();
+        if (sm != null && proxy.type() != Proxy.Type.DIRECT) {
+            InetSocketAddress pAddress = (InetSocketAddress) proxy.address();
+            String pHostName = pAddress.isUnresolved() ? pAddress.getHostName()
+                    : pAddress.getAddress().getHostAddress();
+            sm.checkConnect(pHostName, pAddress.getPort());
+        }
+
         return strmHandler.openConnection(this, proxy);
     }
 

Modified: harmony/enhanced/classlib/branches/java6/modules/luni/src/main/java/java/net/URLEncoder.java
URL: http://svn.apache.org/viewvc/harmony/enhanced/classlib/branches/java6/modules/luni/src/main/java/java/net/URLEncoder.java?rev=884518&r1=884517&r2=884518&view=diff
==============================================================================
--- harmony/enhanced/classlib/branches/java6/modules/luni/src/main/java/java/net/URLEncoder.java (original)
+++ harmony/enhanced/classlib/branches/java6/modules/luni/src/main/java/java/net/URLEncoder.java Thu Nov 26 11:12:49 2009
@@ -49,7 +49,8 @@
      */
     @Deprecated
     public static String encode(String s) {
-        StringBuilder buf = new StringBuilder();
+        // Guess a bit bigger for encoded form
+        StringBuilder buf = new StringBuilder(s.length() + 16);
         for (int i = 0; i < s.length(); i++) {
             char ch = s.charAt(i);
             if ((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z')
@@ -95,7 +96,8 @@
         // check for UnsupportedEncodingException
         "".getBytes(enc); //$NON-NLS-1$
 
-        StringBuffer buf = new StringBuffer();
+        // Guess a bit bigger for encoded form
+        StringBuffer buf = new StringBuffer(s.length() + 16);
         int start = -1;
         for (int i = 0; i < s.length(); i++) {
             char ch = s.charAt(i);

Modified: harmony/enhanced/classlib/branches/java6/modules/luni/src/main/java/java/util/ArrayList.java
URL: http://svn.apache.org/viewvc/harmony/enhanced/classlib/branches/java6/modules/luni/src/main/java/java/util/ArrayList.java?rev=884518&r1=884517&r2=884518&view=diff
==============================================================================
--- harmony/enhanced/classlib/branches/java6/modules/luni/src/main/java/java/util/ArrayList.java (original)
+++ harmony/enhanced/classlib/branches/java6/modules/luni/src/main/java/java/util/ArrayList.java Thu Nov 26 11:12:49 2009
@@ -24,6 +24,8 @@
 import java.io.Serializable;
 import java.lang.reflect.Array;
 
+import org.apache.harmony.luni.internal.nls.Messages;
+
 /**
  * ArrayList is an implementation of {@link List}, backed by an array. All
  * optional operations adding, removing, and replacing are supported. The
@@ -128,7 +130,11 @@
             }
             array[lastIndex++] = object;
         } else {
-            throw new IndexOutOfBoundsException();
+            throw new IndexOutOfBoundsException(
+                    // luni.0A=Index: {0}, Size: {1}
+                    Messages.getString("luni.0A", //$NON-NLS-1$
+                            Integer.valueOf(location),
+                            Integer.valueOf(lastIndex - firstIndex)));
         }
 
         modCount++;
@@ -169,7 +175,11 @@
     public boolean addAll(int location, Collection<? extends E> collection) {
         int size = lastIndex - firstIndex;
         if (location < 0 || location > size) {
-            throw new IndexOutOfBoundsException();
+            throw new IndexOutOfBoundsException(
+                    // luni.0A=Index: {0}, Size: {1}
+                    Messages.getString("luni.0A", //$NON-NLS-1$
+                            Integer.valueOf(location),
+                            Integer.valueOf(lastIndex - firstIndex)));
         }
         if (this == collection) {
             collection = (ArrayList)clone();
@@ -322,7 +332,11 @@
         if (0 <= location && location < (lastIndex - firstIndex)) {
             return array[firstIndex + location];
         }
-        throw new IndexOutOfBoundsException();
+        throw new IndexOutOfBoundsException(
+                // luni.0A=Index: {0}, Size: {1}
+                Messages.getString("luni.0A", //$NON-NLS-1$
+                        Integer.valueOf(location),
+                        Integer.valueOf(lastIndex - firstIndex)));
     }
 
     private void growAtEnd(int required) {
@@ -486,7 +500,11 @@
                 firstIndex = lastIndex = 0;
             }
         } else {
-            throw new IndexOutOfBoundsException();
+            throw new IndexOutOfBoundsException(
+                    // luni.0A=Index: {0}, Size: {1}
+                    Messages.getString("luni.0A", //$NON-NLS-1$
+                            Integer.valueOf(location),
+                            Integer.valueOf(lastIndex - firstIndex)));
         }
 
         modCount++;
@@ -536,7 +554,10 @@
             }
             modCount++;
         } else {
-            throw new IndexOutOfBoundsException();
+            throw new IndexOutOfBoundsException(
+                    // luni.0B=Array index out of range: {0}
+                    Messages.getString("luni.0B", //$NON-NLS-1$
+                            lastIndex - firstIndex - end));
         }
     }
 
@@ -559,7 +580,11 @@
             array[firstIndex + location] = object;
             return result;
         }
-        throw new IndexOutOfBoundsException();
+        throw new IndexOutOfBoundsException(
+                // luni.0A=Index: {0}, Size: {1}
+                Messages.getString("luni.0A", //$NON-NLS-1$
+                        Integer.valueOf(location),
+                        Integer.valueOf(lastIndex - firstIndex)));
     }
 
     /**

Modified: harmony/enhanced/classlib/branches/java6/modules/luni/src/main/java/java/util/Timer.java
URL: http://svn.apache.org/viewvc/harmony/enhanced/classlib/branches/java6/modules/luni/src/main/java/java/util/Timer.java?rev=884518&r1=884517&r2=884518&view=diff
==============================================================================
--- harmony/enhanced/classlib/branches/java6/modules/luni/src/main/java/java/util/Timer.java (original)
+++ harmony/enhanced/classlib/branches/java6/modules/luni/src/main/java/java/util/Timer.java Thu Nov 26 11:12:49 2009
@@ -217,7 +217,7 @@
                         // no tasks scheduled -- sleep until any task appear
                         try {
                             this.wait();
-                        } catch (InterruptedException e) {
+                        } catch (InterruptedException ignored) {
                         }
                         continue;
                     }
@@ -241,8 +241,7 @@
                         // sleep!
                         try {
                             this.wait(timeToSleep);
-                        } catch (InterruptedException e) {
-                            // Ignored
+                        } catch (InterruptedException ignored) {
                         }
                         continue;
                     }
@@ -285,11 +284,16 @@
                     }
                 }
 
-                // run the task
+                boolean taskCompletedNormally = false;
                 try {
                     task.run();
-                } catch (Exception e) {
-                    // Ignored
+                    taskCompletedNormally = true;
+                } finally {
+                    if (!taskCompletedNormally) {
+                        synchronized (this) {
+                            cancelled = true;
+                        }
+                    }
                 }
             }
         }
@@ -549,7 +553,7 @@
             throw new IllegalArgumentException();
         }
         long delay = when.getTime() - System.currentTimeMillis();
-        scheduleImpl(task, delay < 0 ? 0 : delay, period, true);
+        scheduleImpl(task, delay, period, true);
     }
 
     /*

Modified: harmony/enhanced/classlib/branches/java6/modules/luni/src/main/java/org/apache/harmony/luni/internal/net/www/protocol/ftp/FtpURLConnection.java
URL: http://svn.apache.org/viewvc/harmony/enhanced/classlib/branches/java6/modules/luni/src/main/java/org/apache/harmony/luni/internal/net/www/protocol/ftp/FtpURLConnection.java?rev=884518&r1=884517&r2=884518&view=diff
==============================================================================
--- harmony/enhanced/classlib/branches/java6/modules/luni/src/main/java/org/apache/harmony/luni/internal/net/www/protocol/ftp/FtpURLConnection.java (original)
+++ harmony/enhanced/classlib/branches/java6/modules/luni/src/main/java/org/apache/harmony/luni/internal/net/www/protocol/ftp/FtpURLConnection.java Thu Nov 26 11:12:49 2009
@@ -18,6 +18,7 @@
 package org.apache.harmony.luni.internal.net.www.protocol.ftp;
 
 import java.io.BufferedInputStream;
+import java.io.EOFException;
 import java.io.FileNotFoundException;
 import java.io.IOException;
 import java.io.InputStream;
@@ -334,7 +335,6 @@
      * @see java.io.IOException
      * 
      */
-
     @Override
     public OutputStream getOutputStream() throws IOException {
         if (!connected) {
@@ -345,8 +345,15 @@
 
     private int getReply() throws IOException {
         byte[] code = new byte[3];
-        ctrlInput.read(code, 0, code.length);
+        for (int i = 0; i < code.length; i++) {
+            final int tmp = ctrlInput.read();
+            if (tmp == -1) {
+                throw new EOFException();
+            }
+            code[i] = (byte) tmp;
+        }
         replyCode = new String(code, "ISO8859_1"); //$NON-NLS-1$
+        
         boolean multiline = false;
         if (ctrlInput.read() == '-') {
             multiline = true;
@@ -356,7 +363,12 @@
             while (readMultiLine()) {/* Read all of a multiline reply */
             }
         }
-        return Integer.parseInt(new String(code, "ISO8859_1")); //$NON-NLS-1$
+        
+        try {
+            return Integer.parseInt(replyCode);
+        } catch (NumberFormatException e) {
+            throw (IOException)(new IOException("reply code is invalid").initCause(e));
+        }
     }
 
     private void login() throws IOException {

Modified: harmony/enhanced/classlib/branches/java6/modules/luni/src/main/java/org/apache/harmony/luni/internal/nls/messages.properties
URL: http://svn.apache.org/viewvc/harmony/enhanced/classlib/branches/java6/modules/luni/src/main/java/org/apache/harmony/luni/internal/nls/messages.properties?rev=884518&r1=884517&r2=884518&view=diff
==============================================================================
--- harmony/enhanced/classlib/branches/java6/modules/luni/src/main/java/org/apache/harmony/luni/internal/nls/messages.properties (original)
+++ harmony/enhanced/classlib/branches/java6/modules/luni/src/main/java/org/apache/harmony/luni/internal/nls/messages.properties Thu Nov 26 11:12:49 2009
@@ -24,3 +24,5 @@
 luni.07=The stream is corrupted
 luni.08=Invalid Unicode sequence: expected format \\uxxxx
 luni.09=Invalid Unicode sequence: illegal character
+luni.0A=Index: {0}, Size: {1}
+luni.0B=Array index out of range: {0}

Modified: harmony/enhanced/classlib/branches/java6/modules/luni/src/main/java/org/apache/harmony/luni/internal/reflect/ProxyConstantPool.java
URL: http://svn.apache.org/viewvc/harmony/enhanced/classlib/branches/java6/modules/luni/src/main/java/org/apache/harmony/luni/internal/reflect/ProxyConstantPool.java?rev=884518&r1=884517&r2=884518&view=diff
==============================================================================
--- harmony/enhanced/classlib/branches/java6/modules/luni/src/main/java/org/apache/harmony/luni/internal/reflect/ProxyConstantPool.java (original)
+++ harmony/enhanced/classlib/branches/java6/modules/luni/src/main/java/org/apache/harmony/luni/internal/reflect/ProxyConstantPool.java Thu Nov 26 11:12:49 2009
@@ -23,294 +23,294 @@
 import java.lang.reflect.Method;
 
 class ProxyConstantPool implements ProxyConstants {
-	public static final int UTF8_INITIAL_SIZE = 50;
+    public static final int UTF8_INITIAL_SIZE = 50;
 
-	public static final int STRING_INITIAL_SIZE = 21;
+    public static final int STRING_INITIAL_SIZE = 21;
 
-	public static final int FIELD_INITIAL_SIZE = 7;
+    public static final int FIELD_INITIAL_SIZE = 7;
 
-	public static final int METHOD_INITIAL_SIZE = 21;
+    public static final int METHOD_INITIAL_SIZE = 21;
 
-	public static final int INTERFACE_INITIAL_SIZE = 21;
-
-	public static final int CLASS_INITIAL_SIZE = 21;
-
-	public static final int NAMEANDTYPE_INITIAL_SIZE = 21;
-
-	public static final int CONSTANTPOOL_INITIAL_SIZE = 500;
-
-	public static final int CONSTANTPOOL_GROW_SIZE = 1000;
-
-	ProxyCharArrayCache UTF8Cache;
-
-	ProxyCharArrayCache stringCache;
-
-	ProxyCharArrayCache classNameCache;
-
-	ProxyObjectCache fieldCache;
-
-	ProxyObjectCache methodCache;
-
-	ProxyObjectCache interfaceMethodCache;
-
-	ProxyNameAndTypeCache nameAndTypeCache;
-
-	byte[] poolContent;
-
-	int currentIndex;
-
-	int currentOffset;
-
-	ProxyConstantPool(ProxyClassFile classFile) {
-		UTF8Cache = new ProxyCharArrayCache(UTF8_INITIAL_SIZE);
-		stringCache = new ProxyCharArrayCache(STRING_INITIAL_SIZE);
-		classNameCache = new ProxyCharArrayCache(CLASS_INITIAL_SIZE);
-		fieldCache = new ProxyObjectCache(FIELD_INITIAL_SIZE);
-		methodCache = new ProxyObjectCache(METHOD_INITIAL_SIZE);
-		interfaceMethodCache = new ProxyObjectCache(INTERFACE_INITIAL_SIZE);
-		nameAndTypeCache = new ProxyNameAndTypeCache(NAMEANDTYPE_INITIAL_SIZE);
-		poolContent = classFile.header;
-		currentOffset = classFile.headerOffset;
-		currentIndex = 1;
-	}
-
-	int literalIndex(char[] utf8Constant) {
-		int index;
-		if ((index = UTF8Cache.get(utf8Constant)) < 0) {
-			writeU1(Utf8Tag);
-			int savedCurrentOffset = currentOffset;
-			if (currentOffset + 2 >= poolContent.length) {
-				int length = poolContent.length;
-				System.arraycopy(poolContent, 0, (poolContent = new byte[length
-						+ CONSTANTPOOL_GROW_SIZE]), 0, length);
-			}
-			currentOffset += 2;
-			int length = 0;
-			for (int i = 0; i < utf8Constant.length; i++) {
-				char current = utf8Constant[i];
-				if ((current >= 0x0001) && (current <= 0x007F)) {
-					// we only need one byte: ASCII table
-					writeU1(current);
-					length++;
-				} else if (current > 0x07FF) {
-					// we need 3 bytes
-					length += 3;
-					writeU1(0xE0 | ((current >> 12) & 0x0F)); // 0xE0 = 1110
-																// 0000
-					writeU1(0x80 | ((current >> 6) & 0x3F)); // 0x80 = 1000
-																// 0000
-					writeU1(0x80 | (current & 0x3F)); // 0x80 = 1000 0000
-				} else {
-					// we can be 0 or between 0x0080 and 0x07FF
-					// In that case we only need 2 bytes
-					length += 2;
-					writeU1(0xC0 | ((current >> 6) & 0x1F)); // 0xC0 = 1100
-																// 0000
-					writeU1(0x80 | (current & 0x3F)); // 0x80 = 1000 0000
-				}
-			}
-			if (length >= 65535) {
-				currentOffset = savedCurrentOffset - 1;
-				return -1;
-			}
-			index = UTF8Cache.put(utf8Constant, currentIndex++);
-			// Now we know the length that we have to write in the constant pool
-			// we use savedCurrentOffset to do that
-			poolContent[savedCurrentOffset] = (byte) (length >> 8);
-			poolContent[savedCurrentOffset + 1] = (byte) length;
-		}
-		return index;
-	}
-	
-        int literalIndex(Field aField) {	
-        	return literalIndex(aField.getDeclaringClass().getName(), aField.getName(), aField.getType());
-	}
-	
-	int literalIndex(String declaringClass, String name, Class clazz) {
-		int index;
-		String key = declaringClass + "." + name;
-		if ((index = fieldCache.get(key)) < 0) {
-			int classIndex = typeIndex(declaringClass);	
-			int nameAndTypeIndex = literalIndexForNameAndType(
-					literalIndex(name.toCharArray()),
-					literalIndex(ProxyClassFile.getConstantPoolName(clazz)));
-			index = fieldCache.put(key, currentIndex++);
-			writeU1(FieldRefTag);
-			writeU2(classIndex);
-			writeU2(nameAndTypeIndex);
-		}
-		return index;
-	} 	
-	
-	int literalIndex(Constructor<?> aMethod) {
-		int index;
-		if ((index = methodCache.get(aMethod)) < 0) {
-			int classIndex = typeIndex(aMethod.getDeclaringClass().getName());
-			int nameAndTypeIndex = literalIndexForNameAndType(
-					literalIndex(Init), literalIndex(ProxyClassFile
-							.getConstantPoolName(aMethod)));
-			index = methodCache.put(aMethod, currentIndex++);
-			writeU1(MethodRefTag);
-			writeU2(classIndex);
-			writeU2(nameAndTypeIndex);
-		}
-		return index;
-	}
-
-	int literalIndex(Method aMethod) {
-		int index;
-		if (aMethod.getDeclaringClass().isInterface()) {
-			if ((index = interfaceMethodCache.get(aMethod)) < 0) {
-				int classIndex = typeIndex(aMethod.getDeclaringClass()
-						.getName());
-				int nameAndTypeIndex = literalIndexForNameAndType(
-						literalIndex(aMethod.getName().toCharArray()),
-						literalIndex(ProxyClassFile
-								.getConstantPoolName(aMethod)));
-				index = interfaceMethodCache.put(aMethod, currentIndex++);
-				writeU1(InterfaceMethodRefTag);
-				writeU2(classIndex);
-				writeU2(nameAndTypeIndex);
-			}
-		} else if ((index = methodCache.get(aMethod)) < 0) {
-			int classIndex = typeIndex(aMethod.getDeclaringClass().getName());
-			int nameAndTypeIndex = literalIndexForNameAndType(
-					literalIndex(aMethod.getName().toCharArray()),
-					literalIndex(ProxyClassFile.getConstantPoolName(aMethod)));
-			index = methodCache.put(aMethod, currentIndex++);
-			writeU1(MethodRefTag);
-			writeU2(classIndex);
-			writeU2(nameAndTypeIndex);
-		}
-		return index;
-	}
-
-	int literalIndex(String stringConstant) {
-		int index;
-		char[] stringCharArray = stringConstant.toCharArray();
-		if ((index = stringCache.get(stringCharArray)) < 0) {
-			int stringIndex = literalIndex(stringCharArray);
-			index = stringCache.put(stringCharArray, currentIndex++);
-			writeU1(StringTag);
-			writeU2(stringIndex);
-		}
-		return index;
-	}
-
-	int literalIndexForLdc(char[] stringCharArray) {
-		int index;
-		if ((index = stringCache.get(stringCharArray)) < 0) {
-			int stringIndex;
-			if ((stringIndex = UTF8Cache.get(stringCharArray)) < 0) {
-				writeU1(Utf8Tag);
-				int savedCurrentOffset = currentOffset;
-				if (currentOffset + 2 >= poolContent.length) {
-					int length = poolContent.length;
-					System.arraycopy(poolContent, 0,
-							(poolContent = new byte[length
-									+ CONSTANTPOOL_GROW_SIZE]), 0, length);
-				}
-				currentOffset += 2;
-				int length = 0;
-				for (int i = 0; i < stringCharArray.length; i++) {
-					char current = stringCharArray[i];
-					if ((current >= 0x0001) && (current <= 0x007F)) {
-						// we only need one byte: ASCII table
-						writeU1(current);
-						length++;
-					} else if (current > 0x07FF) {
-						// we need 3 bytes
-						length += 3;
-						writeU1(0xE0 | ((current >> 12) & 0x0F)); // 0xE0 =
-																	// 1110 0000
-						writeU1(0x80 | ((current >> 6) & 0x3F)); // 0x80 =
-																	// 1000 0000
-						writeU1(0x80 | (current & 0x3F)); // 0x80 = 1000 0000
-					} else {
-						// we can be 0 or between 0x0080 and 0x07FF
-						// In that case we only need 2 bytes
-						length += 2;
-						writeU1(0xC0 | ((current >> 6) & 0x1F)); // 0xC0 =
-																	// 1100 0000
-						writeU1(0x80 | (current & 0x3F)); // 0x80 = 1000 0000
-					}
-				}
-				if (length >= 65535) {
-					currentOffset = savedCurrentOffset - 1;
-					return -1;
-				}
-				stringIndex = UTF8Cache.put(stringCharArray, currentIndex++);
-				// Now we know the length that we have to write in the constant
-				// pool
-				// we use savedCurrentOffset to do that
-				if (length > 65535)
-					return 0;
-				poolContent[savedCurrentOffset] = (byte) (length >> 8);
-				poolContent[savedCurrentOffset + 1] = (byte) length;
-			}
-			index = stringCache.put(stringCharArray, currentIndex++);
-			writeU1(StringTag);
-			writeU2(stringIndex);
-		}
-		return index;
-	}
-
-	 int literalIndexForNameAndType(int nameIndex, int typeIndex) {
-		int index;
-		int[] key = new int[] { nameIndex, typeIndex };
-		if ((index = nameAndTypeCache.get(key)) == -1) {
-			index = nameAndTypeCache.put(key, currentIndex++);
-			writeU1(NameAndTypeTag);
-			writeU2(nameIndex);
-			writeU2(typeIndex);
-		}
-		return index;
-	}
-
-	int typeIndex(String typeName) {
-		int index;
-		if (typeName.indexOf('.') != -1)
-			typeName = typeName.replace('.', '/');
-		char[] charArray = typeName.toCharArray();
-		if ((index = classNameCache.get(charArray)) < 0) {
-			int nameIndex = literalIndex(charArray);
-			index = classNameCache.put(charArray, currentIndex++);
-			writeU1(ClassTag);
-			writeU2(nameIndex);
-		}
-		return index;
-	}
-
-	private final void writeU1(int value) {
-		try {
-			poolContent[currentOffset++] = (byte) value;
-		} catch (IndexOutOfBoundsException e) {
-			// currentOffset has been ++ already (see the -1)
-			int length = poolContent.length;
-			System.arraycopy(poolContent, 0, (poolContent = new byte[length
-					+ CONSTANTPOOL_GROW_SIZE]), 0, length);
-			poolContent[currentOffset - 1] = (byte) value;
-		}
-	}
-
-	private final void writeU2(int value) {
-		try {
-			poolContent[currentOffset++] = (byte) (value >> 8);
-		} catch (IndexOutOfBoundsException e) {
-			// currentOffset has been ++ already (see the -1)
-			int length = poolContent.length;
-			System.arraycopy(poolContent, 0, (poolContent = new byte[length
-					+ CONSTANTPOOL_GROW_SIZE]), 0, length);
-			poolContent[currentOffset - 1] = (byte) (value >> 8);
-		}
-		try {
-			poolContent[currentOffset++] = (byte) value;
-		} catch (IndexOutOfBoundsException e) {
-			// currentOffset has been ++ already (see the -1)
-			int length = poolContent.length;
-			System.arraycopy(poolContent, 0, (poolContent = new byte[length
-					+ CONSTANTPOOL_GROW_SIZE]), 0, length);
-			poolContent[currentOffset - 1] = (byte) value;
-		}
-	}
+    public static final int INTERFACE_INITIAL_SIZE = 21;
+
+    public static final int CLASS_INITIAL_SIZE = 21;
+
+    public static final int NAMEANDTYPE_INITIAL_SIZE = 21;
+
+    public static final int CONSTANTPOOL_INITIAL_SIZE = 500;
+
+    public static final int CONSTANTPOOL_GROW_SIZE = 1000;
+
+    ProxyCharArrayCache UTF8Cache;
+
+    ProxyCharArrayCache stringCache;
+
+    ProxyCharArrayCache classNameCache;
+
+    ProxyObjectCache fieldCache;
+
+    ProxyObjectCache methodCache;
+
+    ProxyObjectCache interfaceMethodCache;
+
+    ProxyNameAndTypeCache nameAndTypeCache;
+
+    byte[] poolContent;
+
+    int currentIndex;
+
+    int currentOffset;
+
+    ProxyConstantPool(ProxyClassFile classFile) {
+        UTF8Cache = new ProxyCharArrayCache(UTF8_INITIAL_SIZE);
+        stringCache = new ProxyCharArrayCache(STRING_INITIAL_SIZE);
+        classNameCache = new ProxyCharArrayCache(CLASS_INITIAL_SIZE);
+        fieldCache = new ProxyObjectCache(FIELD_INITIAL_SIZE);
+        methodCache = new ProxyObjectCache(METHOD_INITIAL_SIZE);
+        interfaceMethodCache = new ProxyObjectCache(INTERFACE_INITIAL_SIZE);
+        nameAndTypeCache = new ProxyNameAndTypeCache(NAMEANDTYPE_INITIAL_SIZE);
+        poolContent = classFile.header;
+        currentOffset = classFile.headerOffset;
+        currentIndex = 1;
+    }
+
+    int literalIndex(char[] utf8Constant) {
+        int index;
+        if ((index = UTF8Cache.get(utf8Constant)) < 0) {
+            writeU1(Utf8Tag);
+            int savedCurrentOffset = currentOffset;
+            if (currentOffset + 2 >= poolContent.length) {
+                int length = poolContent.length;
+                System.arraycopy(poolContent, 0, (poolContent = new byte[length
+                        + CONSTANTPOOL_GROW_SIZE]), 0, length);
+            }
+            currentOffset += 2;
+            int length = 0;
+            for (int i = 0; i < utf8Constant.length; i++) {
+                char current = utf8Constant[i];
+                if ((current >= 0x0001) && (current <= 0x007F)) {
+                    // we only need one byte: ASCII table
+                    writeU1(current);
+                    length++;
+                } else if (current > 0x07FF) {
+                    // we need 3 bytes
+                    length += 3;
+                    writeU1(0xE0 | ((current >> 12) & 0x0F)); // 0xE0 = 1110
+                                                                // 0000
+                    writeU1(0x80 | ((current >> 6) & 0x3F)); // 0x80 = 1000
+                                                                // 0000
+                    writeU1(0x80 | (current & 0x3F)); // 0x80 = 1000 0000
+                } else {
+                    // we can be 0 or between 0x0080 and 0x07FF
+                    // In that case we only need 2 bytes
+                    length += 2;
+                    writeU1(0xC0 | ((current >> 6) & 0x1F)); // 0xC0 = 1100
+                                                                // 0000
+                    writeU1(0x80 | (current & 0x3F)); // 0x80 = 1000 0000
+                }
+            }
+            if (length >= 65535) {
+                currentOffset = savedCurrentOffset - 1;
+                return -1;
+            }
+            index = UTF8Cache.put(utf8Constant, currentIndex++);
+            // Now we know the length that we have to write in the constant pool
+            // we use savedCurrentOffset to do that
+            poolContent[savedCurrentOffset] = (byte) (length >> 8);
+            poolContent[savedCurrentOffset + 1] = (byte) length;
+        }
+        return index;
+    }
+    
+        int literalIndex(Field aField) {    
+            return literalIndex(aField.getDeclaringClass().getName(), aField.getName(), aField.getType());
+    }
+    
+    int literalIndex(String declaringClass, String name, Class clazz) {
+        int index;
+        String key = declaringClass + "." + name;
+        if ((index = fieldCache.get(key)) < 0) {
+            int classIndex = typeIndex(declaringClass);    
+            int nameAndTypeIndex = literalIndexForNameAndType(
+                    literalIndex(name.toCharArray()),
+                    literalIndex(ProxyClassFile.getConstantPoolName(clazz)));
+            index = fieldCache.put(key, currentIndex++);
+            writeU1(FieldRefTag);
+            writeU2(classIndex);
+            writeU2(nameAndTypeIndex);
+        }
+        return index;
+    }     
+    
+    int literalIndex(Constructor<?> aMethod) {
+        int index;
+        if ((index = methodCache.get(aMethod)) < 0) {
+            int classIndex = typeIndex(aMethod.getDeclaringClass().getName());
+            int nameAndTypeIndex = literalIndexForNameAndType(
+                    literalIndex(Init), literalIndex(ProxyClassFile
+                            .getConstantPoolName(aMethod)));
+            index = methodCache.put(aMethod, currentIndex++);
+            writeU1(MethodRefTag);
+            writeU2(classIndex);
+            writeU2(nameAndTypeIndex);
+        }
+        return index;
+    }
+
+    int literalIndex(Method aMethod) {
+        int index;
+        if (aMethod.getDeclaringClass().isInterface()) {
+            if ((index = interfaceMethodCache.get(aMethod)) < 0) {
+                int classIndex = typeIndex(aMethod.getDeclaringClass()
+                        .getName());
+                int nameAndTypeIndex = literalIndexForNameAndType(
+                        literalIndex(aMethod.getName().toCharArray()),
+                        literalIndex(ProxyClassFile
+                                .getConstantPoolName(aMethod)));
+                index = interfaceMethodCache.put(aMethod, currentIndex++);
+                writeU1(InterfaceMethodRefTag);
+                writeU2(classIndex);
+                writeU2(nameAndTypeIndex);
+            }
+        } else if ((index = methodCache.get(aMethod)) < 0) {
+            int classIndex = typeIndex(aMethod.getDeclaringClass().getName());
+            int nameAndTypeIndex = literalIndexForNameAndType(
+                    literalIndex(aMethod.getName().toCharArray()),
+                    literalIndex(ProxyClassFile.getConstantPoolName(aMethod)));
+            index = methodCache.put(aMethod, currentIndex++);
+            writeU1(MethodRefTag);
+            writeU2(classIndex);
+            writeU2(nameAndTypeIndex);
+        }
+        return index;
+    }
+
+    int literalIndex(String stringConstant) {
+        int index;
+        char[] stringCharArray = stringConstant.toCharArray();
+        if ((index = stringCache.get(stringCharArray)) < 0) {
+            int stringIndex = literalIndex(stringCharArray);
+            index = stringCache.put(stringCharArray, currentIndex++);
+            writeU1(StringTag);
+            writeU2(stringIndex);
+        }
+        return index;
+    }
+
+    int literalIndexForLdc(char[] stringCharArray) {
+        int index;
+        if ((index = stringCache.get(stringCharArray)) < 0) {
+            int stringIndex;
+            if ((stringIndex = UTF8Cache.get(stringCharArray)) < 0) {
+                writeU1(Utf8Tag);
+                int savedCurrentOffset = currentOffset;
+                if (currentOffset + 2 >= poolContent.length) {
+                    int length = poolContent.length;
+                    System.arraycopy(poolContent, 0,
+                            (poolContent = new byte[length
+                                    + CONSTANTPOOL_GROW_SIZE]), 0, length);
+                }
+                currentOffset += 2;
+                int length = 0;
+                for (int i = 0; i < stringCharArray.length; i++) {
+                    char current = stringCharArray[i];
+                    if ((current >= 0x0001) && (current <= 0x007F)) {
+                        // we only need one byte: ASCII table
+                        writeU1(current);
+                        length++;
+                    } else if (current > 0x07FF) {
+                        // we need 3 bytes
+                        length += 3;
+                        writeU1(0xE0 | ((current >> 12) & 0x0F)); // 0xE0 =
+                                                                    // 1110 0000
+                        writeU1(0x80 | ((current >> 6) & 0x3F)); // 0x80 =
+                                                                    // 1000 0000
+                        writeU1(0x80 | (current & 0x3F)); // 0x80 = 1000 0000
+                    } else {
+                        // we can be 0 or between 0x0080 and 0x07FF
+                        // In that case we only need 2 bytes
+                        length += 2;
+                        writeU1(0xC0 | ((current >> 6) & 0x1F)); // 0xC0 =
+                                                                    // 1100 0000
+                        writeU1(0x80 | (current & 0x3F)); // 0x80 = 1000 0000
+                    }
+                }
+                if (length >= 65535) {
+                    currentOffset = savedCurrentOffset - 1;
+                    return -1;
+                }
+                stringIndex = UTF8Cache.put(stringCharArray, currentIndex++);
+                // Now we know the length that we have to write in the constant
+                // pool
+                // we use savedCurrentOffset to do that
+                if (length > 65535)
+                    return 0;
+                poolContent[savedCurrentOffset] = (byte) (length >> 8);
+                poolContent[savedCurrentOffset + 1] = (byte) length;
+            }
+            index = stringCache.put(stringCharArray, currentIndex++);
+            writeU1(StringTag);
+            writeU2(stringIndex);
+        }
+        return index;
+    }
+
+     int literalIndexForNameAndType(int nameIndex, int typeIndex) {
+        int index;
+        int[] key = new int[] { nameIndex, typeIndex };
+        if ((index = nameAndTypeCache.get(key)) == -1) {
+            index = nameAndTypeCache.put(key, currentIndex++);
+            writeU1(NameAndTypeTag);
+            writeU2(nameIndex);
+            writeU2(typeIndex);
+        }
+        return index;
+    }
+
+    int typeIndex(String typeName) {
+        int index;
+        if (typeName.indexOf('.') != -1)
+            typeName = typeName.replace('.', '/');
+        char[] charArray = typeName.toCharArray();
+        if ((index = classNameCache.get(charArray)) < 0) {
+            int nameIndex = literalIndex(charArray);
+            index = classNameCache.put(charArray, currentIndex++);
+            writeU1(ClassTag);
+            writeU2(nameIndex);
+        }
+        return index;
+    }
+
+    private final void writeU1(int value) {
+        try {
+            poolContent[currentOffset++] = (byte) value;
+        } catch (IndexOutOfBoundsException e) {
+            // currentOffset has been ++ already (see the -1)
+            int length = poolContent.length;
+            System.arraycopy(poolContent, 0, (poolContent = new byte[length
+                    + CONSTANTPOOL_GROW_SIZE]), 0, length);
+            poolContent[currentOffset - 1] = (byte) value;
+        }
+    }
+
+    private final void writeU2(int value) {
+        try {
+            poolContent[currentOffset++] = (byte) (value >> 8);
+        } catch (IndexOutOfBoundsException e) {
+            // currentOffset has been ++ already (see the -1)
+            int length = poolContent.length;
+            System.arraycopy(poolContent, 0, (poolContent = new byte[length
+                    + CONSTANTPOOL_GROW_SIZE]), 0, length);
+            poolContent[currentOffset - 1] = (byte) (value >> 8);
+        }
+        try {
+            poolContent[currentOffset++] = (byte) value;
+        } catch (IndexOutOfBoundsException e) {
+            // currentOffset has been ++ already (see the -1)
+            int length = poolContent.length;
+            System.arraycopy(poolContent, 0, (poolContent = new byte[length
+                    + CONSTANTPOOL_GROW_SIZE]), 0, length);
+            poolContent[currentOffset - 1] = (byte) value;
+        }
+    }
 }



Mime
View raw message