Merge "Add tests for canvas clip return values, as well as quickrejection" into mnc-dev
diff --git a/libs/testserver/src/android/webkit/cts/CtsTestServer.java b/libs/testserver/src/android/webkit/cts/CtsTestServer.java
index de8a30d..de88f3b 100644
--- a/libs/testserver/src/android/webkit/cts/CtsTestServer.java
+++ b/libs/testserver/src/android/webkit/cts/CtsTestServer.java
@@ -1032,7 +1032,7 @@
                         conn.receiveRequestEntity( (HttpEntityEnclosingRequest) request);
                     }
 
-                    mExecutorService.submit(new HandleResponseTask(conn, request));
+                    mExecutorService.execute(new HandleResponseTask(conn, request));
                 } catch (IOException e) {
                     // normal during shutdown, ignore
                     Log.w(TAG, e);
@@ -1063,7 +1063,7 @@
             return path.equals(SHUTDOWN_PREFIX);
         }
 
-        private class HandleResponseTask implements Callable<Void> {
+        private class HandleResponseTask implements Runnable {
 
             private DefaultHttpServerConnection mConnection;
 
@@ -1076,12 +1076,15 @@
             }
 
             @Override
-            public Void call() throws Exception {
-                HttpResponse response = mServer.getResponse(mRequest);
-                mConnection.sendResponseHeader(response);
-                mConnection.sendResponseEntity(response);
-                mConnection.close();
-                return null;
+            public void run() {
+                try {
+                    HttpResponse response = mServer.getResponse(mRequest);
+                    mConnection.sendResponseHeader(response);
+                    mConnection.sendResponseEntity(response);
+                    mConnection.close();
+                } catch (Exception e) {
+                    Log.e(TAG, "Error handling request:", e);
+                }
             }
         }
     }
diff --git a/tests/tests/graphics/src/android/graphics/cts/PaintTest.java b/tests/tests/graphics/src/android/graphics/cts/PaintTest.java
index 8d96d91..9f2086d 100644
--- a/tests/tests/graphics/src/android/graphics/cts/PaintTest.java
+++ b/tests/tests/graphics/src/android/graphics/cts/PaintTest.java
@@ -809,7 +809,6 @@
     }
 
     public void testReset() {
-
         Paint p  = new Paint();
         ColorFilter c = new ColorFilter();
         MaskFilter m  = new MaskFilter();
@@ -845,7 +844,6 @@
         assertEquals(null, p.getShader());
         assertEquals(null, p.getTypeface());
         assertEquals(null, p.getXfermode());
-
     }
 
     public void testSetLinearText() {
@@ -1184,6 +1182,51 @@
         }
     }
 
+    public void testGetRunAdvance_nonzeroIndex() {
+        Paint p = new Paint();
+        final String text = "Android powers hundreds of millions of mobile " +
+                "devices in more than 190 countries around the world. It's" +
+                "the largest installed base of any mobile platform and" +
+                "growing fast—every day another million users power up their" +
+                "Android devices for the first time and start looking for" +
+                "apps, games, and other digital content.";
+        // Test offset index does not affect width.
+        final float widthAndroidFirst = p.getRunAdvance(
+                text, 0, 7, 0, text.length(), false, 7);
+        final float widthAndroidSecond = p.getRunAdvance(
+                text, 215, 222, 0, text.length(), false, 222);
+        assertTrue(Math.abs(widthAndroidFirst - widthAndroidSecond) < 1);
+    }
+
+    public void testGetRunAdvance_glyphDependingContext() {
+        Paint p = new Paint();
+        // Test the context change the character shape.
+        // First character should be isolated form because the context ends at index 1.
+        final float isolatedFormWidth = p.getRunAdvance("\u0644\u0644", 0, 1, 0, 1, true, 1);
+        // First character should be initial form because the context ends at index 2.
+        final float initialFormWidth = p.getRunAdvance("\u0644\u0644", 0, 1, 0, 2, true, 1);
+        assertTrue(isolatedFormWidth > initialFormWidth);
+    }
+
+    public void testGetRunAdvance_arabic() {
+        Paint p = new Paint();
+        // Test total width is equals to sum of each character's width.
+        // "What is Unicode?" in Arabic.
+        final String text =
+                "\u0645\u0627\u0020\u0647\u064A\u0020\u0627\u0644\u0634" +
+                "\u0641\u0631\u0629\u0020\u0627\u0644\u0645\u0648\u062D" +
+                "\u062F\u0629\u0020\u064A\u0648\u0646\u064A\u0643\u0648" +
+                "\u062F\u061F";
+        final float totalWidth = p.getRunAdvance(
+                text, 0, text.length(), 0, text.length(), true, text.length());
+        float sumOfCharactersWidth = 0;
+        for (int i = 0; i < text.length(); i++) {
+            sumOfCharactersWidth += p.getRunAdvance(
+                    text, i, i + 1, 0, text.length(), true, i + 1);
+        }
+        assertTrue(Math.abs(totalWidth - sumOfCharactersWidth) < 1);
+    }
+
     public void testGetOffsetForAdvance() {
         Paint p = new Paint();
         {
diff --git a/tests/tests/hardware/src/android/hardware/camera2/cts/DngCreatorTest.java b/tests/tests/hardware/src/android/hardware/camera2/cts/DngCreatorTest.java
index 8184226..0da0ce7 100644
--- a/tests/tests/hardware/src/android/hardware/camera2/cts/DngCreatorTest.java
+++ b/tests/tests/hardware/src/android/hardware/camera2/cts/DngCreatorTest.java
@@ -115,19 +115,7 @@
                     continue;
                 }
 
-                Size[] targetCaptureSizes =
-                        mStaticInfo.getAvailableSizesForFormatChecked(ImageFormat.RAW_SENSOR,
-                                StaticMetadata.StreamDirection.Output);
-
-                assertTrue("No capture sizes available for RAW format!",
-                        targetCaptureSizes.length != 0);
-                Rect activeArray = mStaticInfo.getActiveArraySizeChecked();
-                Size activeArraySize = new Size(activeArray.width(), activeArray.height());
-                assertTrue("Missing ActiveArraySize", activeArray.width() > 0 &&
-                        activeArray.height() > 0);
-                // TODO: Allow PixelArraySize also.
-                assertArrayContains("Available sizes for RAW format must include ActiveArraySize",
-                        targetCaptureSizes, activeArraySize);
+                Size activeArraySize = mStaticInfo.getRawDimensChecked();
 
                 // Create capture image reader
                 CameraTestUtils.SimpleImageReaderListener captureListener
@@ -202,19 +190,7 @@
                     continue;
                 }
 
-                Size[] targetCaptureSizes =
-                        mStaticInfo.getAvailableSizesForFormatChecked(ImageFormat.RAW_SENSOR,
-                                StaticMetadata.StreamDirection.Output);
-
-                assertTrue("No capture sizes available for RAW format!",
-                        targetCaptureSizes.length != 0);
-                Rect activeArray = mStaticInfo.getActiveArraySizeChecked();
-                Size activeArraySize = new Size(activeArray.width(), activeArray.height());
-                assertTrue("Missing ActiveArraySize", activeArray.width() > 0 &&
-                        activeArray.height() > 0);
-                // TODO: Allow PixelArraySize also.
-                assertArrayContains("Available sizes for RAW format must include ActiveArraySize",
-                        targetCaptureSizes, activeArraySize);
+                Size activeArraySize = mStaticInfo.getRawDimensChecked();
 
                 Size[] targetPreviewSizes =
                         mStaticInfo.getAvailableSizesForFormatChecked(ImageFormat.YUV_420_888,
@@ -322,19 +298,7 @@
                     continue;
                 }
 
-                Size[] targetCaptureSizes =
-                        mStaticInfo.getAvailableSizesForFormatChecked(ImageFormat.RAW_SENSOR,
-                                StaticMetadata.StreamDirection.Output);
-
-                assertTrue("No capture sizes available for RAW format!",
-                        targetCaptureSizes.length != 0);
-                Rect activeArray = mStaticInfo.getActiveArraySizeChecked();
-                Size activeArraySize = new Size(activeArray.width(), activeArray.height());
-                assertTrue("Active array has invalid size!", activeArray.width() > 0 &&
-                        activeArray.height() > 0);
-                // TODO: Allow PixelArraySize also.
-                assertArrayContains("Available sizes for RAW format must include ActiveArraySize",
-                        targetCaptureSizes, activeArraySize);
+                Size activeArraySize = mStaticInfo.getRawDimensChecked();
 
                 // Get largest jpeg size
                 Size[] targetJpegSizes =
@@ -369,8 +333,8 @@
                         Bitmap.Config.ARGB_8888);
 
                 Size rawBitmapSize = new Size(rawBitmap.getWidth(), rawBitmap.getHeight());
-                assertTrue("Raw bitmap size must be equal to active array size.",
-                        rawBitmapSize.equals(activeArraySize));
+                assertTrue("Raw bitmap size must be equal to either pre-correction active array" +
+                        " size or pixel array size.", rawBitmapSize.equals(activeArraySize));
 
                 byte[] rawPlane = new byte[raw.getPlanes()[0].getRowStride() * raw.getHeight()];
 
diff --git a/tests/tests/hardware/src/android/hardware/camera2/cts/StillCaptureTest.java b/tests/tests/hardware/src/android/hardware/camera2/cts/StillCaptureTest.java
index 73cfaf7..ee4ddd9 100644
--- a/tests/tests/hardware/src/android/hardware/camera2/cts/StillCaptureTest.java
+++ b/tests/tests/hardware/src/android/hardware/camera2/cts/StillCaptureTest.java
@@ -663,16 +663,7 @@
      */
     private void rawCaptureTestByCamera() throws Exception {
         Size maxPreviewSz = mOrderedPreviewSizes.get(0);
-        Size[] rawSizes = mStaticInfo.getRawOutputSizesChecked();
-
-        assertTrue("No capture sizes available for RAW format!",
-                rawSizes.length != 0);
-        Rect activeArray = mStaticInfo.getActiveArraySizeChecked();
-        Size size = new Size(activeArray.width(), activeArray.height());
-        assertTrue("Missing ActiveArraySize", activeArray.width() > 0 &&
-                activeArray.height() > 0);
-        assertArrayContains("Available sizes for RAW format must include ActiveArraySize",
-                rawSizes, size);
+        Size size = mStaticInfo.getRawDimensChecked();
 
         // Prepare raw capture and start preview.
         CaptureRequest.Builder previewBuilder =
@@ -711,20 +702,12 @@
     private void fullRawCaptureTestByCamera() throws Exception {
         Size maxPreviewSz = mOrderedPreviewSizes.get(0);
         Size maxStillSz = mOrderedStillSizes.get(0);
-        Size[] rawSizes = mStaticInfo.getRawOutputSizesChecked();
 
         SimpleCaptureCallback resultListener = new SimpleCaptureCallback();
         SimpleImageReaderListener jpegListener = new SimpleImageReaderListener();
         SimpleImageReaderListener rawListener = new SimpleImageReaderListener();
 
-        assertTrue("No capture sizes available for RAW format!",
-                rawSizes.length != 0);
-        Rect activeArray = mStaticInfo.getActiveArraySizeChecked();
-        Size size = new Size(activeArray.width(), activeArray.height());
-        assertTrue("Missing ActiveArraySize", activeArray.width() > 0 &&
-                activeArray.height() > 0);
-        assertArrayContains("Available sizes for RAW format must include ActiveArraySize",
-                rawSizes, size);
+        Size size = mStaticInfo.getRawDimensChecked();
 
         if (VERBOSE) {
             Log.v(TAG, "Testing multi capture with size " + size.toString()
diff --git a/tests/tests/hardware/src/android/hardware/camera2/cts/helpers/StaticMetadata.java b/tests/tests/hardware/src/android/hardware/camera2/cts/helpers/StaticMetadata.java
index 74b55e1..a828371 100644
--- a/tests/tests/hardware/src/android/hardware/camera2/cts/helpers/StaticMetadata.java
+++ b/tests/tests/hardware/src/android/hardware/camera2/cts/helpers/StaticMetadata.java
@@ -41,6 +41,8 @@
 import java.util.List;
 import java.util.Set;
 
+import static android.hardware.camera2.cts.helpers.AssertHelpers.*;
+
 /**
  * Helpers to get common static info out of the camera.
  *
@@ -743,6 +745,26 @@
     }
 
     /**
+     * Get and check pre-correction active array size.
+     */
+    public Rect getPreCorrectedActiveArraySizeChecked() {
+        Key<Rect> key = CameraCharacteristics.SENSOR_INFO_PRE_CORRECTION_ACTIVE_ARRAY_SIZE;
+        Rect activeArray = getValueFromKeyNonNull(key);
+
+        if (activeArray == null) {
+            return new Rect(0, 0, 0, 0);
+        }
+
+        Size pixelArraySize = getPixelArraySizeChecked();
+        checkTrueForKey(key, "values left/top are invalid", activeArray.left >= 0 && activeArray.top >= 0);
+        checkTrueForKey(key, "values width/height are invalid",
+                activeArray.width() <= pixelArraySize.getWidth() &&
+                activeArray.height() <= pixelArraySize.getHeight());
+
+        return activeArray;
+    }
+
+    /**
      * Get and check active array size.
      */
     public Rect getActiveArraySizeChecked() {
@@ -763,6 +785,29 @@
     }
 
     /**
+     * Get the dimensions to use for RAW16 buffers.
+     */
+    public Size getRawDimensChecked() throws Exception {
+        Size[] targetCaptureSizes = getAvailableSizesForFormatChecked(ImageFormat.RAW_SENSOR,
+                        StaticMetadata.StreamDirection.Output);
+        Assert.assertTrue("No capture sizes available for RAW format!",
+                targetCaptureSizes.length != 0);
+        Rect activeArray = getPreCorrectedActiveArraySizeChecked();
+        Size preCorrectionActiveArraySize =
+                new Size(activeArray.width(), activeArray.height());
+        Size pixelArraySize = getPixelArraySizeChecked();
+        Assert.assertTrue("Missing pre-correction active array size", activeArray.width() > 0 &&
+                activeArray.height() > 0);
+        Assert.assertTrue("Missing pixel array size", pixelArraySize.getWidth() > 0 &&
+                pixelArraySize.getHeight() > 0);
+        Size[] allowedArraySizes = new Size[] { preCorrectionActiveArraySize,
+                pixelArraySize };
+        return assertArrayContainsAnyOf("Available sizes for RAW format" +
+                " must include either the pre-corrected active array size, or the full " +
+                "pixel array size", targetCaptureSizes, allowedArraySizes);
+    }
+
+    /**
      * Get the sensitivity value and clamp to the range if needed.
      *
      * @param sensitivity Input sensitivity value to check.
diff --git a/tests/tests/net/Android.mk b/tests/tests/net/Android.mk
index a35e145..6524871 100644
--- a/tests/tests/net/Android.mk
+++ b/tests/tests/net/Android.mk
@@ -26,7 +26,8 @@
 
 LOCAL_JAVA_LIBRARIES := voip-common conscrypt org.apache.http.legacy
 
-LOCAL_JNI_SHARED_LIBRARIES := libcts_jni libnativedns_jni
+LOCAL_JNI_SHARED_LIBRARIES := libcts_jni libnativedns_jni \
+                              libnativemultinetwork_jni
 
 # include CtsTestServer as a temporary hack to free net.cts from cts.stub.
 LOCAL_SRC_FILES := $(call all-java-files-under, src)
diff --git a/tests/tests/net/jni/Android.mk b/tests/tests/net/jni/Android.mk
index 75982de..ca82b30 100644
--- a/tests/tests/net/jni/Android.mk
+++ b/tests/tests/net/jni/Android.mk
@@ -28,3 +28,12 @@
 LOCAL_SHARED_LIBRARIES := libnativehelper liblog
 
 include $(BUILD_SHARED_LIBRARY)
+
+include $(CLEAR_VARS)
+LOCAL_MODULE := libnativemultinetwork_jni
+# Don't include this package in any configuration by default.
+LOCAL_MODULE_TAGS := optional
+LOCAL_SRC_FILES := NativeMultinetworkJni.c
+LOCAL_C_INCLUDES := $(JNI_H_INCLUDE)
+LOCAL_SHARED_LIBRARIES := libandroid libnativehelper liblog
+include $(BUILD_SHARED_LIBRARY)
diff --git a/tests/tests/net/jni/NativeMultinetworkJni.c b/tests/tests/net/jni/NativeMultinetworkJni.c
new file mode 100644
index 0000000..9a5ab9c
--- /dev/null
+++ b/tests/tests/net/jni/NativeMultinetworkJni.c
@@ -0,0 +1,216 @@
+/*
+ * Copyright (C) 2010 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+
+#define LOG_TAG "MultinetworkApiTest"
+#include <utils/Log.h>
+
+#include <arpa/inet.h>
+#include <errno.h>
+#include <inttypes.h>
+#include <jni.h>
+#include <netdb.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/socket.h>
+#include <sys/time.h>
+#include <android/multinetwork.h>
+
+#define UNUSED(X) ((void) X)
+
+static const char kHostname[] = "connectivitycheck.android.com";
+
+
+JNIEXPORT jint Java_android_net_cts_MultinetworkApiTest_runGetaddrinfoCheck(
+        JNIEnv* env, jclass class, jlong nethandle) {
+    UNUSED(env);
+    UNUSED(class);
+    net_handle_t handle = (net_handle_t) nethandle;
+    struct addrinfo *res = NULL;
+
+    errno = 0;
+    int rval = android_getaddrinfofornetwork(handle, kHostname, NULL, NULL, &res);
+    const int saved_errno = errno;
+    freeaddrinfo(res);
+
+    ALOGD("android_getaddrinfofornetwork(%llu, %s) returned rval=%d errno=%d",
+          handle, kHostname, rval, saved_errno);
+    return rval == 0 ? 0 : -saved_errno;
+}
+
+JNIEXPORT jint Java_android_net_cts_MultinetworkApiTest_runSetprocnetwork(
+        JNIEnv* env, jclass class, jlong nethandle) {
+    UNUSED(env);
+    UNUSED(class);
+    net_handle_t handle = (net_handle_t) nethandle;
+
+    errno = 0;
+    int rval = android_setprocnetwork(handle);
+    const int saved_errno = errno;
+    ALOGD("android_setprocnetwork(%llu) returned rval=%d errno=%d",
+          handle, rval, saved_errno);
+    return rval == 0 ? 0 : -saved_errno;
+}
+
+JNIEXPORT jint Java_android_net_cts_MultinetworkApiTest_runSetsocknetwork(
+        JNIEnv* env, jclass class, jlong nethandle) {
+    UNUSED(env);
+    UNUSED(class);
+    net_handle_t handle = (net_handle_t) nethandle;
+
+    errno = 0;
+    int fd = socket(AF_INET6, SOCK_DGRAM, IPPROTO_UDP);
+    if (fd < 0) {
+        ALOGD("socket() failed, errno=%d", errno);
+        return -errno;
+    }
+
+    errno = 0;
+    int rval = android_setsocknetwork(handle, fd);
+    const int saved_errno = errno;
+    ALOGD("android_setprocnetwork(%llu, %d) returned rval=%d errno=%d",
+          handle, fd, rval, saved_errno);
+    close(fd);
+    return rval == 0 ? 0 : -saved_errno;
+}
+
+static const int kSockaddrStrLen = INET6_ADDRSTRLEN + strlen("[]:65535");
+
+void sockaddr_ntop(const struct sockaddr *sa, socklen_t salen, char *dst, const size_t size) {
+    char addrstr[INET6_ADDRSTRLEN];
+    char portstr[sizeof("65535")];
+    char buf[sizeof(addrstr) + sizeof(portstr) + sizeof("[]:")];
+    int ret = getnameinfo(sa, salen,
+                          addrstr, sizeof(addrstr),
+                          portstr, sizeof(portstr),
+                          NI_NUMERICHOST | NI_NUMERICSERV);
+    if (ret == 0) {
+        snprintf(buf, sizeof(buf),
+                 (sa->sa_family == AF_INET6) ? "[%s]:%s" : "%s:%s",
+                 addrstr, portstr);
+    } else {
+        sprintf(buf, "???");
+    }
+
+    strlcpy(dst, buf, (strlen(buf) < size - 1) ? strlen(buf) : size - 1);
+}
+
+JNIEXPORT jint Java_android_net_cts_MultinetworkApiTest_runDatagramCheck(
+        JNIEnv* env, jclass class, jlong nethandle) {
+    UNUSED(env);
+    UNUSED(class);
+    const struct addrinfo kHints = {
+        .ai_flags = AI_ADDRCONFIG,
+        .ai_family = AF_UNSPEC,
+        .ai_socktype = SOCK_DGRAM,
+        .ai_protocol = IPPROTO_UDP,
+    };
+    struct addrinfo *res = NULL;
+    net_handle_t handle = (net_handle_t) nethandle;
+
+    // Quoth Ian Swett:
+    //     "QUIC always uses 80 and 443, but only 443 is used for secure(HTTPS) traffic."
+    int rval = android_getaddrinfofornetwork(handle, kHostname, "80", &kHints, &res);
+    if (rval != 0) {
+        ALOGD("android_getaddrinfofornetwork(%llu, %s) returned rval=%d errno=%d",
+              handle, kHostname, rval, errno);
+        freeaddrinfo(res);
+        return -errno;
+    }
+
+    // Rely upon getaddrinfo sorting the best destination to the front.
+    int fd = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
+    if (fd < 0) {
+        ALOGD("socket(%d, %d, %d) failed, errno=%d",
+              res->ai_family, res->ai_socktype, res->ai_protocol, errno);
+        freeaddrinfo(res);
+        return -errno;
+    }
+
+    rval = android_setsocknetwork(handle, fd);
+    ALOGD("android_setprocnetwork(%llu, %d) returned rval=%d errno=%d",
+          handle, fd, rval, errno);
+    if (rval != 0) {
+        close(fd);
+        freeaddrinfo(res);
+        return -errno;
+    }
+
+    char addrstr[kSockaddrStrLen];
+    sockaddr_ntop(res->ai_addr, res->ai_addrlen, addrstr, sizeof(addrstr));
+    ALOGD("Attempting connect() to %s...", addrstr);
+
+    rval = connect(fd, res->ai_addr, res->ai_addrlen);
+    if (rval != 0) {
+        close(fd);
+        freeaddrinfo(res);
+        return -errno;
+    }
+    freeaddrinfo(res);
+
+    struct sockaddr_storage src_addr;
+    socklen_t src_addrlen = sizeof(src_addr);
+    if (getsockname(fd, (struct sockaddr *)&src_addr, &src_addrlen) != 0) {
+        close(fd);
+        return -errno;
+    }
+    sockaddr_ntop((const struct sockaddr *)&src_addr, sizeof(src_addr), addrstr, sizeof(addrstr));
+    ALOGD("... from %s", addrstr);
+
+    // Don't let reads or writes block indefinitely.
+    const struct timeval timeo = { 5, 0 };  // 5 seconds
+    setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, &timeo, sizeof(timeo));
+    setsockopt(fd, SOL_SOCKET, SO_SNDTIMEO, &timeo, sizeof(timeo));
+
+    uint8_t quic_packet[] = {
+        0x0c,                    // public flags: 64bit conn ID, 8bit sequence number
+        0, 0, 0, 0, 0, 0, 0, 0,  // 64bit connection ID
+        0x01,                    // sequence number
+        0x00,                    // private flags
+        0x07,                    // type: regular frame type "PING"
+    };
+
+    arc4random_buf(quic_packet + 1, 8);  // random connection ID
+
+    ssize_t sent = send(fd, quic_packet, sizeof(quic_packet), 0);
+    if (sent < (ssize_t)sizeof(quic_packet)) {
+        ALOGD("send(QUIC packet) returned sent=%zd, errno=%d", sent, errno);
+        close(fd);
+        return -errno;
+    }
+
+    uint8_t response[1500];
+    ssize_t rcvd = recv(fd, response, sizeof(response), 0);
+    if (rcvd < sent) {
+        ALOGD("recv() returned rcvd=%zd, errno=%d", rcvd, errno);
+        close(fd);
+        return -errno;
+    }
+
+    int conn_id_cmp = memcmp(quic_packet + 1, response + 1, 8);
+    if (conn_id_cmp != 0) {
+        ALOGD("sent and received connection IDs do not match");
+        close(fd);
+        return -EPROTO;
+    }
+
+    // TODO: log, and compare to the IP address encoded in the
+    // response, since this should be a public reset packet.
+
+    close(fd);
+    return 0;
+}
diff --git a/tests/tests/net/src/android/net/cts/MultinetworkApiTest.java b/tests/tests/net/src/android/net/cts/MultinetworkApiTest.java
new file mode 100644
index 0000000..51ee50e
--- /dev/null
+++ b/tests/tests/net/src/android/net/cts/MultinetworkApiTest.java
@@ -0,0 +1,155 @@
+/*
+ * Copyright (C) 2015 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package android.net.cts;
+
+import android.content.Context;
+import android.net.ConnectivityManager;
+import android.net.Network;
+import android.net.NetworkCapabilities;
+import android.net.NetworkUtils;
+import android.system.ErrnoException;
+import android.system.OsConstants;
+import android.test.AndroidTestCase;
+
+import java.util.ArrayList;
+
+
+public class MultinetworkApiTest extends AndroidTestCase {
+
+    static {
+        System.loadLibrary("nativemultinetwork_jni");
+    }
+
+    private static final String TAG = "MultinetworkNativeApiTest";
+
+    /**
+     * @return 0 on success
+     */
+    private static native int runGetaddrinfoCheck(long networkHandle);
+    private static native int runSetprocnetwork(long networkHandle);
+    private static native int runSetsocknetwork(long networkHandle);
+    private static native int runDatagramCheck(long networkHandle);
+
+    private ConnectivityManager mCM;
+
+    protected void setUp() throws Exception {
+        super.setUp();
+        mCM = (ConnectivityManager) getContext().getSystemService(Context.CONNECTIVITY_SERVICE);
+    }
+
+    private Network[] getTestableNetworks() {
+        final ArrayList<Network> testableNetworks = new ArrayList<Network>();
+        for (Network network : mCM.getAllNetworks()) {
+            final NetworkCapabilities nc = mCM.getNetworkCapabilities(network);
+            if (nc != null
+                    && nc.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_RESTRICTED)
+                    && nc.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)) {
+                testableNetworks.add(network);
+            }
+        }
+
+        assertTrue(
+                "This test requires that at least one network be connected. " +
+                "Please ensure that the device is connected to a network.",
+                testableNetworks.size() >= 1);
+        return testableNetworks.toArray(new Network[0]);
+    }
+
+    public void testGetaddrinfo() throws ErrnoException {
+        for (Network network : getTestableNetworks()) {
+            int errno = runGetaddrinfoCheck(network.getNetworkHandle());
+            if (errno != 0) {
+                throw new ErrnoException(
+                        "getaddrinfo on " + mCM.getNetworkInfo(network), -errno);
+            }
+        }
+    }
+
+    public void testSetprocnetwork() throws ErrnoException {
+        // Hopefully no prior test in this process space has set a default network.
+        assertNull(mCM.getProcessDefaultNetwork());
+        assertEquals(0, NetworkUtils.getBoundNetworkForProcess());
+
+        for (Network network : getTestableNetworks()) {
+            mCM.setProcessDefaultNetwork(null);
+            assertNull(mCM.getProcessDefaultNetwork());
+
+            int errno = runSetprocnetwork(network.getNetworkHandle());
+            if (errno != 0) {
+                throw new ErrnoException(
+                        "setprocnetwork on " + mCM.getNetworkInfo(network), -errno);
+            }
+            Network processDefault = mCM.getProcessDefaultNetwork();
+            assertNotNull(processDefault);
+            assertEquals(network, processDefault);
+            // TODO: open DatagramSockets, connect them to 192.0.2.1 and 2001:db8::,
+            // and ensure that the source address is in fact on this network as
+            // determined by mCM.getLinkProperties(network).
+
+            mCM.setProcessDefaultNetwork(null);
+        }
+
+        for (Network network : getTestableNetworks()) {
+            NetworkUtils.bindProcessToNetwork(0);
+            assertNull(mCM.getBoundNetworkForProcess());
+
+            int errno = runSetprocnetwork(network.getNetworkHandle());
+            if (errno != 0) {
+                throw new ErrnoException(
+                        "setprocnetwork on " + mCM.getNetworkInfo(network), -errno);
+            }
+            assertEquals(network, new Network(mCM.getBoundNetworkForProcess()));
+            // TODO: open DatagramSockets, connect them to 192.0.2.1 and 2001:db8::,
+            // and ensure that the source address is in fact on this network as
+            // determined by mCM.getLinkProperties(network).
+
+            NetworkUtils.bindProcessToNetwork(0);
+        }
+    }
+
+    public void testSetsocknetwork() throws ErrnoException {
+        for (Network network : getTestableNetworks()) {
+            int errno = runSetsocknetwork(network.getNetworkHandle());
+            if (errno != 0) {
+                throw new ErrnoException(
+                        "setsocknetwork on " + mCM.getNetworkInfo(network), -errno);
+            }
+        }
+    }
+
+    public void testNativeDatagramTransmission() throws ErrnoException {
+        for (Network network : getTestableNetworks()) {
+            int errno = runDatagramCheck(network.getNetworkHandle());
+            if (errno != 0) {
+                throw new ErrnoException(
+                        "DatagramCheck on " + mCM.getNetworkInfo(network), -errno);
+            }
+        }
+    }
+
+    public void testNoSuchNetwork() {
+        final Network eNoNet = new Network(54321);
+        assertNull(mCM.getNetworkInfo(eNoNet));
+
+        final long eNoNetHandle = eNoNet.getNetworkHandle();
+        assertEquals(-OsConstants.ENONET, runSetsocknetwork(eNoNetHandle));
+        assertEquals(-OsConstants.ENONET, runSetprocnetwork(eNoNetHandle));
+        // TODO: correct test permissions so this call is not silently re-mapped
+        // to query on the default network.
+        // assertEquals(-OsConstants.ENONET, runGetaddrinfoCheck(eNoNetHandle));
+    }
+}
diff --git a/tests/tests/net/src/android/net/cts/MultinetworkTest.java b/tests/tests/net/src/android/net/cts/MultinetworkSysctlTest.java
similarity index 96%
rename from tests/tests/net/src/android/net/cts/MultinetworkTest.java
rename to tests/tests/net/src/android/net/cts/MultinetworkSysctlTest.java
index 256c030..c091a13 100644
--- a/tests/tests/net/src/android/net/cts/MultinetworkTest.java
+++ b/tests/tests/net/src/android/net/cts/MultinetworkSysctlTest.java
@@ -27,9 +27,9 @@
 import java.io.IOException;
 
 /**
- * Tests for multinetwork functionality.
+ * Tests for multinetwork sysctl functionality.
  */
-public class MultinetworkTest extends AndroidTestCase {
+public class MultinetworkSysctlTest extends AndroidTestCase {
 
     // Global sysctls. Must be present and set to 1.
     private static final String[] GLOBAL_SYSCTLS = {
diff --git a/tests/tests/widget/src/android/widget/cts/TextViewTest.java b/tests/tests/widget/src/android/widget/cts/TextViewTest.java
index 0f30ca6..ec098f8 100644
--- a/tests/tests/widget/src/android/widget/cts/TextViewTest.java
+++ b/tests/tests/widget/src/android/widget/cts/TextViewTest.java
@@ -78,12 +78,16 @@
 import android.util.TypedValue;
 import android.view.ContextMenu;
 import android.view.ContextMenu.ContextMenuInfo;
+import android.view.ActionMode;
 import android.view.Gravity;
 import android.view.KeyEvent;
+import android.view.Menu;
+import android.view.MenuItem;
 import android.view.View;
 import android.view.View.OnCreateContextMenuListener;
 import android.view.View.OnLongClickListener;
 import android.view.ViewGroup;
+import android.view.accessibility.AccessibilityNodeInfo;
 import android.view.inputmethod.BaseInputConnection;
 import android.view.inputmethod.EditorInfo;
 import android.view.inputmethod.ExtractedText;
@@ -4423,6 +4427,135 @@
         assertEquals(Layout.HYPHENATION_FREQUENCY_FULL, tv.getHyphenationFrequency());
     }
 
+    public void testSetAndGetCustomSelectionActionModeCallback() {
+        final String text = "abcde";
+        mActivity.runOnUiThread(new Runnable() {
+            public void run() {
+                mTextView = new EditText(mActivity);
+                mActivity.setContentView(mTextView);
+                mTextView.setText(text, BufferType.SPANNABLE);
+                mTextView.setTextIsSelectable(true);
+                mTextView.requestFocus();
+                mTextView.setSelected(true);
+            }
+        });
+        mInstrumentation.waitForIdleSync();
+
+        // Check default value.
+        assertNull(mTextView.getCustomSelectionActionModeCallback());
+
+        MockActionModeCallback callbackBlockActionMode = new MockActionModeCallback(false);
+        mTextView.setCustomSelectionActionModeCallback(callbackBlockActionMode);
+        assertEquals(callbackBlockActionMode,
+                mTextView.getCustomSelectionActionModeCallback());
+
+        mActivity.runOnUiThread(new Runnable() {
+            public void run() {
+                // Set selection and try to start action mode.
+                final Bundle args = new Bundle();
+                args.putInt(AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_START_INT, 0);
+                args.putInt(AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_END_INT, text.length());
+                mTextView.performAccessibilityActionInternal(
+                        AccessibilityNodeInfo.ACTION_SET_SELECTION, args);
+            }
+        });
+        mInstrumentation.waitForIdleSync();
+
+        assertEquals(1, callbackBlockActionMode.getCreateCount());
+
+        mActivity.runOnUiThread(new Runnable() {
+            public void run() {
+                // Remove selection and stop action mode.
+                mTextView.onTextContextMenuItem(android.R.id.copy);
+            }
+        });
+        mInstrumentation.waitForIdleSync();
+
+        // Action mode was blocked.
+        assertEquals(0, callbackBlockActionMode.getDestroyCount());
+
+        // Overwrite callback.
+        MockActionModeCallback callbackStartActionMode = new MockActionModeCallback(true);
+        mTextView.setCustomSelectionActionModeCallback(callbackStartActionMode);
+        assertEquals(callbackStartActionMode, mTextView.getCustomSelectionActionModeCallback());
+
+        mActivity.runOnUiThread(new Runnable() {
+            public void run() {
+                // Set selection and try to start action mode.
+                final Bundle args = new Bundle();
+                args.putInt(AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_START_INT, 0);
+                args.putInt(AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_END_INT, text.length());
+                mTextView.performAccessibilityActionInternal(
+                        AccessibilityNodeInfo.ACTION_SET_SELECTION, args);
+
+            }
+        });
+        mInstrumentation.waitForIdleSync();
+
+        assertEquals(1, callbackStartActionMode.getCreateCount());
+
+        mActivity.runOnUiThread(new Runnable() {
+            public void run() {
+                // Remove selection and stop action mode.
+                mTextView.onTextContextMenuItem(android.R.id.copy);
+            }
+        });
+        mInstrumentation.waitForIdleSync();
+
+        // Action mode was started
+        assertEquals(1, callbackStartActionMode.getDestroyCount());
+    }
+
+    public void testSetAndGetCustomInseltionActionMode() {
+        initTextViewForTyping();
+        // Check default value.
+        assertNull(mTextView.getCustomInsertionActionModeCallback());
+
+        MockActionModeCallback callback = new MockActionModeCallback(false);
+        mTextView.setCustomInsertionActionModeCallback(callback);
+        assertEquals(callback, mTextView.getCustomInsertionActionModeCallback());
+        // TODO(Bug: 22033189): Tests the set callback is actually used.
+    }
+
+    private static class MockActionModeCallback implements ActionMode.Callback {
+        private int mCreateCount = 0;
+        private int mDestroyCount = 0;
+        private final boolean mAllowToStartActionMode;
+
+        public MockActionModeCallback(boolean allowToStartActionMode) {
+            mAllowToStartActionMode = allowToStartActionMode;
+        }
+
+        public int getCreateCount() {
+            return mCreateCount;
+        }
+
+        public int getDestroyCount() {
+            return mDestroyCount;
+        }
+
+        @Override
+        public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
+            return false;
+        }
+
+        @Override
+        public void onDestroyActionMode(ActionMode mode) {
+            mDestroyCount++;
+        }
+
+        @Override
+        public boolean onCreateActionMode(ActionMode mode, Menu menu) {
+            mCreateCount++;
+            return mAllowToStartActionMode;
+        }
+
+        @Override
+        public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
+            return false;
+        }
+    };
+
     private static class MockOnEditorActionListener implements OnEditorActionListener {
         private boolean isOnEditorActionCalled;