am 107bf370: am 304ca349: am 29ad030d: Merge "Test that strings interned manually and then later loaded as literals maintain reference equality." into gingerbread

Merge commit '107bf3709fb39f0d77fd9720f6597bd1b284f436' into dalvik-dev

* commit '107bf3709fb39f0d77fd9720f6597bd1b284f436':
  Test that strings interned manually and then later loaded as literals maintain reference equality.
diff --git a/JavaLibrary.mk b/JavaLibrary.mk
index e17206c..68f93d2 100644
--- a/JavaLibrary.mk
+++ b/JavaLibrary.mk
@@ -249,25 +249,6 @@
 
 $(LOCAL_INSTALLED_MODULE): $(HOST_CORE_JAR)
 
-$(LOCAL_INSTALLED_MODULE): run-core-tests
-
-# Definitions to copy the core-tests runner script.
-
-include $(CLEAR_VARS)
-LOCAL_SRC_FILES := run-core-tests
-LOCAL_MODULE_CLASS := EXECUTABLES
-LOCAL_MODULE_TAGS := tests
-LOCAL_MODULE := run-core-tests
-include $(BUILD_PREBUILT)
-
-include $(CLEAR_VARS)
-LOCAL_SRC_FILES := run-core-tests-on-ri
-LOCAL_IS_HOST_MODULE := true
-LOCAL_MODULE_CLASS := EXECUTABLES
-LOCAL_MODULE_TAGS := tests
-LOCAL_MODULE := run-core-tests-on-ri
-include $(BUILD_PREBUILT)
-
 
 #
 # Build for the host.
diff --git a/dalvik/src/main/java/dalvik/system/CloseGuard.java b/dalvik/src/main/java/dalvik/system/CloseGuard.java
new file mode 100644
index 0000000..fbb4951
--- /dev/null
+++ b/dalvik/src/main/java/dalvik/system/CloseGuard.java
@@ -0,0 +1,184 @@
+/*
+ * 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.
+ */
+
+package dalvik.system;
+
+import java.util.logging.Level;
+import java.util.logging.Logger;
+
+/**
+ * CloseGuard is a mechanism for flagging implict finalizer cleanup of
+ * resources that should have been cleaned up by explicit close
+ * methods (aka "explicit termination methods" in Effective Java).
+ * <p>
+ * A simple example: <pre>   {@code
+ *   class Foo {
+ *
+ *       private final CloseGuard guard = CloseGuard.get();
+ *
+ *       ...
+ *
+ *       public Foo() {
+ *           ...;
+ *           guard.open("cleanup");
+ *       }
+ *
+ *       public void cleanup() {
+ *          guard.close();
+ *          ...;
+ *       }
+ *
+ *       protected void finalize() throws Throwable {
+ *           try {
+ *               if (guard != null) {
+ *                   guard.warnIfOpen();
+ *               }
+ *               cleanup();
+ *           } finally {
+ *               super.finalize();
+ *           }
+ *       }
+ *   }
+ * }</pre>
+ *
+ * In usage where the resource to be explictly cleaned up are
+ * allocated after object construction, CloseGuard can protection can
+ * be deferred. For example: <pre>   {@code
+ *   class Bar {
+ *
+ *       private final CloseGuard guard = CloseGuard.getUnopened();
+ *
+ *       ...
+ *
+ *       public Bar() {
+ *           ...;
+ *       }
+ *
+ *       public void connect() {
+ *          ...;
+ *          guard.open("cleanup");
+ *       }
+ *
+ *       public void cleanup() {
+ *          guard.close();
+ *          ...;
+ *       }
+ *
+ *       protected void finalize() throws Throwable {
+ *           try {
+ *               if (guard != null) {
+ *                   guard.warnIfOpen();
+ *               }
+ *               cleanup();
+ *           } finally {
+ *               super.finalize();
+ *           }
+ *       }
+ *   }
+ * }</pre>
+ *
+ * When used in a constructor calls to {@code open} should occur at
+ * the end of the constructor since an exception that would cause
+ * abrupt termination of the constructor will mean that the user will
+ * not have a reference to the object to cleanup explicitly. When used
+ * in a method, the call to {@code open} should occur just after
+ * resource acquisition.
+ *
+ * <p>
+ *
+ * Note that the null check on {@code guard} in the finalizer is to
+ * cover cases where a constructor throws an exception causing the
+ * {@code guard} to be uninitialized.
+ *
+ * @hide
+ */
+public final class CloseGuard {
+
+    /**
+     * Instance used when CloseGuard is disabled to avoid allocation.
+     */
+    private static final CloseGuard NOOP = new CloseGuard();
+
+    /**
+     * Returns a CloseGuard instance. If CloseGuard is enabled, {@code
+     * #open(String)} can be used to set up the instance to warn on
+     * failure to close. If CloseGuard is disabled, a non-null no-op
+     * instanace is returned.
+     */
+    public static CloseGuard get() {
+        if (!enabled()) {
+            return NOOP;
+        }
+        return new CloseGuard();
+    }
+
+    private static boolean enabled() {
+        boolean enabled = true;  // TODO replace compile time with runtime check
+        return enabled;
+    }
+
+    private CloseGuard() {}
+
+    /**
+     * If CloseGuard is enabled, {@code open} initializes the instance
+     * with a warning that the caller should have explictly called the
+     * {@code closer} method instead of relying on finalization.
+     *
+     * @param closer non-null name of explict termination method
+     * @throws NullPointerException if closer is null, regardless of
+     * whether or not CloseGuard is enabled
+     */
+    public void open(String closer) {
+        // always perform the check for valid API usage...
+        if (closer == null) {
+            throw new NullPointerException("closer == null");
+        }
+        // ...but avoid allocating an allocationSite if disabled
+        if (!enabled()) {
+            return;
+        }
+        String message = "Explicit termination method '" + closer + "' not called";
+        allocationSite = new Throwable(message);
+    }
+
+    private Throwable allocationSite;
+
+    /**
+     * Marks this CloseGuard instance as closed to avoid warnings on
+     * finalization.
+     */
+    public void close() {
+        allocationSite = null;
+    }
+
+    /**
+     * If CloseGuard is enabled, logs a warning if the caller did not
+     * properly cleanup by calling an explicit close method
+     * before finalization. If CloseGuard is disable, no action is
+     * performed.
+     */
+    public void warnIfOpen() {
+        if (allocationSite == null) {
+            return;
+        }
+
+        String message =
+                ("A resource was acquired at attached stack trace but never released. "
+                 + "See java.io.Closeable for information on avoiding resource leaks.");
+
+        Logger.global.log(Level.WARNING, message, allocationSite);
+    }
+}
diff --git a/dalvik/src/main/java/dalvik/system/DexFile.java b/dalvik/src/main/java/dalvik/system/DexFile.java
index 3ceefeb..0740f28 100644
--- a/dalvik/src/main/java/dalvik/system/DexFile.java
+++ b/dalvik/src/main/java/dalvik/system/DexFile.java
@@ -32,7 +32,8 @@
  */
 public final class DexFile {
     private final int mCookie;
-    private String mFileName;
+    private final String mFileName;
+    private final CloseGuard guard = CloseGuard.get();
 
     /**
      * Opens a DEX file from a given File object. This will usually be a ZIP/JAR
@@ -79,6 +80,7 @@
 
         mCookie = openDexFile(fileName, null, 0);
         mFileName = fileName;
+        guard.open("close");
         //System.out.println("DEX FILE cookie is " + mCookie);
     }
 
@@ -102,6 +104,7 @@
 
         mCookie = openDexFile(sourceName, outputName, flags);
         mFileName = sourceName;
+        guard.open("close");
         //System.out.println("DEX FILE cookie is " + mCookie);
     }
 
@@ -164,6 +167,7 @@
      * @cts Second sentence is a bit cryptic.
      */
     public void close() throws IOException {
+        guard.close();
         closeDexFile(mCookie);
     }
 
@@ -255,6 +259,9 @@
      */
     @Override protected void finalize() throws Throwable {
         try {
+            if (guard != null) {
+                guard.warnIfOpen();
+            }
             close();
         } finally {
             super.finalize();
diff --git a/icu/src/main/java/com/ibm/icu4jni/ThirdPartyProject.prop b/icu/src/main/java/com/ibm/icu4jni/ThirdPartyProject.prop
deleted file mode 100644
index 7469376..0000000
--- a/icu/src/main/java/com/ibm/icu4jni/ThirdPartyProject.prop
+++ /dev/null
@@ -1,10 +0,0 @@
-# Copyright 2010 Google Inc. All Rights Reserved.
-#Fri Jul 16 10:03:09 PDT 2010
-currentVersion=3.6
-version=Unknown
-isNative=true
-feedurl=http\://www.icu-project.org/repos/icu/icu4jni/trunk/readme.html
-name=icu4jni
-keywords=icu4jni
-onDevice=true
-homepage=http\://www.icu-project.org/repos/icu/icu4jni/trunk/readme.html
diff --git a/include/StaticAssert.h b/include/StaticAssert.h
new file mode 100644
index 0000000..ab809b3
--- /dev/null
+++ b/include/StaticAssert.h
@@ -0,0 +1,28 @@
+/*
+ * 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.
+ */
+
+#ifndef STATIC_ASSERT_H_included
+#define STATIC_ASSERT_H_included
+
+/**
+ * Similar to C++0x's static_assert. Message argument must be a valid identifier, not a string.
+ * Called COMPILE_ASSERT in Google, COMPILE_TIME_ASSERT in other places. This is the usual Google
+ * implementation.
+ */
+#define STATIC_ASSERT(exp, msg) typedef StaticAssert<(bool(exp))> msg[bool(exp) ? 1 : -1]
+template <bool> struct StaticAssert {};
+
+#endif  // STATIC_ASSERT_H_included
diff --git a/luni/src/main/java/com/ibm/icu4jni/common/ErrorCode.java b/luni/src/main/java/com/ibm/icu4jni/common/ErrorCode.java
deleted file mode 100644
index 42d1750..0000000
--- a/luni/src/main/java/com/ibm/icu4jni/common/ErrorCode.java
+++ /dev/null
@@ -1,205 +0,0 @@
-/**
-******************************************************************************
-* Copyright (C) 1996-2005, International Business Machines Corporation and   *
-* others. All Rights Reserved.                                               *
-******************************************************************************
-*
-******************************************************************************
-*/
-
-package com.ibm.icu4jni.common;
-
-/**
-* Error exception class mapping ICU error codes of the enum UErrorCode
-* @author syn wee quek
-* @internal
-*/
-public final class ErrorCode extends Exception
-{
-
-  // public methods --------------------------------------------------------
-
-  /**
-  * Generic mapping from the error codes to java default exceptions.
-  * @param error error code
-  * @return java default exception that maps to the argument error code,
-  *         otherwise if error is not a valid error code, null is returned.
-  * @stable ICU 2.4
-  */
-  public static final RuntimeException getException(int error)
-  {
-    if (error <= U_ZERO_ERROR && error >= U_ERROR_LIMIT) {
-      return null;
-    }
-    String errorname = ERROR_NAMES_[U_ILLEGAL_ARGUMENT_ERROR];
-    switch (error) {
-      case U_ILLEGAL_ARGUMENT_ERROR :
-        return new IllegalArgumentException(errorname);
-      case U_INDEX_OUTOFBOUNDS_ERROR :
-        return new ArrayIndexOutOfBoundsException(errorname);
-      case U_BUFFER_OVERFLOW_ERROR :
-        return new ArrayIndexOutOfBoundsException(errorname);
-      case U_UNSUPPORTED_ERROR :
-        return new UnsupportedOperationException(errorname);
-      default :
-        return new RuntimeException(errorname);
-    }
-  }
-
-  // public static data member ---------------------------------------------
-
-  /**
-  * Start of information results (semantically successful)
-  */
-  public static final int U_ERROR_INFO_START = -128;
-  /**
-  * A resource bundle lookup returned a fallback result (not an error)
-  */
-  public static final int U_USING_FALLBACK_ERROR = -128;
-  /**
-  * A resource bundle lookup returned a result from the root locale (not an
-  * error)
-  */
-  public static final int U_USING_DEFAULT_ERROR = -127;
-  /**
-  * A SafeClone operation required allocating memory (informational
-  * only
-  */
-  public static final int U_SAFECLONE_ALLOCATED_ERROR = -126;
-  /**
-  * This must always be the last warning value to indicate the limit for
-  * UErrorCode warnings (last warning code +1)
-  */
-  public static final int U_ERROR_INFO_LIMIT = -125;
-
-  /**
-  * No error, no warning
-  */
-  public static final int U_ZERO_ERROR = 0;
-  /**
-  * Start of codes indicating failure
-  */
-  public static final int U_ILLEGAL_ARGUMENT_ERROR = 1;
-  public static final int U_MISSING_RESOURCE_ERROR = 2;
-  public static final int U_INVALID_FORMAT_ERROR = 3;
-  public static final int U_FILE_ACCESS_ERROR = 4;
-  /**
-  * Indicates a bug in the library code
-  */
-  public static final int U_INTERNAL_PROGRAM_ERROR = 5;
-  public static final int U_MESSAGE_PARSE_ERROR = 6;
-  /**
-  * Memory allocation error
-  */
-  public static final int U_MEMORY_ALLOCATION_ERROR = 7;
-  public static final int U_INDEX_OUTOFBOUNDS_ERROR = 8;
-  /**
-  * Equivalent to Java ParseException
-  */
-  public static final int U_PARSE_ERROR = 9;
-  /**
-  * In the Character conversion routines: Invalid character or sequence was
-  * encountered
-  */
-  public static final int U_INVALID_CHAR_FOUND = 10;
-  /**
-  * In the Character conversion routines: More bytes are required to complete
-  * the conversion successfully
-  */
-  public static final int U_TRUNCATED_CHAR_FOUND = 11;
-  /**
-  * In codeset conversion: a sequence that does NOT belong in the codepage has
-  * been encountered
-  */
-  public static final int U_ILLEGAL_CHAR_FOUND = 12;
-  /**
-  * Conversion table file found, but corrupted
-  */
-  public static final int U_INVALID_TABLE_FORMAT = 13;
-  /**
-  * Conversion table file not found
-  */
-  public static final int U_INVALID_TABLE_FILE = 14;
-  /**
-  * A result would not fit in the supplied buffer
-  */
-  public static final int U_BUFFER_OVERFLOW_ERROR = 15;
-  /**
-  * Requested operation not supported in current context
-  */
-  public static final int U_UNSUPPORTED_ERROR = 16;
-  /**
-  * an operation is requested over a resource that does not support it
-  */
-  public static final int U_RESOURCE_TYPE_MISMATCH = 17;
-  /**
-  * ISO-2022 illlegal escape sequence
-  */
-  public static final int U_ILLEGAL_ESCAPE_SEQUENCE = 18;
-  /**
-  * ISO-2022 unsupported escape sequence
-  */
-  public static final int U_UNSUPPORTED_ESCAPE_SEQUENCE = 19;
-  /**
-  * No space available for in-buffer expansion for Arabic shaping
-  */
-  public static final int U_NO_SPACE_AVAILABLE = 20;
-  /**
-  * This must always be the last value to indicate the limit for UErrorCode
-  * (last error code +1)
-  */
-  public static final int U_ERROR_LIMIT = 21;
-  /**
-  * Load library flag
-  */
-  public static boolean LIBRARY_LOADED = false;
-
-  // private data member ----------------------------------------------------
-
-  /**
-  * Array of error code names corresponding to the errorcodes.
-  * ie ERROR_NAMES_[0] = name of U_ZERO_ERROR
-  */
-  private static final String ERROR_NAMES_[] = {
-    "U_ZERO_ERROR",               "U_ILLEGAL_ARGUMENT_ERROR",
-    "U_MISSING_RESOURCE_ERROR",   "U_INVALID_FORMAT_ERROR",
-    "U_FILE_ACCESS_ERROR",        "U_INTERNAL_PROGRAM_ERROR",
-    "U_MESSAGE_PARSE_ERROR",      "U_MEMORY_ALLOCATION_ERROR",
-    "U_INDEX_OUTOFBOUNDS_ERROR",  "U_PARSE_ERROR",
-    "U_INVALID_CHAR_FOUND",       "U_TRUNCATED_CHAR_FOUND",
-    "U_ILLEGAL_CHAR_FOUND",       "U_INVALID_TABLE_FORMAT",
-    "U_INVALID_TABLE_FILE",       "U_BUFFER_OVERFLOW_ERROR",
-    "U_UNSUPPORTED_ERROR",        "U_RESOURCE_TYPE_MISMATCH",
-    "U_ILLEGAL_ESCAPE_SEQUENCE",  "U_UNSUPPORTED_ESCAPE_SEQUENCE"
-  };
-  /**
-   * Returns the error name of the input error code
-   * @param ec int value of the error code
-   * @return String name of the error code
-   * @stable ICU 2.4
-   */
-  public static String getErrorName(int ec){
-    return ERROR_NAMES_[ec];
-  }
-
-  /**
-   * Returns true if the input error code denotes success
-   * @param ec int value of the error code
-   * @return boolean
-   * @stable ICU 2.4
-   */
-  public static boolean isSuccess(int ec){
-    return (ec<=U_ZERO_ERROR);
-  }
-
-  /**
-   * Returns true if the input error code denotes failure
-   * @param ec int value of the error code
-   * @return boolean
-   * @stable ICU 2.4
-   */
-  public static boolean isFailure(int ec){
-    return (ec>U_ZERO_ERROR);
-  }
-}
-
diff --git a/luni/src/main/java/com/ibm/icu4jni/text/CollationAttribute.java b/luni/src/main/java/com/ibm/icu4jni/text/CollationAttribute.java
deleted file mode 100644
index eaf626f..0000000
--- a/luni/src/main/java/com/ibm/icu4jni/text/CollationAttribute.java
+++ /dev/null
@@ -1,40 +0,0 @@
-/**
-*******************************************************************************
-* Copyright (C) 1996-2005, International Business Machines Corporation and    *
-* others. All Rights Reserved.                                                *
-*******************************************************************************
-*
-*******************************************************************************
-*/
-
-package com.ibm.icu4jni.text;
-
-/**
- * TODO: move these constants into NativeCollation.
- */
-public final class CollationAttribute {
-    // Values from the native UColAttributeValue enum.
-    public static final int VALUE_DEFAULT = -1;
-    public static final int VALUE_PRIMARY = 0;
-    public static final int VALUE_SECONDARY = 1;
-    public static final int VALUE_TERTIARY = 2;
-    public static final int VALUE_DEFAULT_STRENGTH = VALUE_TERTIARY;
-    public static final int VALUE_QUATERNARY = 3;
-    public static final int VALUE_IDENTICAL = 15;
-    public static final int VALUE_OFF = 16;
-    public static final int VALUE_ON = 17;
-    public static final int VALUE_SHIFTED = 20;
-    public static final int VALUE_NON_IGNORABLE = 21;
-    public static final int VALUE_LOWER_FIRST = 24;
-    public static final int VALUE_UPPER_FIRST = 25;
-    public static final int VALUE_ON_WITHOUT_HANGUL = 28;
-    public static final int VALUE_ATTRIBUTE_VALUE_COUNT = 29;
-    // Values from the UColAttribute enum.
-    public static final int FRENCH_COLLATION = 0;
-    public static final int ALTERNATE_HANDLING = 1;
-    public static final int CASE_FIRST = 2;
-    public static final int CASE_LEVEL = 3;
-    public static final int NORMALIZATION_MODE = 4;
-    public static final int DECOMPOSITION_MODE = NORMALIZATION_MODE;
-    public static final int STRENGTH = 5;
-}
diff --git a/luni/src/main/java/com/ibm/icu4jni/text/Collator.java b/luni/src/main/java/com/ibm/icu4jni/text/Collator.java
deleted file mode 100644
index 9c6ad3a..0000000
--- a/luni/src/main/java/com/ibm/icu4jni/text/Collator.java
+++ /dev/null
@@ -1,247 +0,0 @@
-/**
-*******************************************************************************
-* Copyright (C) 1996-2005, International Business Machines Corporation and    *
-* others. All Rights Reserved.                                                *
-*******************************************************************************
-*
-*
-*******************************************************************************
-*/
-
-package com.ibm.icu4jni.text;
-
-import java.util.Locale;
-
-public abstract class Collator implements Cloneable {
-    /**
-     * Strongest collator strength value. Typically used to denote differences
-     * between base characters. See class documentation for more explanation.
-     * @see #setStrength
-     * @see #getStrength
-     * @stable ICU 2.4
-     */
-    public final static int PRIMARY = CollationAttribute.VALUE_PRIMARY;
-
-    /**
-     * Second level collator strength value.
-     * Accents in the characters are considered secondary differences.
-     * Other differences between letters can also be considered secondary
-     * differences, depending on the language.
-     * See class documentation for more explanation.
-     * @see #setStrength
-     * @see #getStrength
-     * @stable ICU 2.4
-     */
-    public final static int SECONDARY = CollationAttribute.VALUE_SECONDARY;
-
-    /**
-     * Third level collator strength value.
-     * Upper and lower case differences in characters are distinguished at this
-     * strength level. In addition, a variant of a letter differs from the base
-     * form on the tertiary level.
-     * See class documentation for more explanation.
-     * @see #setStrength
-     * @see #getStrength
-     * @stable ICU 2.4
-     */
-    public final static int TERTIARY = CollationAttribute.VALUE_TERTIARY;
-
-    /**
-     * Fourth level collator strength value.
-     * When punctuation is ignored
-     * <a href="http://www-124.ibm.com/icu/userguide/Collate_Concepts.html#Ignoring_Punctuation">
-     * (see Ignoring Punctuations in the user guide)</a> at PRIMARY to TERTIARY
-     * strength, an additional strength level can
-     * be used to distinguish words with and without punctuation.
-     * See class documentation for more explanation.
-     * @see #setStrength
-     * @see #getStrength
-     * @stable ICU 2.4
-     */
-    public final static int QUATERNARY = CollationAttribute.VALUE_QUATERNARY;
-
-    /**
-     * <p>
-     * Smallest Collator strength value. When all other strengths are equal,
-     * the IDENTICAL strength is used as a tiebreaker. The Unicode code point
-     * values of the NFD form of each string are compared, just in case there
-     * is no difference.
-     * See class documentation for more explanation.
-     * </p>
-     * <p>
-     * Note this value is different from JDK's
-     * </p>
-     * @stable ICU 2.4
-     */
-    public final static int IDENTICAL = CollationAttribute.VALUE_IDENTICAL;
-
-    /**
-     * <p>Decomposition mode value. With NO_DECOMPOSITION set, Strings
-     * will not be decomposed for collation. This is the default
-     * decomposition setting unless otherwise specified by the locale
-     * used to create the Collator.</p>
-     *
-     * <p><strong>Note</strong> this value is different from the JDK's.</p>
-     * @see #CANONICAL_DECOMPOSITION
-     * @see #getDecomposition
-     * @see #setDecomposition
-     * @stable ICU 2.4
-     */
-    public final static int NO_DECOMPOSITION = CollationAttribute.VALUE_OFF;
-
-    /**
-     * <p>Decomposition mode value. With CANONICAL_DECOMPOSITION set,
-     * characters that are canonical variants according to the Unicode standard
-     * will be decomposed for collation.</p>
-     *
-     * <p>CANONICAL_DECOMPOSITION corresponds to Normalization Form D as
-     * described in <a href="http://www.unicode.org/unicode/reports/tr15/">
-     * Unicode Technical Report #15</a>.
-     * </p>
-     * @see #NO_DECOMPOSITION
-     * @see #getDecomposition
-     * @see #setDecomposition
-     * @stable ICU 2.4
-     */
-    public final static int CANONICAL_DECOMPOSITION = CollationAttribute.VALUE_ON;
-
-    public static Collator getInstance(Locale locale) {
-        return new RuleBasedCollator(locale);
-    }
-
-    public boolean equals(String source, String target) {
-        return (compare(source, target) == 0);
-    }
-
-    public abstract boolean equals(Object target);
-
-    public abstract Object clone() throws CloneNotSupportedException;
-
-    /**
-     * The comparison function compares the character data stored in two
-     * different strings. Returns information about whether a string is less
-     * than, greater than or equal to another string.
-     * <p>Example of use:
-     * <pre>
-     * .  Collator myCollation = Collator.getInstance(Locale::US);
-     * .  myCollation.setStrength(CollationAttribute.VALUE_PRIMARY);
-     * .  // result would be CollationAttribute.VALUE_EQUAL
-     * .  // ("abc" == "ABC")
-     * .  // (no primary difference between "abc" and "ABC")
-     * .  int result = myCollation.compare("abc", "ABC",3);
-     * .  myCollation.setStrength(CollationAttribute.VALUE_TERTIARY);
-     * .  // result would be Collation.LESS (abc" &lt;&lt;&lt; "ABC")
-     * .  // (with tertiary difference between "abc" and "ABC")
-     * .  int result = myCollation.compare("abc", "ABC",3);
-     * </pre>
-     * @stable ICU 2.4
-     */
-    public abstract int compare(String source, String target);
-
-    /**
-     * Get the decomposition mode of this Collator.
-     * @return the decomposition mode
-     * @see #CANONICAL_DECOMPOSITION
-     * @see #NO_DECOMPOSITION
-     * @stable ICU 2.4
-     */
-    public abstract int getDecomposition();
-
-    /**
-     * Set the normalization mode used int this object
-     * The normalization mode influences how strings are compared.
-     * @param mode desired normalization mode
-     * @see #CANONICAL_DECOMPOSITION
-     * @see #NO_DECOMPOSITION
-     * @stable ICU 2.4
-     */
-    public abstract void setDecomposition(int mode);
-
-    /**
-     * Determines the minimum strength that will be use in comparison or
-     * transformation.
-     * <p>
-     * E.g. with strength == SECONDARY, the tertiary difference is ignored
-     * </p>
-     * <p>
-     * E.g. with strength == PRIMARY, the secondary and tertiary difference
-     * are ignored.
-     * </p>
-     * @return the current comparison level.
-     * @see #PRIMARY
-     * @see #SECONDARY
-     * @see #TERTIARY
-     * @see #QUATERNARY
-     * @see #IDENTICAL
-     * @stable ICU 2.4
-     */
-    public abstract int getStrength();
-
-    /**
-     * Gets the attribute to be used in comparison or transformation.
-     * @param type the attribute to be set from CollationAttribute
-     * @return value attribute value from CollationAttribute
-     * @stable ICU 2.4
-     */
-    public abstract int getAttribute(int type);
-
-    /**
-     * Sets the minimum strength to be used in comparison or transformation.
-     * <p>Example of use:
-     * <pre>
-     * . Collator myCollation = Collator.createInstance(Locale::US);
-     * . myCollation.setStrength(PRIMARY);
-     * . // result will be "abc" == "ABC"
-     * . // tertiary differences will be ignored
-     * . int result = myCollation->compare("abc", "ABC");
-     * </pre>
-     * @param strength the new comparison level.
-     * @see #PRIMARY
-     * @see #SECONDARY
-     * @see #TERTIARY
-     * @see #QUATERNARY
-     * @see #IDENTICAL
-     * @stable ICU 2.4
-     */
-     public abstract void setStrength(int strength);
-
-    /**
-     * Sets the attribute to be used in comparison or transformation.
-     * <p>Example of use:
-     * <pre>
-     * . Collator myCollation = Collator.createInstance(Locale::US);
-     * . myCollation.setAttribute(CollationAttribute.CASE_LEVEL,
-     * .                          CollationAttribute.VALUE_ON);
-     * . int result = myCollation->compare("\\u30C3\\u30CF",
-     * .                                   "\\u30C4\\u30CF");
-     * . // result will be -1.
-     * </pre>
-     * @param type the attribute to be set from CollationAttribute
-     * @param value attribute value from CollationAttribute
-     * @stable ICU 2.4
-     */
-    public abstract void setAttribute(int type, int value);
-
-    /**
-     * Get the sort key as an CollationKey object from the argument string.
-     * To retrieve sort key in terms of byte arrays, use the method as below<br>
-     * <code>
-     * Collator collator = Collator.getInstance();
-     * CollationKey collationKey = collator.getCollationKey("string");
-     * byte[] array = collationKey.toByteArray();
-     * </code><br>
-     * Byte array result are zero-terminated and can be compared using
-     * java.util.Arrays.equals();
-     * @param source string to be processed.
-     * @return the sort key
-     * @stable ICU 2.4
-     */
-    public abstract CollationKey getCollationKey(String source);
-
-    /**
-     * Returns a hash of this collation object
-     * @return hash of this collation object
-     * @stable ICU 2.4
-     */
-    public abstract int hashCode();
-}
diff --git a/luni/src/main/java/com/ibm/icu4jni/text/NativeCollation.java b/luni/src/main/java/com/ibm/icu4jni/text/NativeCollation.java
deleted file mode 100644
index 6ff6535..0000000
--- a/luni/src/main/java/com/ibm/icu4jni/text/NativeCollation.java
+++ /dev/null
@@ -1,228 +0,0 @@
-/**
-*******************************************************************************
-* Copyright (C) 1996-2005, International Business Machines Corporation and    *
-* others. All Rights Reserved.                                                *
-*******************************************************************************
-*
-*
-*******************************************************************************
-*/
-
-package com.ibm.icu4jni.text;
-
-/**
-* Package static class for declaring all native methods for collation use.
-* @author syn wee quek
-* @internal ICU 2.4
-*/
-
-final class NativeCollation {
-  private NativeCollation() {
-  }
-
-  /**
-  * Method to create a new C Collator using the argument locale rules.
-  * @param locale locale name
-  * @return new c collator
-  * @internal ICU 2.4
-  */
-  static native int openCollator(String locale);
-
-  /**
-  * Method to create a new C Collator using the argument rules.
-  * @param rules , set of collation rules
-  * @param normalizationmode default normalization mode
-  * @param collationstrength default collation strength
-  * @return new c collator
-  * @internal ICU 2.4
-  */
-  static native int openCollatorFromRules(String rules,
-                                           int normalizationmode,
-                                           int collationstrength);
-
-  /**
-  * Close a C collator
-  * Once closed, a UCollatorOld should not be used.
-  * @param collatoraddress The UCollatorOld to close
-  * @internal ICU 2.4
-  */
-  static native void closeCollator(int collatoraddress);
-
-  /**
-  * Compare two strings.
-  * The strings will be compared using the normalization mode and options
-  * specified in openCollator or openCollatorFromRules
-  * @param collatoraddress address of the c collator
-  * @param source The source string.
-  * @param target The target string.
-  * @return result of the comparison, Collation.EQUAL,
-  *         Collation.GREATER or Collation.LESS
-  * @internal ICU 2.4
-  */
-  static native int compare(int collatoraddress, String source,
-                            String target);
-
-  /**
-  * Get the normalization mode for this object.
-  * The normalization mode influences how strings are compared.
-  * @param collatoraddress
-  * @return normalization mode; one of the values from Normalization
-  * @internal ICU 2.4
-  */
-  static native int getNormalization(int collatoraddress);
-
-  /**
-  * Set the normalization mode used int this object
-  * The normalization mode influences how strings are compared.
-  * @param collatoraddress the address of the C collator
-  * @param normalizationmode desired normalization mode; one of the values
-  *        from Normalization
-  * @internal ICU 2.4
-  */
-  static native void setNormalization(int collatoraddress,
-                                      int normalizationmode);
-
-  /**
-  * Get the collation rules from a UCollator.
-  * The rules will follow the rule syntax.
-  * @param collatoraddress the address of the C collator
-  * @return collation rules.
-  * @internal ICU 2.4
-  */
-  static native String getRules(int collatoraddress);
-
-  /**
-  * Get a sort key for the argument string
-  * Sort keys may be compared using java.util.Arrays.equals
-  * @param collatoraddress address of the C collator
-  * @param source string for key to be generated
-  * @return sort key
-  * @internal ICU 2.4
-  */
-  static native byte[] getSortKey(int collatoraddress, String source);
-
-  /**
-  * Gets the version information for collation.
-  * @param collatoraddress address of the C collator
-  * @return version information
-  * @internal ICU 2.4
-  */
-  // private native String getVersion(int collatoraddress);
-
-  /**
-  * Universal attribute setter.
-  * @param collatoraddress address of the C collator
-  * @param type type of attribute to be set
-  * @param value attribute value
-  * @exception RuntimeException when error occurs while setting attribute value
-  * @internal ICU 2.4
-  */
-  static native void setAttribute(int collatoraddress, int type, int value);
-
-  /**
-  * Universal attribute getter
-  * @param collatoraddress address of the C collator
-  * @param type type of attribute to be set
-  * @return attribute value
-  * @exception RuntimeException thrown when error occurs while getting attribute value
-  * @internal ICU 2.4
-  */
-  static native int getAttribute(int collatoraddress, int type);
-
-  /**
-  * Thread safe cloning operation
-  * @param collatoraddress address of C collator to be cloned
-  * @return address of the new clone
-  * @exception RuntimeException thrown when error occurs while cloning
-  * @internal ICU 2.4
-  */
-  static native int safeClone(int collatoraddress);
-
-  /**
-  * Create a CollationElementIterator object that will iterator over the
-  * elements in a string, using the collation rules defined in this
-  * RuleBasedCollator
-  * @param collatoraddress address of C collator
-  * @param source string to iterate over
-  * @return address of C collationelementiterator
-  * @internal ICU 2.4
-  */
-  static native int getCollationElementIterator(int collatoraddress,
-                                                 String source);
-
-
-  // collationelementiterator methods -------------------------------------
-
-  /**
-  * Close a C collation element iterator.
-  * @param address of C collation element iterator to close.
-  * @internal ICU 2.4
-  */
-  static native void closeElements(int address);
-
-  /**
-  * Reset the collation elements to their initial state.
-  * This will move the 'cursor' to the beginning of the text.
-  * @param address of C collation element iterator to reset.
-  * @internal ICU 2.4
-  */
-  static native void reset(int address);
-
-  /**
-  * Get the ordering priority of the next collation element in the text.
-  * A single character may contain more than one collation element.
-  * @param address if C collation elements containing the text.
-  * @return next collation elements ordering, or NULLORDER if the end of the
-  *         text is reached.
-  * @internal ICU 2.4
-  */
-  static native int next(int address);
-
-  /**
-  * Get the ordering priority of the previous collation element in the text.
-  * A single character may contain more than one collation element.
-  * @param address of the C collation element iterator containing the text.
-  * @return previous collation element ordering, or NULLORDER if the end of
-  *         the text is reached.
-  * @internal ICU 2.4
-  */
-  static native int previous(int address);
-
-  /**
-  * Get the maximum length of any expansion sequences that end with the
-  * specified comparison order.
-  * @param address of the C collation element iterator containing the text.
-  * @param order collation order returned by previous or next.
-  * @return maximum length of any expansion sequences ending with the
-  *         specified order.
-  * @internal ICU 2.4
-  */
-  static native int getMaxExpansion(int address, int order);
-
-  /**
-  * Set the text containing the collation elements.
-  * @param address of the C collation element iterator to be set
-  * @param source text containing the collation elements.
-  * @internal ICU 2.4
-  */
-  static native void setText(int address, String source);
-
-  /**
-  * Get the offset of the current source character.
-  * This is an offset into the text of the character containing the current
-  * collation elements.
-  * @param address of the C collation elements iterator to query.
-  * @return offset of the current source character.
-  * @internal ICU 2.4
-  */
-  static native int getOffset(int address);
-
-  /**
-  * Set the offset of the current source character.
-  * This is an offset into the text of the character to be processed.
-  * @param address of the C collation element iterator to set.
-  * @param offset The desired character offset.
-  * @internal ICU 2.4
-  */
-  static native void setOffset(int address, int offset);
-}
diff --git a/luni/src/main/java/com/ibm/icu4jni/text/RuleBasedCollator.java b/luni/src/main/java/com/ibm/icu4jni/text/RuleBasedCollator.java
deleted file mode 100644
index b2397bf..0000000
--- a/luni/src/main/java/com/ibm/icu4jni/text/RuleBasedCollator.java
+++ /dev/null
@@ -1,546 +0,0 @@
-/**
-*******************************************************************************
-* Copyright (C) 1996-2005, International Business Machines Corporation and    *
-* others. All Rights Reserved.                                                *
-*******************************************************************************
-*
-*
-*******************************************************************************
-*/
-
-package com.ibm.icu4jni.text;
-
-import java.text.CharacterIterator;
-import java.text.ParseException;
-import java.util.Locale;
-
-/**
-* Concrete implementation class for Collation.
-* <p>
-* The collation table is composed of a list of collation rules, where each
-* rule is of three forms:
-* <pre>
-*    < modifier >
-*    < relation > < text-argument >
-*    < reset > < text-argument >
-* </pre>
-* <p>
-* <code>RuleBasedCollator</code> has the following restrictions for efficiency
-* (other subclasses may be used for more complex languages) :
-* <ol>
-* <li> If a French secondary ordering is specified it applies to the whole
-*      collator object.
-* <li> All non-mentioned Unicode characters are at the end of the collation
-*      order.
-* <li> If a character is not located in the RuleBasedCollator, the default
-*      Unicode Collation Algorithm (UCA) rule-based table is automatically
-*      searched as a backup.
-* </ol>
-*
-* The following demonstrates how to create your own collation rules:
-* <UL Type=disc>
-*    <LI><strong>Text-Argument</strong>: A text-argument is any sequence of
-*        characters, excluding special characters (that is, common whitespace
-*        characters [0009-000D, 0020] and rule syntax characters [0021-002F,
-*        003A-0040, 005B-0060, 007B-007E]). If those characters are desired,
-*        you can put them in single quotes (e.g. ampersand => '&'). Note that
-*        unquoted white space characters are ignored; e.g. <code>b c</code> is
-*        treated as <code>bc</code>.
-*    <LI><strong>Modifier</strong>: There is a single modifier which is used
-*        to specify that all accents (secondary differences) are backwards.
-*        <p>'@' : Indicates that accents are sorted backwards, as in French.
-*    <LI><strong>Relation</strong>: The relations are the following:
-*        <UL Type=square>
-*            <LI>'<' : Greater, as a letter difference (primary)
-*            <LI>';' : Greater, as an accent difference (secondary)
-*            <LI>',' : Greater, as a case difference (tertiary)
-*            <LI>'=' : Equal
-*        </UL>
-*    <LI><strong>Reset</strong>: There is a single reset which is used
-*        primarily for contractions and expansions, but which can also be used
-*        to add a modification at the end of a set of rules.
-*        <p>'&' : Indicates that the next rule follows the position to where
-*            the reset text-argument would be sorted.
-* </UL>
-*
-* <p>
-* This sounds more complicated than it is in practice. For example, the
-* following are equivalent ways of expressing the same thing:
-* <blockquote>
-* <pre>
-* a < b < c
-* a < b & b < c
-* a < c & a < b
-* </pre>
-* </blockquote>
-* Notice that the order is important, as the subsequent item goes immediately
-* after the text-argument. The following are not equivalent:
-* <blockquote>
-* <pre>
-* a < b & a < c
-* a < c & a < b
-* </pre>
-* </blockquote>
-* Either the text-argument must already be present in the sequence, or some
-* initial substring of the text-argument must be present. (e.g. "a < b & ae <
-* e" is valid since "a" is present in the sequence before "ae" is reset). In
-* this latter case, "ae" is not entered and treated as a single character;
-* instead, "e" is sorted as if it were expanded to two characters: "a"
-* followed by an "e". This difference appears in natural languages: in
-* traditional Spanish "ch" is treated as though it contracts to a single
-* character (expressed as "c < ch < d"), while in traditional German a-umlaut
-* is treated as though it expanded to two characters (expressed as "a,A < b,B
-* ... & ae;? & AE;?"). [? and ? are, of course, the escape sequences for
-* a-umlaut.]
-* <p>
-* <strong>Ignorable Characters</strong>
-* <p>
-* For ignorable characters, the first rule must start with a relation (the
-* examples we have used above are really fragments; "a < b" really should be
-* "< a < b"). If, however, the first relation is not "<", then all the all
-* text-arguments up to the first "<" are ignorable. For example, ", - < a < b"
-* makes "-" an ignorable character, as we saw earlier in the word
-* "black-birds". In the samples for different languages, you see that most
-* accents are ignorable.
-*
-* <p><strong>Normalization and Accents</strong>
-* <p>
-* <code>RuleBasedCollator</code> automatically processes its rule table to
-* include both pre-composed and combining-character versions of accented
-* characters. Even if the provided rule string contains only base characters
-* and separate combining accent characters, the pre-composed accented
-* characters matching all canonical combinations of characters from the rule
-* string will be entered in the table.
-* <p>
-* This allows you to use a RuleBasedCollator to compare accented strings even
-* when the collator is set to NO_DECOMPOSITION. However, if the strings to be
-* collated contain combining sequences that may not be in canonical order, you
-* should set the collator to CANONICAL_DECOMPOSITION to enable sorting of
-* combining sequences.
-* For more information, see
-* <A HREF="http://www.aw.com/devpress">The Unicode Standard, Version 3.0</A>.)
-*
-* <p><strong>Errors</strong>
-* <p>
-* The following are errors:
-* <UL Type=disc>
-*     <LI>A text-argument contains unquoted punctuation symbols
-*        (e.g. "a < b-c < d").
-*     <LI>A relation or reset character not followed by a text-argument
-*        (e.g. "a < , b").
-*     <LI>A reset where the text-argument (or an initial substring of the
-*         text-argument) is not already in the sequence or allocated in the
-*         default UCA table.
-*         (e.g. "a < b & e < f")
-* </UL>
-* If you produce one of these errors, a <code>RuleBasedCollator</code> throws
-* a <code>ParseException</code>.
-*
-* <p><strong>Examples</strong>
-* <p>Simple:     "< a < b < c < d"
-* <p>Norwegian:  "< a,A< b,B< c,C< d,D< e,E< f,F< g,G< h,H< i,I< j,J
-*                 < k,K< l,L< m,M< n,N< o,O< p,P< q,Q< r,R< s,S< t,T
-*                < u,U< v,V< w,W< x,X< y,Y< z,Z
-*                 < ?=a?,?=A?
-*                 ;aa,AA< ?,?< ?,?"
-*
-* <p>
-* Normally, to create a rule-based Collator object, you will use
-* <code>Collator</code>'s factory method <code>getInstance</code>.
-* However, to create a rule-based Collator object with specialized rules
-* tailored to your needs, you construct the <code>RuleBasedCollator</code>
-* with the rules contained in a <code>String</code> object. For example:
-* <blockquote>
-* <pre>
-* String Simple = "< a < b < c < d";
-* RuleBasedCollator mySimple = new RuleBasedCollator(Simple);
-* </pre>
-* </blockquote>
-* Or:
-* <blockquote>
-* <pre>
-* String Norwegian = "< a,A< b,B< c,C< d,D< e,E< f,F< g,G< h,H< i,I< j,J" +
-*                 "< k,K< l,L< m,M< n,N< o,O< p,P< q,Q< r,R< s,S< t,T" +
-*                 "< u,U< v,V< w,W< x,X< y,Y< z,Z" +
-*                 "< ?=a?,?=A?" +
-*                 ";aa,AA< ?,?< ?,?";
-* RuleBasedCollator myNorwegian = new RuleBasedCollator(Norwegian);
-* </pre>
-* </blockquote>
-*
-* <p>
-* Combining <code>Collator</code>s is as simple as concatenating strings.
-* Here's an example that combines two <code>Collator</code>s from two
-* different locales:
-* <blockquote>
-* <pre>
-* // Create an en_US Collator object
-* RuleBasedCollator en_USCollator = (RuleBasedCollator)
-*     Collator.getInstance(new Locale("en", "US", ""));
-* // Create a da_DK Collator object
-* RuleBasedCollator da_DKCollator = (RuleBasedCollator)
-*     Collator.getInstance(new Locale("da", "DK", ""));
-* // Combine the two
-* // First, get the collation rules from en_USCollator
-* String en_USRules = en_USCollator.getRules();
-* // Second, get the collation rules from da_DKCollator
-* String da_DKRules = da_DKCollator.getRules();
-* RuleBasedCollator newCollator =
-*     new RuleBasedCollator(en_USRules + da_DKRules);
-* // newCollator has the combined rules
-* </pre>
-* </blockquote>
-*
-* <p>
-* Another more interesting example would be to make changes on an existing
-* table to create a new <code>Collator</code> object.  For example, add
-* "& C < ch, cH, Ch, CH" to the <code>en_USCollator</code> object to create
-* your own:
-* <blockquote>
-* <pre>
-* // Create a new Collator object with additional rules
-* String addRules = "& C < ch, cH, Ch, CH";
-* RuleBasedCollator myCollator =
-*     new RuleBasedCollator(en_USCollator + addRules);
-* // myCollator contains the new rules
-* </pre>
-* </blockquote>
-*
-* <p>
-* The following example demonstrates how to change the order of
-* non-spacing accents,
-* <blockquote>
-* <pre>
-* // old rule
-* String oldRules = "=?;?;?"    // main accents Diaeresis 00A8, Macron 00AF
-*                               // Acute 00BF
-*                 + "< a , A ; ae, AE ; ? , ?"
-*                 + "< b , B < c, C < e, E & C < d, D";
-* // change the order of accent characters
-* String addOn = "& ?;?;?;"; // Acute 00BF, Macron 00AF, Diaeresis 00A8
-* RuleBasedCollator myCollator = new RuleBasedCollator(oldRules + addOn);
-* </pre>
-* </blockquote>
-*
-* <p>
-* The last example shows how to put new primary ordering in before the
-* default setting. For example, in Japanese <code>Collator</code>, you
-* can either sort English characters before or after Japanese characters,
-* <blockquote>
-* <pre>
-* // get en_US Collator rules
-* RuleBasedCollator en_USCollator =
-*                      (RuleBasedCollator)Collator.getInstance(Locale.US);
-* // add a few Japanese character to sort before English characters
-* // suppose the last character before the first base letter 'a' in
-* // the English collation rule is ?
-* String jaString = "& \\u30A2 , \\u30FC < \\u30C8";
-* RuleBasedCollator myJapaneseCollator = new
-*     RuleBasedCollator(en_USCollator.getRules() + jaString);
-* </pre>
-* </blockquote>
-* <P>
-* @author syn wee quek
-* @stable ICU 2.4
-*/
-public final class RuleBasedCollator extends Collator {
-    private int m_collator_;
-    private int m_hashcode_ = 0;
-
-    /**
-     * RuleBasedCollator constructor. This takes the table rules and builds a
-     * collation table out of them. Please see RuleBasedCollator class
-     * description for more details on the collation rule syntax.
-     * @param rules the collation rules to build the collation table from.
-     * @exception ParseException thrown if rules are empty or a Runtime error
-     *            if collator can not be created.
-     * @stable ICU 2.4
-     */
-    public RuleBasedCollator(String rules) throws ParseException {
-        if (rules == null) {
-            throw new NullPointerException();
-        }
-        m_collator_ = NativeCollation.openCollatorFromRules(rules,
-                CollationAttribute.VALUE_OFF, CollationAttribute.VALUE_DEFAULT_STRENGTH);
-    }
-
-    /**
-     * RuleBasedCollator constructor. This takes the table rules and builds a
-     * collation table out of them. Please see RuleBasedCollator class
-     * description for more details on the collation rule syntax.
-     * @param rules the collation rules to build the collation table from.
-     * @param strength collation strength
-     * @exception ParseException thrown if rules are empty or a Runtime error
-     *            if collator can not be created.
-     * @see #PRIMARY
-     * @see #SECONDARY
-     * @see #TERTIARY
-     * @see #QUATERNARY
-     * @see #IDENTICAL
-     * @stable ICU 2.4
-     */
-    public RuleBasedCollator(String rules, int strength) throws ParseException {
-        if (rules == null) {
-            throw new NullPointerException();
-        }
-        m_collator_ = NativeCollation.openCollatorFromRules(rules, CollationAttribute.VALUE_OFF, strength);
-    }
-
-    /**
-     * RuleBasedCollator constructor. This takes the table rules and builds a
-     * collation table out of them. Please see RuleBasedCollator class
-     * description for more details on the collation rule syntax.
-     * <p>Note API change starting from release 2.4. Prior to release 2.4, the
-     * normalizationMode argument values are from the class
-     * com.ibm.icu4jni.text.Normalization. In 2.4,
-     * the valid normalizationMode arguments for this API are
-     * CollationAttribute.VALUE_ON and CollationAttribute.VALUE_OFF.
-     * </p>
-     * @param rules the collation rules to build the collation table from.
-     * @param strength collation strength
-     * @param normalizationMode normalization mode
-     * @exception IllegalArgumentException thrown when constructor error occurs
-     * @see #PRIMARY
-     * @see #SECONDARY
-     * @see #TERTIARY
-     * @see #QUATERNARY
-     * @see #IDENTICAL
-     * @see #CANONICAL_DECOMPOSITION
-     * @see #NO_DECOMPOSITION
-     * @stable ICU 2.4
-     */
-    public RuleBasedCollator(String rules, int normalizationMode, int strength) {
-        if (rules == null) {
-            throw new NullPointerException();
-        }
-        m_collator_ = NativeCollation.openCollatorFromRules(rules, normalizationMode, strength);
-    }
-
-    /**
-     * Makes a complete copy of the current object.
-     * @return a copy of this object if data clone is a success, otherwise null
-     * @stable ICU 2.4
-     */
-    public Object clone() {
-        RuleBasedCollator result = null;
-        int collatoraddress = NativeCollation.safeClone(m_collator_);
-        result = new RuleBasedCollator(collatoraddress);
-        return (Collator)result;
-    }
-
-    /**
-     * The comparison function compares the character data stored in two
-     * different strings. Returns information about whether a string is less
-     * than, greater than or equal to another string.
-     * <p>Example of use:
-     * <br>
-     * <code>
-     *   Collator myCollation = Collator.createInstance(Locale::US);
-     *   myCollation.setStrength(CollationAttribute.VALUE_PRIMARY);
-     *   // result would be 0 ("abc" == "ABC")
-     *   // (no primary difference between "abc" and "ABC")
-     *   int result = myCollation.compare("abc", "ABC",3);
-     *   myCollation.setStrength(CollationAttribute.VALUE_TERTIARY);
-     *   // result would be -1 (abc" &lt;&lt;&lt; "ABC")
-     *   // (with tertiary difference between "abc" and "ABC")
-     *   int result = myCollation.compare("abc", "ABC",3);
-     * </code>
-     */
-    public int compare(String source, String target) {
-        return NativeCollation.compare(m_collator_, source, target);
-    }
-
-    /**
-     * Get the normalization mode for this object.
-     * The normalization mode influences how strings are compared.
-     * @see #CANONICAL_DECOMPOSITION
-     * @see #NO_DECOMPOSITION
-     * @stable ICU 2.4
-     */
-    public int getDecomposition() {
-        return NativeCollation.getNormalization(m_collator_);
-    }
-
-    /**
-     * <p>Sets the decomposition mode of the Collator object on or off.
-     * If the decomposition mode is set to on, string would be decomposed into
-     * NFD format where necessary before sorting.</p>
-     * </p>
-     * @param decompositionmode the new decomposition mode
-     * @see #CANONICAL_DECOMPOSITION
-     * @see #NO_DECOMPOSITION
-     * @stable ICU 2.4
-     */
-    public void setDecomposition(int decompositionmode) {
-        NativeCollation.setAttribute(m_collator_,
-                CollationAttribute.NORMALIZATION_MODE, decompositionmode);
-    }
-
-    /**
-     * Determines the minimum strength that will be use in comparison or
-     * transformation.
-     * <p>
-     * E.g. with strength == CollationAttribute.VALUE_SECONDARY, the tertiary difference
-     * is ignored
-     * </p>
-     * <p>
-     * E.g. with strength == PRIMARY, the secondary and tertiary difference are
-     * ignored.
-     * </p>
-     * @return the current comparison level.
-     * @see #PRIMARY
-     * @see #SECONDARY
-     * @see #TERTIARY
-     * @see #QUATERNARY
-     * @see #IDENTICAL
-     * @stable ICU 2.4
-     */
-    public int getStrength() {
-        return NativeCollation.getAttribute(m_collator_, CollationAttribute.STRENGTH);
-    }
-
-    /**
-     * Sets the minimum strength to be used in comparison or transformation.
-     * <p>Example of use:
-     * <br>
-     * <code>
-     * Collator myCollation = Collator.createInstance(Locale::US);
-     * myCollation.setStrength(PRIMARY);
-     * // result will be "abc" == "ABC"
-     * // tertiary differences will be ignored
-     * int result = myCollation->compare("abc", "ABC");
-     * </code>
-     * @param strength the new comparison level.
-     * @exception IllegalArgumentException when argument does not belong to any collation strength
-     *            mode or error occurs while setting data.
-     * @see #PRIMARY
-     * @see #SECONDARY
-     * @see #TERTIARY
-     * @see #QUATERNARY
-     * @see #IDENTICAL
-     * @stable ICU 2.4
-     */
-    public void setStrength(int strength) {
-        NativeCollation.setAttribute(m_collator_, CollationAttribute.STRENGTH, strength);
-    }
-
-    /**
-     * Sets the attribute to be used in comparison or transformation.
-     * <p>Example of use:
-     * <br>
-     * <code>
-     *  Collator myCollation = Collator.createInstance(Locale::US);
-     *  myCollation.setAttribute(CollationAttribute.CASE_LEVEL,
-     *                           CollationAttribute.VALUE_ON);
-     *  int result = myCollation->compare("\\u30C3\\u30CF",
-     *                                    "\\u30C4\\u30CF");
-     * // result will be -1
-     * </code>
-     * @param type the attribute to be set from CollationAttribute
-     * @param value attribute value from CollationAttribute
-     * @stable ICU 2.4
-     */
-    public void setAttribute(int type, int value) {
-        NativeCollation.setAttribute(m_collator_, type, value);
-    }
-
-    /**
-     * Gets the attribute to be used in comparison or transformation.
-     * @param type the attribute to be set from CollationAttribute
-     * @return value attribute value from CollationAttribute
-     * @stable ICU 2.4
-     */
-    public int getAttribute(int type) {
-        return NativeCollation.getAttribute(m_collator_, type);
-    }
-
-    public CollationKey getCollationKey(String source) {
-        if (source == null) {
-            return null;
-        }
-        byte[] key = NativeCollation.getSortKey(m_collator_, source);
-        if (key == null) {
-            return null;
-        }
-        return new CollationKey(source, key);
-    }
-
-    /**
-     * Get the collation rules of this Collation object
-     * The rules will follow the rule syntax.
-     * @return collation rules.
-     * @stable ICU 2.4
-     */
-    public String getRules() {
-        return NativeCollation.getRules(m_collator_);
-    }
-
-    /**
-     * Create a CollationElementIterator object that will iterator over the
-     * elements in a string, using the collation rules defined in this
-     * RuleBasedCollator
-     * @param source string to iterate over
-     * @return address of C collationelement
-     * @exception IllegalArgumentException thrown when error occurs
-     * @stable ICU 2.4
-     */
-    public CollationElementIterator getCollationElementIterator(String source) {
-        CollationElementIterator result = new CollationElementIterator(
-                NativeCollation.getCollationElementIterator(m_collator_, source));
-        // result.setOwnCollationElementIterator(true);
-        return result;
-    }
-
-    public CollationElementIterator getCollationElementIterator(CharacterIterator it) {
-        // We only implement the String-based API, so build a string from the iterator.
-        return getCollationElementIterator(characterIteratorToString(it));
-    }
-
-    private String characterIteratorToString(CharacterIterator it) {
-        StringBuilder result = new StringBuilder();
-        for (char ch = it.current(); ch != CharacterIterator.DONE; ch = it.next()) {
-            result.append(ch);
-        }
-        return result.toString();
-    }
-
-    @Override
-    public int hashCode() {
-        return 42; // No-one uses RuleBasedCollator as a hash key.
-    }
-
-    /**
-     * Checks if argument object is equals to this object.
-     * @param target object
-     * @return true if source is equivalent to target, false otherwise
-     * @stable ICU 2.4
-     */
-    public boolean equals(Object object) {
-        if (object ==  this) {
-            return true;
-        }
-        if (!(object instanceof RuleBasedCollator)) {
-            return false;
-        }
-        RuleBasedCollator rhs = (RuleBasedCollator) object;
-        return getRules().equals(rhs.getRules()) &&
-                getStrength() == rhs.getStrength() &&
-                getDecomposition() == rhs.getDecomposition();
-    }
-
-    RuleBasedCollator(Locale locale) {
-        m_collator_ = NativeCollation.openCollator(locale.toString());
-    }
-
-    @Override protected void finalize() throws Throwable {
-        try {
-            NativeCollation.closeCollator(m_collator_);
-        } finally {
-            super.finalize();
-        }
-    }
-
-    private RuleBasedCollator(int addr) {
-        m_collator_ = addr;
-    }
-}
diff --git a/luni/src/main/java/java/awt/font/TextAttribute.java b/luni/src/main/java/java/awt/font/TextAttribute.java
index 4a17e4d..7743c50 100644
--- a/luni/src/main/java/java/awt/font/TextAttribute.java
+++ b/luni/src/main/java/java/awt/font/TextAttribute.java
@@ -20,10 +20,7 @@
  */
 package java.awt.font;
 
-import java.io.InvalidObjectException;
 import java.text.AttributedCharacterIterator.Attribute;
-import java.util.HashMap;
-import java.util.Map;
 
 /**
  * The TextAttribute class defines attribute keys and attribute values
@@ -42,10 +39,6 @@
     /** The Constant serialVersionUID. */
     private static final long serialVersionUID = 7744112784117861702L;
 
-    // set of available text attributes
-    /** The Constant attrMap. */
-    private static final Map<String, TextAttribute> attrMap = new HashMap<String, TextAttribute>();
-
     /**
      * Instantiates a new TextAttribute with the specified name.
      *
@@ -53,23 +46,6 @@
      */
     protected TextAttribute(String name) {
         super(name);
-        attrMap.put(name, this);
-    }
-
-    /**
-     * Resolves the instance being deserialized.
-     *
-     * @return the Object.
-     *
-     * @throws InvalidObjectException the InvalidObjectException.
-     */
-    @Override
-    protected Object readResolve() throws InvalidObjectException {
-        TextAttribute result = attrMap.get(this.getName());
-        if (result != null) {
-            return result;
-        }
-        throw new InvalidObjectException("Unknown attribute name");
     }
 
     /**
diff --git a/luni/src/main/java/java/io/Closeable.java b/luni/src/main/java/java/io/Closeable.java
index 623b656..56c2b3c 100644
--- a/luni/src/main/java/java/io/Closeable.java
+++ b/luni/src/main/java/java/io/Closeable.java
@@ -21,6 +21,15 @@
  * are not used any longer. This usually includes all sorts of
  * {@link InputStream}s and {@link OutputStream}s. Calling the {@code close}
  * method releases resources that the object holds.
+ * <p>
+ * A common pattern for using a {@code Closeable} resource: <pre>   {@code
+ *   Closable foo = new Foo();
+ *   try {
+ *      ...;
+ *   } finally {
+ *      foo.close();
+ *   }
+ * }</pre>
  */
 public interface Closeable {
 
@@ -32,4 +41,4 @@
      *             if any error occurs when closing the object.
      */
     public void close() throws IOException;
-}
\ No newline at end of file
+}
diff --git a/luni/src/main/java/java/io/DataInput.java b/luni/src/main/java/java/io/DataInput.java
index b6f3c72..4dad7eb 100644
--- a/luni/src/main/java/java/io/DataInput.java
+++ b/luni/src/main/java/java/io/DataInput.java
@@ -18,7 +18,7 @@
 package java.io;
 
 /**
- * Defines an interface for classes that are able to read typed data from some
+ * Defines an interface for classes that are able to read big-endian typed data from some
  * source. Typically, this data has been written by a class which implements
  * {@link DataOutput}. Types that can be read include byte, 16-bit short, 32-bit
  * int, 32-bit float, 64-bit long, 64-bit double, byte strings, and MUTF-8
@@ -71,7 +71,7 @@
     public abstract byte readByte() throws IOException;
 
     /**
-     * Reads a 16-bit character value.
+     * Reads a big-endian 16-bit character value.
      *
      * @return the next char value.
      * @throws EOFException if the end of the input is reached before the read
@@ -83,7 +83,7 @@
     public abstract char readChar() throws IOException;
 
     /**
-     * Reads a 64-bit double value.
+     * Reads a big-endian 64-bit double value.
      *
      * @return the next double value.
      * @throws EOFException if the end of the input is reached before the read
@@ -95,7 +95,7 @@
     public abstract double readDouble() throws IOException;
 
     /**
-     * Reads a 32-bit float value.
+     * Reads a big-endian 32-bit float value.
      *
      * @return the next float value.
      * @throws EOFException if the end of the input is reached before the read
@@ -140,11 +140,10 @@
      * @see DataOutput#write(byte[])
      * @see DataOutput#write(byte[], int, int)
      */
-    public abstract void readFully(byte[] buffer, int offset, int count)
-            throws IOException;
+    public abstract void readFully(byte[] buffer, int offset, int count) throws IOException;
 
     /**
-     * Reads a 32-bit integer value.
+     * Reads a big-endian 32-bit integer value.
      *
      * @return the next int value.
      * @throws EOFException if the end of the input is reached before the read
@@ -171,7 +170,7 @@
     public abstract String readLine() throws IOException;
 
     /**
-     * Reads a 64-bit long value.
+     * Reads a big-endian 64-bit long value.
      *
      * @return the next long value.
      * @throws EOFException if the end of the input is reached before the read
@@ -183,7 +182,7 @@
     public abstract long readLong() throws IOException;
 
     /**
-     * Reads a 16-bit short value.
+     * Reads a big-endian 16-bit short value.
      *
      * @return the next short value.
      * @throws EOFException if the end of the input is reached before the read
@@ -207,7 +206,7 @@
     public abstract int readUnsignedByte() throws IOException;
 
     /**
-     * Reads a 16-bit unsigned short value and returns it as an int.
+     * Reads a big-endian 16-bit unsigned short value and returns it as an int.
      *
      * @return the next unsigned short value.
      * @throws EOFException if the end of the input is reached before the read
diff --git a/luni/src/main/java/java/io/DataInputStream.java b/luni/src/main/java/java/io/DataInputStream.java
index b63e8bd..bcf22ca 100644
--- a/luni/src/main/java/java/io/DataInputStream.java
+++ b/luni/src/main/java/java/io/DataInputStream.java
@@ -20,7 +20,7 @@
 import java.nio.charset.ModifiedUtf8;
 
 /**
- * Wraps an existing {@link InputStream} and reads typed data from it.
+ * Wraps an existing {@link InputStream} and reads big-endian typed data from it.
  * Typically, this stream has been written by a DataOutputStream. Types that can
  * be read include byte, 16-bit short, 32-bit int, 32-bit float, 64-bit long,
  * 64-bit double, byte strings, and strings encoded in
@@ -93,17 +93,6 @@
         return in.read(buffer, offset, length);
     }
 
-    /**
-     * Reads a boolean from this stream.
-     *
-     * @return the next boolean value from the source stream.
-     * @throws EOFException
-     *             if the end of the filtered stream is reached before one byte
-     *             has been read.
-     * @throws IOException
-     *             if a problem occurs while reading from this stream.
-     * @see DataOutput#writeBoolean(boolean)
-     */
     public final boolean readBoolean() throws IOException {
         int temp = in.read();
         if (temp < 0) {
@@ -112,17 +101,6 @@
         return temp != 0;
     }
 
-    /**
-     * Reads an 8-bit byte value from this stream.
-     *
-     * @return the next byte value from the source stream.
-     * @throws EOFException
-     *             if the end of the filtered stream is reached before one byte
-     *             has been read.
-     * @throws IOException
-     *             if a problem occurs while reading from this stream.
-     * @see DataOutput#writeByte(int)
-     */
     public final byte readByte() throws IOException {
         int temp = in.read();
         if (temp < 0) {
@@ -131,17 +109,6 @@
         return (byte) temp;
     }
 
-    /**
-     * Reads a 16-bit character value from this stream.
-     *
-     * @return the next char value from the source stream.
-     * @throws EOFException
-     *             if the end of the filtered stream is reached before two bytes
-     *             have been read.
-     * @throws IOException
-     *             if a problem occurs while reading from this stream.
-     * @see DataOutput#writeChar(int)
-     */
     public final char readChar() throws IOException {
         if (readToBuff(2) < 0){
             throw new EOFException();
@@ -152,60 +119,24 @@
 
     private int readToBuff(int count) throws IOException {
         int offset = 0;
-
-        while(offset < count) {
+        while (offset < count) {
             int bytesRead = in.read(buff, offset, count - offset);
-            if(bytesRead == -1) return bytesRead;
+            if (bytesRead == -1) {
+                return bytesRead;
+            }
             offset += bytesRead;
         }
         return offset;
     }
 
-    /**
-     * Reads a 64-bit double value from this stream.
-     *
-     * @return the next double value from the source stream.
-     * @throws EOFException
-     *             if the end of the filtered stream is reached before eight
-     *             bytes have been read.
-     * @throws IOException
-     *             if a problem occurs while reading from this stream.
-     * @see DataOutput#writeDouble(double)
-     */
     public final double readDouble() throws IOException {
         return Double.longBitsToDouble(readLong());
     }
 
-    /**
-     * Reads a 32-bit float value from this stream.
-     *
-     * @return the next float value from the source stream.
-     * @throws EOFException
-     *             if the end of the filtered stream is reached before four
-     *             bytes have been read.
-     * @throws IOException
-     *             if a problem occurs while reading from this stream.
-     * @see DataOutput#writeFloat(float)
-     */
     public final float readFloat() throws IOException {
         return Float.intBitsToFloat(readInt());
     }
 
-    /**
-     * Reads bytes from this stream into the byte array {@code buffer}. This
-     * method will block until {@code buffer.length} number of bytes have been
-     * read.
-     *
-     * @param buffer
-     *            to read bytes into.
-     * @throws EOFException
-     *             if the end of the source stream is reached before enough
-     *             bytes have been read.
-     * @throws IOException
-     *             if a problem occurs while reading from this stream.
-     * @see DataOutput#write(byte[])
-     * @see DataOutput#write(byte[], int, int)
-     */
     public final void readFully(byte[] buffer) throws IOException {
         readFully(buffer, 0, buffer.length);
     }
@@ -236,11 +167,6 @@
      * @see java.io.DataInput#readFully(byte[], int, int)
      */
     public final void readFully(byte[] buffer, int offset, int length) throws IOException {
-        // BEGIN android-removed
-        // if (length < 0) {
-        //     throw new IndexOutOfBoundsException();
-        // }
-        // END android-removed
         if (length == 0) {
             return;
         }
@@ -269,17 +195,6 @@
         }
     }
 
-    /**
-     * Reads a 32-bit integer value from this stream.
-     *
-     * @return the next int value from the source stream.
-     * @throws EOFException
-     *             if the end of the filtered stream is reached before four
-     *             bytes have been read.
-     * @throws IOException
-     *             if a problem occurs while reading from this stream.
-     * @see DataOutput#writeInt(int)
-     */
     public final int readInt() throws IOException {
         if (readToBuff(4) < 0){
             throw new EOFException();
@@ -288,18 +203,6 @@
             ((buff[2] & 0xff) << 8) | (buff[3] & 0xff);
     }
 
-    /**
-     * Returns a string that contains the next line of text available from the
-     * source stream. A line is represented by zero or more characters followed
-     * by {@code '\n'}, {@code '\r'}, {@code "\r\n"} or the end of the stream.
-     * The string does not include the newline sequence.
-     *
-     * @return the contents of the line or {@code null} if no characters were
-     *         read before the end of the source stream has been reached.
-     * @throws IOException
-     *             if a problem occurs while reading from this stream.
-     * @deprecated Use {@link BufferedReader}
-     */
     @Deprecated
     public final String readLine() throws IOException {
         StringBuilder line = new StringBuilder(80); // Typical line length
@@ -335,17 +238,6 @@
         }
     }
 
-    /**
-     * Reads a 64-bit long value from this stream.
-     *
-     * @return the next long value from the source stream.
-     * @throws EOFException
-     *             if the end of the filtered stream is reached before eight
-     *             bytes have been read.
-     * @throws IOException
-     *             if a problem occurs while reading from this stream.
-     * @see DataOutput#writeLong(long)
-     */
     public final long readLong() throws IOException {
         if (readToBuff(8) < 0){
             throw new EOFException();
@@ -358,17 +250,6 @@
         return ((i1 & 0xffffffffL) << 32) | (i2 & 0xffffffffL);
     }
 
-    /**
-     * Reads a 16-bit short value from this stream.
-     *
-     * @return the next short value from the source stream.
-     * @throws EOFException
-     *             if the end of the filtered stream is reached before two bytes
-     *             have been read.
-     * @throws IOException
-     *             if a problem occurs while reading from this stream.
-     * @see DataOutput#writeShort(int)
-     */
     public final short readShort() throws IOException {
         if (readToBuff(2) < 0){
             throw new EOFException();
@@ -376,18 +257,6 @@
         return (short) (((buff[0] & 0xff) << 8) | (buff[1] & 0xff));
     }
 
-    /**
-     * Reads an unsigned 8-bit byte value from this stream and returns it as an
-     * int.
-     *
-     * @return the next unsigned byte value from the source stream.
-     * @throws EOFException
-     *             if the end of the filtered stream has been reached before one
-     *             byte has been read.
-     * @throws IOException
-     *             if a problem occurs while reading from this stream.
-     * @see DataOutput#writeByte(int)
-     */
     public final int readUnsignedByte() throws IOException {
         int temp = in.read();
         if (temp < 0) {
@@ -396,18 +265,6 @@
         return temp;
     }
 
-    /**
-     * Reads a 16-bit unsigned short value from this stream and returns it as an
-     * int.
-     *
-     * @return the next unsigned short value from the source stream.
-     * @throws EOFException
-     *             if the end of the filtered stream is reached before two bytes
-     *             have been read.
-     * @throws IOException
-     *             if a problem occurs while reading from this stream.
-     * @see DataOutput#writeShort(int)
-     */
     public final int readUnsignedShort() throws IOException {
         if (readToBuff(2) < 0){
             throw new EOFException();
@@ -415,23 +272,10 @@
         return (char) (((buff[0] & 0xff) << 8) | (buff[1] & 0xff));
     }
 
-    /**
-     * Reads an string encoded in {@link DataInput modified UTF-8} from this
-     * stream.
-     *
-     * @return the next {@link DataInput MUTF-8} encoded string read from the
-     *         source stream.
-     * @throws EOFException if the end of the input is reached before the read
-     *         request can be satisfied.
-     * @throws IOException
-     *             if a problem occurs while reading from this stream.
-     * @see DataOutput#writeUTF(java.lang.String)
-     */
     public final String readUTF() throws IOException {
         return decodeUTF(readUnsignedShort());
     }
 
-
     String decodeUTF(int utfSize) throws IOException {
         return decodeUTF(utfSize, this);
     }
@@ -442,18 +286,6 @@
         return ModifiedUtf8.decode(buf, new char[utfSize], 0, utfSize);
     }
 
-    /**
-     * Reads a string encoded in {@link DataInput modified UTF-8} from the
-     * {@code DataInput} stream {@code in}.
-     *
-     * @param in
-     *            the input stream to read from.
-     * @return the next {@link DataInput MUTF-8} encoded string from the source
-     *         stream.
-     * @throws IOException
-     *             if a problem occurs while reading from this stream.
-     * @see DataOutputStream#writeUTF(java.lang.String)
-     */
     public static final String readUTF(DataInput in) throws IOException {
         return decodeUTF(in.readUnsignedShort(), in);
     }
@@ -479,11 +311,6 @@
         while (skipped < count && (skip = in.skip(count - skipped)) != 0) {
             skipped += skip;
         }
-        // BEGIN android-removed
-        // if (skipped < 0) {
-        //     throw new EOFException();
-        // }
-        // END android-removed
         return skipped;
     }
 }
diff --git a/luni/src/main/java/java/io/DataOutput.java b/luni/src/main/java/java/io/DataOutput.java
index 8275958..1707a2f 100644
--- a/luni/src/main/java/java/io/DataOutput.java
+++ b/luni/src/main/java/java/io/DataOutput.java
@@ -18,7 +18,7 @@
 package java.io;
 
 /**
- * Defines an interface for classes that are able to write typed data to some
+ * Defines an interface for classes that are able to write big-endian typed data to some
  * target. Typically, this data can be read in by a class which implements
  * DataInput. Types that can be written include byte, 16-bit short, 32-bit int,
  * 32-bit float, 64-bit long, 64-bit double, byte strings, and {@link DataInput
@@ -58,9 +58,6 @@
      * @see DataInput#readFully(byte[], int, int)
      */
     public abstract void write(byte[] buffer, int offset, int count) throws IOException;
-    // BEGIN android-note
-    // changed array notation to be consistent with the rest of harmony
-    // END android-note
 
     /**
      * Writes the specified 8-bit byte.
@@ -109,9 +106,8 @@
     public abstract void writeBytes(String str) throws IOException;
 
     /**
-     * Writes the specified 16-bit character. Only the two least significant
-     * bytes of the integer {@code oneByte} are written, with the higher one
-     * written first. This represents the Unicode value of the char.
+     * Writes the specified 16-bit character in big-endian order. Only the two least significant
+     * bytes of the integer {@code oneByte} are written.
      *
      * @param val
      *            the character to write.
@@ -122,7 +118,7 @@
     public abstract void writeChar(int val) throws IOException;
 
     /**
-     * Writes the 16-bit characters contained in {@code str}.
+     * Writes the 16-bit characters contained in {@code str} in big-endian order.
      *
      * @param str
      *            the string that contains the characters to write.
@@ -133,7 +129,7 @@
     public abstract void writeChars(String str) throws IOException;
 
     /**
-     * Writes the specified 64-bit double. The resulting output is the eight
+     * Writes the specified 64-bit double in big-endian order. The resulting output is the eight
      * bytes returned by {@link Double#doubleToLongBits(double)}.
      *
      * @param val
@@ -145,7 +141,7 @@
     public abstract void writeDouble(double val) throws IOException;
 
     /**
-     * Writes the specified 32-bit float. The resulting output is the four bytes
+     * Writes the specified 32-bit float in big-endian order. The resulting output is the four bytes
      * returned by {@link Float#floatToIntBits(float)}.
      *
      * @param val
@@ -157,8 +153,7 @@
     public abstract void writeFloat(float val) throws IOException;
 
     /**
-     * Writes the specified 32-bit int. The resulting output is the four bytes,
-     * highest order first, of {@code val}.
+     * Writes the specified 32-bit int in big-endian order.
      *
      * @param val
      *            the int to write.
@@ -169,8 +164,7 @@
     public abstract void writeInt(int val) throws IOException;
 
     /**
-     * Writes the specified 64-bit long. The resulting output is the eight
-     * bytes, highest order first, of {@code val}.
+     * Writes the specified 64-bit long in big-endian order.
      *
      * @param val
      *            the long to write.
@@ -181,8 +175,8 @@
     public abstract void writeLong(long val) throws IOException;
 
     /**
-     * Writes the specified 16-bit short. Only the lower two bytes of {@code
-     * val} are written with the higher one written first.
+     * Writes the specified 16-bit short in big-endian order. Only the lower two bytes of {@code
+     * val} are written.
      *
      * @param val
      *            the short to write.
diff --git a/luni/src/main/java/java/io/DataOutputStream.java b/luni/src/main/java/java/io/DataOutputStream.java
index 6427fb1..bb80530 100644
--- a/luni/src/main/java/java/io/DataOutputStream.java
+++ b/luni/src/main/java/java/io/DataOutputStream.java
@@ -17,8 +17,10 @@
 
 package java.io;
 
+import java.nio.charset.ModifiedUtf8;
+
 /**
- * Wraps an existing {@link OutputStream} and writes typed data to it.
+ * Wraps an existing {@link OutputStream} and writes big-endian typed data to it.
  * Typically, this stream can be read in by DataInputStream. Types that can be
  * written include byte, 16-bit short, 32-bit int, 32-bit float, 64-bit long,
  * 64-bit double, byte strings, and {@link DataInput MUTF-8} encoded strings.
@@ -89,9 +91,6 @@
      */
     @Override
     public void write(byte[] buffer, int offset, int count) throws IOException {
-        // BEGIN android-note
-        // changed array notation to be consistent with the rest of harmony
-        // END android-note
         if (buffer == null) {
             throw new NullPointerException("buffer == null");
         }
@@ -145,16 +144,6 @@
         written++;
     }
 
-    /**
-     * Writes the low order bytes from a string to the target stream.
-     *
-     * @param str
-     *            the string containing the bytes to write to the target stream.
-     * @throws IOException
-     *             if an error occurs while writing to the target stream.
-     * @see DataInputStream#readFully(byte[])
-     * @see DataInputStream#readFully(byte[],int,int)
-     */
     public final void writeBytes(String str) throws IOException {
         if (str.length() == 0) {
             return;
@@ -167,17 +156,6 @@
         written += bytes.length;
     }
 
-    /**
-     * Writes a 16-bit character to the target stream. Only the two lower bytes
-     * of the integer {@code val} are written, with the higher one written
-     * first. This corresponds to the Unicode value of {@code val}.
-     *
-     * @param val
-     *            the character to write to the target stream
-     * @throws IOException
-     *             if an error occurs while writing to the target stream.
-     * @see DataInputStream#readChar()
-     */
     public final void writeChar(int val) throws IOException {
         buff[0] = (byte) (val >> 8);
         buff[1] = (byte) val;
@@ -185,66 +163,20 @@
         written += 2;
     }
 
-    /**
-     * Writes the 16-bit characters contained in {@code str} to the target
-     * stream.
-     *
-     * @param str
-     *            the string that contains the characters to write to this
-     *            stream.
-     * @throws IOException
-     *             if an error occurs while writing to the target stream.
-     * @see DataInputStream#readChar()
-     */
     public final void writeChars(String str) throws IOException {
-        byte[] newBytes = new byte[str.length() * 2];
-        for (int index = 0; index < str.length(); index++) {
-            int newIndex = index == 0 ? index : index * 2;
-            newBytes[newIndex] = (byte) (str.charAt(index) >> 8);
-            newBytes[newIndex + 1] = (byte) str.charAt(index);
-        }
-        out.write(newBytes);
-        written += newBytes.length;
+        byte[] bytes = str.getBytes("UTF-16BE");
+        out.write(bytes);
+        written += bytes.length;
     }
 
-    /**
-     * Writes a 64-bit double to the target stream. The resulting output is the
-     * eight bytes resulting from calling Double.doubleToLongBits().
-     *
-     * @param val
-     *            the double to write to the target stream.
-     * @throws IOException
-     *             if an error occurs while writing to the target stream.
-     * @see DataInputStream#readDouble()
-     */
     public final void writeDouble(double val) throws IOException {
         writeLong(Double.doubleToLongBits(val));
     }
 
-    /**
-     * Writes a 32-bit float to the target stream. The resulting output is the
-     * four bytes resulting from calling Float.floatToIntBits().
-     *
-     * @param val
-     *            the float to write to the target stream.
-     * @throws IOException
-     *             if an error occurs while writing to the target stream.
-     * @see DataInputStream#readFloat()
-     */
     public final void writeFloat(float val) throws IOException {
         writeInt(Float.floatToIntBits(val));
     }
 
-    /**
-     * Writes a 32-bit int to the target stream. The resulting output is the
-     * four bytes, highest order first, of {@code val}.
-     *
-     * @param val
-     *            the int to write to the target stream.
-     * @throws IOException
-     *             if an error occurs while writing to the target stream.
-     * @see DataInputStream#readInt()
-     */
     public final void writeInt(int val) throws IOException {
         buff[0] = (byte) (val >> 24);
         buff[1] = (byte) (val >> 16);
@@ -254,16 +186,6 @@
         written += 4;
     }
 
-    /**
-     * Writes a 64-bit long to the target stream. The resulting output is the
-     * eight bytes, highest order first, of {@code val}.
-     *
-     * @param val
-     *            the long to write to the target stream.
-     * @throws IOException
-     *             if an error occurs while writing to the target stream.
-     * @see DataInputStream#readLong()
-     */
     public final void writeLong(long val) throws IOException {
         buff[0] = (byte) (val >> 56);
         buff[1] = (byte) (val >> 48);
@@ -277,30 +199,6 @@
         written += 8;
     }
 
-    int writeLongToBuffer(long val, byte[] buffer, int offset) throws IOException {
-        buffer[offset++] = (byte) (val >> 56);
-        buffer[offset++] = (byte) (val >> 48);
-        buffer[offset++] = (byte) (val >> 40);
-        buffer[offset++] = (byte) (val >> 32);
-        buffer[offset++] = (byte) (val >> 24);
-        buffer[offset++] = (byte) (val >> 16);
-        buffer[offset++] = (byte) (val >> 8);
-        buffer[offset++] = (byte) val;
-        return offset;
-    }
-
-    /**
-     * Writes the specified 16-bit short to the target stream. Only the lower
-     * two bytes of the integer {@code val} are written, with the higher one
-     * written first.
-     *
-     * @param val
-     *            the short to write to the target stream.
-     * @throws IOException
-     *             if an error occurs while writing to the target stream.
-     * @see DataInputStream#readShort()
-     * @see DataInputStream#readUnsignedShort()
-     */
     public final void writeShort(int val) throws IOException {
         buff[0] = (byte) (val >> 8);
         buff[1] = (byte) val;
@@ -308,67 +206,7 @@
         written += 2;
     }
 
-    int writeShortToBuffer(int val, byte[] buffer, int offset) throws IOException {
-        buffer[offset++] = (byte) (val >> 8);
-        buffer[offset++] = (byte) val;
-        return offset;
-    }
-
-    /**
-     * Writes the specified encoded in {@link DataInput modified UTF-8} to this
-     * stream.
-     *
-     * @param str
-     *            the string to write to the target stream encoded in
-     *            {@link DataInput modified UTF-8}.
-     * @throws IOException
-     *             if an error occurs while writing to the target stream.
-     * @throws UTFDataFormatException
-     *             if the encoded string is longer than 65535 bytes.
-     * @see DataInputStream#readUTF()
-     */
     public final void writeUTF(String str) throws IOException {
-        long utfCount = countUTFBytes(str);
-        if (utfCount > 65535) {
-            throw new UTFDataFormatException("String more than 65535 UTF bytes long");
-        }
-        byte[] buffer = new byte[(int)utfCount + 2];
-        int offset = 0;
-        offset = writeShortToBuffer((int) utfCount, buffer, offset);
-        offset = writeUTFBytesToBuffer(str, buffer, offset);
-        write(buffer, 0, offset);
-    }
-
-    long countUTFBytes(String str) {
-        int utfCount = 0, length = str.length();
-        for (int i = 0; i < length; i++) {
-            int charValue = str.charAt(i);
-            if (charValue > 0 && charValue <= 127) {
-                utfCount++;
-            } else if (charValue <= 2047) {
-                utfCount += 2;
-            } else {
-                utfCount += 3;
-            }
-        }
-        return utfCount;
-    }
-
-    int writeUTFBytesToBuffer(String str, byte[] buffer, int offset) throws IOException {
-        int length = str.length();
-        for (int i = 0; i < length; i++) {
-            int charValue = str.charAt(i);
-            if (charValue > 0 && charValue <= 127) {
-                buffer[offset++] = (byte) charValue;
-            } else if (charValue <= 2047) {
-                buffer[offset++] = (byte) (0xc0 | (0x1f & (charValue >> 6)));
-                buffer[offset++] = (byte) (0x80 | (0x3f & charValue));
-            } else {
-                buffer[offset++] = (byte) (0xe0 | (0x0f & (charValue >> 12)));
-                buffer[offset++] = (byte) (0x80 | (0x3f & (charValue >> 6)));
-                buffer[offset++] = (byte) (0x80 | (0x3f & charValue));
-             }
-        }
-        return offset;
+        write(ModifiedUtf8.encode(str));
     }
 }
diff --git a/luni/src/main/java/java/io/FileInputStream.java b/luni/src/main/java/java/io/FileInputStream.java
index b55ab8b..5eb78fc 100644
--- a/luni/src/main/java/java/io/FileInputStream.java
+++ b/luni/src/main/java/java/io/FileInputStream.java
@@ -17,6 +17,7 @@
 
 package java.io;
 
+import dalvik.system.CloseGuard;
 import java.nio.NioUtils;
 import java.nio.channels.FileChannel;
 import libcore.io.IoUtils;
@@ -58,6 +59,8 @@
 
     private final Object repositioningLock = new Object();
 
+    private final CloseGuard guard = CloseGuard.get();
+
     /**
      * Constructs a new {@code FileInputStream} that reads from {@code file}.
      *
@@ -81,6 +84,7 @@
         fd.readOnly = true;
         fd.descriptor = Platform.FILE_SYSTEM.open(file.getAbsolutePath(), IFileSystem.O_RDONLY);
         shouldCloseFd = true;
+        guard.open("close");
     }
 
     /**
@@ -104,6 +108,7 @@
         }
         this.fd = fd;
         this.shouldCloseFd = false;
+        this.guard.open("close");
     }
 
     /**
@@ -121,6 +126,7 @@
 
     @Override
     public void close() throws IOException {
+        guard.close();
         synchronized (this) {
             if (channel != null) {
                 channel.close();
@@ -140,6 +146,9 @@
      */
     @Override protected void finalize() throws IOException {
         try {
+            if (guard != null) {
+                guard.warnIfOpen();
+            }
             close();
         } finally {
             try {
diff --git a/luni/src/main/java/java/io/FileOutputStream.java b/luni/src/main/java/java/io/FileOutputStream.java
index 8ac77ef..796d79e 100644
--- a/luni/src/main/java/java/io/FileOutputStream.java
+++ b/luni/src/main/java/java/io/FileOutputStream.java
@@ -17,6 +17,7 @@
 
 package java.io;
 
+import dalvik.system.CloseGuard;
 import java.nio.NioUtils;
 import java.nio.channels.FileChannel;
 import libcore.io.IoUtils;
@@ -60,6 +61,8 @@
     /** File access mode */
     private final int mode;
 
+    private final CloseGuard guard = CloseGuard.get();
+
     /**
      * Constructs a new {@code FileOutputStream} that writes to {@code file}.
      *
@@ -96,6 +99,7 @@
         this.mode = append ? IFileSystem.O_APPEND : IFileSystem.O_WRONLY;
         this.fd.descriptor = Platform.FILE_SYSTEM.open(file.getAbsolutePath(), mode);
         this.shouldCloseFd = true;
+        this.guard.open("close");
     }
 
     /**
@@ -119,6 +123,7 @@
         this.shouldCloseFd = false;
         this.channel = NioUtils.newFileChannel(this, fd.descriptor, IFileSystem.O_WRONLY);
         this.mode = IFileSystem.O_WRONLY;
+        this.guard.open("close");
     }
 
     /**
@@ -137,6 +142,7 @@
 
     @Override
     public void close() throws IOException {
+        guard.close();
         synchronized (this) {
             if (channel != null) {
                 channel.close();
@@ -156,6 +162,9 @@
      */
     @Override protected void finalize() throws IOException {
         try {
+            if (guard != null) {
+                guard.warnIfOpen();
+            }
             close();
         } finally {
             try {
diff --git a/luni/src/main/java/java/io/FilterInputStream.java b/luni/src/main/java/java/io/FilterInputStream.java
index 75b312c..98f4f71 100644
--- a/luni/src/main/java/java/io/FilterInputStream.java
+++ b/luni/src/main/java/java/io/FilterInputStream.java
@@ -179,7 +179,7 @@
      * used. This implementation skips {@code count} number of bytes in the
      * filtered stream.
      *
-     * @param count
+     * @param byteCount
      *            the number of bytes to skip.
      * @return the number of bytes actually skipped.
      * @throws IOException
@@ -188,7 +188,7 @@
      * @see #reset()
      */
     @Override
-    public long skip(long count) throws IOException {
-        return in.skip(count);
+    public long skip(long byteCount) throws IOException {
+        return in.skip(byteCount);
     }
 }
diff --git a/luni/src/main/java/java/io/LineNumberInputStream.java b/luni/src/main/java/java/io/LineNumberInputStream.java
index 31828e9..b0b3841 100644
--- a/luni/src/main/java/java/io/LineNumberInputStream.java
+++ b/luni/src/main/java/java/io/LineNumberInputStream.java
@@ -17,6 +17,8 @@
 
 package java.io;
 
+import libcore.base.Streams;
+
 /**
  * Wraps an existing {@link InputStream} and counts the line terminators
  * encountered while reading the data. Line numbering starts at 0. Recognized
@@ -230,7 +232,7 @@
      * filtered stream and increments the line number count whenever line
      * terminator sequences are skipped.
      *
-     * @param count
+     * @param byteCount
      *            the number of bytes to skip.
      * @return the number of bytes actually skipped.
      * @throws IOException
@@ -240,16 +242,7 @@
      * @see #reset()
      */
     @Override
-    public long skip(long count) throws IOException {
-        if (count <= 0) {
-            return 0;
-        }
-        for (int i = 0; i < count; i++) {
-            int currentChar = read();
-            if (currentChar == -1) {
-                return i;
-            }
-        }
-        return count;
+    public long skip(long byteCount) throws IOException {
+        return Streams.skipByReading(this, byteCount);
     }
 }
diff --git a/luni/src/main/java/java/io/ObjectOutputStream.java b/luni/src/main/java/java/io/ObjectOutputStream.java
index cde98f7..2c5eb7a 100644
--- a/luni/src/main/java/java/io/ObjectOutputStream.java
+++ b/luni/src/main/java/java/io/ObjectOutputStream.java
@@ -20,8 +20,11 @@
 import java.lang.reflect.InvocationTargetException;
 import java.lang.reflect.Method;
 import java.lang.reflect.Proxy;
+import java.nio.ByteOrder;
+import java.nio.charset.ModifiedUtf8;
 import java.util.IdentityHashMap;
-
+import libcore.io.SizeOf;
+import org.apache.harmony.luni.platform.OSMemory;
 
 // BEGIN android-note
 // Harmony uses ObjectAccessors to access fields through JNI. Android has not
@@ -1602,22 +1605,23 @@
      * @throws IOException
      *             If an IO exception happened when writing the String.
      */
-    private Integer writeNewString(String object, boolean unshared)
-            throws IOException {
-        long count = output.countUTFBytes(object);
+    private Integer writeNewString(String object, boolean unshared) throws IOException {
+        long count = ModifiedUtf8.countBytes(object, false);
         byte[] buffer;
         int offset = 0;
         if (count <= 0xffff) {
-            buffer = new byte[(int)count+3];
+            buffer = new byte[1 + SizeOf.SHORT + (int) count];
             buffer[offset++] = TC_STRING;
-            offset = output.writeShortToBuffer((short) count, buffer, offset);
+            OSMemory.pokeShort(buffer, offset, (short) count, ByteOrder.BIG_ENDIAN);
+            offset += SizeOf.SHORT;
         } else {
-            buffer = new byte[(int)count+9];
+            buffer = new byte[1 + SizeOf.LONG + (int) count];
             buffer[offset++] = TC_LONGSTRING;
-            offset = output.writeLongToBuffer(count, buffer, offset);
+            OSMemory.pokeLong(buffer, offset, count, ByteOrder.BIG_ENDIAN);
+            offset += SizeOf.LONG;
         }
-        offset = output.writeUTFBytesToBuffer(object, buffer, offset);
-        output.write(buffer, 0, offset);
+        ModifiedUtf8.encode(buffer, offset, object);
+        output.write(buffer, 0, buffer.length);
 
         Integer handle = nextHandle();
 
diff --git a/luni/src/main/java/java/io/RandomAccessFile.java b/luni/src/main/java/java/io/RandomAccessFile.java
index d835396..cccd695 100644
--- a/luni/src/main/java/java/io/RandomAccessFile.java
+++ b/luni/src/main/java/java/io/RandomAccessFile.java
@@ -17,6 +17,7 @@
 
 package java.io;
 
+import dalvik.system.CloseGuard;
 import java.nio.NioUtils;
 import java.nio.channels.FileChannel;
 import java.nio.charset.ModifiedUtf8;
@@ -46,6 +47,8 @@
 
     private int mode;
 
+    private final CloseGuard guard = CloseGuard.get();
+
     /**
      * Constructs a new {@code RandomAccessFile} based on {@code file} and opens
      * it according to the access string in {@code mode}.
@@ -132,6 +135,7 @@
                 // Ignored
             }
         }
+        guard.open("close");
     }
 
     /**
@@ -169,6 +173,7 @@
      *             if an error occurs while closing this file.
      */
     public void close() throws IOException {
+        guard.close();
         synchronized (this) {
             if (channel != null && channel.isOpen()) {
                 channel.close();
@@ -182,6 +187,9 @@
 
     @Override protected void finalize() throws Throwable {
         try {
+            if (guard != null) {
+                guard.warnIfOpen();
+            }
             close();
         } finally {
             super.finalize();
@@ -909,13 +917,7 @@
      * @see #readChar()
      */
     public final void writeChars(String str) throws IOException {
-        byte[] newBytes = new byte[str.length() * 2];
-        for (int index = 0; index < str.length(); index++) {
-            int newIndex = index == 0 ? index : index * 2;
-            newBytes[newIndex] = (byte) ((str.charAt(index) >> 8) & 0xFF);
-            newBytes[newIndex + 1] = (byte) (str.charAt(index) & 0xFF);
-        }
-        write(newBytes);
+        write(str.getBytes("UTF-16BE"));
     }
 
     /**
@@ -1021,37 +1023,6 @@
      * @see #readUTF()
      */
     public final void writeUTF(String str) throws IOException {
-        int utfCount = 0, length = str.length();
-        for (int i = 0; i < length; i++) {
-            int charValue = str.charAt(i);
-            if (charValue > 0 && charValue <= 127) {
-                utfCount++;
-            } else if (charValue <= 2047) {
-                utfCount += 2;
-            } else {
-                utfCount += 3;
-            }
-        }
-        if (utfCount > 65535) {
-            throw new UTFDataFormatException("String more than 65535 UTF bytes long");
-        }
-        byte[] utfBytes = new byte[utfCount + 2];
-        int utfIndex = 2;
-        for (int i = 0; i < length; i++) {
-            int charValue = str.charAt(i);
-            if (charValue > 0 && charValue <= 127) {
-                utfBytes[utfIndex++] = (byte) charValue;
-            } else if (charValue <= 2047) {
-                utfBytes[utfIndex++] = (byte) (0xc0 | (0x1f & (charValue >> 6)));
-                utfBytes[utfIndex++] = (byte) (0x80 | (0x3f & charValue));
-            } else {
-                utfBytes[utfIndex++] = (byte) (0xe0 | (0x0f & (charValue >> 12)));
-                utfBytes[utfIndex++] = (byte) (0x80 | (0x3f & (charValue >> 6)));
-                utfBytes[utfIndex++] = (byte) (0x80 | (0x3f & charValue));
-            }
-        }
-        utfBytes[0] = (byte) (utfCount >> 8);
-        utfBytes[1] = (byte) utfCount;
-        write(utfBytes);
+        write(ModifiedUtf8.encode(str));
     }
 }
diff --git a/luni/src/main/java/java/lang/Byte.java b/luni/src/main/java/java/lang/Byte.java
index 043a9f3..619b3f8 100644
--- a/luni/src/main/java/java/lang/Byte.java
+++ b/luni/src/main/java/java/lang/Byte.java
@@ -126,7 +126,7 @@
         if (result == intValue) {
             return valueOf(result);
         }
-        throw new NumberFormatException();
+        throw new NumberFormatException("Value out of range for byte: \"" + string + "\"");
     }
 
     @Override
@@ -182,12 +182,7 @@
      *             can not be parsed as a byte value.
      */
     public static byte parseByte(String string) throws NumberFormatException {
-        int intValue = Integer.parseInt(string);
-        byte result = (byte) intValue;
-        if (result == intValue) {
-            return result;
-        }
-        throw new NumberFormatException();
+        return parseByte(string, 10);
     }
 
     /**
@@ -206,14 +201,13 @@
      *             {@code radix > Character.MAX_RADIX}, or if {@code string}
      *             can not be parsed as a byte value.
      */
-    public static byte parseByte(String string, int radix)
-            throws NumberFormatException {
+    public static byte parseByte(String string, int radix) throws NumberFormatException {
         int intValue = Integer.parseInt(string, radix);
         byte result = (byte) intValue;
         if (result == intValue) {
             return result;
         }
-        throw new NumberFormatException();
+        throw new NumberFormatException("Value out of range for byte: \"" + string + "\"");
     }
 
     @Override
@@ -271,8 +265,7 @@
      *             can not be parsed as a byte value.
      * @see #parseByte(String, int)
      */
-    public static Byte valueOf(String string, int radix)
-            throws NumberFormatException {
+    public static Byte valueOf(String string, int radix) throws NumberFormatException {
         return valueOf(parseByte(string, radix));
     }
 
diff --git a/luni/src/main/java/java/lang/CaseMapper.java b/luni/src/main/java/java/lang/CaseMapper.java
index 58a4412..94cf62d 100644
--- a/luni/src/main/java/java/lang/CaseMapper.java
+++ b/luni/src/main/java/java/lang/CaseMapper.java
@@ -16,8 +16,8 @@
 
 package java.lang;
 
-import com.ibm.icu4jni.util.ICU;
 import java.util.Locale;
+import libcore.icu.ICU;
 
 /**
  * Performs case operations as described by http://unicode.org/reports/tr21/tr21-5.html.
diff --git a/luni/src/main/java/java/lang/Integer.java b/luni/src/main/java/java/lang/Integer.java
index c8ac552..db45a7f 100644
--- a/luni/src/main/java/java/lang/Integer.java
+++ b/luni/src/main/java/java/lang/Integer.java
@@ -129,6 +129,10 @@
         return thisValue < thatValue ? -1 : (thisValue == thatValue ? 0 : 1);
     }
 
+    private static NumberFormatException invalidInt(String s) {
+        throw new NumberFormatException("Invalid int: \"" + s + "\"");
+    }
+
     /**
      * Parses the specified string and returns a {@code Integer} instance if the
      * string can be decoded into an integer value. The string may be an
@@ -145,17 +149,13 @@
     public static Integer decode(String string) throws NumberFormatException {
         int length = string.length(), i = 0;
         if (length == 0) {
-            // BEGIN android-changed
-            throw new NumberFormatException("unable to parse '"+string+"' as integer");
-            // END android-changed
+            throw invalidInt(string);
         }
         char firstDigit = string.charAt(i);
         boolean negative = firstDigit == '-';
         if (negative) {
             if (length == 1) {
-                // BEGIN android-changed
-                throw new NumberFormatException("unable to parse '"+string+"' as integer");
-                // END android-changed
+                throw invalidInt(string);
             }
             firstDigit = string.charAt(++i);
         }
@@ -167,9 +167,7 @@
             }
             if ((firstDigit = string.charAt(i)) == 'x' || firstDigit == 'X') {
                 if (++i == length) {
-                    // BEGIN android-changed
-                    throw new NumberFormatException("unable to parse '"+string+"' as integer");
-                    // END android-changed
+                    throw invalidInt(string);
                 }
                 base = 16;
             } else {
@@ -177,9 +175,7 @@
             }
         } else if (firstDigit == '#') {
             if (++i == length) {
-                // BEGIN android-changed
-                throw new NumberFormatException("unable to parse '"+string+"' as integer");
-                // END android-changed
+                throw invalidInt(string);
             }
             base = 16;
         }
@@ -348,60 +344,46 @@
      *             {@code radix > Character.MAX_RADIX}, or if {@code string}
      *             can not be parsed as an integer value.
      */
-    public static int parseInt(String string, int radix)
-            throws NumberFormatException {
-        if (string == null || radix < Character.MIN_RADIX
-                || radix > Character.MAX_RADIX) {
-            // BEGIN android-changed
-            throw new NumberFormatException("unable to parse '"+string+"' as integer");
-            // END android-changed
+    public static int parseInt(String string, int radix) throws NumberFormatException {
+        if (radix < Character.MIN_RADIX || radix > Character.MAX_RADIX) {
+            throw new NumberFormatException("Invalid radix: " + radix);
+        }
+        if (string == null) {
+            throw invalidInt(string);
         }
         int length = string.length(), i = 0;
         if (length == 0) {
-            // BEGIN android-changed
-            throw new NumberFormatException("unable to parse '"+string+"' as integer");
-            // END android-changed
+            throw invalidInt(string);
         }
         boolean negative = string.charAt(i) == '-';
         if (negative && ++i == length) {
-            // BEGIN android-changed
-            throw new NumberFormatException("unable to parse '"+string+"' as integer");
-            // END android-changed
+            throw invalidInt(string);
         }
 
         return parse(string, i, radix, negative);
     }
 
-    private static int parse(String string, int offset, int radix,
-            boolean negative) throws NumberFormatException {
+    private static int parse(String string, int offset, int radix, boolean negative) throws NumberFormatException {
         int max = Integer.MIN_VALUE / radix;
         int result = 0, length = string.length();
         while (offset < length) {
             int digit = Character.digit(string.charAt(offset++), radix);
             if (digit == -1) {
-                // BEGIN android-changed
-                throw new NumberFormatException("unable to parse '"+string+"' as integer");
-                // END android-changed
+                throw invalidInt(string);
             }
             if (max > result) {
-                // BEGIN android-changed
-                throw new NumberFormatException("unable to parse '"+string+"' as integer");
-                // END android-changed
+                throw invalidInt(string);
             }
             int next = result * radix - digit;
             if (next > result) {
-                // BEGIN android-changed
-                throw new NumberFormatException("unable to parse '"+string+"' as integer");
-                // END android-changed
+                throw invalidInt(string);
             }
             result = next;
         }
         if (!negative) {
             result = -result;
             if (result < 0) {
-                // BEGIN android-changed
-                throw new NumberFormatException("unable to parse '"+string+"' as integer");
-                // END android-changed
+                throw invalidInt(string);
             }
         }
         return result;
diff --git a/luni/src/main/java/java/lang/Long.java b/luni/src/main/java/java/lang/Long.java
index 7b7e5f3..ecc4e50 100644
--- a/luni/src/main/java/java/lang/Long.java
+++ b/luni/src/main/java/java/lang/Long.java
@@ -116,6 +116,10 @@
         return thisValue < thatValue ? -1 : (thisValue == thatValue ? 0 : 1);
     }
 
+    private static NumberFormatException invalidLong(String s) {
+        throw new NumberFormatException("Invalid long: \"" + s + "\"");
+    }
+
     /**
      * Parses the specified string and returns a {@code Long} instance if the
      * string can be decoded into a long value. The string may be an optional
@@ -131,13 +135,13 @@
     public static Long decode(String string) throws NumberFormatException {
         int length = string.length(), i = 0;
         if (length == 0) {
-            throw new NumberFormatException();
+            throw invalidLong(string);
         }
         char firstDigit = string.charAt(i);
         boolean negative = firstDigit == '-';
         if (negative) {
             if (length == 1) {
-                throw new NumberFormatException(string);
+                throw invalidLong(string);
             }
             firstDigit = string.charAt(++i);
         }
@@ -149,7 +153,7 @@
             }
             if ((firstDigit = string.charAt(i)) == 'x' || firstDigit == 'X') {
                 if (i == length) {
-                    throw new NumberFormatException(string);
+                    throw invalidLong(string);
                 }
                 i++;
                 base = 16;
@@ -158,7 +162,7 @@
             }
         } else if (firstDigit == '#') {
             if (i == length) {
-                throw new NumberFormatException(string);
+                throw invalidLong(string);
             }
             i++;
             base = 16;
@@ -328,17 +332,19 @@
      *             can not be parsed as a long value.
      */
     public static long parseLong(String string, int radix) throws NumberFormatException {
-        if (string == null || radix < Character.MIN_RADIX
-                || radix > Character.MAX_RADIX) {
-            throw new NumberFormatException();
+        if (radix < Character.MIN_RADIX || radix > Character.MAX_RADIX) {
+            throw new NumberFormatException("Invalid radix: " + radix);
+        }
+        if (string == null) {
+            throw invalidLong(string);
         }
         int length = string.length(), i = 0;
         if (length == 0) {
-            throw new NumberFormatException(string);
+            throw invalidLong(string);
         }
         boolean negative = string.charAt(i) == '-';
         if (negative && ++i == length) {
-            throw new NumberFormatException(string);
+            throw invalidLong(string);
         }
 
         return parse(string, i, radix, negative);
@@ -350,21 +356,21 @@
         while (offset < length) {
             int digit = Character.digit(string.charAt(offset++), radix);
             if (digit == -1) {
-                throw new NumberFormatException(string);
+                throw invalidLong(string);
             }
             if (max > result) {
-                throw new NumberFormatException(string);
+                throw invalidLong(string);
             }
             long next = result * radix - digit;
             if (next > result) {
-                throw new NumberFormatException(string);
+                throw invalidLong(string);
             }
             result = next;
         }
         if (!negative) {
             result = -result;
             if (result < 0) {
-                throw new NumberFormatException(string);
+                throw invalidLong(string);
             }
         }
         return result;
diff --git a/luni/src/main/java/java/lang/Short.java b/luni/src/main/java/java/lang/Short.java
index fd7bca0..93d2172 100644
--- a/luni/src/main/java/java/lang/Short.java
+++ b/luni/src/main/java/java/lang/Short.java
@@ -126,7 +126,7 @@
         if (result == intValue) {
             return valueOf(result);
         }
-        throw new NumberFormatException();
+        throw new NumberFormatException("Value out of range for short: \"" + string + "\"");
     }
 
     @Override
@@ -201,14 +201,13 @@
      *             {@code radix > Character.MAX_RADIX}, or if {@code string}
      *             can not be parsed as a short value.
      */
-    public static short parseShort(String string, int radix)
-            throws NumberFormatException {
+    public static short parseShort(String string, int radix) throws NumberFormatException {
         int intValue = Integer.parseInt(string, radix);
         short result = (short) intValue;
         if (result == intValue) {
             return result;
         }
-        throw new NumberFormatException();
+        throw new NumberFormatException("Value out of range for short: \"" + string + "\"");
     }
 
     /**
diff --git a/luni/src/main/java/java/lang/String.java b/luni/src/main/java/java/lang/String.java
index 333909f..605ea67 100644
--- a/luni/src/main/java/java/lang/String.java
+++ b/luni/src/main/java/java/lang/String.java
@@ -991,6 +991,8 @@
             return Charsets.toIsoLatin1Bytes(value, offset, count);
         } else if (canonicalCharsetName.equals("US-ASCII")) {
             return Charsets.toAsciiBytes(value, offset, count);
+        } else if (canonicalCharsetName.equals("UTF-16BE")) {
+            return Charsets.toBigEndianUtf16Bytes(value, offset, count);
         } else {
             CharBuffer chars = CharBuffer.wrap(this.value, this.offset, this.count);
             ByteBuffer buffer = charset.encode(chars.asReadOnlyBuffer());
@@ -1029,7 +1031,6 @@
         }
     }
 
-    // BEGIN android-added
     /**
      * Version of getChars without bounds checks, for use by other classes
      * within the java.lang package only.  The caller is responsible for
@@ -1039,26 +1040,21 @@
         // NOTE last character not copied!
         System.arraycopy(value, start + offset, buffer, index, end - start);
     }
-    // END android-added
 
-    @Override
-    public int hashCode() {
-        // BEGIN android-changed
+    @Override public int hashCode() {
         int hash = hashCode;
         if (hash == 0) {
-            int multiplier = 1;
-            int _offset = offset;
-            int _count = count;
-            char[] _value = value;
-            for (int i = _offset + _count - 1; i >= _offset; i--) {
-                hash += _value[i] * multiplier;
-                int shifted = multiplier << 5;
-                multiplier = shifted - multiplier;
+            if (count == 0) {
+                return 0;
+            }
+            final int end = count + offset;
+            final char[] chars = value;
+            for (int i = offset; i < end; ++i) {
+                hash = 31*hash + chars[i];
             }
             hashCode = hash;
         }
         return hash;
-        // END android-changed
     }
 
     /**
diff --git a/luni/src/main/java/java/math/BigDecimal.java b/luni/src/main/java/java/math/BigDecimal.java
index f419897..d4c7f43 100644
--- a/luni/src/main/java/java/math/BigDecimal.java
+++ b/luni/src/main/java/java/math/BigDecimal.java
@@ -289,7 +289,8 @@
             throw new NullPointerException();
         }
         if ((last >= in.length) || (offset < 0) || (len <= 0) || (last < 0)) {
-            throw new NumberFormatException();
+            throw new NumberFormatException("Bad offset/length: offset=" + offset +
+                    " len=" + len + " in.length=" + in.length);
         }
         unscaledBuffer = new StringBuilder(len);
         int bufLength = 0;
@@ -301,8 +302,7 @@
         int counter = 0;
         boolean wasNonZero = false;
         // Accumulating all digits until a possible decimal point
-        for (; (offset <= last) && (in[offset] != '.')
-        && (in[offset] != 'e') && (in[offset] != 'E'); offset++) {
+        for (; (offset <= last) && (in[offset] != '.') && (in[offset] != 'e') && (in[offset] != 'E'); offset++) {
             if (!wasNonZero) {
                 if (in[offset] == '0') {
                     counter++;
@@ -496,7 +496,7 @@
      */
     public BigDecimal(double val) {
         if (Double.isInfinite(val) || Double.isNaN(val)) {
-            throw new NumberFormatException("Infinity or NaN");
+            throw new NumberFormatException("Infinity or NaN: " + val);
         }
         long bits = Double.doubleToLongBits(val); // IEEE-754
         long mantissa;
@@ -774,7 +774,7 @@
      */
     public static BigDecimal valueOf(double val) {
         if (Double.isInfinite(val) || Double.isNaN(val)) {
-            throw new NumberFormatException("Infinity or NaN");
+            throw new NumberFormatException("Infinity or NaN: " + val);
         }
         return new BigDecimal(Double.toString(val));
     }
diff --git a/luni/src/main/java/java/math/BigInt.java b/luni/src/main/java/java/math/BigInt.java
index 9955a1d..1768676 100644
--- a/luni/src/main/java/java/math/BigInt.java
+++ b/luni/src/main/java/java/math/BigInt.java
@@ -21,21 +21,17 @@
  * Any Bit-Operations, including Shifting, solely regard the unsigned magnitude.
  * Moreover BigInt objects are mutable and offer efficient in-place-operations.
  */
-class BigInt {
+final class BigInt {
 
     /* Fields used for the internal representation. */
     transient int bignum = 0;
 
-    public void dispose() {
-        if (this.bignum != 0) {
-            NativeBN.BN_free(this.bignum);
-            this.bignum = 0;
-        }
-    }
-
     @Override protected void finalize() throws Throwable {
         try {
-            dispose();
+            if (this.bignum != 0) {
+                NativeBN.BN_free(this.bignum);
+                this.bignum = 0;
+            }
         } finally {
             super.finalize();
         }
@@ -46,11 +42,11 @@
         return this.decString();
     }
 
-    public int getNativeBIGNUM() {
+    int getNativeBIGNUM() {
         return this.bignum;
     }
 
-    public static int consumeErrors(StringBuilder sb) {
+    static int consumeErrors(StringBuilder sb) {
         int cnt = 0;
         int e, reason;
         while ((e = NativeBN.ERR_get_error()) != 0) {
@@ -97,50 +93,54 @@
     }
 
 
-    public static int cmp(BigInt a, BigInt b) {
+    static int cmp(BigInt a, BigInt b) {
         return NativeBN.BN_cmp(a.bignum, b.bignum);
     }
 
 
-    public void putCopy(BigInt from) {
+    void putCopy(BigInt from) {
         this.makeValid();
         Check(NativeBN.BN_copy(this.bignum, from.bignum));
     }
 
-    public BigInt copy() {
+    BigInt copy() {
         BigInt bi = new BigInt();
         bi.putCopy(this);
         return bi;
     }
 
 
-    public void putLongInt(long val) {
+    void putLongInt(long val) {
         this.makeValid();
         Check(NativeBN.putLongInt(this.bignum, val));
     }
 
-    public void putULongInt(long val, boolean neg) {
+    void putULongInt(long val, boolean neg) {
         this.makeValid();
         Check(NativeBN.putULongInt(this.bignum, val, neg));
     }
 
-    public void putDecString(String original) {
+    private NumberFormatException invalidBigInteger(String s) {
+        throw new NumberFormatException("Invalid BigInteger: " + s);
+    }
+
+    void putDecString(String original) {
         String s = checkString(original, 10);
         this.makeValid();
         int usedLen = NativeBN.BN_dec2bn(this.bignum, s);
         Check((usedLen > 0));
         if (usedLen < s.length()) {
-            throw new NumberFormatException(original);
+            throw invalidBigInteger(original);
         }
     }
 
-    public void putHexString(String original) {
+    void putHexString(String original) {
         String s = checkString(original, 16);
         this.makeValid();
         int usedLen = NativeBN.BN_hex2bn(this.bignum, s);
         Check((usedLen > 0));
         if (usedLen < s.length()) {
-            throw new NumberFormatException(original);
+            throw invalidBigInteger(original);
         }
     }
 
@@ -151,7 +151,7 @@
      * ensure we comply with Java's rules.
      * http://code.google.com/p/android/issues/detail?id=7036
      */
-    public String checkString(String s, int base) {
+    String checkString(String s, int base) {
         if (s == null) {
             throw new NullPointerException();
         }
@@ -171,13 +171,13 @@
             }
         }
         if (charCount - i == 0) {
-            throw new NumberFormatException(s);
+            throw invalidBigInteger(s);
         }
         boolean nonAscii = false;
         for (; i < charCount; ++i) {
             char ch = s.charAt(i);
             if (Character.digit(ch, base) == -1) {
-                throw new NumberFormatException(s);
+                throw invalidBigInteger(s);
             }
             if (ch > 128) {
                 nonAscii = true;
@@ -203,159 +203,164 @@
         return result.toString();
     }
 
-    public void putBigEndian(byte[] a, boolean neg) {
+    void putBigEndian(byte[] a, boolean neg) {
         this.makeValid();
         Check(NativeBN.BN_bin2bn(a, a.length, neg, this.bignum));
     }
 
-    public void putLittleEndianInts(int[] a, boolean neg) {
+    void putLittleEndianInts(int[] a, boolean neg) {
         this.makeValid();
         Check(NativeBN.litEndInts2bn(a, a.length, neg, this.bignum));
     }
 
-    public void putBigEndianTwosComplement(byte[] a) {
+    void putBigEndianTwosComplement(byte[] a) {
         this.makeValid();
         Check(NativeBN.twosComp2bn(a, a.length, this.bignum));
     }
 
 
-    public long longInt() {
+    long longInt() {
         return NativeBN.longInt(this.bignum);
     }
 
-    public String decString() {
+    String decString() {
         return NativeBN.BN_bn2dec(this.bignum);
     }
 
-    public String hexString() {
+    String hexString() {
         return NativeBN.BN_bn2hex(this.bignum);
     }
 
-    public byte[] bigEndianMagnitude() {
+    byte[] bigEndianMagnitude() {
         return NativeBN.BN_bn2bin(this.bignum);
     }
 
-    public int[] littleEndianIntsMagnitude() {
+    int[] littleEndianIntsMagnitude() {
         return NativeBN.bn2litEndInts(this.bignum);
     }
 
-    public int sign() {
+    int sign() {
         return NativeBN.sign(this.bignum);
     }
 
-    public void setSign(int val) {
-        if (val > 0) NativeBN.BN_set_negative(this.bignum, 0);
-        else if (val < 0) NativeBN.BN_set_negative(this.bignum, 1);
+    void setSign(int val) {
+        if (val > 0) {
+            NativeBN.BN_set_negative(this.bignum, 0);
+        } else {
+            if (val < 0) NativeBN.BN_set_negative(this.bignum, 1);
+        }
     }
 
-    public boolean twosCompFitsIntoBytes(int desiredByteCount) {
+    boolean twosCompFitsIntoBytes(int desiredByteCount) {
         int actualByteCount = (NativeBN.bitLength(this.bignum) + 7) / 8;
         return actualByteCount <= desiredByteCount;
     }
 
-    public int bitLength() {
+    int bitLength() {
         return NativeBN.bitLength(this.bignum);
     }
 
-    public boolean isBitSet(int n) {
+    boolean isBitSet(int n) {
         return NativeBN.BN_is_bit_set(this.bignum, n);
     }
 
     // n > 0: shift left (multiply)
-    public static BigInt shift(BigInt a, int n) {
+    static BigInt shift(BigInt a, int n) {
         BigInt r = newBigInt();
         Check(NativeBN.BN_shift(r.bignum, a.bignum, n));
         return r;
     }
 
-    public void shift(int n) {
+    void shift(int n) {
         Check(NativeBN.BN_shift(this.bignum, this.bignum, n));
     }
 
-    public void addPositiveInt(int w) {
+    void addPositiveInt(int w) {
         Check(NativeBN.BN_add_word(this.bignum, w));
     }
 
-    public void multiplyByPositiveInt(int w) {
+    void multiplyByPositiveInt(int w) {
         Check(NativeBN.BN_mul_word(this.bignum, w));
     }
 
-    public static int remainderByPositiveInt(BigInt a, int w) {
+    static int remainderByPositiveInt(BigInt a, int w) {
         int rem = NativeBN.BN_mod_word(a.bignum, w);
         Check(rem != -1);
         return rem;
     }
 
-    public static BigInt addition(BigInt a, BigInt b) {
+    static BigInt addition(BigInt a, BigInt b) {
         BigInt r = newBigInt();
         Check(NativeBN.BN_add(r.bignum, a.bignum, b.bignum));
         return r;
     }
 
-    public void add(BigInt a) {
+    void add(BigInt a) {
         Check(NativeBN.BN_add(this.bignum, this.bignum, a.bignum));
     }
 
-    public static BigInt subtraction(BigInt a, BigInt b) {
+    static BigInt subtraction(BigInt a, BigInt b) {
         BigInt r = newBigInt();
         Check(NativeBN.BN_sub(r.bignum, a.bignum, b.bignum));
         return r;
     }
 
 
-    public static BigInt gcd(BigInt a, BigInt b) {
+    static BigInt gcd(BigInt a, BigInt b) {
         BigInt r = newBigInt();
         Check(NativeBN.BN_gcd(r.bignum, a.bignum, b.bignum));
         return r;
     }
 
-    public static BigInt product(BigInt a, BigInt b) {
+    static BigInt product(BigInt a, BigInt b) {
         BigInt r = newBigInt();
         Check(NativeBN.BN_mul(r.bignum, a.bignum, b.bignum));
         return r;
     }
 
-    public static BigInt bigExp(BigInt a, BigInt p) {
+    static BigInt bigExp(BigInt a, BigInt p) {
         // Sign of p is ignored!
         BigInt r = newBigInt();
         Check(NativeBN.BN_exp(r.bignum, a.bignum, p.bignum));
         return r;
     }
 
-    public static BigInt exp(BigInt a, int p) {
+    static BigInt exp(BigInt a, int p) {
         // Sign of p is ignored!
         BigInt power = new BigInt();
         power.putLongInt(p);
         return bigExp(a, power);
         // OPTIONAL:
-//      public int BN_sqr(BigInteger r, BigInteger a, BN_CTX ctx);
-      // int BN_sqr(BIGNUM *r, const BIGNUM *a,BN_CTX *ctx);
+        // int BN_sqr(BigInteger r, BigInteger a, BN_CTX ctx);
+        // int BN_sqr(BIGNUM *r, const BIGNUM *a,BN_CTX *ctx);
     }
 
-    public static void division(BigInt dividend, BigInt divisor,
+    static void division(BigInt dividend, BigInt divisor,
             BigInt quotient, BigInt remainder) {
         int quot, rem;
         if (quotient != null) {
             quotient.makeValid();
             quot = quotient.bignum;
+        } else {
+            quot = 0;
         }
-        else quot = 0;
         if (remainder != null) {
             remainder.makeValid();
             rem = remainder.bignum;
+        } else {
+            rem = 0;
         }
-        else rem = 0;
         Check(NativeBN.BN_div(quot, rem, dividend.bignum, divisor.bignum));
     }
 
-    public static BigInt modulus(BigInt a, BigInt m) {
+    static BigInt modulus(BigInt a, BigInt m) {
         // Sign of p is ignored! ?
         BigInt r = newBigInt();
         Check(NativeBN.BN_nnmod(r.bignum, a.bignum, m.bignum));
         return r;
     }
 
-    public static BigInt modExp(BigInt a, BigInt p, BigInt m) {
+    static BigInt modExp(BigInt a, BigInt p, BigInt m) {
         // Sign of p is ignored!
         BigInt r = newBigInt();
         Check(NativeBN.BN_mod_exp(r.bignum, a.bignum, p.bignum, m.bignum));
@@ -366,20 +371,20 @@
     }
 
 
-    public static BigInt modInverse(BigInt a, BigInt m) {
+    static BigInt modInverse(BigInt a, BigInt m) {
         BigInt r = newBigInt();
         Check(NativeBN.BN_mod_inverse(r.bignum, a.bignum, m.bignum));
         return r;
     }
 
 
-    public static BigInt generatePrimeDefault(int bitLength) {
+    static BigInt generatePrimeDefault(int bitLength) {
         BigInt r = newBigInt();
         Check(NativeBN.BN_generate_prime_ex(r.bignum, bitLength, false, 0, 0, 0));
         return r;
     }
 
-    public boolean isPrime(int certainty) {
+    boolean isPrime(int certainty) {
         return NativeBN.BN_is_prime_ex(bignum, certainty, 0);
     }
 }
diff --git a/luni/src/main/java/java/math/BigInteger.java b/luni/src/main/java/java/math/BigInteger.java
index 681a197..e75c8f2 100644
--- a/luni/src/main/java/java/math/BigInteger.java
+++ b/luni/src/main/java/java/math/BigInteger.java
@@ -217,7 +217,7 @@
             setBigInt(bigInt);
         } else {
             if (radix < Character.MIN_RADIX || radix > Character.MAX_RADIX) {
-                throw new NumberFormatException("bad radix: " + radix);
+                throw new NumberFormatException("Invalid radix: " + radix);
             }
             if (value.isEmpty()) {
                 throw new NumberFormatException("value.isEmpty()");
@@ -243,7 +243,7 @@
             throw new NullPointerException("magnitude == null");
         }
         if (signum < -1 || signum > 1) {
-            throw new NumberFormatException("bad signum: " + signum);
+            throw new NumberFormatException("Invalid signum: " + signum);
         }
         if (signum == 0) {
             for (byte element : magnitude) {
diff --git a/luni/src/main/java/java/net/AddressCache.java b/luni/src/main/java/java/net/AddressCache.java
index 063c9e0..407eaca 100644
--- a/luni/src/main/java/java/net/AddressCache.java
+++ b/luni/src/main/java/java/net/AddressCache.java
@@ -77,6 +77,15 @@
     }
 
     /**
+     * Removes all entries from the cache.
+     */
+    public void clear() {
+        synchronized (map) {
+            map.clear();
+        }
+    }
+
+    /**
      * Returns the cached addresses associated with 'hostname'. Returns null if nothing is known
      * about 'hostname'. Returns an empty array if 'hostname' is known not to exist.
      */
diff --git a/luni/src/main/java/java/net/InetAddress.java b/luni/src/main/java/java/net/InetAddress.java
index cec45c9..bd9113f 100644
--- a/luni/src/main/java/java/net/InetAddress.java
+++ b/luni/src/main/java/java/net/InetAddress.java
@@ -506,6 +506,15 @@
     private static native byte[][] getaddrinfo(String name) throws UnknownHostException;
 
     /**
+     * Removes all entries from the VM's DNS cache. This does not affect the C library's DNS
+     * cache, nor any caching DNS servers between you and the canonical server.
+     * @hide
+     */
+    public static void clearDnsCache() {
+        addressCache.clear();
+    }
+
+    /**
      * Query the IP stack for the host address. The host is in address form.
      *
      * @param addr
@@ -513,8 +522,7 @@
      * @throws UnknownHostException
      *             if an error occurs during lookup.
      */
-    static InetAddress getHostByAddrImpl(byte[] addr)
-            throws UnknownHostException {
+    static InetAddress getHostByAddrImpl(byte[] addr) throws UnknownHostException {
         BlockGuard.getThreadPolicy().onNetwork();
         if (addr.length == 4) {
             return new Inet4Address(addr, getnameinfo(addr));
diff --git a/luni/src/main/java/java/net/InetSocketAddress.java b/luni/src/main/java/java/net/InetSocketAddress.java
index cd1bae3..8a33db8 100644
--- a/luni/src/main/java/java/net/InetSocketAddress.java
+++ b/luni/src/main/java/java/net/InetSocketAddress.java
@@ -28,11 +28,11 @@
 
     private static final long serialVersionUID = 5076001401234631237L;
 
-    private String hostname;
+    private final String hostname;
 
-    private InetAddress addr;
+    private final InetAddress addr;
 
-    private int port;
+    private final int port;
 
     /**
      * Creates a socket endpoint with the given port number {@code port} and
@@ -97,20 +97,22 @@
         if (hostname == null || port < 0 || port > 65535) {
             throw new IllegalArgumentException("host=" + hostname + ", port=" + port);
         }
-        this.hostname = hostname;
         this.port = port;
 
+        InetAddress addr = null;
         if (needResolved) {
             SecurityManager smgr = System.getSecurityManager();
             if (smgr != null) {
                 smgr.checkConnect(hostname, port);
             }
             try {
-                this.addr = InetAddress.getByName(hostname);
-                this.hostname = null;
+                addr = InetAddress.getByName(hostname);
+                hostname = null;
             } catch (UnknownHostException ignored) {
             }
         }
+        this.hostname = hostname;
+        this.addr = addr;
     }
 
     /**
@@ -225,11 +227,6 @@
         return addr.equals(iSockAddr.addr);
     }
 
-    /**
-     * Gets the hashcode of this socket.
-     *
-     * @return the appropriate hashcode.
-     */
     @Override
     public final int hashCode() {
         if (addr == null) {
diff --git a/luni/src/main/java/java/net/ProxySelector.java b/luni/src/main/java/java/net/ProxySelector.java
index b9dee5e..8455274 100644
--- a/luni/src/main/java/java/net/ProxySelector.java
+++ b/luni/src/main/java/java/net/ProxySelector.java
@@ -13,116 +13,137 @@
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
+
 package java.net;
 
 import java.io.IOException;
 import java.util.List;
 
 /**
- * Selects an applicable proxy server when connecting to a resource specified by
- * a URL. Proxy selectors are concrete subclasses of {@code ProxySelector} and
- * can be set as default by calling the {@code setDefault()} method. If a
- * connection can't be established, the caller should notify the proxy selector
- * by invoking the {@code connectFailed()} method.
+ * Selects the proxy server to use, if any, when connecting to a given URL.
+ *
+ * <h3>System Properties</h3>
+ * <p>The default proxy selector is configured by system properties.
+ *
+ * <table border="1" cellpadding="3" cellspacing="0">
+ * <tr class="TableHeadingColor"><th colspan="4">Hostname patterns</th></tr>
+ * <tr><th>URL scheme</th><th>property name</th><th>description</th><th>default</th></tr>
+ * <tr><td>ftp</td><td>ftp.nonProxyHosts</td><td>Hostname pattern for FTP servers to connect to
+ *     directly (without a proxy).</td><td>*</td></tr>
+ * <tr><td>http</td><td>http.nonProxyHosts</td><td>Hostname pattern for HTTP servers to connect to
+ *     directly (without a proxy).</td><td>*</td></tr>
+ * <tr><td>https</td><td>https.nonProxyHosts</td><td>Hostname pattern for HTTPS servers to connect
+ *     to directly (without a proxy).</td><td>*</td></tr>
+ * <tr><td colspan="4"><br></td></tr>
+ *
+ * <tr class="TableHeadingColor"><th colspan="4">{@linkplain Proxy.Type#HTTP HTTP Proxies}</th></tr>
+ * <tr><th>URL scheme</th><th>property name</th><th>description</th><th>default</th></tr>
+ * <tr><td rowspan="2">ftp</td><td>ftp.proxyHost</td><td>Hostname of the HTTP proxy server used for
+ *     FTP requests.</td><td></td></tr>
+ * <tr><td>ftp.proxyPort</td><td>Port number of the HTTP proxy server used for FTP
+ *     requests.</td><td>80</td></tr>
+ * <tr><td rowspan="2">http</td><td>http.proxyHost</td><td>Hostname of the HTTP proxy server used
+ *     for HTTP requests.</td><td></td></tr>
+ * <tr><td>http.proxyPort</td><td>Port number of the HTTP proxy server used for HTTP
+ *     requests.</td><td>80</td></tr>
+ * <tr><td rowspan="2">https</td><td>https.proxyHost</td><td>Hostname of the HTTP proxy server used
+ *     for HTTPS requests.</td><td></td></tr>
+ * <tr><td>https.proxyPort</td><td>Port number of the HTTP proxy server used for HTTPS
+ *     requests.</td><td>443</td></tr>
+ * <tr><td rowspan="2">ftp, http or https</td><td>proxyHost</td><td>Hostname of the HTTP proxy
+ *     server used for FTP, HTTP and HTTPS requests.</td><td></td></tr>
+ * <tr><td>proxyPort</td><td>Port number of the HTTP proxy server.</td><td>80 for FTP and HTTP
+ *     <br>443 for HTTPS</td></tr>
+ * <tr><td colspan="4"><br></td></tr>
+ *
+ * <tr class="TableHeadingColor"><th colspan="4">{@linkplain Proxy.Type#SOCKS SOCKS
+ *     Proxies}</th></tr>
+ * <tr><th>URL scheme</th><th>property name</th><th>description</th><th>default</th></tr>
+ * <tr><td rowspan="2">ftp, http, https or socket</td><td>socksProxyHost</td><td>Hostname of the
+ *     SOCKS proxy server used for FTP, HTTP, HTTPS and raw sockets.<br>Raw socket URLs are of the
+ *     form <code>socket://<i>host</i>:<i>port</i></code></td><td></td></tr>
+ * <tr><td>socksProxyPort</td><td>Port number of the SOCKS proxy server.</td><td>1080</td></tr>
+ * </table>
+ *
+ * <p>Hostname patterns specify which hosts should be connected to directly,
+ * ignoring any other proxy system properties. If the URL's host matches the
+ * corresponding hostname pattern, {@link Proxy#NO_PROXY} is returned.
+ *
+ * <p>The format of a hostname pattern is a list of hostnames that are
+ * separated by {@code |} and that use {@code *} as a wildcard. For example,
+ * setting the {@code http.nonProxyHosts} property to {@code
+ * *.android.com|*.kernel.org} will cause requests to {@code
+ * http://developer.android.com} to be made without a proxy.
+ *
+ * <p>The default proxy selector always returns exactly one proxy. If no proxy
+ * is applicable, {@link Proxy#NO_PROXY} is returned. If multiple proxies are
+ * applicable, such as when both the {@code proxyHost} and {@code
+ * socksProxyHost} system properties are set, the result is the property listed
+ * earliest in the table above.
+ *
+ * <h3>Alternatives</h3>
+ * <p>To request a URL without involving the system proxy selector, explicitly
+ * specify a proxy or {@link Proxy#NO_PROXY} using {@link
+ * URL#openConnection(Proxy)}.
+ *
+ * <p>Use {@link ProxySelector#setDefault(ProxySelector)} to install a custom
+ * proxy selector.
  */
 public abstract class ProxySelector {
 
     private static ProxySelector defaultSelector = new ProxySelectorImpl();
 
-    /*
-     * "getProxySelector" permission. getDefault method requires this
-     * permission.
-     */
-    private final static NetPermission getProxySelectorPermission = new NetPermission(
-            "getProxySelector");
-
-    /*
-     * "setProxySelector" permission. setDefault method requires this
-     * permission.
-     */
-    private final static NetPermission setProxySelectorPermission = new NetPermission(
-            "setProxySelector");
+    private final static NetPermission getProxySelectorPermission
+            = new NetPermission("getProxySelector");
+    private final static NetPermission setProxySelectorPermission
+            = new NetPermission("setProxySelector");
 
     /**
-     * Creates a new {@code ProxySelector} instance.
-     */
-    public ProxySelector() {
-        super();
-    }
-
-    /**
-     * Gets the default {@code ProxySelector} of the system.
+     * Returns the default proxy selector, or null if none exists.
      *
-     * @return the currently set default {@code ProxySelector}.
-     * @throws SecurityException
-     *             if a security manager is installed but it doesn't have the
-     *             NetPermission("getProxySelector").
+     * @throws SecurityException if a security manager is installed but it
+     *     doesn't have the NetPermission("getProxySelector").
      */
     public static ProxySelector getDefault() {
         SecurityManager sm = System.getSecurityManager();
-        if (null != sm) {
+        if (sm != null) {
             sm.checkPermission(getProxySelectorPermission);
         }
         return defaultSelector;
     }
 
     /**
-     * Sets the default {@code ProxySelector} of the system. Removes the system
-     * default {@code ProxySelector} if the parameter {@code selector} is set to
-     * {@code null}.
+     * Sets the default proxy selector. If {@code selector} is null, the current
+     * proxy selector will be removed.
      *
-     * @param selector
-     *            the {@code ProxySelector} instance to set as default or
-     *            {@code null} to remove the current default {@code
-     *            ProxySelector}.
-     * @throws SecurityException
-     *             if a security manager is installed but it doesn't have the
-     *             NetPermission("setProxySelector").
+     * @throws SecurityException if a security manager is installed but it
+     *     doesn't have the NetPermission("setProxySelector").
      */
     public static void setDefault(ProxySelector selector) {
         SecurityManager sm = System.getSecurityManager();
-        if (null != sm) {
+        if (sm != null) {
             sm.checkPermission(setProxySelectorPermission);
         }
         defaultSelector = selector;
     }
 
     /**
-     * Gets all applicable proxies based on the accessing protocol of {@code
-     * uri}. The format of URI is defined as below:
-     * <p>
-     * <li>http URI stands for http connection.</li>
-     * <li>https URI stands for https connection.</li>
-     * <li>ftp URI stands for ftp connection.</li>
-     * <li>socket:://ip:port URI stands for tcp client sockets connection.</li>
+     * Returns the proxy servers to use on connections to {@code uri}. This list
+     * will contain {@link Proxy#NO_PROXY} if no proxy server should be used.
      *
-     * @param uri
-     *            the target URI object.
-     * @return a list containing all applicable proxies. If no proxy is
-     *         available, the list contains only the {@code Proxy.NO_PROXY}
-     *         element.
-     * @throws IllegalArgumentException
-     *             if {@code uri} is {@code null}.
+     * @throws IllegalArgumentException if {@code uri} is null.
      */
     public abstract List<Proxy> select(URI uri);
 
     /**
-     * Notifies the {@code ProxySelector} that a connection to the proxy server
-     * could not be established. A concrete implementation should upon this
-     * notification maintain the list of available proxies, since an updated
-     * version should be provided by {@code select()}.
+     * Notifies this {@code ProxySelector} that a connection to the proxy server
+     * could not be established.
      *
-     * @param uri
-     *            the URI to which the connection could not be established.
-     * @param sa
-     *            the address of the proxy.
-     * @param ioe
-     *            the exception which was thrown during connection
-     *            establishment.
-     * @throws IllegalArgumentException
-     *             if any argument is {@code null}.
-     * @see #select(URI)
+     * @param uri the URI to which the connection could not be established.
+     * @param address the address of the proxy.
+     * @param failure the exception which was thrown during connection
+     *     establishment.
+     * @throws IllegalArgumentException if any argument is null.
      */
-    public abstract void connectFailed(URI uri, SocketAddress sa,
-            IOException ioe);
+    public abstract void connectFailed(URI uri, SocketAddress address, IOException failure);
 }
diff --git a/luni/src/main/java/java/net/ProxySelectorImpl.java b/luni/src/main/java/java/net/ProxySelectorImpl.java
index 571f32b..772b9e5 100644
--- a/luni/src/main/java/java/net/ProxySelectorImpl.java
+++ b/luni/src/main/java/java/net/ProxySelectorImpl.java
@@ -13,311 +13,131 @@
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
+
 package java.net;
 
-import java.io.BufferedInputStream;
-import java.io.File;
-import java.io.FileInputStream;
 import java.io.IOException;
-import java.io.InputStream;
-import java.security.AccessController;
-import java.util.ArrayList;
+import java.util.Collections;
 import java.util.List;
-import java.util.Properties;
-import org.apache.harmony.luni.util.PriviAction;
 
-/**
- * Default implementation for {@code ProxySelector}.
- */
-@SuppressWarnings("unchecked")
-class ProxySelectorImpl extends ProxySelector {
+final class ProxySelectorImpl extends ProxySelector {
 
-    private static final int HTTP_PROXY_PORT = 80;
-
-    private static final int HTTPS_PROXY_PORT = 443;
-
-    private static final int FTP_PROXY_PORT = 80;
-
-    private static final int SOCKS_PROXY_PORT = 1080;
-
-    // Net properties read from net.properties file.
-    private static Properties netProps = null;
-
-    // read net.properties file
-    static {
-        AccessController.doPrivileged(new java.security.PrivilegedAction() {
-            public Object run() {
-                File f = new File(System.getProperty("java.home")
-                        + File.separator + "lib" + File.separator
-                        + "net.properties");
-
-                if (f.exists()) {
-                    try {
-                        FileInputStream fis = new FileInputStream(f);
-                        InputStream is = new BufferedInputStream(fis);
-                        netProps = new Properties();
-                        netProps.load(is);
-                        is.close();
-                    } catch (IOException e) {
-                    }
-                }
-                return null;
-            }
-        });
-    }
-
-    public ProxySelectorImpl() {
-        super();
-    }
-
-    @Override
-    public void connectFailed(URI uri, SocketAddress sa, IOException ioe) {
+    @Override public void connectFailed(URI uri, SocketAddress sa, IOException ioe) {
         if (uri == null || sa == null || ioe == null) {
             throw new IllegalArgumentException();
         }
     }
 
-    @Override
-    public List<Proxy> select(URI uri) {
-        // argument check
+    @Override public List<Proxy> select(URI uri) {
+        return Collections.singletonList(selectOneProxy(uri));
+    }
+
+    private Proxy selectOneProxy(URI uri) {
         if (uri == null) {
             throw new IllegalArgumentException("uri == null");
         }
-        // check scheme
         String scheme = uri.getScheme();
-        if (null == scheme) {
-            throw new IllegalArgumentException();
+        if (scheme == null) {
+            throw new IllegalArgumentException("scheme == null");
         }
 
-        String host = uri.getHost();
-        Proxy proxy = Proxy.NO_PROXY;
-
-        if ("http".equals(scheme)) {
-            proxy = selectHttpProxy(host);
-        } else if ("https".equals(scheme)) {
-            proxy = selectHttpsProxy();
-        } else if ("ftp".equals(scheme)) {
-            proxy = selectFtpProxy(host);
-        } else if ("socket".equals(scheme)) {
-            proxy = selectSocksProxy();
-        }
-        List<Proxy> proxyList = new ArrayList<Proxy>(1);
-        proxyList.add(proxy);
-        return proxyList;
-    }
-
-    /*
-     * Gets proxy for http request. 1. gets from "http.proxyHost", then gets
-     * port from "http.proxyPort", or from "proxyPort" if "http.proxyPort" is
-     * unavailable. 2. gets from "proxyHost" if 1 is unavailable,then get port
-     * from "proxyPort", or from "http.proxyPort" if "proxyPort" is unavailable.
-     * 3. gets from "socksProxyHost" if 2 is unavailable.
-     */
-
-    private Proxy selectHttpProxy(String uriHost) {
-        String host;
-        String port = null;
-        Proxy.Type type = Proxy.Type.DIRECT;
-
-        String nonProxyHosts = getSystemProperty("http.nonProxyHosts");
-        // if host is in non proxy host list, returns Proxy.NO_PROXY
-        if (isNonProxyHost(uriHost, nonProxyHosts)) {
+        int port = -1;
+        Proxy proxy = null;
+        String nonProxyHostsKey = null;
+        boolean httpProxyOkay = true;
+        if ("http".equalsIgnoreCase(scheme)) {
+            port = 80;
+            nonProxyHostsKey = "http.nonProxyHosts";
+            proxy = lookupProxy("http.proxyHost", "http.proxyPort", Proxy.Type.HTTP, port);
+        } else if ("https".equalsIgnoreCase(scheme)) {
+            port = 443;
+            nonProxyHostsKey = "https.nonProxyHosts"; // RI doesn't support this
+            proxy = lookupProxy("https.proxyHost", "https.proxyPort", Proxy.Type.HTTP, port);
+        } else if ("ftp".equalsIgnoreCase(scheme)) {
+            port = 80; // not 21 as you might guess
+            nonProxyHostsKey = "ftp.nonProxyHosts";
+            proxy = lookupProxy("ftp.proxyHost", "ftp.proxyPort", Proxy.Type.HTTP, port);
+        } else if ("socket".equalsIgnoreCase(scheme)) {
+            httpProxyOkay = false;
+        } else {
             return Proxy.NO_PROXY;
         }
 
-        host = getSystemProperty("http.proxyHost");
-        if (null != host) {
-            // case 1: http.proxyHost is set, use exact http proxy
-            type = Proxy.Type.HTTP;
-            port = getSystemPropertyOrAlternative("http.proxyPort",
-                    "proxyPort", String.valueOf(HTTP_PROXY_PORT));
-        } else if ((host = getSystemProperty("proxyHost", null)) != null) {
-            // case 2: proxyHost is set, use exact http proxy
-            type = Proxy.Type.HTTP;
-            port = getSystemPropertyOrAlternative("proxyPort",
-                    "http.proxyPort", String.valueOf(HTTP_PROXY_PORT));
-
-        } else if ((host = getSystemProperty("socksProxyHost")) != null) {
-            // case 3: use socks proxy instead
-            type = Proxy.Type.SOCKS;
-            port = getSystemProperty(
-                    "socksProxyPort", String.valueOf(SOCKS_PROXY_PORT));
-        }
-        int defaultPort = (type == Proxy.Type.SOCKS) ? SOCKS_PROXY_PORT
-                : HTTP_PROXY_PORT;
-        return createProxy(type, host, port, defaultPort);
-    }
-
-    /*
-     * Gets proxy for https request.
-     */
-    private Proxy selectHttpsProxy() {
-        String host;
-        String port = null;
-        Proxy.Type type = Proxy.Type.DIRECT;
-
-        host = getSystemProperty("https.proxyHost");
-        if (null != host) {
-            // case 1: use exact https proxy
-            type = Proxy.Type.HTTP;
-            port = getSystemProperty(
-                    "https.proxyPort", String.valueOf(HTTPS_PROXY_PORT));
-        } else {
-            host = getSystemProperty("socksProxyHost");
-            if (null != host) {
-                // case 2: use socks proxy instead
-                type = Proxy.Type.SOCKS;
-                port = getSystemProperty(
-                        "socksProxyPort", String.valueOf(SOCKS_PROXY_PORT));
-            }
-        }
-        int defaultPort = (type == Proxy.Type.SOCKS) ? SOCKS_PROXY_PORT
-                : HTTPS_PROXY_PORT;
-        return createProxy(type, host, port, defaultPort);
-    }
-
-    /*
-     * Gets proxy for ftp request.
-     */
-    private Proxy selectFtpProxy(String uriHost) {
-        String host;
-        String port = null;
-        Proxy.Type type = Proxy.Type.DIRECT;
-        String nonProxyHosts = getSystemProperty("ftp.nonProxyHosts");
-        // if host is in non proxy host list, returns Proxy.NO_PROXY
-        if (isNonProxyHost(uriHost, nonProxyHosts)) {
+        if (nonProxyHostsKey != null
+                && isNonProxyHost(uri.getHost(), System.getProperty(nonProxyHostsKey))) {
             return Proxy.NO_PROXY;
         }
 
-        host = getSystemProperty("ftp.proxyHost");
-        if (null != host) {
-            // case 1: use exact ftp proxy
-            type = Proxy.Type.HTTP;
-            port = getSystemProperty(
-                    "ftp.proxyPort", String.valueOf(FTP_PROXY_PORT));
-        } else {
-            host = getSystemProperty("socksProxyHost");
-            if (null != host) {
-                // case 2: use socks proxy instead
-                type = Proxy.Type.SOCKS;
-                port = getSystemProperty(
-                        "socksProxyPort", String.valueOf(SOCKS_PROXY_PORT));
+        if (proxy != null) {
+            return proxy;
+        }
+
+        if (httpProxyOkay) {
+            proxy = lookupProxy("proxyHost", "proxyPort", Proxy.Type.HTTP, port);
+            if (proxy != null) {
+                return proxy;
             }
         }
-        int defaultPort = (type == Proxy.Type.SOCKS) ? SOCKS_PROXY_PORT
-                : FTP_PROXY_PORT;
-        return createProxy(type, host, port, defaultPort);
-    }
 
-    /*
-     * Gets proxy for socks request.
-     */
-    private Proxy selectSocksProxy() {
-        String host;
-        String port = null;
-        Proxy.Type type = Proxy.Type.DIRECT;
-
-        host = getSystemProperty("socksProxyHost");
-        if (null != host) {
-            type = Proxy.Type.SOCKS;
-            port = getSystemProperty(
-                    "socksProxyPort", String.valueOf(SOCKS_PROXY_PORT));
+        proxy = lookupProxy("socksProxyHost", "socksProxyPort", Proxy.Type.SOCKS, 1080);
+        if (proxy != null) {
+            return proxy;
         }
-        return createProxy(type, host, port, SOCKS_PROXY_PORT);
+
+        return Proxy.NO_PROXY;
     }
 
-    /*
-     * checks whether the host needs proxy. return true if it doesn't need a
-     * proxy.
+    /**
+     * Returns the proxy identified by the {@code hostKey} system property, or
+     * null.
+     */
+    private Proxy lookupProxy(String hostKey, String portKey, Proxy.Type type, int defaultPort) {
+        String host = System.getProperty(hostKey);
+        if (host == null || host.isEmpty()) {
+            return null;
+        }
+
+        int port = getSystemPropertyInt(portKey, defaultPort);
+        return new Proxy(type, InetSocketAddress.createUnresolved(host, port));
+    }
+
+    private int getSystemPropertyInt(String key, int defaultValue) {
+        String string = System.getProperty(key);
+        if (string != null) {
+            try {
+                return Integer.parseInt(string);
+            } catch (NumberFormatException ignored) {
+            }
+        }
+        return defaultValue;
+    }
+
+    /**
+     * Returns true if the {@code nonProxyHosts} system property pattern exists
+     * and matches {@code host}.
      */
     private boolean isNonProxyHost(String host, String nonProxyHosts) {
-        // nonProxyHosts is not set
-        if (null == host || null == nonProxyHosts) {
+        if (host == null || nonProxyHosts == null) {
             return false;
         }
-        // Construct regex expression of nonProxyHosts
-        int length = nonProxyHosts.length();
-        char ch;
-        StringBuilder buf = new StringBuilder(length);
+
+        // construct pattern
+        StringBuilder patternBuilder = new StringBuilder();
         for (int i = 0; i < nonProxyHosts.length(); i++) {
-            ch = nonProxyHosts.charAt(i);
-            switch (ch) {
-                case '.':
-                    buf.append("\\.");
-                    break;
-                case '*':
-                    buf.append(".*");
-                    break;
-                default:
-                    buf.append(ch);
+            char c = nonProxyHosts.charAt(i);
+            switch (c) {
+            case '.':
+                patternBuilder.append("\\.");
+                break;
+            case '*':
+                patternBuilder.append(".*");
+                break;
+            default:
+                patternBuilder.append(c);
             }
         }
-        String nonProxyHostsReg = buf.toString();
         // check whether the host is the nonProxyHosts.
-        return host.matches(nonProxyHostsReg);
-    }
-
-    /*
-     * Create Proxy by "type","host" and "port".
-     */
-    private Proxy createProxy(Proxy.Type type, String host, String port,
-            int defaultPort) {
-        Proxy proxy;
-        if (type == Proxy.Type.DIRECT) {
-            proxy = Proxy.NO_PROXY;
-        } else {
-            int iPort;
-            try {
-                // BEGIN android-changed
-                iPort = Integer.parseInt(port);
-                // END android-changed
-            } catch (NumberFormatException e) {
-                iPort = defaultPort;
-            }
-            proxy = new Proxy(type, InetSocketAddress.createUnresolved(host,
-                    iPort));
-        }
-        return proxy;
-    }
-
-    /*
-     * gets system property, privileged operation. If the value of the property
-     * is null or empty String, it returns defaultValue.
-     */
-    private String getSystemProperty(final String property) {
-        return getSystemProperty(property, null);
-    }
-
-    /*
-     * gets system property, privileged operation. If the value of the property
-     * is null or empty String, it returns defaultValue.
-     */
-    private String getSystemProperty(final String property,
-            final String defaultValue) {
-        String value = AccessController.doPrivileged(new PriviAction<String>(
-                property));
-        if (value == null || value.isEmpty()) {
-            value = (netProps != null)
-                    ? netProps.getProperty(property, defaultValue)
-                    : defaultValue;
-        }
-        return value;
-    }
-
-    /*
-     * gets system property, privileged operation. If the value of "key"
-     * property is null, then retrieve value from "alternative" property.
-     * Finally, if the value is null or empty String, it returns defaultValue.
-     */
-    private String getSystemPropertyOrAlternative(final String key,
-            final String alternativeKey, final String defaultValue) {
-        String value = getSystemProperty(key);
-        if (value == null) {
-            value = getSystemProperty(alternativeKey);
-            if (null == value) {
-                value = defaultValue;
-            }
-        }
-        return value;
+        String pattern = patternBuilder.toString();
+        return host.matches(pattern);
     }
 }
diff --git a/luni/src/main/java/java/net/URLClassLoader.java b/luni/src/main/java/java/net/URLClassLoader.java
index aad2329..6929834 100644
--- a/luni/src/main/java/java/net/URLClassLoader.java
+++ b/luni/src/main/java/java/net/URLClassLoader.java
@@ -45,6 +45,7 @@
 import java.util.jar.JarEntry;
 import java.util.jar.JarFile;
 import java.util.jar.Manifest;
+import libcore.io.IoUtils;
 
 /**
  * This class loader is responsible for loading classes and resources from a
@@ -161,20 +162,9 @@
                 // Ignore this jar's index
             } catch (IOException e) {
                 // Ignore this jar's index
-            }
-            finally {
-                if (in != null) {
-                    try {
-                        in.close();
-                    } catch (IOException e) {
-                    }
-                }
-                if (is != null) {
-                    try {
-                        is.close();
-                    } catch (IOException e) {
-                    }
-                }
+            } finally {
+                IoUtils.closeQuietly(in);
+                IoUtils.closeQuietly(is);
             }
             return null;
         }
@@ -240,10 +230,7 @@
             } catch (IOException e) {
                 return null;
             } finally {
-                try {
-                    is.close();
-                } catch (IOException e) {
-                }
+                IoUtils.closeQuietly(is);
             }
             if (packageName != null) {
                 String packageDotName = packageName.replace('/', '.');
@@ -401,12 +388,7 @@
             } catch (IOException e) {
                 return null;
             } finally {
-                if (is != null) {
-                    try {
-                        is.close();
-                    } catch (IOException e) {
-                    }
-                }
+                IoUtils.closeQuietly(is);
             }
             if (packageName != null) {
                 String packageDotName = packageName.replace('/', '.');
diff --git a/luni/src/main/java/java/nio/BaseByteBuffer.java b/luni/src/main/java/java/nio/BaseByteBuffer.java
index 73de53c..d6cfb93 100644
--- a/luni/src/main/java/java/nio/BaseByteBuffer.java
+++ b/luni/src/main/java/java/nio/BaseByteBuffer.java
@@ -28,32 +28,32 @@
 
     @Override
     public final CharBuffer asCharBuffer() {
-        return CharToByteBufferAdapter.wrap(this);
+        return CharToByteBufferAdapter.asCharBuffer(this);
     }
 
     @Override
     public final DoubleBuffer asDoubleBuffer() {
-        return DoubleToByteBufferAdapter.wrap(this);
+        return DoubleToByteBufferAdapter.asDoubleBuffer(this);
     }
 
     @Override
     public final FloatBuffer asFloatBuffer() {
-        return FloatToByteBufferAdapter.wrap(this);
+        return FloatToByteBufferAdapter.asFloatBuffer(this);
     }
 
     @Override
     public final IntBuffer asIntBuffer() {
-        return IntToByteBufferAdapter.wrap(this);
+        return IntToByteBufferAdapter.asIntBuffer(this);
     }
 
     @Override
     public final LongBuffer asLongBuffer() {
-        return LongToByteBufferAdapter.wrap(this);
+        return LongToByteBufferAdapter.asLongBuffer(this);
     }
 
     @Override
     public final ShortBuffer asShortBuffer() {
-        return ShortToByteBufferAdapter.wrap(this);
+        return ShortToByteBufferAdapter.asShortBuffer(this);
     }
 
     @Override
diff --git a/luni/src/main/java/java/nio/Buffer.java b/luni/src/main/java/java/nio/Buffer.java
index ecff621..f2e6da0 100644
--- a/luni/src/main/java/java/nio/Buffer.java
+++ b/luni/src/main/java/java/nio/Buffer.java
@@ -45,14 +45,6 @@
  * synchronization issues.
  */
 public abstract class Buffer {
-
-    static final int SIZEOF_CHAR = 2;
-    static final int SIZEOF_DOUBLE = 8;
-    static final int SIZEOF_FLOAT = 4;
-    static final int SIZEOF_INT = 4;
-    static final int SIZEOF_LONG = 8;
-    static final int SIZEOF_SHORT = 2;
-
     /**
      * <code>UNSET_MARK</code> means the mark has not been set.
      */
diff --git a/luni/src/main/java/java/nio/ByteOrder.java b/luni/src/main/java/java/nio/ByteOrder.java
index 2308381..286c970 100644
--- a/luni/src/main/java/java/nio/ByteOrder.java
+++ b/luni/src/main/java/java/nio/ByteOrder.java
@@ -47,8 +47,9 @@
      * This is the only thing that ByteOrder is really used for: to know whether we need to swap
      * bytes to get this order, given bytes in native order. (That is, this is the opposite of
      * the hypothetical "isNativeOrder".)
+     * @hide - needed in libcore.io too.
      */
-    final boolean needsSwap;
+    public final boolean needsSwap;
 
     private ByteOrder(String name, boolean needsSwap) {
         this.name = name;
diff --git a/luni/src/main/java/java/nio/CharToByteBufferAdapter.java b/luni/src/main/java/java/nio/CharToByteBufferAdapter.java
index 8deaac9..4a6d920 100644
--- a/luni/src/main/java/java/nio/CharToByteBufferAdapter.java
+++ b/luni/src/main/java/java/nio/CharToByteBufferAdapter.java
@@ -16,6 +16,8 @@
 
 package java.nio;
 
+import libcore.io.SizeOf;
+
 /**
  * This class wraps a byte buffer to be a char buffer.
  * <p>
@@ -31,14 +33,16 @@
  */
 final class CharToByteBufferAdapter extends CharBuffer {
 
-    static CharBuffer wrap(ByteBuffer byteBuffer) {
-        return new CharToByteBufferAdapter(byteBuffer.slice());
-    }
-
     private final ByteBuffer byteBuffer;
 
-    CharToByteBufferAdapter(ByteBuffer byteBuffer) {
-        super(byteBuffer.capacity() / SIZEOF_CHAR);
+    static CharBuffer asCharBuffer(ByteBuffer byteBuffer) {
+        ByteBuffer slice = byteBuffer.slice();
+        slice.order(byteBuffer.order());
+        return new CharToByteBufferAdapter(slice);
+    }
+
+    private CharToByteBufferAdapter(ByteBuffer byteBuffer) {
+        super(byteBuffer.capacity() / SizeOf.CHAR);
         this.byteBuffer = byteBuffer;
         this.byteBuffer.clear();
         this.effectiveDirectAddress = byteBuffer.effectiveDirectAddress;
@@ -58,8 +62,8 @@
         if (byteBuffer.isReadOnly()) {
             throw new ReadOnlyBufferException();
         }
-        byteBuffer.limit(limit * SIZEOF_CHAR);
-        byteBuffer.position(position * SIZEOF_CHAR);
+        byteBuffer.limit(limit * SizeOf.CHAR);
+        byteBuffer.position(position * SizeOf.CHAR);
         byteBuffer.compact();
         byteBuffer.clear();
         position = limit - position;
@@ -82,7 +86,7 @@
         if (position == limit) {
             throw new BufferUnderflowException();
         }
-        return byteBuffer.getChar(position++ * SIZEOF_CHAR);
+        return byteBuffer.getChar(position++ * SizeOf.CHAR);
     }
 
     @Override
@@ -90,13 +94,13 @@
         if (index < 0 || index >= limit) {
             throw new IndexOutOfBoundsException();
         }
-        return byteBuffer.getChar(index * SIZEOF_CHAR);
+        return byteBuffer.getChar(index * SizeOf.CHAR);
     }
 
     @Override
     public CharBuffer get(char[] dst, int dstOffset, int charCount) {
-        byteBuffer.limit(limit * SIZEOF_CHAR);
-        byteBuffer.position(position * SIZEOF_CHAR);
+        byteBuffer.limit(limit * SizeOf.CHAR);
+        byteBuffer.position(position * SizeOf.CHAR);
         if (byteBuffer instanceof DirectByteBuffer) {
             ((DirectByteBuffer) byteBuffer).get(dst, dstOffset, charCount);
         } else {
@@ -141,7 +145,7 @@
         if (position == limit) {
             throw new BufferOverflowException();
         }
-        byteBuffer.putChar(position++ * SIZEOF_CHAR, c);
+        byteBuffer.putChar(position++ * SizeOf.CHAR, c);
         return this;
     }
 
@@ -150,14 +154,14 @@
         if (index < 0 || index >= limit) {
             throw new IndexOutOfBoundsException();
         }
-        byteBuffer.putChar(index * SIZEOF_CHAR, c);
+        byteBuffer.putChar(index * SizeOf.CHAR, c);
         return this;
     }
 
     @Override
     public CharBuffer put(char[] src, int srcOffset, int charCount) {
-        byteBuffer.limit(limit * SIZEOF_CHAR);
-        byteBuffer.position(position * SIZEOF_CHAR);
+        byteBuffer.limit(limit * SizeOf.CHAR);
+        byteBuffer.position(position * SizeOf.CHAR);
         if (byteBuffer instanceof ReadWriteDirectByteBuffer) {
             ((ReadWriteDirectByteBuffer) byteBuffer).put(src, srcOffset, charCount);
         } else {
@@ -169,8 +173,8 @@
 
     @Override
     public CharBuffer slice() {
-        byteBuffer.limit(limit * SIZEOF_CHAR);
-        byteBuffer.position(position * SIZEOF_CHAR);
+        byteBuffer.limit(limit * SizeOf.CHAR);
+        byteBuffer.position(position * SizeOf.CHAR);
         CharBuffer result = new CharToByteBufferAdapter(byteBuffer.slice());
         byteBuffer.clear();
         return result;
diff --git a/luni/src/main/java/java/nio/DirectByteBuffer.java b/luni/src/main/java/java/nio/DirectByteBuffer.java
index a918ef2..f9097c1 100644
--- a/luni/src/main/java/java/nio/DirectByteBuffer.java
+++ b/luni/src/main/java/java/nio/DirectByteBuffer.java
@@ -17,6 +17,8 @@
 
 package java.nio;
 
+import libcore.io.SizeOf;
+
 abstract class DirectByteBuffer extends BaseByteBuffer {
     // This is the offset into {@code Buffer.block} at which this buffer logically starts.
     // TODO: rewrite this so we set 'block' to an OffsetMemoryBlock?
@@ -43,37 +45,37 @@
     }
 
     final void get(char[] dst, int dstOffset, int charCount) {
-        int byteCount = checkGetBounds(SIZEOF_CHAR, dst.length, dstOffset, charCount);
+        int byteCount = checkGetBounds(SizeOf.CHAR, dst.length, dstOffset, charCount);
         this.block.peekCharArray(offset + position, dst, dstOffset, charCount, order.needsSwap);
         position += byteCount;
     }
 
     final void get(double[] dst, int dstOffset, int doubleCount) {
-        int byteCount = checkGetBounds(SIZEOF_DOUBLE, dst.length, dstOffset, doubleCount);
+        int byteCount = checkGetBounds(SizeOf.DOUBLE, dst.length, dstOffset, doubleCount);
         this.block.peekDoubleArray(offset + position, dst, dstOffset, doubleCount, order.needsSwap);
         position += byteCount;
     }
 
     final void get(float[] dst, int dstOffset, int floatCount) {
-        int byteCount = checkGetBounds(SIZEOF_FLOAT, dst.length, dstOffset, floatCount);
+        int byteCount = checkGetBounds(SizeOf.FLOAT, dst.length, dstOffset, floatCount);
         this.block.peekFloatArray(offset + position, dst, dstOffset, floatCount, order.needsSwap);
         position += byteCount;
     }
 
     final void get(int[] dst, int dstOffset, int intCount) {
-        int byteCount = checkGetBounds(SIZEOF_INT, dst.length, dstOffset, intCount);
+        int byteCount = checkGetBounds(SizeOf.INT, dst.length, dstOffset, intCount);
         this.block.peekIntArray(offset + position, dst, dstOffset, intCount, order.needsSwap);
         position += byteCount;
     }
 
     final void get(long[] dst, int dstOffset, int longCount) {
-        int byteCount = checkGetBounds(SIZEOF_LONG, dst.length, dstOffset, longCount);
+        int byteCount = checkGetBounds(SizeOf.LONG, dst.length, dstOffset, longCount);
         this.block.peekLongArray(offset + position, dst, dstOffset, longCount, order.needsSwap);
         position += byteCount;
     }
 
     final void get(short[] dst, int dstOffset, int shortCount) {
-        int byteCount = checkGetBounds(SIZEOF_SHORT, dst.length, dstOffset, shortCount);
+        int byteCount = checkGetBounds(SizeOf.SHORT, dst.length, dstOffset, shortCount);
         this.block.peekShortArray(offset + position, dst, dstOffset, shortCount, order.needsSwap);
         position += byteCount;
     }
@@ -96,7 +98,7 @@
 
     @Override
     public final char getChar() {
-        int newPosition = position + SIZEOF_CHAR;
+        int newPosition = position + SizeOf.CHAR;
         if (newPosition > limit) {
             throw new BufferUnderflowException();
         }
@@ -107,7 +109,7 @@
 
     @Override
     public final char getChar(int index) {
-        if (index < 0 || (long) index + SIZEOF_CHAR > limit) {
+        if (index < 0 || (long) index + SizeOf.CHAR > limit) {
             throw new IndexOutOfBoundsException();
         }
         return (char) this.block.peekShort(offset + index, order);
@@ -115,7 +117,7 @@
 
     @Override
     public final double getDouble() {
-        int newPosition = position + SIZEOF_DOUBLE;
+        int newPosition = position + SizeOf.DOUBLE;
         if (newPosition > limit) {
             throw new BufferUnderflowException();
         }
@@ -126,7 +128,7 @@
 
     @Override
     public final double getDouble(int index) {
-        if (index < 0 || (long) index + SIZEOF_DOUBLE > limit) {
+        if (index < 0 || (long) index + SizeOf.DOUBLE > limit) {
             throw new IndexOutOfBoundsException();
         }
         return Double.longBitsToDouble(this.block.peekLong(offset + index, order));
@@ -134,7 +136,7 @@
 
     @Override
     public final float getFloat() {
-        int newPosition = position + SIZEOF_FLOAT;
+        int newPosition = position + SizeOf.FLOAT;
         if (newPosition > limit) {
             throw new BufferUnderflowException();
         }
@@ -145,7 +147,7 @@
 
     @Override
     public final float getFloat(int index) {
-        if (index < 0 || (long) index + SIZEOF_FLOAT > limit) {
+        if (index < 0 || (long) index + SizeOf.FLOAT > limit) {
             throw new IndexOutOfBoundsException();
         }
         return Float.intBitsToFloat(this.block.peekInt(offset + index, order));
@@ -153,7 +155,7 @@
 
     @Override
     public final int getInt() {
-        int newPosition = position + SIZEOF_INT;
+        int newPosition = position + SizeOf.INT;
         if (newPosition > limit) {
             throw new BufferUnderflowException();
         }
@@ -164,7 +166,7 @@
 
     @Override
     public final int getInt(int index) {
-        if (index < 0 || (long) index + SIZEOF_INT > limit) {
+        if (index < 0 || (long) index + SizeOf.INT > limit) {
             throw new IndexOutOfBoundsException();
         }
         return this.block.peekInt(offset + index, order);
@@ -172,7 +174,7 @@
 
     @Override
     public final long getLong() {
-        int newPosition = position + SIZEOF_LONG;
+        int newPosition = position + SizeOf.LONG;
         if (newPosition > limit) {
             throw new BufferUnderflowException();
         }
@@ -183,7 +185,7 @@
 
     @Override
     public final long getLong(int index) {
-        if (index < 0 || (long) index + SIZEOF_LONG > limit) {
+        if (index < 0 || (long) index + SizeOf.LONG > limit) {
             throw new IndexOutOfBoundsException();
         }
         return this.block.peekLong(offset + index, order);
@@ -191,7 +193,7 @@
 
     @Override
     public final short getShort() {
-        int newPosition = position + SIZEOF_SHORT;
+        int newPosition = position + SizeOf.SHORT;
         if (newPosition > limit) {
             throw new BufferUnderflowException();
         }
@@ -202,7 +204,7 @@
 
     @Override
     public final short getShort(int index) {
-        if (index < 0 || (long) index + SIZEOF_SHORT > limit) {
+        if (index < 0 || (long) index + SizeOf.SHORT > limit) {
             throw new IndexOutOfBoundsException();
         }
         return this.block.peekShort(offset + index, order);
diff --git a/luni/src/main/java/java/nio/DoubleToByteBufferAdapter.java b/luni/src/main/java/java/nio/DoubleToByteBufferAdapter.java
index 3111920..b5380ba 100644
--- a/luni/src/main/java/java/nio/DoubleToByteBufferAdapter.java
+++ b/luni/src/main/java/java/nio/DoubleToByteBufferAdapter.java
@@ -16,6 +16,8 @@
 
 package java.nio;
 
+import libcore.io.SizeOf;
+
 /**
  * This class wraps a byte buffer to be a double buffer.
  * <p>
@@ -31,14 +33,16 @@
  */
 final class DoubleToByteBufferAdapter extends DoubleBuffer {
 
-    static DoubleBuffer wrap(ByteBuffer byteBuffer) {
-        return new DoubleToByteBufferAdapter(byteBuffer.slice());
-    }
-
     private final ByteBuffer byteBuffer;
 
-    DoubleToByteBufferAdapter(ByteBuffer byteBuffer) {
-        super(byteBuffer.capacity() / SIZEOF_DOUBLE);
+    static DoubleBuffer asDoubleBuffer(ByteBuffer byteBuffer) {
+        ByteBuffer slice = byteBuffer.slice();
+        slice.order(byteBuffer.order());
+        return new DoubleToByteBufferAdapter(slice);
+    }
+
+    private DoubleToByteBufferAdapter(ByteBuffer byteBuffer) {
+        super(byteBuffer.capacity() / SizeOf.DOUBLE);
         this.byteBuffer = byteBuffer;
         this.byteBuffer.clear();
         this.effectiveDirectAddress = byteBuffer.effectiveDirectAddress;
@@ -58,8 +62,8 @@
         if (byteBuffer.isReadOnly()) {
             throw new ReadOnlyBufferException();
         }
-        byteBuffer.limit(limit * SIZEOF_DOUBLE);
-        byteBuffer.position(position * SIZEOF_DOUBLE);
+        byteBuffer.limit(limit * SizeOf.DOUBLE);
+        byteBuffer.position(position * SizeOf.DOUBLE);
         byteBuffer.compact();
         byteBuffer.clear();
         position = limit - position;
@@ -82,7 +86,7 @@
         if (position == limit) {
             throw new BufferUnderflowException();
         }
-        return byteBuffer.getDouble(position++ * SIZEOF_DOUBLE);
+        return byteBuffer.getDouble(position++ * SizeOf.DOUBLE);
     }
 
     @Override
@@ -90,13 +94,13 @@
         if (index < 0 || index >= limit) {
             throw new IndexOutOfBoundsException();
         }
-        return byteBuffer.getDouble(index * SIZEOF_DOUBLE);
+        return byteBuffer.getDouble(index * SizeOf.DOUBLE);
     }
 
     @Override
     public DoubleBuffer get(double[] dst, int dstOffset, int doubleCount) {
-        byteBuffer.limit(limit * SIZEOF_DOUBLE);
-        byteBuffer.position(position * SIZEOF_DOUBLE);
+        byteBuffer.limit(limit * SizeOf.DOUBLE);
+        byteBuffer.position(position * SizeOf.DOUBLE);
         if (byteBuffer instanceof DirectByteBuffer) {
             ((DirectByteBuffer) byteBuffer).get(dst, dstOffset, doubleCount);
         } else {
@@ -141,7 +145,7 @@
         if (position == limit) {
             throw new BufferOverflowException();
         }
-        byteBuffer.putDouble(position++ * SIZEOF_DOUBLE, c);
+        byteBuffer.putDouble(position++ * SizeOf.DOUBLE, c);
         return this;
     }
 
@@ -150,14 +154,14 @@
         if (index < 0 || index >= limit) {
             throw new IndexOutOfBoundsException();
         }
-        byteBuffer.putDouble(index * SIZEOF_DOUBLE, c);
+        byteBuffer.putDouble(index * SizeOf.DOUBLE, c);
         return this;
     }
 
     @Override
     public DoubleBuffer put(double[] src, int srcOffset, int doubleCount) {
-        byteBuffer.limit(limit * SIZEOF_DOUBLE);
-        byteBuffer.position(position * SIZEOF_DOUBLE);
+        byteBuffer.limit(limit * SizeOf.DOUBLE);
+        byteBuffer.position(position * SizeOf.DOUBLE);
         if (byteBuffer instanceof ReadWriteDirectByteBuffer) {
             ((ReadWriteDirectByteBuffer) byteBuffer).put(src, srcOffset, doubleCount);
         } else {
@@ -169,8 +173,8 @@
 
     @Override
     public DoubleBuffer slice() {
-        byteBuffer.limit(limit * SIZEOF_DOUBLE);
-        byteBuffer.position(position * SIZEOF_DOUBLE);
+        byteBuffer.limit(limit * SizeOf.DOUBLE);
+        byteBuffer.position(position * SizeOf.DOUBLE);
         DoubleBuffer result = new DoubleToByteBufferAdapter(byteBuffer.slice());
         byteBuffer.clear();
         return result;
diff --git a/luni/src/main/java/java/nio/FloatToByteBufferAdapter.java b/luni/src/main/java/java/nio/FloatToByteBufferAdapter.java
index 07f28cf..c1e4ee1 100644
--- a/luni/src/main/java/java/nio/FloatToByteBufferAdapter.java
+++ b/luni/src/main/java/java/nio/FloatToByteBufferAdapter.java
@@ -16,6 +16,8 @@
 
 package java.nio;
 
+import libcore.io.SizeOf;
+
 /**
  * This class wraps a byte buffer to be a float buffer.
  * <p>
@@ -30,14 +32,16 @@
  */
 final class FloatToByteBufferAdapter extends FloatBuffer {
 
-    static FloatBuffer wrap(ByteBuffer byteBuffer) {
-        return new FloatToByteBufferAdapter(byteBuffer.slice());
-    }
-
     private final ByteBuffer byteBuffer;
 
+    static FloatBuffer asFloatBuffer(ByteBuffer byteBuffer) {
+        ByteBuffer slice = byteBuffer.slice();
+        slice.order(byteBuffer.order());
+        return new FloatToByteBufferAdapter(slice);
+    }
+
     FloatToByteBufferAdapter(ByteBuffer byteBuffer) {
-        super(byteBuffer.capacity() / SIZEOF_FLOAT);
+        super(byteBuffer.capacity() / SizeOf.FLOAT);
         this.byteBuffer = byteBuffer;
         this.byteBuffer.clear();
         this.effectiveDirectAddress = byteBuffer.effectiveDirectAddress;
@@ -57,8 +61,8 @@
         if (byteBuffer.isReadOnly()) {
             throw new ReadOnlyBufferException();
         }
-        byteBuffer.limit(limit * SIZEOF_FLOAT);
-        byteBuffer.position(position * SIZEOF_FLOAT);
+        byteBuffer.limit(limit * SizeOf.FLOAT);
+        byteBuffer.position(position * SizeOf.FLOAT);
         byteBuffer.compact();
         byteBuffer.clear();
         position = limit - position;
@@ -81,7 +85,7 @@
         if (position == limit) {
             throw new BufferUnderflowException();
         }
-        return byteBuffer.getFloat(position++ * SIZEOF_FLOAT);
+        return byteBuffer.getFloat(position++ * SizeOf.FLOAT);
     }
 
     @Override
@@ -89,13 +93,13 @@
         if (index < 0 || index >= limit) {
             throw new IndexOutOfBoundsException();
         }
-        return byteBuffer.getFloat(index * SIZEOF_FLOAT);
+        return byteBuffer.getFloat(index * SizeOf.FLOAT);
     }
 
     @Override
     public FloatBuffer get(float[] dst, int dstOffset, int floatCount) {
-        byteBuffer.limit(limit * SIZEOF_FLOAT);
-        byteBuffer.position(position * SIZEOF_FLOAT);
+        byteBuffer.limit(limit * SizeOf.FLOAT);
+        byteBuffer.position(position * SizeOf.FLOAT);
         if (byteBuffer instanceof DirectByteBuffer) {
             ((DirectByteBuffer) byteBuffer).get(dst, dstOffset, floatCount);
         } else {
@@ -140,7 +144,7 @@
         if (position == limit) {
             throw new BufferOverflowException();
         }
-        byteBuffer.putFloat(position++ * SIZEOF_FLOAT, c);
+        byteBuffer.putFloat(position++ * SizeOf.FLOAT, c);
         return this;
     }
 
@@ -149,14 +153,14 @@
         if (index < 0 || index >= limit) {
             throw new IndexOutOfBoundsException();
         }
-        byteBuffer.putFloat(index * SIZEOF_FLOAT, c);
+        byteBuffer.putFloat(index * SizeOf.FLOAT, c);
         return this;
     }
 
     @Override
     public FloatBuffer put(float[] src, int srcOffset, int floatCount) {
-        byteBuffer.limit(limit * SIZEOF_FLOAT);
-        byteBuffer.position(position * SIZEOF_FLOAT);
+        byteBuffer.limit(limit * SizeOf.FLOAT);
+        byteBuffer.position(position * SizeOf.FLOAT);
         if (byteBuffer instanceof ReadWriteDirectByteBuffer) {
             ((ReadWriteDirectByteBuffer) byteBuffer).put(src, srcOffset, floatCount);
         } else {
@@ -168,8 +172,8 @@
 
     @Override
     public FloatBuffer slice() {
-        byteBuffer.limit(limit * SIZEOF_FLOAT);
-        byteBuffer.position(position * SIZEOF_FLOAT);
+        byteBuffer.limit(limit * SizeOf.FLOAT);
+        byteBuffer.position(position * SizeOf.FLOAT);
         FloatBuffer result = new FloatToByteBufferAdapter(byteBuffer.slice());
         byteBuffer.clear();
         return result;
diff --git a/luni/src/main/java/java/nio/HeapByteBuffer.java b/luni/src/main/java/java/nio/HeapByteBuffer.java
index 2118115..c19e11b 100644
--- a/luni/src/main/java/java/nio/HeapByteBuffer.java
+++ b/luni/src/main/java/java/nio/HeapByteBuffer.java
@@ -17,6 +17,7 @@
 
 package java.nio;
 
+import libcore.io.SizeOf;
 import org.apache.harmony.luni.platform.OSMemory;
 
 /**
@@ -64,38 +65,38 @@
     }
 
     final void get(char[] dst, int dstOffset, int charCount) {
-        int byteCount = checkGetBounds(SIZEOF_CHAR, dst.length, dstOffset, charCount);
-        OSMemory.unsafeBulkGet(dst, dstOffset, byteCount, backingArray, offset + position, SIZEOF_CHAR, order.needsSwap);
+        int byteCount = checkGetBounds(SizeOf.CHAR, dst.length, dstOffset, charCount);
+        OSMemory.unsafeBulkGet(dst, dstOffset, byteCount, backingArray, offset + position, SizeOf.CHAR, order.needsSwap);
         position += byteCount;
     }
 
     final void get(double[] dst, int dstOffset, int doubleCount) {
-        int byteCount = checkGetBounds(SIZEOF_DOUBLE, dst.length, dstOffset, doubleCount);
-        OSMemory.unsafeBulkGet(dst, dstOffset, byteCount, backingArray, offset + position, SIZEOF_DOUBLE, order.needsSwap);
+        int byteCount = checkGetBounds(SizeOf.DOUBLE, dst.length, dstOffset, doubleCount);
+        OSMemory.unsafeBulkGet(dst, dstOffset, byteCount, backingArray, offset + position, SizeOf.DOUBLE, order.needsSwap);
         position += byteCount;
     }
 
     final void get(float[] dst, int dstOffset, int floatCount) {
-        int byteCount = checkGetBounds(SIZEOF_FLOAT, dst.length, dstOffset, floatCount);
-        OSMemory.unsafeBulkGet(dst, dstOffset, byteCount, backingArray, offset + position, SIZEOF_FLOAT, order.needsSwap);
+        int byteCount = checkGetBounds(SizeOf.FLOAT, dst.length, dstOffset, floatCount);
+        OSMemory.unsafeBulkGet(dst, dstOffset, byteCount, backingArray, offset + position, SizeOf.FLOAT, order.needsSwap);
         position += byteCount;
     }
 
     final void get(int[] dst, int dstOffset, int intCount) {
-        int byteCount = checkGetBounds(SIZEOF_INT, dst.length, dstOffset, intCount);
-        OSMemory.unsafeBulkGet(dst, dstOffset, byteCount, backingArray, offset + position, SIZEOF_INT, order.needsSwap);
+        int byteCount = checkGetBounds(SizeOf.INT, dst.length, dstOffset, intCount);
+        OSMemory.unsafeBulkGet(dst, dstOffset, byteCount, backingArray, offset + position, SizeOf.INT, order.needsSwap);
         position += byteCount;
     }
 
     final void get(long[] dst, int dstOffset, int longCount) {
-        int byteCount = checkGetBounds(SIZEOF_LONG, dst.length, dstOffset, longCount);
-        OSMemory.unsafeBulkGet(dst, dstOffset, byteCount, backingArray, offset + position, SIZEOF_LONG, order.needsSwap);
+        int byteCount = checkGetBounds(SizeOf.LONG, dst.length, dstOffset, longCount);
+        OSMemory.unsafeBulkGet(dst, dstOffset, byteCount, backingArray, offset + position, SizeOf.LONG, order.needsSwap);
         position += byteCount;
     }
 
     final void get(short[] dst, int dstOffset, int shortCount) {
-        int byteCount = checkGetBounds(SIZEOF_SHORT, dst.length, dstOffset, shortCount);
-        OSMemory.unsafeBulkGet(dst, dstOffset, byteCount, backingArray, offset + position, SIZEOF_SHORT, order.needsSwap);
+        int byteCount = checkGetBounds(SizeOf.SHORT, dst.length, dstOffset, shortCount);
+        OSMemory.unsafeBulkGet(dst, dstOffset, byteCount, backingArray, offset + position, SizeOf.SHORT, order.needsSwap);
         position += byteCount;
     }
 
@@ -117,21 +118,21 @@
 
     @Override
     public final char getChar() {
-        int newPosition = position + SIZEOF_CHAR;
+        int newPosition = position + SizeOf.CHAR;
         if (newPosition > limit) {
             throw new BufferUnderflowException();
         }
-        char result = (char) loadShort(position);
+        char result = (char) OSMemory.peekShort(backingArray, offset + position, order);
         position = newPosition;
         return result;
     }
 
     @Override
     public final char getChar(int index) {
-        if (index < 0 || index + SIZEOF_CHAR > limit) {
+        if (index < 0 || index + SizeOf.CHAR > limit) {
             throw new IndexOutOfBoundsException();
         }
-        return (char) loadShort(index);
+        return (char) OSMemory.peekShort(backingArray, offset + index, order);
     }
 
     @Override
@@ -156,114 +157,63 @@
 
     @Override
     public final int getInt() {
-        int newPosition = position + SIZEOF_INT;
+        int newPosition = position + SizeOf.INT;
         if (newPosition > limit) {
             throw new BufferUnderflowException();
         }
-        int result = loadInt(position);
+        int result = OSMemory.peekInt(backingArray, offset + position, order);
         position = newPosition;
         return result;
     }
 
     @Override
     public final int getInt(int index) {
-        if (index < 0 || index + SIZEOF_INT > limit) {
+        if (index < 0 || index + SizeOf.INT > limit) {
             throw new IndexOutOfBoundsException();
         }
-        return loadInt(index);
+        return OSMemory.peekInt(backingArray, offset + index, order);
     }
 
     @Override
     public final long getLong() {
-        int newPosition = position + SIZEOF_LONG;
+        int newPosition = position + SizeOf.LONG;
         if (newPosition > limit) {
             throw new BufferUnderflowException();
         }
-        long result = loadLong(position);
+        long result = OSMemory.peekLong(backingArray, offset + position, order);
         position = newPosition;
         return result;
     }
 
     @Override
     public final long getLong(int index) {
-        if (index < 0 || index + SIZEOF_LONG > limit) {
+        if (index < 0 || index + SizeOf.LONG > limit) {
             throw new IndexOutOfBoundsException();
         }
-        return loadLong(index);
+        return OSMemory.peekLong(backingArray, offset + index, order);
     }
 
     @Override
     public final short getShort() {
-        int newPosition = position + SIZEOF_SHORT;
+        int newPosition = position + SizeOf.SHORT;
         if (newPosition > limit) {
             throw new BufferUnderflowException();
         }
-        short result = loadShort(position);
+        short result = OSMemory.peekShort(backingArray, offset + position, order);
         position = newPosition;
         return result;
     }
 
     @Override
     public final short getShort(int index) {
-        if (index < 0 || index + SIZEOF_SHORT > limit) {
+        if (index < 0 || index + SizeOf.SHORT > limit) {
             throw new IndexOutOfBoundsException();
         }
-        return loadShort(index);
+        return OSMemory.peekShort(backingArray, offset + index, order);
     }
 
     @Override
     public final boolean isDirect() {
         return false;
     }
-
-    private final int loadInt(int index) {
-        int baseOffset = offset + index;
-        if (order == ByteOrder.BIG_ENDIAN) {
-            return (((backingArray[baseOffset++] & 0xff) << 24) |
-                    ((backingArray[baseOffset++] & 0xff) << 16) |
-                    ((backingArray[baseOffset++] & 0xff) <<  8) |
-                    ((backingArray[baseOffset  ] & 0xff) <<  0));
-        } else {
-            return (((backingArray[baseOffset++] & 0xff) <<  0) |
-                    ((backingArray[baseOffset++] & 0xff) <<  8) |
-                    ((backingArray[baseOffset++] & 0xff) << 16) |
-                    ((backingArray[baseOffset  ] & 0xff) << 24));
-        }
-    }
-
-    private final long loadLong(int index) {
-        int baseOffset = offset + index;
-        if (order == ByteOrder.BIG_ENDIAN) {
-            int h = ((backingArray[baseOffset++] & 0xff) << 24) |
-                    ((backingArray[baseOffset++] & 0xff) << 16) |
-                    ((backingArray[baseOffset++] & 0xff) <<  8) |
-                    ((backingArray[baseOffset++] & 0xff) <<  0);
-            int l = ((backingArray[baseOffset++] & 0xff) << 24) |
-                    ((backingArray[baseOffset++] & 0xff) << 16) |
-                    ((backingArray[baseOffset++] & 0xff) <<  8) |
-                    ((backingArray[baseOffset  ] & 0xff) <<  0);
-            return (((long) h) << 32) | l;
-        } else {
-            int l = ((backingArray[baseOffset++] & 0xff) <<  0) |
-                    ((backingArray[baseOffset++] & 0xff) <<  8) |
-                    ((backingArray[baseOffset++] & 0xff) << 16) |
-                    ((backingArray[baseOffset++] & 0xff) << 24);
-            int h = ((backingArray[baseOffset++] & 0xff) <<  0) |
-                    ((backingArray[baseOffset++] & 0xff) <<  8) |
-                    ((backingArray[baseOffset++] & 0xff) << 16) |
-                    ((backingArray[baseOffset  ] & 0xff) << 24);
-            return (((long) h) << 32) | l;
-        }
-    }
-
-    private final short loadShort(int index) {
-        int baseOffset = offset + index;
-        if (order == ByteOrder.BIG_ENDIAN) {
-            return (short)
-                    ((backingArray[baseOffset] << 8) | (backingArray[baseOffset + 1] & 0xff));
-        } else {
-            return (short)
-                    ((backingArray[baseOffset + 1] << 8) | (backingArray[baseOffset] & 0xff));
-        }
-    }
 }
diff --git a/luni/src/main/java/java/nio/IntToByteBufferAdapter.java b/luni/src/main/java/java/nio/IntToByteBufferAdapter.java
index 1b98711..14d6ca9 100644
--- a/luni/src/main/java/java/nio/IntToByteBufferAdapter.java
+++ b/luni/src/main/java/java/nio/IntToByteBufferAdapter.java
@@ -16,6 +16,8 @@
 
 package java.nio;
 
+import libcore.io.SizeOf;
+
 /**
  * This class wraps a byte buffer to be a int buffer.
  * <p>
@@ -31,14 +33,16 @@
  */
 final class IntToByteBufferAdapter extends IntBuffer {
 
-    static IntBuffer wrap(ByteBuffer byteBuffer) {
-        return new IntToByteBufferAdapter(byteBuffer.slice());
-    }
-
     private final ByteBuffer byteBuffer;
 
-    IntToByteBufferAdapter(ByteBuffer byteBuffer) {
-        super(byteBuffer.capacity() / SIZEOF_INT);
+    static IntBuffer asIntBuffer(ByteBuffer byteBuffer) {
+        ByteBuffer slice = byteBuffer.slice();
+        slice.order(byteBuffer.order());
+        return new IntToByteBufferAdapter(slice);
+    }
+
+    private IntToByteBufferAdapter(ByteBuffer byteBuffer) {
+        super(byteBuffer.capacity() / SizeOf.INT);
         this.byteBuffer = byteBuffer;
         this.byteBuffer.clear();
         this.effectiveDirectAddress = byteBuffer.effectiveDirectAddress;
@@ -58,8 +62,8 @@
         if (byteBuffer.isReadOnly()) {
             throw new ReadOnlyBufferException();
         }
-        byteBuffer.limit(limit * SIZEOF_INT);
-        byteBuffer.position(position * SIZEOF_INT);
+        byteBuffer.limit(limit * SizeOf.INT);
+        byteBuffer.position(position * SizeOf.INT);
         byteBuffer.compact();
         byteBuffer.clear();
         position = limit - position;
@@ -82,7 +86,7 @@
         if (position == limit) {
             throw new BufferUnderflowException();
         }
-        return byteBuffer.getInt(position++ * SIZEOF_INT);
+        return byteBuffer.getInt(position++ * SizeOf.INT);
     }
 
     @Override
@@ -90,13 +94,13 @@
         if (index < 0 || index >= limit) {
             throw new IndexOutOfBoundsException();
         }
-        return byteBuffer.getInt(index * SIZEOF_INT);
+        return byteBuffer.getInt(index * SizeOf.INT);
     }
 
     @Override
     public IntBuffer get(int[] dst, int dstOffset, int intCount) {
-        byteBuffer.limit(limit * SIZEOF_INT);
-        byteBuffer.position(position * SIZEOF_INT);
+        byteBuffer.limit(limit * SizeOf.INT);
+        byteBuffer.position(position * SizeOf.INT);
         if (byteBuffer instanceof DirectByteBuffer) {
             ((DirectByteBuffer) byteBuffer).get(dst, dstOffset, intCount);
         } else {
@@ -141,7 +145,7 @@
         if (position == limit) {
             throw new BufferOverflowException();
         }
-        byteBuffer.putInt(position++ * SIZEOF_INT, c);
+        byteBuffer.putInt(position++ * SizeOf.INT, c);
         return this;
     }
 
@@ -150,14 +154,14 @@
         if (index < 0 || index >= limit) {
             throw new IndexOutOfBoundsException();
         }
-        byteBuffer.putInt(index * SIZEOF_INT, c);
+        byteBuffer.putInt(index * SizeOf.INT, c);
         return this;
     }
 
     @Override
     public IntBuffer put(int[] src, int srcOffset, int intCount) {
-        byteBuffer.limit(limit * SIZEOF_INT);
-        byteBuffer.position(position * SIZEOF_INT);
+        byteBuffer.limit(limit * SizeOf.INT);
+        byteBuffer.position(position * SizeOf.INT);
         if (byteBuffer instanceof ReadWriteDirectByteBuffer) {
             ((ReadWriteDirectByteBuffer) byteBuffer).put(src, srcOffset, intCount);
         } else {
@@ -169,8 +173,8 @@
 
     @Override
     public IntBuffer slice() {
-        byteBuffer.limit(limit * SIZEOF_INT);
-        byteBuffer.position(position * SIZEOF_INT);
+        byteBuffer.limit(limit * SizeOf.INT);
+        byteBuffer.position(position * SizeOf.INT);
         IntBuffer result = new IntToByteBufferAdapter(byteBuffer.slice());
         byteBuffer.clear();
         return result;
diff --git a/luni/src/main/java/java/nio/LongToByteBufferAdapter.java b/luni/src/main/java/java/nio/LongToByteBufferAdapter.java
index a426409..80e9a51 100644
--- a/luni/src/main/java/java/nio/LongToByteBufferAdapter.java
+++ b/luni/src/main/java/java/nio/LongToByteBufferAdapter.java
@@ -16,6 +16,8 @@
 
 package java.nio;
 
+import libcore.io.SizeOf;
+
 /**
  * This class wraps a byte buffer to be a long buffer.
  * <p>
@@ -31,14 +33,16 @@
  */
 final class LongToByteBufferAdapter extends LongBuffer {
 
-    static LongBuffer wrap(ByteBuffer byteBuffer) {
-        return new LongToByteBufferAdapter(byteBuffer.slice());
-    }
-
     private final ByteBuffer byteBuffer;
 
-    LongToByteBufferAdapter(ByteBuffer byteBuffer) {
-        super(byteBuffer.capacity() / SIZEOF_LONG);
+    static LongBuffer asLongBuffer(ByteBuffer byteBuffer) {
+        ByteBuffer slice = byteBuffer.slice();
+        slice.order(byteBuffer.order());
+        return new LongToByteBufferAdapter(slice);
+    }
+
+    private LongToByteBufferAdapter(ByteBuffer byteBuffer) {
+        super(byteBuffer.capacity() / SizeOf.LONG);
         this.byteBuffer = byteBuffer;
         this.byteBuffer.clear();
         this.effectiveDirectAddress = byteBuffer.effectiveDirectAddress;
@@ -58,8 +62,8 @@
         if (byteBuffer.isReadOnly()) {
             throw new ReadOnlyBufferException();
         }
-        byteBuffer.limit(limit * SIZEOF_LONG);
-        byteBuffer.position(position * SIZEOF_LONG);
+        byteBuffer.limit(limit * SizeOf.LONG);
+        byteBuffer.position(position * SizeOf.LONG);
         byteBuffer.compact();
         byteBuffer.clear();
         position = limit - position;
@@ -82,7 +86,7 @@
         if (position == limit) {
             throw new BufferUnderflowException();
         }
-        return byteBuffer.getLong(position++ * SIZEOF_LONG);
+        return byteBuffer.getLong(position++ * SizeOf.LONG);
     }
 
     @Override
@@ -90,13 +94,13 @@
         if (index < 0 || index >= limit) {
             throw new IndexOutOfBoundsException();
         }
-        return byteBuffer.getLong(index * SIZEOF_LONG);
+        return byteBuffer.getLong(index * SizeOf.LONG);
     }
 
     @Override
     public LongBuffer get(long[] dst, int dstOffset, int longCount) {
-        byteBuffer.limit(limit * SIZEOF_LONG);
-        byteBuffer.position(position * SIZEOF_LONG);
+        byteBuffer.limit(limit * SizeOf.LONG);
+        byteBuffer.position(position * SizeOf.LONG);
         if (byteBuffer instanceof DirectByteBuffer) {
             ((DirectByteBuffer) byteBuffer).get(dst, dstOffset, longCount);
         } else {
@@ -141,7 +145,7 @@
         if (position == limit) {
             throw new BufferOverflowException();
         }
-        byteBuffer.putLong(position++ * SIZEOF_LONG, c);
+        byteBuffer.putLong(position++ * SizeOf.LONG, c);
         return this;
     }
 
@@ -150,14 +154,14 @@
         if (index < 0 || index >= limit) {
             throw new IndexOutOfBoundsException();
         }
-        byteBuffer.putLong(index * SIZEOF_LONG, c);
+        byteBuffer.putLong(index * SizeOf.LONG, c);
         return this;
     }
 
     @Override
     public LongBuffer put(long[] src, int srcOffset, int longCount) {
-        byteBuffer.limit(limit * SIZEOF_LONG);
-        byteBuffer.position(position * SIZEOF_LONG);
+        byteBuffer.limit(limit * SizeOf.LONG);
+        byteBuffer.position(position * SizeOf.LONG);
         if (byteBuffer instanceof ReadWriteDirectByteBuffer) {
             ((ReadWriteDirectByteBuffer) byteBuffer).put(src, srcOffset, longCount);
         } else {
@@ -169,8 +173,8 @@
 
     @Override
     public LongBuffer slice() {
-        byteBuffer.limit(limit * SIZEOF_LONG);
-        byteBuffer.position(position * SIZEOF_LONG);
+        byteBuffer.limit(limit * SizeOf.LONG);
+        byteBuffer.position(position * SizeOf.LONG);
         LongBuffer result = new LongToByteBufferAdapter(byteBuffer.slice());
         byteBuffer.clear();
         return result;
diff --git a/luni/src/main/java/java/nio/MappedByteBufferAdapter.java b/luni/src/main/java/java/nio/MappedByteBufferAdapter.java
index 1b3b2de..1682a1f 100644
--- a/luni/src/main/java/java/nio/MappedByteBufferAdapter.java
+++ b/luni/src/main/java/java/nio/MappedByteBufferAdapter.java
@@ -18,6 +18,7 @@
 package java.nio;
 
 import java.nio.channels.FileChannel.MapMode;
+import libcore.io.SizeOf;
 
 /**
  * Rather than duplicate all the code from ReadOnlyDirectByteBuffer and
@@ -137,7 +138,7 @@
     public char getChar() {
         wrapped.position(position);
         char result = wrapped.getChar();
-        position += SIZEOF_CHAR;
+        position += SizeOf.CHAR;
         return result;
     }
 
@@ -150,7 +151,7 @@
     public double getDouble() {
         wrapped.position(position);
         double result = wrapped.getDouble();
-        position += SIZEOF_DOUBLE;
+        position += SizeOf.DOUBLE;
         return result;
     }
 
@@ -163,7 +164,7 @@
     public float getFloat() {
         wrapped.position(position);
         float result = wrapped.getFloat();
-        position += SIZEOF_FLOAT;
+        position += SizeOf.FLOAT;
         return result;
     }
 
@@ -176,7 +177,7 @@
     public int getInt() {
         wrapped.position(position);
         int result = wrapped.getInt();
-        position += SIZEOF_INT;
+        position += SizeOf.INT;
         return result;
     }
 
@@ -189,7 +190,7 @@
     public long getLong() {
         wrapped.position(position);
         long result = wrapped.getLong();
-        position += SIZEOF_LONG;
+        position += SizeOf.LONG;
         return result;
     }
 
@@ -202,7 +203,7 @@
     public short getShort() {
         wrapped.position(position);
         short result = wrapped.getShort();
-        position += SIZEOF_SHORT;
+        position += SizeOf.SHORT;
         return result;
     }
 
@@ -253,7 +254,7 @@
     public ByteBuffer putChar(char value) {
         wrapped.position(this.position);
         wrapped.putChar(value);
-        this.position += SIZEOF_CHAR;
+        this.position += SizeOf.CHAR;
         return this;
     }
 
@@ -268,7 +269,7 @@
     public ByteBuffer putDouble(double value) {
         wrapped.position(this.position);
         wrapped.putDouble(value);
-        this.position += SIZEOF_DOUBLE;
+        this.position += SizeOf.DOUBLE;
         return this;
     }
 
@@ -283,7 +284,7 @@
     public ByteBuffer putFloat(float value) {
         wrapped.position(this.position);
         wrapped.putFloat(value);
-        this.position += SIZEOF_FLOAT;
+        this.position += SizeOf.FLOAT;
         return this;
     }
 
@@ -305,7 +306,7 @@
     public ByteBuffer putInt(int value) {
         wrapped.position(this.position);
         wrapped.putInt(value);
-        this.position += SIZEOF_INT;
+        this.position += SizeOf.INT;
         return this;
     }
 
@@ -320,7 +321,7 @@
     public ByteBuffer putLong(long value) {
         wrapped.position(this.position);
         wrapped.putLong(value);
-        this.position += SIZEOF_LONG;
+        this.position += SizeOf.LONG;
         return this;
     }
 
@@ -335,7 +336,7 @@
     public ByteBuffer putShort(short value) {
         wrapped.position(this.position);
         wrapped.putShort(value);
-        this.position += SIZEOF_SHORT;
+        this.position += SizeOf.SHORT;
         return this;
     }
 
diff --git a/luni/src/main/java/java/nio/ReadOnlyCharArrayBuffer.java b/luni/src/main/java/java/nio/ReadOnlyCharArrayBuffer.java
index 0be17e6..6b1a03e 100644
--- a/luni/src/main/java/java/nio/ReadOnlyCharArrayBuffer.java
+++ b/luni/src/main/java/java/nio/ReadOnlyCharArrayBuffer.java
@@ -32,8 +32,8 @@
 final class ReadOnlyCharArrayBuffer extends CharArrayBuffer {
 
     static ReadOnlyCharArrayBuffer copy(CharArrayBuffer other, int markOfOther) {
-        ReadOnlyCharArrayBuffer buf = new ReadOnlyCharArrayBuffer(other.capacity(),
-                other.backingArray, other.offset);
+        ReadOnlyCharArrayBuffer buf =
+                new ReadOnlyCharArrayBuffer(other.capacity(), other.backingArray, other.offset);
         buf.limit = other.limit;
         buf.position = other.position();
         buf.mark = markOfOther;
@@ -110,7 +110,6 @@
 
     @Override
     public CharBuffer slice() {
-        return new ReadOnlyCharArrayBuffer(remaining(), backingArray, offset
-                + position);
+        return new ReadOnlyCharArrayBuffer(remaining(), backingArray, offset + position);
     }
 }
diff --git a/luni/src/main/java/java/nio/ReadOnlyDirectByteBuffer.java b/luni/src/main/java/java/nio/ReadOnlyDirectByteBuffer.java
index 0c93926..d061e9c 100644
--- a/luni/src/main/java/java/nio/ReadOnlyDirectByteBuffer.java
+++ b/luni/src/main/java/java/nio/ReadOnlyDirectByteBuffer.java
@@ -34,7 +34,6 @@
         buf.limit = other.limit;
         buf.position = other.position();
         buf.mark = markOfOther;
-        buf.order(other.order());
         return buf;
     }
 
@@ -134,8 +133,6 @@
 
     @Override
     public ByteBuffer slice() {
-        ReadOnlyDirectByteBuffer buf = new ReadOnlyDirectByteBuffer(block, remaining(), offset + position);
-        buf.order = order;
-        return buf;
+        return new ReadOnlyDirectByteBuffer(block, remaining(), offset + position);
     }
 }
diff --git a/luni/src/main/java/java/nio/ReadOnlyDoubleArrayBuffer.java b/luni/src/main/java/java/nio/ReadOnlyDoubleArrayBuffer.java
index 31719ed..460bbf4 100644
--- a/luni/src/main/java/java/nio/ReadOnlyDoubleArrayBuffer.java
+++ b/luni/src/main/java/java/nio/ReadOnlyDoubleArrayBuffer.java
@@ -31,18 +31,16 @@
  */
 final class ReadOnlyDoubleArrayBuffer extends DoubleArrayBuffer {
 
-    static ReadOnlyDoubleArrayBuffer copy(DoubleArrayBuffer other,
-            int markOfOther) {
-        ReadOnlyDoubleArrayBuffer buf = new ReadOnlyDoubleArrayBuffer(other
-                .capacity(), other.backingArray, other.offset);
+    static ReadOnlyDoubleArrayBuffer copy(DoubleArrayBuffer other, int markOfOther) {
+        ReadOnlyDoubleArrayBuffer buf =
+                new ReadOnlyDoubleArrayBuffer(other.capacity(), other.backingArray, other.offset);
         buf.limit = other.limit;
         buf.position = other.position();
         buf.mark = markOfOther;
         return buf;
     }
 
-    ReadOnlyDoubleArrayBuffer(int capacity, double[] backingArray,
-            int arrayOffset) {
+    ReadOnlyDoubleArrayBuffer(int capacity, double[] backingArray, int arrayOffset) {
         super(capacity, backingArray, arrayOffset);
     }
 
@@ -103,8 +101,7 @@
 
     @Override
     public DoubleBuffer slice() {
-        return new ReadOnlyDoubleArrayBuffer(remaining(), backingArray, offset
-                + position);
+        return new ReadOnlyDoubleArrayBuffer(remaining(), backingArray, offset + position);
     }
 
 }
diff --git a/luni/src/main/java/java/nio/ReadOnlyFloatArrayBuffer.java b/luni/src/main/java/java/nio/ReadOnlyFloatArrayBuffer.java
index f322af6..775e1d8 100644
--- a/luni/src/main/java/java/nio/ReadOnlyFloatArrayBuffer.java
+++ b/luni/src/main/java/java/nio/ReadOnlyFloatArrayBuffer.java
@@ -32,8 +32,8 @@
 final class ReadOnlyFloatArrayBuffer extends FloatArrayBuffer {
 
     static ReadOnlyFloatArrayBuffer copy(FloatArrayBuffer other, int markOfOther) {
-        ReadOnlyFloatArrayBuffer buf = new ReadOnlyFloatArrayBuffer(other.capacity(),
-                other.backingArray, other.offset);
+        ReadOnlyFloatArrayBuffer buf =
+                new ReadOnlyFloatArrayBuffer(other.capacity(), other.backingArray, other.offset);
         buf.limit = other.limit;
         buf.position = other.position();
         buf.mark = markOfOther;
diff --git a/luni/src/main/java/java/nio/ReadOnlyHeapByteBuffer.java b/luni/src/main/java/java/nio/ReadOnlyHeapByteBuffer.java
index 558fcee..ca486cb 100644
--- a/luni/src/main/java/java/nio/ReadOnlyHeapByteBuffer.java
+++ b/luni/src/main/java/java/nio/ReadOnlyHeapByteBuffer.java
@@ -32,12 +32,11 @@
 final class ReadOnlyHeapByteBuffer extends HeapByteBuffer {
 
     static ReadOnlyHeapByteBuffer copy(HeapByteBuffer other, int markOfOther) {
-        ReadOnlyHeapByteBuffer buf = new ReadOnlyHeapByteBuffer(other.backingArray,
-                other.capacity(), other.offset);
+        ReadOnlyHeapByteBuffer buf =
+                new ReadOnlyHeapByteBuffer(other.backingArray, other.capacity(), other.offset);
         buf.limit = other.limit;
         buf.position = other.position();
         buf.mark = markOfOther;
-        buf.order(other.order());
         return buf;
     }
 
@@ -152,9 +151,6 @@
 
     @Override
     public ByteBuffer slice() {
-        ReadOnlyHeapByteBuffer slice = new ReadOnlyHeapByteBuffer(backingArray,
-                remaining(), offset + position);
-        slice.order = order;
-        return slice;
+        return new ReadOnlyHeapByteBuffer(backingArray, remaining(), offset + position);
     }
 }
diff --git a/luni/src/main/java/java/nio/ReadOnlyIntArrayBuffer.java b/luni/src/main/java/java/nio/ReadOnlyIntArrayBuffer.java
index 87119b6..a137b3b 100644
--- a/luni/src/main/java/java/nio/ReadOnlyIntArrayBuffer.java
+++ b/luni/src/main/java/java/nio/ReadOnlyIntArrayBuffer.java
@@ -32,8 +32,8 @@
 final class ReadOnlyIntArrayBuffer extends IntArrayBuffer {
 
     static ReadOnlyIntArrayBuffer copy(IntArrayBuffer other, int markOfOther) {
-        ReadOnlyIntArrayBuffer buf = new ReadOnlyIntArrayBuffer(other.capacity(),
-                other.backingArray, other.offset);
+        ReadOnlyIntArrayBuffer buf =
+                new ReadOnlyIntArrayBuffer(other.capacity(), other.backingArray, other.offset);
         buf.limit = other.limit;
         buf.position = other.position();
         buf.mark = markOfOther;
@@ -101,8 +101,7 @@
 
     @Override
     public IntBuffer slice() {
-        return new ReadOnlyIntArrayBuffer(remaining(), backingArray, offset
-                + position);
+        return new ReadOnlyIntArrayBuffer(remaining(), backingArray, offset + position);
     }
 
 }
diff --git a/luni/src/main/java/java/nio/ReadOnlyLongArrayBuffer.java b/luni/src/main/java/java/nio/ReadOnlyLongArrayBuffer.java
index 3571ec5..87b0c88 100644
--- a/luni/src/main/java/java/nio/ReadOnlyLongArrayBuffer.java
+++ b/luni/src/main/java/java/nio/ReadOnlyLongArrayBuffer.java
@@ -32,8 +32,8 @@
 final class ReadOnlyLongArrayBuffer extends LongArrayBuffer {
 
     static ReadOnlyLongArrayBuffer copy(LongArrayBuffer other, int markOfOther) {
-        ReadOnlyLongArrayBuffer buf = new ReadOnlyLongArrayBuffer(other.capacity(),
-                other.backingArray, other.offset);
+        ReadOnlyLongArrayBuffer buf =
+                new ReadOnlyLongArrayBuffer(other.capacity(), other.backingArray, other.offset);
         buf.limit = other.limit;
         buf.position = other.position();
         buf.mark = markOfOther;
@@ -101,8 +101,7 @@
 
     @Override
     public LongBuffer slice() {
-        return new ReadOnlyLongArrayBuffer(remaining(), backingArray, offset
-                + position);
+        return new ReadOnlyLongArrayBuffer(remaining(), backingArray, offset + position);
     }
 
 }
diff --git a/luni/src/main/java/java/nio/ReadOnlyShortArrayBuffer.java b/luni/src/main/java/java/nio/ReadOnlyShortArrayBuffer.java
index 2c777ab..07b9c90 100644
--- a/luni/src/main/java/java/nio/ReadOnlyShortArrayBuffer.java
+++ b/luni/src/main/java/java/nio/ReadOnlyShortArrayBuffer.java
@@ -32,8 +32,8 @@
 final class ReadOnlyShortArrayBuffer extends ShortArrayBuffer {
 
     static ReadOnlyShortArrayBuffer copy(ShortArrayBuffer other, int markOfOther) {
-        ReadOnlyShortArrayBuffer buf = new ReadOnlyShortArrayBuffer(other.capacity(),
-                other.backingArray, other.offset);
+        ReadOnlyShortArrayBuffer buf =
+                new ReadOnlyShortArrayBuffer(other.capacity(), other.backingArray, other.offset);
         buf.limit = other.limit;
         buf.position = other.position();
         buf.mark = markOfOther;
@@ -101,8 +101,7 @@
 
     @Override
     public ShortBuffer slice() {
-        return new ReadOnlyShortArrayBuffer(remaining(), backingArray, offset
-                + position);
+        return new ReadOnlyShortArrayBuffer(remaining(), backingArray, offset + position);
     }
 
 }
diff --git a/luni/src/main/java/java/nio/ReadWriteCharArrayBuffer.java b/luni/src/main/java/java/nio/ReadWriteCharArrayBuffer.java
index 26ec247..546b3ce 100644
--- a/luni/src/main/java/java/nio/ReadWriteCharArrayBuffer.java
+++ b/luni/src/main/java/java/nio/ReadWriteCharArrayBuffer.java
@@ -31,8 +31,8 @@
 final class ReadWriteCharArrayBuffer extends CharArrayBuffer {
 
     static ReadWriteCharArrayBuffer copy(CharArrayBuffer other, int markOfOther) {
-        ReadWriteCharArrayBuffer buf = new ReadWriteCharArrayBuffer(other.capacity(),
-                other.backingArray, other.offset);
+        ReadWriteCharArrayBuffer buf =
+                new ReadWriteCharArrayBuffer(other.capacity(), other.backingArray, other.offset);
         buf.limit = other.limit;
         buf.position = other.position();
         buf.mark = markOfOther;
diff --git a/luni/src/main/java/java/nio/ReadWriteDirectByteBuffer.java b/luni/src/main/java/java/nio/ReadWriteDirectByteBuffer.java
index 724f4ec..71bd18b 100644
--- a/luni/src/main/java/java/nio/ReadWriteDirectByteBuffer.java
+++ b/luni/src/main/java/java/nio/ReadWriteDirectByteBuffer.java
@@ -17,6 +17,7 @@
 
 package java.nio;
 
+import libcore.io.SizeOf;
 import org.apache.harmony.luni.platform.OSMemory;
 
 /**
@@ -32,11 +33,11 @@
  */
 final class ReadWriteDirectByteBuffer extends DirectByteBuffer {
     static ReadWriteDirectByteBuffer copy(DirectByteBuffer other, int markOfOther) {
-        ReadWriteDirectByteBuffer buf = new ReadWriteDirectByteBuffer(other.block, other.capacity(), other.offset);
+        ReadWriteDirectByteBuffer buf =
+                new ReadWriteDirectByteBuffer(other.block, other.capacity(), other.offset);
         buf.limit = other.limit;
         buf.position = other.position();
         buf.mark = markOfOther;
-        buf.order(other.order());
         return buf;
     }
 
@@ -106,44 +107,44 @@
     }
 
     final void put(char[] src, int srcOffset, int charCount) {
-        int byteCount = checkPutBounds(SIZEOF_CHAR, src.length, srcOffset, charCount);
+        int byteCount = checkPutBounds(SizeOf.CHAR, src.length, srcOffset, charCount);
         this.block.pokeCharArray(offset + position, src, srcOffset, charCount, order.needsSwap);
         position += byteCount;
     }
 
     final void put(double[] src, int srcOffset, int doubleCount) {
-        int byteCount = checkPutBounds(SIZEOF_DOUBLE, src.length, srcOffset, doubleCount);
+        int byteCount = checkPutBounds(SizeOf.DOUBLE, src.length, srcOffset, doubleCount);
         this.block.pokeDoubleArray(offset + position, src, srcOffset, doubleCount, order.needsSwap);
         position += byteCount;
     }
 
     final void put(float[] src, int srcOffset, int floatCount) {
-        int byteCount = checkPutBounds(SIZEOF_FLOAT, src.length, srcOffset, floatCount);
+        int byteCount = checkPutBounds(SizeOf.FLOAT, src.length, srcOffset, floatCount);
         this.block.pokeFloatArray(offset + position, src, srcOffset, floatCount, order.needsSwap);
         position += byteCount;
     }
 
     final void put(int[] src, int srcOffset, int intCount) {
-        int byteCount = checkPutBounds(SIZEOF_INT, src.length, srcOffset, intCount);
+        int byteCount = checkPutBounds(SizeOf.INT, src.length, srcOffset, intCount);
         this.block.pokeIntArray(offset + position, src, srcOffset, intCount, order.needsSwap);
         position += byteCount;
     }
 
     final void put(long[] src, int srcOffset, int longCount) {
-        int byteCount = checkPutBounds(SIZEOF_LONG, src.length, srcOffset, longCount);
+        int byteCount = checkPutBounds(SizeOf.LONG, src.length, srcOffset, longCount);
         this.block.pokeLongArray(offset + position, src, srcOffset, longCount, order.needsSwap);
         position += byteCount;
     }
 
     final void put(short[] src, int srcOffset, int shortCount) {
-        int byteCount = checkPutBounds(SIZEOF_SHORT, src.length, srcOffset, shortCount);
+        int byteCount = checkPutBounds(SizeOf.SHORT, src.length, srcOffset, shortCount);
         this.block.pokeShortArray(offset + position, src, srcOffset, shortCount, order.needsSwap);
         position += byteCount;
     }
 
     @Override
     public ByteBuffer putChar(char value) {
-        int newPosition = position + SIZEOF_CHAR;
+        int newPosition = position + SizeOf.CHAR;
         if (newPosition > limit) {
             throw new BufferOverflowException();
         }
@@ -154,7 +155,7 @@
 
     @Override
     public ByteBuffer putChar(int index, char value) {
-        if (index < 0 || (long) index + SIZEOF_CHAR > limit) {
+        if (index < 0 || (long) index + SizeOf.CHAR > limit) {
             throw new IndexOutOfBoundsException();
         }
         this.block.pokeShort(offset + index, (short) value, order);
@@ -163,7 +164,7 @@
 
     @Override
     public ByteBuffer putDouble(double value) {
-        int newPosition = position + SIZEOF_DOUBLE;
+        int newPosition = position + SizeOf.DOUBLE;
         if (newPosition > limit) {
             throw new BufferOverflowException();
         }
@@ -174,7 +175,7 @@
 
     @Override
     public ByteBuffer putDouble(int index, double value) {
-        if (index < 0 || (long) index + SIZEOF_DOUBLE > limit) {
+        if (index < 0 || (long) index + SizeOf.DOUBLE > limit) {
             throw new IndexOutOfBoundsException();
         }
         this.block.pokeLong(offset + index, Double.doubleToRawLongBits(value), order);
@@ -183,7 +184,7 @@
 
     @Override
     public ByteBuffer putFloat(float value) {
-        int newPosition = position + SIZEOF_FLOAT;
+        int newPosition = position + SizeOf.FLOAT;
         if (newPosition > limit) {
             throw new BufferOverflowException();
         }
@@ -194,7 +195,7 @@
 
     @Override
     public ByteBuffer putFloat(int index, float value) {
-        if (index < 0 || (long) index + SIZEOF_FLOAT > limit) {
+        if (index < 0 || (long) index + SizeOf.FLOAT > limit) {
             throw new IndexOutOfBoundsException();
         }
         this.block.pokeInt(offset + index, Float.floatToRawIntBits(value), order);
@@ -203,7 +204,7 @@
 
     @Override
     public ByteBuffer putInt(int value) {
-        int newPosition = position + SIZEOF_INT;
+        int newPosition = position + SizeOf.INT;
         if (newPosition > limit) {
             throw new BufferOverflowException();
         }
@@ -214,7 +215,7 @@
 
     @Override
     public ByteBuffer putInt(int index, int value) {
-        if (index < 0 || (long) index + SIZEOF_INT > limit) {
+        if (index < 0 || (long) index + SizeOf.INT > limit) {
             throw new IndexOutOfBoundsException();
         }
         this.block.pokeInt(offset + index, value, order);
@@ -223,7 +224,7 @@
 
     @Override
     public ByteBuffer putLong(long value) {
-        int newPosition = position + SIZEOF_LONG;
+        int newPosition = position + SizeOf.LONG;
         if (newPosition > limit) {
             throw new BufferOverflowException();
         }
@@ -234,7 +235,7 @@
 
     @Override
     public ByteBuffer putLong(int index, long value) {
-        if (index < 0 || (long) index + SIZEOF_LONG > limit) {
+        if (index < 0 || (long) index + SizeOf.LONG > limit) {
             throw new IndexOutOfBoundsException();
         }
         this.block.pokeLong(offset + index, value, order);
@@ -243,7 +244,7 @@
 
     @Override
     public ByteBuffer putShort(short value) {
-        int newPosition = position + SIZEOF_SHORT;
+        int newPosition = position + SizeOf.SHORT;
         if (newPosition > limit) {
             throw new BufferOverflowException();
         }
@@ -254,7 +255,7 @@
 
     @Override
     public ByteBuffer putShort(int index, short value) {
-        if (index < 0 || (long) index + SIZEOF_SHORT > limit) {
+        if (index < 0 || (long) index + SizeOf.SHORT > limit) {
             throw new IndexOutOfBoundsException();
         }
         this.block.pokeShort(offset + index, value, order);
@@ -263,9 +264,7 @@
 
     @Override
     public ByteBuffer slice() {
-        ReadWriteDirectByteBuffer buf = new ReadWriteDirectByteBuffer(block, remaining(), offset + position);
-        buf.order = order;
-        return buf;
+        return new ReadWriteDirectByteBuffer(block, remaining(), offset + position);
     }
 
 }
diff --git a/luni/src/main/java/java/nio/ReadWriteDoubleArrayBuffer.java b/luni/src/main/java/java/nio/ReadWriteDoubleArrayBuffer.java
index 9255ff3..880b339 100644
--- a/luni/src/main/java/java/nio/ReadWriteDoubleArrayBuffer.java
+++ b/luni/src/main/java/java/nio/ReadWriteDoubleArrayBuffer.java
@@ -32,8 +32,8 @@
 final class ReadWriteDoubleArrayBuffer extends DoubleArrayBuffer {
 
     static ReadWriteDoubleArrayBuffer copy(DoubleArrayBuffer other, int markOfOther) {
-        ReadWriteDoubleArrayBuffer buf = new ReadWriteDoubleArrayBuffer(other.capacity(),
-                other.backingArray, other.offset);
+        ReadWriteDoubleArrayBuffer buf =
+                new ReadWriteDoubleArrayBuffer(other.capacity(), other.backingArray, other.offset);
         buf.limit = other.limit;
         buf.position = other.position();
         buf.mark = markOfOther;
diff --git a/luni/src/main/java/java/nio/ReadWriteFloatArrayBuffer.java b/luni/src/main/java/java/nio/ReadWriteFloatArrayBuffer.java
index ddae0a1..bf2f485 100644
--- a/luni/src/main/java/java/nio/ReadWriteFloatArrayBuffer.java
+++ b/luni/src/main/java/java/nio/ReadWriteFloatArrayBuffer.java
@@ -32,8 +32,8 @@
 final class ReadWriteFloatArrayBuffer extends FloatArrayBuffer {
 
     static ReadWriteFloatArrayBuffer copy(FloatArrayBuffer other, int markOfOther) {
-        ReadWriteFloatArrayBuffer buf = new ReadWriteFloatArrayBuffer(other.capacity(),
-                other.backingArray, other.offset);
+        ReadWriteFloatArrayBuffer buf =
+                new ReadWriteFloatArrayBuffer(other.capacity(), other.backingArray, other.offset);
         buf.limit = other.limit;
         buf.position = other.position();
         buf.mark = markOfOther;
@@ -48,8 +48,7 @@
         super(capacity);
     }
 
-    ReadWriteFloatArrayBuffer(int capacity, float[] backingArray,
-            int arrayOffset) {
+    ReadWriteFloatArrayBuffer(int capacity, float[] backingArray, int arrayOffset) {
         super(capacity, backingArray, arrayOffset);
     }
 
@@ -60,8 +59,7 @@
 
     @Override
     public FloatBuffer compact() {
-        System.arraycopy(backingArray, position + offset, backingArray, offset,
-                remaining());
+        System.arraycopy(backingArray, position + offset, backingArray, offset, remaining());
         position = limit - position;
         limit = capacity;
         mark = UNSET_MARK;
diff --git a/luni/src/main/java/java/nio/ReadWriteHeapByteBuffer.java b/luni/src/main/java/java/nio/ReadWriteHeapByteBuffer.java
index 98e0b7a..7cd1c5c 100644
--- a/luni/src/main/java/java/nio/ReadWriteHeapByteBuffer.java
+++ b/luni/src/main/java/java/nio/ReadWriteHeapByteBuffer.java
@@ -16,6 +16,7 @@
 
 package java.nio;
 
+import libcore.io.SizeOf;
 import org.apache.harmony.luni.platform.OSMemory;
 
 /**
@@ -32,12 +33,11 @@
 final class ReadWriteHeapByteBuffer extends HeapByteBuffer {
 
     static ReadWriteHeapByteBuffer copy(HeapByteBuffer other, int markOfOther) {
-        ReadWriteHeapByteBuffer buf = new ReadWriteHeapByteBuffer(other.backingArray,
-                other.capacity(), other.offset);
+        ReadWriteHeapByteBuffer buf =
+                new ReadWriteHeapByteBuffer(other.backingArray, other.capacity(), other.offset);
         buf.limit = other.limit;
         buf.position = other.position();
         buf.mark = markOfOther;
-        buf.order(other.order());
         return buf;
     }
 
@@ -119,57 +119,57 @@
     }
 
     final void put(char[] src, int srcOffset, int charCount) {
-        int byteCount = checkPutBounds(SIZEOF_CHAR, src.length, srcOffset, charCount);
-        OSMemory.unsafeBulkPut(backingArray, offset + position, byteCount, src, srcOffset, SIZEOF_CHAR, order.needsSwap);
+        int byteCount = checkPutBounds(SizeOf.CHAR, src.length, srcOffset, charCount);
+        OSMemory.unsafeBulkPut(backingArray, offset + position, byteCount, src, srcOffset, SizeOf.CHAR, order.needsSwap);
         position += byteCount;
     }
 
     final void put(double[] src, int srcOffset, int doubleCount) {
-        int byteCount = checkPutBounds(SIZEOF_DOUBLE, src.length, srcOffset, doubleCount);
-        OSMemory.unsafeBulkPut(backingArray, offset + position, byteCount, src, srcOffset, SIZEOF_DOUBLE, order.needsSwap);
+        int byteCount = checkPutBounds(SizeOf.DOUBLE, src.length, srcOffset, doubleCount);
+        OSMemory.unsafeBulkPut(backingArray, offset + position, byteCount, src, srcOffset, SizeOf.DOUBLE, order.needsSwap);
         position += byteCount;
     }
 
     final void put(float[] src, int srcOffset, int floatCount) {
-        int byteCount = checkPutBounds(SIZEOF_FLOAT, src.length, srcOffset, floatCount);
-        OSMemory.unsafeBulkPut(backingArray, offset + position, byteCount, src, srcOffset, SIZEOF_FLOAT, order.needsSwap);
+        int byteCount = checkPutBounds(SizeOf.FLOAT, src.length, srcOffset, floatCount);
+        OSMemory.unsafeBulkPut(backingArray, offset + position, byteCount, src, srcOffset, SizeOf.FLOAT, order.needsSwap);
         position += byteCount;
     }
 
     final void put(int[] src, int srcOffset, int intCount) {
-        int byteCount = checkPutBounds(SIZEOF_INT, src.length, srcOffset, intCount);
-        OSMemory.unsafeBulkPut(backingArray, offset + position, byteCount, src, srcOffset, SIZEOF_INT, order.needsSwap);
+        int byteCount = checkPutBounds(SizeOf.INT, src.length, srcOffset, intCount);
+        OSMemory.unsafeBulkPut(backingArray, offset + position, byteCount, src, srcOffset, SizeOf.INT, order.needsSwap);
         position += byteCount;
     }
 
     final void put(long[] src, int srcOffset, int longCount) {
-        int byteCount = checkPutBounds(SIZEOF_LONG, src.length, srcOffset, longCount);
-        OSMemory.unsafeBulkPut(backingArray, offset + position, byteCount, src, srcOffset, SIZEOF_LONG, order.needsSwap);
+        int byteCount = checkPutBounds(SizeOf.LONG, src.length, srcOffset, longCount);
+        OSMemory.unsafeBulkPut(backingArray, offset + position, byteCount, src, srcOffset, SizeOf.LONG, order.needsSwap);
         position += byteCount;
     }
 
     final void put(short[] src, int srcOffset, int shortCount) {
-        int byteCount = checkPutBounds(SIZEOF_SHORT, src.length, srcOffset, shortCount);
-        OSMemory.unsafeBulkPut(backingArray, offset + position, byteCount, src, srcOffset, SIZEOF_SHORT, order.needsSwap);
+        int byteCount = checkPutBounds(SizeOf.SHORT, src.length, srcOffset, shortCount);
+        OSMemory.unsafeBulkPut(backingArray, offset + position, byteCount, src, srcOffset, SizeOf.SHORT, order.needsSwap);
         position += byteCount;
     }
 
     @Override
     public ByteBuffer putChar(int index, char value) {
-        if (index < 0 || (long) index + SIZEOF_CHAR > limit) {
+        if (index < 0 || (long) index + SizeOf.CHAR > limit) {
             throw new IndexOutOfBoundsException();
         }
-        storeShort(index, (short) value);
+        OSMemory.pokeShort(backingArray, offset + index, (short) value, order);
         return this;
     }
 
     @Override
     public ByteBuffer putChar(char value) {
-        int newPosition = position + SIZEOF_CHAR;
+        int newPosition = position + SizeOf.CHAR;
         if (newPosition > limit) {
             throw new BufferOverflowException();
         }
-        storeShort(position, (short) value);
+        OSMemory.pokeShort(backingArray, offset + position, (short) value, order);
         position = newPosition;
         return this;
     }
@@ -196,122 +196,66 @@
 
     @Override
     public ByteBuffer putInt(int value) {
-        int newPosition = position + SIZEOF_INT;
+        int newPosition = position + SizeOf.INT;
         if (newPosition > limit) {
             throw new BufferOverflowException();
         }
-        storeInt(position, value);
+        OSMemory.pokeInt(backingArray, offset + position, value, order);
         position = newPosition;
         return this;
     }
 
     @Override
     public ByteBuffer putInt(int index, int value) {
-        if (index < 0 || (long) index + SIZEOF_INT > limit) {
+        if (index < 0 || (long) index + SizeOf.INT > limit) {
             throw new IndexOutOfBoundsException();
         }
-        storeInt(index, value);
+        OSMemory.pokeInt(backingArray, offset + index, value, order);
         return this;
     }
 
     @Override
     public ByteBuffer putLong(int index, long value) {
-        if (index < 0 || (long) index + SIZEOF_LONG > limit) {
+        if (index < 0 || (long) index + SizeOf.LONG > limit) {
             throw new IndexOutOfBoundsException();
         }
-        storeLong(index, value);
+        OSMemory.pokeLong(backingArray, offset + index, value, order);
         return this;
     }
 
     @Override
     public ByteBuffer putLong(long value) {
-        int newPosition = position + SIZEOF_LONG;
+        int newPosition = position + SizeOf.LONG;
         if (newPosition > limit) {
             throw new BufferOverflowException();
         }
-        storeLong(position, value);
+        OSMemory.pokeLong(backingArray, offset + position, value, order);
         position = newPosition;
         return this;
     }
 
     @Override
     public ByteBuffer putShort(int index, short value) {
-        if (index < 0 || (long) index + SIZEOF_SHORT > limit) {
+        if (index < 0 || (long) index + SizeOf.SHORT > limit) {
             throw new IndexOutOfBoundsException();
         }
-        storeShort(index, value);
+        OSMemory.pokeShort(backingArray, offset + index, value, order);
         return this;
     }
 
     @Override
     public ByteBuffer putShort(short value) {
-        int newPosition = position + SIZEOF_SHORT;
+        int newPosition = position + SizeOf.SHORT;
         if (newPosition > limit) {
             throw new BufferOverflowException();
         }
-        storeShort(position, value);
+        OSMemory.pokeShort(backingArray, offset + position, value, order);
         position = newPosition;
         return this;
     }
 
-    private final void storeInt(int index, int value) {
-        int baseOffset = offset + index;
-        if (order == ByteOrder.BIG_ENDIAN) {
-            backingArray[baseOffset++] = (byte) ((value >> 24) & 0xff);
-            backingArray[baseOffset++] = (byte) ((value >> 16) & 0xff);
-            backingArray[baseOffset++] = (byte) ((value >>  8) & 0xff);
-            backingArray[baseOffset  ] = (byte) ((value >>  0) & 0xff);
-        } else {
-            backingArray[baseOffset++] = (byte) ((value >>  0) & 0xff);
-            backingArray[baseOffset++] = (byte) ((value >>  8) & 0xff);
-            backingArray[baseOffset++] = (byte) ((value >> 16) & 0xff);
-            backingArray[baseOffset  ] = (byte) ((value >> 24) & 0xff);
-        }
-    }
-
-    private final void storeLong(int index, long value) {
-        int baseOffset = offset + index;
-        if (order == ByteOrder.BIG_ENDIAN) {
-            int i = (int) (value >> 32);
-            backingArray[baseOffset++] = (byte) ((i >> 24) & 0xff);
-            backingArray[baseOffset++] = (byte) ((i >> 16) & 0xff);
-            backingArray[baseOffset++] = (byte) ((i >>  8) & 0xff);
-            backingArray[baseOffset++] = (byte) ((i >>  0) & 0xff);
-            i = (int) value;
-            backingArray[baseOffset++] = (byte) ((i >> 24) & 0xff);
-            backingArray[baseOffset++] = (byte) ((i >> 16) & 0xff);
-            backingArray[baseOffset++] = (byte) ((i >>  8) & 0xff);
-            backingArray[baseOffset  ] = (byte) ((i >>  0) & 0xff);
-        } else {
-            int i = (int) value;
-            backingArray[baseOffset++] = (byte) ((i >>  0) & 0xff);
-            backingArray[baseOffset++] = (byte) ((i >>  8) & 0xff);
-            backingArray[baseOffset++] = (byte) ((i >> 16) & 0xff);
-            backingArray[baseOffset++] = (byte) ((i >> 24) & 0xff);
-            i = (int) (value >> 32);
-            backingArray[baseOffset++] = (byte) ((i >>  0) & 0xff);
-            backingArray[baseOffset++] = (byte) ((i >>  8) & 0xff);
-            backingArray[baseOffset++] = (byte) ((i >> 16) & 0xff);
-            backingArray[baseOffset  ] = (byte) ((i >> 24) & 0xff);
-        }
-    }
-
-    private final void storeShort(int index, short value) {
-        int baseOffset = offset + index;
-        if (order == ByteOrder.BIG_ENDIAN) {
-            backingArray[baseOffset++] = (byte) ((value >> 8) & 0xff);
-            backingArray[baseOffset  ] = (byte) ((value >> 0) & 0xff);
-        } else {
-            backingArray[baseOffset++] = (byte) ((value >> 0) & 0xff);
-            backingArray[baseOffset  ] = (byte) ((value >> 8) & 0xff);
-        }
-    }
-
     @Override
     public ByteBuffer slice() {
-        ReadWriteHeapByteBuffer slice = new ReadWriteHeapByteBuffer(backingArray, remaining(),
-                offset + position);
-        slice.order = order;
-        return slice;
+        return new ReadWriteHeapByteBuffer(backingArray, remaining(), offset + position);
     }
 }
diff --git a/luni/src/main/java/java/nio/ReadWriteIntArrayBuffer.java b/luni/src/main/java/java/nio/ReadWriteIntArrayBuffer.java
index 94657a4..72dffcb 100644
--- a/luni/src/main/java/java/nio/ReadWriteIntArrayBuffer.java
+++ b/luni/src/main/java/java/nio/ReadWriteIntArrayBuffer.java
@@ -31,8 +31,8 @@
 final class ReadWriteIntArrayBuffer extends IntArrayBuffer {
 
     static ReadWriteIntArrayBuffer copy(IntArrayBuffer other, int markOfOther) {
-        ReadWriteIntArrayBuffer buf = new ReadWriteIntArrayBuffer(other.capacity(),
-                other.backingArray, other.offset);
+        ReadWriteIntArrayBuffer buf =
+                new ReadWriteIntArrayBuffer(other.capacity(), other.backingArray, other.offset);
         buf.limit = other.limit;
         buf.position = other.position();
         buf.mark = markOfOther;
@@ -58,8 +58,7 @@
 
     @Override
     public IntBuffer compact() {
-        System.arraycopy(backingArray, position + offset, backingArray, offset,
-                remaining());
+        System.arraycopy(backingArray, position + offset, backingArray, offset, remaining());
         position = limit - position;
         limit = capacity;
         mark = UNSET_MARK;
diff --git a/luni/src/main/java/java/nio/ReadWriteLongArrayBuffer.java b/luni/src/main/java/java/nio/ReadWriteLongArrayBuffer.java
index d67ce00..e5c5aa3 100644
--- a/luni/src/main/java/java/nio/ReadWriteLongArrayBuffer.java
+++ b/luni/src/main/java/java/nio/ReadWriteLongArrayBuffer.java
@@ -31,8 +31,8 @@
 final class ReadWriteLongArrayBuffer extends LongArrayBuffer {
 
     static ReadWriteLongArrayBuffer copy(LongArrayBuffer other, int markOfOther) {
-        ReadWriteLongArrayBuffer buf = new ReadWriteLongArrayBuffer(other.capacity(),
-                other.backingArray, other.offset);
+        ReadWriteLongArrayBuffer buf =
+                new ReadWriteLongArrayBuffer(other.capacity(), other.backingArray, other.offset);
         buf.limit = other.limit;
         buf.position = other.position();
         buf.mark = markOfOther;
@@ -58,8 +58,7 @@
 
     @Override
     public LongBuffer compact() {
-        System.arraycopy(backingArray, position + offset, backingArray, offset,
-                remaining());
+        System.arraycopy(backingArray, position + offset, backingArray, offset, remaining());
         position = limit - position;
         limit = capacity;
         mark = UNSET_MARK;
diff --git a/luni/src/main/java/java/nio/ReadWriteShortArrayBuffer.java b/luni/src/main/java/java/nio/ReadWriteShortArrayBuffer.java
index d8213c2..727d8c2 100644
--- a/luni/src/main/java/java/nio/ReadWriteShortArrayBuffer.java
+++ b/luni/src/main/java/java/nio/ReadWriteShortArrayBuffer.java
@@ -32,8 +32,8 @@
 final class ReadWriteShortArrayBuffer extends ShortArrayBuffer {
 
     static ReadWriteShortArrayBuffer copy(ShortArrayBuffer other, int markOfOther) {
-        ReadWriteShortArrayBuffer buf = new ReadWriteShortArrayBuffer(other.capacity(),
-                other.backingArray, other.offset);
+        ReadWriteShortArrayBuffer buf =
+                new ReadWriteShortArrayBuffer(other.capacity(), other.backingArray, other.offset);
         buf.limit = other.limit;
         buf.position = other.position();
         buf.mark = markOfOther;
@@ -60,8 +60,7 @@
 
     @Override
     public ShortBuffer compact() {
-        System.arraycopy(backingArray, position + offset, backingArray, offset,
-                remaining());
+        System.arraycopy(backingArray, position + offset, backingArray, offset, remaining());
         position = limit - position;
         limit = capacity;
         mark = UNSET_MARK;
@@ -127,8 +126,7 @@
 
     @Override
     public ShortBuffer slice() {
-        return new ReadWriteShortArrayBuffer(remaining(), backingArray, offset
-                + position);
+        return new ReadWriteShortArrayBuffer(remaining(), backingArray, offset + position);
     }
 
 }
diff --git a/luni/src/main/java/java/nio/ShortToByteBufferAdapter.java b/luni/src/main/java/java/nio/ShortToByteBufferAdapter.java
index 50ac3e5..0f6e680 100644
--- a/luni/src/main/java/java/nio/ShortToByteBufferAdapter.java
+++ b/luni/src/main/java/java/nio/ShortToByteBufferAdapter.java
@@ -16,6 +16,8 @@
 
 package java.nio;
 
+import libcore.io.SizeOf;
+
 /**
  * This class wraps a byte buffer to be a short buffer.
  * <p>
@@ -30,14 +32,16 @@
  */
 final class ShortToByteBufferAdapter extends ShortBuffer {
 
-    static ShortBuffer wrap(ByteBuffer byteBuffer) {
-        return new ShortToByteBufferAdapter(byteBuffer.slice());
-    }
-
     private final ByteBuffer byteBuffer;
 
-    ShortToByteBufferAdapter(ByteBuffer byteBuffer) {
-        super(byteBuffer.capacity() / SIZEOF_SHORT);
+    static ShortBuffer asShortBuffer(ByteBuffer byteBuffer) {
+        ByteBuffer slice = byteBuffer.slice();
+        slice.order(byteBuffer.order());
+        return new ShortToByteBufferAdapter(slice);
+    }
+
+    private ShortToByteBufferAdapter(ByteBuffer byteBuffer) {
+        super(byteBuffer.capacity() / SizeOf.SHORT);
         this.byteBuffer = byteBuffer;
         this.byteBuffer.clear();
         this.effectiveDirectAddress = byteBuffer.effectiveDirectAddress;
@@ -57,8 +61,8 @@
         if (byteBuffer.isReadOnly()) {
             throw new ReadOnlyBufferException();
         }
-        byteBuffer.limit(limit * SIZEOF_SHORT);
-        byteBuffer.position(position * SIZEOF_SHORT);
+        byteBuffer.limit(limit * SizeOf.SHORT);
+        byteBuffer.position(position * SizeOf.SHORT);
         byteBuffer.compact();
         byteBuffer.clear();
         position = limit - position;
@@ -81,7 +85,7 @@
         if (position == limit) {
             throw new BufferUnderflowException();
         }
-        return byteBuffer.getShort(position++ * SIZEOF_SHORT);
+        return byteBuffer.getShort(position++ * SizeOf.SHORT);
     }
 
     @Override
@@ -89,13 +93,13 @@
         if (index < 0 || index >= limit) {
             throw new IndexOutOfBoundsException();
         }
-        return byteBuffer.getShort(index * SIZEOF_SHORT);
+        return byteBuffer.getShort(index * SizeOf.SHORT);
     }
 
     @Override
     public ShortBuffer get(short[] dst, int dstOffset, int shortCount) {
-        byteBuffer.limit(limit * SIZEOF_SHORT);
-        byteBuffer.position(position * SIZEOF_SHORT);
+        byteBuffer.limit(limit * SizeOf.SHORT);
+        byteBuffer.position(position * SizeOf.SHORT);
         if (byteBuffer instanceof DirectByteBuffer) {
             ((DirectByteBuffer) byteBuffer).get(dst, dstOffset, shortCount);
         } else {
@@ -140,7 +144,7 @@
         if (position == limit) {
             throw new BufferOverflowException();
         }
-        byteBuffer.putShort(position++ * SIZEOF_SHORT, c);
+        byteBuffer.putShort(position++ * SizeOf.SHORT, c);
         return this;
     }
 
@@ -149,14 +153,14 @@
         if (index < 0 || index >= limit) {
             throw new IndexOutOfBoundsException();
         }
-        byteBuffer.putShort(index * SIZEOF_SHORT, c);
+        byteBuffer.putShort(index * SizeOf.SHORT, c);
         return this;
     }
 
     @Override
     public ShortBuffer put(short[] src, int srcOffset, int shortCount) {
-        byteBuffer.limit(limit * SIZEOF_SHORT);
-        byteBuffer.position(position * SIZEOF_SHORT);
+        byteBuffer.limit(limit * SizeOf.SHORT);
+        byteBuffer.position(position * SizeOf.SHORT);
         if (byteBuffer instanceof ReadWriteDirectByteBuffer) {
             ((ReadWriteDirectByteBuffer) byteBuffer).put(src, srcOffset, shortCount);
         } else {
@@ -168,8 +172,8 @@
 
     @Override
     public ShortBuffer slice() {
-        byteBuffer.limit(limit * SIZEOF_SHORT);
-        byteBuffer.position(position * SIZEOF_SHORT);
+        byteBuffer.limit(limit * SizeOf.SHORT);
+        byteBuffer.position(position * SizeOf.SHORT);
         ShortBuffer result = new ShortToByteBufferAdapter(byteBuffer.slice());
         byteBuffer.clear();
         return result;
diff --git a/luni/src/main/java/java/nio/charset/Charset.java b/luni/src/main/java/java/nio/charset/Charset.java
index 3a4e40c..800d810 100644
--- a/luni/src/main/java/java/nio/charset/Charset.java
+++ b/luni/src/main/java/java/nio/charset/Charset.java
@@ -17,7 +17,6 @@
 
 package java.nio.charset;
 
-import com.ibm.icu4jni.charset.NativeConverter;
 import java.io.UnsupportedEncodingException;
 import java.nio.ByteBuffer;
 import java.nio.CharBuffer;
@@ -33,6 +32,7 @@
 import java.util.Set;
 import java.util.SortedMap;
 import java.util.TreeMap;
+import libcore.icu.NativeConverter;
 
 /**
  * A charset is a named mapping between Unicode characters and byte sequences. Every
diff --git a/luni/src/main/java/java/nio/charset/CharsetEncoder.java b/luni/src/main/java/java/nio/charset/CharsetEncoder.java
index ca56ae5..739b152 100644
--- a/luni/src/main/java/java/nio/charset/CharsetEncoder.java
+++ b/luni/src/main/java/java/nio/charset/CharsetEncoder.java
@@ -16,12 +16,12 @@
 
 package java.nio.charset;
 
-import com.ibm.icu4jni.charset.CharsetEncoderICU;
 import java.nio.BufferOverflowException;
 import java.nio.BufferUnderflowException;
 import java.nio.ByteBuffer;
 import java.nio.CharBuffer;
 import java.util.Arrays;
+import libcore.icu.CharsetEncoderICU;
 
 /**
  * Transforms a sequence of 16-bit Java characters to a byte sequence in some encoding.
diff --git a/luni/src/main/java/java/nio/charset/Charsets.java b/luni/src/main/java/java/nio/charset/Charsets.java
index 1e11bef..1c2425a 100644
--- a/luni/src/main/java/java/nio/charset/Charsets.java
+++ b/luni/src/main/java/java/nio/charset/Charsets.java
@@ -60,6 +60,22 @@
     public static native byte[] toUtf8Bytes(char[] chars, int offset, int length);
 
     /**
+     * Returns a new byte array containing the bytes corresponding to the given characters,
+     * encoded in UTF-16BE. All characters are representable in UTF-16BE.
+     */
+    public static byte[] toBigEndianUtf16Bytes(char[] chars, int offset, int length) {
+        byte[] result = new byte[length * 2];
+        int end = offset + length;
+        int resultIndex = 0;
+        for (int i = offset; i < end; ++i) {
+            char ch = chars[i];
+            result[resultIndex++] = (byte) (ch >> 8);
+            result[resultIndex++] = (byte) ch;
+        }
+        return result;
+    }
+
+    /**
      * Decodes the given US-ASCII bytes into the given char[]. Equivalent to but faster than:
      *
      * for (int i = 0; i < count; ++i) {
diff --git a/luni/src/main/java/java/nio/charset/ModifiedUtf8.java b/luni/src/main/java/java/nio/charset/ModifiedUtf8.java
index 7481ed7..f4233ef 100644
--- a/luni/src/main/java/java/nio/charset/ModifiedUtf8.java
+++ b/luni/src/main/java/java/nio/charset/ModifiedUtf8.java
@@ -18,6 +18,9 @@
 package java.nio.charset;
 
 import java.io.UTFDataFormatException;
+import java.nio.ByteOrder;
+import libcore.io.SizeOf;
+import org.apache.harmony.luni.platform.OSMemory;
 
 /**
  * @hide internal use only
@@ -60,6 +63,66 @@
         return new String(out, 0, s);
     }
 
+    /**
+     * Returns the number of bytes the modified UTF8 representation of 's' would take. Note
+     * that this is just the space for the bytes representing the characters, not the length
+     * which precedes those bytes, because different callers represent the length differently,
+     * as two, four, or even eight bytes. If {@code shortLength} is true, we'll throw an
+     * exception if the string is too long for its length to be represented by a short.
+     */
+    public static long countBytes(String s, boolean shortLength) throws UTFDataFormatException {
+        long result = 0;
+        final int length = s.length();
+        for (int i = 0; i < length; ++i) {
+            char ch = s.charAt(i);
+            if (ch != 0 && ch <= 127) { // U+0000 uses two bytes.
+                ++result;
+            } else if (ch <= 2047) {
+                result += 2;
+            } else {
+                result += 3;
+            }
+            if (shortLength && result > 65535) {
+                throw new UTFDataFormatException("String more than 65535 UTF bytes long");
+            }
+        }
+        return result;
+    }
+
+    /**
+     * Encodes the <i>modified UTF-8</i> bytes corresponding to string {@code s} into the
+     * byte array {@code dst}, starting at the given {@code offset}.
+     */
+    public static void encode(byte[] dst, int offset, String s) {
+        final int length = s.length();
+        for (int i = 0; i < length; i++) {
+            char ch = s.charAt(i);
+            if (ch != 0 && ch <= 127) { // U+0000 uses two bytes.
+                dst[offset++] = (byte) ch;
+            } else if (ch <= 2047) {
+                dst[offset++] = (byte) (0xc0 | (0x1f & (ch >> 6)));
+                dst[offset++] = (byte) (0x80 | (0x3f & ch));
+            } else {
+                dst[offset++] = (byte) (0xe0 | (0x0f & (ch >> 12)));
+                dst[offset++] = (byte) (0x80 | (0x3f & (ch >> 6)));
+                dst[offset++] = (byte) (0x80 | (0x3f & ch));
+            }
+        }
+    }
+
+    /**
+     * Returns an array containing the <i>modified UTF-8</i> form of {@code s}, using a
+     * big-endian 16-bit length. Throws UTFDataFormatException if {@code s} is too long
+     * for a two-byte length.
+     */
+    public static byte[] encode(String s) throws UTFDataFormatException {
+        int utfCount = (int) ModifiedUtf8.countBytes(s, true);
+        byte[] result = new byte[SizeOf.SHORT + utfCount];
+        OSMemory.pokeShort(result, 0, (short) utfCount, ByteOrder.BIG_ENDIAN);
+        ModifiedUtf8.encode(result, SizeOf.SHORT, s);
+        return result;
+    }
+
     private ModifiedUtf8() {
     }
 }
diff --git a/luni/src/main/java/java/security/KeyStore.java b/luni/src/main/java/java/security/KeyStore.java
index e24eed0..f6add00 100644
--- a/luni/src/main/java/java/security/KeyStore.java
+++ b/luni/src/main/java/java/security/KeyStore.java
@@ -32,6 +32,7 @@
 import javax.security.auth.DestroyFailedException;
 import javax.security.auth.Destroyable;
 import javax.security.auth.callback.CallbackHandler;
+import libcore.io.IoUtils;
 import org.apache.harmony.security.fortress.Engine;
 
 /**
@@ -1038,10 +1039,7 @@
                                             fis = new FileInputStream(fileForLoad);
                                             ks.load(fis, passwd);
                                         } finally {
-                                            // close file input stream
-                                            if( fis != null ) {
-                                                fis.close();
-                                            }
+                                            IoUtils.closeQuietly(fis);
                                         }
                                     } else {
                                         ks.load(new TmpLSParameter(
diff --git a/luni/src/main/java/java/sql/Timestamp.java b/luni/src/main/java/java/sql/Timestamp.java
index 23cbea5..463ea8b 100644
--- a/luni/src/main/java/java/sql/Timestamp.java
+++ b/luni/src/main/java/java/sql/Timestamp.java
@@ -469,7 +469,7 @@
             // Require the next character to be a "."
             if (s.charAt(position) != '.') {
                 throw new NumberFormatException("Bad input string format: expected '.' not '" +
-                        s.charAt(position) + "'");
+                        s.charAt(position) + "' in \"" + s + "\"");
             }
             // Get the length of the number string - need to account for the '.'
             int nanoLength = s.length() - position - 1;
diff --git a/luni/src/main/java/java/text/AttributedCharacterIterator.java b/luni/src/main/java/java/text/AttributedCharacterIterator.java
index b2533ec..2ab8e6a 100644
--- a/luni/src/main/java/java/text/AttributedCharacterIterator.java
+++ b/luni/src/main/java/java/text/AttributedCharacterIterator.java
@@ -19,6 +19,8 @@
 
 import java.io.InvalidObjectException;
 import java.io.Serializable;
+import java.lang.reflect.Field;
+import java.lang.reflect.Modifier;
 import java.util.Map;
 import java.util.Set;
 
@@ -119,20 +121,23 @@
          *             or if it is not a known {@code Attribute}.
          */
         protected Object readResolve() throws InvalidObjectException {
-            if (this.getClass() != Attribute.class) {
-                throw new InvalidObjectException("cannot resolve subclasses");
+            /*
+             * This class is used like Java enums, where all instances are
+             * defined as fields of their own class. To preserve identity
+             * equality, resolve to the canonical instance when deserialized.
+             */
+            try {
+                for (Field field : getClass().getFields()) {
+                    if (field.getType() == getClass() && Modifier.isStatic(field.getModifiers())) {
+                        Attribute candidate = (Attribute) field.get(null);
+                        if (name.equals(candidate.name)) {
+                            return candidate;
+                        }
+                    }
+                }
+            } catch (IllegalAccessException e) {
             }
-            String name = this.getName();
-            if (name.equals(INPUT_METHOD_SEGMENT.getName())) {
-                return INPUT_METHOD_SEGMENT;
-            }
-            if (name.equals(LANGUAGE.getName())) {
-                return LANGUAGE;
-            }
-            if (name.equals(READING.getName())) {
-                return READING;
-            }
-            throw new InvalidObjectException("Unknown attribute");
+            throw new InvalidObjectException("Failed to resolve " + this);
         }
 
         /**
diff --git a/luni/src/main/java/java/text/BreakIterator.java b/luni/src/main/java/java/text/BreakIterator.java
index 09fbc3b..ccc484c 100644
--- a/luni/src/main/java/java/text/BreakIterator.java
+++ b/luni/src/main/java/java/text/BreakIterator.java
@@ -17,9 +17,9 @@
 
 package java.text;
 
-import com.ibm.icu4jni.text.NativeBreakIterator;
-import com.ibm.icu4jni.util.ICU;
 import java.util.Locale;
+import libcore.icu.ICU;
+import libcore.icu.NativeBreakIterator;
 
 /**
  * Locates boundaries in text. This class defines a protocol for objects that
diff --git a/luni/src/main/java/java/text/CollationElementIterator.java b/luni/src/main/java/java/text/CollationElementIterator.java
index 0bdef23..5da3b65 100644
--- a/luni/src/main/java/java/text/CollationElementIterator.java
+++ b/luni/src/main/java/java/text/CollationElementIterator.java
@@ -17,6 +17,8 @@
 
 package java.text;
 
+import libcore.icu.CollationElementIteratorICU;
+
 /**
  * Created by a {@code RuleBasedCollator} to iterate through a string. The
  * result of each iteration is a 32-bit collation element that defines the
@@ -52,9 +54,9 @@
      */
     public static final int NULLORDER = -1;
 
-    private com.ibm.icu4jni.text.CollationElementIterator icuIterator;
+    private CollationElementIteratorICU icuIterator;
 
-    CollationElementIterator(com.ibm.icu4jni.text.CollationElementIterator iterator) {
+    CollationElementIterator(CollationElementIteratorICU iterator) {
         this.icuIterator = iterator;
     }
 
@@ -130,7 +132,7 @@
      * @return the element's 16 bit primary order.
      */
     public static final int primaryOrder(int order) {
-        return com.ibm.icu4jni.text.CollationElementIterator.primaryOrder(order);
+        return CollationElementIteratorICU.primaryOrder(order);
     }
 
     /**
@@ -155,8 +157,7 @@
      * @return the 8 bit secondary order of the element.
      */
     public static final short secondaryOrder(int order) {
-        return (short) com.ibm.icu4jni.text.CollationElementIterator
-                .secondaryOrder(order);
+        return (short) CollationElementIteratorICU.secondaryOrder(order);
     }
 
     /**
@@ -216,7 +217,6 @@
      * @return the 8 bit tertiary order of the element.
      */
     public static final short tertiaryOrder(int order) {
-        return (short) com.ibm.icu4jni.text.CollationElementIterator
-                .tertiaryOrder(order);
+        return (short) CollationElementIteratorICU.tertiaryOrder(order);
     }
 }
diff --git a/luni/src/main/java/java/text/Collator.java b/luni/src/main/java/java/text/Collator.java
index 827031a..689fcb7 100644
--- a/luni/src/main/java/java/text/Collator.java
+++ b/luni/src/main/java/java/text/Collator.java
@@ -17,9 +17,10 @@
 
 package java.text;
 
-import com.ibm.icu4jni.util.ICU;
 import java.util.Comparator;
 import java.util.Locale;
+import libcore.icu.ICU;
+import libcore.icu.RuleBasedCollatorICU;
 
 /**
  * Performs locale-sensitive string comparison. A concrete subclass,
@@ -144,21 +145,17 @@
      */
     public static final int IDENTICAL = 3;
 
-    // Wrapper class of ICU4JNI Collator
-    com.ibm.icu4jni.text.Collator icuColl;
+    RuleBasedCollatorICU icuColl;
 
-    Collator(com.ibm.icu4jni.text.Collator wrapper) {
-        this.icuColl = wrapper;
+    Collator(RuleBasedCollatorICU icuColl) {
+        this.icuColl = icuColl;
     }
 
     /**
      * Constructs a new {@code Collator} instance.
      */
     protected Collator() {
-        super();
-        // BEGIN android-added
-        icuColl = com.ibm.icu4jni.text.Collator.getInstance(Locale.getDefault());
-        // END android-added
+        icuColl = new RuleBasedCollatorICU(Locale.getDefault());
     }
 
     /**
@@ -172,7 +169,7 @@
     public Object clone() {
         try {
             Collator clone = (Collator) super.clone();
-            clone.icuColl = (com.ibm.icu4jni.text.Collator) this.icuColl.clone();
+            clone.icuColl = (RuleBasedCollatorICU) icuColl.clone();
             return clone;
         } catch (CloneNotSupportedException e) {
             throw new AssertionError(e); // android-changed
@@ -227,8 +224,7 @@
             return false;
         }
         Collator collator = (Collator) object;
-        return this.icuColl == null ? collator.icuColl == null : this.icuColl
-                .equals(collator.icuColl);
+        return icuColl == null ? collator.icuColl == null : icuColl.equals(collator.icuColl);
     }
 
     /**
@@ -273,7 +269,7 @@
      *         not supported.
      */
     public int getDecomposition() {
-        return decompositionMode_ICU_Java(this.icuColl.getDecomposition());
+        return decompositionMode_ICU_Java(icuColl.getDecomposition());
     }
 
     /**
@@ -292,7 +288,7 @@
         if (locale == null) {
             throw new NullPointerException();
         }
-        return new RuleBasedCollator(com.ibm.icu4jni.text.Collator.getInstance(locale));
+        return new RuleBasedCollator(new RuleBasedCollatorICU(locale));
     }
 
     /**
@@ -302,7 +298,7 @@
      *         IDENTICAL.
      */
     public int getStrength() {
-        return strength_ICU_Java(this.icuColl.getStrength());
+        return strength_ICU_Java(icuColl.getStrength());
     }
 
     @Override
@@ -320,7 +316,7 @@
      *            {@code FULL_DECOMPOSITION}.
      */
     public void setDecomposition(int value) {
-        this.icuColl.setDecomposition(decompositionMode_Java_ICU(value));
+        icuColl.setDecomposition(decompositionMode_Java_ICU(value));
     }
 
     /**
@@ -333,15 +329,15 @@
      *            if the provided strength value is not valid.
      */
     public void setStrength(int value) {
-        this.icuColl.setStrength(strength_Java_ICU(value));
+        icuColl.setStrength(strength_Java_ICU(value));
     }
 
     private int decompositionMode_Java_ICU(int mode) {
         switch (mode) {
         case Collator.CANONICAL_DECOMPOSITION:
-            return com.ibm.icu4jni.text.Collator.CANONICAL_DECOMPOSITION;
+            return RuleBasedCollatorICU.VALUE_ON;
         case Collator.NO_DECOMPOSITION:
-            return com.ibm.icu4jni.text.Collator.NO_DECOMPOSITION;
+            return RuleBasedCollatorICU.VALUE_OFF;
         }
         throw new IllegalArgumentException();
     }
@@ -349,12 +345,12 @@
     private int decompositionMode_ICU_Java(int mode) {
         int javaMode = mode;
         switch (mode) {
-            case com.ibm.icu4jni.text.Collator.NO_DECOMPOSITION:
-                javaMode = Collator.NO_DECOMPOSITION;
-                break;
-            case com.ibm.icu4jni.text.Collator.CANONICAL_DECOMPOSITION:
-                javaMode = Collator.CANONICAL_DECOMPOSITION;
-                break;
+        case RuleBasedCollatorICU.VALUE_OFF:
+            javaMode = Collator.NO_DECOMPOSITION;
+            break;
+        case RuleBasedCollatorICU.VALUE_ON:
+            javaMode = Collator.CANONICAL_DECOMPOSITION;
+            break;
         }
         return javaMode;
     }
@@ -362,13 +358,13 @@
     private int strength_Java_ICU(int value) {
         switch (value) {
         case Collator.PRIMARY:
-            return com.ibm.icu4jni.text.Collator.PRIMARY;
+            return RuleBasedCollatorICU.VALUE_PRIMARY;
         case Collator.SECONDARY:
-            return com.ibm.icu4jni.text.Collator.SECONDARY;
+            return RuleBasedCollatorICU.VALUE_SECONDARY;
         case Collator.TERTIARY:
-            return com.ibm.icu4jni.text.Collator.TERTIARY;
+            return RuleBasedCollatorICU.VALUE_TERTIARY;
         case Collator.IDENTICAL:
-            return com.ibm.icu4jni.text.Collator.IDENTICAL;
+            return RuleBasedCollatorICU.VALUE_IDENTICAL;
         }
         throw new IllegalArgumentException();
     }
@@ -376,18 +372,18 @@
     private int strength_ICU_Java(int value) {
         int javaValue = value;
         switch (value) {
-            case com.ibm.icu4jni.text.Collator.PRIMARY:
-                javaValue = Collator.PRIMARY;
-                break;
-            case com.ibm.icu4jni.text.Collator.SECONDARY:
-                javaValue = Collator.SECONDARY;
-                break;
-            case com.ibm.icu4jni.text.Collator.TERTIARY:
-                javaValue = Collator.TERTIARY;
-                break;
-            case com.ibm.icu4jni.text.Collator.IDENTICAL:
-                javaValue = Collator.IDENTICAL;
-                break;
+        case RuleBasedCollatorICU.VALUE_PRIMARY:
+            javaValue = Collator.PRIMARY;
+            break;
+        case RuleBasedCollatorICU.VALUE_SECONDARY:
+            javaValue = Collator.SECONDARY;
+            break;
+        case RuleBasedCollatorICU.VALUE_TERTIARY:
+            javaValue = Collator.TERTIARY;
+            break;
+        case RuleBasedCollatorICU.VALUE_IDENTICAL:
+            javaValue = Collator.IDENTICAL;
+            break;
         }
         return javaValue;
     }
diff --git a/luni/src/main/java/java/text/DateFormat.java b/luni/src/main/java/java/text/DateFormat.java
index 45ee0c7..53480e6 100644
--- a/luni/src/main/java/java/text/DateFormat.java
+++ b/luni/src/main/java/java/text/DateFormat.java
@@ -17,14 +17,14 @@
 
 package java.text;
 
-import com.ibm.icu4jni.util.ICU;
-import com.ibm.icu4jni.util.LocaleData;
 import java.io.InvalidObjectException;
 import java.util.Calendar;
 import java.util.Date;
 import java.util.Hashtable;
 import java.util.Locale;
 import java.util.TimeZone;
+import libcore.icu.ICU;
+import libcore.icu.LocaleData;
 
 /**
  * An abstract class for date/time formatting subclasses which formats and
@@ -883,43 +883,6 @@
 
             return table.get(Integer.valueOf(calendarField));
         }
-
-        /**
-         * Resolves instances that are deserialized to the constant
-         * {@code DateFormat.Field} values.
-         *
-         * @return the resolved field object.
-         * @throws InvalidObjectException
-         *             if an error occurs while resolving the field object.
-         */
-        @Override
-        protected Object readResolve() throws InvalidObjectException {
-            if (this.getClass() != Field.class) {
-                throw new InvalidObjectException("cannot resolve subclasses");
-            }
-            if (calendarField != -1) {
-                try {
-                    Field result = ofCalendarField(calendarField);
-
-                    if (result != null && this.getName().equals(result.getName())) {
-                        return result;
-                    }
-                } catch (IllegalArgumentException e) {
-                    throw new InvalidObjectException("Unknown attribute");
-                }
-            } else {
-                if (this.equals(TIME_ZONE)) {
-                    return TIME_ZONE;
-                }
-                if (this.equals(HOUR1)) {
-                    return HOUR1;
-                }
-                if (this.equals(HOUR_OF_DAY1)) {
-                    return HOUR_OF_DAY1;
-                }
-            }
-            throw new InvalidObjectException("Unknown attribute");
-        }
     }
 
     private static void checkDateStyle(int style) {
diff --git a/luni/src/main/java/java/text/DateFormatSymbols.java b/luni/src/main/java/java/text/DateFormatSymbols.java
index 07544c7..73c818e 100644
--- a/luni/src/main/java/java/text/DateFormatSymbols.java
+++ b/luni/src/main/java/java/text/DateFormatSymbols.java
@@ -17,14 +17,14 @@
 
 package java.text;
 
-import com.ibm.icu4jni.util.ICU;
-import com.ibm.icu4jni.util.LocaleData;
 import java.io.IOException;
 import java.io.ObjectInputStream;
 import java.io.ObjectOutputStream;
 import java.io.Serializable;
 import java.util.Arrays;
 import java.util.Locale;
+import libcore.icu.ICU;
+import libcore.icu.LocaleData;
 import libcore.icu.TimeZones;
 
 /**
diff --git a/luni/src/main/java/java/text/DecimalFormat.java b/luni/src/main/java/java/text/DecimalFormat.java
index 00adba3..65f96d8 100644
--- a/luni/src/main/java/java/text/DecimalFormat.java
+++ b/luni/src/main/java/java/text/DecimalFormat.java
@@ -17,8 +17,6 @@
 
 package java.text;
 
-import com.ibm.icu4jni.text.NativeDecimalFormat;
-import com.ibm.icu4jni.util.LocaleData;
 import java.io.IOException;
 import java.io.ObjectInputStream;
 import java.io.ObjectOutputStream;
@@ -28,6 +26,8 @@
 import java.math.RoundingMode;
 import java.util.Currency;
 import java.util.Locale;
+import libcore.icu.LocaleData;
+import libcore.icu.NativeDecimalFormat;
 
 /**
  * A concrete subclass of {@link NumberFormat} that formats decimal numbers. It
diff --git a/luni/src/main/java/java/text/DecimalFormatSymbols.java b/luni/src/main/java/java/text/DecimalFormatSymbols.java
index bc761e4..e8c1c0c 100644
--- a/luni/src/main/java/java/text/DecimalFormatSymbols.java
+++ b/luni/src/main/java/java/text/DecimalFormatSymbols.java
@@ -17,8 +17,6 @@
 
 package java.text;
 
-import com.ibm.icu4jni.util.ICU;
-import com.ibm.icu4jni.util.LocaleData;
 import java.io.IOException;
 import java.io.ObjectInputStream;
 import java.io.ObjectOutputStream;
@@ -26,6 +24,8 @@
 import java.io.Serializable;
 import java.util.Currency;
 import java.util.Locale;
+import libcore.icu.ICU;
+import libcore.icu.LocaleData;
 
 /**
  * Encapsulates the set of symbols (such as the decimal separator, the grouping
diff --git a/luni/src/main/java/java/text/MessageFormat.java b/luni/src/main/java/java/text/MessageFormat.java
index 824ddb8..d740437 100644
--- a/luni/src/main/java/java/text/MessageFormat.java
+++ b/luni/src/main/java/java/text/MessageFormat.java
@@ -1322,22 +1322,5 @@
         protected Field(String fieldName) {
             super(fieldName);
         }
-
-        /**
-         * Resolves instances that are deserialized to the constant
-         * {@code MessageFormat.Field} values.
-         *
-         * @return the resolved field object.
-         * @throws InvalidObjectException
-         *             if an error occurs while resolving the field object.
-         */
-        @Override
-        protected Object readResolve() throws InvalidObjectException {
-            String name = this.getName();
-            if (Objects.equal(name, ARGUMENT.getName())) {
-                return ARGUMENT;
-            }
-            throw new InvalidObjectException("Not a valid MessageFormat.Field, subclass should override readResolve()");
-        }
     }
 }
diff --git a/luni/src/main/java/java/text/NumberFormat.java b/luni/src/main/java/java/text/NumberFormat.java
index a808169..dd38a65 100644
--- a/luni/src/main/java/java/text/NumberFormat.java
+++ b/luni/src/main/java/java/text/NumberFormat.java
@@ -17,8 +17,6 @@
 
 package java.text;
 
-import com.ibm.icu4jni.util.ICU;
-import com.ibm.icu4jni.util.LocaleData;
 import java.io.IOException;
 import java.io.InvalidObjectException;
 import java.io.ObjectInputStream;
@@ -28,6 +26,8 @@
 import java.math.RoundingMode;
 import java.util.Currency;
 import java.util.Locale;
+import libcore.icu.ICU;
+import libcore.icu.LocaleData;
 
 /**
  * The abstract base class for all number formats. This class provides the
@@ -821,52 +821,6 @@
         protected Field(String fieldName) {
             super(fieldName);
         }
-
-        /**
-         * Resolves instances that are deserialized to the constant
-         * {@code NumberFormat.Field} values.
-         *
-         * @return the resolved field object.
-         * @throws InvalidObjectException
-         *             if an error occurs while resolving the field object.
-         */
-        @Override
-        protected Object readResolve() throws InvalidObjectException {
-            if (this.equals(INTEGER)) {
-                return INTEGER;
-            }
-            if (this.equals(FRACTION)) {
-                return FRACTION;
-            }
-            if (this.equals(EXPONENT)) {
-                return EXPONENT;
-            }
-            if (this.equals(EXPONENT_SIGN)) {
-                return EXPONENT_SIGN;
-            }
-            if (this.equals(EXPONENT_SYMBOL)) {
-                return EXPONENT_SYMBOL;
-            }
-            if (this.equals(CURRENCY)) {
-                return CURRENCY;
-            }
-            if (this.equals(DECIMAL_SEPARATOR)) {
-                return DECIMAL_SEPARATOR;
-            }
-            if (this.equals(GROUPING_SEPARATOR)) {
-                return GROUPING_SEPARATOR;
-            }
-            if (this.equals(PERCENT)) {
-                return PERCENT;
-            }
-            if (this.equals(PERMILLE)) {
-                return PERMILLE;
-            }
-            if (this.equals(SIGN)) {
-                return SIGN;
-            }
-            throw new InvalidObjectException("Unknown attribute");
-        }
     }
 
     /**
diff --git a/luni/src/main/java/java/text/RuleBasedBreakIterator.java b/luni/src/main/java/java/text/RuleBasedBreakIterator.java
index 82ff7a4..15b5b12 100644
--- a/luni/src/main/java/java/text/RuleBasedBreakIterator.java
+++ b/luni/src/main/java/java/text/RuleBasedBreakIterator.java
@@ -17,10 +17,10 @@
 
 package java.text;
 
-import com.ibm.icu4jni.text.NativeBreakIterator;
+import libcore.icu.NativeBreakIterator;
 
 /*
- * Default implementation of BreakIterator. Wraps com.ibm.icu4jni.text.NativeBreakIterator.
+ * Default implementation of BreakIterator. Wraps libcore.icu.NativeBreakIterator.
  * We need this because BreakIterator.isBoundary and BreakIterator.preceding are non-abstract,
  * and we don't have Java implementations of those methods (other than the current ones, which
  * forward to the wrapped NativeBreakIterator).
diff --git a/luni/src/main/java/java/text/RuleBasedCollator.java b/luni/src/main/java/java/text/RuleBasedCollator.java
index 9e638c9..f6a19f3 100644
--- a/luni/src/main/java/java/text/RuleBasedCollator.java
+++ b/luni/src/main/java/java/text/RuleBasedCollator.java
@@ -17,6 +17,8 @@
 
 package java.text;
 
+import libcore.icu.RuleBasedCollatorICU;
+
 /**
  * A concrete implementation class for {@code Collation}.
  * <p>
@@ -257,8 +259,7 @@
  * </blockquote>
  */
 public class RuleBasedCollator extends Collator {
-
-    RuleBasedCollator(com.ibm.icu4jni.text.Collator wrapper) {
+    RuleBasedCollator(RuleBasedCollatorICU wrapper) {
         super(wrapper);
     }
 
@@ -289,8 +290,7 @@
             throw new ParseException("empty rules", 0);
         }
         try {
-            this.icuColl = new com.ibm.icu4jni.text.RuleBasedCollator(rules);
-            this.icuColl.setDecomposition(com.ibm.icu4jni.text.Collator.CANONICAL_DECOMPOSITION);
+            icuColl = new RuleBasedCollatorICU(rules);
         } catch (Exception e) {
             if (e instanceof ParseException) {
                 throw (ParseException) e;
@@ -316,9 +316,7 @@
         if (source == null) {
             throw new NullPointerException();
         }
-        return new CollationElementIterator(
-                ((com.ibm.icu4jni.text.RuleBasedCollator) this.icuColl)
-                        .getCollationElementIterator(source));
+        return new CollationElementIterator(((RuleBasedCollatorICU) icuColl).getCollationElementIterator(source));
     }
 
     /**
@@ -332,9 +330,7 @@
         if (source == null) {
             throw new NullPointerException();
         }
-        return new CollationElementIterator(
-                ((com.ibm.icu4jni.text.RuleBasedCollator) this.icuColl)
-                        .getCollationElementIterator(source));
+        return new CollationElementIterator(((RuleBasedCollatorICU) icuColl).getCollationElementIterator(source));
     }
 
     /**
@@ -350,7 +346,7 @@
      * @return the collation rules.
      */
     public String getRules() {
-        return ((com.ibm.icu4jni.text.RuleBasedCollator) this.icuColl).getRules();
+        return ((RuleBasedCollatorICU) icuColl).getRules();
     }
 
     /**
@@ -392,7 +388,7 @@
         if (source == null || target == null) {
             throw new NullPointerException();
         }
-        return this.icuColl.compare(source, target);
+        return icuColl.compare(source, target);
     }
 
     /**
@@ -409,7 +405,7 @@
 
     @Override
     public int hashCode() {
-        return ((com.ibm.icu4jni.text.RuleBasedCollator) this.icuColl).getRules().hashCode();
+        return ((RuleBasedCollatorICU) icuColl).getRules().hashCode();
     }
 
     /**
diff --git a/luni/src/main/java/java/text/SimpleDateFormat.java b/luni/src/main/java/java/text/SimpleDateFormat.java
index e1ff700..6b386f0 100644
--- a/luni/src/main/java/java/text/SimpleDateFormat.java
+++ b/luni/src/main/java/java/text/SimpleDateFormat.java
@@ -17,7 +17,6 @@
 
 package java.text;
 
-import com.ibm.icu4jni.util.LocaleData;
 import java.io.IOException;
 import java.io.ObjectInputStream;
 import java.io.ObjectOutputStream;
@@ -29,6 +28,7 @@
 import java.util.SimpleTimeZone;
 import java.util.TimeZone;
 import java.util.Vector;
+import libcore.icu.LocaleData;
 import libcore.icu.TimeZones;
 
 /**
diff --git a/luni/src/main/java/java/util/Calendar.java b/luni/src/main/java/java/util/Calendar.java
index 780f647..6fcc7a9 100644
--- a/luni/src/main/java/java/util/Calendar.java
+++ b/luni/src/main/java/java/util/Calendar.java
@@ -17,14 +17,14 @@
 
 package java.util;
 
-import com.ibm.icu4jni.util.ICU;
-import com.ibm.icu4jni.util.LocaleData;
 import java.io.IOException;
 import java.io.ObjectInputStream;
 import java.io.ObjectOutputStream;
 import java.io.ObjectStreamField;
 import java.io.Serializable;
 import java.text.DateFormatSymbols;
+import libcore.icu.ICU;
+import libcore.icu.LocaleData;
 
 /**
  * {@code Calendar} is an abstract base class for converting between a
diff --git a/luni/src/main/java/java/util/Currency.java b/luni/src/main/java/java/util/Currency.java
index 84bf833..8ea8a96 100644
--- a/luni/src/main/java/java/util/Currency.java
+++ b/luni/src/main/java/java/util/Currency.java
@@ -17,11 +17,11 @@
 
 package java.util;
 
-import com.ibm.icu4jni.util.ICU;
-import com.ibm.icu4jni.util.LocaleData;
 import java.io.Serializable;
 import java.security.AccessController;
 import java.security.PrivilegedAction;
+import libcore.icu.ICU;
+import libcore.icu.LocaleData;
 
 /**
  * This class represents a currency as identified in the ISO 4217 currency
diff --git a/luni/src/main/java/java/util/Formatter.java b/luni/src/main/java/java/util/Formatter.java
index 87b5036..b3d1578 100644
--- a/luni/src/main/java/java/util/Formatter.java
+++ b/luni/src/main/java/java/util/Formatter.java
@@ -15,8 +15,6 @@
  */
 package java.util;
 
-import com.ibm.icu4jni.text.NativeDecimalFormat;
-import com.ibm.icu4jni.util.LocaleData;
 import java.io.BufferedWriter;
 import java.io.Closeable;
 import java.io.File;
@@ -34,6 +32,9 @@
 import java.nio.charset.Charset;
 import java.security.AccessController;
 import java.security.PrivilegedAction;
+import libcore.icu.LocaleData;
+import libcore.icu.NativeDecimalFormat;
+import libcore.io.IoUtils;
 
 /**
  * Formats arguments according to a format string (like {@code printf} in C).
@@ -828,10 +829,10 @@
             fout = new FileOutputStream(file);
             out = new BufferedWriter(new OutputStreamWriter(fout, csn));
         } catch (RuntimeException e) {
-            closeOutputStream(fout);
+            IoUtils.closeQuietly(fout);
             throw e;
         } catch (UnsupportedEncodingException e) {
-            closeOutputStream(fout);
+            IoUtils.closeQuietly(fout);
             throw e;
         }
 
@@ -1138,17 +1139,6 @@
         return args[index];
     }
 
-    private static void closeOutputStream(OutputStream os) {
-        if (os == null) {
-            return;
-        }
-        try {
-            os.close();
-        } catch (IOException e) {
-            // silently
-        }
-    }
-
     /*
      * Complete details of a single format specifier parsed from a format string.
      */
diff --git a/luni/src/main/java/java/util/Locale.java b/luni/src/main/java/java/util/Locale.java
index fb8a969..2c2f930 100644
--- a/luni/src/main/java/java/util/Locale.java
+++ b/luni/src/main/java/java/util/Locale.java
@@ -17,13 +17,13 @@
 
 package java.util;
 
-import com.ibm.icu4jni.util.ICU;
 import java.io.IOException;
 import java.io.ObjectInputStream;
 import java.io.ObjectOutputStream;
 import java.io.ObjectStreamField;
 import java.io.Serializable;
 import java.security.AccessController;
+import libcore.icu.ICU;
 import org.apache.harmony.luni.util.PriviAction;
 import org.apache.harmony.luni.util.Util;
 
diff --git a/luni/src/main/java/java/util/ResourceBundle.java b/luni/src/main/java/java/util/ResourceBundle.java
index be7c06d..0f19df2 100644
--- a/luni/src/main/java/java/util/ResourceBundle.java
+++ b/luni/src/main/java/java/util/ResourceBundle.java
@@ -17,7 +17,6 @@
 
 package java.util;
 
-import com.ibm.icu4jni.util.ICU;
 import dalvik.system.VMStack;
 import java.io.File;
 import java.io.IOException;
@@ -27,6 +26,7 @@
 import java.net.URLConnection;
 import java.security.AccessController;
 import java.security.PrivilegedAction;
+import libcore.icu.ICU;
 
 /**
  * {@code ResourceBundle} is an abstract class which is the superclass of classes which
diff --git a/luni/src/main/java/java/util/Scanner.java b/luni/src/main/java/java/util/Scanner.java
index b21810b..3d5ac3a 100644
--- a/luni/src/main/java/java/util/Scanner.java
+++ b/luni/src/main/java/java/util/Scanner.java
@@ -35,6 +35,7 @@
 import java.util.regex.MatchResult;
 import java.util.regex.Matcher;
 import java.util.regex.Pattern;
+import libcore.io.IoUtils;
 
 /**
  * A parser that parses a text string of primitive types and strings with the
@@ -191,11 +192,7 @@
         try {
             input = new InputStreamReader(fis, charsetName);
         } catch (UnsupportedEncodingException e) {
-            try {
-                fis.close();
-            } catch (IOException ioException) {
-                // ignore
-            }
+            IoUtils.closeQuietly(fis);
             throw new IllegalArgumentException(e.getMessage());
         }
         initialization();
diff --git a/luni/src/main/java/java/util/ServiceLoader.java b/luni/src/main/java/java/util/ServiceLoader.java
index 1608c1d..8fc232f 100644
--- a/luni/src/main/java/java/util/ServiceLoader.java
+++ b/luni/src/main/java/java/util/ServiceLoader.java
@@ -22,6 +22,7 @@
 import java.net.URL;
 import java.security.AccessController;
 import java.security.PrivilegedAction;
+import libcore.io.IoUtils;
 
 /**
  * A service-provider loader.
@@ -249,12 +250,7 @@
                 } catch (Exception e) {
                     throw new ServiceConfigurationError("Couldn't read " + url, e);
                 } finally {
-                    try {
-                        if (reader != null) {
-                            reader.close();
-                        }
-                    } catch (IOException ex) {
-                    }
+                    IoUtils.closeQuietly(reader);
                 }
             }
         }
diff --git a/luni/src/main/java/java/util/SimpleTimeZone.java b/luni/src/main/java/java/util/SimpleTimeZone.java
index fa2e9e1..a57ab9a 100644
--- a/luni/src/main/java/java/util/SimpleTimeZone.java
+++ b/luni/src/main/java/java/util/SimpleTimeZone.java
@@ -15,12 +15,6 @@
  *  limitations under the License.
  */
 
-// BEGIN android-note
-// This implementation is based on an old version of Apache Harmony. The current
-// Harmony uses ICU4J, which makes it much simpler. We should consider updating
-// this implementation to leverage ICU4JNI.
-// END android-note
-
 package java.util;
 
 import java.io.IOException;
@@ -46,16 +40,6 @@
 
     private static final long serialVersionUID = -403250971215465050L;
 
-    // BEGIN android-removed
-    // private static com.ibm.icu.util.TimeZone getICUTimeZone(final String name){
-    //     return AccessController.doPrivileged(new PrivilegedAction<com.ibm.icu.util.TimeZone>(){
-    //         public com.ibm.icu.util.TimeZone run() {
-    //             return com.ibm.icu.util.TimeZone.getTimeZone(name);
-    //         }
-    //     });
-    // }
-    // END android-removed
-
     private int rawOffset;
 
     private int startYear, startMonth, startDay, startDayOfWeek, startTime;
diff --git a/luni/src/main/java/java/util/jar/JarFile.java b/luni/src/main/java/java/util/jar/JarFile.java
index 9f3eda2..0f42d78 100644
--- a/luni/src/main/java/java/util/jar/JarFile.java
+++ b/luni/src/main/java/java/util/jar/JarFile.java
@@ -26,6 +26,7 @@
 import java.util.List;
 import java.util.zip.ZipEntry;
 import java.util.zip.ZipFile;
+import libcore.base.Streams;
 import org.apache.harmony.archive.util.Util;
 import org.apache.harmony.luni.util.InputStreamHelper;
 
@@ -136,19 +137,8 @@
         }
 
         @Override
-        public long skip(long nbytes) throws IOException {
-            long cnt = 0, rem = 0;
-            byte[] buf = new byte[(int)Math.min(nbytes, 2048L)];
-            while (cnt < nbytes) {
-                int x = read(buf, 0,
-                        (rem = nbytes - cnt) > buf.length ? buf.length
-                                : (int) rem);
-                if (x == -1) {
-                    return cnt;
-                }
-                cnt += x;
-            }
-            return cnt;
+        public long skip(long byteCount) throws IOException {
+            return Streams.skipByReading(this, byteCount);
         }
     }
 
diff --git a/luni/src/main/java/java/util/logging/FileHandler.java b/luni/src/main/java/java/util/logging/FileHandler.java
index bc12b8d..6847d8a 100644
--- a/luni/src/main/java/java/util/logging/FileHandler.java
+++ b/luni/src/main/java/java/util/logging/FileHandler.java
@@ -28,6 +28,7 @@
 import java.security.AccessController;
 import java.security.PrivilegedAction;
 import java.util.Hashtable;
+import libcore.io.IoUtils;
 
 /**
  * A {@code FileHandler} writes logging records into a specified file or a
@@ -202,12 +203,8 @@
                  * undead cycle
                  */
                 lock = channel.tryLock();
-                if (null == lock) {
-                    try {
-                        fileStream.close();
-                    } catch (Exception e) {
-                        // ignore
-                    }
+                if (lock == null) {
+                    IoUtils.closeQuietly(fileStream);
                     continue;
                 }
                 allLocks.put(fileName, lock);
diff --git a/luni/src/main/java/java/util/logging/LogManager.java b/luni/src/main/java/java/util/logging/LogManager.java
index d4c96fb..d561f77 100644
--- a/luni/src/main/java/java/util/logging/LogManager.java
+++ b/luni/src/main/java/java/util/logging/LogManager.java
@@ -37,6 +37,7 @@
 import java.util.Hashtable;
 import java.util.Properties;
 import java.util.StringTokenizer;
+import libcore.io.IoUtils;
 
 /**
  * {@code LogManager} is used to maintain configuration properties of the
@@ -368,12 +369,11 @@
     public void readConfiguration() throws IOException {
         // check config class
         String configClassName = System.getProperty("java.util.logging.config.class");
-        if (null == configClassName
-                || null == getInstanceByClass(configClassName)) {
+        if (configClassName == null || getInstanceByClass(configClassName) == null) {
             // if config class failed, check config file
             String configFile = System.getProperty("java.util.logging.config.file");
 
-            if (null == configFile) {
+            if (configFile == null) {
                 // if cannot find configFile, use default logging.properties
                 configFile = System.getProperty("java.home") + File.separator + "lib" +
                         File.separator + "logging.properties";
@@ -381,27 +381,18 @@
 
             InputStream input = null;
             try {
-                // BEGIN android-removed
-                // input = new BufferedInputStream(new FileInputStream(configFile));
-                // END android-removed
-
-                // BEGIN android-added
                 try {
-                    input = new BufferedInputStream(new FileInputStream(configFile));
-                } catch (Exception ex) {
-                    // consult fixed resource as a last resort
-                    input = new BufferedInputStream(
-                            getClass().getResourceAsStream("logging.properties"));
-                }
-                // END android-added
-                readConfiguration(input);
-            } finally {
-                if (input != null) {
-                    try {
-                        input.close();
-                    } catch (Exception e) {// ignore
+                    input = new FileInputStream(configFile);
+                } catch (IOException exception) {
+                    // fall back to using the built-in logging.properties file
+                    input = LogManager.class.getResourceAsStream("logging.properties");
+                    if (input == null) {
+                        throw exception;
                     }
                 }
+                readConfiguration(new BufferedInputStream(input));
+            } finally {
+                IoUtils.closeQuietly(input);
             }
         }
     }
diff --git a/luni/src/main/java/java/util/logging/SimpleFormatter.java b/luni/src/main/java/java/util/logging/SimpleFormatter.java
index d93742c..f5e7996 100644
--- a/luni/src/main/java/java/util/logging/SimpleFormatter.java
+++ b/luni/src/main/java/java/util/logging/SimpleFormatter.java
@@ -21,6 +21,7 @@
 import java.io.StringWriter;
 import java.text.MessageFormat;
 import java.util.Date;
+import libcore.io.IoUtils;
 
 /**
  * {@code SimpleFormatter} can be used to print a summary of the information
@@ -62,13 +63,7 @@
                 t.printStackTrace(pw);
                 sb.append(sw.toString());
             } finally {
-                if (pw != null) {
-                    try {
-                        pw.close();
-                    } catch (Exception e) {
-                        // ignore
-                    }
-                }
+                IoUtils.closeQuietly(pw);
             }
         }
         return sb.toString();
diff --git a/luni/src/main/java/java/util/prefs/XMLParser.java b/luni/src/main/java/java/util/prefs/XMLParser.java
index 1a108fc..ed1fe0d 100644
--- a/luni/src/main/java/java/util/prefs/XMLParser.java
+++ b/luni/src/main/java/java/util/prefs/XMLParser.java
@@ -26,7 +26,6 @@
 import java.io.OutputStream;
 import java.io.OutputStreamWriter;
 import java.io.StringReader;
-import java.io.Writer;
 import java.nio.channels.FileChannel;
 import java.nio.channels.FileLock;
 import java.security.AccessController;
@@ -40,6 +39,7 @@
 import javax.xml.parsers.DocumentBuilderFactory;
 import javax.xml.parsers.FactoryConfigurationError;
 import javax.xml.parsers.ParserConfigurationException;
+import libcore.io.IoUtils;
 import org.w3c.dom.Document;
 import org.w3c.dom.Element;
 import org.w3c.dom.Node;
@@ -509,7 +509,7 @@
             } catch (SAXException e) {
             } finally {
                 releaseQuietly(lock);
-                closeQuietly(in);
+                IoUtils.closeQuietly(in);
             }
         } else {
             file.delete();
@@ -558,7 +558,7 @@
             out.flush();
         } finally {
             releaseQuietly(lock);
-            closeQuietly(out);
+            IoUtils.closeQuietly(out);
         }
     }
 
@@ -570,22 +570,4 @@
             lock.release();
         } catch (IOException e) {}
     }
-
-    private static void closeQuietly(Writer out) {
-        if (out == null) {
-            return;
-        }
-        try {
-            out.close();
-        } catch (IOException e) {}
-    }
-
-    private static void closeQuietly(InputStream in) {
-        if (in == null) {
-            return;
-        }
-        try {
-            in.close();
-        } catch (IOException e) {}
-    }
 }
diff --git a/luni/src/main/java/java/util/zip/CheckedInputStream.java b/luni/src/main/java/java/util/zip/CheckedInputStream.java
index 296ddd7..f2f3407 100644
--- a/luni/src/main/java/java/util/zip/CheckedInputStream.java
+++ b/luni/src/main/java/java/util/zip/CheckedInputStream.java
@@ -19,6 +19,7 @@
 
 import java.io.IOException;
 import java.io.InputStream;
+import libcore.base.Streams;
 
 /**
  * The {@code CheckedInputStream} class is used to maintain a checksum at the
@@ -102,32 +103,15 @@
     }
 
     /**
-     * Skip up to n bytes of data on the underlying input stream. Any skipped
-     * bytes are added to the running checksum value.
+     * Skip up to {@code byteCount} bytes of data on the underlying input
+     * stream. Any skipped bytes are added to the running checksum value.
      *
-     * @param nbytes
-     *            the number of bytes to skip.
-     * @throws IOException
-     *             if this stream is closed or another I/O error occurs.
+     * @param byteCount the number of bytes to skip.
+     * @throws IOException if this stream is closed or another I/O error occurs.
      * @return the number of bytes skipped.
      */
     @Override
-    public long skip(long nbytes) throws IOException {
-        if (nbytes < 1) {
-            return 0;
-        }
-        long skipped = 0;
-        byte[] b = new byte[(int)Math.min(nbytes, 2048L)];
-        int x, v;
-        while (skipped != nbytes) {
-            x = in.read(b, 0,
-                    (v = (int) (nbytes - skipped)) > b.length ? b.length : v);
-            if (x == -1) {
-                return skipped;
-            }
-            check.update(b, 0, x);
-            skipped += x;
-        }
-        return skipped;
+    public long skip(long byteCount) throws IOException {
+        return Streams.skipByReading(this, byteCount);
     }
 }
diff --git a/luni/src/main/java/java/util/zip/Deflater.java b/luni/src/main/java/java/util/zip/Deflater.java
index 4ac5c47..755db4e 100644
--- a/luni/src/main/java/java/util/zip/Deflater.java
+++ b/luni/src/main/java/java/util/zip/Deflater.java
@@ -17,6 +17,7 @@
 
 package java.util.zip;
 
+import dalvik.system.CloseGuard;
 
 /**
  * This class compresses data using the <i>DEFLATE</i> algorithm (see <a
@@ -128,6 +129,8 @@
 
     private int inLength;
 
+    private final CloseGuard guard = CloseGuard.get();
+
     /**
      * Constructs a new {@code Deflater} instance with default compression
      * level. The strategy can be specified with {@link #setStrategy}, only. A
@@ -169,6 +172,7 @@
         }
         compressLevel = level;
         streamHandle = createStream(compressLevel, strategy, noHeader);
+        guard.open("end");
     }
 
     /**
@@ -251,6 +255,7 @@
      * methods will typically throw an {@code IllegalStateException}.
      */
     public synchronized void end() {
+        guard.close();
         endImpl();
     }
 
@@ -264,6 +269,9 @@
 
     @Override protected void finalize() {
         try {
+            if (guard != null) {
+                guard.warnIfOpen();
+            }
             synchronized (this) {
                 end(); // to allow overriding classes to clean up
                 endImpl(); // in case those classes don't call super.end()
diff --git a/luni/src/main/java/java/util/zip/DeflaterInputStream.java b/luni/src/main/java/java/util/zip/DeflaterInputStream.java
index c0c0f4c..5175f58 100644
--- a/luni/src/main/java/java/util/zip/DeflaterInputStream.java
+++ b/luni/src/main/java/java/util/zip/DeflaterInputStream.java
@@ -20,6 +20,7 @@
 import java.io.FilterInputStream;
 import java.io.IOException;
 import java.io.InputStream;
+import libcore.base.Streams;
 
 /**
  * An {@code InputStream} filter to compress data. Callers read
@@ -168,25 +169,9 @@
      * skip {@code Integer.MAX_VALUE} bytes.
      */
     @Override
-    public long skip(long n) throws IOException {
-        if (n < 0) {
-            throw new IllegalArgumentException();
-        }
-        if (n > Integer.MAX_VALUE) {
-            n = Integer.MAX_VALUE;
-        }
-        checkClosed();
-
-        int remaining = (int) n;
-        byte[] tmp = new byte[Math.min(remaining, DEFAULT_BUFFER_SIZE)];
-        while (remaining > 0) {
-            int count = read(tmp, 0, Math.min(remaining, tmp.length));
-            if (count == -1) {
-                break;
-            }
-            remaining -= count;
-        }
-        return n - remaining;
+    public long skip(long byteCount) throws IOException {
+        byteCount = Math.min(Integer.MAX_VALUE, byteCount);
+        return Streams.skipByReading(this, byteCount);
     }
 
     /**
diff --git a/luni/src/main/java/java/util/zip/Inflater.java b/luni/src/main/java/java/util/zip/Inflater.java
index 9dd56f3..5fb6564 100644
--- a/luni/src/main/java/java/util/zip/Inflater.java
+++ b/luni/src/main/java/java/util/zip/Inflater.java
@@ -17,6 +17,7 @@
 
 package java.util.zip;
 
+import dalvik.system.CloseGuard;
 import java.io.FileDescriptor;
 
 /**
@@ -45,6 +46,8 @@
 
     private long streamHandle = -1;
 
+    private final CloseGuard guard = CloseGuard.get();
+
     /**
      * This constructor creates an inflater that expects a header from the input
      * stream. Use {@code Inflater(boolean)} if the input comes without a ZLIB
@@ -64,6 +67,7 @@
      */
     public Inflater(boolean noHeader) {
         streamHandle = createStream(noHeader);
+        guard.open("end");
     }
 
     private native long createStream(boolean noHeader1);
@@ -73,6 +77,7 @@
      * input/output is discarded. This is also called by the finalize method.
      */
     public synchronized void end() {
+        guard.close();
         if (streamHandle != -1) {
             endImpl(streamHandle);
             inRead = 0;
@@ -85,6 +90,9 @@
 
     @Override protected void finalize() {
         try {
+            if (guard != null) {
+                guard.warnIfOpen();
+            }
             end();
         } finally {
             try {
diff --git a/luni/src/main/java/java/util/zip/ZipFile.java b/luni/src/main/java/java/util/zip/ZipFile.java
index 9493164..61f3afc 100644
--- a/luni/src/main/java/java/util/zip/ZipFile.java
+++ b/luni/src/main/java/java/util/zip/ZipFile.java
@@ -17,17 +17,22 @@
 
 package java.util.zip;
 
+import dalvik.system.CloseGuard;
 import java.io.BufferedInputStream;
+import java.io.EOFException;
 import java.io.DataInputStream;
 import java.io.File;
 import java.io.IOException;
 import java.io.InputStream;
 import java.io.RandomAccessFile;
+import java.nio.ByteOrder;
 import java.security.AccessController;
 import java.security.PrivilegedAction;
 import java.util.Enumeration;
 import java.util.Iterator;
 import java.util.LinkedHashMap;
+import libcore.io.BufferIterator;
+import libcore.io.HeapBufferIterator;
 
 /**
  * This class provides random read access to a <i>ZIP-archive</i> file.
@@ -83,6 +88,8 @@
 
     private final LinkedHashMap<String, ZipEntry> mEntries = new LinkedHashMap<String, ZipEntry>();
 
+    private final CloseGuard guard = CloseGuard.get();
+
     /**
      * Constructs a new {@code ZipFile} with the specified file.
      *
@@ -131,6 +138,7 @@
         mRaf = new RandomAccessFile(fileName, "r");
 
         readCentralDir();
+        guard.open("close");
     }
 
     /**
@@ -147,7 +155,9 @@
 
     @Override protected void finalize() throws IOException {
         try {
-            close();
+            if (guard != null) {
+                guard.warnIfOpen();
+            }
         } finally {
             try {
                 super.finalize();
@@ -164,6 +174,7 @@
      *             if an IOException occurs.
      */
     public void close() throws IOException {
+        guard.close();
         RandomAccessFile raf = mRaf;
 
         if (raf != null) { // Only close initialized instances
@@ -342,33 +353,26 @@
             }
         }
 
-        /*
-         * Found it, read the EOCD.
-         *
-         * For performance we want to use buffered I/O when reading the
-         * file.  We wrap a buffered stream around the random-access file
-         * object.  If we just read from the RandomAccessFile we'll be
-         * doing a read() system call every time.
-         */
-        RAFStream rafs = new RAFStream(mRaf, mRaf.getFilePointer());
-        DataInputStream is = new DataInputStream(new BufferedInputStream(rafs, ENDHDR));
+        // Read the End Of Central Directory. We could use ENDHDR instead of the magic number 18,
+        // but we don't actually need all the header.
+        byte[] eocd = new byte[18];
+        mRaf.readFully(eocd);
 
-        short diskNumber = Short.reverseBytes(is.readShort());
-        short diskWithCentralDir = Short.reverseBytes(is.readShort());
-        short numEntries = Short.reverseBytes(is.readShort());
-        short totalNumEntries = Short.reverseBytes(is.readShort());
-        /*centralDirSize =*/ Integer.reverseBytes(is.readInt());
-        int centralDirOffset = Integer.reverseBytes(is.readInt());
-        /*commentLen =*/ Short.reverseBytes(is.readShort());
+        // Pull out the information we need.
+        BufferIterator it = HeapBufferIterator.iterator(eocd, 0, eocd.length, ByteOrder.LITTLE_ENDIAN);
+        short diskNumber = it.readShort();
+        short diskWithCentralDir = it.readShort();
+        short numEntries = it.readShort();
+        short totalNumEntries = it.readShort();
+        it.skip(4); // Ignore centralDirSize.
+        int centralDirOffset = it.readInt();
 
         if (numEntries != totalNumEntries || diskNumber != 0 || diskWithCentralDir != 0) {
             throw new ZipException("spanned archives not supported");
         }
 
-        /*
-         * Seek to the first CDE and read all entries.
-         */
-        rafs = new RAFStream(mRaf, centralDirOffset);
+        // Seek to the first CDE and read all entries.
+        RAFStream rafs = new RAFStream(mRaf, centralDirOffset);
         BufferedInputStream bin = new BufferedInputStream(rafs, 4096);
         byte[] hdrBuf = new byte[CENHDR]; // Reuse the same buffer for each entry.
         for (int i = 0; i < numEntries; ++i) {
diff --git a/luni/src/main/java/java/util/zip/ZipInputStream.java b/luni/src/main/java/java/util/zip/ZipInputStream.java
index 6191046..1bd7403 100644
--- a/luni/src/main/java/java/util/zip/ZipInputStream.java
+++ b/luni/src/main/java/java/util/zip/ZipInputStream.java
@@ -24,10 +24,11 @@
 import java.nio.charset.ModifiedUtf8;
 import java.util.jar.Attributes;
 import java.util.jar.JarEntry;
+import libcore.base.Streams;
 
 /**
  * This class provides an implementation of {@code FilterInputStream} that
- * uncompresses data from a <i>ZIP-archive</i> input stream.
+ * decompresses data from a <i>ZIP-archive</i> input stream.
  * <p>
  * A <i>ZIP-archive</i> is a collection of compressed (or uncompressed) files -
  * the so called ZIP entries. Therefore when reading from a {@code
@@ -124,7 +125,7 @@
         // Ensure all entry bytes are read
         Exception failure = null;
         try {
-            skip(Long.MAX_VALUE);
+            Streams.skipAll(this);
         } catch (Exception e) {
             failure = e;
         }
@@ -350,34 +351,6 @@
         return read;
     }
 
-    /**
-     * Skips up to the specified number of bytes in the current ZIP entry.
-     *
-     * @param value
-     *            the number of bytes to skip.
-     * @return the number of bytes skipped.
-     * @throws IOException
-     *             if an {@code IOException} occurs.
-     */
-    @Override
-    public long skip(long value) throws IOException {
-        if (value < 0) {
-            throw new IllegalArgumentException();
-        }
-
-        long skipped = 0;
-        byte[] b = new byte[(int)Math.min(value, 2048L)];
-        while (skipped != value) {
-            long rem = value - skipped;
-            int x = read(b, 0, (int) (b.length > rem ? rem : b.length));
-            if (x == -1) {
-                return skipped;
-            }
-            skipped += x;
-        }
-        return skipped;
-    }
-
     @Override
     public int available() throws IOException {
         checkClosed();
diff --git a/luni/src/main/java/javax/crypto/CipherInputStream.java b/luni/src/main/java/javax/crypto/CipherInputStream.java
index 85f38b7..fa6040f 100644
--- a/luni/src/main/java/javax/crypto/CipherInputStream.java
+++ b/luni/src/main/java/javax/crypto/CipherInputStream.java
@@ -21,6 +21,7 @@
 import java.io.IOException;
 import java.io.InputStream;
 import java.security.GeneralSecurityException;
+import libcore.base.Streams;
 
 /**
  * This class wraps an {@code InputStream} and a cipher so that {@code read()}
@@ -162,30 +163,9 @@
         return i;
     }
 
-    /**
-     * Skips up to n bytes from this input stream.
-     * <p>
-     * The number of bytes skipped depends on the result of a call to
-     * {@link CipherInputStream#available() available}. The smaller of n and the
-     * result are the number of bytes being skipped.
-     *
-     * @param n
-     *            the number of bytes that should be skipped.
-     * @return the number of bytes actually skipped.
-     * @throws IOException
-     *             if an error occurs
-     */
     @Override
-    public long skip(long n) throws IOException {
-        long i = 0;
-        int available = available();
-        if (available < n) {
-            n = available;
-        }
-        while ((i < n) && (read() != -1)) {
-            i++;
-        }
-        return i;
+    public long skip(long byteCount) throws IOException {
+        return Streams.skipByReading(this, byteCount);
     }
 
     @Override
diff --git a/luni/src/main/java/javax/xml/datatype/FactoryFinder.java b/luni/src/main/java/javax/xml/datatype/FactoryFinder.java
index a940705..9a6b29b 100644
--- a/luni/src/main/java/javax/xml/datatype/FactoryFinder.java
+++ b/luni/src/main/java/javax/xml/datatype/FactoryFinder.java
@@ -26,6 +26,7 @@
 import java.io.InputStreamReader;
 import java.net.URL;
 import java.util.Properties;
+import libcore.io.IoUtils;
 
 /**
  * <p>Implement pluggabile Datatypes.</p>
@@ -290,18 +291,11 @@
             // XXX Does not handle all possible input as specified by the
             // Jar Service Provider specification
             factoryClassName = rd.readLine();
-        }
-        catch (IOException x) {
+        } catch (IOException x) {
             // No provider found
             return null;
-        }
-        finally {
-            try {
-                // try to close the reader.
-                rd.close();
-            }
-            // Ignore the exception.
-            catch (IOException exc) {}
+        } finally {
+            IoUtils.closeQuietly(rd);
         }
 
         if (factoryClassName != null &&
diff --git a/luni/src/main/java/javax/xml/validation/SchemaFactoryFinder.java b/luni/src/main/java/javax/xml/validation/SchemaFactoryFinder.java
index b475d1d..9cf521a 100644
--- a/luni/src/main/java/javax/xml/validation/SchemaFactoryFinder.java
+++ b/luni/src/main/java/javax/xml/validation/SchemaFactoryFinder.java
@@ -30,6 +30,7 @@
 import java.util.NoSuchElementException;
 import java.util.Properties;
 import javax.xml.XMLConstants;
+import libcore.io.IoUtils;
 
 /**
  * Implementation of {@link SchemaFactory#newInstance(String)}.
@@ -454,12 +455,7 @@
             }
         }
 
-        try {
-            // try to close the reader.
-            rd.close();
-        }
-        // Ignore the exception.
-        catch (IOException exc) {}
+        IoUtils.closeQuietly(rd);
 
         return resultFactory;
     }
diff --git a/luni/src/main/java/javax/xml/xpath/XPathFactoryFinder.java b/luni/src/main/java/javax/xml/xpath/XPathFactoryFinder.java
index c85bfd1..d6ed893 100644
--- a/luni/src/main/java/javax/xml/xpath/XPathFactoryFinder.java
+++ b/luni/src/main/java/javax/xml/xpath/XPathFactoryFinder.java
@@ -30,6 +30,7 @@
 import java.util.NoSuchElementException;
 import java.util.Properties;
 import javax.xml.validation.SchemaFactory;
+import libcore.io.IoUtils;
 
 /**
  * Implementation of {@link XPathFactory#newInstance(String)}.
@@ -365,12 +366,7 @@
             }
         }
 
-        try {
-            // try to close the reader.
-            rd.close();
-        }
-        // Ignore the exception.
-        catch (IOException exc) {}
+        IoUtils.closeQuietly(rd);
 
         return resultFactory;
     }
diff --git a/luni/src/main/java/com/ibm/icu4jni/charset/CharsetDecoderICU.java b/luni/src/main/java/libcore/icu/CharsetDecoderICU.java
similarity index 97%
rename from luni/src/main/java/com/ibm/icu4jni/charset/CharsetDecoderICU.java
rename to luni/src/main/java/libcore/icu/CharsetDecoderICU.java
index 6ab0b22..c44095d 100644
--- a/luni/src/main/java/com/ibm/icu4jni/charset/CharsetDecoderICU.java
+++ b/luni/src/main/java/libcore/icu/CharsetDecoderICU.java
@@ -12,9 +12,8 @@
   *
   * @author Ram Viswanadha, IBM
   */
-package com.ibm.icu4jni.charset;
+package libcore.icu;
 
-import com.ibm.icu4jni.common.ErrorCode;
 import java.nio.ByteBuffer;
 import java.nio.CharBuffer;
 import java.nio.charset.Charset;
@@ -119,8 +118,8 @@
 
     private void updateCallback() {
         ec = NativeConverter.setCallbackDecode(converterHandle, this);
-        if (ErrorCode.isFailure(ec)){
-            throw ErrorCode.getException(ec);
+        if (ErrorCode.isFailure(ec)) {
+            throw ErrorCode.throwException(ec);
         }
     }
 
@@ -151,7 +150,7 @@
                         return CoderResult.malformedForLength(data[INPUT_OFFSET]);
                     }
                 } else {
-                    ErrorCode.getException(ec);
+                    throw ErrorCode.throwException(ec);
                 }
             }
             return CoderResult.UNDERFLOW;
diff --git a/luni/src/main/java/com/ibm/icu4jni/charset/CharsetEncoderICU.java b/luni/src/main/java/libcore/icu/CharsetEncoderICU.java
similarity index 98%
rename from luni/src/main/java/com/ibm/icu4jni/charset/CharsetEncoderICU.java
rename to luni/src/main/java/libcore/icu/CharsetEncoderICU.java
index 6704b1a..31413c0 100644
--- a/luni/src/main/java/com/ibm/icu4jni/charset/CharsetEncoderICU.java
+++ b/luni/src/main/java/libcore/icu/CharsetEncoderICU.java
@@ -12,9 +12,8 @@
  *
  * @author Ram Viswanadha, IBM
  */
-package com.ibm.icu4jni.charset;
+package libcore.icu;
 
-import com.ibm.icu4jni.common.ErrorCode;
 import java.nio.ByteBuffer;
 import java.nio.CharBuffer;
 import java.nio.charset.Charset;
@@ -145,8 +144,8 @@
 
     private void updateCallback() {
         ec = NativeConverter.setCallbackEncode(converterHandle, this);
-        if (ErrorCode.isFailure(ec)){
-            throw ErrorCode.getException(ec);
+        if (ErrorCode.isFailure(ec)) {
+            throw ErrorCode.throwException(ec);
         }
     }
 
@@ -176,7 +175,7 @@
                         return CoderResult.malformedForLength(data[INPUT_OFFSET]);
                     }
                 } else {
-                    ErrorCode.getException(ec);
+                    throw ErrorCode.throwException(ec);
                 }
             }
             return CoderResult.UNDERFLOW;
@@ -229,7 +228,7 @@
                                         output, /* output array of chars */
                                         outEnd, /* output index+1 to be written */
                                         data, /* contains data, inOff,outOff */
-                                        false /* donot flush the data */
+                                        false /* don't flush the data */
                                         );
             if (ErrorCode.isFailure(ec)) {
                 /* If we don't have room for the output return error */
diff --git a/luni/src/main/java/com/ibm/icu4jni/charset/CharsetICU.java b/luni/src/main/java/libcore/icu/CharsetICU.java
similarity index 97%
rename from luni/src/main/java/com/ibm/icu4jni/charset/CharsetICU.java
rename to luni/src/main/java/libcore/icu/CharsetICU.java
index cab7a52..ac84e6c 100644
--- a/luni/src/main/java/com/ibm/icu4jni/charset/CharsetICU.java
+++ b/luni/src/main/java/libcore/icu/CharsetICU.java
@@ -7,7 +7,7 @@
 *******************************************************************************
 */
 
-package com.ibm.icu4jni.charset;
+package libcore.icu;
 
 import java.nio.charset.Charset;
 import java.nio.charset.CharsetDecoder;
diff --git a/luni/src/main/java/com/ibm/icu4jni/text/CollationElementIterator.java b/luni/src/main/java/libcore/icu/CollationElementIteratorICU.java
similarity index 92%
rename from luni/src/main/java/com/ibm/icu4jni/text/CollationElementIterator.java
rename to luni/src/main/java/libcore/icu/CollationElementIteratorICU.java
index e84e438..bb5e809 100644
--- a/luni/src/main/java/com/ibm/icu4jni/text/CollationElementIterator.java
+++ b/luni/src/main/java/libcore/icu/CollationElementIteratorICU.java
@@ -7,11 +7,10 @@
 *******************************************************************************
 */
 
-package com.ibm.icu4jni.text;
+package libcore.icu;
 
 import java.text.CharacterIterator;
 
-
 /**
 * Collation element iterator JNI wrapper.
 * Iterates over the collation elements of a data string.
@@ -37,8 +36,7 @@
 * @author syn wee quek
 * @stable ICU 2.4
 */
-
-public final class CollationElementIterator {
+public final class CollationElementIteratorICU {
     // public data member -------------------------------------------
 
     /**
@@ -159,16 +157,13 @@
         return order & TERTIARY_ORDER_MASK_;
     }
 
-    // protected constructor ----------------------------------------
+    public static CollationElementIteratorICU getInstance(int collatorAddress, String source) {
+        int iteratorAddress = NativeCollation.getCollationElementIterator(collatorAddress, source);
+        return new CollationElementIteratorICU(iteratorAddress);
+    }
 
-    /**
-     * CollationElementIteratorJNI constructor.
-     * The only caller of this class should be
-     * RuleBasedCollator.getCollationElementIterator().
-     * @param collelemiteratoraddress address of C collationelementiterator
-     */
-    CollationElementIterator(int collelemiteratoraddress) {
-        m_collelemiterator_ = collelemiteratoraddress;
+    private CollationElementIteratorICU(int address) {
+        m_collelemiterator_ = address;
     }
 
     // protected methods --------------------------------------------
diff --git a/luni/src/main/java/com/ibm/icu4jni/text/CollationKey.java b/luni/src/main/java/libcore/icu/CollationKeyICU.java
similarity index 81%
rename from luni/src/main/java/com/ibm/icu4jni/text/CollationKey.java
rename to luni/src/main/java/libcore/icu/CollationKeyICU.java
index dbd714c..614d841 100644
--- a/luni/src/main/java/com/ibm/icu4jni/text/CollationKey.java
+++ b/luni/src/main/java/libcore/icu/CollationKeyICU.java
@@ -8,12 +8,14 @@
 *******************************************************************************
 */
 
-package com.ibm.icu4jni.text;
+package libcore.icu;
+
+import java.text.CollationKey;
 
 /**
  * A concrete implementation of the abstract java.text.CollationKey.
  */
-public final class CollationKey extends java.text.CollationKey {
+public final class CollationKeyICU extends CollationKey {
     /**
      * The key.
      */
@@ -24,16 +26,16 @@
      */
     private int hashCode;
 
-    CollationKey(String source, byte[] bytes) {
+    CollationKeyICU(String source, byte[] bytes) {
         super(source);
         this.bytes = bytes;
     }
 
-    public int compareTo(java.text.CollationKey other) {
+    @Override public int compareTo(CollationKey other) {
         // Get the bytes from the other collation key.
         final byte[] rhsBytes;
-        if (other instanceof CollationKey) {
-            rhsBytes = ((CollationKey) other).bytes;
+        if (other instanceof CollationKeyICU) {
+            rhsBytes = ((CollationKeyICU) other).bytes;
         } else {
             rhsBytes = other.toByteArray();
         }
@@ -69,14 +71,7 @@
         return 0;
     }
 
-    /**
-     * Checks if target object is equal to this object.
-     * Target is first casted to CollationKey and bitwise compared.
-     * @param target comparison object
-     * @return true if both objects are equal, false otherwise
-     * @stable ICU 2.4
-     */
-    public boolean equals(Object object) {
+    @Override public boolean equals(Object object) {
         if (object == this) {
             return true;
         }
@@ -96,7 +91,7 @@
      * @return hash value of collation key. Hash value is never 0.
      * @stable ICU 2.4
      */
-    public int hashCode() {
+    @Override public int hashCode() {
         if (hashCode == 0) {
             if (bytes != null && bytes.length != 0) {
                 int len = bytes.length;
@@ -113,7 +108,7 @@
         return hashCode;
     }
 
-    public byte[] toByteArray() {
+    @Override public byte[] toByteArray() {
         if (bytes == null || bytes.length == 0) {
             return null;
         }
diff --git a/luni/src/main/java/libcore/icu/ErrorCode.java b/luni/src/main/java/libcore/icu/ErrorCode.java
new file mode 100644
index 0000000..c093af2
--- /dev/null
+++ b/luni/src/main/java/libcore/icu/ErrorCode.java
@@ -0,0 +1,71 @@
+/**
+******************************************************************************
+* Copyright (C) 1996-2005, International Business Machines Corporation and   *
+* others. All Rights Reserved.                                               *
+******************************************************************************
+*
+******************************************************************************
+*/
+
+package libcore.icu;
+
+/**
+ * Error exception class mapping ICU error codes of the enum UErrorCode
+ * @author syn wee quek
+*/
+public final class ErrorCode extends Exception {
+    public static boolean isFailure(int error) {
+        return error > U_ZERO_ERROR && error < U_ERROR_LIMIT;
+    }
+
+    public static RuntimeException throwException(int error) {
+        if (error <= U_ZERO_ERROR && error >= U_ERROR_LIMIT) {
+            return null;
+        }
+        switch (error) {
+        case U_ILLEGAL_ARGUMENT_ERROR:
+            return new IllegalArgumentException(ERROR_NAMES[error]);
+        case U_INDEX_OUTOFBOUNDS_ERROR:
+        case U_BUFFER_OVERFLOW_ERROR:
+            return new ArrayIndexOutOfBoundsException(ERROR_NAMES[error]);
+        case U_UNSUPPORTED_ERROR:
+            return new UnsupportedOperationException(ERROR_NAMES[error]);
+        }
+        throw new RuntimeException(ERROR_NAMES[error]);
+    }
+
+    // The errors needed by our CharsetDecoderICU/CharsetEncoderICU.
+    public static final int U_ZERO_ERROR = 0;
+    private static final int U_ILLEGAL_ARGUMENT_ERROR = 1;
+    private static final int U_INDEX_OUTOFBOUNDS_ERROR = 8;
+    public static final int U_INVALID_CHAR_FOUND = 10;
+    public static final int U_TRUNCATED_CHAR_FOUND = 11;
+    public static final int U_ILLEGAL_CHAR_FOUND = 12;
+    public static final int U_BUFFER_OVERFLOW_ERROR = 15;
+    private static final int U_UNSUPPORTED_ERROR = 16;
+    private static final int U_ERROR_LIMIT = 21;
+
+    // TODO: this list is incomplete; get these from native code!
+    private static final String ERROR_NAMES[] = {
+        "U_ZERO_ERROR",
+        "U_ILLEGAL_ARGUMENT_ERROR",
+        "U_MISSING_RESOURCE_ERROR",
+        "U_INVALID_FORMAT_ERROR",
+        "U_FILE_ACCESS_ERROR",
+        "U_INTERNAL_PROGRAM_ERROR",
+        "U_MESSAGE_PARSE_ERROR",
+        "U_MEMORY_ALLOCATION_ERROR",
+        "U_INDEX_OUTOFBOUNDS_ERROR",
+        "U_PARSE_ERROR",
+        "U_INVALID_CHAR_FOUND",
+        "U_TRUNCATED_CHAR_FOUND",
+        "U_ILLEGAL_CHAR_FOUND",
+        "U_INVALID_TABLE_FORMAT",
+        "U_INVALID_TABLE_FILE",
+        "U_BUFFER_OVERFLOW_ERROR",
+        "U_UNSUPPORTED_ERROR",
+        "U_RESOURCE_TYPE_MISMATCH",
+        "U_ILLEGAL_ESCAPE_SEQUENCE",
+        "U_UNSUPPORTED_ESCAPE_SEQUENCE"
+    };
+}
diff --git a/luni/src/main/java/com/ibm/icu4jni/util/ICU.java b/luni/src/main/java/libcore/icu/ICU.java
similarity index 99%
rename from luni/src/main/java/com/ibm/icu4jni/util/ICU.java
rename to luni/src/main/java/libcore/icu/ICU.java
index 78e9a1f..3359305 100644
--- a/luni/src/main/java/com/ibm/icu4jni/util/ICU.java
+++ b/luni/src/main/java/libcore/icu/ICU.java
@@ -14,7 +14,7 @@
  * limitations under the License.
  */
 
-package com.ibm.icu4jni.util;
+package libcore.icu;
 
 import java.util.Locale;
 
diff --git a/luni/src/main/java/com/ibm/icu4jni/util/LocaleData.java b/luni/src/main/java/libcore/icu/LocaleData.java
similarity index 99%
rename from luni/src/main/java/com/ibm/icu4jni/util/LocaleData.java
rename to luni/src/main/java/libcore/icu/LocaleData.java
index 67112b6..dba7d7c 100644
--- a/luni/src/main/java/com/ibm/icu4jni/util/LocaleData.java
+++ b/luni/src/main/java/libcore/icu/LocaleData.java
@@ -14,7 +14,7 @@
  * limitations under the License.
  */
 
-package com.ibm.icu4jni.util;
+package libcore.icu;
 
 import java.text.DateFormat;
 import java.util.Arrays;
diff --git a/luni/src/main/java/com/ibm/icu4jni/text/NativeBreakIterator.java b/luni/src/main/java/libcore/icu/NativeBreakIterator.java
similarity index 99%
rename from luni/src/main/java/com/ibm/icu4jni/text/NativeBreakIterator.java
rename to luni/src/main/java/libcore/icu/NativeBreakIterator.java
index bbe45af..86c6924 100644
--- a/luni/src/main/java/com/ibm/icu4jni/text/NativeBreakIterator.java
+++ b/luni/src/main/java/libcore/icu/NativeBreakIterator.java
@@ -14,7 +14,7 @@
  * limitations under the License.
  */
 
-package com.ibm.icu4jni.text;
+package libcore.icu;
 
 import java.text.CharacterIterator;
 import java.text.StringCharacterIterator;
diff --git a/luni/src/main/java/libcore/icu/NativeCollation.java b/luni/src/main/java/libcore/icu/NativeCollation.java
new file mode 100644
index 0000000..2f61c49
--- /dev/null
+++ b/luni/src/main/java/libcore/icu/NativeCollation.java
@@ -0,0 +1,43 @@
+/**
+*******************************************************************************
+* Copyright (C) 1996-2005, International Business Machines Corporation and    *
+* others. All Rights Reserved.                                                *
+*******************************************************************************
+*
+*
+*******************************************************************************
+*/
+
+package libcore.icu;
+
+/**
+* Package static class for declaring all native methods for collation use.
+* @author syn wee quek
+* @internal ICU 2.4
+*/
+public final class NativeCollation {
+    private NativeCollation() {
+    }
+
+    // Collator.
+    public static native void closeCollator(int address);
+    public static native int compare(int address, String source, String target);
+    public static native int getAttribute(int address, int type);
+    public static native int getCollationElementIterator(int address, String source);
+    public static native String getRules(int address);
+    public static native byte[] getSortKey(int address, String source);
+    public static native int openCollator(String locale);
+    public static native int openCollatorFromRules(String rules, int normalizationMode, int collationStrength);
+    public static native int safeClone(int address);
+    public static native void setAttribute(int address, int type, int value);
+
+    // CollationElementIterator.
+    public static native void closeElements(int address);
+    public static native int getMaxExpansion(int address, int order);
+    public static native int getOffset(int address);
+    public static native int next(int address);
+    public static native int previous(int address);
+    public static native void reset(int address);
+    public static native void setOffset(int address, int offset);
+    public static native void setText(int address, String source);
+}
diff --git a/luni/src/main/java/com/ibm/icu4jni/charset/NativeConverter.java b/luni/src/main/java/libcore/icu/NativeConverter.java
similarity index 99%
rename from luni/src/main/java/com/ibm/icu4jni/charset/NativeConverter.java
rename to luni/src/main/java/libcore/icu/NativeConverter.java
index 2e37f32..6165c61 100644
--- a/luni/src/main/java/com/ibm/icu4jni/charset/NativeConverter.java
+++ b/luni/src/main/java/libcore/icu/NativeConverter.java
@@ -7,7 +7,7 @@
 *******************************************************************************
 */
 
-package com.ibm.icu4jni.charset;
+package libcore.icu;
 
 import java.nio.charset.Charset;
 import java.nio.charset.CharsetDecoder;
diff --git a/luni/src/main/java/com/ibm/icu4jni/text/NativeDecimalFormat.java b/luni/src/main/java/libcore/icu/NativeDecimalFormat.java
similarity index 99%
rename from luni/src/main/java/com/ibm/icu4jni/text/NativeDecimalFormat.java
rename to luni/src/main/java/libcore/icu/NativeDecimalFormat.java
index 3138237..1c92d97 100644
--- a/luni/src/main/java/com/ibm/icu4jni/text/NativeDecimalFormat.java
+++ b/luni/src/main/java/libcore/icu/NativeDecimalFormat.java
@@ -14,9 +14,8 @@
  * limitations under the License.
  */
 
-package com.ibm.icu4jni.text;
+package libcore.icu;
 
-import com.ibm.icu4jni.util.LocaleData;
 import java.math.BigDecimal;
 import java.math.BigInteger;
 import java.math.RoundingMode;
@@ -29,6 +28,7 @@
 import java.text.ParsePosition;
 import java.util.Currency;
 import java.util.NoSuchElementException;
+import libcore.icu.LocaleData;
 
 public final class NativeDecimalFormat {
     /**
diff --git a/luni/src/main/java/libcore/icu/RuleBasedCollatorICU.java b/luni/src/main/java/libcore/icu/RuleBasedCollatorICU.java
new file mode 100644
index 0000000..d036c98
--- /dev/null
+++ b/luni/src/main/java/libcore/icu/RuleBasedCollatorICU.java
@@ -0,0 +1,154 @@
+/**
+*******************************************************************************
+* Copyright (C) 1996-2005, International Business Machines Corporation and    *
+* others. All Rights Reserved.                                                *
+*******************************************************************************
+*
+*
+*******************************************************************************
+*/
+
+package libcore.icu;
+
+import java.text.CharacterIterator;
+import java.text.CollationKey;
+import java.text.ParseException;
+import java.util.Locale;
+
+public final class RuleBasedCollatorICU implements Cloneable {
+    // Values from the native UColAttributeValue enum.
+    public static final int VALUE_DEFAULT = -1;
+    public static final int VALUE_PRIMARY = 0;
+    public static final int VALUE_SECONDARY = 1;
+    public static final int VALUE_TERTIARY = 2;
+    public static final int VALUE_DEFAULT_STRENGTH = VALUE_TERTIARY;
+    public static final int VALUE_QUATERNARY = 3;
+    public static final int VALUE_IDENTICAL = 15;
+    public static final int VALUE_OFF = 16;
+    public static final int VALUE_ON = 17;
+    public static final int VALUE_SHIFTED = 20;
+    public static final int VALUE_NON_IGNORABLE = 21;
+    public static final int VALUE_LOWER_FIRST = 24;
+    public static final int VALUE_UPPER_FIRST = 25;
+    public static final int VALUE_ON_WITHOUT_HANGUL = 28;
+    public static final int VALUE_ATTRIBUTE_VALUE_COUNT = 29;
+
+    // Values from the UColAttribute enum.
+    public static final int FRENCH_COLLATION = 0;
+    public static final int ALTERNATE_HANDLING = 1;
+    public static final int CASE_FIRST = 2;
+    public static final int CASE_LEVEL = 3;
+    public static final int DECOMPOSITION_MODE = 4;
+    public static final int STRENGTH = 5;
+
+    // The address of the ICU4C native peer.
+    private int address;
+
+    public RuleBasedCollatorICU(String rules) throws ParseException {
+        if (rules == null) {
+            throw new NullPointerException();
+        }
+        address = NativeCollation.openCollatorFromRules(rules, VALUE_OFF, VALUE_DEFAULT_STRENGTH);
+    }
+
+    public RuleBasedCollatorICU(Locale locale) {
+        address = NativeCollation.openCollator(locale.toString());
+    }
+
+    private RuleBasedCollatorICU(int address) {
+        this.address = address;
+    }
+
+    public Object clone() {
+        return new RuleBasedCollatorICU(NativeCollation.safeClone(address));
+    }
+
+    public int compare(String source, String target) {
+        return NativeCollation.compare(address, source, target);
+    }
+
+    public int getDecomposition() {
+        return NativeCollation.getAttribute(address, DECOMPOSITION_MODE);
+    }
+
+    public void setDecomposition(int mode) {
+        NativeCollation.setAttribute(address, DECOMPOSITION_MODE, mode);
+    }
+
+    public int getStrength() {
+        return NativeCollation.getAttribute(address, STRENGTH);
+    }
+
+    public void setStrength(int strength) {
+        NativeCollation.setAttribute(address, STRENGTH, strength);
+    }
+
+    public void setAttribute(int type, int value) {
+        NativeCollation.setAttribute(address, type, value);
+    }
+
+    public int getAttribute(int type) {
+        return NativeCollation.getAttribute(address, type);
+    }
+
+    public CollationKey getCollationKey(String source) {
+        if (source == null) {
+            return null;
+        }
+        byte[] key = NativeCollation.getSortKey(address, source);
+        if (key == null) {
+            return null;
+        }
+        return new CollationKeyICU(source, key);
+    }
+
+    public String getRules() {
+        return NativeCollation.getRules(address);
+    }
+
+    public CollationElementIteratorICU getCollationElementIterator(String source) {
+        return CollationElementIteratorICU.getInstance(address, source);
+    }
+
+    public CollationElementIteratorICU getCollationElementIterator(CharacterIterator it) {
+        // We only implement the String-based API, so build a string from the iterator.
+        return getCollationElementIterator(characterIteratorToString(it));
+    }
+
+    private String characterIteratorToString(CharacterIterator it) {
+        StringBuilder result = new StringBuilder();
+        for (char ch = it.current(); ch != CharacterIterator.DONE; ch = it.next()) {
+            result.append(ch);
+        }
+        return result.toString();
+    }
+
+    @Override public int hashCode() {
+        return 42; // No-one uses RuleBasedCollatorICU as a hash key.
+    }
+
+    public boolean equals(String source, String target) {
+        return (compare(source, target) == 0);
+    }
+
+    @Override public boolean equals(Object object) {
+        if (object ==  this) {
+            return true;
+        }
+        if (!(object instanceof RuleBasedCollatorICU)) {
+            return false;
+        }
+        RuleBasedCollatorICU rhs = (RuleBasedCollatorICU) object;
+        return getRules().equals(rhs.getRules()) &&
+                getStrength() == rhs.getStrength() &&
+                getDecomposition() == rhs.getDecomposition();
+    }
+
+    @Override protected void finalize() throws Throwable {
+        try {
+            NativeCollation.closeCollator(address);
+        } finally {
+            super.finalize();
+        }
+    }
+}
diff --git a/luni/src/main/java/libcore/io/BufferIterator.java b/luni/src/main/java/libcore/io/BufferIterator.java
index d669b24..2b7b4db 100644
--- a/luni/src/main/java/libcore/io/BufferIterator.java
+++ b/luni/src/main/java/libcore/io/BufferIterator.java
@@ -16,67 +16,42 @@
 
 package libcore.io;
 
-import org.apache.harmony.luni.platform.OSMemory;
-
 /**
  * Iterates over big- or little-endian bytes. See {@link MemoryMappedFile#bigEndianIterator} and
  * {@link MemoryMappedFile#littleEndianIterator}.
  *
  * @hide don't make this public without adding bounds checking.
  */
-public final class BufferIterator {
-    private final int address;
-    private final int size;
-    private final boolean swap;
-
-    private int position;
-
-    BufferIterator(int address, int size, boolean swap) {
-        this.address = address;
-        this.size = size;
-        this.swap = swap;
-    }
-
+public abstract class BufferIterator {
     /**
      * Skips forwards or backwards {@code byteCount} bytes from the current position.
      */
-    public void skip(int byteCount) {
-        position += byteCount;
-    }
+    public abstract void skip(int byteCount);
 
     /**
      * Copies {@code byteCount} bytes from the current position into {@code dst}, starting at
      * {@code dstOffset}, and advances the current position {@code byteCount} bytes.
      */
-    public void readByteArray(byte[] dst, int dstOffset, int byteCount) {
-        OSMemory.peekByteArray(address + position, dst, dstOffset, byteCount);
-        position += byteCount;
-    }
+    public abstract void readByteArray(byte[] dst, int dstOffset, int byteCount);
 
     /**
      * Returns the byte at the current position, and advances the current position one byte.
      */
-    public byte readByte() {
-        byte result = OSMemory.peekByte(address + position);
-        ++position;
-        return result;
-    }
+    public abstract byte readByte();
 
     /**
      * Returns the 32-bit int at the current position, and advances the current position four bytes.
      */
-    public int readInt() {
-        int result = OSMemory.peekInt(address + position, swap);
-        position += 4;
-        return result;
-    }
+    public abstract int readInt();
 
     /**
      * Copies {@code intCount} 32-bit ints from the current position into {@code dst}, starting at
      * {@code dstOffset}, and advances the current position {@code 4 * intCount} bytes.
      */
-    public void readIntArray(int[] dst, int dstOffset, int intCount) {
-        OSMemory.peekIntArray(address + position, dst, dstOffset, intCount, swap);
-        position += 4 * intCount;
-    }
+    public abstract void readIntArray(int[] dst, int dstOffset, int intCount);
+
+    /**
+     * Returns the 16-bit short at the current position, and advances the current position two bytes.
+     */
+    public abstract short readShort();
 }
diff --git a/luni/src/main/java/libcore/io/HeapBufferIterator.java b/luni/src/main/java/libcore/io/HeapBufferIterator.java
new file mode 100644
index 0000000..65a13a4
--- /dev/null
+++ b/luni/src/main/java/libcore/io/HeapBufferIterator.java
@@ -0,0 +1,82 @@
+/*
+ * 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.
+ */
+
+package libcore.io;
+
+import java.nio.ByteOrder;
+import org.apache.harmony.luni.platform.OSMemory;
+
+/**
+ * Iterates over big- or little-endian bytes in a Java byte[].
+ *
+ * @hide don't make this public without adding bounds checking.
+ */
+public final class HeapBufferIterator extends BufferIterator {
+    private final byte[] buffer;
+    private final int offset;
+    private final int byteCount;
+    private final ByteOrder order;
+
+    private int position;
+
+    HeapBufferIterator(byte[] buffer, int offset, int byteCount, ByteOrder order) {
+        this.buffer = buffer;
+        this.offset = offset;
+        this.byteCount = byteCount;
+        this.order = order;
+    }
+
+    public void skip(int byteCount) {
+        position += byteCount;
+    }
+
+    public void readByteArray(byte[] dst, int dstOffset, int byteCount) {
+        System.arraycopy(buffer, offset + position, dst, dstOffset, byteCount);
+        position += byteCount;
+    }
+
+    public byte readByte() {
+        byte result = buffer[offset + position];
+        ++position;
+        return result;
+    }
+
+    public int readInt() {
+        int result = OSMemory.peekInt(buffer, offset + position, order);
+        position += SizeOf.INT;
+        return result;
+    }
+
+    public void readIntArray(int[] dst, int dstOffset, int intCount) {
+        final int byteCount = intCount * SizeOf.INT;
+        OSMemory.unsafeBulkGet(dst, dstOffset, byteCount, buffer, offset + position, SizeOf.INT, order.needsSwap);
+        position += byteCount;
+    }
+
+    public short readShort() {
+        short result = OSMemory.peekShort(buffer, offset + position, order);
+        position += SizeOf.SHORT;
+        return result;
+    }
+
+    /**
+     * Returns a new iterator over {@code buffer}, starting at {@code offset} and continuing for
+     * {@code byteCount} bytes. Items larger than a byte are interpreted using the given byte order.
+     */
+    public static BufferIterator iterator(byte[] buffer, int offset, int byteCount, ByteOrder order) {
+        return new HeapBufferIterator(buffer, offset, byteCount, order);
+    }
+}
diff --git a/luni/src/main/java/libcore/io/IoUtils.java b/luni/src/main/java/libcore/io/IoUtils.java
index 37988f2..29a64ba 100644
--- a/luni/src/main/java/libcore/io/IoUtils.java
+++ b/luni/src/main/java/libcore/io/IoUtils.java
@@ -20,6 +20,7 @@
 import java.io.FileDescriptor;
 import java.io.IOException;
 import java.io.RandomAccessFile;
+import java.net.Socket;
 
 public final class IoUtils {
     private IoUtils() {
@@ -43,6 +44,18 @@
     }
 
     /**
+     * Closes 'socket', ignoring any exceptions. Does nothing if 'socket' is null.
+     */
+    public static void closeQuietly(Socket socket) {
+        if (socket != null) {
+            try {
+                socket.close();
+            } catch (Exception ignored) {
+            }
+        }
+    }
+
+    /**
      * Returns the int file descriptor from within the given FileDescriptor 'fd'.
      */
     public static native int getFd(FileDescriptor fd);
diff --git a/luni/src/main/java/libcore/io/MemoryMappedFile.java b/luni/src/main/java/libcore/io/MemoryMappedFile.java
index 6813c47..10ef8f0 100644
--- a/luni/src/main/java/libcore/io/MemoryMappedFile.java
+++ b/luni/src/main/java/libcore/io/MemoryMappedFile.java
@@ -81,14 +81,14 @@
      * Returns a new iterator that treats the mapped data as big-endian.
      */
     public BufferIterator bigEndianIterator() {
-        return new BufferIterator(address, size, ByteOrder.nativeOrder() != ByteOrder.BIG_ENDIAN);
+        return new NioBufferIterator(address, size, ByteOrder.nativeOrder() != ByteOrder.BIG_ENDIAN);
     }
 
     /**
      * Returns a new iterator that treats the mapped data as little-endian.
      */
     public BufferIterator littleEndianIterator() {
-        return new BufferIterator(address, size, ByteOrder.nativeOrder() != ByteOrder.LITTLE_ENDIAN);
+        return new NioBufferIterator(address, size, ByteOrder.nativeOrder() != ByteOrder.LITTLE_ENDIAN);
     }
 
     /**
diff --git a/luni/src/main/java/libcore/io/NioBufferIterator.java b/luni/src/main/java/libcore/io/NioBufferIterator.java
new file mode 100644
index 0000000..7143896
--- /dev/null
+++ b/luni/src/main/java/libcore/io/NioBufferIterator.java
@@ -0,0 +1,71 @@
+/*
+ * 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.
+ */
+
+package libcore.io;
+
+import org.apache.harmony.luni.platform.OSMemory;
+
+/**
+ * Iterates over big- or little-endian bytes on the native heap.
+ * See {@link MemoryMappedFile#bigEndianIterator} and {@link MemoryMappedFile#littleEndianIterator}.
+ *
+ * @hide don't make this public without adding bounds checking.
+ */
+public final class NioBufferIterator extends BufferIterator {
+    private final int address;
+    private final int size;
+    private final boolean swap;
+
+    private int position;
+
+    NioBufferIterator(int address, int size, boolean swap) {
+        this.address = address;
+        this.size = size;
+        this.swap = swap;
+    }
+
+    public void skip(int byteCount) {
+        position += byteCount;
+    }
+
+    public void readByteArray(byte[] dst, int dstOffset, int byteCount) {
+        OSMemory.peekByteArray(address + position, dst, dstOffset, byteCount);
+        position += byteCount;
+    }
+
+    public byte readByte() {
+        byte result = OSMemory.peekByte(address + position);
+        ++position;
+        return result;
+    }
+
+    public int readInt() {
+        int result = OSMemory.peekInt(address + position, swap);
+        position += SizeOf.INT;
+        return result;
+    }
+
+    public void readIntArray(int[] dst, int dstOffset, int intCount) {
+        OSMemory.peekIntArray(address + position, dst, dstOffset, intCount, swap);
+        position += SizeOf.INT * intCount;
+    }
+
+    public short readShort() {
+        short result = OSMemory.peekShort(address + position, swap);
+        position += SizeOf.SHORT;
+        return result;
+    }
+}
diff --git a/luni/src/test/java/com/google/coretests/Version.java b/luni/src/main/java/libcore/io/SizeOf.java
similarity index 61%
rename from luni/src/test/java/com/google/coretests/Version.java
rename to luni/src/main/java/libcore/io/SizeOf.java
index e76a6bb..728fbfc 100644
--- a/luni/src/test/java/com/google/coretests/Version.java
+++ b/luni/src/main/java/libcore/io/SizeOf.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2008 The Android Open Source Project
+ * 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.
@@ -14,17 +14,16 @@
  * limitations under the License.
  */
 
-package com.google.coretests;
+package libcore.io;
 
-/**
- * This class defines the current version of JUnit
- */
-public class Version {
-    private Version() {
-        // don't instantiate
-    }
+public final class SizeOf {
+    public static final int CHAR = 2;
+    public static final int DOUBLE = 8;
+    public static final int FLOAT = 4;
+    public static final int INT = 4;
+    public static final int LONG = 8;
+    public static final int SHORT = 2;
 
-    public static String id() {
-        return "0.1";
+    private SizeOf() {
     }
 }
diff --git a/luni/src/main/java/org/apache/harmony/luni/internal/net/www/protocol/ftp/FtpURLInputStream.java b/luni/src/main/java/org/apache/harmony/luni/internal/net/www/protocol/ftp/FtpURLInputStream.java
index 65fb258..bd05219 100644
--- a/luni/src/main/java/org/apache/harmony/luni/internal/net/www/protocol/ftp/FtpURLInputStream.java
+++ b/luni/src/main/java/org/apache/harmony/luni/internal/net/www/protocol/ftp/FtpURLInputStream.java
@@ -20,6 +20,7 @@
 import java.io.IOException;
 import java.io.InputStream;
 import java.net.Socket;
+import libcore.io.IoUtils;
 
 /**
  * This class associates a given inputStream with a control socket. This ensures
@@ -63,16 +64,8 @@
 
     @Override
     public void close() {
-        try {
-            is.close();
-        } catch (Exception e) {
-            // ignored
-        }
-        try {
-            controlSocket.close();
-        } catch (Exception e) {
-            // ignored
-        }
+        IoUtils.closeQuietly(is);
+        IoUtils.closeQuietly(controlSocket);
     }
 
     @Override
diff --git a/luni/src/main/java/org/apache/harmony/luni/internal/net/www/protocol/http/AbstractHttpInputStream.java b/luni/src/main/java/org/apache/harmony/luni/internal/net/www/protocol/http/AbstractHttpInputStream.java
index 7219bbe..2a24fa8 100644
--- a/luni/src/main/java/org/apache/harmony/luni/internal/net/www/protocol/http/AbstractHttpInputStream.java
+++ b/luni/src/main/java/org/apache/harmony/luni/internal/net/www/protocol/http/AbstractHttpInputStream.java
@@ -37,7 +37,6 @@
     protected final CacheRequest cacheRequest;
     protected final OutputStream cacheOut;
     protected boolean closed;
-    private byte[] skipBuffer;
 
     AbstractHttpInputStream(InputStream in, HttpURLConnectionImpl httpURLConnection,
             CacheRequest cacheRequest) throws IOException {
@@ -57,26 +56,6 @@
         return count == -1 ? -1 : buffer[0] & 0xff;
     }
 
-    /**
-     * skip(long) is implemented using read(byte[], int, int) so subclasses
-     * only need to override the latter.
-     */
-    @Override public final long skip(long n) throws IOException {
-        if (skipBuffer == null) {
-            skipBuffer = new byte[4096];
-        }
-        long total = 0;
-        while (total < n) {
-            // Calling read() ensures the skipped bytes make it into the response cache.
-            int count = read(skipBuffer, 0, (int) Math.min(n - total, skipBuffer.length));
-            if (count == -1) {
-                break;
-            }
-            total += count;
-        }
-        return total;
-    }
-
     protected final void checkBounds(byte[] buffer, int offset, int count) {
         if (offset < 0 || offset > buffer.length || count < 0 || buffer.length - offset < count) {
             throw new ArrayIndexOutOfBoundsException(
diff --git a/luni/src/main/java/org/apache/harmony/luni/internal/net/www/protocol/http/HttpConnection.java b/luni/src/main/java/org/apache/harmony/luni/internal/net/www/protocol/http/HttpConnection.java
index 2158452..816c75c 100644
--- a/luni/src/main/java/org/apache/harmony/luni/internal/net/www/protocol/http/HttpConnection.java
+++ b/luni/src/main/java/org/apache/harmony/luni/internal/net/www/protocol/http/HttpConnection.java
@@ -18,7 +18,6 @@
 package org.apache.harmony.luni.internal.net.www.protocol.http;
 
 import java.io.BufferedInputStream;
-import java.io.Closeable;
 import java.io.IOException;
 import java.io.InputStream;
 import java.io.OutputStream;
@@ -34,6 +33,7 @@
 import javax.net.ssl.SSLSocket;
 import javax.net.ssl.SSLSocketFactory;
 import libcore.base.Objects;
+import libcore.io.IoUtils;
 import org.apache.harmony.xnet.provider.jsse.OpenSSLSocketImpl;
 
 /**
@@ -85,30 +85,12 @@
     }
 
     public void closeSocketAndStreams() {
-        closeQuietly(sslOutputStream);
-        closeQuietly(sslInputStream);
-        closeQuietly(sslSocket);
-        closeQuietly(outputStream);
-        closeQuietly(inputStream);
-        closeQuietly(socket);
-    }
-
-    private void closeQuietly(Socket socket) {
-        if (socket != null) {
-            try {
-                socket.close();
-            } catch (Exception ignored) {
-            }
-        }
-    }
-
-    private void closeQuietly(Closeable closeable) {
-        if (closeable != null) {
-            try {
-                closeable.close();
-            } catch (Exception ignored) {
-            }
-        }
+        IoUtils.closeQuietly(sslOutputStream);
+        IoUtils.closeQuietly(sslInputStream);
+        IoUtils.closeQuietly(sslSocket);
+        IoUtils.closeQuietly(outputStream);
+        IoUtils.closeQuietly(inputStream);
+        IoUtils.closeQuietly(socket);
     }
 
     public void setSoTimeout(int readTimeout) throws SocketException {
diff --git a/luni/src/main/java/org/apache/harmony/luni/internal/net/www/protocol/http/RetryableOutputStream.java b/luni/src/main/java/org/apache/harmony/luni/internal/net/www/protocol/http/RetryableOutputStream.java
index d02f5a4..efb8eeb 100644
--- a/luni/src/main/java/org/apache/harmony/luni/internal/net/www/protocol/http/RetryableOutputStream.java
+++ b/luni/src/main/java/org/apache/harmony/luni/internal/net/www/protocol/http/RetryableOutputStream.java
@@ -66,8 +66,6 @@
     }
 
     public void writeToSocket(OutputStream socketOut) throws IOException  {
-        close();
         content.writeTo(socketOut);
-        socketOut.flush();
     }
 }
diff --git a/luni/src/main/java/org/apache/harmony/luni/internal/net/www/protocol/jar/JarURLConnectionImpl.java b/luni/src/main/java/org/apache/harmony/luni/internal/net/www/protocol/jar/JarURLConnectionImpl.java
index bc8959b..9864350 100644
--- a/luni/src/main/java/org/apache/harmony/luni/internal/net/www/protocol/jar/JarURLConnectionImpl.java
+++ b/luni/src/main/java/org/apache/harmony/luni/internal/net/www/protocol/jar/JarURLConnectionImpl.java
@@ -380,13 +380,10 @@
     }
 
     private class JarURLConnectionInputStream extends FilterInputStream {
-        InputStream inputStream;
-
-        JarFile jarFile;
+        final JarFile jarFile;
 
         protected JarURLConnectionInputStream(InputStream in, JarFile file) {
             super(in);
-            inputStream = in;
             jarFile = file;
         }
 
@@ -398,20 +395,5 @@
                 jarFile.close();
             }
         }
-
-        @Override
-        public int read() throws IOException {
-            return inputStream.read();
-        }
-
-        @Override
-        public int read(byte[] buf, int off, int nbytes) throws IOException {
-            return inputStream.read(buf, off, nbytes);
-        }
-
-        @Override
-        public long skip(long nbytes) throws IOException {
-            return inputStream.skip(nbytes);
-        }
     }
 }
diff --git a/luni/src/main/java/org/apache/harmony/luni/net/PlainDatagramSocketImpl.java b/luni/src/main/java/org/apache/harmony/luni/net/PlainDatagramSocketImpl.java
index f7e63a4..17d3864 100644
--- a/luni/src/main/java/org/apache/harmony/luni/net/PlainDatagramSocketImpl.java
+++ b/luni/src/main/java/org/apache/harmony/luni/net/PlainDatagramSocketImpl.java
@@ -17,6 +17,7 @@
 
 package org.apache.harmony.luni.net;
 
+import dalvik.system.CloseGuard;
 import java.io.FileDescriptor;
 import java.io.IOException;
 import java.net.DatagramPacket;
@@ -46,6 +47,8 @@
 
     private volatile boolean isNativeConnected;
 
+    private final CloseGuard guard = CloseGuard.get();
+
     /**
      * used to keep address to which the socket was connected to at the native
      * level
@@ -58,6 +61,9 @@
         super();
         this.fd = fd;
         this.localPort = localPort;
+        if (fd.valid()) {
+            guard.open("close");
+        }
     }
 
     public PlainDatagramSocketImpl() {
@@ -82,6 +88,7 @@
 
     @Override
     public synchronized void close() {
+        guard.close();
         try {
             Platform.NETWORK.close(fd);
         } catch (IOException ignored) {
@@ -95,6 +102,9 @@
 
     @Override protected void finalize() throws Throwable {
         try {
+            if (guard != null) {
+                guard.warnIfOpen();
+            }
             close();
         } finally {
             super.finalize();
@@ -174,7 +184,8 @@
     public void send(DatagramPacket packet) throws IOException {
         int port = isNativeConnected ? 0 : packet.getPort();
         InetAddress address = isNativeConnected ? null : packet.getAddress();
-        Platform.NETWORK.send(fd, packet.getData(), packet.getOffset(), packet.getLength(), port, address);
+        Platform.NETWORK.send(fd, packet.getData(), packet.getOffset(), packet.getLength(),
+                              port, address);
     }
 
     public void setOption(int optID, Object val) throws SocketException {
diff --git a/luni/src/main/java/org/apache/harmony/luni/net/PlainSocketImpl.java b/luni/src/main/java/org/apache/harmony/luni/net/PlainSocketImpl.java
index a0ae907..dd34cbc 100644
--- a/luni/src/main/java/org/apache/harmony/luni/net/PlainSocketImpl.java
+++ b/luni/src/main/java/org/apache/harmony/luni/net/PlainSocketImpl.java
@@ -17,6 +17,7 @@
 
 package org.apache.harmony.luni.net;
 
+import dalvik.system.CloseGuard;
 import java.io.FileDescriptor;
 import java.io.IOException;
 import java.io.InputStream;
@@ -54,8 +55,13 @@
 
     private Proxy proxy;
 
+    private final CloseGuard guard = CloseGuard.get();
+
     public PlainSocketImpl(FileDescriptor fd) {
         this.fd = fd;
+        if (fd.valid()) {
+            guard.open("close");
+        }
     }
 
     public PlainSocketImpl(Proxy proxy) {
@@ -73,6 +79,9 @@
         this.localport = localport;
         this.address = addr;
         this.port = port;
+        if (fd.valid()) {
+            guard.open("close");
+        }
     }
 
     @Override
@@ -162,6 +171,7 @@
 
     @Override
     protected synchronized void close() throws IOException {
+        guard.close();
         Platform.NETWORK.close(fd);
     }
 
@@ -210,6 +220,9 @@
 
     @Override protected void finalize() throws Throwable {
         try {
+            if (guard != null) {
+                guard.warnIfOpen();
+            }
             close();
         } finally {
             super.finalize();
diff --git a/luni/src/main/java/org/apache/harmony/luni/net/SocketInputStream.java b/luni/src/main/java/org/apache/harmony/luni/net/SocketInputStream.java
index a78fb0e..e49bab5 100644
--- a/luni/src/main/java/org/apache/harmony/luni/net/SocketInputStream.java
+++ b/luni/src/main/java/org/apache/harmony/luni/net/SocketInputStream.java
@@ -84,9 +84,4 @@
 
         return socket.read(buffer, offset, count);
     }
-
-    @Override
-    public long skip(long n) throws IOException {
-        return (0 == n) ? 0 : super.skip(n);
-    }
 }
diff --git a/luni/src/main/java/org/apache/harmony/luni/platform/OSMemory.java b/luni/src/main/java/org/apache/harmony/luni/platform/OSMemory.java
index c9d9cc0..edc0a63 100644
--- a/luni/src/main/java/org/apache/harmony/luni/platform/OSMemory.java
+++ b/luni/src/main/java/org/apache/harmony/luni/platform/OSMemory.java
@@ -43,6 +43,102 @@
     public static native void unsafeBulkPut(byte[] dst, int dstOffset, int byteCount,
             Object src, int srcOffset, int sizeofElements, boolean swap);
 
+    public static int peekInt(byte[] src, int offset, ByteOrder order) {
+        if (order == ByteOrder.BIG_ENDIAN) {
+            return (((src[offset++] & 0xff) << 24) |
+                    ((src[offset++] & 0xff) << 16) |
+                    ((src[offset++] & 0xff) <<  8) |
+                    ((src[offset  ] & 0xff) <<  0));
+        } else {
+            return (((src[offset++] & 0xff) <<  0) |
+                    ((src[offset++] & 0xff) <<  8) |
+                    ((src[offset++] & 0xff) << 16) |
+                    ((src[offset  ] & 0xff) << 24));
+        }
+    }
+
+    public static long peekLong(byte[] src, int offset, ByteOrder order) {
+        if (order == ByteOrder.BIG_ENDIAN) {
+            int h = ((src[offset++] & 0xff) << 24) |
+                    ((src[offset++] & 0xff) << 16) |
+                    ((src[offset++] & 0xff) <<  8) |
+                    ((src[offset++] & 0xff) <<  0);
+            int l = ((src[offset++] & 0xff) << 24) |
+                    ((src[offset++] & 0xff) << 16) |
+                    ((src[offset++] & 0xff) <<  8) |
+                    ((src[offset  ] & 0xff) <<  0);
+            return (((long) h) << 32L) | ((long) l) & 0xffffffffL;
+        } else {
+            int l = ((src[offset++] & 0xff) <<  0) |
+                    ((src[offset++] & 0xff) <<  8) |
+                    ((src[offset++] & 0xff) << 16) |
+                    ((src[offset++] & 0xff) << 24);
+            int h = ((src[offset++] & 0xff) <<  0) |
+                    ((src[offset++] & 0xff) <<  8) |
+                    ((src[offset++] & 0xff) << 16) |
+                    ((src[offset  ] & 0xff) << 24);
+            return (((long) h) << 32L) | ((long) l) & 0xffffffffL;
+        }
+    }
+
+    public static short peekShort(byte[] src, int offset, ByteOrder order) {
+        if (order == ByteOrder.BIG_ENDIAN) {
+            return (short) ((src[offset] << 8) | (src[offset + 1] & 0xff));
+        } else {
+            return (short) ((src[offset + 1] << 8) | (src[offset] & 0xff));
+        }
+    }
+
+    public static void pokeInt(byte[] dst, int offset, int value, ByteOrder order) {
+        if (order == ByteOrder.BIG_ENDIAN) {
+            dst[offset++] = (byte) ((value >> 24) & 0xff);
+            dst[offset++] = (byte) ((value >> 16) & 0xff);
+            dst[offset++] = (byte) ((value >>  8) & 0xff);
+            dst[offset  ] = (byte) ((value >>  0) & 0xff);
+        } else {
+            dst[offset++] = (byte) ((value >>  0) & 0xff);
+            dst[offset++] = (byte) ((value >>  8) & 0xff);
+            dst[offset++] = (byte) ((value >> 16) & 0xff);
+            dst[offset  ] = (byte) ((value >> 24) & 0xff);
+        }
+    }
+
+    public static void pokeLong(byte[] dst, int offset, long value, ByteOrder order) {
+        if (order == ByteOrder.BIG_ENDIAN) {
+            int i = (int) (value >> 32);
+            dst[offset++] = (byte) ((i >> 24) & 0xff);
+            dst[offset++] = (byte) ((i >> 16) & 0xff);
+            dst[offset++] = (byte) ((i >>  8) & 0xff);
+            dst[offset++] = (byte) ((i >>  0) & 0xff);
+            i = (int) value;
+            dst[offset++] = (byte) ((i >> 24) & 0xff);
+            dst[offset++] = (byte) ((i >> 16) & 0xff);
+            dst[offset++] = (byte) ((i >>  8) & 0xff);
+            dst[offset  ] = (byte) ((i >>  0) & 0xff);
+        } else {
+            int i = (int) value;
+            dst[offset++] = (byte) ((i >>  0) & 0xff);
+            dst[offset++] = (byte) ((i >>  8) & 0xff);
+            dst[offset++] = (byte) ((i >> 16) & 0xff);
+            dst[offset++] = (byte) ((i >> 24) & 0xff);
+            i = (int) (value >> 32);
+            dst[offset++] = (byte) ((i >>  0) & 0xff);
+            dst[offset++] = (byte) ((i >>  8) & 0xff);
+            dst[offset++] = (byte) ((i >> 16) & 0xff);
+            dst[offset  ] = (byte) ((i >> 24) & 0xff);
+        }
+    }
+
+    public static void pokeShort(byte[] dst, int offset, short value, ByteOrder order) {
+        if (order == ByteOrder.BIG_ENDIAN) {
+            dst[offset++] = (byte) ((value >> 8) & 0xff);
+            dst[offset  ] = (byte) ((value >> 0) & 0xff);
+        } else {
+            dst[offset++] = (byte) ((value >> 0) & 0xff);
+            dst[offset  ] = (byte) ((value >> 8) & 0xff);
+        }
+    }
+
     /**
      * Returns the address of byteCount bytes of memory. Unlike the corresponding C library
      * function, the memory returned has been zero-initialized.
diff --git a/luni/src/main/java/org/apache/harmony/luni/util/FloatingPointParser.java b/luni/src/main/java/org/apache/harmony/luni/util/FloatingPointParser.java
index d383f9d..630436e 100644
--- a/luni/src/main/java/org/apache/harmony/luni/util/FloatingPointParser.java
+++ b/luni/src/main/java/org/apache/harmony/luni/util/FloatingPointParser.java
@@ -24,153 +24,163 @@
  */
 public final class FloatingPointParser {
 
-	private static final class StringExponentPair {
-		String s;
+    private static final class StringExponentPair {
+        String s;
 
-		int e;
+        int e;
 
-		boolean negative;
+        boolean negative;
 
-		StringExponentPair(String s, int e, boolean negative) {
-			this.s = s;
-			this.e = e;
-			this.negative = negative;
-		}
-	}
+        StringExponentPair(String s, int e, boolean negative) {
+            this.s = s;
+            this.e = e;
+            this.negative = negative;
+        }
+    }
 
-	/**
-	 * Takes a String and an integer exponent. The String should hold a positive
-	 * integer value (or zero). The exponent will be used to calculate the
-	 * floating point number by taking the positive integer the String
-	 * represents and multiplying by 10 raised to the power of the of the
-	 * exponent. Returns the closest double value to the real number
-	 *
-	 * @param s
-	 *            the String that will be parsed to a floating point
-	 * @param e
-	 *            an int represent the 10 to part
-	 * @return the double closest to the real number
-	 *
-	 * @exception NumberFormatException
-	 *                if the String doesn't represent a positive integer value
-	 */
-	private static native double parseDblImpl(String s, int e);
+    /**
+     * Takes a String and an integer exponent. The String should hold a positive
+     * integer value (or zero). The exponent will be used to calculate the
+     * floating point number by taking the positive integer the String
+     * represents and multiplying by 10 raised to the power of the of the
+     * exponent. Returns the closest double value to the real number
+     *
+     * @param s
+     *            the String that will be parsed to a floating point
+     * @param e
+     *            an int represent the 10 to part
+     * @return the double closest to the real number
+     *
+     * @exception NumberFormatException
+     *                if the String doesn't represent a positive integer value
+     */
+    private static native double parseDblImpl(String s, int e);
 
-	/**
-	 * Takes a String and an integer exponent. The String should hold a positive
-	 * integer value (or zero). The exponent will be used to calculate the
-	 * floating point number by taking the positive integer the String
-	 * represents and multiplying by 10 raised to the power of the of the
-	 * exponent. Returns the closest float value to the real number
-	 *
-	 * @param s
-	 *            the String that will be parsed to a floating point
-	 * @param e
-	 *            an int represent the 10 to part
-	 * @return the float closest to the real number
-	 *
-	 * @exception NumberFormatException
-	 *                if the String doesn't represent a positive integer value
-	 */
-	private static native float parseFltImpl(String s, int e);
+    /**
+     * Takes a String and an integer exponent. The String should hold a positive
+     * integer value (or zero). The exponent will be used to calculate the
+     * floating point number by taking the positive integer the String
+     * represents and multiplying by 10 raised to the power of the of the
+     * exponent. Returns the closest float value to the real number
+     *
+     * @param s
+     *            the String that will be parsed to a floating point
+     * @param e
+     *            an int represent the 10 to part
+     * @return the float closest to the real number
+     *
+     * @exception NumberFormatException
+     *                if the String doesn't represent a positive integer value
+     */
+    private static native float parseFltImpl(String s, int e);
 
-	/**
-	 * Takes a String and does some initial parsing. Should return a
-	 * StringExponentPair containing a String with no leading or trailing white
-	 * space and trailing zeroes eliminated. The exponent of the
-	 * StringExponentPair will be used to calculate the floating point number by
-	 * taking the positive integer the String represents and multiplying by 10
-	 * raised to the power of the of the exponent.
-	 *
-	 * @param s
-	 *            the String that will be parsed to a floating point
-	 * @param length
-	 *            the length of s
-	 * @return a StringExponentPair with necessary values
-	 *
-	 * @exception NumberFormatException
-	 *                if the String doesn't pass basic tests
-	 */
-	private static StringExponentPair initialParse(String s, int length) {
-		boolean negative = false;
-		char c;
-		int start, end, decimal;
-		int e = 0;
+    private static NumberFormatException invalidReal(String s, boolean isDouble) {
+        throw new NumberFormatException("Invalid " + (isDouble ? "double" : "float") + ": \"" + s + "\"");
+    }
 
-		start = 0;
-		if (length == 0)
-			throw new NumberFormatException(s);
+    /**
+     * Takes a String and does some initial parsing. Should return a
+     * StringExponentPair containing a String with no leading or trailing white
+     * space and trailing zeroes eliminated. The exponent of the
+     * StringExponentPair will be used to calculate the floating point number by
+     * taking the positive integer the String represents and multiplying by 10
+     * raised to the power of the of the exponent.
+     *
+     * @param s
+     *            the String that will be parsed to a floating point
+     * @param length
+     *            the length of s
+     * @return a StringExponentPair with necessary values
+     *
+     * @exception NumberFormatException
+     *                if the String doesn't pass basic tests
+     */
+    private static StringExponentPair initialParse(String s, int length, boolean isDouble) {
+        boolean negative = false;
+        char c;
+        int start, end, decimal;
+        int e = 0;
 
-		c = s.charAt(length - 1);
-		if (c == 'D' || c == 'd' || c == 'F' || c == 'f') {
-			length--;
-			if (length == 0)
-				throw new NumberFormatException(s);
-		}
+        start = 0;
+        if (length == 0) {
+            throw invalidReal(s, isDouble);
+        }
+        c = s.charAt(length - 1);
+        if (c == 'D' || c == 'd' || c == 'F' || c == 'f') {
+            length--;
+            if (length == 0) {
+                throw invalidReal(s, isDouble);
+            }
+        }
 
-		end = Math.max(s.indexOf('E'), s.indexOf('e'));
-		if (end > -1) {
-			if (end + 1 == length)
-				throw new NumberFormatException(s);
+        end = Math.max(s.indexOf('E'), s.indexOf('e'));
+        if (end > -1) {
+            if (end + 1 == length) {
+                throw invalidReal(s, isDouble);
+            }
 
-                        int exponent_offset = end + 1;
-                        if (s.charAt(exponent_offset) == '+') {
-                                if (s.charAt(exponent_offset + 1) == '-') {
-                                        throw new NumberFormatException(s);
-                                }
-                                exponent_offset++; // skip the plus sign
-                        }
-			try {
-				e = Integer.parseInt(s.substring(exponent_offset,
-                                                                 length));
-                        } catch (NumberFormatException ex) {
-                                // ex contains the exponent substring
-                                // only so throw a new exception with
-                                // the correct string
-				throw new NumberFormatException(s);
-                        }
+            int exponent_offset = end + 1;
+            if (s.charAt(exponent_offset) == '+') {
+                if (s.charAt(exponent_offset + 1) == '-') {
+                    throw invalidReal(s, isDouble);
+                }
+                exponent_offset++; // skip the plus sign
+            }
+            try {
+                e = Integer.parseInt(s.substring(exponent_offset, length));
+            } catch (NumberFormatException ex) {
+                // ex contains the exponent substring
+                // only so throw a new exception with
+                // the correct string
+                throw invalidReal(s, isDouble);
+            }
 
-		} else {
-			end = length;
-		}
-		if (length == 0)
-			throw new NumberFormatException(s);
+        } else {
+            end = length;
+        }
+        if (length == 0) {
+            throw invalidReal(s, isDouble);
+        }
 
-		c = s.charAt(start);
-		if (c == '-') {
-			++start;
-			--length;
-			negative = true;
-		} else if (c == '+') {
-			++start;
-			--length;
-		}
-		if (length == 0)
-			throw new NumberFormatException(s);
+        c = s.charAt(start);
+        if (c == '-') {
+            ++start;
+            --length;
+            negative = true;
+        } else if (c == '+') {
+            ++start;
+            --length;
+        }
+        if (length == 0) {
+            throw invalidReal(s, isDouble);
+        }
 
-		decimal = s.indexOf('.');
-		if (decimal > -1) {
-			e -= end - decimal - 1;
-			s = s.substring(start, decimal) + s.substring(decimal + 1, end);
-		} else {
-			s = s.substring(start, end);
-		}
+        decimal = s.indexOf('.');
+        if (decimal > -1) {
+            e -= end - decimal - 1;
+            s = s.substring(start, decimal) + s.substring(decimal + 1, end);
+        } else {
+            s = s.substring(start, end);
+        }
 
-		if ((length = s.length()) == 0)
-			throw new NumberFormatException();
+        if ((length = s.length()) == 0) {
+            throw invalidReal(s, isDouble);
+        }
 
-		end = length;
-		while (end > 1 && s.charAt(end - 1) == '0')
-			--end;
+        end = length;
+        while (end > 1 && s.charAt(end - 1) == '0') {
+            --end;
+        }
 
-		start = 0;
-		while (start < end - 1 && s.charAt(start) == '0')
-			start++;
+        start = 0;
+        while (start < end - 1 && s.charAt(start) == '0') {
+            start++;
+        }
 
-		if (end != length || start != 0) {
-			e += length - end;
-			s = s.substring(start, end);
-		}
+        if (end != length || start != 0) {
+            e += length - end;
+            s = s.substring(start, end);
+        }
 
         // Trim the length of very small numbers, natives can only handle down
         // to E-309
@@ -183,145 +193,149 @@
             e += d;
         }
 
-		return new StringExponentPair(s, e, negative);
-	}
+        return new StringExponentPair(s, e, negative);
+    }
 
-	/*
-	 * Assumes the string is trimmed.
-	 */
-	private static double parseDblName(String namedDouble, int length) {
-		// Valid strings are only +Nan, NaN, -Nan, +Infinity, Infinity,
-		// -Infinity.
-		if ((length != 3) && (length != 4) && (length != 8) && (length != 9)) {
-			throw new NumberFormatException();
-		}
+    /*
+     * Assumes the string is trimmed.
+     */
+    private static double parseDblName(String namedDouble, int length) {
+        // Valid strings are only +Nan, NaN, -Nan, +Infinity, Infinity,
+        // -Infinity.
+        if ((length != 3) && (length != 4) && (length != 8) && (length != 9)) {
+            throw invalidReal(namedDouble, true);
+        }
 
-		boolean negative = false;
-		int cmpstart = 0;
-		switch (namedDouble.charAt(0)) {
-		case '-':
-			negative = true; // fall through
-		case '+':
-			cmpstart = 1;
-		default:
-		}
+        boolean negative = false;
+        int cmpstart = 0;
+        switch (namedDouble.charAt(0)) {
+        case '-':
+            negative = true; // fall through
+        case '+':
+            cmpstart = 1;
+        default:
+        }
 
-		if (namedDouble.regionMatches(false, cmpstart, "Infinity", 0, 8)) {
-			return negative ? Double.NEGATIVE_INFINITY
-					: Float.POSITIVE_INFINITY;
-		}
+        if (namedDouble.regionMatches(false, cmpstart, "Infinity", 0, 8)) {
+            return negative ? Double.NEGATIVE_INFINITY : Float.POSITIVE_INFINITY;
+        }
 
-		if (namedDouble.regionMatches(false, cmpstart, "NaN", 0, 3)) {
-			return Double.NaN;
-		}
+        if (namedDouble.regionMatches(false, cmpstart, "NaN", 0, 3)) {
+            return Double.NaN;
+        }
 
-		throw new NumberFormatException();
-	}
+        throw invalidReal(namedDouble, true);
+    }
 
-	/*
-	 * Assumes the string is trimmed.
-	 */
-	private static float parseFltName(String namedFloat, int length) {
-		// Valid strings are only +Nan, NaN, -Nan, +Infinity, Infinity,
-		// -Infinity.
-		if ((length != 3) && (length != 4) && (length != 8) && (length != 9)) {
-			throw new NumberFormatException();
-		}
+    /*
+     * Assumes the string is trimmed.
+     */
+    private static float parseFltName(String namedFloat, int length) {
+        // Valid strings are only +Nan, NaN, -Nan, +Infinity, Infinity,
+        // -Infinity.
+        if ((length != 3) && (length != 4) && (length != 8) && (length != 9)) {
+            throw invalidReal(namedFloat, false);
+        }
 
-		boolean negative = false;
-		int cmpstart = 0;
-		switch (namedFloat.charAt(0)) {
-		case '-':
-			negative = true; // fall through
-		case '+':
-			cmpstart = 1;
-		default:
-		}
+        boolean negative = false;
+        int cmpstart = 0;
+        switch (namedFloat.charAt(0)) {
+        case '-':
+            negative = true; // fall through
+        case '+':
+            cmpstart = 1;
+        default:
+        }
 
-		if (namedFloat.regionMatches(false, cmpstart, "Infinity", 0, 8)) {
-			return negative ? Float.NEGATIVE_INFINITY : Float.POSITIVE_INFINITY;
-		}
+        if (namedFloat.regionMatches(false, cmpstart, "Infinity", 0, 8)) {
+            return negative ? Float.NEGATIVE_INFINITY : Float.POSITIVE_INFINITY;
+        }
 
-		if (namedFloat.regionMatches(false, cmpstart, "NaN", 0, 3)) {
-			return Float.NaN;
-		}
+        if (namedFloat.regionMatches(false, cmpstart, "NaN", 0, 3)) {
+            return Float.NaN;
+        }
 
-		throw new NumberFormatException();
-	}
+        throw invalidReal(namedFloat, false);
+    }
 
-	/**
-	 * Returns the closest double value to the real number in the string.
-	 *
-	 * @param s
-	 *            the String that will be parsed to a floating point
-	 * @return the double closest to the real number
-	 *
-	 * @exception NumberFormatException
-	 *                if the String doesn't represent a double
-	 */
-	public static double parseDouble(String s) {
-		s = s.trim();
-		int length = s.length();
+    /**
+     * Returns the closest double value to the real number in the string.
+     *
+     * @param s
+     *            the String that will be parsed to a floating point
+     * @return the double closest to the real number
+     *
+     * @exception NumberFormatException
+     *                if the String doesn't represent a double
+     */
+    public static double parseDouble(String s) {
+        s = s.trim();
+        int length = s.length();
 
-		if (length == 0) {
-			throw new NumberFormatException(s);
-		}
+        if (length == 0) {
+            throw invalidReal(s, true);
+        }
 
-		// See if this could be a named double
-		char last = s.charAt(length - 1);
-		if ((last == 'y') || (last == 'N')) {
-			return parseDblName(s, length);
-		}
+        // See if this could be a named double
+        char last = s.charAt(length - 1);
+        if ((last == 'y') || (last == 'N')) {
+            return parseDblName(s, length);
+        }
 
         // See if it could be a hexadecimal representation
         if (s.toLowerCase().indexOf("0x") != -1) {
             return HexStringParser.parseDouble(s);
         }
 
-		StringExponentPair info = initialParse(s, length);
+        StringExponentPair info = initialParse(s, length, true);
 
-		double result = parseDblImpl(info.s, info.e);
-		if (info.negative)
-			result = -result;
+        double result = parseDblImpl(info.s, info.e);
+        if (Double.doubleToRawLongBits(result) == 0xffffffffffffffffL) {
+            throw invalidReal(s, true);
+        }
+        if (info.negative) {
+            result = -result;
+        }
+        return result;
+    }
 
-		return result;
-	}
+    /**
+     * Returns the closest float value to the real number in the string.
+     *
+     * @param s
+     *            the String that will be parsed to a floating point
+     * @return the float closest to the real number
+     *
+     * @exception NumberFormatException
+     *                if the String doesn't represent a float
+     */
+    public static float parseFloat(String s) {
+        s = s.trim();
+        int length = s.length();
 
-	/**
-	 * Returns the closest float value to the real number in the string.
-	 *
-	 * @param s
-	 *            the String that will be parsed to a floating point
-	 * @return the float closest to the real number
-	 *
-	 * @exception NumberFormatException
-	 *                if the String doesn't represent a float
-	 */
-	public static float parseFloat(String s) {
-		s = s.trim();
-		int length = s.length();
+        if (length == 0) {
+            throw invalidReal(s, false);
+        }
 
-		if (length == 0) {
-			throw new NumberFormatException(s);
-		}
-
-		// See if this could be a named float
-		char last = s.charAt(length - 1);
-		if ((last == 'y') || (last == 'N')) {
-			return parseFltName(s, length);
-		}
+        // See if this could be a named float
+        char last = s.charAt(length - 1);
+        if ((last == 'y') || (last == 'N')) {
+            return parseFltName(s, length);
+        }
 
         // See if it could be a hexadecimal representation
         if (s.toLowerCase().indexOf("0x") != -1) {
             return HexStringParser.parseFloat(s);
         }
 
-		StringExponentPair info = initialParse(s, length);
-
-		float result = parseFltImpl(info.s, info.e);
-		if (info.negative)
-			result = -result;
-
-		return result;
-	}
+        StringExponentPair info = initialParse(s, length, false);
+        float result = parseFltImpl(info.s, info.e);
+        if (Float.floatToRawIntBits(result) == 0xffffffff) {
+            throw invalidReal(s, false);
+        }
+        if (info.negative) {
+            result = -result;
+        }
+        return result;
+    }
 }
diff --git a/luni/src/main/java/org/apache/harmony/luni/util/HexStringParser.java b/luni/src/main/java/org/apache/harmony/luni/util/HexStringParser.java
index b37a498..8a9d148 100644
--- a/luni/src/main/java/org/apache/harmony/luni/util/HexStringParser.java
+++ b/luni/src/main/java/org/apache/harmony/luni/util/HexStringParser.java
@@ -82,9 +82,8 @@
      * Parses the hex string to a double number.
      */
     public static double parseDouble(String hexString) {
-        HexStringParser parser = new HexStringParser(DOUBLE_EXPONENT_WIDTH,
-                DOUBLE_MANTISSA_WIDTH);
-        long result = parser.parse(hexString);
+        HexStringParser parser = new HexStringParser(DOUBLE_EXPONENT_WIDTH, DOUBLE_MANTISSA_WIDTH);
+        long result = parser.parse(hexString, true);
         return Double.longBitsToDouble(result);
     }
 
@@ -92,17 +91,21 @@
      * Parses the hex string to a float number.
      */
     public static float parseFloat(String hexString) {
-        HexStringParser parser = new HexStringParser(FLOAT_EXPONENT_WIDTH,
-                FLOAT_MANTISSA_WIDTH);
-        int result = (int) parser.parse(hexString);
+        HexStringParser parser = new HexStringParser(FLOAT_EXPONENT_WIDTH, FLOAT_MANTISSA_WIDTH);
+        int result = (int) parser.parse(hexString, false);
         return Float.intBitsToFloat(result);
     }
 
-    private long parse(String hexString) {
-        String[] hexSegments = getSegmentsFromHexString(hexString);
-        String signStr = hexSegments[0];
-        String significantStr = hexSegments[1];
-        String exponentStr = hexSegments[2];
+    private long parse(String hexString, boolean isDouble) {
+        Matcher matcher = PATTERN.matcher(hexString);
+        if (!matcher.matches()) {
+            throw new NumberFormatException("Invalid hex " + (isDouble ? "double" : "float")+ ":" +
+                    hexString);
+        }
+
+        String signStr = matcher.group(1);
+        String significantStr = matcher.group(2);
+        String exponentStr = matcher.group(3);
 
         parseHexSign(signStr);
         parseExponent(exponentStr);
@@ -114,23 +117,6 @@
     }
 
     /*
-     * Analyzes the hex string and extracts the sign and digit segments.
-     */
-    private static String[] getSegmentsFromHexString(String hexString) {
-        Matcher matcher = PATTERN.matcher(hexString);
-        if (!matcher.matches()) {
-            throw new NumberFormatException();
-        }
-
-        String[] hexSegments = new String[3];
-        hexSegments[0] = matcher.group(1);
-        hexSegments[1] = matcher.group(2);
-        hexSegments[2] = matcher.group(3);
-
-        return hexSegments;
-    }
-
-    /*
      * Parses the sign field.
      */
     private void parseHexSign(String signStr) {
diff --git a/luni/src/main/java/org/apache/harmony/security/asn1/ASN1Choice.java b/luni/src/main/java/org/apache/harmony/security/asn1/ASN1Choice.java
index b17a4b0..ae719a5 100644
--- a/luni/src/main/java/org/apache/harmony/security/asn1/ASN1Choice.java
+++ b/luni/src/main/java/org/apache/harmony/security/asn1/ASN1Choice.java
@@ -269,7 +269,7 @@
         Iterator it = map.entrySet().iterator();
 
         for (int i = 0; i < size; i++) {
-        	Map.Entry entry = (Map.Entry) it.next();
+            Map.Entry entry = (Map.Entry) it.next();
             BigInteger identifier = (BigInteger) entry.getKey();
 
             identifiers[0][i] = identifier.intValue();
diff --git a/luni/src/main/java/org/apache/harmony/security/provider/cert/X509CertFactoryImpl.java b/luni/src/main/java/org/apache/harmony/security/provider/cert/X509CertFactoryImpl.java
index 20e5646..0b1f797 100644
--- a/luni/src/main/java/org/apache/harmony/security/provider/cert/X509CertFactoryImpl.java
+++ b/luni/src/main/java/org/apache/harmony/security/provider/cert/X509CertFactoryImpl.java
@@ -860,22 +860,5 @@
                         "position became invalid or stream has not been marked");
             }
         }
-
-        @Override
-        public long skip(long n) throws IOException {
-            if (pos >= 0) {
-                long i = 0;
-                int av = available();
-                if (av < n) {
-                    n = av;
-                }
-                while ((i < n) && (read() != -1)) {
-                    i++;
-                }
-                return i;
-            } else {
-                return inStream.skip(n);
-            }
-        }
     }
 }
diff --git a/luni/src/main/java/org/apache/harmony/security/provider/crypto/DSAPrivateKeyImpl.java b/luni/src/main/java/org/apache/harmony/security/provider/crypto/DSAPrivateKeyImpl.java
index ea26cf8..c0fc766 100644
--- a/luni/src/main/java/org/apache/harmony/security/provider/crypto/DSAPrivateKeyImpl.java
+++ b/luni/src/main/java/org/apache/harmony/security/provider/crypto/DSAPrivateKeyImpl.java
@@ -152,8 +152,8 @@
     }
 
     private void readObject(java.io.ObjectInputStream in) throws NotActiveException, IOException, ClassNotFoundException {
-    	in.defaultReadObject();
-    	params = new DSAParameterSpec(p, q, g);
+        in.defaultReadObject();
+        params = new DSAParameterSpec(p, q, g);
     }
 
 }
diff --git a/luni/src/main/java/org/apache/harmony/security/provider/crypto/DSAPublicKeyImpl.java b/luni/src/main/java/org/apache/harmony/security/provider/crypto/DSAPublicKeyImpl.java
index e4420bd..6b35970 100644
--- a/luni/src/main/java/org/apache/harmony/security/provider/crypto/DSAPublicKeyImpl.java
+++ b/luni/src/main/java/org/apache/harmony/security/provider/crypto/DSAPublicKeyImpl.java
@@ -164,8 +164,8 @@
     }
 
     private void readObject(java.io.ObjectInputStream in) throws NotActiveException, IOException, ClassNotFoundException {
-    	in.defaultReadObject();
-    	params = new DSAParameterSpec(p, q, g);
+        in.defaultReadObject();
+        params = new DSAParameterSpec(p, q, g);
     }
 
 }
diff --git a/luni/src/main/java/org/apache/harmony/security/x501/AttributeTypeAndValueComparator.java b/luni/src/main/java/org/apache/harmony/security/x501/AttributeTypeAndValueComparator.java
index f6a011c..160c62d 100644
--- a/luni/src/main/java/org/apache/harmony/security/x501/AttributeTypeAndValueComparator.java
+++ b/luni/src/main/java/org/apache/harmony/security/x501/AttributeTypeAndValueComparator.java
@@ -32,9 +32,9 @@
  */
 public class AttributeTypeAndValueComparator implements Comparator, Serializable {
 
-	private static final long serialVersionUID = -1286471842007103132L;
+    private static final long serialVersionUID = -1286471842007103132L;
 
-	/**
+    /**
      * compares two AttributeTypeAndValues
      *
      * @param obj1
diff --git a/luni/src/main/java/org/apache/harmony/security/x509/AlgorithmIdentifier.java b/luni/src/main/java/org/apache/harmony/security/x509/AlgorithmIdentifier.java
index eeda86b..9298ba5 100644
--- a/luni/src/main/java/org/apache/harmony/security/x509/AlgorithmIdentifier.java
+++ b/luni/src/main/java/org/apache/harmony/security/x509/AlgorithmIdentifier.java
@@ -143,8 +143,7 @@
     }
 
     public int hashCode() {
-    	return algorithm.hashCode() * 37 +
-    		(parameters != null ? parameters.hashCode() : 0);
+        return algorithm.hashCode() * 37 + (parameters != null ? parameters.hashCode() : 0);
     }
 
     /**
@@ -186,4 +185,3 @@
     };
 
 }
-
diff --git a/luni/src/main/java/org/apache/harmony/security/x509/Extension.java b/luni/src/main/java/org/apache/harmony/security/x509/Extension.java
index b854c60..f30c73f 100644
--- a/luni/src/main/java/org/apache/harmony/security/x509/Extension.java
+++ b/luni/src/main/java/org/apache/harmony/security/x509/Extension.java
@@ -239,7 +239,7 @@
     }
 
     public int hashCode() {
-    	return (extnID.hashCode() * 37 + (critical ? 1 : 0)) * 37 + extnValue.hashCode();
+        return (extnID.hashCode() * 37 + (critical ? 1 : 0)) * 37 + extnValue.hashCode();
     }
 
     public ExtensionValue getDecodedExtensionValue() throws IOException {
@@ -456,4 +456,3 @@
         }
     };
 }
-
diff --git a/luni/src/main/java/org/apache/harmony/security/x509/Extensions.java b/luni/src/main/java/org/apache/harmony/security/x509/Extensions.java
index 2bda81c..5d0603b 100644
--- a/luni/src/main/java/org/apache/harmony/security/x509/Extensions.java
+++ b/luni/src/main/java/org/apache/harmony/security/x509/Extensions.java
@@ -385,11 +385,11 @@
     }
 
     public int hashCode() {
-    	int hashcode = 0;
-    	if (extensions != null) {
-    		hashcode = extensions.hashCode();
-    	}
-    	return hashcode;
+        int hashcode = 0;
+        if (extensions != null) {
+            hashcode = extensions.hashCode();
+        }
+        return hashcode;
     }
 
     /**
@@ -422,4 +422,3 @@
         }
     };
 }
-
diff --git a/luni/src/main/java/org/apache/harmony/security/x509/GeneralName.java b/luni/src/main/java/org/apache/harmony/security/x509/GeneralName.java
index 2a6253b..d52fe89 100644
--- a/luni/src/main/java/org/apache/harmony/security/x509/GeneralName.java
+++ b/luni/src/main/java/org/apache/harmony/security/x509/GeneralName.java
@@ -324,23 +324,23 @@
         return false;
     }
 
-	public int hashCode() {
-		switch(tag) {
-	        case RFC822_NAME:
-	        case DNS_NAME:
-	        case UR_ID:
-	        case REG_ID:
-	        case IP_ADDR:
-	            return name.hashCode();
-	        case DIR_NAME:
-	        case X400_ADDR:
-	        case OTHER_NAME:
-	        case EDIP_NAME:
-	            return getEncoded().hashCode();
-	        default:
-	            return super.hashCode();
-		}
-	}
+    public int hashCode() {
+        switch (tag) {
+        case RFC822_NAME:
+        case DNS_NAME:
+        case UR_ID:
+        case REG_ID:
+        case IP_ADDR:
+            return name.hashCode();
+        case DIR_NAME:
+        case X400_ADDR:
+        case OTHER_NAME:
+        case EDIP_NAME:
+            return getEncoded().hashCode();
+        default:
+            return super.hashCode();
+        }
+    }
 
     /**
      * Checks if the other general name is acceptable by this object.
diff --git a/luni/src/main/java/org/apache/harmony/security/x509/TBSCertList.java b/luni/src/main/java/org/apache/harmony/security/x509/TBSCertList.java
index 4944cba..78b294d 100644
--- a/luni/src/main/java/org/apache/harmony/security/x509/TBSCertList.java
+++ b/luni/src/main/java/org/apache/harmony/security/x509/TBSCertList.java
@@ -153,8 +153,8 @@
         }
 
         public int hashCode() {
-        	return userCertificate.hashCode() * 37 + (int)revocationDate.getTime() / 1000
-        	+ (crlEntryExtensions == null ? 0 : crlEntryExtensions.hashCode());
+            return userCertificate.hashCode() * 37 + (int)revocationDate.getTime() / 1000
+                    + (crlEntryExtensions == null ? 0 : crlEntryExtensions.hashCode());
         }
 
         /**
@@ -363,9 +363,9 @@
     }
 
     public int hashCode() {
-    	return ((version * 37 + signature.hashCode()) * 37
-    		+ issuer.getEncoded().hashCode()) * 37
-    		+ (int)thisUpdate.getTime() / 1000;
+        return ((version * 37 + signature.hashCode()) * 37
+                + issuer.getEncoded().hashCode()) * 37
+                + (int)thisUpdate.getTime() / 1000;
     }
 
     /**
@@ -448,4 +448,3 @@
         }
     };
 }
-
diff --git a/luni/src/main/java/org/apache/harmony/xml/ExpatParser.java b/luni/src/main/java/org/apache/harmony/xml/ExpatParser.java
index 9eb89e9..01b08f2 100644
--- a/luni/src/main/java/org/apache/harmony/xml/ExpatParser.java
+++ b/luni/src/main/java/org/apache/harmony/xml/ExpatParser.java
@@ -24,6 +24,7 @@
 import java.net.URLConnection;
 import java.util.logging.Level;
 import java.util.logging.Logger;
+import libcore.io.IoUtils;
 import org.xml.sax.Attributes;
 import org.xml.sax.ContentHandler;
 import org.xml.sax.DTDHandler;
@@ -348,8 +349,7 @@
                 entityParser.parseFragment(reader);
                 entityParser.append("</externalEntity>");
             } finally {
-                // TODO: Don't eat original exception when close() throws.
-                reader.close();
+                IoUtils.closeQuietly(reader);
             }
             return;
         }
@@ -364,8 +364,7 @@
                 entityParser.append("</externalEntity>"
                         .getBytes(entityParser.encoding));
             } finally {
-                // TODO: Don't eat original exception when close() throws.
-                in.close();
+                IoUtils.closeQuietly(in);
             }
             return;
         }
@@ -386,7 +385,7 @@
             entityParser.append("</externalEntity>"
                     .getBytes(entityParser.encoding));
         } finally {
-            in.close();
+            IoUtils.closeQuietly(in);
         }
     }
 
diff --git a/luni/src/main/java/org/apache/harmony/xml/ExpatReader.java b/luni/src/main/java/org/apache/harmony/xml/ExpatReader.java
index db2b428..972f3ed 100644
--- a/luni/src/main/java/org/apache/harmony/xml/ExpatReader.java
+++ b/luni/src/main/java/org/apache/harmony/xml/ExpatReader.java
@@ -19,6 +19,7 @@
 import java.io.IOException;
 import java.io.InputStream;
 import java.io.Reader;
+import libcore.io.IoUtils;
 import org.xml.sax.ContentHandler;
 import org.xml.sax.DTDHandler;
 import org.xml.sax.EntityResolver;
@@ -261,8 +262,7 @@
             try {
                 parse(reader, input.getPublicId(), input.getSystemId());
             } finally {
-                // TODO: Don't eat original exception when close() throws.
-                reader.close();
+                IoUtils.closeQuietly(reader);
             }
             return;
         }
@@ -274,8 +274,7 @@
             try {
                 parse(in, encoding, input.getPublicId(), input.getSystemId());
             } finally {
-                // TODO: Don't eat original exception when close() throws.
-                in.close();
+                IoUtils.closeQuietly(in);
             }
             return;
         }
@@ -290,7 +289,7 @@
         try {
             parse(in, encoding, input.getPublicId(), systemId);
         } finally {
-            in.close();
+            IoUtils.closeQuietly(in);
         }
     }
 
diff --git a/luni/src/main/java/org/apache/harmony/xnet/provider/jsse/FileClientSessionCache.java b/luni/src/main/java/org/apache/harmony/xnet/provider/jsse/FileClientSessionCache.java
index 31ec396..f6c989f 100644
--- a/luni/src/main/java/org/apache/harmony/xnet/provider/jsse/FileClientSessionCache.java
+++ b/luni/src/main/java/org/apache/harmony/xnet/provider/jsse/FileClientSessionCache.java
@@ -31,6 +31,7 @@
 import java.util.TreeSet;
 import java.util.logging.Level;
 import javax.net.ssl.SSLSession;
+import libcore.io.IoUtils;
 
 /**
  * File-based cache implementation. Only one process should access the
@@ -172,9 +173,7 @@
                 logReadError(host, e);
                 return null;
             } finally {
-                try {
-                    in.close();
-                } catch (IOException e) { /* ignore */ }
+                IoUtils.closeQuietly(in);
             }
         }
 
diff --git a/luni/src/main/java/org/apache/harmony/xnet/provider/jsse/OpenSSLSocketImpl.java b/luni/src/main/java/org/apache/harmony/xnet/provider/jsse/OpenSSLSocketImpl.java
index 819b95a..ca7eed3 100644
--- a/luni/src/main/java/org/apache/harmony/xnet/provider/jsse/OpenSSLSocketImpl.java
+++ b/luni/src/main/java/org/apache/harmony/xnet/provider/jsse/OpenSSLSocketImpl.java
@@ -17,6 +17,7 @@
 package org.apache.harmony.xnet.provider.jsse;
 
 import dalvik.system.BlockGuard;
+import dalvik.system.CloseGuard;
 import java.io.FileDescriptor;
 import java.io.IOException;
 import java.io.InputStream;
@@ -37,6 +38,7 @@
 import javax.net.ssl.SSLException;
 import javax.net.ssl.SSLPeerUnverifiedException;
 import javax.net.ssl.SSLSession;
+import javax.net.ssl.X509TrustManager;
 import javax.security.auth.x500.X500Principal;
 import org.apache.harmony.security.provider.cert.X509CertImpl;
 
@@ -75,6 +77,7 @@
     private final FileDescriptor fd;
     private boolean autoClose;
     private boolean handshakeStarted = false;
+    private final CloseGuard guard = CloseGuard.get();
 
     /**
      * Not set to true until the update from native that tells us the
@@ -358,158 +361,172 @@
             sslParameters.getClientSessionContext().sslCtxNativePointer :
             sslParameters.getServerSessionContext().sslCtxNativePointer;
 
-        this.sslNativePointer = NativeCrypto.SSL_new(sslCtxNativePointer);
-
-        // setup server certificates and private keys.
-        // clients will receive a call back to request certificates.
-        if (!client) {
-            for (String keyType : NativeCrypto.KEY_TYPES) {
-                try {
-                    setCertificate(sslParameters.getKeyManager().chooseServerAlias(keyType,
-                                                                                   null,
-                                                                                   this));
-                } catch (CertificateEncodingException e) {
-                    throw new IOException(e);
-                }
-            }
-        }
-
-        NativeCrypto.setEnabledProtocols(sslNativePointer, enabledProtocols);
-        NativeCrypto.setEnabledCipherSuites(sslNativePointer, enabledCipherSuites);
-        if (enabledCompressionMethods.length != 0) {
-            NativeCrypto.setEnabledCompressionMethods(sslNativePointer, enabledCompressionMethods);
-        }
-        if (useSessionTickets) {
-            NativeCrypto.SSL_clear_options(sslNativePointer, NativeCrypto.SSL_OP_NO_TICKET);
-        }
-        if (hostname != null) {
-            NativeCrypto.SSL_set_tlsext_host_name(sslNativePointer, hostname);
-        }
-
-        boolean enableSessionCreation = sslParameters.getEnableSessionCreation();
-        if (!enableSessionCreation) {
-            NativeCrypto.SSL_set_session_creation_enabled(sslNativePointer,
-                                                          enableSessionCreation);
-        }
-
-        AbstractSessionContext sessionContext;
-        OpenSSLSessionImpl session;
-        if (client) {
-            // look for client session to reuse
-            ClientSessionContext clientSessionContext = sslParameters.getClientSessionContext();
-            sessionContext = clientSessionContext;
-            session = getCachedClientSession(clientSessionContext);
-            if (session != null) {
-                NativeCrypto.SSL_set_session(sslNativePointer,  session.sslSessionNativePointer);
-            }
-        } else {
-            sessionContext = sslParameters.getServerSessionContext();
-            session = null;
-        }
-
-        // setup peer certificate verification
-        if (client) {
-            // TODO support for anonymous cipher would require us to
-            // conditionally use SSL_VERIFY_NONE
-        } else {
-            // needing client auth takes priority...
-            boolean certRequested = false;
-            if (sslParameters.getNeedClientAuth()) {
-                NativeCrypto.SSL_set_verify(sslNativePointer,
-                                            NativeCrypto.SSL_VERIFY_PEER
-                                            | NativeCrypto.SSL_VERIFY_FAIL_IF_NO_PEER_CERT);
-                certRequested = true;
-            // ... over just wanting it...
-            } else if (sslParameters.getWantClientAuth()) {
-                NativeCrypto.SSL_set_verify(sslNativePointer,
-                                            NativeCrypto.SSL_VERIFY_PEER);
-                certRequested = true;
-            // ... and it defaults properly so we don't need call SSL_set_verify in the common case.
-            } else {
-                certRequested = false;
-            }
-
-            if (certRequested) {
-                X509Certificate[] issuers = sslParameters.getTrustManager().getAcceptedIssuers();
-                if (issuers != null && issuers.length != 0) {
-                    byte[][] issuersBytes;
-                    try {
-                        issuersBytes = NativeCrypto.encodeIssuerX509Principals(issuers);
-                    } catch (CertificateEncodingException e) {
-                        throw new IOException("Problem encoding principals", e);
-                    }
-                    NativeCrypto.SSL_set_client_CA_list(sslNativePointer, issuersBytes);
-                }
-            }
-        }
-
-        if (client && full) {
-            // we want to do a full synchronous handshake, so turn off cutthrough
-            NativeCrypto.SSL_clear_mode(sslNativePointer,
-                                        NativeCrypto.SSL_MODE_HANDSHAKE_CUTTHROUGH);
-        }
-
-        // BEGIN android-added
-        // Temporarily use a different timeout for the handshake process
-        int savedTimeoutMilliseconds = getSoTimeout();
-        if (handshakeTimeoutMilliseconds >= 0) {
-            setSoTimeout(handshakeTimeoutMilliseconds);
-        }
-        // END android-added
-
-
-        int sslSessionNativePointer;
+        this.sslNativePointer = 0;
+        boolean exception = true;
         try {
-            sslSessionNativePointer = NativeCrypto.SSL_do_handshake(sslNativePointer, fd, this,
-                                                                    getSoTimeout(), client);
-        } catch (CertificateException e) {
-            throw new SSLPeerUnverifiedException(e.getMessage());
-        }
-        byte[] sessionId = NativeCrypto.SSL_SESSION_session_id(sslSessionNativePointer);
-        sslSession = (OpenSSLSessionImpl) sessionContext.getSession(sessionId);
-        if (sslSession != null) {
-            sslSession.lastAccessedTime = System.currentTimeMillis();
-            LoggerHolder.logger.fine("Reused cached session for "
-                                     + getInetAddress() + ".");
-            NativeCrypto.SSL_SESSION_free(sslSessionNativePointer);
-        } else {
+            sslNativePointer = NativeCrypto.SSL_new(sslCtxNativePointer);
+            guard.open("close");
+
+            // setup server certificates and private keys.
+            // clients will receive a call back to request certificates.
+            if (!client) {
+                for (String keyType : NativeCrypto.KEY_TYPES) {
+                    try {
+                        setCertificate(sslParameters.getKeyManager().chooseServerAlias(keyType,
+                                                                                       null,
+                                                                                       this));
+                    } catch (CertificateEncodingException e) {
+                        throw new IOException(e);
+                    }
+                }
+            }
+
+            NativeCrypto.setEnabledProtocols(sslNativePointer, enabledProtocols);
+            NativeCrypto.setEnabledCipherSuites(sslNativePointer, enabledCipherSuites);
+            if (enabledCompressionMethods.length != 0) {
+                NativeCrypto.setEnabledCompressionMethods(sslNativePointer,
+                                                          enabledCompressionMethods);
+            }
+            if (useSessionTickets) {
+                NativeCrypto.SSL_clear_options(sslNativePointer, NativeCrypto.SSL_OP_NO_TICKET);
+            }
+            if (hostname != null) {
+                NativeCrypto.SSL_set_tlsext_host_name(sslNativePointer, hostname);
+            }
+
+            boolean enableSessionCreation = sslParameters.getEnableSessionCreation();
             if (!enableSessionCreation) {
-                // Should have been prevented by NativeCrypto.SSL_set_session_creation_enabled
-                throw new IllegalStateException("SSL Session may not be created");
+                NativeCrypto.SSL_set_session_creation_enabled(sslNativePointer,
+                                                              enableSessionCreation);
             }
-            X509Certificate[] localCertificates
-                    = createCertChain(NativeCrypto.SSL_get_certificate(sslNativePointer));
-            X509Certificate[] peerCertificates
-                    = createCertChain(NativeCrypto.SSL_get_peer_cert_chain(sslNativePointer));
-            if (wrappedHost == null) {
-                sslSession = new OpenSSLSessionImpl(sslSessionNativePointer,
-                                                    localCertificates, peerCertificates,
-                                                    super.getInetAddress().getHostName(),
-                                                    super.getPort(), sessionContext);
-            } else  {
-                sslSession = new OpenSSLSessionImpl(sslSessionNativePointer,
-                                                    localCertificates, peerCertificates,
-                                                    wrappedHost, wrappedPort,
-                                                    sessionContext);
+
+            AbstractSessionContext sessionContext;
+            OpenSSLSessionImpl session;
+            if (client) {
+                // look for client session to reuse
+                ClientSessionContext clientSessionContext = sslParameters.getClientSessionContext();
+                sessionContext = clientSessionContext;
+                session = getCachedClientSession(clientSessionContext);
+                if (session != null) {
+                    NativeCrypto.SSL_set_session(sslNativePointer,
+                                                 session.sslSessionNativePointer);
+                }
+            } else {
+                sessionContext = sslParameters.getServerSessionContext();
+                session = null;
             }
-            // if not, putSession later in handshakeCompleted() callback
+
+            // setup peer certificate verification
+            if (client) {
+                // TODO support for anonymous cipher would require us to
+                // conditionally use SSL_VERIFY_NONE
+            } else {
+                // needing client auth takes priority...
+                boolean certRequested = false;
+                if (sslParameters.getNeedClientAuth()) {
+                    NativeCrypto.SSL_set_verify(sslNativePointer,
+                                                NativeCrypto.SSL_VERIFY_PEER
+                                                | NativeCrypto.SSL_VERIFY_FAIL_IF_NO_PEER_CERT);
+                    certRequested = true;
+                // ... over just wanting it...
+                } else if (sslParameters.getWantClientAuth()) {
+                    NativeCrypto.SSL_set_verify(sslNativePointer,
+                                                NativeCrypto.SSL_VERIFY_PEER);
+                    certRequested = true;
+                // ... and it defaults properly so don't call SSL_set_verify in the common case.
+                } else {
+                    certRequested = false;
+                }
+
+                if (certRequested) {
+                    X509TrustManager trustManager = sslParameters.getTrustManager();
+                    X509Certificate[] issuers = trustManager.getAcceptedIssuers();
+                    if (issuers != null && issuers.length != 0) {
+                        byte[][] issuersBytes;
+                        try {
+                            issuersBytes = NativeCrypto.encodeIssuerX509Principals(issuers);
+                        } catch (CertificateEncodingException e) {
+                            throw new IOException("Problem encoding principals", e);
+                        }
+                        NativeCrypto.SSL_set_client_CA_list(sslNativePointer, issuersBytes);
+                    }
+                }
+            }
+
+            if (client && full) {
+                // we want to do a full synchronous handshake, so turn off cutthrough
+                NativeCrypto.SSL_clear_mode(sslNativePointer,
+                                            NativeCrypto.SSL_MODE_HANDSHAKE_CUTTHROUGH);
+            }
+
+            // BEGIN android-added
+            // Temporarily use a different timeout for the handshake process
+            int savedTimeoutMilliseconds = getSoTimeout();
+            if (handshakeTimeoutMilliseconds >= 0) {
+                setSoTimeout(handshakeTimeoutMilliseconds);
+            }
+            // END android-added
+
+            int sslSessionNativePointer;
+            try {
+                sslSessionNativePointer = NativeCrypto.SSL_do_handshake(sslNativePointer, fd, this,
+                                                                        getSoTimeout(), client);
+            } catch (CertificateException e) {
+                throw new SSLPeerUnverifiedException(e.getMessage());
+            }
+            byte[] sessionId = NativeCrypto.SSL_SESSION_session_id(sslSessionNativePointer);
+            sslSession = (OpenSSLSessionImpl) sessionContext.getSession(sessionId);
+            if (sslSession != null) {
+                sslSession.lastAccessedTime = System.currentTimeMillis();
+                LoggerHolder.logger.fine("Reused cached session for "
+                                         + getInetAddress() + ".");
+                NativeCrypto.SSL_SESSION_free(sslSessionNativePointer);
+            } else {
+                if (!enableSessionCreation) {
+                    // Should have been prevented by NativeCrypto.SSL_set_session_creation_enabled
+                    throw new IllegalStateException("SSL Session may not be created");
+                }
+                X509Certificate[] localCertificates
+                        = createCertChain(NativeCrypto.SSL_get_certificate(sslNativePointer));
+                X509Certificate[] peerCertificates
+                        = createCertChain(NativeCrypto.SSL_get_peer_cert_chain(sslNativePointer));
+                if (wrappedHost == null) {
+                    sslSession = new OpenSSLSessionImpl(sslSessionNativePointer,
+                                                        localCertificates, peerCertificates,
+                                                        super.getInetAddress().getHostName(),
+                                                        super.getPort(), sessionContext);
+                } else  {
+                    sslSession = new OpenSSLSessionImpl(sslSessionNativePointer,
+                                                        localCertificates, peerCertificates,
+                                                        wrappedHost, wrappedPort,
+                                                        sessionContext);
+                }
+                // if not, putSession later in handshakeCompleted() callback
+                if (handshakeCompleted) {
+                    sessionContext.putSession(sslSession);
+                }
+                LoggerHolder.logger.fine("Created new session for "
+                                         + getInetAddress().getHostName() + ".");
+            }
+
+            // BEGIN android-added
+            // Restore the original timeout now that the handshake is complete
+            if (handshakeTimeoutMilliseconds >= 0) {
+                setSoTimeout(savedTimeoutMilliseconds);
+            }
+            // END android-added
+
+            // if not, notifyHandshakeCompletedListeners later in handshakeCompleted() callback
             if (handshakeCompleted) {
-                sessionContext.putSession(sslSession);
+                notifyHandshakeCompletedListeners();
             }
-            LoggerHolder.logger.fine("Created new session for "
-                                     + getInetAddress().getHostName() + ".");
-        }
 
-        // BEGIN android-added
-        // Restore the original timeout now that the handshake is complete
-        if (handshakeTimeoutMilliseconds >= 0) {
-            setSoTimeout(savedTimeoutMilliseconds);
-        }
-        // END android-added
-
-        // if not, notifyHandshakeCompletedListeners later in handshakeCompleted() callback
-        if (handshakeCompleted) {
-            notifyHandshakeCompletedListeners();
+            exception = false;
+        } finally {
+            // on exceptional exit, free the native content immediate to avoid CloseGuard warning
+            if (exception) {
+                free();
+            }
         }
     }
 
@@ -843,7 +860,6 @@
             try {
                 startHandshake(true);
             } catch (IOException e) {
-
                 // return an invalid session with
                 // invalid cipher suite of "SSL_NULL_WITH_NULL_NULL"
                 return SSLSessionImpl.NULL_SESSION;
@@ -1257,6 +1273,7 @@
         }
         NativeCrypto.SSL_free(sslNativePointer);
         sslNativePointer = 0;
+        guard.close();
     }
 
     @Override protected void finalize() throws Throwable {
@@ -1277,6 +1294,9 @@
              * and will write the close notify to some unsuspecting
              * reader.
              */
+            if (guard != null) {
+                guard.warnIfOpen();
+            }
             free();
         } finally {
             super.finalize();
diff --git a/luni/src/main/java/org/apache/harmony/xnet/provider/jsse/SSLInputStream.java b/luni/src/main/java/org/apache/harmony/xnet/provider/jsse/SSLInputStream.java
index b2501a7..2e62e44 100644
--- a/luni/src/main/java/org/apache/harmony/xnet/provider/jsse/SSLInputStream.java
+++ b/luni/src/main/java/org/apache/harmony/xnet/provider/jsse/SSLInputStream.java
@@ -45,16 +45,6 @@
     @Override
     public abstract int read() throws IOException;
 
-    @Override
-    public long skip(long n) throws IOException {
-        long skept = n;
-        while (n > 0) {
-            read();
-            n--;
-        }
-        return skept;
-    }
-
     /**
      * Reads and returns uint8 value.
      */
diff --git a/luni/src/main/java/org/apache/harmony/xnet/provider/jsse/SSLSocketInputStream.java b/luni/src/main/java/org/apache/harmony/xnet/provider/jsse/SSLSocketInputStream.java
index 68b9a19..950518b 100644
--- a/luni/src/main/java/org/apache/harmony/xnet/provider/jsse/SSLSocketInputStream.java
+++ b/luni/src/main/java/org/apache/harmony/xnet/provider/jsse/SSLSocketInputStream.java
@@ -142,23 +142,6 @@
         return i;
     }
 
-    /**
-     * Method acts as described in spec for superclass.
-     * @see java.io.InputStream#skip(long)
-     */
-    @Override
-    public long skip(long n) throws IOException {
-        long i = 0;
-        int av = available();
-        if (av < n) {
-            n = av;
-        }
-        while ((i < n) && (read() != -1)) {
-            i++;
-        }
-        return i;
-    }
-
     // The helper class devivering the application data from the record layer
     // to this input stream.
     // It 'adapts' the InputStream interface to Appendable, which is used for
diff --git a/luni/src/main/java/org/apache/harmony/xnet/provider/jsse/TrustManagerFactoryImpl.java b/luni/src/main/java/org/apache/harmony/xnet/provider/jsse/TrustManagerFactoryImpl.java
index 7a555ea..149be0c 100644
--- a/luni/src/main/java/org/apache/harmony/xnet/provider/jsse/TrustManagerFactoryImpl.java
+++ b/luni/src/main/java/org/apache/harmony/xnet/provider/jsse/TrustManagerFactoryImpl.java
@@ -21,6 +21,7 @@
 import java.io.File;
 import java.io.FileInputStream;
 import java.io.FileNotFoundException;
+import java.io.InputStream;
 import java.io.IOException;
 import java.security.AccessController;
 import java.security.InvalidAlgorithmParameterException;
@@ -95,7 +96,15 @@
                     pwd = keyStorePwd.toCharArray();
                 }
                 try {
-                    keyStore.load(new BufferedInputStream(new FileInputStream(keyStoreName)), pwd);
+                    InputStream in = null;
+                    try {
+                        in = new BufferedInputStream(new FileInputStream(keyStoreName));
+                        keyStore.load(in, pwd);
+                    } finally {
+                        if (in != null) {
+                            in.close();
+                        }
+                    }
                 } catch (FileNotFoundException e) {
                     throw new KeyStoreException(e);
                 } catch (IOException e) {
diff --git a/luni/src/main/native/ICU.cpp b/luni/src/main/native/ICU.cpp
index 174e01f..a42f36f 100644
--- a/luni/src/main/native/ICU.cpp
+++ b/luni/src/main/native/ICU.cpp
@@ -563,11 +563,11 @@
     NATIVE_METHOD(ICU, getISO3LanguageNative, "(Ljava/lang/String;)Ljava/lang/String;"),
     NATIVE_METHOD(ICU, getISOCountriesNative, "()[Ljava/lang/String;"),
     NATIVE_METHOD(ICU, getISOLanguagesNative, "()[Ljava/lang/String;"),
-    NATIVE_METHOD(ICU, initLocaleDataImpl, "(Ljava/lang/String;Lcom/ibm/icu4jni/util/LocaleData;)Z"),
+    NATIVE_METHOD(ICU, initLocaleDataImpl, "(Ljava/lang/String;Llibcore/icu/LocaleData;)Z"),
     NATIVE_METHOD(ICU, toLowerCase, "(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String;"),
     NATIVE_METHOD(ICU, toUpperCase, "(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String;"),
 };
-int register_com_ibm_icu4jni_util_ICU(JNIEnv* env) {
+int register_libcore_icu_ICU(JNIEnv* env) {
     // Failures to find the ICU data tend to be somewhat obscure because ICU loads its data on first
     // use, which can be anywhere. Force initialization up front so we can report a nice clear error
     // and bail.
@@ -577,5 +577,5 @@
         LOGE("Couldn't initialize ICU: %s", u_errorName(status));
         return -1;
     }
-    return jniRegisterNativeMethods(env, "com/ibm/icu4jni/util/ICU", gMethods, NELEM(gMethods));
+    return jniRegisterNativeMethods(env, "libcore/icu/ICU", gMethods, NELEM(gMethods));
 }
diff --git a/luni/src/main/native/JniConstants.cpp b/luni/src/main/native/JniConstants.cpp
index 5ae3ded..36c0854 100644
--- a/luni/src/main/native/JniConstants.cpp
+++ b/luni/src/main/native/JniConstants.cpp
@@ -61,18 +61,18 @@
     booleanClass = findClass(env, "java/lang/Boolean");
     byteClass = findClass(env, "java/lang/Byte");
     byteArrayClass = findClass(env, "[B");
-    charsetICUClass = findClass(env, "com/ibm/icu4jni/charset/CharsetICU");
+    charsetICUClass = findClass(env, "libcore/icu/CharsetICU");
     constructorClass = findClass(env, "java/lang/reflect/Constructor");
     datagramPacketClass = findClass(env, "java/net/DatagramPacket");
     deflaterClass = findClass(env, "java/util/zip/Deflater");
     doubleClass = findClass(env, "java/lang/Double");
     fieldClass = findClass(env, "java/lang/reflect/Field");
-    fieldPositionIteratorClass = findClass(env, "com/ibm/icu4jni/text/NativeDecimalFormat$FieldPositionIterator");
+    fieldPositionIteratorClass = findClass(env, "libcore/icu/NativeDecimalFormat$FieldPositionIterator");
     inetAddressClass = findClass(env, "java/net/InetAddress");
     inflaterClass = findClass(env, "java/util/zip/Inflater");
     integerClass = findClass(env, "java/lang/Integer");
     interfaceAddressClass = findClass(env, "java/net/InterfaceAddress");
-    localeDataClass = findClass(env, "com/ibm/icu4jni/util/LocaleData");
+    localeDataClass = findClass(env, "libcore/icu/LocaleData");
     longClass = findClass(env, "java/lang/Long");
     methodClass = findClass(env, "java/lang/reflect/Method");
     multicastGroupRequestClass = findClass(env, "java/net/MulticastGroupRequest");
diff --git a/luni/src/main/native/NativeBN.cpp b/luni/src/main/native/NativeBN.cpp
index 4ef8c28..6359e3e 100644
--- a/luni/src/main/native/NativeBN.cpp
+++ b/luni/src/main/native/NativeBN.cpp
@@ -24,9 +24,9 @@
 #include "JniConstants.h"
 #include "ScopedPrimitiveArray.h"
 #include "ScopedUtfChars.h"
+#include "StaticAssert.h"
 #include "UniquePtr.h"
 #include "jni.h"
-#include <assert.h>
 #include <openssl/bn.h>
 #include <openssl/crypto.h>
 #include <openssl/err.h>
@@ -169,7 +169,7 @@
             return JNI_FALSE;
         }
 
-        assert(sizeof(BN_ULONG) == sizeof(jint));
+        STATIC_ASSERT(sizeof(BN_ULONG) == sizeof(jint), BN_ULONG_not_32_bit);
         const BN_ULONG* tmpInts = reinterpret_cast<const BN_ULONG*>(scopedArray.get());
         if ((tmpInts != NULL) && (bn_wexpand(ret, len) != NULL)) {
             int i = len; do { i--; ret->d[i] = tmpInts[i]; } while (i > 0);
@@ -197,10 +197,9 @@
   | (bytes[k + 0] & 0xFF) << 24 )
 
 static jboolean negBigEndianBytes2bn(JNIEnv*, jclass, const unsigned char* bytes, int bytesLen, BIGNUM* ret) {
-// We rely on: (BN_BITS2 == 32), i.e. BN_ULONG is unsigned int and has 4 bytes:
-//
+    // We rely on: (BN_BITS2 == 32), i.e. BN_ULONG is unsigned int and has 4 bytes:
     bn_check_top(ret);
-// FIXME: ASSERT (bytesLen > 0);
+    // FIXME: assert bytesLen > 0
     int intLen = (bytesLen + 3) / 4;
     int firstNonzeroDigit = -2;
     if (bn_wexpand(ret, intLen) != NULL) {
diff --git a/luni/src/main/native/NativeBreakIterator.cpp b/luni/src/main/native/NativeBreakIterator.cpp
index 742a41a..b3eab45 100644
--- a/luni/src/main/native/NativeBreakIterator.cpp
+++ b/luni/src/main/native/NativeBreakIterator.cpp
@@ -139,7 +139,6 @@
     NATIVE_METHOD(NativeBreakIterator, previousImpl, "(I)I"),
     NATIVE_METHOD(NativeBreakIterator, setTextImpl, "(ILjava/lang/String;)V"),
 };
-int register_com_ibm_icu4jni_text_NativeBreakIterator(JNIEnv* env) {
-    return jniRegisterNativeMethods(env, "com/ibm/icu4jni/text/NativeBreakIterator",
-            gMethods, NELEM(gMethods));
+int register_libcore_icu_NativeBreakIterator(JNIEnv* env) {
+    return jniRegisterNativeMethods(env, "libcore/icu/NativeBreakIterator", gMethods, NELEM(gMethods));
 }
diff --git a/luni/src/main/native/NativeCollation.cpp b/luni/src/main/native/NativeCollation.cpp
index d01b46f..60c6488 100644
--- a/luni/src/main/native/NativeCollation.cpp
+++ b/luni/src/main/native/NativeCollation.cpp
@@ -63,19 +63,6 @@
     return ucol_getMaxExpansion(toCollationElements(address), order);
 }
 
-static jint NativeCollation_getNormalization(JNIEnv* env, jclass, jint address) {
-    UErrorCode status = U_ZERO_ERROR;
-    jint result = ucol_getAttribute(toCollator(address), UCOL_NORMALIZATION_MODE, &status);
-    icu4jni_error(env, status);
-    return result;
-}
-
-static void NativeCollation_setNormalization(JNIEnv* env, jclass, jint address, jint mode) {
-    UErrorCode status = U_ZERO_ERROR;
-    ucol_setAttribute(toCollator(address), UCOL_NORMALIZATION_MODE, UColAttributeValue(mode), &status);
-    icu4jni_error(env, status);
-}
-
 static jint NativeCollation_getOffset(JNIEnv*, jclass, jint address) {
     return ucol_getOffset(toCollationElements(address));
 }
@@ -182,7 +169,6 @@
     NATIVE_METHOD(NativeCollation, getAttribute, "(II)I"),
     NATIVE_METHOD(NativeCollation, getCollationElementIterator, "(ILjava/lang/String;)I"),
     NATIVE_METHOD(NativeCollation, getMaxExpansion, "(II)I"),
-    NATIVE_METHOD(NativeCollation, getNormalization, "(I)I"),
     NATIVE_METHOD(NativeCollation, getOffset, "(I)I"),
     NATIVE_METHOD(NativeCollation, getRules, "(I)Ljava/lang/String;"),
     NATIVE_METHOD(NativeCollation, getSortKey, "(ILjava/lang/String;)[B"),
@@ -193,11 +179,9 @@
     NATIVE_METHOD(NativeCollation, reset, "(I)V"),
     NATIVE_METHOD(NativeCollation, safeClone, "(I)I"),
     NATIVE_METHOD(NativeCollation, setAttribute, "(III)V"),
-    NATIVE_METHOD(NativeCollation, setNormalization, "(II)V"),
     NATIVE_METHOD(NativeCollation, setOffset, "(II)V"),
     NATIVE_METHOD(NativeCollation, setText, "(ILjava/lang/String;)V"),
 };
-int register_com_ibm_icu4jni_text_NativeCollator(JNIEnv* env) {
-    return jniRegisterNativeMethods(env, "com/ibm/icu4jni/text/NativeCollation",
-                gMethods, NELEM(gMethods));
+int register_libcore_icu_NativeCollation(JNIEnv* env) {
+    return jniRegisterNativeMethods(env, "libcore/icu/NativeCollation", gMethods, NELEM(gMethods));
 }
diff --git a/luni/src/main/native/NativeConverter.cpp b/luni/src/main/native/NativeConverter.cpp
index e2894d6..7587fc6 100644
--- a/luni/src/main/native/NativeConverter.cpp
+++ b/luni/src/main/native/NativeConverter.cpp
@@ -8,8 +8,6 @@
 *******************************************************************************
 */
 /*
- *  @(#) icujniinterface.c	1.2 00/10/11
- *
  * (C) Copyright IBM Corp. 2000 - All Rights Reserved
  *  A JNI wrapper to ICU native converter Interface
  * @author: Ram Viswanadha
@@ -686,7 +684,6 @@
     NATIVE_METHOD(NativeConverter, setCallbackDecode, "(JII[C)I"),
     NATIVE_METHOD(NativeConverter, setCallbackEncode, "(JII[B)I"),
 };
-int register_com_ibm_icu4jni_converters_NativeConverter(JNIEnv* env) {
-    return jniRegisterNativeMethods(env, "com/ibm/icu4jni/charset/NativeConverter",
-                gMethods, NELEM(gMethods));
+int register_libcore_icu_NativeConverter(JNIEnv* env) {
+    return jniRegisterNativeMethods(env, "libcore/icu/NativeConverter", gMethods, NELEM(gMethods));
 }
diff --git a/luni/src/main/native/NativeDecimalFormat.cpp b/luni/src/main/native/NativeDecimalFormat.cpp
index 4fc7448..51113fa 100644
--- a/luni/src/main/native/NativeDecimalFormat.cpp
+++ b/luni/src/main/native/NativeDecimalFormat.cpp
@@ -336,9 +336,9 @@
     NATIVE_METHOD(NativeDecimalFormat, applyPatternImpl, "(IZLjava/lang/String;)V"),
     NATIVE_METHOD(NativeDecimalFormat, cloneImpl, "(I)I"),
     NATIVE_METHOD(NativeDecimalFormat, close, "(I)V"),
-    NATIVE_METHOD(NativeDecimalFormat, formatDouble, "(IDLcom/ibm/icu4jni/text/NativeDecimalFormat$FieldPositionIterator;)[C"),
-    NATIVE_METHOD(NativeDecimalFormat, formatLong, "(IJLcom/ibm/icu4jni/text/NativeDecimalFormat$FieldPositionIterator;)[C"),
-    NATIVE_METHOD(NativeDecimalFormat, formatDigitList, "(ILjava/lang/String;Lcom/ibm/icu4jni/text/NativeDecimalFormat$FieldPositionIterator;)[C"),
+    NATIVE_METHOD(NativeDecimalFormat, formatDouble, "(IDLlibcore/icu/NativeDecimalFormat$FieldPositionIterator;)[C"),
+    NATIVE_METHOD(NativeDecimalFormat, formatLong, "(IJLlibcore/icu/NativeDecimalFormat$FieldPositionIterator;)[C"),
+    NATIVE_METHOD(NativeDecimalFormat, formatDigitList, "(ILjava/lang/String;Llibcore/icu/NativeDecimalFormat$FieldPositionIterator;)[C"),
     NATIVE_METHOD(NativeDecimalFormat, getAttribute, "(II)I"),
     NATIVE_METHOD(NativeDecimalFormat, getTextAttribute, "(II)Ljava/lang/String;"),
     NATIVE_METHOD(NativeDecimalFormat, open, "(Ljava/lang/String;Ljava/lang/String;CCLjava/lang/String;CLjava/lang/String;Ljava/lang/String;CCLjava/lang/String;CCCC)I"),
@@ -350,7 +350,6 @@
     NATIVE_METHOD(NativeDecimalFormat, setTextAttribute, "(IILjava/lang/String;)V"),
     NATIVE_METHOD(NativeDecimalFormat, toPatternImpl, "(IZ)Ljava/lang/String;"),
 };
-int register_com_ibm_icu4jni_text_NativeDecimalFormat(JNIEnv* env) {
-    return jniRegisterNativeMethods(env, "com/ibm/icu4jni/text/NativeDecimalFormat", gMethods,
-            NELEM(gMethods));
+int register_libcore_icu_NativeDecimalFormat(JNIEnv* env) {
+    return jniRegisterNativeMethods(env, "libcore/icu/NativeDecimalFormat", gMethods, NELEM(gMethods));
 }
diff --git a/luni/src/main/native/Register.cpp b/luni/src/main/native/Register.cpp
index 56bfc28..380bb7e 100644
--- a/luni/src/main/native/Register.cpp
+++ b/luni/src/main/native/Register.cpp
@@ -25,11 +25,6 @@
     extern int register_dalvik_system_TouchDex(JNIEnv* env);
 }
 
-extern int register_com_ibm_icu4jni_converters_NativeConverter(JNIEnv* env);
-extern int register_com_ibm_icu4jni_text_NativeBreakIterator(JNIEnv* env);
-extern int register_com_ibm_icu4jni_text_NativeCollator(JNIEnv* env);
-extern int register_com_ibm_icu4jni_text_NativeDecimalFormat(JNIEnv* env);
-extern int register_com_ibm_icu4jni_util_ICU(JNIEnv* env);
 extern int register_java_io_Console(JNIEnv* env);
 extern int register_java_io_File(JNIEnv* env);
 extern int register_java_io_FileDescriptor(JNIEnv* env);
@@ -55,6 +50,11 @@
 extern int register_java_util_zip_CRC32(JNIEnv* env);
 extern int register_java_util_zip_Deflater(JNIEnv* env);
 extern int register_java_util_zip_Inflater(JNIEnv* env);
+extern int register_libcore_icu_ICU(JNIEnv* env);
+extern int register_libcore_icu_NativeBreakIterator(JNIEnv* env);
+extern int register_libcore_icu_NativeCollation(JNIEnv* env);
+extern int register_libcore_icu_NativeConverter(JNIEnv* env);
+extern int register_libcore_icu_NativeDecimalFormat(JNIEnv* env);
 extern int register_libcore_icu_NativeIDN(JNIEnv* env);
 extern int register_libcore_icu_NativeNormalizer(JNIEnv* env);
 extern int register_libcore_icu_NativePluralRules(JNIEnv* env);
@@ -76,11 +76,6 @@
     JniConstants::init(env);
 
     bool result =
-            register_com_ibm_icu4jni_converters_NativeConverter(env) != -1 &&
-            register_com_ibm_icu4jni_text_NativeBreakIterator(env) != -1 &&
-            register_com_ibm_icu4jni_text_NativeCollator(env) != -1 &&
-            register_com_ibm_icu4jni_text_NativeDecimalFormat(env) != -1 &&
-            register_com_ibm_icu4jni_util_ICU(env) != -1 &&
             register_java_io_Console(env) != -1 &&
             register_java_io_File(env) != -1 &&
             register_java_io_FileDescriptor(env) != -1 &&
@@ -106,6 +101,11 @@
             register_java_util_zip_CRC32(env) != -1 &&
             register_java_util_zip_Deflater(env) != -1 &&
             register_java_util_zip_Inflater(env) != -1 &&
+            register_libcore_icu_ICU(env) != -1 &&
+            register_libcore_icu_NativeBreakIterator(env) != -1 &&
+            register_libcore_icu_NativeCollation(env) != -1 &&
+            register_libcore_icu_NativeConverter(env) != -1 &&
+            register_libcore_icu_NativeDecimalFormat(env) != -1 &&
             register_libcore_icu_NativeIDN(env) != -1 &&
             register_libcore_icu_NativeNormalizer(env) != -1 &&
             register_libcore_icu_NativePluralRules(env) != -1 &&
diff --git a/luni/src/main/native/cbigint.cpp b/luni/src/main/native/cbigint.cpp
index 0b7cc42..da15fcb 100644
--- a/luni/src/main/native/cbigint.cpp
+++ b/luni/src/main/native/cbigint.cpp
@@ -251,29 +251,26 @@
 
 #if __BYTE_ORDER != __LITTLE_ENDIAN
 void simpleMultiplyAddHighPrecisionBigEndianFix(uint64_t* arg1, int32_t length, uint64_t arg2, uint32_t* result) {
-	/* Assumes result can hold the product and arg2 only holds 32 bits
-	   of information */
-	uint64_t product;
-	int32_t index, resultIndex;
+    /* Assumes result can hold the product and arg2 only holds 32 bits of information */
+    int32_t index = 0;
+    int32_t resultIndex = 0;
+    uint64_t product = 0;
 
-	index = resultIndex = 0;
-	product = 0;
+    do {
+        product = HIGH_IN_U64(product) + result[halfAt(resultIndex)] + arg2 * LOW_U32_FROM_PTR(arg1 + index);
+        result[halfAt(resultIndex)] = LOW_U32_FROM_VAR(product);
+        ++resultIndex;
+        product = HIGH_IN_U64(product) + result[halfAt(resultIndex)] + arg2 * HIGH_U32_FROM_PTR(arg1 + index);
+        result[halfAt(resultIndex)] = LOW_U32_FROM_VAR(product);
+        ++resultIndex;
+    } while (++index < length);
 
-	do {
-		product = HIGH_IN_U64(product) + result[halfAt(resultIndex)] + arg2 * LOW_U32_FROM_PTR(arg1 + index);
-		result[halfAt(resultIndex)] = LOW_U32_FROM_VAR(product);
-		++resultIndex;
-		product = HIGH_IN_U64(product) + result[halfAt(resultIndex)] + arg2 * HIGH_U32_FROM_PTR(arg1 + index);
-		result[halfAt(resultIndex)] = LOW_U32_FROM_VAR(product);
-		++resultIndex;
-	} while (++index < length);
-
-	result[halfAt(resultIndex)] += HIGH_U32_FROM_VAR(product);
-	if (result[halfAt(resultIndex)] < HIGH_U32_FROM_VAR(product)) {
-		/* must be careful with ++ operator and macro expansion */
-		++resultIndex;
-		while (++result[halfAt(resultIndex)] == 0) ++resultIndex;
-	}
+    result[halfAt(resultIndex)] += HIGH_U32_FROM_VAR(product);
+    if (result[halfAt(resultIndex)] < HIGH_U32_FROM_VAR(product)) {
+        /* must be careful with ++ operator and macro expansion */
+        ++resultIndex;
+        while (++result[halfAt(resultIndex)] == 0) ++resultIndex;
+    }
 }
 #endif
 
diff --git a/luni/src/main/native/java_io_File.cpp b/luni/src/main/native/java_io_File.cpp
index e14cf73..ea8d12b 100644
--- a/luni/src/main/native/java_io_File.cpp
+++ b/luni/src/main/native/java_io_File.cpp
@@ -24,6 +24,7 @@
 #include "ScopedLocalRef.h"
 #include "ScopedPrimitiveArray.h"
 #include "ScopedUtfChars.h"
+#include "StaticAssert.h"
 
 #include <dirent.h>
 #include <errno.h>
@@ -208,6 +209,7 @@
     if (!doStatFs(env, javaPath, sb)) {
         return 0;
     }
+    STATIC_ASSERT(sizeof(sb.f_bfree) == sizeof(jlong), statfs_not_64_bit);
     return sb.f_bfree * sb.f_bsize; // free block count * block size in bytes.
 }
 
@@ -216,6 +218,7 @@
     if (!doStatFs(env, javaPath, sb)) {
         return 0;
     }
+    STATIC_ASSERT(sizeof(sb.f_blocks) == sizeof(jlong), statfs_not_64_bit);
     return sb.f_blocks * sb.f_bsize; // total block count * block size in bytes.
 }
 
@@ -224,6 +227,7 @@
     if (!doStatFs(env, javaPath, sb)) {
         return 0;
     }
+    STATIC_ASSERT(sizeof(sb.f_bavail) == sizeof(jlong), statfs_not_64_bit);
     return sb.f_bavail * sb.f_bsize; // non-root free block count * block size in bytes.
 }
 
diff --git a/luni/src/main/native/org_apache_harmony_luni_platform_OSFileSystem.cpp b/luni/src/main/native/org_apache_harmony_luni_platform_OSFileSystem.cpp
index 658b962..346eef5 100644
--- a/luni/src/main/native/org_apache_harmony_luni_platform_OSFileSystem.cpp
+++ b/luni/src/main/native/org_apache_harmony_luni_platform_OSFileSystem.cpp
@@ -37,7 +37,6 @@
 #include "ScopedUtfChars.h"
 #include "UniquePtr.h"
 
-#include <assert.h>
 #include <errno.h>
 #include <fcntl.h>
 #include <limits.h>
@@ -106,7 +105,7 @@
 
 // Checks whether we can safely treat the given jlong as an off_t without
 // accidental loss of precision.
-// TODO: this is bogus; we should use _FILE_OFFSET_BITS=64.
+// TODO: this is bogus; we should use _FILE_OFFSET_BITS=64, but bionic doesn't support it.
 static bool offsetTooLarge(JNIEnv* env, jlong longOffset) {
     if (sizeof(off_t) >= sizeof(jlong)) {
         // We're only concerned about the possibility that off_t is
@@ -116,7 +115,11 @@
     }
 
     // TODO: use std::numeric_limits<off_t>::max() and min() when we have them.
-    assert(sizeof(off_t) == sizeof(int));
+    if (sizeof(off_t) != sizeof(int)) {
+        jniThrowException(env, "java/lang/AssertionError",
+                "off_t is smaller than 64-bit, but not 32-bit!");
+        return true;
+    }
     static const off_t off_t_max = INT_MAX;
     static const off_t off_t_min = INT_MIN;
 
@@ -136,8 +139,8 @@
     return (length == 0x7fffffffffffffffLL) ? 0 : length;
 }
 
-static struct flock flockFromStartAndLength(jlong start, jlong length) {
-    struct flock lock;
+static struct flock64 flockFromStartAndLength(jlong start, jlong length) {
+    struct flock64 lock;
     memset(&lock, 0, sizeof(lock));
 
     lock.l_whence = SEEK_SET;
@@ -147,15 +150,11 @@
     return lock;
 }
 
-static jint OSFileSystem_lockImpl(JNIEnv* env, jobject, jint fd,
+static jint OSFileSystem_lockImpl(JNIEnv*, jobject, jint fd,
         jlong start, jlong length, jint typeFlag, jboolean waitFlag) {
 
     length = translateLockLength(length);
-    if (offsetTooLarge(env, start) || offsetTooLarge(env, length)) {
-        return -1;
-    }
-
-    struct flock lock(flockFromStartAndLength(start, length));
+    struct flock64 lock(flockFromStartAndLength(start, length));
 
     if ((typeFlag & SHARED_LOCK_TYPE) == SHARED_LOCK_TYPE) {
         lock.l_type = F_RDLCK;
@@ -163,20 +162,16 @@
         lock.l_type = F_WRLCK;
     }
 
-    int waitMode = (waitFlag) ? F_SETLKW : F_SETLK;
+    int waitMode = (waitFlag) ? F_SETLKW64 : F_SETLK64;
     return TEMP_FAILURE_RETRY(fcntl(fd, waitMode, &lock));
 }
 
 static void OSFileSystem_unlockImpl(JNIEnv* env, jobject, jint fd, jlong start, jlong length) {
     length = translateLockLength(length);
-    if (offsetTooLarge(env, start) || offsetTooLarge(env, length)) {
-        return;
-    }
-
-    struct flock lock(flockFromStartAndLength(start, length));
+    struct flock64 lock(flockFromStartAndLength(start, length));
     lock.l_type = F_UNLCK;
 
-    int rc = TEMP_FAILURE_RETRY(fcntl(fd, F_SETLKW, &lock));
+    int rc = TEMP_FAILURE_RETRY(fcntl(fd, F_SETLKW64, &lock));
     if (rc == -1) {
         jniThrowIOException(env, errno);
     }
@@ -337,14 +332,7 @@
         return -1;
     }
 
-    // If the offset is relative, lseek(2) will tell us whether it's too large.
-    // We're just worried about too large an absolute offset, which would cause
-    // us to lie to lseek(2).
-    if (offsetTooLarge(env, offset)) {
-        return -1;
-    }
-
-    jlong result = lseek(fd, offset, nativeWhence);
+    jlong result = lseek64(fd, offset, nativeWhence);
     if (result == -1) {
         jniThrowIOException(env, errno);
     }
@@ -352,17 +340,14 @@
 }
 
 static void OSFileSystem_fsync(JNIEnv* env, jobject, jint fd, jboolean metadataToo) {
-    if (!metadataToo) {
-        LOGW("fdatasync(2) unimplemented on Android - doing fsync(2)"); // http://b/2667481
-    }
-    int rc = fsync(fd);
-    // int rc = metadataToo ? fsync(fd) : fdatasync(fd);
+    int rc = metadataToo ? fsync(fd) : fdatasync(fd);
     if (rc == -1) {
         jniThrowIOException(env, errno);
     }
 }
 
 static jint OSFileSystem_truncate(JNIEnv* env, jobject, jint fd, jlong length) {
+    // TODO: if we had ftruncate64, we could kill this (http://b/3107933).
     if (offsetTooLarge(env, length)) {
         return -1;
     }
diff --git a/luni/src/main/native/org_apache_harmony_luni_platform_OSMemory.cpp b/luni/src/main/native/org_apache_harmony_luni_platform_OSMemory.cpp
index 5005341..b2f387d 100644
--- a/luni/src/main/native/org_apache_harmony_luni_platform_OSMemory.cpp
+++ b/luni/src/main/native/org_apache_harmony_luni_platform_OSMemory.cpp
@@ -45,58 +45,38 @@
     return reinterpret_cast<T>(static_cast<uintptr_t>(address));
 }
 
-static inline void fastSwap16(jshort& v) {
-#if __ARM_ARCH__ >= 6
-    asm("rev16 %[v], %[v]" : [v] "+r" (v));
-#else
-    v = bswap_16(v);
-#endif
-}
-
-static inline void fastSwap32(jint& v) {
-#if __ARM_ARCH__ >= 6
-    asm("rev %[v], %[v]" : [v] "+r" (v));
-#else
-    v = bswap_32(v);
-#endif
-}
-
-static void swapShorts(jshort* dstShorts, const jshort* srcShorts, size_t count) {
+static inline void swapShorts(jshort* dstShorts, const jshort* srcShorts, size_t count) {
     // Do 32-bit swaps as long as possible...
     jint* dst = reinterpret_cast<jint*>(dstShorts);
     const jint* src = reinterpret_cast<const jint*>(srcShorts);
     for (size_t i = 0; i < count / 2; ++i) {
         jint v = *src++;                            // v=ABCD
-        fastSwap32(v);                              // v=DCBA
+        v = bswap_32(v);                            // v=DCBA
         jint v2 = (v << 16) | ((v >> 16) & 0xffff); // v=BADC
         *dst++ = v2;
     }
     // ...with one last 16-bit swap if necessary.
     if ((count % 2) != 0) {
         jshort v = *reinterpret_cast<const jshort*>(src);
-        fastSwap16(v);
-        *reinterpret_cast<jshort*>(dst) = v;
+        *reinterpret_cast<jshort*>(dst) = bswap_16(v);
     }
 }
 
-static void swapInts(jint* dstInts, const jint* srcInts, size_t count) {
+static inline void swapInts(jint* dstInts, const jint* srcInts, size_t count) {
     for (size_t i = 0; i < count; ++i) {
         jint v = *srcInts++;
-        fastSwap32(v);
-        *dstInts++ = v;
+        *dstInts++ = bswap_32(v);
     }
 }
 
-static void swapLongs(jlong* dstLongs, const jlong* srcLongs, size_t count) {
+static inline void swapLongs(jlong* dstLongs, const jlong* srcLongs, size_t count) {
     jint* dst = reinterpret_cast<jint*>(dstLongs);
     const jint* src = reinterpret_cast<const jint*>(srcLongs);
     for (size_t i = 0; i < count; ++i) {
         jint v1 = *src++;
         jint v2 = *src++;
-        fastSwap32(v1);
-        fastSwap32(v2);
-        *dst++ = v2;
-        *dst++ = v1;
+        *dst++ = bswap_32(v2);
+        *dst++ = bswap_32(v1);
     }
 }
 
@@ -249,14 +229,14 @@
 static jshort OSMemory_peekShort(JNIEnv*, jclass, jint srcAddress, jboolean swap) {
     jshort result = *cast<const jshort*>(srcAddress);
     if (swap) {
-        fastSwap16(result);
+        result = bswap_16(result);
     }
     return result;
 }
 
 static void OSMemory_pokeShort(JNIEnv*, jclass, jint dstAddress, jshort value, jboolean swap) {
     if (swap) {
-        fastSwap16(value);
+        value = bswap_16(value);
     }
     *cast<jshort*>(dstAddress) = value;
 }
@@ -264,14 +244,14 @@
 static jint OSMemory_peekInt(JNIEnv*, jclass, jint srcAddress, jboolean swap) {
     jint result = *cast<const jint*>(srcAddress);
     if (swap) {
-        fastSwap32(result);
+        result = bswap_32(result);
     }
     return result;
 }
 
 static void OSMemory_pokeInt(JNIEnv*, jclass, jint dstAddress, jint value, jboolean swap) {
     if (swap) {
-        fastSwap32(value);
+        value = bswap_32(value);
     }
     *cast<jint*>(dstAddress) = value;
 }
diff --git a/luni/src/main/native/org_apache_harmony_luni_platform_OSNetworkSystem.cpp b/luni/src/main/native/org_apache_harmony_luni_platform_OSNetworkSystem.cpp
index b3a316f..7d3a0cf 100644
--- a/luni/src/main/native/org_apache_harmony_luni_platform_OSNetworkSystem.cpp
+++ b/luni/src/main/native/org_apache_harmony_luni_platform_OSNetworkSystem.cpp
@@ -28,7 +28,6 @@
 #include "valueOf.h"
 
 #include <arpa/inet.h>
-#include <assert.h>
 #include <errno.h>
 #include <netdb.h>
 #include <netinet/in.h>
@@ -359,20 +358,36 @@
     group_req groupRequest;
 
     // Get the IPv4 or IPv6 multicast address to join or leave.
-    jfieldID fid = env->GetFieldID(JniConstants::multicastGroupRequestClass,
+    static jfieldID grGroupFid = env->GetFieldID(JniConstants::multicastGroupRequestClass,
             "gr_group", "Ljava/net/InetAddress;");
-    jobject group = env->GetObjectField(javaGroupRequest, fid);
+    jobject group = env->GetObjectField(javaGroupRequest, grGroupFid);
     if (!inetAddressToSocketAddress(env, group, 0, &groupRequest.gr_group)) {
         return;
     }
 
     // Get the interface index to use (or 0 for "whatever").
-    fid = env->GetFieldID(JniConstants::multicastGroupRequestClass, "gr_interface", "I");
-    groupRequest.gr_interface = env->GetIntField(javaGroupRequest, fid);
+    static jfieldID grInterfaceFid =
+            env->GetFieldID(JniConstants::multicastGroupRequestClass, "gr_interface", "I");
+    groupRequest.gr_interface = env->GetIntField(javaGroupRequest, grInterfaceFid);
 
+    // Decide exactly what we're trying to do...
     int level = groupRequest.gr_group.ss_family == AF_INET ? IPPROTO_IP : IPPROTO_IPV6;
     int option = join ? MCAST_JOIN_GROUP : MCAST_LEAVE_GROUP;
+
     int rc = setsockopt(fd, level, option, &groupRequest, sizeof(groupRequest));
+    if (rc == -1 && errno == EINVAL) {
+        // Maybe we're a 32-bit binary talking to a 64-bit kernel?
+        // glibc doesn't automatically handle this.
+        struct group_req64 {
+            uint32_t gr_interface;
+            uint32_t my_padding;
+            sockaddr_storage gr_group;
+        };
+        group_req64 groupRequest64;
+        groupRequest64.gr_interface = groupRequest.gr_interface;
+        memcpy(&groupRequest64.gr_group, &groupRequest.gr_group, sizeof(groupRequest.gr_group));
+        rc = setsockopt(fd, level, option, &groupRequest64, sizeof(groupRequest64));
+    }
     if (rc == -1) {
         jniThrowSocketException(env, errno);
         return;
diff --git a/luni/src/main/native/org_apache_harmony_luni_util_FloatingPointParser.cpp b/luni/src/main/native/org_apache_harmony_luni_util_FloatingPointParser.cpp
index fdae21a..1428a80 100644
--- a/luni/src/main/native/org_apache_harmony_luni_util_FloatingPointParser.cpp
+++ b/luni/src/main/native/org_apache_harmony_luni_util_FloatingPointParser.cpp
@@ -332,7 +332,7 @@
  * is currently set such that if the oscillation occurs more than twice
  * then return the original approximation.
  */
-static jdouble doubleAlgorithm(JNIEnv*, uint64_t* f, int32_t length, jint e, jdouble z) {
+static jdouble doubleAlgorithm(JNIEnv* env, uint64_t* f, int32_t length, jint e, jdouble z) {
   uint64_t m;
   int32_t k, comparison, comparison2;
   uint64_t* x;
@@ -510,9 +510,7 @@
   free(y);
   free(D);
   free(D2);
-
-  DOUBLE_TO_LONGBITS (z) = -2;
-
+  jniThrowException(env, "java/lang/OutOfMemoryError", NULL);
   return z;
 }
 
@@ -584,7 +582,6 @@
             break; \
         } \
     }
-#define ERROR_OCCURRED(x) (HIGH_I32_FROM_VAR(x) < 0)
 
 static jfloat createFloat(JNIEnv* env, const char* s, jint e) {
   /* assumes s is a null terminated string with at least one
@@ -809,7 +806,7 @@
  * is currently set such that if the oscillation occurs more than twice
  * then return the original approximation.
  */
-static jfloat floatAlgorithm(JNIEnv*, uint64_t* f, int32_t length, jint e, jfloat z) {
+static jfloat floatAlgorithm(JNIEnv* env, uint64_t* f, int32_t length, jint e, jfloat z) {
   uint64_t m;
   int32_t k, comparison, comparison2;
   uint64_t* x;
@@ -987,9 +984,7 @@
   free(y);
   free(D);
   free(D2);
-
-  FLOAT_TO_INTBITS (z) = -2;
-
+  jniThrowException(env, "java/lang/OutOfMemoryError", NULL);
   return z;
 }
 
@@ -998,16 +993,7 @@
     if (str.c_str() == NULL) {
         return 0.0;
     }
-    jfloat flt = createFloat(env, str.c_str(), e);
-
-    if (((int32_t) FLOAT_TO_INTBITS (flt)) >= 0) {
-        return flt;
-    } else if (((int32_t) FLOAT_TO_INTBITS (flt)) == (int32_t) - 1) {
-        jniThrowException(env, "java/lang/NumberFormatException", NULL);
-    } else {
-        jniThrowException(env, "java/lang/OutOfMemoryError", NULL);
-    }
-    return 0.0;
+    return createFloat(env, str.c_str(), e);
 }
 
 static jdouble FloatingPointParser_parseDblImpl(JNIEnv* env, jclass, jstring s, jint e) {
@@ -1015,16 +1001,7 @@
     if (str.c_str() == NULL) {
         return 0.0;
     }
-    jdouble dbl = createDouble(env, str.c_str(), e);
-
-    if (!ERROR_OCCURRED (dbl)) {
-        return dbl;
-    } else if (LOW_I32_FROM_VAR (dbl) == (int32_t) - 1) {
-        jniThrowException(env, "java/lang/NumberFormatException", NULL);
-    } else {
-        jniThrowException(env, "java/lang/OutOfMemoryError", NULL);
-    }
-    return 0.0;
+    return createDouble(env, str.c_str(), e);
 }
 
 static JNINativeMethod gMethods[] = {
diff --git a/luni/src/test/java/com/google/coretests/CoreTestDummy.java b/luni/src/test/java/com/google/coretests/CoreTestDummy.java
deleted file mode 100644
index 4e1400d..0000000
--- a/luni/src/test/java/com/google/coretests/CoreTestDummy.java
+++ /dev/null
@@ -1,72 +0,0 @@
-/*
- * Copyright (C) 2009 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 com.google.coretests;
-
-import junit.framework.TestCase;
-import dalvik.annotation.AndroidOnly;
-import dalvik.annotation.BrokenTest;
-import dalvik.annotation.KnownFailure;
-import dalvik.annotation.SideEffect;
-
-/**
- * A dummy test for testing our CoreTestRunner.
- */
-public class CoreTestDummy extends TestCase {
-
-    @AndroidOnly("")
-    public void testAndroidOnlyPass() {
-    }
-
-    @AndroidOnly("")
-    public void testAndroidOnlyFail() {
-        fail("Oops!");
-    }
-
-    @BrokenTest("")
-    public void testBrokenTestPass() {
-    }
-
-    @BrokenTest("")
-    public void testBrokenTestFail() {
-        fail("Oops!");
-    }
-
-    @KnownFailure("")
-    public void testKnownFailurePass() {
-    }
-
-    @KnownFailure("")
-    public void testKnownFailureFail() {
-        fail("Oops!");
-    }
-
-    @SideEffect("")
-    public void testSideEffectPass() {
-    }
-
-    @SideEffect("")
-    public void testSideEffectFail() {
-        fail("Oops!");
-    }
-
-    public void testNormalPass() {
-    }
-
-    public void testNormalFail() {
-        fail("Oops!");
-    }
-
-}
diff --git a/luni/src/test/java/com/google/coretests/CoreTestIsolator.java b/luni/src/test/java/com/google/coretests/CoreTestIsolator.java
deleted file mode 100644
index 53b2fdf..0000000
--- a/luni/src/test/java/com/google/coretests/CoreTestIsolator.java
+++ /dev/null
@@ -1,120 +0,0 @@
-/*
- * Copyright (C) 2009 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 com.google.coretests;
-
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.io.ObjectOutputStream;
-import java.io.OutputStream;
-import java.io.PrintStream;
-import java.util.logging.Level;
-import java.util.logging.Logger;
-
-import junit.framework.Test;
-import junit.framework.TestFailure;
-import junit.framework.TestResult;
-import junit.framework.TestSuite;
-import junit.textui.TestRunner;
-
-/**
- * A minimalistic TestRunner implementation that silently executes a single test
- * method and writes a possible stack trace to a temporary file. Used for
- * isolating tests.
- */
-public class CoreTestIsolator extends TestRunner {
-
-    /**
-     * Creates a new CoreTestIsolator. The superclass needs to be able to build
-     * a proper ResultPrinter, so we pass it a null device for printing stuff.
-     */
-    public CoreTestIsolator() {
-        super(new PrintStream(new OutputStream() {
-            @Override
-            public void write(int oneByte) throws IOException {
-                // Null device
-            }
-        }));
-    }
-
-    @Override
-    protected TestResult createTestResult() {
-        return new TestResult();
-    }
-
-    /**
-     * Provides the main entry point. First and second argument are class and
-     * method name, respectively. Third argument is the temporary file name for
-     * the result. Exits with one of the usual JUnit exit values.
-     */
-    public static void main(String args[]) {
-        Logger.global.setLevel(Level.OFF);
-
-        CoreTestIsolator testRunner = new CoreTestIsolator();
-        try {
-            TestResult r = testRunner.start(args);
-
-            if (!r.wasSuccessful()) {
-                // Store failure or error - we know there must be one
-                Throwable failure = r.failureCount() != 0 ?
-                        ((TestFailure)r.failures().nextElement()).
-                                thrownException() :
-                        ((TestFailure)r.errors().nextElement()).
-                                thrownException();
-
-                saveStackTrace(failure, args[2]);
-
-                System.exit(FAILURE_EXIT);
-            } else {
-                // Nothing to see here, please get along
-                System.exit(SUCCESS_EXIT);
-            }
-        } catch(Exception e) {
-            // Let main TestRunner know about execution problem
-            saveStackTrace(e, args[2]);
-            System.exit(EXCEPTION_EXIT);
-        }
-
-    }
-
-    /**
-     * Saves a given stack trace to a given file.
-     */
-    private static void saveStackTrace(Throwable throwable, String fileName) {
-        try {
-            FileOutputStream fos = new FileOutputStream(fileName);
-            ObjectOutputStream oos = new ObjectOutputStream(fos);
-
-            oos.writeObject(throwable);
-
-            oos.flush();
-            oos.close();
-        } catch (IOException ex) {
-            // Ignore
-        }
-    }
-
-    @Override
-    protected TestResult start(String args[]) {
-        try {
-            Test suite = TestSuite.createTest(Class.forName(args[0]), args[1]);
-            return doRun(suite);
-        }
-        catch(Exception e) {
-            throw new RuntimeException("Unable to launch test", e);
-        }
-    }
-
-}
diff --git a/luni/src/test/java/com/google/coretests/CoreTestPrinter.java b/luni/src/test/java/com/google/coretests/CoreTestPrinter.java
deleted file mode 100644
index acfabcc..0000000
--- a/luni/src/test/java/com/google/coretests/CoreTestPrinter.java
+++ /dev/null
@@ -1,180 +0,0 @@
-/*
- * Copyright (C) 2009 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 com.google.coretests;
-
-import java.io.PrintStream;
-
-import junit.framework.Test;
-import junit.framework.TestCase;
-import junit.framework.TestResult;
-import junit.textui.ResultPrinter;
-
-/**
- * A special ResultPrinter implementation that displays additional statistics
- * about the test that have been executed.
- */
-public class CoreTestPrinter extends ResultPrinter {
-
-    /**
-     * The last test class we executed.
-     */
-    private Class<?> fLastClass;
-
-    /**
-     * The current output column for dots.
-     */
-    private int fColumn;
-
-    /**
-     * The time it took to execute the tests.
-     */
-    private int fRunTime;
-
-    /**
-     * The flags the user specified.
-     */
-    private int fFlags;
-
-    /**
-     * Creates a new CoreTestPrinter for the given parameters.
-     */
-    public CoreTestPrinter(PrintStream writer, int flags) {
-        super(writer);
-        fFlags = flags;
-    }
-
-    @Override
-    protected void printHeader(long runTime) {
-        fRunTime = (int)(runTime / 1000);
-
-        if (fColumn != 0) {
-            getWriter().println();
-        }
-
-        getWriter().println();
-    }
-
-    @Override
-    protected void printFooter(TestResult result) {
-        CoreTestResult coreResult = (CoreTestResult)result;
-
-        PrintStream printer = getWriter();
-
-        if (fColumn != 0) {
-            printer.println();
-        }
-
-        printer.println();
-        printer.println("Total tests   : " + coreResult.fTotalTestCount);
-        printer.println("Tests run     : " + coreResult.runCount());
-        printer.println("Tests ignored : " + coreResult.fIgnoredCount);
-
-        printer.println();
-        printer.println("Normal tests  : " + coreResult.fNormalTestCount);
-        printer.println("Android-only  : " + coreResult.fAndroidOnlyCount);
-        printer.println("Broken tests  : " + coreResult.fBrokenTestCount);
-        printer.println("Known failures: " + coreResult.fKnownFailureCount);
-        printer.println("Side-effects  : " + coreResult.fSideEffectCount);
-
-        printMemory();
-
-        int seconds = fRunTime;
-
-        int hours = seconds / 3600;
-        seconds = seconds % 3600;
-
-        int minutes = seconds / 60;
-        seconds = seconds % 60;
-
-        String text = String.format("%02d:%02d:%02d", hours, minutes, seconds);
-
-        printer.println();
-        printer.println("Time taken    : " + text);
-
-        super.printFooter(result);
-    }
-
-    /**
-     * Dumps some memory info.
-     */
-    private void printMemory() {
-        PrintStream printer = getWriter();
-        Runtime runtime = Runtime.getRuntime();
-
-        long total = runtime.totalMemory();
-        long free = runtime.freeMemory();
-        long used = total - free;
-
-        printer.println();
-        printer.println("Total memory  : " + total);
-        printer.println("Used memory   : " + used);
-        printer.println("Free memory   : " + free);
-    }
-
-    @Override
-    public void startTest(Test test) {
-        TestCase caze = (TestCase)test;
-
-        if (fLastClass == null ||
-                caze.getClass().getPackage() != fLastClass.getPackage()) {
-
-            if (fColumn != 0) {
-                getWriter().println();
-                fColumn = 0;
-            }
-
-            getWriter().println();
-            Package pack = caze.getClass().getPackage();
-            getWriter().println(pack == null ? "Default package" :
-                pack.getName());
-            getWriter().println();
-
-        }
-
-        if ((fFlags & CoreTestSuite.VERBOSE) != 0) {
-            if (caze.getClass() != fLastClass) {
-                if (fColumn != 0) {
-                    getWriter().println();
-                    fColumn = 0;
-                }
-
-                String name = caze.getClass().getSimpleName().toString();
-
-                printMemory();
-                getWriter().println("Now executing : " + name);
-                getWriter().println();
-            }
-        }
-
-        getWriter().print(".");
-        if (fColumn++ >= 40) {
-            getWriter().println();
-            fColumn= 0;
-        }
-
-        fLastClass = caze.getClass();
-    }
-
-    @Override
-    public void addError(Test test, Throwable t) {
-        if (t instanceof CoreTestTimeout) {
-            getWriter().print("T");
-        } else {
-            super.addError(test, t);
-        }
-    }
-
-}
diff --git a/luni/src/test/java/com/google/coretests/CoreTestResult.java b/luni/src/test/java/com/google/coretests/CoreTestResult.java
deleted file mode 100644
index 02267fa..0000000
--- a/luni/src/test/java/com/google/coretests/CoreTestResult.java
+++ /dev/null
@@ -1,170 +0,0 @@
-/*
- * Copyright (C) 2009 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 com.google.coretests;
-
-import java.lang.reflect.Method;
-
-import junit.framework.Protectable;
-import junit.framework.Test;
-import junit.framework.TestCase;
-import junit.framework.TestResult;
-import dalvik.annotation.KnownFailure;
-import dalvik.annotation.SideEffect;
-
-/**
- * A special TestResult implementation that is able to filter out annotated
- * tests and handles our known failures properly (expects them to fail).
- * Handy when running the Core Libraries tests on Android, the bare-metal
- * Dalvik VM, or the RI.
- */
-public class CoreTestResult extends TestResult {
-
-    /**
-     * The flags the user specified for this test run.
-     */
-    protected int fFlags;
-
-    /**
-     * The timeout the user specified for this test run.
-     */
-    protected int fTimeout;
-
-    /**
-     * The total number of tests in the original suite.
-     */
-    protected int fTotalTestCount;
-
-    /**
-     * The number of Android-only tests in the original suite.
-     */
-    protected int fAndroidOnlyCount;
-
-    /**
-     * The number of broken tests in the original suite.
-     */
-    protected int fBrokenTestCount;
-
-    /**
-     * The number of known failures in the original suite.
-     */
-    protected int fKnownFailureCount;
-
-    /**
-     * The number of side-effective tests in the original suite.
-     */
-    protected int fSideEffectCount;
-
-    /**
-     * The number of normal (non-annotated) tests in the original suite.
-     */
-    protected int fNormalTestCount;
-
-    /**
-     * The number of ignored tests, that is, the number of tests that were
-     * excluded from this suite due to their annotations.
-     */
-    protected int fIgnoredCount;
-
-    /**
-     * Creates a new CoreTestResult with the given flags and timeout.
-     */
-    public CoreTestResult(int flags, int timeout) {
-        super();
-
-        fFlags = flags;
-        fTimeout = timeout;
-    }
-
-    /**
-     * Checks whether the given TestCase method has the given annotation.
-     */
-    @SuppressWarnings("unchecked")
-    boolean hasAnnotation(TestCase test, Class clazz) {
-        try {
-            Method method = test.getClass().getMethod(test.getName());
-            return method.getAnnotation(clazz) != null;
-        } catch (Exception e) {
-            // Ignore
-        }
-
-        return false;
-    }
-
-    @Override
-    @SuppressWarnings("deprecation")
-    public void runProtected(final Test test, Protectable p) {
-        if ((fFlags & CoreTestSuite.DRY_RUN) == 0) {
-            if (test instanceof TestCase) {
-                TestCase testCase = (TestCase)test;
-
-                // Check whether we need to invert the test result (known failures)
-                boolean invert = hasAnnotation(testCase, KnownFailure.class) &&
-                        (fFlags & CoreTestSuite.INVERT_KNOWN_FAILURES) != 0;
-
-                // Check whether we need to isolate the test (side effects)
-                boolean isolate = hasAnnotation(testCase, SideEffect.class) &&
-                        (fFlags & CoreTestSuite.ISOLATE_NONE) == 0 ||
-                        (fFlags & CoreTestSuite.ISOLATE_ALL) != 0;
-
-                CoreTestRunnable runnable = new CoreTestRunnable(
-                        testCase, this, p, invert, isolate);
-
-                if (fTimeout > 0) {
-                    Thread thread = new Thread(runnable);
-                    thread.start();
-                    try {
-                        thread.join(fTimeout * 1000);
-                    } catch (InterruptedException ex) {
-                        // Ignored
-                    }
-                    if (thread.isAlive()) {
-                        StackTraceElement[] trace = thread.getStackTrace();
-                        runnable.stop();
-                        thread.stop();
-                        try {
-                            thread.join(fTimeout * 1000);
-                        } catch (InterruptedException ex) {
-                            // Ignored
-                        }
-
-                        CoreTestTimeout timeout = new CoreTestTimeout("Test timed out");
-                        timeout.setStackTrace(trace);
-                        addError(test, timeout);
-                    }
-                } else {
-                    runnable.run();
-                }
-            }
-        }
-    }
-
-    /**
-     * Updates the statistics in this TestResult. Called from the TestSuite,
-     * since, once the original suite has been filtered, we don't actually see
-     * these tests here anymore.
-     */
-    void updateStats(int total, int androidOnly, int broken, int knownFailure,
-            int normal, int ignored, int sideEffect) {
-
-        this.fTotalTestCount += total;
-        this.fAndroidOnlyCount += androidOnly;
-        this.fBrokenTestCount += broken;
-        this.fKnownFailureCount += knownFailure;
-        this.fNormalTestCount += normal;
-        this.fIgnoredCount += ignored;
-        this.fSideEffectCount += sideEffect;
-    }
-}
diff --git a/luni/src/test/java/com/google/coretests/CoreTestRunnable.java b/luni/src/test/java/com/google/coretests/CoreTestRunnable.java
deleted file mode 100644
index 177a291..0000000
--- a/luni/src/test/java/com/google/coretests/CoreTestRunnable.java
+++ /dev/null
@@ -1,172 +0,0 @@
-/*
- * Copyright (C) 2009 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 com.google.coretests;
-
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.ObjectInputStream;
-
-import junit.framework.AssertionFailedError;
-import junit.framework.Protectable;
-import junit.framework.TestCase;
-import junit.framework.TestResult;
-import junit.textui.TestRunner;
-
-/**
- * A wrapper around a single test that allows to execute the test either in the
- * same thread, in a separate thread, or even in a different process.
- */
-public class CoreTestRunnable implements Runnable {
-
-    private static boolean IS_DALVIK = "Dalvik".equals(
-            System.getProperty("java.vm.name"));
-
-    /**
-     * The test case we are supposed to run.
-     */
-    private TestCase fTest;
-
-    /**
-     * The TestResult we need to update after the run.
-     */
-    private TestResult fResult;
-
-    /**
-     * The Protectable that JUnit has created for us.
-     */
-    private Protectable fProtectable;
-
-    /**
-     * Reflects whether we need to invert the test result, which is used for
-     * treating known failures.
-     */
-    private boolean fInvert;
-
-    /**
-     * Reflects whether we need to isolate the test, which means we run it in
-     * a separate process.
-     */
-    private boolean fIsolate;
-
-    /**
-     * If we are isolating the test case, this holds the process that is running
-     * it.
-     */
-    private Process fProcess;
-
-    /**
-     * Creates a new CoreTestRunnable for the given parameters.
-     */
-    public CoreTestRunnable(TestCase test, TestResult result,
-            Protectable protectable, boolean invert, boolean isolate) {
-
-        this.fTest = test;
-        this.fProtectable = protectable;
-        this.fResult = result;
-        this.fInvert = invert;
-        this.fIsolate = isolate;
-    }
-
-    /**
-     * Executes the test and stores the results. May be run from a secondary
-     * Thread.
-     */
-    public void run() {
-        try {
-            if (fIsolate) {
-                runExternally();
-            } else {
-                runInternally();
-            }
-
-            if (fInvert) {
-                fInvert = false;
-                throw new AssertionFailedError(
-                        "@KnownFailure expected to fail, but succeeded");
-            }
-        } catch (AssertionFailedError e) {
-            if (!fInvert) {
-                fResult.addFailure(fTest, e);
-            }
-        } catch (ThreadDeath e) { // don't catch ThreadDeath by accident
-            throw e;
-        } catch (Throwable e) {
-            if (!fInvert) {
-                fResult.addError(fTest, e);
-            }
-        }
-    }
-
-    /**
-     * Tells the test case to stop. Only used with isolation. We need to kill
-     * the external process in this case.
-     */
-    public void stop() {
-        if (fProcess != null) {
-            fProcess.destroy();
-        }
-    }
-
-    /**
-     * Runs the test case in the same process. This is basically what a
-     * run-of-the-mill JUnit does, except we might also do it in a secondary
-     * thread.
-     */
-    private void runInternally() throws Throwable {
-        fProtectable.protect();
-    }
-
-    /**
-     * Runs the test case in a different process. This is what we do for
-     * isolating test cases that have side effects or do suffer from them.
-     */
-    private void runExternally() throws Throwable {
-        Throwable throwable = null;
-
-        File file = File.createTempFile("isolation", ".tmp");
-
-        String program = (IS_DALVIK ? "dalvikvm" : "java") +
-                " -classpath " + System.getProperty("java.class.path") +
-                " -Djava.home=" + System.getProperty("java.home") +
-                " -Duser.home=" + System.getProperty("user.home") +
-                " -Djava.io.tmpdir=" + System.getProperty("java.io.tmpdir") +
-                " com.google.coretests.CoreTestIsolator" +
-                " " + fTest.getClass().getName() +
-                " " + fTest.getName() +
-                " " + file.getAbsolutePath();
-        fProcess = Runtime.getRuntime().exec(program);
-
-        int result = fProcess.waitFor();
-
-        if (result != TestRunner.SUCCESS_EXIT) {
-            try {
-                FileInputStream fis = new FileInputStream(file);
-                ObjectInputStream ois = new ObjectInputStream(fis);
-                throwable = (Throwable)ois.readObject();
-                ois.close();
-            } catch (Exception ex) {
-                throwable = new RuntimeException("Error isolating test: " + program, ex);
-            }
-        }
-
-        file.delete();
-
-        if (throwable != null) {
-            throw throwable;
-        }
-    }
-
-}
diff --git a/luni/src/test/java/com/google/coretests/CoreTestRunner.java b/luni/src/test/java/com/google/coretests/CoreTestRunner.java
deleted file mode 100644
index aa62ca4..0000000
--- a/luni/src/test/java/com/google/coretests/CoreTestRunner.java
+++ /dev/null
@@ -1,329 +0,0 @@
-/*
- * Copyright (C) 2009 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 com.google.coretests;
-
-import java.util.ArrayList;
-import java.util.List;
-import java.util.logging.Level;
-import java.util.logging.Logger;
-
-import junit.framework.Test;
-import junit.framework.TestResult;
-import junit.framework.TestSuite;
-import junit.textui.ResultPrinter;
-import junit.textui.TestRunner;
-
-/**
- * A special TestRunner implementation that is able to filter out annotated
- * tests and handles our known failures properly (expects them to fail).
- * Handy when running the Core Libraries tests on Android, the bare-metal
- * Dalvik VM, or the RI.
- */
-public class CoreTestRunner extends TestRunner {
-
-    /**
-     * Reflects our environment.
-     */
-    private static boolean IS_DALVIK = "Dalvik".equals(
-            System.getProperty("java.vm.name"));
-
-    /**
-     * Defines the default flags for running on Dalvik.
-     */
-    private static final int DEFAULT_FLAGS_DALVIK =
-            CoreTestSuite.RUN_ANDROID_ONLY |
-            CoreTestSuite.RUN_NORMAL_TESTS |
-            CoreTestSuite.RUN_KNOWN_FAILURES |
-            CoreTestSuite.RUN_SIDE_EFFECTS |
-            CoreTestSuite.INVERT_KNOWN_FAILURES;
-
-    /**
-     * Defines the default flags for running on an RI.
-     */
-    private static final int DEFAULT_FLAGS_NON_DALVIK =
-            CoreTestSuite.RUN_NORMAL_TESTS |
-            CoreTestSuite.RUN_KNOWN_FAILURES |
-            CoreTestSuite.RUN_SIDE_EFFECTS;
-
-    /**
-     * Holds the flags specified by the user on the command line.
-     */
-    private int fFlags;
-
-    /**
-     * Holds the timeout value specified by the user on the command line.
-     */
-    private int fTimeout;
-
-    private int fStep = 1;
-
-    /**
-     * The path to write XML reports to, or {@code null} for no reports.
-     */
-    private String xmlReportsDirectory;
-
-    /**
-     * Creates a new instance of our CoreTestRunner.
-     */
-    public CoreTestRunner() {
-        super();
-    }
-
-    @Override
-    protected TestResult createTestResult() {
-        return new CoreTestResult(fFlags, fTimeout);
-    }
-
-    protected ResultPrinter createPrinter() {
-        return new CoreTestPrinter(System.out, fFlags);
-    }
-
-    /**
-     * Provides our main entry point.
-     */
-    public static void main(String args[]) {
-        Logger.global.setLevel(Level.OFF);
-
-        System.out.println(
-                "--------------------------------------------------");
-        System.out.println("Android Core Libraries Test Suite");
-        System.out.println("Version 1.0");
-        System.out.println(
-                "Copyright (c) 2009 The Android Open Source Project");
-        System.out.println("");
-
-        CoreTestRunner testRunner = new CoreTestRunner();
-        try {
-            TestResult r = testRunner.start(args);
-
-            System.out.println(
-            "--------------------------------------------------");
-
-            if (!r.wasSuccessful()) {
-                System.exit(FAILURE_EXIT);
-            } else {
-                System.exit(SUCCESS_EXIT);
-            }
-        } catch(Exception e) {
-            System.err.println(e.getMessage());
-            System.exit(EXCEPTION_EXIT);
-        }
-
-    }
-
-    @Override
-    public TestResult doRun(Test suite, boolean wait) {
-        setPrinter(createPrinter());
-
-        /*
-         * Make sure the original suite is unreachable after we have
-         * created the new one, so GC can dispose terminated tests.
-         */
-        CoreTestSuite coreTestSuite = new CoreTestSuite(suite, fFlags, fStep, null);
-
-        XmlReportPrinter xmlReportPrinter = xmlReportsDirectory != null
-                ? new XmlReportPrinter(coreTestSuite)
-                : null;
-
-        TestResult result = super.doRun(coreTestSuite, wait);
-
-        if (xmlReportPrinter != null) {
-            System.out.print("Printing XML Reports... ");
-            xmlReportPrinter.setResults(result);
-            int numFiles = xmlReportPrinter.generateReports(xmlReportsDirectory);
-            System.out.println(numFiles + " files written.");
-        }
-
-        return result;
-    }
-
-    /**
-     * Prints a help screen on the console.
-     */
-    private void showHelp() {
-        System.out.println("Usage: run-core-tests [OPTION]... [TEST]...");
-        System.out.println();
-        System.out.println("Where each TEST is a class name, optionally followed");
-        System.out.println("by \"#\" and a method name, and each OPTION is one of");
-        System.out.println("the following:");
-        System.out.println();
-        System.out.println("    --include-all");
-        System.out.println("    --exclude-all");
-        System.out.println("    --include-android-only");
-        System.out.println("    --exclude-android-only");
-        System.out.println("    --include-broken-tests");
-        System.out.println("    --exclude-broken-tests");
-        System.out.println("    --include-known-failures");
-        System.out.println("    --exclude-known-failures");
-        System.out.println("    --include-normal-tests");
-        System.out.println("    --exclude-normal-tests");
-        System.out.println("    --include-side-effects");
-        System.out.println("    --exclude-side-effects");
-        System.out.println();
-        System.out.println("    --known-failures-must-fail");
-        System.out.println("    --known-failures-must-pass");
-        System.out.println("    --timeout <seconds>");
-        // System.out.println("    --find-side-effect <test>");
-        System.out.println("    --isolate-all");
-        System.out.println("    --isolate-none");
-        System.out.println("    --verbose");
-        System.out.println("    --xml-reports-directory <path>");
-        System.out.println("    --help");
-        System.out.println();
-        System.out.println("Default parameters are:");
-        System.out.println();
-
-        if (IS_DALVIK) {
-            System.out.println("    --include-android-only");
-            System.out.println("    --exclude-broken-tests");
-            System.out.println("    --include-known-failures");
-            System.out.println("    --include-normal-tests");
-            System.out.println("    --include-side-effects");
-            System.out.println("    --known-failures-must-fail");
-        } else {
-            System.out.println("    --exclude-android-only");
-            System.out.println("    --exclude-broken-tests");
-            System.out.println("    --include-known-failures");
-            System.out.println("    --include-normal-tests");
-            System.out.println("    --include-side-effects");
-            System.out.println("    --known-failures-must-pass");
-        }
-
-        System.out.println();
-    }
-
-    /**
-     * Tries to create a Test instance from the given strings. The strings might
-     * either specify a class only or a class plus a method name, separated by
-     * a "#".
-     */
-    private Test createTest(List<String> testCases) throws Exception {
-        TestSuite result = new TestSuite();
-        for (String testCase : testCases) {
-            int p = testCase.indexOf("#");
-            if (p != -1) {
-                String testName = testCase.substring(p + 1);
-                testCase = testCase.substring(0, p);
-
-                result.addTest(TestSuite.createTest(Class.forName(testCase), testName));
-            } else {
-                result.addTest(getTest(testCase));
-            }
-        }
-        return result;
-    }
-
-    @Override
-    protected TestResult start(String args[]) throws Exception {
-        List<String> testNames = new ArrayList<String>();
-        // String victimName = null;
-
-        boolean wait = false;
-
-        if (IS_DALVIK) {
-            fFlags = DEFAULT_FLAGS_DALVIK;
-        } else {
-            fFlags = DEFAULT_FLAGS_NON_DALVIK;
-        }
-
-        for (int i= 0; i < args.length; i++) {
-            if (args[i].startsWith("--")) {
-                if (args[i].equals("--wait")) {
-                    wait = true;
-                } else if (args[i].equals("--include-all")) {
-                    fFlags = fFlags | CoreTestSuite.RUN_ALL_TESTS;
-                } else if (args[i].equals("--exclude-all")) {
-                    fFlags = fFlags & ~CoreTestSuite.RUN_ALL_TESTS;
-                } else if (args[i].equals("--include-android-only")) {
-                    fFlags = fFlags | CoreTestSuite.RUN_ANDROID_ONLY;
-                } else if (args[i].equals("--exclude-android-only")) {
-                    fFlags = fFlags & ~CoreTestSuite.RUN_ANDROID_ONLY;
-                } else if (args[i].equals("--include-broken-tests")) {
-                    fFlags = fFlags | CoreTestSuite.RUN_BROKEN_TESTS;
-                } else if (args[i].equals("--exclude-broken-tests")) {
-                    fFlags = fFlags & ~CoreTestSuite.RUN_BROKEN_TESTS;
-                } else if (args[i].equals("--include-known-failures")) {
-                    fFlags = fFlags | CoreTestSuite.RUN_KNOWN_FAILURES;
-                } else if (args[i].equals("--exclude-known-failures")) {
-                    fFlags = fFlags & ~CoreTestSuite.RUN_KNOWN_FAILURES;
-                } else if (args[i].equals("--include-normal-tests")) {
-                    fFlags = fFlags | CoreTestSuite.RUN_NORMAL_TESTS;
-                } else if (args[i].equals("--exclude-normal-tests")) {
-                    fFlags = fFlags & ~CoreTestSuite.RUN_NORMAL_TESTS;
-                } else if (args[i].equals("--include-side-effects")) {
-                    fFlags = fFlags | CoreTestSuite.RUN_SIDE_EFFECTS;
-                } else if (args[i].equals("--exclude-side-effects")) {
-                    fFlags = fFlags & ~CoreTestSuite.RUN_SIDE_EFFECTS;
-                } else if (args[i].equals("--known-failures-must-fail")) {
-                    fFlags = fFlags | CoreTestSuite.INVERT_KNOWN_FAILURES;
-                } else if (args[i].equals("--known-failures-must-pass")) {
-                    fFlags = fFlags & ~CoreTestSuite.INVERT_KNOWN_FAILURES;
-                } else if (args[i].equals("--timeout")) {
-                    fTimeout = Integer.parseInt(args[++i]);
-                } else if (args[i].equals("--reverse")) {
-                    fFlags = fFlags | CoreTestSuite.REVERSE;
-                } else if (args[i].equals("--step")) {
-                    fStep = Integer.parseInt(args[++i]);
-                } else if (args[i].equals("--isolate-all")) {
-                    fFlags = (fFlags | CoreTestSuite.ISOLATE_ALL) &
-                                   ~CoreTestSuite.ISOLATE_NONE;
-                } else if (args[i].equals("--isolate-none")) {
-                    fFlags = (fFlags | CoreTestSuite.ISOLATE_NONE) &
-                                   ~CoreTestSuite.ISOLATE_ALL;
-                } else if (args[i].equals("--verbose")) {
-                    fFlags = fFlags | CoreTestSuite.VERBOSE;
-                // } else if (args[i].equals("--find-side-effect")) {
-                //    victimName = args[++i];
-                } else if (args[i].equals("--dry-run")) {
-                    fFlags = fFlags | CoreTestSuite.DRY_RUN;
-                } else if (args[i].equals("--xml-reports-directory")) {
-                    xmlReportsDirectory = args[++i];
-                } else if (args[i].equals("--help")) {
-                    showHelp();
-                    System.exit(1);
-                } else {
-                    unknownArgument(args[i]);
-                }
-            } else if (args[i].startsWith("-")) {
-                unknownArgument(args[i]);
-            } else {
-                testNames.add(args[i]);
-            }
-        }
-
-        if (IS_DALVIK) {
-            System.out.println("Using Dalvik VM version " +
-                    System.getProperty("java.vm.version"));
-        } else {
-            System.out.println("Using Java VM version " +
-                    System.getProperty("java.version"));
-        }
-        System.out.println();
-
-        try {
-            return doRun(createTest(testNames), wait);
-        }
-        catch(Exception e) {
-            e.printStackTrace();
-            throw new Exception("Could not create and run test suite: " + e);
-        }
-    }
-
-    private static void unknownArgument(String arg) {
-        System.err.println("Unknown argument " + arg + ", try --help");
-        System.exit(1);
-    }
-}
diff --git a/luni/src/test/java/com/google/coretests/CoreTestSuite.java b/luni/src/test/java/com/google/coretests/CoreTestSuite.java
deleted file mode 100644
index 8e94b83..0000000
--- a/luni/src/test/java/com/google/coretests/CoreTestSuite.java
+++ /dev/null
@@ -1,357 +0,0 @@
-/*
- * Copyright (C) 2009 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 com.google.coretests;
-
-import java.lang.reflect.Field;
-import java.lang.reflect.Method;
-import java.lang.reflect.Modifier;
-import java.util.Enumeration;
-import java.util.Vector;
-
-import junit.framework.Test;
-import junit.framework.TestCase;
-import junit.framework.TestFailure;
-import junit.framework.TestResult;
-import junit.framework.TestSuite;
-import dalvik.annotation.AndroidOnly;
-import dalvik.annotation.BrokenTest;
-import dalvik.annotation.KnownFailure;
-import dalvik.annotation.SideEffect;
-
-/**
- * A special TestSuite implementation that flattens the hierarchy of a given
- * JUnit TestSuite and removes tests after executing them. This is so the core
- * tests actually have a chance to succeed, since they do consume quite some
- * memory and many tests do not (have a chance to) cleanup properly after
- * themselves. The class also implements our filtering mechanism for tests, so
- * it becomes easy to only include or exclude tests based on their annotations
- * (like, say, execute all Android-only tests that are not known to be broken).
- */
-public class CoreTestSuite implements Test {
-
-    /**
-     * Include all normal tests in the suite.
-     */
-    public static final int RUN_NORMAL_TESTS = 1;
-
-    /**
-     * Include all broken tests in the suite.
-     */
-    public static final int RUN_BROKEN_TESTS = 2;
-
-    /**
-     * Include all known failures in the suite.
-     */
-    public static final int RUN_KNOWN_FAILURES = 4;
-
-    /**
-     * Include all Android-only tests in the suite.
-     */
-    public static final int RUN_ANDROID_ONLY = 8;
-
-    /**
-     * Include side-effective tests in the suite.
-     */
-    public static final int RUN_SIDE_EFFECTS = 16;
-
-    /**
-     * Include all tests in the suite.
-     */
-    public static final int RUN_ALL_TESTS =
-            RUN_NORMAL_TESTS | RUN_BROKEN_TESTS |
-            RUN_KNOWN_FAILURES | RUN_SIDE_EFFECTS | RUN_ANDROID_ONLY;
-
-    /**
-     * Special treatment for known failures: they are expected to fail, so we
-     * throw an Exception if they succeed and accept them failing.
-     */
-    public static final int INVERT_KNOWN_FAILURES = 32;
-
-    /**
-     * Run each test in its own VM.
-     */
-    public static final int ISOLATE_ALL = 64;
-
-    /**
-     * Run no test in its own VM.
-     */
-    public static final int ISOLATE_NONE = 128;
-
-    /**
-     * Be verbose.
-     */
-    public static final int VERBOSE = 256;
-
-    public static final int REVERSE = 512;
-
-    public static final int DRY_RUN = 1024;
-
-    private final String name;
-
-    /**
-     * The total number of tests in the original suite.
-     */
-    protected int fTotalCount;
-
-    /**
-     * The number of Android-only tests in the original suite.
-     */
-    protected int fAndroidOnlyCount;
-
-    /**
-     * The number of broken tests in the original suite.
-     */
-    protected int fBrokenCount;
-
-    /**
-     * The number of known failures in the original suite.
-     */
-    protected int fKnownFailureCount;
-
-    /**
-     * The number of side-effective tests in the original suite.
-     */
-    protected int fSideEffectCount;
-
-    /**
-     * The number of normal (non-annotated) tests in the original suite.
-     */
-    protected int fNormalCount;
-
-    /**
-     * The number of ignored tests, that is, the number of tests that were
-     * excluded from this suite due to their annotations.
-     */
-    protected int fIgnoredCount;
-
-    /**
-     * Contains the actual test cases in a reverse-ordered, flat list.
-     */
-    private Vector<Test> fTests = new Vector<Test>();
-
-    private TestCase fVictim;
-
-    private int fStep;
-
-    private int fFlags;
-
-    /**
-     * Creates a new CoreTestSuite for the given ordinary JUnit Test (which may
-     * be a TestCase or TestSuite). The CoreTestSuite will be a flattened and
-     * potentially filtered subset of the original JUnit Test. The flags
-     * determine the way we filter.
-     */
-    public CoreTestSuite(Test suite, int flags, int step, TestCase victim) {
-        super();
-
-        name = suite.toString();
-        fStep = step;
-        addAndFlatten(suite, flags);
-        fVictim = victim;
-        fFlags = flags;
-    }
-
-    /**
-     * Adds the given ordinary JUnit Test (which may be a TestCase or TestSuite)
-     * to this CoreTestSuite. Note we are storing the tests in reverse order,
-     * so it's easier to remove a finished test from the end of the list.
-     */
-    private void addAndFlatten(Test test, int flags) {
-        if (test instanceof TestSuite) {
-            TestSuite suite = (TestSuite)test;
-
-            if ((flags & REVERSE) != 0) {
-                for (int i = suite.testCount() - 1; i >= 0; i--) {
-                    addAndFlatten(suite.testAt(i), flags);
-                }
-            } else {
-                for (int i = 0; i < suite.testCount(); i++) {
-                    addAndFlatten(suite.testAt(i), flags);
-                }
-            }
-        } else if (test instanceof TestCase) {
-            TestCase testCase = (TestCase)test;
-            boolean ignoreMe = false;
-
-            boolean isAndroidOnly = hasAnnotation(testCase, AndroidOnly.class);
-            boolean isBrokenTest = hasAnnotation(testCase, BrokenTest.class);
-            boolean isKnownFailure = hasAnnotation(testCase, KnownFailure.class);
-            boolean isSideEffect = hasAnnotation(testCase, SideEffect.class);
-            boolean isNormalTest =
-                    !(isAndroidOnly || isBrokenTest || isKnownFailure ||
-                      isSideEffect);
-
-            if (isAndroidOnly) {
-                fAndroidOnlyCount++;
-            }
-
-            if (isBrokenTest) {
-                fBrokenCount++;
-            }
-
-            if (isKnownFailure) {
-                fKnownFailureCount++;
-            }
-
-            if (isNormalTest) {
-                fNormalCount++;
-            }
-
-            if (isSideEffect) {
-                fSideEffectCount++;
-            }
-
-            if ((flags & RUN_ANDROID_ONLY) == 0 && isAndroidOnly) {
-                ignoreMe = true;
-            }
-
-            if ((flags & RUN_BROKEN_TESTS) == 0 && isBrokenTest) {
-                ignoreMe = true;
-            }
-
-            if ((flags & RUN_KNOWN_FAILURES) == 0 && isKnownFailure) {
-                ignoreMe = true;
-            }
-
-            if (((flags & RUN_NORMAL_TESTS) == 0) && isNormalTest) {
-                ignoreMe = true;
-            }
-
-            if (((flags & RUN_SIDE_EFFECTS) == 0) && isSideEffect) {
-                ignoreMe = true;
-            }
-
-            this.fTotalCount++;
-
-            if (!ignoreMe) {
-                fTests.add(test);
-            } else {
-                this.fIgnoredCount++;
-            }
-        } else {
-            System.out.println("Warning: Don't know how to handle " +
-                    test.getClass().getName() + " " + test.toString());
-        }
-    }
-
-    /**
-     * Checks whether the given TestCase class has the given annotation.
-     */
-    @SuppressWarnings("unchecked")
-    private boolean hasAnnotation(TestCase test, Class clazz) {
-        try {
-            Method method = test.getClass().getMethod(test.getName());
-            return method.getAnnotation(clazz) != null;
-        } catch (Exception e) {
-            // Ignore
-        }
-
-        return false;
-    }
-
-    /**
-     * Runs the tests and collects their result in a TestResult.
-     */
-    public void run(TestResult result) {
-        // Run tests
-        int i = 0;
-
-        while (fTests.size() != 0 && !result.shouldStop()) {
-            TestCase test = (TestCase)fTests.elementAt(i);
-
-            Thread.currentThread().setContextClassLoader(
-                    test.getClass().getClassLoader());
-
-            test.run(result);
-
-            /*
-            if (fVictim != null) {
-                TestResult dummy = fVictim.run();
-
-                if (dummy.failureCount() != 0) {
-                    result.addError(fTests.elementAt(i), new RuntimeException(
-                            "Probable side effect",
-                            ((TestFailure)dummy.failures().nextElement()).
-                            thrownException()));
-                } else if (dummy.errorCount() != 0) {
-                    result.addError(fTests.elementAt(i), new RuntimeException(
-                            "Probable side effect",
-                            ((TestFailure)dummy.errors().nextElement()).
-                            thrownException()));
-                }
-            }
-            */
-
-            fTests.remove(i);
-
-            if (fTests.size() != 0) {
-                i = (i + fStep - 1) % fTests.size();
-            }
-
-        }
-
-        // Forward overall stats to TestResult, so ResultPrinter can see it.
-        if (result instanceof CoreTestResult) {
-            ((CoreTestResult)result).updateStats(
-                    fTotalCount, fAndroidOnlyCount, fBrokenCount,
-                    fKnownFailureCount, fNormalCount, fIgnoredCount,
-                    fSideEffectCount);
-        }
-    }
-
-    /**
-     * Nulls all reference fields in the given test object. This method helps
-     * us with those test classes that don't have an explicit tearDown()
-     * method. Normally the garbage collector should take care of everything,
-     * but it can't hurt to support it a bit.
-     */
-    private void cleanup(TestCase test) {
-        Field[] fields = test.getClass().getDeclaredFields();
-        for (int i = 0; i < fields.length; i++) {
-            Field f = fields[i];
-            if (!f.getType().isPrimitive() &&
-                    (f.getModifiers() & Modifier.STATIC) == 0) {
-                try {
-                    f.setAccessible(true);
-                    f.set(test, null);
-                } catch (Exception ex) {
-                    // Nothing we can do about it.
-                }
-            }
-        }
-    }
-
-    /**
-     * Returns the tests as an enumeration. Note this is empty once the tests
-     * have been executed.
-     */
-    @SuppressWarnings("unchecked")
-    public Enumeration tests() {
-        return fTests.elements();
-    }
-
-    /**
-     * Returns the number of tests in the suite. Note this is zero once the
-     * tests have been executed.
-     */
-    public int countTestCases() {
-        return fTests.size();
-    }
-
-    @Override public String toString() {
-        return name;
-    }
-}
diff --git a/luni/src/test/java/com/google/coretests/CoreTestTimeout.java b/luni/src/test/java/com/google/coretests/CoreTestTimeout.java
deleted file mode 100644
index 864e4e4..0000000
--- a/luni/src/test/java/com/google/coretests/CoreTestTimeout.java
+++ /dev/null
@@ -1,32 +0,0 @@
-/*
- * Copyright (C) 2009 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 com.google.coretests;
-
-/**
- * A special exception for timeouts during tests. The CoreResultPrinter knows
- * how to handle this.
- */
-@SuppressWarnings("serial")
-public class CoreTestTimeout extends RuntimeException {
-
-    /**
-     * Creates a new instance with the given message.
-     */
-    public CoreTestTimeout(String message) {
-        super(message);
-    }
-
-}
diff --git a/luni/src/test/java/com/google/coretests/Main.java b/luni/src/test/java/com/google/coretests/Main.java
deleted file mode 100644
index 73c8ce5..0000000
--- a/luni/src/test/java/com/google/coretests/Main.java
+++ /dev/null
@@ -1,50 +0,0 @@
-/*
- * Copyright (C) 2008 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 com.google.coretests;
-
-import junit.textui.TestRunner;
-import tests.AllTests;
-
-/**
- * Main class to run the core tests.
- */
-public class Main
-{
-    public static void main(String[] args) {
-        if (args.length == 0) {
-            System.out.println("Running all tests...");
-            CoreTestRunner.main(new String[] { "tests.AllTests" });
-        } else if ("--stats".equals(args[0])) {
-            // Delegate to new stats test runner
-            String[] args2 = new String[args.length - 1];
-            System.arraycopy(args, 1, args2, 0, args2.length);
-
-            if (args2.length == 0) {
-                System.out.println("Running all tests with stats...");
-                StatTestRunner.run(AllTests.suite());
-            } else {
-                System.out.println("Running selected tests with stats...");
-                StatTestRunner.main(args2);
-            }
-        } else {
-            System.out.println("Running selected tests...");
-            CoreTestRunner.main(args);
-        }
-
-        Runtime.getRuntime().halt(0);
-    }
-}
diff --git a/luni/src/test/java/com/google/coretests/PerfStatCollector.java b/luni/src/test/java/com/google/coretests/PerfStatCollector.java
deleted file mode 100644
index 4ef7c03..0000000
--- a/luni/src/test/java/com/google/coretests/PerfStatCollector.java
+++ /dev/null
@@ -1,257 +0,0 @@
-/*
- * Copyright (C) 2008 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 com.google.coretests;
-
-import dalvik.system.VMDebug;
-
-import junit.framework.AssertionFailedError;
-import junit.framework.Test;
-import junit.framework.TestListener;
-
-import java.io.PrintStream;
-import java.util.ArrayList;
-import java.util.Iterator;
-
-public class PerfStatCollector implements TestListener {
-
-    public boolean listAll = false;
-    public boolean listBad = false;
-    public long thresholdDuration = 3600 * 1000; // in milliseconds
-    public boolean twoLines = true;
-    public boolean bigMarking = true;
-
-    private static boolean havePreciseTime =
-        VMDebug.threadCpuTimeNanos() != -1;
-
-    public class Item {
-        Test test;
-        long startTime, duration;
-        int res;
-        public boolean existsInStore;
-        public int id;
-        public int bestRes;
-        public long lastBestAt;
-        public int lastRes;
-        public long lastDuration;
-        public int statCount;
-        public double statAvgDuration;
-        public long statMinDuration;
-        public long statMaxDuration;
-        int adhocRelevance;
-        public int histRelevance;
-        public boolean isTransition;
-        boolean printed = false;
-
-        void update(boolean rBad, long rthDurat) {
-            // AdHoc Evaluation:
-            if (rBad && (res != 0)) {
-                // no success:
-                adhocRelevance = 2;
-            }
-            else if (duration >= rthDurat) {
-                // long duration:
-                adhocRelevance = 1;
-            }
-            else {
-                adhocRelevance = 0;
-            }
-
-            StatsStore.use1(this);
-        }
-
-        void print1(PrintStream out, boolean bigMarking) {
-            switch (histRelevance) {
-            case -4:
-                if (bigMarking) {
-                    out.println();
-                    out.println("*** *** *** *** *** ATTENTION *** *** *** *** ***");
-                    out.println("*** *** *** *** *** ATTENTION *** *** *** *** ***");
-                    out.println("*** *** *** *** *** ATTENTION *** *** *** *** ***");
-                    out.println("Test ran SUCCESSFULLY once, but NOT this time!!!!");
-                    out.println("*** *** *** *** *** ATTENTION *** *** *** *** ***");
-                    out.println("*** *** *** *** *** ATTENTION *** *** *** *** ***");
-                    out.println("*** *** *** *** *** ATTENTION *** *** *** *** ***");
-                }
-                out.print("-4 VBAD"); break;
-            case 4: out.print(" 4 Good"); break;
-            case 3: out.print(" 3 good"); break;
-            case -2: out.print("-2 SLOW"); break;
-            case 2: out.print(" 2 Fast"); break;
-            case 1: out.print(" 1 fast"); break;
-            case -3:
-                if (res == -2) out.print("-3 FAIL");
-                else out.print("-3 ERR ");
-                break;
-            default:
-                if (res == 0) out.print("       ");
-                else if (res == -2) out.print("   fail");
-                else out.print("   err ");
-            }
-            if (isTransition) out.print("! ");
-            else out.print("  ");
-            out.print(test.toString());
-            out.format(": %d# %d(%d) [%d..%d] %.1f ms",
-                    statCount, duration, lastDuration,
-                    statMinDuration, statMaxDuration, statAvgDuration);
-            out.println();
-            printed = true;
-        }
-
-        void print2(PrintStream out, boolean bigMarking) {
-            out.format("%5d. ", id);
-
-            out.println(test.toString());
-            out.print("       ");
-
-            switch (histRelevance) {
-                case -4: out.print("FAIL"); break;
-                case 4: out.print("PASS"); break;
-                case 3: out.print("PASS"); break;
-                case -2: out.print("SLOW"); break;
-                case 2: out.print("FAST"); break;
-                case 1: out.print("PASS"); break;
-                case -3:
-                    if (res == -2) out.print("FAIL");
-                    else out.print("ERR ");
-                    break;
-                default:
-                    if (res == 0) out.print("PASS");
-                    else if (res == -2) out.print("FAIL");
-                    else out.print("XCPT");
-            }
-
-            out.format(" %d ms (min %d ms, max %d ms, avg %#.1f ms, %d runs)",
-                    duration,
-                    statMinDuration, statMaxDuration, statAvgDuration,
-                    statCount);
-            out.println();
-
-            printed = true;
-        }
-
-        void print(PrintStream out, boolean bigMarking) {
-            if (twoLines) print2(out, bigMarking);
-            else print1(out, bigMarking);
-        }
-
-        boolean checkPrint(PrintStream out) {
-            if (printed) return false;
-            print(out, false);
-            return true;
-        }
-    }
-
-    ArrayList<Item> items;
-    Item current;
-
-    PrintStream fWriter;
-    int fColumn= 0;
-
-    public PerfStatCollector(PrintStream writer)  {
-        fWriter= writer;
-        items = new ArrayList();
-    }
-
-    synchronized void digest() {
-        int totalCnt = 0;
-        int adhocRelevantCnt = 0;
-        int histRelevantCnt = 0;
-        long evalStartTime = System.currentTimeMillis();
-        PrintStream out = fWriter;
-        out.println("Failure and Performance Statistics:");
-        Iterator<Item> r = items.iterator();
-        while (r.hasNext()) {
-            Item item = r.next();
-            item.update(listBad, thresholdDuration);
-            if (item.histRelevance != 0) {
-                item.print(out, bigMarking);
-                histRelevantCnt++;
-            }
-            if (item.adhocRelevance != 0) {
-                if (item.checkPrint(out))
-                    adhocRelevantCnt++;
-            }
-            if (listAll) item.checkPrint(out);
-            totalCnt++;
-        }
-        long evalDuration = System.currentTimeMillis() - evalStartTime;
-        out.println();
-        out.print(totalCnt); out.println(" tests run totally.");
-        out.print(histRelevantCnt);
-                out.println(" tests listed due to historical relevance.");
-//        out.print(adhocRelevantCnt);
-//                out.println(" tests listed due to ad-hoc-relevance.");
-//        out.print(totalCnt - histRelevantCnt - adhocRelevantCnt);
-//                out.println(" tests NOT listed due to relevance.");
-        out.println();
-        out.print("Time used in Statistics Acquisition: ");
-        out.print(evalDuration);
-        out.print("ms");
-        out.println();
-    }
-
-
-    public PrintStream getWriter() {
-        return fWriter;
-    }
-
-    /**
-     * @see junit.framework.TestListener#addError(Test, Throwable)
-     */
-    public void addError(Test test, Throwable t) {
-        current.res = -1;
-    }
-
-    /**
-     * @see junit.framework.TestListener#addFailure(Test, AssertionFailedError)
-     */
-    public void addFailure(Test test, AssertionFailedError t) {
-        current.res = -2;
-    }
-
-    /**
-     * @see junit.framework.TestListener#startTest(Test)
-     */
-    public void startTest(Test test) {
-        System.gc();
-        current = new Item();
-        current.test = test;
-        current.startTime = currentTimeMillis();
-        items.add(current);
-    }
-
-    /**
-     * @see junit.framework.TestListener#endTest(Test)
-     */
-    public void endTest(Test test) {
-        current.duration = currentTimeMillis() - current.startTime;
-    }
-
-    /*
-     * Returns a "current time" in ms. Depending on the environment, this is
-     * either the actual CPU time out current thread has used so far, or the
-     * wall clock time of the system.
-     */
-    private long currentTimeMillis() {
-        if (havePreciseTime) {
-            return VMDebug.threadCpuTimeNanos() / 1000;
-        } else {
-            return System.currentTimeMillis();
-        }
-    }
-
-}
diff --git a/luni/src/test/java/com/google/coretests/ResultPrinter.java b/luni/src/test/java/com/google/coretests/ResultPrinter.java
deleted file mode 100644
index 93f3f2b..0000000
--- a/luni/src/test/java/com/google/coretests/ResultPrinter.java
+++ /dev/null
@@ -1,157 +0,0 @@
-/*
- * Copyright (C) 2008 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 com.google.coretests;
-
-import java.io.PrintStream;
-// The following line was removed for compatibility with Android libraries.
-//import java.text.NumberFormat;
-import java.util.Enumeration;
-
-import junit.framework.AssertionFailedError;
-import junit.framework.Test;
-import junit.framework.TestFailure;
-import junit.framework.TestListener;
-import junit.framework.TestResult;
-import junit.runner.BaseTestRunner;
-
-public class ResultPrinter implements TestListener {
-    PrintStream fWriter;
-    int fColumn= 0;
-
-    public ResultPrinter(PrintStream writer) {
-        fWriter= writer;
-    }
-
-    /* API for use by textui.TestRunner
-     */
-
-    synchronized void print(TestResult result, long runTime) {
-        printHeader(runTime);
-        printErrors(result);
-        printFailures(result);
-        printFooter(result);
-    }
-
-    void printWaitPrompt() {
-        getWriter().println();
-        getWriter().println("<RETURN> to continue");
-    }
-
-    /* Internal methods
-     */
-
-    protected void printHeader(long runTime) {
-        getWriter().println();
-        getWriter().println("Time: "+elapsedTimeAsString(runTime));
-    }
-
-    protected void printErrors(TestResult result) {
-        printDefects(result.errors(), result.errorCount(), "error");
-    }
-
-    protected void printFailures(TestResult result) {
-        printDefects(result.failures(), result.failureCount(), "failure");
-    }
-
-    protected void printDefects(Enumeration booBoos, int count, String type) {
-        if (count == 0) return;
-        if (count == 1)
-            getWriter().println("There was " + count + " " + type + ":");
-        else
-            getWriter().println("There were " + count + " " + type + "s:");
-        for (int i= 1; booBoos.hasMoreElements(); i++) {
-            printDefect((TestFailure) booBoos.nextElement(), i);
-        }
-    }
-
-    public void printDefect(TestFailure booBoo, int count) { // only public for testing purposes
-        printDefectHeader(booBoo, count);
-        printDefectTrace(booBoo);
-    }
-
-    protected void printDefectHeader(TestFailure booBoo, int count) {
-        // I feel like making this a println, then adding a line giving the throwable a chance to print something
-        // before we get to the stack trace.
-        getWriter().print(count + ") " + booBoo.failedTest());
-    }
-
-    protected void printDefectTrace(TestFailure booBoo) {
-        getWriter().print(BaseTestRunner.getFilteredTrace(booBoo.trace()));
-    }
-
-    protected void printFooter(TestResult result) {
-        if (result.wasSuccessful()) {
-            getWriter().println();
-            getWriter().print("OK");
-            getWriter().println (" (" + result.runCount() + " test" + (result.runCount() == 1 ? "": "s") + ")");
-
-        } else {
-            getWriter().println();
-            getWriter().println("FAILURES!!!");
-            getWriter().println("Tests run: "+result.runCount()+
-                         ",  Failures: "+result.failureCount()+
-                         ",  Errors: "+result.errorCount());
-        }
-        getWriter().println();
-    }
-
-
-    /**
-     * Returns the formatted string of the elapsed time.
-     * Duplicated from BaseTestRunner. Fix it.
-     */
-    protected String elapsedTimeAsString(long runTime) {
-            // The following line was altered for compatibility with
-            // Android libraries.
-        return Double.toString((double)runTime/1000);
-    }
-
-    public PrintStream getWriter() {
-        return fWriter;
-    }
-    /**
-     * @see junit.framework.TestListener#addError(Test, Throwable)
-     */
-    public void addError(Test test, Throwable t) {
-        getWriter().print("E");
-    }
-
-    /**
-     * @see junit.framework.TestListener#addFailure(Test, AssertionFailedError)
-     */
-    public void addFailure(Test test, AssertionFailedError t) {
-        getWriter().print("F");
-    }
-
-    /**
-     * @see junit.framework.TestListener#endTest(Test)
-     */
-    public void endTest(Test test) {
-    }
-
-    /**
-     * @see junit.framework.TestListener#startTest(Test)
-     */
-    public void startTest(Test test) {
-        getWriter().print(".");
-        if (fColumn++ >= 40) {
-            getWriter().println();
-            fColumn= 0;
-        }
-    }
-
-}
diff --git a/luni/src/test/java/com/google/coretests/StatTestRunner.java b/luni/src/test/java/com/google/coretests/StatTestRunner.java
deleted file mode 100644
index 602a241..0000000
--- a/luni/src/test/java/com/google/coretests/StatTestRunner.java
+++ /dev/null
@@ -1,230 +0,0 @@
-/*
- * Copyright (C) 2008 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 com.google.coretests;
-
-import junit.framework.Test;
-import junit.framework.TestResult;
-import junit.framework.TestSuite;
-import junit.runner.BaseTestRunner;
-import junit.runner.StandardTestSuiteLoader;
-import junit.runner.TestSuiteLoader;
-
-import java.io.PrintStream;
-
-/**
- * A command line based tool to run tests.
- * <pre>
- * java junit.textui.TestRunner [-wait] TestCaseClass
- * </pre>
- * TestRunner expects the name of a TestCase class as argument.
- * If this class defines a static <code>suite</code> method it
- * will be invoked and the returned test is run. Otherwise all
- * the methods starting with "test" having no arguments are run.
- * <p>
- * When the wait command line argument is given TestRunner
- * waits until the users types RETURN.
- * <p>
- * TestRunner prints a trace as the tests are executed followed by a
- * summary at the end.
- */
-public class StatTestRunner extends BaseTestRunner {
-    private ResultPrinter fPrinter;
-    private PerfStatCollector fPerfStatCollector;
-
-    public static final int SUCCESS_EXIT= 0;
-    public static final int FAILURE_EXIT= 1;
-    public static final int EXCEPTION_EXIT= 2;
-
-    public static final String DEFAULT_DATABASE = "sqlite:/coretests.db";
-    public static final String DEFAULT_DRIVER = "SQLite.JDBCDriver";
-
-    public static String connectionURL;
-    public static String jdbcDriver;
-
-    /**
-     * Constructs a TestRunner.
-     */
-    public StatTestRunner() {
-        this(System.out);
-    }
-
-    /**
-     * Constructs a TestRunner using the given stream for all the output
-     */
-    public StatTestRunner(PrintStream writer) {
-        this(new ResultPrinter(writer));
-    }
-
-    /**
-     * Constructs a TestRunner using the given ResultPrinter all the output
-     */
-    public StatTestRunner(ResultPrinter printer) {
-        fPrinter= printer;
-        fPerfStatCollector = new PerfStatCollector(printer.getWriter());
-    }
-
-    /**
-     * Runs a suite extracted from a TestCase subclass.
-     */
-    static public void run(Class testClass) {
-        run(new TestSuite(testClass));
-    }
-
-    /**
-     * Runs a single test and collects its results.
-     * This method can be used to start a test run
-     * from your program.
-     * <pre>
-     * public static void main (String[] args) {
-     *     test.textui.TestRunner.run(suite());
-     * }
-     * </pre>
-     */
-    static public TestResult run(Test test) {
-        StatTestRunner runner= new StatTestRunner();
-        try {
-            return runner.doRun(test, false);
-        }
-        catch (Exception e) {
-            return null;
-        }
-    }
-
-    /**
-     * Runs a single test and waits until the user
-     * types RETURN.
-     */
-    static public void runAndWait(Test suite) {
-        StatTestRunner aTestRunner= new StatTestRunner();
-        try {
-            aTestRunner.doRun(suite, true);
-        }
-        catch (Exception e) {}
-    }
-
-    /**
-     * Always use the StandardTestSuiteLoader. Overridden from
-     * BaseTestRunner.
-     */
-    public TestSuiteLoader getLoader() {
-        return new StandardTestSuiteLoader();
-    }
-
-    public void testFailed(int status, Test test, Throwable t) {
-    }
-
-    public void testStarted(String testName) {
-    }
-
-    public void testEnded(String testName) {
-    }
-
-    public TestResult doRun(Test suite, boolean wait) throws Exception {
-        StatsStore.open(jdbcDriver, connectionURL);
-        TestResult result = new TestResult();
-        result.addListener(fPrinter);
-        result.addListener(fPerfStatCollector);
-        long startTime= System.currentTimeMillis();
-        StatsStore.now = startTime;
-        suite.run(result);
-        long endTime= System.currentTimeMillis();
-        long runTime= endTime-startTime;
-        fPrinter.print(result, runTime);
-        fPerfStatCollector.digest();
-        StatsStore.close();
-
-        pause(wait);
-        return result;
-    }
-
-    protected void pause(boolean wait) {
-        if (!wait) return;
-        fPrinter.printWaitPrompt();
-        try {
-            System.in.read();
-        }
-        catch(Exception e) {
-        }
-    }
-
-    public static void main(String args[]) {
-        StatTestRunner aTestRunner= new StatTestRunner();
-        try {
-            TestResult r= aTestRunner.start(args);
-            if (!r.wasSuccessful())
-                System.exit(FAILURE_EXIT);
-            System.exit(SUCCESS_EXIT);
-        } catch(Exception e) {
-            System.err.println(e.getMessage());
-            System.exit(EXCEPTION_EXIT);
-        }
-    }
-
-    /**
-     * Starts a test run. Analyzes the command line arguments
-     * and runs the given test suite.
-     */
-    protected TestResult start(String args[]) throws Exception {
-        String testCase= "";
-        boolean wait= false;
-
-        jdbcDriver = System.getProperty("android.coretests.driver", DEFAULT_DRIVER);
-        connectionURL = System.getProperty("android.coretests.database", "jdbc:" + DEFAULT_DATABASE);
-
-        for (int i= 0; i < args.length; i++) {
-            if (args[i].equals("--all"))
-                fPerfStatCollector.listAll = true;
-            else if (args[i].equals("--bad"))
-                fPerfStatCollector.listBad = true;
-            else if (args[i].equals("--nobig"))
-                fPerfStatCollector.bigMarking = false;
-            else if (args[i].equals("--s")) {
-                fPerfStatCollector.thresholdDuration =
-                    Integer.valueOf(args[++i]);
-            } else if (args[i].equals("-wait"))
-                wait= true;
-            else if (args[i].equals("-c"))
-                testCase= extractClassName(args[++i]);
-            else if (args[i].equals("-v"))
-                System.err.println("JUnit "+Version.id()+" (plus Android performance stats)");
-            else
-                testCase= args[i];
-        }
-
-        if (testCase.equals(""))
-            throw new Exception("Usage: TestRunner [-wait] testCaseName, where name is the name of the TestCase class");
-
-        try {
-            Test suite= getTest(testCase);
-            return doRun(suite, wait);
-        }
-        catch (Exception e) {
-            throw new Exception("Exception: " + e);
-        }
-    }
-
-    protected void runFailed(String message) {
-        System.err.println(message);
-        System.exit(FAILURE_EXIT);
-    }
-
-    public void setPrinter(ResultPrinter printer) {
-        fPrinter= printer;
-    }
-
-
-}
diff --git a/luni/src/test/java/com/google/coretests/StatsStore.java b/luni/src/test/java/com/google/coretests/StatsStore.java
deleted file mode 100644
index 2c18ab3..0000000
--- a/luni/src/test/java/com/google/coretests/StatsStore.java
+++ /dev/null
@@ -1,309 +0,0 @@
-/*
- * Copyright (C) 2008 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 com.google.coretests;
-
-
-import junit.framework.Test;
-
-import java.io.File;
-import java.sql.Connection;
-import java.sql.DriverManager;
-import java.sql.PreparedStatement;
-import java.sql.ResultSet;
-import java.sql.SQLException;
-import java.sql.Statement;
-
-
-public class StatsStore {
-
-    static final String sysVersion = "1.0";
-
-    static Connection conn;
-    static Statement stmt;
-    static PreparedStatement insertStmt, selectByNameStmt, updateStmt;
-    static PreparedStatement insertDetStmt, insertEventStmt;
-    static PreparedStatement selectAllStmt;
-
-    public static long now;
-
-    static int compareDuration(long dur, long refDur) {
-        long diff = dur - refDur;
-        if (diff <= 0) {
-            if ((double)-diff / refDur > 0.5) return 1; // remarkably faster
-            else return 0; // equivalent duration (maybe a bit faster)
-        }
-        else if (diff < 20) return 0; // not measurably slower: equivalent duration
-        else if ((double)diff / refDur < 0.2) return 0; // just little slower: equivalent duration
-        else return -1; // relevantly SLOWer
-    }
-
-    static void initStats(PerfStatCollector.Item a) {
-        a.statMinDuration = a.duration;
-        a.statMaxDuration = a.duration;
-        a.statAvgDuration = a.duration;
-        a.statCount = 1;
-    }
-
-    static void adjustStats(PerfStatCollector.Item a) {
-        if (a.duration < a.statMinDuration) a.statMinDuration = a.duration;
-        else
-        if (a.duration > a.statMaxDuration) a.statMaxDuration = a.duration;
-        a.statAvgDuration = ((a.statAvgDuration * a.statCount + a.duration) / (a.statCount + 1));
-        a.statCount++;
-    }
-
-    static void adjustStatsOptimistic(PerfStatCollector.Item a) {
-        adjustStats(a);
-        // Could consider reducing a.statMaxDuration.
-    }
-
-    static void use1(PerfStatCollector.Item a) {
-        Test test;
-        int pos;
-        PreparedStatement selectStmt = selectByNameStmt;
-        try {
-            try {
-                insertStmt.setString(1, a.test.toString());
-                insertStmt.execute();
-            } catch (SQLException e) {}
-            selectStmt.setString(1, a.test.toString());
-            ResultSet row = selectStmt.executeQuery();
-            row.first();
-            pos = 1;
-            a.id = row.getInt(pos); pos++;
-            a.bestRes = row.getInt(pos); pos++;
-            a.lastBestAt = row.getLong(pos); pos++;
-            a.lastRes = row.getInt(pos); pos++;
-            a.lastDuration = row.getLong(pos); pos++;
-            a.statCount = row.getInt(pos); pos++;
-            a.statAvgDuration = row.getDouble(pos); pos++;
-            a.statMinDuration = row.getLong(pos); pos++;
-            a.statMaxDuration = row.getLong(pos); pos++;
-            if (a.res == 0) {
-                if (a.bestRes == 100) {
-                    a.bestRes = 0; a.lastBestAt = now;
-                    a.histRelevance = 0; // Good from scratch.
-                    a.isTransition = false;
-                    initStats(a);
-                } else if (a.bestRes != 0) {
-                    a.bestRes = 0; a.lastBestAt = now;
-                    a.histRelevance = 4; // "Good" for the first time:
-                    a.isTransition = true; // was bad before.
-                    initStats(a);
-                } else if (a.lastRes != 0) {
-                    a.bestRes = 0; a.lastBestAt = now;
-                    a.histRelevance = 3; // "good" again:
-                    a.isTransition = true; // was bad in between.
-                    adjustStats(a);
-                } else {
-                    // res == lastRes == bestRes == 0:
-                    int cmp = compareDuration(a.duration, a.statMinDuration);
-                    if (cmp >= 0) {
-                        a.bestRes = 0; a.lastBestAt = now;
-                        if (cmp > 0) {
-                            a.histRelevance = 2; // "Fast"er than ever before.
-                            a.isTransition = true;
-                            adjustStatsOptimistic(a);
-                        } else if (compareDuration(a.duration, a.lastDuration) > 0) {
-                            // As fast as best but faster than last run:
-                            a.histRelevance = 1; // "fast" again.
-                            a.isTransition = true;
-                            adjustStatsOptimistic(a);
-                        } else {
-                            a.histRelevance = 0; // Equivalent Duration:
-                            a.isTransition = false; // usual good case.
-                            adjustStats(a);
-                        }
-                    } else {
-                        if (compareDuration(a.duration, a.lastDuration) < 0) {
-                            a.histRelevance = -2; // "SLOW"!!!
-                            a.isTransition = true;
-                            adjustStats(a);
-                        } else {
-                            a.histRelevance = -2; // Still "SLOW"!!!
-                            a.isTransition = false; // (But NO transition!)
-                            adjustStats(a);
-                        }
-                    }
-                }
-            } else if (a.bestRes == 0) {
-                if (a.lastRes == 0) {
-                    a.histRelevance = -4; // "VBAD"!!!
-                    a.isTransition = true;
-                } else {
-                    a.histRelevance = -4; // Still "VBAD"!!!
-                    a.isTransition = false; // (But NO transition!)
-                }
-                // DON'T adjust statistics: they should reflect good runs, only.
-            } else if (a.bestRes == 100) {
-                a.bestRes = -3; // Just mark as NOT good.
-                a.histRelevance = -3; // Bad (initial run).
-                a.isTransition = true;
-                initStats(a);
-            } else {
-                a.histRelevance = 0; // Still Failure or Error:
-                a.isTransition = false; // usual bad case.
-                adjustStats(a);
-            }
-            pos = 1;
-            updateStmt.setInt(pos, a.bestRes); pos++;
-            updateStmt.setLong(pos, a.lastBestAt); pos++;
-            updateStmt.setInt(pos, a.res); pos++;
-            updateStmt.setLong(pos, a.duration); pos++;
-            updateStmt.setInt(pos, a.statCount); pos++;
-            updateStmt.setDouble(pos, a.statAvgDuration); pos++;
-            updateStmt.setLong(pos, a.statMinDuration); pos++;
-            updateStmt.setLong(pos, a.statMaxDuration); pos++;
-            updateStmt.setInt(pos, a.id); pos++;
-            updateStmt.execute();
-            pos = 1;
-            insertDetStmt.setInt(pos, a.id); pos++;
-            insertDetStmt.setLong(pos, now); pos++;
-            insertDetStmt.setInt(pos, a.statCount); pos++;
-            insertDetStmt.setInt(pos, a.res); pos++;
-            insertDetStmt.setLong(pos, a.duration); pos++;
-            insertDetStmt.execute();
-            if (a.isTransition) {
-                pos = 1;
-                insertEventStmt.setInt(pos, a.id); pos++;
-                insertEventStmt.setLong(pos, now); pos++;
-                insertEventStmt.setInt(pos, a.histRelevance); pos++;
-                insertEventStmt.setInt(pos, a.res); pos++;
-                insertEventStmt.setLong(pos, a.duration); pos++;
-                insertEventStmt.execute();
-            }
-        }
-        catch (SQLException e) {
-            int x = 0;
-        }
-    }
-
-//    static void use2(PerfStatCollector.Item a) {
-//    }
-
-    static void execOrIgnore(String sql) {
-        try { stmt.execute(sql); }
-        catch (SQLException e) {}
-    }
-
-    static void open(String jdbcDriver, String connectionURL)
-    throws Exception {
-//        try {
-            Class.forName(jdbcDriver).newInstance();
-            conn = DriverManager.getConnection(connectionURL);
-            stmt = conn.createStatement();
-            String dbVersion;
-            try {
-                ResultSet res = stmt.executeQuery("SELECT id FROM Version");
-                res.first();
-                dbVersion = res.getString(1);
-            }
-            catch (SQLException e) {
-                dbVersion = "";
-            }
-            if (!dbVersion.equals(sysVersion)) {
-                execOrIgnore("DROP TABLE Test_Cases;");
-                stmt.execute("CREATE TABLE Test_Cases (" +
-                        "  id INTEGER PRIMARY KEY AUTOINCREMENT, " +
-                        "  name VARCHAR(255) UNIQUE, " +
-                        // (best_Res != 0) ==> (last_Best_At == 0) never ran good!
-                        "  best_Res INTEGER, last_Best_At INTEGER, " +
-                        "  last_Res INTEGER, last_Duration INTEGER, " +
-                        "  stat_Cnt INTEGER, stat_Avg NUMBER(20, 2), " +
-                        "  stat_Min INTEGER, stat_Max INTEGER);");
-                execOrIgnore("DROP TABLE Test_Case_Runs;");
-                stmt.execute("CREATE TABLE Test_Case_Runs (" +
-                        "  test_Id INTEGER, run_At INTEGER, " +
-                        "  iteration INTEGER, res INTEGER, duration INTEGER, " +
-                        "  PRIMARY KEY (test_Id, run_At));");
-                execOrIgnore("DROP TABLE Test_Case_Events;");
-                stmt.execute("CREATE TABLE Test_Case_Events (" +
-                        "  test_Id INTEGER, run_At INTEGER, " +
-                        "  relevance INTEGER, " +
-                        "  res INTEGER, duration INTEGER, " +
-                        "  PRIMARY KEY (test_Id, run_At));");
-//                stmt.execute("CREATE PROCEDURE useSample (IN pName TEXT, " +
-//                        "pRes INTEGER, pDuration INTEGER, pTime INTEGER) " +
-//                        "BEGIN " +
-//                        "  INSERT OR IGNORE INTO TestCases (name)" +
-//                        "  VALUES (pName);" +
-//                        "END;");
-                execOrIgnore("DROP TABLE Version;");
-                stmt.execute("CREATE TABLE Version(id VARCHAR(31));");
-                stmt.execute("INSERT INTO Version (id) VALUES ('" + sysVersion + "');");
-            }
-//            updateStmt = conn.prepareStatement("useSample(:name, :res, :duration, :time)");
-    //        firstConnection.setTransactionIsolation(Connection.TRANSACTION_SERIALIZABLE);
-    //        firstStmt = firstConnection.createStatement();
-    //        firstStmt.execute("create table tbl1(one varchar(10), two smallint)");
-            insertStmt = conn.prepareStatement("INSERT " +
-                    "INTO Test_Cases (name, stat_Cnt) VALUES (?, 0);");
-            selectByNameStmt = conn.prepareStatement("SELECT id, " +
-                    "  IFNULL(best_Res, 100), IFNULL(last_Best_At, 0), " +
-                    "  IFNULL(last_Res, 100), IFNULL(last_Duration, 0), " +
-                    "  IFNULL(stat_Cnt, 0), IFNULL(stat_Avg, 0), " +
-                    "  IFNULL(stat_Min, 0), IFNULL(stat_Max, 0) " +
-                    "FROM Test_Cases WHERE name = ?;");
-            updateStmt = conn.prepareStatement("UPDATE Test_Cases SET " +
-                    "  best_Res = ?, last_Best_At = ?, " +
-                    "  last_Res = ?, last_Duration = ?, " +
-                    "  stat_Cnt = ?, stat_Avg = ?, " +
-                    "  stat_Min = ?, stat_Max = ? " +
-                    "WHERE id = ?;");
-            insertDetStmt = conn.prepareStatement("INSERT " +
-                    "INTO Test_Case_Runs (test_Id, run_At, iteration, res, duration) " +
-                    "VALUES (?, ?, ?, ?, ?);");
-            insertEventStmt = conn.prepareStatement("INSERT " +
-                    "INTO Test_Case_Events (test_Id, run_At, relevance, res, duration) " +
-                    "VALUES (?, ?, ?, ?, ?);");
-            selectAllStmt = conn.prepareStatement("SELECT id, name, " +
-                    "last_Res, stat_Cnt, " +
-                    "last_Duration, stat_Avg, stat_Min, stat_Max " +
-                    "FROM Test_Cases;");
-
-            try {
-//                ResultSet res = stmt.executeQuery("PRAGMA CACHE_SIZE;");
-//                res.first();
-//                System.out.print("CACHE_SIZE = ");
-//                System.out.println(res.getString(1));
-//                stmt.execute("PRAGMA CACHE_SIZE = 5000;");
-                stmt.execute("PRAGMA SYNCHRONOUS = OFF;");
-                stmt.execute("PRAGMA temp_store = MEMORY;");
-            }
-            catch (SQLException e) {
-                dbVersion = "";
-            }
-            stmt.close();
-            conn.commit();
-//        }
-//        catch (Exception e) {
-//            conn = null;
-//        }
-//        return conn != null;
-    }
-
-    static void close() {
-        try {
-            conn.commit();
-            conn.close();
-            conn = null;
-        }
-        catch (Exception e) {
-            conn = null;
-        }
-    }
-}
diff --git a/luni/src/test/java/com/google/coretests/XmlReportPrinter.java b/luni/src/test/java/com/google/coretests/XmlReportPrinter.java
deleted file mode 100644
index f098b3a..0000000
--- a/luni/src/test/java/com/google/coretests/XmlReportPrinter.java
+++ /dev/null
@@ -1,257 +0,0 @@
-/*
- *  Licensed to the Apache Software Foundation (ASF) under one or more
- *  contributor license agreements.  See the NOTICE file distributed with
- *  this work for additional information regarding copyright ownership.
- *  The ASF licenses this file to You 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 com.google.coretests;
-
-import junit.framework.Test;
-import junit.framework.TestCase;
-import junit.framework.TestFailure;
-import junit.framework.TestResult;
-import junit.runner.BaseTestRunner;
-import org.kxml2.io.KXmlSerializer;
-
-import java.io.File;
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.text.SimpleDateFormat;
-import java.util.ArrayList;
-import java.util.Date;
-import java.util.Enumeration;
-import java.util.HashMap;
-import java.util.LinkedHashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.TimeZone;
-
-
-/**
- * Writes JUnit results to a series of XML files in a format consistent with
- * Ant's XMLJUnitResultFormatter.
- *
- * <p>Unlike Ant's formatter, this class does not report the execution time of
- * tests.
- */
-public class XmlReportPrinter {
-
-    private static final String TESTSUITE = "testsuite";
-    private static final String TESTCASE = "testcase";
-    private static final String ERROR = "error";
-    private static final String FAILURE = "failure";
-    private static final String ATTR_NAME = "name";
-    private static final String ATTR_TIME = "time";
-    private static final String ATTR_ERRORS = "errors";
-    private static final String ATTR_FAILURES = "failures";
-    private static final String ATTR_TESTS = "tests";
-    private static final String ATTR_TYPE = "type";
-    private static final String ATTR_MESSAGE = "message";
-    private static final String PROPERTIES = "properties";
-    private static final String ATTR_CLASSNAME = "classname";
-    private static final String TIMESTAMP = "timestamp";
-    private static final String HOSTNAME = "hostname";
-
-    /** the XML namespace */
-    private static final String ns = null;
-
-    /** the test suites, which each contain tests */
-    private final Map<String, Suite> suites = new LinkedHashMap<String, Suite>();
-
-    /**
-     * Create a report printer that prints the specified test suite. Since the
-     * CoreTestSuite nulls-out tests after they're run (to limit memory
-     * consumption), it is necessary to create the report printer prior to test
-     * execution.
-     */
-    public XmlReportPrinter(CoreTestSuite allTests) {
-        // partition the tests by suite to be consistent with Ant's printer
-        for (Enumeration<Test> e = allTests.tests(); e.hasMoreElements(); ) {
-            TestId test = new TestId(e.nextElement());
-
-            // create the suite's entry in the map if necessary
-            Suite suite = suites.get(test.className);
-            if (suite == null) {
-                suite = new Suite(test.className);
-                suites.put(test.className, suite);
-            }
-
-            suite.tests.add(test);
-        }
-    }
-
-    public void setResults(TestResult result) {
-        populateFailures(true, result.errors());
-        populateFailures(false, result.failures());
-    }
-
-    /**
-     * Populate the list of failures in each of the suites.
-     */
-    private void populateFailures(boolean errors, Enumeration<TestFailure> failures) {
-        while (failures.hasMoreElements()) {
-            TestFailure failure = failures.nextElement();
-            TestId test = new TestId(failure.failedTest());
-            Suite suite = suites.get(test.className);
-
-            if (suite == null) {
-                throw new IllegalStateException( "received a failure for a "
-                        + "test that wasn't in the original test suite!");
-            }
-
-            if (errors) {
-                suite.errors.put(test, failure);
-            } else {
-                suite.failures.put(test, failure);
-            }
-        }
-    }
-
-    public int generateReports(String directory) {
-        File parent = new File(directory);
-        parent.mkdirs();
-
-        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
-        TimeZone gmt = TimeZone.getTimeZone("GMT");
-        dateFormat.setTimeZone(gmt);
-        dateFormat.setLenient(true);
-        String timestamp = dateFormat.format(new Date());
-
-        for (Suite suite : suites.values()) {
-            FileOutputStream stream = null;
-            try {
-                stream = new FileOutputStream(new File(parent, "TEST-" + suite.name + ".xml"));
-
-                KXmlSerializer serializer = new KXmlSerializer();
-                serializer.setOutput(stream, "UTF-8");
-                serializer.startDocument("UTF-8", null);
-                serializer.setFeature(
-                        "http://xmlpull.org/v1/doc/features.html#indent-output", true);
-                suite.print(serializer, timestamp);
-                serializer.endDocument();
-            } catch (IOException e) {
-                throw new RuntimeException(e);
-            } finally {
-                if (stream != null) {
-                    try {
-                        stream.close();
-                    } catch (IOException ignored) {
-                        ignored.printStackTrace();
-                    }
-                }
-            }
-        }
-
-        return suites.size();
-    }
-
-    static class Suite {
-        private final String name;
-        private final List<TestId> tests = new ArrayList<TestId>();
-        private final Map<TestId, TestFailure> failures = new HashMap<TestId, TestFailure>();
-        private final Map<TestId, TestFailure> errors = new HashMap<TestId, TestFailure>();
-
-        Suite(String name) {
-            this.name = name;
-        }
-
-        void print(KXmlSerializer serializer, String timestamp) throws IOException {
-            serializer.startTag(ns, TESTSUITE);
-            serializer.attribute(ns, ATTR_NAME, name);
-            serializer.attribute(ns, ATTR_TESTS, Integer.toString(tests.size()));
-            serializer.attribute(ns, ATTR_FAILURES, Integer.toString(failures.size()));
-            serializer.attribute(ns, ATTR_ERRORS, Integer.toString(errors.size()));
-            serializer.attribute(ns, ATTR_TIME, "0");
-
-            serializer.attribute(ns, TIMESTAMP, timestamp);
-            serializer.attribute(ns, HOSTNAME, "localhost");
-            serializer.startTag(ns, PROPERTIES);
-            serializer.endTag(ns, PROPERTIES);
-
-            for (TestId testId : tests) {
-                TestFailure error = errors.get(testId);
-                TestFailure failure = failures.get(testId);
-
-                if (error != null) {
-                    testId.printFailure(serializer, ERROR, error.thrownException());
-                } else if (failure != null) {
-                    testId.printFailure(serializer, FAILURE, failure.thrownException());
-                } else {
-                    testId.printSuccess(serializer);
-                }
-            }
-
-            serializer.endTag(ns, TESTSUITE);
-        }
-    }
-
-    private static class TestId {
-        private final String name;
-        private final String className;
-
-        TestId(Test test) {
-            this.name = test instanceof TestCase
-                    ? ((TestCase) test).getName()
-                    : test.toString();
-            this.className = test.getClass().getName();
-        }
-
-        void printSuccess(KXmlSerializer serializer) throws IOException {
-            serializer.startTag(ns, TESTCASE);
-            printAttributes(serializer);
-            serializer.endTag(ns, TESTCASE);
-        }
-
-        void printFailure(KXmlSerializer serializer, String type, Throwable t)
-                throws IOException {
-            serializer.startTag(ns, TESTCASE);
-            printAttributes(serializer);
-
-            serializer.startTag(ns, type);
-            String message = t.getMessage();
-            if (message != null && message.length() > 0) {
-                serializer.attribute(ns, ATTR_MESSAGE, t.getMessage());
-            }
-            serializer.attribute(ns, ATTR_TYPE, t.getClass().getName());
-            serializer.text(sanitize(BaseTestRunner.getFilteredTrace(t)));
-            serializer.endTag(ns, type);
-
-            serializer.endTag(ns, TESTCASE);
-        }
-
-        void printAttributes(KXmlSerializer serializer) throws IOException {
-            serializer.attribute(ns, ATTR_NAME, name);
-            serializer.attribute(ns, ATTR_CLASSNAME, className);
-            serializer.attribute(ns, ATTR_TIME, "0");
-        }
-
-        @Override public boolean equals(Object o) {
-            return o instanceof TestId
-                    && ((TestId) o).name.equals(name)
-                    && ((TestId) o).className.equals(className);
-        }
-
-        @Override public int hashCode() {
-            return name.hashCode() ^ className.hashCode();
-        }
-
-        /**
-         * Returns the text in a format that is safe for use in an XML document.
-         */
-        private static String sanitize(String text) {
-            return text.replace("\0", "<\\0>");
-        }
-    }
-}
diff --git a/luni/src/test/java/com/ibm/icu4jni/util/ICUTest.java b/luni/src/test/java/libcore/icu/ICUTest.java
similarity index 98%
rename from luni/src/test/java/com/ibm/icu4jni/util/ICUTest.java
rename to luni/src/test/java/libcore/icu/ICUTest.java
index c950e0a..9282167 100644
--- a/luni/src/test/java/com/ibm/icu4jni/util/ICUTest.java
+++ b/luni/src/test/java/libcore/icu/ICUTest.java
@@ -14,7 +14,7 @@
  * limitations under the License.
  */
 
-package com.ibm.icu4jni.util;
+package libcore.icu;
 
 import java.util.Locale;
 
diff --git a/luni/src/test/java/libcore/java/io/DataOutputStreamTest.java b/luni/src/test/java/libcore/java/io/DataOutputStreamTest.java
new file mode 100644
index 0000000..666a44e
--- /dev/null
+++ b/luni/src/test/java/libcore/java/io/DataOutputStreamTest.java
@@ -0,0 +1,150 @@
+/*
+ * 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.
+ */
+
+package libcore.java.io;
+
+import java.io.ByteArrayOutputStream;
+import java.io.DataOutputStream;
+import java.io.UTFDataFormatException;
+import java.util.Arrays;
+import junit.framework.TestCase;
+
+public final class DataOutputStreamTest extends TestCase {
+    private ByteArrayOutputStream bytes = new ByteArrayOutputStream();
+    private DataOutputStream os = new DataOutputStream(bytes);
+
+    public void test_writeBoolean() throws Exception {
+        os.writeBoolean(true);
+        os.writeBoolean(false);
+        assertEquals("[01, 00]", toHexString(bytes.toByteArray()));
+    }
+
+    public void test_writeByte() throws Exception {
+        os.writeByte(-1);
+        os.writeByte(0);
+        os.writeByte(1);
+        os.writeByte(129);
+        // writeByte takes only the bottom byte from its int parameter.
+        os.writeByte(0x1234);
+        assertEquals("[ff, 00, 01, 81, 34]", toHexString(bytes.toByteArray()));
+    }
+
+    public void test_writeBytes() throws Exception {
+        // writeBytes takes only the bottom byte from each character.
+        os.writeBytes("0\u12341");
+        assertEquals("[30, 34, 31]", toHexString(bytes.toByteArray()));
+    }
+
+    public void test_writeChar() throws Exception {
+        // writeChar writes two-byte big-endian characters.
+        os.writeChar('0');
+        os.writeChar(0x1234);
+        assertEquals("[00, 30, 12, 34]", toHexString(bytes.toByteArray()));
+    }
+
+    public void test_writeChars() throws Exception {
+        // writeChars writes two-byte big-endian characters.
+        os.writeChars("0\u12341");
+        assertEquals("[00, 30, 12, 34, 00, 31]", toHexString(bytes.toByteArray()));
+    }
+
+    public void test_writeDouble() throws Exception {
+        os.writeDouble(Double.longBitsToDouble(0x0123456789abcdefL));
+        assertEquals("[01, 23, 45, 67, 89, ab, cd, ef]", toHexString(bytes.toByteArray()));
+    }
+
+    public void test_writeFloat() throws Exception {
+        os.writeFloat(Float.intBitsToFloat(0x01234567));
+        assertEquals("[01, 23, 45, 67]", toHexString(bytes.toByteArray()));
+    }
+
+    public void test_writeInt() throws Exception {
+        os.writeInt(0x01234567);
+        assertEquals("[01, 23, 45, 67]", toHexString(bytes.toByteArray()));
+    }
+
+    public void test_writeLong() throws Exception {
+        os.writeLong(0x0123456789abcdefL);
+        assertEquals("[01, 23, 45, 67, 89, ab, cd, ef]", toHexString(bytes.toByteArray()));
+    }
+
+    public void test_writeShort() throws Exception {
+        // writeShort only writes the bottommost 16 bits of its int parameter.
+        os.writeShort(0x01234567);
+        assertEquals("[45, 67]", toHexString(bytes.toByteArray()));
+    }
+
+    public void test_writeUTF() throws Exception {
+        // The limit is 65535 *bytes* but we want to test 2- and 3-byte characters too.
+        char[] chars = new char[65535 - 1 - 2];
+        Arrays.fill(chars, 0, chars.length, 'a');
+        chars[0] = '\u0666'; // a two-byte character
+        chars[1] = '\u2603'; // a three-byte character
+        String maxLength = new String(chars);
+        os.writeUTF(maxLength);
+        byte[] expected = new byte[2 + 65535];
+        expected[0] = (byte) 0xff;
+        expected[1] = (byte) 0xff;
+        // U+0666 = 0xD9 0xA6
+        expected[2] = (byte) 0xd9;
+        expected[3] = (byte) 0xa6;
+        // U+2603 = 0xE2 0x98 0x83
+        expected[4] = (byte) 0xe2;
+        expected[5] = (byte) 0x98;
+        expected[6] = (byte) 0x83;
+        Arrays.fill(expected, 7, expected.length, (byte) 'a');
+        assertEquals(Arrays.toString(expected), Arrays.toString(bytes.toByteArray()));
+    }
+
+    public void test_writeUTF_NUL() throws Exception {
+        // This is a special case, represented with two non-zero bytes.
+        os.writeUTF("\u0000");
+        assertEquals("[00, 02, c0, 80]", toHexString(bytes.toByteArray()));
+    }
+
+    public void test_writeUTF_too_long() throws Exception {
+        String tooLong = new String(new char[65536]);
+        try {
+            os.writeUTF(tooLong);
+            fail("should throw UTFDataFormatException");
+        } catch (UTFDataFormatException expected) {
+        }
+        assertEquals("[]", toHexString(bytes.toByteArray()));
+    }
+
+    /**
+     * Returns a string representation of a byte array that's more useful for debugging.
+     * TODO: move this somewhere where it's available to all tests.
+     */
+    public static String toHexString(byte[] array) {
+        if (array == null) {
+            return null;
+        }
+        if (array.length == 0) {
+            return "[]";
+        }
+        StringBuilder sb = new StringBuilder();
+        sb.append('[');
+        // TODO: don't use String.format if we put this in the library. Too expensive!
+        sb.append(String.format("%02x", array[0] & 0xff));
+        for (int i = 1; i < array.length; i++) {
+            sb.append(", ");
+            sb.append(String.format("%02x", array[i] & 0xff));
+        }
+        sb.append(']');
+        return sb.toString();
+    }
+}
diff --git a/luni/src/test/java/libcore/java/io/ObjectOutputStreamTest.java b/luni/src/test/java/libcore/java/io/ObjectOutputStreamTest.java
new file mode 100644
index 0000000..9228162
--- /dev/null
+++ b/luni/src/test/java/libcore/java/io/ObjectOutputStreamTest.java
@@ -0,0 +1,35 @@
+/*
+ * 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.
+ */
+
+package libcore.java.io;
+
+import java.io.ByteArrayOutputStream;
+import java.io.ObjectOutputStream;
+import junit.framework.TestCase;
+
+public final class ObjectOutputStreamTest extends TestCase {
+    public void testLongString() throws Exception {
+        // Most modified UTF-8 is limited to 64KiB, but serialized strings can have an 8-byte
+        // length, so this should never throw java.io.UTFDataFormatException...
+        StringBuilder sb = new StringBuilder();
+        for (int i = 0; i < 64*1024 * 2; ++i) {
+            sb.append('a');
+        }
+        String s = sb.toString();
+        ObjectOutputStream os = new ObjectOutputStream(new ByteArrayOutputStream());
+        os.writeObject(s);
+    }
+}
diff --git a/luni/src/test/java/tests/api/java/io/RandomAccessFileTest.java b/luni/src/test/java/libcore/java/io/OldRandomAccessFileTest.java
similarity index 81%
rename from luni/src/test/java/tests/api/java/io/RandomAccessFileTest.java
rename to luni/src/test/java/libcore/java/io/OldRandomAccessFileTest.java
index 91636bb..c26babf 100644
--- a/luni/src/test/java/tests/api/java/io/RandomAccessFileTest.java
+++ b/luni/src/test/java/libcore/java/io/OldRandomAccessFileTest.java
@@ -15,12 +15,7 @@
  *  limitations under the License.
  */
 
-package tests.api.java.io;
-
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
+package libcore.java.io;
 
 import java.io.EOFException;
 import java.io.File;
@@ -33,8 +28,7 @@
 import java.nio.channels.FileChannel;
 import java.nio.channels.NonWritableChannelException;
 
-@TestTargetClass(RandomAccessFile.class)
-public class RandomAccessFileTest extends junit.framework.TestCase {
+public class OldRandomAccessFileTest extends junit.framework.TestCase {
 
     public String fileName;
 
@@ -55,12 +49,6 @@
      * @tests java.io.RandomAccessFile#RandomAccessFile(java.io.File,
      *        java.lang.String)
      */
-    @TestTargetNew(
-        level = TestLevel.PARTIAL_COMPLETE,
-        notes = "",
-        method = "RandomAccessFile",
-        args = {java.io.File.class, java.lang.String.class}
-    )
     public void test_ConstructorLjava_io_FileLjava_lang_String() throws Exception {
         RandomAccessFile raf = null;
         File tmpFile = new File(fileName);
@@ -114,12 +102,6 @@
      * @tests java.io.RandomAccessFile#RandomAccessFile(java.lang.String,
      *        java.lang.String)
      */
-    @TestTargetNew(
-        level = TestLevel.PARTIAL_COMPLETE,
-        notes = "",
-        method = "RandomAccessFile",
-        args = {java.lang.String.class, java.lang.String.class}
-    )
     public void test_ConstructorLjava_lang_StringLjava_lang_String()
             throws IOException {
         RandomAccessFile raf = null;
@@ -183,12 +165,6 @@
     /**
      * @tests java.io.RandomAccessFile#close()
      */
-    @TestTargetNew(
-        level = TestLevel.SUFFICIENT,
-        notes = "No IOException checking, requires native code that can be forced to throw such an exception.",
-        method = "close",
-        args = {}
-    )
     public void test_close() {
         // Test for method void java.io.RandomAccessFile.close()
         try {
@@ -202,12 +178,6 @@
     /**
      * @tests java.io.RandomAccessFile#getChannel()
      */
-    @TestTargetNew(
-        level = TestLevel.COMPLETE,
-        notes = "",
-        method = "getChannel",
-        args = {}
-    )
     public void test_getChannel() throws IOException {
 
         RandomAccessFile raf = new java.io.RandomAccessFile(fileName, "rw");
@@ -228,12 +198,6 @@
     /**
      * @tests java.io.RandomAccessFile#getFD()
      */
-    @TestTargetNew(
-        level = TestLevel.SUFFICIENT,
-        notes = "No IOException checking since this exception is not thrown.",
-        method = "getFD",
-        args = {}
-    )
     public void test_getFD() throws IOException {
         // Test for method java.io.FileDescriptor
         // java.io.RandomAccessFile.getFD()
@@ -248,12 +212,6 @@
     /**
      * @tests java.io.RandomAccessFile#getFilePointer()
      */
-    @TestTargetNew(
-        level = TestLevel.COMPLETE,
-        notes = "",
-        method = "getFilePointer",
-        args = {}
-    )
     public void test_getFilePointer() throws IOException {
         // Test for method long java.io.RandomAccessFile.getFilePointer()
         RandomAccessFile raf = new java.io.RandomAccessFile(fileName, "rw");
@@ -272,12 +230,6 @@
     /**
      * @tests java.io.RandomAccessFile#length()
      */
-    @TestTargetNew(
-        level = TestLevel.COMPLETE,
-        notes = "",
-        method = "length",
-        args = {}
-    )
     public void test_length() throws IOException {
         // Test for method long java.io.RandomAccessFile.length()
         RandomAccessFile raf = new java.io.RandomAccessFile(fileName, "rw");
@@ -296,20 +248,6 @@
     /**
      * @tests java.io.RandomAccessFile#read()
      */
-    @TestTargets({
-        @TestTargetNew(
-            level = TestLevel.COMPLETE,
-            notes = "",
-            method = "write",
-            args = {int.class}
-        ),
-        @TestTargetNew(
-            level = TestLevel.COMPLETE,
-            notes = "",
-            method = "read",
-            args = {}
-        )
-    })
     public void test_read_write() throws IOException {
         int i;
         byte[] testBuf = testString.getBytes();
@@ -350,12 +288,6 @@
     /**
      * @tests java.io.RandomAccessFile#read(byte[])
      */
-    @TestTargetNew(
-        level = TestLevel.COMPLETE,
-        notes = "",
-        method = "read",
-        args = {byte[].class}
-    )
     public void test_read$B() throws IOException {
         FileOutputStream fos = new java.io.FileOutputStream(fileName);
         fos.write(testString.getBytes(), 0, testLength);
@@ -385,12 +317,6 @@
     /**
      * @tests java.io.RandomAccessFile#read(byte[], int, int)
      */
-    @TestTargetNew(
-        level = TestLevel.COMPLETE,
-        notes = "",
-        method = "read",
-        args = {byte[].class, int.class, int.class}
-    )
     public void test_read$BII() throws IOException {
         int bytesRead;
         RandomAccessFile raf = new java.io.RandomAccessFile(fileName, "rw");
@@ -454,20 +380,6 @@
      * @tests java.io.RandomAccessFile#readBoolean()
      * @tests java.io.RandomAccessFile#writeBoolean(boolean)
      */
-    @TestTargets({
-        @TestTargetNew(
-            level = TestLevel.SUFFICIENT,
-            notes = "Tests against golden file missing.",
-            method = "writeBoolean",
-            args = {boolean.class}
-        ),
-        @TestTargetNew(
-            level = TestLevel.SUFFICIENT,
-            notes = "Tests against golden file missing.",
-            method = "readBoolean",
-            args = {}
-        )
-    })
     public void test_read_writeBoolean() throws IOException {
         RandomAccessFile raf = new java.io.RandomAccessFile(fileName, "rw");
         raf.writeBoolean(true);
@@ -505,20 +417,6 @@
      * @tests java.io.RandomAccessFile#readByte()
      * @tests java.io.RandomAccessFile#writeByte(byte)
      */
-    @TestTargets({
-        @TestTargetNew(
-            level = TestLevel.SUFFICIENT,
-            notes = "Tests against golden file missing.",
-            method = "writeByte",
-            args = {int.class}
-        ),
-        @TestTargetNew(
-            level = TestLevel.SUFFICIENT,
-            notes = "Tests against golden file missing.",
-            method = "readByte",
-            args = {}
-        )
-    })
     public void test_read_writeByte() throws IOException {
         RandomAccessFile raf = new java.io.RandomAccessFile(fileName, "rw");
         raf.writeByte(Byte.MIN_VALUE);
@@ -565,20 +463,6 @@
      * @tests java.io.RandomAccessFile#readChar()
      * @tests java.io.RandomAccessFile#writeChar(char)
      */
-    @TestTargets({
-        @TestTargetNew(
-            level = TestLevel.SUFFICIENT,
-            notes = "Tests against golden file missing.",
-            method = "writeChar",
-            args = {int.class}
-        ),
-        @TestTargetNew(
-            level = TestLevel.SUFFICIENT,
-            notes = "Tests against golden file missing.",
-            method = "readChar",
-            args = {}
-        )
-    })
     public void test_read_writeChar() throws IOException {
         RandomAccessFile raf = new java.io.RandomAccessFile(fileName, "rw");
         raf.writeChar(Character.MIN_VALUE);
@@ -625,20 +509,6 @@
      * @tests java.io.RandomAccessFile#readDouble()
      * @tests java.io.RandomAccessFile#writeDouble(double)
      */
-    @TestTargets({
-        @TestTargetNew(
-            level = TestLevel.SUFFICIENT,
-            notes = "Tests against golden file missing.",
-            method = "writeDouble",
-            args = {double.class}
-        ),
-        @TestTargetNew(
-            level = TestLevel.SUFFICIENT,
-            notes = "Tests against golden file missing.",
-            method = "readDouble",
-            args = {}
-        )
-    })
     public void test_read_writeDouble() throws IOException {
         RandomAccessFile raf = new java.io.RandomAccessFile(fileName, "rw");
         raf.writeDouble(Double.MAX_VALUE);
@@ -676,20 +546,6 @@
      * @tests java.io.RandomAccessFile#readFloat()
      * @tests java.io.RandomAccessFile#writeFloat(double)
      */
-    @TestTargets({
-        @TestTargetNew(
-            level = TestLevel.SUFFICIENT,
-            notes = "Tests against golden file missing.",
-            method = "writeFloat",
-            args = {float.class}
-        ),
-        @TestTargetNew(
-            level = TestLevel.SUFFICIENT,
-            notes = "Tests against golden file missing.",
-            method = "readFloat",
-            args = {}
-        )
-    })
     public void test_read_writeFloat() throws IOException {
         RandomAccessFile raf = new java.io.RandomAccessFile(fileName, "rw");
         raf.writeFloat(Float.MAX_VALUE);
@@ -727,20 +583,6 @@
      * @tests java.io.RandomAccessFile#readInt()
      * @tests java.io.RandomAccessFile#writeInt(char)
      */
-    @TestTargets({
-        @TestTargetNew(
-            level = TestLevel.SUFFICIENT,
-            notes = "Tests against golden file missing.",
-            method = "writeInt",
-            args = {int.class}
-        ),
-        @TestTargetNew(
-            level = TestLevel.SUFFICIENT,
-            notes = "Tests against golden file missing.",
-            method = "readInt",
-            args = {}
-        )
-    })
     public void test_read_writeInt() throws IOException {
         RandomAccessFile raf = new java.io.RandomAccessFile(fileName, "rw");
         raf.writeInt(Integer.MIN_VALUE);
@@ -787,20 +629,6 @@
      * @tests java.io.RandomAccessFile#readLong()
      * @tests java.io.RandomAccessFile#writeLong(char)
      */
-    @TestTargets({
-        @TestTargetNew(
-            level = TestLevel.SUFFICIENT,
-            notes = "Tests against golden file missing.",
-            method = "writeLong",
-            args = {long.class}
-        ),
-        @TestTargetNew(
-            level = TestLevel.SUFFICIENT,
-            notes = "Tests against golden file missing.",
-            method = "readLong",
-            args = {}
-        )
-    })
     public void test_read_writeLong() throws IOException {
         RandomAccessFile raf = new java.io.RandomAccessFile(fileName, "rw");
         raf.writeLong(Long.MIN_VALUE);
@@ -847,20 +675,6 @@
      * @tests java.io.RandomAccessFile#readShort()
      * @tests java.io.RandomAccessFile#writeShort(short)
      */
-    @TestTargets({
-        @TestTargetNew(
-            level = TestLevel.SUFFICIENT,
-            notes = "Tests against golden file missing.",
-            method = "writeShort",
-            args = {int.class}
-        ),
-        @TestTargetNew(
-            level = TestLevel.SUFFICIENT,
-            notes = "Tests against golden file missing.",
-            method = "readShort",
-            args = {}
-        )
-    })
     public void test_read_writeShort() throws IOException {
         RandomAccessFile raf = new java.io.RandomAccessFile(fileName, "rw");
         raf.writeShort(Short.MIN_VALUE);
@@ -907,20 +721,6 @@
      * @tests java.io.RandomAccessFile#readUTF()
      * @tests java.io.RandomAccessFile#writeShort(char)
      */
-    @TestTargets({
-        @TestTargetNew(
-            level = TestLevel.SUFFICIENT,
-            notes = "Tests against golden file missing.",
-            method = "writeUTF",
-            args = {java.lang.String.class}
-        ),
-        @TestTargetNew(
-            level = TestLevel.SUFFICIENT,
-            notes = "Tests against golden file missing.",
-            method = "readUTF",
-            args = {}
-        )
-    })
     public void test_read_writeUTF() throws IOException {
         RandomAccessFile raf = new java.io.RandomAccessFile(fileName, "rw");
         raf.writeUTF(unihw);
@@ -954,20 +754,6 @@
      * @tests java.io.RandomAccessFile#writeBytes(java.lang.String)
      * @tests java.io.RandomAccessFile#readFully(byte[])
      */
-    @TestTargets({
-        @TestTargetNew(
-            level = TestLevel.SUFFICIENT,
-            notes = "Tests against golden file missing.",
-            method = "writeBytes",
-            args = {java.lang.String.class}
-        ),
-        @TestTargetNew(
-            level = TestLevel.SUFFICIENT,
-            notes = "Tests against golden file missing.",
-            method = "readFully",
-            args = {byte[].class}
-        )
-    })
     public void test_readFully$B_writeBytesLjava_lang_String() throws IOException {
         byte[] buf = new byte[testLength];
         RandomAccessFile raf = new java.io.RandomAccessFile(fileName, "rw");
@@ -1011,20 +797,6 @@
      * @tests java.io.RandomAccessFile#writeBytes(java.lang.String)
      * @tests java.io.RandomAccessFile#readFully(byte[], int, int)
      */
-    @TestTargets({
-        @TestTargetNew(
-            level = TestLevel.SUFFICIENT,
-            notes = "Tests against golden file missing.",
-            method = "writeBytes",
-            args = {java.lang.String.class}
-        ),
-        @TestTargetNew(
-            level = TestLevel.SUFFICIENT,
-            notes = "Tests against golden file missing.",
-            method = "readFully",
-            args = {byte[].class, int.class, int.class}
-        )
-    })
     public void test_readFully$BII() throws IOException {
         byte[] buf = new byte[testLength];
         RandomAccessFile raf = new java.io.RandomAccessFile(fileName, "rw");
@@ -1087,12 +859,6 @@
     /**
      * @tests java.io.RandomAccessFile#readUnsignedByte()
      */
-    @TestTargetNew(
-        level = TestLevel.SUFFICIENT,
-        notes = "Tests against golden file missing.",
-        method = "readUnsignedByte",
-        args = {}
-    )
     public void test_readUnsignedByte() throws IOException {
         RandomAccessFile raf = new java.io.RandomAccessFile(fileName, "rw");
         raf.writeByte(-1);
@@ -1120,12 +886,6 @@
     /**
      * @tests java.io.RandomAccessFile#readUnsignedShort()
      */
-    @TestTargetNew(
-        level = TestLevel.SUFFICIENT,
-        notes = "Tests against golden file missing.",
-        method = "readUnsignedShort",
-        args = {}
-    )
     public void test_readUnsignedShort() throws IOException {
         RandomAccessFile raf = new java.io.RandomAccessFile(fileName, "rw");
         raf.writeShort(-1);
@@ -1153,12 +913,6 @@
     /**
      * @tests java.io.RandomAccessFile#readLine()
      */
-    @TestTargetNew(
-        level = TestLevel.SUFFICIENT,
-        notes = "",
-        method = "readLine",
-        args = {}
-    )
     public void test_readLine() throws IOException {
         // Test for method java.lang.String java.io.RandomAccessFile.readLine()
         RandomAccessFile raf = new java.io.RandomAccessFile(fileName, "rw");
@@ -1184,12 +938,6 @@
     /**
      * @tests java.io.RandomAccessFile#seek(long)
      */
-    @TestTargetNew(
-        level = TestLevel.COMPLETE,
-        notes = "",
-        method = "seek",
-        args = {long.class}
-    )
     public void test_seekJ() throws IOException {
         // Test for method void java.io.RandomAccessFile.seek(long)
         RandomAccessFile raf = new java.io.RandomAccessFile(fileName, "rw");
@@ -1200,15 +948,6 @@
         } catch (IOException e) {
             // Expected.
         }
-        // BEGIN android-added
-        try {
-            // Android uses 32-bit off_t, so anything larger than a signed 32-bit int won't work.
-            raf.seek(((long) Integer.MAX_VALUE) + 1);
-            fail("Test 2: IOException expected.");
-        } catch (IOException e) {
-            // Expected.
-        }
-        // END android-added
 
         raf.write(testString.getBytes(), 0, testLength);
         raf.seek(12);
@@ -1227,12 +966,6 @@
     /**
      * @tests java.io.RandomAccessFile#skipBytes(int)
      */
-    @TestTargetNew(
-        level = TestLevel.COMPLETE,
-        notes = "",
-        method = "skipBytes",
-        args = {int.class}
-    )
     public void test_skipBytesI() throws IOException {
         byte[] buf = new byte[5];
         RandomAccessFile raf = new java.io.RandomAccessFile(fileName, "rw");
@@ -1265,12 +998,6 @@
     /**
      * @tests java.io.RandomAccessFile#skipBytes(int)
      */
-    @TestTargetNew(
-        level = TestLevel.COMPLETE,
-        notes = "",
-        method = "setLength",
-        args = {long.class}
-    )
     public void test_setLengthJ() throws IOException {
         int bytesRead;
         long truncLength = (long) (testLength * 0.75);
@@ -1305,23 +1032,12 @@
         assertEquals("Test 7: Incorrect file length;",
                 testLength + 2, raf.length());
 
-        // BEGIN android-added
-        // Exception testing.
-        try {
-            // Android uses 32-bit off_t, so anything larger than a signed 32-bit int won't work.
-            raf.setLength(((long) Integer.MAX_VALUE) + 1);
-            fail("Test 8: IOException expected.");
-        } catch (IOException e) {
-            // Expected.
-        }
-        // END android-added
-
         // Exception testing.
         try {
             raf.setLength(-1);
             fail("Test 9: IllegalArgumentException expected.");
-        } catch (IllegalArgumentException e) {
-            // Expected.
+        } catch (IOException expected) {
+        } catch (IllegalArgumentException expected) {
         }
 
         raf.close();
@@ -1336,12 +1052,6 @@
     /**
      * @tests java.io.RandomAccessFile#write(byte[])
      */
-    @TestTargetNew(
-        level = TestLevel.COMPLETE,
-        notes = "",
-        method = "write",
-        args = {byte[].class}
-    )
     public void test_write$B() throws IOException {
         byte[] rbuf = new byte[4000];
         RandomAccessFile raf = new java.io.RandomAccessFile(fileName, "rw");
@@ -1384,12 +1094,6 @@
     /**
      * @tests java.io.RandomAccessFile#write(byte[], int, int)
      */
-    @TestTargetNew(
-        level = TestLevel.COMPLETE,
-        notes = "",
-        method = "write",
-        args = {byte[].class, int.class, int.class}
-    )
     public void test_write$BII() throws Exception {
         RandomAccessFile raf = new java.io.RandomAccessFile(fileName, "rw");
         byte[] rbuf = new byte[4000];
@@ -1471,12 +1175,6 @@
     /**
      * @tests java.io.RandomAccessFile#writeChars(java.lang.String)
      */
-    @TestTargetNew(
-        level = TestLevel.SUFFICIENT,
-        notes = "Tests against golden file missing.",
-        method = "writeChars",
-        args = {java.lang.String.class}
-    )
     public void test_writeCharsLjava_lang_String() throws IOException {
         RandomAccessFile raf = new java.io.RandomAccessFile(fileName, "rw");
         raf.writeChars(unihw);
diff --git a/luni/src/test/java/libcore/java/io/RandomAccessFileTest.java b/luni/src/test/java/libcore/java/io/RandomAccessFileTest.java
index f2709cb..c716204 100644
--- a/luni/src/test/java/libcore/java/io/RandomAccessFileTest.java
+++ b/luni/src/test/java/libcore/java/io/RandomAccessFileTest.java
@@ -17,12 +17,41 @@
 package libcore.java.io;
 
 import java.io.File;
+import java.io.FileNotFoundException;
 import java.io.IOException;
 import java.io.RandomAccessFile;
 import junit.framework.TestCase;
 
 public final class RandomAccessFileTest extends TestCase {
 
+    private File file;
+
+    @Override protected void setUp() throws Exception {
+        file = File.createTempFile("RandomAccessFileTest", "tmp");
+    }
+
+    @Override protected void tearDown() throws Exception {
+        file.delete();
+    }
+
+    public void testSeekTooLarge() throws FileNotFoundException {
+        RandomAccessFile raf = new RandomAccessFile(file, "rw");
+        try {
+            raf.seek(Long.MAX_VALUE);
+            fail();
+        } catch (IOException expected) {
+        }
+    }
+
+    public void testSetLengthTooLarge() throws FileNotFoundException {
+        RandomAccessFile raf = new RandomAccessFile(file, "rw");
+        try {
+            raf.setLength(Long.MAX_VALUE);
+            fail();
+        } catch (IOException expected) {
+        }
+    }
+
     // http://b/3015023
     public void testRandomAccessFileHasCleanupFinalizer() throws IOException {
         int tooManyOpenFiles = 2000;
diff --git a/luni/src/test/java/libcore/java/lang/ProcessBuilderTest.java b/luni/src/test/java/libcore/java/lang/ProcessBuilderTest.java
index 6b8edcb..320cafb 100644
--- a/luni/src/test/java/libcore/java/lang/ProcessBuilderTest.java
+++ b/luni/src/test/java/libcore/java/lang/ProcessBuilderTest.java
@@ -16,13 +16,16 @@
 
 package libcore.java.lang;
 
+import java.io.File;
 import java.util.HashMap;
 import java.util.Map;
 import static tests.support.Support_Exec.execAndCheckOutput;
 
 public class ProcessBuilderTest extends junit.framework.TestCase {
     private static String shell() {
-        return "Dalvik".equals(System.getProperty("java.vm.name")) ? "/system/bin/sh" : "/bin/sh";
+        String deviceSh = "/system/bin/sh";
+        String desktopSh = "/bin/sh";
+        return new File(deviceSh).exists() ? deviceSh : desktopSh;
     }
 
     public void testRedirectErrorStream(boolean doRedirect,
diff --git a/luni/src/test/java/libcore/java/net/OldResponseCacheTest.java b/luni/src/test/java/libcore/java/net/OldResponseCacheTest.java
index 2422adc..662c3a5 100644
--- a/luni/src/test/java/libcore/java/net/OldResponseCacheTest.java
+++ b/luni/src/test/java/libcore/java/net/OldResponseCacheTest.java
@@ -20,6 +20,7 @@
 import dalvik.annotation.TestTargetClass;
 import dalvik.annotation.TestTargetNew;
 import dalvik.annotation.TestTargets;
+import java.io.ByteArrayInputStream;
 import java.io.IOException;
 import java.io.InputStream;
 import java.io.OutputStream;
@@ -265,9 +266,8 @@
     class TestCacheResponse extends CacheResponse {
         InputStream is = null;
 
-        public TestCacheResponse(String filename) {
-            String path = getClass().getPackage().getName().replace(".", "/");
-            is = getClass().getResourceAsStream("/" + path + "/" + filename);
+        public TestCacheResponse(String body) {
+            is = new ByteArrayInputStream(body.getBytes());
         }
 
         @Override
@@ -313,7 +313,7 @@
         public CacheResponse get(URI uri, String rqstMethod, Map rqstHeaders) {
             getWasCalled = uri;
             if (testGet && uri.equals(uri1)) {
-                return new TestCacheResponse("file1.cache");
+                return new TestCacheResponse("Cache test");
             }
             return null;
         }
diff --git a/luni/src/test/java/libcore/java/net/ProxySelectorTest.java b/luni/src/test/java/libcore/java/net/ProxySelectorTest.java
new file mode 100644
index 0000000..491cb8d
--- /dev/null
+++ b/luni/src/test/java/libcore/java/net/ProxySelectorTest.java
@@ -0,0 +1,207 @@
+/*
+ * 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.
+ */
+
+package libcore.java.net;
+
+import static java.net.InetSocketAddress.createUnresolved;
+import java.net.Proxy;
+import java.net.ProxySelector;
+import java.net.URI;
+import java.net.URISyntaxException;
+import java.util.Arrays;
+import junit.framework.TestCase;
+
+public final class ProxySelectorTest extends TestCase {
+
+    private ProxySelector proxySelector;
+
+    private URI httpUri;
+    private URI ftpUri;
+    private URI httpsUri;
+    private URI socketUri;
+    private URI otherUri;
+
+    protected void setUp() throws Exception {
+        super.setUp();
+        proxySelector = ProxySelector.getDefault();
+        httpUri = new URI("http://android.com");
+        ftpUri = new URI("ftp://android.com");
+        httpsUri = new URI("https://android.com");
+        socketUri = new URI("socket://android.com");
+        otherUri = new URI("other://android.com");
+    }
+
+    @Override protected void tearDown() throws Exception {
+        System.clearProperty("ftp.proxyHost");
+        System.clearProperty("ftp.proxyPort");
+        System.clearProperty("ftp.nonProxyHosts");
+        System.clearProperty("http.proxyHost");
+        System.clearProperty("http.proxyPort");
+        System.clearProperty("http.nonProxyHosts");
+        System.clearProperty("https.proxyHost");
+        System.clearProperty("https.proxyPort");
+        System.clearProperty("https.nonProxyHosts");
+        System.clearProperty("other.proxyHost");
+        System.clearProperty("other.proxyPort");
+        System.clearProperty("socket.proxyHost");
+        System.clearProperty("socket.proxyPort");
+        System.clearProperty("proxyHost");
+        System.clearProperty("proxyPort");
+    }
+
+    public void testNoProxySystemProperty() throws URISyntaxException {
+        assertEquals(Arrays.asList(Proxy.NO_PROXY), proxySelector.select(ftpUri));
+        assertEquals(Arrays.asList(Proxy.NO_PROXY), proxySelector.select(httpUri));
+        assertEquals(Arrays.asList(Proxy.NO_PROXY), proxySelector.select(httpsUri));
+        assertEquals(Arrays.asList(Proxy.NO_PROXY), proxySelector.select(socketUri));
+        assertEquals(Arrays.asList(Proxy.NO_PROXY), proxySelector.select(otherUri));
+    }
+
+    public void testProxyHostOnly() throws URISyntaxException {
+        System.setProperty("ftp.proxyHost", "a");
+        System.setProperty("http.proxyHost", "b");
+        System.setProperty("https.proxyHost", "c");
+        System.setProperty("other.proxyHost", "d");
+        System.setProperty("socket.proxyHost", "d");
+        assertEquals(Arrays.asList(new Proxy(Proxy.Type.HTTP, createUnresolved("a", 80))),
+                proxySelector.select(ftpUri));
+        assertEquals(Arrays.asList(new Proxy(Proxy.Type.HTTP, createUnresolved("b", 80))),
+                proxySelector.select(httpUri));
+        assertEquals(Arrays.asList(new Proxy(Proxy.Type.HTTP, createUnresolved("c", 443))),
+                proxySelector.select(httpsUri));
+        assertEquals(Arrays.asList(Proxy.NO_PROXY), proxySelector.select(otherUri));
+        assertEquals(Arrays.asList(Proxy.NO_PROXY), proxySelector.select(socketUri));
+    }
+
+    public void testProxyHostPort() throws URISyntaxException {
+        System.setProperty("ftp.proxyHost", "a");
+        System.setProperty("ftp.proxyPort", "1001");
+        System.setProperty("http.proxyHost", "b");
+        System.setProperty("http.proxyPort", "1002");
+        System.setProperty("https.proxyHost", "c");
+        System.setProperty("https.proxyPort", "1003");
+        System.setProperty("other.proxyHost", "d");
+        System.setProperty("other.proxyPort", "1004");
+        System.setProperty("socket.proxyHost", "e");
+        System.setProperty("socket.proxyPort", "1005");
+        assertEquals(Arrays.asList(new Proxy(Proxy.Type.HTTP, createUnresolved("a", 1001))),
+                proxySelector.select(ftpUri));
+        assertEquals(Arrays.asList(new Proxy(Proxy.Type.HTTP, createUnresolved("b", 1002))),
+                proxySelector.select(httpUri));
+        assertEquals(Arrays.asList(new Proxy(Proxy.Type.HTTP, createUnresolved("c", 1003))),
+                proxySelector.select(httpsUri));
+        assertEquals(Arrays.asList(Proxy.NO_PROXY), proxySelector.select(socketUri));
+        assertEquals(Arrays.asList(Proxy.NO_PROXY), proxySelector.select(otherUri));
+    }
+
+    public void testProxyPortOnly() throws URISyntaxException {
+        System.setProperty("ftp.proxyPort", "1001");
+        System.setProperty("http.proxyPort", "1002");
+        System.setProperty("https.proxyPort", "1003");
+        System.setProperty("other.proxyPort", "1004");
+        System.setProperty("socket.proxyPort", "1005");
+        assertEquals(Arrays.asList(Proxy.NO_PROXY), proxySelector.select(ftpUri));
+        assertEquals(Arrays.asList(Proxy.NO_PROXY), proxySelector.select(httpUri));
+        assertEquals(Arrays.asList(Proxy.NO_PROXY), proxySelector.select(httpsUri));
+        assertEquals(Arrays.asList(Proxy.NO_PROXY), proxySelector.select(socketUri));
+        assertEquals(Arrays.asList(Proxy.NO_PROXY), proxySelector.select(otherUri));
+    }
+
+    public void testHttpsDoesNotUseHttpProperties() throws URISyntaxException {
+        System.setProperty("http.proxyHost", "a");
+        System.setProperty("http.proxyPort", "1001");
+        assertEquals(Arrays.asList(Proxy.NO_PROXY), proxySelector.select(httpsUri));
+    }
+
+    public void testProxyHost() throws URISyntaxException {
+        System.setProperty("proxyHost", "a");
+        assertEquals(Arrays.asList(new Proxy(Proxy.Type.HTTP, createUnresolved("a", 80))),
+                proxySelector.select(ftpUri));
+        assertEquals(Arrays.asList(new Proxy(Proxy.Type.HTTP, createUnresolved("a", 80))),
+                proxySelector.select(httpUri));
+        assertEquals(Arrays.asList(new Proxy(Proxy.Type.HTTP, createUnresolved("a", 443))),
+                proxySelector.select(httpsUri));
+        assertEquals(Arrays.asList(Proxy.NO_PROXY), proxySelector.select(socketUri));
+        assertEquals(Arrays.asList(Proxy.NO_PROXY), proxySelector.select(otherUri));
+    }
+
+    public void testHttpProxyHostPreferredOverProxyHost() throws URISyntaxException {
+        System.setProperty("http.proxyHost", "a");
+        System.setProperty("proxyHost", "b");
+        assertEquals(Arrays.asList(new Proxy(Proxy.Type.HTTP, createUnresolved("a", 80))),
+                proxySelector.select(httpUri));
+    }
+
+    public void testSocksProxyHost() throws URISyntaxException {
+        System.setProperty("socksProxyHost", "a");
+        assertEquals(Arrays.asList(new Proxy(Proxy.Type.SOCKS, createUnresolved("a", 1080))),
+                proxySelector.select(ftpUri));
+        assertEquals(Arrays.asList(new Proxy(Proxy.Type.SOCKS, createUnresolved("a", 1080))),
+                proxySelector.select(httpUri));
+        assertEquals(Arrays.asList(new Proxy(Proxy.Type.SOCKS, createUnresolved("a", 1080))),
+                proxySelector.select(httpsUri));
+        assertEquals(Arrays.asList(new Proxy(Proxy.Type.SOCKS, createUnresolved("a", 1080))),
+                proxySelector.select(socketUri));
+        assertEquals(Arrays.asList(Proxy.NO_PROXY), proxySelector.select(otherUri));
+    }
+
+    public void testSocksProxyHostAndPort() throws URISyntaxException {
+        System.setProperty("socksProxyHost", "a");
+        System.setProperty("socksProxyPort", "1001");
+        assertEquals(Arrays.asList(new Proxy(Proxy.Type.SOCKS, createUnresolved("a", 1001))),
+                proxySelector.select(ftpUri));
+        assertEquals(Arrays.asList(new Proxy(Proxy.Type.SOCKS, createUnresolved("a", 1001))),
+                proxySelector.select(httpUri));
+        assertEquals(Arrays.asList(new Proxy(Proxy.Type.SOCKS, createUnresolved("a", 1001))),
+                proxySelector.select(httpsUri));
+        assertEquals(Arrays.asList(new Proxy(Proxy.Type.SOCKS, createUnresolved("a", 1001))),
+                proxySelector.select(socketUri));
+        assertEquals(Arrays.asList(Proxy.NO_PROXY), proxySelector.select(otherUri));
+    }
+
+    public void testNonProxyHostsFtp() throws URISyntaxException {
+        System.setProperty("ftp.nonProxyHosts", "*.com");
+        System.setProperty("ftp.proxyHost", "a");
+        assertEquals(Arrays.asList(new Proxy(Proxy.Type.HTTP, createUnresolved("a", 80))),
+                proxySelector.select(new URI("ftp://foo.net")));
+        assertEquals(Arrays.asList(Proxy.NO_PROXY),
+                proxySelector.select(new URI("ftp://foo.com")));
+    }
+
+    public void testNonProxyHostsHttp() throws URISyntaxException {
+        System.setProperty("http.nonProxyHosts", "*.com");
+        System.setProperty("http.proxyHost", "a");
+        assertEquals(Arrays.asList(new Proxy(Proxy.Type.HTTP, createUnresolved("a", 80))),
+                proxySelector.select(new URI("http://foo.net")));
+        assertEquals(Arrays.asList(Proxy.NO_PROXY),
+                proxySelector.select(new URI("http://foo.com")));
+    }
+
+    public void testNonProxyHostsHttps() throws URISyntaxException {
+        System.setProperty("https.nonProxyHosts", "*.com");
+        System.setProperty("https.proxyHost", "a");
+        assertEquals(Arrays.asList(new Proxy(Proxy.Type.HTTP, createUnresolved("a", 443))),
+                proxySelector.select(new URI("https://foo.net")));
+        assertEquals(Arrays.asList(Proxy.NO_PROXY),
+                proxySelector.select(new URI("https://foo.com")));
+    }
+
+    public void testSchemeCaseSensitive() throws URISyntaxException {
+        System.setProperty("http.proxyHost", "a");
+        assertEquals(Arrays.asList(new Proxy(Proxy.Type.HTTP, createUnresolved("a", 80))),
+                proxySelector.select(new URI("HTTP://foo.net")));
+    }
+}
diff --git a/luni/src/test/java/libcore/java/nio/BufferTest.java b/luni/src/test/java/libcore/java/nio/BufferTest.java
index 9c741a5..712e964 100644
--- a/luni/src/test/java/libcore/java/nio/BufferTest.java
+++ b/luni/src/test/java/libcore/java/nio/BufferTest.java
@@ -21,8 +21,16 @@
 import junit.framework.TestCase;
 
 public class BufferTest extends TestCase {
-    public void testByteSwappedHeapBulkGet() throws Exception {
-        ByteBuffer b = ByteBuffer.allocate(10);
+    public void testByteSwappedBulkGetDirect() throws Exception {
+        testByteSwappedBulkGet(true);
+    }
+
+    public void testByteSwappedBulkGetHeap() throws Exception {
+        testByteSwappedBulkGet(false);
+    }
+
+    private void testByteSwappedBulkGet(boolean direct) throws Exception {
+        ByteBuffer b = direct ? ByteBuffer.allocateDirect(10) : ByteBuffer.allocate(10);
         for (int i = 0; i < b.limit(); ++i) {
             b.put(i, (byte) i);
         }
@@ -95,7 +103,7 @@
         assertEquals(0, shorts[5]);
     }
 
-    public static String toString(ByteBuffer b) {
+    private static String toString(ByteBuffer b) {
         StringBuilder result = new StringBuilder();
         for (int i = 0; i < b.limit(); ++i) {
             result.append(String.format("%02x", (int) b.get(i)));
@@ -103,8 +111,16 @@
         return result.toString();
     }
 
-    public void testByteSwappedHeapBulkPut() throws Exception {
-        ByteBuffer b = ByteBuffer.allocate(10);
+    public void testByteSwappedBulkPutDirect() throws Exception {
+        testByteSwappedBulkPut(true);
+    }
+
+    public void testByteSwappedBulkPutHeap() throws Exception {
+        testByteSwappedBulkPut(false);
+    }
+
+    private void testByteSwappedBulkPut(boolean direct) throws Exception {
+        ByteBuffer b = direct ? ByteBuffer.allocateDirect(10) : ByteBuffer.allocate(10);
         b.position(1);
 
         char[] chars = new char[] { '\u2222', '\u0102', '\u0304', '\u0506', '\u0708', '\u2222' };
@@ -144,4 +160,144 @@
         b.order(ByteOrder.LITTLE_ENDIAN).asShortBuffer().put(shorts, 1, 4);
         assertEquals("00020104030605080700", toString(b));
     }
+
+    public void testByteBufferByteOrderDirectRW() throws Exception {
+        testByteBufferByteOrder(true, false);
+    }
+
+    public void testByteBufferByteOrderHeapRW() throws Exception {
+        testByteBufferByteOrder(false, false);
+    }
+
+    public void testByteBufferByteOrderDirectRO() throws Exception {
+        testByteBufferByteOrder(true, true);
+    }
+
+    public void testByteBufferByteOrderHeapRO() throws Exception {
+        testByteBufferByteOrder(false, true);
+    }
+
+    private void testByteBufferByteOrder(boolean direct, boolean readOnly) throws Exception {
+        // allocate/allocateDirect always returns a big-endian buffer.
+        ByteBuffer b = direct ? ByteBuffer.allocateDirect(10) : ByteBuffer.allocate(10);
+        if (readOnly) {
+            b = b.asReadOnlyBuffer();
+        }
+        assertEquals(ByteOrder.BIG_ENDIAN, b.order());
+
+        // wrap always returns a big-endian buffer.
+        assertEquals(ByteOrder.BIG_ENDIAN, b.wrap(new byte[10]).order());
+
+        // duplicate always returns a big-endian buffer.
+        b.order(ByteOrder.BIG_ENDIAN);
+        assertEquals(ByteOrder.BIG_ENDIAN, b.duplicate().order());
+        b.order(ByteOrder.LITTLE_ENDIAN);
+        assertEquals(ByteOrder.BIG_ENDIAN, b.duplicate().order());
+
+        // slice always returns a big-endian buffer.
+        b.order(ByteOrder.BIG_ENDIAN);
+        assertEquals(ByteOrder.BIG_ENDIAN, b.slice().order());
+        b.order(ByteOrder.LITTLE_ENDIAN);
+        assertEquals(ByteOrder.BIG_ENDIAN, b.slice().order());
+
+        // asXBuffer always returns a current-endian buffer.
+        b.order(ByteOrder.BIG_ENDIAN);
+        assertEquals(ByteOrder.BIG_ENDIAN, b.asCharBuffer().order());
+        assertEquals(ByteOrder.BIG_ENDIAN, b.asDoubleBuffer().order());
+        assertEquals(ByteOrder.BIG_ENDIAN, b.asFloatBuffer().order());
+        assertEquals(ByteOrder.BIG_ENDIAN, b.asIntBuffer().order());
+        assertEquals(ByteOrder.BIG_ENDIAN, b.asLongBuffer().order());
+        assertEquals(ByteOrder.BIG_ENDIAN, b.asShortBuffer().order());
+        b.order(ByteOrder.LITTLE_ENDIAN);
+        assertEquals(ByteOrder.LITTLE_ENDIAN, b.asCharBuffer().order());
+        assertEquals(ByteOrder.LITTLE_ENDIAN, b.asDoubleBuffer().order());
+        assertEquals(ByteOrder.LITTLE_ENDIAN, b.asFloatBuffer().order());
+        assertEquals(ByteOrder.LITTLE_ENDIAN, b.asIntBuffer().order());
+        assertEquals(ByteOrder.LITTLE_ENDIAN, b.asLongBuffer().order());
+        assertEquals(ByteOrder.LITTLE_ENDIAN, b.asShortBuffer().order());
+    }
+
+    public void testCharBufferByteOrder() throws Exception {
+        // Everything always returns a native-endian buffer.
+        CharBuffer b = CharBuffer.allocate(10);
+        assertEquals(ByteOrder.nativeOrder(), b.order());
+        assertEquals(ByteOrder.nativeOrder(), b.wrap(new char[10]).order());
+        assertEquals(ByteOrder.nativeOrder(), b.duplicate().order());
+        assertEquals(ByteOrder.nativeOrder(), b.slice().order());
+        b = b.asReadOnlyBuffer();
+        assertEquals(ByteOrder.nativeOrder(), b.order());
+        assertEquals(ByteOrder.nativeOrder(), b.wrap(new char[10]).order());
+        assertEquals(ByteOrder.nativeOrder(), b.duplicate().order());
+        assertEquals(ByteOrder.nativeOrder(), b.slice().order());
+    }
+
+    public void testDoubleBufferByteOrder() throws Exception {
+        // Everything always returns a native-endian buffer.
+        DoubleBuffer b = DoubleBuffer.allocate(10);
+        assertEquals(ByteOrder.nativeOrder(), b.order());
+        assertEquals(ByteOrder.nativeOrder(), b.wrap(new double[10]).order());
+        assertEquals(ByteOrder.nativeOrder(), b.duplicate().order());
+        assertEquals(ByteOrder.nativeOrder(), b.slice().order());
+        b = b.asReadOnlyBuffer();
+        assertEquals(ByteOrder.nativeOrder(), b.order());
+        assertEquals(ByteOrder.nativeOrder(), b.wrap(new double[10]).order());
+        assertEquals(ByteOrder.nativeOrder(), b.duplicate().order());
+        assertEquals(ByteOrder.nativeOrder(), b.slice().order());
+    }
+
+    public void testFloatBufferByteOrder() throws Exception {
+        // Everything always returns a native-endian buffer.
+        FloatBuffer b = FloatBuffer.allocate(10);
+        assertEquals(ByteOrder.nativeOrder(), b.order());
+        assertEquals(ByteOrder.nativeOrder(), b.wrap(new float[10]).order());
+        assertEquals(ByteOrder.nativeOrder(), b.duplicate().order());
+        assertEquals(ByteOrder.nativeOrder(), b.slice().order());
+        b = b.asReadOnlyBuffer();
+        assertEquals(ByteOrder.nativeOrder(), b.order());
+        assertEquals(ByteOrder.nativeOrder(), b.wrap(new float[10]).order());
+        assertEquals(ByteOrder.nativeOrder(), b.duplicate().order());
+        assertEquals(ByteOrder.nativeOrder(), b.slice().order());
+    }
+
+    public void testIntBufferByteOrder() throws Exception {
+        // Everything always returns a native-endian buffer.
+        IntBuffer b = IntBuffer.allocate(10);
+        assertEquals(ByteOrder.nativeOrder(), b.order());
+        assertEquals(ByteOrder.nativeOrder(), b.wrap(new int[10]).order());
+        assertEquals(ByteOrder.nativeOrder(), b.duplicate().order());
+        assertEquals(ByteOrder.nativeOrder(), b.slice().order());
+        b = b.asReadOnlyBuffer();
+        assertEquals(ByteOrder.nativeOrder(), b.order());
+        assertEquals(ByteOrder.nativeOrder(), b.wrap(new int[10]).order());
+        assertEquals(ByteOrder.nativeOrder(), b.duplicate().order());
+        assertEquals(ByteOrder.nativeOrder(), b.slice().order());
+    }
+
+    public void testLongBufferByteOrder() throws Exception {
+        // Everything always returns a native-endian buffer.
+        LongBuffer b = LongBuffer.allocate(10);
+        assertEquals(ByteOrder.nativeOrder(), b.order());
+        assertEquals(ByteOrder.nativeOrder(), b.wrap(new long[10]).order());
+        assertEquals(ByteOrder.nativeOrder(), b.duplicate().order());
+        assertEquals(ByteOrder.nativeOrder(), b.slice().order());
+        b = b.asReadOnlyBuffer();
+        assertEquals(ByteOrder.nativeOrder(), b.order());
+        assertEquals(ByteOrder.nativeOrder(), b.wrap(new long[10]).order());
+        assertEquals(ByteOrder.nativeOrder(), b.duplicate().order());
+        assertEquals(ByteOrder.nativeOrder(), b.slice().order());
+    }
+
+    public void testShortBufferByteOrder() throws Exception {
+        // Everything always returns a native-endian buffer.
+        ShortBuffer b = ShortBuffer.allocate(10);
+        assertEquals(ByteOrder.nativeOrder(), b.order());
+        assertEquals(ByteOrder.nativeOrder(), b.wrap(new short[10]).order());
+        assertEquals(ByteOrder.nativeOrder(), b.duplicate().order());
+        assertEquals(ByteOrder.nativeOrder(), b.slice().order());
+        b = b.asReadOnlyBuffer();
+        assertEquals(ByteOrder.nativeOrder(), b.order());
+        assertEquals(ByteOrder.nativeOrder(), b.wrap(new short[10]).order());
+        assertEquals(ByteOrder.nativeOrder(), b.duplicate().order());
+        assertEquals(ByteOrder.nativeOrder(), b.slice().order());
+    }
 }
diff --git a/luni/src/test/java/libcore/java/nio/channels/ChannelsTest.java b/luni/src/test/java/libcore/java/nio/channels/ChannelsTest.java
new file mode 100644
index 0000000..4bbf3a9
--- /dev/null
+++ b/luni/src/test/java/libcore/java/nio/channels/ChannelsTest.java
@@ -0,0 +1,60 @@
+/*
+ * 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.
+ */
+
+package libcore.java.nio.channels;
+
+import java.io.IOException;
+import java.nio.ByteBuffer;
+import java.nio.channels.Channels;
+import java.nio.channels.IllegalBlockingModeException;
+import java.nio.channels.Pipe;
+import java.nio.channels.WritableByteChannel;
+import junit.framework.TestCase;
+
+public final class ChannelsTest extends TestCase {
+
+    public void testStreamNonBlocking() throws IOException {
+        Pipe.SourceChannel sourceChannel = createNonBlockingChannel("abc".getBytes("UTF-8"));
+        try {
+            Channels.newInputStream(sourceChannel).read();
+            fail();
+        } catch (IllegalBlockingModeException expected) {
+        }
+    }
+
+    /**
+     * This fails on the RI which violates its own promise to throw when
+     * read in non-blocking mode.
+     */
+    public void testReaderNonBlocking() throws IOException {
+        Pipe.SourceChannel sourceChannel = createNonBlockingChannel("abc".getBytes("UTF-8"));
+        try {
+            Channels.newReader(sourceChannel, "UTF-8").read();
+            fail();
+        } catch (IllegalBlockingModeException expected) {
+        }
+    }
+
+    private Pipe.SourceChannel createNonBlockingChannel(byte[] content) throws IOException {
+        Pipe pipe = Pipe.open();
+        WritableByteChannel sinkChannel = pipe.sink();
+        sinkChannel.write(ByteBuffer.wrap(content));
+        Pipe.SourceChannel sourceChannel = pipe.source();
+        sourceChannel.configureBlocking(false);
+        return sourceChannel;
+    }
+}
+
diff --git a/luni/src/test/java/libcore/java/text/AttributedCharacterIteratorAttributeTest.java b/luni/src/test/java/libcore/java/text/AttributedCharacterIteratorAttributeTest.java
new file mode 100644
index 0000000..9119582
--- /dev/null
+++ b/luni/src/test/java/libcore/java/text/AttributedCharacterIteratorAttributeTest.java
@@ -0,0 +1,69 @@
+/*
+ * 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.
+ */
+
+package libcore.java.text;
+
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.InvalidObjectException;
+import java.io.ObjectInputStream;
+import java.io.ObjectOutputStream;
+import java.text.AttributedCharacterIterator;
+import java.text.DateFormat;
+import java.text.NumberFormat;
+import junit.framework.TestCase;
+
+/**
+ * AttributedCharacterIterator.Attribute is used like the base enum type and
+ * subclassed by unrelated classes.
+ */
+public final class AttributedCharacterIteratorAttributeTest extends TestCase {
+
+    public void testSerialization() throws IOException, ClassNotFoundException {
+        assertSameReserialized(AttributedCharacterIterator.Attribute.LANGUAGE);
+        assertSameReserialized(DateFormat.Field.ERA);
+        assertSameReserialized(DateFormat.Field.TIME_ZONE);
+        assertSameReserialized(NumberFormat.Field.INTEGER);
+    }
+
+    public void testSerializingSubclass() throws IOException, ClassNotFoundException {
+        AttributedCharacterIterator.Attribute a = new CustomAttribute();
+        try {
+            reserialize(a);
+            fail();
+        } catch (InvalidObjectException expected) {
+        }
+    }
+
+    private void assertSameReserialized(Object o) throws ClassNotFoundException, IOException {
+        assertSame(o, reserialize(o));
+    }
+
+    private Object reserialize(Object o) throws IOException, ClassNotFoundException {
+        ByteArrayOutputStream out = new ByteArrayOutputStream();
+        new ObjectOutputStream(out).writeObject(o);
+        InputStream in = new ByteArrayInputStream(out.toByteArray());
+        return new ObjectInputStream(in).readObject();
+    }
+
+    private static class CustomAttribute extends AttributedCharacterIterator.Attribute {
+        public CustomAttribute() {
+            super("a");
+        }
+    }
+}
diff --git a/luni/src/test/java/libcore/java/text/CollatorTest.java b/luni/src/test/java/libcore/java/text/CollatorTest.java
index 844af5b..78cb6f0 100644
--- a/luni/src/test/java/libcore/java/text/CollatorTest.java
+++ b/luni/src/test/java/libcore/java/text/CollatorTest.java
@@ -92,9 +92,7 @@
         RuleBasedCollator coll = new RuleBasedCollator(rule);
 
         assertEquals(Collator.TERTIARY, coll.getStrength());
-        // This is a harmony test, but it assumes that RuleBasedCollators default to
-        // NO_DECOMPOSITION, which isn't true on Android.
-        // assertEquals(Collator.NO_DECOMPOSITION, coll.getDecomposition());
+        assertEquals(Collator.NO_DECOMPOSITION, coll.getDecomposition());
         RuleBasedCollator other = new RuleBasedCollator(rule);
         assertTrue(coll.equals(other));
 
diff --git a/luni/src/test/java/libcore/java/util/OldScannerTest.java b/luni/src/test/java/libcore/java/util/OldScannerTest.java
new file mode 100644
index 0000000..b51cfbc
--- /dev/null
+++ b/luni/src/test/java/libcore/java/util/OldScannerTest.java
@@ -0,0 +1,559 @@
+/* Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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 libcore.java.util;
+
+import java.io.IOException;
+import java.io.StringReader;
+import java.net.InetSocketAddress;
+import java.nio.CharBuffer;
+import java.nio.channels.IllegalBlockingModeException;
+import java.nio.channels.ServerSocketChannel;
+import java.nio.channels.SocketChannel;
+import java.util.Arrays;
+import java.util.NoSuchElementException;
+import java.util.Scanner;
+import java.util.regex.MatchResult;
+import java.util.regex.Pattern;
+import junit.framework.TestCase;
+import tests.support.Support_PortManager;
+
+public final class OldScannerTest extends TestCase {
+
+    private Scanner s;
+
+    public void test_findWithinHorizon_Ljava_lang_StringI() {
+        // This method searches through the input up to the specified search
+        // horizon(exclusive).
+        s = new Scanner("123test");
+        String result = s.findWithinHorizon("\\p{Lower}", 5);
+        assertEquals("t", result);
+        MatchResult mresult = s.match();
+        assertEquals(3, mresult.start());
+        assertEquals(4, mresult.end());
+
+        s = new Scanner("12345test1234test next");
+        /*
+         * If the pattern is found the scanner advances past the input that
+         * matched and returns the string that matched the pattern.
+         */
+        result = s.findWithinHorizon("\\p{Digit}+", 2);
+        assertEquals("12", result);
+        mresult = s.match();
+        assertEquals(0, mresult.start());
+        assertEquals(2, mresult.end());
+        // Position is now pointing at the bar. "12|345test1234test next"
+
+        result = s.findWithinHorizon("\\p{Digit}+", 6);
+        assertEquals("345", result);
+
+        mresult = s.match();
+        assertEquals(2, mresult.start());
+        assertEquals(5, mresult.end());
+        // Position is now pointing at the bar. "12345|test1234test next"
+
+        // If no such pattern is detected then the null is returned and the
+        // scanner's position remains unchanged.
+        result = s.findWithinHorizon("\\p{Digit}+", 3);
+        assertNull(result);
+
+        try {
+            s.match();
+            fail("Should throw IllegalStateException");
+        } catch (IllegalStateException e) {
+            // expected
+        }
+        assertEquals("345", mresult.group());
+        assertEquals(2, mresult.start());
+        assertEquals(5, mresult.end());
+        // Position is now still pointing at the bar. "12345|test1234test next"
+
+        // If horizon is 0, then the horizon is ignored and this method
+        // continues to search through the input looking for the specified
+        // pattern without bound.
+        result = s.findWithinHorizon("\\p{Digit}+", 0);
+        mresult = s.match();
+        assertEquals(9, mresult.start());
+        assertEquals(13, mresult.end());
+        // Position is now pointing at the bar. "12345test1234|test next"
+
+        assertEquals("test", s.next());
+        mresult = s.match();
+        assertEquals(13, mresult.start());
+        assertEquals(17, mresult.end());
+
+        assertEquals("next", s.next());
+        mresult = s.match();
+        assertEquals(18, mresult.start());
+        assertEquals(22, mresult.end());
+
+        try {
+            s.findWithinHorizon((String)null, 1);
+            fail("Should throw NullPointerException");
+        } catch (NullPointerException e) {
+            // expected
+        }
+
+        try {
+            s.findWithinHorizon("\\p{Digit}+", -1);
+            fail("Should throw IllegalArgumentException");
+        } catch (IllegalArgumentException e) {
+            // expected
+        }
+
+        s.close();
+        // on RI throws NullPointerException
+        /*
+         * try { System.out.println("fsdfs"); s.findWithinHorizon((String) null,
+         * -1); System.out.println("fsdfs"); fail("Should throw
+         * IllegalStateException"); } catch (IllegalStateException e) { //
+         * expected }
+         */
+        s = new Scanner("test");
+        result = s.findWithinHorizon("\\w+", 10);
+        assertEquals("test", result);
+
+        s = new Scanner("aa\n\rb");
+        String patternStr = "^(a)$";
+        result = s.findWithinHorizon("a", 5);
+        assertEquals("a", result);
+        mresult = s.match();
+        assertEquals(0, mresult.start());
+        assertEquals(1, mresult.end());
+
+        result = s.findWithinHorizon(patternStr, 5);
+        assertNull(result);
+
+        try {
+            mresult = s.match();
+            fail("Should throw IllegalStateException");
+        } catch (IllegalStateException e) {
+            // expected
+        }
+
+        s = new Scanner("");
+        result = s.findWithinHorizon("^", 0);
+        assertEquals("", result);
+        MatchResult matchResult = s.match();
+        assertEquals(0, matchResult.start());
+        assertEquals(0, matchResult.end());
+
+        result = s.findWithinHorizon("$", 0);
+        assertEquals("", result);
+        matchResult = s.match();
+        assertEquals(0, matchResult.start());
+        assertEquals(0, matchResult.end());
+
+        s = new Scanner("1 fish 2 fish red fish blue fish");
+        result = s.findWithinHorizon("(\\d+) fish (\\d+) fish (\\w+) fish (\\w+)", 10);
+        assertNull(result);
+
+        try {
+            mresult = s.match();
+            fail("Should throw IllegalStateException");
+        } catch (IllegalStateException e) {
+            // expected
+        }
+        assertEquals(0, mresult.groupCount());
+
+        result = s.findWithinHorizon("(\\d+) fish (\\d+) fish (\\w+) fish (\\w+)", 100);
+        assertEquals("1 fish 2 fish red fish blue", result);
+        mresult = s.match();
+        assertEquals(4, mresult.groupCount());
+        assertEquals("1", mresult.group(1));
+        assertEquals("2", mresult.group(2));
+        assertEquals("red", mresult.group(3));
+        assertEquals("blue", mresult.group(4));
+
+        s = new Scanner("test");
+        s.close();
+        try {
+            s.findWithinHorizon("test", 1);
+            fail("Should throw IllegalStateException");
+        } catch (IllegalStateException e) {
+            // expected
+        }
+
+        s = new Scanner("word1 WorD2  ");
+        s.close();
+        try {
+            s.findWithinHorizon("\\d+", 10);
+            fail("should throw IllegalStateException");
+        } catch (IllegalStateException e) {
+            // expected
+        }
+
+        s = new Scanner("word1 WorD2 wOrd3 ");
+        patternStr = "\\d+";
+        assertEquals("1", s.findWithinHorizon(patternStr, 10));
+        assertEquals("WorD2", s.next());
+        assertEquals("3", s.findWithinHorizon(patternStr, 15));
+
+        // Regression test
+        s = new Scanner(new MockStringReader("MockStringReader"));
+        patternStr = "test";
+        result = s.findWithinHorizon(patternStr, 10);
+        assertEquals("test", result);
+
+        // Test the situation when input length is longer than buffer size.
+        StringBuilder stringBuilder = new StringBuilder();
+        for (int i = 0; i < 1026; i++) {
+            stringBuilder.append('a');
+        }
+        s = new Scanner(stringBuilder.toString());
+        patternStr = "\\p{Lower}+";
+        result = s.findWithinHorizon(patternStr, 1026);
+        assertEquals(stringBuilder.toString(), result);
+
+        // Test the situation when input length is longer than buffer size and
+        // set horizon to buffer size.
+        stringBuilder = new StringBuilder();
+        for (int i = 0; i < 1026; i++) {
+            stringBuilder.append('a');
+        }
+        s = new Scanner(stringBuilder.toString());
+        patternStr = "\\p{Lower}+";
+        result = s.findWithinHorizon(patternStr, 1022);
+        assertEquals(1022, result.length());
+        assertEquals(stringBuilder.subSequence(0, 1022), result);
+
+        // Test the situation, under which pattern is clipped by buffer.
+        stringBuilder = new StringBuilder();
+        for (int i = 0; i < 1022; i++) {
+            stringBuilder.append(' ');
+        }
+        stringBuilder.append("bbc");
+        assertEquals(1025, stringBuilder.length());
+        s = new Scanner(stringBuilder.toString());
+        patternStr = "bbc";
+        result = s.findWithinHorizon(patternStr, 1025);
+        assertEquals(3, result.length());
+        assertEquals(stringBuilder.subSequence(1022, 1025), result);
+
+        stringBuilder = new StringBuilder();
+        for (int i = 0; i < 1026; i++) {
+            stringBuilder.append('a');
+        }
+        s = new Scanner(stringBuilder.toString());
+        patternStr = "\\p{Lower}+";
+        result = s.findWithinHorizon(patternStr, 0);
+        assertEquals(stringBuilder.toString(), result);
+
+        stringBuilder = new StringBuilder();
+        for (int i = 0; i < 10240; i++) {
+            stringBuilder.append('-');
+        }
+        stringBuilder.replace(0, 2, "aa");
+        s = new Scanner(stringBuilder.toString());
+        result = s.findWithinHorizon("aa", 0);
+        assertEquals("aa", result);
+
+        s = new Scanner("aaaa");
+        result = s.findWithinHorizon("a*", 0);
+        assertEquals("aaaa", result);
+    }
+
+    public void test_findInLine_LString() {
+        s = new Scanner("test");
+        try {
+            s.findInLine((String) null);
+            fail("Should throw NullPointerException");
+        } catch (NullPointerException e) {
+            // expected
+        }
+
+        s.close();
+        try {
+            s.findInLine((String) null);
+            fail("Should throw NullPointerException");
+        } catch (NullPointerException e) {
+            // expected
+        }
+        try {
+            s.findInLine("test");
+            fail("Should throw IllegalStateException");
+        } catch (IllegalStateException e) {
+            // exptected
+        }
+
+        s = new Scanner("");
+
+        String result = s.findInLine("^");
+        assertEquals("", result);
+        MatchResult matchResult = s.match();
+        assertEquals(0, matchResult.start());
+        assertEquals(0, matchResult.end());
+
+        result = s.findInLine("$");
+        assertEquals("", result);
+        matchResult = s.match();
+        assertEquals(0, matchResult.start());
+        assertEquals(0, matchResult.end());
+
+        /*
+         * When we use the operation of findInLine(Pattern), the match region
+         * should not span the line separator.
+         */
+        s = new Scanner("aa\nb.b");
+        result = s.findInLine("a\nb*");
+        assertNull(result);
+
+        s = new Scanner("aa\nbb.b");
+        result = s.findInLine("\\.");
+        assertNull(result);
+
+        s = new Scanner("abcd1234test\n");
+        result = s.findInLine("\\p{Lower}+");
+        assertEquals("abcd", result);
+        matchResult = s.match();
+        assertEquals(0, matchResult.start());
+        assertEquals(4, matchResult.end());
+
+        result = s.findInLine("\\p{Digit}{5}");
+        assertNull(result);
+        try {
+            matchResult = s.match();
+            fail("Should throw IllegalStateException");
+        } catch (IllegalStateException e) {
+            // expected
+        }
+        assertEquals(0, matchResult.start());
+        assertEquals(4, matchResult.end());
+
+        result = s.findInLine("\\p{Lower}+");
+        assertEquals("test", result);
+        matchResult = s.match();
+        assertEquals(8, matchResult.start());
+        assertEquals(12, matchResult.end());
+
+        char[] chars = new char[2048];
+        Arrays.fill(chars, 'a');
+        StringBuilder stringBuilder = new StringBuilder();
+        stringBuilder.append(chars);
+        stringBuilder.append("1234");
+        s = new Scanner(stringBuilder.toString());
+        result = s.findInLine("\\p{Digit}+");
+        assertEquals("1234", result);
+        matchResult = s.match();
+        assertEquals(2048, matchResult.start());
+        assertEquals(2052, matchResult.end());
+
+        s = new Scanner("test1234\n1234 test");
+        result = s.findInLine("test");
+        assertEquals("test", result);
+        matchResult = s.match();
+        assertEquals(0, matchResult.start());
+        assertEquals(4, matchResult.end());
+
+        int number = s.nextInt();
+        assertEquals(1234, number);
+        matchResult = s.match();
+        assertEquals(4, matchResult.start());
+        assertEquals(8, matchResult.end());
+
+        result = s.next();
+        assertEquals("1234", result);
+        matchResult = s.match();
+        assertEquals(9, matchResult.start());
+        assertEquals(13, matchResult.end());
+
+        result = s.findInLine("test");
+        assertEquals("test", result);
+        matchResult = s.match();
+        assertEquals(14, matchResult.start());
+        assertEquals(18, matchResult.end());
+
+        s = new Scanner("test\u0085\ntest");
+        result = s.findInLine("est");
+        assertEquals("est", result);
+        result = s.findInLine("est");
+        assertEquals("est", result);
+
+        s = new Scanner("test\ntest");
+        result = s.findInLine("est");
+        assertEquals("est", result);
+        result = s.findInLine("est");
+        assertEquals("est", result);
+
+        s = new Scanner("test\n123\ntest");
+        result = s.findInLine("est");
+        assertEquals("est", result);
+        result = s.findInLine("est");
+    }
+
+    public void test_skip_LPattern() {
+        s = new Scanner("test");
+        try {
+            s.skip((String) null);
+            fail("Should throw NullPointerException");
+        } catch (NullPointerException e) {
+            // expected
+        }
+
+        // If pattern does not match, NoSuchElementException will be thrown out.
+        s = new Scanner("1234");
+        try {
+            s.skip(Pattern.compile("\\p{Lower}"));
+            fail("Should throw NoSuchElementException");
+        } catch (NoSuchElementException e) {
+            // expected
+        }
+        // Then, no matchResult will be thrown out.
+        try {
+            s.match();
+            fail("Should throw IllegalStateException");
+        } catch (IllegalStateException e) {
+            // expected
+        }
+
+        s.skip(Pattern.compile("\\p{Digit}"));
+        MatchResult matchResult = s.match();
+        assertEquals(0, matchResult.start());
+        assertEquals(1, matchResult.end());
+
+        s.skip(Pattern.compile("\\p{Digit}+"));
+        matchResult = s.match();
+        assertEquals(1, matchResult.start());
+        assertEquals(4, matchResult.end());
+
+        s.close();
+        try {
+            s.skip(Pattern.compile("test"));
+            fail("Should throw IllegalStateException");
+        } catch (IllegalStateException e) {
+            // expected
+        }
+
+        MockStringReader2Read reader = new MockStringReader2Read("test");
+        s = new Scanner(reader);
+        try {
+            s.skip(Pattern.compile("\\p{Digit}{4}"));
+            fail("Should throw NoSuchElementException");
+        } catch (NoSuchElementException e) {
+            // expected
+        }
+        try {
+            s.match();
+            fail("Should throw IllegalStateException");
+        } catch (IllegalStateException e) {
+            // expected
+        }
+        s.skip(Pattern.compile("\\p{Digit}{3}\\p{Lower}"));
+        matchResult = s.match();
+        assertEquals(0, matchResult.start());
+        assertEquals(4, matchResult.end());
+
+        s.close();
+        try {
+            s.skip((Pattern) null);
+            fail("Should throw IllegalStateException");
+        } catch (IllegalStateException e) {
+            // expected
+        }
+
+        StringBuilder stringBuilder = new StringBuilder();
+        char [] chars = new char[1024];
+        Arrays.fill(chars, 'a');
+        stringBuilder.append(chars);
+        stringBuilder.append('3');
+        s = new Scanner(stringBuilder.toString());
+        s.skip(Pattern.compile("\\p{Lower}+\\p{Digit}"));
+        matchResult = s.match();
+        assertEquals(0, matchResult.start());
+        assertEquals(1025, matchResult.end());
+
+        // Large amount of input may be cached
+        chars = new char[102400];
+        Arrays.fill(chars, 'a');
+        stringBuilder = new StringBuilder();
+        stringBuilder.append(chars);
+        s = new Scanner(stringBuilder.toString());
+        s.skip(Pattern.compile(".*"));
+        matchResult = s.match();
+        assertEquals(0, matchResult.start());
+        assertEquals(102400, matchResult.end());
+
+        // skip something without risking a NoSuchElementException
+        s.skip(Pattern.compile("[ \t]*"));
+        matchResult = s.match();
+        assertEquals(102400, matchResult.start());
+        assertEquals(102400, matchResult.end());
+    }
+
+    public void test_Constructor_LReadableByteChannel()
+            throws IOException {
+        InetSocketAddress localAddr = new InetSocketAddress("127.0.0.1",
+                Support_PortManager.getNextPort());
+        ServerSocketChannel ssc = ServerSocketChannel.open();
+        ssc.socket().bind(localAddr);
+
+        SocketChannel sc = SocketChannel.open();
+        sc.connect(localAddr);
+        sc.configureBlocking(false);
+        assertFalse(sc.isBlocking());
+
+        ssc.accept().close();
+        ssc.close();
+        assertFalse(sc.isBlocking());
+
+        Scanner s = new Scanner(sc);
+        try {
+            s.hasNextInt();
+            fail();
+        } catch (IllegalBlockingModeException expected) {
+        }
+
+        sc.close();
+    }
+
+    private static class MockStringReader extends StringReader {
+
+        public MockStringReader(String param) {
+            super(param);
+        }
+
+        public int read(CharBuffer target) throws IOException {
+            target.append('t');
+            target.append('e');
+            target.append('s');
+            target.append('t');
+            throw new IOException();
+        }
+    }
+
+    private static class MockStringReader2Read extends StringReader {
+        private int timesRead = 1;
+
+        public MockStringReader2Read(String param) {
+            super(param);
+        }
+
+        public int read(CharBuffer target) throws IOException {
+            if (timesRead == 1) {
+                target.append('1');
+                target.append('2');
+                target.append('3');
+                timesRead++;
+                return 3;
+            } else if (timesRead == 2) {
+                target.append('t');
+                timesRead++;
+                return 1;
+            } else {
+                throw new IOException();
+            }
+        }
+    }
+}
diff --git a/luni/src/test/java/org/apache/harmony/archive/tests/java/util/jar/DalvikExecTest.java b/luni/src/test/java/libcore/java/util/jar/DalvikExecTest.java
similarity index 98%
rename from luni/src/test/java/org/apache/harmony/archive/tests/java/util/jar/DalvikExecTest.java
rename to luni/src/test/java/libcore/java/util/jar/DalvikExecTest.java
index 2df14b4..1f66653 100644
--- a/luni/src/test/java/org/apache/harmony/archive/tests/java/util/jar/DalvikExecTest.java
+++ b/luni/src/test/java/libcore/java/util/jar/DalvikExecTest.java
@@ -14,11 +14,7 @@
  * limitations under the License.
  */
 
-package org.apache.harmony.archive.tests.java.util.jar;
-
-import junit.framework.TestCase;
-import static tests.support.Support_Exec.execAndGetOutput;
-import tests.support.resource.Support_Resources;
+package libcore.java.util.jar;
 
 import java.io.ByteArrayOutputStream;
 import java.io.File;
@@ -30,6 +26,9 @@
 import java.util.jar.JarFile;
 import java.util.jar.JarOutputStream;
 import java.util.jar.Manifest;
+import junit.framework.TestCase;
+import static tests.support.Support_Exec.execAndGetOutput;
+import tests.support.resource.Support_Resources;
 
 
 public class DalvikExecTest extends TestCase {
@@ -40,6 +39,9 @@
         ProcessBuilder builder = new ProcessBuilder();
 
         String base = System.getenv("OUT");
+        if (base == null) {
+            base = "";
+        }
         builder.command().add(base + "/system/bin/dalvikvm");
 
         builder.command().add("-Djava.io.tmpdir=/tmp/mc");
diff --git a/luni/src/test/java/org/apache/harmony/archive/tests/java/util/jar/AttributesNameTest.java b/luni/src/test/java/libcore/java/util/jar/OldAttributesNameTest.java
similarity index 78%
rename from luni/src/test/java/org/apache/harmony/archive/tests/java/util/jar/AttributesNameTest.java
rename to luni/src/test/java/libcore/java/util/jar/OldAttributesNameTest.java
index f390ffd..0d83715 100644
--- a/luni/src/test/java/org/apache/harmony/archive/tests/java/util/jar/AttributesNameTest.java
+++ b/luni/src/test/java/libcore/java/util/jar/OldAttributesNameTest.java
@@ -15,34 +15,23 @@
  * limitations under the License.
  */
 
-package org.apache.harmony.archive.tests.java.util.jar;
+package libcore.java.util.jar;
 
 import java.util.jar.Attributes;
 import junit.framework.TestCase;
 
-public class AttributesNameTest extends TestCase {
+public class OldAttributesNameTest extends TestCase {
 
     /**
      * @tests java.util.jar.Attributes.Name#Name(java.lang.String)
      */
     public void test_AttributesName_Constructor() {
-        // Regression for HARMONY-85
         try {
-            new Attributes.Name(
-                    "01234567890123456789012345678901234567890123456789012345678901234567890");
-            fail("Assert 0: should have thrown IllegalArgumentException");
-        } catch (IllegalArgumentException e) {
-            // expected
-        }
-
-        try {
-            new Attributes.Name((String) null);
+            new Attributes.Name(null);
             fail("NullPointerException expected");
         } catch (NullPointerException ee) {
             // expected
         }
-
-        assertNotNull(new Attributes.Name("Attr"));
     }
 
     public void test_equalsLjava_lang_Object() {
diff --git a/luni/src/test/java/libcore/java/util/jar/OldAttributesTest.java b/luni/src/test/java/libcore/java/util/jar/OldAttributesTest.java
new file mode 100644
index 0000000..e945e32
--- /dev/null
+++ b/luni/src/test/java/libcore/java/util/jar/OldAttributesTest.java
@@ -0,0 +1,104 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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 libcore.java.util.jar;
+
+import java.util.jar.Attributes;
+import junit.framework.TestCase;
+
+public class OldAttributesTest extends TestCase {
+    private Attributes a;
+
+    @Override
+    protected void setUp() {
+        a = new Attributes();
+        a.putValue("1", "one");
+        a.putValue("2", "two");
+        a.putValue("3", "three");
+        a.putValue("4", "four");
+    }
+
+    public void test_getLjava_lang_Object() {
+
+        try {
+            a.getValue("IllegalArgumentException expected");
+        } catch (IllegalArgumentException ee) {
+            // expected
+        }
+    }
+
+    public void test_Constructor() {
+        Attributes attr = new Attributes();
+        assertTrue(attr.size() >= 0);
+    }
+
+    public void test_ConstructorI() {
+        Attributes attr = new Attributes(10);
+        assertTrue(attr.size() >= 0);
+    }
+
+    public void test_getLjava_lang_Object_true() {
+        assertEquals("a) Incorrect value returned", "one", a
+                .get(new Attributes.Name("1")));
+        assertNull("b) Incorrect value returned", a.get("0"));
+        assertNull("b) Incorrect value returned", a.get("1"));
+    }
+
+    public void test_getValueLjava_util_jar_Attributes_Name() {
+        assertEquals("a) Incorrect value returned", "one", a
+                .getValue(new Attributes.Name("1")));
+        assertNull("b) Incorrect value returned", a
+                .getValue(new Attributes.Name("0")));
+    }
+
+    public void test_hashCode() {
+        Attributes b = (Attributes) a.clone();
+        b.putValue("33", "Thirty three");
+        assertNotSame(a.hashCode(), b.hashCode());
+        b = (Attributes) a.clone();
+        b.clear();
+        assertNotSame(a.hashCode(), b.hashCode());
+    }
+
+    public void test_putValueLjava_lang_StringLjava_lang_String() {
+        Attributes b = new Attributes();
+        b.put(new Attributes.Name("1"), "one");
+        b.putValue("2", "two");
+        b.put(new Attributes.Name("3"), "three");
+        b.putValue("4", "four");
+
+        assertTrue(a.equals(b));
+
+        try {
+            b.putValue(null, "null");
+            fail("NullPointerException expected");
+        } catch (NullPointerException ee) {
+            // expected
+        }
+
+        StringBuffer sb = new StringBuffer();
+        for (int i = 0; i < 0x10000; i++) {
+            sb.append('3');
+        }
+        try {
+            b.putValue(new String(sb), "wrong name");
+            fail("IllegalArgumentException expected");
+        } catch (IllegalArgumentException ee) {
+            // expected
+        }
+    }
+}
diff --git a/luni/src/test/java/libcore/java/util/jar/OldJarEntryTest.java b/luni/src/test/java/libcore/java/util/jar/OldJarEntryTest.java
new file mode 100644
index 0000000..ed24d8b
--- /dev/null
+++ b/luni/src/test/java/libcore/java/util/jar/OldJarEntryTest.java
@@ -0,0 +1,138 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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 libcore.java.util.jar;
+
+import java.io.File;
+import java.io.IOException;
+import java.util.jar.JarEntry;
+import java.util.jar.JarFile;
+import java.util.zip.ZipEntry;
+import junit.framework.TestCase;
+import tests.support.resource.Support_Resources;
+
+
+public class OldJarEntryTest extends TestCase {
+    private ZipEntry zipEntry;
+    private JarEntry jarEntry;
+    private JarFile jarFile;
+    private final String jarName = "hyts_patch.jar";
+    private final String entryName = "foo/bar/A.class";
+    private File resources;
+
+    @Override
+    protected void setUp() throws Exception {
+        resources = Support_Resources.createTempFolder();
+        Support_Resources.copyFile(resources, null, jarName);
+        jarFile = new JarFile(new File(resources, jarName));
+    }
+
+    @Override
+    protected void tearDown() throws Exception {
+        if (jarFile != null) {
+            jarFile.close();
+        }
+    }
+
+    /**
+     * @throws IOException
+     * @tests java.util.jar.JarEntry#JarEntry(java.util.jar.JarEntry)
+     */
+    public void test_ConstructorLjava_util_jar_JarEntry_on_null() throws IOException {
+        JarEntry newJarEntry = new JarEntry(jarFile.getJarEntry(entryName));
+        assertNotNull(newJarEntry);
+
+        jarEntry = null;
+        try {
+            newJarEntry = new JarEntry(jarEntry);
+            fail("Should throw NullPointerException");
+        } catch (NullPointerException e) {
+            // Expected
+        }
+    }
+
+    /**
+     * @tests java.util.jar.JarEntry#JarEntry(java.util.zip.ZipEntry)
+     */
+    public void test_ConstructorLjava_util_zip_ZipEntry() {
+        assertNotNull("Jar file is null", jarFile);
+        zipEntry = jarFile.getEntry(entryName);
+        assertNotNull("Zip entry is null", zipEntry);
+        jarEntry = new JarEntry(zipEntry);
+        assertNotNull("Jar entry is null", jarEntry);
+        assertEquals("Wrong entry constructed--wrong name", entryName, jarEntry
+                .getName());
+        assertEquals("Wrong entry constructed--wrong size", 311, jarEntry
+                .getSize());
+    }
+
+    /**
+     * @tests java.util.jar.JarEntry#getAttributes()
+     */
+    public void test_getAttributes() {
+        JarFile attrJar = null;
+        File file = null;
+
+        Support_Resources.copyFile(resources, null, "Broken_manifest.jar");
+        try {
+            attrJar = new JarFile(new File(resources, "Broken_manifest.jar"));
+            jarEntry = attrJar.getJarEntry("META-INF/");
+            jarEntry.getAttributes();
+            fail("IOException expected");
+        } catch (IOException e) {
+            // expected.
+        }
+    }
+
+    public void test_ConstructorLjava_lang_String() {
+        assertNotNull("Jar file is null", jarFile);
+        zipEntry = jarFile.getEntry(entryName);
+        assertNotNull("Zip entry is null", zipEntry);
+        jarEntry = new JarEntry(entryName);
+        assertNotNull("Jar entry is null", jarEntry);
+        assertEquals("Wrong entry constructed--wrong name", entryName, jarEntry
+                .getName());
+        try {
+            jarEntry = new JarEntry((String) null);
+            fail("NullPointerException expected");
+        } catch (NullPointerException ee) {
+            // expected
+        }
+        StringBuffer sb = new StringBuffer();
+        for (int i = 0; i < 0x10000; i++) {
+            sb.append('3');
+        }
+        try {
+            jarEntry = new JarEntry(new String(sb));
+            fail("IllegalArgumentException expected");
+        } catch (IllegalArgumentException ee) {
+            // expected
+        }
+    }
+
+    public void test_ConstructorLjava_util_jar_JarEntry() {
+        assertNotNull("Jar file is null", jarFile);
+        JarEntry je = jarFile.getJarEntry(entryName);
+        assertNotNull("Jar entry is null", je);
+        jarEntry = new JarEntry(je);
+        assertNotNull("Jar entry is null", jarEntry);
+        assertEquals("Wrong entry constructed--wrong name", entryName, jarEntry
+                .getName());
+        assertEquals("Wrong entry constructed--wrong size", 311, jarEntry
+                .getSize());
+    }
+}
diff --git a/luni/src/test/java/org/apache/harmony/archive/tests/java/util/jar/JarExceptionTest.java b/luni/src/test/java/libcore/java/util/jar/OldJarExceptionTest.java
similarity index 88%
rename from luni/src/test/java/org/apache/harmony/archive/tests/java/util/jar/JarExceptionTest.java
rename to luni/src/test/java/libcore/java/util/jar/OldJarExceptionTest.java
index a23837e..397931a 100644
--- a/luni/src/test/java/org/apache/harmony/archive/tests/java/util/jar/JarExceptionTest.java
+++ b/luni/src/test/java/libcore/java/util/jar/OldJarExceptionTest.java
@@ -15,15 +15,12 @@
  * limitations under the License.
  */
 
-package org.apache.harmony.archive.tests.java.util.jar;
+package libcore.java.util.jar;
 
-import java.io.ByteArrayInputStream;
-import java.io.IOException;
-import java.util.jar.Manifest;
-import junit.framework.TestCase;
 import java.util.jar.JarException;
+import junit.framework.TestCase;
 
-public class JarExceptionTest extends TestCase {
+public class OldJarExceptionTest extends TestCase {
     /**
      * @tests java.util.jar.JarException#JarException(java.lang.String)
      */
diff --git a/luni/src/test/java/libcore/java/util/jar/OldJarFileTest.java b/luni/src/test/java/libcore/java/util/jar/OldJarFileTest.java
new file mode 100644
index 0000000..0da4d0e
--- /dev/null
+++ b/luni/src/test/java/libcore/java/util/jar/OldJarFileTest.java
@@ -0,0 +1,293 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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 libcore.java.util.jar;
+
+import java.io.File;
+import java.io.IOException;
+import java.io.InputStream;
+import java.security.Permission;
+import java.util.jar.JarEntry;
+import java.util.jar.JarFile;
+import java.util.zip.ZipException;
+import java.util.zip.ZipFile;
+import junit.framework.TestCase;
+import tests.support.resource.Support_Resources;
+
+public class OldJarFileTest extends TestCase {
+
+    private final String jarName = "hyts_patch.jar"; // a 'normal' jar file
+    private final String entryName = "foo/bar/A.class";
+    private File resources;
+
+    // custom security manager
+    SecurityManager sm = new SecurityManager() {
+        final String forbidenPermissionName = "user.dir";
+
+        public void checkPermission(Permission perm) {
+            if (perm.getName().equals(forbidenPermissionName)) {
+                throw new SecurityException();
+            }
+        }
+    };
+
+    @Override
+    protected void setUp() {
+        resources = Support_Resources.createTempFolder();
+    }
+
+    /**
+     * @tests java.util.jar.JarFile#JarFile(java.io.File)
+     */
+    public void test_ConstructorLjava_io_File() throws IOException {
+        try {
+            new JarFile(new File("Wrong.file"));
+            fail("Should throw IOException");
+        } catch (IOException e) {
+            // expected
+        }
+        SecurityManager oldSm = System.getSecurityManager();
+        System.setSecurityManager(sm);
+        try {
+            new JarFile(new File("tmp.jar"));
+            fail("Should throw SecurityException");
+        } catch (IOException e) {
+            fail("Should throw SecurityException");
+        } catch (SecurityException e) {
+            // expected
+        } finally {
+            System.setSecurityManager(oldSm);
+        }
+
+        Support_Resources.copyFile(resources, null, jarName);
+        new JarFile(new File(resources, jarName));
+    }
+
+    /**
+     * @tests java.util.jar.JarFile#JarFile(java.lang.String)
+     */
+    public void test_ConstructorLjava_lang_String() throws IOException {
+        try {
+            new JarFile("Wrong.file");
+            fail("Should throw IOException");
+        } catch (IOException e) {
+            // expected
+        }
+        SecurityManager oldSm = System.getSecurityManager();
+        System.setSecurityManager(sm);
+        try {
+            new JarFile("tmp.jar");
+            fail("Should throw SecurityException");
+        } catch (IOException e) {
+            fail("Should throw SecurityException");
+        } catch (SecurityException e) {
+            // expected
+        } finally {
+            System.setSecurityManager(oldSm);
+        }
+
+        Support_Resources.copyFile(resources, null, jarName);
+        String fileName = (new File(resources, jarName)).getCanonicalPath();
+        new JarFile(fileName);
+    }
+
+    /**
+     * @tests java.util.jar.JarFile#JarFile(java.lang.String, boolean)
+     */
+    public void test_ConstructorLjava_lang_StringZ() throws IOException {
+        try {
+            new JarFile("Wrong.file", false);
+            fail("Should throw IOException");
+        } catch (IOException e) {
+            // expected
+        }
+        SecurityManager oldSm = System.getSecurityManager();
+        System.setSecurityManager(sm);
+        try {
+            new JarFile("tmp.jar", true);
+            fail("Should throw SecurityException");
+        } catch (IOException e) {
+            fail("Should throw SecurityException");
+        } catch (SecurityException e) {
+            // expected
+        } finally {
+            System.setSecurityManager(oldSm);
+        }
+
+        Support_Resources.copyFile(resources, null, jarName);
+        String fileName = (new File(resources, jarName)).getCanonicalPath();
+        new JarFile(fileName, true);
+    }
+
+    /**
+     * @tests java.util.jar.JarFile#JarFile(java.io.File, boolean)
+     */
+    public void test_ConstructorLjava_io_FileZ() throws IOException {
+        try {
+            new JarFile(new File("Wrong.file"), true);
+            fail("Should throw IOException");
+        } catch (IOException e) {
+            // expected
+        }
+        SecurityManager oldSm = System.getSecurityManager();
+        System.setSecurityManager(sm);
+        try {
+            new JarFile(new File("tmp.jar"), false);
+            fail("Should throw SecurityException");
+        } catch (IOException e) {
+            fail("Should throw SecurityException");
+        } catch (SecurityException e) {
+            // expected
+        } finally {
+            System.setSecurityManager(oldSm);
+        }
+
+        Support_Resources.copyFile(resources, null, jarName);
+        new JarFile(new File(resources, jarName), false);
+    }
+
+    /**
+     * @tests java.util.jar.JarFile#JarFile(java.io.File, boolean, int)
+     */
+    public void test_ConstructorLjava_io_FileZI() {
+        try {
+            new JarFile(new File("Wrong.file"), true,
+                    ZipFile.OPEN_READ);
+            fail("Should throw IOException");
+        } catch (IOException e) {
+            // expected
+        }
+        SecurityManager oldSm = System.getSecurityManager();
+        System.setSecurityManager(sm);
+        try {
+            new JarFile(new File("tmp.jar"), false,
+                    ZipFile.OPEN_READ);
+            fail("Should throw SecurityException");
+        } catch (IOException e) {
+            fail("Should throw SecurityException");
+        } catch (SecurityException e) {
+            // expected
+        } finally {
+            System.setSecurityManager(oldSm);
+        }
+
+        try {
+            Support_Resources.copyFile(resources, null, jarName);
+            new JarFile(new File(resources, jarName), false,
+                    ZipFile.OPEN_READ);
+        } catch (IOException e) {
+            fail("Should not throw IOException");
+        }
+
+        try {
+            Support_Resources.copyFile(resources, null, jarName);
+            new JarFile(new File(resources, jarName), false,
+                    ZipFile.OPEN_READ | ZipFile.OPEN_DELETE + 33);
+            fail("Should throw IllegalArgumentException");
+        } catch (IOException e) {
+            fail("Should not throw IOException");
+        } catch (IllegalArgumentException e) {
+            // expected
+        }
+    }
+
+
+
+    public void test_close() throws IOException {
+        String modifiedJarName = "Modified_SF_EntryAttributes.jar";
+        Support_Resources.copyFile(resources, null, modifiedJarName);
+        JarFile jarFile = new JarFile(new File(resources, modifiedJarName), true);
+        jarFile.entries();
+
+        jarFile.close();
+        jarFile.close();
+
+        // Can not check IOException
+    }
+
+    /**
+     * @throws IOException
+     * @tests java.util.jar.JarFile#getInputStream(java.util.zip.ZipEntry)
+     */
+    public void test_getInputStreamLjava_util_jar_JarEntry() throws IOException {
+        File localFile = null;
+        try {
+            Support_Resources.copyFile(resources, null, jarName);
+            localFile = new File(resources, jarName);
+        } catch (Exception e) {
+            fail("Failed to create local file: " + e);
+        }
+
+        byte[] b = new byte[1024];
+        try {
+            JarFile jf = new JarFile(localFile);
+            java.io.InputStream is = jf.getInputStream(jf.getEntry(entryName));
+            // BEGIN android-removed
+            // jf.close();
+            // END android-removed
+            assertTrue("Returned invalid stream", is.available() > 0);
+            int r = is.read(b, 0, 1024);
+            is.close();
+            StringBuffer sb = new StringBuffer(r);
+            for (int i = 0; i < r; i++) {
+                sb.append((char) (b[i] & 0xff));
+            }
+            String contents = sb.toString();
+            assertTrue("Incorrect stream read", contents.indexOf("bar") > 0);
+            // BEGIN android-added
+            jf.close();
+            // END android-added
+        } catch (Exception e) {
+            fail("Exception during test: " + e.toString());
+        }
+
+        try {
+            JarFile jf = new JarFile(localFile);
+            InputStream in = jf.getInputStream(new JarEntry("invalid"));
+            assertNull("Got stream for non-existent entry", in);
+        } catch (Exception e) {
+            fail("Exception during test 2: " + e);
+        }
+
+        try {
+            Support_Resources.copyFile(resources, null, jarName);
+            File signedFile = new File(resources, jarName);
+            JarFile jf = new JarFile(signedFile);
+            JarEntry jre = new JarEntry("foo/bar/A.class");
+            jf.getInputStream(jre);
+            // InputStream returned in any way, exception can be thrown in case
+            // of reading from this stream only.
+            // fail("Should throw ZipException");
+        } catch (ZipException ee) {
+            // expected
+        }
+
+        try {
+            Support_Resources.copyFile(resources, null, jarName);
+            File signedFile = new File(resources, jarName);
+            JarFile jf = new JarFile(signedFile);
+            JarEntry jre = new JarEntry("foo/bar/A.class");
+            jf.close();
+            jf.getInputStream(jre);
+            // InputStream returned in any way, exception can be thrown in case
+            // of reading from this stream only.
+            // The same for IOException
+            fail("Should throw IllegalStateException");
+        } catch (IllegalStateException ee) {
+            // expected
+        }
+    }
+}
diff --git a/luni/src/test/java/libcore/java/util/jar/OldJarInputStreamTest.java b/luni/src/test/java/libcore/java/util/jar/OldJarInputStreamTest.java
new file mode 100644
index 0000000..77bb3ba3
--- /dev/null
+++ b/luni/src/test/java/libcore/java/util/jar/OldJarInputStreamTest.java
@@ -0,0 +1,92 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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 libcore.java.util.jar;
+
+import java.io.BufferedInputStream;
+import java.io.ByteArrayInputStream;
+import java.io.File;
+import java.io.IOException;
+import java.io.InputStream;
+import java.util.jar.JarInputStream;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipException;
+import tests.support.resource.Support_Resources;
+
+public class OldJarInputStreamTest extends junit.framework.TestCase {
+
+    public void test_ConstructorLjava_io_InputStreamZ() {
+        try {
+            // we need a buffered stream because ByteArrayInputStream.close() is a no-op
+            InputStream is = new BufferedInputStream(new ByteArrayInputStream(new byte[0]));
+            is.close();
+            new JarInputStream(is, false);
+            fail("IOException expected");
+        } catch (IOException ee) {
+            // expected
+        }
+    }
+
+
+    class Mock_JarInputStream extends JarInputStream {
+
+        public Mock_JarInputStream(InputStream in) throws IOException {
+            super(in);
+        }
+
+        public ZipEntry createZipEntry(String str) {
+            return super.createZipEntry(str);
+        }
+    }
+
+    public void test_createZipEntryLjava_lang_String() throws Exception {
+        File resources = Support_Resources.createTempFolder();
+        Support_Resources.copyFile(resources, null, "Broken_entry.jar");
+        InputStream is = Support_Resources.getStream("Broken_entry.jar");
+        Mock_JarInputStream mjis = new Mock_JarInputStream(is);
+        assertNotNull(mjis.createZipEntry("New entry"));
+    }
+
+    public void test_read$ZII() throws Exception {
+        File resources = Support_Resources.createTempFolder();
+        Support_Resources.copyFile(resources, null, "Broken_entry_data.jar");
+        InputStream is = Support_Resources.getStream("Broken_entry_data.jar");
+        JarInputStream jis = new JarInputStream(is, true);
+        byte b[] = new byte[100];
+
+        jis.getNextEntry();
+        jis.read(b, 0, 100);
+        jis.getNextEntry();
+        jis.getNextEntry();
+        jis.getNextEntry();
+
+        try {
+            jis.read(b, 0, 100);
+            fail("ZipException expected");
+        } catch (ZipException ee) {
+            // expected
+        }
+
+        try {
+            jis.close();  // Android throws exception here, already!
+            jis.read(b, 0, 100);  // But RI here, only!
+            fail("IOException expected");
+        } catch (IOException ee) {
+            // expected
+        }
+    }
+}
diff --git a/luni/src/test/java/libcore/java/util/jar/OldJarOutputStreamTest.java b/luni/src/test/java/libcore/java/util/jar/OldJarOutputStreamTest.java
new file mode 100644
index 0000000..e5e2f32
--- /dev/null
+++ b/luni/src/test/java/libcore/java/util/jar/OldJarOutputStreamTest.java
@@ -0,0 +1,43 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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 libcore.java.util.jar;
+
+import java.io.File;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.OutputStream;
+import java.util.jar.JarEntry;
+import java.util.jar.JarOutputStream;
+import java.util.jar.Manifest;
+
+public class OldJarOutputStreamTest extends junit.framework.TestCase {
+
+    public void test_putNextEntryLjava_util_zip_ZipEntry() throws Exception {
+        final String entryName = "foo/bar/execjartest/MainClass.class";
+        Manifest newman = new Manifest();
+        File outputJar = File.createTempFile("hyts_", ".jar");
+        OutputStream os = new FileOutputStream(outputJar);
+        JarOutputStream jout = new JarOutputStream(os, newman);
+        os.close();
+        try {
+            jout.putNextEntry(new JarEntry(entryName));
+            fail("IOException expected");
+        } catch (IOException expected) {
+        }
+    }
+}
diff --git a/luni/src/test/java/libcore/java/util/jar/OldManifestTest.java b/luni/src/test/java/libcore/java/util/jar/OldManifestTest.java
new file mode 100644
index 0000000..9552aef
--- /dev/null
+++ b/luni/src/test/java/libcore/java/util/jar/OldManifestTest.java
@@ -0,0 +1,144 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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 libcore.java.util.jar;
+
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.File;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.net.MalformedURLException;
+import java.net.URL;
+import java.util.jar.Attributes;
+import java.util.jar.Manifest;
+import junit.framework.TestCase;
+import tests.support.resource.Support_Resources;
+
+public class OldManifestTest extends TestCase {
+
+    public void test_ConstructorLjava_util_jar_Manifest() {
+        // Test for method java.util.jar.Manifest()
+        Manifest emptyManifest = new Manifest();
+        Manifest emptyClone = new Manifest(emptyManifest);
+        assertTrue("Should have no entries", emptyClone.getEntries().isEmpty());
+        assertTrue("Should have no main attributes", emptyClone
+                .getMainAttributes().isEmpty());
+        assertEquals(emptyClone, emptyManifest);
+        assertEquals(emptyClone, emptyManifest.clone());
+    }
+
+    private void assertAttribute(Attributes attr, String name, String value) {
+        assertEquals("Incorrect " + name, value, attr.getValue(name));
+    }
+
+    private void checkManifest(Manifest manifest) {
+        Attributes main = manifest.getMainAttributes();
+        assertAttribute(main, "Bundle-Name", "ClientSupport");
+        assertAttribute(main, "Bundle-Description",
+                "Provides SessionService, AuthenticationService. Extends RegistryService.");
+        assertAttribute(main, "Bundle-Activator",
+                "com.ibm.ive.eccomm.client.support.ClientSupportActivator");
+        assertAttribute(
+                main,
+                "Import-Package",
+                "com.ibm.ive.eccomm.client.services.log,com.ibm.ive.eccomm.client.services.registry,com.ibm.ive.eccomm.service.registry; specification-version=1.0.0,com.ibm.ive.eccomm.service.session; specification-version=1.0.0,com.ibm.ive.eccomm.service.framework; specification-version=1.2.0,org.osgi.framework; specification-version=1.0.0,org.osgi.service.log; specification-version=1.0.0,com.ibm.ive.eccomm.flash; specification-version=1.2.0,com.ibm.ive.eccomm.client.xml,com.ibm.ive.eccomm.client.http.common,com.ibm.ive.eccomm.client.http.client");
+        assertAttribute(
+                main,
+                "Import-Service",
+                "org.osgi.service.log.LogReaderServiceorg.osgi.service.log.LogService,com.ibm.ive.eccomm.service.registry.RegistryService");
+        assertAttribute(
+                main,
+                "Export-Package",
+                "com.ibm.ive.eccomm.client.services.authentication; specification-version=1.0.0,com.ibm.ive.eccomm.service.authentication; specification-version=1.0.0,com.ibm.ive.eccomm.common; specification-version=1.0.0,com.ibm.ive.eccomm.client.services.registry.store; specification-version=1.0.0");
+        assertAttribute(
+                main,
+                "Export-Service",
+                "com.ibm.ive.eccomm.service.authentication.AuthenticationService,com.ibm.ive.eccomm.service.session.SessionService");
+        assertAttribute(main, "Bundle-Vendor", "IBM");
+        assertAttribute(main, "Bundle-Version", "1.2.0");
+    }
+
+    public void test_clone() throws IOException {
+        Manifest emptyManifest = new Manifest();
+        Manifest emptyClone = (Manifest) emptyManifest.clone();
+        assertTrue("Should have no entries", emptyClone.getEntries().isEmpty());
+        assertTrue("Should have no main attributes", emptyClone
+                .getMainAttributes().isEmpty());
+        assertEquals(emptyClone, emptyManifest);
+        assertEquals(emptyManifest.clone().getClass().getName(),
+                "java.util.jar.Manifest");
+
+        Manifest manifest = new Manifest(new URL(Support_Resources
+                .getURL("manifest/hyts_MANIFEST.MF")).openStream());
+        Manifest manifestClone = (Manifest) manifest.clone();
+        manifestClone.getMainAttributes();
+        checkManifest(manifestClone);
+    }
+
+    public void test_equals() throws IOException {
+        Manifest manifest1 = new Manifest(new URL(Support_Resources.getURL(
+                "manifest/hyts_MANIFEST.MF")).openStream());
+        Manifest manifest2 = new Manifest(new URL(Support_Resources.getURL(
+                "manifest/hyts_MANIFEST.MF")).openStream());
+        Manifest manifest3 = new Manifest();
+
+        assertTrue(manifest1.equals(manifest1));
+        assertTrue(manifest1.equals(manifest2));
+        assertFalse(manifest1.equals(manifest3));
+        assertFalse(manifest1.equals(this));
+    }
+
+    public void test_writeLjava_io_OutputStream() throws IOException {
+        byte b[];
+        Manifest manifest1 = null;
+        Manifest manifest2 = null;
+        try {
+            manifest1 = new Manifest(new URL(Support_Resources
+                    .getURL("manifest/hyts_MANIFEST.MF")).openStream());
+        } catch (MalformedURLException e) {
+            fail("Malformed URL");
+        }
+
+        ByteArrayOutputStream baos = new ByteArrayOutputStream();
+
+        manifest1.write(baos);
+
+        b = baos.toByteArray();
+
+        File f = File.createTempFile("111", "111");
+        FileOutputStream fos = new FileOutputStream(f);
+        fos.close();
+        try {
+            manifest1.write(fos);
+            fail("IOException expected");
+        } catch (IOException e) {
+            // expected
+        }
+        f.delete();
+
+        ByteArrayInputStream bais = new ByteArrayInputStream(b);
+
+        try {
+            manifest2 = new Manifest(bais);
+        } catch (MalformedURLException e) {
+            fail("Malformed URL");
+        }
+
+        assertTrue(manifest1.equals(manifest2));
+    }
+
+}
diff --git a/luni/src/test/java/org/apache/harmony/archive/tests/java/util/zip/DataFormatExceptionTest.java b/luni/src/test/java/libcore/java/util/zip/OldDataFormatExceptionTest.java
similarity index 89%
rename from luni/src/test/java/org/apache/harmony/archive/tests/java/util/zip/DataFormatExceptionTest.java
rename to luni/src/test/java/libcore/java/util/zip/OldDataFormatExceptionTest.java
index 929227d..3439cd8 100644
--- a/luni/src/test/java/org/apache/harmony/archive/tests/java/util/zip/DataFormatExceptionTest.java
+++ b/luni/src/test/java/libcore/java/util/zip/OldDataFormatExceptionTest.java
@@ -14,13 +14,13 @@
  * limitations under the License.
  */
 
-package org.apache.harmony.archive.tests.java.util.zip;
+package libcore.java.util.zip;
 
 import junit.framework.TestCase;
 
 import java.util.zip.DataFormatException;
 
-public class DataFormatExceptionTest extends TestCase {
+public class OldDataFormatExceptionTest extends TestCase {
 
     public void testDataFormatException() {
         DataFormatException dfe = new DataFormatException();
diff --git a/luni/src/test/java/org/apache/harmony/archive/tests/java/util/zip/ZipExceptionTest.java b/luni/src/test/java/libcore/java/util/zip/OldZipExceptionTest.java
similarity index 90%
rename from luni/src/test/java/org/apache/harmony/archive/tests/java/util/zip/ZipExceptionTest.java
rename to luni/src/test/java/libcore/java/util/zip/OldZipExceptionTest.java
index 9f3be8d..f44fbf5 100644
--- a/luni/src/test/java/org/apache/harmony/archive/tests/java/util/zip/ZipExceptionTest.java
+++ b/luni/src/test/java/libcore/java/util/zip/OldZipExceptionTest.java
@@ -14,13 +14,13 @@
  * limitations under the License.
  */
 
-package org.apache.harmony.archive.tests.java.util.zip;
+package libcore.java.util.zip;
 
 import junit.framework.TestCase;
 
 import java.util.zip.ZipException;
 
-public class ZipExceptionTest extends TestCase {
+public class OldZipExceptionTest extends TestCase {
 
     public void testZipException() {
         ZipException zz = new ZipException();
diff --git a/luni/src/test/java/libcore/java/util/zip/OldZipFileTest.java b/luni/src/test/java/libcore/java/util/zip/OldZipFileTest.java
new file mode 100644
index 0000000..cd28114
--- /dev/null
+++ b/luni/src/test/java/libcore/java/util/zip/OldZipFileTest.java
@@ -0,0 +1,196 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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 libcore.java.util.zip;
+
+import tests.support.Support_PlatformFile;
+import tests.support.resource.Support_Resources;
+
+import java.io.ByteArrayOutputStream;
+import java.io.File;
+import java.io.FileOutputStream;
+import java.io.FilePermission;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.security.Permission;
+import java.util.Enumeration;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipException;
+import java.util.zip.ZipFile;
+
+public class OldZipFileTest extends junit.framework.TestCase {
+
+    public byte[] getAllBytesFromStream(InputStream is) throws IOException {
+        ByteArrayOutputStream bs = new ByteArrayOutputStream();
+        byte[] buf = new byte[512];
+        int iRead;
+        while ((iRead = is.read(buf, 0, buf.length)) != -1) {
+            bs.write(buf, 0, iRead);
+        }
+        return bs.toByteArray();
+    }
+
+    public void test_size() throws IOException {
+        zfile.close();
+        try {
+            zfile.size();
+            fail("IllegalStateException expected");
+        } catch (IllegalStateException expected) {
+        }
+    }
+
+    public void test_getEntryLjava_lang_String_AndroidOnly() throws IOException {
+        java.util.zip.ZipEntry zentry = zfile.getEntry("File1.txt");
+        assertNotNull("Could not obtain ZipEntry", zentry);
+        int r;
+        InputStream in;
+
+        zentry = zfile.getEntry("testdir1");
+        assertNotNull("Must be able to obtain ZipEntry: testdir1", zentry);
+        in = zfile.getInputStream(zentry);
+        /*
+         * Android delivers empty InputStream, RI no InputStream at all. The
+         * spec doesn't clarify this, so we need to deal with both situations.
+         */
+        int data = -1;
+        if (in != null) {
+            data = in.read();
+            in.close();
+        }
+        assertEquals("Must not be able to read directory data", -1, data);
+    }
+
+    // the file hyts_zipFile.zip in setup must be included as a resource
+    private String tempFileName;
+
+    private ZipFile zfile;
+
+    /**
+     * @throws IOException
+     * @tests java.util.zip.ZipFile#close()
+     */
+    public void test_close() throws IOException {
+        // Test for method void java.util.zip.ZipFile.close()
+        File fl = new File(tempFileName);
+        ZipFile zf = new ZipFile(fl);
+        InputStream is1 = zf.getInputStream(zf.getEntry("File1.txt"));
+        InputStream is2 = zf.getInputStream(zf.getEntry("File2.txt"));
+
+        is1.read();
+        is2.read();
+
+        zf.close();
+
+        try {
+            is1.read();
+            fail("IOException expected");
+        } catch (IOException ee) {
+            // expected
+        }
+
+        try {
+            is2.read();
+            fail("IOException expected");
+        } catch (IOException ee) {
+            // expected
+        }
+    }
+
+    public void test_getEntryLjava_lang_String_Ex() throws IOException {
+        java.util.zip.ZipEntry zentry = zfile.getEntry("File1.txt");
+        assertNotNull("Could not obtain ZipEntry", zentry);
+
+        zfile.close();
+        try {
+            zfile.getEntry("File2.txt");
+            fail("IllegalStateException expected");
+        } catch (IllegalStateException ee) {
+        }
+    }
+
+    /**
+     * @throws IOException
+     * @tests java.util.zip.ZipFile#getInputStream(java.util.zip.ZipEntry)
+     */
+    public void test_getInputStreamLjava_util_zip_ZipEntry() throws IOException {
+        // Test for method java.io.InputStream
+        // java.util.zip.ZipFile.getInputStream(java.util.zip.ZipEntry)
+        ZipEntry zentry = null;
+        InputStream is = null;
+
+        zentry = zfile.getEntry("File2.txt");
+        zfile.close();
+        try {
+            is = zfile.getInputStream(zentry);
+            fail("IllegalStateException expected");
+        } catch (IllegalStateException ee) {
+            // expected
+        }
+    }
+
+    /**
+     * Sets up the fixture, for example, open a network connection. This method
+     * is called before a test is executed.
+     */
+    @Override
+    protected void setUp() throws IOException {
+        // Create a local copy of the file since some tests want to alter information.
+        tempFileName = System.getProperty("java.io.tmpdir");
+        String separator = System.getProperty("file.separator");
+        if (tempFileName.charAt(tempFileName.length() - 1) == separator.charAt(0)) {
+            tempFileName = Support_PlatformFile.getNewPlatformFile(tempFileName, "gabba.zip");
+        } else {
+            tempFileName = Support_PlatformFile.getNewPlatformFile(
+                    tempFileName + separator, "gabba.zip");
+        }
+
+        File f = new File(tempFileName);
+        f.delete();
+        InputStream is = Support_Resources.getStream("hyts_ZipFile.zip");
+        FileOutputStream fos = new FileOutputStream(f);
+        byte[] rbuf = getAllBytesFromStream(is);
+        fos.write(rbuf, 0, rbuf.length);
+        is.close();
+        fos.close();
+        zfile = new ZipFile(f);
+    }
+
+    /**
+     * Tears down the fixture, for example, close a network connection. This
+     * method is called after a test is executed.
+     */
+    @Override
+    protected void tearDown() throws IOException {
+        // Note zfile is a user-defined zip file used by other tests and
+        // should not be deleted
+        zfile.close();
+        tempFileName = System.getProperty("java.io.tmpdir");
+        String separator = System.getProperty("file.separator");
+        if (tempFileName.charAt(tempFileName.length() - 1) == separator
+                .charAt(0)) {
+            tempFileName = Support_PlatformFile.getNewPlatformFile(
+                    tempFileName, "gabba.zip");
+        } else {
+            tempFileName = Support_PlatformFile.getNewPlatformFile(
+                    tempFileName + separator, "gabba.zip");
+        }
+
+        File f = new File(tempFileName);
+        f.delete();
+    }
+}
diff --git a/luni/src/test/java/libcore/java/util/zip/OldZipInputStreamTest.java b/luni/src/test/java/libcore/java/util/zip/OldZipInputStreamTest.java
new file mode 100644
index 0000000..f28817c
--- /dev/null
+++ b/luni/src/test/java/libcore/java/util/zip/OldZipInputStreamTest.java
@@ -0,0 +1,176 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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 libcore.java.util.zip;
+
+import java.io.ByteArrayOutputStream;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipException;
+import java.util.zip.ZipInputStream;
+import java.util.zip.ZipOutputStream;
+import junit.framework.TestCase;
+import tests.support.resource.Support_Resources;
+
+public class OldZipInputStreamTest extends TestCase {
+    private ZipInputStream zis;
+    private byte[] dataBytes = "Some data in my file".getBytes();
+
+    @Override
+    protected void setUp() throws IOException {
+        InputStream is = Support_Resources.getStream("hyts_ZipFile.zip");
+        if (is == null) {
+            System.out.println("file hyts_ZipFile.zip can not be found");
+        }
+        zis = new ZipInputStream(is);
+
+        ByteArrayOutputStream bos = new ByteArrayOutputStream();
+        ZipOutputStream zos = new ZipOutputStream(bos);
+        ZipEntry entry = new ZipEntry("myFile");
+        zos.putNextEntry(entry);
+        zos.write(dataBytes);
+        zos.closeEntry();
+        zos.close();
+    }
+
+    @Override
+    protected void tearDown() throws IOException {
+        if (zis != null) {
+            zis.close();
+        }
+    }
+
+    public void test_skipJ() throws Exception {
+        File resources = Support_Resources.createTempFolder();
+        Support_Resources.copyFile(resources, null, "Broken_manifest.jar");
+        FileInputStream fis = new FileInputStream(new File(resources,
+                "Broken_manifest.jar"));
+
+        ZipInputStream zis1 = new ZipInputStream(fis);
+
+        zis1.getNextEntry();
+        zis1.getNextEntry();
+
+        try {
+            zis1.skip(10);
+            fail("ZipException expected");
+        } catch (ZipException ee) {
+            // expected
+        }
+
+        try {
+            zis1.close();  // Android throws exception here, already!
+            zis1.skip(10);  // But RI here, only!
+            fail("IOException expected");
+        } catch (IOException ee) {
+            // expected
+        }
+    }
+
+    public void test_read$BII() throws Exception {
+        byte[] rbuf;
+
+        File resources = Support_Resources.createTempFolder();
+        Support_Resources.copyFile(resources, null, "Broken_manifest.jar");
+        FileInputStream fis = new FileInputStream(new File(resources,
+                "Broken_manifest.jar"));
+
+        ZipInputStream zis1 = new ZipInputStream(fis);
+
+        zis1.getNextEntry();
+        zis1.getNextEntry();
+
+        rbuf = new byte[100];
+
+        try {
+            zis1.read(rbuf, 10, 90);
+            fail("ZipException expected");
+        } catch (ZipException ee) {
+            // expected
+        }
+
+        try {
+            zis1.close();  // Android throws exception here, already!
+            zis1.read(rbuf, 10, 90);  // But RI here, only!
+            fail("IOException expected");
+        } catch (IOException ee) {
+            // expected
+        }
+    }
+
+    public void test_closeEntry() throws Exception {
+        zis.getNextEntry();
+        zis.closeEntry();
+        zis.getNextEntry();
+        zis.close();
+        try {
+            zis.closeEntry();
+            fail("IOException expected");
+        } catch (IOException ee) {
+            // expected
+        }
+        File resources = Support_Resources.createTempFolder();
+        Support_Resources.copyFile(resources, null, "Broken_manifest.jar");
+        FileInputStream fis = new FileInputStream(new File(resources,
+                "Broken_manifest.jar"));
+
+        ZipInputStream zis1 = new ZipInputStream(fis);
+
+        try {
+            for (int i = 0; i < 6; i++) {
+                zis1.getNextEntry();
+                zis1.closeEntry();
+            }
+            fail("ZipException expected");
+        } catch (ZipException ee) {
+            // expected
+        }
+    }
+
+    class Mock_ZipInputStream extends ZipInputStream {
+        boolean createFlag = false;
+
+        public Mock_ZipInputStream(InputStream arg0) {
+            super(arg0);
+        }
+
+        boolean getCreateFlag() {
+            return createFlag;
+        }
+
+        protected ZipEntry createZipEntry(String name) {
+            createFlag = true;
+            return super.createZipEntry(name);
+        }
+    }
+
+    public void test_createZipEntryLjava_lang_String() throws Exception {
+
+        File resources = Support_Resources.createTempFolder();
+        Support_Resources.copyFile(resources, null, "Broken_manifest.jar");
+        File fl = new File(resources, "Broken_manifest.jar");
+        FileInputStream fis = new FileInputStream(fl);
+
+        Mock_ZipInputStream zis1 = new Mock_ZipInputStream(fis);
+        assertFalse(zis1.getCreateFlag());
+        zis1.getNextEntry();
+        assertTrue(zis1.getCreateFlag());
+    }
+}
diff --git a/luni/src/test/java/libcore/java/util/zip/ZipFileTest.java b/luni/src/test/java/libcore/java/util/zip/ZipFileTest.java
index 1e01064..89b430f 100644
--- a/luni/src/test/java/libcore/java/util/zip/ZipFileTest.java
+++ b/luni/src/test/java/libcore/java/util/zip/ZipFileTest.java
@@ -64,7 +64,7 @@
      * Compresses a single random file into a .zip archive.
      */
     private File createZipFile(int uncompressedSize) throws IOException {
-        File result = File.createTempFile("ZipFileTest", "zip");
+        File result = File.createTempFile("OldZipFileTest", "zip");
         result.deleteOnExit();
 
         ZipOutputStream out = new ZipOutputStream(new FileOutputStream(result));
diff --git a/luni/src/test/java/libcore/javax/crypto/CipherInputStreamTest.java b/luni/src/test/java/libcore/javax/crypto/CipherInputStreamTest.java
new file mode 100644
index 0000000..40fd8fd
--- /dev/null
+++ b/luni/src/test/java/libcore/javax/crypto/CipherInputStreamTest.java
@@ -0,0 +1,74 @@
+/*
+ * 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.
+ */
+
+package libcore.javax.crypto;
+
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.util.Arrays;
+import javax.crypto.Cipher;
+import javax.crypto.CipherInputStream;
+import javax.crypto.SecretKey;
+import javax.crypto.spec.SecretKeySpec;
+import junit.framework.TestCase;
+
+public final class CipherInputStreamTest extends TestCase {
+
+    private final byte[] keyBytes = { 127, -2, -95, -39, 35, 118, 121, -92 };
+    private final String plainText = "abcde";
+    private final byte[] cipherText = { 121, -124, -106, 43, -55, -67, -105, -75 };
+    private SecretKey key;
+
+    @Override protected void setUp() throws Exception {
+        key = new SecretKeySpec(keyBytes, "DES");
+    }
+
+    public void testEncrypt() throws Exception {
+        Cipher cipher = Cipher.getInstance("DES");
+        cipher.init(Cipher.ENCRYPT_MODE, key);
+        InputStream in = new CipherInputStream(
+                new ByteArrayInputStream(plainText.getBytes("UTF-8")), cipher);
+        byte[] bytes = readAll(in);
+        assertEquals(Arrays.toString(cipherText), Arrays.toString(bytes));
+    }
+
+    public void testDecrypt() throws Exception {
+        Cipher cipher = Cipher.getInstance("DES");
+        cipher.init(Cipher.DECRYPT_MODE, key);
+        InputStream in = new CipherInputStream(new ByteArrayInputStream(cipherText), cipher);
+        byte[] bytes = readAll(in);
+        assertEquals(plainText, new String(bytes, "UTF-8"));
+    }
+
+    public void testSkip() throws Exception {
+        Cipher cipher = Cipher.getInstance("DES");
+        cipher.init(Cipher.DECRYPT_MODE, key);
+        InputStream in = new CipherInputStream(new ByteArrayInputStream(cipherText), cipher);
+        assertTrue(in.skip(5) > 0);
+    }
+
+    private byte[] readAll(InputStream in) throws IOException {
+        ByteArrayOutputStream out = new ByteArrayOutputStream();
+        int count;
+        byte[] buffer = new byte[1024];
+        while ((count = in.read(buffer)) != -1) {
+            out.write(buffer, 0, count);
+        }
+        return out.toByteArray();
+    }
+}
diff --git a/luni/src/test/java/libcore/javax/net/ssl/SSLContextTest.java b/luni/src/test/java/libcore/javax/net/ssl/SSLContextTest.java
index 5c26a00..976e428 100644
--- a/luni/src/test/java/libcore/javax/net/ssl/SSLContextTest.java
+++ b/luni/src/test/java/libcore/javax/net/ssl/SSLContextTest.java
@@ -305,5 +305,6 @@
         assertNotNull(testContext.serverSocket);
         assertNotNull(testContext.host);
         assertTrue(testContext.port != 0);
+        testContext.close();
     }
 }
diff --git a/luni/src/test/java/libcore/javax/net/ssl/SSLEngineTest.java b/luni/src/test/java/libcore/javax/net/ssl/SSLEngineTest.java
index 94558db..24471a1 100644
--- a/luni/src/test/java/libcore/javax/net/ssl/SSLEngineTest.java
+++ b/luni/src/test/java/libcore/javax/net/ssl/SSLEngineTest.java
@@ -64,6 +64,7 @@
         String[] cipherSuites = e.getSupportedCipherSuites();
         StandardNames.assertSupportedCipherSuites(StandardNames.CIPHER_SUITES, cipherSuites);
         assertNotSame(cipherSuites, e.getSupportedCipherSuites());
+        c.close();
     }
 
     @KnownFailure("No *_WITH_NULL_* ciphers work because of 'Invalid transformation: null'")
@@ -96,6 +97,7 @@
                 }
             }));
         }
+        c.close();
     }
 
     public void test_SSLEngine_getEnabledCipherSuites() throws Exception {
@@ -104,6 +106,7 @@
         String[] cipherSuites = e.getEnabledCipherSuites();
         StandardNames.assertValidCipherSuites(StandardNames.CIPHER_SUITES, cipherSuites);
         assertNotSame(cipherSuites, e.getEnabledCipherSuites());
+        c.close();
     }
 
     public void test_SSLEngine_setEnabledCipherSuites() throws Exception {
@@ -129,6 +132,7 @@
         e.setEnabledCipherSuites(new String[0]);
         e.setEnabledCipherSuites(e.getEnabledCipherSuites());
         e.setEnabledCipherSuites(e.getSupportedCipherSuites());
+        c.close();
     }
 
     public void test_SSLEngine_getSupportedProtocols() throws Exception {
@@ -137,6 +141,7 @@
         String[] protocols = e.getSupportedProtocols();
         StandardNames.assertSupportedProtocols(StandardNames.SSL_SOCKET_PROTOCOLS, protocols);
         assertNotSame(protocols, e.getSupportedProtocols());
+        c.close();
     }
 
     public void test_SSLEngine_getEnabledProtocols() throws Exception {
@@ -145,6 +150,7 @@
         String[] protocols = e.getEnabledProtocols();
         StandardNames.assertValidProtocols(StandardNames.SSL_SOCKET_PROTOCOLS, protocols);
         assertNotSame(protocols, e.getEnabledProtocols());
+        c.close();
     }
 
     public void test_SSLEngine_setEnabledProtocols() throws Exception {
@@ -169,6 +175,7 @@
         e.setEnabledProtocols(new String[0]);
         e.setEnabledProtocols(e.getEnabledProtocols());
         e.setEnabledProtocols(e.getSupportedProtocols());
+        c.close();
     }
 
     public void test_SSLEngine_getSession() throws Exception {
@@ -177,6 +184,7 @@
         SSLSession session = e.getSession();
         assertNotNull(session);
         assertFalse(session.isValid());
+        c.close();
     }
 
     public void test_SSLEngine_beginHandshake() throws Exception {
@@ -189,6 +197,8 @@
         }
 
         assertConnected(TestSSLEnginePair.create(null));
+
+        c.close();
     }
 
     @KnownFailure("NO SERVER CERTIFICATE FOUND")
@@ -202,18 +212,21 @@
             fail();
         } catch (SSLHandshakeException expected) {
         }
+        c.close();
     }
 
     public void test_SSLEngine_beginHandshake_noClientCertificate() throws Exception {
         TestSSLContext c = TestSSLContext.create();
         SSLEngine[] engines = TestSSLEnginePair.connect(c, null);
         assertConnected(engines[0], engines[1]);
+        c.close();
     }
 
     public void test_SSLEngine_getUseClientMode() throws Exception {
         TestSSLContext c = TestSSLContext.create();
         assertFalse(c.clientContext.createSSLEngine().getUseClientMode());
         assertFalse(c.clientContext.createSSLEngine(null, -1).getUseClientMode());
+        c.close();
     }
 
     @KnownFailure("SSLHandshakeException instead assertNotConnected")
@@ -305,12 +318,15 @@
         TestKeyStore.assertChainLength(p.client.getSession().getLocalCertificates());
         TestSSLContext.assertClientCertificateChain(clientAuthContext.clientTrustManager,
                                                     p.client.getSession().getLocalCertificates());
+        clientAuthContext.close();
+        c.close();
     }
 
     public void test_SSLEngine_getEnableSessionCreation() throws Exception {
         TestSSLContext c = TestSSLContext.create();
         SSLEngine e = c.clientContext.createSSLEngine();
         assertTrue(e.getEnableSessionCreation());
+        c.close();
     }
 
     @KnownFailure("SSLException instead assertNotConnected")
@@ -357,6 +373,8 @@
 
         assertEquals(p.getWantClientAuth(), e.getWantClientAuth());
         assertEquals(p.getNeedClientAuth(), e.getNeedClientAuth());
+
+        c.close();
     }
 
     public void test_SSLEngine_setSSLParameters() throws Exception {
@@ -409,6 +427,7 @@
             assertFalse(e.getNeedClientAuth());
             assertFalse(e.getWantClientAuth());
         }
+        c.close();
     }
 
     public void test_TestSSLEnginePair_create() throws Exception {
diff --git a/luni/src/test/java/libcore/javax/net/ssl/SSLSessionContextTest.java b/luni/src/test/java/libcore/javax/net/ssl/SSLSessionContextTest.java
index 3263c57..d75dc23 100644
--- a/luni/src/test/java/libcore/javax/net/ssl/SSLSessionContextTest.java
+++ b/luni/src/test/java/libcore/javax/net/ssl/SSLSessionContextTest.java
@@ -16,12 +16,15 @@
 
 package libcore.javax.net.ssl;
 
+import java.util.ArrayList;
 import java.util.Arrays;
 import java.util.Collections;
 import java.util.Enumeration;
 import java.util.Iterator;
 import java.util.LinkedList;
+import java.util.List;
 import javax.net.ssl.SSLSessionContext;
+import javax.net.ssl.SSLSocket;
 import junit.framework.TestCase;
 
 public class SSLSessionContextTest extends TestCase {
@@ -56,6 +59,7 @@
     public void test_SSLSessionContext_getIds() {
         TestSSLContext c = TestSSLContext.create();
         assertSSLSessionContextSize(0, c);
+        c.close();
 
         TestSSLSocketPair s = TestSSLSocketPair.create();
         assertSSLSessionContextSize(1, s.c);
@@ -70,6 +74,7 @@
             assertEquals(32, serverId.length);
             assertTrue(Arrays.equals(clientId, serverId));
         }
+        s.close();
     }
 
     public void test_SSLSessionContext_getSession() {
@@ -88,6 +93,7 @@
         }
         assertNull(c.serverContext.getServerSessionContext().getSession(new byte[0]));
         assertNull(c.serverContext.getServerSessionContext().getSession(new byte[1]));
+        c.close();
 
         TestSSLSocketPair s = TestSSLSocketPair.create();
         SSLSessionContext client = s.c.clientContext.getClientSessionContext();
@@ -102,6 +108,7 @@
             assertNotNull(server.getSession(serverId));
             assertTrue(Arrays.equals(serverId, server.getSession(serverId).getId()));
         }
+        s.close();
     }
 
     public void test_SSLSessionContext_getSessionCacheSize() {
@@ -110,12 +117,14 @@
                      c.clientContext.getClientSessionContext().getSessionCacheSize());
         assertEquals(TestSSLContext.EXPECTED_DEFAULT_SERVER_SSL_SESSION_CACHE_SIZE,
                      c.serverContext.getServerSessionContext().getSessionCacheSize());
+        c.close();
 
         TestSSLSocketPair s = TestSSLSocketPair.create();
         assertEquals(TestSSLContext.EXPECTED_DEFAULT_CLIENT_SSL_SESSION_CACHE_SIZE,
                      s.c.clientContext.getClientSessionContext().getSessionCacheSize());
         assertEquals(TestSSLContext.EXPECTED_DEFAULT_SERVER_SSL_SESSION_CACHE_SIZE,
                      s.c.serverContext.getServerSessionContext().getSessionCacheSize());
+        s.close();
     }
 
     public void test_SSLSessionContext_setSessionCacheSize_noConnect() {
@@ -126,6 +135,7 @@
         assertNoConnectSetSessionCacheSizeBehavior(
                 TestSSLContext.EXPECTED_DEFAULT_SERVER_SSL_SESSION_CACHE_SIZE,
                 c.serverContext.getServerSessionContext());
+        c.close();
     }
 
     private static void assertNoConnectSetSessionCacheSizeBehavior(int expectedDefault,
@@ -149,9 +159,10 @@
         assertEquals(TestSSLContext.EXPECTED_DEFAULT_SERVER_SSL_SESSION_CACHE_SIZE,
                      server.getSessionCacheSize());
         assertSSLSessionContextSize(1, s.c);
+        s.close();
     }
 
-    public void test_SSLSessionContext_setSessionCacheSize_dynamic() {
+    public void test_SSLSessionContext_setSessionCacheSize_dynamic() throws Exception {
         TestSSLContext c = TestSSLContext.create();
         SSLSessionContext client = c.clientContext.getClientSessionContext();
         SSLSessionContext server = c.serverContext.getServerSessionContext();
@@ -201,11 +212,12 @@
         String cipherSuite2 = uniqueCipherSuites.get(1);
         String cipherSuite3 = uniqueCipherSuites.get(2);
 
-        TestSSLSocketPair.connect(c, new String[] { cipherSuite1 }, null);
+        List<SSLSocket[]> toClose = new ArrayList<SSLSocket[]>();
+        toClose.add(TestSSLSocketPair.connect(c, new String[] { cipherSuite1 }, null));
         assertSSLSessionContextSize(1, c);
-        TestSSLSocketPair.connect(c, new String[] { cipherSuite2 }, null);
+        toClose.add(TestSSLSocketPair.connect(c, new String[] { cipherSuite2 }, null));
         assertSSLSessionContextSize(2, c);
-        TestSSLSocketPair.connect(c, new String[] { cipherSuite3 }, null);
+        toClose.add(TestSSLSocketPair.connect(c, new String[] { cipherSuite3 }, null));
         assertSSLSessionContextSize(3, c);
 
         client.setSessionCacheSize(1);
@@ -213,15 +225,22 @@
         assertEquals(1, client.getSessionCacheSize());
         assertEquals(1, server.getSessionCacheSize());
         assertSSLSessionContextSize(1, c);
-        TestSSLSocketPair.connect(c, new String[] { cipherSuite1 }, null);
+        toClose.add(TestSSLSocketPair.connect(c, new String[] { cipherSuite1 }, null));
         assertSSLSessionContextSize(1, c);
 
         client.setSessionCacheSize(2);
         server.setSessionCacheSize(2);
-        TestSSLSocketPair.connect(c, new String[] { cipherSuite2 }, null);
+        toClose.add(TestSSLSocketPair.connect(c, new String[] { cipherSuite2 }, null));
         assertSSLSessionContextSize(2, c);
-        TestSSLSocketPair.connect(c, new String[] { cipherSuite3 }, null);
+        toClose.add(TestSSLSocketPair.connect(c, new String[] { cipherSuite3 }, null));
         assertSSLSessionContextSize(2, c);
+
+        for (SSLSocket[] pair : toClose) {
+            for (SSLSocket s : pair) {
+                s.close();
+            }
+        }
+        c.close();
     }
 
     public void test_SSLSessionContext_getSessionTimeout() {
@@ -230,12 +249,14 @@
                      c.clientContext.getClientSessionContext().getSessionTimeout());
         assertEquals(TestSSLContext.EXPECTED_DEFAULT_SSL_SESSION_CACHE_TIMEOUT,
                      c.serverContext.getServerSessionContext().getSessionTimeout());
+        c.close();
 
         TestSSLSocketPair s = TestSSLSocketPair.create();
         assertEquals(TestSSLContext.EXPECTED_DEFAULT_SSL_SESSION_CACHE_TIMEOUT,
                      s.c.clientContext.getClientSessionContext().getSessionTimeout());
         assertEquals(TestSSLContext.EXPECTED_DEFAULT_SSL_SESSION_CACHE_TIMEOUT,
                      s.c.serverContext.getServerSessionContext().getSessionTimeout());
+        s.close();
     }
 
     public void test_SSLSessionContext_setSessionTimeout() throws Exception {
@@ -259,6 +280,7 @@
             fail();
         } catch (IllegalArgumentException expected) {
         }
+        c.close();
 
         TestSSLSocketPair s = TestSSLSocketPair.create();
         assertSSLSessionContextSize(1, s.c);
@@ -266,5 +288,6 @@
         s.c.clientContext.getClientSessionContext().setSessionTimeout(1);
         s.c.serverContext.getServerSessionContext().setSessionTimeout(1);
         assertSSLSessionContextSize(0, s.c);
+        s.close();
     }
 }
diff --git a/luni/src/test/java/libcore/javax/net/ssl/SSLSessionTest.java b/luni/src/test/java/libcore/javax/net/ssl/SSLSessionTest.java
index d54520c..217dfe9 100644
--- a/luni/src/test/java/libcore/javax/net/ssl/SSLSessionTest.java
+++ b/luni/src/test/java/libcore/javax/net/ssl/SSLSessionTest.java
@@ -30,6 +30,7 @@
         assertFalse(s.invalid.isValid());
         assertTrue(s.server.isValid());
         assertTrue(s.client.isValid());
+        s.close();
     }
 
     public void test_SSLSession_getApplicationBufferSize() {
@@ -37,6 +38,7 @@
         assertTrue(s.invalid.getApplicationBufferSize() > 0);
         assertTrue(s.server.getApplicationBufferSize() > 0);
         assertTrue(s.client.getApplicationBufferSize() > 0);
+        s.close();
     }
 
     public void test_SSLSession_getCipherSuite() {
@@ -48,6 +50,7 @@
         assertEquals(s.server.getCipherSuite(),
                      s.client.getCipherSuite());
         assertTrue(StandardNames.CIPHER_SUITES.contains(s.server.getCipherSuite()));
+        s.close();
     }
 
     public void test_SSLSession_getCreationTime() {
@@ -56,6 +59,7 @@
         assertTrue(s.server.getCreationTime() > 0);
         assertTrue(s.client.getCreationTime() > 0);
         assertTrue(Math.abs(s.server.getCreationTime() - s.client.getCreationTime()) < 1 * 1000);
+        s.close();
     }
 
     public void test_SSLSession_getId() {
@@ -71,6 +75,7 @@
             assertTrue(Arrays.equals(s.server.getId(), s.client.getId()));
         }
         assertEquals(32, s.client.getId().length);
+        s.close();
     }
 
     public void test_SSLSession_getLastAccessedTime() {
@@ -84,6 +89,7 @@
                    s.server.getCreationTime());
         assertTrue(s.client.getLastAccessedTime() >=
                    s.client.getCreationTime());
+        s.close();
     }
 
     public void test_SSLSession_getLocalCertificates() throws Exception {
@@ -96,6 +102,7 @@
                                                     s.server.getLocalCertificates());
         TestSSLContext.assertCertificateInKeyStore(s.server.getLocalCertificates()[0],
                                                    s.s.c.serverKeyStore);
+        s.close();
     }
 
     public void test_SSLSession_getLocalPrincipal() throws Exception {
@@ -106,6 +113,7 @@
         assertNotNull(s.server.getLocalPrincipal().getName());
         TestSSLContext.assertCertificateInKeyStore(s.server.getLocalPrincipal(),
                                                    s.s.c.serverKeyStore);
+        s.close();
     }
 
     public void test_SSLSession_getPacketBufferSize() {
@@ -113,6 +121,7 @@
         assertTrue(s.invalid.getPacketBufferSize() > 0);
         assertTrue(s.server.getPacketBufferSize() > 0);
         assertTrue(s.client.getPacketBufferSize() > 0);
+        s.close();
     }
 
     public void test_SSLSession_getPeerCertificateChain() throws Exception {
@@ -129,6 +138,7 @@
             fail();
         } catch (SSLPeerUnverifiedException expected) {
         }
+        s.close();
     }
 
     public void test_SSLSession_getPeerCertificates() throws Exception {
@@ -149,6 +159,7 @@
             fail();
         } catch (SSLPeerUnverifiedException expected) {
         }
+        s.close();
     }
 
     public void test_SSLSession_getPeerHost() {
@@ -156,6 +167,7 @@
         assertNull(s.invalid.getPeerHost());
         assertNotNull(s.server.getPeerHost());
         assertNotNull(s.client.getPeerHost());
+        s.close();
     }
 
     public void test_SSLSession_getPeerPort() {
@@ -163,6 +175,7 @@
         assertEquals(-1, s.invalid.getPeerPort());
         assertTrue(s.server.getPeerPort() > 0);
         assertEquals(s.s.c.port, s.client.getPeerPort());
+        s.close();
     }
 
     public void test_SSLSession_getPeerPrincipal() throws Exception {
@@ -181,6 +194,7 @@
         assertNotNull(s.client.getPeerPrincipal().getName());
         TestSSLContext.assertCertificateInKeyStore(s.client.getPeerPrincipal(),
                                                    s.s.c.serverKeyStore);
+        s.close();
     }
 
     public void test_SSLSession_getProtocol() {
@@ -192,6 +206,7 @@
         assertEquals(s.server.getProtocol(),
                      s.client.getProtocol());
         assertTrue(StandardNames.SSL_SOCKET_PROTOCOLS.contains(s.server.getProtocol()));
+        s.close();
     }
 
     public void test_SSLSession_getSessionContext() {
@@ -205,6 +220,7 @@
                      s.client.getSessionContext());
         assertNotSame(s.server.getSessionContext(),
                       s.client.getSessionContext());
+        s.close();
     }
 
     public void test_SSLSession_getValue() {
@@ -214,16 +230,19 @@
         } catch (IllegalArgumentException expected) {
         }
         assertNull(s.invalid.getValue("BOGUS"));
+        s.close();
     }
 
     public void test_SSLSession_getValueNames() {
         TestSSLSessions s = TestSSLSessions.create();
         assertNotNull(s.invalid.getValueNames());
         assertEquals(0, s.invalid.getValueNames().length);
+        s.close();
     }
 
     public void test_SSLSession_invalidate() {
         TestSSLSessions s = TestSSLSessions.create();
+
         assertFalse(s.invalid.isValid());
         s.invalid.invalidate();
         assertFalse(s.invalid.isValid());
@@ -238,6 +257,8 @@
         s.client.invalidate();
         assertFalse(s.client.isValid());
         assertNull(s.client.getSessionContext());
+
+        s.close();
     }
 
     public void test_SSLSession_isValid() {
@@ -245,6 +266,7 @@
         assertFalse(s.invalid.isValid());
         assertTrue(s.server.isValid());
         assertTrue(s.client.isValid());
+        s.close();
     }
 
     public void test_SSLSession_putValue() {
@@ -257,6 +279,7 @@
         assertSame(value, s.invalid.getValue(key));
         assertEquals(1, s.invalid.getValueNames().length);
         assertEquals(key, s.invalid.getValueNames()[0]);
+        s.close();
     }
 
     public void test_SSLSession_removeValue() {
@@ -269,5 +292,6 @@
         s.invalid.removeValue(key);
         assertNull(s.invalid.getValue(key));
         assertEquals(0, s.invalid.getValueNames().length);
+        s.close();
     }
 }
diff --git a/luni/src/test/java/libcore/javax/net/ssl/SSLSocketTest.java b/luni/src/test/java/libcore/javax/net/ssl/SSLSocketTest.java
index 5e9567a..821b6e8 100644
--- a/luni/src/test/java/libcore/javax/net/ssl/SSLSocketTest.java
+++ b/luni/src/test/java/libcore/javax/net/ssl/SSLSocketTest.java
@@ -118,9 +118,10 @@
             assertEquals(clientToServer.length, readFromClient);
             assertEquals(clientToServerString, new String(serverFromClient, 0, readFromClient));
             assertEquals(serverToClientString, new String(clientFromServer, 0, readFromServer));
-            server.close();
             client.close();
+            server.close();
         }
+        c.close();
     }
 
     public void test_SSLSocket_getEnabledCipherSuites() throws Exception {
@@ -246,6 +247,9 @@
                                                     peerCertificates);
         TestSSLContext.assertCertificateInKeyStore(peerCertificates[0], c.serverKeyStore);
         thread.join();
+        client.close();
+        server.close();
+        c.close();
     }
 
     public void test_SSLSocket_startHandshake_noKeyStore() throws Exception {
@@ -254,10 +258,12 @@
         SSLSocket client = (SSLSocket) c.clientContext.getSocketFactory().createSocket(c.host,
                                                                                        c.port);
         try {
-            SSLSocket server = (SSLSocket) c.serverSocket.accept();
+            c.serverSocket.accept();
             fail();
         } catch (SSLException expected) {
         }
+        client.close();
+        c.close();
     }
 
     public void test_SSLSocket_startHandshake_noClientCertificate() throws Exception {
@@ -281,6 +287,9 @@
         thread.start();
         client.startHandshake();
         thread.join();
+        client.close();
+        server.close();
+        c.close();
     }
 
     public void test_SSLSocket_HandshakeCompletedListener() throws Exception {
@@ -384,6 +393,9 @@
                 handshakeCompletedListenerCalled.wait();
             }
         }
+        client.close();
+        server.close();
+        c.close();
     }
 
     public void test_SSLSocket_HandshakeCompletedListener_RuntimeException() throws Exception {
@@ -410,6 +422,9 @@
         });
         client.startHandshake();
         thread.join();
+        client.close();
+        server.close();
+        c.close();
     }
 
     public void test_SSLSocket_getUseClientMode() throws Exception {
@@ -419,6 +434,9 @@
         SSLSocket server = (SSLSocket) c.serverSocket.accept();
         assertTrue(client.getUseClientMode());
         assertFalse(server.getUseClientMode());
+        client.close();
+        server.close();
+        c.close();
     }
 
     public void test_SSLSocket_setUseClientMode() throws Exception {
@@ -499,6 +517,9 @@
         if (socketTimeoutException[0] != null) {
             throw socketTimeoutException[0];
         }
+        client.close();
+        server.close();
+        c.close();
     }
 
     public void test_SSLSocket_clientAuth() throws Exception {
@@ -544,6 +565,9 @@
         TestSSLContext.assertClientCertificateChain(c.clientTrustManager,
                                                     client.getSession().getLocalCertificates());
         thread.join();
+        client.close();
+        server.close();
+        c.close();
     }
 
     public void test_SSLSocket_getEnableSessionCreation() throws Exception {
@@ -553,6 +577,9 @@
         SSLSocket server = (SSLSocket) c.serverSocket.accept();
         assertTrue(client.getEnableSessionCreation());
         assertTrue(server.getEnableSessionCreation());
+        client.close();
+        server.close();
+        c.close();
     }
 
     public void test_SSLSocket_setEnableSessionCreation_server() throws Exception {
@@ -583,6 +610,9 @@
         } catch (SSLException expected) {
         }
         thread.join();
+        client.close();
+        server.close();
+        c.close();
     }
 
     public void test_SSLSocket_setEnableSessionCreation_client() throws Exception {
@@ -613,6 +643,9 @@
         } catch (SSLException expected) {
         }
         thread.join();
+        client.close();
+        server.close();
+        c.close();
     }
 
     public void test_SSLSocket_getSSLParameters() throws Exception {
@@ -770,6 +803,8 @@
             fail();
         } catch (IllegalArgumentException expected) {
         }
+
+        pair.close();
     }
 
     public void test_SSLSocket_setSoTimeout_basic() throws Exception {
@@ -885,6 +920,7 @@
         assertNotNull(test.client.getSession());
         assertTrue(test.server.getSession().isValid());
         assertTrue(test.client.getSession().isValid());
+        test.close();
     }
 
     /**
@@ -901,6 +937,14 @@
             } else {
                 System.out.print("X");
             }
+
+            /*
+              We don't close on purpose in this stress test to add
+              races in file descriptors reuse when the garbage
+              collector runs concurrently and finalizes sockets
+            */
+            // test.close();
+
         }
     }
 
diff --git a/luni/src/test/java/org/apache/harmony/archive/tests/java/util/jar/AllTests.java b/luni/src/test/java/org/apache/harmony/archive/tests/java/util/jar/AllTests.java
deleted file mode 100644
index cd3746a..0000000
--- a/luni/src/test/java/org/apache/harmony/archive/tests/java/util/jar/AllTests.java
+++ /dev/null
@@ -1,42 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements.  See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You 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 org.apache.harmony.archive.tests.java.util.jar;
-
-import junit.framework.Test;
-import junit.framework.TestSuite;
-
-/**
- * Test suite for java.util.jar package.
- */
-public class AllTests {
-    public static Test suite() {
-        TestSuite suite = new TestSuite(
-                "Suite org.apache.harmony.archive.tests.java.util.jar");
-        suite.addTestSuite(AttributesNameTest.class);
-        suite.addTestSuite(AttributesTest.class);
-        suite.addTestSuite(JarEntryTest.class);
-        suite.addTestSuite(JarExceptionTest.class);
-        suite.addTestSuite(JarExecTest.class);
-        suite.addTestSuite(JarFileTest.class);
-        suite.addTestSuite(JarInputStreamTest.class);
-        suite.addTestSuite(JarOutputStreamTest.class);
-        suite.addTestSuite(ManifestTest.class);
-        suite.addTestSuite(ZipExecTest.class);
-        return suite;
-    }
-}
diff --git a/luni/src/test/java/org/apache/harmony/archive/tests/java/util/jar/AttributesTest.java b/luni/src/test/java/org/apache/harmony/archive/tests/java/util/jar/AttributesTest.java
deleted file mode 100644
index a4ac213..0000000
--- a/luni/src/test/java/org/apache/harmony/archive/tests/java/util/jar/AttributesTest.java
+++ /dev/null
@@ -1,391 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements.  See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You 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 org.apache.harmony.archive.tests.java.util.jar;
-
-import java.util.Collection;
-import java.util.Collections;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.Map;
-import java.util.Set;
-import java.util.jar.Attributes;
-import junit.framework.TestCase;
-
-public class AttributesTest extends TestCase {
-    private Attributes a;
-
-    @Override
-    protected void setUp() {
-        a = new Attributes();
-        a.putValue("1", "one");
-        a.putValue("2", "two");
-        a.putValue("3", "three");
-        a.putValue("4", "four");
-    }
-
-    /**
-     * @tests java.util.jar.Attributes#Attributes(java.util.jar.Attributes)
-     */
-    public void test_ConstructorLjava_util_jar_Attributes() {
-        Attributes a2 = new Attributes(a);
-        assertEquals(a, a2);
-        a.putValue("1", "one(1)");
-        assertTrue("equal", !a.equals(a2));
-    }
-
-    /**
-     * @tests java.util.jar.Attributes#clear()
-     */
-    public void test_clear() {
-        a.clear();
-        assertNull("a) All entries should be null after clear", a.get("1"));
-        assertNull("b) All entries should be null after clear", a.get("2"));
-        assertNull("c) All entries should be null after clear", a.get("3"));
-        assertNull("d) All entries should be null after clear", a.get("4"));
-        assertTrue("Should not contain any keys", !a.containsKey("1"));
-    }
-
-    /**
-     * @tests java.util.jar.Attributes#containsKey(java.lang.Object)
-     */
-    public void test_containsKeyLjava_lang_Object() {
-        assertTrue("a) Should have returned false", !a.containsKey(new Integer(
-                1)));
-        assertTrue("b) Should have returned false", !a.containsKey("0"));
-        assertTrue("Should have returned true", a
-                .containsKey(new Attributes.Name("1")));
-    }
-
-    /**
-     * @tests java.util.jar.Attributes#containsValue(java.lang.Object)
-     */
-    public void test_containsValueLjava_lang_Object() {
-        assertTrue("Should have returned false", !a.containsValue("One"));
-        assertTrue("Should have returned true", a.containsValue("one"));
-    }
-
-    /**
-     * @tests java.util.jar.Attributes#entrySet()
-     */
-    public void test_entrySet() {
-        Set<Map.Entry<Object, Object>> entrySet = a.entrySet();
-        Set<Object> keySet = new HashSet<Object>();
-        Set<Object> valueSet = new HashSet<Object>();
-        Iterator<?> i;
-        assertEquals(4, entrySet.size());
-        i = entrySet.iterator();
-        while (i.hasNext()) {
-            java.util.Map.Entry<?, ?> e;
-            e = (Map.Entry<?, ?>) i.next();
-            keySet.add(e.getKey());
-            valueSet.add(e.getValue());
-        }
-        assertTrue("a) Should contain entry", valueSet.contains("one"));
-        assertTrue("b) Should contain entry", valueSet.contains("two"));
-        assertTrue("c) Should contain entry", valueSet.contains("three"));
-        assertTrue("d) Should contain entry", valueSet.contains("four"));
-        assertTrue("a) Should contain key", keySet
-                .contains(new Attributes.Name("1")));
-        assertTrue("b) Should contain key", keySet
-                .contains(new Attributes.Name("2")));
-        assertTrue("c) Should contain key", keySet
-                .contains(new Attributes.Name("3")));
-        assertTrue("d) Should contain key", keySet
-                .contains(new Attributes.Name("4")));
-    }
-
-    /**
-     * @tests java.util.jar.Attributes#get(java.lang.Object)
-     */
-    public void test_getLjava_lang_Object() {
-        assertEquals("a) Incorrect value returned", "one", a.getValue("1"));
-        assertNull("b) Incorrect value returned", a.getValue("0"));
-
-        try {
-            a.getValue("IllegalArgumentException expected");
-        } catch (IllegalArgumentException ee) {
-            // expected
-        }
-    }
-
-    /**
-     * @tests java.util.jar.Attributes#isEmpty()
-     */
-    public void test_isEmpty() {
-        assertTrue("Should not be empty", !a.isEmpty());
-        a.clear();
-        assertTrue("a) Should be empty", a.isEmpty());
-        a = new Attributes();
-        assertTrue("b) Should be empty", a.isEmpty());
-    }
-
-    /**
-     * @tests java.util.jar.Attributes#keySet()
-     */
-    public void test_keySet() {
-        Set<?> s = a.keySet();
-        assertEquals(4, s.size());
-        assertTrue("a) Should contain entry", s.contains(new Attributes.Name(
-                "1")));
-        assertTrue("b) Should contain entry", s.contains(new Attributes.Name(
-                "2")));
-        assertTrue("c) Should contain entry", s.contains(new Attributes.Name(
-                "3")));
-        assertTrue("d) Should contain entry", s.contains(new Attributes.Name(
-                "4")));
-    }
-
-    /**
-     * @tests java.util.jar.Attributes#putAll(java.util.Map)
-     */
-    public void test_putAllLjava_util_Map() {
-        Attributes b = new Attributes();
-        b.putValue("3", "san");
-        b.putValue("4", "shi");
-        b.putValue("5", "go");
-        b.putValue("6", "roku");
-        a.putAll(b);
-        assertEquals("Should not have been replaced", "one", a.getValue("1"));
-        assertEquals("Should have been replaced", "san", a.getValue("3"));
-        assertEquals("Should have been added", "go", a.getValue("5"));
-        Attributes atts = new Attributes();
-        assertNull("Assert 0: ", atts.put(Attributes.Name.CLASS_PATH,
-                "tools.jar"));
-        assertNull("Assert 1: ", atts
-                .put(Attributes.Name.MANIFEST_VERSION, "1"));
-        Attributes atts2 = new Attributes();
-        atts2.putAll(atts);
-        assertEquals("Assert 2:", "tools.jar", atts2
-                .get(Attributes.Name.CLASS_PATH));
-        assertEquals("Assert 3: ", "1", atts2
-                .get(Attributes.Name.MANIFEST_VERSION));
-        try {
-            atts.putAll(Collections.EMPTY_MAP);
-            fail("Assert 4: no class cast from attrib parameter");
-        } catch (ClassCastException e) {
-            // Expected
-        }
-    }
-
-    /**
-     * @tests java.util.jar.Attributes#putAll(java.util.Map)
-     */
-    public void test_putAllLjava_util_Map2() {
-        // Regression for HARMONY-464
-        try {
-            new Attributes().putAll((Map) null);
-            fail("ClassCastException expected");
-        } catch (ClassCastException e) {
-        }
-        // verify that special care for null is done in the Attributes.putAll()
-        // method
-        try {
-            new Attributes() {
-                @Override
-                public void putAll(Map<?, ?> attrib) {
-                    map.putAll(attrib);
-                }
-            }.putAll((Map<?, ?>) null);
-            fail("NullPointerException expected");
-        } catch (NullPointerException e) {
-        }
-    }
-
-    /**
-     * @tests java.util.jar.Attributes#remove(java.lang.Object)
-     */
-    public void test_removeLjava_lang_Object() {
-        a.remove(new Attributes.Name("1"));
-        a.remove(new Attributes.Name("3"));
-        assertNull("Should have been removed", a.getValue("1"));
-        assertEquals("Should not have been removed", "four", a.getValue("4"));
-    }
-
-    /**
-     * @tests java.util.jar.Attributes#size()
-     */
-    public void test_size() {
-        assertEquals("Incorrect size returned", 4, a.size());
-        a.clear();
-        assertEquals(0, a.size());
-    }
-
-    /**
-     * @tests java.util.jar.Attributes#values()
-     */
-    public void test_values() {
-        Collection<?> valueCollection = a.values();
-        assertTrue("a) Should contain entry", valueCollection.contains("one"));
-        assertTrue("b) Should contain entry", valueCollection.contains("two"));
-        assertTrue("c) Should contain entry", valueCollection.contains("three"));
-        assertTrue("d) Should contain entry", valueCollection.contains("four"));
-    }
-
-    /**
-     * @tests java.util.jar.Attributes#clone()
-     */
-    public void test_clone() {
-        Attributes a2 = (Attributes) a.clone();
-        assertEquals(a, a2);
-        a.putValue("1", "one(1)");
-        assertTrue("equal", !a.equals(a2));
-    }
-
-    /**
-     * @tests java.util.jar.Attributes#equals(java.lang.Object)
-     */
-    public void test_equalsLjava_lang_Object() {
-        Attributes.Name n1 = new Attributes.Name("name"), n2 = new Attributes.Name(
-                "Name");
-        assertEquals(n1, n2);
-        Attributes a1 = new Attributes();
-        a1.putValue("one", "1");
-        a1.putValue("two", "2");
-        Attributes a2 = new Attributes();
-        a2.putValue("One", "1");
-        a2.putValue("TWO", "2");
-        assertEquals(a1, a2);
-    }
-
-    /**
-     * @tests java.util.jar.Attributes.put(java.lang.Object, java.lang.Object)
-     */
-    public void test_putLjava_lang_ObjectLjava_lang_Object() {
-        Attributes atts = new Attributes();
-        assertNull("Assert 0: ", atts.put(Attributes.Name.CLASS_PATH,
-                "tools.jar"));
-        assertEquals("Assert 1: ", "tools.jar", atts
-                .getValue(Attributes.Name.CLASS_PATH));
-        // Regression for HARMONY-79
-        try {
-            atts.put("not a name", "value");
-            fail("Assert 2: no class cast from key parameter");
-        } catch (ClassCastException e) {
-            // Expected
-        }
-        try {
-            atts.put(Attributes.Name.CLASS_PATH, Boolean.TRUE);
-            fail("Assert 3: no class cast from value parameter");
-        } catch (ClassCastException e) {
-            // Expected
-        }
-    }
-
-    /**
-     * @tests java.util.jar.Attributes.put(java.lang.Object, java.lang.Object)
-     */
-    public void test_putLjava_lang_ObjectLjava_lang_Object_Null() {
-
-        Attributes attribute = new Attributes();
-
-        assertFalse(attribute.containsKey(null));
-        assertFalse(attribute.containsValue(null));
-        attribute.put(null, null);
-        attribute.put(null, null);
-        assertEquals(1, attribute.size());
-        assertTrue(attribute.containsKey(null));
-        assertTrue(attribute.containsValue(null));
-        assertNull(attribute.get(null));
-
-        String value = "It's null";
-        attribute.put(null, value);
-        assertEquals(1, attribute.size());
-        assertEquals(value, attribute.get(null));
-
-        Attributes.Name name = new Attributes.Name("null");
-        attribute.put(name, null);
-        assertEquals(2, attribute.size());
-        assertNull(attribute.get(name));
-    }
-
-    /**
-     * @tests java.util.jar.Attributes.hashCode()
-     */
-    public void test_hashCode_consistent_with_map() {
-        MockAttributes mockAttr = new MockAttributes();
-        mockAttr.putValue("1", "one");
-        assertEquals(mockAttr.getMap().hashCode(), mockAttr.hashCode());
-    }
-
-    private static class MockAttributes extends Attributes {
-        public Map<Object, Object> getMap() {
-            return map;
-        }
-    }
-
-    public void test_Constructor() {
-        Attributes attr = new Attributes();
-        assertTrue(attr.size() >= 0);
-    }
-
-    public void test_ConstructorI() {
-        Attributes attr = new Attributes(10);
-        assertTrue(attr.size() >= 0);
-    }
-
-    public void test_getLjava_lang_Object_true() {
-        assertEquals("a) Incorrect value returned", "one", a
-                .get(new Attributes.Name("1")));
-        assertNull("b) Incorrect value returned", a.get("0"));
-        assertNull("b) Incorrect value returned", a.get("1"));
-    }
-
-    public void test_getValueLjava_util_jar_Attributes_Name() {
-        assertEquals("a) Incorrect value returned", "one", a
-                .getValue(new Attributes.Name("1")));
-        assertNull("b) Incorrect value returned", a
-                .getValue(new Attributes.Name("0")));
-    }
-
-    public void test_hashCode() {
-        Attributes b = (Attributes) a.clone();
-        b.putValue("33", "Thirty three");
-        assertNotSame(a.hashCode(), b.hashCode());
-        b = (Attributes) a.clone();
-        b.clear();
-        assertNotSame(a.hashCode(), b.hashCode());
-    }
-
-    public void test_putValueLjava_lang_StringLjava_lang_String() {
-        Attributes b = new Attributes();
-        b.put(new Attributes.Name("1"), "one");
-        b.putValue("2", "two");
-        b.put(new Attributes.Name("3"), "three");
-        b.putValue("4", "four");
-
-        assertTrue(a.equals(b));
-
-        try {
-            b.putValue(null, "null");
-            fail("NullPointerException expected");
-        } catch (NullPointerException ee) {
-            // expected
-        }
-
-        StringBuffer sb = new StringBuffer();
-        for (int i = 0; i < 0x10000; i++) {
-            sb.append('3');
-        }
-        try {
-            b.putValue(new String(sb), "wrong name");
-            fail("IllegalArgumentException expected");
-        } catch (IllegalArgumentException ee) {
-            // expected
-        }
-    }
-}
diff --git a/luni/src/test/java/org/apache/harmony/archive/tests/java/util/jar/JarEntryTest.java b/luni/src/test/java/org/apache/harmony/archive/tests/java/util/jar/JarEntryTest.java
deleted file mode 100644
index 47d2a6c..0000000
--- a/luni/src/test/java/org/apache/harmony/archive/tests/java/util/jar/JarEntryTest.java
+++ /dev/null
@@ -1,251 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements.  See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You 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 org.apache.harmony.archive.tests.java.util.jar;
-
-import java.io.File;
-import java.io.IOException;
-import java.io.InputStream;
-import java.security.CodeSigner;
-import java.util.Enumeration;
-import java.util.List;
-import java.util.jar.JarEntry;
-import java.util.jar.JarFile;
-import java.util.zip.ZipEntry;
-import junit.framework.TestCase;
-import tests.support.resource.Support_Resources;
-
-
-public class JarEntryTest extends TestCase {
-    private ZipEntry zipEntry;
-
-    private JarEntry jarEntry;
-
-    private JarFile jarFile;
-
-    private final String jarName = "hyts_patch.jar";
-
-    private final String entryName = "foo/bar/A.class";
-
-    private final String entryName2 = "Blah.txt";
-
-    private final String attJarName = "hyts_att.jar";
-
-    private final String attEntryName = "HasAttributes.txt";
-
-    private final String attEntryName2 = "NoAttributes.txt";
-
-    private File resources;
-
-    @Override
-    protected void setUp() throws Exception {
-        resources = Support_Resources.createTempFolder();
-        Support_Resources.copyFile(resources, null, jarName);
-        jarFile = new JarFile(new File(resources, jarName));
-    }
-
-    @Override
-    protected void tearDown() throws Exception {
-        if (jarFile != null) {
-            jarFile.close();
-        }
-    }
-
-    /**
-     * @throws IOException
-     * @tests java.util.jar.JarEntry#JarEntry(java.util.jar.JarEntry)
-     */
-    public void test_ConstructorLjava_util_jar_JarEntry_on_null() throws IOException {
-        JarEntry newJarEntry = new JarEntry(jarFile.getJarEntry(entryName));
-        assertNotNull(newJarEntry);
-
-        jarEntry = null;
-        try {
-            newJarEntry = new JarEntry(jarEntry);
-            fail("Should throw NullPointerException");
-        } catch (NullPointerException e) {
-            // Expected
-        }
-    }
-
-    /**
-     * @tests java.util.jar.JarEntry#JarEntry(java.util.zip.ZipEntry)
-     */
-    public void test_ConstructorLjava_util_zip_ZipEntry() {
-        assertNotNull("Jar file is null", jarFile);
-        zipEntry = jarFile.getEntry(entryName);
-        assertNotNull("Zip entry is null", zipEntry);
-        jarEntry = new JarEntry(zipEntry);
-        assertNotNull("Jar entry is null", jarEntry);
-        assertEquals("Wrong entry constructed--wrong name", entryName, jarEntry
-                .getName());
-        assertEquals("Wrong entry constructed--wrong size", 311, jarEntry
-                .getSize());
-    }
-
-    /**
-     * @tests java.util.jar.JarEntry#getAttributes()
-     */
-    public void test_getAttributes() {
-        JarFile attrJar = null;
-        File file = null;
-        try {
-            Support_Resources.copyFile(resources, null, attJarName);
-            file = new File(resources, attJarName);
-            attrJar = new JarFile(file);
-        } catch (Exception e) {
-            assertTrue(file + " does not exist", file.exists());
-            fail("Exception opening file: " + e.toString());
-        }
-        try {
-            jarEntry = attrJar.getJarEntry(attEntryName);
-            assertNotNull("Should have Manifest attributes", jarEntry
-                    .getAttributes());
-        } catch (Exception e) {
-            fail("Exception during 2nd test: " + e.toString());
-        }
-        try {
-            jarEntry = attrJar.getJarEntry(attEntryName2);
-            assertNull("Shouldn't have any Manifest attributes", jarEntry
-                    .getAttributes());
-            attrJar.close();
-        } catch (Exception e) {
-            fail("Exception during 1st test: " + e.toString());
-        }
-
-        Support_Resources.copyFile(resources, null, "Broken_manifest.jar");
-        try {
-            attrJar = new JarFile(new File(resources, "Broken_manifest.jar"));
-            jarEntry = attrJar.getJarEntry("META-INF/");
-            jarEntry.getAttributes();
-            fail("IOException expected");
-        } catch (IOException e) {
-            // expected.
-        }
-    }
-
-    /**
-     * @tests java.util.jar.JarEntry#getCertificates()
-     */
-    public void test_getCertificates() throws Exception {
-        zipEntry = jarFile.getEntry(entryName2);
-        jarEntry = new JarEntry(zipEntry);
-        assertNull("Shouldn't have any Certificates", jarEntry
-                .getCertificates());
-
-        // Regression Test for HARMONY-3424
-        String jarFileName = "TestCodeSigners.jar";
-        Support_Resources.copyFile(resources, null, jarFileName);
-        File file = new File(resources, jarFileName);
-        JarFile jarFile = new JarFile(file);
-        JarEntry jarEntry1 = jarFile.getJarEntry("Test.class");
-        JarEntry jarEntry2 = jarFile.getJarEntry("Test.class");
-        InputStream in = jarFile.getInputStream(jarEntry1);
-        byte[] buffer = new byte[1024];
-        // BEGIN android-changed
-        // the certificates are non-null too early and in.available() fails
-        // while (in.available() > 0) {
-        //     assertNull("getCertificates() should be null until the entry is read",
-        //             jarEntry1.getCertificates());
-        //     assertNull(jarEntry2.getCertificates());
-        //     in.read(buffer);
-        // }
-        while (in.read(buffer) >= 0);
-        in.close();
-        // END android-changed
-        assertEquals("the file is fully read", -1, in.read());
-        assertNotNull(jarEntry1.getCertificates());
-        assertNotNull(jarEntry2.getCertificates());
-        in.close();
-    }
-
-    /**
-     * @tests java.util.jar.JarEntry#getCodeSigners()
-     */
-    public void test_getCodeSigners() throws IOException {
-        String jarFileName = "TestCodeSigners.jar";
-        Support_Resources.copyFile(resources, null, jarFileName);
-        File file = new File(resources, jarFileName);
-        JarFile jarFile = new JarFile(file);
-        JarEntry jarEntry = jarFile.getJarEntry("Test.class");
-        InputStream in = jarFile.getInputStream(jarEntry);
-        byte[] buffer = new byte[1024];
-        while (in.available() > 0) {
-            // BEGIN android-changed
-            // the code signers are non-null too early
-            // assertNull("getCodeSigners() should be null until the entry is read",
-            //         jarEntry.getCodeSigners());
-            // END android-changed
-            in.read(buffer);
-        }
-        assertEquals("the file is fully read", -1, in.read());
-        CodeSigner[] codeSigners = jarEntry.getCodeSigners();
-        assertEquals(2, codeSigners.length);
-        List<?> certs_bob = codeSigners[0].getSignerCertPath()
-                .getCertificates();
-        List<?> certs_alice = codeSigners[1].getSignerCertPath()
-                .getCertificates();
-        if (1 == certs_bob.size()) {
-            List<?> temp = certs_bob;
-            certs_bob = certs_alice;
-            certs_alice = temp;
-        }
-        assertEquals(2, certs_bob.size());
-        assertEquals(1, certs_alice.size());
-        assertNull(
-                "getCodeSigners() of a primitive JarEntry should return null",
-                new JarEntry("aaa").getCodeSigners());
-    }
-
-    public void test_ConstructorLjava_lang_String() {
-        assertNotNull("Jar file is null", jarFile);
-        zipEntry = jarFile.getEntry(entryName);
-        assertNotNull("Zip entry is null", zipEntry);
-        jarEntry = new JarEntry(entryName);
-        assertNotNull("Jar entry is null", jarEntry);
-        assertEquals("Wrong entry constructed--wrong name", entryName, jarEntry
-                .getName());
-        try {
-            jarEntry = new JarEntry((String) null);
-            fail("NullPointerException expected");
-        } catch (NullPointerException ee) {
-            // expected
-        }
-        StringBuffer sb = new StringBuffer();
-        for (int i = 0; i < 0x10000; i++) {
-            sb.append('3');
-        }
-        try {
-            jarEntry = new JarEntry(new String(sb));
-            fail("IllegalArgumentException expected");
-        } catch (IllegalArgumentException ee) {
-            // expected
-        }
-    }
-
-    public void test_ConstructorLjava_util_jar_JarEntry() {
-        assertNotNull("Jar file is null", jarFile);
-        JarEntry je = jarFile.getJarEntry(entryName);
-        assertNotNull("Jar entry is null", je);
-        jarEntry = new JarEntry(je);
-        assertNotNull("Jar entry is null", jarEntry);
-        assertEquals("Wrong entry constructed--wrong name", entryName, jarEntry
-                .getName());
-        assertEquals("Wrong entry constructed--wrong size", 311, jarEntry
-                .getSize());
-    }
-}
diff --git a/luni/src/test/java/org/apache/harmony/archive/tests/java/util/jar/JarExecTest.java b/luni/src/test/java/org/apache/harmony/archive/tests/java/util/jar/JarExecTest.java
deleted file mode 100644
index e70bb87..0000000
--- a/luni/src/test/java/org/apache/harmony/archive/tests/java/util/jar/JarExecTest.java
+++ /dev/null
@@ -1,276 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with this
- * work for additional information regarding copyright ownership. The ASF
- * licenses this file to You 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 org.apache.harmony.archive.tests.java.util.jar;
-
-import static tests.support.Support_Exec.execAndGetOutput;
-import static tests.support.Support_Exec.javaProcessBuilder;
-import tests.support.resource.Support_Resources;
-
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.util.jar.Attributes;
-import java.util.jar.JarEntry;
-import java.util.jar.JarOutputStream;
-import java.util.jar.Manifest;
-
-/**
- *
- * tests for various cases of java -jar ... execution
- *
- */
-
-public class JarExecTest extends junit.framework.TestCase {
-    /**
-     * regression test for HARMONY-1562 issue
-     *
-     */
-    public void test_1562() throws Exception {
-        // create the manifest
-        Manifest man = new Manifest();
-        Attributes att = man.getMainAttributes();
-        att.put(Attributes.Name.MANIFEST_VERSION, "1.0");
-        att.put(Attributes.Name.MAIN_CLASS, "foo.bar.execjartest.Foo");
-
-        File outputJar = File.createTempFile("hyts_", ".jar");
-        outputJar.deleteOnExit();
-        JarOutputStream jout = new JarOutputStream(new FileOutputStream(
-                outputJar), man);
-        File resources = Support_Resources.createTempFolder();
-
-        for (String jarClass : new String[] {"Foo", "Bar"}) {
-            jout.putNextEntry(new JarEntry("foo/bar/execjartest/" + jarClass
-                    + ".class"));
-            jout.write(getResource(resources, "hyts_" + jarClass + ".ser"));
-        }
-
-        jout.close();
-
-        // execute the JAR and read the result
-        ProcessBuilder builder = javaProcessBuilder();
-        builder.command().add("-jar");
-        builder.command().add(outputJar.getAbsolutePath());
-        assertTrue("Error executing JAR",
-                execAndGetOutput(builder).startsWith("FOOBAR"));
-    }
-
-    /**
-     * tests Class-Path entry in manifest
-     *
-     * @throws Exception in case of troubles
-     */
-    public void test_jar_class_path() throws Exception {
-        File fooJar = File.createTempFile("hyts_", ".jar");
-        File barJar = File.createTempFile("hyts_", ".jar");
-        fooJar.deleteOnExit();
-        barJar.deleteOnExit();
-
-        // create the manifest
-        Manifest man = new Manifest();
-        Attributes att = man.getMainAttributes();
-        att.put(Attributes.Name.MANIFEST_VERSION, "1.0");
-        att.put(Attributes.Name.MAIN_CLASS, "foo.bar.execjartest.Foo");
-        att.put(Attributes.Name.CLASS_PATH, barJar.getName());
-
-        File resources = Support_Resources.createTempFolder();
-
-        JarOutputStream joutFoo = new JarOutputStream(new FileOutputStream(
-                fooJar), man);
-        joutFoo.putNextEntry(new JarEntry("foo/bar/execjartest/Foo.class"));
-        joutFoo.write(getResource(resources, "hyts_Foo.ser"));
-        joutFoo.close();
-
-        JarOutputStream joutBar = new JarOutputStream(new FileOutputStream(
-                barJar));
-        joutBar.putNextEntry(new JarEntry("foo/bar/execjartest/Bar.class"));
-        joutBar.write(getResource(resources, "hyts_Bar.ser"));
-        joutBar.close();
-
-        // execute the JAR and read the result
-        ProcessBuilder builder = javaProcessBuilder();
-        builder.command().add("-jar");
-        builder.command().add(fooJar.getAbsolutePath());
-        assertTrue("Error executing JAR",
-                execAndGetOutput(builder).startsWith("FOOBAR"));
-
-        // rewrite manifest so it contains not only reference to bar but useless
-        // entries as well
-        att.put(Attributes.Name.CLASS_PATH, "xx yy zz " + barJar.getName());
-        joutFoo = new JarOutputStream(new FileOutputStream(fooJar), man);
-        joutFoo.putNextEntry(new JarEntry("foo/bar/execjartest/Foo.class"));
-        joutFoo.write(getResource(resources, "hyts_Foo.ser"));
-        joutFoo.close();
-        // execute the JAR and read the result
-        assertTrue("Error executing JAR",
-                execAndGetOutput(builder).startsWith( "FOOBAR"));
-
-        // play with relative file names - put relative path as ../<parent dir
-        // name>/xx.jar
-        att.put(Attributes.Name.CLASS_PATH, ".." + File.separator
-                + barJar.getParentFile().getName() + File.separator
-                + barJar.getName());
-        joutFoo = new JarOutputStream(new FileOutputStream(fooJar), man);
-        joutFoo.putNextEntry(new JarEntry("foo/bar/execjartest/Foo.class"));
-        joutFoo.write(getResource(resources, "hyts_Foo.ser"));
-        joutFoo.close();
-        // execute the JAR and read the result
-        assertTrue("Error executing JAR",
-                execAndGetOutput(builder).startsWith( "FOOBAR"));
-    }
-
-    /**
-     * tests case when Main-Class is not in the jar launched but in another jar
-     * referenced by Class-Path
-     *
-     * @throws Exception in case of troubles
-     */
-    public void test_main_class_in_another_jar() throws Exception {
-        File fooJar = File.createTempFile("hyts_", ".jar");
-        File barJar = File.createTempFile("hyts_", ".jar");
-        fooJar.deleteOnExit();
-        barJar.deleteOnExit();
-
-        // create the manifest
-        Manifest man = new Manifest();
-        Attributes att = man.getMainAttributes();
-        att.put(Attributes.Name.MANIFEST_VERSION, "1.0");
-        att.put(Attributes.Name.MAIN_CLASS, "foo.bar.execjartest.Foo");
-        att.put(Attributes.Name.CLASS_PATH, fooJar.getName());
-
-        File resources = Support_Resources.createTempFolder();
-
-        JarOutputStream joutFoo = new JarOutputStream(new FileOutputStream(
-                fooJar));
-        joutFoo.putNextEntry(new JarEntry("foo/bar/execjartest/Foo.class"));
-        joutFoo.write(getResource(resources, "hyts_Foo.ser"));
-        joutFoo.close();
-
-        JarOutputStream joutBar = new JarOutputStream(new FileOutputStream(
-                barJar), man);
-        joutBar.putNextEntry(new JarEntry("foo/bar/execjartest/Bar.class"));
-        joutBar.write(getResource(resources, "hyts_Bar.ser"));
-        joutBar.close();
-
-        // execute the JAR and read the result
-        ProcessBuilder builder = javaProcessBuilder();
-        builder.command().add("-jar");
-        builder.command().add(barJar.getAbsolutePath());
-        assertTrue("Error executing JAR",
-                execAndGetOutput(builder).startsWith("FOOBAR"));
-    }
-
-    public void test_classpath() throws Exception {
-        File resources = Support_Resources.createTempFolder();
-
-        File fooJar = File.createTempFile("hyts_", ".jar");
-        fooJar.deleteOnExit();
-
-        JarOutputStream joutFoo = new JarOutputStream(new FileOutputStream(
-                fooJar));
-        joutFoo.putNextEntry(new JarEntry("foo/bar/execjartest/Foo.class"));
-        joutFoo.write(getResource(resources, "hyts_Foo.ser"));
-        joutFoo.putNextEntry(new JarEntry("foo/bar/execjartest/Bar.class"));
-        joutFoo.write(getResource(resources, "hyts_Bar.ser"));
-        joutFoo.close();
-
-        // execute the JAR and read the result
-        ProcessBuilder builder = javaProcessBuilder();
-        builder.environment().put("CLASSPATH", fooJar.getAbsolutePath());
-        builder.command().add("foo.bar.execjartest.Foo");
-
-        assertTrue("Error executing class from ClassPath",
-                execAndGetOutput(builder).startsWith("FOOBAR"));
-
-        // ok - next try - add -cp to path - it should override env
-        File booJar = File.createTempFile("hyts_", ".jar");
-        booJar.deleteOnExit();
-
-        JarOutputStream joutBoo = new JarOutputStream(new FileOutputStream(
-                booJar));
-        joutBoo.putNextEntry(new JarEntry("foo/bar/execjartest/Foo.class"));
-        String booBody = new String(getResource(resources, "hyts_Foo.ser"),
-                "iso-8859-1");
-        booBody = booBody.replaceFirst("FOO", "BOO");
-        joutBoo.write(booBody.getBytes("iso-8859-1"));
-        joutBoo.putNextEntry(new JarEntry("foo/bar/execjartest/Bar.class"));
-        String farBody = new String(getResource(resources, "hyts_Bar.ser"),
-                "iso-8859-1");
-        farBody = farBody.replaceFirst("BAR", "FAR");
-        joutBoo.write(farBody.getBytes("iso-8859-1"));
-        joutBoo.close();
-
-        builder = javaProcessBuilder();
-        builder.environment().put("CLASSPATH", fooJar.getAbsolutePath());
-        builder.command().add("-cp");
-        builder.command().add(booJar.getAbsolutePath());
-        builder.command().add("foo.bar.execjartest.Foo");
-
-        assertTrue("Error executing class specified by -cp",
-                execAndGetOutput(builder).startsWith("BOOFAR"));
-
-        // now add -jar option - it should override env and classpath
-        Manifest man = new Manifest();
-        Attributes att = man.getMainAttributes();
-        att.put(Attributes.Name.MANIFEST_VERSION, "1.0");
-        att.put(Attributes.Name.MAIN_CLASS, "foo.bar.execjartest.Foo");
-
-        File zooJar = File.createTempFile("hyts_", ".jar");
-        zooJar.deleteOnExit();
-
-        JarOutputStream joutZoo = new JarOutputStream(new FileOutputStream(
-                zooJar), man);
-        joutZoo.putNextEntry(new JarEntry("foo/bar/execjartest/Foo.class"));
-        String zooBody = new String(getResource(resources, "hyts_Foo.ser"),
-                "iso-8859-1");
-        zooBody = zooBody.replaceFirst("FOO", "ZOO");
-        joutZoo.write(zooBody.getBytes("iso-8859-1"));
-        joutZoo.putNextEntry(new JarEntry("foo/bar/execjartest/Bar.class"));
-        String zarBody = new String(getResource(resources, "hyts_Bar.ser"),
-                "iso-8859-1");
-        zarBody = zarBody.replaceFirst("BAR", "ZAR");
-        joutZoo.write(zarBody.getBytes("iso-8859-1"));
-        joutZoo.close();
-
-        builder = javaProcessBuilder();
-        builder.environment().put("CLASSPATH", fooJar.getAbsolutePath());
-        builder.command().add("-cp");
-        builder.command().add(booJar.getAbsolutePath());
-        builder.command().add("-jar");
-        builder.command().add(zooJar.getAbsolutePath());
-
-        assertTrue("Error executing class specified by -jar",
-                execAndGetOutput(builder).startsWith("ZOOZAR"));
-    }
-
-    private static byte[] getResource(File tempDir, String resourceName)
-            throws IOException {
-        Support_Resources.copyFile(tempDir, null, resourceName);
-        File resourceFile = new File(tempDir, resourceName);
-        resourceFile.deleteOnExit();
-
-        // read whole resource data into memory
-        byte[] resourceBody = new byte[(int) resourceFile.length()];
-        FileInputStream fis = new FileInputStream(resourceFile);
-        fis.read(resourceBody);
-        fis.close();
-
-        return resourceBody;
-    }
-
-}
diff --git a/luni/src/test/java/org/apache/harmony/archive/tests/java/util/jar/JarFileTest.java b/luni/src/test/java/org/apache/harmony/archive/tests/java/util/jar/JarFileTest.java
deleted file mode 100644
index 8a9ef5f..0000000
--- a/luni/src/test/java/org/apache/harmony/archive/tests/java/util/jar/JarFileTest.java
+++ /dev/null
@@ -1,945 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements.  See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You 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 org.apache.harmony.archive.tests.java.util.jar;
-
-
-import junit.framework.TestCase;
-
-import tests.support.Support_PlatformFile;
-import tests.support.resource.Support_Resources;
-
-import java.io.ByteArrayOutputStream;
-import java.io.File;
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.net.URL;
-import java.security.Permission;
-import java.security.cert.Certificate;
-import java.util.Enumeration;
-import java.util.Vector;
-import java.util.jar.Attributes;
-import java.util.jar.JarEntry;
-import java.util.jar.JarFile;
-import java.util.jar.JarOutputStream;
-import java.util.jar.Manifest;
-import java.util.zip.ZipEntry;
-import java.util.zip.ZipException;
-import java.util.zip.ZipFile;
-
-
-public class JarFileTest extends TestCase {
-
-    // BEGIN android-added
-    public byte[] getAllBytesFromStream(InputStream is) throws IOException {
-        ByteArrayOutputStream bs = new ByteArrayOutputStream();
-        byte[] buf = new byte[666];
-        int iRead;
-        int off;
-        while (is.available() > 0) {
-            iRead = is.read(buf, 0, buf.length);
-            if (iRead > 0) bs.write(buf, 0, iRead);
-        }
-        return bs.toByteArray();
-    }
-
-    // END android-added
-
-    private final String jarName = "hyts_patch.jar"; // a 'normal' jar file
-
-    private final String jarName2 = "hyts_patch2.jar";
-
-    private final String jarName3 = "hyts_manifest1.jar";
-
-    private final String jarName4 = "hyts_signed.jar";
-
-    private final String jarName5 = "hyts_signed_inc.jar";
-
-    private final String entryName = "foo/bar/A.class";
-
-    private final String entryName3 = "coucou/FileAccess.class";
-
-    private final String integrateJar = "Integrate.jar";
-
-    private final String integrateJarEntry = "Test.class";
-
-    private final String emptyEntryJar = "EmptyEntries_signed.jar";
-
-    private final String emptyEntry1 = "subfolder/internalSubset01.js";
-
-    private final String emptyEntry2 = "svgtest.js";
-
-    private final String emptyEntry3 = "svgunit.js";
-
-    private File resources;
-
-    // custom security manager
-    SecurityManager sm = new SecurityManager() {
-        final String forbidenPermissionName = "user.dir";
-
-        public void checkPermission(Permission perm) {
-            if (perm.getName().equals(forbidenPermissionName)) {
-                throw new SecurityException();
-            }
-        }
-    };
-
-    @Override
-    protected void setUp() {
-        resources = Support_Resources.createTempFolder();
-    }
-
-    /**
-     * @tests java.util.jar.JarFile#JarFile(java.io.File)
-     */
-    public void test_ConstructorLjava_io_File() {
-        try {
-            JarFile jarFile = new JarFile(new File("Wrong.file"));
-            fail("Should throw IOException");
-        } catch (IOException e) {
-            // expected
-        }
-        SecurityManager oldSm = System.getSecurityManager();
-        System.setSecurityManager(sm);
-        try {
-            JarFile jarFile = new JarFile(new File("tmp.jar"));
-            fail("Should throw SecurityException");
-        } catch (IOException e) {
-            fail("Should throw SecurityException");
-        } catch (SecurityException e) {
-            // expected
-        } finally {
-            System.setSecurityManager(oldSm);
-        }
-
-        try {
-            Support_Resources.copyFile(resources, null, jarName);
-            JarFile jarFile = new JarFile(new File(resources, jarName));
-        } catch (IOException e) {
-            fail("Should not throw IOException");
-        }
-    }
-
-    /**
-     * @tests java.util.jar.JarFile#JarFile(java.lang.String)
-     */
-    public void test_ConstructorLjava_lang_String() {
-        try {
-            JarFile jarFile = new JarFile("Wrong.file");
-            fail("Should throw IOException");
-        } catch (IOException e) {
-            // expected
-        }
-        SecurityManager oldSm = System.getSecurityManager();
-        System.setSecurityManager(sm);
-        try {
-            JarFile jarFile = new JarFile("tmp.jar");
-            fail("Should throw SecurityException");
-        } catch (IOException e) {
-            fail("Should throw SecurityException");
-        } catch (SecurityException e) {
-            // expected
-        } finally {
-            System.setSecurityManager(oldSm);
-        }
-
-        try {
-            Support_Resources.copyFile(resources, null, jarName);
-            String fileName = (new File(resources, jarName)).getCanonicalPath();
-            JarFile jarFile = new JarFile(fileName);
-        } catch (IOException e) {
-            fail("Should not throw IOException");
-        }
-    }
-
-    /**
-     * @tests java.util.jar.JarFile#JarFile(java.lang.String, boolean)
-     */
-    public void test_ConstructorLjava_lang_StringZ() {
-        try {
-            JarFile jarFile = new JarFile("Wrong.file", false);
-            fail("Should throw IOException");
-        } catch (IOException e) {
-            // expected
-        }
-        SecurityManager oldSm = System.getSecurityManager();
-        System.setSecurityManager(sm);
-        try {
-            JarFile jarFile = new JarFile("tmp.jar", true);
-            fail("Should throw SecurityException");
-        } catch (IOException e) {
-            fail("Should throw SecurityException");
-        } catch (SecurityException e) {
-            // expected
-        } finally {
-            System.setSecurityManager(oldSm);
-        }
-
-        try {
-            Support_Resources.copyFile(resources, null, jarName);
-            String fileName = (new File(resources, jarName)).getCanonicalPath();
-            JarFile jarFile = new JarFile(fileName, true);
-        } catch (IOException e) {
-            fail("Should not throw IOException");
-        }
-    }
-
-    /**
-     * @tests java.util.jar.JarFile#JarFile(java.io.File, boolean)
-     */
-    public void test_ConstructorLjava_io_FileZ() {
-        try {
-            JarFile jarFile = new JarFile(new File("Wrong.file"), true);
-            fail("Should throw IOException");
-        } catch (IOException e) {
-            // expected
-        }
-        SecurityManager oldSm = System.getSecurityManager();
-        System.setSecurityManager(sm);
-        try {
-            JarFile jarFile = new JarFile(new File("tmp.jar"), false);
-            fail("Should throw SecurityException");
-        } catch (IOException e) {
-            fail("Should throw SecurityException");
-        } catch (SecurityException e) {
-            // expected
-        } finally {
-            System.setSecurityManager(oldSm);
-        }
-
-        try {
-            Support_Resources.copyFile(resources, null, jarName);
-            JarFile jarFile = new JarFile(new File(resources, jarName), false);
-        } catch (IOException e) {
-            fail("Should not throw IOException");
-        }
-    }
-
-    /**
-     * @tests java.util.jar.JarFile#JarFile(java.io.File, boolean, int)
-     */
-    public void test_ConstructorLjava_io_FileZI() {
-        try {
-            JarFile jarFile = new JarFile(new File("Wrong.file"), true,
-                    ZipFile.OPEN_READ);
-            fail("Should throw IOException");
-        } catch (IOException e) {
-            // expected
-        }
-        SecurityManager oldSm = System.getSecurityManager();
-        System.setSecurityManager(sm);
-        try {
-            JarFile jarFile = new JarFile(new File("tmp.jar"), false,
-                    ZipFile.OPEN_READ);
-            fail("Should throw SecurityException");
-        } catch (IOException e) {
-            fail("Should throw SecurityException");
-        } catch (SecurityException e) {
-            // expected
-        } finally {
-            System.setSecurityManager(oldSm);
-        }
-
-        try {
-            Support_Resources.copyFile(resources, null, jarName);
-            JarFile jarFile = new JarFile(new File(resources, jarName), false,
-                    ZipFile.OPEN_READ);
-        } catch (IOException e) {
-            fail("Should not throw IOException");
-        }
-
-        try {
-            Support_Resources.copyFile(resources, null, jarName);
-            JarFile jarFile = new JarFile(new File(resources, jarName), false,
-                    ZipFile.OPEN_READ | ZipFile.OPEN_DELETE + 33);
-            fail("Should throw IllegalArgumentException");
-        } catch (IOException e) {
-            fail("Should not throw IOException");
-        } catch (IllegalArgumentException e) {
-            // expected
-        }
-    }
-
-    /**
-     * Constructs JarFile object.
-     *
-     * @tests java.util.jar.JarFile#JarFile(java.io.File)
-     * @tests java.util.jar.JarFile#JarFile(java.lang.String)
-     */
-    public void testConstructor_file() throws IOException {
-        File f = new File(resources, jarName);
-        Support_Resources.copyFile(resources, null, jarName);
-        assertTrue(new JarFile(f).getEntry(entryName).getName().equals(
-                entryName));
-        assertTrue(new JarFile(f.getPath()).getEntry(entryName).getName()
-                .equals(entryName));
-    }
-
-    /**
-     * @tests java.util.jar.JarFile#entries()
-     */
-    public void test_entries() throws Exception {
-        /*
-         * Note only (and all of) the following should be contained in the file
-         * META-INF/ META-INF/MANIFEST.MF foo/ foo/bar/ foo/bar/A.class Blah.txt
-         */
-        Support_Resources.copyFile(resources, null, jarName);
-        JarFile jarFile = new JarFile(new File(resources, jarName));
-        Enumeration<JarEntry> e = jarFile.entries();
-        int i;
-        for (i = 0; e.hasMoreElements(); i++) {
-            e.nextElement();
-        }
-        assertEquals(jarFile.size(), i);
-        jarFile.close();
-        assertEquals(6, i);
-    }
-
-    public void test_entries2() throws Exception {
-        Support_Resources.copyFile(resources, null, jarName);
-        JarFile jarFile = new JarFile(new File(resources, jarName));
-        Enumeration<JarEntry> enumeration = jarFile.entries();
-        jarFile.close();
-        try {
-            enumeration.hasMoreElements();
-            fail("hasMoreElements() did not detect a closed jar file");
-        } catch (IllegalStateException e) {
-        }
-        Support_Resources.copyFile(resources, null, jarName);
-        jarFile = new JarFile(new File(resources, jarName));
-        enumeration = jarFile.entries();
-        jarFile.close();
-        try {
-            enumeration.nextElement();
-            fail("nextElement() did not detect closed jar file");
-        } catch (IllegalStateException e) {
-        }
-    }
-
-    /**
-     * @throws IOException
-     * @tests java.util.jar.JarFile#getJarEntry(java.lang.String)
-     */
-    public void test_getEntryLjava_lang_String() throws IOException {
-        try {
-            Support_Resources.copyFile(resources, null, jarName);
-            JarFile jarFile = new JarFile(new File(resources, jarName));
-            assertEquals("Error in returned entry", 311, jarFile.getEntry(
-                    entryName).getSize());
-            jarFile.close();
-        } catch (Exception e) {
-            fail("Exception during test: " + e.toString());
-        }
-
-        Support_Resources.copyFile(resources, null, jarName);
-        JarFile jarFile = new JarFile(new File(resources, jarName));
-        Enumeration<JarEntry> enumeration = jarFile.entries();
-        assertTrue(enumeration.hasMoreElements());
-        while (enumeration.hasMoreElements()) {
-            JarEntry je = enumeration.nextElement();
-            jarFile.getEntry(je.getName());
-        }
-
-        enumeration = jarFile.entries();
-        assertTrue(enumeration.hasMoreElements());
-        JarEntry je = enumeration.nextElement();
-        try {
-            jarFile.close();
-            jarFile.getEntry(je.getName());
-            // fail("IllegalStateException expected.");
-        } catch (IllegalStateException ee) { // Per documentation exception
-            // may be thrown.
-            // expected
-        }
-    }
-
-    /**
-     * @throws IOException
-     * @tests java.util.jar.JarFile#getJarEntry(java.lang.String)
-     */
-    public void test_getJarEntryLjava_lang_String() throws IOException {
-        try {
-            Support_Resources.copyFile(resources, null, jarName);
-            JarFile jarFile = new JarFile(new File(resources, jarName));
-            assertEquals("Error in returned entry", 311, jarFile.getJarEntry(
-                    entryName).getSize());
-            jarFile.close();
-        } catch (Exception e) {
-            fail("Exception during test: " + e.toString());
-        }
-
-        Support_Resources.copyFile(resources, null, jarName);
-        JarFile jarFile = new JarFile(new File(resources, jarName));
-        Enumeration<JarEntry> enumeration = jarFile.entries();
-        assertTrue(enumeration.hasMoreElements());
-        while (enumeration.hasMoreElements()) {
-            JarEntry je = enumeration.nextElement();
-            jarFile.getJarEntry(je.getName());
-        }
-
-        enumeration = jarFile.entries();
-        assertTrue(enumeration.hasMoreElements());
-        JarEntry je = enumeration.nextElement();
-        try {
-            jarFile.close();
-            jarFile.getJarEntry(je.getName());
-            // fail("IllegalStateException expected.");
-        } catch (IllegalStateException ee) { // Per documentation exception
-            // may be thrown.
-            // expected
-        }
-    }
-
-
-    /**
-     * @tests java.util.jar.JarFile#getJarEntry(java.lang.String)
-     */
-    public void testGetJarEntry() throws Exception {
-        Support_Resources.copyFile(resources, null, jarName);
-        JarFile jarFile = new JarFile(new File(resources, jarName));
-        assertEquals("Error in returned entry", 311, jarFile.getEntry(
-                entryName).getSize());
-        jarFile.close();
-
-        // tests for signed jars
-        // test all signed jars in the /Testres/Internal/SignedJars directory
-        String jarDirUrl = Support_Resources
-                .getResourceURL("/../internalres/signedjars");
-        Vector<String> signedJars = new Vector<String>();
-        try {
-            InputStream is = new URL(jarDirUrl + "/jarlist.txt").openStream();
-            while (is.available() > 0) {
-                StringBuilder linebuff = new StringBuilder(80); // Typical line
-                // length
-                done: while (true) {
-                    int nextByte = is.read();
-                    switch (nextByte) {
-                        case -1:
-                            break done;
-                        case (byte) '\r':
-                            if (linebuff.length() == 0) {
-                                // ignore
-                            }
-                            break done;
-                        case (byte) '\n':
-                            if (linebuff.length() == 0) {
-                                // ignore
-                            }
-                            break done;
-                        default:
-                            linebuff.append((char) nextByte);
-                    }
-                }
-                if (linebuff.length() == 0) {
-                    break;
-                }
-                String line = linebuff.toString();
-                signedJars.add(line);
-            }
-            is.close();
-        } catch (IOException e) {
-            // no list of jars found
-        }
-
-        for (int i = 0; i < signedJars.size(); i++) {
-            String jarName = signedJars.get(i);
-            try {
-                File file = Support_Resources.getExternalLocalFile(jarDirUrl
-                        + "/" + jarName);
-                jarFile = new JarFile(file, true);
-                boolean foundCerts = false;
-                Enumeration<JarEntry> e = jarFile.entries();
-                while (e.hasMoreElements()) {
-                    JarEntry entry = e.nextElement();
-                    InputStream is = jarFile.getInputStream(entry);
-                    is.skip(100000);
-                    is.close();
-                    Certificate[] certs = entry.getCertificates();
-                    if (certs != null && certs.length > 0) {
-                        foundCerts = true;
-                        break;
-                    }
-                }
-                assertTrue(
-                        "No certificates found during signed jar test for jar \""
-                                + jarName + "\"", foundCerts);
-            } catch (IOException e) {
-                fail("Exception during signed jar test for jar \"" + jarName
-                        + "\": " + e.toString());
-            }
-        }
-    }
-
-    /**
-     * @tests java.util.jar.JarFile#getManifest()
-     */
-    public void test_getManifest() {
-        // Test for method java.util.jar.Manifest
-        // java.util.jar.JarFile.getManifest()
-        try {
-            Support_Resources.copyFile(resources, null, jarName);
-            JarFile jarFile = new JarFile(new File(resources, jarName));
-            assertNotNull("Error--Manifest not returned", jarFile.getManifest());
-            jarFile.close();
-        } catch (Exception e) {
-            fail("Exception during 1st test: " + e.toString());
-        }
-        try {
-            Support_Resources.copyFile(resources, null, jarName2);
-            JarFile jarFile = new JarFile(new File(resources, jarName2));
-            assertNull("Error--should have returned null", jarFile
-                    .getManifest());
-            jarFile.close();
-        } catch (Exception e) {
-            fail("Exception during 2nd test: " + e.toString());
-        }
-
-        try {
-            // jarName3 was created using the following test
-            Support_Resources.copyFile(resources, null, jarName3);
-            JarFile jarFile = new JarFile(new File(resources, jarName3));
-            assertNotNull("Should find manifest without verifying", jarFile
-                    .getManifest());
-            jarFile.close();
-        } catch (Exception e) {
-            fail("Exception during 3rd test: " + e.toString());
-        }
-
-        try {
-            // this is used to create jarName3 used in the previous test
-            Manifest manifest = new Manifest();
-            Attributes attributes = manifest.getMainAttributes();
-            attributes.put(new Attributes.Name("Manifest-Version"), "1.0");
-            ByteArrayOutputStream manOut = new ByteArrayOutputStream();
-            manifest.write(manOut);
-            byte[] manBytes = manOut.toByteArray();
-            File file = File.createTempFile(
-                    Support_PlatformFile.getNewPlatformFile("hyts_manifest1",
-                            ""), ".jar");
-            JarOutputStream jarOut = new JarOutputStream(new FileOutputStream(
-                    file.getAbsolutePath()));
-            ZipEntry entry = new ZipEntry("META-INF/");
-            entry.setSize(0);
-            jarOut.putNextEntry(entry);
-            entry = new ZipEntry(JarFile.MANIFEST_NAME);
-            entry.setSize(manBytes.length);
-            jarOut.putNextEntry(entry);
-            jarOut.write(manBytes);
-            entry = new ZipEntry("myfile");
-            entry.setSize(1);
-            jarOut.putNextEntry(entry);
-            jarOut.write(65);
-            jarOut.close();
-            JarFile jar = new JarFile(file.getAbsolutePath(), false);
-            assertNotNull("Should find manifest without verifying", jar
-                    .getManifest());
-            jar.close();
-            file.delete();
-        } catch (IOException e) {
-            fail("IOException 3");
-        }
-        try {
-            Support_Resources.copyFile(resources, null, jarName2);
-            JarFile jF = new JarFile(new File(resources, jarName2));
-            jF.close();
-            jF.getManifest();
-            fail("FAILED: expected IllegalStateException");
-        } catch (IllegalStateException ise) {
-            // expected;
-        } catch (Exception e) {
-            fail("Exception during 4th test: " + e.toString());
-        }
-
-        Support_Resources.copyFile(resources, null, "Broken_manifest.jar");
-        JarFile jf;
-        try {
-            jf = new JarFile(new File(resources, "Broken_manifest.jar"));
-            jf.getManifest();
-            fail("IOException expected.");
-        } catch (IOException e) {
-            // expected.
-        }
-    }
-
-    /**
-     * @tests java.util.jar.JarFile#getInputStream(java.util.zip.ZipEntry)
-     */
-    // This test doesn't pass on RI. If entry size is set up incorrectly,
-    // SecurityException is thrown. But SecurityException is thrown on RI only
-    // if jar file is signed incorrectly.
-    public void test_getInputStreamLjava_util_jar_JarEntry_subtest0() {
-        File signedFile = null;
-        try {
-            Support_Resources.copyFile(resources, null, jarName4);
-            signedFile = new File(resources, jarName4);
-        } catch (Exception e) {
-            fail("Failed to create local file 2: " + e);
-        }
-
-        try {
-            JarFile jar = new JarFile(signedFile);
-            JarEntry entry = new JarEntry(entryName3);
-            InputStream in = jar.getInputStream(entry);
-            in.read();
-        } catch (Exception e) {
-            fail("Exception during test 3: " + e);
-        }
-
-        try {
-            JarFile jar = new JarFile(signedFile);
-            JarEntry entry = new JarEntry(entryName3);
-            InputStream in = jar.getInputStream(entry);
-            // BEGIN android-added
-            byte[] dummy = getAllBytesFromStream(in);
-            // END android-added
-            assertNull("found certificates", entry.getCertificates());
-        } catch (Exception e) {
-            fail("Exception during test 4: " + e);
-        }
-
-        try {
-            JarFile jar = new JarFile(signedFile);
-            JarEntry entry = new JarEntry(entryName3);
-            entry.setSize(1076);
-            InputStream in = jar.getInputStream(entry);
-            // BEGIN android-added
-            byte[] dummy = getAllBytesFromStream(in);
-            // END android-added
-            fail("SecurityException should be thrown.");
-        } catch (SecurityException e) {
-            // expected
-        } catch (Exception e) {
-            fail("Exception during test 5: " + e);
-        }
-
-        try {
-            Support_Resources.copyFile(resources, null, jarName5);
-            signedFile = new File(resources, jarName5);
-        } catch (Exception e) {
-            fail("Failed to create local file 5: " + e);
-        }
-
-        try {
-            JarFile jar = new JarFile(signedFile);
-            JarEntry entry = new JarEntry(entryName3);
-            InputStream in = jar.getInputStream(entry);
-            fail("SecurityException should be thrown.");
-        } catch (SecurityException e) {
-            // expected
-        } catch (Exception e) {
-            fail("Exception during test 5: " + e);
-        }
-    }
-
-    /*
-     * The jar created by 1.4 which does not provide a
-     * algorithm-Digest-Manifest-Main-Attributes entry in .SF file.
-     */
-    public void test_Jar_created_before_java_5() throws IOException {
-        String modifiedJarName = "Created_by_1_4.jar";
-        Support_Resources.copyFile(resources, null, modifiedJarName);
-        JarFile jarFile = new JarFile(new File(resources, modifiedJarName),
-                true);
-        Enumeration<JarEntry> entries = jarFile.entries();
-        while (entries.hasMoreElements()) {
-            ZipEntry zipEntry = entries.nextElement();
-            jarFile.getInputStream(zipEntry);
-        }
-    }
-
-    /* The jar is intact, then everything is all right. */
-    public void test_JarFile_Integrate_Jar() throws IOException {
-        String modifiedJarName = "Integrate.jar";
-        Support_Resources.copyFile(resources, null, modifiedJarName);
-        JarFile jarFile = new JarFile(new File(resources, modifiedJarName),
-                true);
-        Enumeration<JarEntry> entries = jarFile.entries();
-        while (entries.hasMoreElements()) {
-            ZipEntry zipEntry = entries.nextElement();
-            jarFile.getInputStream(zipEntry).skip(Long.MAX_VALUE);
-        }
-    }
-
-    /**
-     * The jar is intact, but the entry object is modified.
-     */
-    public void testJarVerificationModifiedEntry() throws IOException {
-        Support_Resources.copyFile(resources, null, integrateJar);
-        File f = new File(resources, integrateJar);
-
-        JarFile jarFile = new JarFile(f);
-        ZipEntry zipEntry = jarFile.getJarEntry(integrateJarEntry);
-        zipEntry.setSize(zipEntry.getSize() + 1);
-        jarFile.getInputStream(zipEntry).skip(Long.MAX_VALUE);
-
-        jarFile = new JarFile(f);
-        zipEntry = jarFile.getJarEntry(integrateJarEntry);
-        zipEntry.setSize(zipEntry.getSize() - 1);
-        try {
-            //jarFile.getInputStream(zipEntry).skip(Long.MAX_VALUE);
-            jarFile.getInputStream(zipEntry).read(new byte[5000], 0, 5000);
-            fail("SecurityException expected");
-        } catch (SecurityException e) {
-            // desired
-        }
-    }
-
-    /*
-     * If another entry is inserted into Manifest, no security exception will be
-     * thrown out.
-     */
-    public void test_JarFile_InsertEntry_in_Manifest_Jar() throws IOException {
-        String modifiedJarName = "Inserted_Entry_Manifest.jar";
-        Support_Resources.copyFile(resources, null, modifiedJarName);
-        JarFile jarFile = new JarFile(new File(resources, modifiedJarName),
-                true);
-        Enumeration<JarEntry> entries = jarFile.entries();
-        int count = 0;
-        while (entries.hasMoreElements()) {
-
-            ZipEntry zipEntry = entries.nextElement();
-            jarFile.getInputStream(zipEntry);
-            count++;
-        }
-        assertEquals(5, count);
-    }
-
-    /*
-     * If another entry is inserted into Manifest, no security exception will be
-     * thrown out.
-     */
-    public void test_Inserted_Entry_Manifest_with_DigestCode()
-            throws IOException {
-        String modifiedJarName = "Inserted_Entry_Manifest_with_DigestCode.jar";
-        Support_Resources.copyFile(resources, null, modifiedJarName);
-        JarFile jarFile = new JarFile(new File(resources, modifiedJarName),
-                true);
-        Enumeration<JarEntry> entries = jarFile.entries();
-        int count = 0;
-        while (entries.hasMoreElements()) {
-            ZipEntry zipEntry = entries.nextElement();
-            jarFile.getInputStream(zipEntry);
-            count++;
-        }
-        assertEquals(5, count);
-    }
-
-    /*
-     * The content of Test.class is modified, jarFile.getInputStream will not
-     * throw security Exception, but it will anytime before the inputStream got
-     * from getInputStream method has been read to end.
-     */
-    public void test_JarFile_Modified_Class() throws IOException {
-        String modifiedJarName = "Modified_Class.jar";
-        Support_Resources.copyFile(resources, null, modifiedJarName);
-        JarFile jarFile = new JarFile(new File(resources, modifiedJarName),
-                true);
-        Enumeration<JarEntry> entries = jarFile.entries();
-        while (entries.hasMoreElements()) {
-            ZipEntry zipEntry = entries.nextElement();
-            jarFile.getInputStream(zipEntry);
-        }
-        /* The content of Test.class has been tampered. */
-        ZipEntry zipEntry = jarFile.getEntry("Test.class");
-        InputStream in = jarFile.getInputStream(zipEntry);
-        byte[] buffer = new byte[1024];
-        try {
-            while (in.available() > 0) {
-                in.read(buffer);
-            }
-            fail("SecurityException expected");
-        } catch (SecurityException e) {
-            // desired
-        }
-    }
-
-    /*
-     * In the Modified.jar, the main attributes of META-INF/MANIFEST.MF is
-     * tampered manually. Hence the RI 5.0 JarFile.getInputStream of any
-     * JarEntry will throw security exception.
-     */
-    public void test_JarFile_Modified_Manifest_MainAttributes()
-            throws IOException {
-        String modifiedJarName = "Modified_Manifest_MainAttributes.jar";
-        Support_Resources.copyFile(resources, null, modifiedJarName);
-        JarFile jarFile = new JarFile(new File(resources, modifiedJarName),
-                true);
-        Enumeration<JarEntry> entries = jarFile.entries();
-        while (entries.hasMoreElements()) {
-            ZipEntry zipEntry = entries.nextElement();
-            try {
-                jarFile.getInputStream(zipEntry);
-                fail("SecurityException expected");
-            } catch (SecurityException e) {
-                // desired
-            }
-        }
-    }
-
-    /*
-     * It is all right in our original JarFile. If the Entry Attributes, for
-     * example Test.class in our jar, the jarFile.getInputStream will throw
-     * Security Exception.
-     */
-    public void test_JarFile_Modified_Manifest_EntryAttributes()
-            throws IOException {
-        String modifiedJarName = "Modified_Manifest_EntryAttributes.jar";
-        Support_Resources.copyFile(resources, null, modifiedJarName);
-        JarFile jarFile = new JarFile(new File(resources, modifiedJarName),
-                true);
-        Enumeration<JarEntry> entries = jarFile.entries();
-        while (entries.hasMoreElements()) {
-            ZipEntry zipEntry = entries.nextElement();
-            try {
-                jarFile.getInputStream(zipEntry);
-                fail("should throw Security Exception");
-            } catch (SecurityException e) {
-                // desired
-            }
-        }
-    }
-
-    /*
-     * If the content of the .SA file is modified, no matter what it resides,
-     * JarFile.getInputStream of any JarEntry will throw Security Exception.
-     */
-    public void test_JarFile_Modified_SF_EntryAttributes() throws IOException {
-        String modifiedJarName = "Modified_SF_EntryAttributes.jar";
-        Support_Resources.copyFile(resources, null, modifiedJarName);
-        JarFile jarFile = new JarFile(new File(resources, modifiedJarName),
-                true);
-        Enumeration<JarEntry> entries = jarFile.entries();
-        while (entries.hasMoreElements()) {
-            ZipEntry zipEntry = entries.nextElement();
-            try {
-                jarFile.getInputStream(zipEntry);
-                fail("should throw Security Exception");
-            } catch (SecurityException e) {
-                // desired
-            }
-        }
-    }
-
-    public void test_close() throws IOException {
-        String modifiedJarName = "Modified_SF_EntryAttributes.jar";
-        Support_Resources.copyFile(resources, null, modifiedJarName);
-        JarFile jarFile = new JarFile(new File(resources, modifiedJarName),
-                true);
-        Enumeration<JarEntry> entries = jarFile.entries();
-
-        jarFile.close();
-        jarFile.close();
-
-        // Can not check IOException
-    }
-
-    /**
-     * @throws IOException
-     * @tests java.util.jar.JarFile#getInputStream(java.util.zip.ZipEntry)
-     */
-    public void test_getInputStreamLjava_util_jar_JarEntry() throws IOException {
-        File localFile = null;
-        try {
-            Support_Resources.copyFile(resources, null, jarName);
-            localFile = new File(resources, jarName);
-        } catch (Exception e) {
-            fail("Failed to create local file: " + e);
-        }
-
-        byte[] b = new byte[1024];
-        try {
-            JarFile jf = new JarFile(localFile);
-            java.io.InputStream is = jf.getInputStream(jf.getEntry(entryName));
-            // BEGIN android-removed
-            // jf.close();
-            // END android-removed
-            assertTrue("Returned invalid stream", is.available() > 0);
-            int r = is.read(b, 0, 1024);
-            is.close();
-            StringBuffer sb = new StringBuffer(r);
-            for (int i = 0; i < r; i++) {
-                sb.append((char) (b[i] & 0xff));
-            }
-            String contents = sb.toString();
-            assertTrue("Incorrect stream read", contents.indexOf("bar") > 0);
-            // BEGIN android-added
-            jf.close();
-            // END android-added
-        } catch (Exception e) {
-            fail("Exception during test: " + e.toString());
-        }
-
-        try {
-            JarFile jf = new JarFile(localFile);
-            InputStream in = jf.getInputStream(new JarEntry("invalid"));
-            assertNull("Got stream for non-existent entry", in);
-        } catch (Exception e) {
-            fail("Exception during test 2: " + e);
-        }
-
-        try {
-            Support_Resources.copyFile(resources, null, jarName);
-            File signedFile = new File(resources, jarName);
-            JarFile jf = new JarFile(signedFile);
-            JarEntry jre = new JarEntry("foo/bar/A.class");
-            jf.getInputStream(jre);
-            // InputStream returned in any way, exception can be thrown in case
-            // of reading from this stream only.
-            // fail("Should throw ZipException");
-        } catch (ZipException ee) {
-            // expected
-        }
-
-        try {
-            Support_Resources.copyFile(resources, null, jarName);
-            File signedFile = new File(resources, jarName);
-            JarFile jf = new JarFile(signedFile);
-            JarEntry jre = new JarEntry("foo/bar/A.class");
-            jf.close();
-            jf.getInputStream(jre);
-            // InputStream returned in any way, exception can be thrown in case
-            // of reading from this stream only.
-            // The same for IOException
-            fail("Should throw IllegalStateException");
-        } catch (IllegalStateException ee) {
-            // expected
-        }
-    }
-
-    /**
-     * The jar is intact, but the entry object is modified.
-     */
-    // Regression test for issue introduced by HARMONY-4569: signed archives containing files with size 0 could not get verified.
-    public void testJarVerificationEmptyEntry() throws IOException {
-        Support_Resources.copyFile(resources, null, emptyEntryJar);
-        File f = new File(resources, emptyEntryJar);
-
-        JarFile jarFile = new JarFile(f);
-
-        ZipEntry zipEntry = jarFile.getJarEntry(emptyEntry1);
-        int res = jarFile.getInputStream(zipEntry).read(new byte[100], 0, 100);
-        assertEquals("Wrong length of empty jar entry", -1, res);
-
-        zipEntry = jarFile.getJarEntry(emptyEntry2);
-        res = jarFile.getInputStream(zipEntry).read(new byte[100], 0, 100);
-        assertEquals("Wrong length of empty jar entry", -1, res);
-
-        zipEntry = jarFile.getJarEntry(emptyEntry3);
-        res = jarFile.getInputStream(zipEntry).read();
-        assertEquals("Wrong length of empty jar entry", -1, res);
-    }
-}
diff --git a/luni/src/test/java/org/apache/harmony/archive/tests/java/util/jar/JarInputStreamTest.java b/luni/src/test/java/org/apache/harmony/archive/tests/java/util/jar/JarInputStreamTest.java
deleted file mode 100644
index b41a212..0000000
--- a/luni/src/test/java/org/apache/harmony/archive/tests/java/util/jar/JarInputStreamTest.java
+++ /dev/null
@@ -1,533 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements.  See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You 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 org.apache.harmony.archive.tests.java.util.jar;
-
-import tests.support.resource.Support_Resources;
-
-import java.io.File;
-import java.io.IOException;
-import java.io.InputStream;
-import java.net.URL;
-import java.util.Arrays;
-import java.util.HashSet;
-import java.util.Set;
-import java.util.jar.JarEntry;
-import java.util.jar.JarInputStream;
-import java.util.jar.Manifest;
-import java.util.zip.ZipEntry;
-import java.util.zip.ZipException;
-
-public class JarInputStreamTest extends junit.framework.TestCase {
-    // a 'normal' jar file
-    private String jarName;
-
-    // same as patch.jar but without a manifest file
-    private String jarName2;
-
-    private final String entryName = "foo/bar/A.class";
-
-    private static final int indexofDSA = 2;
-
-    private static final int indexofTESTCLASS = 4;
-
-    private static final int totalEntries = 4;
-
-    @Override
-    protected void setUp() {
-        jarName = Support_Resources.getURL("morestuff/hyts_patch.jar");
-        jarName2 = Support_Resources.getURL("morestuff/hyts_patch2.jar");
-    }
-
-    /**
-     * @tests java.util.jar.JarInputStream#JarInputStream(java.io.InputStream)
-     */
-    public void test_ConstructorLjava_io_InputStream() {
-        // Test for method java.util.jar.JarInputStream(java.io.InputStream)
-        InputStream is = null;
-        JarInputStream jis = null;
-        try {
-            is = new URL(jarName).openConnection().getInputStream();
-            boolean hasCorrectEntry = false;
-            jis = new JarInputStream(is);
-            assertNotNull("The jar input stream should have a manifest", jis
-                    .getManifest());
-            JarEntry je = jis.getNextJarEntry();
-            while (je != null) {
-                if (je.getName().equals(entryName)) {
-                    hasCorrectEntry = true;
-                }
-                je = jis.getNextJarEntry();
-            }
-            assertTrue(
-                    "The jar input stream does not contain the correct entries",
-                    hasCorrectEntry);
-        } catch (Exception e) {
-            fail("Exception during test: " + e.toString());
-        }
-
-        try {
-            is.close();
-            jis = new JarInputStream(is);
-            fail("IOException expected");
-        } catch (IOException ee) {
-            // expected
-        }
-    }
-
-    /**
-     * @tests java.util.jar.JarInputStream#getManifest()
-     */
-    public void test_getManifest() {
-        // Test for method java.util.jar.Manifest
-        // java.util.jar.JarInputStream.getManifest()
-        try {
-            Manifest m;
-
-            InputStream is = new URL(jarName2).openConnection()
-                    .getInputStream();
-            JarInputStream jis = new JarInputStream(is);
-            m = jis.getManifest();
-            assertNull("The jar input stream should not have a manifest", m);
-
-            is = new URL(jarName).openConnection().getInputStream();
-            jis = new JarInputStream(is);
-            m = jis.getManifest();
-            assertNotNull("The jar input stream should have a manifest", m);
-        } catch (Exception e) {
-            fail("Exception during test: " + e.toString());
-        }
-
-    }
-
-    /**
-     * @tests java.util.jar.JarInputStream#getNextJarEntry()
-     */
-    public void test_getNextJarEntry() throws Exception {
-        final Set<String> desired = new HashSet<String>(Arrays
-                .asList(new String[] {
-                        "foo/", "foo/bar/", "foo/bar/A.class", "Blah.txt"}));
-        Set<String> actual = new HashSet<String>();
-        InputStream is = new URL(jarName).openConnection().getInputStream();
-        JarInputStream jis = new JarInputStream(is);
-        JarEntry je = jis.getNextJarEntry();
-        while (je != null) {
-            actual.add(je.toString());
-            je = jis.getNextJarEntry();
-        }
-        assertEquals(actual, desired);
-        jis.close();
-
-        try {
-            jis.getNextJarEntry();
-            fail("IOException expected");
-        } catch (IOException ee) {
-            // expected
-        }
-
-        File resources = Support_Resources.createTempFolder();
-        Support_Resources.copyFile(resources, null, "Broken_entry.jar");
-        is = Support_Resources.getStream("Broken_entry.jar");
-        jis = new JarInputStream(is, false);
-        jis.getNextJarEntry();
-        try {
-            jis.getNextJarEntry();
-            fail("ZipException expected");
-        } catch (ZipException ee) {
-            // expected
-        }
-    }
-
-    public void test_getNextJarEntry_Ex() throws Exception {
-        final Set<String> desired = new HashSet<String>(Arrays
-                .asList("foo/", "foo/bar/", "foo/bar/A.class", "Blah.txt"));
-        Set<String> actual = new HashSet<String>();
-        InputStream is = new URL(jarName).openConnection().getInputStream();
-        JarInputStream jis = new JarInputStream(is);
-        JarEntry je = jis.getNextJarEntry();
-        while (je != null) {
-            actual.add(je.toString());
-            je = jis.getNextJarEntry();
-        }
-        assertEquals(actual, desired);
-        jis.close();
-
-        try {
-            jis.getNextJarEntry();
-            fail("IOException expected");
-        } catch (IOException ee) {
-            // expected
-        }
-
-        File resources = Support_Resources.createTempFolder();
-        Support_Resources.copyFile(resources, null, "Broken_entry.jar");
-        is = Support_Resources.getStream("Broken_entry.jar");
-        jis = new JarInputStream(is, false);
-        jis.getNextJarEntry();
-        try {
-            jis.getNextJarEntry();
-            fail("ZipException expected");
-        } catch (ZipException ee) {
-            // expected
-        }
-    }
-
-    public void test_JarInputStream_Integrate_Jar_getNextEntry()
-            throws IOException {
-        String intJarName = Support_Resources.getURL("Integrate.jar");
-        InputStream is = new URL(intJarName).openConnection().getInputStream();
-        JarInputStream jin = new JarInputStream(is, true);
-        ZipEntry entry = null;
-        int count = 0;
-        while (count == 0 || entry != null) {
-            count++;
-            entry = jin.getNextEntry();
-        }
-        assertEquals(totalEntries + 1, count);
-        jin.close();
-    }
-
-    public void test_JarInputStream_Modified_Class_getNextEntry()
-            throws IOException {
-        String modJarName = Support_Resources.getURL("Modified_Class.jar");
-        InputStream is = new URL(modJarName).openConnection().getInputStream();
-        JarInputStream jin = new JarInputStream(is, true);
-        ZipEntry zipEntry = null;
-
-        int count = 0;
-        while (count == 0 || zipEntry != null) {
-            count++;
-            try {
-                zipEntry = jin.getNextEntry();
-                if (count == indexofTESTCLASS + 1) {
-                    fail("Should throw Security Exception");
-                }
-            } catch (SecurityException e) {
-                if (count != indexofTESTCLASS + 1) {
-                    throw e;
-                }
-
-            }
-        }
-        assertEquals(totalEntries + 2, count);
-        jin.close();
-    }
-
-    public void test_JarInputStream_Modified_Manifest_MainAttributes_getNextEntry()
-            throws IOException {
-        String modJarName = Support_Resources.getURL("Modified_Manifest_MainAttributes.jar");
-        InputStream is = new URL(modJarName).openConnection()
-                .getInputStream();
-        JarInputStream jin = new JarInputStream(is, true);
-
-        assertEquals("META-INF/TESTROOT.SF", jin.getNextEntry().getName());
-        assertEquals("META-INF/TESTROOT.DSA", jin.getNextEntry().getName());
-        try {
-            jin.getNextEntry();
-            fail();
-        } catch (SecurityException expected) {
-        }
-        assertEquals("META-INF/", jin.getNextEntry().getName());
-        assertEquals("Test.class", jin.getNextEntry().getName());
-        assertNull(jin.getNextEntry());
-        jin.close();
-    }
-
-    public void test_JarInputStream_Modified_Manifest_EntryAttributes_getNextEntry()
-            throws IOException {
-        String modJarName = Support_Resources
-                .getURL("Modified_Manifest_EntryAttributes.jar");
-        InputStream is = new URL(modJarName).openConnection().getInputStream();
-        JarInputStream jin = new JarInputStream(is, true);
-        ZipEntry zipEntry = null;
-
-        int count = 0;
-        while (count == 0 || zipEntry != null) {
-            count++;
-            try {
-                zipEntry = jin.getNextEntry();
-                if (count == indexofDSA + 1) {
-                    fail("Should throw Security Exception");
-                }
-            } catch (SecurityException e) {
-                if (count != indexofDSA + 1) {
-                    throw e;
-                }
-            }
-        }
-        assertEquals(totalEntries + 2, count);
-        jin.close();
-    }
-
-    public void test_JarInputStream_Modified_SF_EntryAttributes_getNextEntry()
-            throws IOException {
-        String modJarName = Support_Resources
-                .getURL("Modified_SF_EntryAttributes.jar");
-        InputStream is = new URL(modJarName).openConnection().getInputStream();
-        JarInputStream jin = new JarInputStream(is, true);
-        ZipEntry zipEntry = null;
-
-        int count = 0;
-        while (count == 0 || zipEntry != null) {
-            count++;
-            try {
-                zipEntry = jin.getNextEntry();
-                if (count == indexofDSA + 1) {
-                    fail("Should throw Security Exception");
-                }
-            } catch (SecurityException e) {
-                if (count != indexofDSA + 1) {
-                    throw e;
-                }
-            }
-        }
-        assertEquals(totalEntries + 2, count);
-        jin.close();
-    }
-
-    public void test_JarInputStream_Modified_Class_read() throws IOException {
-        String modJarName = Support_Resources.getURL("Modified_Class.jar");
-        InputStream is = new URL(modJarName).openConnection().getInputStream();
-        JarInputStream jin = new JarInputStream(is, true);
-        int count = 0;
-        ZipEntry zipEntry = null;
-        while (count == 0 || zipEntry != null) {
-            count++;
-            zipEntry = jin.getNextEntry();
-            byte[] buffer = new byte[1024];
-            try {
-                int length = 0;
-                while (length >= 0) {
-                    length = jin.read(buffer);
-                }
-                if (count == indexofTESTCLASS) {
-                    fail("Should throw Security Exception");
-                }
-            } catch (SecurityException e) {
-                if (count < indexofTESTCLASS) {
-                    throw e;
-                }
-            }
-        }
-        assertEquals(totalEntries + 1, count);
-        jin.close();
-    }
-
-    public void test_Integrate_Jar_read() throws IOException {
-        String intJarName = Support_Resources.getURL("Integrate.jar");
-        InputStream is = new URL(intJarName).openConnection().getInputStream();
-        JarInputStream jin = new JarInputStream(is, true);
-        int count = 0;
-        ZipEntry zipEntry = null;
-        while (count == 0 || zipEntry != null) {
-            count++;
-            zipEntry = jin.getNextEntry();
-            byte[] buffer = new byte[1024];
-            int length = 0;
-            while (length >= 0) {
-                length = jin.read(buffer);
-            }
-
-        }
-        assertEquals(totalEntries + 1, count);
-        jin.close();
-    }
-
-    public void test_JarInputStream_Modified_Manifest_MainAttributes_read()
-            throws IOException {
-        String modJarName = Support_Resources
-                .getURL("Modified_Manifest_MainAttributes.jar");
-        InputStream is = new URL(modJarName).openConnection().getInputStream();
-        JarInputStream jin = new JarInputStream(is, true);
-        int count = 0;
-        ZipEntry zipEntry = null;
-        while (count == 0 || zipEntry != null) {
-            count++;
-            zipEntry = jin.getNextEntry();
-            byte[] buffer = new byte[1024];
-            try {
-                int length = 0;
-                while (length >= 0) {
-                    length = jin.read(buffer);
-                }
-                if (count == indexofDSA) {
-                    fail("Should throw Security Exception");
-                }
-            } catch (SecurityException e) {
-                if (count != indexofDSA) {
-                    throw e;
-                }
-            }
-        }
-        assertEquals(totalEntries + 1, count);
-        jin.close();
-    }
-
-    public void test_JarInputStream_Modified_SF_EntryAttributes_read()
-            throws IOException {
-        String modJarName = Support_Resources
-                .getURL("Modified_SF_EntryAttributes.jar");
-        InputStream is = new URL(modJarName).openConnection().getInputStream();
-        JarInputStream jin = new JarInputStream(is, true);
-        int count = 0;
-        ZipEntry zipEntry = null;
-        while (count == 0 || zipEntry != null) {
-            count++;
-            zipEntry = jin.getNextEntry();
-            byte[] buffer = new byte[1024];
-            try {
-                int length = 0;
-                while (length >= 0) {
-                    length = jin.read(buffer);
-                }
-                if (count == indexofDSA) {
-                    fail("Should throw Security Exception");
-                }
-            } catch (SecurityException e) {
-                if (count != indexofDSA) {
-                    throw e;
-                }
-            }
-        }
-        assertEquals(totalEntries + 1, count);
-        jin.close();
-    }
-
-    public void test_ConstructorLjava_io_InputStreamZ() {
-        // Test for method java.util.jar.JarInputStream(java.io.InputStream)
-        InputStream is = null;
-        JarInputStream jis = null;
-        try {
-            is = new URL(jarName).openConnection().getInputStream();
-            boolean hasCorrectEntry = false;
-            jis = new JarInputStream(is, true);
-            assertNotNull("The jar input stream should have a manifest", jis
-                    .getManifest());
-            JarEntry je = jis.getNextJarEntry();
-            while (je != null) {
-                if (je.getName().equals(entryName)) {
-                    hasCorrectEntry = true;
-                }
-                je = jis.getNextJarEntry();
-            }
-            assertTrue(
-                    "The jar input stream does not contain the correct entries",
-                    hasCorrectEntry);
-        } catch (Exception e) {
-            fail("Exception during test: " + e.toString());
-        }
-
-        try {
-            is.close();
-            jis = new JarInputStream(is, false);
-            fail("IOException expected");
-        } catch (IOException ee) {
-            // expected
-        }
-    }
-
-    public void test_closeAfterException() throws Exception {
-        File resources = Support_Resources.createTempFolder();
-        Support_Resources.copyFile(resources, null, "Broken_entry.jar");
-        InputStream is = Support_Resources.getStream("Broken_entry.jar");
-        JarInputStream jis = new JarInputStream(is, false);
-        jis.getNextEntry();
-        try {
-            jis.getNextEntry();
-            fail("ZipException expected");
-        } catch (ZipException ee) {
-            // expected
-        }
-        jis.close();
-        try {
-            jis.getNextEntry();
-            fail("IOException expected");
-        } catch (IOException ee) {
-            // expected
-        }
-    }
-
-    public void test_getNextEntry() throws Exception {
-        File resources = Support_Resources.createTempFolder();
-        Support_Resources.copyFile(resources, null, "Broken_entry.jar");
-        InputStream is = Support_Resources.getStream("Broken_entry.jar");
-        JarInputStream jis = new JarInputStream(is, false);
-        jis.getNextEntry();
-        try {
-            jis.getNextEntry();
-            fail("ZipException expected");
-        } catch (ZipException ee) {
-            // expected
-        }
-
-        try {
-            jis.close();  // Android throws exception here, already!
-            jis.getNextEntry();  // But RI here, only!
-            fail("IOException expected");
-        } catch (IOException ee) {
-            // expected
-        }
-    }
-
-    class Mock_JarInputStream extends JarInputStream {
-
-        public Mock_JarInputStream(InputStream in) throws IOException {
-            super(in);
-        }
-
-        public ZipEntry createZipEntry(String str) {
-            return super.createZipEntry(str);
-        }
-    }
-
-    public void test_createZipEntryLjava_lang_String() throws Exception {
-        File resources = Support_Resources.createTempFolder();
-        Support_Resources.copyFile(resources, null, "Broken_entry.jar");
-        InputStream is = Support_Resources.getStream("Broken_entry.jar");
-        Mock_JarInputStream mjis = new Mock_JarInputStream(is);
-        assertNotNull(mjis.createZipEntry("New entry"));
-    }
-
-    public void test_read$ZII() throws Exception {
-        File resources = Support_Resources.createTempFolder();
-        Support_Resources.copyFile(resources, null, "Broken_entry_data.jar");
-        InputStream is = Support_Resources.getStream("Broken_entry_data.jar");
-        JarInputStream jis = new JarInputStream(is, true);
-        byte b[] = new byte[100];
-
-        jis.getNextEntry();
-        jis.read(b, 0, 100);
-        jis.getNextEntry();
-        jis.getNextEntry();
-        jis.getNextEntry();
-
-        try {
-            jis.read(b, 0, 100);
-            fail("ZipException expected");
-        } catch (ZipException ee) {
-            // expected
-        }
-
-        try {
-            jis.close();  // Android throws exception here, already!
-            jis.read(b, 0, 100);  // But RI here, only!
-            fail("IOException expected");
-        } catch (IOException ee) {
-            // expected
-        }
-    }
-}
diff --git a/luni/src/test/java/org/apache/harmony/archive/tests/java/util/jar/JarOutputStreamTest.java b/luni/src/test/java/org/apache/harmony/archive/tests/java/util/jar/JarOutputStreamTest.java
deleted file mode 100644
index 678ec73..0000000
--- a/luni/src/test/java/org/apache/harmony/archive/tests/java/util/jar/JarOutputStreamTest.java
+++ /dev/null
@@ -1,180 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements.  See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You 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 org.apache.harmony.archive.tests.java.util.jar;
-
-import java.io.File;
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.OutputStream;
-import java.net.URL;
-import java.util.jar.Attributes;
-import java.util.jar.JarEntry;
-import java.util.jar.JarOutputStream;
-import java.util.jar.Manifest;
-import java.util.zip.ZipEntry;
-
-import tests.support.resource.Support_Resources;
-
-public class JarOutputStreamTest extends junit.framework.TestCase {
-
-    /**
-     * @tests java.util.jar.JarOutputStream#putNextEntry(java.util.zip.ZipEntry)
-     */
-    public void test_putNextEntryLjava_util_zip_ZipEntry() throws Exception {
-        // testClass file`s actual extension is .class, since having .class
-        // extension files in source dir causes
-        // problems on eclipse, the extension is changed into .ser or it can be
-        // anything. The file is being
-        // read by inputstream and being written to other file,
-        // as long as the content of the file is not changed, the extension does
-        // not matter
-        final String testClass = "hyts_mainClass.ser";
-        final String entryName = "foo/bar/execjartest/MainClass.class";
-
-        // test whether specifying the main class in the manifest
-        // works using either /'s or .'s as a separator
-        final String[] manifestMain = {
-                "foo.bar.execjartest.MainClass",
-                "foo/bar/execjartest/MainClass"};
-
-        for (String element : manifestMain) {
-
-            // create the manifest
-            Manifest newman = new Manifest();
-            Attributes att = newman.getMainAttributes();
-            att.put(Attributes.Name.MANIFEST_VERSION, "1.0");
-            att.put(Attributes.Name.MAIN_CLASS, element);
-
-            File outputJar = null;
-            JarOutputStream jout = null;
-
-            // open the output jarfile
-            outputJar = File.createTempFile("hyts_", ".jar");
-            jout = new JarOutputStream(new FileOutputStream(outputJar),
-                    newman);
-            jout.putNextEntry(new JarEntry(entryName));
-
-            File resources = Support_Resources.createTempFolder();
-
-            // read in the class file, and output it to the jar
-            Support_Resources.copyFile(resources, null, testClass);
-            URL jarURL = new URL((new File(resources, testClass)).toURL()
-                    .toString());
-            InputStream jis = jarURL.openStream();
-
-            byte[] bytes = new byte[1024];
-            int len;
-            while ((len = jis.read(bytes)) != -1) {
-                jout.write(bytes, 0, len);
-            }
-
-            jout.flush();
-            jout.close();
-            jis.close();
-
-            String res = null;
-            // set up the VM parameters
-            String[] args = new String[2];
-            args[0] = "-jar";
-            args[1] = outputJar.getAbsolutePath();
-
-// It's not that simple to execute a JAR against Dalvik VM (see DalvikExecTest):
-//
-//            try {
-//                // execute the JAR and read the result
-//                res = Support_Exec.execJava(args, null, true);
-//            } catch (Exception e) {
-//                fail("Exception executing test JAR: " + e);
-//            }
-//
-//            assertTrue("Error executing JAR test on: " + element
-//                    + ". Result returned was incorrect.", res
-//                    .startsWith("TEST"));
-            outputJar.delete();
-
-            try {
-                // open the output jarfile
-                outputJar = File.createTempFile("hyts_", ".jar");
-                OutputStream os = new FileOutputStream(outputJar);
-                jout = new JarOutputStream(os, newman);
-                os.close();
-                jout.putNextEntry(new JarEntry(entryName));
-                fail("IOException expected");
-            } catch (IOException e) {
-                // expected
-            }
-        }
-    }
-
-    public void test_JarOutputStreamLjava_io_OutputStreamLjava_util_jar_Manifest()
-            throws IOException {
-        File fooJar = File.createTempFile("hyts_", ".jar");
-        File barZip = File.createTempFile("hyts_", ".zip");
-
-        FileOutputStream fos = new FileOutputStream(fooJar);
-
-        Manifest man = new Manifest();
-        Attributes att = man.getMainAttributes();
-        att.put(Attributes.Name.MANIFEST_VERSION, "1.0");
-        att.put(Attributes.Name.MAIN_CLASS, "foo.bar.execjartest.Foo");
-        att.put(Attributes.Name.CLASS_PATH, barZip.getName());
-
-        fos.close();
-        try {
-            JarOutputStream joutFoo = new JarOutputStream(fos, man);
-            fail("IOException expected");
-        } catch (IOException ee) {
-            // expected
-        }
-    }
-
-    public void test_JarOutputStreamLjava_io_OutputStream() throws IOException {
-        File fooJar = File.createTempFile("hyts_", ".jar");
-
-        FileOutputStream fos = new FileOutputStream(fooJar);
-        ZipEntry ze = new ZipEntry("Test");
-
-        try {
-            JarOutputStream joutFoo = new JarOutputStream(fos);
-            joutFoo.putNextEntry(ze);
-            joutFoo.write(33);
-        } catch (IOException ee) {
-            fail("IOException is not expected");
-        }
-
-        fos.close();
-        fooJar.delete();
-        try {
-            JarOutputStream joutFoo = new JarOutputStream(fos);
-            joutFoo.putNextEntry(ze);
-            fail("IOException expected");
-        } catch (IOException ee) {
-            // expected
-        }
-    }
-
-    @Override
-    protected void setUp() {
-    }
-
-    @Override
-    protected void tearDown() {
-    }
-
-}
diff --git a/luni/src/test/java/org/apache/harmony/archive/tests/java/util/jar/ManifestTest.java b/luni/src/test/java/org/apache/harmony/archive/tests/java/util/jar/ManifestTest.java
deleted file mode 100644
index aafda90..0000000
--- a/luni/src/test/java/org/apache/harmony/archive/tests/java/util/jar/ManifestTest.java
+++ /dev/null
@@ -1,500 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements.  See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You 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 org.apache.harmony.archive.tests.java.util.jar;
-
-import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
-import java.io.File;
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.net.URL;
-import java.net.MalformedURLException;
-import java.util.Map;
-import java.util.jar.Attributes;
-import java.util.jar.JarFile;
-import java.util.jar.Manifest;
-
-import junit.framework.TestCase;
-
-import tests.support.resource.Support_Resources;
-
-public class ManifestTest extends TestCase {
-
-    private final String jarName = "hyts_patch.jar";
-
-    private final String attJarName = "hyts_att.jar";
-
-    private Manifest m;
-
-    private Manifest m2;
-
-    private final String ATT_ENTRY_NAME = "HasAttributes.txt";
-
-    private final String MANIFEST_NAME = "manifest/hyts_MANIFEST.MF";
-
-    private File resources;
-
-    @Override
-    protected void setUp() {
-        resources = Support_Resources.createTempFolder();
-        try {
-            Support_Resources.copyFile(resources, null, jarName);
-            JarFile jarFile = new JarFile(new File(resources, jarName));
-            m = jarFile.getManifest();
-            jarFile.close();
-            Support_Resources.copyFile(resources, null, attJarName);
-            jarFile = new JarFile(new File(resources, attJarName));
-            m2 = jarFile.getManifest();
-            jarFile.close();
-        } catch (Exception e) {
-            fail("Exception during setup: " + e.toString());
-        }
-    }
-
-    private Manifest getManifest(String fileName) {
-        try {
-            Support_Resources.copyFile(resources, null, fileName);
-            JarFile jarFile = new JarFile(new File(resources, fileName));
-            Manifest m = jarFile.getManifest();
-            jarFile.close();
-            return m;
-        } catch (Exception e) {
-            fail("Exception during setup: " + e.toString());
-            return null;
-        }
-    }
-
-    /**
-     * @tests java.util.jar.Manifest#Manifest()
-     */
-    public void test_Constructor() {
-        // Test for method java.util.jar.Manifest()
-        Manifest emptyManifest = new Manifest();
-        assertTrue("Should have no entries", emptyManifest.getEntries()
-                .isEmpty());
-        assertTrue("Should have no main attributes", emptyManifest
-                .getMainAttributes().isEmpty());
-    }
-
-    /**
-     * @tests java.util.jar.Manifest#Manifest(java.util.jar.Manifest)
-     */
-    public void testCopyingConstructor() throws IOException {
-        Manifest firstManifest = new Manifest(new URL(Support_Resources
-                .getURL(MANIFEST_NAME)).openStream());
-        Manifest secondManifest = new Manifest(firstManifest);
-        assertEquals(firstManifest, secondManifest);
-    }
-
-    /**
-     * @tests java.util.jar.Manifest#Manifest(Manifest)
-     */
-    public void test_ConstructorLjava_util_jar_Manifest() {
-        // Test for method java.util.jar.Manifest()
-        Manifest emptyManifest = new Manifest();
-        Manifest emptyClone = new Manifest(emptyManifest);
-        assertTrue("Should have no entries", emptyClone.getEntries().isEmpty());
-        assertTrue("Should have no main attributes", emptyClone
-                .getMainAttributes().isEmpty());
-        assertEquals(emptyClone, emptyManifest);
-        assertEquals(emptyClone, emptyManifest.clone());
-    }
-
-    private void assertAttribute(Attributes attr, String name, String value) {
-        assertEquals("Incorrect " + name, value, attr.getValue(name));
-    }
-
-    private void checkManifest(Manifest manifest) {
-        Attributes main = manifest.getMainAttributes();
-        assertAttribute(main, "Bundle-Name", "ClientSupport");
-        assertAttribute(main, "Bundle-Description",
-                "Provides SessionService, AuthenticationService. Extends RegistryService.");
-        assertAttribute(main, "Bundle-Activator",
-                "com.ibm.ive.eccomm.client.support.ClientSupportActivator");
-        assertAttribute(
-                main,
-                "Import-Package",
-                "com.ibm.ive.eccomm.client.services.log,com.ibm.ive.eccomm.client.services.registry,com.ibm.ive.eccomm.service.registry; specification-version=1.0.0,com.ibm.ive.eccomm.service.session; specification-version=1.0.0,com.ibm.ive.eccomm.service.framework; specification-version=1.2.0,org.osgi.framework; specification-version=1.0.0,org.osgi.service.log; specification-version=1.0.0,com.ibm.ive.eccomm.flash; specification-version=1.2.0,com.ibm.ive.eccomm.client.xml,com.ibm.ive.eccomm.client.http.common,com.ibm.ive.eccomm.client.http.client");
-        assertAttribute(
-                main,
-                "Import-Service",
-                "org.osgi.service.log.LogReaderServiceorg.osgi.service.log.LogService,com.ibm.ive.eccomm.service.registry.RegistryService");
-        assertAttribute(
-                main,
-                "Export-Package",
-                "com.ibm.ive.eccomm.client.services.authentication; specification-version=1.0.0,com.ibm.ive.eccomm.service.authentication; specification-version=1.0.0,com.ibm.ive.eccomm.common; specification-version=1.0.0,com.ibm.ive.eccomm.client.services.registry.store; specification-version=1.0.0");
-        assertAttribute(
-                main,
-                "Export-Service",
-                "com.ibm.ive.eccomm.service.authentication.AuthenticationService,com.ibm.ive.eccomm.service.session.SessionService");
-        assertAttribute(main, "Bundle-Vendor", "IBM");
-        assertAttribute(main, "Bundle-Version", "1.2.0");
-    }
-
-    /**
-     * @tests java.util.jar.Manifest#Manifest(java.io.InputStream)
-     */
-    public void test_ConstructorLjava_io_InputStream() throws IOException {
-        Manifest m = getManifest(attJarName);
-        ByteArrayOutputStream baos = new ByteArrayOutputStream();
-        m.write(baos);
-        InputStream is = new ByteArrayInputStream(baos.toByteArray());
-        Manifest mCopy = new Manifest(is);
-        assertEquals(m, mCopy);
-
-        Manifest manifest = new Manifest(new URL(Support_Resources
-                .getURL(MANIFEST_NAME)).openStream());
-        checkManifest(manifest);
-
-        // regression test for HARMONY-5424
-        String manifestContent = "Manifest-Version: 1.0\nCreated-By: Apache\nPackage: \nBuild-Jdk: 1.4.1_01\n\n"
-                + "Name: \nSpecification-Title: foo\nSpecification-Version: 1.0\nSpecification-Vendor: \n"
-                + "Implementation-Title: \nImplementation-Version: 1.0\nImplementation-Vendor: \n\n";
-        ByteArrayInputStream bis = new ByteArrayInputStream(manifestContent
-                .getBytes("ISO-8859-1"));
-
-
-        Manifest mf = new Manifest(bis);
-        assertEquals("Should be 4 main attributes", 4, mf.getMainAttributes()
-                .size());
-
-        Map<String, Attributes> entries = mf.getEntries();
-        assertEquals("Should be one named entry", 1, entries.size());
-
-        Attributes namedEntryAttributes = (Attributes) (entries.get(""));
-        assertEquals("Should be 6 named entry attributes", 6,
-                namedEntryAttributes.size());
-    }
-
-    /**
-     * @tests java.util.jar.Manifest#clear()
-     */
-    public void test_clear() {
-        m2.clear();
-        assertTrue("Should have no entries", m2.getEntries().isEmpty());
-        assertTrue("Should have no main attributes", m2.getMainAttributes()
-                .isEmpty());
-    }
-
-    public void test_clone() throws IOException {
-        Manifest emptyManifest = new Manifest();
-        Manifest emptyClone = (Manifest) emptyManifest.clone();
-        assertTrue("Should have no entries", emptyClone.getEntries().isEmpty());
-        assertTrue("Should have no main attributes", emptyClone
-                .getMainAttributes().isEmpty());
-        assertEquals(emptyClone, emptyManifest);
-        assertEquals(emptyManifest.clone().getClass().getName(),
-                "java.util.jar.Manifest");
-
-        Manifest manifest = new Manifest(new URL(Support_Resources
-                .getURL("manifest/hyts_MANIFEST.MF")).openStream());
-        Manifest manifestClone = (Manifest) manifest.clone();
-        manifestClone.getMainAttributes();
-        checkManifest(manifestClone);
-    }
-
-    public void test_equals() throws IOException {
-        Manifest manifest1 = new Manifest(new URL(Support_Resources.getURL(
-                "manifest/hyts_MANIFEST.MF")).openStream());
-        Manifest manifest2 = new Manifest(new URL(Support_Resources.getURL(
-                "manifest/hyts_MANIFEST.MF")).openStream());
-        Manifest manifest3 = new Manifest();
-
-        assertTrue(manifest1.equals(manifest1));
-        assertTrue(manifest1.equals(manifest2));
-        assertFalse(manifest1.equals(manifest3));
-        assertFalse(manifest1.equals(this));
-    }
-
-    public void test_hashCode() throws IOException {
-        Manifest manifest1 = new Manifest(new URL(Support_Resources
-                .getURL("manifest/hyts_MANIFEST.MF")).openStream());
-        Manifest manifest2 = new Manifest();
-        assertEquals(manifest1.hashCode(), manifest1.hashCode());
-        assertNotSame(manifest1.hashCode(), manifest2.hashCode());
-    }
-
-	/**
-	 * @tests java.util.jar.Manifest#getAttributes(java.lang.String)
-	 */
-	public void test_getAttributesLjava_lang_String() {
-		assertNull("Should not exist",
-				m2.getAttributes("Doesn't Exist"));
-		assertEquals("Should exist", "OK", m2.getAttributes("HasAttributes.txt").get(
-				new Attributes.Name("MyAttribute")));
-	}
-
-	/**
-	 * @tests java.util.jar.Manifest#getEntries()
-	 */
-	public void test_getEntries() {
-		Map<String, Attributes> myMap = m2.getEntries();
-		assertNull("Shouldn't exist", myMap.get("Doesn't exist"));
-		assertEquals("Should exist",
-				"OK", myMap.get("HasAttributes.txt").get(
-						new Attributes.Name("MyAttribute")));
-	}
-
-	/**
-	 * @tests java.util.jar.Manifest#getMainAttributes()
-	 */
-	public void test_getMainAttributes() {
-		// Test for method java.util.jar.Attributes
-		// java.util.jar.Manifest.getMainAttributes()
-		Attributes a = m.getMainAttributes();
-		assertEquals("Manifest_Version should return 1.0", "1.0", a.get(
-				Attributes.Name.MANIFEST_VERSION));
-	}
-
-    public void test_writeLjava_io_OutputStream() throws IOException {
-        byte b[] = null;
-        Manifest manifest1 = null;
-        Manifest manifest2 = null;
-        InputStream is = null;
-        try {
-            manifest1 = new Manifest(new URL(Support_Resources
-                    .getURL("manifest/hyts_MANIFEST.MF")).openStream());
-        } catch (MalformedURLException e) {
-            fail("Malformed URL");
-        }
-
-        ByteArrayOutputStream baos = new ByteArrayOutputStream();
-
-        manifest1.write(baos);
-
-        b = baos.toByteArray();
-
-        File f = File.createTempFile("111", "111");
-        FileOutputStream fos = new FileOutputStream(f);
-        fos.close();
-        try {
-            manifest1.write(fos);
-            fail("IOException expected");
-        } catch (IOException e) {
-            // expected
-        }
-        f.delete();
-
-        ByteArrayInputStream bais = new ByteArrayInputStream(b);
-
-        try {
-            manifest2 = new Manifest(bais);
-        } catch (MalformedURLException e) {
-            fail("Malformed URL");
-        }
-
-        assertTrue(manifest1.equals(manifest2));
-    }
-
-    /**
-     * Ensures compatibility with manifests produced by gcc.
-     *
-     * @see <a
-     *      href="http://issues.apache.org/jira/browse/HARMONY-5662">HARMONY-5662</a>
-     */
-    public void testNul() throws IOException {
-        String manifestContent =
-                "Manifest-Version: 1.0\nCreated-By: nasty gcc tool\n\n\0";
-
-        byte[] bytes = manifestContent.getBytes("ISO-8859-1");
-        new Manifest(new ByteArrayInputStream(bytes)); // the last NUL is ok
-
-        bytes[bytes.length - 1] = 26;
-        new Manifest(new ByteArrayInputStream(bytes)); // the last EOF is ok
-
-        bytes[bytes.length - 1] = 'A'; // the last line ignored
-        new Manifest(new ByteArrayInputStream(bytes));
-
-        bytes[2] = 0; // NUL char in Manifest
-        try {
-            new Manifest(new ByteArrayInputStream(bytes));
-            fail("IOException expected");
-        } catch (IOException e) {
-            // desired
-        }
-    }
-
-    public void testDecoding() throws IOException {
-        Manifest m = getManifest(attJarName);
-        final byte[] bVendor = new byte[] { (byte) 0xd0, (byte) 0x9C,
-                (byte) 0xd0, (byte) 0xb8, (byte) 0xd0, (byte) 0xbb,
-                (byte) 0xd0, (byte) 0xb0, (byte) 0xd1, (byte) 0x8f, ' ',
-                (byte) 0xd0, (byte) 0xb4, (byte) 0xd0, (byte) 0xbe,
-                (byte) 0xd1, (byte) 0x87, (byte) 0xd1, (byte) 0x83,
-                (byte) 0xd0, (byte) 0xbd, (byte) 0xd1, (byte) 0x8C,
-                (byte) 0xd0, (byte) 0xba, (byte) 0xd0, (byte) 0xb0, ' ',
-                (byte) 0xd0, (byte) 0x9C, (byte) 0xd0, (byte) 0xb0,
-                (byte) 0xd1, (byte) 0x88, (byte) 0xd0, (byte) 0xb0 };
-
-        final byte[] bSpec = new byte[] { (byte) 0xe1, (byte) 0x88,
-                (byte) 0xb0, (byte) 0xe1, (byte) 0x88, (byte) 0x8b,
-                (byte) 0xe1, (byte) 0x88, (byte) 0x9d, ' ', (byte) 0xe1,
-                (byte) 0x9a, (byte) 0xa0, (byte) 0xe1, (byte) 0x9a,
-                (byte) 0xb1, (byte) 0xe1, (byte) 0x9b, (byte) 0x81,
-                (byte) 0xe1, (byte) 0x9a, (byte) 0xa6, ' ', (byte) 0xd8,
-                (byte) 0xb3, (byte) 0xd9, (byte) 0x84, (byte) 0xd8,
-                (byte) 0xa7, (byte) 0xd9, (byte) 0x85, ' ', (byte) 0xd8,
-                (byte) 0xb9, (byte) 0xd8, (byte) 0xb3, (byte) 0xd9,
-                (byte) 0x84, (byte) 0xd8, (byte) 0xa7, (byte) 0xd9,
-                (byte) 0x85, (byte) 0xd8, (byte) 0xa9, ' ', (byte) 0xdc,
-                (byte) 0xab, (byte) 0xdc, (byte) 0xa0, (byte) 0xdc,
-                (byte) 0xa1, (byte) 0xdc, (byte) 0x90, ' ', (byte) 0xe0,
-                (byte) 0xa6, (byte) 0xb6, (byte) 0xe0, (byte) 0xa6,
-                (byte) 0xbe, (byte) 0xe0, (byte) 0xa6, (byte) 0xa8,
-                (byte) 0xe0, (byte) 0xa7, (byte) 0x8d, (byte) 0xe0,
-                (byte) 0xa6, (byte) 0xa4, (byte) 0xe0, (byte) 0xa6,
-                (byte) 0xbf, ' ', (byte) 0xd0, (byte) 0xa0, (byte) 0xd0,
-                (byte) 0xb5, (byte) 0xd0, (byte) 0xba, (byte) 0xd1,
-                (byte) 0x8a, (byte) 0xd0, (byte) 0xb5, (byte) 0xd0,
-                (byte) 0xbb, ' ', (byte) 0xd0, (byte) 0x9c, (byte) 0xd0,
-                (byte) 0xb8, (byte) 0xd1, (byte) 0x80, ' ', (byte) 0xe0,
-                (byte) 0xa6, (byte) 0xb6, (byte) 0xe0, (byte) 0xa6,
-                (byte) 0xbe, (byte) 0xe0, (byte) 0xa6, (byte) 0xa8,
-                (byte) 0xe0, (byte) 0xa7, (byte) 0x8d, (byte) 0xe0,
-                (byte) 0xa6, (byte) 0xa4, (byte) 0xe0, (byte) 0xa6,
-                (byte) 0xbf, ' ', (byte) 0xe0, (byte) 0xbd, (byte) 0x9e,
-                (byte) 0xe0, (byte) 0xbd, (byte) 0xb2, (byte) 0xe0,
-                (byte) 0xbc, (byte) 0x8b, (byte) 0xe0, (byte) 0xbd,
-                (byte) 0x96, (byte) 0xe0, (byte) 0xbd, (byte) 0x91,
-                (byte) 0xe0, (byte) 0xbd, (byte) 0xba, ' ', (byte) 0xd0,
-                (byte) 0x9c, (byte) 0xd0, (byte) 0xb0, (byte) 0xd1,
-                (byte) 0x88, (byte) 0xd0, (byte) 0xb0, (byte) 0xd1,
-                (byte) 0x80, ' ', (byte) 0xe1, (byte) 0x8f, (byte) 0x99,
-                (byte) 0xe1, (byte) 0x8e, (byte) 0xaf, (byte) 0xe1,
-                (byte) 0x8f, (byte) 0xb1, ' ', (byte) 0xcf, (byte) 0xa8,
-                (byte) 0xce, (byte) 0xb9, (byte) 0xcf, (byte) 0x81,
-                (byte) 0xce, (byte) 0xb7, (byte) 0xce, (byte) 0xbd,
-                (byte) 0xce, (byte) 0xb7, ' ', (byte) 0xde, (byte) 0x90,
-                (byte) 0xde, (byte) 0xaa, (byte) 0xde, (byte) 0x85,
-                (byte) 0xde, (byte) 0xa6, ' ', (byte) 0xe0, (byte) 0xbd,
-                (byte) 0x82, (byte) 0xe0, (byte) 0xbd, (byte) 0x9e,
-                (byte) 0xe0, (byte) 0xbd, (byte) 0xb2, (byte) 0xe0,
-                (byte) 0xbc, (byte) 0x8b, (byte) 0xe0, (byte) 0xbd,
-                (byte) 0x96, (byte) 0xe0, (byte) 0xbd, (byte) 0x91,
-                (byte) 0xe0, (byte) 0xbd, (byte) 0xba, ' ', (byte) 0xce,
-                (byte) 0x95, (byte) 0xce, (byte) 0xb9, (byte) 0xcf,
-                (byte) 0x81, (byte) 0xce, (byte) 0xae, (byte) 0xce,
-                (byte) 0xbd, (byte) 0xce, (byte) 0xb7, ' ', (byte) 0xd8,
-                (byte) 0xb5, (byte) 0xd9, (byte) 0x84, (byte) 0xd8,
-                (byte) 0xad, ' ', (byte) 0xe0, (byte) 0xaa, (byte) 0xb6,
-                (byte) 0xe0, (byte) 0xaa, (byte) 0xbe, (byte) 0xe0,
-                (byte) 0xaa, (byte) 0x82, (byte) 0xe0, (byte) 0xaa,
-                (byte) 0xa4, (byte) 0xe0, (byte) 0xaa, (byte) 0xbf, ' ',
-                (byte) 0xe5, (byte) 0xb9, (byte) 0xb3, (byte) 0xe5,
-                (byte) 0x92, (byte) 0x8c, ' ', (byte) 0xd7, (byte) 0xa9,
-                (byte) 0xd7, (byte) 0x9c, (byte) 0xd7, (byte) 0x95,
-                (byte) 0xd7, (byte) 0x9d, ' ', (byte) 0xd7, (byte) 0xa4,
-                (byte) 0xd7, (byte) 0xa8, (byte) 0xd7, (byte) 0x99,
-                (byte) 0xd7, (byte) 0x93, (byte) 0xd7, (byte) 0x9f, ' ',
-                (byte) 0xe5, (byte) 0x92, (byte) 0x8c, (byte) 0xe5,
-                (byte) 0xb9, (byte) 0xb3, ' ', (byte) 0xe5, (byte) 0x92,
-                (byte) 0x8c, (byte) 0xe5, (byte) 0xb9, (byte) 0xb3, ' ',
-                (byte) 0xd8, (byte) 0xaa, (byte) 0xd9, (byte) 0x89,
-                (byte) 0xd9, (byte) 0x86, (byte) 0xda, (byte) 0x86,
-                (byte) 0xd9, (byte) 0x84, (byte) 0xd9, (byte) 0x89,
-                (byte) 0xd9, (byte) 0x82, ' ', (byte) 0xe0, (byte) 0xae,
-                (byte) 0x85, (byte) 0xe0, (byte) 0xae, (byte) 0xae,
-                (byte) 0xe0, (byte) 0xaf, (byte) 0x88, (byte) 0xe0,
-                (byte) 0xae, (byte) 0xa4, (byte) 0xe0, (byte) 0xae,
-                (byte) 0xbf, ' ', (byte) 0xe0, (byte) 0xb0, (byte) 0xb6,
-                (byte) 0xe0, (byte) 0xb0, (byte) 0xbe, (byte) 0xe0,
-                (byte) 0xb0, (byte) 0x82, (byte) 0xe0, (byte) 0xb0,
-                (byte) 0xa4, (byte) 0xe0, (byte) 0xb0, (byte) 0xbf, ' ',
-                (byte) 0xe0, (byte) 0xb8, (byte) 0xaa, (byte) 0xe0,
-                (byte) 0xb8, (byte) 0xb1, (byte) 0xe0, (byte) 0xb8,
-                (byte) 0x99, (byte) 0xe0, (byte) 0xb8, (byte) 0x95,
-                (byte) 0xe0, (byte) 0xb8, (byte) 0xb4, (byte) 0xe0,
-                (byte) 0xb8, (byte) 0xa0, (byte) 0xe0, (byte) 0xb8,
-                (byte) 0xb2, (byte) 0xe0, (byte) 0xb8, (byte) 0x9e, ' ',
-                (byte) 0xe1, (byte) 0x88, (byte) 0xb0, (byte) 0xe1,
-                (byte) 0x88, (byte) 0x8b, (byte) 0xe1, (byte) 0x88,
-                (byte) 0x9d, ' ', (byte) 0xe0, (byte) 0xb7, (byte) 0x83,
-                (byte) 0xe0, (byte) 0xb7, (byte) 0x8f, (byte) 0xe0,
-                (byte) 0xb6, (byte) 0xb8, (byte) 0xe0, (byte) 0xb6,
-                (byte) 0xba, ' ', (byte) 0xe0, (byte) 0xa4, (byte) 0xb6,
-                (byte) 0xe0, (byte) 0xa4, (byte) 0xbe, (byte) 0xe0,
-                (byte) 0xa4, (byte) 0xa8, (byte) 0xe0, (byte) 0xa5,
-                (byte) 0x8d, (byte) 0xe0, (byte) 0xa4, (byte) 0xa4,
-                (byte) 0xe0, (byte) 0xa4, (byte) 0xbf, (byte) 0xe0,
-                (byte) 0xa4, (byte) 0x83, ' ', (byte) 0xe1, (byte) 0x83,
-                (byte) 0x9b, (byte) 0xe1, (byte) 0x83, (byte) 0xa8,
-                (byte) 0xe1, (byte) 0x83, (byte) 0x95, (byte) 0xe1,
-                (byte) 0x83, (byte) 0x98, (byte) 0xe1, (byte) 0x83,
-                (byte) 0x93, (byte) 0xe1, (byte) 0x83, (byte) 0x9d,
-                (byte) 0xe1, (byte) 0x83, (byte) 0x91, (byte) 0xe1,
-                (byte) 0x83, (byte) 0x90 };
-        // TODO Cannot make the following word work, encoder changes needed
-        // (byte) 0xed, (byte) 0xa0, (byte) 0x80,
-        // (byte) 0xed, (byte) 0xbc, (byte) 0xb2, (byte) 0xed,
-        // (byte) 0xa0, (byte) 0x80, (byte) 0xed, (byte) 0xbc,
-        // (byte) 0xb0, (byte) 0xed, (byte) 0xa0, (byte) 0x80,
-        // (byte) 0xed, (byte) 0xbd, (byte) 0x85, (byte) 0xed,
-        // (byte) 0xa0, (byte) 0x80, (byte) 0xed, (byte) 0xbc,
-        // (byte) 0xb0, (byte) 0xed, (byte) 0xa0, (byte) 0x80,
-        // (byte) 0xed, (byte) 0xbc, (byte) 0xb9, (byte) 0xed,
-        // (byte) 0xa0, (byte) 0x80, (byte) 0xed, (byte) 0xbc,
-        // (byte) 0xb8, (byte) 0xed, (byte) 0xa0, (byte) 0x80,
-        // (byte) 0xed, (byte) 0xbc, (byte) 0xb9, ' '
-
-        final String vendor = new String(bVendor, "UTF-8");
-        final String spec = new String(bSpec, "UTF-8");
-        m.getMainAttributes()
-                .put(Attributes.Name.IMPLEMENTATION_VENDOR, vendor);
-        m.getAttributes(ATT_ENTRY_NAME).put(
-                Attributes.Name.IMPLEMENTATION_VENDOR, vendor);
-        m.getEntries().get(ATT_ENTRY_NAME).put(
-                Attributes.Name.SPECIFICATION_TITLE, spec);
-
-        ByteArrayOutputStream baos = new ByteArrayOutputStream();
-        m.write(baos);
-        m = new Manifest(new ByteArrayInputStream(baos.toByteArray()));
-
-        assertEquals(vendor, m.getMainAttributes().get(
-                Attributes.Name.IMPLEMENTATION_VENDOR));
-        assertEquals(vendor, m.getEntries().get(ATT_ENTRY_NAME).get(
-                Attributes.Name.IMPLEMENTATION_VENDOR));
-        assertEquals(spec, m.getAttributes(ATT_ENTRY_NAME).get(
-                Attributes.Name.SPECIFICATION_TITLE));
-    }
-
-    /**
-     * @tests {@link java.util.jar.Manifest#read(java.io.InputStream)
-     */
-    public void testRead() {
-        // Regression for HARMONY-89
-        InputStream is = new InputStreamImpl();
-        try {
-            new Manifest().read(is);
-            fail("IOException expected");
-        } catch (IOException e) {
-            // desired
-        }
-    }
-
-    // helper class
-    private class InputStreamImpl extends InputStream {
-        public InputStreamImpl() {
-            super();
-        }
-
-        @Override
-        public int read() {
-            return 0;
-        }
-    }
-}
diff --git a/luni/src/test/java/org/apache/harmony/archive/tests/java/util/jar/ZipExecTest.java b/luni/src/test/java/org/apache/harmony/archive/tests/java/util/jar/ZipExecTest.java
deleted file mode 100644
index c57ccbe..0000000
--- a/luni/src/test/java/org/apache/harmony/archive/tests/java/util/jar/ZipExecTest.java
+++ /dev/null
@@ -1,275 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements.  See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You 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 org.apache.harmony.archive.tests.java.util.jar;
-
-import static tests.support.Support_Exec.javaProcessBuilder;
-import static tests.support.Support_Exec.execAndGetOutput;
-import tests.support.resource.Support_Resources;
-
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.util.jar.Attributes;
-import java.util.jar.JarEntry;
-import java.util.jar.JarOutputStream;
-import java.util.jar.Manifest;
-import java.util.zip.ZipEntry;
-import java.util.zip.ZipOutputStream;
-
-/**
- *
- * tests for various cases of java -jar ... execution with .zip files as args
- * some tests are just copy of JarExecTest ones
- */
-
-public class ZipExecTest extends junit.framework.TestCase {
-    public void test_1562() throws Exception {
-        Manifest man = new Manifest();
-        Attributes att = man.getMainAttributes();
-        att.put(Attributes.Name.MANIFEST_VERSION, "1.0");
-        att.put(Attributes.Name.MAIN_CLASS, "foo.bar.execjartest.Foo");
-
-        File outputZip = File.createTempFile("hyts_", ".zip");
-        outputZip.deleteOnExit();
-        ZipOutputStream zout = new ZipOutputStream(new FileOutputStream(
-                outputZip));
-        File resources = Support_Resources.createTempFolder();
-
-        for (String zipClass : new String[] {"Foo", "Bar"}) {
-            zout.putNextEntry(new ZipEntry("foo/bar/execjartest/" + zipClass
-                    + ".class"));
-            zout.write(getResource(resources, "hyts_" + zipClass + ".ser"));
-        }
-
-        zout.putNextEntry(new ZipEntry("META-INF/MANIFEST.MF"));
-        man.write(zout);
-        zout.close();
-
-        ProcessBuilder builder = javaProcessBuilder();
-        builder.command().add("-jar");
-        builder.command().add(outputZip.getAbsolutePath());
-
-        assertTrue("Error executing ZIP",
-                execAndGetOutput(builder).startsWith("FOOBAR"));
-    }
-
-    /**
-     * tests Class-Path entry in manifest
-     *
-     * @throws Exception in case of troubles
-     */
-    public void test_zip_class_path() throws Exception {
-        File fooZip = File.createTempFile("hyts_", ".zip");
-        File barZip = File.createTempFile("hyts_", ".zip");
-        fooZip.deleteOnExit();
-        barZip.deleteOnExit();
-
-        // create the manifest
-        Manifest man = new Manifest();
-        Attributes att = man.getMainAttributes();
-        att.put(Attributes.Name.MANIFEST_VERSION, "1.0");
-        att.put(Attributes.Name.MAIN_CLASS, "foo.bar.execjartest.Foo");
-        att.put(Attributes.Name.CLASS_PATH, barZip.getName());
-
-        File resources = Support_Resources.createTempFolder();
-
-        ZipOutputStream zoutFoo = new ZipOutputStream(new FileOutputStream(
-                fooZip));
-        zoutFoo.putNextEntry(new ZipEntry("META-INF/MANIFEST.MF"));
-        man.write(zoutFoo);
-        zoutFoo.putNextEntry(new ZipEntry("foo/bar/execjartest/Foo.class"));
-        zoutFoo.write(getResource(resources, "hyts_Foo.ser"));
-        zoutFoo.close();
-
-        ZipOutputStream zoutBar = new ZipOutputStream(new FileOutputStream(
-                barZip));
-        zoutBar.putNextEntry(new ZipEntry("foo/bar/execjartest/Bar.class"));
-        zoutBar.write(getResource(resources, "hyts_Bar.ser"));
-        zoutBar.close();
-
-        // execute the JAR and read the result
-        ProcessBuilder builder = javaProcessBuilder();
-        builder.command().add("-jar");
-        builder.command().add(fooZip.getAbsolutePath());
-        assertTrue("Error executing JAR",
-                execAndGetOutput(builder).startsWith( "FOOBAR"));
-
-        // rewrite manifest so it contains not only reference to bar but useless
-        // entries as well
-        att.put(Attributes.Name.CLASS_PATH, "xx yy zz " + barZip.getName());
-        zoutFoo = new ZipOutputStream(new FileOutputStream(fooZip));
-        zoutFoo.putNextEntry(new ZipEntry("META-INF/MANIFEST.MF"));
-        man.write(zoutFoo);
-        zoutFoo.putNextEntry(new ZipEntry("foo/bar/execjartest/Foo.class"));
-        zoutFoo.write(getResource(resources, "hyts_Foo.ser"));
-        zoutFoo.close();
-        // execute the JAR and read the result
-        assertTrue("Error executing JAR",
-                execAndGetOutput(builder).startsWith("FOOBAR"));
-
-
-        // play with relative file names - put relative path as ../<parent dir
-        // name>/xx.zip
-        att.put(Attributes.Name.CLASS_PATH, ".." + File.separator
-                + barZip.getParentFile().getName() + File.separator
-                + barZip.getName());
-        zoutFoo = new ZipOutputStream(new FileOutputStream(fooZip));
-        zoutFoo.putNextEntry(new ZipEntry("META-INF/MANIFEST.MF"));
-        man.write(zoutFoo);
-        zoutFoo.putNextEntry(new ZipEntry("foo/bar/execjartest/Foo.class"));
-        zoutFoo.write(getResource(resources, "hyts_Foo.ser"));
-        zoutFoo.close();
-        // execute the ZIP and read the result
-        assertTrue("Error executing JAR",
-                execAndGetOutput(builder).startsWith("FOOBAR"));
-    }
-
-
-    public void test_zip_jar_mix() throws Exception {
-        File fooJar = File.createTempFile("hyts_", ".jar");
-        File barZip = File.createTempFile("hyts_", ".zip");
-        fooJar.deleteOnExit();
-        barZip.deleteOnExit();
-
-        // create the manifest
-        Manifest man = new Manifest();
-        Attributes att = man.getMainAttributes();
-        att.put(Attributes.Name.MANIFEST_VERSION, "1.0");
-        att.put(Attributes.Name.MAIN_CLASS, "foo.bar.execjartest.Foo");
-        att.put(Attributes.Name.CLASS_PATH, barZip.getName());
-
-        File resources = Support_Resources.createTempFolder();
-
-        JarOutputStream joutFoo = new JarOutputStream(new FileOutputStream(
-                fooJar), man);
-        joutFoo.putNextEntry(new JarEntry("foo/bar/execjartest/Foo.class"));
-        joutFoo.write(getResource(resources, "hyts_Foo.ser"));
-        joutFoo.close();
-
-        ZipOutputStream zoutBar = new ZipOutputStream(new FileOutputStream(
-                barZip));
-        zoutBar.putNextEntry(new ZipEntry("foo/bar/execjartest/Bar.class"));
-        zoutBar.write(getResource(resources, "hyts_Bar.ser"));
-        zoutBar.close();
-
-        ProcessBuilder builder = javaProcessBuilder();
-        builder.command().add("-jar");
-        builder.command().add(fooJar.getAbsolutePath());
-        assertTrue("Error executing JAR",
-                execAndGetOutput(builder).startsWith("FOOBAR"));
-    }
-
-    public void test_zip_jar_mix_1() throws Exception {
-        File fooZip = File.createTempFile("hyts_", ".zip");
-        File barJar = File.createTempFile("hyts_", ".jar");
-        fooZip.deleteOnExit();
-        barJar.deleteOnExit();
-
-        // create the manifest
-        Manifest man = new Manifest();
-        Attributes att = man.getMainAttributes();
-        att.put(Attributes.Name.MANIFEST_VERSION, "1.0");
-        att.put(Attributes.Name.MAIN_CLASS, "foo.bar.execjartest.Foo");
-        att.put(Attributes.Name.CLASS_PATH, barJar.getName());
-
-        File resources = Support_Resources.createTempFolder();
-
-        ZipOutputStream zoutFoo = new ZipOutputStream(new FileOutputStream(
-                fooZip));
-        zoutFoo.putNextEntry(new ZipEntry("META-INF/MANIFEST.MF"));
-        man.write(zoutFoo);
-        zoutFoo.putNextEntry(new ZipEntry("foo/bar/execjartest/Foo.class"));
-        zoutFoo.write(getResource(resources, "hyts_Foo.ser"));
-        zoutFoo.close();
-
-        JarOutputStream joutBar = new JarOutputStream(new FileOutputStream(
-                barJar));
-        joutBar.putNextEntry(new ZipEntry("foo/bar/execjartest/Bar.class"));
-        joutBar.write(getResource(resources, "hyts_Bar.ser"));
-        joutBar.close();
-
-        // execute the JAR and read the result
-        ProcessBuilder builder = javaProcessBuilder();
-        builder.command().add("-jar");
-        builder.command().add(fooZip.getAbsolutePath());
-        assertTrue("Error executing ZIP",
-                execAndGetOutput(builder).startsWith("FOOBAR"));
-    }
-
-    /**
-     * tests case when Main-Class is not in the zip launched but in another zip
-     * referenced by Class-Path
-     *
-     * @throws Exception in case of troubles
-     */
-    public void test_main_class_in_another_zip() throws Exception {
-        File fooZip = File.createTempFile("hyts_", ".zip");
-        File barZip = File.createTempFile("hyts_", ".zip");
-        fooZip.deleteOnExit();
-        barZip.deleteOnExit();
-
-        // create the manifest
-        Manifest man = new Manifest();
-        Attributes att = man.getMainAttributes();
-        att.put(Attributes.Name.MANIFEST_VERSION, "1.0");
-        att.put(Attributes.Name.MAIN_CLASS, "foo.bar.execjartest.Foo");
-        att.put(Attributes.Name.CLASS_PATH, fooZip.getName());
-
-        File resources = Support_Resources.createTempFolder();
-
-        ZipOutputStream zoutFoo = new ZipOutputStream(new FileOutputStream(
-                fooZip));
-        zoutFoo.putNextEntry(new ZipEntry("foo/bar/execjartest/Foo.class"));
-        zoutFoo.write(getResource(resources, "hyts_Foo.ser"));
-        zoutFoo.close();
-
-        ZipOutputStream zoutBar = new ZipOutputStream(new FileOutputStream(
-                barZip));
-        zoutBar.putNextEntry(new ZipEntry("META-INF/MANIFEST.MF"));
-        man.write(zoutBar);
-
-        zoutBar.putNextEntry(new ZipEntry("foo/bar/execjartest/Bar.class"));
-        zoutBar.write(getResource(resources, "hyts_Bar.ser"));
-        zoutBar.close();
-
-        // execute the JAR and read the result
-        ProcessBuilder builder = javaProcessBuilder();
-        builder.command().add("-jar");
-        builder.command().add(barZip.getAbsolutePath());
-        assertTrue("Error executing JAR",
-                execAndGetOutput(builder).startsWith("FOOBAR"));
-    }
-
-
-    private static byte[] getResource(File tempDir, String resourceName)
-            throws IOException {
-        Support_Resources.copyFile(tempDir, null, resourceName);
-        File resourceFile = new File(tempDir, resourceName);
-        resourceFile.deleteOnExit();
-
-        // read whole resource data into memory
-        byte[] resourceBody = new byte[(int) resourceFile.length()];
-        FileInputStream fis = new FileInputStream(resourceFile);
-        fis.read(resourceBody);
-        fis.close();
-
-        return resourceBody;
-    }
-
-}
diff --git a/luni/src/test/java/org/apache/harmony/archive/tests/java/util/zip/AllTests.java b/luni/src/test/java/org/apache/harmony/archive/tests/java/util/zip/AllTests.java
deleted file mode 100644
index f06590e..0000000
--- a/luni/src/test/java/org/apache/harmony/archive/tests/java/util/zip/AllTests.java
+++ /dev/null
@@ -1,36 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements.  See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You 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 org.apache.harmony.archive.tests.java.util.zip;
-
-import junit.framework.Test;
-import junit.framework.TestSuite;
-
-/**
- * Test suite for java.util.zip package.
- */
-public class AllTests {
-    public static Test suite() {
-        TestSuite suite = new TestSuite("Suite org.apache.harmony.archive.tests.java.util.zip");
-        suite.addTestSuite(DataFormatExceptionTest.class);
-        suite.addTestSuite(ZipExceptionTest.class);
-        suite.addTestSuite(ZipFileTest.class);
-        suite.addTestSuite(ZipInputStreamTest.class);
-        // $JUnit-END$
-        return suite;
-    }
-}
diff --git a/luni/src/test/java/org/apache/harmony/archive/tests/java/util/zip/ZipFileTest.java b/luni/src/test/java/org/apache/harmony/archive/tests/java/util/zip/ZipFileTest.java
deleted file mode 100644
index 78af99b..0000000
--- a/luni/src/test/java/org/apache/harmony/archive/tests/java/util/zip/ZipFileTest.java
+++ /dev/null
@@ -1,532 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements.  See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You 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 org.apache.harmony.archive.tests.java.util.zip;
-
-import tests.support.Support_PlatformFile;
-import tests.support.resource.Support_Resources;
-
-import java.io.ByteArrayOutputStream;
-import java.io.File;
-import java.io.FileOutputStream;
-import java.io.FilePermission;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.OutputStream;
-import java.security.Permission;
-import java.util.Enumeration;
-import java.util.zip.ZipEntry;
-import java.util.zip.ZipException;
-import java.util.zip.ZipFile;
-
-public class ZipFileTest extends junit.framework.TestCase {
-
-    public byte[] getAllBytesFromStream(InputStream is) throws IOException {
-        ByteArrayOutputStream bs = new ByteArrayOutputStream();
-        byte[] buf = new byte[512];
-        int iRead;
-        int off;
-        while (is.available() > 0) {
-            iRead = is.read(buf, 0, buf.length);
-            if (iRead > 0) bs.write(buf, 0, iRead);
-        }
-        return bs.toByteArray();
-    }
-
-    // the file hyts_zipFile.zip in setup must be included as a resource
-    private String tempFileName;
-
-    private ZipFile zfile;
-
-    // custom security manager
-    SecurityManager sm = new SecurityManager() {
-        final String forbidenPermissionAction = "read";
-
-
-
-        public void checkPermission(Permission perm) {
-            // only check if it's a FilePermission because Locale checks
-            // for a PropertyPermission with action"read" to get system props.
-            if (perm instanceof FilePermission
-                    && perm.getActions().equals(forbidenPermissionAction)) {
-                throw new SecurityException();
-            }
-        }
-    };
-
-    /**
-     * @tests java.util.zip.ZipFile#ZipFile(java.io.File)
-     */
-    public void test_ConstructorLjava_io_File() {
-        // Test for method java.util.zip.ZipFile(java.io.File)
-        assertTrue("Used to test", true);
-    }
-
-    /**
-     * @tests java.util.zip.ZipFile#ZipFile(java.io.File, int)
-     */
-    public void test_ConstructorLjava_io_FileI() throws IOException {
-        zfile.close(); // about to reopen the same temp file
-        File file = new File(tempFileName);
-        ZipFile zip = new ZipFile(file, ZipFile.OPEN_DELETE | ZipFile.OPEN_READ);
-        zip.close();
-        assertTrue("Zip should not exist", !file.exists());
-        file = new File(tempFileName);
-        file.delete();
-        try {
-            zip = new ZipFile(file, ZipFile.OPEN_READ);
-            fail("IOException expected");
-        } catch (IOException ee) {
-            // expected
-        }
-        // IOException can not be checked throws ZipException in case of IO
-        // problems.
-        SecurityManager oldSm = System.getSecurityManager();
-        System.setSecurityManager(sm);
-        try {
-            file = new File(tempFileName);
-            zip = new ZipFile(file, ZipFile.OPEN_READ);
-            fail("SecurityException expected");
-        } catch (SecurityException e) {
-            // expected
-        } finally {
-            System.setSecurityManager(oldSm);
-        }
-        file = new File(tempFileName);
-        try {
-            zip = new ZipFile(file, -1);
-            fail("IllegalArgumentException expected");
-        } catch (IllegalArgumentException ee) {
-            // expected
-        }
-    }
-
-    /**
-     * @throws IOException
-     * @tests java.util.zip.ZipFile#ZipFile(java.lang.String)
-     */
-    public void test_ConstructorLjava_lang_String() throws IOException {
-        System.setProperty("user.dir", System.getProperty("java.io.tmpdir"));
-
-        zfile.close(); // about to reopen the same temp file
-        ZipFile zip = new ZipFile(tempFileName);
-        zip.close();
-        File file = File.createTempFile("zip", "tmp");
-        try {
-            zip = new ZipFile(file.getName());
-            fail("ZipException expected");
-        } catch (ZipException ee) {
-            // expected
-        }
-        file.delete();
-        // IOException can not be checked throws ZipException in case of IO
-        // problems.
-        SecurityManager oldSm = System.getSecurityManager();
-        System.setSecurityManager(sm);
-        try {
-            zip = new ZipFile(tempFileName);
-            fail("SecurityException expected");
-        } catch (SecurityException e) {
-            // expected
-        } finally {
-            System.setSecurityManager(oldSm);
-        }
-    }
-
-    protected ZipEntry test_finalize1(ZipFile zip) {
-        return zip.getEntry("File1.txt");
-    }
-
-    protected ZipFile test_finalize2(File file) throws IOException {
-        return new ZipFile(file);
-    }
-
-    /**
-     * @tests java.util.zip.ZipFile#finalize()
-     */
-    public void test_finalize() throws IOException {
-        InputStream in = Support_Resources.getStream("hyts_ZipFile.zip");
-        File file = Support_Resources.createTempFile(".jar");
-        OutputStream out = new FileOutputStream(file);
-        int result;
-        byte[] buf = new byte[4096];
-        while ((result = in.read(buf)) != -1) {
-            out.write(buf, 0, result);
-        }
-        in.close();
-        out.close();
-        /*
-         * ZipFile zip = new ZipFile(file); ZipEntry entry1 =
-         * zip.getEntry("File1.txt"); assertNotNull("Did not find entry",
-         * entry1); entry1 = null; zip = null;
-         */
-
-        assertNotNull("Did not find entry",
-                test_finalize1(test_finalize2(file)));
-        System.gc();
-        System.gc();
-        System.runFinalization();
-        file.delete();
-        assertTrue("Zip should not exist", !file.exists());
-    }
-
-    /**
-     * @throws IOException
-     * @tests java.util.zip.ZipFile#close()
-     */
-    public void test_close() throws IOException {
-        // Test for method void java.util.zip.ZipFile.close()
-        File fl = new File(tempFileName);
-        ZipFile zf = new ZipFile(fl);
-        InputStream is1 = zf.getInputStream(zf.getEntry("File1.txt"));
-        InputStream is2 = zf.getInputStream(zf.getEntry("File2.txt"));
-
-        is1.read();
-        is2.read();
-
-        zf.close();
-
-        try {
-            is1.read();
-            fail("IOException expected");
-        } catch (IOException ee) {
-            // expected
-        }
-
-        try {
-            is2.read();
-            fail("IOException expected");
-        } catch (IOException ee) {
-            // expected
-        }
-    }
-
-    /**
-     * @tests java.util.zip.ZipFile#entries()
-     */
-    public void test_entries() throws Exception {
-        // Test for method java.util.Enumeration java.util.zip.ZipFile.entries()
-        Enumeration<? extends ZipEntry> enumer = zfile.entries();
-        int c = 0;
-        while (enumer.hasMoreElements()) {
-            ++c;
-            enumer.nextElement();
-        }
-        assertTrue("Incorrect number of entries returned: " + c, c == 6);
-
-        Enumeration<? extends ZipEntry> enumeration = zfile.entries();
-        zfile.close();
-        try {
-            enumeration.nextElement();
-            fail("did not detect closed file");
-        } catch (IllegalStateException expected) {
-        }
-
-        try {
-            enumeration.hasMoreElements();
-            fail("did not detect closed file");
-        } catch (IllegalStateException expected) {
-        }
-
-        try {
-            zfile.entries();
-            fail("did not detect closed file");
-        } catch (IllegalStateException expected) {
-        }
-    }
-
-    /**
-     * @tests java.util.zip.ZipFile#getEntry(java.lang.String)
-     */
-    public void test_getEntryLjava_lang_String() throws IOException {
-        // Test for method java.util.zip.ZipEntry
-        // java.util.zip.ZipFile.getEntry(java.lang.String)
-        java.util.zip.ZipEntry zentry = zfile.getEntry("File1.txt");
-        assertNotNull("Could not obtain ZipEntry", zentry);
-        int r;
-        InputStream in;
-
-        zentry = zfile.getEntry("testdir1/File1.txt");
-        assertNotNull("Could not obtain ZipEntry: testdir1/File1.txt", zentry);
-        zentry = zfile.getEntry("testdir1/");
-        assertNotNull("Could not obtain ZipEntry: testdir1/", zentry);
-        in = zfile.getInputStream(zentry);
-        assertNotNull("testdir1/ should not have null input stream", in);
-        r = in.read();
-        in.close();
-        assertEquals("testdir1/ should not contain data", -1, r);
-
-        zentry = zfile.getEntry("testdir1/testdir1");
-        assertNotNull("Could not obtain ZipEntry: testdir1/testdir1", zentry);
-        in = zfile.getInputStream(zentry);
-        byte[] buf = new byte[256];
-        r = in.read(buf);
-        in.close();
-        assertEquals("incorrect contents", "This is also text", new String(buf,
-                0, r));
-    }
-
-    public void test_getEntryLjava_lang_String_AndroidOnly() throws IOException {
-        java.util.zip.ZipEntry zentry = zfile.getEntry("File1.txt");
-        assertNotNull("Could not obtain ZipEntry", zentry);
-        int r;
-        InputStream in;
-
-        zentry = zfile.getEntry("testdir1");
-        assertNotNull("Must be able to obtain ZipEntry: testdir1", zentry);
-        in = zfile.getInputStream(zentry);
-        /*
-         * Android delivers empty InputStream, RI no InputStream at all. The
-         * spec doesn't clarify this, so we need to deal with both situations.
-         */
-        int data = -1;
-        if (in != null) {
-            data = in.read();
-            in.close();
-        }
-        assertEquals("Must not be able to read directory data", -1, data);
-    }
-
-    public void test_getEntryLjava_lang_String_Ex() throws IOException {
-        java.util.zip.ZipEntry zentry = zfile.getEntry("File1.txt");
-        assertNotNull("Could not obtain ZipEntry", zentry);
-
-        zfile.close();
-        try {
-            zfile.getEntry("File2.txt");
-            fail("IllegalStateException expected");
-        } catch (IllegalStateException ee) {
-        }
-    }
-
-    /**
-     * @throws IOException
-     * @tests java.util.zip.ZipFile#getInputStream(java.util.zip.ZipEntry)
-     */
-    public void test_getInputStreamLjava_util_zip_ZipEntry() throws IOException {
-        // Test for method java.io.InputStream
-        // java.util.zip.ZipFile.getInputStream(java.util.zip.ZipEntry)
-        ZipEntry zentry = null;
-        InputStream is = null;
-        try {
-            zentry = zfile.getEntry("File1.txt");
-            is = zfile.getInputStream(zentry);
-            byte[] rbuf = new byte[1000];
-            int r;
-            is.read(rbuf, 0, r = (int) zentry.getSize());
-            assertEquals("getInputStream read incorrect data", "This is text",
-                    new String(rbuf, 0, r));
-        } catch (java.io.IOException e) {
-            fail("IOException during getInputStream");
-        } finally {
-            try {
-                is.close();
-            } catch (java.io.IOException e) {
-                fail("Failed to close input stream");
-            }
-        }
-
-        zentry = zfile.getEntry("File2.txt");
-        zfile.close();
-        try {
-            is = zfile.getInputStream(zentry);
-            fail("IllegalStateException expected");
-        } catch (IllegalStateException ee) {
-            // expected
-        }
-
-        // ZipException can not be checked. Stream object returned or null.
-    }
-
-    /**
-     * @tests java.util.zip.ZipFile#getName()
-     */
-    public void test_getName() {
-        // Test for method java.lang.String java.util.zip.ZipFile.getName()
-        assertTrue("Returned incorrect name: " + zfile.getName(), zfile
-                .getName().equals(tempFileName));
-    }
-
-    /**
-     * @throws IOException
-     * @tests java.util.zip.ZipFile#size()
-     */
-    public void test_size() throws IOException {
-        assertEquals(6, zfile.size());
-        zfile.close();
-        try {
-            zfile.size();
-            fail("IllegalStateException expected");
-        } catch (IllegalStateException expected) {
-        }
-    }
-
-    /**
-     * @tests java.io.InputStream#reset()
-     */
-    public void test_reset() throws IOException {
-        // read an uncompressed entry
-        ZipEntry zentry = zfile.getEntry("File1.txt");
-        InputStream is = zfile.getInputStream(zentry);
-        byte[] rbuf1 = new byte[6];
-        byte[] rbuf2 = new byte[6];
-        int r1, r2;
-        r1 = is.read(rbuf1);
-        assertEquals(rbuf1.length, r1);
-        r2 = is.read(rbuf2);
-        assertEquals(rbuf2.length, r2);
-
-        try {
-            is.reset();
-            fail();
-        } catch (IOException expected) {
-        }
-        is.close();
-
-        // read a compressed entry
-        byte[] rbuf3 = new byte[4185];
-        ZipEntry zentry2 = zfile.getEntry("File3.txt");
-        is = zfile.getInputStream(zentry2);
-        r1 = is.read(rbuf3);
-        assertEquals(4183, r1);
-        try {
-            is.reset();
-            fail();
-        } catch (IOException expected) {
-        }
-        is.close();
-
-        is = zfile.getInputStream(zentry2);
-        r1 = is.read(rbuf3, 0, 3000);
-        assertEquals(3000, r1);
-        try {
-            is.reset();
-            fail();
-        } catch (IOException expected) {
-        }
-        is.close();
-    }
-
-    /**
-     * @tests java.io.InputStream#reset()
-     */
-    public void test_reset_subtest0() throws IOException {
-        // read an uncompressed entry
-        ZipEntry zentry = zfile.getEntry("File1.txt");
-        InputStream is = zfile.getInputStream(zentry);
-        byte[] rbuf1 = new byte[12];
-        byte[] rbuf2 = new byte[12];
-        int r = is.read(rbuf1, 0, 4);
-        assertEquals(4, r);
-        is.mark(0);
-        r = is.read(rbuf1);
-        assertEquals(8, r);
-        assertEquals(-1, is.read());
-
-        try {
-            is.reset();
-            fail();
-        } catch (IOException expected) {
-        }
-
-        is.close();
-
-        // read a compressed entry
-        byte[] rbuf3 = new byte[4185];
-        ZipEntry zentry2 = zfile.getEntry("File3.txt");
-        is = zfile.getInputStream(zentry2);
-        r = is.read(rbuf3, 0, 3000);
-        assertEquals(3000, r);
-        is.mark(0);
-        r = is.read(rbuf3);
-        assertEquals(1183, r);
-        assertEquals(-1, is.read());
-
-        try {
-            is.reset();
-            fail();
-        } catch (IOException expected) {
-        }
-
-        is.close();
-    }
-
-	/**
-     * Sets up the fixture, for example, open a network connection. This method
-     * is called before a test is executed.
-     */
-    @Override
-    protected void setUp() {
-        try {
-            // Create a local copy of the file since some tests want to alter
-            // information.
-            tempFileName = System.getProperty("java.io.tmpdir");
-            String separator = System.getProperty("file.separator");
-            if (tempFileName.charAt(tempFileName.length() - 1) == separator
-                    .charAt(0)) {
-                tempFileName = Support_PlatformFile.getNewPlatformFile(
-                        tempFileName, "gabba.zip");
-            } else {
-                tempFileName = Support_PlatformFile.getNewPlatformFile(
-                        tempFileName + separator, "gabba.zip");
-            }
-
-            File f = new File(tempFileName);
-            f.delete();
-            InputStream is = Support_Resources.getStream("hyts_ZipFile.zip");
-            FileOutputStream fos = new FileOutputStream(f);
-            byte[] rbuf = getAllBytesFromStream(is);
-            fos.write(rbuf, 0, rbuf.length);
-            is.close();
-            fos.close();
-            zfile = new ZipFile(f);
-        } catch (Exception e) {
-            System.out.println("Exception during ZipFile setup:");
-            e.printStackTrace();
-        }
-    }
-
-    /**
-     * Tears down the fixture, for example, close a network connection. This
-     * method is called after a test is executed.
-     */
-    @Override
-    protected void tearDown() {
-        try {
-            if (zfile != null) {
-                // Note zfile is a user-defined zip file used by other tests and
-                // should not be deleted
-                zfile.close();
-                tempFileName = System.getProperty("java.io.tmpdir");
-                String separator = System.getProperty("file.separator");
-                if (tempFileName.charAt(tempFileName.length() - 1) == separator
-                        .charAt(0)) {
-                    tempFileName = Support_PlatformFile.getNewPlatformFile(
-                            tempFileName, "gabba.zip");
-                } else {
-                    tempFileName = Support_PlatformFile.getNewPlatformFile(
-                            tempFileName + separator, "gabba.zip");
-                }
-
-                File f = new File(tempFileName);
-                f.delete();
-            }
-        } catch (Exception e) {
-        }
-    }
-
-}
diff --git a/luni/src/test/java/org/apache/harmony/archive/tests/java/util/zip/ZipInputStreamTest.java b/luni/src/test/java/org/apache/harmony/archive/tests/java/util/zip/ZipInputStreamTest.java
deleted file mode 100644
index b2c0ab3..0000000
--- a/luni/src/test/java/org/apache/harmony/archive/tests/java/util/zip/ZipInputStreamTest.java
+++ /dev/null
@@ -1,378 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements.  See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You 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 org.apache.harmony.archive.tests.java.util.zip;
-
-import junit.framework.TestCase;
-
-import tests.support.resource.Support_Resources;
-
-import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.FilterInputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.util.zip.ZipEntry;
-import java.util.zip.ZipException;
-import java.util.zip.ZipInputStream;
-import java.util.zip.ZipOutputStream;
-
-public class ZipInputStreamTest extends TestCase {
-    // the file hyts_zipFile.zip used in setup needs to included as a resource
-    private ZipEntry zentry;
-
-    private ZipInputStream zis;
-
-    private byte[] zipBytes;
-
-    private byte[] dataBytes = "Some data in my file".getBytes();
-
-    @Override
-    protected void setUp() {
-        try {
-            InputStream is = Support_Resources.getStream("hyts_ZipFile.zip");
-            if (is == null) {
-                System.out.println("file hyts_ZipFile.zip can not be found");
-            }
-            zis = new ZipInputStream(is);
-
-            ByteArrayOutputStream bos = new ByteArrayOutputStream();
-            ZipOutputStream zos = new ZipOutputStream(bos);
-            ZipEntry entry = new ZipEntry("myFile");
-            zos.putNextEntry(entry);
-            zos.write(dataBytes);
-            zos.closeEntry();
-            zos.close();
-            zipBytes = bos.toByteArray();
-        } catch (Exception e) {
-            System.out.println("Exception during ZipFile setup:");
-            e.printStackTrace();
-        }
-    }
-
-    @Override
-    protected void tearDown() {
-        if (zis != null) {
-            try {
-                zis.close();
-            } catch (Exception e) {
-            }
-        }
-    }
-
-    /**
-     * @tests java.util.zip.ZipInputStream#ZipInputStream(java.io.InputStream)
-     */
-    public void test_ConstructorLjava_io_InputStream() throws Exception {
-        zentry = zis.getNextEntry();
-        zis.closeEntry();
-    }
-
-    /**
-     * @tests java.util.zip.ZipInputStream#close()
-     */
-    public void test_close() {
-        try {
-            zis.close();
-            byte[] rbuf = new byte[10];
-            zis.read(rbuf, 0, 1);
-        } catch (IOException e) {
-            return;
-        }
-        fail("Read data after stream was closed");
-    }
-
-    /**
-     * @tests java.util.zip.ZipInputStream#close()
-     */
-    public void test_close2() throws Exception {
-        // Regression for HARMONY-1101
-        zis.close();
-        // another call to close should NOT cause an exception
-        zis.close();
-    }
-
-    /**
-     * @tests java.util.zip.ZipInputStream#closeEntry()
-     */
-    public void test_closeEntry() throws Exception {
-        zentry = zis.getNextEntry();
-        zis.closeEntry();
-        zentry = zis.getNextEntry();
-        zis.close();
-        try {
-            zis.closeEntry();
-            fail("IOException expected");
-        } catch (IOException ee) {
-            // expected
-        }
-        File resources = Support_Resources.createTempFolder();
-        Support_Resources.copyFile(resources, null, "Broken_manifest.jar");
-        FileInputStream fis = new FileInputStream(new File(resources,
-                "Broken_manifest.jar"));
-
-        ZipInputStream zis1 = new ZipInputStream(fis);
-
-        try {
-            for (int i = 0; i < 6; i++) {
-                zis1.getNextEntry();
-                zis1.closeEntry();
-            }
-            fail("ZipException expected");
-        } catch (ZipException ee) {
-            // expected
-        }
-    }
-
-    public void test_closeAfterException() throws Exception {
-        File resources = Support_Resources.createTempFolder();
-        Support_Resources.copyFile(resources, null, "Broken_manifest.jar");
-        FileInputStream fis = new FileInputStream(new File(resources,
-                "Broken_manifest.jar"));
-
-        ZipInputStream zis1 = new ZipInputStream(fis);
-
-        try {
-            for (int i = 0; i < 6; i++) {
-                zis1.getNextEntry();
-            }
-            fail("ZipException expected");
-        } catch (ZipException ee) {
-            // expected
-        }
-
-        zis1.close();
-        try {
-            zis1.getNextEntry();
-            fail("IOException expected");
-        } catch (IOException ee) {
-            // expected
-        }
-    }
-
-    /**
-     * @tests java.util.zip.ZipInputStream#getNextEntry()
-     */
-    public void test_getNextEntry() throws Exception {
-        assertNotNull("getNextEntry failed", zis.getNextEntry());
-
-        File resources = Support_Resources.createTempFolder();
-        Support_Resources.copyFile(resources, null, "Broken_manifest.jar");
-        FileInputStream fis = new FileInputStream(new File(resources,
-                "Broken_manifest.jar"));
-
-        ZipInputStream zis1 = new ZipInputStream(fis);
-
-        try {
-            for (int i = 0; i < 6; i++) {
-                zis1.getNextEntry();
-            }
-            fail("ZipException expected");
-        } catch (ZipException ee) {
-            // expected
-        }
-
-        try {
-            zis1.close();  // Android throws exception here, already!
-            zis1.getNextEntry();  // But RI here, only!
-            fail("IOException expected");
-        } catch (IOException ee) {
-            // expected
-        }
-    }
-
-    /**
-     * @tests java.util.zip.ZipInputStream#read(byte[], int, int)
-     */
-    public void test_read$BII() throws Exception {
-        zentry = zis.getNextEntry();
-        byte[] rbuf = new byte[(int) zentry.getSize()];
-        int r = zis.read(rbuf, 0, rbuf.length);
-        new String(rbuf, 0, r);
-        assertEquals("Failed to read entry", 12, r);
-
-        File resources = Support_Resources.createTempFolder();
-        Support_Resources.copyFile(resources, null, "Broken_manifest.jar");
-        FileInputStream fis = new FileInputStream(new File(resources,
-                "Broken_manifest.jar"));
-
-        ZipInputStream zis1 = new ZipInputStream(fis);
-
-        zis1.getNextEntry();
-        zis1.getNextEntry();
-
-        rbuf = new byte[100];
-
-        try {
-            zis1.read(rbuf, 10, 90);
-            fail("ZipException expected");
-        } catch (ZipException ee) {
-            // expected
-        }
-
-        try {
-            zis1.close();  // Android throws exception here, already!
-            zis1.read(rbuf, 10, 90);  // But RI here, only!
-            fail("IOException expected");
-        } catch (IOException ee) {
-            // expected
-        }
-    }
-
-    public void testReadOneByteAtATime() throws IOException {
-        InputStream in = new FilterInputStream(Support_Resources.getStream("hyts_ZipFile.zip")) {
-            @Override
-            public int read(byte[] buffer, int offset, int count) throws IOException {
-                return super.read(buffer, offset, 1); // one byte at a time
-            }
-
-            @Override
-            public int read(byte[] buffer) throws IOException {
-                return super.read(buffer, 0, 1); // one byte at a time
-            }
-        };
-
-        zis = new ZipInputStream(in);
-        while ((zentry = zis.getNextEntry()) != null) {
-            zentry.getName();
-        }
-        zis.close();
-    }
-
-    /**
-     * @tests java.util.zip.ZipInputStream#skip(long)
-     */
-    public void test_skipJ() throws Exception {
-        zentry = zis.getNextEntry();
-        byte[] rbuf = new byte[(int) zentry.getSize()];
-        zis.skip(2);
-        int r = zis.read(rbuf, 0, rbuf.length);
-        assertEquals("Failed to skip data", 10, r);
-
-        zentry = zis.getNextEntry();
-        zentry = zis.getNextEntry();
-        long s = zis.skip(1025);
-        assertTrue("invalid skip: " + s, s == 1025);
-
-        ZipInputStream zis = new ZipInputStream(new ByteArrayInputStream(
-                zipBytes));
-        zis.getNextEntry();
-        long skipLen = dataBytes.length / 2;
-        assertEquals("Assert 0: failed valid skip", skipLen, zis.skip(skipLen));
-        zis.skip(dataBytes.length);
-        assertEquals("Assert 1: performed invalid skip", 0, zis.skip(1));
-        assertEquals("Assert 2: failed zero len skip", 0, zis.skip(0));
-        try {
-            zis.skip(-1);
-            fail("Assert 3: Expected Illegal argument exception");
-        } catch (IllegalArgumentException e) {
-            // Expected
-        }
-
-        File resources = Support_Resources.createTempFolder();
-        Support_Resources.copyFile(resources, null, "Broken_manifest.jar");
-        FileInputStream fis = new FileInputStream(new File(resources,
-                "Broken_manifest.jar"));
-
-        ZipInputStream zis1 = new ZipInputStream(fis);
-
-        zis1.getNextEntry();
-        zis1.getNextEntry();
-
-        try {
-            zis1.skip(10);
-            fail("ZipException expected");
-        } catch (ZipException ee) {
-            // expected
-        }
-
-        try {
-            zis1.close();  // Android throws exception here, already!
-            zis1.skip(10);  // But RI here, only!
-            fail("IOException expected");
-        } catch (IOException ee) {
-            // expected
-        }
-    }
-
-    public void test_available() throws Exception {
-
-        File resources = Support_Resources.createTempFolder();
-        Support_Resources.copyFile(resources, null, "hyts_ZipFile.zip");
-        File fl = new File(resources, "hyts_ZipFile.zip");
-        FileInputStream fis = new FileInputStream(fl);
-
-        ZipInputStream zis1 = new ZipInputStream(fis);
-        ZipEntry entry = zis1.getNextEntry();
-        assertNotNull("No entry in the archive.", entry);
-        long entrySize = entry.getSize();
-        assertTrue("Entry size was < 1", entrySize > 0);
-        int i = 0;
-        while (zis1.available() > 0) {
-            zis1.skip(1);
-            i++;
-        }
-        if (i != entrySize) {
-            fail("ZipInputStream.available or ZipInputStream.skip does not " +
-                    "working properly. Only skipped " + i +
-                    " bytes instead of " + entrySize);
-        }
-        assertEquals(0, zis1.skip(1));
-        assertEquals(0, zis1.available());
-        zis1.closeEntry();
-        assertEquals(1, zis.available());
-        zis1.close();
-        try {
-            zis1.available();
-            fail("IOException expected");
-        } catch (IOException ee) {
-            // expected
-        }
-    }
-
-    class Mock_ZipInputStream extends ZipInputStream {
-        boolean createFlag = false;
-
-        public Mock_ZipInputStream(InputStream arg0) {
-            super(arg0);
-        }
-
-        boolean getCreateFlag() {
-            return createFlag;
-        }
-
-        protected ZipEntry createZipEntry(String name) {
-            createFlag = true;
-            return super.createZipEntry(name);
-        }
-    }
-
-    public void test_createZipEntryLjava_lang_String() throws Exception {
-
-        File resources = Support_Resources.createTempFolder();
-        Support_Resources.copyFile(resources, null, "Broken_manifest.jar");
-        File fl = new File(resources, "Broken_manifest.jar");
-        FileInputStream fis = new FileInputStream(fl);
-
-        Mock_ZipInputStream zis1 = new Mock_ZipInputStream(fis);
-        assertFalse(zis1.getCreateFlag());
-        zis1.getNextEntry();
-        assertTrue(zis1.getCreateFlag());
-    }
-}
diff --git a/luni/src/test/java/org/apache/harmony/luni/platform/OSMemoryTest.java b/luni/src/test/java/org/apache/harmony/luni/platform/OSMemoryTest.java
index 185bc66..197b277 100644
--- a/luni/src/test/java/org/apache/harmony/luni/platform/OSMemoryTest.java
+++ b/luni/src/test/java/org/apache/harmony/luni/platform/OSMemoryTest.java
@@ -38,6 +38,7 @@
             // Regular copy.
             OSMemory.pokeIntArray(ptr, values, 0, values.length, false);
             assertIntsEqual(values, ptr, false);
+            assertIntsEqual(swappedValues, ptr, true);
         } finally {
             OSMemory.free(ptr);
         }
@@ -46,7 +47,8 @@
         try {
             // Swapped copy.
             OSMemory.pokeIntArray(ptr, values, 0, values.length, true);
-            assertIntsEqual(swappedValues, ptr, true);
+            assertIntsEqual(values, ptr, true);
+            assertIntsEqual(swappedValues, ptr, false);
         } finally {
             OSMemory.free(ptr);
         }
@@ -57,7 +59,8 @@
             for (int i = 0; i < values.length; ++i) {
                 OSMemory.pokeIntArray(ptr + i * scale, values, i, 1, true);
             }
-            assertIntsEqual(swappedValues, ptr, true);
+            assertIntsEqual(values, ptr, true);
+            assertIntsEqual(swappedValues, ptr, false);
         } finally {
             OSMemory.free(ptr);
         }
@@ -81,6 +84,7 @@
             // Regular copy. Memset first so we start from a known state.
             OSMemory.pokeShortArray(ptr, values, 0, values.length, false);
             assertShortsEqual(values, ptr, false);
+            assertShortsEqual(swappedValues, ptr, true);
         } finally {
             OSMemory.free(ptr);
         }
@@ -89,7 +93,8 @@
         try {
             // Swapped copy.
             OSMemory.pokeShortArray(ptr, values, 0, values.length, true);
-            assertShortsEqual(swappedValues, ptr, true);
+            assertShortsEqual(values, ptr, true);
+            assertShortsEqual(swappedValues, ptr, false);
         } finally {
             OSMemory.free(ptr);
         }
@@ -100,7 +105,8 @@
             for (int i = 0; i < values.length; ++i) {
                 OSMemory.pokeShortArray(ptr + i * scale, values, i, 1, true);
             }
-            assertShortsEqual(swappedValues, ptr, true);
+            assertShortsEqual(values, ptr, true);
+            assertShortsEqual(swappedValues, ptr, false);
         } finally {
             OSMemory.free(ptr);
         }
diff --git a/luni/src/test/java/tests/AllTests.java b/luni/src/test/java/tests/AllTests.java
index c17cf8f..27be1f6 100644
--- a/luni/src/test/java/tests/AllTests.java
+++ b/luni/src/test/java/tests/AllTests.java
@@ -34,7 +34,6 @@
 
         // Harmony-written test suites (often with Android tests added in).
         suite.addTest(tests.annotation.AllTests.suite());
-        suite.addTest(tests.archive.AllTests.suite());
         suite.addTest(tests.concurrent.AllTests.suite());
         suite.addTest(tests.dom.AllTests.suite());
         suite.addTest(tests.luni.AllTestsIo.suite());
diff --git a/luni/src/test/java/tests/api/java/io/AllTests.java b/luni/src/test/java/tests/api/java/io/AllTests.java
index c41968e..9c5f129 100644
--- a/luni/src/test/java/tests/api/java/io/AllTests.java
+++ b/luni/src/test/java/tests/api/java/io/AllTests.java
@@ -82,7 +82,6 @@
         suite.addTestSuite(PrintWriterTest.class);
         suite.addTestSuite(PushbackInputStreamTest.class);
         suite.addTestSuite(PushbackReaderTest.class);
-        suite.addTestSuite(RandomAccessFileTest.class);
         suite.addTestSuite(SequenceInputStreamTest.class);
         suite.addTestSuite(SerializablePermissionTest.class);
         suite.addTestSuite(StreamCorruptedExceptionTest.class);
diff --git a/luni/src/test/java/tests/api/java/util/AllTests.java b/luni/src/test/java/tests/api/java/util/AllTests.java
index 71ca767..fe1c93d 100644
--- a/luni/src/test/java/tests/api/java/util/AllTests.java
+++ b/luni/src/test/java/tests/api/java/util/AllTests.java
@@ -64,7 +64,6 @@
         suite.addTestSuite(PropertyResourceBundleTest.class);
         suite.addTestSuite(RandomTest.class);
         suite.addTestSuite(ResourceBundleTest.class);
-        suite.addTestSuite(ScannerTest.class);
         suite.addTestSuite(SimpleTimeZoneTest.class);
         suite.addTestSuite(StackTest.class);
         suite.addTestSuite(StringTokenizerTest.class);
diff --git a/luni/src/test/java/tests/api/java/util/ScannerTest.java b/luni/src/test/java/tests/api/java/util/ScannerTest.java
deleted file mode 100644
index 5587a42..0000000
--- a/luni/src/test/java/tests/api/java/util/ScannerTest.java
+++ /dev/null
@@ -1,6918 +0,0 @@
-/* Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements.  See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You 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 tests.api.java.util;
-
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.KnownFailure;
-
-import java.io.Closeable;
-import java.io.EOFException;
-import java.io.File;
-import java.io.FileNotFoundException;
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.OutputStream;
-import java.io.PipedInputStream;
-import java.io.StringReader;
-import java.math.BigDecimal;
-import java.math.BigInteger;
-import java.net.InetSocketAddress;
-import java.net.ServerSocket;
-import java.net.Socket;
-import java.net.SocketAddress;
-import java.nio.CharBuffer;
-import java.nio.channels.FileChannel;
-import java.nio.channels.ReadableByteChannel;
-import java.nio.channels.ServerSocketChannel;
-import java.nio.channels.SocketChannel;
-import java.nio.charset.Charset;
-import java.util.Arrays;
-import java.util.InputMismatchException;
-import java.util.Locale;
-import java.util.NoSuchElementException;
-import java.util.Scanner;
-import java.util.regex.MatchResult;
-import java.util.regex.Pattern;
-
-import tests.support.Support_Locale;
-import tests.support.Support_PortManager;
-
-import junit.framework.TestCase;
-
-@TestTargetClass(Scanner.class)
-public class ScannerTest extends TestCase {
-    static final boolean disableRIBugs = false;
-
-    private Scanner s;
-
-    private ServerSocket server;
-
-    private SocketAddress address;
-
-    private SocketChannel client;
-
-    private Socket serverSocket;
-
-    private OutputStream os;
-
-    private static class MockCloseable implements Closeable, Readable {
-
-        public void close() throws IOException {
-            throw new IOException();
-        }
-
-        public int read(CharBuffer cb) throws IOException {
-            throw new EOFException();
-        }
-
-    }
-
-    /**
-     * @tests java.util.Scanner#Scanner(File)
-     */
-    @TestTargetNew(
-        level = TestLevel.COMPLETE,
-        notes = "",
-        method = "Scanner",
-        args = {java.io.File.class}
-    )
-    public void test_ConstructorLjava_io_File() throws IOException {
-        File tmpFile = File.createTempFile("TestFileForScanner", ".tmp");
-        s = new Scanner(tmpFile);
-        assertNotNull(s);
-        s.close();
-        assertTrue(tmpFile.delete());
-
-        try {
-            s = new Scanner(tmpFile);
-            fail("should throw FileNotFoundException");
-        } catch (FileNotFoundException e) {
-            // expected
-        }
-
-        tmpFile = File.createTempFile("TestFileForScanner", ".tmp");
-        FileOutputStream fos = new FileOutputStream(tmpFile);
-        fos.write("test".getBytes());
-
-        s = new Scanner(tmpFile);
-        tmpFile.delete();
-
-        // Scanner(File = null)
-        try {
-            s = new Scanner((File) null);
-            fail("Should throw NullPointerException");
-        } catch (NullPointerException e) {
-            // expected
-        }
-
-        // TODO: test if the default charset is used.
-    }
-
-    /**
-     * @tests java.util.Scanner#Scanner(File, String)
-     */
-    @TestTargetNew(
-        level = TestLevel.COMPLETE,
-        notes = "",
-        method = "Scanner",
-        args = {java.io.File.class, java.lang.String.class}
-    )
-    public void test_ConstructorLjava_io_FileLjava_lang_String()
-            throws IOException {
-        File tmpFile = File.createTempFile("TestFileForScanner", ".tmp");
-        s = new Scanner(tmpFile, Charset.defaultCharset().name());
-        assertNotNull(s);
-        s.close();
-        assertTrue(tmpFile.delete());
-
-        try {
-            s = new Scanner(tmpFile, Charset.defaultCharset().name());
-            fail("should throw FileNotFoundException");
-        } catch (FileNotFoundException e) {
-            // expected
-        }
-
-        try {
-            s = new Scanner(tmpFile, null);
-            fail("should throw FileNotFoundException");
-        } catch (FileNotFoundException e) {
-            // expected
-        }
-
-        tmpFile = File.createTempFile("TestFileForScanner", ".tmp");
-        try {
-            s = new Scanner(tmpFile, "invalid charset");
-            fail("should throw IllegalArgumentException");
-        } catch (IllegalArgumentException e) {
-            // expected
-        }
-
-        //fail on RI. File is opened but not closed when exception is thrown on
-        // RI.
-        assertTrue(tmpFile.delete());
-
-        // Scanner(File = null, Charset = null)
-        try {
-            s = new Scanner((File) null, null);
-            fail("Should throw NullPointerException");
-        } catch (NullPointerException e) {
-            // expected
-        }
-
-        // Scanner(File = null, Charset = UTF-8)
-        try {
-            s = new Scanner((File) null, "UTF-8");
-            fail("Should throw NullPointerException");
-        } catch (NullPointerException e) {
-            // expected
-        }
-
-        // Scanner(File = null, Charset = invalid)
-        try {
-            s = new Scanner((File) null, "invalid");
-            fail("Should throw NullPointerException");
-        } catch (NullPointerException e) {
-            // expected
-        }
-
-        // Scanner(File, Charset = null)
-        try {
-            File f = File.createTempFile("test", ".tmp");
-            s = new Scanner(f, null);
-            fail("Should throw IllegalArgumentException");
-        } catch (IllegalArgumentException e) {
-            // expected
-        }
-
-        // TODO: test if the specified charset is used.
-    }
-
-    /**
-     * @tests java.util.Scanner#Scanner(InputStream)
-     */
-    @TestTargetNew(
-        level = TestLevel.COMPLETE,
-        notes = "",
-        method = "Scanner",
-        args = {java.io.InputStream.class}
-    )
-    public void test_ConstructorLjava_io_InputStream() {
-        s = new Scanner(new PipedInputStream());
-        assertNotNull(s);
-        s.close();
-
-        // Scanner(InputStream)
-        try {
-            s = new Scanner((InputStream) null);
-            fail("Should throw NullPointerException");
-        } catch (NullPointerException e) {
-            // expected
-        }
-
-        // TODO: test if the default charset is used.
-    }
-
-    /**
-     * @tests java.util.Scanner#Scanner(InputStream, String)
-     */
-    @TestTargetNew(
-        level = TestLevel.COMPLETE,
-        notes = "",
-        method = "Scanner",
-        args = {java.io.InputStream.class, java.lang.String.class}
-    )
-    public void test_ConstructorLjava_io_InputStreamLjava_lang_String() {
-        s = new Scanner(new PipedInputStream(), Charset.defaultCharset().name());
-        assertNotNull(s);
-        s.close();
-
-        try {
-            s = new Scanner((PipedInputStream) null, "invalid charset");
-            fail("should throw NullPointerException");
-        } catch (NullPointerException e) {
-            // expected
-        }
-
-        try {
-            s = new Scanner(new PipedInputStream(), null);
-            fail("should throw NullPointerException");
-        } catch (NullPointerException e) {
-            // expected
-        }
-
-        try {
-            s = new Scanner(new PipedInputStream(), "invalid charset");
-            fail("should throw IllegalArgumentException");
-        } catch (IllegalArgumentException e) {
-            // expected
-        }
-
-        // TODO: test if the specified charset is used.
-    }
-
-    /**
-     * @tests java.util.Scanner#Scanner(Readable)
-     */
-    @TestTargetNew(
-        level = TestLevel.COMPLETE,
-        notes = "",
-        method = "Scanner",
-        args = {java.lang.Readable.class}
-    )
-    public void test_ConstructorLjava_lang_Readable() {
-        s = new Scanner(new StringReader("test string"));
-        assertNotNull(s);
-        s.close();
-
-        // Scanner(Readable)
-        try {
-            s = new Scanner((Readable) null);
-            fail("Should throw NullPointerException");
-        } catch (NullPointerException e) {
-            // expected
-        }
-    }
-
-    /**
-     * @tests java.util.Scanner#Scanner(ReadableByteChannel)
-     */
-    @TestTargetNew(
-        level = TestLevel.COMPLETE,
-        notes = "",
-        method = "Scanner",
-        args = {java.nio.channels.ReadableByteChannel.class}
-    )
-    public void test_ConstructorLjava_nio_channels_ReadableByteChannel()
-            throws IOException {
-        File tmpFile = File.createTempFile("TestFileForScanner", ".tmp");
-        FileChannel fc = new FileOutputStream(tmpFile).getChannel();
-        s = new Scanner(fc);
-        assertNotNull(s);
-        s.close();
-        assertTrue(tmpFile.delete());
-
-        // Scanner(ReadableByteChannel)
-        try {
-            s = new Scanner((ReadableByteChannel) null);
-            fail("Should throw NullPointerException");
-        } catch (NullPointerException e) {
-            // expected
-        }
-
-        // TODO: test if the default charset is used.
-    }
-
-    /**
-     * @tests java.util.Scanner#Scanner(ReadableByteChannel, String)
-     */
-    @TestTargetNew(
-        level = TestLevel.COMPLETE,
-        notes = "",
-        method = "Scanner",
-        args = {java.nio.channels.ReadableByteChannel.class, java.lang.String.class}
-    )
-    public void test_ConstructorLjava_nio_channels_ReadableByteChannelLjava_lang_String()
-            throws IOException {
-        File tmpFile = File.createTempFile("TestFileForScanner", ".tmp");
-        FileChannel fc = new FileOutputStream(tmpFile).getChannel();
-        s = new Scanner(fc, Charset.defaultCharset().name());
-        assertNotNull(s);
-        s.close();
-
-        fc = new FileOutputStream(tmpFile).getChannel();
-        try {
-            s = new Scanner(fc, "invalid charset");
-            fail("should throw IllegalArgumentException");
-        } catch (IllegalArgumentException e) {
-            // expected
-        }
-        fc.close();
-        assertTrue(tmpFile.delete());
-
-        // Scanner(ReadableByteChannel = null, Charset = null)
-        try {
-            s = new Scanner((ReadableByteChannel) null, null);
-            fail("Should throw NullPointerException");
-        } catch (NullPointerException e) {
-            // expected
-        }
-
-        // Scanner(ReadableByteChannel = null, Charset = invalid)
-        try {
-            s = new Scanner((ReadableByteChannel) null, "invalid");
-            fail("Should throw NullPointerException");
-        } catch (NullPointerException e) {
-            // expected
-        }
-
-        // Scanner(ReadableByteChannel, Charset = null)
-        try {
-            s = new Scanner(fc, null);
-            fail("Should throw IllegalArgumentException");
-        } catch (IllegalArgumentException e) {
-            // expected
-        }
-        // TODO: test if the specified charset is used.
-    }
-
-    /**
-     * @tests java.util.Scanner#Scanner(String)
-     */
-    @TestTargetNew(
-        level = TestLevel.COMPLETE,
-        notes = "",
-        method = "Scanner",
-        args = {java.lang.String.class}
-    )
-    public void test_ConstructorLjava_lang_String() {
-        s = new Scanner("test string");
-        assertNotNull(s);
-        s.close();
-
-        // Scanner(String)
-        try {
-            s = new Scanner((String) null);
-            fail("Should throw NullPointerException");
-        } catch (NullPointerException e) {
-            // expected
-        }
-    }
-
-    /**
-     * @tests java.util.Scanner#close()
-     */
-    @TestTargetNew(
-        level = TestLevel.COMPLETE,
-        notes = "",
-        method = "close",
-        args = {}
-    )
-    public void test_close() throws IOException {
-        File tmpFile = File.createTempFile("TestFileForScanner", ".tmp");
-        FileOutputStream fos = new FileOutputStream(tmpFile);
-        FileChannel fc = fos.getChannel();
-        s = new Scanner(fc);
-
-        // Write out a int before the scanner is closed, should be OK.
-        fos.write(12);
-
-        s.close();
-        assertFalse(fc.isOpen());
-
-        // Write out a int after the scanner is closed, IOException should be
-        // thrown out.
-        try {
-            fos.write(12);
-            fail("Should throw IOException");
-        } catch (IOException e) {
-            // expected
-        }
-
-        s.close(); // no exception should be thrown
-        assertTrue(tmpFile.delete());
-    }
-
-    /**
-     * @tests java.util.Scanner#ioException()
-     */
-    @TestTargetNew(
-        level = TestLevel.COMPLETE,
-        notes = "",
-        method = "ioException",
-        args = {}
-    )
-    public void test_ioException() throws IOException {
-        MockCloseable mc = new MockCloseable();
-        s = new Scanner(mc);
-        assertNull(s.ioException()); // No operation, no exception
-
-        s.close(); // IOException should be cached
-        assertNotNull(s.ioException());
-        assertTrue(s.ioException() instanceof IOException);
-    }
-
-    /**
-     * @tests java.util.Scanner#delimiter()
-     */
-    @TestTargetNew(
-        level = TestLevel.COMPLETE,
-        notes = "",
-        method = "delimiter",
-        args = {}
-    )
-    public void test_delimiter() {
-        s = new Scanner("test");
-        Pattern pattern = s.delimiter();
-        assertEquals("\\p{javaWhitespace}+", pattern.toString());
-    }
-
-    /**
-     * @tests java.util.Scanner#useDelimiter(Pattern)
-     */
-    @TestTargetNew(
-        level = TestLevel.COMPLETE,
-        notes = "",
-        method = "useDelimiter",
-        args = {java.util.regex.Pattern.class}
-    )
-    public void test_useDelimiter_LPattern() {
-        s = new Scanner("test");
-        s.useDelimiter(Pattern.compile("\\w+"));
-        assertEquals("\\w+", s.delimiter().toString());
-
-        s = new Scanner("test");
-        s.useDelimiter((Pattern) null);
-        assertNull(s.delimiter());
-    }
-
-    /**
-     * @tests java.util.Scanner#useDelimiter(String)
-     */
-    @TestTargetNew(
-        level = TestLevel.COMPLETE,
-        notes = "",
-        method = "useDelimiter",
-        args = {java.lang.String.class}
-    )
-    public void test_useDelimiter_String() {
-        s = new Scanner("test");
-        try {
-            s.useDelimiter((String) null);
-            fail("Should throw NullPointerException");
-        } catch (NullPointerException e) {
-            // expected
-        }
-
-        s = new Scanner("test");
-        s.useDelimiter("\\w+");
-        assertEquals("\\w+", s.delimiter().toString());
-    }
-
-    /**
-     * @tests java.util.Scanner#locale()
-     */
-    @TestTargetNew(
-        level = TestLevel.COMPLETE,
-        notes = "",
-        method = "locale",
-        args = {}
-    )
-    public void test_locale() {
-        s = new Scanner("test");
-        assertEquals(Locale.getDefault(), s.locale());
-    }
-
-    /**
-     * @tests java.util.Scanner#useLocale(Locale)
-     */
-    @TestTargetNew(
-        level = TestLevel.COMPLETE,
-        notes = "",
-        method = "useLocale",
-        args = {java.util.Locale.class}
-    )
-    public void test_useLocale_LLocale() {
-        s = new Scanner("test");
-        try {
-            s.useLocale(null);
-            fail("Should throw NullPointerException");
-        } catch (NullPointerException e) {
-            // expected
-        }
-
-        s.useLocale(new Locale("test", "test"));
-        assertEquals(new Locale("test", "test"), s.locale());
-    }
-
-    /**
-     * @tests java.util.Scanner#radix()
-     */
-    @TestTargetNew(
-        level = TestLevel.COMPLETE,
-        notes = "",
-        method = "radix",
-        args = {}
-    )
-    public void test_radix() {
-        s = new Scanner("test");
-        assertEquals(10, s.radix());
-    }
-
-    /**
-     * @tests java.util.Scanner#useRadix()
-     */
-    @TestTargetNew(
-        level = TestLevel.COMPLETE,
-        notes = "",
-        method = "useRadix",
-        args = {int.class}
-    )
-    public void test_useRadix_I() {
-        s = new Scanner("test");
-        try {
-            s.useRadix(Character.MIN_RADIX - 1);
-            fail("Should throw IllegalArgumentException");
-        } catch (IllegalArgumentException e) {
-            // expected
-        }
-        try {
-            s.useRadix(Character.MAX_RADIX + 1);
-            fail("Should throw IllegalArgumentException");
-        } catch (IllegalArgumentException e) {
-            // expected
-        }
-        s.useRadix(11);
-        assertEquals(11, s.radix());
-    }
-
-    /**
-     * @tests java.util.Scanner#remove()
-     */
-    @TestTargetNew(
-        level = TestLevel.COMPLETE,
-        notes = "",
-        method = "remove",
-        args = {}
-    )
-    public void test_remove() {
-        s = new Scanner("aab*b*").useDelimiter("\\*");
-        try {
-            s.remove();
-            fail("should throw UnsupportedOperationException");
-        } catch (UnsupportedOperationException e) {
-            //Expected
-        }
-    }
-
-    /**
-     * @tests java.util.Scanner#match()
-     */
-    @TestTargetNew(
-        level = TestLevel.COMPLETE,
-        notes = "",
-        method = "match",
-        args = {}
-    )
-    public void test_match() {
-        MatchResult result ;
-        s = new Scanner("1 2 ");
-        try {
-            s.match();
-            fail("should throw IllegalStateException");
-        } catch (IllegalStateException e) {
-            // Expected
-        }
-        assertEquals("1", s.next());
-        assertEquals("2", s.next());
-        result = s.match();
-        assertEquals(2, result.start());
-        assertEquals(3, result.end());
-        assertEquals(2, result.start(0));
-        assertEquals(3, result.end(0));
-        assertEquals("2", result.group());
-        assertEquals("2", result.group(0));
-        assertEquals(0, result.groupCount());
-        try {
-            result.start(1);
-            fail("should throw IndexOutOfBoundsException");
-        } catch (IndexOutOfBoundsException e) {
-            // Expected
-        }
-        try {
-            s.next();
-            fail("should throw NoSuchElementException");
-        } catch (NoSuchElementException e) {
-            // Expected
-        }
-        try {
-            s.match();
-            fail("should throw IllegalStateException");
-        } catch (IllegalStateException e) {
-            // Expected
-        }
-
-        s = new Scanner("True faLse");
-        try {
-            s.match();
-            fail("should throw IllegalStateException");
-        } catch (IllegalStateException e) {
-            // Expected
-        }
-        assertTrue(s.nextBoolean());
-        result = s.match();
-        assertEquals(0, result.start());
-        assertEquals(4, result.end());
-        assertEquals(0, result.start(0));
-        assertEquals(4, result.end(0));
-        assertEquals("True", result.group());
-        assertEquals(0, result.groupCount());
-        assertFalse(s.nextBoolean());
-        try {
-            s.nextBoolean();
-            fail("should throw NoSuchElementException");
-        } catch (NoSuchElementException e) {
-            // Expected
-        }
-        try {
-            s.match();
-            fail("should throw IllegalStateException");
-        } catch (IllegalStateException e) {
-            // Expected
-        }
-
-        s = new Scanner("True faLse");
-        assertTrue(s.nextBoolean());
-        result = s.match();
-        assertEquals(0, result.start());
-        assertEquals(4, result.end());
-        assertEquals(0, result.start(0));
-        assertEquals(4, result.end(0));
-        assertEquals("True", result.group());
-        assertEquals(0, result.groupCount());
-        s.close();
-        try {
-            s.nextBoolean();
-            fail("should throw IllegalStateException");
-        } catch (IllegalStateException e) {
-            // Expected
-        }
-        result = s.match();
-        assertEquals(0, result.start());
-        assertEquals(4, result.end());
-        assertEquals(0, result.start(0));
-        assertEquals(4, result.end(0));
-        assertEquals("True", result.group());
-        assertEquals(0, result.groupCount());
-
-        s = new Scanner("True fase");
-        assertTrue(s.nextBoolean());
-        assertEquals(0, result.groupCount());
-        try {
-            s.nextBoolean();
-            fail("Should throw InputMismatchException");
-        } catch (InputMismatchException e) {
-            // expected
-        }
-        try {
-            s.match();
-            fail("should throw IllegalStateException");
-        } catch (IllegalStateException e) {
-            // Expected
-        }
-
-        s = new Scanner("True fase");
-        assertTrue(s.nextBoolean());
-        try {
-            s.next((Pattern)null);
-            fail("Should throw NullPointerException");
-        } catch (NullPointerException e) {
-            // Expected
-        }
-        result = s.match();
-        assertEquals(0, result.start());
-        assertEquals(4, result.end());
-        assertEquals(0, result.start(0));
-        assertEquals(4, result.end(0));
-        assertEquals("True", result.group());
-        assertEquals(0, result.groupCount());
-
-    }
-
-    /**
-     * @throws IOException
-     * @tests java.util.Scanner#next()
-     */
-    @TestTargetNew(
-        level = TestLevel.COMPLETE,
-        notes = "",
-        method = "next",
-        args = {}
-    )
-    public void test_next() throws IOException {
-        // use special delimiter
-        s = new Scanner("1**2").useDelimiter("\\*");
-        assertEquals("1", s.next());
-        assertEquals("", s.next());
-        assertEquals("2", s.next());
-
-        s = new Scanner(" \t 1 \t 2").useDelimiter("\\s*");
-        assertEquals("1", s.next());
-        assertEquals("2", s.next());
-        try {
-            s.next();
-            fail("should throw NoSuchElementException");
-        } catch (NoSuchElementException e) {
-            // Expected
-        }
-
-        s = new Scanner("a").useDelimiter("a?");
-        try {
-            s.next();
-            fail("should throw NoSuchElementException");
-        } catch (NoSuchElementException e) {
-            // Expected
-        }
-
-        s = new Scanner("aa").useDelimiter("a?");
-        assertEquals("", s.next());
-        try {
-            s.next();
-            fail("should throw NoSuchElementException");
-        } catch (NoSuchElementException e) {
-            // Expected
-        }
-
-
-        s = new Scanner("word( )test( )").useDelimiter("\\( \\)");
-        assertEquals("word", s.next());
-        assertEquals("test", s.next());
-
-        s = new Scanner("? next  ").useDelimiter("( )");
-        assertEquals("?", s.next());
-        assertEquals("next", s.next());
-        assertEquals("", s.next());
-
-        s = new Scanner("word1 word2  ");
-        assertEquals("word1", s.next());
-        assertEquals("word2", s.next());
-        // test boundary case
-        try {
-            s.next();
-            fail("should throw NoSuchElementException");
-        } catch (NoSuchElementException e) {
-            // Expected
-        }
-
-        // just delimiter exists in this scanner
-        s = new Scanner(" ");
-        try {
-            s.next();
-            fail("Should throw NoSuchElementException");
-        } catch (NoSuchElementException e) {
-            // Expected
-        }
-
-        // nothing exists in this scanner
-        s = new Scanner("");
-        try {
-            s.next();
-            fail("Should throw NoSuchElementException");
-        } catch (NoSuchElementException e) {
-            // Expected
-        }
-
-        // no delimiter exists in this scanner
-        s = new Scanner("test");
-        assertEquals("test", s.next());
-
-        // input resourse starts with delimiter
-        s = new Scanner("  test");
-        assertEquals("test", s.next());
-
-        // input resource ends with delimiter
-        s = new Scanner("  test  ");
-        assertEquals("test", s.next());
-
-        // Harmony uses 1024 as default buffer size,
-        // What if a sentence can not be read in all in once.
-        StringBuilder longSentence = new StringBuilder(1025);
-        for (int i = 0; i < 11; i++) {
-            longSentence.append(" ");
-        }
-        for (int i = 11; i < 1026; i++) {
-            longSentence.append("a");
-        }
-        s = new Scanner(longSentence.toString());
-        assertEquals(longSentence.toString().trim(), s.next());
-
-        s = new Scanner(" test test");
-        assertEquals("test", s.next());
-        assertEquals("test", s.next());
-
-        // What if use a delimiter of length 0.
-        s = new Scanner("test\ntest").useDelimiter(Pattern.compile("^",
-                Pattern.MULTILINE));
-        assertEquals("test\n", s.next());
-        assertEquals("test", s.next());
-
-        s = new Scanner("").useDelimiter(Pattern.compile("^",
-                Pattern.MULTILINE));
-        try {
-            s.next();
-            fail("should throw NoSuchElementException");
-        } catch (NoSuchElementException e) {
-            // Expected
-        }
-
-        s = new Scanner("").useDelimiter(Pattern.compile("^*",
-                Pattern.MULTILINE));
-        try {
-            s.next();
-            fail("should throw NoSuchElementException");
-        } catch (NoSuchElementException e) {
-            // Expected
-        }
-
-        s = new Scanner("test\ntest").useDelimiter(Pattern.compile("^*",
-                Pattern.MULTILINE));
-        assertEquals("t", s.next());
-        assertEquals("e", s.next());
-
-        s = new Scanner("\ntest\ntest").useDelimiter(Pattern.compile("$",
-                Pattern.MULTILINE));
-        assertEquals("\ntest", s.next());
-        assertEquals("\ntest", s.next());
-
-        // test socket inputStream
-        // Harmony uses 1024 as default buffer size,
-        // what if the leading delimiter is larger than 1023
-        for (int i = 0; i < 1024; i++) {
-            os.write(" ".getBytes());
-        }
-        os.write("  1 2 ".getBytes());
-        s = new Scanner(client);
-        assertEquals("1", s.next());
-        assertEquals("2", s.next());
-        os.write("  1 2".getBytes());
-        serverSocket.close();
-        assertEquals("1", s.next());
-        assertEquals("2", s.next());
-        try {
-            s.next();
-            fail("should throw NoSuchElementException");
-        } catch (NoSuchElementException e) {
-            // Expected
-        }
-
-        s.close();
-        try {
-            s.next();
-            fail("IllegalStateException expected");
-        } catch (IllegalStateException e) {
-            //expected
-        }
-    }
-
-    /**
-     * @throws IOException
-     * @tests java.util.Scanner#next(Pattern)
-     */
-    @TestTargetNew(
-        level = TestLevel.COMPLETE,
-        notes = "",
-        method = "next",
-        args = {java.util.regex.Pattern.class}
-    )
-    public void test_nextLPattern() throws IOException {
-        Pattern pattern;
-        s = new Scanner("aab*2*").useDelimiter("\\*");
-        pattern = Pattern.compile("a*b");
-        assertEquals("aab", s.next(pattern));
-        try {
-            s.next(pattern);
-            fail("should throw InputMismatchException");
-        } catch (InputMismatchException e) {
-            // Expected
-        }
-
-        s = new Scanner("word ? ");
-        pattern = Pattern.compile("\\w+");
-        assertEquals("word", s.next(pattern));
-        try {
-            s.next(pattern);
-            fail("should throw InputMismatchException");
-        } catch (InputMismatchException e) {
-            // Expected
-        }
-
-        s = new Scanner("word1 word2  ");
-        pattern = Pattern.compile("\\w+");
-        assertEquals("word1", s.next(pattern));
-        assertEquals("word2", s.next(pattern));
-        // test boundary case
-        try {
-            s.next(pattern);
-            fail("should throw NoSuchElementException");
-        } catch (NoSuchElementException e) {
-            // Expected
-        }
-
-        // test socket inputStream
-
-        os.write("aab 2".getBytes());
-        serverSocket.close();
-
-        s = new Scanner(client);
-        pattern = Pattern.compile("a*b");
-        assertEquals("aab", s.next(pattern));
-        try {
-            s.next(pattern);
-            fail("should throw InputMismatchException");
-        } catch (InputMismatchException e) {
-            // Expected
-        }
-
-        s.close();
-        try {
-            s.next(pattern);
-            fail("IllegalStateException expected");
-        } catch (IllegalStateException e) {
-            //expected
-        }
-    }
-
-    /**
-     * @throws IOException
-     * @tests java.util.Scanner#next(String)
-     */
-    @TestTargetNew(
-        level = TestLevel.COMPLETE,
-        notes = "",
-        method = "next",
-        args = {java.lang.String.class}
-    )
-    public void test_nextLString() throws IOException {
-        s = new Scanner("b*a*").useDelimiter("\\*");
-        assertEquals("b", s.next("a*b"));
-        try {
-            s.next("a*b");
-            fail("should throw InputMismatchException");
-        } catch (InputMismatchException e) {
-            // Expected
-        }
-
-        s = new Scanner("word ? ");
-        assertEquals("word", s.next("\\w+"));
-        try {
-            s.next("\\w+");
-            fail("should throw InputMismatchException");
-        } catch (InputMismatchException e) {
-            // Expected
-        }
-
-        s = new Scanner("word1 next  ");
-        assertEquals("word1", s.next("\\w+"));
-        assertEquals("next", s.next("\\w+"));
-        // test boundary case
-        try {
-            s.next("\\w+");
-            fail("should throw NoSuchElementException");
-        } catch (NoSuchElementException e) {
-            // Expected
-        }
-
-        // test socket inputStream
-        os.write("aab 2".getBytes());
-        serverSocket.close();
-
-        s = new Scanner(client);
-        assertEquals("aab", s.next("a*b"));
-        try {
-            s.next("a*b");
-            fail("should throw InputMismatchException");
-        } catch (InputMismatchException e) {
-            // Expected
-        }
-
-        s.close();
-        try {
-            s.next("a*b");
-            fail("IllegalStateException expected");
-        } catch (IllegalStateException e) {
-            //expected
-        }
-    }
-
-    /**
-     * @throws IOException
-     * @tests java.util.Scanner#nextBoolean()
-     */
-    @TestTargetNew(
-        level = TestLevel.COMPLETE,
-        notes = "",
-        method = "nextBoolean",
-        args = {}
-    )
-    public void test_nextBoolean() throws IOException {
-        // case insensitive
-        s = new Scanner("TRue");
-        assertTrue(s.nextBoolean());
-
-        s = new Scanner("tRue false");
-        assertTrue(s.nextBoolean());
-        assertFalse(s.nextBoolean());
-        try {
-            s.nextBoolean();
-            fail("Should throw NoSuchElementException");
-        } catch (NoSuchElementException e) {
-            // Expected
-        }
-
-        s = new Scanner("true1");
-        try {
-            s.nextBoolean();
-            fail("Should throw InputMismatchException");
-        } catch (InputMismatchException e) {
-            // Expected
-        }
-
-        try {
-            s = new Scanner("");
-            s.nextBoolean();
-            fail("Should throw NoSuchElementException");
-        } catch (NoSuchElementException e) {
-            // Expected
-        }
-
-        // test socket inputStream
-        os.write("true false".getBytes());
-        serverSocket.close();
-
-        s = new Scanner(client);
-        assertTrue(s.nextBoolean());
-        assertFalse(s.nextBoolean());
-
-        // ues '*' as delimiter
-        s = new Scanner("true**false").useDelimiter("\\*");
-        assertTrue(s.nextBoolean());
-        try {
-            s.nextBoolean();
-            fail("should throw NoSuchElementException");
-        } catch (NoSuchElementException e) {
-            // Expected
-        }
-
-        s = new Scanner("false( )").useDelimiter("\\( \\)");
-        assertFalse(s.nextBoolean());
-
-        s.close();
-        try {
-            s.nextBoolean();
-            fail("IllegalStateException expected");
-        } catch (IllegalStateException e) {
-            //expected
-        }
-    }
-
-    /**
-     * @throws IOException
-     * @tests java.util.Scanner#nextInt(int)
-     */
-    @TestTargetNew(
-        level = TestLevel.COMPLETE,
-        notes = "",
-        method = "nextInt",
-        args = {int.class}
-    )
-    public void test_nextIntI() throws IOException {
-        Locale[] requiredLocales = {Locale.GERMANY, Locale.ENGLISH, Locale.CHINESE};
-        if (!Support_Locale.areLocalesAvailable(requiredLocales)) {
-            // locale dependent test, bug 1943269
-            return;
-        }
-        s = new Scanner("123 456");
-        assertEquals(123, s.nextInt(10));
-        assertEquals(456, s.nextInt(10));
-        try {
-            s.nextInt(10);
-            fail("Should throw NoSuchElementException");
-        } catch (NoSuchElementException e) {
-            // Expected
-        }
-
-        // If the radix is different from 10
-        s = new Scanner("123 456");
-        assertEquals(38, s.nextInt(5));
-        try {
-            s.nextInt(5);
-            fail("Should throw InputMismatchException");
-        } catch (InputMismatchException e) {
-            // Expected
-        }
-
-        // If the number is out of range
-        s = new Scanner("123456789123456789123456789123456789");
-        try {
-            s.nextInt(10);
-            fail("Should throw InputMismatchException");
-        } catch (InputMismatchException e) {
-            // Expected
-        }
-
-        /*
-         * Different locale can only recognize corresponding locale sensitive
-         * string. ',' is used in many locales as group separator.
-         */
-        s = new Scanner("23,456 23,456");
-        s.useLocale(Locale.GERMANY);
-        try {
-            s.nextInt(10);
-            fail("Should throw InputMismatchException");
-        } catch (InputMismatchException e) {
-            // expected
-        }
-        s.useLocale(Locale.ENGLISH);
-        // If exception is thrown out, input will not be advanced.
-        assertEquals(23456, s.nextInt(10));
-        assertEquals(23456, s.nextInt(10));
-
-        /*
-         * ''' is used in many locales as group separator.
-         */
-        s = new Scanner("23'456 23'456");
-        s.useLocale(Locale.GERMANY);
-        try {
-            s.nextInt(10);
-            fail("Should throw InputMismatchException");
-        } catch (InputMismatchException e) {
-            // expected
-        }
-        s.useLocale(new Locale("de", "CH"));
-        // If exception is thrown out, input will not be advanced.
-        assertEquals(23456, s.nextInt(10));
-        assertEquals(23456, s.nextInt(10));
-
-        /*
-         * The input string has Arabic-Indic digits.
-         */
-        s = new Scanner("1\u06602 1\u06662");
-        assertEquals(102, s.nextInt(10));
-        try {
-            s.nextInt(5);
-            fail("Should throw InputMismatchException");
-        } catch (InputMismatchException e) {
-            // Expected
-        }
-        assertEquals(162, s.nextInt(10));
-
-        /*
-         * '.' is used in many locales as group separator. The input string
-         * has Arabic-Indic digits .
-         */
-        s = new Scanner("23.45\u0666 23.456");
-        s.useLocale(Locale.CHINESE);
-        try {
-            s.nextInt(10);
-            fail("Should throw InputMismatchException");
-        } catch (InputMismatchException e) {
-            // expected
-        }
-        s.useLocale(Locale.GERMANY);
-        // If exception is thrown out, input will not be advanced.
-        assertEquals(23456, s.nextInt(10));
-        assertEquals(23456, s.nextInt(10));
-
-        // The input string starts with zero
-        s = new Scanner("03,456");
-        s.useLocale(Locale.ENGLISH);
-        try {
-            s.nextInt(10);
-            fail("Should throw InputMismatchException");
-        } catch (InputMismatchException e) {
-            // expected
-        }
-
-        s = new Scanner("03456");
-        assertEquals(3456, s.nextInt(10));
-
-        s = new Scanner("\u06603,456");
-        s.useLocale(Locale.ENGLISH);
-        assertEquals(3456, s.nextInt(10));
-
-        s = new Scanner("E3456");
-        assertEquals(930902, s.nextInt(16));
-        // The following test case fails on RI, because RI does not support
-        // letter as leading digit
-        if (!disableRIBugs) {
-            s = new Scanner("E3,456");
-            s.useLocale(Locale.ENGLISH);
-            assertEquals(930902, s.nextInt(16));
-        }
-
-        /*
-         * There are 3 types of zero digit in all locales, '0' '\u0966' '\u0e50'
-         * respectively, but they are not differentiated.
-         */
-        s = new Scanner("12300");
-        s.useLocale(Locale.CHINESE);
-        assertEquals(12300, s.nextInt(10));
-
-        s = new Scanner("123\u0966\u0966");
-        s.useLocale(Locale.CHINESE);
-        assertEquals(12300, s.nextInt(10));
-
-        s = new Scanner("123\u0e50\u0e50");
-        s.useLocale(Locale.CHINESE);
-        assertEquals(12300, s.nextInt(10));
-
-        /*
-         * There are three types of negative prefix all in all. '' '-' '(' There
-         * are three types of negative suffix all in all. '' '-' ')' '(' and ')'
-         * must be used togethor. Prefix '-' and suffix '-' must be used
-         * exclusively.
-         */
-
-        /*
-         * According to Integer regular expression: Integer :: = ( [-+]? (*
-         * Numeral ) ) | LocalPositivePrefix Numeral LocalPositiveSuffix |
-         * LocalNegativePrefix Numeral LocalNegativeSuffix 123- should be
-         * recognized by scanner with locale ar_AE, (123) shouble be recognized
-         * by scanner with locale mk_MK. But this is not the case on RI.
-         */
-        if (Support_Locale.areLocalesAvailable(new Locale[] {new Locale("ar", "AE")})) {
-          s = new Scanner("-123 123- -123-");
-          s.useLocale(new Locale("ar", "AE"));
-          assertEquals(-123, s.nextInt(10));
-          // The following test case fails on RI
-          if (!disableRIBugs) {
-              assertEquals(-123, s.nextInt(10));
-          }
-          try {
-              s.nextInt(10);
-              fail("Should throw InputMismatchException");
-          } catch (InputMismatchException e) {
-              // expected
-          }
-        }
-
-        // locale dependent test, bug 1943269
-        if (Support_Locale.areLocalesAvailable(new Locale[] { new Locale("mk", "MK")})) {
-            s = new Scanner("-123 123- (123)");
-            s.useLocale(new Locale("mk", "MK"));
-            assertEquals(-123, s.nextInt(10));
-            try {
-                s.nextInt();
-                fail("Should throw InputMismatchException");
-            } catch (InputMismatchException e) {
-                // expected
-            }
-            // Skip the un-recognizable token 123-.
-            assertEquals("123-", s.next());
-            // The following test case fails on RI
-            if (!disableRIBugs) {
-                assertEquals(-123, s.nextInt(10));
-
-            // If the parameter radix is illegal, the following test cases fail on
-            // RI
-                try {
-                    s.nextInt(Character.MIN_RADIX - 1);
-                    fail("Should throw IllegalArgumentException");
-                } catch (IllegalArgumentException e) {
-                    // Expected
-                }
-                try {
-                    s.nextInt(Character.MAX_RADIX + 1);
-                    fail("Should throw IllegalArgumentException");
-                } catch (IllegalArgumentException e) {
-                    // Expected
-                }
-            }
-        }
-
-        s.close();
-        try {
-            s.nextInt(10);
-            fail("IllegalStateException expected");
-        } catch (IllegalStateException e) {
-            //expected
-        }
-    }
-
-    /**
-     * @throws IOException
-     * @tests java.util.Scanner#nextInt()
-     */
-    @TestTargetNew(
-        level = TestLevel.COMPLETE,
-        notes = "",
-        method = "nextInt",
-        args = {}
-    )
-    public void test_nextInt() throws IOException {
-        Locale[] requiredLocales = {Locale.GERMANY, Locale.CHINESE, Locale.ENGLISH};
-        if (!Support_Locale.areLocalesAvailable(requiredLocales)) {
-            // locale dependent test, bug 1943269
-            return;
-        }
-        s = new Scanner("123 456");
-        assertEquals(123, s.nextInt());
-        assertEquals(456, s.nextInt());
-        try {
-            s.nextInt();
-            fail("Should throw NoSuchElementException");
-        } catch (NoSuchElementException e) {
-            // Expected
-        }
-
-        // If the radix is different from 10
-        s = new Scanner("123 456");
-        s.useRadix(5);
-        assertEquals(38, s.nextInt());
-        try {
-            s.nextInt();
-            fail("Should throw InputMismatchException");
-        } catch (InputMismatchException e) {
-            // Expected
-        }
-
-        // If the number is out of range
-        s = new Scanner("123456789123456789123456789123456789");
-        try {
-            s.nextInt();
-            fail("Should throw InputMismatchException");
-        } catch (InputMismatchException e) {
-            // Expected
-        }
-
-        /*
-         * Different locale can only recognize corresponding locale sensitive
-         * string. ',' is used in many locales as group separator.
-         */
-        s = new Scanner("23,456 23,456");
-        s.useLocale(Locale.GERMANY);
-        try {
-            s.nextInt();
-            fail("Should throw InputMismatchException");
-        } catch (InputMismatchException e) {
-            // expected
-        }
-        s.useLocale(Locale.ENGLISH);
-        // If exception is thrown out, input will not be advanced.
-        assertEquals(23456, s.nextInt());
-        assertEquals(23456, s.nextInt());
-
-        /*
-         * ''' is used in many locales as group separator.
-         */
-        s = new Scanner("23'456 23'456");
-        s.useLocale(Locale.GERMANY);
-        try {
-            s.nextInt();
-            fail("Should throw InputMismatchException");
-        } catch (InputMismatchException e) {
-            // expected
-        }
-        s.useLocale(new Locale("de", "CH"));
-        // If exception is thrown out, input will not be advanced.
-        assertEquals(23456, s.nextInt());
-        assertEquals(23456, s.nextInt());
-
-        /*
-         * The input string has Arabic-Indic digits.
-         */
-        s = new Scanner("1\u06602 1\u06662");
-        assertEquals(102, s.nextInt());
-        s.useRadix(5);
-        try {
-            s.nextInt();
-            fail("Should throw InputMismatchException");
-        } catch (InputMismatchException e) {
-            // Expected
-        }
-        s.useRadix(10);
-        assertEquals(162, s.nextInt());
-
-        /*
-         * '.' is used in many locales as group separator. The input string
-         * has Arabic-Indic digits .
-         */
-        s = new Scanner("23.45\u0666 23.456");
-        s.useLocale(Locale.CHINESE);
-        try {
-            s.nextInt();
-            fail("Should throw InputMismatchException");
-        } catch (InputMismatchException e) {
-            // expected
-        }
-        s.useLocale(Locale.GERMANY);
-        // If exception is thrown out, input will not be advanced.
-        assertEquals(23456, s.nextInt());
-        assertEquals(23456, s.nextInt());
-
-        // The input string starts with zero
-        s = new Scanner("03,456");
-        s.useLocale(Locale.ENGLISH);
-        try {
-            s.nextInt();
-            fail("Should throw InputMismatchException");
-        } catch (InputMismatchException e) {
-            // expected
-        }
-
-        s = new Scanner("03456");
-        assertEquals(3456, s.nextInt());
-
-        s = new Scanner("\u06603,456");
-        s.useLocale(Locale.ENGLISH);
-        assertEquals(3456, s.nextInt());
-
-        s = new Scanner("E3456");
-        s.useRadix(16);
-        assertEquals(930902, s.nextInt());
-
-        // The following test case fails on RI, because RI does not support
-        // letter as leading digit
-        s = new Scanner("E3,456");
-        s.useLocale(Locale.ENGLISH);
-        s.useRadix(16);
-        if (!disableRIBugs) {
-            assertEquals(930902, s.nextInt());
-        }
-
-        /*
-         * There are 3 types of zero digit in all locales, '0' '\u0966' '\u0e50'
-         * respectively, but they are not differentiated.
-         */
-        s = new Scanner("12300");
-        s.useLocale(Locale.CHINESE);
-        assertEquals(12300, s.nextInt());
-
-        s = new Scanner("123\u0966\u0966");
-        s.useLocale(Locale.CHINESE);
-        assertEquals(12300, s.nextInt());
-
-        s = new Scanner("123\u0e50\u0e50");
-        s.useLocale(Locale.CHINESE);
-        assertEquals(12300, s.nextInt());
-
-        /*
-         * There are three types of negative prefix all in all. '' '-' '(' There
-         * are three types of negative suffix all in all. '' '-' ')' '(' and ')'
-         * must be used togethor. Prefix '-' and suffix '-' must be used
-         * exclusively.
-         */
-
-        /*
-         * According to Integer regular expression: Integer :: = ( [-+]? (*
-         * Numeral ) ) | LocalPositivePrefix Numeral LocalPositiveSuffix |
-         * LocalNegativePrefix Numeral LocalNegativeSuffix 123- should be
-         * recognized by scanner with locale ar_AE, (123) shouble be recognized
-         * by scanner with locale mk_MK. But this is not the case on RI.
-         */
-        if (Support_Locale.areLocalesAvailable(new Locale[] {new Locale("ar", "AE")})) {
-          s = new Scanner("-123 123- -123-");
-          s.useLocale(new Locale("ar", "AE"));
-          assertEquals(-123, s.nextInt());
-          // The following test case fails on RI
-          if (!disableRIBugs) {
-              assertEquals(-123, s.nextInt());
-          }
-          try {
-              s.nextInt();
-              fail("Should throw InputMismatchException");
-          } catch (InputMismatchException e) {
-              // expected
-          }
-        }
-
-        // locale dependent test, bug 1943269
-        if (Support_Locale.areLocalesAvailable(new Locale[] { new Locale("mk", "MK")})) {
-            s = new Scanner("-123 123- (123)");
-            s.useLocale(new Locale("mk", "MK"));
-            assertEquals(-123, s.nextInt());
-            try {
-                s.nextInt();
-                fail("Should throw InputMismatchException");
-            } catch (InputMismatchException e) {
-                // expected
-            }
-            // Skip the un-recognizable token 123-.
-            assertEquals("123-", s.next());
-            // The following test case fails on RI
-            if (!disableRIBugs) {
-                assertEquals(-123, s.nextInt());
-            }
-        }
-
-        s.close();
-        try {
-            s.nextInt();
-            fail("IllegalStateException expected");
-        } catch (IllegalStateException e) {
-            //expected
-        }
-    }
-
-    /**
-     * @throws IOException
-     * @tests java.util.Scanner#nextByte(int)
-     */
-    @TestTargetNew(
-        level = TestLevel.COMPLETE,
-        notes = "",
-        method = "nextByte",
-        args = {int.class}
-    )
-    public void test_nextByteI() throws IOException {
-        s = new Scanner("123 126");
-        assertEquals(123, s.nextByte(10));
-        assertEquals(126, s.nextByte(10));
-        try {
-            s.nextByte(10);
-            fail("Should throw NoSuchElementException");
-        } catch (NoSuchElementException e) {
-            // Expected
-        }
-
-        // If the radix is different from 10
-        s = new Scanner("123 126");
-        assertEquals(38, s.nextByte(5));
-        try {
-            s.nextByte(5);
-            fail("Should throw InputMismatchException");
-        } catch (InputMismatchException e) {
-            // Expected
-        }
-
-        // If the number is out of range
-        s = new Scanner("1234");
-        try {
-            s.nextByte(10);
-            fail("Should throw InputMismatchException");
-        } catch (InputMismatchException e) {
-            // Expected
-        }
-
-        /*
-         * The input string has Arabic-Indic digits.
-         */
-        s = new Scanner("1\u06602 12\u0666");
-        assertEquals(102, s.nextByte(10));
-        try {
-            s.nextByte(5);
-            fail("Should throw InputMismatchException");
-        } catch (InputMismatchException e) {
-            // Expected
-        }
-        assertEquals(126, s.nextByte(10));
-
-        s = new Scanner("012");
-        assertEquals(12, s.nextByte(10));
-
-        s = new Scanner("E");
-        assertEquals(14, s.nextByte(16));
-
-        /*
-         * There are 3 types of zero digit in all locales, '0' '\u0966' '\u0e50'
-         * respectively, but they are not differentiated.
-         */
-        s = new Scanner("100");
-        s.useLocale(Locale.CHINESE);
-        assertEquals(100, s.nextByte(10));
-
-        s = new Scanner("1\u0966\u0966");
-        s.useLocale(Locale.CHINESE);
-        assertEquals(100, s.nextByte(10));
-
-        s = new Scanner("1\u0e50\u0e50");
-        s.useLocale(Locale.CHINESE);
-        assertEquals(100, s.nextByte(10));
-
-        s = new Scanner("-123");
-        s.useLocale(new Locale("ar", "AE"));
-        assertEquals(-123, s.nextByte(10));
-
-
-        s = new Scanner("-123");
-        s.useLocale(new Locale("mk", "MK"));
-        assertEquals(-123, s.nextByte(10));
-
-        s.close();
-        try {
-            s.nextByte(10);
-            fail("IllegalStateException expected");
-        } catch (IllegalStateException e) {
-            //expected
-        }
-    }
-
-    /**
-     * @throws IOException
-     * @tests java.util.Scanner#nextByte()
-     */
-    @TestTargetNew(
-        level = TestLevel.COMPLETE,
-        notes = "",
-        method = "nextByte",
-        args = {}
-    )
-    public void test_nextByte() throws IOException {
-        s = new Scanner("123 126");
-        assertEquals(123, s.nextByte());
-        assertEquals(126, s.nextByte());
-        try {
-            s.nextByte();
-            fail("Should throw NoSuchElementException");
-        } catch (NoSuchElementException e) {
-            // Expected
-        }
-
-        // If the radix is different from 10
-        s = new Scanner("123 126");
-        s.useRadix(5);
-        assertEquals(38, s.nextByte());
-        try {
-            s.nextByte();
-            fail("Should throw InputMismatchException");
-        } catch (InputMismatchException e) {
-            // Expected
-        }
-
-        // If the number is out of range
-        s = new Scanner("1234");
-        try {
-            s.nextByte();
-            fail("Should throw InputMismatchException");
-        } catch (InputMismatchException e) {
-            // Expected
-        }
-
-        /*
-         * The input string has Arabic-Indic digits.
-         */
-        s = new Scanner("1\u06602 12\u0666");
-        assertEquals(102, s.nextByte());
-        s.useRadix(5);
-        try {
-            s.nextByte();
-            fail("Should throw InputMismatchException");
-        } catch (InputMismatchException e) {
-            // Expected
-        }
-        s.useRadix(10);
-        assertEquals(126, s.nextByte());
-
-        s = new Scanner("012");
-        assertEquals(12, s.nextByte());
-
-        s = new Scanner("E");
-        s.useRadix(16);
-        assertEquals(14, s.nextByte());
-
-        /*
-         * There are 3 types of zero digit in all locales, '0' '\u0966' '\u0e50'
-         * respectively, but they are not differentiated.
-         */
-        s = new Scanner("100");
-        s.useLocale(Locale.CHINESE);
-        assertEquals(100, s.nextByte());
-
-        s = new Scanner("1\u0966\u0966");
-        s.useLocale(Locale.CHINESE);
-        assertEquals(100, s.nextByte());
-
-        s = new Scanner("1\u0e50\u0e50");
-        s.useLocale(Locale.CHINESE);
-        assertEquals(100, s.nextByte());
-
-        s = new Scanner("-123");
-        s.useLocale(new Locale("ar", "AE"));
-        assertEquals(-123, s.nextByte());
-
-        s = new Scanner("-123");
-        s.useLocale(new Locale("mk", "MK"));
-        assertEquals(-123, s.nextByte());
-
-        s.close();
-        try {
-            s.nextByte();
-            fail("IllegalStateException expected");
-        } catch (IllegalStateException e) {
-            //expected
-        }
-    }
-
-    /**
-     * @throws IOException
-     * @tests java.util.Scanner#nextFloat()
-     */
-    @TestTargetNew(
-        level = TestLevel.COMPLETE,
-        notes = "",
-        method = "nextFloat",
-        args = {}
-    )
-    public void test_nextFloat() throws IOException {
-        Locale[] requiredLocales = {Locale.ENGLISH, Locale.GERMANY};
-        if (!Support_Locale.areLocalesAvailable(requiredLocales)) {
-            // locale dependent test, bug 1943269
-            return;
-        }
-        s = new Scanner("123 45\u0666. 123.4 .123 ");
-        s.useLocale(Locale.ENGLISH);
-        assertEquals((float)123.0, s.nextFloat());
-        assertEquals((float)456.0, s.nextFloat());
-        assertEquals((float)123.4, s.nextFloat());
-        assertEquals((float)0.123, s.nextFloat());
-        try {
-            s.nextFloat();
-            fail("Should throw NoSuchElementException");
-        } catch (NoSuchElementException e) {
-            // Expected
-        }
-
-        s = new Scanner("+123.4 -456.7 123,456.789 0.1\u06623,4");
-        s.useLocale(Locale.ENGLISH);
-        assertEquals((float)123.4, s.nextFloat());
-        assertEquals((float)-456.7, s.nextFloat());
-        assertEquals((float)123456.789, s.nextFloat());
-        try {
-            s.nextFloat();
-            fail("Should throw InputMismatchException");
-        } catch (InputMismatchException e) {
-            // Expected
-        }
-
-        // Scientific notation
-        s = new Scanner("+123.4E10 -456.7e+12 123,456.789E-10");
-        s.useLocale(Locale.ENGLISH);
-        assertEquals((float)1.234E12, s.nextFloat());
-        assertEquals((float)-4.567E14, s.nextFloat());
-        assertEquals((float)1.23456789E-5, s.nextFloat());
-
-        s = new Scanner("NaN Infinity -Infinity");
-        assertEquals(Float.NaN, s.nextFloat());
-        assertEquals(Float.POSITIVE_INFINITY, s.nextFloat());
-        assertEquals(Float.NEGATIVE_INFINITY, s.nextFloat());
-
-        String str=String.valueOf(Float.MAX_VALUE*2);
-        s=new Scanner(str);
-        assertEquals(Float.POSITIVE_INFINITY,s.nextFloat());
-
-        /*
-         * Different locale can only recognize corresponding locale sensitive
-         * string. ',' is used in many locales as group separator.
-         */
-        s = new Scanner("23,456 23,456");
-        s.useLocale(Locale.ENGLISH);
-        assertEquals((float)23456.0, s.nextFloat());
-        s.useLocale(Locale.GERMANY);
-        assertEquals((float)23.456, s.nextFloat());
-
-        s = new Scanner("23.456 23.456");
-        s.useLocale(Locale.ENGLISH);
-        assertEquals((float)23.456, s.nextFloat());
-        s.useLocale(Locale.GERMANY);
-        assertEquals((float)23456.0, s.nextFloat());
-
-        s = new Scanner("23,456.7 23.456,7");
-        s.useLocale(Locale.ENGLISH);
-        assertEquals((float)23456.7, s.nextFloat());
-        s.useLocale(Locale.GERMANY);
-        assertEquals((float)23456.7, s.nextFloat());
-
-        // locale dependent test, bug 1943269
-        // Note: although "123.4-" is the correct localized form for ar_AE, the
-        // RI only accepts "-123.4".
-        if (false) {
-            s = new Scanner("-123.4 123.4- -123.4-");
-            s.useLocale(new Locale("ar", "AE"));
-            assertEquals((float)-123.4, s.nextFloat());
-            //The following test case fails on RI
-            if (!disableRIBugs) {
-                assertEquals((float)-123.4, s.nextFloat());
-            }
-            try {
-                s.nextFloat();
-                fail("Should throw InputMismatchException");
-            } catch (InputMismatchException e) {
-                // Expected
-            }
-        }
-
-        // locale dependent test, bug 1943269
-        if (Support_Locale.areLocalesAvailable(new Locale[] { new Locale("mk", "MK") })) {
-            s = new Scanner("(123) 123- -123");
-            s.useLocale(new Locale("mk", "MK"));
-            if (!disableRIBugs) {
-                assertEquals((float)-123.0, s.nextFloat());
-            }
-            try {
-                s.nextFloat();
-                fail("Should throw InputMismatchException");
-            } catch (InputMismatchException e) {
-                // Expected
-            }
-            // Skip the un-recognizable token 123-.
-            if (!disableRIBugs) {
-                assertEquals("123-", s.next());
-                assertEquals((float)-123.0, s.nextFloat());
-            }
-        }
-
-        s.close();
-        try {
-            s.nextFloat();
-            fail("IllegalStateException expected");
-        } catch (IllegalStateException e) {
-            //expected
-        }
-    }
-
-    /**
-     * @throws IOException
-     * @tests java.util.Scanner#nextBigInteger(int)
-     */
-    @TestTargetNew(
-        level = TestLevel.COMPLETE,
-        notes = "",
-        method = "nextBigInteger",
-        args = {int.class}
-    )
-    public void test_nextBigIntegerI() throws IOException {
-        s = new Scanner("123 456");
-        assertEquals(new BigInteger("123"), s.nextBigInteger(10));
-        assertEquals(new BigInteger("456"), s.nextBigInteger(10));
-        try {
-            s.nextBigInteger(10);
-            fail("Should throw NoSuchElementException");
-        } catch (NoSuchElementException e) {
-            // Expected
-        }
-
-        // If the radix is different from 10
-        s = new Scanner("123 456");
-        assertEquals(new BigInteger("38"), s.nextBigInteger(5));
-        try {
-            s.nextBigInteger(5);
-            fail("Should throw InputMismatchException");
-        } catch (InputMismatchException e) {
-            // Expected
-        }
-
-        /*
-         * Different locale can only recognize corresponding locale sensitive
-         * string. ',' is used in many locales as group separator.
-         */
-        s = new Scanner("23,456 23,456");
-        s.useLocale(Locale.GERMANY);
-        try {
-            s.nextBigInteger(10);
-            fail("Should throw InputMismatchException");
-        } catch (InputMismatchException e) {
-            // Expected
-        }
-        s.useLocale(Locale.ENGLISH);
-        // If exception is thrown out, input will not be advanced.
-        assertEquals(new BigInteger("23456"), s.nextBigInteger(10));
-        assertEquals(new BigInteger("23456"), s.nextBigInteger(10));
-
-        /*
-         * ''' is used in many locales as group separator.
-         */
-        s = new Scanner("23'456 23'456");
-        s.useLocale(Locale.GERMANY);
-        try {
-            s.nextBigInteger(10);
-            fail("Should throw InputMismatchException");
-        } catch (InputMismatchException e) {
-            // Expected
-        }
-        s.useLocale(new Locale("de", "CH"));
-        // If exception is thrown out, input will not be advanced.
-        assertEquals(new BigInteger("23456"), s.nextBigInteger(10));
-        assertEquals(new BigInteger("23456"), s.nextBigInteger(10));
-
-        /*
-         * The input string has Arabic-Indic digits.
-         */
-        s = new Scanner("1\u06602 1\u06662");
-        assertEquals(new BigInteger("102"), s.nextBigInteger(10));
-        try {
-            s.nextBigInteger(5);
-            fail("Should throw InputMismatchException");
-        } catch (InputMismatchException e) {
-            // Expected
-        }
-        assertEquals(new BigInteger("162"), s.nextBigInteger(10));
-
-        /*
-         * '.' is used in many locales as group separator. The input string
-         * has Arabic-Indic digits .
-         */
-        s = new Scanner("23.45\u0666 23.456");
-        s.useLocale(Locale.CHINESE);
-        try {
-            s.nextBigInteger(10);
-            fail("Should throw InputMismatchException");
-        } catch (InputMismatchException e) {
-            // Expected
-        }
-        s.useLocale(Locale.GERMANY);
-        // If exception is thrown out, input will not be advanced.
-        assertEquals(new BigInteger("23456"), s.nextBigInteger(10));
-        assertEquals(new BigInteger("23456"), s.nextBigInteger(10));
-
-        // The input string starts with zero
-        s = new Scanner("03,456");
-        s.useLocale(Locale.ENGLISH);
-        try {
-            s.nextBigInteger(10);
-            fail("Should throw InputMismatchException");
-        } catch (InputMismatchException e) {
-            // Expected
-        }
-
-        s = new Scanner("03456");
-        assertEquals(new BigInteger("3456"), s.nextBigInteger(10));
-
-        s = new Scanner("\u06603,456");
-        s.useLocale(Locale.ENGLISH);
-        assertEquals(new BigInteger("3456"), s.nextBigInteger(10));
-
-        s = new Scanner("E34");
-        assertEquals(new BigInteger("3636"), s.nextBigInteger(16));
-
-        /*
-         * There are 3 types of zero digit in all locales, '0' '\u0966' '\u0e50'
-         * respectively, but they are not differentiated.
-         */
-        s = new Scanner("12300");
-        s.useLocale(Locale.CHINESE);
-        assertEquals(new BigInteger("12300"), s.nextBigInteger(10));
-
-        s = new Scanner("123\u0966\u0966");
-        s.useLocale(Locale.CHINESE);
-        assertEquals(new BigInteger("12300"), s.nextBigInteger(10));
-
-        s = new Scanner("123\u0e50\u0e50");
-        s.useLocale(Locale.CHINESE);
-        assertEquals(new BigInteger("12300"), s.nextBigInteger(10));
-
-        s = new Scanner("-123");
-        s.useLocale(new Locale("ar", "AE"));
-        assertEquals(new BigInteger("-123"), s.nextBigInteger(10));
-
-
-        s = new Scanner("-123");
-        s.useLocale(new Locale("mk", "MK"));
-        assertEquals(new BigInteger("-123"), s.nextBigInteger(10));
-
-        s.close();
-        try {
-            s.nextBigInteger(10);
-            fail("IllegalStateException expected");
-        } catch (IllegalStateException e) {
-            //expected
-        }
-    }
-
-    /**
-     * @throws IOException
-     * @tests java.util.Scanner#nextBigInteger()
-     */
-    @TestTargetNew(
-        level = TestLevel.COMPLETE,
-        notes = "",
-        method = "nextBigInteger",
-        args = {}
-    )
-    public void test_nextBigInteger() throws IOException {
-        s = new Scanner("123 456");
-        assertEquals(new BigInteger("123"), s.nextBigInteger());
-        assertEquals(new BigInteger("456"), s.nextBigInteger());
-        try {
-            s.nextBigInteger();
-            fail("Should throw NoSuchElementException");
-        } catch (NoSuchElementException e) {
-            // Expected
-        }
-
-        // If the radix is different from 10
-        s = new Scanner("123 456");
-        s.useRadix(5);
-        assertEquals(new BigInteger("38"), s.nextBigInteger());
-        try {
-            s.nextBigInteger();
-            fail("Should throw InputMismatchException");
-        } catch (InputMismatchException e) {
-            // Expected
-        }
-
-        /*
-         * Different locale can only recognize corresponding locale sensitive
-         * string. ',' is used in many locales as group separator.
-         */
-        s = new Scanner("23,456 23,456");
-        s.useLocale(Locale.GERMANY);
-        try {
-            s.nextBigInteger();
-            fail("Should throw InputMismatchException");
-        } catch (InputMismatchException e) {
-            // Expected
-        }
-        s.useLocale(Locale.ENGLISH);
-        // If exception is thrown out, input will not be advanced.
-        assertEquals(new BigInteger("23456"), s.nextBigInteger());
-        assertEquals(new BigInteger("23456"), s.nextBigInteger());
-
-        /*
-         * ''' is used in many locales as group separator.
-         */
-        s = new Scanner("23'456 23'456");
-        s.useLocale(Locale.GERMANY);
-        try {
-            s.nextBigInteger();
-            fail("Should throw InputMismatchException");
-        } catch (InputMismatchException e) {
-            // Expected
-        }
-        s.useLocale(new Locale("de", "CH"));
-        // If exception is thrown out, input will not be advanced.
-        assertEquals(new BigInteger("23456"), s.nextBigInteger());
-        assertEquals(new BigInteger("23456"), s.nextBigInteger());
-
-        /*
-         * The input string has Arabic-Indic digits.
-         */
-        s = new Scanner("1\u06602 1\u06662");
-        assertEquals(new BigInteger("102"), s.nextBigInteger());
-        s.useRadix(5);
-        try {
-            s.nextBigInteger();
-            fail("Should throw InputMismatchException");
-        } catch (InputMismatchException e) {
-            // Expected
-        }
-        s.useRadix(10);
-        assertEquals(new BigInteger("162"), s.nextBigInteger());
-
-        /*
-         * '.' is used in many locales as group separator. The input string
-         * has Arabic-Indic digits .
-         */
-        s = new Scanner("23.45\u0666 23.456");
-        s.useLocale(Locale.CHINESE);
-        try {
-            s.nextBigInteger();
-            fail("Should throw InputMismatchException");
-        } catch (InputMismatchException e) {
-            // Expected
-        }
-        s.useLocale(Locale.GERMANY);
-        // If exception is thrown out, input will not be advanced.
-        assertEquals(new BigInteger("23456"), s.nextBigInteger());
-        assertEquals(new BigInteger("23456"), s.nextBigInteger());
-
-        // The input string starts with zero
-        s = new Scanner("03,456");
-        s.useLocale(Locale.ENGLISH);
-        try {
-            s.nextBigInteger();
-            fail("Should throw InputMismatchException");
-        } catch (InputMismatchException e) {
-            // Expected
-        }
-
-        s = new Scanner("03456");
-        assertEquals(new BigInteger("3456"), s.nextBigInteger());
-
-        s = new Scanner("\u06603,456");
-        s.useLocale(Locale.ENGLISH);
-        assertEquals(new BigInteger("3456"), s.nextBigInteger());
-
-        s = new Scanner("E34");
-        s.useRadix(16);
-        assertEquals(new BigInteger("3636"), s.nextBigInteger());
-
-        /*
-         * There are 3 types of zero digit in all locales, '0' '\u0966' '\u0e50'
-         * respectively, but they are not differentiated.
-         */
-        s = new Scanner("12300");
-        s.useLocale(Locale.CHINESE);
-        assertEquals(new BigInteger("12300"), s.nextBigInteger());
-
-        s = new Scanner("123\u0966\u0966");
-        s.useLocale(Locale.CHINESE);
-        assertEquals(new BigInteger("12300"), s.nextBigInteger());
-
-        s = new Scanner("123\u0e50\u0e50");
-        s.useLocale(Locale.CHINESE);
-        assertEquals(new BigInteger("12300"), s.nextBigInteger());
-
-        s = new Scanner("-123");
-        s.useLocale(new Locale("ar", "AE"));
-        assertEquals(new BigInteger("-123"), s.nextBigInteger());
-
-        s = new Scanner("-123");
-        s.useLocale(new Locale("mk", "MK"));
-        assertEquals(new BigInteger("-123"), s.nextBigInteger());
-
-        s.close();
-        try {
-            s.nextBigInteger();
-            fail("IllegalStateException expected");
-        } catch (IllegalStateException e) {
-            //expected
-        }
-    }
-
-    /**
-     * @throws IOException
-     * @tests java.util.Scanner#nextShort(int)
-     */
-    @TestTargetNew(
-        level = TestLevel.COMPLETE,
-        notes = "",
-        method = "nextShort",
-        args = {int.class}
-    )
-    public void test_nextShortI() throws IOException {
-        Locale[] requiredLocales = {Locale.GERMANY, Locale.CHINESE, Locale.ENGLISH};
-        if (!Support_Locale.areLocalesAvailable(requiredLocales)) {
-            // locale dependent test, bug 1943269
-            return;
-        }
-        s = new Scanner("123 456");
-        assertEquals(123, s.nextShort(10));
-        assertEquals(456, s.nextShort(10));
-        try {
-            s.nextShort(10);
-            fail("Should throw NoSuchElementException");
-        } catch (NoSuchElementException e) {
-            // Expected
-        }
-
-        // If the radix is different from 10
-        s = new Scanner("123 456");
-        assertEquals(38, s.nextShort(5));
-        try {
-            s.nextShort(5);
-            fail("Should throw InputMismatchException");
-        } catch (InputMismatchException e) {
-            // Expected
-        }
-
-        // If the number is out of range
-        s = new Scanner("123456789");
-        try {
-            s.nextShort(10);
-            fail("Should throw InputMismatchException");
-        } catch (InputMismatchException e) {
-            // Expected
-        }
-
-        /*
-         * Different locale can only recognize corresponding locale sensitive
-         * string. ',' is used in many locales as group separator.
-         */
-        s = new Scanner("23,456 23,456");
-        s.useLocale(Locale.GERMANY);
-        try {
-            s.nextShort(10);
-            fail("Should throw InputMismatchException");
-        } catch (InputMismatchException e) {
-            // Expected
-        }
-        s.useLocale(Locale.ENGLISH);
-        // If exception is thrown out, input will not be advanced.
-        assertEquals(23456, s.nextShort(10));
-        assertEquals(23456, s.nextShort(10));
-
-        /*
-         * ''' is used in many locales as group separator.
-         */
-        s = new Scanner("23'456 23'456");
-        s.useLocale(Locale.GERMANY);
-        try {
-            s.nextShort(10);
-            fail("Should throw InputMismatchException");
-        } catch (InputMismatchException e) {
-            // Expected
-        }
-        s.useLocale(new Locale("de", "CH"));
-        // If exception is thrown out, input will not be advanced.
-        assertEquals(23456, s.nextShort(10));
-        assertEquals(23456, s.nextShort(10));
-
-        /*
-         * The input string has Arabic-Indic digits.
-         */
-        s = new Scanner("1\u06602 1\u06662");
-        assertEquals(102, s.nextShort(10));
-        try {
-            s.nextShort(5);
-            fail("Should throw InputMismatchException");
-        } catch (InputMismatchException e) {
-            // Expected
-        }
-        assertEquals(162, s.nextShort(10));
-
-        /*
-         * '.' is used in many locales as group separator. The input string
-         * has Arabic-Indic digits .
-         */
-        s = new Scanner("23.45\u0666 23.456");
-        s.useLocale(Locale.CHINESE);
-        try {
-            s.nextShort(10);
-            fail("Should throw InputMismatchException");
-        } catch (InputMismatchException e) {
-            // Expected
-        }
-        s.useLocale(Locale.GERMANY);
-        // If exception is thrown out, input will not be advanced.
-        assertEquals(23456, s.nextShort(10));
-        assertEquals(23456, s.nextShort(10));
-
-        // The input string starts with zero
-        s = new Scanner("03,456");
-        s.useLocale(Locale.ENGLISH);
-        try {
-            s.nextShort(10);
-            fail("Should throw InputMismatchException");
-        } catch (InputMismatchException e) {
-            // Expected
-        }
-
-        s = new Scanner("03456");
-        assertEquals(3456, s.nextShort(10));
-
-        s = new Scanner("\u06603,456");
-        s.useLocale(Locale.ENGLISH);
-        assertEquals(3456, s.nextShort(10));
-
-        s = new Scanner("E34");
-        assertEquals(3636, s.nextShort(16));
-
-        /*
-         * There are 3 types of zero digit in all locales, '0' '\u0966' '\u0e50'
-         * respectively, but they are not differentiated.
-         */
-        s = new Scanner("12300");
-        s.useLocale(Locale.CHINESE);
-        assertEquals(12300, s.nextShort(10));
-
-        s = new Scanner("123\u0966\u0966");
-        s.useLocale(Locale.CHINESE);
-        assertEquals(12300, s.nextShort(10));
-
-        s = new Scanner("123\u0e50\u0e50");
-        s.useLocale(Locale.CHINESE);
-        assertEquals(12300, s.nextShort(10));
-
-        s = new Scanner("-123");
-        s.useLocale(new Locale("ar", "AE"));
-        assertEquals(-123, s.nextShort(10));
-
-
-        s = new Scanner("-123");
-        s.useLocale(new Locale("mk", "MK"));
-        assertEquals(-123, s.nextShort(10));
-
-        s.close();
-        try {
-            s.nextShort(10);
-            fail("IllegalStateException expected");
-        } catch (IllegalStateException e) {
-            //expected
-        }
-    }
-
-    /**
-     * @throws IOException
-     * @tests java.util.Scanner#nextShort()
-     */
-    @TestTargetNew(
-        level = TestLevel.COMPLETE,
-        notes = "",
-        method = "nextShort",
-        args = {}
-    )
-    public void test_nextShort() throws IOException {
-        Locale[] requiredLocales = {Locale.GERMANY, Locale.CHINESE, Locale.ENGLISH};
-        if (!Support_Locale.areLocalesAvailable(requiredLocales)) {
-            // locale dependent test, bug 1943269
-            return;
-        }
-        s = new Scanner("123 456");
-        assertEquals(123, s.nextShort());
-        assertEquals(456, s.nextShort());
-        try {
-            s.nextShort();
-            fail("Should throw NoSuchElementException");
-        } catch (NoSuchElementException e) {
-            // Expected
-        }
-
-        // If the radix is different from 10
-        s = new Scanner("123 456");
-        s.useRadix(5);
-        assertEquals(38, s.nextShort());
-        try {
-            s.nextShort();
-            fail("Should throw InputMismatchException");
-        } catch (InputMismatchException e) {
-            // Expected
-        }
-
-        // If the number is out of range
-        s = new Scanner("123456789");
-        try {
-            s.nextShort();
-            fail("Should throw InputMismatchException");
-        } catch (InputMismatchException e) {
-            // Expected
-        }
-
-        /*
-         * Different locale can only recognize corresponding locale sensitive
-         * string. ',' is used in many locales as group separator.
-         */
-        s = new Scanner("23,456 23,456");
-        s.useLocale(Locale.GERMANY);
-        try {
-            s.nextShort();
-            fail("Should throw InputMismatchException");
-        } catch (InputMismatchException e) {
-            // Expected
-        }
-        s.useLocale(Locale.ENGLISH);
-        // If exception is thrown out, input will not be advanced.
-        assertEquals(23456, s.nextShort());
-        assertEquals(23456, s.nextShort());
-
-        /*
-         * ''' is used in many locales as group separator.
-         */
-        s = new Scanner("23'456 23'456");
-        s.useLocale(Locale.GERMANY);
-        try {
-            s.nextShort();
-            fail("Should throw InputMismatchException");
-        } catch (InputMismatchException e) {
-            // Expected
-        }
-        s.useLocale(new Locale("de", "CH"));
-        // If exception is thrown out, input will not be advanced.
-        assertEquals(23456, s.nextShort());
-        assertEquals(23456, s.nextShort());
-
-        /*
-         * The input string has Arabic-Indic digits.
-         */
-        s = new Scanner("1\u06602 1\u06662");
-        assertEquals(102, s.nextShort());
-        s.useRadix(5);
-        try {
-            s.nextShort();
-            fail("Should throw InputMismatchException");
-        } catch (InputMismatchException e) {
-            // Expected
-        }
-        s.useRadix(10);
-        assertEquals(162, s.nextShort());
-
-        /*
-         * '.' is used in many locales as group separator. The input string
-         * has Arabic-Indic digits .
-         */
-        s = new Scanner("23.45\u0666 23.456");
-        s.useLocale(Locale.CHINESE);
-        try {
-            s.nextShort();
-            fail("Should throw InputMismatchException");
-        } catch (InputMismatchException e) {
-            // Expected
-        }
-        s.useLocale(Locale.GERMANY);
-        // If exception is thrown out, input will not be advanced.
-        assertEquals(23456, s.nextShort());
-        assertEquals(23456, s.nextShort());
-
-        // The input string starts with zero
-        s = new Scanner("03,456");
-        s.useLocale(Locale.ENGLISH);
-        try {
-            s.nextShort();
-            fail("Should throw InputMismatchException");
-        } catch (InputMismatchException e) {
-            // Expected
-        }
-
-        s = new Scanner("03456");
-        assertEquals(3456, s.nextShort());
-
-        s = new Scanner("\u06603,456");
-        s.useLocale(Locale.ENGLISH);
-        assertEquals(3456, s.nextShort());
-
-        s = new Scanner("E34");
-        s.useRadix(16);
-        assertEquals(3636, s.nextShort());
-
-        /*
-         * There are 3 types of zero digit in all locales, '0' '\u0966' '\u0e50'
-         * respectively, but they are not differentiated.
-         */
-        s = new Scanner("12300");
-        s.useLocale(Locale.CHINESE);
-        assertEquals(12300, s.nextShort());
-
-        s = new Scanner("123\u0966\u0966");
-        s.useLocale(Locale.CHINESE);
-        assertEquals(12300, s.nextShort());
-
-        s = new Scanner("123\u0e50\u0e50");
-        s.useLocale(Locale.CHINESE);
-        assertEquals(12300, s.nextShort());
-
-        s = new Scanner("-123");
-        s.useLocale(new Locale("ar", "AE"));
-        assertEquals(-123, s.nextShort());
-
-        s = new Scanner("-123");
-        s.useLocale(new Locale("mk", "MK"));
-        assertEquals(-123, s.nextShort());
-
-        s.close();
-        try {
-            s.nextShort();
-            fail("IllegalStateException expected");
-        } catch (IllegalStateException e) {
-            //expected
-        }
-    }
-
-    /**
-     * @throws IOException
-     * @tests java.util.Scanner#nextLong(int)
-     */
-    @TestTargetNew(
-        level = TestLevel.COMPLETE,
-        notes = "",
-        method = "nextLong",
-        args = {int.class}
-    )
-    public void test_nextLongI() throws IOException {
-        Locale[] requiredLocales = {Locale.GERMANY, Locale.CHINESE, Locale.ENGLISH};
-        if (!Support_Locale.areLocalesAvailable(requiredLocales)) {
-            // locale dependent test, bug 1943269
-            return;
-        }
-        s = new Scanner("123 456");
-        assertEquals(123, s.nextLong(10));
-        assertEquals(456, s.nextLong(10));
-        try {
-            s.nextLong(10);
-            fail("Should throw NoSuchElementException");
-        } catch (NoSuchElementException e) {
-            // Expected
-        }
-
-        // If the radix is different from 10
-        s = new Scanner("123 456");
-        assertEquals(38, s.nextLong(5));
-        try {
-            s.nextLong(5);
-            fail("Should throw InputMismatchException");
-        } catch (InputMismatchException e) {
-            // Expected
-        }
-
-        // If the number is out of range
-        s = new Scanner("123456789123456789123456789123456789");
-        try {
-            s.nextLong(10);
-            fail("Should throw InputMismatchException");
-        } catch (InputMismatchException e) {
-            // Expected
-        }
-
-        /*
-         * Different locale can only recognize corresponding locale sensitive
-         * string. ',' is used in many locales as group separator.
-         */
-        s = new Scanner("23,456 23,456");
-        s.useLocale(Locale.GERMANY);
-        try {
-            s.nextLong(10);
-            fail("Should throw InputMismatchException");
-        } catch (InputMismatchException e) {
-            // Expected
-        }
-        s.useLocale(Locale.ENGLISH);
-        // If exception is thrown out, input will not be advanced.
-        assertEquals(23456, s.nextLong(10));
-        assertEquals(23456, s.nextLong(10));
-
-        /*
-         * ''' is used in many locales as group separator.
-         */
-        s = new Scanner("23'456 23'456");
-        s.useLocale(Locale.GERMANY);
-        try {
-            s.nextLong(10);
-            fail("Should throw InputMismatchException");
-        } catch (InputMismatchException e) {
-            // Expected
-        }
-        s.useLocale(new Locale("de", "CH"));
-        // If exception is thrown out, input will not be advanced.
-        assertEquals(23456, s.nextLong(10));
-        assertEquals(23456, s.nextLong(10));
-
-        /*
-         * The input string has Arabic-Indic digits.
-         */
-        s = new Scanner("1\u06602 1\u06662");
-        assertEquals(102, s.nextLong(10));
-        try {
-            s.nextLong(5);
-            fail("Should throw InputMismatchException");
-        } catch (InputMismatchException e) {
-            // Expected
-        }
-        assertEquals(162, s.nextLong(10));
-
-        /*
-         * '.' is used in many locales as group separator. The input string
-         * has Arabic-Indic digits .
-         */
-        s = new Scanner("23.45\u0666 23.456");
-        s.useLocale(Locale.CHINESE);
-        try {
-            s.nextLong(10);
-            fail("Should throw InputMismatchException");
-        } catch (InputMismatchException e) {
-            // Expected
-        }
-        s.useLocale(Locale.GERMANY);
-        // If exception is thrown out, input will not be advanced.
-        assertEquals(23456, s.nextLong(10));
-        assertEquals(23456, s.nextLong(10));
-
-        // The input string starts with zero
-        s = new Scanner("03,456");
-        s.useLocale(Locale.ENGLISH);
-        try {
-            s.nextLong(10);
-            fail("Should throw InputMismatchException");
-        } catch (InputMismatchException e) {
-            // Expected
-        }
-
-        s = new Scanner("03456");
-        assertEquals(3456, s.nextLong(10));
-
-        s = new Scanner("\u06603,456");
-        s.useLocale(Locale.ENGLISH);
-        assertEquals(3456, s.nextLong(10));
-
-        s = new Scanner("E34");
-        assertEquals(3636, s.nextLong(16));
-
-        /*
-         * There are 3 types of zero digit in all locales, '0' '\u0966' '\u0e50'
-         * respectively, but they are not differentiated.
-         */
-        s = new Scanner("12300");
-        s.useLocale(Locale.CHINESE);
-        assertEquals(12300, s.nextLong(10));
-
-        s = new Scanner("123\u0966\u0966");
-        s.useLocale(Locale.CHINESE);
-        assertEquals(12300, s.nextLong(10));
-
-        s = new Scanner("123\u0e50\u0e50");
-        s.useLocale(Locale.CHINESE);
-        assertEquals(12300, s.nextLong(10));
-
-        s = new Scanner("-123");
-        s.useLocale(new Locale("ar", "AE"));
-        assertEquals(-123, s.nextLong(10));
-
-
-        s = new Scanner("-123");
-        s.useLocale(new Locale("mk", "MK"));
-        assertEquals(-123, s.nextLong(10));
-
-        s.close();
-        try {
-            s.nextLong(10);
-            fail("IllegalStateException expected");
-        } catch (IllegalStateException e) {
-            //expected
-        }
-    }
-
-    /**
-     * @throws IOException
-     * @tests java.util.Scanner#nextLong()
-     */
-    @TestTargetNew(
-        level = TestLevel.COMPLETE,
-        notes = "",
-        method = "nextLong",
-        args = {}
-    )
-    public void test_nextLong() throws IOException {
-        Locale[] requiredLocales = {Locale.GERMANY, Locale.CHINESE, Locale.ENGLISH};
-        if (!Support_Locale.areLocalesAvailable(requiredLocales)) {
-            // locale dependent test, bug 1943269
-            return;
-        }
-        s = new Scanner("123 456");
-        assertEquals(123, s.nextLong());
-        assertEquals(456, s.nextLong());
-        try {
-            s.nextLong();
-            fail("Should throw NoSuchElementException");
-        } catch (NoSuchElementException e) {
-            // Expected
-        }
-
-        // If the radix is different from 10
-        s = new Scanner("123 456");
-        s.useRadix(5);
-        assertEquals(38, s.nextLong());
-        try {
-            s.nextLong();
-            fail("Should throw InputMismatchException");
-        } catch (InputMismatchException e) {
-            // Expected
-        }
-
-        // If the number is out of range
-        s = new Scanner("123456789123456789123456789123456789");
-        try {
-            s.nextLong();
-            fail("Should throw InputMismatchException");
-        } catch (InputMismatchException e) {
-            // Expected
-        }
-
-        /*
-         * Different locale can only recognize corresponding locale sensitive
-         * string. ',' is used in many locales as group separator.
-         */
-        s = new Scanner("23,456 23,456");
-        s.useLocale(Locale.GERMANY);
-        try {
-            s.nextLong();
-            fail("Should throw InputMismatchException");
-        } catch (InputMismatchException e) {
-            // Expected
-        }
-        s.useLocale(Locale.ENGLISH);
-        // If exception is thrown out, input will not be advanced.
-        assertEquals(23456, s.nextLong());
-        assertEquals(23456, s.nextLong());
-
-        /*
-         * ''' is used in many locales as group separator.
-         */
-        s = new Scanner("23'456 23'456");
-        s.useLocale(Locale.GERMANY);
-        try {
-            s.nextLong();
-            fail("Should throw InputMismatchException");
-        } catch (InputMismatchException e) {
-            // Expected
-        }
-        s.useLocale(new Locale("de", "CH"));
-        // If exception is thrown out, input will not be advanced.
-        assertEquals(23456, s.nextLong());
-        assertEquals(23456, s.nextLong());
-
-        /*
-         * The input string has Arabic-Indic digits.
-         */
-        s = new Scanner("1\u06602 1\u06662");
-        assertEquals(102, s.nextLong());
-        s.useRadix(5);
-        try {
-            s.nextLong();
-            fail("Should throw InputMismatchException");
-        } catch (InputMismatchException e) {
-            // Expected
-        }
-        s.useRadix(10);
-        assertEquals(162, s.nextLong());
-
-        /*
-         * '.' is used in many locales as group separator. The input string
-         * has Arabic-Indic digits .
-         */
-        s = new Scanner("23.45\u0666 23.456");
-        s.useLocale(Locale.CHINESE);
-        try {
-            s.nextLong();
-            fail("Should throw InputMismatchException");
-        } catch (InputMismatchException e) {
-            // Expected
-        }
-        s.useLocale(Locale.GERMANY);
-        // If exception is thrown out, input will not be advanced.
-        assertEquals(23456, s.nextLong());
-        assertEquals(23456, s.nextLong());
-
-        // The input string starts with zero
-        s = new Scanner("03,456");
-        s.useLocale(Locale.ENGLISH);
-        try {
-            s.nextLong();
-            fail("Should throw InputMismatchException");
-        } catch (InputMismatchException e) {
-            // Expected
-        }
-
-        s = new Scanner("03456");
-        assertEquals(3456, s.nextLong());
-
-        s = new Scanner("\u06603,456");
-        s.useLocale(Locale.ENGLISH);
-        assertEquals(3456, s.nextLong());
-
-        s = new Scanner("E34");
-        s.useRadix(16);
-        assertEquals(3636, s.nextLong());
-
-        /*
-         * There are 3 types of zero digit in all locales, '0' '\u0966' '\u0e50'
-         * respectively, but they are not differentiated.
-         */
-        s = new Scanner("12300");
-        s.useLocale(Locale.CHINESE);
-        assertEquals(12300, s.nextLong());
-
-        s = new Scanner("123\u0966\u0966");
-        s.useLocale(Locale.CHINESE);
-        assertEquals(12300, s.nextLong());
-
-        s = new Scanner("123\u0e50\u0e50");
-        s.useLocale(Locale.CHINESE);
-        assertEquals(12300, s.nextLong());
-
-        s = new Scanner("-123");
-        s.useLocale(new Locale("ar", "AE"));
-        assertEquals(-123, s.nextLong());
-
-        s = new Scanner("-123");
-        s.useLocale(new Locale("mk", "MK"));
-        assertEquals(-123, s.nextLong());
-
-        s.close();
-        try {
-            s.nextLong();
-            fail("IllegalStateException expected");
-        } catch (IllegalStateException e) {
-            //expected
-        }
-    }
-
-    /**
-     * @throws IOException
-     * @tests java.util.Scanner#hasNext()
-     */
-    @TestTargetNew(
-        level = TestLevel.COMPLETE,
-        notes = "",
-        method = "hasNext",
-        args = {}
-    )
-    public void test_hasNext() throws IOException {
-        s = new Scanner("1##2").useDelimiter("\\#");
-        assertTrue(s.hasNext());
-        assertEquals("1", s.next());
-        assertEquals("", s.next());
-        assertEquals("2", s.next());
-        assertFalse(s.hasNext());
-        s.close();
-        try {
-            s.hasNext();
-            fail("should throw IllegalStateException");
-        } catch (IllegalStateException e) {
-            // expected
-        }
-
-        s = new Scanner("1( )2( )").useDelimiter("\\( \\)");
-        assertTrue(s.hasNext());
-        assertTrue(s.hasNext());
-        assertEquals("1", s.next());
-        assertEquals("2", s.next());
-
-        s = new Scanner("1 2  ").useDelimiter("( )");
-        assertEquals("1", s.next());
-        assertEquals("2", s.next());
-        assertTrue(s.hasNext());
-        assertEquals("", s.next());
-
-        s = new Scanner("1\n2  ");
-        assertEquals("1", s.next());
-        assertTrue(s.hasNext());
-        assertEquals("2", s.next());
-        assertFalse(s.hasNext());
-        // test boundary case
-        try {
-            s.next();
-            fail("should throw NoSuchElementException");
-        } catch (NoSuchElementException e) {
-            // Expected
-        }
-
-        s = new Scanner("1'\n'2  ");
-        assertEquals("1'", s.next());
-        assertTrue(s.hasNext());
-        assertEquals("'2", s.next());
-        assertFalse(s.hasNext());
-        // test boundary case
-        try {
-            s.next();
-            fail("should throw NoSuchElementException");
-        } catch (NoSuchElementException e) {
-            // Expected
-        }
-
-        s = new Scanner("  ");
-        assertFalse(s.hasNext());
-
-        // test socket inputStream
-
-        os.write("1 2".getBytes());
-        serverSocket.close();
-
-        s = new Scanner(client);
-        assertEquals("1", s.next());
-        assertTrue(s.hasNext());
-        assertEquals("2", s.next());
-        assertFalse(s.hasNext());
-        try {
-            s.next();
-            fail("should throw NoSuchElementException");
-        } catch (NoSuchElementException e) {
-            // Expected
-        }
-    }
-
-    /**
-     * @throws IOException
-     * @tests java.util.Scanner#hasNext(Pattern)
-     */
-    @TestTargetNew(
-        level = TestLevel.COMPLETE,
-        notes = "",
-        method = "hasNext",
-        args = {java.util.regex.Pattern.class}
-    )
-    public void test_hasNextLPattern() throws IOException {
-        Pattern pattern;
-        s = new Scanner("aab@2@abb@").useDelimiter("\\@");
-        pattern = Pattern.compile("a*b");
-        assertTrue(s.hasNext(pattern));
-        assertEquals("aab", s.next(pattern));
-        assertFalse(s.hasNext(pattern));
-        try {
-            s.next(pattern);
-            fail("should throw InputMismatchException");
-        } catch (InputMismatchException e) {
-            // Expected
-        }
-
-        s = new Scanner("word ? ");
-        pattern = Pattern.compile("\\w+");
-        assertTrue(s.hasNext(pattern));
-        assertEquals("word", s.next(pattern));
-        assertFalse(s.hasNext(pattern));
-        try {
-            s.next(pattern);
-            fail("should throw InputMismatchException");
-        } catch (InputMismatchException e) {
-            // Expected
-        }
-
-        s = new Scanner("word1 WorD2  ");
-        pattern = Pattern.compile("\\w+");
-        assertTrue(s.hasNext(pattern));
-        assertEquals("word1", s.next(pattern));
-        assertTrue(s.hasNext(pattern));
-        assertEquals("WorD2", s.next(pattern));
-        assertFalse(s.hasNext(pattern));
-        try {
-            s.next(pattern);
-            fail("should throw NoSuchElementException");
-        } catch (NoSuchElementException e) {
-            // Expected
-        }
-
-        s = new Scanner("word1 WorD2  ");
-        pattern = Pattern.compile("\\w+");
-        try {
-            s.hasNext((Pattern) null);
-            fail("Should throw NullPointerException");
-        } catch (NullPointerException e) {
-            // expected
-        }
-        s.close();
-        try {
-            s.hasNext(pattern);
-            fail("should throw IllegalStateException");
-        } catch (IllegalStateException e) {
-            // expected
-        }
-
-        // test socket inputStream
-        os.write("aab b".getBytes());
-        serverSocket.close();
-
-        s = new Scanner(client);
-        pattern = Pattern.compile("a+b");
-        assertTrue(s.hasNext(pattern));
-        assertEquals("aab", s.next(pattern));
-        assertFalse(s.hasNext(pattern));
-        try {
-            s.next(pattern);
-            fail("should throw InputMismatchException");
-        } catch (InputMismatchException e) {
-            // Expected
-        }
-    }
-
-    /**
-     * @throws IOException
-     * @tests java.util.Scanner#hasNext(String)
-     */
-    @TestTargetNew(
-        level = TestLevel.COMPLETE,
-        notes = "",
-        method = "hasNext",
-        args = {java.lang.String.class}
-    )
-    public void test_hasNextLString() throws IOException {
-        s = new Scanner("aab@2@abb@").useDelimiter("\\@");
-        try {
-            s.hasNext((String)null);
-            fail("Should throw NullPointerException");
-        } catch (NullPointerException e) {
-            // expected
-        }
-
-        s = new Scanner("aab*b*").useDelimiter("\\*");
-        assertTrue(s.hasNext("a+b"));
-        assertEquals("aab", s.next("a+b"));
-        assertFalse(s.hasNext("a+b"));
-        try {
-            s.next("a+b");
-            fail("should throw InputMismatchException");
-        } catch (InputMismatchException e) {
-            // Expected
-        }
-        s.close();
-        try {
-            s.hasNext("a+b");
-            fail("should throw IllegalStateException");
-        } catch (IllegalStateException e) {
-            // expected
-        }
-
-        s = new Scanner("WORD ? ");
-        assertTrue(s.hasNext("\\w+"));
-        assertEquals("WORD", s.next("\\w+"));
-        assertFalse(s.hasNext("\\w+"));
-        try {
-            s.next("\\w+");
-            fail("should throw InputMismatchException");
-        } catch (InputMismatchException e) {
-            // Expected
-        }
-
-        s = new Scanner("word1 word2  ");
-        assertEquals("word1", s.next("\\w+"));
-        assertEquals("word2", s.next("\\w+"));
-        // test boundary case
-        try {
-            s.next("\\w+");
-            fail("should throw NoSuchElementException");
-        } catch (NoSuchElementException e) {
-            // Expected
-        }
-
-        // test socket inputStream
-
-        os.write("aab 2".getBytes());
-        serverSocket.close();
-
-        s = new Scanner(client);
-        assertTrue(s.hasNext("a*b"));
-        assertEquals("aab", s.next("a*b"));
-        assertFalse(s.hasNext("a*b"));
-        try {
-            s.next("a*b");
-            fail("should throw InputMismatchException");
-        } catch (InputMismatchException e) {
-            // Expected
-        }
-    }
-
-    /**
-     * @throws IOException
-     * @tests java.util.Scanner#hasNextBoolean()
-     */
-    @TestTargetNew(
-        level = TestLevel.COMPLETE,
-        notes = "",
-        method = "hasNextBoolean",
-        args = {}
-    )
-    public void test_hasNextBoolean() throws IOException {
-
-        s = new Scanner("TRue");
-        assertTrue(s.hasNextBoolean());
-        assertTrue(s.nextBoolean());
-
-        s = new Scanner("tRue false");
-        assertTrue(s.hasNextBoolean());
-        assertTrue(s.nextBoolean());
-        assertTrue(s.hasNextBoolean());
-        assertFalse(s.nextBoolean());
-
-        s = new Scanner("");
-        assertFalse(s.hasNextBoolean());
-
-        // test socket inputStream
-
-        os.write("true false ".getBytes());
-        serverSocket.close();
-
-        s = new Scanner(client);
-        assertTrue(s.hasNextBoolean());
-        assertTrue(s.nextBoolean());
-
-        // ues '*' as delimiter
-        s = new Scanner("true**false").useDelimiter("\\*");
-        assertTrue(s.hasNextBoolean());
-        assertTrue(s.nextBoolean());
-        assertFalse(s.hasNextBoolean());
-        try {
-            s.nextBoolean();
-            fail("should throw NoSuchElementException");
-        } catch (NoSuchElementException e) {
-            // Expected
-        }
-
-        s = new Scanner("false( )").useDelimiter("\\( \\)");
-        assertTrue(s.hasNextBoolean());
-        assertFalse(s.nextBoolean());
-        assertFalse(s.hasNextBoolean());
-
-        s.close();
-        try {
-            s.hasNextBoolean();
-            fail("IllegalStateException expected");
-        } catch (IllegalStateException e) {
-            //expected
-        }
-    }
-
-    /**
-     * @throws IOException
-     * @tests java.util.Scanner#hasNextByte(int)
-     */
-    @TestTargetNew(
-        level = TestLevel.PARTIAL_COMPLETE,
-        notes = "IllegalStateException checking missed.",
-        method = "hasNextByte",
-        args = {int.class}
-    )
-    public void test_hasNextByteI() throws IOException {
-        s = new Scanner("123 126");
-        assertTrue(s.hasNextByte(10));
-        assertEquals(123, s.nextByte(10));
-        assertTrue(s.hasNextByte(10));
-        assertEquals(126, s.nextByte(10));
-        assertFalse(s.hasNextByte(10));
-        try {
-            s.nextByte(10);
-            fail("Should throw NoSuchElementException");
-        } catch (NoSuchElementException e) {
-            // Expected
-        }
-
-        // If the radix is different from 10
-        s = new Scanner("123 126");
-        assertTrue(s.hasNextByte(5));
-        assertEquals(38, s.nextByte(5));
-        assertFalse(s.hasNextByte(5));
-        try {
-            s.nextByte(5);
-            fail("Should throw InputMismatchException");
-        } catch (InputMismatchException e) {
-            // Expected
-        }
-
-        // If the number is out of range
-        s = new Scanner("1234");
-        assertFalse(s.hasNextByte(10));
-        try {
-            s.nextByte(10);
-            fail("Should throw InputMismatchException");
-        } catch (InputMismatchException e) {
-            // Expected
-        }
-
-        /*
-         * The input string has Arabic-Indic digits.
-         */
-        s = new Scanner("1\u06602 12\u0666");
-        assertTrue(s.hasNextByte(10));
-        assertEquals(102, s.nextByte(10));
-        assertFalse(s.hasNextByte(5));
-        try {
-            s.nextByte(5);
-            fail("Should throw InputMismatchException");
-        } catch (InputMismatchException e) {
-            // Expected
-        }
-        assertTrue(s.hasNextByte(10));
-        assertEquals(126, s.nextByte(10));
-
-        s = new Scanner("012");
-        assertTrue(s.hasNextByte(10));
-        assertEquals(12, s.nextByte(10));
-
-        s = new Scanner("E");
-        assertTrue(s.hasNextByte(16));
-        assertEquals(14, s.nextByte(16));
-
-        /*
-         * There are 3 types of zero digit in all locales, '0' '\u0966' '\u0e50'
-         * respectively, but they are not differentiated.
-         */
-        s = new Scanner("100");
-        s.useLocale(Locale.CHINESE);
-        assertTrue(s.hasNextByte(10));
-        assertEquals(100, s.nextByte(10));
-
-        s = new Scanner("1\u0966\u0966");
-        s.useLocale(Locale.CHINESE);
-        assertTrue(s.hasNextByte(10));
-        assertEquals(100, s.nextByte(10));
-
-        s = new Scanner("1\u0e50\u0e50");
-        s.useLocale(Locale.CHINESE);
-        assertTrue(s.hasNextByte(10));
-        assertEquals(100, s.nextByte(10));
-
-        s = new Scanner("-123");
-        s.useLocale(new Locale("ar", "AE"));
-        assertTrue(s.hasNextByte(10));
-        assertEquals(-123, s.nextByte(10));
-
-
-        s = new Scanner("-123");
-        s.useLocale(new Locale("mk", "MK"));
-        assertTrue(s.hasNextByte(10));
-        assertEquals(-123, s.nextByte(10));
-    }
-
-    /**
-     * @throws IOException
-     * @tests java.util.Scanner#hasNextByte(int)
-     */
-    @TestTargetNew(
-        level = TestLevel.PARTIAL_COMPLETE,
-        notes = "Regression test.",
-        method = "hasNextByte",
-        args = {int.class}
-    )
-    public void test_hasNextByteI_cache() throws IOException{
-        //regression for HARMONY-2063
-        s = new Scanner("123 45");
-        assertTrue(s.hasNextByte(8));
-        assertEquals(83, s.nextByte());
-        assertEquals(45, s.nextByte());
-
-        s = new Scanner("123 45");
-        assertTrue(s.hasNextByte(10));
-        assertTrue(s.hasNextByte(8));
-        assertEquals(83, s.nextByte());
-        assertEquals(45, s.nextByte());
-
-        s = new Scanner("-123 -45");
-        assertTrue(s.hasNextByte(8));
-        assertEquals(-123, s.nextInt());
-        assertEquals(-45, s.nextByte());
-
-        s = new Scanner("123 45");
-        assertTrue(s.hasNextByte());
-        s.close();
-        try {
-            s.nextByte();
-            fail("Should throw IllegalStateException");
-        } catch (IllegalStateException e) {
-            // expected
-        }
-    }
-    /**
-     * @throws IOException
-     * @tests java.util.Scanner#hasNextByte()
-     */
-    @TestTargetNew(
-        level = TestLevel.COMPLETE,
-        notes = "",
-        method = "hasNextByte",
-        args = {}
-    )
-    public void test_hasNextByte() throws IOException {
-        s = new Scanner("123 126");
-        assertTrue(s.hasNextByte());
-        assertEquals(123, s.nextByte());
-        assertTrue(s.hasNextByte());
-        assertEquals(126, s.nextByte());
-        assertFalse(s.hasNextByte());
-        try {
-            s.nextByte();
-            fail("Should throw NoSuchElementException");
-        } catch (NoSuchElementException e) {
-            // Expected
-        }
-
-        // If the radix is different from 10
-        s = new Scanner("123 126");
-        s.useRadix(5);
-        assertTrue(s.hasNextByte());
-        assertEquals(38, s.nextByte());
-        assertFalse(s.hasNextByte());
-        try {
-            s.nextByte();
-            fail("Should throw InputMismatchException");
-        } catch (InputMismatchException e) {
-            // Expected
-        }
-
-        // If the number is out of range
-        s = new Scanner("1234");
-        assertFalse(s.hasNextByte());
-        try {
-            s.nextByte();
-            fail("Should throw InputMismatchException");
-        } catch (InputMismatchException e) {
-            // Expected
-        }
-
-        /*
-         * The input string has Arabic-Indic digits.
-         */
-        s = new Scanner("1\u06602 12\u0666");
-        assertTrue(s.hasNextByte());
-        assertEquals(102, s.nextByte());
-        s.useRadix(5);
-        assertFalse(s.hasNextByte());
-        try {
-            s.nextByte();
-            fail("Should throw InputMismatchException");
-        } catch (InputMismatchException e) {
-            // Expected
-        }
-        s.useRadix(10);
-        assertTrue(s.hasNextByte());
-        assertEquals(126, s.nextByte());
-
-        s = new Scanner("012");
-        assertEquals(12, s.nextByte());
-
-        s = new Scanner("E");
-        s.useRadix(16);
-        assertTrue(s.hasNextByte());
-        assertEquals(14, s.nextByte());
-
-        /*
-         * There are 3 types of zero digit in all locales, '0' '\u0966' '\u0e50'
-         * respectively, but they are not differentiated.
-         */
-        s = new Scanner("100");
-        s.useLocale(Locale.CHINESE);
-        assertTrue(s.hasNextByte());
-        assertEquals(100, s.nextByte());
-
-        s = new Scanner("1\u0966\u0966");
-        s.useLocale(Locale.CHINESE);
-        assertTrue(s.hasNextByte());
-        assertEquals(100, s.nextByte());
-
-        s = new Scanner("1\u0e50\u0e50");
-        s.useLocale(Locale.CHINESE);
-        assertTrue(s.hasNextByte());
-        assertEquals(100, s.nextByte());
-
-        s = new Scanner("-123");
-        s.useLocale(new Locale("ar", "AE"));
-        assertTrue(s.hasNextByte());
-        assertEquals(-123, s.nextByte());
-
-        s = new Scanner("-123");
-        s.useLocale(new Locale("mk", "MK"));
-        assertTrue(s.hasNextByte());
-        assertEquals(-123, s.nextByte());
-
-        s.close();
-        try {
-            s.hasNextByte();
-            fail("IllegalStateException expected");
-        } catch (IllegalStateException e) {
-            //expected
-        }
-    }
-
-    /**
-     * @throws IOException
-     * @tests java.util.Scanner#hasNextBigInteger(int)
-     */
-    @TestTargetNew(
-        level = TestLevel.PARTIAL_COMPLETE,
-        notes = "IllegalStateException checking missed.",
-        method = "hasNextBigInteger",
-        args = {int.class}
-    )
-    public void test_hasNextBigIntegerI() throws IOException {
-        s = new Scanner("123 456");
-        assertTrue(s.hasNextBigInteger(10));
-        assertEquals(new BigInteger("123"), s.nextBigInteger(10));
-        assertTrue(s.hasNextBigInteger(10));
-        assertEquals(new BigInteger("456"), s.nextBigInteger(10));
-        assertFalse(s.hasNextBigInteger(10));
-        try {
-            s.nextBigInteger(10);
-            fail("Should throw NoSuchElementException");
-        } catch (NoSuchElementException e) {
-            // Expected
-        }
-
-        // If the radix is different from 10
-        s = new Scanner("123 456");
-        assertTrue(s.hasNextBigInteger(5));
-        assertEquals(new BigInteger("38"), s.nextBigInteger(5));
-        assertFalse(s.hasNextBigInteger(5));
-        try {
-            s.nextBigInteger(5);
-            fail("Should throw InputMismatchException");
-        } catch (InputMismatchException e) {
-            // Expected
-        }
-
-        /*
-         * Different locale can only recognize corresponding locale sensitive
-         * string. ',' is used in many locales as group separator.
-         */
-        s = new Scanner("23,456 23,456");
-        s.useLocale(Locale.GERMANY);
-        assertFalse(s.hasNextBigInteger(10));
-        try {
-            s.nextBigInteger(10);
-            fail("Should throw InputMismatchException");
-        } catch (InputMismatchException e) {
-            // Expected
-        }
-        s.useLocale(Locale.ENGLISH);
-        // If exception is thrown out, input will not be advanced.
-        assertTrue(s.hasNextBigInteger(10));
-        assertEquals(new BigInteger("23456"), s.nextBigInteger(10));
-        assertTrue(s.hasNextBigInteger(10));
-        assertEquals(new BigInteger("23456"), s.nextBigInteger(10));
-
-        /*
-         * ''' is used in many locales as group separator.
-         */
-        s = new Scanner("23'456 23'456");
-        s.useLocale(Locale.GERMANY);
-        assertFalse(s.hasNextBigInteger(10));
-        try {
-            s.nextBigInteger(10);
-            fail("Should throw InputMismatchException");
-        } catch (InputMismatchException e) {
-            // Expected
-        }
-        s.useLocale(new Locale("de", "CH"));
-        // If exception is thrown out, input will not be advanced.
-        assertTrue(s.hasNextBigInteger(10));
-        assertEquals(new BigInteger("23456"), s.nextBigInteger(10));
-        assertTrue(s.hasNextBigInteger(10));
-        assertEquals(new BigInteger("23456"), s.nextBigInteger(10));
-
-        /*
-         * The input string has Arabic-Indic digits.
-         */
-        s = new Scanner("1\u06602 1\u06662");
-        assertTrue(s.hasNextBigInteger(10));
-        assertEquals(new BigInteger("102"), s.nextBigInteger(10));
-        assertFalse(s.hasNextBigInteger(5));
-        try {
-            s.nextBigInteger(5);
-            fail("Should throw InputMismatchException");
-        } catch (InputMismatchException e) {
-            // Expected
-        }
-        assertTrue(s.hasNextBigInteger(10));
-        assertEquals(new BigInteger("162"), s.nextBigInteger(10));
-
-        /*
-         * '.' is used in many locales as group separator. The input string
-         * has Arabic-Indic digits .
-         */
-        s = new Scanner("23.45\u0666 23.456");
-        s.useLocale(Locale.CHINESE);
-        assertFalse(s.hasNextBigInteger(10));
-        try {
-            s.nextBigInteger(10);
-            fail("Should throw InputMismatchException");
-        } catch (InputMismatchException e) {
-            // Expected
-        }
-        s.useLocale(Locale.GERMANY);
-        // If exception is thrown out, input will not be advanced.
-        assertTrue(s.hasNextBigInteger(10));
-        assertEquals(new BigInteger("23456"), s.nextBigInteger(10));
-        assertTrue(s.hasNextBigInteger(10));
-        assertEquals(new BigInteger("23456"), s.nextBigInteger(10));
-
-        // The input string starts with zero
-        s = new Scanner("03,456");
-        s.useLocale(Locale.ENGLISH);
-        assertFalse(s.hasNextBigInteger(10));
-        try {
-            s.nextBigInteger(10);
-            fail("Should throw InputMismatchException");
-        } catch (InputMismatchException e) {
-            // Expected
-        }
-
-        s = new Scanner("03456");
-        assertTrue(s.hasNextBigInteger(10));
-        assertEquals(new BigInteger("3456"), s.nextBigInteger(10));
-
-        s = new Scanner("\u06603,456");
-        s.useLocale(Locale.ENGLISH);
-        assertTrue(s.hasNextBigInteger(10));
-        assertEquals(new BigInteger("3456"), s.nextBigInteger(10));
-
-        s = new Scanner("E34");
-        assertTrue(s.hasNextBigInteger(16));
-        assertEquals(new BigInteger("3636"), s.nextBigInteger(16));
-
-        /*
-         * There are 3 types of zero digit in all locales, '0' '\u0966' '\u0e50'
-         * respectively, but they are not differentiated.
-         */
-        s = new Scanner("12300");
-        s.useLocale(Locale.CHINESE);
-        assertTrue(s.hasNextBigInteger(10));
-        assertEquals(new BigInteger("12300"), s.nextBigInteger(10));
-
-        s = new Scanner("123\u0966\u0966");
-        s.useLocale(Locale.CHINESE);
-        assertTrue(s.hasNextBigInteger(10));
-        assertEquals(new BigInteger("12300"), s.nextBigInteger(10));
-
-        s = new Scanner("123\u0e50\u0e50");
-        s.useLocale(Locale.CHINESE);
-        assertTrue(s.hasNextBigInteger(10));
-        assertEquals(new BigInteger("12300"), s.nextBigInteger(10));
-
-        s = new Scanner("-123");
-        s.useLocale(new Locale("ar", "AE"));
-        assertTrue(s.hasNextBigInteger(10));
-        assertEquals(new BigInteger("-123"), s.nextBigInteger(10));
-
-
-        s = new Scanner("-123");
-        s.useLocale(new Locale("mk", "MK"));
-        assertTrue(s.hasNextBigInteger(10));
-        assertEquals(new BigInteger("-123"), s.nextBigInteger(10));
-    }
-
-    /**
-     * @throws IOException
-     * @tests java.util.Scanner#hasNextBigInteger(int)
-     */
-    @TestTargetNew(
-        level = TestLevel.PARTIAL_COMPLETE,
-        notes = "Regression test.",
-        method = "hasNextBigInteger",
-        args = {int.class}
-    )
-    public void test_hasNextBigIntegerI_cache() throws IOException {
-        //regression for HARMONY-2063
-        s = new Scanner("123 123456789123456789");
-        assertTrue(s.hasNextBigInteger(16));
-        assertEquals(new BigInteger("291"), s.nextBigInteger());
-        assertEquals(new BigInteger("123456789123456789"), s.nextBigInteger());
-
-        s = new Scanner("123456789123456789 456");
-        assertTrue(s.hasNextBigInteger(16));
-        assertTrue(s.hasNextBigInteger(10));
-        assertEquals(new BigInteger("123456789123456789"), s.nextBigInteger());
-        assertEquals(new BigInteger("456"), s.nextBigInteger());
-
-        s = new Scanner("-123 -123456789123456789");
-        assertTrue(s.hasNextBigInteger(8));
-        assertEquals(-123, s.nextShort());
-        assertEquals(new BigInteger("-123456789123456789"), s.nextBigInteger());
-
-        s = new Scanner("123 456");
-        assertTrue(s.hasNextBigInteger());
-        s.close();
-        try {
-            s.nextBigInteger();
-            fail("Should throw IllegalStateException");
-        } catch (IllegalStateException e) {
-            // expected
-        }
-    }
-
-    /**
-     * @throws IOException
-     * @tests java.util.Scanner#hasNextBigInteger()
-     */
-    @TestTargetNew(
-        level = TestLevel.COMPLETE,
-        notes = "",
-        method = "hasNextBigInteger",
-        args = {}
-    )
-    public void test_hasNextBigInteger() throws IOException {
-        s = new Scanner("123 456");
-        assertTrue(s.hasNextBigInteger());
-        assertEquals(new BigInteger("123"), s.nextBigInteger());
-        assertTrue(s.hasNextBigInteger());
-        assertEquals(new BigInteger("456"), s.nextBigInteger());
-        assertFalse(s.hasNextBigInteger());
-        try {
-            s.nextBigInteger();
-            fail("Should throw NoSuchElementException");
-        } catch (NoSuchElementException e) {
-            // Expected
-        }
-
-        // If the radix is different from 10
-        s = new Scanner("123 456");
-        s.useRadix(5);
-        assertTrue(s.hasNextBigInteger());
-        assertEquals(new BigInteger("38"), s.nextBigInteger());
-        assertFalse(s.hasNextBigInteger());
-        try {
-            s.nextBigInteger();
-            fail("Should throw InputMismatchException");
-        } catch (InputMismatchException e) {
-            // Expected
-        }
-
-        /*
-         * Different locale can only recognize corresponding locale sensitive
-         * string. ',' is used in many locales as group separator.
-         */
-        s = new Scanner("23,456 23,456");
-        s.useLocale(Locale.GERMANY);
-        assertFalse(s.hasNextBigInteger());
-        try {
-            s.nextBigInteger();
-            fail("Should throw InputMismatchException");
-        } catch (InputMismatchException e) {
-            // Expected
-        }
-        s.useLocale(Locale.ENGLISH);
-        // If exception is thrown out, input will not be advanced.
-        assertTrue(s.hasNextBigInteger());
-        assertEquals(new BigInteger("23456"), s.nextBigInteger());
-        assertTrue(s.hasNextBigInteger());
-        assertEquals(new BigInteger("23456"), s.nextBigInteger());
-
-        /*
-         * ''' is used in many locales as group separator.
-         */
-        s = new Scanner("23'456 23'456");
-        s.useLocale(Locale.GERMANY);
-        assertFalse(s.hasNextBigInteger());
-        try {
-            s.nextBigInteger();
-            fail("Should throw InputMismatchException");
-        } catch (InputMismatchException e) {
-            // Expected
-        }
-        s.useLocale(new Locale("de", "CH"));
-        // If exception is thrown out, input will not be advanced.
-        assertTrue(s.hasNextBigInteger());
-        assertEquals(new BigInteger("23456"), s.nextBigInteger());
-        assertTrue(s.hasNextBigInteger());
-        assertEquals(new BigInteger("23456"), s.nextBigInteger());
-
-        /*
-         * The input string has Arabic-Indic digits.
-         */
-        s = new Scanner("1\u06602 1\u06662");
-        assertEquals(new BigInteger("102"), s.nextBigInteger());
-        s.useRadix(5);
-        assertFalse(s.hasNextBigInteger());
-        try {
-            s.nextBigInteger();
-            fail("Should throw InputMismatchException");
-        } catch (InputMismatchException e) {
-            // Expected
-        }
-        s.useRadix(10);
-        assertTrue(s.hasNextBigInteger());
-        assertEquals(new BigInteger("162"), s.nextBigInteger());
-
-        /*
-         * '.' is used in many locales as group separator. The input string
-         * has Arabic-Indic digits .
-         */
-        s = new Scanner("23.45\u0666 23.456");
-        s.useLocale(Locale.CHINESE);
-        assertFalse(s.hasNextBigInteger());
-        try {
-            s.nextBigInteger();
-            fail("Should throw InputMismatchException");
-        } catch (InputMismatchException e) {
-            // Expected
-        }
-        s.useLocale(Locale.GERMANY);
-        // If exception is thrown out, input will not be advanced.
-        assertTrue(s.hasNextBigInteger());
-        assertEquals(new BigInteger("23456"), s.nextBigInteger());
-        assertTrue(s.hasNextBigInteger());
-        assertEquals(new BigInteger("23456"), s.nextBigInteger());
-
-        // The input string starts with zero
-        s = new Scanner("03,456");
-        s.useLocale(Locale.ENGLISH);
-        assertFalse(s.hasNextBigInteger());
-        try {
-            s.nextBigInteger();
-            fail("Should throw InputMismatchException");
-        } catch (InputMismatchException e) {
-            // Expected
-        }
-
-        s = new Scanner("03456");
-        assertTrue(s.hasNextBigInteger());
-        assertEquals(new BigInteger("3456"), s.nextBigInteger());
-
-        s = new Scanner("\u06603,456");
-        s.useLocale(Locale.ENGLISH);
-        assertTrue(s.hasNextBigInteger());
-        assertEquals(new BigInteger("3456"), s.nextBigInteger());
-
-        s = new Scanner("E34");
-        s.useRadix(16);
-        assertTrue(s.hasNextBigInteger());
-        assertEquals(new BigInteger("3636"), s.nextBigInteger());
-
-        /*
-         * There are 3 types of zero digit in all locales, '0' '\u0966' '\u0e50'
-         * respectively, but they are not differentiated.
-         */
-        s = new Scanner("12300");
-        s.useLocale(Locale.CHINESE);
-        assertTrue(s.hasNextBigInteger());
-        assertEquals(new BigInteger("12300"), s.nextBigInteger());
-
-        s = new Scanner("123\u0966\u0966");
-        s.useLocale(Locale.CHINESE);
-        assertTrue(s.hasNextBigInteger());
-        assertEquals(new BigInteger("12300"), s.nextBigInteger());
-
-        s = new Scanner("123\u0e50\u0e50");
-        s.useLocale(Locale.CHINESE);
-        assertTrue(s.hasNextBigInteger());
-        assertEquals(new BigInteger("12300"), s.nextBigInteger());
-
-        s = new Scanner("-123");
-        s.useLocale(new Locale("ar", "AE"));
-        assertTrue(s.hasNextBigInteger());
-        assertEquals(new BigInteger("-123"), s.nextBigInteger());
-
-        s = new Scanner("-123");
-        s.useLocale(new Locale("mk", "MK"));
-        assertTrue(s.hasNextBigInteger());
-        assertEquals(new BigInteger("-123"), s.nextBigInteger());
-
-        s.close();
-        try {
-            s.hasNextBigInteger();
-            fail("IllegalStateException expected");
-        } catch (IllegalStateException e) {
-            //expected
-        }
-    }
-
-    /**
-     * @throws IOException
-     * @tests java.util.Scanner#hasNextInt(int)
-     */
-    @TestTargetNew(
-        level = TestLevel.PARTIAL_COMPLETE,
-        notes = "IllegalStateException checking missed.",
-        method = "hasNextInt",
-        args = {int.class}
-    )
-    public void test_hasNextIntI() throws IOException {
-        Locale mkLocale = new Locale("mk", "MK");
-        Locale arLocale = new Locale("ar", "AE");
-        Locale deLocale = new Locale("de", "CH");
-        Locale[] requiredLocales = {Locale.GERMANY, Locale.ENGLISH, Locale.CHINESE,
-                mkLocale, arLocale, deLocale};
-        if (!Support_Locale.areLocalesAvailable(requiredLocales)) {
-            // locale dependent test, bug 1943269
-            return;
-        }
-        s = new Scanner("123 456");
-        assertEquals(123, s.nextInt(10));
-        assertTrue(s.hasNextInt(10));
-        assertEquals(456, s.nextInt(10));
-        assertFalse(s.hasNextInt(10));
-        try {
-            s.nextInt(10);
-            fail("Should throw NoSuchElementException");
-        } catch (NoSuchElementException e) {
-            // Expected
-        }
-
-        // If the radix is different from 10
-        s = new Scanner("123 456");
-        assertTrue(s.hasNextInt(5));
-        assertEquals(38, s.nextInt(5));
-        assertFalse(s.hasNextInt(5));
-        try {
-            s.nextInt(5);
-            fail("Should throw InputMismatchException");
-        } catch (InputMismatchException e) {
-            // Expected
-        }
-
-        // If the number is out of range
-        s = new Scanner("123456789123456789123456789123456789");
-        assertFalse(s.hasNextInt(10));
-
-        /*
-         * Different locale can only recognize corresponding locale sensitive
-         * string. ',' is used in many locales as group separator.
-         */
-        s = new Scanner("23,456");
-        s.useLocale(Locale.GERMANY);
-        assertFalse(s.hasNextInt(10));
-        s.useLocale(Locale.ENGLISH);
-        // If exception is thrown out, input will not be advanced.
-        assertTrue(s.hasNextInt(10));
-        /*
-         * ''' is used in many locales as group separator.
-         */
-        s = new Scanner("23'456");
-        s.useLocale(Locale.GERMANY);
-        assertFalse(s.hasNextInt(10));
-        s.useLocale(deLocale);
-        // If exception is thrown out, input will not be advanced.
-        assertTrue(s.hasNextInt(10));
-
-        /*
-         * The input string has Arabic-Indic digits.
-         */
-        s = new Scanner("1\u06662");
-        assertTrue(s.hasNextInt(10));
-        assertFalse(s.hasNextInt(5));
-
-        /*
-         * '.' is used in many locales as group separator. The input string
-         * has Arabic-Indic digits .
-         */
-        s = new Scanner("23.45\u0666");
-        s.useLocale(Locale.CHINESE);
-        assertFalse(s.hasNextInt(10));
-        try {
-            s.nextInt(10);
-            fail("Should throw InputMismatchException");
-        } catch (InputMismatchException e) {
-            // expected
-        }
-        s.useLocale(Locale.GERMANY);
-        assertTrue(s.hasNextInt(10));
-
-        // The input string starts with zero
-        s = new Scanner("03,456");
-        s.useLocale(Locale.ENGLISH);
-        assertFalse(s.hasNextInt(10));
-        try {
-            s.nextInt(10);
-            fail("Should throw InputMismatchException");
-        } catch (InputMismatchException e) {
-            // expected
-        }
-
-        s = new Scanner("03456");
-        assertTrue(s.hasNextInt(10));
-        assertEquals(3456, s.nextInt(10));
-
-        s = new Scanner("\u06603,456");
-        s.useLocale(Locale.ENGLISH);
-        assertTrue(s.hasNextInt(10));
-        assertEquals(3456, s.nextInt(10));
-
-        s = new Scanner("E3456");
-        assertTrue(s.hasNextInt(16));
-        assertEquals(930902, s.nextInt(16));
-        // The following test case fails on RI, because RI does not support
-        // letter as leading digit
-        s = new Scanner("E3,456");
-        s.useLocale(Locale.ENGLISH);
-        if (!disableRIBugs) {
-            assertTrue(s.hasNextInt(16));
-            assertEquals(930902, s.nextInt(16));
-
-            // If parameter radix is illegal, the following test case fails on RI
-            try {
-                s.hasNextInt(Character.MIN_RADIX - 1);
-                fail("Should throw IllegalArgumentException");
-            } catch (IllegalArgumentException e) {
-                // Expected
-            }
-        }
-
-        /*
-         * There are 3 types of zero digit in all locales, '0' '\u0966' '\u0e50'
-         * respectively, but they are not differentiated.
-         */
-        s = new Scanner("12300");
-        s.useLocale(Locale.CHINESE);
-        assertTrue(s.hasNextInt(10));
-        assertEquals(12300, s.nextInt(10));
-
-        s = new Scanner("123\u0966\u0966");
-        s.useLocale(Locale.CHINESE);
-        assertTrue(s.hasNextInt(10));
-        assertEquals(12300, s.nextInt(10));
-
-        s = new Scanner("123\u0e50\u0e50");
-        s.useLocale(Locale.CHINESE);
-        assertTrue(s.hasNextInt(10));
-        assertEquals(12300, s.nextInt(10));
-
-        /*
-         * There are three types of negative prefix all in all. '' '-' '(' There
-         * are three types of negative suffix all in all. '' '-' ')' '(' and ')'
-         * must be used togethor. Prefix '-' and suffix '-' must be used
-         * exclusively.
-         */
-
-        /*
-         * According to Integer regular expression: Integer :: = ( [-+]? (*
-         * Numeral ) ) | LocalPositivePrefix Numeral LocalPositiveSuffix |
-         * LocalNegativePrefix Numeral LocalNegativeSuffix 123- should be
-         * recognized by scanner with locale ar_AE, (123) shouble be recognized
-         * by scanner with locale mk_MK. But this is not the case on RI.
-         */
-        s = new Scanner("-123 123- -123-");
-        s.useLocale(arLocale);
-        assertTrue(s.hasNextInt(10));
-        assertEquals(-123, s.nextInt(10));
-        // The following test case fails on RI
-        if (!disableRIBugs) {
-            assertTrue(s.hasNextInt(10));
-            assertEquals(-123, s.nextInt(10));
-        }
-        assertFalse(s.hasNextInt(10));
-        try {
-            s.nextInt(10);
-            fail("Should throw InputMismatchException");
-        } catch (InputMismatchException e) {
-            // expected
-        }
-
-        s = new Scanner("-123 123- (123)");
-        s.useLocale(mkLocale);
-        assertTrue(s.hasNextInt(10));
-        assertEquals(-123, s.nextInt(10));
-        assertFalse(s.hasNextInt(10));
-        try {
-            s.nextInt();
-            fail("Should throw InputMismatchException");
-        } catch (InputMismatchException e) {
-            // expected
-        }
-        // Skip the un-recognizable token 123-.
-        assertEquals("123-", s.next());
-        // The following test case fails on RI
-        if (!disableRIBugs) {
-            assertTrue(s.hasNextInt(10));
-            assertEquals(-123, s.nextInt(10));
-        }
-    }
-
-    /**
-     * @throws IOException
-     * @tests java.util.Scanner#hasNextInt(int)
-     */
-    @TestTargetNew(
-        level = TestLevel.PARTIAL_COMPLETE,
-        notes = "Regression test",
-        method = "hasNextInt",
-        args = {int.class}
-    )
-    public void test_hasNextIntI_cache() throws IOException {
-        //regression for HARMONY-2063
-        s = new Scanner("123 456");
-        assertTrue(s.hasNextInt(16));
-        assertEquals(291, s.nextInt(10));
-        assertEquals(456, s.nextInt());
-
-        s = new Scanner("123 456");
-        assertTrue(s.hasNextInt(16));
-        assertTrue(s.hasNextInt(8));
-        assertEquals(83, s.nextInt());
-        assertEquals(456, s.nextInt());
-
-        s = new Scanner("-123 -456 -789");
-        assertTrue(s.hasNextInt(8));
-        assertEquals(-123, s.nextShort());
-        assertEquals(-456, s.nextInt());
-        assertTrue(s.hasNextShort(16));
-        assertEquals(-789, s.nextInt());
-
-        s = new Scanner("123 456");
-        assertTrue(s.hasNextInt());
-        s.close();
-        try {
-            s.nextInt();
-            fail("Should throw IllegalStateException");
-        } catch (IllegalStateException e) {
-            // expected
-        }
-    }
-    /**
-     * @throws IOException
-     * @tests java.util.Scanner#hasNextInt()
-     */
-    @TestTargetNew(
-        level = TestLevel.COMPLETE,
-        notes = "",
-        method = "hasNextInt",
-        args = {}
-    )
-    public void test_hasNextInt() throws IOException {
-        Locale mkLocale = new Locale("mk", "MK");
-        Locale arLocale = new Locale("ar", "AE");
-        Locale deLocale = new Locale("de", "CH");
-        Locale[] requiredLocales = {Locale.GERMANY, Locale.ENGLISH, Locale.CHINESE,
-                mkLocale, arLocale, deLocale};
-        if (!Support_Locale.areLocalesAvailable(requiredLocales)) {
-            // locale dependent test, bug 1943269
-            return;
-        }
-        s = new Scanner("123 456");
-        assertTrue(s.hasNextInt());
-        assertEquals(123, s.nextInt());
-        assertEquals(456, s.nextInt());
-        assertFalse(s.hasNextInt());
-        try {
-            s.nextInt();
-            fail("Should throw NoSuchElementException");
-        } catch (NoSuchElementException e) {
-            // Expected
-        }
-
-        // If the radix is different from 10
-        s = new Scanner("123 456");
-        s.useRadix(5);
-        assertTrue(s.hasNextInt());
-        assertEquals(38, s.nextInt());
-        assertFalse(s.hasNextInt());
-        try {
-            s.nextInt();
-            fail("Should throw InputMismatchException");
-        } catch (InputMismatchException e) {
-            // Expected
-        }
-
-        // If the number is out of range
-        s = new Scanner("123456789123456789123456789123456789");
-        assertFalse(s.hasNextInt());
-
-        /*
-         * Different locale can only recognize corresponding locale sensitive
-         * string. ',' is used in many locales as group separator.
-         */
-        s = new Scanner("23,456");
-        s.useLocale(Locale.GERMANY);
-        assertFalse(s.hasNextInt());
-        s.useLocale(Locale.ENGLISH);
-        assertTrue(s.hasNextInt());
-
-        /*
-         * ''' is used in many locales as group separator.
-         */
-        s = new Scanner("23'456");
-        s.useLocale(Locale.GERMANY);
-        assertFalse(s.hasNextInt());
-        s.useLocale(deLocale);
-        assertTrue(s.hasNextInt());
-
-        /*
-         * The input string has Arabic-Indic digits.
-         */
-        s = new Scanner("1\u06662");
-        s.useRadix(5);
-        assertFalse(s.hasNextInt());
-
-        /*
-         * '.' is used in many locales as group separator. The input string
-         * has Arabic-Indic digits .
-         */
-        s = new Scanner("23.45\u0666");
-        s.useLocale(Locale.CHINESE);
-        assertFalse(s.hasNextInt());
-        s.useLocale(Locale.GERMANY);
-        assertTrue(s.hasNextInt());
-
-        // The input string starts with zero
-        s = new Scanner("03,456");
-        s.useLocale(Locale.ENGLISH);
-        assertFalse(s.hasNextInt());
-        try {
-            s.nextInt();
-            fail("Should throw InputMismatchException");
-        } catch (InputMismatchException e) {
-            // expected
-        }
-
-        s = new Scanner("03456");
-        assertTrue(s.hasNextInt());
-        assertEquals(3456, s.nextInt());
-
-        s = new Scanner("\u06603,456");
-        s.useLocale(Locale.ENGLISH);
-        assertEquals(3456, s.nextInt());
-
-        s = new Scanner("E3456");
-        s.useRadix(16);
-        assertTrue(s.hasNextInt());
-        assertEquals(930902, s.nextInt());
-
-        // The following test case fails on RI, because RI does not support
-        // letter as leading digit
-        s = new Scanner("E3,456");
-        s.useLocale(Locale.ENGLISH);
-        s.useRadix(16);
-        if (!disableRIBugs) {
-            assertTrue(s.hasNextInt());
-            assertEquals(930902, s.nextInt());
-        }
-
-        /*
-         * There are 3 types of zero digit in all locales, '0' '\u0966' '\u0e50'
-         * respectively, but they are not differentiated.
-         */
-        s = new Scanner("12300");
-        s.useLocale(Locale.CHINESE);
-        assertTrue(s.hasNextInt());
-        assertEquals(12300, s.nextInt());
-
-        s = new Scanner("123\u0966\u0966");
-        s.useLocale(Locale.CHINESE);
-        assertTrue(s.hasNextInt());
-        assertEquals(12300, s.nextInt());
-
-        s = new Scanner("123\u0e50\u0e50");
-        s.useLocale(Locale.CHINESE);
-        assertTrue(s.hasNextInt());
-        assertEquals(12300, s.nextInt());
-
-        /*
-         * There are three types of negative prefix all in all. '' '-' '(' There
-         * are three types of negative suffix all in all. '' '-' ')' '(' and ')'
-         * must be used togethor. Prefix '-' and suffix '-' must be used
-         * exclusively.
-         */
-
-        /*
-         * According to Integer regular expression: Integer :: = ( [-+]? (*
-         * Numeral ) ) | LocalPositivePrefix Numeral LocalPositiveSuffix |
-         * LocalNegativePrefix Numeral LocalNegativeSuffix 123- should be
-         * recognized by scanner with locale ar_AE, (123) shouble be recognized
-         * by scanner with locale mk_MK. But this is not the case on RI.
-         */
-        s = new Scanner("-123 123- -123-");
-        s.useLocale(arLocale);
-        assertTrue(s.hasNextInt());
-        assertEquals(-123, s.nextInt());
-        // The following test case fails on RI
-        if (!disableRIBugs) {
-            assertTrue(s.hasNextInt());
-            assertEquals(-123, s.nextInt());
-        }
-        assertFalse(s.hasNextInt());
-        try {
-            s.nextInt();
-            fail("Should throw InputMismatchException");
-        } catch (InputMismatchException e) {
-            // expected
-        }
-
-        s = new Scanner("-123 123- (123)");
-        s.useLocale(mkLocale);
-        assertTrue(s.hasNextInt());
-        assertEquals(-123, s.nextInt());
-        try {
-            s.nextInt();
-            fail("Should throw InputMismatchException");
-        } catch (InputMismatchException e) {
-            // expected
-        }
-        // Skip the un-recognizable token 123-.
-        assertEquals("123-", s.next());
-        // The following test case fails on RI
-        if (!disableRIBugs) {
-            assertTrue(s.hasNextInt());
-            assertEquals(-123, s.nextInt());
-        }
-
-        s.close();
-        try {
-            s.hasNextInt();
-            fail("IllegalStateException expected");
-        } catch (IllegalStateException e) {
-            //expected
-        }
-    }
-
-    /**
-     * @throws IOException
-     * @tests java.util.Scanner#hasNextFloat()
-     */
-    @TestTargetNew(
-        level = TestLevel.COMPLETE,
-        notes = "",
-        method = "hasNextFloat",
-        args = {}
-    )
-    public void test_hasNextFloat() throws IOException {
-        Locale mkLocale = new Locale("mk", "MK");
-        Locale arLocale = new Locale("ar", "AE");
-        Locale[] requiredLocales = {Locale.GERMANY, Locale.ENGLISH, mkLocale, arLocale};
-        if (!Support_Locale.areLocalesAvailable(requiredLocales)) {
-            // locale dependent test, bug 1943269
-            return;
-        }
-        s = new Scanner("123 45\u0666. 123.4 .123 ");
-        s.useLocale(Locale.ENGLISH);
-        assertTrue(s.hasNextFloat());
-        assertEquals((float)123.0, s.nextFloat());
-        assertTrue(s.hasNextFloat());
-        assertEquals((float)456.0, s.nextFloat());
-        assertTrue(s.hasNextFloat());
-        assertEquals((float)123.4, s.nextFloat());
-        assertTrue(s.hasNextFloat());
-        assertEquals((float)0.123, s.nextFloat());
-        assertFalse(s.hasNextFloat());
-        try {
-            s.nextFloat();
-            fail("Should throw NoSuchElementException");
-        } catch (NoSuchElementException e) {
-            // Expected
-        }
-
-        s = new Scanner("+123.4 -456.7 123,456.789 0.1\u06623,4");
-        s.useLocale(Locale.ENGLISH);
-        assertTrue(s.hasNextFloat());
-        assertEquals((float)123.4, s.nextFloat());
-        assertTrue(s.hasNextFloat());
-        assertEquals((float)-456.7, s.nextFloat());
-        assertTrue(s.hasNextFloat());
-        assertEquals((float)123456.789, s.nextFloat());
-        assertFalse(s.hasNextFloat());
-        try {
-            s.nextFloat();
-            fail("Should throw InputMismatchException");
-        } catch (InputMismatchException e) {
-            // Expected
-        }
-
-        // Scientific notation
-        s = new Scanner("+123.4E10 -456.7e+12 123,456.789E-10");
-        s.useLocale(Locale.ENGLISH);
-        assertTrue(s.hasNextFloat());
-        assertEquals((float)1.234E12, s.nextFloat());
-        assertTrue(s.hasNextFloat());
-        assertEquals((float)-4.567E14, s.nextFloat());
-        assertTrue(s.hasNextFloat());
-        assertEquals((float)1.23456789E-5, s.nextFloat());
-
-        s = new Scanner("NaN Infinity -Infinity");
-        assertTrue(s.hasNextFloat());
-        assertEquals(Float.NaN, s.nextFloat());
-        assertTrue(s.hasNextFloat());
-        assertEquals(Float.POSITIVE_INFINITY, s.nextFloat());
-        assertTrue(s.hasNextFloat());
-        assertEquals(Float.NEGATIVE_INFINITY, s.nextFloat());
-
-        String str=String.valueOf(Float.MAX_VALUE*2);
-        s=new Scanner(str);
-        assertTrue(s.hasNextFloat());
-        assertEquals(Float.POSITIVE_INFINITY,s.nextFloat());
-
-        /*
-         * Different locale can only recognize corresponding locale sensitive
-         * string. ',' is used in many locales as group separator.
-         */
-        s = new Scanner("23,456 23,456");
-        s.useLocale(Locale.ENGLISH);
-        assertTrue(s.hasNextFloat());
-        assertEquals((float)23456.0, s.nextFloat());
-        s.useLocale(Locale.GERMANY);
-        assertTrue(s.hasNextFloat());
-        assertEquals((float)23.456, s.nextFloat());
-
-        s = new Scanner("23.456 23.456");
-        s.useLocale(Locale.ENGLISH);
-        assertTrue(s.hasNextFloat());
-        assertEquals((float)23.456, s.nextFloat());
-        s.useLocale(Locale.GERMANY);
-        assertTrue(s.hasNextFloat());
-        assertEquals((float)23456.0, s.nextFloat());
-
-        s = new Scanner("23,456.7 23.456,7");
-        s.useLocale(Locale.ENGLISH);
-        assertTrue(s.hasNextFloat());
-        assertEquals((float)23456.7, s.nextFloat());
-        s.useLocale(Locale.GERMANY);
-        assertTrue(s.hasNextFloat());
-        assertEquals((float)23456.7, s.nextFloat());
-
-        s = new Scanner("-123.4 123.4- -123.4-");
-        s.useLocale(arLocale);
-        assertTrue(s.hasNextFloat());
-        assertEquals((float)-123.4, s.nextFloat());
-        //The following test case fails on RI
-        if (!disableRIBugs) {
-            assertTrue(s.hasNextFloat());
-            assertEquals((float)-123.4, s.nextFloat());
-        }
-        try {
-            s.nextFloat();
-            fail("Should throw InputMismatchException");
-        } catch (InputMismatchException e) {
-            // Expected
-        }
-
-        s = new Scanner("(123) 123- -123");
-        s.useLocale(mkLocale);
-        if (!disableRIBugs) {
-            assertTrue(s.hasNextFloat());
-            assertEquals((float)-123.0, s.nextFloat());
-        }
-        assertFalse(s.hasNextFloat());
-        try {
-            s.nextFloat();
-            fail("Should throw InputMismatchException");
-        } catch (InputMismatchException e) {
-            // Expected
-        }
-        // Skip the un-recognizable token 123-.
-        if (!disableRIBugs) {
-            assertEquals("123-", s.next());
-            assertTrue(s.hasNextFloat());
-            assertEquals((float)-123.0, s.nextFloat());
-        }
-
-        s = new Scanner("+123.4 -456.7");
-        s.useLocale(Locale.ENGLISH);
-        assertTrue(s.hasNextFloat());
-        s.close();
-        try{
-            s.nextFloat();
-            fail("Should throw IllegalStateException");
-        }catch(IllegalStateException e){
-            //expected
-        }
-
-    }
-
-    /**
-     * @throws IOException
-     * @tests java.util.Scanner#hasNextShort(int)
-     */
-    @TestTargetNew(
-        level = TestLevel.PARTIAL_COMPLETE,
-        notes = "IllegalStateException checking missed.",
-        method = "hasNextShort",
-        args = {int.class}
-    )
-    public void test_hasNextShortI() throws IOException {
-        Locale[] requiredLocales = {Locale.GERMANY, Locale.ENGLISH, Locale.CHINESE};
-        if (!Support_Locale.areLocalesAvailable(requiredLocales)) {
-            // locale dependent test, bug 1943269
-            return;
-        }
-        s = new Scanner("123 456");
-        assertTrue(s.hasNextShort(10));
-        assertEquals(123, s.nextShort(10));
-        assertTrue(s.hasNextShort(10));
-        assertEquals(456, s.nextShort(10));
-        assertFalse(s.hasNextShort(10));
-        try {
-            s.nextShort(10);
-            fail("Should throw NoSuchElementException");
-        } catch (NoSuchElementException e) {
-            // Expected
-        }
-
-        // If the radix is different from 10
-        s = new Scanner("123 456");
-        assertTrue(s.hasNextShort(5));
-        assertEquals(38, s.nextShort(5));
-        assertFalse(s.hasNextShort(5));
-        try {
-            s.nextShort(5);
-            fail("Should throw InputMismatchException");
-        } catch (InputMismatchException e) {
-            // Expected
-        }
-
-        // If the number is out of range
-        s = new Scanner("123456789");
-        assertFalse(s.hasNextShort(10));
-        try {
-            s.nextShort(10);
-            fail("Should throw InputMismatchException");
-        } catch (InputMismatchException e) {
-            // Expected
-        }
-
-        /*
-         * Different locale can only recognize corresponding locale sensitive
-         * string. ',' is used in many locales as group separator.
-         */
-        s = new Scanner("23,456 23,456");
-        s.useLocale(Locale.GERMANY);
-        assertFalse(s.hasNextShort(10));
-        try {
-            s.nextShort(10);
-            fail("Should throw InputMismatchException");
-        } catch (InputMismatchException e) {
-            // Expected
-        }
-        s.useLocale(Locale.ENGLISH);
-        // If exception is thrown out, input will not be advanced.
-        assertTrue(s.hasNextShort(10));
-        assertEquals(23456, s.nextInt(10));
-        assertTrue(s.hasNextShort(10));
-        assertEquals(23456, s.nextInt(10));
-
-        /*
-         * ''' is used in many locales as group separator.
-         */
-        s = new Scanner("23'456 23'456");
-        s.useLocale(Locale.GERMANY);
-        assertFalse(s.hasNextShort(10));
-        try {
-            s.nextShort(10);
-            fail("Should throw InputMismatchException");
-        } catch (InputMismatchException e) {
-            // Expected
-        }
-        s.useLocale(new Locale("de", "CH"));
-        // If exception is thrown out, input will not be advanced.
-        assertTrue(s.hasNextShort(10));
-        assertEquals(23456, s.nextShort(10));
-        assertTrue(s.hasNextShort(10));
-        assertEquals(23456, s.nextShort(10));
-
-        /*
-         * The input string has Arabic-Indic digits.
-         */
-        s = new Scanner("1\u06602 1\u06662");
-        assertTrue(s.hasNextShort(10));
-        assertEquals(102, s.nextShort(10));
-        assertFalse(s.hasNextShort(5));
-        try {
-            s.nextShort(5);
-            fail("Should throw InputMismatchException");
-        } catch (InputMismatchException e) {
-            // Expected
-        }
-        assertTrue(s.hasNextShort(10));
-        assertEquals(162, s.nextShort(10));
-
-        /*
-         * '.' is used in many locales as group separator. The input string
-         * has Arabic-Indic digits .
-         */
-        s = new Scanner("23.45\u0666 23.456");
-        s.useLocale(Locale.CHINESE);
-        assertFalse(s.hasNextShort(10));
-        try {
-            s.nextShort(10);
-            fail("Should throw InputMismatchException");
-        } catch (InputMismatchException e) {
-            // Expected
-        }
-        s.useLocale(Locale.GERMANY);
-        // If exception is thrown out, input will not be advanced.
-        assertTrue(s.hasNextShort(10));
-        assertEquals(23456, s.nextShort(10));
-        assertTrue(s.hasNextShort(10));
-        assertEquals(23456, s.nextShort(10));
-
-        // The input string starts with zero
-        s = new Scanner("03,456");
-        s.useLocale(Locale.ENGLISH);
-        assertFalse(s.hasNextShort(10));
-        try {
-            s.nextShort(10);
-            fail("Should throw InputMismatchException");
-        } catch (InputMismatchException e) {
-            // Expected
-        }
-
-        s = new Scanner("03456");
-        assertTrue(s.hasNextShort(10));
-        assertEquals(3456, s.nextShort(10));
-
-        s = new Scanner("\u06603,456");
-        s.useLocale(Locale.ENGLISH);
-        assertTrue(s.hasNextShort(10));
-        assertEquals(3456, s.nextShort(10));
-
-        s = new Scanner("E34");
-        assertTrue(s.hasNextShort(16));
-        assertEquals(3636, s.nextShort(16));
-
-        /*
-         * There are 3 types of zero digit in all locales, '0' '\u0966' '\u0e50'
-         * respectively, but they are not differentiated.
-         */
-        s = new Scanner("12300");
-        s.useLocale(Locale.CHINESE);
-        assertTrue(s.hasNextShort(10));
-        assertEquals(12300, s.nextShort(10));
-
-        s = new Scanner("123\u0966\u0966");
-        s.useLocale(Locale.CHINESE);
-        assertTrue(s.hasNextShort(10));
-        assertEquals(12300, s.nextShort(10));
-
-        s = new Scanner("123\u0e50\u0e50");
-        s.useLocale(Locale.CHINESE);
-        assertTrue(s.hasNextShort(10));
-        assertEquals(12300, s.nextShort(10));
-
-        s = new Scanner("-123");
-        s.useLocale(new Locale("ar", "AE"));
-        assertTrue(s.hasNextShort(10));
-        assertEquals(-123, s.nextShort(10));
-
-
-        s = new Scanner("-123");
-        s.useLocale(new Locale("mk", "MK"));
-        assertTrue(s.hasNextShort(10));
-        assertEquals(-123, s.nextShort(10));
-    }
-
-    /**
-     * @throws IOException
-     * @tests java.util.Scanner#hasNextShort()
-     */
-    @TestTargetNew(
-        level = TestLevel.COMPLETE,
-        notes = "",
-        method = "hasNextShort",
-        args = {}
-    )
-    public void test_hasNextShort() throws IOException {
-        Locale deLocale = new Locale("de", "CH");
-        Locale arLocale = new Locale("ar", "AE");
-        Locale mkLocale = new Locale("mk", "MK");
-        Locale[] requiredLocales = {Locale.GERMANY, Locale.ENGLISH, Locale.CHINESE, deLocale,
-                arLocale, mkLocale};
-        if (!Support_Locale.areLocalesAvailable(requiredLocales)) {
-            // locale dependent test, bug 1943269
-            return;
-        }
-        s = new Scanner("123 456");
-        assertTrue(s.hasNextShort());
-        assertEquals(123, s.nextShort());
-        assertTrue(s.hasNextShort());
-        assertEquals(456, s.nextShort());
-        assertFalse(s.hasNextShort());
-        try {
-            s.nextShort();
-            fail("Should throw NoSuchElementException");
-        } catch (NoSuchElementException e) {
-            // Expected
-        }
-
-        // If the radix is different from 10
-        s = new Scanner("123 456");
-        s.useRadix(5);
-        assertTrue(s.hasNextShort());
-        assertEquals(38, s.nextShort());
-        assertFalse(s.hasNextShort());
-        try {
-            s.nextShort();
-            fail("Should throw InputMismatchException");
-        } catch (InputMismatchException e) {
-            // Expected
-        }
-
-        // If the number is out of range
-        s = new Scanner("123456789");
-        assertFalse(s.hasNextShort());
-        try {
-            s.nextShort();
-            fail("Should throw InputMismatchException");
-        } catch (InputMismatchException e) {
-            // Expected
-        }
-
-        /*
-         * Different locale can only recognize corresponding locale sensitive
-         * string. ',' is used in many locales as group separator.
-         */
-        s = new Scanner("23,456 23,456");
-        s.useLocale(Locale.GERMANY);
-        assertFalse(s.hasNextShort());
-        try {
-            s.nextShort();
-            fail("Should throw InputMismatchException");
-        } catch (InputMismatchException e) {
-            // Expected
-        }
-        s.useLocale(Locale.ENGLISH);
-        // If exception is thrown out, input will not be advanced.
-        assertTrue(s.hasNextShort());
-        assertEquals(23456, s.nextShort());
-        assertTrue(s.hasNextShort());
-        assertEquals(23456, s.nextShort());
-
-        /*
-         * ''' is used in many locales as group separator.
-         */
-        s = new Scanner("23'456 23'456");
-        s.useLocale(Locale.GERMANY);
-        assertFalse(s.hasNextShort());
-        try {
-            s.nextShort();
-            fail("Should throw InputMismatchException");
-        } catch (InputMismatchException e) {
-            // Expected
-        }
-        s.useLocale(deLocale);
-        // If exception is thrown out, input will not be advanced.
-        assertTrue(s.hasNextShort());
-        assertEquals(23456, s.nextShort());
-        assertTrue(s.hasNextShort());
-        assertEquals(23456, s.nextShort());
-
-        /*
-         * The input string has Arabic-Indic digits.
-         */
-        s = new Scanner("1\u06602 1\u06662");
-        assertEquals(102, s.nextShort());
-        s.useRadix(5);
-        assertFalse(s.hasNextShort());
-        try {
-            s.nextShort();
-            fail("Should throw InputMismatchException");
-        } catch (InputMismatchException e) {
-            // Expected
-        }
-        s.useRadix(10);
-        assertTrue(s.hasNextShort());
-        assertEquals(162, s.nextShort());
-
-        /*
-         * '.' is used in many locales as group separator. The input string
-         * has Arabic-Indic digits .
-         */
-        s = new Scanner("23.45\u0666 23.456");
-        s.useLocale(Locale.CHINESE);
-        assertFalse(s.hasNextShort());
-        try {
-            s.nextShort();
-            fail("Should throw InputMismatchException");
-        } catch (InputMismatchException e) {
-            // Expected
-        }
-        s.useLocale(Locale.GERMANY);
-        // If exception is thrown out, input will not be advanced.
-        assertTrue(s.hasNextShort());
-        assertEquals(23456, s.nextShort());
-        assertTrue(s.hasNextShort());
-        assertEquals(23456, s.nextShort());
-
-        // The input string starts with zero
-        s = new Scanner("03,456");
-        s.useLocale(Locale.ENGLISH);
-        assertFalse(s.hasNextShort());
-        try {
-            s.nextShort();
-            fail("Should throw InputMismatchException");
-        } catch (InputMismatchException e) {
-            // Expected
-        }
-
-        s = new Scanner("03456");
-        assertTrue(s.hasNextShort());
-        assertEquals(3456, s.nextShort());
-
-        s = new Scanner("\u06603,456");
-        s.useLocale(Locale.ENGLISH);
-        assertTrue(s.hasNextShort());
-        assertEquals(3456, s.nextShort());
-
-        s = new Scanner("E34");
-        s.useRadix(16);
-        assertTrue(s.hasNextShort());
-        assertEquals(3636, s.nextShort());
-
-        /*
-         * There are 3 types of zero digit in all locales, '0' '\u0966' '\u0e50'
-         * respectively, but they are not differentiated.
-         */
-        s = new Scanner("12300");
-        s.useLocale(Locale.CHINESE);
-        assertTrue(s.hasNextShort());
-        assertEquals(12300, s.nextShort());
-
-        s = new Scanner("123\u0966\u0966");
-        s.useLocale(Locale.CHINESE);
-        assertTrue(s.hasNextShort());
-        assertEquals(12300, s.nextShort());
-
-        s = new Scanner("123\u0e50\u0e50");
-        s.useLocale(Locale.CHINESE);
-        assertTrue(s.hasNextShort());
-        assertEquals(12300, s.nextShort());
-
-        s = new Scanner("-123");
-        s.useLocale(arLocale);
-        assertTrue(s.hasNextShort());
-        assertEquals(-123, s.nextShort());
-
-        s = new Scanner("-123");
-        s.useLocale(mkLocale);
-        assertTrue(s.hasNextShort());
-        assertEquals(-123, s.nextShort());
-
-        s.close();
-        try {
-            s.hasNextShort();
-            fail("IllegalStateException expected");
-        } catch (IllegalStateException e) {
-            //expected
-        }
-    }
-
-    /**
-     * @throws IOException
-     * @tests java.util.Scanner#hasNextShort(int)
-     */
-    @TestTargetNew(
-        level = TestLevel.PARTIAL_COMPLETE,
-        notes = "Regression test.",
-        method = "hasNextShort",
-        args = {int.class}
-    )
-    public void test_hasNextShortI_cache() throws IOException {
-        //regression for HARMONY-2063
-        s = new Scanner("123 456");
-        assertTrue(s.hasNextShort(16));
-        assertEquals(291, s.nextShort());
-        assertEquals(456, s.nextShort());
-
-        s = new Scanner("123 456");
-        assertTrue(s.hasNextShort(16));
-        assertTrue(s.hasNextShort(8));
-        assertEquals(83, s.nextShort());
-        assertEquals(456, s.nextShort());
-
-        s = new Scanner("-123 -456 -789");
-        assertTrue(s.hasNextShort(8));
-        assertEquals(-123, s.nextInt());
-        assertEquals(-456, s.nextShort());
-        assertTrue(s.hasNextInt(16));
-        assertEquals(-789, s.nextShort());
-
-        s = new Scanner("123 456");
-        assertTrue(s.hasNextShort());
-        s.close();
-        try {
-            s.nextShort();
-            fail("Should throw IllegalStateException");
-        } catch (IllegalStateException e) {
-            // expected
-        }
-    }
-
-    /**
-     * @throws IOException
-     * @tests java.util.Scanner#hasNextLong(int)
-     */
-    @TestTargetNew(
-        level = TestLevel.PARTIAL_COMPLETE,
-        notes = "IllegalStateException checking missed.",
-        method = "hasNextLong",
-        args = {int.class}
-    )
-    public void test_hasNextLongI() throws IOException {
-        Locale[] requiredLocales = {Locale.GERMANY, Locale.ENGLISH, Locale.CHINESE};
-        if (!Support_Locale.areLocalesAvailable(requiredLocales)) {
-            // locale dependent test, bug 1943269
-            return;
-        }
-        s = new Scanner("123 456");
-        assertTrue(s.hasNextLong(10));
-        assertEquals(123, s.nextLong(10));
-        assertTrue(s.hasNextLong(10));
-        assertEquals(456, s.nextLong(10));
-        assertFalse(s.hasNextLong(10));
-        try {
-            s.nextLong(10);
-            fail("Should throw NoSuchElementException");
-        } catch (NoSuchElementException e) {
-            // Expected
-        }
-
-        // If the radix is different from 10
-        s = new Scanner("123 456");
-        assertTrue(s.hasNextLong(5));
-        assertEquals(38, s.nextLong(5));
-        assertFalse(s.hasNextLong(5));
-        try {
-            s.nextLong(5);
-            fail("Should throw InputMismatchException");
-        } catch (InputMismatchException e) {
-            // Expected
-        }
-
-        // If the number is out of range
-        s = new Scanner("123456789123456789123456789123456789");
-        assertFalse(s.hasNextLong(10));
-        try {
-            s.nextLong(10);
-            fail("Should throw InputMismatchException");
-        } catch (InputMismatchException e) {
-            // Expected
-        }
-
-        /*
-         * Different locale can only recognize corresponding locale sensitive
-         * string. ',' is used in many locales as group separator.
-         */
-        s = new Scanner("23,456 23,456");
-        s.useLocale(Locale.GERMANY);
-        assertFalse(s.hasNextShort(10));
-        try {
-            s.nextLong(10);
-            fail("Should throw InputMismatchException");
-        } catch (InputMismatchException e) {
-            // Expected
-        }
-        s.useLocale(Locale.ENGLISH);
-        // If exception is thrown out, input will not be advanced.
-        assertTrue(s.hasNextLong(10));
-        assertEquals(23456, s.nextLong(10));
-        assertTrue(s.hasNextLong(10));
-        assertEquals(23456, s.nextLong(10));
-
-        /*
-         * ''' is used in many locales as group separator.
-         */
-        s = new Scanner("23'456 23'456");
-        s.useLocale(Locale.GERMANY);
-        assertFalse(s.hasNextLong(10));
-        try {
-            s.nextLong(10);
-            fail("Should throw InputMismatchException");
-        } catch (InputMismatchException e) {
-            // Expected
-        }
-        s.useLocale(new Locale("de", "CH"));
-        // If exception is thrown out, input will not be advanced.
-        assertTrue(s.hasNextLong(10));
-        assertEquals(23456, s.nextLong(10));
-        assertTrue(s.hasNextLong(10));
-        assertEquals(23456, s.nextLong(10));
-
-        /*
-         * The input string has Arabic-Indic digits.
-         */
-        s = new Scanner("1\u06602 1\u06662");
-        assertTrue(s.hasNextLong(10));
-        assertEquals(102, s.nextLong(10));
-        assertFalse(s.hasNextLong(5));
-        try {
-            s.nextLong(5);
-            fail("Should throw InputMismatchException");
-        } catch (InputMismatchException e) {
-            // Expected
-        }
-        assertTrue(s.hasNextLong(10));
-        assertEquals(162, s.nextLong(10));
-
-        /*
-         * '.' is used in many locales as group separator. The input string
-         * has Arabic-Indic digits .
-         */
-        s = new Scanner("23.45\u0666 23.456");
-        s.useLocale(Locale.CHINESE);
-        assertFalse(s.hasNextLong(10));
-        try {
-            s.nextLong(10);
-            fail("Should throw InputMismatchException");
-        } catch (InputMismatchException e) {
-            // Expected
-        }
-        s.useLocale(Locale.GERMANY);
-        // If exception is thrown out, input will not be advanced.
-        assertTrue(s.hasNextLong(10));
-        assertEquals(23456, s.nextLong(10));
-        assertTrue(s.hasNextLong(10));
-        assertEquals(23456, s.nextLong(10));
-
-        // The input string starts with zero
-        s = new Scanner("03,456");
-        s.useLocale(Locale.ENGLISH);
-        assertFalse(s.hasNextLong(10));
-        try {
-            s.nextLong(10);
-            fail("Should throw InputMismatchException");
-        } catch (InputMismatchException e) {
-            // Expected
-        }
-
-        s = new Scanner("03456");
-        assertTrue(s.hasNextLong(10));
-        assertEquals(3456, s.nextLong(10));
-
-        s = new Scanner("\u06603,456");
-        s.useLocale(Locale.ENGLISH);
-        assertTrue(s.hasNextLong(10));
-        assertEquals(3456, s.nextLong(10));
-
-        s = new Scanner("E34");
-        assertTrue(s.hasNextLong(16));
-        assertEquals(3636, s.nextLong(16));
-
-        /*
-         * There are 3 types of zero digit in all locales, '0' '\u0966' '\u0e50'
-         * respectively, but they are not differentiated.
-         */
-        s = new Scanner("12300");
-        s.useLocale(Locale.CHINESE);
-        assertTrue(s.hasNextLong(10));
-        assertEquals(12300, s.nextLong(10));
-
-        s = new Scanner("123\u0966\u0966");
-        s.useLocale(Locale.CHINESE);
-        assertTrue(s.hasNextLong(10));
-        assertEquals(12300, s.nextLong(10));
-
-        s = new Scanner("123\u0e50\u0e50");
-        s.useLocale(Locale.CHINESE);
-        assertTrue(s.hasNextLong(10));
-        assertEquals(12300, s.nextLong(10));
-
-        s = new Scanner("-123");
-        s.useLocale(new Locale("ar", "AE"));
-        assertTrue(s.hasNextLong(10));
-        assertEquals(-123, s.nextLong(10));
-
-
-        s = new Scanner("-123");
-        s.useLocale(new Locale("mk", "MK"));
-        assertTrue(s.hasNextLong(10));
-        assertEquals(-123, s.nextLong(10));
-    }
-
-    /**
-     * @throws IOException
-     * @tests java.util.Scanner#hasNextLong(int)
-     */
-    @TestTargetNew(
-        level = TestLevel.PARTIAL_COMPLETE,
-        notes = "Regression test.",
-        method = "hasNextLong",
-        args = {int.class}
-    )
-    public void test_hasNextLongI_cache() throws IOException {
-        //regression for HARMONY-2063
-        s = new Scanner("123 456");
-        assertTrue(s.hasNextLong(16));
-        assertEquals(291, s.nextLong());
-        assertEquals(456, s.nextLong());
-
-        s = new Scanner("123 456");
-        assertTrue(s.hasNextLong(16));
-        assertTrue(s.hasNextLong(8));
-        assertEquals(83, s.nextLong());
-        assertEquals(456, s.nextLong());
-
-        s = new Scanner("-123 -456 -789");
-        assertTrue(s.hasNextLong(8));
-        assertEquals(-123, s.nextInt());
-        assertEquals(-456, s.nextLong());
-        assertTrue(s.hasNextShort(16));
-        assertEquals(-789, s.nextLong());
-
-        s = new Scanner("123 456");
-        assertTrue(s.hasNextLong());
-        s.close();
-        try {
-            s.nextLong();
-            fail("Should throw IllegalStateException");
-        } catch (IllegalStateException e) {
-            // expected
-        }
-    }
-
-    /**
-     * @throws IOException
-     * @tests java.util.Scanner#hasNextLong()
-     */
-    @TestTargetNew(
-        level = TestLevel.COMPLETE,
-        notes = "",
-        method = "hasNextLong",
-        args = {}
-    )
-    public void test_hasNextLong() throws IOException {
-        Locale deLocale = new Locale("de", "CH");
-        Locale arLocale = new Locale("ar", "AE");
-        Locale mkLocale = new Locale("mk", "MK");
-        Locale[] requiredLocales = {Locale.GERMANY, Locale.ENGLISH, Locale.CHINESE, deLocale,
-                arLocale, mkLocale};
-        if (!Support_Locale.areLocalesAvailable(requiredLocales)) {
-            // locale dependent test, bug 1943269
-            return;
-        }
-        s = new Scanner("123 456");
-        assertTrue(s.hasNextLong());
-        assertEquals(123, s.nextLong());
-        assertTrue(s.hasNextLong());
-        assertEquals(456, s.nextLong());
-        assertFalse(s.hasNextLong());
-        try {
-            s.nextLong();
-            fail("Should throw NoSuchElementException");
-        } catch (NoSuchElementException e) {
-            // Expected
-        }
-
-        // If the radix is different from 10
-        s = new Scanner("123 456");
-        s.useRadix(5);
-        assertTrue(s.hasNextLong());
-        assertEquals(38, s.nextLong());
-        assertFalse(s.hasNextLong());
-        try {
-            s.nextLong();
-            fail("Should throw InputMismatchException");
-        } catch (InputMismatchException e) {
-            // Expected
-        }
-
-        // If the number is out of range
-        s = new Scanner("123456789123456789123456789123456789");
-        assertFalse(s.hasNextLong());
-        try {
-            s.nextLong();
-            fail("Should throw InputMismatchException");
-        } catch (InputMismatchException e) {
-            // Expected
-        }
-
-        /*
-         * Different locale can only recognize corresponding locale sensitive
-         * string. ',' is used in many locales as group separator.
-         */
-        s = new Scanner("23,456 23,456");
-        s.useLocale(Locale.GERMANY);
-        assertFalse(s.hasNextLong());
-        try {
-            s.nextLong();
-            fail("Should throw InputMismatchException");
-        } catch (InputMismatchException e) {
-            // Expected
-        }
-        s.useLocale(Locale.ENGLISH);
-        // If exception is thrown out, input will not be advanced.
-        assertTrue(s.hasNextLong());
-        assertEquals(23456, s.nextLong());
-        assertTrue(s.hasNextLong());
-        assertEquals(23456, s.nextLong());
-
-        /*
-         * ''' is used in many locales as group separator.
-         */
-        s = new Scanner("23'456 23'456");
-        s.useLocale(Locale.GERMANY);
-        assertFalse(s.hasNextLong());
-        try {
-            s.nextLong();
-            fail("Should throw InputMismatchException");
-        } catch (InputMismatchException e) {
-            // Expected
-        }
-        s.useLocale(deLocale);
-        // If exception is thrown out, input will not be advanced.
-        assertTrue(s.hasNextLong());
-        assertEquals(23456, s.nextLong());
-        assertTrue(s.hasNextLong());
-        assertEquals(23456, s.nextLong());
-
-        /*
-         * The input string has Arabic-Indic digits.
-         */
-        s = new Scanner("1\u06602 1\u06662");
-        assertEquals(102, s.nextLong());
-        s.useRadix(5);
-        assertFalse(s.hasNextLong());
-        try {
-            s.nextLong();
-            fail("Should throw InputMismatchException");
-        } catch (InputMismatchException e) {
-            // Expected
-        }
-        s.useRadix(10);
-        assertTrue(s.hasNextLong());
-        assertEquals(162, s.nextLong());
-
-        /*
-         * '.' is used in many locales as group separator. The input string
-         * has Arabic-Indic digits .
-         */
-        s = new Scanner("23.45\u0666 23.456");
-        s.useLocale(Locale.CHINESE);
-        assertFalse(s.hasNextLong());
-        try {
-            s.nextLong();
-            fail("Should throw InputMismatchException");
-        } catch (InputMismatchException e) {
-            // Expected
-        }
-        s.useLocale(Locale.GERMANY);
-        // If exception is thrown out, input will not be advanced.
-        assertTrue(s.hasNextLong());
-        assertEquals(23456, s.nextLong());
-        assertTrue(s.hasNextLong());
-        assertEquals(23456, s.nextLong());
-
-        // The input string starts with zero
-        s = new Scanner("03,456");
-        s.useLocale(Locale.ENGLISH);
-        assertFalse(s.hasNextLong());
-        try {
-            s.nextLong();
-            fail("Should throw InputMismatchException");
-        } catch (InputMismatchException e) {
-            // Expected
-        }
-
-        s = new Scanner("03456");
-        assertTrue(s.hasNextLong());
-        assertEquals(3456, s.nextLong());
-
-        s = new Scanner("\u06603,456");
-        s.useLocale(Locale.ENGLISH);
-        assertTrue(s.hasNextLong());
-        assertEquals(3456, s.nextLong());
-
-        s = new Scanner("E34");
-        s.useRadix(16);
-        assertTrue(s.hasNextLong());
-        assertEquals(3636, s.nextLong());
-
-        /*
-         * There are 3 types of zero digit in all locales, '0' '\u0966' '\u0e50'
-         * respectively, but they are not differentiated.
-         */
-        s = new Scanner("12300");
-        s.useLocale(Locale.CHINESE);
-        assertTrue(s.hasNextLong());
-        assertEquals(12300, s.nextLong());
-
-        s = new Scanner("123\u0966\u0966");
-        s.useLocale(Locale.CHINESE);
-        assertTrue(s.hasNextLong());
-        assertEquals(12300, s.nextLong());
-
-        s = new Scanner("123\u0e50\u0e50");
-        s.useLocale(Locale.CHINESE);
-        assertTrue(s.hasNextLong());
-        assertEquals(12300, s.nextLong());
-
-        s = new Scanner("-123");
-        s.useLocale(arLocale);
-        assertTrue(s.hasNextLong());
-        assertEquals(-123, s.nextLong());
-
-        s = new Scanner("-123");
-        s.useLocale(mkLocale);
-        assertTrue(s.hasNextLong());
-        assertEquals(-123, s.nextLong());
-
-        s.close();
-        try {
-            s.hasNextLong();
-            fail("IllegalStateException expected");
-        } catch (IllegalStateException e) {
-            //expected
-        }
-    }
-
-    /**
-     * @throws IOException
-     * @tests java.util.Scanner#nextDouble()
-     */
-    @TestTargetNew(
-        level = TestLevel.COMPLETE,
-        notes = "",
-        method = "hasNextDouble",
-        args = {}
-    )
-    public void test_hasNextDouble() throws IOException {
-        Locale[] requiredLocales = {Locale.GERMANY, Locale.ENGLISH};
-        if (!Support_Locale.areLocalesAvailable(requiredLocales)) {
-            // locale dependent test, bug 1943269
-            return;
-        }
-        s = new Scanner("123 45\u0666. 123.4 .123 ");
-        s.useLocale(Locale.ENGLISH);
-        assertTrue(s.hasNextDouble());
-        assertEquals(123.0, s.nextDouble());
-        assertTrue(s.hasNextDouble());
-        assertEquals(456.0, s.nextDouble());
-        assertTrue(s.hasNextDouble());
-        assertEquals(123.4, s.nextDouble());
-        assertTrue(s.hasNextDouble());
-        assertEquals(0.123, s.nextDouble());
-        assertFalse(s.hasNextDouble());
-        try {
-            s.nextDouble();
-            fail("Should throw NoSuchElementException");
-        } catch (NoSuchElementException e) {
-            // Expected
-        }
-
-        s = new Scanner("+123.4 -456.7 123,456.789 0.1\u06623,4");
-        s.useLocale(Locale.ENGLISH);
-        assertTrue(s.hasNextDouble());
-        assertEquals(123.4, s.nextDouble());
-        assertTrue(s.hasNextDouble());
-        assertEquals(-456.7, s.nextDouble());
-        assertTrue(s.hasNextDouble());
-        assertEquals(123456.789, s.nextDouble());
-        assertFalse(s.hasNextDouble());
-        try {
-            s.nextDouble();
-            fail("Should throw InputMismatchException");
-        } catch (InputMismatchException e) {
-            // Expected
-        }
-
-        // Scientific notation
-        s = new Scanner("+123.4E10 -456.7e+12 123,456.789E-10");
-        s.useLocale(Locale.ENGLISH);
-        assertTrue(s.hasNextDouble());
-        assertEquals(1.234E12, s.nextDouble());
-        assertTrue(s.hasNextDouble());
-        assertEquals(-4.567E14, s.nextDouble());
-        assertTrue(s.hasNextDouble());
-        assertEquals(1.23456789E-5, s.nextDouble());
-
-        s = new Scanner("NaN Infinity -Infinity");
-        assertTrue(s.hasNextDouble());
-        assertEquals(Double.NaN, s.nextDouble());
-        assertTrue(s.hasNextDouble());
-        assertEquals(Double.POSITIVE_INFINITY, s.nextDouble());
-        assertTrue(s.hasNextDouble());
-        assertEquals(Double.NEGATIVE_INFINITY, s.nextDouble());
-
-        String str=String.valueOf(Double.MAX_VALUE*2);
-        s=new Scanner(str);
-        assertTrue(s.hasNextDouble());
-        assertEquals(Double.POSITIVE_INFINITY,s.nextDouble());
-
-        /*
-         * Different locale can only recognize corresponding locale sensitive
-         * string. ',' is used in many locales as group separator.
-         */
-        s = new Scanner("23,456 23,456");
-        s.useLocale(Locale.ENGLISH);
-        assertTrue(s.hasNextDouble());
-        assertEquals(23456.0, s.nextDouble());
-        s.useLocale(Locale.GERMANY);
-        assertTrue(s.hasNextDouble());
-        assertEquals(23.456, s.nextDouble());
-
-        s = new Scanner("23.456 23.456");
-        s.useLocale(Locale.ENGLISH);
-        assertTrue(s.hasNextDouble());
-        assertEquals(23.456, s.nextDouble());
-        s.useLocale(Locale.GERMANY);
-        assertTrue(s.hasNextDouble());
-        assertEquals(23456.0, s.nextDouble());
-
-        s = new Scanner("23,456.7 23.456,7");
-        s.useLocale(Locale.ENGLISH);
-        assertTrue(s.hasNextDouble());
-        assertEquals(23456.7, s.nextDouble());
-        s.useLocale(Locale.GERMANY);
-        assertTrue(s.hasNextDouble());
-        assertEquals(23456.7, s.nextDouble());
-
-        s = new Scanner("-123.4");
-        s.useLocale(Locale.ENGLISH);
-        assertTrue(s.hasNextDouble());
-        assertEquals(-123.4, s.nextDouble());
-
-        s = new Scanner("+123.4 -456.7");
-        s.useLocale(Locale.ENGLISH);
-        assertTrue(s.hasNextDouble());
-        s.close();
-        try{
-            s.nextDouble();
-            fail("Should throw IllegalStateException");
-        }catch(IllegalStateException e){
-            //expected
-        }
-    }
-
-    /**
-     * @throws IOException
-     * @tests java.util.Scanner#hasNextBigDecimal()
-     */
-    @TestTargetNew(
-        level = TestLevel.COMPLETE,
-        notes = "",
-        method = "hasNextBigDecimal",
-        args = {}
-    )
-    public void test_hasNextBigDecimal() throws IOException {
-        Locale[] requiredLocales = {Locale.GERMANY, Locale.ENGLISH};
-        if (!Support_Locale.areLocalesAvailable(requiredLocales)) {
-            // locale dependent test, bug 1943269
-            return;
-        }
-        s = new Scanner("123 45\u0666. 123.4 .123 ");
-        s.useLocale(Locale.ENGLISH);
-        assertTrue(s.hasNextBigDecimal());
-        assertEquals(new BigDecimal("123"), s.nextBigDecimal());
-        assertTrue(s.hasNextBigDecimal());
-        assertEquals(new BigDecimal("456"), s.nextBigDecimal());
-        assertTrue(s.hasNextBigDecimal());
-        assertEquals(new BigDecimal("123.4"), s.nextBigDecimal());
-        assertTrue(s.hasNextBigDecimal());
-        assertEquals(new BigDecimal("0.123"), s.nextBigDecimal());
-        assertFalse(s.hasNextBigDecimal());
-        try {
-            s.nextBigDecimal();
-            fail("Should throw NoSuchElementException");
-        } catch (NoSuchElementException e) {
-            // Expected
-        }
-
-        s = new Scanner("+123.4 -456.7 123,456.789 0.1\u06623,4");
-        s.useLocale(Locale.ENGLISH);
-        assertTrue(s.hasNextBigDecimal());
-        assertEquals(new BigDecimal("123.4"), s.nextBigDecimal());
-        assertTrue(s.hasNextBigDecimal());
-        assertEquals(new BigDecimal("-456.7"), s.nextBigDecimal());
-        assertTrue(s.hasNextBigDecimal());
-        assertEquals(new BigDecimal("123456.789"), s.nextBigDecimal());
-        assertFalse(s.hasNextBigDecimal());
-        try {
-            s.nextBigDecimal();
-            fail("Should throw InputMismatchException");
-        } catch (InputMismatchException e) {
-            // Expected
-        }
-
-        // Scientific notation
-        s = new Scanner("+123.4E10 -456.7e+12 123,456.789E-10");
-        s.useLocale(Locale.ENGLISH);
-        assertTrue(s.hasNextBigDecimal());
-        assertEquals(new BigDecimal("1.234E12"), s.nextBigDecimal());
-        assertTrue(s.hasNextBigDecimal());
-        assertEquals(new BigDecimal("-4.567E14"), s.nextBigDecimal());
-        assertTrue(s.hasNextBigDecimal());
-        assertEquals(new BigDecimal("1.23456789E-5"), s.nextBigDecimal());
-
-        s = new Scanner("NaN");
-        assertFalse(s.hasNextBigDecimal());
-        try {
-            s.nextBigDecimal();
-            fail("Should throw InputMismatchException");
-        } catch (InputMismatchException e) {
-            // Expected
-        }
-
-        /*
-         * Different locale can only recognize corresponding locale sensitive
-         * string. ',' is used in many locales as group separator.
-         */
-        s = new Scanner("23,456 23,456");
-        s.useLocale(Locale.ENGLISH);
-        assertTrue(s.hasNextBigDecimal());
-        assertEquals(new BigDecimal("23456"), s.nextBigDecimal());
-        s.useLocale(Locale.GERMANY);
-        assertTrue(s.hasNextBigDecimal());
-        assertEquals(new BigDecimal("23.456"), s.nextBigDecimal());
-
-        s = new Scanner("23.456 23.456");
-        s.useLocale(Locale.ENGLISH);
-        assertTrue(s.hasNextBigDecimal());
-        assertEquals(new BigDecimal("23.456"), s.nextBigDecimal());
-        s.useLocale(Locale.GERMANY);
-        assertTrue(s.hasNextBigDecimal());
-        assertEquals(new BigDecimal("23456"), s.nextBigDecimal());
-
-        s = new Scanner("23,456.7");
-        s.useLocale(Locale.ENGLISH);
-        assertTrue(s.hasNextBigDecimal());
-        assertEquals(new BigDecimal("23456.7"), s.nextBigDecimal());
-
-        s = new Scanner("-123.4");
-        s.useLocale(Locale.ENGLISH);
-        assertTrue(s.hasNextBigDecimal());
-        assertEquals(new BigDecimal("-123.4"), s.nextBigDecimal());
-
-        s.close();
-        try {
-            s.hasNextBigDecimal();
-            fail("IllegalStateException expected");
-        } catch (IllegalStateException e) {
-            //expected
-        }
-    }
-
-    private static class MockStringReader extends StringReader {
-
-        public MockStringReader(String param) {
-            super(param);
-        }
-
-        public int read(CharBuffer target) throws IOException {
-            target.append('t');
-            target.append('e');
-            target.append('s');
-            target.append('t');
-            throw new IOException();
-        }
-
-    }
-
-    private static class MockStringReader2Read extends StringReader {
-        private int timesRead = 1;
-
-        public MockStringReader2Read(String param) {
-            super(param);
-        }
-
-        public int read(CharBuffer target) throws IOException {
-            if (timesRead == 1) {
-                target.append('1');
-                target.append('2');
-                target.append('3');
-                timesRead++;
-                return 3;
-            } else if (timesRead == 2) {
-                target.append('t');
-                timesRead++;
-                return 1;
-            } else {
-                throw new IOException();
-            }
-        }
-
-    }
-
-    /**
-     * @tests java.util.Scanner#findWithinHorizon(Pattern, int)
-     */
-    @TestTargetNew(
-        level = TestLevel.COMPLETE,
-        notes = "",
-        method = "findWithinHorizon",
-        args = {java.util.regex.Pattern.class, int.class}
-    )
-    public void test_findWithinHorizon_LPatternI(){
-
-        // This method searches through the input up to the specified search
-        // horizon(exclusive).
-        s = new Scanner("123test");
-        String result = s.findWithinHorizon(Pattern.compile("\\p{Lower}"), 5);
-        assertEquals("t", result);
-        MatchResult mresult = s.match();
-        assertEquals(3, mresult.start());
-        assertEquals(4, mresult.end());
-
-        s = new Scanner("12345test1234test next");
-        /*
-         * If the pattern is found the scanner advances past the input that
-         * matched and returns the string that matched the pattern.
-         */
-        result = s.findWithinHorizon(Pattern.compile("\\p{Digit}+"), 2);
-        assertEquals("12", result);
-        mresult = s.match();
-        assertEquals(0, mresult.start());
-        assertEquals(2, mresult.end());
-        // Postion is now pointing at the bar. "12|345test1234test next"
-
-        result = s.findWithinHorizon(Pattern.compile("\\p{Digit}+"), 6);
-        assertEquals("345", result);
-
-        mresult = s.match();
-        assertEquals(2, mresult.start());
-        assertEquals(5, mresult.end());
-        // Postion is now pointing at the bar. "12345|test1234test next"
-
-        // If no such pattern is detected then the null is returned and the
-        // scanner's position remains unchanged.
-        result = s.findWithinHorizon(Pattern.compile("\\p{Digit}+"), 3);
-        assertNull(result);
-
-        try {
-            s.match();
-            fail("Should throw IllegalStateException");
-        } catch (IllegalStateException e) {
-            // expected
-        }
-        assertEquals("345", mresult.group());
-        assertEquals(2, mresult.start());
-        assertEquals(5, mresult.end());
-        // Postion is now still pointing at the bar. "12345|test1234test next"
-
-        // If horizon is 0, then the horizon is ignored and this method
-        // continues to search through the input looking for the specified
-        // pattern without bound.
-        result = s.findWithinHorizon(Pattern.compile("\\p{Digit}+"), 0);
-        mresult = s.match();
-        assertEquals(9, mresult.start());
-        assertEquals(13, mresult.end());
-        // Postion is now pointing at the bar. "12345test1234|test next"
-
-        assertEquals("test", s.next());
-        mresult = s.match();
-        assertEquals(13, mresult.start());
-        assertEquals(17, mresult.end());
-
-        assertEquals("next", s.next());
-        mresult = s.match();
-        assertEquals(18, mresult.start());
-        assertEquals(22, mresult.end());
-
-        try {
-            s.findWithinHorizon((Pattern) null, -1);
-            fail("Should throw NullPointerException");
-        } catch (NullPointerException e) {
-            // expected
-        }
-
-        try {
-            s.findWithinHorizon(Pattern.compile("\\p{Digit}+"), -1);
-            fail("Should throw IllegalArgumentException");
-        } catch (IllegalArgumentException e) {
-            // expected
-        }
-
-        s.close();
-        try {
-            s.findWithinHorizon((Pattern) null, -1);
-            fail("Should throw IllegalStateException");
-        } catch (IllegalStateException e) {
-            // expected
-        }
-
-        s = new Scanner("test");
-        result = s.findWithinHorizon(Pattern.compile("\\w+"), 10);
-        assertEquals("test", result);
-
-        s = new Scanner("aa\n\rb");
-        String patternStr = "^(a)$";
-        result = s.findWithinHorizon(Pattern.compile("a"), 5);
-        assertEquals("a", result);
-        mresult = s.match();
-        assertEquals(0, mresult.start());
-        assertEquals(1, mresult.end());
-
-        result = s.findWithinHorizon(Pattern.compile(patternStr,
-                Pattern.MULTILINE), 5);
-        assertNull(result);
-
-        try {
-            mresult = s.match();
-            fail("Should throw IllegalStateException");
-        } catch (IllegalStateException e) {
-            // expected
-        }
-
-        s = new Scanner("");
-        result = s.findWithinHorizon(Pattern.compile("^"), 0);
-        assertEquals("", result);
-        MatchResult matchResult = s.match();
-        assertEquals(0, matchResult.start());
-        assertEquals(0, matchResult.end());
-
-        result = s.findWithinHorizon(Pattern.compile("$"), 0);
-        assertEquals("", result);
-        matchResult = s.match();
-        assertEquals(0, matchResult.start());
-        assertEquals(0, matchResult.end());
-
-        s = new Scanner("1 fish 2 fish red fish blue fish");
-        result = s.findWithinHorizon(Pattern
-                .compile("(\\d+) fish (\\d+) fish (\\w+) fish (\\w+)"), 10);
-        assertNull(result);
-
-        try {
-            mresult = s.match();
-            fail("Should throw IllegalStateException");
-        } catch (IllegalStateException e) {
-            // expected
-        }
-        assertEquals(0, mresult.groupCount());
-
-        result = s.findWithinHorizon(Pattern
-                .compile("(\\d+) fish (\\d+) fish (\\w+) fish (\\w+)"), 100);
-        assertEquals("1 fish 2 fish red fish blue", result);
-        mresult = s.match();
-        assertEquals(4, mresult.groupCount());
-        assertEquals("1", mresult.group(1));
-        assertEquals("2", mresult.group(2));
-        assertEquals("red", mresult.group(3));
-        assertEquals("blue", mresult.group(4));
-
-        s = new Scanner("test");
-        s.close();
-        try {
-            s.findWithinHorizon(Pattern.compile("test"), 1);
-            fail("Should throw IllegalStateException");
-        } catch (IllegalStateException e) {
-            // expected
-        }
-
-        s = new Scanner("word1 WorD2  ");
-        s.close();
-        try {
-            s.findWithinHorizon(Pattern.compile("\\d+"), 10);
-            fail("should throw IllegalStateException");
-        } catch (IllegalStateException e) {
-            // expected
-        }
-
-        s = new Scanner("word1 WorD2 wOrd3 ");
-        Pattern pattern = Pattern.compile("\\d+");
-        assertEquals("1", s.findWithinHorizon(pattern, 10));
-        assertEquals("WorD2", s.next());
-        assertEquals("3", s.findWithinHorizon(pattern, 15));
-
-        // Regression test
-        s = new Scanner(new MockStringReader("MockStringReader"));
-        pattern = Pattern.compile("test");
-        result = s.findWithinHorizon(pattern, 10);
-        assertEquals("test", result);
-
-        // Test the situation when input length is longer than buffer size.
-        StringBuilder stringBuilder = new StringBuilder();
-        for (int i = 0; i < 1026; i++) {
-            stringBuilder.append('a');
-        }
-        s = new Scanner(stringBuilder.toString());
-        pattern = Pattern.compile("\\p{Lower}+");
-        result = s.findWithinHorizon(pattern, 1026);
-        assertEquals(stringBuilder.toString(), result);
-
-        // Test the situation when input length is longer than buffer size and
-        // set horizon to buffer size.
-        stringBuilder = new StringBuilder();
-        for (int i = 0; i < 1026; i++) {
-            stringBuilder.append('a');
-        }
-        s = new Scanner(stringBuilder.toString());
-        pattern = Pattern.compile("\\p{Lower}+");
-        result = s.findWithinHorizon(pattern, 1022);
-        assertEquals(1022, result.length());
-        assertEquals(stringBuilder.subSequence(0, 1022), result);
-
-        // Test the situation, under which pattern is clipped by buffer.
-        stringBuilder = new StringBuilder();
-        for (int i = 0; i < 1022; i++) {
-            stringBuilder.append(' ');
-        }
-        stringBuilder.append("bbc");
-        assertEquals(1025, stringBuilder.length());
-        s = new Scanner(stringBuilder.toString());
-        pattern = Pattern.compile("bbc");
-        result = s.findWithinHorizon(pattern, 1025);
-        assertEquals(3, result.length());
-        assertEquals(stringBuilder.subSequence(1022, 1025), result);
-
-        stringBuilder = new StringBuilder();
-        for (int i = 0; i < 1026; i++) {
-            stringBuilder.append('a');
-        }
-        s = new Scanner(stringBuilder.toString());
-        pattern = Pattern.compile("\\p{Lower}+");
-        result = s.findWithinHorizon(pattern, 0);
-        assertEquals(stringBuilder.toString(), result);
-
-        stringBuilder = new StringBuilder();
-        for (int i = 0; i < 10240; i++) {
-            stringBuilder.append('-');
-        }
-        stringBuilder.replace(0, 2, "aa");
-        s = new Scanner(stringBuilder.toString());
-        result = s.findWithinHorizon(Pattern.compile("aa"), 0);
-        assertEquals("aa", result);
-
-        s = new Scanner("aaaa");
-        result = s.findWithinHorizon(Pattern.compile("a*"), 0);
-        assertEquals("aaaa", result);
-    }
-
-    /**
-     * @tests java.util.Scanner#findWithinHorizon(String, int) Copy of Pattern
-     *        test for String
-     */
-    @TestTargetNew(
-        level = TestLevel.COMPLETE,
-        notes = "",
-        method = "findWithinHorizon",
-        args = {java.lang.String.class, int.class}
-    )
-    public void test_findWithinHorizon_Ljava_lang_StringI() {
-
-        // This method searches through the input up to the specified search
-        // horizon(exclusive).
-        s = new Scanner("123test");
-        String result = s.findWithinHorizon("\\p{Lower}", 5);
-        assertEquals("t", result);
-        MatchResult mresult = s.match();
-        assertEquals(3, mresult.start());
-        assertEquals(4, mresult.end());
-
-        s = new Scanner("12345test1234test next");
-        /*
-         * If the pattern is found the scanner advances past the input that
-         * matched and returns the string that matched the pattern.
-         */
-        result = s.findWithinHorizon("\\p{Digit}+", 2);
-        assertEquals("12", result);
-        mresult = s.match();
-        assertEquals(0, mresult.start());
-        assertEquals(2, mresult.end());
-        // Postion is now pointing at the bar. "12|345test1234test next"
-
-        result = s.findWithinHorizon("\\p{Digit}+", 6);
-        assertEquals("345", result);
-
-        mresult = s.match();
-        assertEquals(2, mresult.start());
-        assertEquals(5, mresult.end());
-        // Postion is now pointing at the bar. "12345|test1234test next"
-
-        // If no such pattern is detected then the null is returned and the
-        // scanner's position remains unchanged.
-        result = s.findWithinHorizon("\\p{Digit}+", 3);
-        assertNull(result);
-
-        try {
-            s.match();
-            fail("Should throw IllegalStateException");
-        } catch (IllegalStateException e) {
-            // expected
-        }
-        assertEquals("345", mresult.group());
-        assertEquals(2, mresult.start());
-        assertEquals(5, mresult.end());
-        // Postion is now still pointing at the bar. "12345|test1234test next"
-
-        // If horizon is 0, then the horizon is ignored and this method
-        // continues to search through the input looking for the specified
-        // pattern without bound.
-        result = s.findWithinHorizon("\\p{Digit}+", 0);
-        mresult = s.match();
-        assertEquals(9, mresult.start());
-        assertEquals(13, mresult.end());
-        // Postion is now pointing at the bar. "12345test1234|test next"
-
-        assertEquals("test", s.next());
-        mresult = s.match();
-        assertEquals(13, mresult.start());
-        assertEquals(17, mresult.end());
-
-        assertEquals("next", s.next());
-        mresult = s.match();
-        assertEquals(18, mresult.start());
-        assertEquals(22, mresult.end());
-
-        try {
-            s.findWithinHorizon((String)null, 1);
-            fail("Should throw NullPointerException");
-        } catch (NullPointerException e) {
-            // expected
-        }
-
-        try {
-            s.findWithinHorizon("\\p{Digit}+", -1);
-            fail("Should throw IllegalArgumentException");
-        } catch (IllegalArgumentException e) {
-            // expected
-        }
-
-        s.close();
-        // on RI throws NullPointerException
-        /*
-         * try { System.out.println("fsdfs"); s.findWithinHorizon((String) null,
-         * -1); System.out.println("fsdfs"); fail("Should throw
-         * IllegalStateException"); } catch (IllegalStateException e) { //
-         * expected }
-         */
-        s = new Scanner("test");
-        result = s.findWithinHorizon("\\w+", 10);
-        assertEquals("test", result);
-
-        s = new Scanner("aa\n\rb");
-        String patternStr = "^(a)$";
-        result = s.findWithinHorizon("a", 5);
-        assertEquals("a", result);
-        mresult = s.match();
-        assertEquals(0, mresult.start());
-        assertEquals(1, mresult.end());
-
-        result = s.findWithinHorizon(patternStr, 5);
-        assertNull(result);
-
-        try {
-            mresult = s.match();
-            fail("Should throw IllegalStateException");
-        } catch (IllegalStateException e) {
-            // expected
-        }
-
-        s = new Scanner("");
-        result = s.findWithinHorizon("^", 0);
-        assertEquals("", result);
-        MatchResult matchResult = s.match();
-        assertEquals(0, matchResult.start());
-        assertEquals(0, matchResult.end());
-
-        result = s.findWithinHorizon("$", 0);
-        assertEquals("", result);
-        matchResult = s.match();
-        assertEquals(0, matchResult.start());
-        assertEquals(0, matchResult.end());
-
-        s = new Scanner("1 fish 2 fish red fish blue fish");
-        result = s.findWithinHorizon("(\\d+) fish (\\d+) fish (\\w+) fish (\\w+)", 10);
-        assertNull(result);
-
-        try {
-            mresult = s.match();
-            fail("Should throw IllegalStateException");
-        } catch (IllegalStateException e) {
-            // expected
-        }
-        assertEquals(0, mresult.groupCount());
-
-        result = s.findWithinHorizon("(\\d+) fish (\\d+) fish (\\w+) fish (\\w+)", 100);
-        assertEquals("1 fish 2 fish red fish blue", result);
-        mresult = s.match();
-        assertEquals(4, mresult.groupCount());
-        assertEquals("1", mresult.group(1));
-        assertEquals("2", mresult.group(2));
-        assertEquals("red", mresult.group(3));
-        assertEquals("blue", mresult.group(4));
-
-        s = new Scanner("test");
-        s.close();
-        try {
-            s.findWithinHorizon("test", 1);
-            fail("Should throw IllegalStateException");
-        } catch (IllegalStateException e) {
-            // expected
-        }
-
-        s = new Scanner("word1 WorD2  ");
-        s.close();
-        try {
-            s.findWithinHorizon("\\d+", 10);
-            fail("should throw IllegalStateException");
-        } catch (IllegalStateException e) {
-            // expected
-        }
-
-        s = new Scanner("word1 WorD2 wOrd3 ");
-        patternStr = "\\d+";
-        assertEquals("1", s.findWithinHorizon(patternStr, 10));
-        assertEquals("WorD2", s.next());
-        assertEquals("3", s.findWithinHorizon(patternStr, 15));
-
-        // Regression test
-        s = new Scanner(new MockStringReader("MockStringReader"));
-        patternStr = "test";
-        result = s.findWithinHorizon(patternStr, 10);
-        assertEquals("test", result);
-
-        // Test the situation when input length is longer than buffer size.
-        StringBuilder stringBuilder = new StringBuilder();
-        for (int i = 0; i < 1026; i++) {
-            stringBuilder.append('a');
-        }
-        s = new Scanner(stringBuilder.toString());
-        patternStr = "\\p{Lower}+";
-        result = s.findWithinHorizon(patternStr, 1026);
-        assertEquals(stringBuilder.toString(), result);
-
-        // Test the situation when input length is longer than buffer size and
-        // set horizon to buffer size.
-        stringBuilder = new StringBuilder();
-        for (int i = 0; i < 1026; i++) {
-            stringBuilder.append('a');
-        }
-        s = new Scanner(stringBuilder.toString());
-        patternStr = "\\p{Lower}+";
-        result = s.findWithinHorizon(patternStr, 1022);
-        assertEquals(1022, result.length());
-        assertEquals(stringBuilder.subSequence(0, 1022), result);
-
-        // Test the situation, under which pattern is clipped by buffer.
-        stringBuilder = new StringBuilder();
-        for (int i = 0; i < 1022; i++) {
-            stringBuilder.append(' ');
-        }
-        stringBuilder.append("bbc");
-        assertEquals(1025, stringBuilder.length());
-        s = new Scanner(stringBuilder.toString());
-        patternStr = "bbc";
-        result = s.findWithinHorizon(patternStr, 1025);
-        assertEquals(3, result.length());
-        assertEquals(stringBuilder.subSequence(1022, 1025), result);
-
-        stringBuilder = new StringBuilder();
-        for (int i = 0; i < 1026; i++) {
-            stringBuilder.append('a');
-        }
-        s = new Scanner(stringBuilder.toString());
-        patternStr = "\\p{Lower}+";
-        result = s.findWithinHorizon(patternStr, 0);
-        assertEquals(stringBuilder.toString(), result);
-
-        stringBuilder = new StringBuilder();
-        for (int i = 0; i < 10240; i++) {
-            stringBuilder.append('-');
-        }
-        stringBuilder.replace(0, 2, "aa");
-        s = new Scanner(stringBuilder.toString());
-        result = s.findWithinHorizon("aa", 0);
-        assertEquals("aa", result);
-
-        s = new Scanner("aaaa");
-        result = s.findWithinHorizon("a*", 0);
-        assertEquals("aaaa", result);
-    }
-
-    /**
-     * @tests java.util.Scanner#findInLine(Pattern)
-     */
-    @TestTargetNew(
-        level = TestLevel.COMPLETE,
-        notes = "",
-        method = "findInLine",
-        args = {java.util.regex.Pattern.class}
-    )
-    public void test_findInLine_LPattern() {
-
-        Scanner s = new Scanner("");
-        try {
-            s.findInLine((Pattern) null);
-            fail("Should throw NullPointerException");
-        } catch (NullPointerException e) {
-            // Expected
-        }
-        String result = s.findInLine(Pattern.compile("^"));
-        assertEquals("", result);
-        MatchResult matchResult = s.match();
-        assertEquals(0, matchResult.start());
-        assertEquals(0, matchResult.end());
-
-        result = s.findInLine(Pattern.compile("$"));
-        assertEquals("", result);
-        matchResult = s.match();
-        assertEquals(0, matchResult.start());
-        assertEquals(0, matchResult.end());
-
-        /*
-         * When we use the operation of findInLine(Pattern), the match region
-         * should not span the line separator.
-         */
-        s = new Scanner("aa\nb.b");
-        result = s.findInLine(Pattern.compile("a\nb*"));
-        assertNull(result);
-
-        s = new Scanner("aa\nbb.b");
-        result = s.findInLine(Pattern.compile("\\."));
-        assertNull(result);
-
-        s = new Scanner("abcd1234test\n");
-        result = s.findInLine(Pattern.compile("\\p{Lower}+"));
-        assertEquals("abcd", result);
-        matchResult = s.match();
-        assertEquals(0, matchResult.start());
-        assertEquals(4, matchResult.end());
-
-        result = s.findInLine(Pattern.compile("\\p{Digit}{5}"));
-        assertNull(result);
-        try {
-            matchResult = s.match();
-            fail("Should throw IllegalStateException");
-        } catch (IllegalStateException e) {
-            // expected
-        }
-        assertEquals(0, matchResult.start());
-        assertEquals(4, matchResult.end());
-
-        result = s.findInLine(Pattern.compile("\\p{Lower}+"));
-        assertEquals("test", result);
-        matchResult = s.match();
-        assertEquals(8, matchResult.start());
-        assertEquals(12, matchResult.end());
-
-        char[] chars = new char[2048];
-        Arrays.fill(chars, 'a');
-        StringBuilder stringBuilder = new StringBuilder();
-        stringBuilder.append(chars);
-        stringBuilder.append("1234");
-        s = new Scanner(stringBuilder.toString());
-        result = s.findInLine(Pattern.compile("\\p{Digit}+"));
-        assertEquals("1234", result);
-        matchResult = s.match();
-        assertEquals(2048, matchResult.start());
-        assertEquals(2052, matchResult.end());
-
-        s = new Scanner("test");
-        s.close();
-        try {
-            s.findInLine((Pattern) null);
-            fail("Should throw IllegalStateException");
-        } catch (IllegalStateException e) {
-            // expected
-        }
-
-        s = new Scanner("test1234\n1234 test");
-        result = s.findInLine(Pattern.compile("test"));
-        assertEquals("test", result);
-        matchResult = s.match();
-        assertEquals(0, matchResult.start());
-        assertEquals(4, matchResult.end());
-
-        int number = s.nextInt();
-        assertEquals(1234, number);
-        matchResult = s.match();
-        assertEquals(4, matchResult.start());
-        assertEquals(8, matchResult.end());
-
-        result = s.next();
-        assertEquals("1234", result);
-        matchResult = s.match();
-        assertEquals(9, matchResult.start());
-        assertEquals(13, matchResult.end());
-
-        result = s.findInLine(Pattern.compile("test"));
-        assertEquals("test", result);
-        matchResult = s.match();
-        assertEquals(14, matchResult.start());
-        assertEquals(18, matchResult.end());
-
-        s = new Scanner("test\u0085\ntest");
-        result = s.findInLine("est");
-        assertEquals("est", result);
-        result = s.findInLine("est");
-        assertEquals("est", result);
-
-        s = new Scanner("test\ntest");
-        result = s.findInLine("est");
-        assertEquals("est", result);
-        result = s.findInLine("est");
-        assertEquals("est", result);
-
-        s = new Scanner("test\n123\ntest");
-        result = s.findInLine("est");
-        assertEquals("est", result);
-        result = s.findInLine("est");
-        // RI fails. It is a RI's bug.
-        if (!disableRIBugs) {
-            assertNull(result);
-        }
-    }
-
-    /**
-     * @tests java.util.Scanner#findInLine(String)
-     */
-    @TestTargetNew(
-        level = TestLevel.COMPLETE,
-        notes = "",
-        method = "findInLine",
-        args = {java.lang.String.class}
-    )
-    public void test_findInLine_LString() {
-        s = new Scanner("test");
-        try {
-            s.findInLine((String) null);
-            fail("Should throw NullPointerException");
-        } catch (NullPointerException e) {
-            // expected
-        }
-
-        s.close();
-        try {
-            s.findInLine((String) null);
-            fail("Should throw NullPointerException");
-        } catch (NullPointerException e) {
-            // expected
-        }
-        try {
-            s.findInLine("test");
-            fail("Should throw IllegalStateException");
-        } catch (IllegalStateException e) {
-            // exptected
-        }
-
-        s = new Scanner("");
-
-        String result = s.findInLine("^");
-        assertEquals("", result);
-        MatchResult matchResult = s.match();
-        assertEquals(0, matchResult.start());
-        assertEquals(0, matchResult.end());
-
-        result = s.findInLine("$");
-        assertEquals("", result);
-        matchResult = s.match();
-        assertEquals(0, matchResult.start());
-        assertEquals(0, matchResult.end());
-
-        /*
-         * When we use the operation of findInLine(Pattern), the match region
-         * should not span the line separator.
-         */
-        s = new Scanner("aa\nb.b");
-        result = s.findInLine("a\nb*");
-        assertNull(result);
-
-        s = new Scanner("aa\nbb.b");
-        result = s.findInLine("\\.");
-        assertNull(result);
-
-        s = new Scanner("abcd1234test\n");
-        result = s.findInLine("\\p{Lower}+");
-        assertEquals("abcd", result);
-        matchResult = s.match();
-        assertEquals(0, matchResult.start());
-        assertEquals(4, matchResult.end());
-
-        result = s.findInLine("\\p{Digit}{5}");
-        assertNull(result);
-        try {
-            matchResult = s.match();
-            fail("Should throw IllegalStateException");
-        } catch (IllegalStateException e) {
-            // expected
-        }
-        assertEquals(0, matchResult.start());
-        assertEquals(4, matchResult.end());
-
-        result = s.findInLine("\\p{Lower}+");
-        assertEquals("test", result);
-        matchResult = s.match();
-        assertEquals(8, matchResult.start());
-        assertEquals(12, matchResult.end());
-
-        char[] chars = new char[2048];
-        Arrays.fill(chars, 'a');
-        StringBuilder stringBuilder = new StringBuilder();
-        stringBuilder.append(chars);
-        stringBuilder.append("1234");
-        s = new Scanner(stringBuilder.toString());
-        result = s.findInLine("\\p{Digit}+");
-        assertEquals("1234", result);
-        matchResult = s.match();
-        assertEquals(2048, matchResult.start());
-        assertEquals(2052, matchResult.end());
-
-        s = new Scanner("test1234\n1234 test");
-        result = s.findInLine("test");
-        assertEquals("test", result);
-        matchResult = s.match();
-        assertEquals(0, matchResult.start());
-        assertEquals(4, matchResult.end());
-
-        int number = s.nextInt();
-        assertEquals(1234, number);
-        matchResult = s.match();
-        assertEquals(4, matchResult.start());
-        assertEquals(8, matchResult.end());
-
-        result = s.next();
-        assertEquals("1234", result);
-        matchResult = s.match();
-        assertEquals(9, matchResult.start());
-        assertEquals(13, matchResult.end());
-
-        result = s.findInLine("test");
-        assertEquals("test", result);
-        matchResult = s.match();
-        assertEquals(14, matchResult.start());
-        assertEquals(18, matchResult.end());
-
-        s = new Scanner("test\u0085\ntest");
-        result = s.findInLine("est");
-        assertEquals("est", result);
-        result = s.findInLine("est");
-        assertEquals("est", result);
-
-        s = new Scanner("test\ntest");
-        result = s.findInLine("est");
-        assertEquals("est", result);
-        result = s.findInLine("est");
-        assertEquals("est", result);
-
-        s = new Scanner("test\n123\ntest");
-        result = s.findInLine("est");
-        assertEquals("est", result);
-        result = s.findInLine("est");
-        // RI fails. It is a RI's bug.
-        if (!disableRIBugs) {
-            assertNull(result);
-        }
-
-
-    }
-
-    /**
-     * @tests java.util.Scanner#skip(Pattern)
-     */
-    @TestTargetNew(
-        level = TestLevel.COMPLETE,
-        notes = "",
-        method = "skip",
-        args = {java.util.regex.Pattern.class}
-    )
-    public void test_skip_LPattern() {
-        s = new Scanner("test");
-        try {
-            s.skip((String) null);
-            fail("Should throw NullPointerException");
-        } catch (NullPointerException e) {
-            // expected
-        }
-
-        // If pattern does not match, NoSuchElementException will be thrown out.
-        s = new Scanner("1234");
-        try {
-            s.skip(Pattern.compile("\\p{Lower}"));
-            fail("Should throw NoSuchElementException");
-        } catch (NoSuchElementException e) {
-            // expected
-        }
-        // Then, no matchResult will be thrown out.
-        try {
-            s.match();
-            fail("Should throw IllegalStateException");
-        } catch (IllegalStateException e) {
-            // expected
-        }
-
-        s.skip(Pattern.compile("\\p{Digit}"));
-        MatchResult matchResult = s.match();
-        assertEquals(0, matchResult.start());
-        assertEquals(1, matchResult.end());
-
-        s.skip(Pattern.compile("\\p{Digit}+"));
-        matchResult = s.match();
-        assertEquals(1, matchResult.start());
-        assertEquals(4, matchResult.end());
-
-        s.close();
-        try {
-            s.skip(Pattern.compile("test"));
-            fail("Should throw IllegalStateException");
-        } catch (IllegalStateException e) {
-            // expected
-        }
-
-        MockStringReader2Read reader = new MockStringReader2Read("test");
-        s = new Scanner(reader);
-        try {
-            s.skip(Pattern.compile("\\p{Digit}{4}"));
-            fail("Should throw NoSuchElementException");
-        } catch (NoSuchElementException e) {
-            // expected
-        }
-        try {
-            s.match();
-            fail("Should throw IllegalStateException");
-        } catch (IllegalStateException e) {
-            // expected
-        }
-        s.skip(Pattern.compile("\\p{Digit}{3}\\p{Lower}"));
-        matchResult = s.match();
-        assertEquals(0, matchResult.start());
-        assertEquals(4, matchResult.end());
-
-        s.close();
-        try {
-            s.skip((Pattern) null);
-            fail("Should throw IllegalStateException");
-        } catch (IllegalStateException e) {
-            // expected
-        }
-
-        StringBuilder stringBuilder = new StringBuilder();
-        char [] chars = new char[1024];
-        Arrays.fill(chars, 'a');
-        stringBuilder.append(chars);
-        stringBuilder.append('3');
-        s = new Scanner(stringBuilder.toString());
-        s.skip(Pattern.compile("\\p{Lower}+\\p{Digit}"));
-        matchResult = s.match();
-        assertEquals(0, matchResult.start());
-        assertEquals(1025, matchResult.end());
-
-        // Large amount of input may be cached
-        chars = new char[102400];
-        Arrays.fill(chars, 'a');
-        stringBuilder = new StringBuilder();
-        stringBuilder.append(chars);
-        s = new Scanner(stringBuilder.toString());
-        s.skip(Pattern.compile(".*"));
-        matchResult = s.match();
-        assertEquals(0, matchResult.start());
-        assertEquals(102400, matchResult.end());
-
-        // skip something without risking a NoSuchElementException
-        s.skip(Pattern.compile("[ \t]*"));
-        matchResult = s.match();
-        assertEquals(102400, matchResult.start());
-        assertEquals(102400, matchResult.end());
-    }
-
-    /**
-     * @tests java.util.Scanner#skip(String)
-     */
-    @TestTargetNew(
-        level = TestLevel.COMPLETE,
-        notes = "",
-        method = "skip",
-        args = {java.lang.String.class}
-    )
-    public void test_skip_LString() {
-        s = new Scanner("test");
-        try {
-            s.skip((String) null);
-            fail("Should throw NullPointerException");
-        } catch (NullPointerException e) {
-            // expected
-        }
-
-        // If pattern does not match, NoSuchElementException will be thrown out.
-        s = new Scanner("1234");
-        try {
-            s.skip("\\p{Lower}");
-            fail("Should throw NoSuchElementException");
-        } catch (NoSuchElementException e) {
-            // expected
-        }
-        // Then, no matchResult will be thrown out.
-        try {
-            s.match();
-            fail("Should throw IllegalStateException");
-        } catch (IllegalStateException e) {
-            // expected
-        }
-
-        s.skip("\\p{Digit}");
-        MatchResult matchResult = s.match();
-        assertEquals(0, matchResult.start());
-        assertEquals(1, matchResult.end());
-
-        s.skip("\\p{Digit}+");
-        matchResult = s.match();
-        assertEquals(1, matchResult.start());
-        assertEquals(4, matchResult.end());
-
-        s.close();
-        try {
-            s.skip("test");
-            fail("Should throw IllegalStateException");
-        } catch (IllegalStateException e) {
-            // expected
-        }
-
-        MockStringReader2Read reader = new MockStringReader2Read("test");
-        s = new Scanner(reader);
-        try {
-            s.skip("\\p{Digit}{4}");
-            fail("Should throw NoSuchElementException");
-        } catch (NoSuchElementException e) {
-            // expected
-        }
-        try {
-            s.match();
-            fail("Should throw IllegalStateException");
-        } catch (IllegalStateException e) {
-            // expected
-        }
-        s.skip("\\p{Digit}{3}\\p{Lower}");
-        matchResult = s.match();
-        assertEquals(0, matchResult.start());
-        assertEquals(4, matchResult.end());
-
-        s.close();
-        try {
-            s.skip("");
-            fail("Should throw IllegalStateException");
-        } catch (IllegalStateException e) {
-            // expected
-        }
-
-        StringBuilder stringBuilder = new StringBuilder();
-        char [] chars = new char[1024];
-        Arrays.fill(chars, 'a');
-        stringBuilder.append(chars);
-        stringBuilder.append('3');
-        s = new Scanner(stringBuilder.toString());
-        s.skip("\\p{Lower}+\\p{Digit}");
-        matchResult = s.match();
-        assertEquals(0, matchResult.start());
-        assertEquals(1025, matchResult.end());
-
-        // Large amount of input may be cached
-        chars = new char[102400];
-        Arrays.fill(chars, 'a');
-        stringBuilder = new StringBuilder();
-        stringBuilder.append(chars);
-        s = new Scanner(stringBuilder.toString());
-        s.skip(".*");
-        matchResult = s.match();
-        assertEquals(0, matchResult.start());
-        assertEquals(102400, matchResult.end());
-
-        // skip something without risking a NoSuchElementException
-        s.skip("[ \t]*");
-        matchResult = s.match();
-        assertEquals(102400, matchResult.start());
-        assertEquals(102400, matchResult.end());
-
-        s = new Scanner("test");
-        try {
-            s.skip((String) null);
-            fail("Should throw NullPointerException");
-        } catch (NullPointerException e) {
-            // expected
-        }
-    }
-
-    /**
-     * @throws IOException
-     * @tests java.util.Scanner#nextDouble()
-     */
-    @TestTargetNew(
-        level = TestLevel.COMPLETE,
-        notes = "",
-        method = "nextDouble",
-        args = {}
-    )
-    public void test_nextDouble() throws IOException {
-        Locale[] requiredLocales = {Locale.GERMANY, Locale.ENGLISH};
-        if (!Support_Locale.areLocalesAvailable(requiredLocales)) {
-            // locale dependent test, bug 1943269
-            return;
-        }
-        s = new Scanner("123 45\u0666. 123.4 .123 ");
-        s.useLocale(Locale.ENGLISH);
-        assertEquals(123.0, s.nextDouble());
-        assertEquals(456.0, s.nextDouble());
-        assertEquals(123.4, s.nextDouble());
-        assertEquals(0.123, s.nextDouble());
-        try {
-            s.nextDouble();
-            fail("Should throw NoSuchElementException");
-        } catch (NoSuchElementException e) {
-            // Expected
-        }
-
-        s = new Scanner("+123.4 -456.7 123,456.789 0.1\u06623,4");
-        s.useLocale(Locale.ENGLISH);
-        assertEquals(123.4, s.nextDouble());
-        assertEquals(-456.7, s.nextDouble());
-        assertEquals(123456.789, s.nextDouble());
-        try {
-            s.nextDouble();
-            fail("Should throw InputMismatchException");
-        } catch (InputMismatchException e) {
-            // Expected
-        }
-
-        // Scientific notation
-        s = new Scanner("+123.4E10 -456.7e+12 123,456.789E-10");
-        s.useLocale(Locale.ENGLISH);
-        assertEquals(1.234E12, s.nextDouble());
-        assertEquals(-4.567E14, s.nextDouble());
-        assertEquals(1.23456789E-5, s.nextDouble());
-
-        s = new Scanner("NaN Infinity -Infinity");
-        assertEquals(Double.NaN, s.nextDouble());
-        assertEquals(Double.POSITIVE_INFINITY, s.nextDouble());
-        assertEquals(Double.NEGATIVE_INFINITY, s.nextDouble());
-
-        //The following test case fails on RI
-        s=new Scanner("\u221e");
-        s.useLocale(Locale.ENGLISH);
-//        assertEquals(Double.POSITIVE_INFINITY, s.nextDouble());
-
-        String str=String.valueOf(Double.MAX_VALUE*2);
-        s=new Scanner(str);
-        assertEquals(Double.POSITIVE_INFINITY,s.nextDouble());
-
-        /*
-         * Different locale can only recognize corresponding locale sensitive
-         * string. ',' is used in many locales as group separator.
-         */
-        s = new Scanner("23,456 23,456");
-        s.useLocale(Locale.ENGLISH);
-        assertEquals(23456.0, s.nextDouble());
-        s.useLocale(Locale.GERMANY);
-        assertEquals(23.456, s.nextDouble());
-
-        s = new Scanner("23.456 23.456");
-        s.useLocale(Locale.ENGLISH);
-        assertEquals(23.456, s.nextDouble());
-        s.useLocale(Locale.GERMANY);
-        assertEquals(23456.0, s.nextDouble());
-
-        s = new Scanner("23,456.7 23.456,7");
-        s.useLocale(Locale.ENGLISH);
-        assertEquals(23456.7, s.nextDouble());
-        s.useLocale(Locale.GERMANY);
-        assertEquals(23456.7, s.nextDouble());
-
-        s = new Scanner("-123.4");
-        s.useLocale(Locale.ENGLISH);
-        assertEquals(-123.4, s.nextDouble());
-
-        s.close();
-        try {
-            s.nextDouble();
-            fail("IllegalStateException expected");
-        } catch (IllegalStateException e) {
-            //expected
-        }
-    }
-
-    /**
-     * @throws IOException
-     * @tests java.util.Scanner#nextBigDecimal()
-     */
-    @TestTargetNew(
-        level = TestLevel.COMPLETE,
-        notes = "",
-        method = "nextBigDecimal",
-        args = {}
-    )
-    public void test_nextBigDecimal() throws IOException {
-        Locale[] requiredLocales = {Locale.ENGLISH, Locale.GERMANY};
-        if (!Support_Locale.areLocalesAvailable(requiredLocales)) {
-            // locale dependent test, bug 1943269
-            return;
-        }
-        s = new Scanner("123 45\u0666. 123.4 .123 ");
-        s.useLocale(Locale.ENGLISH);
-        assertEquals(new BigDecimal("123"), s.nextBigDecimal());
-        assertEquals(new BigDecimal("456"), s.nextBigDecimal());
-        assertEquals(new BigDecimal("123.4"), s.nextBigDecimal());
-        assertEquals(new BigDecimal("0.123"), s.nextBigDecimal());
-        try {
-            s.nextBigDecimal();
-            fail("Should throw NoSuchElementException");
-        } catch (NoSuchElementException e) {
-            // Expected
-        }
-
-        s = new Scanner("+123.4 -456.7 123,456.789 0.1\u06623,4");
-        s.useLocale(Locale.ENGLISH);
-        assertEquals(new BigDecimal("123.4"), s.nextBigDecimal());
-        assertEquals(new BigDecimal("-456.7"), s.nextBigDecimal());
-        assertEquals(new BigDecimal("123456.789"), s.nextBigDecimal());
-        try {
-            s.nextBigDecimal();
-            fail("Should throw InputMismatchException");
-        } catch (InputMismatchException e) {
-            // Expected
-        }
-
-        // Scientific notation
-        s = new Scanner("+123.4E10 -456.7e+12 123,456.789E-10");
-        s.useLocale(Locale.ENGLISH);
-        assertEquals(new BigDecimal("1.234E12"), s.nextBigDecimal());
-        assertEquals(new BigDecimal("-4.567E14"), s.nextBigDecimal());
-        assertEquals(new BigDecimal("1.23456789E-5"), s.nextBigDecimal());
-
-        s = new Scanner("NaN");
-        try {
-            s.nextBigDecimal();
-            fail("Should throw InputMismatchException");
-        } catch (InputMismatchException e) {
-            // Expected
-        }
-
-        /*
-         * Different locale can only recognize corresponding locale sensitive
-         * string. ',' is used in many locales as group separator.
-         */
-        s = new Scanner("23,456 23,456");
-        s.useLocale(Locale.ENGLISH);
-        assertEquals(new BigDecimal("23456"), s.nextBigDecimal());
-        s.useLocale(Locale.GERMANY);
-        assertEquals(new BigDecimal("23.456"), s.nextBigDecimal());
-
-        s = new Scanner("23.456 23.456");
-        s.useLocale(Locale.ENGLISH);
-        assertEquals(new BigDecimal("23.456"), s.nextBigDecimal());
-        s.useLocale(Locale.GERMANY);
-        assertEquals(new BigDecimal("23456"), s.nextBigDecimal());
-
-        s = new Scanner("23,456.7");
-        s.useLocale(Locale.ENGLISH);
-        assertEquals(new BigDecimal("23456.7"), s.nextBigDecimal());
-
-        s = new Scanner("-123.4");
-        s.useLocale(Locale.ENGLISH);
-        assertEquals(new BigDecimal("-123.4"), s.nextBigDecimal());
-
-        s.close();
-        try {
-            s.nextBigDecimal();
-            fail("IllegalStateException expected");
-        } catch (IllegalStateException e) {
-            //expected
-        }
-    }
-
-    /**
-     * @tests java.util.Scanner#toString()
-     */
-    @TestTargetNew(
-        level = TestLevel.COMPLETE,
-        notes = "",
-        method = "toString",
-        args = {}
-    )
-    public void test_toString() {
-        s = new Scanner("test");
-        assertNotNull(s.toString());
-    }
-
-    /**
-     * @tests java.util.Scanner#nextLine()
-     */
-    @TestTargetNew(
-        level = TestLevel.COMPLETE,
-        notes = "",
-        method = "nextLine",
-        args = {}
-    )
-    public void test_nextLine() {
-        s = new Scanner("");
-        s.close();
-        try {
-            s.nextLine();
-            fail("Should throw IllegalStateException");
-        } catch (IllegalStateException e) {
-            // expected
-        }
-
-        s = new Scanner("test\r\ntest");
-        String result = s.nextLine();
-        assertEquals("test", result);
-        MatchResult matchResult = s.match();
-        assertEquals(0, matchResult.start());
-        assertEquals(6, matchResult.end());
-
-        s = new Scanner("\u0085");
-        result = s.nextLine();
-        assertEquals("", result);
-        matchResult = s.match();
-        assertEquals(0, matchResult.start());
-        assertEquals(1, matchResult.end());
-
-        s = new Scanner("\u2028");
-        result = s.nextLine();
-        assertEquals("", result);
-        matchResult = s.match();
-        assertEquals(0, matchResult.start());
-        assertEquals(1, matchResult.end());
-
-        s = new Scanner("\u2029");
-        result = s.nextLine();
-        assertEquals("", result);
-        matchResult = s.match();
-        assertEquals(0, matchResult.start());
-        assertEquals(1, matchResult.end());
-
-        s = new Scanner("");
-        try {
-            result = s.nextLine();
-            fail("Should throw NoSuchElementException");
-        } catch (NoSuchElementException e) {
-            // expected
-        }
-        try {
-            s.match();
-            fail("Should throw IllegalStateException");
-        } catch (IllegalStateException e) {
-            // expected
-        }
-
-        s = new Scanner("Ttest");
-        result = s.nextLine();
-        assertEquals("Ttest", result);
-        matchResult = s.match();
-        assertEquals(0, matchResult.start());
-        assertEquals(5, matchResult.end());
-
-        s = new Scanner("\r\n");
-        result = s.nextLine();
-        assertEquals("", result);
-        matchResult = s.match();
-        assertEquals(0, matchResult.start());
-        assertEquals(2, matchResult.end());
-
-        char[] chars = new char[1024];
-        Arrays.fill(chars, 'a');
-        StringBuilder stringBuilder = new StringBuilder();
-        stringBuilder.append(chars);
-        chars = new char[] { '+', '-' };
-        stringBuilder.append(chars);
-        stringBuilder.append("\u2028");
-        s = new Scanner(stringBuilder.toString());
-        result = s.nextLine();
-
-        assertEquals(stringBuilder.toString().substring(0, 1026), result);
-        matchResult = s.match();
-        assertEquals(0, matchResult.start());
-        assertEquals(1027, matchResult.end());
-
-        chars = new char[1023];
-        Arrays.fill(chars, 'a');
-        stringBuilder = new StringBuilder();
-        stringBuilder.append(chars);
-        stringBuilder.append("\r\n");
-        s = new Scanner(stringBuilder.toString());
-        result = s.nextLine();
-
-        assertEquals(stringBuilder.toString().substring(0, 1023), result);
-        matchResult = s.match();
-        assertEquals(0, matchResult.start());
-        assertEquals(1025, matchResult.end());
-
-        s = new Scanner("  ");
-        result = s.nextLine();
-        assertEquals("  ", result);
-
-        s = new Scanner("test\n\n\n");
-        result = s.nextLine();
-        assertEquals("test", result);
-        matchResult = s.match();
-        assertEquals(0, matchResult.start());
-        assertEquals(5, matchResult.end());
-        result = s.nextLine();
-        matchResult = s.match();
-        assertEquals(5, matchResult.start());
-        assertEquals(6, matchResult.end());
-
-        s = new Scanner("\n\n\n");
-        result = s.nextLine();
-        assertEquals("", result);
-        matchResult = s.match();
-        assertEquals(0, matchResult.start());
-        assertEquals(1, matchResult.end());
-        result = s.nextLine();
-        matchResult = s.match();
-        assertEquals(1, matchResult.start());
-        assertEquals(2, matchResult.end());
-
-        s = new Scanner("123 test\n   ");
-        int value = s.nextInt();
-        assertEquals(123, value);
-
-        result = s.nextLine();
-        assertEquals(" test", result);
-
-        s = new Scanner("test\n ");
-        result = s.nextLine();
-        assertEquals("test", result);
-    }
-
-    /**
-     * @tests java.util.Scanner#hasNextLine()
-     */
-    @TestTargetNew(
-        level = TestLevel.COMPLETE,
-        notes = "",
-        method = "hasNextLine",
-        args = {}
-    )
-    public void test_hasNextLine() {
-
-        s = new Scanner("");
-        s.close();
-        try {
-            s.hasNextLine();
-            fail("Should throw IllegalStateException");
-        } catch (IllegalStateException e) {
-            // expected
-        }
-
-        s = new Scanner("test\r\ntest");
-        boolean result = s.hasNextLine();
-        assertTrue(result);
-        MatchResult matchResult = s.match();
-        assertEquals(0, matchResult.start());
-        assertEquals(6, matchResult.end());
-
-        s = new Scanner("\u0085");
-        result = s.hasNextLine();
-        assertTrue(result);
-        matchResult = s.match();
-        assertEquals(0, matchResult.start());
-        assertEquals(1, matchResult.end());
-
-        s = new Scanner("\u2028");
-        result = s.hasNextLine();
-        assertTrue(result);
-        matchResult = s.match();
-        assertEquals(0, matchResult.start());
-        assertEquals(1, matchResult.end());
-
-        s = new Scanner("\u2029");
-        result = s.hasNextLine();
-        assertTrue(result);
-        matchResult = s.match();
-        assertEquals(0, matchResult.start());
-        assertEquals(1, matchResult.end());
-
-        s = new Scanner("test\n");
-        assertTrue(s.hasNextLine());
-        matchResult = s.match();
-        assertEquals(0, matchResult.start());
-        assertEquals(5, matchResult.end());
-
-        char[] chars = new char[2048];
-        Arrays.fill(chars, 'a');
-        StringBuilder stringBuilder = new StringBuilder();
-        stringBuilder.append(chars);
-        s = new Scanner(stringBuilder.toString());
-        result = s.hasNextLine();
-        assertTrue(result);
-
-        matchResult = s.match();
-        assertEquals(0, matchResult.start());
-        assertEquals(2048, matchResult.end());
-
-        s = new Scanner("\n\n\n");
-        assertTrue(s.hasNextLine());
-        matchResult = s.match();
-        assertEquals(0, matchResult.start());
-        assertEquals(1, matchResult.end());
-
-        // The scanner will not advance any input.
-        assertTrue(s.hasNextLine());
-        matchResult = s.match();
-        assertEquals(0, matchResult.start());
-        assertEquals(1, matchResult.end());
-    }
-
-    protected void setUp() throws Exception {
-        super.setUp();
-
-        server = new ServerSocket(0);
-        address = new InetSocketAddress("127.0.0.1", server.getLocalPort());
-
-        client = SocketChannel.open();
-        client.connect(address);
-        serverSocket = server.accept();
-
-        os = serverSocket.getOutputStream();
-    }
-
-    protected void tearDown() throws Exception {
-        super.tearDown();
-
-        try {
-            serverSocket.close();
-        } catch (Exception e) {
-
-        }
-        try {
-            client.close();
-        } catch (Exception e) {
-            // do nothing
-        }
-        try {
-            server.close();
-        } catch (Exception e) {
-            // do nothing
-        }
-    }
-
-    /**
-     * @tests java.util.Scanner#Scanner(ReadableByteChannel)
-     */
-    @TestTargetNew(
-        level = TestLevel.COMPLETE,
-        notes = "",
-        method = "Scanner",
-        args = {java.nio.channels.ReadableByteChannel.class}
-    )
-    public void test_Constructor_LReadableByteChannel()
-            throws IOException {
-        InetSocketAddress localAddr = new InetSocketAddress("127.0.0.1",
-                Support_PortManager.getNextPort());
-        ServerSocketChannel ssc = ServerSocketChannel.open();
-        ssc.socket().bind(localAddr);
-
-        SocketChannel sc = SocketChannel.open();
-        sc.connect(localAddr);
-        sc.configureBlocking(false);
-        assertFalse(sc.isBlocking());
-
-        ssc.accept().close();
-        ssc.close();
-        assertFalse(sc.isBlocking());
-
-        Scanner s = new Scanner(sc);
-        while (s.hasNextInt()) {
-            s.nextInt();
-        }
-
-        sc.close();
-    }
-}
diff --git a/luni/src/test/java/tests/archive/AllTests.java b/luni/src/test/java/tests/archive/AllTests.java
deleted file mode 100644
index 50800f4..0000000
--- a/luni/src/test/java/tests/archive/AllTests.java
+++ /dev/null
@@ -1,34 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements.  See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You 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 tests.archive;
-
-import junit.framework.Test;
-import junit.framework.TestSuite;
-
-public class AllTests {
-    public static Test suite() {
-        TestSuite suite = new TestSuite("All Archive test suites");
-        // $JUnit-BEGIN$
-        suite.addTest(org.apache.harmony.archive.tests.java.util.jar.AllTests
-                .suite());
-        suite.addTest(org.apache.harmony.archive.tests.java.util.zip.AllTests
-                .suite());
-        // $JUnit-END$
-        return suite;
-    }
-}
diff --git a/luni/src/test/resources/tests/api/java/net/file1.cache b/luni/src/test/resources/tests/api/java/net/file1.cache
deleted file mode 100644
index 9245960..0000000
--- a/luni/src/test/resources/tests/api/java/net/file1.cache
+++ /dev/null
@@ -1 +0,0 @@
-Cache test
\ No newline at end of file
diff --git a/run-core-tests b/run-core-tests
deleted file mode 100755
index 9a4ff38..0000000
--- a/run-core-tests
+++ /dev/null
@@ -1,45 +0,0 @@
-# -*- mode: bash -*-
-#
-# Copyright (C) 2007 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.
-
-# To run these tests:
-# mmm -j14 dalvik snod
-# adb reboot bootloader && fastboot flashall
-# adb shell run-core-tests
-
-tmp=/data/core-tests.tmp
-mkdir $tmp
-chmod 777 $tmp
-
-# Build the classpath by putting together the jar file for each module.
-classpath="/system/framework/core-junitrunner.jar:/system/framework/core-tests.jar"
-classpath="$classpath:/system/framework/sqlite-jdbc.jar" # Bonus item for jdbc testing.
-modules="dom json support xml"
-for module in $modules; do
-  classpath="$classpath:/system/framework/core-tests-$module.jar"
-done
-
-exec dalvikvm \
-     -Duser.name=root \
-     -Duser.language=en \
-     -Duser.region=US \
-     -Duser.dir=$tmp \
-     -Duser.home=$tmp \
-     -Djava.io.tmpdir=$tmp \
-     -Djavax.net.ssl.trustStore=/system/etc/security/cacerts.bks \
-     -classpath $classpath \
-     -Xcheck:jni \
-     -Xmx64M \
-     com.google.coretests.Main "$@"
diff --git a/run-core-tests-on-ri b/run-core-tests-on-ri
deleted file mode 100755
index 466994c..0000000
--- a/run-core-tests-on-ri
+++ /dev/null
@@ -1,23 +0,0 @@
-#
-# Copyright (C) 2007 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.
-
-# Run all the tests contained in the core-tests library on an RI that
-# is supposed to be in the path.
-
-top=$ANDROID_BUILD_TOP
-
-java -cp $top/cts/tools/utils/lib/junit.jar:$top/out/host/common/core-tests.jar \
-     -Xmx16M \
-     com.google.coretests.Main "$@"
diff --git a/sqlite-jdbc/VERSION b/sqlite-jdbc/VERSION
index 23bd019..8e6c0d3 100644
--- a/sqlite-jdbc/VERSION
+++ b/sqlite-jdbc/VERSION
@@ -1 +1 @@
-20100131
+20100727
diff --git a/sqlite-jdbc/src/main/java/SQLite/Backup.java b/sqlite-jdbc/src/main/java/SQLite/Backup.java
new file mode 100644
index 0000000..13c0b109
--- /dev/null
+++ b/sqlite-jdbc/src/main/java/SQLite/Backup.java
@@ -0,0 +1,99 @@
+package SQLite;
+
+/**
+ * Class wrapping an SQLite backup object.
+ */
+
+public class Backup {
+
+    /**
+     * Internal handle for the native SQLite API.
+     */
+
+    protected long handle = 0;
+
+    /**
+     * Finish a backup.
+     */
+
+    protected void finish() throws SQLite.Exception {
+	synchronized(this) {
+	    _finalize();
+	}
+    }
+
+    /**
+     * Destructor for object.
+     */
+
+    protected void finalize() {
+	synchronized(this) {
+	    try {
+		_finalize();
+	    } catch (SQLite.Exception e) {
+	    }
+	}
+    }
+
+    protected native void _finalize() throws SQLite.Exception;
+
+    /**
+     * Perform a backup step.
+     *
+     * @param n number of pages to backup
+     * @return true when backup completed
+     */
+
+    public boolean step(int n) throws SQLite.Exception {
+	synchronized(this) {
+	    return _step(n);
+	}
+    }
+
+    private native boolean _step(int n) throws SQLite.Exception;
+
+    /**
+     * Perform the backup in one step.
+     */
+
+    public void backup() throws SQLite.Exception {
+	synchronized(this) {
+	    _step(-1);
+	}
+    }
+
+    /**
+     * Return number of remaining pages to be backed up.
+     */
+
+    public int remaining() throws SQLite.Exception {
+	synchronized(this) {
+	    return _remaining();
+	}
+    }
+
+    private native int _remaining() throws SQLite.Exception;
+
+    /**
+     * Return the total number of pages in the backup source database.
+     */
+
+    public int pagecount() throws SQLite.Exception {
+	synchronized(this) {
+	    return _pagecount();
+	}
+    }
+
+    private native int _pagecount() throws SQLite.Exception;
+
+    /**
+     * Internal native initializer.
+     */
+
+    private static native void internal_init();
+
+    static {
+	internal_init();
+    }
+}
+
diff --git a/sqlite-jdbc/src/main/java/SQLite/Blob.java b/sqlite-jdbc/src/main/java/SQLite/Blob.java
index 2724670..3e28225 100644
--- a/sqlite-jdbc/src/main/java/SQLite/Blob.java
+++ b/sqlite-jdbc/src/main/java/SQLite/Blob.java
@@ -30,7 +30,11 @@
 	this.pos = 0;
     }
 
-    @Override
+    /**
+     * Return number of available bytes for reading.
+     * @return available input bytes
+     */
+
     public int available() throws IOException {
 	int ret = blob.size - pos;
 	return (ret < 0) ? 0 : ret;
diff --git a/sqlite-jdbc/src/main/java/SQLite/Database.java b/sqlite-jdbc/src/main/java/SQLite/Database.java
index f15df94..e7d6f29 100644
--- a/sqlite-jdbc/src/main/java/SQLite/Database.java
+++ b/sqlite-jdbc/src/main/java/SQLite/Database.java
@@ -395,7 +395,6 @@
      * @param sql the SQL statement to be executed
      * @param args arguments for the SQL statement, '%q' substitution
      * @param tbl TableResult to receive result set
-     * @return result set
      */
 
     public void get_table(String sql, String args[], TableResult tbl)
@@ -595,6 +594,82 @@
     private native void _trace(Trace tr);
 
     /**
+     * Initiate a database backup, SQLite 3.x only.
+     *
+     * @param dest destination database
+     * @param destName schema of destination database to be backed up
+     * @param srcName schema of source database
+     * @return Backup object to perform the backup operation
+     */
+
+    public Backup backup(Database dest, String destName, String srcName)
+	throws SQLite.Exception {
+	synchronized(this) {
+	    Backup b = new Backup();
+	    _backup(b, dest, destName, this, srcName);
+	    return b;
+	}
+    }
+
+    private static native void _backup(Backup b, Database dest,
+				       String destName, Database src,
+				       String srcName)
+	throws SQLite.Exception;
+
+    /**
+     * Set profile function. Only available in SQLite 3.6 and above,
+     * otherwise a no-op.
+     *
+     * @param pr the trace function
+     */
+
+    public void profile(Profile pr) {
+	synchronized(this) {
+	    _profile(pr);
+	}
+    }
+
+    private native void _profile(Profile pr);
+
+    /**
+     * Return information on SQLite runtime status.
+     * Only available in SQLite 3.6 and above,
+     * otherwise a no-op.
+     *
+     * @param op   operation code
+     * @param info output buffer, must be able to hold two
+     *             values (current/highwater)
+     * @param flag reset flag
+     * @return SQLite error code
+     */
+
+    public synchronized static int status(int op, int info[], boolean flag) {
+	return _status(op, info, flag);
+    }
+
+    private native static int _status(int op, int info[], boolean flag);
+
+    /**
+     * Return information on SQLite connection status.
+     * Only available in SQLite 3.6 and above,
+     * otherwise a no-op.
+     *
+     * @param op operation code
+     * @param info output buffer, must be able to hold two
+     *             values (current/highwater)
+     * @param flag reset flag
+     * @return SQLite error code
+     */
+
+    public int db_status(int op, int info[], boolean flag) {
+	synchronized(this) {
+	    return _db_status(op, info, flag);
+	}
+    }
+
+    private native int _db_status(int op, int info[], boolean flag);
+
+    /**
      * Compile and return SQLite VM for SQL statement. Only available
      * in SQLite 2.8.0 and above, otherwise a no-op.
      *
diff --git a/sqlite-jdbc/src/main/java/SQLite/Profile.java b/sqlite-jdbc/src/main/java/SQLite/Profile.java
new file mode 100644
index 0000000..0413fe2
--- /dev/null
+++ b/sqlite-jdbc/src/main/java/SQLite/Profile.java
@@ -0,0 +1,19 @@
+package SQLite;
+
+/**
+ * Callback interface for SQLite's profile function.
+ */
+
+public interface Profile {
+
+    /**
+     * Callback to profile (ie log) one SQL statement
+     * with its estimated execution time.
+     *
+     * @param stmt SQL statement string
+     * @param est  estimated execution time in milliseconds.
+     */
+
+    public void profile(String stmt, long est);
+}
+
diff --git a/sqlite-jdbc/src/main/java/SQLite/Stmt.java b/sqlite-jdbc/src/main/java/SQLite/Stmt.java
index 5a6e7c2..f668f90 100644
--- a/sqlite-jdbc/src/main/java/SQLite/Stmt.java
+++ b/sqlite-jdbc/src/main/java/SQLite/Stmt.java
@@ -225,9 +225,9 @@
      */
 
     public Object column(int col) throws SQLite.Exception {
-        switch (column_type(col)) {
+	switch (column_type(col)) {
 	case Constants.SQLITE_INTEGER:
-	    return Long.valueOf(column_long(col)); // android-changed: performance;
+	    return Long.valueOf(column_long(col)); // android-changed: performance
 	case Constants.SQLITE_FLOAT:
 	    return new Double(column_double(col));
 	case Constants.SQLITE_BLOB:
@@ -271,6 +271,15 @@
     public native String column_origin_name(int col) throws SQLite.Exception;
 
     /**
+     * Return statement status information.
+     * @param op which counter to report
+     * @param flg reset flag
+     * @return counter
+     */
+
+    public native int status(int op, boolean flg);
+
+    /**
      * Destructor for object.
      */
 
diff --git a/sqlite-jdbc/src/main/native/sqlite_jni.c b/sqlite-jdbc/src/main/native/sqlite_jni.c
index 0384fc9..6e5648c 100644
--- a/sqlite-jdbc/src/main/native/sqlite_jni.c
+++ b/sqlite-jdbc/src/main/native/sqlite_jni.c
@@ -58,6 +58,7 @@
     jobject cb;			/* Callback object */
     jobject ai;			/* Authorizer object */
     jobject tr;			/* Trace object */
+    jobject pr;			/* Profile object */
     jobject ph;			/* ProgressHandler object */
     JNIEnv *env;		/* Java environment for callbacks */
     int row1;			/* true while processing first row */
@@ -71,7 +72,10 @@
     sqlite3_stmt *stmt;		/* For callback() */
 #endif
 #if HAVE_SQLITE3 && HAVE_SQLITE3_INCRBLOBIO
-  struct hbl *blobs;		/* SQLite3 blob handles */
+    struct hbl *blobs;		/* SQLite3 blob handles */
+#endif
+#if HAVE_SQLITE3 && HAVE_SQLITE3_BACKUPAPI
+  struct hbk *backups;		/* SQLite3 backup handles */
 #endif
 } handle;
 
@@ -116,6 +120,16 @@
 } hbl;
 #endif
 
+#if HAVE_SQLITE3 && HAVE_SQLITE3_BACKUPAPI
+/* internal handle for sqlite3_backup */
+
+typedef struct hbk {
+    struct hbk *next;		/* next blob handle */
+    sqlite3_backup *bkup;	/* SQLite3 backup handle */
+    handle *h;			/* SQLite database handle (source) */
+} hbk;
+#endif
+
 /* ISO to/from UTF-8 translation */
 
 typedef struct {
@@ -137,6 +151,7 @@
 static jfieldID F_SQLite_Stmt_error_code = 0;
 static jfieldID F_SQLite_Blob_handle = 0;
 static jfieldID F_SQLite_Blob_size = 0;
+static jfieldID F_SQLite_Backup_handle = 0;
 
 static jmethodID M_java_lang_String_getBytes = 0;
 static jmethodID M_java_lang_String_getBytes2 = 0;
@@ -234,6 +249,17 @@
 }
 #endif
 
+#if HAVE_SQLITE3 && HAVE_SQLITE3_BACKUPAPI
+static void *
+gethbk(JNIEnv *env, jobject obj)
+{
+    jvalue v;
+
+    v.j = (*env)->GetLongField(env, obj, F_SQLite_Backup_handle);
+    return (void *) v.l;
+}
+#endif
+
 static void
 delglobrefp(JNIEnv *env, jobject *obj)
 {
@@ -340,6 +366,7 @@
 	dest->result = dest->tofree = malloc(strlen(utf) + 1);
 #else
 	jsize utflen = (*env)->GetStringUTFLength(env, src);
+	jsize uclen = (*env)->GetStringLength(env, src);
 
 	dest->result = dest->tofree = malloc(utflen + 1);
 #endif
@@ -351,7 +378,8 @@
 	strcpy(dest->result, utf);
 	(*env)->ReleaseStringUTFChars(env, src, utf);
 #else
-	(*env)->GetStringUTFRegion(env, src, 0, utflen, dest->result);
+	(*env)->GetStringUTFRegion(env, src, 0, uclen, dest->result);
+	dest->result[utflen] = '\0';
 #endif
 	return dest->result;
     }
@@ -752,6 +780,9 @@
 #if HAVE_SQLITE3 && HAVE_SQLITE3_INCRBLOBIO
 	hbl *bl;
 #endif
+#if HAVE_SQLITE3 && HAVE_SQLITE3_BACKUPAPI
+	hbk *bk;
+#endif
 #if HAVE_SQLITE_COMPILE
 	hvm *v;
 
@@ -820,6 +851,17 @@
 	    bl->blob = 0;
 	}
 #endif
+#if HAVE_SQLITE3 && HAVE_SQLITE3_BACKUPAPI
+	while ((bk = h->backups)) {
+	    h->backups = bk->next;
+	    bk->next = 0;
+	    bk->h = 0;
+	    if (bk->bkup) {
+		sqlite3_backup_finish(bk->bkup);
+	    }
+	    bk->bkup = 0;
+	}
+#endif
 	delglobrefp(env, &h->bh);
 	delglobrefp(env, &h->cb);
 	delglobrefp(env, &h->ai);
@@ -1050,7 +1092,7 @@
 	    return;
 	}
 	h->sqlite = 0;
-	h->bh = h->cb = h->ai = h->tr = h->ph = 0;
+	h->bh = h->cb = h->ai = h->tr = h->pr = h->ph = 0;
 	/* CHECK THIS */
 #if HAVE_BOTH_SQLITE
 	h->is3 = 0;
@@ -1074,6 +1116,9 @@
 #if HAVE_SQLITE3 && HAVE_SQLITE3_INCRBLOBIO
 	h->blobs = 0;
 #endif
+#if HAVE_SQLITE3 && HAVE_SQLITE3_BACKUPAPI
+	h->backups = 0;
+#endif
     }
     h->env = 0;
     if (!file) {
@@ -3550,7 +3595,7 @@
 	return;
     }
     len16 = len16 + sizeof (jchar) - ((char *) tail - (char *) sql16);
-    if (len16 < (jsize) sizeof (jchar)) {
+    if (len16 < sizeof (jchar)) {
 	len16 = sizeof (jchar);
     }
     v = malloc(sizeof (hvm) + len16);
@@ -4279,6 +4324,21 @@
     return 0;
 }
 
+JNIEXPORT jint JNICALL
+Java_SQLite_Stmt_status(JNIEnv *env, jobject obj, jint op, jboolean flg)
+{
+    jint count = 0;
+#if HAVE_SQLITE3 && HAVE_SQLITE3_STMT_STATUS
+    hvm *v = gethstmt(env, obj);
+
+    if (v && v->vm && v->h) {
+	count = sqlite3_stmt_status((sqlite3_stmt *) v->vm, op,
+				    flg == JNI_TRUE);
+    }
+#endif
+    return count;
+}
+
 JNIEXPORT void JNICALL
 Java_SQLite_Stmt_finalize(JNIEnv *env, jobject obj)
 {
@@ -4306,6 +4366,12 @@
 	throwex(env, "null blob");
 	return;
     }
+#if HAVE_BOTH_SQLITE
+    if (!h->is3) {
+	throwex(env, "not a SQLite 3 database");
+	return;
+    }
+#endif
     if (h && h->sqlite) {
 	trans2iso(env, h->haveutf, h->enc, dbname, &dbn);
 	exc = (*env)->ExceptionOccurred(env);
@@ -4564,6 +4630,313 @@
 #endif
 }
 
+
+JNIEXPORT void JNICALL
+Java_SQLite_Database__1backup(JNIEnv *env, jclass cls, jobject bkupj,
+			      jobject dest, jstring destName,
+			      jobject src, jstring srcName)
+{
+#if HAVE_SQLITE3 && HAVE_SQLITE3_BACKUPAPI
+    handle *hsrc = gethandle(env, src);
+    handle *hdest = gethandle(env, dest);
+    hbk *bk;
+    jthrowable exc;
+    transstr dbns, dbnd;
+    sqlite3_backup *bkup;
+    jvalue vv;
+
+    if (!bkupj) {
+	throwex(env, "null backup");
+	return;
+    }
+    if (!hsrc) {
+	throwex(env, "no source database");
+	return;
+    }
+    if (!hdest) {
+	throwex(env, "no destination database");
+	return;
+    }
+#if HAVE_BOTH_SQLITE
+    if (!hsrc->is3 || !hdest->is3) {
+	throwex(env, "not a SQLite 3 database");
+	return;
+    }
+#endif
+    if (!hsrc->sqlite) {
+	throwex(env, "source database not open");
+	return;
+    }
+    if (!hdest->sqlite) {
+	throwex(env, "destination database not open");
+	return;
+    }
+    trans2iso(env, hdest->haveutf, hdest->enc, destName, &dbnd);
+    exc = (*env)->ExceptionOccurred(env);
+    if (exc) {
+	(*env)->DeleteLocalRef(env, exc);
+	return;
+    }
+    trans2iso(env, hsrc->haveutf, hsrc->enc, srcName, &dbns);
+    exc = (*env)->ExceptionOccurred(env);
+    if (exc) {
+	transfree(&dbnd);
+	(*env)->DeleteLocalRef(env, exc);
+	return;
+    }
+    bkup = sqlite3_backup_init((sqlite3 *) hdest->sqlite, dbnd.result,
+			       (sqlite3 *) hsrc->sqlite, dbns.result);
+    transfree(&dbnd);
+    transfree(&dbns);
+    if (!bkup) {
+	const char *err = sqlite3_errmsg((sqlite3 *) hdest->sqlite);
+
+	seterr(env, src, sqlite3_errcode((sqlite3 *) hdest->sqlite));
+	throwex(env, err ? err : "error in backup init");
+	return;
+    }
+    bk = malloc(sizeof (hbk));
+    if (!bk) {
+	sqlite3_backup_finish(bkup);
+	throwoom(env, "unable to get SQLite backup handle");
+	return;
+    }
+    bk->next = hsrc->backups;
+    hsrc->backups = bk;
+    bk->bkup = bkup;
+    bk->h = hsrc;
+    vv.j = 0;
+    vv.l = (jobject) bk;
+    (*env)->SetLongField(env, bkupj, F_SQLite_Backup_handle, vv.j);
+    return;
+#else
+    throwex(env, "unsupported");
+#endif
+}
+
+JNIEXPORT void JNICALL
+Java_SQLite_Backup__1finalize(JNIEnv *env, jobject obj)
+{
+#if HAVE_SQLITE3 && HAVE_SQLITE3_BACKUPAPI
+    hbk *bk = gethbk(env, obj);
+    int ret = SQLITE_OK;
+    char *err = 0;
+
+    if (bk) {
+	if (bk->h) {
+	    handle *h = bk->h;
+	    hbk *bkc, **bkp;
+
+	    bkp = &h->backups;
+	    bkc = *bkp;
+	    while (bkc) {
+		if (bkc == bk) {
+		    *bkp = bkc->next;
+		    break;
+		}
+		bkp = &bkc->next;
+		bkc = *bkp;
+	    }
+	}
+	if (bk->bkup) {
+	    ret = sqlite3_backup_finish(bk->bkup);
+	    if (ret != SQLITE_OK && bk->h) {
+		err = (char *) sqlite3_errmsg((sqlite3 *) bk->h->sqlite);
+	    }
+	}
+	bk->bkup = 0;
+	free(bk);
+	(*env)->SetLongField(env, obj, F_SQLite_Backup_handle, 0);
+	if (ret != SQLITE_OK) {
+	    throwex(env, err ? err : "unknown error");
+	}
+    }
+#endif
+}
+
+JNIEXPORT jboolean JNICALL
+Java_SQLite_Backup__1step(JNIEnv *env, jobject obj, jint n)
+{
+    jboolean result = JNI_TRUE;
+#if HAVE_SQLITE3 && HAVE_SQLITE3_BACKUPAPI
+    hbk *bk = gethbk(env, obj);
+    int ret;
+
+    if (bk) {
+	if (bk->bkup) {
+	    ret = sqlite3_backup_step(bk->bkup, (int) n);
+	    switch (ret) {
+	    case SQLITE_DONE:
+		break;
+	    case SQLITE_LOCKED:
+	    case SQLITE_BUSY:
+	    case SQLITE_OK:
+		result = JNI_FALSE;
+		break;
+	    default:
+		result = JNI_FALSE;
+		throwex(env, "backup step failed");
+		break;
+	    }
+	}
+    } else {
+	throwex(env, "stale backup object");
+    }
+#else
+    throwex(env, "unsupported");
+#endif
+    return result;
+}
+
+JNIEXPORT jint JNICALL
+Java_SQLite_Backup__1remaining(JNIEnv *env, jobject obj)
+{
+    jint result = 0;
+#if HAVE_SQLITE3 && HAVE_SQLITE3_BACKUPAPI
+    hbk *bk = gethbk(env, obj);
+
+    if (bk) {
+	if (bk->bkup) {
+	    result = sqlite3_backup_remaining(bk->bkup);
+	}
+    }
+#else
+    throwex(env, "unsupported");
+#endif
+    return result;
+}
+
+JNIEXPORT jint JNICALL
+Java_SQLite_Backup__1pagecount(JNIEnv *env, jobject obj)
+{
+    jint result = 0;
+#if HAVE_SQLITE3 && HAVE_SQLITE3_BACKUPAPI
+    hbk *bk = gethbk(env, obj);
+
+    if (bk) {
+	if (bk->bkup) {
+	    result = sqlite3_backup_pagecount(bk->bkup);
+	}
+    }
+#else
+    throwex(env, "unsupported");
+#endif
+    return result;
+}
+
+#if HAVE_SQLITE3_PROFILE
+static void
+doprofile(void *arg, const char *msg, sqlite_uint64 est)
+{
+    handle *h = (handle *) arg;
+    JNIEnv *env = h->env;
+
+    if (env && h->pr && msg) {
+	jthrowable exc;
+	jclass cls = (*env)->GetObjectClass(env, h->pr);
+	jmethodID mid;
+
+	mid = (*env)->GetMethodID(env, cls, "profile",
+				  "(Ljava/lang/String;J)V");
+	if (mid) {
+	    transstr tr;
+#if _MSC_VER && (_MSC_VER < 1300)
+	    jlong ms = est / (3600i64 * 24i64 * 1000i64);
+#else
+	    jlong ms = est / (3600LL * 24LL * 1000LL);
+#endif
+
+	    trans2utf(env, h->haveutf, h->enc, msg, &tr);
+	    exc = (*env)->ExceptionOccurred(env);
+	    if (exc) {
+		(*env)->DeleteLocalRef(env, exc);
+		(*env)->ExceptionClear(env);
+		return;
+	    }
+	    (*env)->CallVoidMethod(env, h->pr, mid, tr.jstr, ms);
+	    (*env)->ExceptionClear(env);
+	    (*env)->DeleteLocalRef(env, tr.jstr);
+	    return;
+	}
+    }
+    return;
+}
+#endif
+
+JNIEXPORT void JNICALL
+Java_SQLite_Database__1profile(JNIEnv *env, jobject obj, jobject tr)
+{
+#if HAVE_SQLITE3_PROFILE
+    handle *h = gethandle(env, obj);
+
+    if (h && h->sqlite) {
+	delglobrefp(env, &h->pr);
+	globrefset(env, tr, &h->pr);
+#if HAVE_BOTH_SQLITE
+	if (h->is3) {
+	    sqlite3_profile((sqlite3 *) h->sqlite, h->pr ? doprofile : 0, h);
+	}
+#else
+#if HAVE_SQLITE3
+	sqlite3_profile((sqlite3 *) h->sqlite, h->pr ? doprofile : 0, h);
+#endif
+#endif
+    }
+#endif
+}
+
+JNIEXPORT jint JNICALL
+Java_SQLite_Database__1status(JNIEnv *env, jclass cls, jint op,
+			      jintArray info, jboolean flag)
+{
+    jint ret = SQLITE_ERROR;
+#if HAVE_SQLITE3_STATUS
+    int data[2] = { 0, 0 };
+    jint jdata[2];
+#if HAVE_SQLITE3
+    ret = sqlite3_status(op, &data[0], &data[2], flag);
+    if (ret == SQLITE_OK) {
+	jdata[0] = data[0];
+	jdata[1] = data[1];
+	(*env)->SetIntArrayRegion(env, info, 0, 2, jdata);
+    }
+#endif
+#endif
+    return ret;
+}
+
+JNIEXPORT jint JNICALL
+Java_SQLite_Database__1db_1status(JNIEnv *env, jobject obj, jint op,
+				  jintArray info, jboolean flag)
+{
+    jint ret = SQLITE_ERROR;
+#if HAVE_SQLITE3_DB_STATUS
+    handle *h = gethandle(env, obj);
+    int data[2] = { 0, 0 };
+    jint jdata[2];
+
+    if (h && h->sqlite) {
+#if HAVE_BOTH_SQLITE
+	if (h->is3) {
+	    ret = sqlite3_db_status((sqlite3 *) h->sqlite, op, &data[0],
+				    &data[1], flag);
+	}
+#else
+#if HAVE_SQLITE3
+	ret = sqlite3_db_status((sqlite3 *) h->sqlite, op, &data[0],
+				&data[2], flag);
+#endif
+#endif
+	if (ret == SQLITE_OK) {
+	    jdata[0] = data[0];
+	    jdata[1] = data[1];
+	    (*env)->SetIntArrayRegion(env, info, 0, 2, jdata);
+	}
+    }
+#endif
+    return ret;
+}
+
 JNIEXPORT void JNICALL
 Java_SQLite_Stmt_internal_1init(JNIEnv *env, jclass cls)
 {
@@ -4592,6 +4965,13 @@
 }
 
 JNIEXPORT void JNICALL
+Java_SQLite_Backup_internal_1init(JNIEnv *env, jclass cls)
+{
+    F_SQLite_Backup_handle =
+	(*env)->GetFieldID(env, cls, "handle", "J");
+}
+
+JNIEXPORT void JNICALL
 Java_SQLite_Database_internal_1init(JNIEnv *env, jclass cls)
 {
 #if defined(DONT_USE_JNI_ONLOAD) || !defined(JNI_VERSION_1_2)
diff --git a/support/src/test/java/libcore/javax/net/ssl/TestSSLContext.java b/support/src/test/java/libcore/javax/net/ssl/TestSSLContext.java
index 3e466bc..f171c6c 100644
--- a/support/src/test/java/libcore/javax/net/ssl/TestSSLContext.java
+++ b/support/src/test/java/libcore/javax/net/ssl/TestSSLContext.java
@@ -115,6 +115,14 @@
         this.port = port;
     }
 
+    public void close() {
+        try {
+            serverSocket.close();
+        } catch (Exception e) {
+            throw new RuntimeException(e);
+        }
+    }
+
     /**
      * Usual TestSSLContext creation method, creates underlying
      * SSLContext with certificate and key as well as SSLServerSocket
diff --git a/support/src/test/java/libcore/javax/net/ssl/TestSSLSessions.java b/support/src/test/java/libcore/javax/net/ssl/TestSSLSessions.java
index d2f1a36..df027db 100644
--- a/support/src/test/java/libcore/javax/net/ssl/TestSSLSessions.java
+++ b/support/src/test/java/libcore/javax/net/ssl/TestSSLSessions.java
@@ -58,6 +58,10 @@
         this.s = s;
     }
 
+    public void close() {
+        s.close();
+    }
+
     public static final TestSSLSessions create() {
         try {
             SSLSocketFactory sf = (SSLSocketFactory) SSLSocketFactory.getDefault();
diff --git a/support/src/test/java/libcore/javax/net/ssl/TestSSLSocketPair.java b/support/src/test/java/libcore/javax/net/ssl/TestSSLSocketPair.java
index ed96bc9..abbcf8c 100644
--- a/support/src/test/java/libcore/javax/net/ssl/TestSSLSocketPair.java
+++ b/support/src/test/java/libcore/javax/net/ssl/TestSSLSocketPair.java
@@ -40,6 +40,16 @@
         this.client = client;
     }
 
+    public void close() {
+        c.close();
+        try {
+            server.close();
+            client.close();
+        } catch (Exception e) {
+            throw new RuntimeException(e);
+        }
+    }
+
     /**
      * based on test_SSLSocket_startHandshake
      */