Merge "Port OpenJDK8 java.lang functional util methods"
diff --git a/benchmarks/src/benchmarks/regression/IntegerBenchmark.java b/benchmarks/src/benchmarks/regression/IntegerBenchmark.java
index f7f97c7..c9614d4 100644
--- a/benchmarks/src/benchmarks/regression/IntegerBenchmark.java
+++ b/benchmarks/src/benchmarks/regression/IntegerBenchmark.java
@@ -133,4 +133,16 @@
         }
         return t;
     }
+
+    public int timeIntegerValueOf(int reps) throws Exception {
+        String[] intStrings = new String[]{"0", "1", "12", "123", "1234", "12345",
+                                           "123456", "1234567", "12345678"};
+        int t = 0;
+        for (int i = 0; i < reps; ++i) {
+            for (int j = 0; j < intStrings.length; ++j) {
+                t += Integer.valueOf(intStrings[j]);
+            }
+        }
+        return t;
+    }
 }
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/Arrays2Test.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/Arrays2Test.java
index a61e343..3caf588 100644
--- a/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/Arrays2Test.java
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/Arrays2Test.java
@@ -486,4 +486,21 @@
             fail();
         } catch(NullPointerException expected) {}
     }
+
+    public void test_replaceAll() throws Exception {
+        List<Integer> list = Arrays.asList(0, 1, 2);
+        list.replaceAll(k -> k + 1);
+        assertEquals((Integer)1, list.get(0));
+        assertEquals((Integer)2, list.get(1));
+        assertEquals((Integer)3, list.get(2));
+        assertEquals(3, list.size());
+    }
+
+    public void test_replaceAll_NPE() throws Exception {
+        List<Integer> list = Arrays.asList(0, 1, 2);
+        try {
+            list.replaceAll(null);
+            fail();
+        } catch(NullPointerException expected) {}
+    }
 }
diff --git a/luni/src/test/java/libcore/java/nio/channels/DatagramChannelTest.java b/luni/src/test/java/libcore/java/nio/channels/DatagramChannelTest.java
index 609a990..5169e9b 100644
--- a/luni/src/test/java/libcore/java/nio/channels/DatagramChannelTest.java
+++ b/luni/src/test/java/libcore/java/nio/channels/DatagramChannelTest.java
@@ -17,6 +17,7 @@
 package libcore.java.nio.channels;
 
 import java.io.IOException;
+import java.net.BindException;
 import java.net.DatagramSocket;
 import java.net.Inet4Address;
 import java.net.Inet6Address;
@@ -25,10 +26,9 @@
 import java.net.NetworkInterface;
 import java.net.StandardSocketOptions;
 import java.nio.ByteBuffer;
+import java.nio.channels.AlreadyBoundException;
 import java.nio.channels.ClosedChannelException;
 import java.nio.channels.DatagramChannel;
-import java.nio.channels.SocketChannel;
-import java.nio.channels.UnresolvedAddressException;
 import java.util.Enumeration;
 import java.util.Set;
 
@@ -181,6 +181,49 @@
         assertNotNull(socket.getFileDescriptor$());
     }
 
+    public void test_bind() throws IOException {
+        InetSocketAddress socketAddress = new InetSocketAddress(Inet4Address.LOOPBACK, 0);
+        DatagramChannel channel = DatagramChannel.open();
+        channel.bind(socketAddress);
+        assertEquals(socketAddress.getAddress(),
+                ((InetSocketAddress)(channel.getLocalAddress())).getAddress());
+        assertTrue(((InetSocketAddress)(channel.getLocalAddress())).getPort() > 0);
+
+        try {
+            channel.bind(socketAddress);
+            fail();
+        } catch (AlreadyBoundException expected) {
+        }
+
+        socketAddress = new InetSocketAddress(Inet4Address.LOOPBACK,
+                ((InetSocketAddress)(channel.getLocalAddress())).getPort());
+        try {
+            DatagramChannel.open().bind(socketAddress);
+            fail();
+        } catch (BindException expected) {}
+
+        channel.close();
+        socketAddress = new InetSocketAddress(Inet4Address.LOOPBACK, 0);
+        try {
+            channel.bind(socketAddress);
+        } catch (ClosedChannelException expected) {}
+    }
+
+    public void test_getRemoteAddress() throws IOException {
+        InetSocketAddress socketAddress = new InetSocketAddress(Inet4Address.LOOPBACK, 0);
+        DatagramChannel clientChannel = DatagramChannel.open();
+        DatagramChannel serverChannel = DatagramChannel.open();
+        serverChannel.bind(socketAddress);
+
+        assertNull(clientChannel.getRemoteAddress());
+
+        clientChannel.connect(serverChannel.getLocalAddress());
+        assertEquals(socketAddress.getAddress(),
+                ((InetSocketAddress)(clientChannel.getRemoteAddress())).getAddress());
+        assertEquals(((InetSocketAddress)(serverChannel.getLocalAddress())).getPort(),
+                ((InetSocketAddress)(clientChannel.getRemoteAddress())).getPort());
+    }
+
     private static InetAddress getNonLoopbackNetworkInterfaceAddress(boolean ipv4) throws IOException {
         Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
         while (networkInterfaces.hasMoreElements()) {
diff --git a/luni/src/test/java/libcore/java/nio/channels/ServerSocketChannelTest.java b/luni/src/test/java/libcore/java/nio/channels/ServerSocketChannelTest.java
index 1178b70..113779d 100644
--- a/luni/src/test/java/libcore/java/nio/channels/ServerSocketChannelTest.java
+++ b/luni/src/test/java/libcore/java/nio/channels/ServerSocketChannelTest.java
@@ -22,10 +22,13 @@
 import java.net.NetworkInterface;
 import java.net.ServerSocket;
 import java.net.SocketException;
+import java.net.StandardSocketOptions;
+import java.nio.channels.AlreadyBoundException;
 import java.nio.channels.ClosedChannelException;
 import java.nio.channels.ServerSocketChannel;
 import java.nio.channels.SocketChannel;
 import java.nio.channels.UnresolvedAddressException;
+import java.nio.channels.UnsupportedAddressTypeException;
 import java.util.Enumeration;
 import java.util.Set;
 
@@ -136,6 +139,58 @@
         ssc.close();
     }
 
+    public void test_bind$SocketAddress() throws IOException {
+        ServerSocketChannel ssc = ServerSocketChannel.open();
+        ssc.bind(new InetSocketAddress(InetAddress.getLoopbackAddress(), 0));
+        assertEquals(InetAddress.getLoopbackAddress(),
+                ((InetSocketAddress)(ssc.getLocalAddress())).getAddress());
+        assertTrue(((InetSocketAddress)(ssc.getLocalAddress())).getPort() > 0);
+
+        try {
+            ssc.bind(new InetSocketAddress(InetAddress.getLoopbackAddress(),
+                    ((InetSocketAddress)(ssc.getLocalAddress())).getPort()));
+            fail();
+        } catch (AlreadyBoundException expected) {
+        }
+
+        try {
+            ServerSocketChannel ssc1 = ServerSocketChannel.open();
+            ssc1.bind(new InetSocketAddress("1.1.1.1.1.1.1", 0));
+            fail();
+        } catch (UnresolvedAddressException expected) {
+        }
+
+        ssc.close();
+        try {
+            ssc.bind(new InetSocketAddress("1.1.1.1.1.1.1", 0));
+            fail();
+        } catch (ClosedChannelException expected) {
+        }
+    }
+
+    public void test_setOption() throws Exception {
+        ServerSocketChannel sc = ServerSocketChannel.open();
+        sc.setOption(StandardSocketOptions.SO_REUSEADDR, true);
+
+        // Assert that we can read back the option from the channel...
+        assertTrue(sc.getOption(StandardSocketOptions.SO_REUSEADDR));
+
+        sc.setOption(StandardSocketOptions.SO_REUSEADDR, false);
+
+        // Assert that we can read back the option from the channel...
+        assertEquals(false, (boolean)sc.getOption(StandardSocketOptions.SO_REUSEADDR));
+
+        sc.setOption(StandardSocketOptions.SO_RCVBUF, 1100);
+        assertTrue(1100 <= sc.getOption(StandardSocketOptions.SO_RCVBUF));
+
+        sc.close();
+        try {
+            sc.setOption(StandardSocketOptions.SO_RCVBUF, 2000);
+            fail();
+        } catch (ClosedChannelException expected) {
+        }
+    }
+
     private static boolean canConnect(InetSocketAddress address) {
         try {
             SocketChannel socketChannel = SocketChannel.open(address);
diff --git a/luni/src/test/java/libcore/java/nio/channels/SocketChannelTest.java b/luni/src/test/java/libcore/java/nio/channels/SocketChannelTest.java
index d31b222..72609ee 100644
--- a/luni/src/test/java/libcore/java/nio/channels/SocketChannelTest.java
+++ b/luni/src/test/java/libcore/java/nio/channels/SocketChannelTest.java
@@ -20,278 +20,378 @@
 import java.io.InputStream;
 import java.io.OutputStream;
 import java.lang.reflect.Field;
+import java.net.BindException;
 import java.net.ConnectException;
-import java.net.Socket;
-import java.net.SocketImpl;
+import java.net.Inet4Address;
 import java.net.InetAddress;
 import java.net.InetSocketAddress;
 import java.net.ServerSocket;
+import java.net.Socket;
+import java.net.SocketImpl;
 import java.net.StandardSocketOptions;
 import java.nio.ByteBuffer;
+import java.nio.channels.AlreadyBoundException;
 import java.nio.channels.ClosedChannelException;
-import java.nio.channels.SocketChannel;
-import java.nio.channels.Selector;
+import java.nio.channels.NotYetConnectedException;
 import java.nio.channels.SelectionKey;
-import java.nio.channels.UnresolvedAddressException;
-import java.util.Set;
-
-import static android.system.OsConstants.*;
+import java.nio.channels.Selector;
+import java.nio.channels.SocketChannel;
 
 public class SocketChannelTest extends junit.framework.TestCase {
 
-  public void test_read_intoReadOnlyByteArrays() throws Exception {
-    ByteBuffer readOnly = ByteBuffer.allocate(1).asReadOnlyBuffer();
-    ServerSocket ss = new ServerSocket(0);
-    ss.setReuseAddress(true);
-    SocketChannel sc = SocketChannel.open(ss.getLocalSocketAddress());
-    try {
-      sc.read(readOnly);
-      fail();
-    } catch (IllegalArgumentException expected) {
-    }
-    try {
-      sc.read(new ByteBuffer[] { readOnly });
-      fail();
-    } catch (IllegalArgumentException expected) {
-    }
-    try {
-      sc.read(new ByteBuffer[] { readOnly }, 0, 1);
-      fail();
-    } catch (IllegalArgumentException expected) {
-    }
-  }
-
-  // https://code.google.com/p/android/issues/detail?id=56684
-  public void test_56684() throws Exception {
-    SocketChannel sc = SocketChannel.open();
-    sc.configureBlocking(false);
-
-    Selector selector = Selector.open();
-    SelectionKey selectionKey = sc.register(selector, SelectionKey.OP_CONNECT);
-
-    try {
-      // This test originally mocked the connect syscall to return ENETUNREACH.
-      // This is not easily doable in openJdk libcore, but a connect to broadcast
-      // address (255.255.255.255) for a TCP connection produces ENETUNREACH
-      // Kernel code that does it is at
-      // http://lxr.free-electrons.com/source/net/ipv4/tcp_ipv4.c?v=3.18#L182
-      sc.connect(new InetSocketAddress(InetAddress.getByAddress(new byte[] {
-                    (byte) 255, (byte) 255, (byte)255, (byte)255 }), 0));
-      fail();
-    } catch (ConnectException ex) {
+    public void test_read_intoReadOnlyByteArrays() throws Exception {
+        ByteBuffer readOnly = ByteBuffer.allocate(1).asReadOnlyBuffer();
+        ServerSocket ss = new ServerSocket(0);
+        ss.setReuseAddress(true);
+        SocketChannel sc = SocketChannel.open(ss.getLocalSocketAddress());
+        try {
+            sc.read(readOnly);
+            fail();
+        } catch (IllegalArgumentException expected) {
+        }
+        try {
+            sc.read(new ByteBuffer[] { readOnly });
+            fail();
+        } catch (IllegalArgumentException expected) {
+        }
+        try {
+            sc.read(new ByteBuffer[] { readOnly }, 0, 1);
+            fail();
+        } catch (IllegalArgumentException expected) {
+        }
     }
 
-    try {
-      sc.finishConnect();
-      fail();
-    } catch (ClosedChannelException expected) {
-    }
-  }
+    // https://code.google.com/p/android/issues/detail?id=56684
+    public void test_56684() throws Exception {
+        SocketChannel sc = SocketChannel.open();
+        sc.configureBlocking(false);
 
-  /** Checks that closing a Socket's output stream also closes the Socket and SocketChannel. */
-  public void test_channelSocketOutputStreamClosureState() throws Exception {
-    ServerSocket ss = new ServerSocket(0);
+        Selector selector = Selector.open();
+        SelectionKey selectionKey = sc.register(selector, SelectionKey.OP_CONNECT);
 
-    SocketChannel sc = SocketChannel.open(ss.getLocalSocketAddress());
-    sc.configureBlocking(true);
+        try {
+            // This test originally mocked the connect syscall to return ENETUNREACH.
+            // This is not easily doable in openJdk libcore, but a connect to broadcast
+            // address (255.255.255.255) for a TCP connection produces ENETUNREACH
+            // Kernel code that does it is at
+            // http://lxr.free-electrons.com/source/net/ipv4/tcp_ipv4.c?v=3.18#L182
+            sc.connect(new InetSocketAddress(InetAddress.getByAddress(new byte[] {
+                    (byte) 255, (byte) 255, (byte) 255, (byte) 255 }), 0));
+            fail();
+        } catch (ConnectException ex) {
+        }
 
-    Socket scSocket = sc.socket();
-    OutputStream os = scSocket.getOutputStream();
-
-    assertTrue(sc.isOpen());
-    assertFalse(scSocket.isClosed());
-
-    os.close();
-
-    assertFalse(sc.isOpen());
-    assertTrue(scSocket.isClosed());
-
-    ss.close();
-  }
-
-  /** Checks that closing a Socket's input stream also closes the Socket and SocketChannel. */
-  public void test_channelSocketInputStreamClosureState() throws Exception {
-    ServerSocket ss = new ServerSocket(0);
-
-    SocketChannel sc = SocketChannel.open(ss.getLocalSocketAddress());
-    sc.configureBlocking(true);
-
-    Socket scSocket = sc.socket();
-    InputStream is = scSocket.getInputStream();
-
-    assertTrue(sc.isOpen());
-    assertFalse(scSocket.isClosed());
-
-    is.close();
-
-    assertFalse(sc.isOpen());
-    assertTrue(scSocket.isClosed());
-
-    ss.close();
-  }
-
-  /** Checks the state of the SocketChannel and associated Socket after open() */
-  public void test_open_initialState() throws Exception {
-    SocketChannel sc = SocketChannel.open();
-    try {
-      assertNull(sc.socket().getLocalSocketAddress());
-
-      Socket socket = sc.socket();
-      assertFalse(socket.isBound());
-      assertFalse(socket.isClosed());
-      assertFalse(socket.isConnected());
-      assertEquals(-1, socket.getLocalPort());
-      assertTrue(socket.getLocalAddress().isAnyLocalAddress());
-      assertNull(socket.getLocalSocketAddress());
-      assertNull(socket.getInetAddress());
-      assertEquals(0, socket.getPort());
-      assertNull(socket.getRemoteSocketAddress());
-      assertFalse(socket.getReuseAddress());
-
-      assertSame(sc, socket.getChannel());
-    } finally {
-      sc.close();
-    }
-  }
-
-  public void test_bind_unresolvedAddress() throws IOException {
-    SocketChannel sc = SocketChannel.open();
-    try {
-      sc.socket().bind(new InetSocketAddress("unresolvedname", 31415));
-      fail();
-    } catch (IOException expected) {
+        try {
+            sc.finishConnect();
+            fail();
+        } catch (ClosedChannelException expected) {
+        }
     }
 
-    assertNull(sc.socket().getLocalSocketAddress());
-    assertTrue(sc.isOpen());
-    assertFalse(sc.isConnected());
+    /** Checks that closing a Socket's output stream also closes the Socket and SocketChannel. */
+    public void test_channelSocketOutputStreamClosureState() throws Exception {
+        ServerSocket ss = new ServerSocket(0);
 
-    sc.close();
-  }
+        SocketChannel sc = SocketChannel.open(ss.getLocalSocketAddress());
+        sc.configureBlocking(true);
 
-  /** Checks that the SocketChannel and associated Socket agree on the socket state. */
-  public void test_bind_socketStateSync() throws IOException {
-    SocketChannel sc = SocketChannel.open();
-    assertNull(sc.socket().getLocalSocketAddress());
+        Socket scSocket = sc.socket();
+        OutputStream os = scSocket.getOutputStream();
 
-    Socket socket = sc.socket();
-    assertNull(socket.getLocalSocketAddress());
-    assertFalse(socket.isBound());
+        assertTrue(sc.isOpen());
+        assertFalse(scSocket.isClosed());
 
-    InetSocketAddress bindAddr = new InetSocketAddress("localhost", 0);
-    sc.socket().bind(bindAddr);
+        os.close();
 
-    InetSocketAddress actualAddr = (InetSocketAddress) sc.socket().getLocalSocketAddress();
-    assertEquals(actualAddr, socket.getLocalSocketAddress());
-    assertEquals(bindAddr.getHostName(), actualAddr.getHostName());
-    assertTrue(socket.isBound());
-    assertFalse(socket.isConnected());
-    assertFalse(socket.isClosed());
+        assertFalse(sc.isOpen());
+        assertTrue(scSocket.isClosed());
 
-    sc.close();
+        ss.close();
+    }
 
-    assertFalse(sc.isOpen());
-    assertTrue(socket.isClosed());
-  }
+    /** Checks that closing a Socket's input stream also closes the Socket and SocketChannel. */
+    public void test_channelSocketInputStreamClosureState() throws Exception {
+        ServerSocket ss = new ServerSocket(0);
 
-  /**
-   * Checks that the SocketChannel and associated Socket agree on the socket state, even if
-   * the Socket object is requested/created after bind().
-   */
-  public void test_bind_socketObjectCreationAfterBind() throws IOException {
-    SocketChannel sc = SocketChannel.open();
-    assertNull(sc.socket().getLocalSocketAddress());
+        SocketChannel sc = SocketChannel.open(ss.getLocalSocketAddress());
+        sc.configureBlocking(true);
 
-    InetSocketAddress bindAddr = new InetSocketAddress("localhost", 0);
-    sc.socket().bind(bindAddr);
+        Socket scSocket = sc.socket();
+        InputStream is = scSocket.getInputStream();
 
-    // Socket object creation after bind().
-    Socket socket = sc.socket();
-    InetSocketAddress actualAddr = (InetSocketAddress) sc.socket().getLocalSocketAddress();
-    assertEquals(actualAddr, socket.getLocalSocketAddress());
-    assertEquals(bindAddr.getHostName(), actualAddr.getHostName());
-    assertTrue(socket.isBound());
-    assertFalse(socket.isConnected());
-    assertFalse(socket.isClosed());
+        assertTrue(sc.isOpen());
+        assertFalse(scSocket.isClosed());
 
-    sc.close();
+        is.close();
 
-    assertFalse(sc.isOpen());
-    assertTrue(socket.isClosed());
-  }
+        assertFalse(sc.isOpen());
+        assertTrue(scSocket.isClosed());
 
-  /**
-   * Tests connect() and object state for a blocking SocketChannel. Blocking mode is the default.
-   */
-  public void test_connect_blocking() throws Exception {
-    ServerSocket ss = new ServerSocket(0);
+        ss.close();
+    }
 
-    SocketChannel sc = SocketChannel.open();
-    assertTrue(sc.isBlocking());
+    /** Checks the state of the SocketChannel and associated Socket after open() */
+    public void test_open_initialState() throws Exception {
+        SocketChannel sc = SocketChannel.open();
+        try {
+            assertNull(sc.socket().getLocalSocketAddress());
 
-    assertTrue(sc.connect(ss.getLocalSocketAddress()));
+            Socket socket = sc.socket();
+            assertFalse(socket.isBound());
+            assertFalse(socket.isClosed());
+            assertFalse(socket.isConnected());
+            assertEquals(-1, socket.getLocalPort());
+            assertTrue(socket.getLocalAddress().isAnyLocalAddress());
+            assertNull(socket.getLocalSocketAddress());
+            assertNull(socket.getInetAddress());
+            assertEquals(0, socket.getPort());
+            assertNull(socket.getRemoteSocketAddress());
+            assertFalse(socket.getReuseAddress());
 
-    assertTrue(sc.socket().isBound());
-    assertTrue(sc.isConnected());
-    assertTrue(sc.socket().isConnected());
-    assertFalse(sc.socket().isClosed());
-    assertTrue(sc.isBlocking());
+            assertSame(sc, socket.getChannel());
+        } finally {
+            sc.close();
+        }
+    }
 
-    ss.close();
-    sc.close();
-  }
+    public void test_bind_unresolvedAddress() throws IOException {
+        SocketChannel sc = SocketChannel.open();
+        try {
+            sc.socket().bind(new InetSocketAddress("unresolvedname", 31415));
+            fail();
+        } catch (IOException expected) {
+        }
 
-  /** Tests connect() and object state for a non-blocking SocketChannel. */
-  public void test_connect_nonBlocking() throws Exception {
-    ServerSocket ss = new ServerSocket(0);
-
-    SocketChannel sc = SocketChannel.open();
-    assertTrue(sc.isBlocking());
-    sc.configureBlocking(false);
-    assertFalse(sc.isBlocking());
-
-    if (!sc.connect(ss.getLocalSocketAddress())) {
-      do {
-        assertTrue(sc.socket().isBound());
+        assertNull(sc.socket().getLocalSocketAddress());
+        assertTrue(sc.isOpen());
         assertFalse(sc.isConnected());
-        assertFalse(sc.socket().isConnected());
+
+        sc.close();
+    }
+
+    /** Checks that the SocketChannel and associated Socket agree on the socket state. */
+    public void test_bind_socketStateSync() throws IOException {
+        SocketChannel sc = SocketChannel.open();
+        assertNull(sc.socket().getLocalSocketAddress());
+
+        Socket socket = sc.socket();
+        assertNull(socket.getLocalSocketAddress());
+        assertFalse(socket.isBound());
+
+        InetSocketAddress bindAddr = new InetSocketAddress("localhost", 0);
+        sc.socket().bind(bindAddr);
+
+        InetSocketAddress actualAddr = (InetSocketAddress) sc.socket().getLocalSocketAddress();
+        assertEquals(actualAddr, socket.getLocalSocketAddress());
+        assertEquals(bindAddr.getHostName(), actualAddr.getHostName());
+        assertTrue(socket.isBound());
+        assertFalse(socket.isConnected());
+        assertFalse(socket.isClosed());
+
+        sc.close();
+
+        assertFalse(sc.isOpen());
+        assertTrue(socket.isClosed());
+    }
+
+    /**
+     * Checks that the SocketChannel and associated Socket agree on the socket state, even if
+     * the Socket object is requested/created after bind().
+     */
+    public void test_bind_socketObjectCreationAfterBind() throws IOException {
+        SocketChannel sc = SocketChannel.open();
+        assertNull(sc.socket().getLocalSocketAddress());
+
+        InetSocketAddress bindAddr = new InetSocketAddress("localhost", 0);
+        sc.socket().bind(bindAddr);
+
+        // Socket object creation after bind().
+        Socket socket = sc.socket();
+        InetSocketAddress actualAddr = (InetSocketAddress) sc.socket().getLocalSocketAddress();
+        assertEquals(actualAddr, socket.getLocalSocketAddress());
+        assertEquals(bindAddr.getHostName(), actualAddr.getHostName());
+        assertTrue(socket.isBound());
+        assertFalse(socket.isConnected());
+        assertFalse(socket.isClosed());
+
+        sc.close();
+
+        assertFalse(sc.isOpen());
+        assertTrue(socket.isClosed());
+    }
+
+    /**
+     * Tests connect() and object state for a blocking SocketChannel. Blocking mode is the default.
+     */
+    public void test_connect_blocking() throws Exception {
+        ServerSocket ss = new ServerSocket(0);
+
+        SocketChannel sc = SocketChannel.open();
+        assertTrue(sc.isBlocking());
+
+        assertTrue(sc.connect(ss.getLocalSocketAddress()));
+
+        assertTrue(sc.socket().isBound());
+        assertTrue(sc.isConnected());
+        assertTrue(sc.socket().isConnected());
         assertFalse(sc.socket().isClosed());
-      } while (!sc.finishConnect());
+        assertTrue(sc.isBlocking());
+
+        ss.close();
+        sc.close();
     }
-    assertTrue(sc.socket().isBound());
-    assertTrue(sc.isConnected());
-    assertTrue(sc.socket().isConnected());
-    assertFalse(sc.socket().isClosed());
-    assertFalse(sc.isBlocking());
 
-    ss.close();
-    sc.close();
-  }
+    /** Tests connect() and object state for a non-blocking SocketChannel. */
+    public void test_connect_nonBlocking() throws Exception {
+        ServerSocket ss = new ServerSocket(0);
 
-  public void test_Socket_impl_notNull() throws Exception {
-    SocketChannel sc = SocketChannel.open();
-    Socket socket = sc.socket();
-    Field f_impl = Socket.class.getDeclaredField("impl");
-    f_impl.setAccessible(true);
-    Object implFieldValue = f_impl.get(socket);
-    assertNotNull(implFieldValue);
-    assertTrue(implFieldValue instanceof SocketImpl);
-  }
+        SocketChannel sc = SocketChannel.open();
+        assertTrue(sc.isBlocking());
+        sc.configureBlocking(false);
+        assertFalse(sc.isBlocking());
 
-  public void test_setOption() throws Exception {
-    SocketChannel sc = SocketChannel.open();
-    sc.setOption(StandardSocketOptions.SO_LINGER, 1000);
+        if (!sc.connect(ss.getLocalSocketAddress())) {
+            do {
+                assertTrue(sc.socket().isBound());
+                assertFalse(sc.isConnected());
+                assertFalse(sc.socket().isConnected());
+                assertFalse(sc.socket().isClosed());
+            } while (!sc.finishConnect());
+        }
+        assertTrue(sc.socket().isBound());
+        assertTrue(sc.isConnected());
+        assertTrue(sc.socket().isConnected());
+        assertFalse(sc.socket().isClosed());
+        assertFalse(sc.isBlocking());
 
-    // Assert that we can read back the option from the channel...
-    assertEquals(1000, (int) sc.<Integer>getOption(StandardSocketOptions.SO_LINGER));
-    // ... and its socket adaptor.
-    assertEquals(1000, sc.socket().getSoLinger());
-
-    sc.close();
-    try {
-        sc.setOption(StandardSocketOptions.SO_LINGER, 2000);
-        fail();
-    } catch (ClosedChannelException expected) {
+        ss.close();
+        sc.close();
     }
-  }
+
+    public void test_Socket_impl_notNull() throws Exception {
+        SocketChannel sc = SocketChannel.open();
+        Socket socket = sc.socket();
+        Field f_impl = Socket.class.getDeclaredField("impl");
+        f_impl.setAccessible(true);
+        Object implFieldValue = f_impl.get(socket);
+        assertNotNull(implFieldValue);
+        assertTrue(implFieldValue instanceof SocketImpl);
+    }
+
+    public void test_setOption() throws Exception {
+        SocketChannel sc = SocketChannel.open();
+        sc.setOption(StandardSocketOptions.SO_LINGER, 1000);
+
+        // Assert that we can read back the option from the channel...
+        assertEquals(1000, (int) sc.<Integer>getOption(StandardSocketOptions.SO_LINGER));
+        // ... and its socket adaptor.
+        assertEquals(1000, sc.socket().getSoLinger());
+
+        sc.close();
+        try {
+            sc.setOption(StandardSocketOptions.SO_LINGER, 2000);
+            fail();
+        } catch (ClosedChannelException expected) {
+        }
+    }
+
+    public void test_bind() throws IOException {
+        InetSocketAddress socketAddress = new InetSocketAddress(Inet4Address.LOOPBACK, 0);
+        SocketChannel sc = SocketChannel.open();
+        sc.bind(socketAddress);
+        assertEquals(socketAddress.getAddress(),
+                ((InetSocketAddress) (sc.getLocalAddress())).getAddress());
+        assertTrue(((InetSocketAddress) (sc.getLocalAddress())).getPort() > 0);
+
+        try {
+            sc.bind(socketAddress);
+            fail();
+        } catch (AlreadyBoundException expected) {
+        }
+
+        socketAddress = new InetSocketAddress(Inet4Address.LOOPBACK,
+                ((InetSocketAddress) (sc.getLocalAddress())).getPort());
+        try {
+            SocketChannel.open().bind(socketAddress);
+            fail();
+        } catch (BindException expected) {
+        }
+
+        sc.close();
+        socketAddress = new InetSocketAddress(Inet4Address.LOOPBACK, 0);
+        try {
+            sc.bind(socketAddress);
+        } catch (ClosedChannelException expected) {
+        }
+    }
+
+    public void test_getRemoteAddress() throws IOException {
+        SocketChannel sc = SocketChannel.open();
+        ServerSocket ss = new ServerSocket(0);
+
+        assertNull(sc.getRemoteAddress());
+
+        sc.connect(ss.getLocalSocketAddress());
+        assertEquals(sc.getRemoteAddress(), ss.getLocalSocketAddress());
+    }
+
+    public void test_shutdownInput() throws IOException {
+        SocketChannel channel1 = SocketChannel.open();
+        ServerSocket server1 = new ServerSocket(0);
+        InetSocketAddress localAddr1 = new InetSocketAddress("127.0.0.1", server1.getLocalPort());
+
+        // initialize write content
+        byte[] writeContent = new byte[10];
+        for (int i = 0; i < writeContent.length; i++) {
+            writeContent[i] = (byte) i;
+        }
+
+        // establish connection
+        channel1.connect(localAddr1);
+        Socket acceptedSocket = server1.accept();
+        // use OutputStream.write to write bytes data.
+        OutputStream out = acceptedSocket.getOutputStream();
+        out.write(writeContent);
+        // use close to guarantee all data is sent
+        acceptedSocket.close();
+
+        channel1.configureBlocking(false);
+        ByteBuffer readContent = ByteBuffer.allocate(10 + 1);
+        channel1.shutdownInput();
+        assertEquals(-1, channel1.read(readContent));
+    }
+
+    public void test_shutdownOutput() throws IOException {
+        SocketChannel channel1 = SocketChannel.open();
+        ServerSocket server1 = new ServerSocket(0);
+        InetSocketAddress localAddr1 = new InetSocketAddress("127.0.0.1", server1.getLocalPort());
+
+        // initialize write content
+        ByteBuffer writeContent = ByteBuffer.allocate(10);
+        for (int i = 0; i < 10; i++) {
+            writeContent.put((byte) i);
+        }
+        writeContent.flip();
+
+        try {
+            channel1.shutdownOutput();
+            fail();
+        } catch (NotYetConnectedException expected) {}
+
+        // establish connection
+        channel1.connect(localAddr1);
+        channel1.shutdownOutput();
+
+        try {
+            channel1.write(writeContent);
+            fail();
+        } catch (ClosedChannelException expected) {}
+
+        channel1.close();
+
+        try {
+            channel1.shutdownOutput();
+            fail();
+        } catch(ClosedChannelException expected) {}
+    }
 }
diff --git a/luni/src/test/java/libcore/java/text/DecimalFormatTest.java b/luni/src/test/java/libcore/java/text/DecimalFormatTest.java
index 2b8b566..0eae20a 100644
--- a/luni/src/test/java/libcore/java/text/DecimalFormatTest.java
+++ b/luni/src/test/java/libcore/java/text/DecimalFormatTest.java
@@ -283,13 +283,6 @@
         assertEquals(expected, numberFormat.format(2.01));
     }
 
-    // http://b/27855939
-    public void testBug27855939() {
-        DecimalFormat df = new DecimalFormat("00");
-        assertEquals("01", df.format(BigDecimal.ONE));
-        assertEquals("00", df.format(BigDecimal.ZERO));
-    }
-
     // Confirm the currency symbol used by a format is determined by the locale of the format
     // not the current default Locale.
     public void testSetCurrency_symbolOrigin() {
diff --git a/ojluni/src/main/java/java/lang/Character.java b/ojluni/src/main/java/java/lang/Character.java
index bb69d91..5b9038a 100755
--- a/ojluni/src/main/java/java/lang/Character.java
+++ b/ojluni/src/main/java/java/lang/Character.java
@@ -6458,6 +6458,21 @@
      * @since   1.5
      */
     public static int digit(int codePoint, int radix) {
+        if (radix < MIN_RADIX || radix > MAX_RADIX) {
+            return -1;
+        }
+        if (codePoint < 128) {
+            // Optimized for ASCII
+            int result = -1;
+            if ('0' <= codePoint && codePoint <= '9') {
+                result = codePoint - '0';
+            } else if ('a' <= codePoint && codePoint <= 'z') {
+                result = 10 + (codePoint - 'a');
+            } else if ('A' <= codePoint && codePoint <= 'Z') {
+                result = 10 + (codePoint - 'A');
+            }
+            return result < radix ? result : -1;
+        }
         return digitImpl(codePoint, radix);
     }
 
diff --git a/ojluni/src/main/java/java/nio/channels/ServerSocketChannel.java b/ojluni/src/main/java/java/nio/channels/ServerSocketChannel.java
index 127fb5b..63ed42f 100755
--- a/ojluni/src/main/java/java/nio/channels/ServerSocketChannel.java
+++ b/ojluni/src/main/java/java/nio/channels/ServerSocketChannel.java
@@ -138,7 +138,7 @@
      * @return  This channel
      *
      * @throws  AlreadyBoundException               {@inheritDoc}
-     * @throws  UnsupportedAddressTypeException     {@inheritDoc}
+     * @throws  UnresolvedAddressException
      * @throws  ClosedChannelException              {@inheritDoc}
      * @throws  IOException                         {@inheritDoc}
      * @throws  SecurityException
diff --git a/ojluni/src/main/java/java/util/Arrays.java b/ojluni/src/main/java/java/util/Arrays.java
index 6274b45..38980df 100755
--- a/ojluni/src/main/java/java/util/Arrays.java
+++ b/ojluni/src/main/java/java/util/Arrays.java
@@ -33,6 +33,7 @@
 import java.util.function.IntToDoubleFunction;
 import java.util.function.IntToLongFunction;
 import java.util.function.IntUnaryOperator;
+import java.util.function.UnaryOperator;
 import java.util.stream.DoubleStream;
 import java.util.stream.IntStream;
 import java.util.stream.LongStream;
@@ -3696,6 +3697,15 @@
         }
 
         @Override
+        public void replaceAll(UnaryOperator<E> operator) {
+            Objects.requireNonNull(operator);
+            E[] a = this.a;
+            for (int i = 0; i < a.length; i++) {
+                a[i] = operator.apply(a[i]);
+            }
+        }
+
+        @Override
         public Spliterator<E> spliterator() {
             return Spliterators.spliterator(a, Spliterator.ORDERED);
         }
diff --git a/ojluni/src/main/java/java/util/stream/LongStream.java b/ojluni/src/main/java/java/util/stream/LongStream.java
index 33d74ec..84189ef 100644
--- a/ojluni/src/main/java/java/util/stream/LongStream.java
+++ b/ojluni/src/main/java/java/util/stream/LongStream.java
@@ -24,6 +24,7 @@
  */
 package java.util.stream;
 
+import java.math.BigInteger;
 import java.nio.charset.Charset;
 import java.util.Arrays;
 import java.util.Collection;
@@ -790,8 +791,11 @@
             // Split the range in two and concatenate
             // Note: if the range is [Long.MIN_VALUE, Long.MAX_VALUE) then
             // the lower range, [Long.MIN_VALUE, 0) will be further split in two
-            // Android-changed: no divideUnsigned support yet
-            long m = startInclusive + ((endExclusive - startInclusive) / 2) + 1;
+            // Android-changed: no divideUnsigned support yet, use BigInteger instead.
+            long m = startInclusive +
+                BigInteger.valueOf(endExclusive).subtract(BigInteger.valueOf(startInclusive))
+                     .divide(BigInteger.valueOf(2)).longValue() + 1;
+
             return concat(range(startInclusive, m), range(m, endExclusive));
         } else {
             return StreamSupport.longStream(
@@ -825,8 +829,11 @@
             // Note: if the range is [Long.MIN_VALUE, Long.MAX_VALUE] then
             // the lower range, [Long.MIN_VALUE, 0), and upper range,
             // [0, Long.MAX_VALUE], will both be further split in two
-            // Android-changed: no divideUnsigned support yet
-            long m = startInclusive + ((endInclusive - startInclusive) / 2) + 1;
+            // Android-changed: no divideUnsigned support yet, use BigInteger instead.
+            long m = startInclusive +
+                BigInteger.valueOf(endInclusive).subtract(BigInteger.valueOf(startInclusive))
+                     .divide(BigInteger.valueOf(2)).longValue() + 1;
+
             return concat(range(startInclusive, m), rangeClosed(m, endInclusive));
         } else {
             return StreamSupport.longStream(
diff --git a/ojluni/src/main/java/sun/security/jca/ProviderConfig.java b/ojluni/src/main/java/sun/security/jca/ProviderConfig.java
index 62f8bdd..fc4ee76 100755
--- a/ojluni/src/main/java/sun/security/jca/ProviderConfig.java
+++ b/ojluni/src/main/java/sun/security/jca/ProviderConfig.java
@@ -208,58 +208,68 @@
                 if (debug != null) {
                     debug.println("Loading provider: " + ProviderConfig.this);
                 }
+
                 try {
-                    ClassLoader cl = ClassLoader.getSystemClassLoader();
-                    Class<?> provClass;
-                    if (cl != null) {
-                        provClass = cl.loadClass(className);
-                    } else {
-                        provClass = Class.forName(className);
-                    }
-                    Object obj;
-                    if (hasArgument() == false) {
-                        obj = provClass.newInstance();
-                    } else {
-                        Constructor<?> cons = provClass.getConstructor(CL_STRING);
-                        obj = cons.newInstance(argument);
-                    }
-                    if (obj instanceof Provider) {
-                        if (debug != null) {
-                            debug.println("Loaded provider " + obj);
+                    // First try with the boot classloader.
+                    return initProvider(className, Object.class.getClassLoader());
+                } catch (Exception e1) {
+                    // If that fails, try with the system classloader.
+                    try {
+                        return initProvider(className, ClassLoader.getSystemClassLoader());
+                    } catch (Exception e) {
+                        Throwable t;
+                        if (e instanceof InvocationTargetException) {
+                            t = ((InvocationTargetException)e).getCause();
+                        } else {
+                            t = e;
                         }
-                        return (Provider)obj;
-                    } else {
                         if (debug != null) {
-                            debug.println(className + " is not a provider");
+                            debug.println("Error loading provider " + ProviderConfig.this);
+                            t.printStackTrace();
                         }
-                        disableLoad();
+                        // provider indicates fatal error, pass through exception
+                        if (t instanceof ProviderException) {
+                            throw (ProviderException)t;
+                        }
+                        // provider indicates that loading should not be retried
+                        if (t instanceof UnsupportedOperationException) {
+                            disableLoad();
+                        }
                         return null;
                     }
-                } catch (Exception e) {
-                    Throwable t;
-                    if (e instanceof InvocationTargetException) {
-                        t = ((InvocationTargetException)e).getCause();
-                    } else {
-                        t = e;
-                    }
-                    if (debug != null) {
-                        debug.println("Error loading provider " + ProviderConfig.this);
-                        t.printStackTrace();
-                    }
-                    // provider indicates fatal error, pass through exception
-                    if (t instanceof ProviderException) {
-                        throw (ProviderException)t;
-                    }
-                    // provider indicates that loading should not be retried
-                    if (t instanceof UnsupportedOperationException) {
-                        disableLoad();
-                    }
-                    return null;
                 }
             }
         });
     }
 
+    private Provider initProvider(String className, ClassLoader cl) throws Exception {
+        Class<?> provClass;
+        if (cl != null) {
+            provClass = cl.loadClass(className);
+        } else {
+            provClass = Class.forName(className);
+        }
+        Object obj;
+        if (hasArgument() == false) {
+            obj = provClass.newInstance();
+        } else {
+            Constructor<?> cons = provClass.getConstructor(CL_STRING);
+            obj = cons.newInstance(argument);
+        }
+        if (obj instanceof Provider) {
+            if (debug != null) {
+                debug.println("Loaded provider " + obj);
+            }
+            return (Provider)obj;
+        } else {
+            if (debug != null) {
+                debug.println(className + " is not a provider");
+            }
+            disableLoad();
+            return null;
+        }
+    }
+
     /**
      * Perform property expansion of the provider value.
      *
diff --git a/ojluni/src/main/java/sun/security/jca/Providers.java b/ojluni/src/main/java/sun/security/jca/Providers.java
index d66d4f8..2212dc2 100755
--- a/ojluni/src/main/java/sun/security/jca/Providers.java
+++ b/ojluni/src/main/java/sun/security/jca/Providers.java
@@ -56,6 +56,15 @@
         // triggers a getInstance() call (although that should not happen)
         providerList = ProviderList.EMPTY;
         providerList = ProviderList.fromSecurityProperties();
+
+        // removeInvalid is specified to try initializing all configured providers
+        // and removing those that aren't instantiable. This has the side effect
+        // of eagerly initializing all providers.
+        final int numConfiguredProviders = providerList.size();
+        providerList = providerList.removeInvalid();
+        if (numConfiguredProviders != providerList.size()) {
+            throw new AssertionError("Unable to configure default providers");
+        }
     }
 
     private Providers() {